/*
 * Copyright (C) 2017 Joao Paulo Fernandes Ventura, Udi Cohen
 *
 * 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.udinic.accounts_authenticator_example.authentication;

import android.os.Bundle;
import android.support.annotation.NonNull;

import com.google.android.gms.tasks.Continuation;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.GetTokenResult;

import static android.accounts.AccountManager.KEY_ACCOUNT_NAME;
import static android.accounts.AccountManager.KEY_AUTHTOKEN;
import static android.accounts.AccountManager.KEY_PASSWORD;
import static com.google.common.base.Preconditions.checkNotNull;

class SignUpTask implements Continuation<Bundle, Task<Bundle>> {

    private Bundle mAuthData;

    @Override
    public Task<Bundle> then(@NonNull Task<Bundle> task) throws Exception {
        mAuthData = checkNotNull(task.getResult());
        return signUp().continueWithTask(getAuthToken()).continueWith(getResult());
    }

    private Task<AuthResult> signUp() {
        return FirebaseAuth.getInstance().createUserWithEmailAndPassword(
                checkNotNull(mAuthData.getString(KEY_ACCOUNT_NAME)),
                checkNotNull(mAuthData.getString(KEY_PASSWORD))
        );
    }

    private Continuation<AuthResult, Task<GetTokenResult>> getAuthToken() {
        return new Continuation<AuthResult, Task<GetTokenResult>>() {
            @Override
            public Task<GetTokenResult> then(@NonNull Task<AuthResult> task) throws Exception {
                return task.getResult().getUser().getToken(true);
            }
        };
    }

    private Continuation<GetTokenResult, Bundle> getResult() {
        return new Continuation<GetTokenResult, Bundle> () {
            @Override
            public Bundle then(@NonNull Task<GetTokenResult> task) throws Exception {
                mAuthData.putString(KEY_AUTHTOKEN, checkNotNull(task.getResult().getToken()));
                return mAuthData;
            }
        };
    }

}

Create Firebase sign up task

:sparkles: Create Firebase sign up task


package com.bdt.kiradb;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.util.Arrays;
import java.util.Collection;

@RunWith(Parameterized.class)
public class IterableTest {

    private final Integer integer;

    public IterableTest(Integer integer) {
        this.integer = integer;
    }

    @Parameterized.Parameters
    public static Collection<Object[]> theData() {
        Object[][] data = new Object[][]{
                {1}, {2}, {3}, {4}
        };

        return Arrays.asList(data);
    }

    @Test
    public void testMe() {
//        System.out.printf("i: %d\n", integer);
    }

}

Add an example of a JUnit test where JUnit itself iterates over
some user provided set of data.

com.bdt.kiradb.IterableTest

Reference:  http://www.mkyong.com/unittest/junit-4-tutorial-6-parameterized-test/


package problems;

import java.util.Stack;

public class BinaryTreeUpsideDown {

    class TreeNode {
        int val;
        TreeNode left, right;

        public TreeNode(int value) {
            this.val = value;
        }
    }

    public final TreeNode upsideDownBinaryTree(TreeNode root) {
        // recursive solution
        if (root == null || root.left == null)
            return root;

        final TreeNode parent = root.left;
        final TreeNode head = upsideDownBinaryTree(parent);
        parent.left = root.right;
        parent.right = root;
        root.left = root.right = null;
        return head;
    }

    public final TreeNode upsideDownBinaryTree2(TreeNode root) {
        // iterative solution using stack
        Stack<TreeNode> st = new Stack<TreeNode>();
        TreeNode left = root;
        while (left != null) {
            st.push(left);
            left = left.left;
        }
        TreeNode head = st.isEmpty() ? null : st.pop();
        TreeNode parent = head;
        while (st.size() > 0) {
            TreeNode t = st.pop();
            parent.right = t;
            parent.left = t.right;
            t.left = t.right = null;
            parent = t;
        }
        return head;
    }

    void PreorderPrintTree(TreeNode root) {
        if (root == null)
            System.out.print("#,");
        else {
            System.out.print(root.val + ",");
            PreorderPrintTree(root.left);
            PreorderPrintTree(root.right);
        }
    }

    public static void main(String[] args) {
        BinaryTreeUpsideDown ud = new BinaryTreeUpsideDown();

        TreeNode root = ud.new TreeNode(1);
        root.left = ud.new TreeNode(2);
        root.right = ud.new TreeNode(3);
        root.left.left = ud.new TreeNode(4);
        root.left.right = ud.new TreeNode(5);

        TreeNode head = ud.upsideDownBinaryTree2(root);
        ud.PreorderPrintTree(head);
    }
}

Add Binary Tree Upside Down

Add Binary Tree Upside Down


package simple.xml.load;

import java.io.FileOutputStream;
import java.io.StringWriter;

import simple.xml.ValidationTestCase;
import simple.xml.ElementArray;
import simple.xml.Element;
import simple.xml.Attribute;
import simple.xml.Text;
import simple.xml.Root;

public class TextTest extends ValidationTestCase {

   private static final String SOURCE =
   "<test>\n"+
   "   <array>\n"+
   "     <text name='a' version='ONE'>Example 1</text>\r\n"+
   "     <text name='b' version='TWO'>Example 2</text>\r\n"+
   "     <text name='c' version='THREE'>Example 3</text>\r\n"+
   "   </array>\n\r"+
   "</test>";

   @Root(name="test")
   private static class TextList {

      @ElementArray(name="array")
      private TextEntry[] array;
   }

   @Root(name="text")
   private static class TextEntry {

      @Attribute(name="name")
      private String name;

      @Attribute(name="version")
      private Version version;

      @Text
      private String text;
   }

   private enum Version {

      ONE,
      TWO,
      THREE
   }

   private Persister persister;

   public void setUp() throws Exception {
      persister = new Persister();
   }

   public void testText() throws Exception {
      TextList list = persister.read(TextList.class, SOURCE);

      assertEquals(list.array[0].version, Version.ONE);
      assertEquals(list.array[0].name, "a");
      assertEquals(list.array[0].text, "Example 1");
      assertEquals(list.array[1].version, Version.TWO);
      assertEquals(list.array[1].name, "b");
      assertEquals(list.array[1].text, "Example 2");
      assertEquals(list.array[2].version, Version.THREE);
      assertEquals(list.array[2].name, "c");
      assertEquals(list.array[2].text, "Example 3");

      StringWriter buffer = new StringWriter();
      persister.write(list, buffer);
      validate(list, persister);

      list = persister.read(TextList.class, buffer.toString());

      assertEquals(list.array[0].version, Version.ONE);
      assertEquals(list.array[0].name, "a");
      assertEquals(list.array[0].text, "Example 1");
      assertEquals(list.array[1].version, Version.TWO);
      assertEquals(list.array[1].name, "b");
      assertEquals(list.array[1].text, "Example 2");
      assertEquals(list.array[2].version, Version.THREE);
      assertEquals(list.array[2].name, "c");
      assertEquals(list.array[2].text, "Example 3");

      validate(list, persister);
   }
}

Add unit testing for text annotations

Add unit testing for text annotations


/*******************************************************************************
 * Copyright (c) 2017 Eurotech and/or its affiliates 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
 *
 * Contributors:
 *     Eurotech - initial API and implementation
 *******************************************************************************/
package org.eclipse.kapua.service.certificate;

import org.eclipse.kapua.model.KapuaUpdatableEntityPredicates;

public interface CertificatePredicates extends KapuaUpdatableEntityPredicates {

    /**
     * Certificate name
     */
    public static final String NAME = "name";

    public static final String USAGE = "certificateUsages";

    public static final String USAGE_NAME = USAGE + ".name";

}

/*******************************************************************************
 * Copyright (c) 2017 Eurotech and/or its affiliates 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
 *
 * Contributors:
 *     Eurotech - initial API and implementation
 *******************************************************************************/
package org.eclipse.kapua.service.certificate;

import org.eclipse.kapua.model.KapuaUpdatableEntityPredicates;

public interface CertificatePredicates extends KapuaUpdatableEntityPredicates {

    /**
     * Certificate name
     */
    public static final String NAME = "name";

    public static final String USAGE = "certificateUsages";

    public static final String USAGE_NAME = USAGE + ".name";

    public static final String STATUS = "status";

}

Add Status in Certificate Predicates

Add Status in Certificate Predicates

Signed-off-by: Claudio Mezzasalma <acdb73fa11473662b10f45613ec005f8be976786@eurotech.com>


package org.jboss.forge.addons.envers.commands;

import org.jboss.forge.addon.configuration.Configuration;
import org.jboss.forge.addon.configuration.facets.ConfigurationFacet;
import org.jboss.forge.addon.projects.ProjectFactory;
import org.jboss.forge.addon.projects.Projects;
import org.jboss.forge.addon.ui.command.CommandExecutionListener;
import org.jboss.forge.addon.ui.command.UICommand;
import org.jboss.forge.addon.ui.context.UIExecutionContext;
import org.jboss.forge.addon.ui.context.UISelection;
import org.jboss.forge.addon.ui.result.Result;

import javax.inject.Inject;

/**
 * @author Ivan St. Ivanov
 */
public class JpaEntityCreationListener implements CommandExecutionListener
{
   @Override public void preCommandExecuted(UICommand uiCommand, UIExecutionContext uiExecutionContext)
   {

   }

   @Inject
   private ProjectFactory projectFactory;

   @Override public void postCommandExecuted(UICommand uiCommand, UIExecutionContext uiExecutionContext, Result result)
   {
      String commandName = uiCommand
               .getMetadata(uiExecutionContext.getUIContext())
               .getName();
      if (commandName.equals("JPA: New Entity") && projectFactory != null)
      {

         Configuration configuration = Projects
                  .getSelectedProject(projectFactory, uiExecutionContext.getUIContext())
                  .getFacet(ConfigurationFacet.class)
                  .getConfiguration();
         if ((Boolean) configuration.getProperty(Constants.AUTO_AUDIT_CONFIG_ENTRY))
         {
            uiExecutionContext.getUIContext().getSelection();
         }

      }
   }

   @Override public void postCommandFailure(UICommand uiCommand, UIExecutionContext uiExecutionContext,
            Throwable throwable)
   {

   }
}

Add the command listener showcase

Add the command listener showcase


/*
 *  Copyright 2011 Couchbase, 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.
 *  under the License.
 */
package org.couchbase.mock.memcached.protocol;

import java.nio.ByteBuffer;
import org.couchbase.mock.memcached.Item;

/**
 *
 * @author Trond Norbye <trond.norbye@gmail.com>
 */
public class BinaryGetResponse extends BinaryResponse {
    public BinaryGetResponse(BinaryCommand command, ErrorCode error) {
        super(command, error);
    }

    public BinaryGetResponse(BinaryCommand command, Item item) {
        super(create(command, item));
    }

    private static ByteBuffer create(BinaryCommand command, Item item) {
        final ByteBuffer message = BinaryResponse.create(command, ErrorCode.SUCCESS,
                4 /* flags */, 0, item.getValue().length, 0);
        message.putInt(item.getFlags());
        message.put(item.getValue());
        message.rewind();
        return message;
    }

}

/*
 *  Copyright 2011 Couchbase, 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.
 *  under the License.
 */
package org.couchbase.mock.memcached.protocol;

import java.nio.ByteBuffer;
import org.couchbase.mock.memcached.Item;

/**
 *
 * @author Trond Norbye <trond.norbye@gmail.com>
 */
public class BinaryGetResponse extends BinaryResponse {
    public BinaryGetResponse(BinaryCommand command, ErrorCode error) {
        super(command, error);
    }

    public BinaryGetResponse(BinaryCommand command, Item item) {
        super(create(command, item));
    }

    private static ByteBuffer create(BinaryCommand command, Item item) {
        final ByteBuffer message = BinaryResponse.create(command, ErrorCode.SUCCESS,
                4 /* flags */, 0, item.getValue().length, item.getCas());
        message.putInt(item.getFlags());
        message.put(item.getValue());
        message.rewind();
        return message;
    }

}

Return CAS for get operation

Return CAS for get operation

Change-Id: I50d3851dd1954e96c3046e69e507caa6622b6412
Reviewed-on: http://review.couchbase.org/11954
Tested-by: Sergey Avseyev <87f6d5e4fd3644c3c20800cde7fd3ad1569370b3@gmail.com>
Reviewed-by: Trond Norbye <60edd2ef23891a753f231b0c6f161dc634079a93@gmail.com>


package org.jsmpp.util;

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

public class HexUtilTest {

	@Test
	public void testEncode()
	{
		String res = HexUtil.convertStringToHexString("hello world");

		assertEquals("68656c6c6f20776f726c64", res);
	}
}

Add minor unit tests for HexUtil

Add minor unit tests for HexUtil


/*
 * 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.hadoop.contract;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.contract.AbstractFSContract;
import org.apache.hadoop.fs.contract.AbstractFSContractTestBase;
import org.junit.Test;

import java.net.URL;

public class TestTachyonFSContractLoaded extends AbstractFSContractTestBase {

  @Override
  protected AbstractFSContract createContract(Configuration conf) {
    return new TachyonFSContract(conf);
  }

  @Test
  public void testContractWorks() throws Throwable {
    String key = getContract().getConfKey(SUPPORTS_ATOMIC_RENAME);
    assertNotNull("not set: " + key, getContract().getConf().get(key));
    assertFalse("true: " + key, getContract().isSupported(SUPPORTS_ATOMIC_RENAME, false));
  }

  @Test
  public void testContractResourceOnClasspath() throws Throwable {
    URL url = this.getClass().getClassLoader().getResource(TachyonFSContract.CONTRACT_XML);
    assertNotNull("could not find contract resource", url);
  }
}

Add test for contract xml loading.

Add test for contract xml loading.


package com.madisp.bad;

import com.madisp.bad.eval.BadConverter;
import com.madisp.bad.eval.BadScope;
import com.madisp.bad.expr.Expression;
import com.madisp.bad.expr.ExpressionFactory;

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

/**
 * Created with IntelliJ IDEA.
 * User: madis
 * Date: 5/18/13
 * Time: 6:25 PM
 */
public class ConsoleRepl {
	public static void main(String[] args) throws IOException {
		ExpressionFactory factory = new ExpressionFactory();
		BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
		System.out.println("Repl running, type 'exit' to quit.");
		BadScope scope = new BadScope(null, new Object());
		String s;
		while (!(s = getLine(reader)).equals("exit")) {
			if (s.isEmpty()) {
				continue;
			}
			try {
				Expression expr = factory.buildExpression(s);
				System.out.println(BadConverter.string(expr.value(scope)));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private static String getLine(BufferedReader reader) throws IOException {
		System.out.print("> ");
		System.out.flush();
		return reader.readLine().trim();
	}
}

Add plain old Java main class with a script REPL


/*
 * 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 fs.command;

import fs.App;
import fs.Disk;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Leo
 */
public class CopyVirtualToVirtualCommand extends Command{

    public static final String COMMAND = "copyVtoV";

    @Override
    public void execute(String[] args)
    {
        try
        {
            if (args.length != 4)
            {
                reportSyntaxError();
                return;
            }
            String virtualOriginPath = args[1];
            String virtualDestinationPath = args[3];
            App app = App.getInstance();
            Disk disk = app.getDisk();
            disk.copyVirtualToVirtual(virtualOriginPath, virtualDestinationPath);
        }
        catch (Exception ex)
        {
            Logger.getLogger(CopyRealToVirtualCommand.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    protected String getName()
    {
        return COMMAND;
    }

    @Override
    protected String getDescription()
    {
        return "Copies a content from a virtual node to another virtual node of the File System";
    }

    @Override
    protected String getSyntax()
    {
        return getName() + "VirtualOriginPath /to/ VirtualDestinationPath";
    }

}

Copy virtual to virtual command implemented.


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

import java.nio.file.Path;
import java.util.List;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;

class TestProjectTests {

  private final Path projects = Path.of("src/test-project");

  @Nested
  class Empty {

    @Test
    void build(@TempDir Path work) {
      assertThrows(AssertionError.class, () -> new Probe(projects.resolve("empty"), work));
    }
  }

  @Nested
  class MissingModule {

    @Test
    void build(@TempDir Path work) {
      var probe = new Probe(projects.resolve("missing-module"), work);
      assertEquals(1, probe.bach.main(List.of("build")), probe.toString());
      assertLinesMatch(
          List.of(">> INIT >>", ">> build(<empty>)", ">> BUILD >>", "Bach::compile"),
          probe.lines());
      assertLinesMatch(
          List.of(
              "project.modules=[a]",
              "project.requires=[b]",
              "found in library=[]",
              "Missing module(s) are: b",
              "Compilation failed."),
          probe.errors());
    }
  }
}

Build all test projects as part of the integration tests


/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2013 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.undertow.server.security;

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

/**
 * A test case to test the SPNEGO authentication mechanism.
 *
 * @author Darran Lofthouse
 */
public class SpnegoAuthenticationTestCase {

    @BeforeClass
    public static void startServers() {

    }

    @AfterClass
    public static void stopServers() {

    }

    @Test
    public void test() {

    }

}

[UNDERTOW-143] Test for SPNEGO authentication in issolation.

To be continued...


public class QuickSelect
{
    /**
     * @param nums Unsorted array
     * @param k k-th smallest element to return
     * @return k-th smallest element
     */
    public int quickSelect(int[] nums, int k)
    {
        // Boundary check omitted

        int i = 0;
        int j = nums.length-1;

        while (true)
        {
            int pos = partition(nums, i, j);

            if (pos == k-1) return nums[pos];
            else if (pos < k-1) i = pos+1;
            else j = pos-1;
        }
    }

    private int partition(int[] nums, int i, int j)
    {
        int pivot = nums[j];

        int k = j-1;
        while (i <= k)
        {
            if (nums[i] <= pivot) i++;
            else
            {
                swap(nums, i, k);
                k--;
            }
        }

        swap(nums, i, j);
        return i;
    }

    private void swap(int[] nums, int i, int j)
    {
        int t = nums[j];
        nums[j] = nums[i];
        nums[i] = t;
    }
}

Add implementation for quick select

Add implementation for quick select


// Use length variable to help copy an array.
class ACopy {
	public static void main(String args[]) {
		int i;
		int nums1[] = new int[10];
		int nums2[] = new int[10];

		for(i=0; i < nums1.length; i++)
			nums1[i] = i;

		// copy nums1 to nums2
		if(nums2.length == nums1.length)
			for(i = 0; i < nums2.length; i++)
				nums2[i] = nums1[i];

		for(i=0; i < nums2.length; i++)
			System.out.print(nums2[i] + " ");
	}
}


import static de.retest.recheck.ignore.FilterLoader.load;
import static java.nio.file.Paths.get;
import static org.assertj.core.api.Assertions.assertThat;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import de.retest.recheck.review.ignore.io.ErrorHandlingLoader;
import io.github.netmikey.logunit.api.LogCapturer;

class DefaultRecheckIgnoreTest {

	@RegisterExtension
	LogCapturer warningAndErrorLogs = LogCapturer.create() //
			.captureForType( ErrorHandlingLoader.class );

	@Test
	void default_recheck_ignore_should_load_without_exception() throws Exception {
		load( get( getClass().getResource( "default-recheck.ignore" ).toURI() ) ).load();

		// Assert that no error was logged...
		assertThat( warningAndErrorLogs.size() ).isEqualTo( 0 );
	}

}

Add a test that checks that the default-recheck.ignore is not faulty


package com.bert.pixels.models;

/**
 * Possible colors for a pixel
 */
public enum Color {
  /**
   * Red pixels can only more right.
   */
  RED,
  /**
   * Yellow pixels can only more left.
   */
  YELLOW
}

Add enum for pixel colors

[PIXELS] Add enum for pixel colors

Tests:
- none


package seedu.tasklist.model;

import static org.junit.Assert.assertEquals;

import java.util.Date;

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

import seedu.tasklist.commons.exceptions.IllegalValueException;

import seedu.tasklist.model.tag.UniqueTagList;
import seedu.tasklist.model.task.Comment;
import seedu.tasklist.model.task.DeadlineTask;
import seedu.tasklist.model.task.EventTask;
import seedu.tasklist.model.task.FloatingTask;
import seedu.tasklist.model.task.Name;
import seedu.tasklist.model.task.Priority;
import seedu.tasklist.model.task.Status;
import seedu.tasklist.model.task.Task;

public class TaskTest {
    private Task task;
    private TaskTestHelper helper;

    @Before
    public void initialize() {
        helper = new TaskTestHelper();
    }

    @Test
    public void create_FloatingTask_returnsTrue() throws Exception {
        task = helper.createFloatingTask();
        assertEquals(task.getType(), FloatingTask.TYPE);
    }

    @Test
    public void create_EventTask_returnsTrue() throws Exception {
        task = helper.createEventTask();
        assertEquals(task.getType(), EventTask.TYPE);
    }

    @Test
    public void create_DeadlineTask_returnsTrue() throws Exception {
        task = helper.createDeadlineTask();
        assertEquals(task.getType(), DeadlineTask.TYPE);
    }

    class TaskTestHelper {

        /**
         * Creates floating task
         */
        public Task createFloatingTask() throws IllegalValueException {
            return new FloatingTask(new Name("testFloatingTask1"), new Comment("test"),
                                     new Priority("medium"), new Status(), new UniqueTagList());
        }

        /**
         * Creates an event task
         */
        public Task createEventTask() throws IllegalValueException {
            return new EventTask(new Name("testEventTask1"), new Comment("test"),
                                    new Priority("low"), new Status(), new Date(), new Date(), new UniqueTagList());
        }

        /**
         * Creates a deadline task
         */
        public Task createDeadlineTask() throws IllegalValueException {
            return new DeadlineTask(new Name("testDeadlineTask1"), new Comment("test"),
                                    new Priority("high"), new Status(), new Date(), new UniqueTagList());
        }
    }
}

Create TaskTesk.java to test for 3 types of task


// Use commas in a for statement.
class Comma {
	public static void main(String args[]) {
		int i, j;

		for(i=0, j=10; i < j; i++, j--)
			System.out.println("i and j: " + i + " " + j);
	}
}

Use commas in a for statement

Use commas in a for statement


package org.projectodd.nodej;

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

import java.io.IOException;

import org.dynjs.runtime.DynObject;
import org.dynjs.runtime.Types;
import org.junit.Before;
import org.junit.Test;

public class PathTest extends NodejTestSupport {

    @Before
    public void beforeTests() {
        assertThat(eval("path = require('path'); path").getClass()).isEqualTo(DynObject.class);
    }

    @Test
    public void testNormalize() {
        assertThat(eval("path.normalize('/foo/bar//baz/asdf/quux/..')")).isEqualTo("/foo/bar/baz/asdf");
    }

    @Test
    public void testJoin() {
        assertThat(eval("path.join('/foo', 'bar', 'baz/asdf', 'quux', '..')")).isEqualTo("/foo/bar/baz/asdf");
        assertThat(eval("path.join('foo', {}, 'bar')")).isEqualTo("foo/bar");
    }

    @Test
    public void testResolve() {
        assertThat(eval("path.resolve('/foo/bar', './baz')")).isEqualTo("/foo/bar/baz");
    }

    @Test
    public void testRelative() {
        assertThat(eval("path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb')")).isEqualTo("../../impl/bbb");
    }

    @Test
    public void testDirname() {
        assertThat(eval("path.dirname('/foo/bar/baz/asdf/quux')")).isEqualTo("/foo/bar/baz/asdf");
    }

    @Test
    public void testBasename() {
        assertThat(eval("path.basename('/foo/bar/baz/asdf/quux.html')")).isEqualTo("quux.html");
        // TODO: Not clear why this is failing
//        assertThat(eval("path.basename('/foo/bar/baz/asdf/quux.html', '.html')")).isEqualTo("quux");
    }

    @Test
    public void testExtname() {
        assertThat(eval("path.extname('index.html')")).isEqualTo(".html");
    }

    @Test
    public void testPathSep() {
        assertThat(eval("path.sep")).isEqualTo(System.getProperty("file.separator"));
    }
}

Add tests for node.js require('path')

Add tests for node.js require('path')


package tc.oc.projectares.api;

import javax.annotation.Nullable;

public class PlayerManager {
    public static @Nullable Player getPlayer(org.bukkit.entity.Player bukkit) {
        throw new UnsupportedOperationException();
    }
}

Add an example of a static method that would need to be overwritten using reflection.


package org.realityforge.gwt.appcache.server.mgwt;

import org.realityforge.gwt.appcache.server.propertyprovider.UserAgentPropertyProvider;

public class MgwtManifestServlet
  extends AbstractMgwtManifestServlet
{
  public MgwtManifestServlet()
  {
    addPropertyProvider( new MgwtOsPropertyProvider() );
    addPropertyProvider( new UserAgentPropertyProvider() );
    addPropertyProvider( new MobileUserAgentProvider() );
  }
}

Add a concrete mgwt servlet

Add a concrete mgwt servlet


package org.jdesktop.swingx.painter;

import org.jdesktop.beans.AbstractBeanInfoTest;

public class AlphaPainterBeanInfoTest extends AbstractBeanInfoTest<AlphaPainter<Object>> {
    /**
     * {@inheritDoc}
     */
    @Override
    protected AlphaPainter<Object> createInstance() {
        return new AlphaPainter<Object>();
    }
}

Add bean test for AlphaPainter.

Add bean test for AlphaPainter.


/**
 * Copyright 2012 55 Minutes (http://www.55minutes.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 fiftyfive.wicket.js.locator;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

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

/**
 * Helper class that parses JavaScript files for special
 * Sprockets comments
 * like these:
 *

 * //= require library_name
 * //= require ./file_name

 *

 * Note that paths can also be surrounded by quotes, but they are completely optional:
 *

 * //= require "library_name"
 * //= require "./file_name"

 *
 * @since 4.0
 */
public class SprocketsParserImplV4 implements SprocketsParser
{
    private static final Logger LOGGER = LoggerFactory.getLogger(
        SprocketsParserImplV4.class
    );

    static final Pattern REQ = Pattern.compile("^\\s*//=\\s*require\\s+(\\S.*\\S)\\s*$");

    public List<Sprocket> parseSprockets(BufferedReader javascript)
        throws IOException
    {
        List<Sprocket> sprockets = new ArrayList<Sprocket>();

        while(true)
        {
            String line = javascript.readLine();
            if(null == line) break;

            Matcher require = REQ.matcher(line);
            if(!require.find()) continue;

            String path = stripQuotes(require.group(1));
            boolean isLibrary = !(path.startsWith("./") || path.startsWith("../"));
            sprockets.add(new Sprocket(isLibrary, path));
        }
        return sprockets;
    }

    private String stripQuotes(String path)
    {
        String[] quotes = new String[] { "\"", "'" };
        for(String q : quotes)
        {
            if(path.startsWith(q) && path.endsWith(q))
            {
                path = path.substring(1, path.length() - 1);
                break;
            }
        }
        return path;
    }
}

Introduce parse logic for new sprockets syntax

Previously we used `<>` and `""` to differentiate library references and local paths, respectively, in sprockets `//= require` declarations. Taking a cue from the latest version of sprockets, change this syntax such that `//= require` implies a library reference, unless the path starts with `./` or `../`.


/*
 * #%L
 * SciJava Common shared library for SciJava software.
 * %%
 * Copyright (C) 2009 - 2015 Board of Regents of the University of
 * Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck
 * Institute of Molecular Cell Biology and Genetics.
 * %%
 * 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 HOLDERS 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.
 * #L%
 */

package org.scijava.io;

import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;

/**
 * {@link Location} backed by a {@link URL}.
 *
 * @author Curtis Rueden
 */
public class URLLocation extends AbstractLocation {

	/** The URL backing this location. */
	private final URL url;

	public URLLocation(final URL url) {
		this.url = url;
	}

	// -- URLLocation methods --

	/** Gets the associated {@link URL}. */
	public URL getURL() {
		return url;
	}

	// -- Location methods --

	/**
	 * Gets the associated {@link URI}, or null if this URL is not formatted
	 * strictly according to to RFC2396 and cannot be converted to a URI.
	 */
	@Override
	public URI getURI() {
		try {
			return getURL().toURI();
		}
		catch (final URISyntaxException exc) {
			return null;
		}
	}

}

Add a location type backed by a remote URL


package ch.hevs.aislab.magpie.broker.repository;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import ch.hevs.aislab.magpie.broker.model.MobileClient;

@Repository
public interface MobileClientRepo extends CrudRepository<MobileClient, Long>{

	MobileClient findByUsername(String username);

}

Add repo for the mobile users

Add repo for the mobile users


package com.example.storm;

import backtype.storm.task.OutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.IRichBolt;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Tuple;
import com.example.Marker;
import java.util.Arrays;
import java.util.Map;

public class MarkerBolt implements IRichBolt {

	private Marker marker;
	private OutputCollector collector;

	@Override
	public void prepare(Map stormConf, TopologyContext topologyContext, OutputCollector outputCollector) {
		collector = outputCollector;
		marker = new Marker();
	}

	@Override
	public void execute(Tuple tuple) {
		Long number = tuple.getLongByField("number");
		String heading = tuple.getStringByField("heading");
		Marker.Attributes bean = marker.mark(number);
		collector.emit(tuple, Arrays.<Object>asList(heading, bean.getIsEven(), bean.getSource()));
		collector.ack(tuple);
	}

	@Override
	public void cleanup() {
	}

	@Override
	public void declareOutputFields(OutputFieldsDeclarer outputFieldsDeclarer) {
		outputFieldsDeclarer.declare(new Fields("heading", "isEven", "source"));
	}

	@Override
	public Map<String, Object> getComponentConfiguration() {
		return null;
	}

}

Simplify demo + bean output fields.

Simplify demo + bean output fields.


package symbolTable.entries;

public class LocalVariableEntry extends AVariableEntry {

    /**
     * LocalVariableEntry Constructor
     *
     * @param name
     * @param scope
     */
    public LocalVariableEntry(String name, int scope) {
        super(name, scope);

    }
}

[symbolTable] Add class to prepresent local variables.


package net.acomputerdog.TerrainEdit.main;

import net.acomputerdog.BlazeLoader.main.Version;
import net.acomputerdog.BlazeLoader.mod.Mod;

public class ModTerrainEdit extends Mod {
    /**
     * Returns ID used to identify this mod internally, even among different versions of the same mod.  Mods should override.
     * --This should never be changed after the mod has been released!--
     *
     * @return Returns the id of the mod.
     */
    @Override
    public String getModId() {
        return "acomputerdog.terrainedit";
    }

    /**
     * Returns the user-friendly name of the mod.  Mods should override.
     * --Can be changed among versions, so this should not be used to ID mods!--
     *
     * @return Returns user-friendly name of the mod.
     */
    @Override
    public String getModName() {
        return "Terrain Edit";
    }

    /**
     * Gets the version of the mod as an integer for choosing the newer version.
     *
     * @return Return the version of the mod as an integer.
     */
    @Override
    public int getIntModVersion() {
        return 0;
    }

    /**
     * Gets the version of the mod as a String for display.
     *
     * @return Returns the version of the mod as an integer.
     */
    @Override
    public String getStringModVersion() {
        return "0.0";
    }

    /**
     * Returns true if this mod is compatible with the installed version of BlazeLoader.  This should be checked using Version.class.
     * -Called before mod is loaded!  Do not depend on Mod.load()!-
     *
     * @return Returns true if the mod is compatible with the installed version of BlazeLoader.
     */
    @Override
    public boolean isCompatibleWithBLVersion() {
        if(Version.getMinecraftVersion().equals("1.6.4") && Version.getGlobalVersion() == 0 && Version.getApiVersion() <= 2){
            return true;
        }else{
            System.out.println("TerrainEdit - Incorrect version, aborting launch!");
            return false;
        }
    }

    /**
     * Gets a user-friendly description of the mod.
     *
     * @return Return a String representing a user-friendly version of the mod.
     */
    @Override
    public String getModDescription() {
        return "A command-line terrain editor";
    }

    /**
     * Called when mod is loaded.  Called before game is loaded.
     */
    @Override
    public void load() {
        super.load();
    }

    /**
     * Called when mod is started.  Game is fully loaded and can be interacted with.
     */
    @Override
    public void start() {
        super.start();
    }

    /**
     * Called when mod is stopped.  Game is about to begin shutting down, so mod should release system resources, close streams, etc.
     */
    @Override
    public void stop() {
        super.stop();
    }
}

Correct method description in Mod

Correct method description in Mod


package leetcode.number_of_1_bits;

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        n = n - ((n >> 1) & 0x55555555);
        n = (n & 0x33333333) + ((n >> 2) & 0x33333333);
        return (((n + (n >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;
    }

    public static void main(String[] args){
        System.err.println(new Solution().hammingWeight(-1));
    }
}

Add java solution for 191. Number of 1 Bits

191. Number of 1 Bits: https://leetcode.com/problems/number-of-1-bits/


package org.gozer.services;

import org.junit.Test;
import org.kevoree.kcl.KevoreeJarClassLoader;
import org.kevoree.resolver.MavenResolver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.net.MalformedURLException;
import java.util.Arrays;

public class KCLTest {

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

    @Test
    public void should_load_classe() throws MalformedURLException, IllegalAccessException, InstantiationException, NoSuchMethodException {
        KevoreeJarClassLoader kclScope1 = new KevoreeJarClassLoader();
        kclScope1.isolateFromSystem();

        KevoreeJarClassLoader kclScope = new KevoreeJarClassLoader();

        MavenResolver resolver = new MavenResolver();
        resolver.setBasePath("target/repository");

        File dependencyPath = resolver.resolve("mvn:org.springframework:spring-core:3.2.4.RELEASE:jar", Arrays.asList("http://repo1.maven.org/maven2"));

        kclScope.addJarFromURL(dependencyPath.toURI().toURL());
        LOGGER.info("deploiement jar path : {}", dependencyPath.toURI().toURL());
        kclScope1.addChild(kclScope);

        Class cl1 = kclScope.loadClass("org.springframework.core.io.Resource");
        Object objOfCl1 = cl1.newInstance();

//        KevoreeJarClassLoader kclScope2 = new KevoreeJarClassLoader();
//
//        //can be call dynamicallly at anytime
//        //removeChild also available
//        kclScope2.addChild(kclScope1);
//
//        Class clMain = kclScope2.loadClass("yourMain");
//        //slf4j classes will be resolved transitively
//        clMain.getMethod("main").invoke();
    }
}

Add an unit test to have simple example of KCL


package us.crast.mondochest;

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

import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;

public class DirectionalStrings {
	private static Map<String, BlockFace> dirs = new HashMap<String, BlockFace>();

	public static Block parseDirectional(Block context, String directioninfo) throws MondoMessage {
		String[] directional = directioninfo.split(" ");
		if ((directional.length % 2) != 0) {
			throw new MondoMessage("Directional info specification is invalid");
		}
		for (int i = 0; i < directional.length; i+=2) {
			BlockFace desired_face = dirs.get(directional[i].toUpperCase());
			if (desired_face == null) {
				throw new MondoMessage(String.format("Direction must be one of up/down/north/south/east/west, got '{0}'", directional[i]));
			}
			int distance = Integer.parseInt(directional[i+1]);
			if (distance < 0) {
				distance = -distance;
				desired_face = desired_face.getOppositeFace();
			}
			context = context.getRelative(desired_face, distance);
		}
		return context;
	}

	static {
		dirs.put("UP", BlockFace.UP);
		dirs.put("DOWN", BlockFace.DOWN);
		dirs.put("EAST", BlockFace.EAST);
		dirs.put("WEST", BlockFace.WEST);
		dirs.put("NORTH", BlockFace.NORTH);
		dirs.put("SOUTH", BlockFace.SOUTH);
	}
}

Add in support for parsing directional strings like 'up 7 east 12'


package jenkins.plugins.git;

import hudson.model.Item;
import hudson.model.TopLevelItem;
import hudson.plugins.git.GitStatus;
import jenkins.scm.api.SCMSource;
import jenkins.scm.api.SCMSourceOwner;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Collections;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

/**
 * @author Robin Müller
 */
public class GitSCMSourceTest {

    public static final String REMOTE = "git@remote:test/project.git";

    @Rule
    public JenkinsRule jenkins = new JenkinsRule();

    private GitStatus gitStatus;

    @Before
    public void setup() {
        gitStatus = new GitStatus();
    }

    @Test
    public void testSourceOwnerTriggeredByDoNotifyCommit() throws ServletException, IOException {
        GitSCMSource gitSCMSource = new GitSCMSource("id", REMOTE, "", "*", "", false);
        GitSCMSourceOwner scmSourceOwner = setupGitSCMSourceOwner(gitSCMSource);
        jenkins.getInstance().add(scmSourceOwner, "gitSourceOwner");

        gitStatus.doNotifyCommit(mock(HttpServletRequest.class), REMOTE, "master", "");

        verify(scmSourceOwner).onSCMSourceUpdated(gitSCMSource);
    }

    private GitSCMSourceOwner setupGitSCMSourceOwner(GitSCMSource gitSCMSource) {
        GitSCMSourceOwner owner = mock(GitSCMSourceOwner.class);
        when(owner.getSCMSources()).thenReturn(Collections.<SCMSource>singletonList(gitSCMSource));
        when(owner.hasPermission(Item.READ)).thenReturn(true);
        return owner;
    }

    private interface GitSCMSourceOwner extends TopLevelItem, SCMSourceOwner {}
}

Add test of GitStatus.Listener onNotifyCommit method


package com.google.sps.servlets;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Transaction;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthException;
import com.google.firebase.auth.UserRecord;
import com.google.sps.firebase.FirebaseAppManager;
import java.io.IOException;
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// Once class owner submits a TA email, retrieve that user and add them as a TA to the class
@WebServlet("/create-user")
public class CreateUser extends HttpServlet {

  private FirebaseAuth authInstance;

  // Get the current session
  @Override
  public void init(ServletConfig config) throws ServletException {
    try {
      authInstance = FirebaseAuth.getInstance(FirebaseAppManager.getApp());
    } catch (IOException e) {
      throw new ServletException(e);
    }
  }

}

Create servlet for adding user entity.

Create servlet for adding user entity.


/* This file is part of SableCC ( http://sablecc.org ).
 *
 * See the NOTICE file distributed with this work for copyright information.
 *
 * 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 ticket25;

import org.junit.Test;
import org.sablecc.sablecc.automaton.graph.State;
import org.sablecc.sablecc.automaton.graph.Transition;

public class TransitionBug {

    @Test
    public void bug() {

        State<Integer> state = new State<Integer>("state");
        Transition<Integer> transition = new Transition<Integer>(state, state,
                null);

        // Line that causes the bug.
        transition.equals(transition);
    }
}

Add regression test. See ticket:25.

Add regression test. See ticket:25.

Signed-off-by: Etienne M. Gagnon <bf06ec0eb40152cd863534753d026b021022c851@j-meg.com>


package ru.nsu.ccfit.bogush;

import ru.nsu.ccfit.bogush.msg.*;

public class ClientMessageHandler implements MessageHandler {
	private Client client;
	private LoginPayload loginPayload;

	public ClientMessageHandler(Client client) {
		this.client = client;
	}

	@Override
	public void handle(LoginMessage message) {

	}

	@Override
	public void handle(LogoutMessage message) {

	}

	@Override
	public void handle(SuccessMessage message) {

	}

	@Override
	public void handle(ErrorMessage message) {

	}

	@Override
	public void handle(TextMessage message) {

	}

	@Override
	public void handle(UserListMessage message) {

	}

	@Override
	public void handle(Message message) {

	}
}

Add empty client message handler

Add empty client message handler


package com.adsdk.sdk.nativeads;

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

public class NativeViewBinder {
	private Map<String, Integer> textAssetsBidings;
	private Map<String, Integer> imageAssetsBidings;
	private int adLayoutId;

	public NativeViewBinder(int layoutId) {
		adLayoutId = layoutId;
		textAssetsBidings = new HashMap<String, Integer>();
		imageAssetsBidings = new HashMap<String, Integer>();
	}

	public void bindTextAsset(String tag, int id) {
		textAssetsBidings.put(tag, id);
	}

	public void bindImageAsset(String tag, int id) {
		imageAssetsBidings.put(tag, id);
	}

	public int getAdLayoutId() {
		return adLayoutId;
	}

	public int getIdForTextAsset(String tag) {
		Integer result = textAssetsBidings.get(tag);
		if (result != null) {
			return result;
		} else {
			return 0;
		}
	}

	public int getIdForImageAsset(String tag) {
		Integer result = imageAssetsBidings.get(tag);
		if (result != null) {
			return result;
		} else {
			return 0;
		}
	}

	public Set<String> getTextAssetsBindingsKeySet() {
		return textAssetsBidings.keySet();
	}

	public Set<String> getImageAssetsBindingsKeySet() {
		return imageAssetsBidings.keySet();
	}

}

Introduce native ad view binder.

Introduce native ad view binder.


package com.google.sps.data;

import com.google.maps.model.LatLng;
import java.util.TimeZone;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** */
@RunWith(JUnit4.class)
public final class LocationTest {
  Location location = new Location("Los Angeles");
  Location blankLocation = new Location(" ");

  @Test
  public void checkAddressField() {
    String actual = location.getAddress();
    String expected = "Los Angeles";
    Assert.assertEquals(expected, actual);
  }

  @Test
  public void checkFormattedAddressField() {
    String actual = location.getAddressFormatted();
    String expected = "Los Angeles, CA, USA";
    Assert.assertEquals(expected, actual);
  }

  @Test
  public void checkLatitude() {
    Double actual = location.getLat();
    Double expected = 34.05223420;
    Assert.assertEquals(expected, actual);
  }

  @Test
  public void checkLongitude() {
    Double actual = location.getLng();
    Double expected = -118.24368490;
    Assert.assertEquals(expected, actual);
  }

  @Test
  public void checkCoords() {
    LatLng actual = location.getCoords();
    LatLng expected = new LatLng(34.05223420, -118.24368490);
    Assert.assertEquals(expected, actual);
  }

  @Test
  public void checkTimeZoneID() {
    String actual = location.getTimeZoneID();
    String expected = "America/Los_Angeles";
    Assert.assertEquals(expected, actual);
  }

  @Test
  public void checkTimeZone() {
    TimeZone actual = location.getTimeZone();
    TimeZone expected = TimeZone.getTimeZone("America/Los_Angeles");
    Assert.assertEquals(expected, actual);
  }

  @Test
  public void checkBlankAddressField() {
    String actual = blankLocation.getAddress();
    String expected = " ";
    Assert.assertEquals(expected, actual);
  }

  @Test
  public void checkBlankFormattedAddressField() {
    String actual = blankLocation.getAddressFormatted();
    String expected = null;
    Assert.assertEquals(expected, actual);
  }

  @Test
  public void checkBlankLatitude() {
    Double actual = blankLocation.getLat();
    Double expected = 0.0;
    Assert.assertEquals(expected, actual);
  }

  @Test
  public void checkBlankLongitude() {
    Double actual = blankLocation.getLng();
    Double expected = 0.0;
    Assert.assertEquals(expected, actual);
  }

  @Test
  public void checkBlankCoords() {
    LatLng actual = blankLocation.getCoords();
    LatLng expected = null;
    Assert.assertEquals(expected, actual);
  }

  @Test
  public void checkBlankTimeZoneID() {
    String actual = blankLocation.getTimeZoneID();
    String expected = null;
    Assert.assertEquals(expected, actual);
  }

  @Test
  public void checkBlankTimeZone() {
    TimeZone actual = blankLocation.getTimeZone();
    TimeZone expected = null;
    Assert.assertEquals(expected, actual);
  }
}

Add testing for Location class

Add testing for Location class


package org.nwapw.abacus.number;

import java.util.HashMap;

public abstract class externalFunction {

    private HashMap<String, Function> functions;

    public externalFunction(){
        functions=new HashMap<>();
    }

    public boolean hasFunction(Function x){
        return functions.containsKey(x);
    }
    public Function getFunction(String x){
        return functions.get(x);
    }
    public boolean registerFunction(String x, Function y){
        if(!functions.containsKey(x))
            return functions.put(x,y)==null;
        return false;
    }
    public Function functionFor(String x){
        return null;
    }
    public abstract void load();
}

Add an abstact class for external functions


/*
 * Copyright 2010-2011 Ning, Inc.
 *
 * Ning 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 com.ning.billing.entitlement.api.migration;

import org.testng.annotations.Test;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Stage;
import com.ning.billing.entitlement.glue.MockEngineModuleMemory;

public class TestMigrationMemory extends TestMigration {
    @Override
    protected Injector getInjector() {
        return Guice.createInjector(Stage.DEVELOPMENT, new MockEngineModuleMemory());
    }

    @Test(enabled=true, groups="sql")
    public void testSingleBasePlan() {
        invokeRealMethod(this);
    }

    @Test(enabled=true, groups="sql")
    public void testSingleBasePlanFutureCancelled() {
        invokeRealMethod(this);
    }

    @Test(enabled=true, groups="sql")
    public void testSingleBasePlanWithPendingPhase() {
        invokeRealMethod(this);
    }

    @Test(enabled=true, groups="sql")
    public void testSingleBasePlanWithPendingChange() {
        invokeRealMethod(this);
    }
}

Add in memory test for migartion

Add in memory test for migartion


package com.growthbeat.message;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v4.content.AsyncTaskLoader;

public class ImageLoader {

	private final static ImageLoader instance = new ImageLoader();

	private Map<String, AsyncUrlImageLoader> cachedImages = new HashMap<String, AsyncUrlImageLoader>();

	public static ImageLoader getInstance() {
		return ImageLoader.instance;
	}

	public AsyncUrlImageLoader generateLoader(Context context, String url) {

		AsyncUrlImageLoader asyncUrlImageLoader = cachedImages.get(url);
		if (asyncUrlImageLoader == null) {
			asyncUrlImageLoader = new AsyncUrlImageLoader(context, url);
			cachedImages.put(url, asyncUrlImageLoader);
		}

		return asyncUrlImageLoader;

	}

	public static class AsyncUrlImageLoader extends AsyncTaskLoader<Bitmap> {

		private String url;
		private Bitmap bitmap;

		public AsyncUrlImageLoader(Context context, String url) {
			super(context);
			this.url = url;
		}

		@Override
		public Bitmap loadInBackground() {

			try {
				URL url = new URL(this.url);
				HttpURLConnection connection = (HttpURLConnection) url.openConnection();
				connection.setDoInput(true);
				connection.connect();
				this.bitmap = BitmapFactory.decodeStream(connection.getInputStream());
				return bitmap;
			} catch (IOException e) {
			}

			return null;
		}

		@Override
		public void onCanceled(Bitmap bitmap) {
			if (bitmap == null)
				return;
			if (bitmap.isRecycled())
				return;
			this.bitmap = bitmap;
			this.bitmap.isRecycled();
			this.bitmap = null;

		}

		public Bitmap getBitmap() {
			return this.bitmap;
		}

		public boolean needLoad() {
			return this.bitmap == null || (this.bitmap != null && this.bitmap.isRecycled());
		}

	}

}

Create async url load and cache class

Create async url load and cache class


/*
 * Copyright (C) 2017 the original author or authors.
 *
 * This file is part of jBB Application Project.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  You may obtain a copy of the License at
 *        http://www.apache.org/licenses/LICENSE-2.0
 */

package org.jbb.frontend.impl.faq.logic;

import com.google.common.collect.Lists;
import com.google.common.eventbus.Subscribe;
import org.jbb.frontend.impl.faq.dao.FaqCategoryRepository;
import org.jbb.frontend.impl.faq.model.FaqCategoryEntity;
import org.jbb.frontend.impl.faq.model.FaqEntryEntity;
import org.jbb.lib.eventbus.JbbEventBus;
import org.jbb.system.event.DatabaseSettingsChangedEvent;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
public class FaqAutoCreator {

    private final FaqCategoryRepository faqCategoryRepository;

    public FaqAutoCreator(FaqCategoryRepository faqCategoryRepository,
        JbbEventBus jbbEventBus) {
        this.faqCategoryRepository = faqCategoryRepository;
        jbbEventBus.register(this);
    }

    @Subscribe
    @Transactional
    public void buildFaq(DatabaseSettingsChangedEvent e) {
        if (faqIsEmpty()) {
            FaqEntryEntity firstFaqEntry = FaqEntryEntity.builder()
                .question("What is jBB?")
                .answer("jBB is a bulletin board software")
                .position(1)
                .build();

            FaqEntryEntity secondFaqEntry = FaqEntryEntity.builder()
                .question("How can I get support?")
                .answer("Visit https://github.com/jbb-project/jbb")
                .position(2)
                .build();

            FaqCategoryEntity firstCategory = FaqCategoryEntity.builder()
                .name("General")
                .entries(Lists.newArrayList(firstFaqEntry, secondFaqEntry))
                .position(1)
                .build();

            faqCategoryRepository.save(firstCategory);
        }

    }

    private boolean faqIsEmpty() {
        return faqCategoryRepository.count() == 0;
    }
}

Create dummy entries in FAQ after scratch install


package jft.rest;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import org.apache.http.client.fluent.Executor;
import org.apache.http.client.fluent.Request;
import org.apache.http.message.BasicNameValuePair;
import org.testng.Assert;
import org.testng.SkipException;
import org.testng.annotations.Test;

import java.io.IOException;
import java.util.Set;

/**
 * Created by Anna on 14.06.16.
 */
public class RestTests {

    @Test
    public void testCreateIssue() throws IOException {
        Set<Issue> oldIssues= getIssues();
        Issue newIssue = new Issue().withSubject("test subject").withDescription("test description");
        int id = createIssue(newIssue);
        Set<Issue> newIssues= getIssues();
        oldIssues.add(newIssue.withId(id));
        Assert.assertEquals(newIssues, oldIssues);
    }

    private int createIssue(Issue newIssue) throws IOException {
        String json = getExecutor().execute(Request.Post("http://demo.bugify.com/api/issues.json")
                .bodyForm(new BasicNameValuePair("subject", newIssue.getSubject()),
                        new BasicNameValuePair("description", newIssue.getDescription())))
                .returnContent().asString();
        JsonElement parsed = new JsonParser().parse(json);
        return parsed.getAsJsonObject().get("issue_id").getAsInt();
    }

    private Set<Issue> getIssues() throws IOException {
        String json = getExecutor().execute(Request.Get("http://demo.bugify.com/api/issues.json")).returnContent().asString();
        JsonElement parsed = new JsonParser().parse(json);
        JsonElement issues = parsed.getAsJsonObject().get("issues");
        return new Gson().fromJson(issues, new TypeToken<Set<Issue>>(){}.getType());
    }

    private Executor getExecutor(){
        return Executor.newInstance().auth("LSGjeU4yP1X493ud1hNniA==", "");
    }

    public void skipIfNotFixed(int issueId) throws IOException {
        if (isIssueOpen(issueId)) {
            throw new SkipException("Ignored because of issue " + issueId);
        }
    }

    public boolean isIssueOpen(int issueId) throws IOException {

        String json = getExecutor().execute(Request.Get("http://demo.bugify.com/api/issues/" + issueId + ".json"))
                .returnContent().asString();
        JsonElement parsed = new JsonParser().parse(json);
        JsonArray issues = parsed.getAsJsonObject().get("issues").getAsJsonArray();
        String status = issues.get(0).getAsJsonObject().get("state_name").getAsString();
        return (status.equals("Open"));
    }

    @Test
    public void testSkipping() throws IOException {
        skipIfNotFixed(1);
        System.out.println("not skipped");
    }
}

Test for verifying if bug was fixed

Test for verifying if bug was fixed


/**
 *
 */
package com.boundary.sdk;

import java.util.Map;

import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import org.apache.camel.component.syslog.SyslogMessage;

import com.boundary.sdk.Event;

/**
 * @author davidg
 *
 */
public class DebugProcessor implements Processor {

	private boolean debug = false;
	/**
	 *
	 */

	public DebugProcessor() {
		this(false);
	}
	public DebugProcessor(boolean debug) {
		// TODO Auto-generated constructor stub
	}

	@Override
	public void process(Exchange exchange) throws Exception {
        System.out.println("Received message body: " + exchange.getIn().getBody(String.class));
        Message m = exchange.getIn();
        Object o = m.getBody();
        System.out.println("Class: " + o.getClass());
        Map <String,Object> headers = m.getHeaders();
        System.out.println("headers: " + headers);
	}
}

Add processor for debugging messages

Add processor for debugging messages


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

package org.springframework.context.annotation.spr12334;

import org.junit.Test;

import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

/**
 * @author Juergen Hoeller
 * @author Alex Pogrebnyak
 */
public class Spr12334Tests {

	@Test
	public void shouldNotScanTwice() {
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
		context.scan(TestImport.class.getPackage().getName());
		context.refresh();
		context.getBean(TestConfiguration.class);
	}

	@Import(TestImport.class)
	public @interface AnotherImport {
	}

	@Configuration
	@AnotherImport
	public static class TestConfiguration {
	}

	public static class TestImport implements ImportBeanDefinitionRegistrar {

		private boolean scanned = false;

		@Override
		public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry)  {
			if (this.scanned) {
				throw new IllegalStateException("Already scanned");
			}
			this.scanned = true;
		}
	}

}

Test for ImportBeanDefinitionRegistrar double scan

Issue: SPR-12334


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

import org.vertx.java.platform.Verticle;
import org.vertx.java.core.logging.Logger;
import org.vertx.java.core.Handler;
import org.vertx.java.core.AsyncResult;
import org.vertx.java.core.json.JsonObject;

import com.blankstyle.vine.definition.VineDefinition;
import com.blankstyle.vine.context.VineContext;
import com.blankstyle.vine.ReliableSeedVerticle;
import com.blankstyle.vine.Groupings;
import com.blankstyle.vine.Root;
import com.blankstyle.vine.local.LocalRoot;
import com.blankstyle.vine.feeder.Executor;
import com.blankstyle.vine.feeder.BasicExecutor;

/**
 * A process pool example.
 *
 * This example uses a single seed with multiple worker instances to
 * perform RPC on a pool of workers.
 *
 * @author Jordan Halterman
 */
class ProcessPoolVine extends Verticle {

  public static class ProcessPool extends ReliableSeedVerticle {

    @Override
    public void process(JsonObject data) {
      emit(new JsonObject().putNumber("result", data.getInteger("first") * data.getInteger("second")));
      ack(data);
    }

  }

  private Logger logger;

  @Override
  public void start() {
    logger = container.logger();

    VineDefinition vine = new VineDefinition("processpool");
    vine.feed("pool", ProcessPool.class.getName(), 6).groupBy(Groupings.random());

    final Root root = new LocalRoot(vertx, container);
    root.deploy(vine, new Handler<AsyncResult<VineContext>>() {
      @Override
      public void handle(Handler<AsyncResult<VineContext>> result) {
        if (result.succeeded()) {
          final VineContext context = result.result();
          Executor executor = new BasicExecutor(context, vertx);
          executor.execute(new JsonObject().putNumber("first", 10).putNumber("second", 100), new Handler<AsyncResult<JsonObject>>() {
            @Override
            public void handle(AsyncResult<JsonObject> result) {
              if (result.succeeded()) {
                logger.info(String.format("10 * 100 = %d", result.result().getInteger("result")));
              }
              else {
                logger.warning("Failed to execute vine. " + result.cause());
              }
              root.shutdown(context);
            }
          });
        }
      }
    });
  }

}

Add new custom feeder example.

Add new custom feeder example.


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

package com.dmdirc.util.validators;

/**
 * Validates a port number.
 */
public class IntegerPortValidator extends IntegerValidator {

    /**
     * The minimum port number.
     */
    private static final int MIN_PORT = 1;

    /**
     * The maximum port number.
     */
    private static final int MAX_PORT = 65535;

    /**
     * Creates a new port validator.
     */
    public IntegerPortValidator() {
        super(MIN_PORT, MAX_PORT);
    }

}

Add port validator that takes Integer

Add port validator that takes Integer

Change-Id: I4d3d94c3dc60690a958a5b2fc8534c35c1f8b61e
Reviewed-on: http://gerrit.dmdirc.com/3590
Automatic-Compile: DMDirc Build Manager
Reviewed-by: Chris Smith <711c73f64afdce07b7e38039a96d2224209e9a6c@dmdirc.com>


package in.joind.adapter;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;

import in.joind.EventListFragment;
import in.joind.R;

public class EventTypePagerAdapter extends FragmentStatePagerAdapter {
    Context context;

    public EventTypePagerAdapter(FragmentManager fm, Context context) {
        super(fm);
        this.context = context;
    }

    @Override
    public Fragment getItem(int position) {
        Fragment fragment = new EventListFragment();
        Bundle args = new Bundle();
        args.putString(EventListFragment.ARG_LIST_TYPE_KEY, getItemTypeForPosition(position));
        fragment.setArguments(args);

        return fragment;
    }

    @Override
    public int getCount() {
        // Hot, Upcoming, My events, Past
        return 4;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
            default:
                return context.getString(R.string.activityMainEventsHot);
            case 1:
                return context.getString(R.string.activityMainEventsUpcoming);
            case 2:
                return context.getString(R.string.activityMainEventsMyEvent);
            case 3:
                return context.getString(R.string.activityMainEventsPast);
        }
    }

    private String getItemTypeForPosition(int position)
    {
        switch (position) {
            case 0:
            default:
                return EventListFragment.LIST_TYPE_HOT;
            case 1:
                return EventListFragment.LIST_TYPE_UPCOMING;
            case 2:
                return EventListFragment.LIST_TYPE_MY_EVENTS;
            case 3:
                return EventListFragment.LIST_TYPE_PAST;
        }
    }
}

Add adapter class for ViewPager.

Add adapter class for ViewPager.


package com.salesforce.storm.spout.sideline.kafka.failedMsgRetryManagers;

import com.salesforce.storm.spout.sideline.TupleMessageId;

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

/**
 * Never retry failed messages.
 */
public class NoRetryFailedMsgRetryManager implements FailedMsgRetryManager {
    @Override
    public void prepare(Map stormConfig) {
        // Nothing to do
    }

    @Override
    public void failed(TupleMessageId messageId) {
        // Nothing to do
    }

    @Override
    public void acked(TupleMessageId messageId) {
        // Nothing to do
    }

    @Override
    public void retryStarted(TupleMessageId messageId) {
        // Nothing to do
    }

    @Override
    public TupleMessageId nextFailedMessageToRetry() {
        return null;
    }

    @Override
    public boolean shouldReEmitMsg(TupleMessageId messageId) {
        // Never re-emit
        return false;
    }

    @Override
    public boolean retryFurther(Long offset) {
        return false;
    }

    @Override
    public Set<TupleMessageId> clearOffsetsBefore(TupleMessageId messageId) {
        return null;
    }
}

Add FailedMsgRetryManager that never retries failed tuples.


package fr.bouyguestelecom.tv.openapi.secondscreen.httputils;

import android.content.Context;

/**
 * A Http REST client to send request to the BboxAPI. All requests are asynchronous.
 * @author Pierre-Etienne Cherière PCHERIER@bouyguestelecom.fr
 */
public class BboxRestClient extends RestClient {

    private static final String TAG = "BboxRestClient";

    private String BBOX_IP;
    private String URL;
    private String idSessionHeader = null;

    /**
     * The constructor need the IP of the Bbox and the current {@link android.content.Context Context}
     * @param bboxIp
     * @param context
     */
    public BboxRestClient(String bboxIp, Context context) {
        super(context, "http://" + bboxIp + ":8080/api.bbox.lan/v0/", TAG);
        BBOX_IP = bboxIp;
        URL = "http://" + BBOX_IP + ":8080/api.bbox.lan/v0/";
    }

    public String getBboxIP() {
        return BBOX_IP;
    }

    public String getIdSession()
    {
        return idSessionHeader;
    }

    public void setIdSession(String headerName, String headerValue)
    {
        idSessionHeader = headerValue;
        super.setHeader(headerName, headerValue);
    }
}

Add commented method that will be used in next release for
authentication purpose.
Force use of async http 1.4.4 (1.4.6 break usage of headers)

Add a missing file from the previous update


/*
 * Zorbage: an algebraic data hierarchy for use in numeric processing.
 *
 * Copyright (C) 2016-2018 Barry DeZonia
 *
 * 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 HOLDERS 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 nom.bdezonia.zorbage.procedure;

import nom.bdezonia.zorbage.basic.procedure.Procedure1;
import nom.bdezonia.zorbage.type.algebra.Addition;
import nom.bdezonia.zorbage.type.algebra.Group;

/**
 *
 * @author Barry DeZonia
 *
 */
public class Ramp<T extends Group<T,U> & Addition<U>, U> implements Procedure1<U> {

	private T group;
	private U currValue;
	private U delta;

	public Ramp(T group, U startValue, U delta) {
		this.group = group;
		this.currValue = group.construct(startValue);
		this.delta = group.construct(delta);
	}

	@Override
	public void call(U a) {
		// assign curr value to output
		group.assign(currValue, a);
		// setup next value
		group.add(currValue, delta, currValue);
	}
}

Define a ramp procedure for easily filling datasets


package jamex.link;

import java.util.Collection;
import java.util.LinkedList;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import javax.jms.Message;
import javax.jms.MessageListener;
import static org.junit.Assert.*;

final class MessageCollector
  implements MessageListener
{
  private static final int MAX_MESSAGE_COUNT = 10;

  private final LinkedBlockingQueue<Message> m_messages = new LinkedBlockingQueue<Message>( MAX_MESSAGE_COUNT );

  @Override
  public void onMessage( final Message message )
  {
    m_messages.add( message );
  }

  Collection<Message> expectMessageCount( final int expectedMessageCount,
                                          final long maxWait )
    throws InterruptedException
  {
    final LinkedList<Message> results = new LinkedList<Message>();
    final long start = System.currentTimeMillis();
    long now;
    while( results.size() < expectedMessageCount &&
           ( ( now = System.currentTimeMillis() ) < start + maxWait ) )
    {
      final long waitTime = Math.max( 1, start + maxWait - now );
      final Message message = m_messages.poll( waitTime, TimeUnit.MILLISECONDS );
      results.add( message );
    }

    assertEquals( "Expected message count", expectedMessageCount, results.size() );
    return results;
  }
}

Add in class that collects result messages


/*
 * 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-16
 * Site       : https://www.acmicpc.net/problem/1001
 */
public class Boj1001 {

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

}

Solve No.1001 from Baekjoon Online Judge


/*
 * Scala (https://www.scala-lang.org)
 *
 * Copyright EPFL and Lightbend, Inc.
 *
 * Licensed under Apache License 2.0
 * (http://www.apache.org/licenses/LICENSE-2.0).
 *
 * See the NOTICE file distributed with this work for
 * additional information regarding copyright ownership.
 */

package scala.runtime;

import java.lang.invoke.*;

public final class Static {
    private Static() {
    }

    public static CallSite bootstrap(MethodHandles.Lookup lookup, String invokedName, MethodType invokedType, MethodHandle handle, Object... args) throws Throwable {
        Object value = handle.invokeWithArguments(args);
        return new ConstantCallSite(MethodHandles.constant(invokedType.returnType(), value));
    }
}

Add a generic bootstrap method for future use

I plan to use this in place of `SymbolLiteral.bootstrap` and
`StructuralCallSite.bootstrap`.

It will also support future use cases for per-callsite constants
built atop invokedynamic, such as `ClassTag`s or regular expressions.


package io.scif.config;

import static org.junit.Assert.fail;

import io.scif.codec.CompressionType;

import org.junit.Test;

public class SCIFIOConfigTest {

	@Test
	public void testWriterGetCompression() {
		SCIFIOConfig scifioConfig = new SCIFIOConfig();
		// use a invalid string
		if (scifioConfig.writerSetCompression("Invalid") != null) {
			fail(
				"Null expected when using invlalid compressiong value, but not returned");
		}

		for (CompressionType ct : CompressionType.values()) {
			if (scifioConfig.writerSetCompression(ct.getCompression()) == null) {
				fail("An instance of CompressionType is expected, but returned null.");
			}
			if (!scifioConfig.writerGetCompression().equals(ct.getCompression())) {
				fail("Method did not set scifioConfig's non-static field.");
			}
		}
	}

}

Test functionality of writerSetCompression in SCIFIOConfig


/***************************************************************************
 *   Copyright (C) 2008 by Fabrizio Montesi                                *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Library General Public License as       *
 *   published by the Free Software Foundation; either version 2 of the    *
 *   License, or (at your option) 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 General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this program; if not, write to the                 *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 *                                                                         *
 *   For details about the authors of this software, see the AUTHORS file. *
 ***************************************************************************/

package joliex.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import jolie.net.CommMessage;
import jolie.runtime.ByteArray;
import jolie.runtime.FaultException;
import jolie.runtime.JavaService;
import jolie.runtime.Value;

/**
 *
 * @author fmontesi
 */
public class ZipUtils extends JavaService
{
	static private int BUFFER_SIZE = 1024;

	static private ByteArray inputStreamToByteArray( InputStream istream )
		throws IOException
	{
		ByteArrayOutputStream ostream = new ByteArrayOutputStream();
		byte buffer[] = new byte[ BUFFER_SIZE ];
		int read;
		while( (read=istream.read( buffer )) >= 0 ) {
			ostream.write( buffer, 0, read );
		}
		return new ByteArray( ostream.toByteArray() );
	}

	public CommMessage readEntry( CommMessage request )
		throws FaultException
	{
		Value response = Value.create();
		try {
			ZipFile file = new ZipFile(
				request.value().getFirstChild( "filename" ).strValue()
			);
			ZipEntry entry = file.getEntry(
				request.value().getFirstChild( "entry" ).strValue()
			);
			if ( entry != null ) {
				response.setValue(
					inputStreamToByteArray( file.getInputStream( entry ) )
				);
			}
		} catch( IOException e ) {
			throw new FaultException( e );
		}
		return CommMessage.createResponse( request, response );
	}
}

Support for reading ZIP file entries.

Support for reading ZIP file entries.


//@@author A0138848M
package seedu.oneline.model.task;

import static org.junit.Assert.*;

import seedu.oneline.commons.exceptions.IllegalValueException;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

public class TaskTimeTest {

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    private void IllegalValueExceptionThrown(String inputTime, String errorMessage) throws Exception{
        thrown.expect(IllegalValueException.class);
        thrown.expectMessage(errorMessage);
        new TaskTime(inputTime);
    }

    // Tests for invalid time inputs to TaskTime constructor

    /**
     * Invalid equivalence partitions for time: null, empty, other strings
     */

    @Test
    public void constructor_nullTime_assertionThrown() {
        thrown.expect(AssertionError.class);
        try {
            new TaskTime(null);
        } catch (IllegalValueException e){
            // should throw an assertion error instead of an illegal value exception
            assert false;
        }
    }

    @Test
    public void constructor_emptyTime_assertionThrown() throws Exception {
        IllegalValueExceptionThrown("", TaskTime.MESSAGE_TASK_TIME_CONSTRAINTS);
    }

    @Test
    public void constructor_unsupportedTimeFormats_assertionThrown() throws Exception {
        IllegalValueExceptionThrown("day after", TaskTime.MESSAGE_TASK_TIME_CONSTRAINTS);
        IllegalValueExceptionThrown("clearly not a time format", TaskTime.MESSAGE_TASK_TIME_CONSTRAINTS);
        IllegalValueExceptionThrown("Tuesd", TaskTime.MESSAGE_TASK_TIME_CONSTRAINTS);
    }

}

Add initial test cases for tasktime

Add initial test cases for tasktime


// Copyright (c) 2003 Brian Wellington (bwelling@xbill.org)

package org.xbill.DNS;

/**
 * Helper functions for doing serial arithmetic.  These should be used when
 * setting/checking SOA serial numbers.
 *
 * @author Brian Wellington
 */

public final class Serial {

private static final long MAX32 = 0xFFFFFFFFL;

private
Serial() {
}

/**
 * Compares two numbers using serial arithmetic.  The numbers are assumed
 * to be 32 bit unsigned integers stored in longs.
 * @param serial1 The first integer
 * @param serial2 The second integer
 * @return 0 if the 2 numbers are equal, a positive number if serial1 is greater
 * than serial2, and a negative number if serial2 is greater than serial1.
 * @throws IllegalArgumentException serial1 or serial2 is out of range
 */
public static int
compare(long serial1, long serial2) {
	if (serial1 < 0 || serial1 > MAX32)
		throw new IllegalArgumentException(serial1 + " out of range");
	if (serial2 < 0 || serial2 > MAX32)
		throw new IllegalArgumentException(serial2 + " out of range");
	long diff = serial1 - serial2;
	if (diff >= MAX32)
		diff -= (MAX32 + 1);
	else if (diff < -MAX32)
		diff += (MAX32 + 1);
	return (int)diff;
}

/**
 * Increments a serial number.  The number is assumed to be a 32 bit unsigned
 * integer stored in a long.  This basically adds 1 and resets the value to
 * 0 if it is 2^32.
 * @param val The serial number
 * @return The incremented serial number
 * @throws IllegalArgumentException serial is out of range
 */
public static long
increment(long serial) {
	if (serial < 0 || serial > MAX32)
		throw new IllegalArgumentException(serial + " out of range");
	if (serial == MAX32)
		return 0;
	return serial + 1;
}

}

Add a class for doing serial arithmetic.

git-svn-id: fcb33a7ee5ec38b96370833547f088a4e742b712@1097 c76caeb1-94fd-44dd-870f-0c9d92034fc1


/*
 * Copyright 2022 The JSpecify 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.
 */

import org.jspecify.nullness.NullMarked;
import org.jspecify.nullness.Nullable;
import org.jspecify.nullness.NullnessUnspecified;

@NullMarked
interface WildcardBoundWithAnnotations {
  <T> void use(Supplier<? extends T> s, Lib<T> l);

  <T> void useUnspec(Supplier<? extends @NullnessUnspecified T> s, Lib<T> l);

  <T> void useUnionNull(Supplier<? extends @Nullable T> s, Lib<T> l);

  default <T> void x0(Supplier<? extends T> s, Lib<T> l) {
    use(s, l);
    useUnspec(s, l);
    useUnionNull(s, l);
  }

  default <T> void x1(Supplier<? extends @NullnessUnspecified T> s, Lib<T> l) {
    // jspecify_nullness_not_enough_information
    use(s, l);
    // jspecify_nullness_not_enough_information
    useUnspec(s, l);
    useUnionNull(s, l);
  }

  default <T> void x2(Supplier<? extends @Nullable T> s, Lib<T> l) {
    // jspecify_nullness_mismatch
    use(s, l);
    // jspecify_nullness_not_enough_information
    useUnspec(s, l);
    useUnionNull(s, l);
  }

  interface Supplier<T extends @Nullable Object> {}

  interface Lib<T> {}
}

Add a sample inspired by a mis-annotated Guava API that our prototype missed.

https://github.com/google/guava/blob/156694066b5198740a820c6eef723fb86c054343/guava/src/com/google/common/base/FunctionalEquivalence.java#L41

...has `? extends T`, but its caller...

https://github.com/google/guava/blob/156694066b5198740a820c6eef723fb86c054343/guava/src/com/google/common/base/Equivalence.java#L157

...has `? extends @Nullable T`.

That shouldn't be allowed: Both should have `? extends @Nullable T`.

(It's possible that the extra `Lib` parameter in this sample isn't
necessary. I added it while debugging a mistake of mine (specifically, a
missing bound on the type parameter of `Supplier`), and I didn't try
later to remove it.)


import io.ddf.DDF;
import io.ddf.datasource.JDBCDataSourceDescriptor;
import io.ddf.exception.DDFException;
import io.ddf.spark.BaseTest;
import org.junit.Assert;
import org.junit.Test;

import java.net.URISyntaxException;

/**
 * Created by nhanitvn on 11/8/15.
 */
public class DataLoadingTests extends BaseTest {
    @Test
    public void testLoadFromJDBC() throws DDFException, URISyntaxException {
        // load data from a MySQL
        JDBCDataSourceDescriptor desc = new JDBCDataSourceDescriptor("jdbc:mysql://localhost:3306/test", "pauser", "papwd", "mtcars");

        DDF ddf = manager.load(desc);
        Assert.assertTrue(ddf != null);
        Assert.assertEquals(ddf.getNumColumns(), 11);
        Assert.assertEquals(ddf.getNumRows(), 32);
    }
}

Add test for loading from JDBC to SparkDDFManager


package tutorial;

import io.reactors.japi.*;
import java.util.concurrent.*;
import java.util.HashMap;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;

public class event_streams {

}

Create stub for event stream example tests.


/**
 * <License>
 */
package edu.colorado.csdms.wmt.client;

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

import com.google.gwt.junit.client.GWTTestCase;

import edu.colorado.csdms.wmt.client.data.ComponentJSO;

/**
 * Tests for {@link ComponentJSO}. JUnit integration is provided by extending
 * {@link GWTTestCase}.
 *
 * @see http://www.gwtproject.org/doc/latest/DevGuideTesting.html
 * @see http://www.gwtproject.org/doc/latest/tutorial/JUnit.html
 * @see http://blog.danielwellman.com/2008/08/testing-json-parsing-using-javascript-overlay-types-in-gwt-15.html
 * @author Mark Piper (mark.piper@colorado.edu)
 */
public class ComponentJSOTest extends GWTTestCase {

  private ComponentJSO componentJSO;
  private String id;
  private String componentClass;
  private String name;

  /**
   * The module that sources this class. Must be present.
   */
  @Override
  public String getModuleName() {
     return "edu.colorado.csdms.wmt.WMT";
  }

  /**
   * A JSNI method that defines a fixture for the tests. Returns a
   * {@link ComponentJSO} object for testing.
   *
   * @param id
   * @param componentClass
   * @param name
   */
  private native ComponentJSO testComponentJSO(String id, String componentClass,
      String name) /*-{
		return {
			"id" : id,
			"class" : componentClass,
			"name" : name
		}
  }-*/;

  @Before
  @Override
  protected void gwtSetUp() throws Exception {
    id = "child";
    componentClass = "Child";
    name = "Child_0";
    componentJSO = testComponentJSO(id, componentClass, name);
  }

  @After
  @Override
  protected void gwtTearDown() throws Exception {
  }

  @Test
  public void testGetId() {
    assertEquals(id, componentJSO.getId());
  }

  @Test
  public void testGetComponentClass() {
    assertEquals(componentClass, componentJSO.getComponentClass());
  }

  @Test
  public void testGetName() {
    assertEquals(name, componentJSO.getName());
  }
}

Add tests for new methods in ComponentJSO


/*
 * 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-10-01
 * Site       : https://www.acmicpc.net/problem/10809
 */

public class Boj10809 {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String inputs = br.readLine();
        int[] atoz = new int[26];
        for(int i=0; i<atoz.length; i++){
            atoz[i] = -1;
        }
        for(int i=0; i<inputs.length(); i++){
            if(atoz[(int)inputs.charAt(i) - 97] == -1) {
                atoz[(int) inputs.charAt(i) - 97] = i;
            }
        }
        for(int i=0; i<atoz.length; i++){
            System.out.print(atoz[i] + " ");
        }
    }

}

Solve No.10809 from Baekjoon Online Judge


package leetcode.course_schedule_ii;

import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.Set;

public class Solution {
    public int[] findOrder(int numCourses, int[][] prerequisites) {
        Map<Integer, Set<Integer>> mapForward = new HashMap<Integer, Set<Integer>>();
        Map<Integer, Set<Integer>> mapBackward = new HashMap<Integer, Set<Integer>>();
        Set<Integer> allCourses = new HashSet<Integer>();
        int[] ret = new int[numCourses];
        int retIdx = 0;
        for(int i = 0; i < numCourses; i++){
            allCourses.add(i);
        }
        if(prerequisites == null) return new int[]{};
        for(int[] prerequisite : prerequisites){
            if(prerequisite[0] == prerequisite[1]) return new int[]{};
            Set<Integer> s;

            s = mapBackward.get(prerequisite[0]);
            if(s == null){
                s = new HashSet<Integer>();
                mapBackward.put(prerequisite[0], s);
            }
            s.add(prerequisite[1]);

            s = mapForward.get(prerequisite[1]);
            if(s == null){
                s = new HashSet<Integer>();
                mapForward.put(prerequisite[1], s);
            }
            s.add(prerequisite[0]);
        }
        Queue<Integer> queue = new LinkedList<Integer>();
        for(int x : mapForward.keySet()){
            Set<Integer> s = mapBackward.get(x);
            if(s == null || s.size() == 0){
                queue.offer(x);
                allCourses.remove(x);
                ret[retIdx++] = x;
            }
        }
        while(!queue.isEmpty()){
            int x = queue.remove();
            Set<Integer> s = mapForward.get(x);
            if(s != null){
                for(int y : s){
                    Set<Integer> s2 = mapBackward.get(y);
                    s2.remove(x);
                    if(s2.isEmpty()){
                        queue.offer(y);
                        allCourses.remove(y);
                        ret[retIdx++] = y;
                    }
                }
            }
        }
        for(Set<Integer> s : mapBackward.values()){
            if(!s.isEmpty()) return new int[]{};
        }
        for(int x : allCourses){
            ret[retIdx++] = x;
        }
        return ret;
    }
}

Add java solution for 210. Course Schedule II

210. Course Schedule II: https://leetcode.com/problems/course-schedule-ii/


package src.writer;

import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;
import javafx.stage.Window;

import java.io.File;

/**
 * Created by Vladyslav Dovhopol on 3/27/17.
 */
class OutputDirectory {

    /**
     * Choose directory where all reports will be saved.
     * @return Directory. May be NULL if no file has been chosen.
     */
    public File choose() {
        DirectoryChooser directoryChooser = new DirectoryChooser();
        directoryChooser.setTitle("Choose directory where to save reports");

        Window window = new Stage();

        window.centerOnScreen();

        return directoryChooser.showDialog(window);
    }
}

Choose directory where to save reports.

Choose directory where to save reports.