// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.security.tls;

import java.util.Arrays;

/**
 * @author bjorncs
 */
public enum AuthorizationMode {
    DISABLE("disable"),
    LOG_ONLY("log-only"),
    ENFORCE("enforce");

    final String configValue;

    AuthorizationMode(String configValue) {
        this.configValue = configValue;
    }

    public String configValue() {
        return configValue;
    }

    static AuthorizationMode fromConfigValue(String configValue) {
        return Arrays.stream(values())
                .filter(v -> v.configValue.equals(configValue))
                .findFirst()
                .orElseThrow(() -> new IllegalArgumentException("Unknown value: " + configValue));
    }
}

// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.security.tls;

import java.util.Arrays;

/**
 * @author bjorncs
 */
public enum AuthorizationMode {
    DISABLE("disable"),
    LOG_ONLY("log_only"),
    ENFORCE("enforce");

    final String configValue;

    AuthorizationMode(String configValue) {
        this.configValue = configValue;
    }

    public String configValue() {
        return configValue;
    }

    static AuthorizationMode fromConfigValue(String configValue) {
        return Arrays.stream(values())
                .filter(v -> v.configValue.equals(configValue))
                .findFirst()
                .orElseThrow(() -> new IllegalArgumentException("Unknown value: " + configValue));
    }
}

Change LOG_ONLY config value from 'log-only' to 'log_only'


package jp.ac.nii.prl.mape.autoscaling.analysis;

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

import jp.ac.nii.prl.mape.autoscaling.analysis.service.DeploymentService;

@Configuration
public class TestContext {

	@Bean
	public DeploymentService deploymentService() {
		return Mockito.mock(DeploymentService.class);
	}
}

package jp.ac.nii.prl.mape.autoscaling.analysis;

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

import jp.ac.nii.prl.mape.autoscaling.analysis.service.DeploymentService;
import jp.ac.nii.prl.mape.autoscaling.analysis.service.VirtualMachineService;

@Configuration
public class TestContext {

	@Bean
	public DeploymentService deploymentService() {
		return Mockito.mock(DeploymentService.class);
	}

	@Bean
	public VirtualMachineService virtualMachineService() {
		return Mockito.mock(VirtualMachineService.class);
	}
}

Add VirtualMachineController mock to testing context


package com.elmakers.mine.bukkit.magic.dao;

import org.bukkit.Material;

import com.elmakers.mine.bukkit.persisted.PersistClass;
import com.elmakers.mine.bukkit.persisted.PersistField;
import com.elmakers.mine.bukkit.persistence.dao.MaterialData;

@PersistClass(schema="magic", name="cost", contained=true)
public class CastingCost
{
    public void addItem(Material material, int count)
    {
        this.item = new MaterialData(material);
        this.count = count;
    }

    @PersistField
    public float getHealth()
    {
        return health;
    }

    public void setHealth(float health)
    {
        this.health = health;
    }

    @PersistField
    public MaterialData getItem()
    {
        return item;
    }

    public void setItem(MaterialData item)
    {
        this.item = item;
    }

    @PersistField
    public int getCount()
    {
        return count;
    }

    public void setCount(int count)
    {
        this.count = count;
    }

    protected float        health = 0;
    protected MaterialData item   = null;
    protected int          count  = 0;
}

package com.elmakers.mine.bukkit.magic.dao;

import org.bukkit.Material;

import com.elmakers.mine.bukkit.persisted.PersistClass;
import com.elmakers.mine.bukkit.persisted.PersistField;
import com.elmakers.mine.bukkit.persistence.dao.MaterialData;

@PersistClass(schema="magic", name="cost", contained=true)
public class CastingCost
{
    protected float        health = 0;
    protected float        mana   = 0;
    protected MaterialData item   = null;
    protected int          count  = 0;

    public void addItem(Material material, int count)
    {
        this.item = new MaterialData(material);
        this.count = count;
    }

    @PersistField
    public float getHealth()
    {
        return health;
    }

    public void setHealth(float health)
    {
        this.health = health;
    }

    @PersistField
    public MaterialData getItem()
    {
        return item;
    }

    public void setItem(MaterialData item)
    {
        this.item = item;
    }

    @PersistField
    public int getCount()
    {
        return count;
    }

    public void setCount(int count)
    {
        this.count = count;
    }

    @PersistField
    public float getMana()
    {
        return mana;
    }

    public void setMana(float mana)
    {
        this.mana = mana;
    }

}

Add mana to casting cost.


package com.elmakers.mine.bukkit.api.maps;

import org.bukkit.inventory.ItemStack;

import java.util.List;

public interface MapController {
    List<URLMap> getAll();
    void loadMap(String world, short id, String url, String name, int x, int y, int width, int height, Integer priority);
    ItemStack getURLItem(String world, String url, String name, int x, int y, int width, int height, Integer priority);
    void forceReloadPlayerPortrait(String worldName, String playerName);
    ItemStack getPlayerPortrait(String worldName, String playerName, Integer priority, String photoName);
    ItemStack getMapItem(short id);
    boolean hasMap(short id);
    boolean remove(short id);
    void save();
    short getURLMapId(String world, String url, String name, int x, int y, int width, int height, Integer priority);
    short getURLMapId(String world, String url);
}

package com.elmakers.mine.bukkit.api.maps;

import org.bukkit.inventory.ItemStack;

import java.util.List;

public interface MapController {
    List<URLMap> getAll();
    URLMap getMap(short id);
    void loadMap(String world, short id, String url, String name, int x, int y, int width, int height, Integer priority);
    ItemStack getURLItem(String world, String url, String name, int x, int y, int width, int height, Integer priority);
    void forceReloadPlayerPortrait(String worldName, String playerName);
    ItemStack getPlayerPortrait(String worldName, String playerName, Integer priority, String photoName);
    ItemStack getMapItem(short id);
    boolean hasMap(short id);
    boolean remove(short id);
    void save();
    short getURLMapId(String world, String url, String name, int x, int y, int width, int height, Integer priority);
    short getURLMapId(String world, String url);
}

Add API method to fetch a URLMap by id


package com.boundary.sdk.event;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.commons.daemon.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

class EchoTask extends TimerTask {
    @Override
    public void run() {
        System.out.println(new Date() + " running ...");
    }
}

public class BoundaryEventDaemon extends EventApplication implements Daemon {

	private static Logger LOG = LoggerFactory.getLogger(BoundaryEventDaemon.class);

    private static Timer timer = null;

    public BoundaryEventDaemon() {

    }

    public static void main(String[] args) {
//        timer = new Timer();
//        timer.schedule(new EchoTask(), 0, 1000);
    }

    public void init(DaemonContext dc) throws DaemonInitException, Exception {
        System.out.println("initializing ...");
    }

    public void start() throws Exception {
        System.out.println("starting ...");
        boot();
    }

    public void stop() throws Exception {
        System.out.println("stopping ...");
        main.stop();

        if (timer != null) {
            timer.cancel();
        }
    }

    public void destroy() {
        System.out.println("done.");
    }
 }

// Copyright 2014 Boundary, 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.boundary.sdk.event;
import java.util.Timer;

import org.apache.commons.daemon.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class BoundaryEventDaemon extends EventApplication implements Daemon {

	private static Logger LOG = LoggerFactory.getLogger(BoundaryEventDaemon.class);

    public BoundaryEventDaemon() {

    }

    public static void main(String[] args) {

    }

    public void init(DaemonContext dc) throws DaemonInitException, Exception {
        LOG.info("Initializing ...");
    }

    public void start() throws Exception {
    	LOG.info("Starting ...");
        boot();
    }

    public void stop() throws Exception {
    	LOG.info("Stopping ...");
        main.stop();
    }

    public void destroy() {
    	LOG.info("Destroy ...");
    }
 }

Clean up ; remove unused imports ; license header


/*
 * Copyright 2007 Russell Harmon
 *
 *    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.eatnumber1.util.concurrent;

import java.util.concurrent.Callable;
import org.jetbrains.annotations.NotNull;

/**
 * @author Russell Harmon
 * @since Jul 13, 2007
 */
public class ThreadUtils {
    private ThreadUtils() {}

    @NotNull
    public static <T> Callable<T> caughtCallable( @NotNull Callable<T> callable ) {
        return new ExceptionReportingCallable<T>(callable);
    }
}

/*
 * Copyright 2007 Russell Harmon
 *
 *    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.eatnumber1.util.concurrent;

import java.util.concurrent.Callable;
import org.jetbrains.annotations.NotNull;

/**
 * @author Russell Harmon
 * @since Jul 13, 2007
 */
public class ThreadUtils {
    private ThreadUtils() {}

    @NotNull
    public static <T> Callable<T> caughtCallable( @NotNull Callable<T> callable ) {
        return new ExceptionReportingCallable<T>(callable);
    }

    @NotNull
    public static <T> Runnable runnable( @NotNull Callable<T> callable ) {
        return new ThreadAdapter<T>(callable);
    }
}

Add runnable method to convert a callable into a runnable.


package nu.studer.teamcity.buildscan.internal;

import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public final class Util {

    private static final Pattern BUILD_SCAN_URL_PATTERN = Pattern.compile("https?://.*/s/(.*)");

    private Util() {
    }

    public static boolean isBuildScanUrl(String text) {
        return doGetBuildScanId(text).isPresent();
    }

    public static String getBuildScanId(String text) {
        //noinspection OptionalGetWithoutIsPresent
        return doGetBuildScanId(text).get();
    }

    private static Optional<String> doGetBuildScanId(String text) {
        Matcher matcher = BUILD_SCAN_URL_PATTERN.matcher(text);
        return matcher.matches() ? Optional.of(matcher.group(1)) : Optional.empty();
    }
}

package nu.studer.teamcity.buildscan.internal;

import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

final class Util {

    private static final Pattern BUILD_SCAN_URL_PATTERN = Pattern.compile("https?://.*/s/(.*)");

    static boolean isBuildScanUrl(String text) {
        return doGetBuildScanId(text).isPresent();
    }

    static String getBuildScanId(String text) {
        //noinspection OptionalGetWithoutIsPresent
        return doGetBuildScanId(text).get();
    }

    private static Optional<String> doGetBuildScanId(String text) {
        Matcher matcher = BUILD_SCAN_URL_PATTERN.matcher(text);
        return matcher.matches() ? Optional.of(matcher.group(1)) : Optional.empty();
    }

    private Util() {
    }

}

Reduce class and method visibility


/*
 * This file is part of the DITA Open Toolkit project.
 *
 * Copyright 2011 Jarno Elovirta
 *
 * See the accompanying LICENSE file for applicable license.
 */
package org.dita.dost.platform;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;

/**
 * List transtypes integration action.
 *
 * @since 1.5.4
 * @author Jarno Elovirta
 */
final class ListTranstypeAction extends ImportAction {

    /**
     * Get result.
     */
    @Override
    public void getResult(final ContentHandler buf) throws SAXException {
        final String separator = paramTable.getOrDefault("separator", "|");
        final List<String> v = valueSet.stream()
                .map(fileValue -> fileValue.value)
                .collect(Collectors.toList());
        Collections.sort(v);
        final StringBuilder retBuf = new StringBuilder();
        for (final Iterator<String> i = v.iterator(); i.hasNext();) {
            retBuf.append(i.next());
            if (i.hasNext()) {
                retBuf.append(separator);
            }
        }
        final char[] ret = retBuf.toString().toCharArray();
        buf.characters(ret, 0, ret.length);
    }

    @Override
    public String getResult() {
        throw new UnsupportedOperationException();
    }

}

/*
 * This file is part of the DITA Open Toolkit project.
 *
 * Copyright 2011 Jarno Elovirta
 *
 * See the accompanying LICENSE file for applicable license.
 */
package org.dita.dost.platform;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;

/**
 * List transtypes integration action.
 *
 * @since 1.5.4
 * @author Jarno Elovirta
 */
final class ListTranstypeAction extends ImportAction {

    /**
     * Get result.
     */
    @Override
    public void getResult(final ContentHandler buf) throws SAXException {
        final String separator = paramTable.getOrDefault("separator", "|");
        final List<String> v = valueSet.stream()
                .map(fileValue -> fileValue.value)
                .distinct()
                .collect(Collectors.toList());
        Collections.sort(v);
        final StringBuilder retBuf = new StringBuilder();
        for (final Iterator<String> i = v.iterator(); i.hasNext();) {
            retBuf.append(i.next());
            if (i.hasNext()) {
                retBuf.append(separator);
            }
        }
        final char[] ret = retBuf.toString().toCharArray();
        buf.characters(ret, 0, ret.length);
    }

    @Override
    public String getResult() {
        throw new UnsupportedOperationException();
    }

}

Drop duplicates when listing transform types


/*
 * Copyright 2015 Hewlett-Packard Development Company, L.P.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
 */

package com.hp.autonomy.types.requests.idol.actions.tags;

import lombok.Data;

import java.io.Serializable;

@SuppressWarnings({"WeakerAccess", "unused"})
@Data
public class TagName implements Serializable {
    private static final long serialVersionUID = -6221132711228529797L;
    private final String id;
    private final String name;

    public TagName(final String name, final String id) {
        this.name = name;
        this.id = id;
    }
}

/*
 * Copyright 2015 Hewlett-Packard Development Company, L.P.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
 */

package com.hp.autonomy.types.requests.idol.actions.tags;

import com.fasterxml.jackson.annotation.JsonCreator;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.io.Serializable;

@SuppressWarnings({"WeakerAccess", "unused"})
@Getter
@NoArgsConstructor
@EqualsAndHashCode
public class TagName implements Serializable {
    private static final long serialVersionUID = -6221132711228529797L;
    private String id;
    private String name;

    @JsonCreator
    public TagName(final String path) {
        name = getFieldNameFromPath(path);
        id = adjustFieldPath(path, name);
    }

    private String adjustFieldPath(final String fieldPath, final String fieldName) {
        // Need an extra '/' to be able to query a field by its root path (since wildcards in Idol config file take the form */SOME_FIELD)
        // However, for the special autn_date field which does not have a path, adding such a '/' would break the query
        return fieldName.equals(fieldPath) || fieldPath.startsWith("/") ? fieldPath : '/' + fieldPath;
    }

    private String getFieldNameFromPath(final String value) {
        return value.contains("/") ? value.substring(value.lastIndexOf('/') + 1) : value;
    }
}

Undo change a3351c6 as the update to haven-search-components required to use it is currently on hold


package com.team254.frc2013.commands;

import edu.wpi.first.wpilibj.Timer;

/**
 * Shoots a disc that is already loaded into the shooter.
 *
 * @author tom@team254.com (Tom Bottiglieri)
 * @author pat@team254.com (Patrick Fairbank)
 */
public class ShootCommand extends CommandBase {
  private Timer shooterTimer;

  public ShootCommand() {
    requires(shooter);
    shooterTimer = new Timer();
  }

  protected void initialize() {
    // Don't fire the piston if the shooter is not turned on.
    if (shooter.isOn()) {
      shooter.extend();
      shooterTimer.reset();
      shooterTimer.start();
    }
  }

  protected void execute() {
  }

  protected boolean isFinished() {
    return shooterTimer.get() > 0.2 || !shooter.isOn();
  }

  protected void end() {
    System.out.println("RPM of shot: " + shooter.getRpm());
    shooter.retract();
  }

  protected void interrupted() {
  }
}

package com.team254.frc2013.commands;

import edu.wpi.first.wpilibj.Timer;

/**
 * Shoots a disc that is already loaded into the shooter.
 *
 * @author tom@team254.com (Tom Bottiglieri)
 * @author pat@team254.com (Patrick Fairbank)
 */
public class ShootCommand extends CommandBase {
  private Timer shooterTimer;

  public ShootCommand() {
    requires(shooter);
    shooterTimer = new Timer();
  }

  protected void initialize() {
    // Don't fire the piston if the shooter is not turned on.
    if (shooter.isOn()) {
      shooter.extend();
      shooterTimer.reset();
      shooterTimer.start();
    }
    conveyor.setMotor(-.175);
    intake.setIntakePower(-.1);
  }

  protected void execute() {
  }

  protected boolean isFinished() {
    return shooterTimer.get() > 0.2 || !shooter.isOn();
  }

  protected void end() {
    System.out.println("RPM of shot: " + shooter.getRpm());
    shooter.retract();
  }

  protected void interrupted() {
  }
}

Make conveyor run backwards as disc is shooting to prevent jams


/**
 * Waffle (https://github.com/Waffle/waffle)
 *
 * Copyright (c) 2010-2016 Application Security, Inc.
 *
 * All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse
 * Public License v1.0 which accompanies this distribution, and is available at
 * https://www.eclipse.org/legal/epl-v10.html.
 *
 * Contributors: Application Security, Inc.
 */
package waffle.apache;

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

/**
 * Windows Realm Tests.
 *
 * @author dblock[at]dblock[dot]org
 */
public class WindowsRealmTests {

    /**
     * Test properties.
     */
    @Test
    public void testProperties() {
        final WindowsRealm realm = new WindowsRealm();
        Assert.assertNull(realm.getPassword(null));
        Assert.assertNull(realm.getPrincipal(null));
        // To support tomcat 9.0.0.M13 and lower this will still work
        Assert.assertEquals("waffle.apache.WindowsRealm/1.0", realm.getName());
        // In tomcat 9.0.0.M15+, this is all that will now report
        Assert.assertEquals("WindowsRealm", WindowsRealm.class.getSimpleName());
    }
}

/**
 * Waffle (https://github.com/Waffle/waffle)
 *
 * Copyright (c) 2010-2017 Application Security, Inc.
 *
 * All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse
 * Public License v1.0 which accompanies this distribution, and is available at
 * https://www.eclipse.org/legal/epl-v10.html.
 *
 * Contributors: Application Security, Inc.
 */
package waffle.apache;

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

/**
 * Windows Realm Tests.
 *
 * @author dblock[at]dblock[dot]org
 */
public class WindowsRealmTests {

    /**
     * Test properties.
     */
    @Test
    public void testProperties() {
        final WindowsRealm realm = new WindowsRealm();
        Assert.assertNull(realm.getPassword(null));
        Assert.assertNull(realm.getPrincipal(null));
        // To support tomcat 9.0.0.M13 and lower this will still work
        Assert.assertEquals("waffle.apache.WindowsRealm/1.0", realm.getName());
        // In tomcat 9.0.0.M15+, this is all that will now report
        Assert.assertEquals("WindowsRealm", realm.getClass().getSimpleName());
    }
}

Correct test to use the instantiated class instead


package com.kaviju.accesscontrol.authentication;

import java.util.Random;

public class RandomPasswordGenerator {
	static final String possibleChars = "23456789abcdefghjklmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ@#$%?&*()-+";
	static Random rnd = new Random();

	static public String newPassword(int len) {
		{
			StringBuilder password = new StringBuilder( len );
			for( int i = 0; i < len; i++ ) {
				int nextCharIndex = rnd.nextInt(possibleChars.length());
				password.append(possibleChars.charAt(nextCharIndex));
			}
			return password.toString();
		}
	}
}

package com.kaviju.accesscontrol.authentication;

import java.util.Random;

public class RandomPasswordGenerator {
	static final String possibleChars = "23456789abcdefghjklmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ@#$%?&*()-+";
	static final String possibleDigits = "0123456789";
	static Random rnd = new Random();

	static public String newPassword(int len) {
		{
			StringBuilder password = new StringBuilder( len );
			for( int i = 0; i < len; i++ ) {
				int nextCharIndex = rnd.nextInt(possibleChars.length());
				password.append(possibleChars.charAt(nextCharIndex));
			}
			return password.toString();
		}
	}

	static public String newDigitsPassword(int len) {
		{
			StringBuilder password = new StringBuilder( len );
			for( int i = 0; i < len; i++ ) {
				int nextCharIndex = rnd.nextInt(possibleDigits.length());
				password.append(possibleDigits.charAt(nextCharIndex));
			}
			return password.toString();
		}
	}
}

Add a digits only password generator.


package nl.tudelft.ewi.dea.jaxrs.html;

import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import nl.tudelft.ewi.dea.BuildInfo;
import nl.tudelft.ewi.dea.jaxrs.html.utils.Renderer;

import com.google.inject.persist.Transactional;
import com.google.inject.servlet.RequestScoped;

@RequestScoped
@Path("login")
@Produces(MediaType.TEXT_HTML)
public class LoginPage {

	private final Renderer renderer;
	private final BuildInfo buildInfo;

	@Inject
	public LoginPage(Renderer renderer, BuildInfo buildInfo) {
		this.renderer = renderer;
		this.buildInfo = buildInfo;
	}

	@GET
	@Transactional
	public String servePage() {
		return renderer
				.setValue("buildInfo", buildInfo)
				.render("login.tpl");
	}

}

package nl.tudelft.ewi.dea.jaxrs.html;

import java.net.URI;

import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import nl.tudelft.ewi.dea.BuildInfo;
import nl.tudelft.ewi.dea.jaxrs.html.utils.Renderer;
import nl.tudelft.ewi.dea.security.SecurityProvider;

import com.google.inject.persist.Transactional;
import com.google.inject.servlet.RequestScoped;

@RequestScoped
@Path("login")
@Produces(MediaType.TEXT_HTML)
public class LoginPage {

	private final Renderer renderer;
	private final BuildInfo buildInfo;
	private final SecurityProvider securityProvider;

	@Inject
	public LoginPage(SecurityProvider securityProvider,
			Renderer renderer, BuildInfo buildInfo) {

		this.securityProvider = securityProvider;
		this.renderer = renderer;
		this.buildInfo = buildInfo;
	}

	@GET
	@Transactional
	public Response servePage() {
		if (securityProvider.getSubject().isAuthenticated()) {
			return Response.seeOther(URI.create("/dashboard")).build();
		}

		return Response.ok(renderer
				.setValue("buildInfo", buildInfo)
				.render("login.tpl")).build();
	}
}

Fix issue-45: When already logged in, the login page should redirect to the dashboard.


package hello;

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Hello.class)
@AutoConfigureMockMvc
@ActiveProfiles("test")
public class HomePageTest {

	@Autowired
	private MockMvc mvc;

	@Test
	public void getRoot() throws Exception {
		mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.TEXT_HTML)).andExpect(status().isOk());
	}

	@Test
	public void getJsonRoot() throws Exception {
		mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
				.andExpect(status().isOk());
	}
}

package hello;

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Hello.class)
@AutoConfigureMockMvc
@ActiveProfiles("test")
public class HomePageTest {

	@Autowired
	private MockMvc mvc;

	@Test
	public void getRoot() throws Exception {
		mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.TEXT_HTML)).andExpect(status().isOk());
	}
}

Remove the test for / via the API.


package com.fewlaps.mentiondetector;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

public class RemovePunctuationMarks {

    private static final String EMPTY = "";
    private static final String[] PUNCTUATION_MARKS = {
            "!", "\\?", "", "", "\\(", "\\)", "\\{", "\\}", "\\[", "\\]"
    };

    private static List<Pattern> cache;

    public String removePunctuationMarks(String text) {
        for (Pattern pattern : getPatterns()) {
            text = pattern.matcher(text).replaceAll(EMPTY);
        }
        return text;
    }

    private List<Pattern> getPatterns() {
        if (cache == null) {
            cache = new ArrayList(PUNCTUATION_MARKS.length);
            for (String mark : PUNCTUATION_MARKS) {
                cache.add(Pattern.compile(mark));
            }
        }
        return cache;
    }
}

package com.fewlaps.mentiondetector;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

public class RemovePunctuationMarks {

    private static final String EMPTY = "";
    private static final String[] PUNCTUATION_MARKS = {
            "!", "\\?", "�", "�", "\\(", "\\)", "\\{", "\\}", "\\[", "\\]"
    };

    private static List<Pattern> cache;

    public String removePunctuationMarks(String text) {
        for (Pattern pattern : getPatterns()) {
            text = pattern.matcher(text).replaceAll(EMPTY);
        }
        return text;
    }

    private List<Pattern> getPatterns() {
        if (cache == null) {
            cache = new ArrayList(PUNCTUATION_MARKS.length);
            for (String mark : PUNCTUATION_MARKS) {
                cache.add(Pattern.compile(mark));
            }
        }
        return cache;
    }
}

Convert the file to UTF-8


package in.testpress.testpress.events;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;

import in.testpress.testpress.R;
import in.testpress.testpress.authenticator.CodeVerificationActivity.Timer;
import in.testpress.testpress.core.Constants;

public class SmsReceivingEvent extends BroadcastReceiver {
    public String code;
    private Timer timer;
    public SmsReceivingEvent(Timer timer) {
        this.timer = timer;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        // Retrieves a map of extended data from the intent.
        final Bundle bundle = intent.getExtras();
        try {
            if (bundle != null) {
                final Object[] pdusObj = (Object[]) bundle.get("pdus");
                SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[0]);
                String senderNum = currentMessage.getDisplayOriginatingAddress();
                if (senderNum.matches(".*TSTPRS")) { //check whether TSTPRS present in senderAddress
                    String smsContent = currentMessage.getDisplayMessageBody();
                    //get the code from smsContent
                    code = smsContent.replaceAll(".*(?<=Thank you for registering at +"+Constants.Http.URL_BASE +"+. Your authorization code is )([^\n]*)(?=.).*", "$1");
                    timer.cancel();
                    timer.onFinish();
                }
            } // bundle is null
        } catch (Exception e) {
            timer.cancel();
            timer.onFinish();
        }
    }
}

package in.testpress.testpress.events;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;

import in.testpress.testpress.authenticator.CodeVerificationActivity.Timer;

public class SmsReceivingEvent extends BroadcastReceiver {
    public String code;
    private Timer timer;
    public SmsReceivingEvent(Timer timer) {
        this.timer = timer;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        // Retrieves a map of extended data from the intent.
        final Bundle bundle = intent.getExtras();
        try {
            if (bundle != null) {
                final Object[] pdusObj = (Object[]) bundle.get("pdus");
                SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[0]);
                String senderNum = currentMessage.getDisplayOriginatingAddress();
                if (senderNum.matches(".*TSTPRS")) { //check whether TSTPRS present in senderAddress
                    String smsContent = currentMessage.getDisplayMessageBody();
                    //get the code from smsContent
                    code = smsContent.replaceAll(".*(?=.*)(?<=Your authorization code is )([^\n]*)(?=.).*", "$1");
                    timer.cancel();
                    timer.onFinish();
                }
            } // bundle is null
        } catch (Exception e) {
            timer.cancel();
            timer.onFinish();
        }
    }
}

Modify sms format in sms receiving event


package hiteware.com.halfwaythere;

import android.widget.TextView;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;

/**
 * Created by jasonhite on 4/29/15.
 */

@RunWith(CustomRobolectricRunner.class)
@Config(constants = BuildConfig.class)
public class SensorIntegrationTest
{
    public MainActivity CreatedActivity;
    public TestInjectableApplication application;

    StepSensorChange stepSensorChange;

    @Before
    public void setUp()
    {
        application = (TestInjectableApplication) RuntimeEnvironment.application;
        CreatedActivity = Robolectric.buildActivity(MainActivity.class).create().postResume().get();
        stepSensorChange = application.stepSensorChangeModule.provideStepSensorChange();
    }

    @Test
    public void whenAStepCounterValueIsInjectedTheDisplayIsUpdated()
    {
        stepSensorChange.onSensorChanged(SensorValue.CreateSensorEvent(24));
        assertThat(((TextView) CreatedActivity.findViewById(R.id.step_value)).getText().toString(), equalTo("23"));
    }
}

package hiteware.com.halfwaythere;

import android.widget.TextView;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;

/**
 * Created by jasonhite on 4/29/15.
 */

@RunWith(CustomRobolectricRunner.class)
@Config(constants = BuildConfig.class)
public class SensorIntegrationTest
{
    public MainActivity CreatedActivity;
    public TestInjectableApplication application;

    StepSensorChange stepSensorChange;

    @Before
    public void setUp()
    {
        application = (TestInjectableApplication) RuntimeEnvironment.application;
        CreatedActivity = Robolectric.buildActivity(MainActivity.class).create().postResume().get();
        stepSensorChange = application.stepSensorChangeModule.provideStepSensorChange();
    }

    @Test
    public void whenAStepCounterValueIsInjectedTheDisplayIsUpdated()
    {
        stepSensorChange.onSensorChanged(SensorValue.CreateSensorEvent(23));
        assertThat(((TextView) CreatedActivity.findViewById(R.id.step_value)).getText().toString(), equalTo("23"));
    }
}

Revert "Intentional fail to make Jenkins Fail if it is checking tests"


package org.reactfx;

import static org.junit.Assert.*;

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

public class PrependEventStreamTest {

    @Test
    public void test() {
        EventCounter countsTwice = new EventCounter();
        EventCounter countsOnce = new EventCounter();

        EventSource<Boolean> source = new EventSource<>();
        EventStream<Boolean> stream = source.prepend(true);

        stream.subscribe(countsTwice::accept);
        source.push(false);
        stream.subscribe(countsOnce::accept);

        assertEquals("Counts Twice failed", 2, countsTwice.get());
        assertEquals("Counts Once failed", 1, countsOnce.get());
    }
}

package org.reactfx;

import static org.junit.Assert.*;

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

import org.junit.Test;
import org.reactfx.value.Var;

public class PrependEventStreamTest {

    @Test
    public void test() {
        EventCounter countsTwice = new EventCounter();
        EventCounter countsOnce = new EventCounter();

        EventSource<Boolean> source = new EventSource<>();
        EventStream<Boolean> stream = source.prepend(true);

        stream.subscribe(countsTwice::accept);
        source.push(false);
        stream.subscribe(countsOnce::accept);

        assertEquals("Counts Twice failed", 2, countsTwice.get());
        assertEquals("Counts Once failed", 1, countsOnce.get());
    }

    @Test
    public void testAutoEmittingStream() {
        List<Integer> emitted = new ArrayList<>();
        Var<Integer> source = Var.newSimpleVar(1);
        EventStream<Integer> stream = source.values().prepend(0);
        stream.subscribe(emitted::add);
        assertEquals(Arrays.asList(0, 1), emitted);
    }
}

Add failing test for prepend.


/*
 * Copyright 2016 Real Logic 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 uk.co.real_logic.aeron.driver.stats;

import uk.co.real_logic.agrona.concurrent.CountersManager;
import uk.co.real_logic.agrona.concurrent.status.Position;

public class SenderPos
{
    /**
     * Type id of a sender position counter.
     */
    public static final int SENDER_POSITION_TYPE_ID = 4;

    public static Position allocate(
        final CountersManager countersManager,
        final long registrationId,
        final int sessionId,
        final int streamId,
        final String channel)
    {
        return StreamPositionCounter.allocate(
            "sender hwm", SENDER_POSITION_TYPE_ID, countersManager, registrationId, sessionId, streamId, channel);
    }
}

/*
 * Copyright 2016 Real Logic 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 uk.co.real_logic.aeron.driver.stats;

import uk.co.real_logic.agrona.concurrent.CountersManager;
import uk.co.real_logic.agrona.concurrent.status.Position;

public class SenderPos
{
    /**
     * Type id of a sender position counter.
     */
    public static final int SENDER_POSITION_TYPE_ID = 2;

    public static Position allocate(
        final CountersManager countersManager,
        final long registrationId,
        final int sessionId,
        final int streamId,
        final String channel)
    {
        return StreamPositionCounter.allocate(
            "sender pos", SENDER_POSITION_TYPE_ID, countersManager, registrationId, sessionId, streamId, channel);
    }
}

Fix typo in sender position counter setup.


package de.nedelosk.modularmachines.api.modules;

import de.nedelosk.modularmachines.api.modules.energy.IModuleHeat;
import de.nedelosk.modularmachines.api.modules.storaged.IModuleModuleStorage;

public interface IModuleCasing extends IModuleModuleStorage, IModuleTickable, IModuleHeat {

}

package de.nedelosk.modularmachines.api.modules;

import de.nedelosk.modularmachines.api.modules.energy.IModuleHeat;
import de.nedelosk.modularmachines.api.modules.storaged.IModuleModuleStorage;

public interface IModuleCasing extends IModuleModuleStorage {

}

Remove tickable interface from casing


/*
 * 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.jdbi.v3.sqlite3;

import org.jdbi.v3.core.mapper.ColumnMapper;
import org.jdbi.v3.core.statement.StatementContext;

import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.sql.ResultSet;
import java.sql.SQLException;

public class URLColumnMapper implements ColumnMapper<URL> {

    @Override
    public URL map(ResultSet r, int columnNumber, StatementContext ctx) throws SQLException {
        URL url = null;

        try {
            url = URI.create(r.getString(columnNumber)).toURL();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return url;
    }
}

/*
 * 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.jdbi.v3.sqlite3;

import org.jdbi.v3.core.mapper.ColumnMapper;
import org.jdbi.v3.core.statement.StatementContext;

import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.sql.ResultSet;
import java.sql.SQLException;

public class URLColumnMapper implements ColumnMapper<URL> {

    @Override
    public URL map(ResultSet r, int columnNumber, StatementContext ctx) throws SQLException {
        URL url = null;

        try {
            url = URI.create(r.getString(columnNumber)).toURL();
        } catch (MalformedURLException e) {
            throw new SQLException(e);
        }
        return url;
    }
}

Throw exception when url could not be created from result set.


package in.twizmwaz.cardinal.module.modules.filter.parsers;

import in.twizmwaz.cardinal.module.modules.filter.FilterParser;
import in.twizmwaz.cardinal.util.NumUtils;
import org.jdom2.Element;

public class KillstreakFilterParser extends FilterParser {

    private int min, max, count;
    private boolean repeat;

    public KillstreakFilterParser(final Element element) {
        super(element);
        try {
            this.min = NumUtils.parseInt(element.getAttributeValue("min"));
        } catch (NumberFormatException e) {
            this.min = -1;
        }
        try {
            this.max = NumUtils.parseInt(element.getAttributeValue("max"));
        } catch (NumberFormatException e) {
            this.max = -1;
        }
        try {
            this.count = NumUtils.parseInt(element.getAttributeValue("count"));
        } catch (NumberFormatException e) {
            this.count = -1;
        }
        try {
            this.repeat = Boolean.parseBoolean(element.getAttributeValue("repeat"));
        } catch (NumberFormatException e) {
            this.repeat = false;
        }
    }

    public int getMin() {
        return min;
    }

    public int getMax() {
        return max;
    }

    public int getCount() {
        return count;
    }

    public boolean isRepeat() {
        return repeat;
    }

}

package in.twizmwaz.cardinal.module.modules.filter.parsers;

import in.twizmwaz.cardinal.module.modules.filter.FilterParser;
import in.twizmwaz.cardinal.util.NumUtils;
import org.jdom2.Element;

public class KillstreakFilterParser extends FilterParser {

    private int min, max, count;
    private boolean repeat;

    public KillstreakFilterParser(final Element element) {
        super(element);
        this.min = element.getAttributeValue("min") != null ?
                NumUtils.parseInt(element.getAttributeValue("min")) : -1;
        this.max = element.getAttributeValue("max") != null ?
                NumUtils.parseInt(element.getAttributeValue("max")) : -1;
        this.count = element.getAttributeValue("count") != null ?
                NumUtils.parseInt(element.getAttributeValue("count")) : -1;
        this.repeat = element.getAttributeValue("repeat") != null && NumUtils.parseBoolean(element.getAttributeValue("repeat"));
    }

    public int getMin() {
        return min;
    }

    public int getMax() {
        return max;
    }

    public int getCount() {
        return count;
    }

    public boolean isRepeat() {
        return repeat;
    }

}

Fix an NPE when parsing killstreaks


package fr.synchrotron.soleil.ica.ci.lib.workflow;

import java.util.Arrays;

/**
 * @author Gregory Boissinot
 */
public class DefaultWorkflow extends Workflow {

    private static final String DEFAULT_STATUS_BUILD = "BUILD";
    private static final String DEFAULT_STATUS_INTEGRATION = "INTEGRATION";
    private static final String DEFAULT_STATUS_RELEASE = "RELEASE";
    private static final String[] status = new String[]{DEFAULT_STATUS_BUILD, DEFAULT_STATUS_INTEGRATION, DEFAULT_STATUS_RELEASE};

    public DefaultWorkflow() {
        super("DEFAULT_WORKFLOW", Arrays.asList(status));
    }

    public StatusVersion extractStatusAndVersionFromMavenVersion(String version) {
        final String snapshotVersionSuffix = "-SNAPSHOT";
        StatusVersion statusVersion = new StatusVersion();
        if (version.endsWith(snapshotVersionSuffix)) {
            statusVersion.status = DEFAULT_STATUS_BUILD;
            statusVersion.version = version.substring(0, version.lastIndexOf(snapshotVersionSuffix));
            return statusVersion;
        }

        if (version.endsWith("." + DEFAULT_STATUS_INTEGRATION)) {
            statusVersion.status = DEFAULT_STATUS_INTEGRATION;
            statusVersion.version = version.substring(0, version.lastIndexOf("." + DEFAULT_STATUS_INTEGRATION));
            return statusVersion;
        }

        statusVersion.status = DEFAULT_STATUS_RELEASE;
        statusVersion.version = version;
        return statusVersion;
    }
}

package fr.synchrotron.soleil.ica.ci.lib.workflow;

import java.util.Arrays;

/**
 * @author Gregory Boissinot
 */
public class DefaultWorkflow extends Workflow {

    private static final String DEFAULT_STATUS_BUILD = "BUILD";
    private static final String DEFAULT_STATUS_INTEGRATION = "INTEGRATION";
    private static final String DEFAULT_STATUS_RELEASE = "RELEASE";
    private static final String[] status = new String[]{DEFAULT_STATUS_BUILD, DEFAULT_STATUS_INTEGRATION, DEFAULT_STATUS_RELEASE};

    public DefaultWorkflow() {
        super("DEFAULT_WORKFLOW", Arrays.asList(status));
    }

    public StatusVersion extractStatusAndVersionFromMavenVersion(String version) {
        final String snapshotVersionSuffix = "-SNAPSHOT";
        StatusVersion statusVersion = new StatusVersion();
        if (version.endsWith(snapshotVersionSuffix)) {
            statusVersion.status = DEFAULT_STATUS_BUILD;
            statusVersion.version = version.substring(0, version.lastIndexOf(snapshotVersionSuffix));
            return statusVersion;
        }

        if (version.endsWith("." + DEFAULT_STATUS_INTEGRATION)) {
            statusVersion.status = DEFAULT_STATUS_INTEGRATION;
            statusVersion.version = version.substring(0, version.lastIndexOf("." + DEFAULT_STATUS_INTEGRATION));
            return statusVersion;
        }

        if (version.endsWith("." + DEFAULT_STATUS_RELEASE)) {
            statusVersion.status = DEFAULT_STATUS_RELEASE;
            statusVersion.version = version.substring(0, version.lastIndexOf("." + DEFAULT_STATUS_RELEASE));
            return statusVersion;
        }

        statusVersion.status = DEFAULT_STATUS_RELEASE;
        statusVersion.version = version;
        return statusVersion;
    }
}

Fix bug for release status


package com.redhat.ceylon.eclipse.core.model;

import java.lang.ref.WeakReference;

import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit;
import com.redhat.ceylon.eclipse.core.typechecker.IdePhasedUnit;

public abstract class CeylonUnit extends IdeUnit {

    public CeylonUnit() {
        phasedUnitRef = null;
    }

    protected WeakReference<IdePhasedUnit> phasedUnitRef;

    final protected void createPhasedUnitRef(IdePhasedUnit phasedUnit) {
        phasedUnitRef = new WeakReference<IdePhasedUnit>(phasedUnit);
    }

    protected abstract void setPhasedUnitIfNecessary();

    public IdePhasedUnit getPhasedUnit() {
        setPhasedUnitIfNecessary();
        return phasedUnitRef.get();
    }
}

package com.redhat.ceylon.eclipse.core.model;

import java.lang.ref.WeakReference;

import com.redhat.ceylon.compiler.typechecker.context.PhasedUnit;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
import com.redhat.ceylon.eclipse.core.typechecker.IdePhasedUnit;

public abstract class CeylonUnit extends IdeUnit {

    public CeylonUnit() {
        phasedUnitRef = null;
    }

    protected WeakReference<IdePhasedUnit> phasedUnitRef;

    final protected void createPhasedUnitRef(IdePhasedUnit phasedUnit) {
        phasedUnitRef = new WeakReference<IdePhasedUnit>(phasedUnit);
    }

    protected abstract void setPhasedUnitIfNecessary();

    public IdePhasedUnit getPhasedUnit() {
        setPhasedUnitIfNecessary();
        return phasedUnitRef.get();
    }

    public Tree.CompilationUnit getCompilationUnit() {
        IdePhasedUnit pu = getPhasedUnit();
        if (pu == null) {
            return null;
        }
        return pu.getCompilationUnit();
    }

}

Add a CompilationUnit getter on the model Unit (to avoid testing for null each time)


package org.broadinstitute.sting.gatk.walkers.varianteval.stratifications;

import org.broadinstitute.sting.gatk.contexts.ReferenceContext;
import org.broadinstitute.sting.gatk.refdata.RefMetaDataTracker;
import org.broadinstitute.sting.utils.variantcontext.VariantContext;

import java.util.ArrayList;

public class Sample extends VariantStratifier {
    // needs the sample names
    private ArrayList<String> samples;

    @Override
    public void initialize() {
        samples = new ArrayList<String>();
        samples.addAll(getVariantEvalWalker().getSampleNamesForEvaluation());
    }

    public ArrayList<String> getAllStates() {
        return samples;
    }

    public ArrayList<String> getRelevantStates(ReferenceContext ref, RefMetaDataTracker tracker, VariantContext comp, String compName, VariantContext eval, String evalName, String sampleName) {
        ArrayList<String> relevantStates = new ArrayList<String>();
        relevantStates.add(sampleName);

        return relevantStates;
    }
}

package org.broadinstitute.sting.gatk.walkers.varianteval.stratifications;

import org.broadinstitute.sting.gatk.contexts.ReferenceContext;
import org.broadinstitute.sting.gatk.refdata.RefMetaDataTracker;
import org.broadinstitute.sting.utils.variantcontext.VariantContext;

import java.util.ArrayList;

public class Sample extends VariantStratifier {
    // needs the sample names
    private ArrayList<String> samples;

    @Override
    public void initialize() {
        samples = new ArrayList<String>();
        samples.addAll(getVariantEvalWalker().getSampleNamesForStratification());
    }

    public ArrayList<String> getAllStates() {
        return samples;
    }

    public ArrayList<String> getRelevantStates(ReferenceContext ref, RefMetaDataTracker tracker, VariantContext comp, String compName, VariantContext eval, String evalName, String sampleName) {
        ArrayList<String> relevantStates = new ArrayList<String>();
        relevantStates.add(sampleName);

        return relevantStates;
    }
}

Use the right set of sample names


package com.lagopusempire.lagopuscommandsystem.parsing;

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

/**
 *
 * @author MrZoraman
 */
public abstract class SyntaxParserBase
{
    private final String script;

    private final StringBuilder builder = new StringBuilder();
    private final List<String> elements = new ArrayList<>();

    public SyntaxParserBase(String script)
    {
        this.script = script;
    }

    protected abstract void iterate(int index, char c);

    protected void finished() { }

    protected void flush()
    {
        if(builder.length() > 0)
        {
            elements.add(builder.toString());
            builder.setLength(0);
        }
    }

    protected void push(char c)
    {
        builder.append(c);
    }

    public String[] parse()
    {
        char[] chars = script.toCharArray();
        for(int ii = 0; ii < chars.length; ii++)
        {
            iterate(ii, chars[ii]);
        }

        finished();

        flush();

        return elementsToArray();
    }

    private String[] elementsToArray()
    {
        return elements.toArray(new String[elements.size()]);
    }
}

package com.lagopusempire.lagopuscommandsystem.parsing;

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

/**
 *
 * @author MrZoraman
 */
public abstract class SyntaxParserBase
{
    private final String script;

    private final StringBuilder builder = new StringBuilder();
    private final List<String> elements = new ArrayList<>();

    public SyntaxParserBase(String script)
    {
        this.script = script;
    }

    protected abstract void iterate(int index, char c);

    protected void finished() { }

    protected void flush()
    {
        if(builder.length() > 0)
        {
            elements.add(builder.toString());
            builder.setLength(0);
        }
    }

    protected void push(char c)
    {
        builder.append(c);
    }

    public String[] parse()
    {
        char[] chars = script.toCharArray();
        int ii = 0;
        for(ii = 0; ii < chars.length; ii++)
        {
            iterate(ii, chars[ii]);
        }

        finished();

        flush();

        return elementsToArray();
    }

    private String[] elementsToArray()
    {
        return elements.toArray(new String[elements.size()]);
    }
}

Revert "cleaned up code a little"


package com.example;

import org.junit.runners.model.InitializationError;
import org.robolectric.AndroidManifest;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.res.Fs;

/**
 * A Robolectric TestRunner for running tests in a Gradle SubModule.
 * Created by jasondonmoyer on 11/24/14.
 */
public class RobolectricGradleSubModuleTestRunner extends RobolectricTestRunner {

    private static final int MAX_SDK_SUPPORTED_BY_ROBOLECTRIC = 18;

    public RobolectricGradleSubModuleTestRunner(Class<?> testClass) throws InitializationError {
        super(testClass);
    }

    protected String getAndroidManifestPath() {
        return "../deckard-gradle/app/src/main/AndroidManifest.xml";
    }

    protected String getResPath() {
        return "../deckard-gradle/app/src/main/res";
    }

    @Override
    protected final AndroidManifest getAppManifest(Config config) {
        return new AndroidManifest(Fs.fileFromPath(getAndroidManifestPath()),
                Fs.fileFromPath(getResPath())) {
            @Override
            public int getTargetSdkVersion() {
                return MAX_SDK_SUPPORTED_BY_ROBOLECTRIC;
            }
        };
    }

}

package com.example;

import org.junit.runners.model.InitializationError;
import org.robolectric.AndroidManifest;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.res.Fs;

/**
 * A Robolectric TestRunner for running tests in a Gradle SubModule.
 * Created by jasondonmoyer on 11/24/14.
 */
public class RobolectricGradleSubModuleTestRunner extends RobolectricTestRunner {

    private static final int MAX_SDK_SUPPORTED_BY_ROBOLECTRIC = 18;

    public RobolectricGradleSubModuleTestRunner(Class<?> testClass) throws InitializationError {
        super(testClass);
    }

    protected String getAndroidManifestPath() {
        return "../app/src/main/AndroidManifest.xml";
    }

    protected String getResPath() {
        return "../app/src/main/res";
    }

    @Override
    protected final AndroidManifest getAppManifest(Config config) {
        return new AndroidManifest(Fs.fileFromPath(getAndroidManifestPath()),
                Fs.fileFromPath(getResPath())) {
            @Override
            public int getTargetSdkVersion() {
                return MAX_SDK_SUPPORTED_BY_ROBOLECTRIC;
            }
        };
    }

}

Correct AndroidManifest and res paths


/*
 * Copyright 2000-2014 JetBrains s.r.o.
 *
 * 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.intellij.openapi.vfs.encoding;

import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurableProvider;
import com.intellij.openapi.project.Project;
import com.intellij.util.PlatformUtils;

/**
 * @author Sergey.Malenkov
 */
public final class FileEncodingConfigurableProvider extends ConfigurableProvider {
  private final Project myProject;

  public FileEncodingConfigurableProvider(Project project) {
    myProject = project;
  }

  @Override
  public boolean canCreateConfigurable() {
    return !PlatformUtils.isRubyMine();
  }

  @Override
  public Configurable createConfigurable() {
    return new FileEncodingConfigurable(myProject);
  }
}

/*
 * Copyright 2000-2014 JetBrains s.r.o.
 *
 * 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.intellij.openapi.vfs.encoding;

import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurableProvider;
import com.intellij.openapi.project.Project;

/**
 * @author Sergey.Malenkov
 */
public final class FileEncodingConfigurableProvider extends ConfigurableProvider {
  private final Project myProject;

  public FileEncodingConfigurableProvider(Project project) {
    myProject = project;
  }

  @Override
  public boolean canCreateConfigurable() {
    return true;
  }

  @Override
  public Configurable createConfigurable() {
    return new FileEncodingConfigurable(myProject);
  }
}

Return "File Encodings" settings page for RubyMine


package com.alexstyl.specialdates.search;

import com.alexstyl.specialdates.contact.Contact;
import com.alexstyl.specialdates.date.ContactEvent;
import com.alexstyl.specialdates.events.peopleevents.EventType;

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

final class ContactEventViewModelFactory {

    private final ContactEventLabelCreator eventLabelCreator;

    ContactEventViewModelFactory(ContactEventLabelCreator eventLabelCreator) {
        this.eventLabelCreator = eventLabelCreator;
    }

    List<ContactEventViewModel> createViewModelFrom(List<ContactWithEvents> contactEvents) {
        List<ContactEventViewModel> models = new ArrayList<>();
        for (ContactWithEvents contactEvent : contactEvents) {

            Contact contact = contactEvent.getContact();

            for (ContactEvent event : contactEvent.getEvents()) {
                String eventLabel = eventLabelCreator.createFor(event);
                int variant = getVariationFor(event);
                ContactEventViewModel viewModel = new ContactEventViewModel(contact, eventLabel, colorOf(event.getType()), variant);
                models.add(viewModel);
            }
        }
        return models;
    }

    private int colorOf(EventType type) {
        return 0;
    }

    private int getVariationFor(ContactEvent event) {
        return (int) event.getContact().getContactID();
    }
}

package com.alexstyl.specialdates.search;

import com.alexstyl.specialdates.contact.Contact;
import com.alexstyl.specialdates.date.ContactEvent;
import com.alexstyl.specialdates.upcoming.EventColors;

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

final class ContactEventViewModelFactory {

    private final ContactEventLabelCreator eventLabelCreator;

    ContactEventViewModelFactory(ContactEventLabelCreator eventLabelCreator) {
        this.eventLabelCreator = eventLabelCreator;
    }

    List<ContactEventViewModel> createViewModelFrom(List<ContactWithEvents> contactEvents) {
        List<ContactEventViewModel> models = new ArrayList<>();
        for (ContactWithEvents contactEvent : contactEvents) {

            Contact contact = contactEvent.getContact();

            for (ContactEvent event : contactEvent.getEvents()) {
                String eventLabel = eventLabelCreator.createFor(event);
                int variant = getVariationFor(event);
                ContactEventViewModel viewModel = new ContactEventViewModel(
                        contact,
                        eventLabel,
                        EventColors.INSTANCE.colorOf(event.getType()),
                        variant
                );
                models.add(viewModel);
            }
        }
        return models;
    }

    private int getVariationFor(ContactEvent event) {
        return (int) event.getContact().getContactID();
    }
}

Use EventColors to pass the right event color


// Copyright (c) 1999 Brian Wellington (bwelling@xbill.org)
// Portions Copyright (c) 1999 Network Associates, Inc.

package org.xbill.DNS;

import java.util.*;
import java.io.*;
import java.net.*;

/**
 * A special-purpose thread used by Resolvers (both SimpleResolver and
 * ExtendedResolver) to perform asynchronous queries.
 *
 * @author Brian Wellington
 */

class ResolveThread implements Runnable {

private Message query;
private Object id;
private ResolverListener listener;
private Resolver res;

/** Creates a new ResolveThread */
public
ResolveThread(Resolver res, Message query, Object id,
	      ResolverListener listener)
{
	this.res = res;
	this.query = query;
	this.id = id;
	this.listener = listener;
}

/**
 * Performs the query, and executes the callback.
 */
public void
run() {
	try {
		Message response = res.send(query);
		listener.receiveMessage(id, response);
	}
	catch (Exception e) {
		listener.handleException(id, e);
	}
}

}

// Copyright (c) 1999 Brian Wellington (bwelling@xbill.org)
// Portions Copyright (c) 1999 Network Associates, Inc.

package org.xbill.DNS;

import java.util.*;
import java.io.*;
import java.net.*;

/**
 * A special-purpose thread used by Resolvers (both SimpleResolver and
 * ExtendedResolver) to perform asynchronous queries.
 *
 * @author Brian Wellington
 */

class ResolveThread extends Thread {

private Message query;
private Object id;
private ResolverListener listener;
private Resolver res;

/** Creates a new ResolveThread */
public
ResolveThread(Resolver res, Message query, Object id,
	      ResolverListener listener)
{
	this.res = res;
	this.query = query;
	this.id = id;
	this.listener = listener;
}

/**
 * Performs the query, and executes the callback.
 */
public void
run() {
	try {
		Message response = res.send(query);
		listener.receiveMessage(id, response);
	}
	catch (Exception e) {
		listener.handleException(id, e);
	}
}

}

Make this a subclass of Thread.


package org.wildfly.swarm.examples.jaxrs.swagger;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import io.swagger.annotations.*;
import javax.ws.rs.core.MediaType;

import org.joda.time.DateTime;

@Path("/time")
@Api(value = "/time", description = "Get the time", tags = "time")
@Produces(MediaType.APPLICATION_JSON)
public class TimeResource {

    @GET
    @Path("/now")
    @ApiOperation(value = "Get the current time",
            notes = "Returns the time as a string",
            response = String.class
    )
    @Produces(MediaType.APPLICATION_JSON)
    public String get() {
        return "The time is " + new DateTime();
    }
}

package org.wildfly.swarm.examples.jaxrs.swagger;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import io.swagger.annotations.*;
import javax.ws.rs.core.MediaType;

import org.joda.time.DateTime;

@Path("/time")
@Api(value = "/time", description = "Get the time", tags = "time")
@Produces(MediaType.APPLICATION_JSON)
public class TimeResource {

    @GET
    @Path("/now")
    @ApiOperation(value = "Get the current time",
            notes = "Returns the time as a string",
            response = String.class
    )
    @Produces(MediaType.APPLICATION_JSON)
    public String get() {
        return String.format("{\"value\" : \"The time is %s\"}", new DateTime());
    }
}

Change the format into json because Swagger UI requires strict JSON


package com.strohwitwer.awesomevalidation.validators;

import android.graphics.Color;
import android.widget.EditText;

import com.strohwitwer.awesomevalidation.ValidationHolder;
import com.strohwitwer.awesomevalidation.helper.RangeHelper;
import com.strohwitwer.awesomevalidation.helper.SpanHelper;
import com.strohwitwer.awesomevalidation.utility.ValidationCallback;

import java.util.ArrayList;
import java.util.regex.Matcher;

public class ColorationValidator extends Validator {

    private int mColor = Color.RED;

    public void setColor(int color) {
        mColor = color;
    }

    @Override
    public boolean trigger() {
        return checkFields(new ValidationCallback() {
            @Override
            public void execute(ValidationHolder validationHolder, Matcher matcher) {
                ArrayList<int[]> listOfMatching = new ArrayList<int[]>();
                while (matcher.find()) {
                    listOfMatching.add(new int[]{matcher.start(), matcher.end() - 1});
                }
                EditText editText = validationHolder.getEditText();
                ArrayList<int[]> listOfNotMatching = RangeHelper.inverse(listOfMatching, validationHolder.getText().length());
                SpanHelper.setColor(editText, mColor, listOfNotMatching);
                editText.setError(validationHolder.getErrMsg());
            }
        });
    }

    @Override
    public void halt() {
        for (ValidationHolder validationHolder : mValidationHolderList) {
            EditText editText = validationHolder.getEditText();
            editText.setError(null);
            SpanHelper.reset(editText);
        }
    }

}

package com.strohwitwer.awesomevalidation.validators;

import android.graphics.Color;
import android.widget.EditText;

import com.strohwitwer.awesomevalidation.ValidationHolder;
import com.strohwitwer.awesomevalidation.helper.RangeHelper;
import com.strohwitwer.awesomevalidation.helper.SpanHelper;
import com.strohwitwer.awesomevalidation.utility.ValidationCallback;

import java.util.ArrayList;
import java.util.regex.Matcher;

public class ColorationValidator extends Validator {

    private int mColor = Color.RED;

    public void setColor(int color) {
        mColor = color;
    }

    @Override
    public boolean trigger() {
        halt();
        return checkFields(new ValidationCallback() {
            @Override
            public void execute(ValidationHolder validationHolder, Matcher matcher) {
                ArrayList<int[]> listOfMatching = new ArrayList<int[]>();
                while (matcher.find()) {
                    listOfMatching.add(new int[]{matcher.start(), matcher.end() - 1});
                }
                EditText editText = validationHolder.getEditText();
                ArrayList<int[]> listOfNotMatching = RangeHelper.inverse(listOfMatching, validationHolder.getText().length());
                SpanHelper.setColor(editText, mColor, listOfNotMatching);
                editText.setError(validationHolder.getErrMsg());
            }
        });
    }

    @Override
    public void halt() {
        for (ValidationHolder validationHolder : mValidationHolderList) {
            EditText editText = validationHolder.getEditText();
            editText.setError(null);
            SpanHelper.reset(editText);
        }
    }

}

Add the missing halt() call in trigger method to clear previous styles.


package tk.martijn_heil.kingdomessentials.signs;

import lombok.Getter;
import org.jetbrains.annotations.Nullable;

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

import static com.google.common.base.Preconditions.checkArgument;

public class ExecutableSignRegister
{
    @Getter private List<ExecutableSign> registeredSigns = new ArrayList<>();

    public void addExecutableSign(ExecutableSign sign)
    {
        checkArgument(!registeredSigns.contains(sign), "this sign is already registered.");
    }

    @Nullable
    public ExecutableSign get(String action)
    {
        for (ExecutableSign sign : registeredSigns)
        {
            if(sign.getAction().equals(action)) return sign;
        }

        return null;
    }
}

package tk.martijn_heil.kingdomessentials.signs;

import lombok.Getter;
import org.jetbrains.annotations.Nullable;

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

import static com.google.common.base.Preconditions.checkArgument;

public class ExecutableSignRegister
{
    @Getter private List<ExecutableSign> registeredSigns = new ArrayList<>();

    public void addExecutableSign(ExecutableSign sign)
    {
        checkArgument(!registeredSigns.contains(sign), "this sign is already registered.");

        this.registeredSigns.add(sign);
    }

    @Nullable
    public ExecutableSign get(String action)
    {
        for (ExecutableSign sign : registeredSigns)
        {
            if(sign.getAction().equals(action)) return sign;
        }

        return null;
    }
}

Fix a new ExecutableSign not being added to the register


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

package com.googlesource.gerrit.plugins.cookbook;

import com.google.gerrit.sshd.CommandMetaData;
import com.google.gerrit.sshd.SshCommand;

import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.Option;

@CommandMetaData(name = "print", description = "Print greeting in different languages")
public final class PrintHelloWorldCommand extends SshCommand {

  @Argument(usage = "name of user")
  private String name = "world";

  @Option(name = "--french", usage = "output in French?")
  private boolean french = false;

  @Override
  public void run() throws UnloggedFailure, Failure, Exception {
    final String greeting = (french ? "Bonjour " : "Hello ");
    // Note the use of '\n' instead of println to keep platform-agnostic line
    // terminator.
    stdout.print(greeting + name + "!\n");
  }
}

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

package com.googlesource.gerrit.plugins.cookbook;

import com.google.gerrit.sshd.CommandMetaData;
import com.google.gerrit.sshd.SshCommand;

import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.Option;

@CommandMetaData(name = "print", description = "Print greeting in different languages")
public final class PrintHelloWorldCommand extends SshCommand {

  @Argument(usage = "name of user")
  private String name = "world";

  @Option(name = "--french", usage = "output in French?")
  private boolean french = false;

  @Override
  public void run() {
    final String greeting = (french ? "Bonjour " : "Hello ");
    // Note the use of '\n' instead of println to keep platform-agnostic line
    // terminator.
    stdout.print(greeting + name + "!\n");
  }
}

Remove unnecessary exceptions from hello command class declaration


package fr.tvbarthel.apps.simpleweatherforcast.ui;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.List;

import fr.tvbarthel.apps.simpleweatherforcast.R;
import fr.tvbarthel.apps.simpleweatherforcast.model.App;

public class MoreAppsAdapter extends ArrayAdapter<App> {

    public MoreAppsAdapter(Context context, List<App> apps) {
        super(context, R.layout.row_more_apps, apps);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        RelativeLayout appView = (RelativeLayout) convertView;
        App app = getItem(position);

        if (appView == null) {
            LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            appView = (RelativeLayout) inflater.inflate(R.layout.row_more_apps, parent, false);
        }

        ((TextView) appView.findViewById(R.id.row_more_apps_name)).setText(app.getNameResourceId());
        ((ImageView) appView.findViewById(R.id.row_more_apps_logo)).setImageResource(app.getLogoResourceId());

        return appView;
    }
}

package fr.tvbarthel.apps.simpleweatherforcast.ui;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.List;

import fr.tvbarthel.apps.simpleweatherforcast.R;
import fr.tvbarthel.apps.simpleweatherforcast.model.App;

public class MoreAppsAdapter extends ArrayAdapter<App> {

    public MoreAppsAdapter(Context context, List<App> apps) {
        super(context, R.layout.row_more_apps, apps);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        RelativeLayout appView = (RelativeLayout) convertView;
        App app = getItem(position);

        if (appView == null) {
            LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            appView = (RelativeLayout) inflater.inflate(R.layout.row_more_apps, parent, false);
            ViewHolder holder = new ViewHolder();
            holder.appName = (TextView) appView.findViewById(R.id.row_more_apps_name);
            holder.appLogo = (ImageView) appView.findViewById(R.id.row_more_apps_logo);
            appView.setTag(holder);
        }

        ViewHolder holder = (ViewHolder) appView.getTag();
        holder.appName.setText(app.getNameResourceId());
        holder.appLogo.setImageResource(app.getLogoResourceId());

        return appView;
    }

    private static class ViewHolder {
        TextView appName;
        ImageView appLogo;
    }
}

Use a view holder pattern


// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.jdisc.metric;

import com.yahoo.jdisc.Metric;
import com.yahoo.jdisc.application.MetricConsumer;
import com.yahoo.jdisc.core.ActiveContainerStatistics;
import org.junit.Test;
import org.mockito.Mockito;

import static org.junit.Assert.assertTrue;

public class MetricUpdaterTest {

    @Test
    public void testFreeMemory() throws InterruptedException {
        MetricConsumer consumer = Mockito.mock(MetricConsumer.class);
        MetricProvider provider = MetricProviders.newInstance(consumer);

        Metric metric = provider.get();
        MetricUpdater updater = new MetricUpdater(metric, Mockito.mock(ActiveContainerStatistics.class), 10);
        long start = System.currentTimeMillis();
        boolean updated = false;
        while (System.currentTimeMillis() - start < 60000 && !updated) {
            Thread.sleep(10);
            if (memoryMetricsUpdated(updater)) {
                updated = true;
            }
        }
        assertTrue(memoryMetricsUpdated(updater));
    }

    private boolean memoryMetricsUpdated(MetricUpdater updater) {
        return updater.getFreeMemory()>0 && updater.getTotalMemory()>0;
    }
}

// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.jdisc.metric;

import com.yahoo.jdisc.Metric;
import com.yahoo.jdisc.application.MetricConsumer;
import com.yahoo.jdisc.core.ActiveContainerStatistics;
import org.junit.Test;
import org.mockito.Mockito;

import static org.junit.Assert.assertTrue;

public class MetricUpdaterTest {

    @Test
    public void testFreeMemory() throws InterruptedException {
        MetricConsumer consumer = Mockito.mock(MetricConsumer.class);
        MetricProvider provider = MetricProviders.newInstance(consumer);

        Metric metric = provider.get();
        MetricUpdater updater = new MetricUpdater(metric, new ActiveContainerStatistics(), 10);
        long start = System.currentTimeMillis();
        boolean updated = false;
        while (System.currentTimeMillis() - start < 60000 && !updated) {
            Thread.sleep(10);
            if (memoryMetricsUpdated(updater)) {
                updated = true;
            }
        }
        assertTrue(memoryMetricsUpdated(updater));
    }

    private boolean memoryMetricsUpdated(MetricUpdater updater) {
        return updater.getFreeMemory()>0 && updater.getTotalMemory()>0;
    }
}

Revert "Mock ActiveContainerStatistics as its constructor is package-private"


package org.knowm.xchange.binance.dto.account;

import com.fasterxml.jackson.annotation.JsonProperty;
import java.math.BigDecimal;
import java.util.List;

public final class BinanceAccountInformation {

  public final BigDecimal makerCommission;
  public final BigDecimal takerCommission;
  public final BigDecimal buyerCommission;
  public final BigDecimal sellerCommission;
  public final boolean canTrade;
  public final boolean canWithdraw;
  public final boolean canDeposit;
  public List<BinanceBalance> balances;

  public BinanceAccountInformation(
      @JsonProperty("makerCommission") BigDecimal makerCommission,
      @JsonProperty("takerCommission") BigDecimal takerCommission,
      @JsonProperty("buyerCommission") BigDecimal buyerCommission,
      @JsonProperty("sellerCommission") BigDecimal sellerCommission,
      @JsonProperty("canTrade") boolean canTrade,
      @JsonProperty("canWithdraw") boolean canWithdraw,
      @JsonProperty("canDeposit") boolean canDeposit,
      @JsonProperty("balances") List<BinanceBalance> balances) {
    this.makerCommission = makerCommission;
    this.takerCommission = takerCommission;
    this.buyerCommission = buyerCommission;
    this.sellerCommission = sellerCommission;
    this.canTrade = canTrade;
    this.canWithdraw = canWithdraw;
    this.canDeposit = canDeposit;
    this.balances = balances;
  }
}

package org.knowm.xchange.binance.dto.account;

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

import com.fasterxml.jackson.annotation.JsonProperty;

public final class BinanceAccountInformation {

  public final BigDecimal makerCommission;
  public final BigDecimal takerCommission;
  public final BigDecimal buyerCommission;
  public final BigDecimal sellerCommission;
  public final boolean canTrade;
  public final boolean canWithdraw;
  public final boolean canDeposit;
  public final long updateTime;
  public List<BinanceBalance> balances;

  public BinanceAccountInformation(
      @JsonProperty("makerCommission") BigDecimal makerCommission,
      @JsonProperty("takerCommission") BigDecimal takerCommission,
      @JsonProperty("buyerCommission") BigDecimal buyerCommission,
      @JsonProperty("sellerCommission") BigDecimal sellerCommission,
      @JsonProperty("canTrade") boolean canTrade,
      @JsonProperty("canWithdraw") boolean canWithdraw,
      @JsonProperty("canDeposit") boolean canDeposit,
      @JsonProperty("updateTime") long updateTime,
      @JsonProperty("balances") List<BinanceBalance> balances) {
    this.makerCommission = makerCommission;
    this.takerCommission = takerCommission;
    this.buyerCommission = buyerCommission;
    this.sellerCommission = sellerCommission;
    this.canTrade = canTrade;
    this.canWithdraw = canWithdraw;
    this.canDeposit = canDeposit;
    this.updateTime = updateTime;
    this.balances = balances;
  }
}

Include timestamp in balance requests


/*
 * Copyright 2015 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.gradle.model.internal.registry;

import com.google.common.collect.Lists;
import org.gradle.api.Nullable;
import org.gradle.model.internal.core.rule.describe.ModelRuleDescriptor;

import java.util.Deque;

public class RuleContext {

    private static final ThreadLocal<Deque<ModelRuleDescriptor>> STACK = new ThreadLocal<Deque<ModelRuleDescriptor>>() {
        @Override
        protected Deque<ModelRuleDescriptor> initialValue() {
            return Lists.newLinkedList();
        }
    };

    @Nullable
    public static ModelRuleDescriptor get() {
        return STACK.get().peek();
    }

    public static void run(ModelRuleDescriptor descriptor, Runnable runnable) {
        STACK.get().push(descriptor);
        try {
            runnable.run();
        } finally {
            STACK.get().pop();
        }
    }
}

/*
 * Copyright 2015 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.gradle.model.internal.registry;

import org.gradle.api.Nullable;
import org.gradle.model.internal.core.rule.describe.ModelRuleDescriptor;

import java.util.ArrayDeque;
import java.util.Deque;

public class RuleContext {

    private static final ThreadLocal<Deque<ModelRuleDescriptor>> STACK = new ThreadLocal<Deque<ModelRuleDescriptor>>() {
        @Override
        protected Deque<ModelRuleDescriptor> initialValue() {
            return new ArrayDeque<ModelRuleDescriptor>();
        }
    };

    @Nullable
    public static ModelRuleDescriptor get() {
        return STACK.get().peek();
    }

    public static void run(ModelRuleDescriptor descriptor, Runnable runnable) {
        STACK.get().push(descriptor);
        try {
            runnable.run();
        } finally {
            STACK.get().pop();
        }
    }
}

Use an ArrayDeque instead of LinkedList to store current rule execution context


import org.json.simple.JSONObject;

/** Representation of the geoip information for a given IP address, created
    from a JSON representation of the information returned by the Pings server.
    Includes the longitude and latitude, and the city and country.
 */
public class GeoipInfo {

    final public String city;
    final public String country;

    final public double longitude;
    final public double latitude;

    /** Constructs a GeoipInfo object from JSON information returned by
        the Pings server. */
    public GeoipInfo(JSONObject json) {
        city = (String)json.get("city");
        country = (String)json.get("country_name");

        /*FIXME : jsonobject get cast into doubles which are cast into floats
        and then cast back into double*/
        longitude = ((Double)json.get("longitude")).floatValue();
        latitude = ((Double)json.get("latitude")).floatValue();
    }

    /**
     * An alternative constructor for testing purpose
     */
    //TODO : remove it when useless
    public GeoipInfo(String city,String country,double longitude,double latitude) {
    	this.city = city;
    	this.country = country;
    	this.longitude = longitude;
    	this.latitude = latitude;
    }
}

import org.json.simple.JSONObject;

/** Representation of the geoip information for a given IP address, created
    from a JSON representation of the information returned by the Pings server.
    Includes the longitude and latitude, and the city and country.
 */
public class GeoipInfo {

    final public String city;
    final public String country;

    final public double longitude;
    final public double latitude;

    /** Constructs a GeoipInfo object from JSON information returned by
        the Pings server. */
    public GeoipInfo(JSONObject json) {
        city = (String)json.get("city");
        country = (String)json.get("country_name");

        longitude = ((Number)json.get("longitude")).doubleValue();
        latitude = ((Number)json.get("latitude")).doubleValue();
    }

    /**
     * An alternative constructor for testing purposes.
     */
    public GeoipInfo(String city, String country,
                     double longitude, double latitude) {
    	this.city = city;
    	this.country = country;
    	this.longitude = longitude;
    	this.latitude = latitude;
    }
}

Fix conversion of parsed JSON numbers to double so they do not go through a float value in between; also use correct Java base class returned by Json-simple for boxed numbers.


package com.creitz.sudokusolver;

//Charles Reitz
//1/4/15

public class SudokuSolver {

	private Grid mGrid;

	public SudokuSolver(String file) {
		mGrid = new Grid(file);
	}

	public boolean solve() {

		while (mGrid.hasEmpty()) {
			if (!mGrid.fillAnyEmptySquare()) {
				break;
			}
		}

		return !mGrid.hasEmpty();
	}

	public Grid getGrid() {
		return mGrid;
	}

	public void print() {
		mGrid.print();
	}

	public static void main(String[] args) {

		SudokuSolver solver = new SudokuSolver(args[0]);
		System.out.println("\nRead board: ");
		solver.print();
		if (solver.solve()) {
			System.out.println("Solution board: ");
			solver.print();
		} else {
			System.out.println("Board has multiple solutions or no solution.");
			solver.print();
		}
	}
}

package com.creitz.sudokusolver;

//Charles Reitz
//1/4/15

public class SudokuSolver {

	private Grid mGrid;

	public SudokuSolver(String file) {
		mGrid = new Grid(file);
	}

	public boolean solve() {

		while (mGrid.hasEmpty()) {
			if (!mGrid.fillAnyEmptySquare()) {
				break;
			}
		}

		return !mGrid.hasEmpty();
	}

	public Grid getGrid() {
		return mGrid;
	}

	public void print() {
		mGrid.print();
	}

	public static void main(String[] args) {

		SudokuSolver solver = new SudokuSolver(args[0]);
		System.out.println("\nRead board: ");
		solver.print();
		if (solver.solve()) {
			System.out.println("Solution board: ");
			solver.print();
		} else {
			System.out.println("Board does not have a unique solution.");
		}
	}
}

Add test for no solution.


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

import com.axelor.apps.crm.db.Opportunity;

public class OpportunityManagementRepository extends OpportunityRepository {
	@Override
	public Opportunity copy(Opportunity entity, boolean deep) {
		entity.setSalesStageSelect(1);
		return super.copy(entity, deep);
	}
}

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

import com.axelor.apps.crm.db.Opportunity;

public class OpportunityManagementRepository extends OpportunityRepository {
	@Override
	public Opportunity copy(Opportunity entity, boolean deep) {
		entity.setSalesStageSelect(1);
		entity.setLostReason(null);
		return super.copy(entity, deep);
	}
}

Reset lost reason field on copy


package fr.inria.jessy.protocol;

import java.util.Set;

import fr.inria.jessy.communication.JessyGroupManager;
import fr.inria.jessy.store.DataStore;
import fr.inria.jessy.transaction.ExecutionHistory;
import fr.inria.jessy.transaction.termination.TwoPhaseCommit;

/**
 * This class implements Non-Monotonic Snapshot Isolation consistency criterion.
 *
 * @author Masoud Saeida Ardekani
 *
 */
public class NMSI_PDV_2PC extends NMSI_PDV_GC {

	public NMSI_PDV_2PC(JessyGroupManager m, DataStore dataStore) {
		super(m, dataStore);
	}

	/**
	 * Coordinator needs to only wait for the vote from the 2PC manager.
	 *
	 */
	@Override
	public Set<String> getVotersToJessyProxy(
			Set<String> termincationRequestReceivers,
			ExecutionHistory executionHistory) {
		termincationRequestReceivers.clear();
		termincationRequestReceivers.add(TwoPhaseCommit.getCoordinatorId(executionHistory,manager.getPartitioner()));
		return termincationRequestReceivers;
	}
}

package fr.inria.jessy.protocol;

import java.util.Set;

import fr.inria.jessy.communication.JessyGroupManager;
import fr.inria.jessy.store.DataStore;
import fr.inria.jessy.transaction.ExecutionHistory;
import fr.inria.jessy.transaction.termination.TwoPhaseCommit;
import fr.inria.jessy.transaction.termination.vote.Vote;

/**
 * This class implements Non-Monotonic Snapshot Isolation consistency criterion.
 *
 * @author Masoud Saeida Ardekani
 *
 */
public class NMSI_PDV_2PC extends NMSI_PDV_GC {

	public NMSI_PDV_2PC(JessyGroupManager m, DataStore dataStore) {
		super(m, dataStore);
	}

	/**
	 * Coordinator needs to only wait for the vote from the 2PC manager.
	 *
	 */
	@Override
	public Set<String> getVotersToJessyProxy(
			Set<String> termincationRequestReceivers,
			ExecutionHistory executionHistory) {
		termincationRequestReceivers.clear();
		termincationRequestReceivers.add(TwoPhaseCommit.getCoordinatorId(executionHistory,manager.getPartitioner()));
		return termincationRequestReceivers;
	}

	@Override
	public void voteReceived(Vote vote) {

		/*
		 * if vote.getVotePiggyBack() is null, it means that it is preemptively aborted in DistributedTermination, and
		 * DistributedTermination sets votePiggyback to null.
		 *
		 */
		if (vote.getVotePiggyBack()==null ){
			return;
		}

		super.voteReceived(vote);
	}
}

Fix the blocking problem of NMSI with 2PC.


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

package co.phoenixlab.discord.api.entities;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Builder;

@Builder
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class WebsocketEndpointResponse {

    private String url;

}

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

package co.phoenixlab.discord.api.entities;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Builder;

import java.net.URI;

@Builder
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class WebsocketEndpointResponse {

    private URI url;

}

Change websocket endpoint to URI


package org.zeropage.apps.zeropage.database.notification;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

class NotificationOpenHelper extends SQLiteOpenHelper {
    private static final int VERSION = 1;
    private static final String DATABASE_NAME = "notification.db";

    NotificationOpenHelper(Context context) {
        super(context, DATABASE_NAME, null, VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table " + NotificationTable.NAME + "(" +
                " _id integer primary key autoincrement, " +
                NotificationTable.Column.DATE + ", " +
                NotificationTable.Column.TITLE + ", " +
                NotificationTable.Column.BODY + ", " +
                ")"
        );
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}

package org.zeropage.apps.zeropage.database.notification;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

class NotificationOpenHelper extends SQLiteOpenHelper {
    private static final int VERSION = 1;
    private static final String DATABASE_NAME = "notification.db";

    NotificationOpenHelper(Context context) {
        super(context, DATABASE_NAME, null, VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table " + NotificationTable.NAME + "(" +
                " _id integer primary key autoincrement, " +
                NotificationTable.Column.DATE + ", " +
                NotificationTable.Column.TITLE + ", " +
                NotificationTable.Column.BODY +
                ")"
        );
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}

Fix create table syntax error.