package com.sunny.grokkingalgorithms.ctci.c1;

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

/**
 * Created by sundas on 3/13/2018.
 */
class Holder2D{
   public int i;
   public int j;
}
public class SetRowAndColumnToZero {

  /*
  if an element in an MXN matrix is zeror, the entire row and column is set to 0.
   */

  /**
   *
   * @param matrix
   * @return
   */
  public static int[][] setToZero(int[][] matrix){
    List<Holder2D> markPoints = new ArrayList<>();
    /*
    First paas to find mark points
     */
    for(int i = 0; i < matrix.length ; i++){
      for(int j  = 0; j < matrix[i].length ; j++){
        if(matrix[i][j] == 0){
          Holder2D holder2D = new Holder2D();
          holder2D.i = i;
          holder2D.j = j;
          markPoints.add(holder2D);
        }
      }
    }
    /*
    Second passs to change all rows and columsn corresponding to markpoints to zero
     */
    for(Holder2D holder2D : markPoints){
      int i = holder2D.i;
      int j = holder2D.j;
      paintWithZeros(matrix,i,j);
    }
    return matrix;
  }

  public static void paintWithZeros(int[][] matrix,int i,int j){
    /*
    Paint row and co,un
     */
    for(int index = 0; index < matrix[i].length ; index++){
      matrix[i][index] = 0;
    }
    /*
    Paint column
     */
    for(int index = 0;index < matrix.length ; index++){
      matrix[index][j] = 0;
    }
  }

  /**
   *
   * @param args
   */
  public static void main(String[] args) {
    int[][] matrix = new int[][]{
        {1,2,3},
        {4,0,6},
        {7,8,9}
    };
    MatrixRotation.printMatrix(matrix);
    int[][] modified = setToZero(matrix);
    MatrixRotation.printMatrix(modified);
    System.out.println("Next");
    matrix = new int[][]{
        {1,2,3},
        {4,5,6},
        {7,8,0}
    };
    MatrixRotation.printMatrix(matrix);
    modified = setToZero(matrix);
    MatrixRotation.printMatrix(modified);
  }

}

Set rows and columns of an mxn matrix to zero if any of the lements is zero.


import java.util.ArrayList;
import java.util.Scanner;

/**
 * Created by Nathan_Zeplowitz on 4/11/15.
 */
public class PrimeFactors {
    public static void main(String[] args) {
        PrimeFactors primeFactors = new PrimeFactors();
        Scanner in = new Scanner(System.in);

        System.out.println("Enter a number");
        int n = in.nextInt();
        primeFactors.generate(n);
    }

    private void generate(int n) {
        ArrayList<Integer> primeFactors = new ArrayList<Integer>();
        for (int i = 2; i <= n; i++) {
            while (n % i == 0) {
                primeFactors.add(i);
                n /= i;
            }
        }
        for (int i = 0; i < primeFactors.size(); i++) {
            if (i == primeFactors.size() - 1) {
                System.out.print(primeFactors.get(i));
            } else {
                System.out.print(primeFactors.get(i) + ",");
            }
        }
    }
}

Add Solution for Prime Factor Exercise

Add Solution for Prime Factor Exercise


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

import com.google.common.base.Stopwatch;
import com.google.common.io.ByteStreams;
import java.io.OutputStream;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author shevek
 */
@Ignore
public class ParallelGZIPPerformanceTest {

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

    @Test
    public void testThreads() throws Exception {
        LOG.info("AvailableProcessors = " + Runtime.getRuntime().availableProcessors());
        Random r = new Random();
        byte[] data = new byte[1024 * 1024];
        r.nextBytes(data);
        for (int i = 0; i < data.length; i++)
            data[i] = (byte) (data[i] & 0x7f);  // Strip the top bit to make it amenable to Huffman compression.

        OutputStream out = ByteStreams.nullOutputStream();
        ParallelGZIPOutputStream gzip = new ParallelGZIPOutputStream(out);
        Stopwatch stopwatch = Stopwatch.createStarted();

        for (int i = 0; i < 1024 * 20; i++) {
            gzip.write(data);
        }
        gzip.close();

        long elapsed = stopwatch.elapsed(TimeUnit.MILLISECONDS);
        LOG.info("elapsed=" + elapsed);
    }
}

Add performance test for use with profilers.


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

import org.gradle.api.NonNullApi;

Add `@NonNullApi` to newly introduced package


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

import java.util.Optional;
import org.junit.Assert;
import org.junit.Test;

/**
 * A unit test class for {@link SimpleJavaProcessConfig}.
 *
 * @author Viktor Csomor
 */
public class SimpleJavaProcessConfigTest {

  @Test
  public void testAdditionalClassPathsAreIncludedInJointClassPath() {
    String additionalClassPath1 = "home/classes";
    String additionalClassPath2 = "somewhere_else/classes";
    SimpleJavaProcessConfig config = new SimpleJavaProcessConfig(null, additionalClassPath1, additionalClassPath2);
    Optional<String> optionalClassPath = config.getClassPath();
    Assert.assertTrue(optionalClassPath.isPresent());
    String classPath = optionalClassPath.get();
    Assert.assertTrue(classPath.contains(additionalClassPath1));
    Assert.assertTrue(classPath.contains(additionalClassPath2));
  }

}

Add a unit test for class path handling in SimpleJavaProcessConfig


package org.metaborg.util.inject;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
import com.google.inject.util.Types;

public class GenericInjectUtils {
    public static <T> Key<T> key(Type rawType, Type... typeArgs) {
        final ParameterizedType type = Types.newParameterizedType(rawType, typeArgs);
        @SuppressWarnings("unchecked") final Key<T> key = (Key<T>) Key.get(type);
        return key;
    }

    public static <T> Key<T> key(TypeLiteral<T> typeLiteral, Type... typeArgs) {
        final Class<? super T> rawType = typeLiteral.getRawType();
        return key(rawType, typeArgs);
    }

    public static <T> T instance(Injector injector, Type rawType, Type... typeArgs) {
        final Key<T> key = key(rawType, typeArgs);
        return injector.getInstance(key);
    }

    public static <T> T instance(Injector injector, TypeLiteral<T> typeLiteral, Type... typeArgs) {
        final Key<T> key = key(typeLiteral, typeArgs);
        return injector.getInstance(key);
    }
}

Add utility class for instantiating generic classes from a Guice injector.


package org.fedorahosted.flies.core.action;

import javax.persistence.EntityManager;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.ProduceMime;

import org.fedorahosted.flies.core.model.Project;
import org.fedorahosted.flies.core.model.ProjectSeries;
import org.fedorahosted.flies.core.model.ProjectTarget;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;

@Name("projectResource")
@Path("/project")
public class ProjectResource {

  @In
  private EntityManager entityManager;

  @Out(required = false)
  private Project project;

  @GET
  @Path("/{projectId}")
  @ProduceMime("text/plain")
  public Project getProject(@PathParam("projectId") long id) {
     return project = entityManager.find(Project.class, id);
  }

}

Add a Resources class of REST

Add a Resources class of REST


/**
 * Twist in the Tale 3.3 from the OCA Java SE 7 book by Mala Gupta (Manning Publications)
 * Created by Josef on 12/27/13.
 */
class Phone2 {
    public String model;
    private double weight;
    public void setWeight(double w) {weight = w;}
    public double getWeight() {return weight;}
}

Add code for Twist in the Tale 3.3

Add code for Twist in the Tale 3.3


package tc.oc.commons.core.format;

import javax.inject.Inject;

import net.md_5.bungee.api.chat.BaseComponent;
import tc.oc.commons.core.chat.Component;

import static net.md_5.bungee.api.ChatColor.*;

public class GeneralFormatter {

    @Inject private GeneralFormatter() {}

    private final Component brandName = new Component("PGM", GOLD);

    public BaseComponent brandName() {
        return brandName;
    }

    public String publicHostname() {
        return "localhost"; // TODO: configurable
    }
}

package tc.oc.commons.core.format;

import javax.inject.Inject;

import net.md_5.bungee.api.chat.BaseComponent;
import tc.oc.commons.core.chat.Component;

import static net.md_5.bungee.api.ChatColor.*;

public class GeneralFormatter {

    @Inject private GeneralFormatter() {}

    private final Component brandName = new Component("Stratus", GOLD);

    public BaseComponent brandName() {
        return brandName;
    }

    public String publicHostname() {
        return "play.stratus.network"; // TODO: configurable
    }
}

Change lobby branding to stratus

Change lobby branding to stratus


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

package org.onehippo.forge.webservices.jaxrs.models;

import org.junit.Test;

import static org.junit.Assert.*;

public class HippoVersionInfoTest {

    @Test
    public void testGetCmsVersion() throws Exception {
        final HippoVersionInfo hippoVersionInfo = new HippoVersionInfo();
        final String cmsVersion = "7.9.3";
        hippoVersionInfo.setCmsVersion(cmsVersion);
        assertTrue(cmsVersion.equals(hippoVersionInfo.getCmsVersion()));
    }

    @Test
    public void testGetRepositoryVersion() throws Exception {
        final HippoVersionInfo hippoVersionInfo = new HippoVersionInfo();
        final String repositoryVersion = "7.9.2";
        hippoVersionInfo.setRepositoryVersion(repositoryVersion);
        assertTrue(repositoryVersion.equals(hippoVersionInfo.getRepositoryVersion()));
    }
}

Add some more test coverage

Add some more test coverage


/**
 * Given a 2d grid map of '1's (land) and '0's (water), count the number of islands.
 * An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically.
 * You may assume all four edges of the grid are all surrounded by water.
 */

public class Solution {
  public int numIslands(char[][] grid) {
    if (grid.length == 0 || grid[0].length == 0) return 0;
    Stack<int[]> stack = new Stack<int[]>();

    int count = 0;
    for (int i = 0; i < grid.length; i ++) {
      for (int j = 0; j < grid[0].length; j ++) {

        // Hit land which can be AT MOST 1 island.
        // Therefore increment by only 1 and convert all nearby land into water.
        if (grid[i][j] == '1') {
          count++;
          stack.clear();
          stack.push(new int[] { i, j });
          while (!stack.isEmpty()) {
            int[] pair = stack.pop();
            int x = pair[0];
            int y = pair[1];
            if (x >= grid.length || x < 0 || y >= grid[0].length || y < 0 || grid[x][y] == '0') continue;
            grid[x][y] = '0';
            stack.push(new int[] { x + 1, y });
            stack.push(new int[] { x - 1, y });
            stack.push(new int[] { x, y + 1 });
            stack.push(new int[] { x, y - 1 });

          }
        }
      }
    }
    return count;
  }
}

Add number of islands 200

Add number of islands 200


/**
 * @file SimpleHttpServer.java
 * @author Valery Samovich
 * @version 1
 * @date 2015/02/06
 */

package com.samovich.specialized.httpserver;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

/*
 * a simple static http server
*/
public class SimpleHttpServer {

    public static void main(String[] args) throws Exception {
        HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
        server.createContext("/test", new MyHandler());
        server.setExecutor(null); // creates a default executor
        server.start();
        System.out.println("Server started.");
    }

    static class MyHandler implements HttpHandler {

        public void handle(HttpExchange t) throws IOException {
            String response = "Http Server is started on port 8000";
            t.sendResponseHeaders(200, response.length());
            OutputStream os = t.getResponseBody();
            os.write(response.getBytes());
            os.close();
        }

    }

}

Add example of Http Server and fix package name


import juglr.Box;
import juglr.BoxParser;
import juglr.JSonBoxParser;
import juglr.net.HTTP;
import juglr.net.HTTPRequestWriter;
import juglr.net.HTTPResponseReader;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * Flood the HTTPServerExample with requests
 */
public class HTTPServerExampleClient {

    public static void main(String[] args) throws Exception {
        InetSocketAddress socketAddress =
                   new InetSocketAddress("localhost", 4567);
        for (int i = 1; i < 10000; i++) {
            ByteBuffer buf = ByteBuffer.allocate(1024);
            SocketChannel channel = SocketChannel.open(socketAddress);

            // Send request
            HTTPRequestWriter w = new HTTPRequestWriter(channel, buf);
            w.writeMethod(HTTP.Method.POST);
            w.writeUri("/actor/calc/");
            w.writeVersion(HTTP.Version.ONE_ZERO);
            w.writeHeader("User-Agent", "Juglr/0.2");
            w.startBody();
            w.writeBody("{\"isPrime\" : " + i + "}");
            w.flush();

            // Read response
            buf.clear();
            HTTPResponseReader r = new HTTPResponseReader(channel, buf);
            HTTP.Version v = r.readVersion();
            if (v == HTTP.Version.ERROR || v == HTTP.Version.UNKNOWN) {
                throw new IOException("Bad protocol version version");
            }
            int status = r.readStatus().httpOrdinal();
            if (status < 200 || status >= 300) {
                channel.close();
                throw new RuntimeException("Bad response code " + status);
            }

            byte[] bbuf = new byte[1024];
            while (r.readHeaderField(bbuf) > 0) {
                // Ignore headers
            }

            BoxParser parser = new JSonBoxParser();
            Box box = parser.parse(new InputStreamReader(r.streamBody()));
            System.out.println("Response: " + box.toString());

            w.close();
        }

    }

}

Implement a raw sample client hammering the HTTPExampleServer with requests.


package npe;

public class GuaranteedDereferenceInteractionWithAssertionMethods {

	public Object x;

	public boolean b;

	public int falsePositive() {

		if (x == null)
			System.out.println("x is null");
		if (b) {
			x = bar();
			checkForError();
		}

		return x.hashCode();
	}

	public void checkForError() {

	}

	public Object bar() {
		return new Object();
	}

}

Add false positive test case for interaction with assertion methods

git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@6382 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3


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

package com.hp.autonomy.iod.client.error;

public class IodServerErrorException extends RuntimeException implements IodErrorException {
    private static final long serialVersionUID = -1623916762461350039L;

    private final IodErrorCode errorCode;

    public IodServerErrorException(final IodError iodError) {
        super(iodError.getReason());

        this.errorCode = iodError.getErrorCode();
    }

    @Override
    public IodErrorCode getErrorCode() {
        return errorCode;
    }
}

Add file missing from last commit.

Add file missing from last commit.


package com.test.sorting;

import com.sorting.SelectionSort;

import junit.framework.TestCase;

public class TestSelectionSort extends TestCase {

    public void testSelectionSort() {

        String[] A = { "zs", "qw", "qr", "miguel", "rtd", "fgs", "qq", "mk", "slao", "oiu", "vf", "xs", "er", "qw",
                "bv" };
        Integer[] B = { 2, 4, 7, 542, 0, 1, 3, 0, 6, 2, 7, 9, 10, 2, 4, 6, 0, 3, 2, 9, 2, 77, 33, 22, 5, 4, 2, 2, 2 };

        SelectionSort.sort(A);
        SelectionSort.sort(B);

        String[] sortedA = { "bv", "er", "fgs", "miguel", "mk", "oiu", "qq", "qr", "qw", "qw", "rtd", "slao", "vf",
                "xs", "zs" };
        Integer[] sortedB = { 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4, 4, 5, 6, 6, 7, 7, 9, 9, 10, 22, 33, 77,
                542 };

        for (int i = 0; i < A.length; i++) {
            assertEquals(true, A[i].equals(sortedA[i]));
        }

        for (int i = 0; i < B.length; i++) {
            assertEquals(true, B[i].equals(sortedB[i]));
        }

    }

}

Add JUnit test for SelectionSort

Add JUnit test for SelectionSort


/*
 * Copyright 2015 Henrik Olsson
 *
 * 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.meisolsson.githubsdk.model;

import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import com.meisolsson.githubsdk.core.FormattedTime;
import com.google.auto.value.AutoValue;
import com.squareup.moshi.Json;
import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;

import java.util.Date;
import java.util.List;

@AutoValue
public abstract class ClientErrorResponse implements Parcelable {
    @AutoValue
    public abstract static class BlockReason implements Parcelable {
        @Nullable
        public abstract String reason();

        @Json(name = "created_at")
        @FormattedTime
        @Nullable
        public abstract Date createdAt();

        @Json(name = "html_url")
        @Nullable
        public abstract String htmlUrl();

        public static JsonAdapter<BlockReason> jsonAdapter(Moshi moshi) {
            return new AutoValue_ClientErrorResponse_BlockReason.MoshiJsonAdapter(moshi);
        }
    }

    @AutoValue
    public abstract static class FieldError implements Parcelable {
        public enum Reason {
            @Json(name = "missing") MissingResource,
            @Json(name = "missing_field") MissingField,
            @Json(name = "invalid") Invalid,
            @Json(name = "already_exists") AlreadyExists,
            @Json(name = "too_large") TooLarge,
            @Json(name = "custom") Custom
        }

        @NonNull
        public abstract String resource();

        @NonNull
        public abstract String field();

        @Json(name = "code")
        @NonNull
        public abstract Reason reason();

        @Nullable
        public abstract String message();

        public static JsonAdapter<FieldError> jsonAdapter(Moshi moshi) {
            return new AutoValue_ClientErrorResponse_FieldError.MoshiJsonAdapter(moshi);
        }
    }

    @Nullable
    public abstract String message();

    @Json(name = "block")
    @Nullable
    public abstract BlockReason blockReason();

    @Nullable
    public abstract List<FieldError> errors();

    @Json(name = "documentation_url")
    @Nullable
    public abstract String documentationUrl();

    public static JsonAdapter<ClientErrorResponse> jsonAdapter(Moshi moshi) {
        return new AutoValue_ClientErrorResponse.MoshiJsonAdapter(moshi);
    }
}

Add model for GitHub's error response.

Add model for GitHub's error response.


package org.slc.sli.modeling.rest;

import static org.junit.Assert.*;

import java.util.ArrayList;

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

/**
 * JUnit test for Application class.
 *
 * @author wscott
 *
 */
public class ApplicationTest {
    private Application application; // class under test

    private static final ArrayList<Documentation> DOC = new ArrayList<Documentation>(0);
    private static final Grammars GRAMMARS = new Grammars(DOC, new ArrayList<Include>(0));
    private static final Resources RESOURCES = new Resources("base", DOC, new ArrayList<Resource>(0));
    private static final ArrayList<ResourceType> RESOURCE_TYPES = new ArrayList<ResourceType>(0);
    private static final ArrayList<Method> METHODS = new ArrayList<Method>(0);
    private static final ArrayList<Representation> REPRESENTATIONS = new ArrayList<Representation>(0);

    @Before
    public void setup() throws Exception {

        application = new Application(DOC, GRAMMARS, RESOURCES, RESOURCE_TYPES, METHODS, REPRESENTATIONS,
                REPRESENTATIONS);
    }

    @Test(expected = NullPointerException.class)
    public void testNullResourceTypes() {
        new Application(DOC, GRAMMARS, RESOURCES, null, METHODS, REPRESENTATIONS, REPRESENTATIONS);
    }

    @Test(expected = NullPointerException.class)
    public void testNullMethods() {
        new Application(DOC, GRAMMARS, RESOURCES, RESOURCE_TYPES, null, REPRESENTATIONS, REPRESENTATIONS);
    }

    @Test(expected = NullPointerException.class)
    public void testNullRepresentations() {
        new Application(DOC, GRAMMARS, RESOURCES, RESOURCE_TYPES, METHODS, null, REPRESENTATIONS);
    }

    @Test(expected = NullPointerException.class)
    public void testNullFaults() {
        new Application(DOC, GRAMMARS, RESOURCES, RESOURCE_TYPES, METHODS, REPRESENTATIONS, null);
    }

    @Test
    public void testGetGrammars() {
        assertEquals(GRAMMARS, application.getGrammars());
    }

    @Test
    public void testGetResources() {
        assertEquals(RESOURCES, application.getResources());
    }

    @Test
    public void testGetResourceTypes() {
        assertEquals(RESOURCE_TYPES, application.getResourceTypes());
    }

    @Test
    public void testGetMethods() {
        assertEquals(METHODS, application.getMethods());
    }

    @Test
    public void testGetRepresentations() {
        assertEquals(REPRESENTATIONS, application.getRepresentations());
    }

    @Test
    public void testGetFaults() {
        assertEquals(REPRESENTATIONS, application.getFaults());
    }

    @Test
    public void testToString() {
        assertTrue(!"".equals(application.toString()));
    }

}

Add JUnit test for Application class in rest modeling module.


package com.easternedgerobotics.rov.integration;

import com.easternedgerobotics.rov.event.EventPublisher;
import com.easternedgerobotics.rov.event.UdpEventPublisher;
import com.easternedgerobotics.rov.io.Motor;
import com.easternedgerobotics.rov.io.pololu.PololuMaestro;
import com.easternedgerobotics.rov.io.pololu.PololuMaestroOutputChannel;
import com.easternedgerobotics.rov.value.SpeedValue;

import com.pi4j.io.serial.Serial;
import com.pi4j.io.serial.SerialFactory;

import rx.Observable;

@SuppressWarnings({"checkstyle:magicnumber"})
public final class IndividualMotorTest {
    private IndividualMotorTest() {

    }

    public static void main(final String[] args) throws InterruptedException {
        final byte deviceNumber = Byte.parseByte(args[0]);
        final byte channel = Byte.parseByte(args[1]);
        final int baudRate = 115200;

        final Serial serial = SerialFactory.createInstance();
        final PololuMaestro maestro = new PololuMaestro(serial, deviceNumber);
        serial.open("/dev/ttyACM0", baudRate);

        final EventPublisher eventPublisher = new UdpEventPublisher("255.255.255.255");

        final Observable<SpeedValue> speeds = eventPublisher.valuesOfType(SpeedValue.class);
        final SpeedValue speed = SpeedValue.create("Test");

        final Motor motor = new Motor(
            speeds.filter(x -> x.getName().equals("Test")),
            new PololuMaestroOutputChannel(maestro, channel, Motor.MAX_FWD, Motor.MAX_REV));

        System.out.println("Test Started");
        System.out.println("Motor is stopped");
        Thread.sleep(1000);

        eventPublisher.emit(speed.setSpeed(.5f));
        Thread.sleep(1000);
        System.out.println("Motor on half power clockwise");
        motor.write();

        eventPublisher.emit(speed.setSpeed(0f));
        Thread.sleep(1000);
        System.out.println("Motor is stopped");
        motor.write();

        eventPublisher.emit(speed.setSpeed(-.5f));
        Thread.sleep(1000);
        System.out.println("Motor on half power counter-clockwise");
        motor.write();

        Thread.sleep(1000);
        System.out.println("Motor is stopped");
        motor.writeZero();
    }
}

Add individual test for motors

Add individual test for motors


/*
 * Copyright (C) 2004 EBI, GRL
 *
 * This library is free software; you can redistribute it and/or modify it under the terms of the
 * GNU Lesser General Public License as published by the Free Software Foundation; either version
 * 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
 * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along with this library;
 * if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
 * 02111-1307 USA
 */

package org.ensembl.healthcheck.testcase.generic;

import org.ensembl.healthcheck.DatabaseRegistry;
import org.ensembl.healthcheck.DatabaseType;
import org.ensembl.healthcheck.testcase.MultiDatabaseTestCase;

/**
 * Check that the seq region table is the same in all necessary databases.
 */
public class CoordSystemAcrossSpecies extends MultiDatabaseTestCase {

    private DatabaseType[] types = {DatabaseType.CORE, DatabaseType.CDNA, DatabaseType.VEGA, DatabaseType.OTHERFEATURES};

    /**
     * Creates a new instance of CoordSystemAcrossSpecies
     */
    public CoordSystemAcrossSpecies() {

        addToGroup("release");
        setDescription("Check that the coord_system table is the same across all generic DBs; if not it will cause problems on the website.");

    }

    /**
     * Make sure that the seq_region tables are all the same.
     *
     * @param dbr The database registry containing all the specified databases.
     * @return True if the seq_region_attrib table is the same across all the species in the
     *         registry.
     */
    public boolean run(DatabaseRegistry dbr) {

        return checkTableAcrossSpecies("coord_system", dbr, types, "All coord_system tables are the same", "coord_system tables are different");

    } // run

} // CoordSystemAcrossSpecies

Check that coord_system table is the same across all databases for a species.


package nl.tudelft.watchdog.logic.interval.active;

import java.util.HashMap;
import java.util.Map;

import nl.tudelft.watchdog.util.GSONUtil;

/**
 * Construct intervals from textual representations.
 */
public class IntervalFactory {

	static Map<IntervalType, Class<? extends IntervalBase>> intervalTypes = new HashMap<>();

	static {
		intervalTypes.put(IntervalType.Reading, ReadingInterval.class);
		intervalTypes.put(IntervalType.Session, SessionInterval.class);
		intervalTypes.put(IntervalType.Typing, TypingInterval.class);
	}

	/**
	 *
	 */
	public static <T extends IntervalBase> T fromJSON(String json) {
		Map<String, String> tmp = new HashMap<String, String>();
		tmp = GSONUtil.gson().fromJson(json, tmp.getClass());

		Class<? extends IntervalBase> type = intervalTypes.get(IntervalType
				.fromMnemonic(tmp.get("at")));
		return (T) fromJSON(json, type);
	}

	/**
	 * Construct an IntervalBase subtype using a JSON string as input.
	 */
	public static <T extends IntervalBase> T fromJSON(String json, Class<T> type) {
		T a = GSONUtil.gson().fromJson(json, type);
		return a;
	}
}

Create Intervals from text (JSON ATM)

Create Intervals from text (JSON ATM)


package org.tensorics;

/**
 * Created by kkrol on 29/10/2015.
 */
public class KamilTest {

    public void testDummy() {

    }
}

Test case to trigger build.

Test case to trigger build.

git-svn-id: 44110302500ff4d6168e3867631ad1bb4eb9722b@11199 6cd15df7-5b2d-4548-a7df-5dcce267a22b


/**
* OpenCPS is the open source Core Public Services software
* Copyright (C) 2016-present OpenCPS community

* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.

* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/

package org.opencps.report.datasource;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.data.JsonDataSource;

/**
 * @author trungnt
 *
 */
public class JRJSONDataSource extends JsonDataSource {

	public JRJSONDataSource(InputStream stream)
	    throws JRException {
		super(
		    stream);

	}

	public JRJSONDataSource(InputStream jsonStream, String selectExpression)
	    throws JRException {
		super(
		    jsonStream, selectExpression);

	}

	public static JRJSONDataSource getInstance(String json)
	    throws JRException {

		InputStream stream = new ByteArrayInputStream(json
		    .getBytes(StandardCharsets.UTF_8));
		return new JRJSONDataSource(stream);
	}

	public static JRJSONDataSource getInstance(InputStream stream)
	    throws JRException {

		return new JRJSONDataSource(stream);
	}

	public static JRJSONDataSource getInstance(
	    InputStream jsonStream, String selectExpression)
	    throws JRException {

		return new JRJSONDataSource(jsonStream, selectExpression);
	}
}

Add JSONDataSource for jasper portlet

Add JSONDataSource for jasper portlet


package ro.gov.ithub.infotranspub.sql;
import java.io.IOException;
import java.sql.SQLException;

import org.apache.commons.dbcp.BasicDataSource;

public class DataSource {

    private static DataSource     datasource;
    private BasicDataSource ds;

    private DataSource() throws IOException, SQLException {
        ds = new BasicDataSource();
        ds.setDriverClassName("org.postgresql.Driver");
        ds.setUsername("alex");
        ds.setPassword("");
        ds.setUrl("jdbc:postgresql://localhost/infotranspub");

     // the settings below are optional -- dbcp can work with defaults
        //ds.setMinIdle(5);
        //--ds.setMaxActive(20);
        //ds.setMaxIdle(20);
        //ds.setMaxOpenPreparedStatements(180);

    }

    public static DataSource getInstance() throws IOException, SQLException{
        if (datasource == null) {
            datasource = new DataSource();
            return datasource;
        } else {
            return datasource;
        }
    }

    public java.sql.Connection getConnection() throws SQLException {
        return this.ds.getConnection();
    }

}

Add datasource for pool of connections to postgres


package com.antew.redditinpictures.library.interfaces;

import android.content.Intent;

import com.antew.redditinpictures.library.reddit.MySubreddits;
import com.antew.redditinpictures.library.reddit.RedditApi;
import com.antew.redditinpictures.library.reddit.RedditLoginResponse;

public interface RedditUpdateProvider {
    public void addNewPosts(RedditApi api);
    public void setRequestInProgress(boolean inProgress);
    public void onError(int errorCode);
    public void createService(Intent intent);
    public void loginComplete(RedditLoginResponse response);
    public void mySubreddits(MySubreddits mySubreddits);
}

Add interface for updating reddit data in an activity.


/*
 * Copyright (c) 2015 Inocybe and others.  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
 */

package org.opendaylight.ovsdb.openstack.netvirt;

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

import java.net.HttpURLConnection;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import org.opendaylight.neutron.spi.NeutronFloatingIP;
import org.opendaylight.ovsdb.openstack.netvirt.api.Action;
import org.opendaylight.ovsdb.openstack.netvirt.impl.NeutronL3Adapter;

/**
 * Unit test for {@link FloatingIPHandler}
 */
@RunWith(MockitoJUnitRunner.class)
public class FloatingIPHandlerTest {

    @InjectMocks private FloatingIPHandler floatingHandler = mock(FloatingIPHandler.class, Mockito.CALLS_REAL_METHODS);
    @InjectMocks private NeutronL3Adapter neutronL3Adapter = mock(NeutronL3Adapter.class);

    @Test
    public void testCanCreateFloatingIP(){
        assertEquals("Error, did not return the correct HTTP status code", HttpURLConnection.HTTP_OK, floatingHandler.canCreateFloatingIP(mock(NeutronFloatingIP.class)));
    }

    @Test
    public void testCanUpdateFloatingIP(){
        assertEquals("Error, did not return the correct HTTP status code", HttpURLConnection.HTTP_OK, floatingHandler.canUpdateFloatingIP(mock(NeutronFloatingIP.class), mock(NeutronFloatingIP.class)));
    }

    @Test
    public void testCanDeleteFloatingIP(){
        assertEquals("Error, did not return the correct HTTP status code", HttpURLConnection.HTTP_OK, floatingHandler.canDeleteFloatingIP(mock(NeutronFloatingIP.class)));
    }

    @Test
    public void testProcessEvent(){
        NorthboundEvent ev = mock(NorthboundEvent.class);

        when(ev.getNeutronFloatingIP()).thenReturn(mock(NeutronFloatingIP.class));
        when(ev.getAction()).thenReturn(Action.UPDATE);

        verifyNoMoreInteractions(neutronL3Adapter);

        floatingHandler.processEvent((AbstractEvent) ev);

        verify(neutronL3Adapter, times(1)).handleNeutronFloatingIPEvent(ev.getNeutronFloatingIP(), ev.getAction());;

        when(ev.getAction()).thenReturn(Action.ADD);
        verify(neutronL3Adapter, times(0)).handleNeutronFloatingIPEvent(ev.getNeutronFloatingIP(), ev.getAction());;

        when(ev.getAction()).thenReturn(Action.DELETE);
        verify(neutronL3Adapter, times(0)).handleNeutronFloatingIPEvent(ev.getNeutronFloatingIP(), ev.getAction());;
    }
}

Add JUnit testing for FloatingIPHandler class.

Change-Id: I1a5dc5fb7c7bc9b4a856925bb0ff731bf0d48e8b
Signed-off-by: Alexis de Talhouët <3f85d13b1d0fb141169e8f22f55d7ee87dcd5f00@inocybe.com>


/*
 * Created by brightSPARK Labs
 * www.brightsparklabs.com
 */

package com.brightsparklabs.asanti.reader.parser;

import java.text.ParseException;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.brightsparklabs.asanti.model.schema.AsnSchemaTypeDefinition;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;

/**
 * Logic for parsing the {@code IMPORTS} from a module within an ASN.1 schema
 *
 * @author brightSPARK Labs
 */
public class AsnSchemaImportsParser
{
    // -------------------------------------------------------------------------
    // CONSTANTS
    // -------------------------------------------------------------------------

    /** pattern to match an import statement pertaining to a single module */
    private static final Pattern PATTERN_MODULE_IMPORT = Pattern.compile("(.+?) FROM (.+?) \\{.+?\\}");

    /** splitter to separate comma delimited strings */
    private static final Splitter COMMA_SPLITTER = Splitter.on(',')
            .omitEmptyStrings()
            .trimResults();

    // -------------------------------------------------------------------------
    // PUBLIC METHODS
    // -------------------------------------------------------------------------

    /**
     * Parses a type definition from a module from an ASN.1 schema
     *
     * @param name
     *            the name of the defined type (i.e. the text on the left hand
     *            side of the {@code ::=})
     * @param value
     *            the value of the defined type (i.e. the text on the right hand
     *            side of the {@code ::=})
     *
     * @return an {@link AsnSchemaTypeDefinition} representing the parsed data
     *
     * @throws ParseException
     *             if any errors occur while parsing the type
     */
    public static ImmutableMap<String, String> parse(String imports) throws ParseException
    {
        final Map<String, String> typeToModule = Maps.newHashMap();

        final Matcher matcher = PATTERN_MODULE_IMPORT.matcher(imports);
        while (matcher.find())
        {
            final Iterable<String> types = COMMA_SPLITTER.split(matcher.group(1));
            final String module = matcher.group(2);
            for (final String type : types)
            {
                typeToModule.put(type, module);
            }
        }
        return ImmutableMap.copyOf(typeToModule);
    }
}

Add parser for parsing IMPORTS section

ASN-27: Add parser for parsing IMPORTS section


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

import java.util.Map;
import java.util.Set;
import org.opengis.util.Type;
import org.opengis.util.TypeName;
import org.opengis.util.MemberName;
import org.opengis.util.Record;
import org.opengis.util.RecordType;
import org.opengis.util.RecordSchema;

/**
 * Auto-generated by NetBeans.
 */
public class DefaultRecordType implements RecordType {

    @Override
    public TypeName getTypeName() {
        throw new UnsupportedOperationException();
    }

    @Override
    public RecordSchema getContainer() {
        throw new UnsupportedOperationException();
    }

    @Override
    public Map<MemberName, Type> getMemberTypes() {
        throw new UnsupportedOperationException();
    }

    @Override
    public Set<MemberName> getMembers() {
        throw new UnsupportedOperationException();
    }

    @Override
    public TypeName locate(MemberName mn) {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean isInstance(Record record) {
        throw new UnsupportedOperationException();
    }
}

Add the auto-generated stub for licensing reason (making clear that we start this class from scratch).

git-svn-id: 38d176a088663cba44dd40f58e77e6472acb7674@1495957 13f79535-47bb-0310-9956-ffa450edef68


//371. Sum of Two Integers
/**
 * Calculate the sum of two integers a and b,
 * but you are not allowed to use the operator + and -.
 *
 * Example:
 * Given a = 1 and b = 2, return 3.
 *
 * Tags: Bit Manipulation
 * Similar Problems: (M) Add Two Numbers
 *
 * @author Xinyue Zhang
 *
 */
public class Solution {
    public int getSum(int a, int b) {
        if (a == 0) return b;
        if (b == 0) return a;

        while (b != 0) {
            int carry = a & b;  //find carry
            a = a ^ b;          //xor
            b = carry << 1;     //left shift carry bit
        }

        return a;
    }

    public static void main(String[] args) {
        int a = 7, b = 3;
        Solution sol = new Solution();
        System.out.println(sol.getSum(a, b));
    }
}

Add solution for 371. Sum of Two Integers


/*
Copyright (c) 2015, Colorado State University
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

This software is provided by the copyright holders and contributors "as is" and
any express or implied warranties, including, but not limited to, the implied
warranties of merchantability and fitness for a particular purpose are
disclaimed. In no event shall the copyright holder or contributors be liable for
any direct, indirect, incidental, special, exemplary, or consequential damages
(including, but not limited to, procurement of substitute goods or services;
loss of use, data, or profits; or business interruption) however caused and on
any theory of liability, whether in contract, strict liability, or tort
(including negligence or otherwise) arising in any way out of the use of this
software, even if advised of the possibility of such damage.
*/

package io.elssa.event;

public class EventLinkException extends Exception {

    private static final long serialVersionUID = -5470653927564794388L;

    public EventLinkException() {
        super();
    }

    public EventLinkException(String s) {
        super(s);
    }

    public EventLinkException(String s, Throwable e) {
        super(s, e);
    }
}

Add exception for event handler linking errors


package com.codahale.metrics.servlet;

import com.codahale.metrics.MetricRegistry;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class MetricsContextListener implements ServletContextListener {
    private final MetricRegistry registry;

    public MetricsContextListener(MetricRegistry registry) {
        this.registry = registry;
    }

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        sce.getServletContext().setAttribute(DefaultWebappMetricsFilter.REGISTRY_ATTRIBUTE, registry);
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
    }
}

Add a context listener to metrics-servlet.

Closes #360.


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

/**
 * A reference-counted resource used in the decryption of media samples.
 *
 * @param <T> The reference type with which to make {@link Owner#onLastReferenceReleased} calls.
 */
public abstract class CryptoResource<T extends CryptoResource<T>> {

  /**
   * Implemented by the class in charge of managing a {@link CryptoResource resource's} lifecycle.
   */
  public interface Owner<T extends CryptoResource<T>> {

    /**
     * Called when the last reference to a {@link CryptoResource} is {@link #releaseReference()
     * released}.
     */
    void onLastReferenceReleased(CryptoResource<T> resource);
  }

  // TODO: Consider adding a handler on which the owner should be called.
  private final CryptoResource.Owner<T> owner;
  private int referenceCount;

  /**
   * Creates a new instance with no incoming references.
   *
   * @param owner The owner of this instance.
   */
  public CryptoResource(Owner<T> owner) {
    this.owner = owner;
    referenceCount = 0;
  }

  /** Increases by one the incoming reference count for this resource. */
  public void acquireReference() {
    referenceCount++;
  }

  /**
   * Decreases by one the incoming reference count for this resource, and notifies the owner if said
   * count reached zero as a result of this operation.
   *
   * <p>Must only be called as releasing counter-part of {@link #acquireReference()}.
   */
  @SuppressWarnings("unchecked")
  public synchronized void releaseReference() {
    if (--referenceCount == 0) {
      owner.onLastReferenceReleased(this);
    } else if (referenceCount < 0) {
      throw new IllegalStateException("Illegal release of resource.");
    }
  }
}

Add abstract superclass for Crypto resources

Necessary for implementing scheme-independant resource management.

Example: A media source needs to have ownership of a crypto resource
while samples are in buffer (but not yet in the renderer).
PiperOrigin-RevId: 241698575


package leetcode;

import java.util.List;

/**
 * https://leetcode.com/problems/subsets/
 */
public class Problem78 {
    public List<List<Integer>> subsets(int[] nums) {
        return null;
    }

    public static void main(String[] args) {
        Problem78 prob = new Problem78();
        for (List<Integer> list : prob.subsets(new int[]{1, 2, 3})) {
            System.out.println(list);
        }
    }
}

Create skeleton for problem 78

Create skeleton for problem 78


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

package algorithm.boj;

import java.io.*;

/**
 * Created by haeun on 2017-09-18
 * Site       : https://www.acmicpc.net/problem/1008
 */
public class Boj1008 {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] inputs = br.readLine().split(" ");
        br.close();
        double a = Double.parseDouble(inputs[0]);
        double b = Double.parseDouble(inputs[1]);
        System.out.print(a/b);
    }

}

Solve No.1008 from Baekjoon Online Judge


package com.boundary.plugin.sdk;

import static org.junit.Assert.*;

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

public class MeasureTest {

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
	}

	@AfterClass
	public static void tearDownAfterClass() throws Exception {
	}

	@Before
	public void setUp() throws Exception {
	}

	@After
	public void tearDown() throws Exception {
	}

	@Test
	public void test() {
		fail("Not yet implemented");
	}

}

Add test directory and JUnit test

Add test directory and JUnit test


import java.util.*;
import java.io.*;
import java.math.*;

/**
 * Auto-generated code below aims at helping you parse
 * the standard input according to the problem statement.
 **/
class Solution {

    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();

        int[] tableau = new int[n];

        for (int i = 0; i < n; i++) {
            int x = in.nextInt();
            tableau[i] = x;
        }
        System.err.println("TABLEAU INI: " + afficher(tableau));
        System.err.println(estTrie(tableau));

        int nbEchange = 0 ;

        for (int i = 0; i < tableau.length; i++) {
            System.err.println(" valeur i : " + i + " " + estTrie(tableau));
            if(tableau[i] == 0 && estTrie(tableau)==false){
                boolean trouve = false;
                for (int j = tableau.length-1; j>=0 ; j--) {
                    if(tableau[j] == 1 && trouve==false){
                        trouve = true;
                        tableau[i] =1;
                        tableau[j] =0;
                        nbEchange++;
                        System.err.println("ECHANGE N°: " + nbEchange + " soit : " + afficher(tableau));
                    }
                }
            }
        }

        // Write an action using System.out.println()
        // To debug: System.err.println("Debug messages...");

        System.out.println(nbEchange);
    }

    public static boolean estTrie(int[] tableau){
        boolean answer = true;

        for (int i = 1; i < tableau.length; i++) {
            if(tableau[i-1] == 0 && tableau[i] == 1){
                answer = false;
            }
        }
        return answer;

    }

    public static String afficher(int[] tableau){
        String answer = "";
        for (int i = 1; i < tableau.length; i++) {
            answer += Integer.toString(tableau[i]);
            answer += " ";
        }
        return answer;
    }
}

Add Community nb Mini échange

Add Community nb Mini échange


package de.gurkenlabs.litiengine.environment.tilemap.xml;

import org.junit.Test;

import junit.framework.Assert;

public class CustomPropertyProviderTests {

  @Test
  public void testSetCustomProperty() {
    CustomPropertyProvider propProvider = new CustomPropertyProvider();
    propProvider.setCustomProperty("test", "testvalue");

    Assert.assertEquals("testvalue", propProvider.getCustomProperty("test"));
    Assert.assertNull(propProvider.getCustomProperty("test2"));
    Assert.assertEquals(1, propProvider.getAllCustomProperties().size());

    propProvider.setCustomProperty("test", "testvalue2");

    Assert.assertEquals("testvalue2", propProvider.getCustomProperty("test"));
  }
}

Add test for CustomPropertyProvider implementation.


package org.wildfly.swarm.it.springdata;

import org.jboss.arquillian.drone.api.annotation.Drone;
import org.jboss.arquillian.junit.Arquillian;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import org.wildfly.swarm.it.AbstractIntegrationTest;

import static org.fest.assertions.Assertions.assertThat;

/**
 * @author Ken Finnigan
 */
@RunWith(Arquillian.class)
public class SpringDataApplicationIT extends AbstractIntegrationTest {

    @Drone
    WebDriver browser;

    @Test
    public void testEmployees() {
        browser.navigate().to("http://localhost:8080/employee");
        assertThat(browser.getPageSource()).contains("Priya");
    }
}

Create a test for Spring Data

Create a test for Spring Data


package at.ac.tuwien.inso.method_security_tests;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import at.ac.tuwien.inso.entity.Student;
import at.ac.tuwien.inso.entity.UisUser;
import at.ac.tuwien.inso.service.UserCreationService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@SpringBootTest
@ActiveProfiles("test")
@Transactional
public class UserCreationServiceSecurityTests {

    @Autowired
    private UserCreationService userCreationService;

    private UisUser user = new Student("student1", "student", "student@student.com");

    @Test(expected = AuthenticationCredentialsNotFoundException.class)
    public void createNotAuthenticated() {
        userCreationService.create(user);
    }

    @Test(expected = AccessDeniedException.class)
    @WithMockUser(roles = "STUDENT")
    public void createAuthenticatedAsStudent() {
        userCreationService.create(user);
    }

    @Test(expected = AccessDeniedException.class)
    @WithMockUser(roles = "LECTURER")
    public void createAuthenticatedAsLecturer() {
        userCreationService.create(user);
    }

    @Test(expected = NullPointerException.class)
    @WithMockUser(roles = "ADMIN")
    public void createAuthenticatedAsAdmin() {
        userCreationService.create(user);
    }

}

Add tests for security for UserCreationService


package hello.config.data;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Profile;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import hello.models.Greeting;
import hello.services.GreetingService;

@Component
@Profile({ "default", "test" })
public class InitialDataLoader implements ApplicationListener<ContextRefreshedEvent> {

	private final static Logger log = LoggerFactory.getLogger(InitialDataLoader.class);

	private final static String GREETING = "Hello, %s!";

	@Autowired
	private GreetingService greetingService;

	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {

		if (greetingService.count() > 0) {
			log.info("Database already populated. Skipping data initialization.");
			return;
		}

		Greeting greeting = new Greeting();
		greeting.setTemplate(GREETING);

		greetingService.save(greeting);

		log.info("Added greeting (" + greeting.getId() + "): " + greeting.getTemplate());
	}
}

Add an initial data loader class for default/test.


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

/**
 * Package to test JOrphanUtils methods
 */

package org.apache.jorphan.exec;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import junit.framework.TestCase;

public class TestKeyToolUtils extends TestCase {

    public TestKeyToolUtils() {
        super();
    }

    public TestKeyToolUtils(String arg0) {
        super(arg0);
    }

    /*
     * Check the assumption that a missing executable will generate
     * either an IOException or status which is neither 0 nor 1
     *
     */
    public void testCheckKeytool() throws Exception {
        SystemCommand sc = new SystemCommand(null, null);
        List<String> arguments = new ArrayList<String>();
        arguments.add("xyzqwas"); // should not exist
        try {
            int status = sc.run(arguments);
            if (status == 0 || status ==1) {
                fail("Unexpected status " + status);
            }
            System.out.println("testCheckKeytool:status="+status);
        } catch (IOException e) {
            System.out.println("testCheckKeytool:Exception="+e);
        }
    }
}

Test assumptions regarding keytool check

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

Former-commit-id: f1630236f4ad20b255344b162ec57ca38f01684d


/*
 * JBoss, Home of Professional Open Source
 * Copyright 2007, Red Hat Middleware LLC, and individual contributors
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.jboss.test.util.test.concurrent;

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import org.jboss.util.threadpool.BasicTaskWrapper;
import org.jboss.util.threadpool.BasicThreadPool;
import org.jboss.util.threadpool.RunnableTaskWrapper;
import org.jboss.util.threadpool.Task;
import org.jboss.logging.Logger;
import junit.framework.TestCase;

/**
 * Tests of thread pool with Tasks added to the pool
 *
 * @see org.jboss.util.threadpool.ThreadPool
 * @author Adrian.Brock
 * @author Scott.Stark@jboss.org
 * @version $Revision: 2787 $
 */
public class ThreadPoolInterruptedThreadUnitTestCase extends TestCase
{
   public ThreadPoolInterruptedThreadUnitTestCase(String name)
   {
      super(name);
   }

   public static class TestRunnable implements Runnable
   {
      public CountDownLatch latch = new CountDownLatch(1);
      public void run()
      {
         latch.countDown();
      }
   }

   public void testInterruptedExecute() throws Exception
   {
      BasicThreadPool pool = new BasicThreadPool();
      TestRunnable runnable = new TestRunnable();

      Thread.currentThread().interrupt();
      try
      {
         pool.run(runnable);
      }
      finally
      {
         assertTrue(Thread.interrupted());
      }
      assertTrue(runnable.latch.await(10, TimeUnit.SECONDS));
   }
}

Add a test for scheduling work when the thread is interrupted

git-svn-id: 0b89cb198aff298a3b54656df1faf72b8dabb985@2788 15291643-af16-0410-b526-a589213603f9


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

import com.intellij.lang.ASTNode;
import uk.co.reecedunn.intellij.plugin.xquery.lang.XQueryVersion;
import uk.co.reecedunn.intellij.plugin.xquery.settings.XQueryProjectSettings;
import uk.co.reecedunn.intellij.plugin.xquery.tests.Specification;

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

public class UpdateFacility10ParserTest extends XQuery10ParserTest {
    // region Initialization

    public void initializeSettings(XQueryProjectSettings settings) {
        settings.setImplementation("w3c");
        settings.setXQueryVersion(XQueryVersion.XQUERY_1_0);
        settings.setXQuery10Dialect("w3c/1.0-update");
    }

    // endregion
}

Add an XQuery Update Facility 1.0 parser test class.


package uk.ac.ebi.quickgo.geneproduct.common.document;

/**
 * Enumeration that expresses the possible types of gene products.
 *
 * @author Ricardo Antunes
 */
public enum GeneProductType {
    COMPLEX("complex"),
    PROTEIN("protein"),
    RNA("rna");

    private String name;

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

    public String getName() {
        return name;
    }

    public static GeneProductType typeOf(String name) {
        for (GeneProductType type : GeneProductType.values()) {
            if (type.getName().equalsIgnoreCase(name)) {
                return type;
            }
        }

        throw new IllegalArgumentException("The provided name argument does not map to an existing gene product type");
    }
}

Add enum that enumerates allowable gene product types.


/*
 * (C) Copyright 2016 Hewlett Packard Enterprise Development LP
 *
 * 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 monasca.common.hibernate.db;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;

import org.joda.time.DateTime;

import monasca.common.model.alarm.AlarmNotificationMethodType;

@Entity
@Table(name = "notification_method_type")
public class NotificationMethodTypesDb {
  private static final long serialVersionUID = 106453452028781371L;

  @Id
  @Column(name = "name", length = 20)
  private String name;

  public NotificationMethodTypesDb() {
  }

  public NotificationMethodTypesDb(String name){
    this.name = name;
  }

  public void setName(final String name) {
    this.name = name;
  }

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

}

Add entity for notification_method_type table

Change-Id: I85142882654f65bbf9b47b661484a7d0ccf48ea2
Partially-implements: blueprint notification-engine-plugin
Implements: blueprint Notification Engine Plugin System


/*-
 * Copyright 2016 Diamond Light Source Ltd.
 *
 * 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
 */

package org.eclipse.dawnsci.plotting.api.histogram;

import org.eclipse.dawnsci.plotting.api.histogram.HistoCategory;

/**
 * used to manage colour categories
 */
public interface IHistogramCategory {

	/**
	 *
	 * @return colour category
	 */
	public HistoCategory getCategory();
}

Add interface to more easily create new colour categories through extension points


package org.realityforge.replicant.example.server.service.tyrelll.replicate;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.realityforge.replicant.server.EntityMessage;

/**
 * Provides ordering of EntityMessages so as to ensure their correct processing when retrieved from the database
 * Order changes as they should be processed, so a to make subsequent retrieval and application easier.
 * Ordering is:
 * - Deletions, then updates
 * - Within deletions, order by type, desc, so as to delete in the reverse order from the schema set
 * - Within updates, order by type, as, so as to create in the order from the schema set
 * - Within identical types, order by change time, desc on delete, asc on update.
 */
public final class EntityMessageSorter
  implements Comparator<EntityMessage>
{
  private EntityMessageSorter()
  {
  }

  public static List<EntityMessage> sort( final Collection<EntityMessage> messages )
  {
    final ArrayList<EntityMessage> sortedMessages = new ArrayList<EntityMessage>( messages );
    Collections.sort( sortedMessages, COMPARATOR );
    return sortedMessages;
  }

  public static final EntityMessageSorter COMPARATOR = new EntityMessageSorter();

  @Override
  public int compare( final EntityMessage o1, final EntityMessage o2 )
  {
    if ( o1.isDelete() )
    {
      if ( o2.isUpdate() )
      {
        return -1;
      }
      final int typeComparison = o2.getTypeID() - o1.getTypeID();
      if ( 0 != typeComparison )
      {
        return typeComparison;
      }
      if ( o2.getTimestamp() < o1.getTimestamp() )
      {
        return -1;
      }
      if ( o2.getTimestamp() > o1.getTimestamp() )
      {
        return 1;
      }
      return 0;
    }
    if ( o2.isDelete() )
    {
      return 1;
    }
    final int typeComparison = o1.getTypeID() - o2.getTypeID();
    if ( 0 != typeComparison )
    {
      return typeComparison;
    }
    if ( o1.getTimestamp() < o2.getTimestamp() )
    {
      return -1;
    }
    if ( o1.getTimestamp() > o2.getTimestamp() )
    {
      return 1;
    }
    return 0;
  }
}

Add utility class to sort EntityMessages


package org.hibernate.validator.test.engine.failfast;

import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.validation.constraints.NotNull;

import org.testng.annotations.Test;

import org.hibernate.validator.HibernateValidator;
import org.hibernate.validator.HibernateValidatorConfiguration;
import org.hibernate.validator.HibernateValidatorFactory;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.test.util.TestUtil;

import static org.hibernate.validator.test.util.TestUtil.assertNumberOfViolations;

/**
 * @author Emmanuel Bernard
 * @author Kevin Pollet - SERLI - kevin.pollet@serli.com
 */
public class FailFastTest {
	@Test
	public void testFailFastSetOnValidatorFactory() {
		final HibernateValidatorConfiguration configuration = TestUtil.getConfiguration( HibernateValidator.class );
		final ValidatorFactory factory = configuration.failFast( true ).buildValidatorFactory();

		final Validator validator = factory.getValidator();
		A testInstance = new A();

		Set<ConstraintViolation<A>> constraintViolations = validator.validate( testInstance );
		assertNumberOfViolations( constraintViolations, 1 );
	}

	@Test
	public void testFailFastSetOnValidator() {
		final HibernateValidatorConfiguration configuration = TestUtil.getConfiguration( HibernateValidator.class );
		final ValidatorFactory factory = configuration.buildValidatorFactory();

		final Validator validator =
				factory.unwrap(HibernateValidatorFactory.class)
					.usingHibernateContext()
						.failFast( true )
					.getValidator();
		A testInstance = new A();

		Set<ConstraintViolation<A>> constraintViolations = validator.validate( testInstance );
		assertNumberOfViolations( constraintViolations, 1 );
	}

	class A {
		@NotNull
		String b;

		@NotNull @Email
		String c;
	}
}

Add fail fast unit tests.

HV-381: Add fail fast unit tests.


/*
 * Copyright 2018 B2i Healthcare Pte Ltd, http://b2i.sg
 *
 * 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.b2international.snowowl.snomed.core.domain;

/**
 * Enumerates available export file layouts for reference sets.
 */
public enum Rf2RefSetExportLayout {

	/**
	 * Reference set content for the same type are concatenated into a single file.
	 */
	COMBINED("One file per reference set type"),

	/**
	 * A separate file is created for each reference set.
	 */
	INDIVIDUAL("One file per reference set");

	private String displayLabel;

	private Rf2RefSetExportLayout(final String displayLabel) {
		this.displayLabel = displayLabel;
	}

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

SO-2881: Add enum for defining the RF2 reference set export type


/*
 * Copyright (c) 2015 Inocybe and others.  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
 */

package org.opendaylight.ovsdb.openstack.netvirt.providers.openflow13.services;

import org.junit.Test;

/**
 * Unit test for {@link L2RewriteService}
 */
public class L2RewriteServiceTest {

    @Test
    public void test() {
        // TODO nothing has been done in L2RewriteService class yet.
    }

}

Add JUnit testing for L2RewriteService class.

Change-Id: I902ce652c3edb0857cca697ead04a9ffd475db67
Signed-off-by: Alexis de Talhouët <3f85d13b1d0fb141169e8f22f55d7ee87dcd5f00@inocybe.com>


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

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

import com.cloudera.cdk.morphline.base.PrettyPrinter;

public class PrettyPrinterTest extends Assert {

  @Test
  public void testBasic() throws Exception {
    PrettyPrinter.main(new String[] {"target/test-classes/test-morphlines/grokSyslogNgCisco.conf"});
    PrettyPrinter.main(new String[] {"target/test-classes/test-morphlines/parseComplexConfig.conf"});
  }

}

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

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

import com.cloudera.cdk.morphline.base.PrettyPrinter;

public class PrettyPrinterTest extends Assert {

  @Test
  public void testBasic() throws Exception {
    PrettyPrinter.main(new String[] {"target/test-classes/test-morphlines/grokSyslogNgCisco.conf"});
    PrettyPrinter.main(new String[] {"target/test-classes/test-morphlines/parseComplexConfig.conf"});
    PrettyPrinter.main(new String[0]);
  }

}

CDK-237: Add utility to nicely indent and format a morphline config file


package io.quarkus.test.devconsole;

import org.hamcrest.Matchers;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import io.quarkus.test.QuarkusDevModeTest;
import io.restassured.RestAssured;

/**
 * Note that this test cannot be placed under the relevant {@code -deployment} module because then the DEV UI processor would
 * not be able to locate the template resources correctly.
 */
public class DevConsoleHibernateSearchDisabledTest {

    @RegisterExtension
    static final QuarkusDevModeTest test = new QuarkusDevModeTest()
            .withApplicationRoot((jar) -> jar.addAsResource(
                    new StringAsset("quarkus.datasource.db-kind=h2\n"
                            + "quarkus.datasource.jdbc.url=jdbc:h2:mem:test\n"
                            // Hibernate Search is disabled: the dev console should be empty.
                            + "quarkus.hibernate-search-orm.enabled=false\n"
                            + "quarkus.hibernate-search-orm.elasticsearch.version=7.10\n"),
                    "application.properties")
                    .addClasses(MyIndexedEntity.class));

    @Test
    public void testPages() {
        RestAssured.get("q/dev/io.quarkus.quarkus-hibernate-search-orm-elasticsearch/entity-types")
                .then()
                .statusCode(200)
                .body(Matchers.containsString("No indexed entities were found"));
    }

}

Test the Hibernate Search Dev Console when Hibernate Search is disabled


package fr.tvbarthel.apps.simpleweatherforcast.openweathermap;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import java.io.IOException;
import java.net.MalformedURLException;

import fr.tvbarthel.apps.simpleweatherforcast.utils.SharedPreferenceUtils;
import fr.tvbarthel.apps.simpleweatherforcast.utils.URLUtils;

public class DailyForecastJsonGetter extends AsyncTask<Void, Void, Void> {

	private Context mContext;

	public DailyForecastJsonGetter(Context context) {
		super();
		mContext = context;
	}

	@Override
	protected Void doInBackground(Void... params) {
		String json = getJsonAsString();
		if(json != null) {
			SharedPreferenceUtils.storeWeather(mContext, json);
		}
		Log.d("argonne", json);
		return null;
	}

	private String getJsonAsString() {
		String result = null;
		try {
			//TODO use real location.
			result = URLUtils.getAsString("http://api.openweathermap.org/data/2.5/forecast/daily?lat=35&lon=139&cnt=14&mode=json&APPID=c756ce72a59777bd32a5762e12e74057");
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}
}

Add an async task to get the json.

Add an async task to get the json.


package com.example.sugartest;

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

import com.example.models.Note;
import com.example.models.Tag;

@RunWith(RobolectricTestRunner.class)
@Config(emulateSdk = 18, manifest = "example/src/main/AndroidManifest.xml")
public class NoteTest {
    @Test
    public void simpleNoteTest() throws Exception {
        Note note = new Note(0, "Note", "this is a note", new Tag("tag"));
        assert(note.getTitle().equals("Note"));
    }
}

Add a simple note test to example

Add a simple note test to example


package leetcode.h_index_ii;

public class Solution {
    public int hIndex(int[] citations) {
        if(citations == null || citations.length == 0) return 0;
        int size = citations.length;
        int U = size, L = -1;
        while(L + 1 < U){
            int mid = L + (U - L) / 2;
            if(citations[mid] >= size - mid){
                U = mid;
            }else{
                L = mid;
            }
        }
        return size - U;
    }
}

Add java solution for 275. H-Index II

Add java solution for 275. H-Index II

275. H-Index II: https://leetcode.com/problems/h-index-ii/


/*
 * Copyright (c) 2014, Colorado State University All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer. 2. Redistributions in
 * binary form must reproduce the above copyright notice, this list of
 * conditions and the following disclaimer in the documentation and/or other
 * materials provided with the distribution.
 *
 * This software is provided by the copyright holders and contributors "as is"
 * and any express or implied warranties, including, but not limited to, the
 * implied warranties of merchantability and fitness for a particular purpose
 * are disclaimed. In no event shall the copyright holder or contributors be
 * liable for any direct, indirect, incidental, special, exemplary, or
 * consequential damages (including, but not limited to, procurement of
 * substitute goods or services; loss of use, data, or profits; or business
 * interruption) however caused and on any theory of liability, whether in
 * contract, strict liability, or tort (including negligence or otherwise)
 * arising in any way out of the use of this software, even if advised of the
 * possibility of such damage.
 */

/**
 * Utility classes for parsing FASTA, SAM/BAM, GenBank, and other sequence data
 * formats to be stored in Mendel
 *
 * @author ctolooee
 *
 */
package mendel.parse;

Add parse package for biological files

Add parse package for biological files


package com.codeaffine.home.control.admin.ui.preference.collection;

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

import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.ILabelProvider;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;

import com.codeaffine.home.control.admin.ui.test.DisplayHelper;

public class CollectionPropertyDescriptorTest {

  @Rule
  public final DisplayHelper displayHelper = new DisplayHelper();

  private CollectionPropertyDescriptor descriptor;

  @Before
  public void setUp() {
    descriptor = new CollectionPropertyDescriptor( "id", "displayName" );
  }

  @Test
  public void createPropertyEditor() {
    CellEditor actual = descriptor.createPropertyEditor( displayHelper.createShell() );

    assertThat( actual ).isInstanceOf( CollectionCellEditor.class );
  }

  @Test
  public void getLabelProvider() {
    ILabelProvider labelProvider = descriptor.getLabelProvider();
    String actual = labelProvider.getText( "text" );

    assertThat( actual ).isEmpty();
  }

  @Test( expected = IllegalArgumentException.class )
  public void constructWithNullAsIdArgument() {
    new CollectionPropertyDescriptor( null, "displayName" );
  }

  @Test( expected = IllegalArgumentException.class )
  public void constructWithNullAsDisplayNameArgument() {
    new CollectionPropertyDescriptor( "id", null );
  }

  @Test( expected = IllegalArgumentException.class )
  public void createPropertyEditorWithNullAsParentArgument() {
    descriptor.createPropertyEditor( null );
  }
}

Create test case for CollectionPropertyDescriptor


package us.kbase.workspace.test.workspace;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;

import org.junit.Test;

import us.kbase.common.test.TestCommon;
import us.kbase.workspace.database.Provenance;
import us.kbase.workspace.database.WorkspaceUser;

public class ProvenanceTest {

	//TODO TEST add more tests

	@Test
	public void setAndGetWorkspaceID() throws Exception {
		final Provenance p = new Provenance(new WorkspaceUser("u"));

		p.setWorkspaceID(1L);
		assertThat("incorrect wsid", p.getWorkspaceID(), is(1L));

		p.setWorkspaceID(null);
		assertThat("incorrect wsid", p.getWorkspaceID(), is(nullValue()));
	}

	@Test
	public void failSetWorkspaceID() throws Exception {
		try {
			new Provenance(new WorkspaceUser("u")).setWorkspaceID(0L);
			fail("expected exception");
		} catch (Exception got) {
			TestCommon.assertExceptionCorrect(got,
					new IllegalArgumentException("wsid must be > 0"));
		}
	}

}

Add more tests for setWorkspaceID in provenance


package me.haosdent.cgroup.subsystem;

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

public class TestMemory {

  @Before
  public void setUp() {}

  @After
  public void tearDown() {}

  @Test
  public void testGetStat() {}

  @Test
  public void testGetPhysicalUsage() {}

  @Test
  public void testGetWithSwapUsage() {}

  @Test
  public void testGetMaxPhysicalUsage() {}

  @Test
  public void testGetMaxWithSwapUsage() {}

  @Test
  public void testSetPhysicalUsageLimit() {}

  @Test
  public void testSetWithSwapUsageLimit() {}

  @Test
  public void testGetPhysicalFailCount() {}

  @Test
  public void testGetWithSwapFailCount() {}

  @Test
  public void testClearForceEmpty() {}

  @Test
  public void testSetSwappiness() {}

  @Test
  public void testSetUseHierarchy() {}

  @Test
  public void testSetOomControl() {}
}

Add memory subsystem test class.

Add memory subsystem test class.


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

import com.google.javascript.jscomp.CompilerOptions.J2clPassMode;
import com.google.javascript.jscomp.CompilerOptions.LanguageMode;

public final class J2clIntegrationTest extends IntegrationTestCase {
  public void testStripNoSideEffectsClinit() {
    String source =
        LINE_JOINER.join(
            "class Preconditions {",
            "  static clinit() {",
            "    Preconditions.clinit = function() {};",
            "  }",
            "  static checkNotNull(obj) {",
            "    Preconditions.clinit();",
            "    return obj;",
            "  }",
            "}",
            "class Main {",
            "  static main() {",
            "    var a = Preconditions.checkNotNull(null);",
            "    alert('hello!');",
            "  }",
            "}",
            "Main.main();");
    // TODO(tdeegan): Change to just "alert('hello') when we can determine clinit() is
    // pure and can be stripped.
    test(createCompilerOptions(), source, "function a(){a=function(){}}a();alert('hello!')");
  }

  @Override
  CompilerOptions createCompilerOptions() {
    CompilerOptions options = new CompilerOptions();
    CompilationLevel.ADVANCED_OPTIMIZATIONS.setOptionsForCompilationLevel(options);
    options.setLanguageIn(LanguageMode.ECMASCRIPT6_TYPED);
    options.setLanguageOut(LanguageMode.ECMASCRIPT5);
    options.setJ2clPass(J2clPassMode.ON);
    return options;
  }
}

Add example for unstripped method because of computed side effects.

Add new J2clIntegrationTest

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=135824169


/**
 * Copyright (c) 2014-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.yoga;

import com.facebook.proguard.annotations.DoNotStrip;

@DoNotStrip
public class YogaValue {
  static final YogaValue UNDEFINED = new YogaValue(YogaConstants.UNDEFINED, YogaUnit.UNDEFINED);
  static final YogaValue ZERO = new YogaValue(0, YogaUnit.PIXEL);

  public final float value;
  public final YogaUnit unit;

  public YogaValue(float value, YogaUnit unit) {
    this.value = value;
    this.unit = unit;
  }

  @DoNotStrip
  YogaValue(float value, int unit) {
    this(value, YogaUnit.fromInt(unit));
  }

  @Override
  public boolean equals(Object other) {
    if (other instanceof YogaValue) {
      final YogaValue otherValue = (YogaValue) other;
      return value == otherValue.value && unit == otherValue.unit;
    }
    return false;
  }

  @Override
  public int hashCode() {
    return Float.floatToIntBits(value) + unit.intValue();
  }
}

/**
 * Copyright (c) 2014-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.yoga;

import com.facebook.proguard.annotations.DoNotStrip;

@DoNotStrip
public class YogaValue {
  static final YogaValue UNDEFINED = new YogaValue(YogaConstants.UNDEFINED, YogaUnit.UNDEFINED);
  static final YogaValue ZERO = new YogaValue(0, YogaUnit.PIXEL);

  public final float value;
  public final YogaUnit unit;

  public YogaValue(float value, YogaUnit unit) {
    this.value = value;
    this.unit = unit;
  }

  @DoNotStrip
  YogaValue(float value, int unit) {
    this(value, YogaUnit.fromInt(unit));
  }

  @Override
  public boolean equals(Object other) {
    if (other instanceof YogaValue) {
      final YogaValue otherValue = (YogaValue) other;
      if (unit == otherValue.unit) {
        return unit == YogaUnit.UNDEFINED || Float.compare(value, otherValue.value) == 0;
      }
    }
    return false;
  }

  @Override
  public int hashCode() {
    return Float.floatToIntBits(value) + unit.intValue();
  }
}

Use Float.compare in java equals

Use Float.compare in java equals

Reviewed By: astreet

Differential Revision: D4531805

fbshipit-source-id: 723e15381e9fa39837a4c99f726501eda26af11b


package leetcode.word_search;

import java.util.Stack;

public class Solution {
	private int H, W;
	public static class State{
		int x, y, depth;
		boolean restore;
		public State(int x, int y, int depth){
			this.x = x;
			this.y = y;
			this.depth = depth;
		}
	}
	public boolean dfs(char[][] board, int sx, int sy, char[] chars){
		Stack<State> stack = new Stack<State>();
		stack.push(new State(sx, sy, 0));
		while(!stack.isEmpty()){
			State current = stack.peek();
			if(current.restore){
				board[current.x][current.y] = chars[current.depth];
				stack.pop();
				continue;
			}else{
				current.restore = true;
			}
			int x = current.x;
			int y = current.y;
			int depth = current.depth;
			if(depth + 1 == chars.length) return true;
			board[x][y] = 0;
			int nx, ny;
			nx = x - 1;
			ny = y;
			if(0 <= nx && nx < H && 0 <= ny && ny < W && chars[depth + 1] == board[nx][ny]){
				stack.push(new State(nx, ny, depth + 1));
			}
			nx = x + 1;
			ny = y;
			if(0 <= nx && nx < H && 0 <= ny && ny < W && chars[depth + 1] == board[nx][ny]){
				stack.push(new State(nx, ny, depth + 1));
			}
			nx = x;
			ny = y - 1;
			if(0 <= nx && nx < H && 0 <= ny && ny < W && chars[depth + 1] == board[nx][ny]){
				stack.push(new State(nx, ny, depth + 1));
			}
			nx = x;
			ny = y + 1;
			if(0 <= nx && nx < H && 0 <= ny && ny < W && chars[depth + 1] == board[nx][ny]){
				stack.push(new State(nx, ny, depth + 1));
			}
		}
		return false;
	}

    public boolean exist(char[][] board, String word) {
    	char[] chars = word.toCharArray();
    	char first = chars[0];

    	H = board.length;
    	W = board[0].length;
    	for(int i = 0; i < H; i++){
    		for(int j = 0; j < W; j++){
    			if(board[i][j] == first){
    				if(dfs(board, i, j, chars)){
    					return true;
    				}
    			}
    		}
    	}
    	return false;
    }

    public static void main(String[] args){
    	char[][] board = new char[][]{"aa".toCharArray()};
    	System.err.println(new Solution().exist(board, "aaa"));
    }
}

Add java solution for 79. Word Search

Add java solution for 79. Word Search

79. Word Search: https://leetcode.com/problems/word-search/


package leetcode;

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

/**
 * https://leetcode.com/problems/remove-invalid-parentheses/
 */
public class Problem301 {
    public List<String> removeInvalidParentheses(String s) {
        List<String> result = new ArrayList<>();
        // TODO
        return result;
    }

    public static void main(String[] args) {
        Problem301 prob = new Problem301();
    }
}

Create a skeleton for problem 301

Create a skeleton for problem 301


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

package edu.cwru.sicu_sms;

/**
 * This class is an abstraction for building sub-controller classes to be most likely used by the main {@link Controller} to manage serial connections and other real-time activities pertaining to biomedical signal processing.
 *
 * @since December 3, 2016
 * @author Ted Frohlich <ttf10@case.edu>
 * @author Abby Walker <amw138@case.edu>
 */
abstract class BioSigController {

}

Create abstract biosignal controller class


/*
 *  Copyright 2012 Eric F. Savage, code@efsavage.com
 *
 *   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.ajah.email;

import java.util.logging.Level;

import javax.mail.MessagingException;
import javax.mail.Store;

import lombok.extern.java.Log;

import com.sun.mail.imap.IMAPFolder;

/**
 * Utilities for dealing with Mail
 * @author Eric F. Savage, code@efsavage.com.
 */
@Log
public class MailUtils {

	/**
	 * Closes an {@link IMAPFolder}, logging but ignoring any errors that occur
	 * while doing so.
	 *
	 * @param folder
	 *            The folder to close.
	 */
	public static void safeClose(IMAPFolder folder) {
		if (folder != null && folder.isOpen()) {
			try {
				folder.close(false);
			} catch (MessagingException e) {
				log.log(Level.WARNING, e.getMessage(), e);
			}
		}
	}

	/**
	 * Closes an {@link IMAPFolder}, logging but ignoring any errors that occur
	 * while doing so.
	 *
	 * @param store
	 *            The store to close.
	 */
	public static void safeClose(Store store) {
		if (store != null && store.isConnected()) {
			try {
				store.close();
			} catch (MessagingException e) {
				log.log(Level.WARNING, e.getMessage(), e);
			}
		}
	}

}

Add safeClose for IMAP connection objects


package leetcode.unique_paths;

public class Solution {
	public static int C(int n, int m){
		if(n - m < m) m = n - m;
		long ans = 1;
		for(int i = 1; i <= m; i++){
			ans *= n + 1 - i;
			ans /= i;
		}
		return (int)ans;
	}

    public int uniquePaths(int m, int n) {
    	if(m == 0 || n == 0) return 1;
    	return C(m + n - 2, n - 1);
    }

    public static void main(String[] args){
    	System.err.println(new Solution().uniquePaths(51, 9) + "");
    }
}

Add java solution for 62. Unique Paths

Add java solution for 62. Unique Paths

62. Unique Paths: https://leetcode.com/problems/unique-paths/


package org.dynmap;

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

public class Log {
    protected static final Logger log = Logger.getLogger("Minecraft");
    protected static final String LOG_PREFIX = "[dynmap] ";
    public static boolean verbose = false;
    public static void info(String msg) {
        log.log(Level.INFO, LOG_PREFIX + msg);
    }
    public static void verboseinfo(String msg) {
        if(verbose)
            log.log(Level.INFO, LOG_PREFIX + msg);
    }
    public static void severe(Throwable e) {
        log.log(Level.SEVERE, LOG_PREFIX + "Exception occured: ", e);
    }
    public static void severe(String msg) {
        log.log(Level.SEVERE, LOG_PREFIX + msg);
    }
    public static void severe(String msg, Throwable e) {
        log.log(Level.SEVERE, LOG_PREFIX + msg, e);
    }
    public static void warning(String msg) {
        log.log(Level.WARNING, LOG_PREFIX + msg);
    }
    public static void warning(String msg, Throwable e) {
        log.log(Level.WARNING, LOG_PREFIX + msg, e);
    }
}

package org.dynmap;

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

public class Log {
    protected static Logger log = Logger.getLogger("Minecraft");
    protected static String prefix = "[dynmap] ";
    public static boolean verbose = false;
    public static void setLogger(Logger logger, String pre) {
        log = logger;
        if((pre != null) && (pre.length() > 0))
            prefix = pre + " ";
        else
            prefix = "";
    }
    public static void info(String msg) {
        log.log(Level.INFO, prefix + msg);
    }
    public static void verboseinfo(String msg) {
        if(verbose)
            log.log(Level.INFO, prefix + msg);
    }
    public static void severe(Throwable e) {
        log.log(Level.SEVERE, prefix + "Exception occured: ", e);
    }
    public static void severe(String msg) {
        log.log(Level.SEVERE, prefix + msg);
    }
    public static void severe(String msg, Throwable e) {
        log.log(Level.SEVERE, prefix + msg, e);
    }
    public static void warning(String msg) {
        log.log(Level.WARNING, prefix + msg);
    }
    public static void warning(String msg, Throwable e) {
        log.log(Level.WARNING, prefix + msg, e);
    }
}

Add support for injecting logger to core


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

package tachyon.worker.keyvalue;

import java.io.IOException;

/**
 * Interface of key-value Index.
 */
public interface Index {

  /**
   * Puts a key into the index, associated with an offset into the key-value payload.
   *
   * @param key bytes of key
   * @param offset offset of this key in payload
   * @return true on success, false otherwise
   */
  boolean put(byte[] key, int offset) throws IOException;

  /**
   * Gets the bytes of value given the key
   *
   * @param key bytes of key
   * @param payload the byte array of all key value payload
   * @return bytes of value, or null if not found
   */
  byte[] get(byte[] key, PayloadReader reader) throws IOException ;

  /**
   * @return size of this index in bytes.
   */
  int byteCount();

  /**
   * @return size of this index in bytes.
   */
  int keyCount();

  /**
   * @return byte array of this index.
   */
  byte[] toByteArray();
}

Add interface of KeyValue index

Add interface of KeyValue index