package net.cdahmedeh.ultimeter.ui.main;

import net.cdahmedeh.ultimeter.persistence.dao.TodoManager;
import net.cdahmedeh.ultimeter.persistence.manager.PersistenceManager;
import net.cdahmedeh.ultimeter.ui.controller.TodoController;
import net.cdahmedeh.ultimeter.ui.view.TodoView;

import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

/**
 * This class starts the Ultimeter UI.
 *
 * @author Ahmed El-Hajjar
 *
 */
public class Ultimeter {
    public static void main(String[] args) throws Exception {
        // Prepare persistence utilities.
        final PersistenceManager persistenceManager = new PersistenceManager();
        final TodoManager todoManager = new TodoManager(persistenceManager);

        // Prepare controllers
        final TodoController todoController = new TodoController(todoManager);

        // Create the UI display
        final Display display = new Display();
        final Shell shell = new Shell(display);
        shell.setLayout(new FillLayout());

        // Create Views
        @SuppressWarnings("unused")
        final TodoView todoView = new TodoView(shell, todoController);

        // Display the UI
        shell.open();

        // Start event loop
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }

        // Clean up.
        display.dispose();
    }
}

package net.cdahmedeh.ultimeter.ui.main;

import net.cdahmedeh.ultimeter.persistence.dao.TodoManager;
import net.cdahmedeh.ultimeter.persistence.manager.PersistenceManager;
import net.cdahmedeh.ultimeter.ui.controller.TodoController;
import net.cdahmedeh.ultimeter.ui.view.TodoView;

import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

/**
 * This class starts the Ultimeter UI.
 *
 * @author Ahmed El-Hajjar
 *
 */
public class Ultimeter {
    public static void main(String[] args) throws Exception {
        // Prepare persistence utilities.
        final PersistenceManager persistenceManager = new PersistenceManager();
        final TodoManager todoManager = new TodoManager(persistenceManager);

        // Prepare controllers
        final TodoController todoController = new TodoController(todoManager);

        // Create the UI display
        final Display display = new Display();
        final Shell shell = new Shell(display);
        shell.setText("Ultimeter - Time Management System");
        shell.setLayout(new FillLayout());

        // Create Views
        @SuppressWarnings("unused")
        final TodoView todoView = new TodoView(shell, todoController);

        // Display the UI
        shell.open();

        // Start event loop
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }

        // Clean up.
        display.dispose();
    }
}

Set application title in titlebar.


package ru.yandex.qatools.allure.e2e;

import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.remote.DesiredCapabilities;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;

/**
 * @author Artem Eroshenko eroshenkoam@yandex-team.ru
 *         Date: 1/24/14
 */
public class AllureCommonPageTest {

    @Test
    public void sampleTitleTest() {
        WebDriver driver = new PhantomJSDriver(DesiredCapabilities.firefox());
        driver.get("http://0.0.0.0:8080/e2e");
        assertThat(driver.getTitle(), equalTo("Allure Dashboard"));
    }
}

package ru.yandex.qatools.allure.e2e;

import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.remote.DesiredCapabilities;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;

/**
 * @author Artem Eroshenko eroshenkoam@yandex-team.ru
 *         Date: 1/24/14
 */
public class AllureCommonPageTest {

    @Test
    public void sampleTitleTest() {
        WebDriver driver = new PhantomJSDriver(DesiredCapabilities.firefox());
        driver.get("http://0.0.0.0:8080/e2e/index.html");
        assertThat(driver.getTitle(), equalTo("Allure Dashboard"));
    }
}

Fix allure report path in test


package io.bootique.undertow.command;

import com.google.inject.Inject;
import com.google.inject.Provider;
import io.bootique.application.CommandMetadata;
import io.bootique.cli.Cli;
import io.bootique.command.CommandOutcome;
import io.bootique.command.CommandWithMetadata;
import io.bootique.undertow.UndertowServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Command for running Undertow server.
 *
 * @since 0.1
 */
public class ServerCommand extends CommandWithMetadata {

    private static final Logger LOGGER = LoggerFactory.getLogger(ServerCommand.class);

    private final Provider<UndertowServer> serverProvider;

    @Inject
    public ServerCommand(Provider<UndertowServer> serverProvider) {
        super(createMetadata());
        this.serverProvider = serverProvider;
    }

    @Override
    public CommandOutcome run(Cli cli) {
        LOGGER.info("Will run Undertow Server...");

        UndertowServer server = serverProvider.get();

        try {
            server.start();
        } catch (Exception e) {
            return CommandOutcome.failed(1, e);
        }

        try {
            Thread.currentThread().join();
        } catch (InterruptedException ie) {
            try {
                server.stop();
            } catch (Exception se) {
                return CommandOutcome.failed(1, se);
            }
        }

        return CommandOutcome.succeeded();
    }

    private static CommandMetadata createMetadata() {
        return CommandMetadata
                .builder(ServerCommand.class)
                .description("Starts Undertow server.")
                .build();
    }
}

package io.bootique.undertow.command;

import com.google.inject.Inject;
import com.google.inject.Provider;
import io.bootique.cli.Cli;
import io.bootique.command.CommandOutcome;
import io.bootique.command.CommandWithMetadata;
import io.bootique.meta.application.CommandMetadata;
import io.bootique.undertow.UndertowServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Command for running Undertow server.
 *
 * @since 0.1
 */
public class ServerCommand extends CommandWithMetadata {

    private static final Logger LOGGER = LoggerFactory.getLogger(ServerCommand.class);

    private final Provider<UndertowServer> serverProvider;

    @Inject
    public ServerCommand(Provider<UndertowServer> serverProvider) {
        super(createMetadata());
        this.serverProvider = serverProvider;
    }

    @Override
    public CommandOutcome run(Cli cli) {
        LOGGER.info("Will run Undertow Server...");

        UndertowServer server = serverProvider.get();

        try {
            server.start();
        } catch (Exception e) {
            return CommandOutcome.failed(1, e);
        }

        try {
            Thread.currentThread().join();
        } catch (InterruptedException ie) {
            try {
                server.stop();
            } catch (Exception se) {
                return CommandOutcome.failed(1, se);
            }
        }

        return CommandOutcome.succeeded();
    }

    private static CommandMetadata createMetadata() {
        return CommandMetadata
                .builder(ServerCommand.class)
                .description("Starts Undertow server.")
                .build();
    }
}

Fix build. Change CommandMetadata import.


package info.u_team.u_team_test.init;

import info.u_team.u_team_core.util.registry.*;
import info.u_team.u_team_test.screen.*;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;

public class TestScreens {

	public static void setup(FMLClientSetupEvent event) {
		MainThreadWorker.run(() -> {
			ClientRegistry.registerScreen(TestContainers.BASIC, BasicTileEntityScreen::new);
			ClientRegistry.registerScreen(TestContainers.BASIC_ENERGY_CREATOR, BasicEnergyCreatorScreen::new);
			ClientRegistry.registerScreen(TestContainers.BASIC_FLUID_INVENTORY, BasicFluidInventoryScreen::new);
		});
	}

	public static void registerMod(IEventBus bus) {
		bus.addListener(TestScreens::setup);
	}
}

package info.u_team.u_team_test.init;

import info.u_team.u_team_core.util.registry.*;
import info.u_team.u_team_test.screen.*;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;

public class TestScreens {

	private static void setup(FMLClientSetupEvent event) {
		MainThreadWorker.run(() -> {
			ClientRegistry.registerScreen(TestContainers.BASIC, BasicTileEntityScreen::new);
			ClientRegistry.registerScreen(TestContainers.BASIC_ENERGY_CREATOR, BasicEnergyCreatorScreen::new);
			ClientRegistry.registerScreen(TestContainers.BASIC_FLUID_INVENTORY, BasicFluidInventoryScreen::new);
		});
	}

	public static void registerMod(IEventBus bus) {
		bus.addListener(TestScreens::setup);
	}
}

Make the listener method private now


/**
 * @file Introductions.java
 * @author Valery Samovich
 * @version 1
 * @date 2015/04/07
 */

/**
 * TeamTreehouse. Java Basics.
 */
package com.samovich.basics.introduction.treehouse;

import java.io.Console;

public class Introductions {

    public static void main(String[] args) {
        Console console = System.console();
        // Welcome to the Introductions program!
        String firstName = "Valery";
        // thisIsAnExampleOfCamelCasing
        console.printf("Hello, my name is %s\n", firstName);
        console.printf("%s is learning how to write Java\n", firstName);
    }

}

/**
 * @file Introductions.java
 * @author Valery Samovich
 * @version 1
 * @date 2015/04/07
 */

package com.samovich.basics.introduction.treehouse;

import java.io.Console;

public class Introductions {

    public static void main(String[] args) throws NullPointerException{
        Console console = System.console();
        // Welcome to the Introductions program!
        String firstName;
        firstName = console.readLine("What is your name? ");
        // thisIsAnExampleOfCamelCasing
        console.printf("Hello, my name is %s\n", firstName);
        console.printf("%s is learning how to write Java\n", firstName);
    }

}

Add Introduction class for Team Treehouse example


package me.anky.connectid.data;

import java.util.List;

public class ConnectionsRepository implements ConnectionsDataSource {

    @Override
    public List<ConnectidConnection> getConnections() {
        return null;
    }
}

package me.anky.connectid.data;

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

public class ConnectionsRepository implements ConnectionsDataSource {

    @Override
    public List<ConnectidConnection> getConnections() {

        // Retrieve data from a real database and return it here.
        // Because I am having trouble wrapping my head around Loaders
        // and ContentProviders in the Model, I am just returning some fake
        // data in the List format expected by the Presenter.
        // There is something called Room which may do this job better.
        // Room deals with something it calls DAOs (database access objects)

        List<ConnectidConnection> connections = new ArrayList<>();
        connections.add(new ConnectidConnection("Aragorn", "you have my sword"));
        connections.add(new ConnectidConnection("Legolas", "and you have my bow"));
        connections.add(new ConnectidConnection("Gimli", "and my axe!"));
        connections.add(new ConnectidConnection("Gandalf", "fly, you fools!"));
        connections.add(new ConnectidConnection("Bilbo", "misses his ring"));
        connections.add(new ConnectidConnection("Frodo", "misses his finger"));
        connections.add(new ConnectidConnection("Boromir", "one does not simply"));

        return connections;
    }
}

Implement MVP on john branch


package com.zyeeda.framework.entities.base;

import javax.validation.constraints.NotNull;

@javax.persistence.MappedSuperclass
public class SimpleDomainEntity extends DomainEntity {

    private static final long serialVersionUID = -2200108673372668900L;

    private String name;
    private String description;

    @javax.persistence.Basic
    @javax.persistence.Column(name = "F_NAME")
    @NotNull
    public String getName() {
        return this.name;
    }
    public void setName(String name) {
        this.name = name;
    }

    @javax.persistence.Basic
    @javax.persistence.Column(name = "F_DESC", length = 2000)
    public String getDescription() {
        return this.description;
    }
    public void setDescription(String description) {
        this.description = description;
    }

}

package com.zyeeda.framework.entities.base;

import javax.validation.constraints.NotNull;

@javax.persistence.MappedSuperclass
public class SimpleDomainEntity extends DomainEntity {

    private static final long serialVersionUID = -2200108673372668900L;

    private String name;
    private String description;

    @javax.persistence.Basic
    @javax.persistence.Column(name = "F_NAME")
    public String getName() {
        return this.name;
    }
    public void setName(String name) {
        this.name = name;
    }

    @javax.persistence.Basic
    @javax.persistence.Column(name = "F_DESC", length = 2000)
    public String getDescription() {
        return this.description;
    }
    public void setDescription(String description) {
        this.description = description;
    }

}

Remove @NotNull annotation to name field.


/**
 * Waffle (https://github.com/dblock/waffle)
 *
 * Copyright (c) 2010 - 2014 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
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Application Security, Inc.
 */
package waffle.servlet;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import org.junit.Test;

import waffle.windows.auth.IWindowsAccount;
import waffle.windows.auth.IWindowsIdentity;

/**
 * @author Tony BenBrahim <tony.benbrahim@airliquide.com>
 *
 */
public class WindowsPrincipalTest {

	private static final String TEST_FQN = "ACME\\john.smith";

	@Test
	public void testToString() {
		final IWindowsIdentity windowsIdentity = mock(IWindowsIdentity.class);
		when(windowsIdentity.getFqn()).thenReturn(TEST_FQN);
		when(windowsIdentity.getGroups()).thenReturn(new IWindowsAccount[0]);
		final WindowsPrincipal principal = new WindowsPrincipal(windowsIdentity);
		assertEquals(TEST_FQN, principal.getName());
		assertEquals(TEST_FQN, principal.toString());
	}

}

Format Enforced & JDK8 proper Javadoc


package edu.pdx.cs410J.web;

import org.junit.Test;

import java.io.IOException;
import java.net.HttpURLConnection;

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

/**
 * Unit tests for the HttpRequestHelper class
 */
public class HttpRequestHelperTest {

  private HttpRequestHelper helper = new HttpRequestHelper();

  @Test
  public void testGet() throws IOException {
    HttpRequestHelper.Response response = helper.get("http://www.google.com");
    assertEquals(HttpURLConnection.HTTP_OK, response.getCode());
    assertTrue(response.getContent().contains("Google"));
  }

  @Test
  public void testGetWithParameters() throws IOException {
    HttpRequestHelper.Response response = helper.get("http://search.yahoo.com/search", "p", "Java");
    assertEquals(HttpURLConnection.HTTP_OK, response.getCode());
    assertTrue(response.getContent().contains("Java"));

  }
}

package edu.pdx.cs410J.web;

import org.junit.Test;

import java.io.IOException;
import java.net.HttpURLConnection;

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

/**
 * Unit tests for the HttpRequestHelper class
 */
public class HttpRequestHelperTest {

  private HttpRequestHelper helper = new HttpRequestHelper();

  @Test
  public void testGet() throws IOException {
    HttpRequestHelper.Response response = helper.get("http://www.google.com");
    assertEquals(HttpURLConnection.HTTP_OK, response.getCode());
    assertTrue(response.getContent().contains("Google"));
  }

  @Test
  public void testGetWithParameters() throws IOException {
    HttpRequestHelper.Response response = helper.get("https://www.google.com/search", "p", "Java");
    assertEquals(HttpURLConnection.HTTP_OK, response.getCode());
    assertTrue(response.getContent().contains("Java"));

  }
}

Test the HttpRequestHelper by loading a google search URL instead of Yahoo. Yahoo recently changed something that broke this.


package gcUnrelatedTypes;

import java.util.ArrayList;
import java.util.HashSet;

public class ComplicatedParameterization {

	static class Foo<E> extends HashSet<ArrayList<E>> {}

	Foo<Integer> myFoo = new Foo<Integer>();

	void add(ArrayList<Integer> a) {
		myFoo.add(a);
	}

	boolean contains(ArrayList<Integer> a) {
		return myFoo.contains(a);
	}

}

package gcUnrelatedTypes;

import java.util.ArrayList;
import java.util.HashSet;

public class ComplicatedParameterization {

	static class Foo<E> extends HashSet<ArrayList<E>> {}

	Foo<Integer> myFoo = new Foo<Integer>();

	void add(ArrayList<Integer> a) {
		myFoo.add(a);
	}

	boolean falsePositive(ArrayList<Integer> a) {
		return myFoo.contains(a);
	}

}

Rename method -> false positive


package src;

public class Main {

    public static void main(String[] args) {

        if(args.length != 2)    // принимаем 3 аргумента - имя пользователя, игру и имя файла кода
            return;

        Tournament tournament = new Tournament(args[0], args[1], args[2]);

        int gameResult = tournament.Game();

        return;
    }
}

package src;

import java.io.IOException;

public class Main {

    public static void main(String[] args) {

        if(args.length != 3)    // принимаем 3 аргумента - имя пользователя, игру и имя файла кода
            return;

        Tournament tournament = new Tournament(args[0], args[1], args[2]);

        try {
            int gameResult = tournament.Game();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return;
    }
}

Add try...catch for IOException. There are many places, where this exception may appear.


package com.fernandocejas.java.samples.optional;

import com.fernandocejas.arrow.annotations.See;
import com.fernandocejas.arrow.strings.Strings;

@See(ref = "")
public class UseCaseScenario03 {

  public UseCaseScenario03() {
    //empty
  }

  @Override public String toString() {
    return Strings.EMPTY;
  }
}

package com.fernandocejas.java.samples.optional;

import com.fernandocejas.arrow.annotations.See;
import com.fernandocejas.arrow.optional.Optional;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import rx.Observable;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

@See(ref = "")
public class UseCaseScenario03 {

  public static final Func1<Optional<List<String>>, Observable<List<String>>> TO_AD_ITEM =
      new Func1<Optional<List<String>>, Observable<List<String>>>() {
        @Override public Observable<List<String>> call(Optional<List<String>> ads) {
          return ads.isPresent()
              ? Observable.just(ads.get())
              : Observable.just(Collections.<String>emptyList());
        }
      };

  public static final Func1<List<String>, Boolean> EMPTY_ELEMENTS =
      new Func1<List<String>, Boolean>() {
        @Override public Boolean call(List<String> ads) {
          return !ads.isEmpty();
        }
      };

  public UseCaseScenario03() {
    //empty
  }

  @Override public String toString() {
    final StringBuilder builder = new StringBuilder();
    feed().subscribe(new Action1<List<String>>() {
      @Override public void call(List<String> feed) {
        for (String feedElement : feed) {
          builder.append("\n").append(feedElement);
        }
      }
    });
    return builder.toString();
  }

  private Observable<List<String>> feed() {
    return ads()
        .flatMap(TO_AD_ITEM)
        .filter(EMPTY_ELEMENTS)
        .concatWith(users())
        .observeOn(Schedulers.immediate());
  }

  private Observable<List<String>> users() {
    return Observable.just(Arrays.asList("IronMan", "Wolverine", "Batman", "Superman"));
  }

  private Observable<Optional<List<String>>> ads() {
    return Observable.just(Optional.fromNullable(Collections.singletonList("This is and Ad")));
  }
}

Add third case scenario for Optional sample.


package org.badvision.outlaweditor.data;

import java.util.List;
import org.badvision.outlaweditor.Application;
import org.badvision.outlaweditor.data.xml.Global;
import org.badvision.outlaweditor.data.xml.NamedEntity;

public class DataUtilities {
    public static void ensureGlobalExists() {
        if (Application.gameData.getGlobal() == null) {
            Application.gameData.setGlobal(new Global());
        }
    }

    public static void sortNamedEntities(List<? extends NamedEntity> entities) {
        if (entities == null) {
            return;
        }
        entities.sort((a,b)->{
            String nameA = a == null ? "" : nullSafe(a.getName());
            String nameB = b == null ? "" : nullSafe(b.getName());
            return nameA.compareTo(nameB);
        });
    }

    public static String nullSafe(String str) {
        if (str == null) return "";
        return str;
    }

    public static String uppercaseFirst(String str) {
        StringBuilder b = new StringBuilder(str);
        int i = 0;
        do {
            b.replace(i, i + 1, b.substring(i, i + 1).toUpperCase());
            i = b.indexOf(" ", i) + 1;
        } while (i > 0 && i < b.length());
        return b.toString();
    }
}

package org.badvision.outlaweditor.data;

import java.util.List;
import org.badvision.outlaweditor.Application;
import org.badvision.outlaweditor.data.xml.Global;
import org.badvision.outlaweditor.data.xml.NamedEntity;

public class DataUtilities {
    public static void ensureGlobalExists() {
        if (Application.gameData.getGlobal() == null) {
            Application.gameData.setGlobal(new Global());
        }
    }

    public static void sortNamedEntities(List<? extends NamedEntity> entities) {
        if (entities == null) {
            return;
        }
        entities.sort((a,b)->{
            String nameA = a == null ? "" : nullSafe(a.getName());
            String nameB = b == null ? "" : nullSafe(b.getName());
            if (nameA.equalsIgnoreCase("init")) return -1;
            if (nameB.equalsIgnoreCase("init")) return 1;
            return nameA.compareTo(nameB);
        });
    }

    public static String nullSafe(String str) {
        if (str == null) return "";
        return str;
    }

    public static String uppercaseFirst(String str) {
        StringBuilder b = new StringBuilder(str);
        int i = 0;
        do {
            b.replace(i, i + 1, b.substring(i, i + 1).toUpperCase());
            i = b.indexOf(" ", i) + 1;
        } while (i > 0 && i < b.length());
        return b.toString();
    }
}

Put "init" as the topmost item in the sort again


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

package com.google.android.gnd.rx;

import javax.annotation.Nullable;

/** The result of an operation that can return either true, false, or fail with an exception. */
public class BooleanResult extends Result<Boolean> {
  private BooleanResult(@Nullable Boolean value, @Nullable Throwable error) {
    super(value, error);
  }

  public static BooleanResult ofTrue() {
    return new BooleanResult(true, null);
  }

  public static BooleanResult ofFalse() {
    return new BooleanResult(false, null);
  }

  public static BooleanResult error(Throwable t) {
    return new BooleanResult(null, t);
  }

  /**
   * Returns true if the operation succeeded with a result of {@code true}, or false otherwise. Note
   * that false is also returned if the operation failed in error.
   */
  public boolean isTrue() {
    return get().orElse(false);
  }
}

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

package com.google.android.gnd.rx;

import javax.annotation.Nullable;

/** The result of an operation that can return either true, false, or fail with an exception. */
public class BooleanResult extends Result<Boolean> {
  private BooleanResult(@Nullable Boolean value, @Nullable Throwable error) {
    super(value, error);
  }

  public static BooleanResult ofTrue() {
    return new BooleanResult(true, null);
  }

  public static BooleanResult ofFalse() {
    return new BooleanResult(false, null);
  }

  public static BooleanResult error(Throwable t) {
    return new BooleanResult(null, t);
  }

  /**
   * Returns true if the operation succeeded with a result of {@code true}, or false otherwise. Note
   * that false is also returned if the operation failed in error.
   */
  public boolean isTrue() {
    return get().orElse(false);
  }
}

Correct copyright on new file


package com.chrisdempewolf.pinterest.methods.network;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class NetworkHelper {

    public static ResponseMessageAndStatusCode submitDeleteRequest(final HttpDelete httpDelete) throws IOException {
        try (final CloseableHttpResponse response = HttpClients.createDefault().execute(httpDelete)) {
            final String responseBody = EntityUtils.toString(response.getEntity());
            final int statusCode = response.getStatusLine().getStatusCode();

            return new ResponseMessageAndStatusCode(statusCode, responseBody);
        }
    }
}

package com.chrisdempewolf.pinterest.methods.network;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class NetworkHelper {

    public static ResponseMessageAndStatusCode submitDeleteRequest(final HttpDelete httpDelete) throws IOException {
        return submitRequest(httpDelete);
    }

    public static ResponseMessageAndStatusCode submitPostRequest(final HttpPost httpPost) throws IOException {
        return submitRequest(httpPost);
    }

    private static ResponseMessageAndStatusCode submitRequest(final HttpRequestBase httpRequestBase) throws IOException {
        try (final CloseableHttpResponse response = HttpClients.createDefault().execute(httpRequestBase)) {
            final String responseBody = EntityUtils.toString(response.getEntity());
            final int statusCode = response.getStatusLine().getStatusCode();

            return new ResponseMessageAndStatusCode(statusCode, responseBody);
        }
    }
}

Update network helper to include POST requests


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

/**
 * How would you design an integer stack which, in addition to push and pop, also has a function
 * min which returns the minimum element? Push, pop and min should all operate in 0(1) time.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class ConstantComplexityOrderStack {

}

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

import java.util.Stack;

/**
 * How would you design an integer stack which, in addition to push and pop, also has a function
 * min which returns the minimum element? Push, pop and min should all operate in 0(1) time.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class ConstantComplexityOrderStack {

  /**
   * Approach based on a inner data structure to store the stack of integers and in the same object
   * the current min value we had when the element was pushed. With this approach we get a time
   * complexity order equals to O(1) but a space complexity order equals to O(N) where N is the
   * number of elements in the stack.
   */
  public static class Stack1 extends Stack<MinValue> {

    public void push(int item) {
      int newMin = Math.min(item, getMin());
      super.push(new MinValue(item, newMin));
    }

    public int getMin() {
      if (isEmpty()) {
        return Integer.MAX_VALUE;
      } else {
        return peek().minValue;
      }
    }
  }

  static class MinValue {
    final int value;
    final int minValue;

    MinValue(int value, int minValue) {
      this.value = value;
      this.minValue = minValue;
    }
  }
}

Add first implementation to problem 63


// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.provision.zone;

import com.yahoo.config.provision.CloudName;
import com.yahoo.config.provision.Environment;
import com.yahoo.config.provision.RegionName;
import com.yahoo.config.provision.SystemName;

/**
 * @author hakonhall
 */
public interface ZoneApi {

    SystemName getSystemName();

    ZoneId getId();

    /** Returns the SYSTEM.ENVIRONMENT.REGION string. */
    default String getFullName() {
        return getSystemName().value() + "." + getEnvironment().value() + "." + getRegionName().value();
    }

    /**
     * Returns the virtual ID of this zone. For ordinary zones this is the same as {@link ZoneApi#getId()}, for a
     * system represented as a zone this is a fixed ID that is independent of the actual zone ID.
     */
    default ZoneId getVirtualId() {
        return getId();
    }

    default Environment getEnvironment() { return getId().environment(); }

    default RegionName getRegionName() { return getId().region(); }

    CloudName getCloudName();

    /** Returns the region name within the cloud, e.g. 'us-east-1' in AWS */
    String getCloudNativeRegionName();

}

// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.provision.zone;

import com.yahoo.config.provision.CloudName;
import com.yahoo.config.provision.Environment;
import com.yahoo.config.provision.RegionName;
import com.yahoo.config.provision.SystemName;

/**
 * @author hakonhall
 */
public interface ZoneApi {

    SystemName getSystemName();

    /**
     * Returns the ID of the zone.
     *
     * WARNING: The ID of a controller zone is equal to the ID of a prod zone in the same region.
     * @see #getVirtualId()
     */
    ZoneId getId();

    /** Returns the SYSTEM.ENVIRONMENT.REGION string. */
    default String getFullName() {
        return getSystemName().value() + "." + getEnvironment().value() + "." + getRegionName().value();
    }

    /**
     * Returns {@link #getId()} for all zones except the controller zone.  Unlike {@link #getId()},
     * the virtual ID of a controller is distinct from all other zones.
     */
    default ZoneId getVirtualId() {
        return getId();
    }

    default Environment getEnvironment() { return getId().environment(); }

    default RegionName getRegionName() { return getId().region(); }

    CloudName getCloudName();

    /** Returns the region name within the cloud, e.g. 'us-east-1' in AWS */
    String getCloudNativeRegionName();

}

Document difference between ID and virtual ID


package io.reon.http;

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

public class ResponseReader extends MessageReader {

	public ResponseReader(InputStream is) {
		super(is);
	}

	public Response read() throws IOException {
		Response resp = parse(readHeader());
		if (resp == null) return null;
		return ResponseBuilder.with(resp).withBody(input).build();
	}

	public static Response parse(String req) throws HttpBadRequestException {
		if (req == null || req.length() == 0) return null;
		String[] lines = req.split("\\r\\n", 2);
		String[] segments = lines[0].split(" ");
		String protocolVersion = segments[0];
		StatusCode sc = StatusCode.byValue(Integer.parseInt(segments[1]));
		String reason = null;
		if(segments.length>=3) {
			reason = lines[0].substring(lines[0].indexOf(segments[2]));
		}
		Headers headers = Headers.parse(lines[1]);
		return new Response(protocolVersion, sc, reason, headers);
	}
}

package io.reon.http;

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

public class ResponseReader extends MessageReader {

	public ResponseReader(InputStream is) {
		super(is);
	}

	public Response read() throws IOException {
		Response resp = parse(readHeader());
		if (resp == null) return null;
		return ResponseBuilder.with(resp).withBody(input).build();
	}

	public static Response parse(String req) throws HttpBadRequestException {
		if (req == null || req.length() == 0) return null;
		String[] lines = req.split("\\r\\n", 2);
		String[] segments = lines[0].split(" ");
		String protocolVersion = segments[0];
		StatusCode sc = StatusCode.byValue(Integer.parseInt(segments[1]));
		String reason = null;
		if(segments.length>=3) {
			reason = lines[0].substring(lines[0].indexOf(segments[2]));
		}
		Headers headers;
		if (lines.length > 1) {
			headers = Headers.parse(lines[1]);
		} else {
			headers = new Headers();
		}
		return new Response(protocolVersion, sc, reason, headers);
	}
}

Fix for one line HTTP responses


package de.stephanlindauer.criticalmaps.model;

import android.app.Activity;
import android.provider.Settings;

import de.stephanlindauer.criticalmaps.utils.AeSimpleSHA1;

public class UserModel {

    //singleton
    private static UserModel instance;

    private String uniqueDeviceIdHashed;

    public static UserModel getInstance() {
        if (UserModel.instance == null) {
            UserModel.instance = new UserModel();
        }
        return UserModel.instance;
    }

    public void initialize(Activity activity) {
        this.uniqueDeviceIdHashed = AeSimpleSHA1.SHA1(Settings.Secure.getString(activity.getContentResolver(),
                Settings.Secure.ANDROID_ID));
    }

    public String getUniqueDeviceIdHashed() {
        return uniqueDeviceIdHashed;
    }
}

package de.stephanlindauer.criticalmaps.model;

import android.app.Activity;
import android.provider.Settings;
import de.stephanlindauer.criticalmaps.utils.AeSimpleSHA1;

import static android.provider.Settings.Secure.getString;

public class UserModel {

    //singleton
    private static UserModel instance;

    private String uniqueDeviceIdHashed;

    public static UserModel getInstance() {
        if (UserModel.instance == null) {
            UserModel.instance = new UserModel();
        }
        return UserModel.instance;
    }

    public void initialize(Activity activity) {
        final String androidId = getString(activity.getContentResolver(), Settings.Secure.ANDROID_ID);
        uniqueDeviceIdHashed = AeSimpleSHA1.SHA1(androidId);
    }

    public String getUniqueDeviceIdHashed() {
        return uniqueDeviceIdHashed;
    }
}

Break down really long line


package org.jctools.util;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.LockSupport;

public class TestUtil {
    public static final int CONCURRENT_TEST_DURATION = Integer.getInteger("org.jctools.concTestDurationMs", 500);
    public static final int TEST_TIMEOUT = 30000;
    private static final AtomicInteger threadIndex = new AtomicInteger();
    public static void sleepQuietly(long timeMs) {
        LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(timeMs));
    }

    public static void startWaitJoin(AtomicBoolean stop, List<Thread> threads) throws InterruptedException
    {
        for (Thread t : threads) t.start();
        Thread.sleep(CONCURRENT_TEST_DURATION);
        stop.set(true);
        for (Thread t : threads)  t.join();
        stop.set(false);
    }

    public static void threads(Runnable runnable, int count, List<Thread> threads)
    {
        if (count <= 0)
            count = Runtime.getRuntime().availableProcessors() - 1;

        for (int i = 0; i < count; i++)
        {
            Thread thread = new Thread(runnable);
            thread.setName("JCTools test thread-" + threadIndex.getAndIncrement());
            threads.add(thread);
        }
    }
    public static final class Val
    {
        public int value;
    }
}

package org.jctools.util;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.LockSupport;

public class TestUtil {
    public static final int CONCURRENT_TEST_DURATION = Integer.getInteger("org.jctools.concTestDurationMs", 500);
    public static final int CONCURRENT_TEST_THREADS = Integer.getInteger("org.jctools.concTestThreads", Runtime.getRuntime().availableProcessors());
    public static final int TEST_TIMEOUT = 30000;
    private static final AtomicInteger threadIndex = new AtomicInteger();
    public static void sleepQuietly(long timeMs) {
        LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(timeMs));
    }

    public static void startWaitJoin(AtomicBoolean stop, List<Thread> threads) throws InterruptedException
    {
        for (Thread t : threads) t.start();
        Thread.sleep(CONCURRENT_TEST_DURATION);
        stop.set(true);
        for (Thread t : threads)  t.join();
        stop.set(false);
    }

    public static void threads(Runnable runnable, int count, List<Thread> threads)
    {
        if (count <= 0)
            count = CONCURRENT_TEST_THREADS - 1;

        for (int i = 0; i < count; i++)
        {
            Thread thread = new Thread(runnable);
            thread.setName("JCTools test thread-" + threadIndex.getAndIncrement());
            threads.add(thread);
        }
    }
    public static final class Val
    {
        public int value;
    }
}

Add test control for number of threads


/*************************GO-LICENSE-START*********************************
 * Copyright 2015 ThoughtWorks, 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.
 *************************GO-LICENSE-END***********************************/

package com.thoughtworks.cruise.page;

import com.thoughtworks.cruise.Urls;
import com.thoughtworks.cruise.state.ScenarioState;
import net.sf.sahi.client.Browser;

public class OnAdministrationPage extends CruisePage {
	public OnAdministrationPage(ScenarioState state, Browser browser) {
		super(state, browser);
	}

	@com.thoughtworks.gauge.Step("Verify page title is <pageTitle> - On Administration Page")
	public void verifyPageTitleIs(String pageTitle) {
		super.verifyPageTitleIs(pageTitle);
	}

	@Override
	protected String url() {
		return Urls.urlFor("/tab/admin");
	}

}

/*************************GO-LICENSE-START*********************************
 * Copyright 2015 ThoughtWorks, 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.
 *************************GO-LICENSE-END***********************************/

package com.thoughtworks.cruise.page;

import com.thoughtworks.cruise.Urls;
import com.thoughtworks.cruise.state.ScenarioState;
import net.sf.sahi.client.Browser;

public class OnAdministrationPage extends CruisePage {
	public OnAdministrationPage(ScenarioState state, Browser browser) {
		super(state, browser);
	}

	@com.thoughtworks.gauge.Step("Verify page title is <pageTitle> - On Administration Page")
	public void verifyPageTitleIs(String pageTitle) {
		super.verifyPageTitleIs(pageTitle);
	}

	@Override
	protected String url() {
		return Urls.urlFor("/admin/config_xml");
	}

}

Test the correct admin page


package uk.co.eggsylife.controller;

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

@RestController
public class HomeController {

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String showHomePage() {
        return "Welcome to v0.0.2 of the application";
    }
}

package uk.co.eggsylife.controller;

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

@RestController
public class HomeController {

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String showHomePage() {
        return "Welcome to v0.0.1 of the application";
    }
}

Revert version for demo purposes


package org.adaptlab.chpir.android.survey.Models;

import java.util.List;

import org.adaptlab.chpir.android.activerecordcloudsync.ReceiveTable;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.activeandroid.Model;
import com.activeandroid.annotation.Column;
import com.activeandroid.annotation.Table;
import com.activeandroid.query.Select;

@Table(name = "Instruments")
public class Instrument extends Model implements ReceiveTable {
    private static final String TAG = "Instrument";

    @Column(name = "Title")
    private String mTitle;

    public Instrument() {
        super();
    }

    public String getTitle() {
        return mTitle;
    }

    public void setTitle(String title) {
        mTitle = title;
    }

    public List<Question> questions() {
        return getMany(Question.class, "Instrument");
    }

    public static List<Instrument> getAll() {
        return new Select().from(Instrument.class).orderBy("Id ASC").execute();
    }

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

    @Override
    public void createObjectFromJSON(JSONObject jsonObject) {
        try {
            setTitle(jsonObject.getString("title"));
            this.save();
        } catch (JSONException je) {
            Log.e(TAG, "Error parsing object json", je);
        }
    }
}

package org.adaptlab.chpir.android.survey.Models;

import java.util.List;

import org.adaptlab.chpir.android.activerecordcloudsync.ReceiveTable;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.activeandroid.Model;
import com.activeandroid.annotation.Column;
import com.activeandroid.annotation.Table;
import com.activeandroid.query.Select;

@Table(name = "Instruments")
public class Instrument extends Model implements ReceiveTable {
    private static final String TAG = "Instrument";

    @Column(name = "Title")
    private String mTitle;
    // https://github.com/pardom/ActiveAndroid/issues/22
    @Column(name = "RemoteId", unique = true, onUniqueConflict = Column.ConflictAction.REPLACE)
    private Long mRemoteId;

    public Instrument() {
        super();
    }

    public String getTitle() {
        return mTitle;
    }

    public void setTitle(String title) {
        mTitle = title;
    }

    public Long getRemoteId() {
        return mRemoteId;
    }

    public void setRemoteId(Long id) {
        mRemoteId = id;
    }

    public List<Question> questions() {
        return getMany(Question.class, "Instrument");
    }

    public static List<Instrument> getAll() {
        return new Select().from(Instrument.class).orderBy("Id ASC").execute();
    }

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

    @Override
    public void createObjectFromJSON(JSONObject jsonObject) {
        try {
            setRemoteId(jsonObject.getLong("id"));
            setTitle(jsonObject.getString("title"));
            this.save();
        } catch (JSONException je) {
            Log.e(TAG, "Error parsing object json", je);
        }
    }
}

Replace column on remote update


/*
 *
 *
 * Copyright (C) 2006 SIPfoundry Inc.
 * Licensed by SIPfoundry under the LGPL license.
 *
 * Copyright (C) 2006 Pingtel Corp.
 * Licensed to SIPfoundry under a Contributor Agreement.
 *
 * $
 */
package org.sipfoundry.sipxconfig.common;

import org.sipfoundry.sipxconfig.common.X509Selector;

import junit.framework.TestCase;

public class X509SelectorTest extends TestCase {

    public void testAvailableAlgorithm() {
        String alg = new X509Selector.getAvailableAlgorithm();
        // only works w/2 VM vendors. If others are known to work, add here
        assertTrue(alg.equals("SunX509") || alg.equals("IbmX509"));
    }

    public void testUnavailableAlgorithm() {
        assertNull(new X509Selector().getAvailableAlgorithm(new String[] { "bogus" }));
    }

}

/*
 *
 *
 * Copyright (C) 2006 SIPfoundry Inc.
 * Licensed by SIPfoundry under the LGPL license.
 *
 * Copyright (C) 2006 Pingtel Corp.
 * Licensed to SIPfoundry under a Contributor Agreement.
 *
 * $
 */
package org.sipfoundry.sipxconfig.common;

import org.sipfoundry.sipxconfig.common.X509Selector;

import junit.framework.TestCase;

public class X509SelectorTest extends TestCase {

    public void testAvailableAlgorithm() {
        String alg = new X509Selector().getAvailableAlgorithm();
        // only works w/2 VM vendors. If others are known to work, add here
        assertTrue(alg.equals("SunX509") || alg.equals("IbmX509"));
    }

    public void testUnavailableAlgorithm() {
        assertNull(new X509Selector().getAvailableAlgorithm(new String[] { "bogus" }));
    }

}

FIX BUILD compiler error in 509selector unit test


package com.custardsource.parfait.dxm;

public interface IdentifierSourceSet {
    public IdentifierSource instanceDomainSource();
    public IdentifierSource instanceSource(String domain);
    public IdentifierSource metricSource();

    public static IdentifierSourceSet DEFAULT_SET = new IdentifierSourceSet() {
        private final IdentifierSource DEFAULT_SOURCE = new HashingIdentifierSource();

        @Override
        public IdentifierSource metricSource() {
            return DEFAULT_SOURCE;
        }

        @Override
        public IdentifierSource instanceSource(String domain) {
            return DEFAULT_SOURCE;
        }

        @Override
        public IdentifierSource instanceDomainSource() {
            return DEFAULT_SOURCE;
        }
    };
}

package com.custardsource.parfait.dxm;

public interface IdentifierSourceSet {
    public IdentifierSource instanceDomainSource();
    public IdentifierSource instanceSource(String domain);
    public IdentifierSource metricSource();

    public static IdentifierSourceSet DEFAULT_SET = new IdentifierSourceSet() {
        private final IdentifierSource DEFAULT_SOURCE = new HashingIdentifierSource();

        @Override
        public IdentifierSource metricSource() {
            return DEFAULT_SOURCE;
        }

        @Override
        public IdentifierSource instanceSource(String domain) {
            return DEFAULT_SOURCE;
        }

        @Override
        public IdentifierSource instanceDomainSource() {
            return DEFAULT_SOURCE;
        }
    };

    /**
     * {@link IdentifierSourceSet} which will fail for indoms and metrics, but allow default hashed
     * values for Instances
     */
    public static IdentifierSourceSet EXPLICIT_SET = new IdentifierSourceSet() {
        private final IdentifierSource DEFAULT_SOURCE = new HashingIdentifierSource();
        private final IdentifierSource ERROR_SOURCE = new ErrorThrowingIdentifierSource();

        @Override
        public IdentifierSource metricSource() {
            return ERROR_SOURCE;
        }

        @Override
        public IdentifierSource instanceSource(String domain) {
            return DEFAULT_SOURCE;
        }

        @Override
        public IdentifierSource instanceDomainSource() {
            return ERROR_SOURCE;
        }
    };
}

Add an explicit metric set for the most typical use case (caring about metric + indom identifiers, but not instance ones)


package com.github.klane.wann.core;

import com.github.klane.wann.function.activation.ActivationFunction;
import com.github.klane.wann.function.input.InputFunction;
import com.google.common.base.Preconditions;
import javafx.util.Builder;

public abstract class WANNBuilder<T, U extends WANNBuilder<T, U>> implements Builder<T> {

    ActivationFunction activationFunction;
    Double bias;
    boolean biasFlag;
    InputFunction inputFunction;
    String name;

    public U activationFunction(final ActivationFunction activationFunction) {
        if (this.activationFunction == null) {
            this.activationFunction = activationFunction;
        }

        return this.get();
    }

    public U bias(final boolean biasFlag) {
        this.biasFlag = biasFlag;
        return this.get();
    }

    public U bias(final Double bias) {
        if (this.bias == null) {
            this.bias = bias;
            this.biasFlag = true;
        }

        return this.get();
    }

    @Override
    public abstract T build();

    public U inputFunction(final InputFunction inputFunction) {
        if (this.inputFunction == null) {
            this.inputFunction = inputFunction;
        }

        return this.get();
    }

    public U name(final String name) {
        Preconditions.checkNotNull(name);

        if (this.name == null) {
            this.name = name;
        }

        return this.get();
    }

    abstract U get();
}

package com.github.klane.wann.core;

import com.github.klane.wann.function.activation.ActivationFunction;
import com.github.klane.wann.function.input.InputFunction;
import com.google.common.base.Preconditions;
import javafx.util.Builder;

public abstract class WANNBuilder<T, U extends WANNBuilder<T, U>> implements Builder<T> {

    ActivationFunction activationFunction;
    Double bias;
    boolean biasFlag;
    InputFunction inputFunction;
    String name;

    public U activationFunction(final ActivationFunction activationFunction) {
        if (this.activationFunction == null) {
            this.activationFunction = activationFunction;
        }

        return this.get();
    }

    public U bias(final boolean biasFlag) {
        if (this.bias == null) {
            this.biasFlag = biasFlag;
        }

        return this.get();
    }

    public U bias(final Double bias) {
        if (this.bias == null) {
            this.bias = bias;
            this.biasFlag = true;
        }

        return this.get();
    }

    @Override
    public abstract T build();

    public U inputFunction(final InputFunction inputFunction) {
        if (this.inputFunction == null) {
            this.inputFunction = inputFunction;
        }

        return this.get();
    }

    public U name(final String name) {
        Preconditions.checkNotNull(name);

        if (this.name == null) {
            this.name = name;
        }

        return this.get();
    }

    abstract U get();
}

Fix bug where specified bias is ignored.


package info.u_team.u_team_test.init;

import info.u_team.u_team_test.entity.TestLivingEntity;
import net.minecraftforge.event.entity.EntityAttributeCreationEvent;
import net.minecraftforge.eventbus.api.IEventBus;

public class TestGlobalEntityTypeAttributes {

	private static void entityAttributionCreation(EntityAttributeCreationEvent event) {
		event.put(TestEntityTypes.TEST_LIVING.get(), TestLivingEntity.registerAttributes().create());
	}

	public static void registerMod(IEventBus bus) {
		bus.addListener(TestGlobalEntityTypeAttributes::entityAttributionCreation);
	}

}

package info.u_team.u_team_test.init;

import info.u_team.u_team_test.entity.TestLivingEntity;
import net.minecraftforge.event.entity.EntityAttributeCreationEvent;
import net.minecraftforge.eventbus.api.IEventBus;

public class TestGlobalEntityTypeAttributes {

	private static void entityAttributionCreation(EntityAttributeCreationEvent event) {
		event.put(TestEntityTypes.TEST_LIVING.get(), TestLivingEntity.createAttributes().build());
	}

	public static void registerMod(IEventBus bus) {
		bus.addListener(TestGlobalEntityTypeAttributes::entityAttributionCreation);
	}

}

Fix registry of entity type attributes


package com.fsck.k9.mailstore.migrations;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

class MigrationTo61 {

    static void addFolderRemoteId(SQLiteDatabase db) {
        if (!columnExists(db, "folders", "remoteId")) {
            db.execSQL("ALTER TABLE folders ADD remoteId TEXT");
            db.execSQL("UPDATE folders SET remoteId = name");
        }
    }

    private static boolean columnExists(SQLiteDatabase db, String table, String columnName) {
        Cursor columnCursor = db.rawQuery("PRAGMA table_info(" + table + ")", null);
        boolean foundColumn = false;
        while (columnCursor.moveToNext()) {
            String currentColumnName = columnCursor.getString(1);
            if (currentColumnName.equals(columnName)) {
                foundColumn = true;
                break;
            }
        }
        columnCursor.close();
        return foundColumn;
    }
}

package com.fsck.k9.mailstore.migrations;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

class MigrationTo61 {

    static void addFolderRemoteId(SQLiteDatabase db) {
        if (!columnExists(db, "folders", "remoteId")) {
            db.execSQL("ALTER TABLE folders ADD remoteId TEXT");
            db.execSQL("UPDATE folders SET remoteId = name");
            db.execSQL("DROP INDEX IF EXISTS folder_name");
            db.execSQL("CREATE INDEX IF NOT EXISTS folder_remoteId ON folders (remoteId)");
        }
    }

    private static boolean columnExists(SQLiteDatabase db, String table, String columnName) {
        Cursor columnCursor = db.rawQuery("PRAGMA table_info(" + table + ")", null);
        boolean foundColumn = false;
        while (columnCursor.moveToNext()) {
            String currentColumnName = columnCursor.getString(1);
            if (currentColumnName.equals(columnName)) {
                foundColumn = true;
                break;
            }
        }
        columnCursor.close();
        return foundColumn;
    }
}

Update indexes on folders table during migration


package nl.hsac.fitnesse.fixture.util.selenium;

import nl.hsac.fitnesse.fixture.util.selenium.by.ConstantBy;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import java.util.List;

/**
 * Helper to determine which value(s) of a select is currently selected.
 */
public class SelectHelper {
    private static final By SELECTED_OPTIONS_BY = ConstantBy.getSelectedOptionsBy();
    private final WebElement selectElement;

    public SelectHelper(WebElement element) {
        selectElement = element;
    }

    public WebElement getFirstSelectedOption() {
        List<WebElement> selectedOptions = getAllSelectedOptions();
        return selectedOptions.isEmpty()? null : selectedOptions.get(0);
    }

    public List<WebElement> getAllSelectedOptions() {
        return selectElement.findElements(SELECTED_OPTIONS_BY);
    }

    /**
     * @param element element to check
     * @return true if element is indeed a 'select'.
     */
    public static boolean isSelect(WebElement element) {
        String tagName = element.getTagName();
        return tagName != null && "select".equals(tagName.toLowerCase());
    }
}

package nl.hsac.fitnesse.fixture.util.selenium;

import nl.hsac.fitnesse.fixture.util.selenium.by.ConstantBy;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import java.util.List;

/**
 * Helper to determine which value(s) of a select is currently selected.
 */
public class SelectHelper {
    private static final By SELECTED_OPTIONS_BY = ConstantBy.getSelectedOptionsBy();
    private final WebElement selectElement;

    public SelectHelper(WebElement element) {
        selectElement = element;
    }

    public WebElement getFirstSelectedOption() {
        List<WebElement> selectedOptions = getAllSelectedOptions();
        return selectedOptions.isEmpty()? null : selectedOptions.get(0);
    }

    public List<WebElement> getAllSelectedOptions() {
        return selectElement.findElements(SELECTED_OPTIONS_BY);
    }

    /**
     * @param element element to check
     * @return true if element is indeed a 'select'.
     */
    public static boolean isSelect(WebElement element) {
        String tagName = element.getTagName();
        return "select".equalsIgnoreCase(tagName);
    }
}

Use standard method instead of rolling our own


package com.example.whatsmymood;

import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

/**
 * Created by Malcolm on 2017-03-11.
 */

public class CreateUserController {

    public CreateUserController(){
    }

    public boolean create(String username, String password) {

        // Check that user name is unique in elastic search index

        ElasticSearchUserController.GetUserTask getUserTask = new ElasticSearchUserController.GetUserTask();
        getUserTask.execute(username);

        try {
            ArrayList<UserAccount> userList = getUserTask.get();
            if (!userList.isEmpty()) {
                return false;
            } else {
                UserAccount user = new UserAccount(username, password);
                ElasticSearchUserController.AddUserTask addUserTask = new ElasticSearchUserController.AddUserTask();
                addUserTask.execute(user);
                return true;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

    }

}

package com.example.whatsmymood;

import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

/**
 * Created by Malcolm on 2017-03-11.
 */

public class CreateUserController {

    public CreateUserController(){
    }

    public boolean create(String username, String password) {

        // Check that user name is unique in elastic search index

        ElasticSearchUserController.GetUserTask getUserTask = new ElasticSearchUserController.GetUserTask();
        getUserTask.execute(username);

        try {
            ArrayList<UserAccount> userList = getUserTask.get();
            if (!userList.isEmpty()) {
                return false;
            } else {
                UserAccount user = new UserAccount(username, password);
                ElasticSearchUserController.AddUserTask addUserTask = new ElasticSearchUserController.AddUserTask();
                addUserTask.execute(user);
                return true;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return false;
    }

}

Create Account works with elastic search


package ml.shifu.shifu.core;

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

public class ConvergeJudgerTest {

    @Test
    public void testJudge() {
        ConvergeJudger judger = new ConvergeJudger();

        Assert.assertTrue(judger.judge(1.0, 2.0));
        Assert.assertTrue(judger.judge(1.0, 1.0));
        Assert.assertFalse(judger.judge(1.0, 0.1));
    }

}

package ml.shifu.shifu.core;

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

public class ConvergeJudgerTest {

    private ConvergeJudger judger;

    @BeforeClass
    public void setUp() {
        this.judger = new ConvergeJudger();
    }

    @Test
    public void testJudge() {
        Assert.assertTrue(judger.judge(1.0, 2.0));
        Assert.assertTrue(judger.judge(1.0, 1.0));
        Assert.assertFalse(judger.judge(1.0, 0.1));
    }

}

Use setup to initialize judger instance.


/*
 * Licensed under MIT (https://github.com/ligoj/ligoj/blob/master/LICENSE)
 */
package org.ligoj.app.resource.plugin.repository;

import java.util.function.Function;

import javax.cache.expiry.AccessedExpiryPolicy;
import javax.cache.expiry.Duration;

import org.ligoj.bootstrap.resource.system.cache.CacheManagerAware;
import org.springframework.stereotype.Component;

import com.hazelcast.cache.HazelcastCacheManager;
import com.hazelcast.config.CacheConfig;

/**
 * Plug-in cache configuration.
 */
@Component
public class PluginCache implements CacheManagerAware {

	@Override
	public void onCreate(final HazelcastCacheManager cacheManager, final Function<String, CacheConfig<?, ?>> provider) {
		final CacheConfig<?, ?> central = provider.apply("authorizations");
		central.setExpiryPolicyFactory(AccessedExpiryPolicy.factoryOf(Duration.ONE_DAY));
		cacheManager.createCache("plugins-last-version-central", central);
		final CacheConfig<?, ?> nexus = provider.apply("authorizations");
		nexus.setExpiryPolicyFactory(AccessedExpiryPolicy.factoryOf(Duration.ONE_DAY));
		cacheManager.createCache("plugins-last-version-nexus", nexus);
	}
}

/*
 * Licensed under MIT (https://github.com/ligoj/ligoj/blob/master/LICENSE)
 */
package org.ligoj.app.resource.plugin.repository;

import java.util.function.Function;

import javax.cache.expiry.AccessedExpiryPolicy;
import javax.cache.expiry.Duration;
import javax.cache.expiry.ModifiedExpiryPolicy;

import org.ligoj.bootstrap.resource.system.cache.CacheManagerAware;
import org.springframework.stereotype.Component;

import com.hazelcast.cache.HazelcastCacheManager;
import com.hazelcast.config.CacheConfig;

/**
 * Plug-in cache configuration.
 */
@Component
public class PluginCache implements CacheManagerAware {

	@Override
	public void onCreate(final HazelcastCacheManager cacheManager, final Function<String, CacheConfig<?, ?>> provider) {
		final CacheConfig<?, ?> central = provider.apply("authorizations");
		central.setExpiryPolicyFactory(ModifiedExpiryPolicy.factoryOf(Duration.ONE_DAY));
		cacheManager.createCache("plugins-last-version-central", central);
		final CacheConfig<?, ?> nexus = provider.apply("authorizations");
		nexus.setExpiryPolicyFactory(AccessedExpiryPolicy.factoryOf(Duration.ONE_DAY));
		cacheManager.createCache("plugins-last-version-nexus", nexus);
	}
}

Change expiring cache policy of registry


package org.wildfly.swarm.undertow;

import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.Node;

/**
 * @author Bob McWhirter
 */
public interface StaticContentContainer<T extends Archive<T>> extends Archive<T> {

    default T staticContent() {
        return staticContent( "/", "." );
    }

    default T staticContent(String context) {
        return staticContent( context, "." );
    }

    default T staticContent(String context, String base) {
        as(WARArchive.class).addModule("org.wildfly.swarm.undertow", "runtime");
        as(WARArchive.class).addAsServiceProvider("io.undertow.server.handlers.builder.HandlerBuilder", "org.wildfly.swarm.runtime.undertow.StaticHandlerBuilder");

        Node node = as(WARArchive.class).get("WEB-INF/undertow-handlers.conf");

        UndertowHandlersAsset asset = null;
        if ( node == null ) {
            asset = new UndertowHandlersAsset();
            as(WARArchive.class).add( asset, "WEB-INF/undertow-handlers.conf" );
        } else {
            asset = (UndertowHandlersAsset) node.getAsset();
        }

        asset.staticContent( context, base );

        return (T) this;
    }
}

package org.wildfly.swarm.undertow;

import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.Node;

/**
 * @author Bob McWhirter
 */
public interface StaticContentContainer<T extends Archive<T>> extends Archive<T> {

    default T staticContent() {
        return staticContent( "/", "." );
    }

    default T staticContent(String context) {
        return staticContent( context, "." );
    }

    default T staticContent(String context, String base) {
        as(WARArchive.class).addModule("org.wildfly.swarm.undertow", "runtime");
        as(WARArchive.class).addAsServiceProvider("io.undertow.server.handlers.builder.HandlerBuilder", "org.wildfly.swarm.undertow.runtime.StaticHandlerBuilder");

        Node node = as(WARArchive.class).get("WEB-INF/undertow-handlers.conf");

        UndertowHandlersAsset asset = null;
        if ( node == null ) {
            asset = new UndertowHandlersAsset();
            as(WARArchive.class).add( asset, "WEB-INF/undertow-handlers.conf" );
        } else {
            asset = (UndertowHandlersAsset) node.getAsset();
        }

        asset.staticContent( context, base );

        return (T) this;
    }
}

Fix Undertow static handler package name, as it was renamed


package com.sqisland.android.advanced_textview;

import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.widget.TextView;

public class CustomFontActivity extends Activity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_custom_font);

    TextView textView = (TextView) findViewById(R.id.text);
    Typeface typeface = Typeface.createFromAsset(getAssets(), "Ruthie.ttf");
    textView.setTypeface(typeface);
  }
}

package com.sqisland.android.advanced_textview;

import android.app.Activity;
import android.content.Context;
import android.graphics.Typeface;
import android.os.Bundle;
import android.widget.TextView;
import android.view.View;
import android.util.AttributeSet;

public class CustomFontActivity extends Activity {

  private Typeface typeface;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    typeface = Typeface.createFromAsset(getAssets(), "Ruthie.ttf");
    setContentView(R.layout.activity_custom_font);
  }

  @Override
  public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
    //this would apply to all textviews in the app
    if (name.equals("TextView")) {
      System.out.println("loading custom font");
      TextView view = new TextView(this, attrs);
      view.setTypeface(typeface);
      return view;
    }

    return super.onCreateView(parent, name, context, attrs);
  }

  @Override
  public View onCreateView(String name, Context context, AttributeSet attrs) {
    //this would apply to all textviews in the app
    if (name.equals("TextView")) {
      System.out.println("loading custom font");
      TextView view = new TextView(this, attrs);
      view.setTypeface(typeface);
      return view;
    }

    return super.onCreateView(name, context, attrs);
  }

}

Load the custom font in all textviews.


package org.asciidoctor.jruby.ast.impl;

import org.jruby.RubyStruct;

import org.asciidoctor.ast.Footnote;
import org.jruby.javasupport.JavaEmbedUtils;

public class FootnoteImpl implements Footnote {

    private static final String INDEX_KEY_NAME = "index";
    private static final String ID_KEY_NAME = "id";
    private static final String TEXT_KEY_NAME = "text";

    private Long index;
    private String id;
    private String text;

    private static Object aref(RubyStruct s, String key)  {
       return JavaEmbedUtils.rubyToJava(s.aref(JavaEmbedUtils.javaToRuby(s.getRuntime(), key)));
    }

    public static Footnote getInstance(Long index, String id, String text)  {
        FootnoteImpl footnote = new FootnoteImpl();
        footnote.index = index;
        footnote.id = id;
        footnote.text = text;
        return footnote;
    }

    public static Footnote getInstance(RubyStruct rubyFootnote) {
        return FootnoteImpl.getInstance(
                (Long) aref(rubyFootnote, INDEX_KEY_NAME),
                (String) aref(rubyFootnote, ID_KEY_NAME),
                (String) aref(rubyFootnote, TEXT_KEY_NAME));
    }

    @Override
    public Long getIndex() { return index; }

    @Override
    public String getId() { return id; }

    @Override
    public String getText() { return text; }
}

package org.asciidoctor.jruby.ast.impl;

import org.jruby.RubyStruct;

import org.asciidoctor.ast.Footnote;
import org.jruby.javasupport.JavaEmbedUtils;

public class FootnoteImpl implements Footnote {

    private static final String INDEX_KEY_NAME = "index";
    private static final String ID_KEY_NAME = "id";
    private static final String TEXT_KEY_NAME = "text";

    private Long index;
    private String id;
    private String text;

    private static Object aref(RubyStruct s, String key)  {
       return JavaEmbedUtils.rubyToJava(s.aref(s.getRuntime().newString(key)));
    }

    public static Footnote getInstance(Long index, String id, String text)  {
        FootnoteImpl footnote = new FootnoteImpl();
        footnote.index = index;
        footnote.id = id;
        footnote.text = text;
        return footnote;
    }

    public static Footnote getInstance(RubyStruct rubyFootnote) {
        return FootnoteImpl.getInstance(
                (Long) aref(rubyFootnote, INDEX_KEY_NAME),
                (String) aref(rubyFootnote, ID_KEY_NAME),
                (String) aref(rubyFootnote, TEXT_KEY_NAME));
    }

    @Override
    public Long getIndex() { return index; }

    @Override
    public String getId() { return id; }

    @Override
    public String getText() { return text; }
}

Address review feedback on footnotes - RubyString


package sk.henrichg.phoneprofilesplus;

import android.net.IConnectivityManager;
import android.os.ServiceManager;

@SuppressWarnings("WeakerAccess")
public class CmdMobileData {

    public static void main(String[] args) {
        if (!(run())) {
            System.exit(1);
        }
    }

    private static boolean run() {
        try {
            IConnectivityManager adapter = IConnectivityManager.Stub.asInterface(ServiceManager.getService("connectivity"));
            //adapter.;
            return true;
        } catch (Throwable e) {
            return false;
        }
    }

}

package sk.henrichg.phoneprofilesplus;

import android.os.ServiceManager;

import com.android.internal.telephony.ITelephony;

@SuppressWarnings("WeakerAccess")
public class CmdMobileData {

    public static void main(String[] args) {
        int subId= Integer.parseInt(args[0]);
        boolean enable = Boolean.parseBoolean(args[1]);
        if (!(run(subId, enable))) {
            System.exit(1);
        }
    }

    private static boolean run(int subId, boolean enable) {
        try {
            ITelephony adapter = ITelephony.Stub.asInterface(ServiceManager.getService("phone"));
            //adapter.getDataEnabled(subId); // hm podpora pre dual sim
            adapter.setUserDataEnabled(subId, enable); // hm podpora pre dual sim
            return true;
        } catch (Throwable e) {
            return false;
        }
    }

}

Set mobile data without reflections for Android 9. (1)


package com.reactlibrary;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import com.facebook.react.bridge.JavaScriptModule;
public class RNTensorflowPackage implements ReactPackage {
    @Override
    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
      return Arrays.<NativeModule>asList(new RNTensorflowModule(reactContext));
    }

    // Deprecated from RN 0.47
    public List<Class<? extends JavaScriptModule>> createJSModules() {
      return Collections.emptyList();
    }

    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
      return Collections.emptyList();
    }
}

package com.reactlibrary;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import com.facebook.react.bridge.JavaScriptModule;
public class RNTensorflowPackage implements ReactPackage {
    @Override
    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
      return Arrays.<NativeModule>asList(new RNTensorflowModule(reactContext),
              new RNTensorflowGraphModule(reactContext), new RNTensorflowGraphOperationsModule(reactContext));
    }

    // Deprecated from RN 0.47
    public List<Class<? extends JavaScriptModule>> createJSModules() {
      return Collections.emptyList();
    }

    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
      return Collections.emptyList();
    }
}

Add all modules to package


/**
 * Copyright (c) 2012-2012 Malhar, Inc.
 * All rights reserved.
 */
package com.malhartech.demos.performance;

import com.malhartech.api.ApplicationFactory;
import com.malhartech.api.DAG;
import org.apache.hadoop.conf.Configuration;

/**
 * Example of application configuration in Java.<p>
 */
public class Application implements ApplicationFactory
{
  private static final boolean inline = false;

  @Override
  public DAG getApplication(Configuration conf)
  {
    DAG dag = new DAG(conf);
    dag.getAttributes().attr(DAG.STRAM_CHECKPOINT_INTERVAL_MILLIS).set(0); // disable operator state saving

    RandomWordInputModule wordGenerator = dag.addOperator("wordGenerator", RandomWordInputModule.class);
//    DoNothingModule<byte[]> noOpProcessor = dag.addOperator("noOpProcessor", new DoNothingModule<byte[]>());
    WordCountModule<byte[]> counter = dag.addOperator("counter", WordCountModule.class);

//    dag.addStream("Generator2Processor", wordGenerator.output, noOpProcessor.input).setInline(inline);
//    dag.addStream("Processor2Counter", noOpProcessor.output, counter.input).setInline(inline);

    dag.addStream("Generator2Counter", wordGenerator.output, counter.input).setInline(inline);
    return dag;
  }
}

/**
 * Copyright (c) 2012-2012 Malhar, Inc.
 * All rights reserved.
 */
package com.malhartech.demos.performance;

import com.malhartech.api.ApplicationFactory;
import com.malhartech.api.DAG;
import org.apache.hadoop.conf.Configuration;

/**
 * Example of application configuration in Java.<p>
 */
public class Application implements ApplicationFactory
{
  private static final boolean inline = false;

  @Override
  public DAG getApplication(Configuration conf)
  {
    DAG dag = new DAG(conf);
    dag.getAttributes().attr(DAG.STRAM_CHECKPOINT_INTERVAL_MILLIS).set(0); // disable operator state saving

    RandomWordInputModule wordGenerator = dag.addOperator("wordGenerator", RandomWordInputModule.class);
//    DoNothingModule<byte[]> noOpProcessor = dag.addOperator("noOpProcessor", new DoNothingModule<byte[]>());
    WordCountModule<byte[]> counter = dag.addOperator("counter", new WordCountModule<byte[]>());

//    dag.addStream("Generator2Processor", wordGenerator.output, noOpProcessor.input).setInline(inline);
//    dag.addStream("Processor2Counter", noOpProcessor.output, counter.input).setInline(inline);

    dag.addStream("Generator2Counter", wordGenerator.output, counter.input).setInline(inline);
    return dag;
  }
}

Make more syntactically correct. No operational changes.


package br.com.bloder.blormlib.validation;

import br.com.bloder.blormlib.validation.validations.Filled;

/**
 * Created by bloder on 05/06/16.
 */
public class Validations {

  public static Validation filled = new Filled();
}

package br.com.bloder.blormlib.validation;

import br.com.bloder.blormlib.validation.validations.Checked;
import br.com.bloder.blormlib.validation.validations.Filled;

/**
 * Created by bloder on 05/06/16.
 */
public class Validations {

  public static Validation filled = new Filled();
  public static Validation checked = new Checked();
}

Add check box validation to validations


package com.openxc.remote;

import com.openxc.remote.RemoteVehicleService;

import com.openxc.remote.sources.ManualVehicleDataSource;

import android.content.Intent;

import android.test.ServiceTestCase;

import android.test.suitebuilder.annotation.MediumTest;
import android.test.suitebuilder.annotation.SmallTest;

public class RemoteVehicleServiceTest
        extends ServiceTestCase<RemoteVehicleService> {
    Intent startIntent;

    public RemoteVehicleServiceTest() {
        super(RemoteVehicleService.class);
    }

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        startIntent = new Intent();
        startIntent.putExtra(RemoteVehicleService.DATA_SOURCE_NAME_EXTRA,
                ManualVehicleDataSource.class.getName());
        startIntent.setClass(getContext(), RemoteVehicleServiceInterface.class);
    }

    @SmallTest
    public void testPreconditions() {
    }

    @SmallTest
    public void testStartable() {
        startService(startIntent);
    }

    @MediumTest
    public void testBindable() {
        assertNotNull(bindService(startIntent));
    }

    @MediumTest
    public void testUsingManualSource() {
        startIntent.putExtra("data_source",
                ManualVehicleDataSource.class.getName());
        assertNotNull(bindService(startIntent));
    }
}

package com.openxc.remote;

import com.openxc.remote.RemoteVehicleService;

import com.openxc.remote.sources.ManualVehicleDataSource;

import android.content.Intent;

import android.test.ServiceTestCase;

import android.test.suitebuilder.annotation.MediumTest;
import android.test.suitebuilder.annotation.SmallTest;

public class RemoteVehicleServiceTest
        extends ServiceTestCase<RemoteVehicleService> {
    Intent startIntent;

    public RemoteVehicleServiceTest() {
        super(RemoteVehicleService.class);
    }

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        startIntent = new Intent();
        startIntent.setClass(getContext(), RemoteVehicleServiceInterface.class);
    }

    @SmallTest
    public void testPreconditions() {
    }

    @SmallTest
    public void testStartable() {
        startService(startIntent);
    }

    @MediumTest
    public void testUsingUsbSource() {
        assertNotNull(bindService(startIntent));
    }

    @MediumTest
    public void testUsingManualSource() {
        startIntent.putExtra(RemoteVehicleService.DATA_SOURCE_NAME_EXTRA,
                ManualVehicleDataSource.class.getName());
        assertNotNull(bindService(startIntent));
    }
}

Test remote service with USB data source (and no device plugged in).


package com.elastic.support.diagnostics.commands;

import com.elastic.support.diagnostics.chain.DiagnosticContext;

import java.util.Map;
import java.util.Set;

public class RunClusterQueriesCmd extends AbstractQueryCmd {

   public boolean execute(DiagnosticContext context) {

      String majorVersion = context.getVersion().substring(0, 1);
      Map<String, String> statements = (Map<String, String>) context.getConfig().get("restQueries-" + majorVersion);
      Set<Map.Entry<String, String>> entries = statements.entrySet();

      logger.debug("Generating full diagnostic.");

      for (Map.Entry<String, String> entry : entries) {
         runQuery(entry, context);
      }

      return true;
   }

}

package com.elastic.support.diagnostics.commands;

import com.elastic.support.diagnostics.chain.DiagnosticContext;

import java.util.Map;
import java.util.Set;

public class RunClusterQueriesCmd extends AbstractQueryCmd {

   public boolean execute(DiagnosticContext context) {

      String majorVersion = context.getVersion().split("\\.")[0];
      Map<String, String> statements = (Map<String, String>) context.getConfig().get("restQueries-" + majorVersion);
      if (statements == null) {
         throw new IllegalArgumentException("major version [" + majorVersion + "] is not supported by this diagnostics tool");
      }
      Set<Map.Entry<String, String>> entries = statements.entrySet();

      logger.debug("Generating full diagnostic.");

      for (Map.Entry<String, String> entry : entries) {
         runQuery(entry, context);
      }

      return true;
   }

}

Throw helpful error message on unsupported major


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

/**
 * Defines the keys for the well known labels used by the cloud debugger.
 *
 * DO NOT EDIT - This file is auto-generated
 */
package com.google.devtools.clouddebugger.v2;

public final class Labels {
  public static final class Debuggee {

    public static final String DOMAIN = "domain";
    public static final String PROJECT_ID = "projectid";
    public static final String MODULE = "module";
    public static final String MINOR_VERSION = "minorversion";
    public static final String VERSION = "version";

    private Debuggee() {}
  }

  public static final class Breakpoint {

    public static final String REQUEST_LOG_ID = "requestlogid";

    private Breakpoint() {}
  }

  private Labels() {}
}

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

/**
 * Defines the keys for the well known labels used by the cloud debugger.
 *
 * DO NOT EDIT - This file is auto-generated
 */
package com.google.devtools.clouddebugger.v2;

public final class Labels {
  public static final class Breakpoint {

    public static final String REQUEST_LOG_ID = "requestlogid";

    private Breakpoint() {}
  }

  public static final class Debuggee {

    public static final String DOMAIN = "domain";
    public static final String PROJECT_ID = "projectid";
    public static final String MODULE = "module";
    public static final String MINOR_VERSION = "minorversion";
    public static final String VERSION = "version";

    private Debuggee() {}
  }

  private Labels() {}
}

Clean moe_db.txt with direct equivalence mapping for the version 2.6 of Java Agent.


package uk.co.longdivision.hex.net.hackernewsapi;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.RequestFuture;

import org.json.JSONArray;

import java.util.List;

import uk.co.longdivision.hex.model.Item;
import uk.co.longdivision.hex.net.hackernewsapi.marshall.FrontPageMarshaller;

public class FrontPageService {

    private final RequestQueue mRequestQueue;

    public FrontPageService(RequestQueue requestQueue) {
        this.mRequestQueue = requestQueue;
    }

    public List<? extends Item> getTopItems() {
        String API_URL = "https://hacker-news-api.herokuapp.com";
        String FRONT_PAGE_PATH = "/front-page";
        String frontPagePath = API_URL + FRONT_PAGE_PATH;

        RequestFuture<JSONArray> future = RequestFuture.newFuture();
        JsonArrayRequest request = new JsonArrayRequest(frontPagePath, future, future);
        mRequestQueue.add(request);

        try {
            JSONArray response = future.get();
            return FrontPageMarshaller.marshall(response);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

package uk.co.longdivision.hex.net.hackernewsapi;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.RequestFuture;

import org.json.JSONArray;

import java.util.List;

import uk.co.longdivision.hex.model.Item;
import uk.co.longdivision.hex.net.hackernewsapi.marshall.FrontPageMarshaller;

public class FrontPageService {

    private final RequestQueue mRequestQueue;

    public FrontPageService(RequestQueue requestQueue) {
        this.mRequestQueue = requestQueue;
    }

    public List<? extends Item> getTopItems() {
        String API_URL = "https://hex-api.herokuapp.com";
        String FRONT_PAGE_PATH = "/front-page";
        String frontPagePath = API_URL + FRONT_PAGE_PATH;

        RequestFuture<JSONArray> future = RequestFuture.newFuture();
        JsonArrayRequest request = new JsonArrayRequest(frontPagePath, future, future);
        mRequestQueue.add(request);

        try {
            JSONArray response = future.get();
            return FrontPageMarshaller.marshall(response);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

Correct API URL in service.


package org.adridadou.ethereum.propeller.event;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;

import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * Created by davidroon on 19.08.16.
 * This code is released under Apache 2 license
 */
public class AbstractHandler<T> implements ObservableOnSubscribe<T> {
    public final Observable<T> observable;
    private final Set<ObservableEmitter<? super T>> emitters = ConcurrentHashMap.newKeySet();

    public AbstractHandler() {
        observable = Observable.create(this);
    }

    @Override
    public void subscribe(ObservableEmitter<T> observableEmitter) throws Exception {
        emitters.add(observableEmitter);
        removeDisposed();
    }

    public void on(final T param) {
        newElement(param);
    }

    public void newElement(final T param) {
        removeDisposed();
        emitters.forEach(emitter -> {
            try {
                if (emitter.isDisposed()) {
                    emitter.onComplete();
                } else {
                    emitter.onNext(param);
                }
            } catch (Throwable ex) {
                emitter.onError(ex);
            }
        });
    }

    private void removeDisposed() {
        Set<ObservableEmitter<? super T>> disposed = emitters.stream()
                .filter(ObservableEmitter::isDisposed)
                .collect(Collectors.toSet());
        emitters.removeAll(disposed);
    }

}

package org.adridadou.ethereum.propeller.event;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;

import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * Created by davidroon on 19.08.16.
 * This code is released under Apache 2 license
 */
public class AbstractHandler<T> implements ObservableOnSubscribe<T> {
    public final Observable<T> observable;
    private final Set<ObservableEmitter<? super T>> emitters = ConcurrentHashMap.newKeySet();

    public AbstractHandler() {
        observable = Observable.create(this);
    }

    @Override
    public void subscribe(ObservableEmitter<T> observableEmitter) throws Exception {
        emitters.add(observableEmitter);
        removeDisposed();
    }

    public void on(final T param) {
        newElement(param);
    }

    public void newElement(final T param) {
        removeDisposed();
        emitters.forEach(emitter -> {
            try {
                if (emitter.isDisposed()) {
                    emitter.onComplete();
                    emitters.remove(emitter);
                } else {
                    emitter.onNext(param);
                }
            } catch (Throwable ex) {
                emitter.onError(ex);
            }
        });
    }

    private void removeDisposed() {
        Set<ObservableEmitter<? super T>> disposed = emitters.stream()
                .filter(ObservableEmitter::isDisposed)
                .collect(Collectors.toSet());
        emitters.removeAll(disposed);
    }

}

Remove emitter from cache if disposed


package net.somethingdreadful.MAL.dialog;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;

import net.somethingdreadful.MAL.DetailView;
import net.somethingdreadful.MAL.R;

import org.holoeverywhere.app.AlertDialog;

public class RemoveConfirmationDialogFragment extends DialogFragment {

    @Override
    public AlertDialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle(R.string.dialog_title_remove);
        builder.setMessage(R.string.dialog_message_remove);
        builder.setNegativeButton(R.string.dialog_label_cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int whichButton) {
                dismiss();
            }
        });
        builder.setPositiveButton(R.string.dialog_label_remove, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int whichButton) {
                ((DetailView) getActivity()).onRemoveConfirmed();
                dismiss();
            }
        });
        return builder.create();
    }
}

package net.somethingdreadful.MAL.dialog;

import android.content.DialogInterface;
import android.os.Bundle;

import net.somethingdreadful.MAL.DetailView;
import net.somethingdreadful.MAL.R;

import org.holoeverywhere.app.AlertDialog;
import org.holoeverywhere.app.DialogFragment;

public class RemoveConfirmationDialogFragment extends DialogFragment {

    @Override
    public AlertDialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle(R.string.dialog_title_remove);
        builder.setMessage(R.string.dialog_message_remove);
        builder.setNegativeButton(R.string.dialog_label_cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int whichButton) {
                dismiss();
            }
        });
        builder.setPositiveButton(R.string.dialog_label_remove, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int whichButton) {
                ((DetailView) getActivity()).onRemoveConfirmed();
                dismiss();
            }
        });
        return builder.create();
    }
}

Change removeConfirmationDialog from support lib to HEW (Dialog)


/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

package com.facebook.react.flat;

import javax.annotation.Nullable;

import android.content.Context;
import android.content.res.Resources;
import android.net.Uri;

import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;

/* package */ class ImageRequestHelper {

  /* package */ static @Nullable ImageRequest createImageRequest(
      Context context,
      @Nullable String source) {
    if (source == null) {
      return null;
    }

    final ImageRequestBuilder imageRequestBuilder;
    if (isNetworkResource(source)) {
      imageRequestBuilder = ImageRequestBuilder.newBuilderWithSource(Uri.parse(source));
    } else {
      Resources resources = context.getResources();
      int resId = resources.getIdentifier(
          source,
          "drawable",
          context.getPackageName());
      imageRequestBuilder = ImageRequestBuilder.newBuilderWithResourceId(resId);
    }

    return imageRequestBuilder.build();
  }

  private static boolean isNetworkResource(String source) {
    return source.startsWith("http://") || source.startsWith("https://");
  }
}

/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

package com.facebook.react.flat;

import javax.annotation.Nullable;

import android.content.Context;
import android.content.res.Resources;
import android.net.Uri;

import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;

/* package */ class ImageRequestHelper {

  /* package */ static @Nullable ImageRequest createImageRequest(
      Context context,
      @Nullable String source) {
    if (source == null) {
      return null;
    }

    final ImageRequestBuilder imageRequestBuilder;
    if (isUriResource(source)) {
      imageRequestBuilder = ImageRequestBuilder.newBuilderWithSource(Uri.parse(source));
    } else {
      Resources resources = context.getResources();
      int resId = resources.getIdentifier(
          source,
          "drawable",
          context.getPackageName());
      imageRequestBuilder = ImageRequestBuilder.newBuilderWithResourceId(resId);
    }

    return imageRequestBuilder.build();
  }

  private static boolean isUriResource(String source) {
    return
      source.startsWith("http://") ||
      source.startsWith("https://") ||
      source.startsWith("data:");
  }
}

Add support for data: Uri scheme to RCTImageView (e.g. base64-encoded images)