package com.erudika.scoold.utils.avatars;

public enum AvatarFormat {
	Square25,
	Square32,
	Square50,
	Square127,
	Profile,
}

Add enum for each size already use


/**
 * @author Johannes Donath
 */

@Volatile
package org.basinmc.faucet.event;

import org.basinmc.faucet.internal.warn.Volatile;

Mark the entire event API volatile for now as we will probably twiddle its bits a few more times.


package com.proofpoint.log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

public class LoggingWriter extends StringWriter
{
    private final Logger logger;
    private final Type type;

    public enum Type
    {
        DEBUG,
        INFO
    }

    public LoggingWriter(Logger logger, Type type)
    {
        this.logger = logger;
        this.type = type;
    }

    @Override
    public void close() throws IOException
    {
        flush();
        super.close();
    }

    @Override
    public void flush()
    {
        BufferedReader  in = new BufferedReader(new StringReader(getBuffer().toString()));
        for(;;)
        {
            try
            {
                String      line = in.readLine();
                if ( line == null )
                {
                    break;
                }

                switch ( type )
                {
                    default:
                    case DEBUG:
                    {
                        if ( logger.isDebugEnabled() )
                        {
                            logger.debug(line);
                        }
                        break;
                    }

                    case INFO:
                    {
                        if ( logger.isInfoEnabled() )
                        {
                            logger.info(line);
                        }
                        break;
                    }
                }
            }
            catch ( IOException e )
            {
                throw new Error(e); // should never get here
            }
        }

        getBuffer().setLength(0);
    }

    public void printMessage(String message, Object... args) throws IOException
    {
        write(String.format(message, args) + "\n");
    }
}

Revert "no longer needed". Actually used by Bootstrap


package fr.openium.blinkiumandroid;

import org.junit.Test;

import java.util.Arrays;

import fr.openium.blinkiumandroid.utils.ConvertUtils;

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

/**
 * Created by ogoutet on 15/03/2017.
 */

public class ConvertUtilsTest {

    @Test
    public void testAsciiToBinWithSimpleChar(){
        // expect
        byte[] expected = {0,1,1,0,0,0,0,1};
        //when
        byte[] result = ConvertUtils.asciiToBin('a');
        //assert
        assertTrue(Arrays.equals(expected,result));
    }

    @Test
    public void testAsciiToBinNulChar(){
        // expect
        byte[] expected = {0,0,0,0,0,0,0,0};
        //when
        byte[] result = ConvertUtils.asciiToBin(Character.MIN_VALUE);
        //assert
        assertTrue(Arrays.equals(expected,result));
    }

    @Test
    public void testAsciiToBinMaxAsciiChar(){
        // expect
        byte[] expected = {0,1,1,1,1,1,1,1};
        //when
        byte[] result = ConvertUtils.asciiToBin((char)127);
        //assert
        assertTrue(Arrays.equals(expected,result));
    }

    @Test
    public void testAsciiToBinUnhadledChar(){
        // expect
        byte[] expected = {0,1,1,1,1,1,1,1};
        //when
        byte[] result = ConvertUtils.asciiToBin('\u24d4');
        //assert
        assertTrue(Arrays.equals(expected,result));
    }
}

Add of the first tests of the ConvertUtils class


package com.elastisys.scale.cloudpool.api;

import com.google.gson.annotations.SerializedName;

/**
 * Supported cloud pool protocols.
 */
public enum Protocol {
    /** HTTP protocol. */
    @SerializedName("http")
    HTTP("http"),
    /** HTTPS protocol. */
    @SerializedName("https")
    HTTPS("https");

    /** The protocol name to use in URIs. */
    private final String protocolName;

    Protocol(String protocolName) {
        this.protocolName = protocolName;
    }

    /**
     * The protocol name to use in URIs. For example, "http".
     *
     * @return
     */
    public String getProtocolName() {
        return this.protocolName;
    }
}

Add supported protocols enum in api


package com.google.sps.utilities;

import com.google.sps.data.Event;
import com.google.sps.data.User;
import com.google.sps.data.VolunteeringOpportunity;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class EventRanker {
  /**
   * Sorts events based on each event's score.
   * Breaks ties with the event's number of VolunteeringOpportunity
   * requiredSkills that match the user's skills.
   *
   * @param user The user for whom the events are ranked
   * @param unrankedEvents A {@link Set} of events that need to be ranked
   * @return A {@link List} of events that is ranked according to
   * each element's score
   */
  public List<Event> rankEvents(User user, Set<Event> unrankedEvents) {
    return new ArrayList<>();
  }
}

Change event ranker class name


package com.sunny.grokkingalgorithms.fasttrack.treesandgraphs;

import com.sunny.grokkingalgorithms.ctci.c4.util.BinaryTreeNode;
import com.sunny.grokkingalgorithms.ctci.c4.util.TreeUtils;

/**
 * Created by sundas on 6/10/2018.
 */
public class InsertANodeInABST {

  /*
  Insert a node in a binary search tree
   */

  /**
   *
   * @param root
   */
   public static void insertIntoBST(BinaryTreeNode root,int key,BinaryTreeNode parent,boolean leftChild){
     /*
     Essentially find an empty spot and insert it , fullfiling the BST criteria.
      */
     if(root == null){
       BinaryTreeNode node = new BinaryTreeNode();
       node.data = key;
       /*
       We need to know the direction
        */
       if(parent != null){
         if(leftChild){
           parent.left = node;
         }
         else{
           parent.right = node;
         }
       }
       return;
     }
     if(root.data == key){
       return;
     }
     /*
     Go left
      */
     if(key < root.data){
       insertIntoBST(root.left,key,root,true);
     }
     /*
     Go right
      */
     else{
       insertIntoBST(root.right,key,root,false);
     }
   }

  /**
   *
   * @param args
   */
  public static void main(String[] args) {
    BinaryTreeNode root = TreeUtils.createBST();
    TreeUtils.performBfsLevelMarker(root);
    System.out.println("############################");
    insertIntoBST(root, 12, null, false);
    System.out.println("Inserting 12");
    TreeUtils.performBfsLevelMarker(root);
    System.out.println("############################");
    System.out.println("Inorder traversal");
    TreeUtils.inorder(root);
    insertIntoBST(root, 2, null, false);
    System.out.println("Inserting 12");
    TreeUtils.performBfsLevelMarker(root);
    System.out.println("############################");
    System.out.println("Inorder traversal");
    TreeUtils.inorder(root);
    insertIntoBST(root, 8, null, false);
    System.out.println("Inserting 8");
    TreeUtils.performBfsLevelMarker(root);
    System.out.println("############################");
    System.out.println("Inorder traversal");
    TreeUtils.inorder(root);
    insertIntoBST(root, 1, null, false);
    System.out.println("Inserting 1");
    TreeUtils.performBfsLevelMarker(root);
    System.out.println("############################");
    System.out.println("Inorder traversal");
    TreeUtils.inorder(root);
  }

}

Insert into BST recursive , O(N) worst case , O(logn) for balanced BST.


public class Solution {

    public static int countSegments(String s) {

        int spaceCount = 0;

        s += " ";

        for (int i = 1; i < s.length(); i++) {

            if (s.charAt(i) == ' ' && s.charAt(i - 1) != ' ') {
                spaceCount++;
            }

        }

        return spaceCount;

    }

}

Create : 434 Number of Segments in a String


/*
 * Copyright (C) 2014 Klaus Reimer <k@ailis.de>
 * See LICENSE.md for licensing information.
 */

package org.usb4java;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

/**
 * Tests the {@link LibUsbException} class.
 *
 * @author Klaus Reimer (k@ailis.de)
 */
public class LibUsbExceptionTest
{
    /**
     * Tests the constructor with only an error code.
     */
    @Test
    public void testConstructorWithCode()
    {
        final LibUsbException e =
            new LibUsbException(LibUsb.ERROR_INVALID_PARAM);
        assertEquals(LibUsb.ERROR_INVALID_PARAM, e.getErrorCode());
        assertEquals("USB error 2: Invalid parameter", e.getMessage());

    }

    /**
     * Tests the constructor with an error code and a message.
     */
    @Test
    public void testConstructorWithCodeAndMessage()
    {
        final LibUsbException e =
            new LibUsbException("Custom message", LibUsb.ERROR_INVALID_PARAM);
        assertEquals(LibUsb.ERROR_INVALID_PARAM, e.getErrorCode());
        assertEquals("USB error 2: Custom message: Invalid parameter",
            e.getMessage());

    }
}

Add unit test for LibUsbException class.


package seedu.ezdo.model.task;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.reflect.Whitebox;

import seedu.ezdo.model.tag.UniqueTagList;
import seedu.ezdo.model.todo.DueDate;
import seedu.ezdo.model.todo.Name;
import seedu.ezdo.model.todo.Priority;
import seedu.ezdo.model.todo.StartDate;
import seedu.ezdo.model.todo.Task;
import seedu.ezdo.model.todo.UniqueTaskList;
import seedu.ezdo.model.todo.UniqueTaskList.SortCriteria;
//@@author A0139248X
@RunWith(PowerMockRunner.class)
public class UniqueTaskListEnumTest {

    private UniqueTaskList utl = new UniqueTaskList();

    @Test(expected = AssertionError.class)
    @PrepareForTest(SortCriteria.class)
    public void unknownValueShouldThrowException() throws Exception {
        utl.add(new Task(new Name("lol"), new Priority("1"), new StartDate("today"), new DueDate("tomorrow"),
                new UniqueTagList("jesus")));
        utl.add(new Task(new Name("lasdfol"), new Priority("1"), new StartDate("today"), new DueDate("tomorrow"),
                new UniqueTagList("jesus")));

        SortCriteria C = PowerMockito.mock(SortCriteria.class);
        Whitebox.setInternalState(C, "name", "C");
        Whitebox.setInternalState(C, "ordinal", 4);

        PowerMockito.mockStatic(SortCriteria.class);
        PowerMockito.when(SortCriteria.values()).thenReturn(new SortCriteria[]{SortCriteria.NAME, SortCriteria.PRIORITY,
                SortCriteria.DUE_DATE, SortCriteria.START_DATE, C});

        utl.sortTasks(C, true);
    }
}

Create SortCriteria enum test for UniqueTaskList


package uk.ac.edukapp.renderer;

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

import uk.ac.edukapp.model.Widgetprofile;

public class UploadResults {

	private String uploadMessage;
	private Widgetprofile widgetProfile;
	private String widgetFolderPath;
	private List<String> htmlFileList;

	/**
	 * @return the uploadMessage
	 */
	public String getUploadMessage() {
		return uploadMessage;
	}

	/**
	 * @param uploadMessage the uploadMessage to set
	 */
	public void setUploadMessage(String uploadMessage) {
		this.uploadMessage = uploadMessage;
	}

	/**
	 * @return the widgetProfile
	 */
	public Widgetprofile getWidgetProfile() {
		return widgetProfile;
	}

	/**
	 * @param widgetProfile the widgetProfile to set
	 */
	public void setWidgetProfile(Widgetprofile widgetProfile) {
		this.widgetProfile = widgetProfile;
	}

	/**
	 * @return the widgetFolderPath
	 */
	public String getWidgetFolderPath() {
		return widgetFolderPath;
	}

	/**
	 * @param widgetFolderPath the widgetFolderPath to set
	 */
	public void setWidgetFolderPath(String widgetFolderPath) {
		this.widgetFolderPath = widgetFolderPath;
	}

	public void setHTMLFileList ( List<File> inList ) {
		htmlFileList = new ArrayList<String>();
		for ( File f : inList ) {
			htmlFileList.add(f.getName());
		}
	}

	public List<String> getHtmlFileList() {
		return htmlFileList;
	}

}

Return object for the widget creator calls.


package jenkins.bugs;

import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;

import hudson.security.HudsonPrivateSecurityRealm;
import jenkins.model.Jenkins;

public class Jenkins41511Test {

    @BeforeClass
    public static void setUpClass() {
        System.setProperty(Jenkins.class.getName()+".slaveAgentPort", "10000");
        System.setProperty(Jenkins.class.getName()+".slaveAgentPortEnforce", "true");
    }

    @Rule
    public JenkinsRule j = new JenkinsRule();

    @Test
    public void configRoundTrip() throws Exception {
        Jenkins.getInstance().setSecurityRealm(new HudsonPrivateSecurityRealm(true, false, null));
        j.submit(j.createWebClient().goTo("configureSecurity").getFormByName("config"));
    }
}

Add a test showing the problem


package controllers;

import org.ow2.chameleon.wisdom.api.DefaultController;
import org.ow2.chameleon.wisdom.api.annotations.Controller;
import org.ow2.chameleon.wisdom.api.annotations.Route;
import org.ow2.chameleon.wisdom.api.http.HttpMethod;
import org.ow2.chameleon.wisdom.api.http.Result;

@Controller
public class Session extends DefaultController {

    // tag::session[]
    @Route(method= HttpMethod.GET, uri = "/session")
    public Result readSession() {
        String user = session("connected");
        if(user != null) {
            return ok("Hello " + user);
        } else {
            return unauthorized("Oops, you are not connected");
        }
    }
    // end::session[]

    // tag::login[]
    @Route(method= HttpMethod.GET, uri = "/session/login")
    public Result login() {
        String user = session("connected");
        if(user != null) {
            return ok("Already connected");
        } else {
            session("connected", "wisdom");
            return readSession();
        }
    }
    // end::login[]

    // tag::logout[]
    @Route(method= HttpMethod.GET, uri = "/session/logout")
    public Result logout() {
        session().remove("connected");
        return ok("You have been logged out");
    }
    // end::logout[]

    // tag::clear[]
    @Route(method= HttpMethod.GET, uri = "/session/clear")
    public Result clear() {
        session().clear();
        return ok("You have been logged out");
    }
    // end::clear[]

    // tag::flash[]
    @Route(method= HttpMethod.GET, uri = "/session/flash")
    public Result welcome() {
        String message = flash("success");
        if(message == null) {
            message = "Welcome!";
            flash("success", message);
        }
        return ok(message);
    }
    // end::flash[]
}

Add a session controller to support the documentation


package org.apache.velocity.test.misc;

/*
 * Copyright 2006 The Apache Software Foundation.
 *
 * 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.
 */

public class UberspectorTestObject
{
    private String regular;
    private String premium;

    private boolean regularBool;
    private boolean premiumBool;

    private String ambigous;

    /**
     * @return the premium
     */
    public String getpremium()
    {
        return premium;
    }

    /**
     * @param premium the premium to set
     */
    public void setpremium(String premium)
    {
        this.premium = premium;
    }

    /**
     * @return the premiumBool
     */
    public boolean ispremiumBool()
    {
        return premiumBool;
    }

    /**
     * @param premiumBool the premiumBool to set
     */
    public void setpremiumBool(boolean premiumBool)
    {
        this.premiumBool = premiumBool;
    }

    /**
     * @return the regular
     */
    public String getRegular()
    {
        return regular;
    }

    /**
     * @param regular the regular to set
     */
    public void setRegular(String regular)
    {
        this.regular = regular;
    }

    /**
     * @return the regularBool
     */
    public boolean isRegularBool()
    {
        return regularBool;
    }

    /**
     * @param regularBool the regularBool to set
     */
    public void setRegularBool(boolean regularBool)
    {
        this.regularBool = regularBool;
    }

    /**
     * @return the ambigous
     */
    public String getAmbigous()
    {
        return ambigous;
    }

    /**
     * @param ambigous the ambigous to set
     */
    public void setAmbigous(String ambigous)
    {
        this.ambigous = ambigous;
    }

    /**
     * @param ambigous the ambigous to set
     */
    public void setAmbigous(StringBuffer ambigous)
    {
        this.ambigous = ambigous.toString();
    }
}

Test Object for the UberspectorTestCase


/*
 * Copyright (C) 2014  Ohm Data
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (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 Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package c5db.util;

import com.google.common.collect.Iterators;

import java.util.Iterator;

public class C5Iterators {

  /**
   * Lazily advance the passed Iterator the given number of times. A lazy variant of
   * {@link com.google.common.collect.Iterators#advance}
   *
   * @return A new Iterator object representing the given Iterator advanced a specified
   * number of times, calling the given Iterator's next() method when needed.
   */
  public static <T> Iterator<T> advanced(Iterator<T> backingIterator, int numberToAdvance) {
    return new Iterator<T>() {
      private boolean advanced;

      @Override
      public boolean hasNext() {
        lazilyAdvance();
        return backingIterator.hasNext();
      }

      @Override
      public T next() {
        lazilyAdvance();
        return backingIterator.next();
      }

      @Override
      public void remove() {
        lazilyAdvance();
        backingIterator.remove();
      }

      private void lazilyAdvance() {
        if (!advanced) {
          Iterators.advance(backingIterator, numberToAdvance);
          advanced = true;
        }
      }
    };
  }
}

Add a lazy Iterator advance method


/*
 * Copyright (c) 2009 Kathryn Huxtable and Kenneth Orr.
 *
 * This file is part of the SeaGlass Pluggable Look and Feel.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * $Id$
 */
package com.seaglasslookandfeel.state;

import java.awt.Component;
import java.awt.Container;

import javax.swing.JComponent;
import javax.swing.JToolBar;

/**
 * Is the control in a toolbar?
 */
public class ControlInToolBarState extends State {
    public ControlInToolBarState() {
        super("InToolBar");
    }

    public boolean isInState(JComponent c) {
        for (Component comp = (Component) c; comp != null; comp = ((Container) comp).getParent()) {
            if (comp instanceof JToolBar) {
                return true;
            } else if (!(comp instanceof Container)) {
                break;
            }
        }
        return false;
    }
}

Check in state to determine if a control is in a toolbar.


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

import com.github.pedrovgs.linkedlist.ListNode;
import org.junit.Before;
import org.junit.Test;

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

/**
 * @author Pedro Vicente Gómez Sánchez.
 */
public class DeleteListNodeTest {

  private DeleteListNode deleteNode;

  @Before public void setUp() {
    deleteNode = new DeleteListNode();
  }

  @Test(expected = IllegalArgumentException.class) public void shouldNotAcceptNullNodes() {
    deleteNode.delete(null);
  }

  @Test public void shouldNotModifyNodeIfListContainsJustThatNode() {
    ListNode<Integer> head = new ListNode<Integer>(1);

    deleteNode.delete(head);

    assertEquals(head, head);
  }

  @Test public void shouldRemoveListNode() {
    ListNode<Integer> head = new ListNode<Integer>(0);
    ListNode<Integer> n1 = new ListNode<Integer>(1);
    ListNode<Integer> n2 = new ListNode<Integer>(2);
    head.setNext(n1);
    n1.setNext(n2);

    deleteNode.delete(n1);

    assertListContainsElements(new Integer[] { 0, 2 }, head);
  }

  @Test public void shouldRemoveHead() {
    ListNode<Integer> head = new ListNode<Integer>(0);
    ListNode<Integer> n1 = new ListNode<Integer>(1);
    ListNode<Integer> n2 = new ListNode<Integer>(2);
    head.setNext(n1);
    n1.setNext(n2);

    deleteNode.delete(head);

    assertListContainsElements(new Integer[] { 1, 2 }, n1);
  }

  private void assertListContainsElements(Integer[] integers, ListNode<Integer> head) {
    int arrayLength = integers.length;
    ListNode<Integer> currentNode = head;

    int i = 0;
    while (i < arrayLength) {
      assertEquals(integers[i], currentNode.getData());
      currentNode = currentNode.getNext();
      i++;
    }
    assertNull(currentNode);
  }
}

Add some tests to problem 59


/*
 * Copyright  1999-2004 The Apache Software Foundation
 *
 *  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.apache.lenya.cms.publication;

import java.util.List;

/**
 * @version $Id: PublicationHelper.java,v 1.1 2004/08/26 22:18:19 roku Exp $
 */
public final class PublicationHelper {

    private Publication publication;

    public PublicationHelper(Publication publication) {
        this.publication = publication;
    }

    /**
     * Returns all documents of a publication.
     * @param area
     * @return
     * @see Document
     * @see Publication
     */
    public Document[] getAllDocuments(String area, String language) throws DocumentException {
        try {
            List allNodes = getPublication().getSiteTree(area).getNode("/").preOrder();
            Document[] documents = new Document[allNodes.size()-1];

            for(int i=1; i<allNodes.size(); i++) {
                documents[i-1] = DefaultDocumentBuilder.getInstance().createDocument(getPublication(), area,
                        ((SiteTreeNode)allNodes.get(i)).getAbsoluteId(), language);
            }
            return documents;
        } catch(SiteTreeException e) {
            throw new DocumentException("Can not access sitetree to get document ids.", e);
        } catch(DocumentBuildException e) {
            throw new DocumentException("Can not build document from id obtained from sitetree.", e);
        }
    }

    /**
     * @return Returns the publication.
     */
    public Publication getPublication() {
        return publication;
    }
}

Support for getting al docs from a pub via sitetree


import com.messagebird.MessageBirdClient;
import com.messagebird.MessageBirdService;
import com.messagebird.MessageBirdServiceImpl;
import com.messagebird.exceptions.GeneralException;
import com.messagebird.exceptions.UnauthorizedException;
import com.messagebird.objects.conversations.*;

public class ExampleUpdateConversation {

    public static void main(String[] args) {
        if (args.length < 3) {
            System.out.println("Please specify your access key, the ID of a conversation and the status to update the conversation to." +
                    " Example : java -jar <this jar file> test_accesskey test_conversationId archived");
            return;
        }

        // First create your service object
        final MessageBirdService wsr = new MessageBirdServiceImpl(args[0]);

        // Add the service to the client
        final MessageBirdClient messageBirdClient = new MessageBirdClient(wsr);
        final ConversationStatus newStatus = ConversationStatus.forValue(args[2]);
        try {
            final Conversation response = messageBirdClient.updateConversation(args[1], newStatus);
            // Display message response
            System.out.println(response.toString());
        } catch (UnauthorizedException | GeneralException exception) {
            if (exception.getErrors() != null) {
                System.out.println(exception.getErrors().toString());
            }
            exception.printStackTrace();
        }
    }
}

Add example for updating conversation.


package org.apache.camel.component.restlet;

import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.JndiRegistry;
import org.apache.camel.util.jsse.KeyManagersParameters;
import org.apache.camel.util.jsse.KeyStoreParameters;
import org.apache.camel.util.jsse.SSLContextParameters;

import org.junit.Test;

import java.io.File;

/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *

 * http://www.apache.org/licenses/LICENSE-2.0
 *

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
public class RestletProducerSSLTest extends RestletTestSupport {

	public static final String BODY = "some body";

	@Override
	protected JndiRegistry createRegistry() throws Exception {

		SSLContextParameters sslContextParameters = createSSLContext();

		JndiRegistry registry = super.createRegistry();
		registry.bind("mySSLContextParameters", sslContextParameters);

		return registry;
	}

	@Test
	public void testRestletProducerComponentSSL() throws Exception {
		String out = template.requestBody("direct:startWithEndpointSSL", "neco", String.class);
		assertEquals(BODY, out);
	}

	@Override
	protected RouteBuilder createRouteBuilder() throws Exception {
		return new RouteBuilder() {
			@Override
			public void configure() throws Exception {
				from("direct:startWithEndpointSSL").to("restlet:https://localhost:" + portNum + "/?restletMethod=post&sslContextParameters=#mySSLContextParameters");

				from("restlet:https://localhost:" + portNum + "/?restletMethods=post&sslContextParameters=#mySSLContextParameters")
						.process(new Processor() {
							public void process(Exchange exchange) throws Exception {
								exchange.getOut().setBody(BODY);
							}
						});
			}
		};
	}

	protected SSLContextParameters createSSLContext() {
		KeyStoreParameters ksp = new KeyStoreParameters();
		ksp.setResource(new File("src/test/resources/jsse/localhost.ks").getAbsolutePath());
		ksp.setPassword("changeit");

		KeyManagersParameters kmp = new KeyManagersParameters();
		kmp.setKeyPassword("changeit");
		kmp.setKeyStore(ksp);

		SSLContextParameters sslContextParameters = new SSLContextParameters();
		sslContextParameters.setKeyManagers(kmp);

		return sslContextParameters;
	}
}

Test SSL communication on Restlet producer


package uk.ac.ebi.quickgo.annotation.validation;

import javax.validation.ConstraintValidatorContext;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationContextLoader;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;

/**
 * @author Tony Wardell
 * Date: 22/11/2016
 * Time: 09:38
 * Created with IntelliJ IDEA.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MockValidationConfig.class, loader = SpringApplicationContextLoader.class)
@ActiveProfiles(profiles = MockValidationConfig.DB_REF_VALIDATION_SUCCEEDS)
public class ReferenceValuesValidationIT {

    @Autowired
    ReferenceValuesValidation refValidator;
    private ConstraintValidatorContext mockContext;

    @Before
    public void setup(){
        mockContext = mock(ConstraintValidatorContext.class);
    }

    @Test
    public void validationSucceedsIfKnownDb(){
        assertThat(refValidator.isValid(new String[]{"PMID:123456"}, mockContext), is(true));
    }

    @Test
    public void validationSucceedsIfDbNotSpecified(){
        assertThat(refValidator.isValid(new String[]{"123456"}, mockContext), is(true));
    }

    @Test
    public void validationSucceedsIfArgumentListIsNull(){
        assertThat(refValidator.isValid(null, mockContext), is(true));
    }

    @Test
    public void validationFailsIfUnknownDb(){
        assertThat(refValidator.isValid(new String[]{"XXXX:123456"}, mockContext), is(false));
    }

    @Test(expected = IllegalArgumentException.class)
    public void validationFailsIfArgumentListContainsNull(){
       refValidator.isValid(new String[]{null}, mockContext);
    }
}

Test for validation of Reference values for annotation filtering.


package in.co.nebulax.maestro.utils;

public class Subjects {

	public static String[][] subjects = new String[][] {

			// Class 1
			{ "English", "Hindi", "Maths", "E.V.S" },

			// Class 2
			{ "English", "Hindi", "Maths", "E.V.S" },

			// Class 3
			{ "English", "Hindi", "Maths", "E.V.S", "Social Studies" },

			// Class 4
			{ "English", "Hindi", "Maths", "Science", "Social Studies" },

			// Class 5
			{ "English", "Hindi", "Maths", "Science", "Social Studies" },

			// Class 6
			{ "English", "Hindi", "Maths", "Science", "Social Studies",
					"Sanskrit" },

			// Class 7
			{ "English", "Hindi", "Maths", "Science", "Social Studies",
					"Sanskrit" },

			// Class 8
			{ "English", "Hindi", "Maths", "Science", "Social Studies",
					"Sanskrit" },

			// Class 9
			{ "English", "Hindi", "Maths", "Science", "Social Studies",
					"Sanskrit" },

			// Class 10
			{ "English", "Hindi", "Maths", "Science", "Social Studies",
					"Sanskrit" },

			// Class 11
			{ "English", "Hindi", "Maths", "Physics", "Chemistry",
					"Accountancy", "Business Studies", "Political Science",
					"History" },

			// Class 12
			{ "English", "Hindi", "Maths", "Physics", "Chemistry",
					"Accountancy", "Business Studies", "Political Science",
					"History" }, };
}

Add subjects according to class


/**
 * Let's make our magic 8 ball game work repeatedly!
 * Maybe we'll even allow exiting...
 */
package com.comp110.lecture10;

import java.util.Scanner;

public class Magic8BallRedux {

  public static void main(String[] args) {

    System.out.println("Ask me a yes/no question...");
    Scanner keyboard = new Scanner(System.in);
    keyboard.nextLine(); // We don't care what the user asks...

    // Generate a random response value
    double randomNumber = Math.random() * 3.0;
    int response = (int)randomNumber;

    // Depending on the generated value, pick a response
    if (response == 0) {
      System.out.println("Definitely. Yes.");
    } else if (response == 1) {
      System.out.println("Eh, maybe...");
    } else {
      System.out.println("Nope, no way.");
    }

  }

}

Add magic 8 ball demo to lecture 10.


package net.imagej.ops.views;

import org.scijava.ItemIO;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;

import net.imagej.ops.view.ViewOps;
import net.imagej.ops.view.ViewOps.Translate;
import net.imglib2.RandomAccessible;
import net.imglib2.view.MixedTransformView;
import net.imglib2.view.Views;

@Plugin(type = ViewOps.Translate.class, name = ViewOps.Translate.NAME)
public class DefaultTranslate<T> extends
		AbstractView<RandomAccessible<T>, MixedTransformView<T>> implements
		Translate<RandomAccessible<T>, MixedTransformView<T>>{

	@Parameter(type = ItemIO.INPUT)
	private long[] translation;

	@Override
	public MixedTransformView<T> compute(RandomAccessible<T> input) {
		return Views.translate(input, translation);
	}

}

Add default implementation of Translate interface.


package com.github.jmchilton.blend4j.galaxy;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;

public class SslHacking {

  public static void disableCertificateCheck() {
    javax.net.ssl.TrustManager x509 = new javax.net.ssl.X509TrustManager() {
      public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws java.security.cert.CertificateException {
        return;
      }

      public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws java.security.cert.CertificateException {
        return;
      }

      public java.security.cert.X509Certificate[] getAcceptedIssuers() {
        return null;
      }
    };
    SSLContext ctx = null;
    try {
      ctx = SSLContext.getInstance("SSL");
      ctx.init(null, new javax.net.ssl.TrustManager[]{x509}, null);
    } catch (java.security.GeneralSecurityException ex) {
    }

    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid = new HostnameVerifier() {
      public boolean verify(String hostname, SSLSession session) {
        return true;
      }
    };
    // Install the all-trusting host verifier
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
    HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
  }
}

Add utility for hacking disabling SSL checks if required.


package galileo.event;

import java.io.IOException;

import galileo.serialization.SerializationInputStream;
import galileo.serialization.SerializationOutputStream;

/**
 * Encapsulates a raw (byte[] based) event that includes a String representing
 * the event synopsis.  This can be used to essentially 'tag' particular blobs
 * of data without writing specific events.
 *
 * @author malensek
 */
public class EventWithSynopsis implements Event {

    private String synopsis;
    private byte[] data;
    private boolean compress = false;

    public EventWithSynopsis(String synopsis, byte[] data) {
        this.synopsis = synopsis;
        this.data = data;
    }

    /**
     * Enables compression when serializing this event.  When deserializing,
     * this setting has no effect.
     */
    public void enableCompression() {
        this.compress = true;
    }

    /**
     * Disables compression when serializing this event.  This is the default
     * behavior.  When deserializing, this setting has no effect.
     */
    public void disableCompression() {
        this.compress = false;
    }

    @Deserialize
    public EventWithSynopsis(SerializationInputStream in)
    throws IOException {
        this.synopsis = in.readString();
        this.data = in.readCompressableField();
    }

    @Override
    public void serialize(SerializationOutputStream out)
    throws IOException {
        out.writeString(synopsis);
        out.writeCompressableField(data, compress);
    }
}

Add event with String-based synopsis


package org.ccnx.ccn.impl.repo;

import java.io.IOException;

import org.ccnx.ccn.CCNHandle;
import org.ccnx.ccn.impl.CCNFlowControl;
import org.ccnx.ccn.protocol.ContentObject;

/**
 * Special flow controller to write CCN objects to repository internally
 *
 */

public class RepositoryInternalFlowControl extends CCNFlowControl {
	RepositoryStore _repo;

	public RepositoryInternalFlowControl(RepositoryStore repo, CCNHandle handle) throws IOException {
		super(handle);
		_repo = repo;
	}

	/**
	 * Put to the repository instead of ccnd
	 */
	public ContentObject put(ContentObject co) throws IOException {
		try {
			_repo.saveContent(co);
		} catch (RepositoryException e) {
			throw new IOException(e.getMessage());
		}
		return co;
	}

	/**
	 * Don't do waitForPutDrain
	 */
	public void afterClose() throws IOException {};
}

Add new flow controller to allow internal writes to repo


package com.zelory.kace.adressbook.presenter;

import com.zelory.kace.adressbook.data.DataManager;
import com.zelory.kace.adressbook.data.model.AddressBook;
import rx.Observable;
import rx.schedulers.Schedulers;

import javax.swing.*;
import java.io.File;

public class AddressBookPresenter {
    private View view;

    public AddressBookPresenter(View view) {
        this.view = view;
    }

    public void loadAddressBook(File file) {
        view.showLoading();
        DataManager.getInstance()
                .loadAddressBook(file)
                .subscribeOn(Schedulers.io())
                .subscribe(addressBook -> SwingUtilities.invokeLater(() -> {
                    view.showAddressBook(addressBook);
                    view.dismissLoading();
                }), throwable -> SwingUtilities.invokeLater(() -> {
                    view.onError(throwable);
                    view.dismissLoading();
                }));
    }

    public void saveAddressBook(AddressBook addressBook, String path) {
        view.showLoading();
        DataManager.getInstance()
                .save(addressBook, path)
                .subscribeOn(Schedulers.io())
                .subscribe(savedAddressBook -> SwingUtilities.invokeLater(() -> {
                    view.showAddressBook(savedAddressBook);
                    view.dismissLoading();
                }), throwable -> SwingUtilities.invokeLater(() -> {
                    view.onError(throwable);
                    view.dismissLoading();
                }));
    }

    public void sortPersonsByName(AddressBook addressBook) {
        view.showLoading();
        Observable.from(addressBook.getPersons())
                .toSortedList((person1, person2) -> person1.getName().compareTo(person2.getName()))
                .doOnNext(addressBook::setPersons)
                .subscribeOn(Schedulers.io())
                .subscribe(savedAddressBook -> SwingUtilities.invokeLater(() -> {
                    view.showAddressBook(addressBook);
                    view.dismissLoading();
                }), throwable -> SwingUtilities.invokeLater(() -> {
                    view.onError(throwable);
                    view.dismissLoading();
                }));
    }

    public void sortPersonsByZip(AddressBook addressBook) {
        view.showLoading();
        Observable.from(addressBook.getPersons())
                .toSortedList((person1, person2) -> person1.getZip().compareTo(person2.getZip()))
                .doOnNext(addressBook::setPersons)
                .subscribeOn(Schedulers.io())
                .subscribe(savedAddressBook -> SwingUtilities.invokeLater(() -> {
                    view.showAddressBook(addressBook);
                    view.dismissLoading();
                }), throwable -> SwingUtilities.invokeLater(() -> {
                    view.onError(throwable);
                    view.dismissLoading();
                }));
    }

    public interface View {

        void showAddressBook(AddressBook addressBook);

        void showLoading();

        void dismissLoading();

        void onError(Throwable throwable);
    }
}

Add presenter to handle saving and loading data asynchronously


/**
 * Copyright (C) 2009-2013 FoundationDB, LLC
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.foundationdb.sql.pg;

import org.junit.Test;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.sql.SQLException;
import java.util.Map;

public class PostgresServerProtocolV2IT extends PostgresServerITBase
{
    @Override
    protected Map<String, String> startupConfigProperties() {
        return uniqueStartupConfigProperties(PostgresServerProtocolV2IT.class);
    }

    @Override
    protected String getConnectionURL() {
        return super.getConnectionURL() + "?protocolVersion=2";
    }

    @Test
    public void checkRejection() throws Exception {
        try {
            openConnection();
        }
        catch (SQLException ex) {
            assertTrue("message is readable",
                       (ex.getMessage().indexOf("Unsupported protocol version 2") > 0));
            return;
        }
        fail("Expected connection to be rejected.");
    }

}

Add an IT for that.


/*
 * #%L
 * ImageJ software for multidimensional image processing and analysis.
 * %%
 * Copyright (C) 2014 - 2015 Board of Regents of the University of
 * Wisconsin-Madison, University of Konstanz and Brian Northan.
 * %%
 * 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 net.imagej.ops;

/**
 * Factory which creates a typed output object given two typed inputs.
 *
 * @author Curtis Rueden
 */
public interface BinaryOutputFactory<I1, I2, O> extends
	OutputFactory<BinaryInput<I1, I2>, O>
{

	/**
	 * Create an output object given two inputs.
	 *
	 * @param input1
	 *            first input which determines how to create the output
	 * @param input2
	 *            second input which determines how to create the output
	 * @return output, depending on the input
	 */
	O createOutput(I1 input1, I2 input2);

	// -- OutputFactory methods --

	@Override
	default O createOutput(final BinaryInput<I1, I2> input) {
		return createOutput(input.in1(), input.in2());
	}

}

Add OutputFactory interface for binary input pairs


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

public class Booleans {

    /**
     * @param s
     *            a {@code String} containing the {@code boolean} representation to parse, may be {@code null} or
     *            {@code ""}
     * @param defaultValue
     *            the return value, use {@code defaultValue} if {@code s} is {@code null} or {@code ""}
     * @return the boolean value represented by the argument.
     */
    public static boolean parseBoolean(String s, boolean defaultValue) {
        return Strings.isEmpty(s) ? defaultValue : Boolean.parseBoolean(s);
    }

}

Refactor duplicate code in a new API Boolean.parseBoolean(String, boolean), which also checks for empty strings in addition to nulls.


package webserver;

import converters.JsonConverter;
import datamodel.Job;
import datamodel.Request;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import rabbit.Sender;

import javax.servlet.http.HttpServletRequest;

@RestController
public class RequestController {

    @RequestMapping(value = "/request", method = RequestMethod.POST)
    public ResponseEntity<Job> jobRequest(@RequestBody String requestBody, HttpServletRequest httpRequest) {
        Request request = JsonConverter.jsonStringToObject(requestBody, Request.class);

        if ((request.getClientId() != null) && (request.getCommand() != null)) {
            Sender sender = new Sender();
            String jobId = sender.send(request, httpRequest.getRemoteAddr());
            sender.closeConnection();
            return new ResponseEntity<Job>(new Job(jobId), HttpStatus.ACCEPTED);
        }
        else {
            return new ResponseEntity<Job>(new Job("-1"), HttpStatus.BAD_REQUEST);
        }

    }
}

Add controller for REST calls.


package com.mapswithme.maps.widget.placepage;

import android.support.annotation.NonNull;

public class HotelPriceInfo
{
  @NonNull
  private final String mId;
  @NonNull
  private final String mPrice;
  @NonNull
  private final String mCurrency;
  private final int mDiscount;
  private final boolean mHasSmartDeal;

  public HotelPriceInfo(@NonNull String id, @NonNull String price, @NonNull String currency,
                        int discount, boolean hasSmartDeal)
  {
    mId = id;
    mPrice = price;
    mCurrency = currency;
    mDiscount = discount;
    mHasSmartDeal = hasSmartDeal;
  }

  @NonNull
  public String getId()
  {
    return mId;
  }

  @NonNull
  public String getPrice()
  {
    return mPrice;
  }

  @NonNull
  public String getCurrency()
  {
    return mCurrency;
  }

  public int getDiscount()
  {
    return 20;
  }

  public boolean hasSmartDeal()
  {
    return mHasSmartDeal;
  }

  @Override
  public String toString()
  {
    final StringBuilder sb = new StringBuilder("HotelPriceInfo{");
    sb.append("mId='").append(mId).append('\'');
    sb.append(", mPrice='").append(mPrice).append('\'');
    sb.append(", mCurrency='").append(mCurrency).append('\'');
    sb.append(", mDiscount=").append(mDiscount);
    sb.append(", mHasSmartDeal=").append(mHasSmartDeal);
    sb.append('}');
    return sb.toString();
  }
}

package com.mapswithme.maps.widget.placepage;

import android.support.annotation.NonNull;

public class HotelPriceInfo
{
  @NonNull
  private final String mId;
  @NonNull
  private final String mPrice;
  @NonNull
  private final String mCurrency;
  private final int mDiscount;
  private final boolean mHasSmartDeal;

  public HotelPriceInfo(@NonNull String id, @NonNull String price, @NonNull String currency,
                        int discount, boolean hasSmartDeal)
  {
    mId = id;
    mPrice = price;
    mCurrency = currency;
    mDiscount = discount;
    mHasSmartDeal = hasSmartDeal;
  }

  @NonNull
  public String getId()
  {
    return mId;
  }

  @NonNull
  public String getPrice()
  {
    return mPrice;
  }

  @NonNull
  public String getCurrency()
  {
    return mCurrency;
  }

  public int getDiscount()
  {
    return mDiscount;
  }

  public boolean hasSmartDeal()
  {
    return mHasSmartDeal;
  }

  @Override
  public String toString()
  {
    final StringBuilder sb = new StringBuilder("HotelPriceInfo{");
    sb.append("mId='").append(mId).append('\'');
    sb.append(", mPrice='").append(mPrice).append('\'');
    sb.append(", mCurrency='").append(mCurrency).append('\'');
    sb.append(", mDiscount=").append(mDiscount);
    sb.append(", mHasSmartDeal=").append(mHasSmartDeal);
    sb.append('}');
    return sb.toString();
  }
}

Revert discount value for hotel price


package cz.cuni.mff.d3s.spl.core.data.storage;

import java.util.Collection;

import cz.cuni.mff.d3s.spl.core.data.PrecomputedStatistics;
import cz.cuni.mff.d3s.spl.core.data.SampleStorage;
import cz.cuni.mff.d3s.spl.core.data.SerieDataSource;
import cz.cuni.mff.d3s.spl.core.data.Statistics;

public class OriginalSerieDataSource implements SerieDataSource {

	private SampleStorage samples;
	private long myStartTime;
	private long myEndTime;

	public OriginalSerieDataSource(SampleStorage storage) {
		this(storage, Long.MIN_VALUE, Long.MAX_VALUE);
	}

	private OriginalSerieDataSource(SampleStorage storage, long segmentStartTime, long segmentEndTime) {
		samples = storage;
		myStartTime = segmentStartTime;
		myEndTime = segmentEndTime;
	}

	@Override
	public Statistics get() {
		Collection<Long> all = getSamples();
		return PrecomputedStatistics.create(all);
	}

	@Override
	public SerieDataSource getSegment(long startTime, long endTime) {
		return new OriginalSerieDataSource(samples, startTime, endTime);
	}

	@Override
	public String toString() {
		return String.format("SerieDataSource on '%s' (%d)",
				samples, getSamples().size());
	}

	private Collection<Long> getSamples() {
		return samples.get(myStartTime, myEndTime).values();
	}
}

Implement source directly working above samples


/*
 * Java Genetic Algorithm Library (@__identifier__@).
 * Copyright (c) @__year__@ Franz Wilhelmstötter
 *
 * 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.
 *
 * Author:
 *    Franz Wilhelmstötter (franz.wilhelmstoetter@gmail.com)
 */
package io.jenetics.ext.internal;

import static io.jenetics.CharacterGene.DEFAULT_CHARACTERS;

import java.util.Objects;
import java.util.Random;
import java.util.stream.Collectors;

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

/**
 * @author Franz Wilhelmstötter
 */
public class EscaperTest {

	private static final Escaper ESCAPER = new Escaper('\\', 'a', 'b', 'c');

	@Test(dataProvider = "strings")
	public void escape(final String original, final String escaped) {
		final String esc = ESCAPER.escape(original);
		final String orig = ESCAPER.unescape(esc);

		Assert.assertEquals(esc, escaped);
		Assert.assertEquals(orig, original);
	}

	@DataProvider
	public Object[][] strings() {
		return new Object[][] {
			{"", ""},
			{"t", "t"},
			{"a", "\\a"},
			{"\\", "\\"}
		};
	}

	@Test(invocationCount = 10)
	public void escapeRandomStrings() {
		final String original = nextString(new Random());
		final String escaped = ESCAPER.escape(original);
		Assert.assertEquals(ESCAPER.unescape(escaped), original);
	}

	private static String nextString(final Random random) {
		return random.ints(0, DEFAULT_CHARACTERS.length())
			.limit(100)
			.mapToObj(DEFAULT_CHARACTERS::get)
			.map(Objects::toString)
			.collect(Collectors.joining());
	}

}

Add tests for 'Escaper' class.


/*
 * Copyright 2016 EPAM Systems
 *
 *
 * This file is part of EPAM Report Portal.
 * https://github.com/reportportal/service-api
 *
 * Report Portal is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Report Portal 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 General Public License
 * along with Report Portal.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.epam.ta.reportportal.config;

import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.util.text.BasicTextEncryptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Encrypt beans configuration for password values
 *
 * @author Andrei_Ramanchuk
 */
@Configuration
public class EncryptConfiguration {

	private static final String DEFAULT_PASS = "reportportal";

	@Bean(name = "basicEncryptor")
	public BasicTextEncryptor getBasicEncrypt() {
		BasicTextEncryptor basic = new BasicTextEncryptor();
		basic.setPassword(DEFAULT_PASS);
		return basic;
	}

	@Bean(name = "strongEncryptor")
	public StandardPBEStringEncryptor getStrongEncryptor() {
		StandardPBEStringEncryptor strong = new StandardPBEStringEncryptor();
		strong.setPassword(DEFAULT_PASS);
		strong.setAlgorithm("PBEWithMD5AndTripleDES");
		return strong;
	}
}

Encrypt bean configuration was added.


/*
 * 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 com.blazzify.jasonium.ui;

import com.blazzify.jasonium.MainApp;
import com.blazzify.jasonium.models.Server;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.Window;

/**
 *
 * @author Azzuwan Aziz <azzuwan@gmail.com>
 */
public class ServerTree extends TreeView<Server> {

    ObjectMapper mapper = new ObjectMapper();

    public ServerTree() {
    }

    public ServerTree(Window root, Map<String, String> servers) {
        Image imgRoot = new Image(getClass().getClassLoader().getResourceAsStream("icons/servers.png"));
        Server node = new Server();
        node.setName("Servers");
        TreeItem<Server> rootNode = new TreeItem<>(node, new ImageView(imgRoot));
        servers.forEach((t, u) -> {
            Server s = new Server();
            try {
                s = mapper.readValue(u.toString(), Server.class);
            } catch (IOException ex) {
                Logger.getLogger(MainApp.class.getName()).log(Level.SEVERE, null, ex);
            }
            Image imgOffline = new Image(getClass().getClassLoader().getResourceAsStream("icons/server-off.png"));
            TreeItem<Server> child = new TreeItem<>(s, new ImageView(imgOffline));
            rootNode.getChildren().add(child);
        });
        this.setRoot(rootNode);
        this.setOnContextMenuRequested((event) -> {
            ServerTreeContextMenu menu = new ServerTreeContextMenu();
            Window w = root.getScene().getWindow();
            Double winX = w.getX();
            Double winY = w.getY();
            menu.show(w, event.getSceneX() + winX, event.getSceneY() + winY);
        });
    }

}

Refactor server tree into it's own component


package net.imagej.ops.views;

import net.imagej.ops.view.ViewOps;
import net.imagej.ops.view.ViewOps.UnShear;
import net.imglib2.RandomAccessible;
import net.imglib2.view.TransformView;

import org.scijava.ItemIO;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;

@Plugin(type = ViewOps.UnShear.class, name = ViewOps.UnShear.NAME)
public class DefaultUnshear<T> extends
		AbstractView<RandomAccessible<T>, TransformView<T>> implements
		UnShear<RandomAccessible<T>, TransformView<T>> {

	@Parameter(type = ItemIO.INPUT)
	private int shearDimension;

	@Parameter(type = ItemIO.INPUT)
	private int referenceDimension;

	@Override
	public TransformView<T> compute(RandomAccessible<T> input) {
		throw new UnsupportedOperationException();
	}

}

Add default implementation of Unshear interface.


package Logger;

import Constant.FilePath;
import Database.Config;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.File;

import static org.junit.Assert.*;

public class LogWriterTest {

    LogWriter logWriter;

    @Before
    public void setUp() throws Exception {
        logWriter = new LogWriter(new File(FilePath.LOG_FILE_PATH.toString()));
    }

    @After
    public void tearDown() throws Exception {

    }

    @Test
    public void testWrite() throws Exception {
        logWriter.write(Log.p(
                this.getClass().getSimpleName(),
                "wrote to file", System.currentTimeMillis()
        ));
    }
}

Add Test to fail LogWriter


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

package com.google.gerrit.server.cancellation;

import com.google.gerrit.common.Nullable;
import java.util.Optional;

/** Exception to signal that the current request is cancelled and should be aborted. */
public class RequestCancelledException extends RuntimeException {
  private static final long serialVersionUID = 1L;

  private final RequestStateProvider.Reason cancellationReason;
  private final Optional<String> cancellationMessage;

  /**
   * Create a {@code RequestCancelledException}.
   *
   * @param cancellationReason the reason why the request is cancelled
   * @param cancellationMessage an optional message providing details about the cancellation
   */
  public RequestCancelledException(
      RequestStateProvider.Reason cancellationReason, @Nullable String cancellationMessage) {
    super(createMessage(cancellationReason, cancellationMessage));
    this.cancellationReason = cancellationReason;
    this.cancellationMessage = Optional.ofNullable(cancellationMessage);
  }

  private static String createMessage(
      RequestStateProvider.Reason cancellationReason, @Nullable String message) {
    StringBuilder messageBuilder = new StringBuilder();
    messageBuilder.append(String.format("Request cancelled: %s", cancellationReason.name()));
    if (message != null) {
      messageBuilder.append(String.format(" (%s)", message));
    }
    return messageBuilder.toString();
  }

  /** Returns the reason why the request is cancelled. */
  public RequestStateProvider.Reason getCancellationReason() {
    return cancellationReason;
  }

  /**
   * Returns a message providing details about the cancellation, or {@link Optional#empty()} if none
   * is available.
   */
  public Optional<String> getCancellationMessage() {
    return cancellationMessage;
  }
}

Define an exception that is thrown if a request is cancelled


package com.sibisoft.faizaniftikhartdd;

import static org.junit.Assert.*;

import org.junit.Test;

public class DollarEquality {

	@Test
	public void testEquality()
	{
		assertTrue(new Dollar(5).equals(new Dollar(5)));
	}

}

Add new test case for equal method(Fake Implementation) to make red bar


/**
 *
 */
package algorithms.implementation;

import java.util.Scanner;

/**
 * Challenge: https://www.hackerrank.com/challenges/lisa-workbook
 *
 * @author Sudharsanan Muralidharan
 */
public class LisasWorkbook {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    int k = in.nextInt();
    int[] t = new int[n];

    for (int i = 0; i < n; i++) {
      t[i] = in.nextInt();
    }

    int page = 0;
    int special = 0;
    for (int i = 0; i < t.length; i++) {
      int num = t[i];
      int start = 0, end = 0;
      while (num > 0) {
        start = end + 1;
        page++;
        if (num > k) {
          num = num - k;
          end += k;
        } else {
          end += num;
          num = 0;
        }

        if (page >= start && page <= end) {
          special++;
        }
      }
    }

    System.out.println(special);
    in.close();
  }
}

Add Naive solution for Lisas Workbook


/*
 ************************************************************************
 ****  C A N A D I A N   A S T R O N O M Y   D A T A   C E N T R E  *****
 *
 * (c) 2010.                         (c) 2010.
 * National Research Council            Conseil national de recherches
 * Ottawa, Canada, K1A 0R6              Ottawa, Canada, K1A 0R6
 * All rights reserved                  Tous droits reserves
 *
 * NRC disclaims any warranties         Le CNRC denie toute garantie
 * expressed, implied, or statu-        enoncee, implicite ou legale,
 * tory, of any kind with respect       de quelque nature que se soit,
 * to the software, including           concernant le logiciel, y com-
 * without limitation any war-          pris sans restriction toute
 * ranty of merchantability or          garantie de valeur marchande
 * fitness for a particular pur-        ou de pertinence pour un usage
 * pose.  NRC shall not be liable       particulier.  Le CNRC ne
 * in any event for any damages,        pourra en aucun cas etre tenu
 * whether direct or indirect,          responsable de tout dommage,
 * special or general, consequen-       direct ou indirect, particul-
 * tial or incidental, arising          ier ou general, accessoire ou
 * from the use of the software.        fortuit, resultant de l'utili-
 *                                      sation du logiciel.
 *
 *
 * @author jenkinsd
 * Jan 6, 2010 - 10:15:22 AM
 *
 *
 *
 ****  C A N A D I A N   A S T R O N O M Y   D A T A   C E N T R E  *****
 ************************************************************************
 */
package ca.nrc.cadc.uws.web;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import ca.nrc.cadc.uws.web.restlet.resources.*;

@RunWith(Suite.class)
@Suite.SuiteClasses
({
        AsynchResourceTestCase.class,
        JobAsynchResourceExecutionTest.class,
        JobSyncSubmissionResourceTest.class,
        ResultResourceTest.class
})
public class CADCUWSTestSuite
{
}

Add unit tests to build.xml.


package guitests;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

import seedu.jobs.model.task.UniqueTaskList.IllegalTimeException;
import seedu.jobs.testutil.TestTask;

//@@author A0164440M
public class ListCommandTest extends TaskBookGuiTest {

    @Test
  //TODO add success cases listed by all, complete, in-progress
    public void list_nonEmptyList() throws IllegalArgumentException, IllegalTimeException {

        //list all tasks
        assertListWithoutArgumentResult("list", td.CS3101, td.CS3102, td.CS3103, td.CS3104,
                td.CS3105, td.CS3106, td.CS3107, td.CS5101);

        // complete some tasks
        int completeTasks = 6;
        for (int i = 0; i < completeTasks; i++) {
            commandBox.runCommand("complete " + (i + 1));
        }

        // list all completed tasks
        assertListWithArgumentResult("list complete", td.CS3101, td.CS3102, td.CS3103, td.CS3104,
                td.CS3105, td.CS3106);

        // list all in-progress tasks
        assertListWithArgumentResult("list in-progress", td.CS3107, td.CS5101);
    }

    @Test
    public void find_emptyList() throws IllegalArgumentException, IllegalTimeException {
        // list with wrong argument
        assertListWithArgumentResult("list abc");

        commandBox.runCommand("clear");
        assertListWithoutArgumentResult("list"); // no results
    }

    private void assertListWithArgumentResult(String command, TestTask... expectedHits)
            throws IllegalArgumentException, IllegalTimeException {
        commandBox.runCommand(command);
        assertListSize(expectedHits.length);
        assertResultMessage(expectedHits.length + " tasks listed!");
        assertTrue(taskListPanel.isListMatching(expectedHits));
    }

    private void assertListWithoutArgumentResult(String command, TestTask... expectedHits)
            throws IllegalArgumentException, IllegalTimeException {
        commandBox.runCommand(command);
        assertListSize(expectedHits.length);
        assertResultMessage("Listed all tasks");
        assertTrue(taskListPanel.isListMatching(expectedHits));
    }
}

Add test case for list command


/*
 * Copyright 2014 Open mHealth
 *
 * 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.openmhealth.dsu.domain;

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

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat;
import static org.openmhealth.dsu.domain.DataPointModality.SELF_REPORTED;

/**
 * A suite of unit tests for the data point modality enumeration.
 *
 * @author Emerson Farrugia
 */
@RunWith(BlockJUnit4ClassRunner.class)
public class DataPointModalityUnitTests {

    @Test
    public void getJsonValueShouldReturnCorrectValue() throws Exception {
        assertThat(SELF_REPORTED.getJsonValue(), equalTo("self reported"));
    }

    @Test
    public void findByJsonValueShouldReturnNullWithUndefinedValue() throws Exception {
        assertThat(DataPointModality.findByJsonValue(null), nullValue());
    }

    @Test
    public void findByJsonValueShouldReturnNullWithUnknownValue() throws Exception {
        assertThat(DataPointModality.findByJsonValue("foo"), nullValue());
    }

    @Test
    public void findByJsonValueShouldReturnMatchingValue() throws Exception {
        assertThat(DataPointModality.findByJsonValue("self reported"), equalTo(SELF_REPORTED));
    }
}

Add data point modality unit tests.


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

package com.crimsoncricket.ddd.port.adapter.jpa;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.time.ZoneId;

@Converter(autoApply = true)
public class ZoneIdConverter implements AttributeConverter<ZoneId, String> {

    @Override
    public String convertToDatabaseColumn(ZoneId attribute) {
        if (attribute == null)
            return null;

        return attribute.getId();
    }

    @Override
    public ZoneId convertToEntityAttribute(String dbData) {
        if (dbData == null)
            return null;

        return ZoneId.of(dbData);
    }
}

Add Jpa converter for ZoneId from the java.time API


/**
 * Aeronica's mxTune MOD
 * Copyright {2016} Paul Boese a.k.a. Aeronica
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.aeronica.mods.mxtune.network.client;

import java.io.IOException;

import net.aeronica.mods.mxtune.groups.PlayManager;
import net.aeronica.mods.mxtune.network.AbstractMessage.AbstractClientMessage;
import net.aeronica.mods.mxtune.sound.ClientAudio;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.network.PacketBuffer;
import net.minecraftforge.fml.common.network.ByteBufUtils;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

public class StopPlayMessage extends AbstractClientMessage<StopPlayMessage>
{

    private Integer playID;

    public StopPlayMessage() {}

    public StopPlayMessage(Integer playID) {this.playID = playID;}

    @Override
    protected void read(PacketBuffer buffer) throws IOException
    {
        playID = ByteBufUtils.readVarInt(buffer, 5);
    }

    @Override
    protected void write(PacketBuffer buffer) throws IOException
    {
        ByteBufUtils.writeVarInt(buffer, playID, 5);
    }

    @Override
    public void process(EntityPlayer player, Side side)
    {
        if (side.isClient())
        {
            handleClientSide(player);
        } else
        {
            handleServerSide(player);
        }
    }

    @SideOnly(Side.CLIENT)
    public void handleClientSide(EntityPlayer playerSP)
    {
        // TODO: More Cleanup for playing - resetting all the players PlayStatuses
        ClientAudio.stop(playID);
    }

    public void handleServerSide(EntityPlayer playerMP)
    {
        //PlayManager.stopPlayID(playID);
    }

}

Rework Play Music chain to improve reliability, eliminate clicks and pops on abrupt cutoff. Part 1


package leetcode.unique_binary_search_trees;

public class Solution {
    public int numTrees(int n) {
        return Catalan(n);
    }
    public static int Catalan(int n){
    	long ans = 1;
    	for(int i = 1; i <= n; i++){
    		ans *= (2 * n - i + 1);
    		ans /= i;
    	}
    	return (int)(ans / (n + 1));
    }

    public static void main(String[] args){
    	for(int i = 0; i < 10; i++){
    		System.err.println(Solution.Catalan(i));
    	}
    }
}

Add java solution for 96. Unique Binary Search Trees


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

package com.google.sps.servlets;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/registration")
public class RegistrationServlet extends HttpServlet {

  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String role = request.getParameter("role");
    String name = request.getParameter("name");
    String email = request.getParameter("email");
    List<String> topics = Arrays.asList(request.getParameter("math"), request.getParameter("english"), request.getParameter("other"));

    topics = topics
            .stream()
            .filter(t -> t!= null)
            .collect(Collectors.toList());

    response.setContentType("text/html;");
    response.getWriter().println("
Student or tutor? " + role + "
");
    response.getWriter().println("
Name: " + name + "
");
    response.getWriter().println("
Email: " + email + "
");
    response.getWriter().println("
Subject(s): " + topics + "
");
  }
}

Add basic servlet that responds with user info


package leetcode.evaluate_reverse_polish_notation;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.Stack;

public class Solution {
    public int evalRPN(String[] tokens) {
    	Stack<String> stack = new Stack<String>();
    	Set<String> operatorSet = new HashSet<String>(Arrays.asList(new String[]{"+", "-", "*", "/"}));
    	for(String token : tokens){
    		if(operatorSet.contains(token)){
    			int operand2 = Integer.parseInt(stack.pop());
    			int operand1 = Integer.parseInt(stack.pop());
    			if(token.equals("+")){
    				stack.push(Integer.toString(operand1 + operand2));
    			}else if(token.equals("-")){
    				stack.push(Integer.toString(operand1 - operand2));
    			}else if(token.equals("*")){
    				stack.push(Integer.toString(operand1 * operand2));
    			}else if(token.equals("/")){
    				stack.push(Integer.toString(operand1 / operand2));
    			}
    		}else{
    			stack.push(token);
    		}
    	}
    	return Integer.parseInt(stack.pop());
    }

    public static void main(String[] args){
    	System.err.println(new Solution().evalRPN(new String[]{"2", "1", "+", "3", "*"}));
    }
}

Add java solution for 150. Evaluate Reverse Polish Notation


package com.github.aureliano.achmed.os.pkg;

import com.github.aureliano.achmed.command.CommandResponse;
import com.github.aureliano.achmed.resources.properties.PackageProperties;

public class YumPackageManager implements IPackageManager {

	private PackageProperties properties;

	public YumPackageManager() {
		super();
	}

	public CommandResponse install() {
		throw new UnsupportedOperationException("Method not implemented yet.");
	}

	public CommandResponse uninstall() {
		throw new UnsupportedOperationException("Method not implemented yet.");
	}

	public String latest() {
		throw new UnsupportedOperationException("Method not implemented yet.");
	}

	public void setPackageProperties(PackageProperties properties) {
		this.properties = properties;
	}

	public PackageProperties getPackageProperties() {
		return this.properties;
	}
}

Create template of yum package manager.


package edu.agh.tunev.model.kkm;

import java.util.Vector;

import edu.agh.tunev.model.AbstractModel;
import edu.agh.tunev.model.PersonProfile;
import edu.agh.tunev.statistics.Statistics.AddCallback;
import edu.agh.tunev.world.World;
import edu.agh.tunev.world.World.ProgressCallback;

public final class Model extends AbstractModel {

	public final static String MODEL_NAME = "Autorski (\u00a9 2012 Jakub Rakoczy)";

	public Model(World world) {
		super(world);
	}

	@Override
	public void simulate(double duration, Vector<PersonProfile> profiles,
			ProgressCallback progressCallback, AddCallback addCallback) {
		// TODO Auto-generated method stub

	}

}

Create main class od KKM model


package to.etc.domui.component.form;

import to.etc.domui.util.*;

public class InstanceReadOnlyModel<T> implements IReadOnlyModel<T> {
	private T m_instance;

	public InstanceReadOnlyModel(T instance) {
		m_instance = instance;
	}

	@Override
	public T getValue() throws Exception {
		return m_instance;
	}
}

Add instance model helper class


/**
 * Copyright (C) 2012 Gist Labs, LLC. (http://gistlabs.com)
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */
package com.gistlabs.mechanize.integration.test;

import static org.junit.Assert.*;

import org.json.JSONException;
import org.junit.Test;

import com.gistlabs.mechanize.MechanizeAgent;
import com.gistlabs.mechanize.json.JsonPage;

/**
 *
 */
public class AndroidJsonApiIT {

	@Test
	public void testAndroidJsonApiDemo() throws JSONException {
		MechanizeAgent agent = new MechanizeAgent();
		JsonPage page = (JsonPage) agent.get("http://api.androidhive.info/contacts/");

		assertNotNull(page.json().getJSONArray("contacts"));
	}
}

Add Json integration test for reading and parsing Json


package com.box.l10n.mojito.collect;

import com.google.common.collect.ImmutableMap;

import java.util.Map;
import java.util.stream.Collector;

public class ImmutableMapCollectors {
    public static <K,V> Collector<Map.Entry<K, V>, ?, ImmutableMap<K, V>> MapEntriesToImmutableMap() {
        return ImmutableMap.toImmutableMap(Map.Entry::getKey, Map.Entry::getValue);
    }
}

Add simple collect for Map entries to ImmutableMap


package io.vertx.example.shell.prompt;

import io.vertx.core.AbstractVerticle;
import io.vertx.example.util.Runner;
import io.vertx.ext.shell.Shell;
import io.vertx.ext.shell.ShellServer;
import io.vertx.ext.shell.ShellService;
import io.vertx.ext.shell.ShellServiceOptions;
import io.vertx.ext.shell.command.CommandResolver;
import io.vertx.ext.shell.term.TelnetTermOptions;
import io.vertx.ext.shell.term.TermServer;
import io.vertx.ext.shell.term.impl.TelnetTermServer;

import java.util.concurrent.atomic.AtomicInteger;

public class PromptCommand  extends AbstractVerticle {
  // Convenience method so you can run it in your IDE
  public static void main(String[] args) {
    Runner.runExample(PromptCommand.class);
  }

  @Override
  public void start() throws Exception {

    ShellServer server = ShellServer.create(vertx);
    AtomicInteger ai = new AtomicInteger(0);
    server.shellHandler(shell -> {
      shell.setPrompt(s -> {
        try {
          return "C: " + ai.incrementAndGet();
        } catch (Exception e) {
          System.err.println("Counter");
          e.printStackTrace();
        }
        return "NOOP";
      });
    });
    TelnetTermOptions tto = new TelnetTermOptions().setPort(3000).setHost("localhost");
    TermServer telnetTermServer = TermServer.createTelnetTermServer(vertx,tto);
    server.registerTermServer(telnetTermServer);

    server.registerCommandResolver(CommandResolver.baseCommands(vertx));

    server.listen(ar -> {
      if (!ar.succeeded()) {
        ar.cause().printStackTrace();
      }
    });

  }
}

Add example on how to set the prompt


package org.beanmaker.util;

import org.jcodegen.html.DivTag;

import java.util.ResourceBundle;

public interface HtmlDefaultButtonsHelper {

    DivTag getDefaultDialogButtons(
            final HtmlFormHelper htmlFormHelper,
            final long id,
            final String name,
            final ResourceBundle resourceBundle);

    DivTag getDefaultDialogButtons(
            final HtmlFormHelper htmlFormHelper,
            final long id,
            final String name,
            final ResourceBundle resourceBundle,
            final boolean submitDisabled);

    DivTag getLonelyCloseButton(final ResourceBundle resourceBundle);

}

Add interface for parameterization of buttons in forms


package jenkins.bugs;

import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;

import hudson.security.HudsonPrivateSecurityRealm;
import jenkins.model.Jenkins;

public class Jenkins41511Test {

    @BeforeClass
    public static void setUpClass() {
        System.setProperty(Jenkins.class.getName()+".slaveAgentPort", "10000");
        System.setProperty(Jenkins.class.getName()+".slaveAgentPortEnforce", "true");
    }

    @Rule
    public JenkinsRule j = new JenkinsRule();

    @Test
    public void configRoundTrip() throws Exception {
        Jenkins.getInstance().setSecurityRealm(new HudsonPrivateSecurityRealm(true, false, null));
        j.submit(j.createWebClient().goTo("configureSecurity").getFormByName("config"));
    }
}

Add a test showing the problem


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

package gerrit;

import com.google.gerrit.server.rules.StoredValues;
import com.googlecode.prolog_cafe.exceptions.PrologException;
import com.googlecode.prolog_cafe.lang.IntegerTerm;
import com.googlecode.prolog_cafe.lang.Operation;
import com.googlecode.prolog_cafe.lang.Predicate;
import com.googlecode.prolog_cafe.lang.Prolog;
import com.googlecode.prolog_cafe.lang.Term;
import org.eclipse.jgit.revwalk.RevCommit;

/**
 * Prolog fact for the number of parents of a given commit
 *
 * <pre>
 *   'commit_parent_count'(-Count)
 * </pre>
 */
public class PRED_commit_parent_count_1 extends Predicate.P1 {
  public PRED_commit_parent_count_1(Term a1, Operation n) {
    arg1 = a1;
    cont = n;
  }

  @Override
  public Operation exec(Prolog engine) throws PrologException {
    engine.setB0();
    Term a1 = arg1.dereference();

    RevCommit commit = StoredValues.COMMIT.get(engine);

    if (!a1.unify(new IntegerTerm(commit.getParentCount()), engine.trail)) {
      return engine.fail();
    }
    return cont;
  }
}

Add prolog predicate to determine number of parents


package org.opennms.web.svclayer;

public class ProgressMonitor {

	private int m_phaseCount = 1;
	private int m_phase = 0;
	private String m_phaseLabel = "Loading";
	private Object m_result = null;
	private Exception m_exception = null;

	public int getPhaseCount() {
		return m_phaseCount;
	}

	public void setPhaseCount(int phaseCount) {
		m_phaseCount = phaseCount;
	}

	public String getPhaseLabel() {
		return m_phaseLabel;
	}

	public int getPhase() {
		return m_phase;
	}

	public void beginNextPhase(String phaseLabel) {
		m_phaseLabel = phaseLabel;
		m_phase++;
	}

	public void finished(Object result) {
		m_result = result;
		m_phaseLabel = "Done";
		m_phase = m_phaseCount;
	}

	public boolean isFinished() {
		return m_result != null;
	}

	public Object getResult() {
		return m_result;
	}

	public boolean isError() {
		return m_exception != null;
	}

	public Exception getException() {
		return m_exception;
	}

	public void errorOccurred(Exception e) {
		m_exception = e;
	}

}

Add progress bar to loading of Surveillence page


package com.google.sps.tool;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

import java.util.List;
import java.util.ArrayList;
import com.google.sps.data.Card;
import com.google.sps.data.Folder;

public class EntityTestingTool {

  public static boolean checkForNoNullValues(Entity card) {
    return (card.getProperty("blobKey") != null  &&
      card.getProperty("labels") != null &&
      card.getProperty("textTranslated") != null &&
      card.getProperty("textNotTranslated") != null &&
      card.getProperty("fromLang") != null &&
      card.getProperty("toLang") != null &&
      card.getProperty("cardKey") != null);
  }

  public static List<Folder> populateDatastoreWithFolders(Folder FOLDER_A, Folder FOLDER_B, DatastoreService datastore, String USERKEY) {

    Entity folderA_Entity = FOLDER_A.createEntity(KeyFactory.stringToKey(USERKEY));
    Entity folderB_Entity = FOLDER_B.createEntity(KeyFactory.stringToKey(USERKEY));

    // Update entity in datastore
    datastore.put(folderA_Entity);
    datastore.put(folderB_Entity);

    List<Folder> folders = new ArrayList<>();
    folders.add(Folder.EntityToFolder(folderA_Entity));
    folders.add(Folder.EntityToFolder(folderB_Entity));

    return folders;
  }

  public static List<Card> populateDatastoreWithCards(Card CARD_A, Card CARD_B, DatastoreService datastore, String FOLDERKEY) {

    Entity CardA_Entity = CARD_A.createEntity(KeyFactory.stringToKey(FOLDERKEY));
    Entity CardB_Entity = CARD_B.createEntity(KeyFactory.stringToKey(FOLDERKEY));

    // Update entity in datastore
    datastore.put(CardA_Entity);
    datastore.put(CardB_Entity);

    List<Card> cards = new ArrayList<>();
    cards.add(Card.EntityToCard(CardA_Entity));
    cards.add(Card.EntityToCard(CardB_Entity));

    return cards;
  }

}

Implement a class with testing methods


package org.numenta.nupic.util;

import static org.junit.Assert.*;

import org.junit.Test;

public class MethodSignatureTest {

    @Test
    public void testSetParam() {
        MethodSignature ms = new MethodSignature(2);

        int param1 = 5;
        ms.setParam(param1, 0);
        assertEquals(5, ms.get(0));

        String test = "test";
        ms.setParam(test, 1);
        assertEquals("test", ms.get(1));

        try {
            ms.setParam("fail", 2);
            fail();
        }catch(Exception e) {
            assertEquals(e.getClass(), ArrayIndexOutOfBoundsException.class);
        }
    }

    @Test
    public void testSetParams() {
        MethodSignature ms = new MethodSignature(2);

        int param1 = 5;
        String test = "test";
        ms.setParams(param1, test);
        assertEquals(5, ms.get(0));
        assertEquals("test", ms.get(1));

        try {
            ms.setParam("fail", 2);
            fail();
        }catch(Exception e) {
            assertEquals(e.getClass(), ArrayIndexOutOfBoundsException.class);
        }
    }

}

Add Test class to appease github bellyaching


package datamodel;

public class CommandPidAndResults {
    private long commadnPid;
    private String commandResults;

    public CommandPidAndResults(long commadnPid, String commandResults) {
        this.commadnPid = commadnPid;
        this.commandResults = commandResults;
    }

    public long getCommadnPid() {
        return commadnPid;
    }

    public void setCommadnPid(long commadnPid) {
        this.commadnPid = commadnPid;
    }

    public String getCommandResults() {
        return commandResults;
    }

    public void setCommandResults(String commandResults) {
        this.commandResults = commandResults;
    }
}

Add datamodel for mentaining information abbout process pid and process output.


package ca.corefacility.bioinformatics.irida.service;

import ca.corefacility.bioinformatics.irida.model.Project;
import ca.corefacility.bioinformatics.irida.model.Role;
import ca.corefacility.bioinformatics.irida.model.User;
import org.springframework.transaction.annotation.Transactional;

/**
 * A specialized service layer for projects.
 *
 * @author Franklin Bristow <franklin.bristow@phac-aspc.gc.ca>
 */
@Transactional
public interface ProjectService extends CRUDService<String, Project> {

    /**
     * Add the specified user to the project with a role. If the user is a
     * manager for the project, then the user should be added to the project
     * with the 'ROLE_MANAGER' role.
     *
     * @param project the project to add the user to.
     * @param user the user to add to the project.
     * @param role the role that the user plays on the project.
     */
    public void addUserToProject(Project project, User user, Role role);
}

Add support for persisting Projects.


/*
 * 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.prestosql.sql.query;

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

public class TestPredicatePushdown
{
    private QueryAssertions assertions;

    @BeforeClass
    public void init()
    {
        assertions = new QueryAssertions();
    }

    @AfterClass(alwaysRun = true)
    public void teardown()
    {
        assertions.close();
        assertions = null;
    }

    @Test
    public void testConditionalExpressionWithFailingExpression()
    {
        assertions.assertQuery("" +
                        "WITH t (k, a) AS ( " +
                        "    VALUES " +
                        "        (1, 1), " +
                        "        (2, 0) " +
                        ")," +
                        "u (k, v) AS ( " +
                        "    VALUES" +
                        "        (1, 'x'), " +
                        "        (2, 'y') " +
                        ") " +
                        "SELECT * " +
                        "FROM ( " +
                        "    SELECT v, if(v = 'x', 1 / a) AS r" +
                        "    FROM t JOIN u ON t.k = u.k " +
                        ") " +
                        "WHERE v = 'x' AND r IS NOT NULL",
                "VALUES ('x', 1)");

        assertions.assertQuery(
                "WITH t (k, v) AS ( " +
                        "    VALUES " +
                        "        (1, 1), " +
                        "        (2, 0) " +
                        "), " +
                        "u (k) AS ( " +
                        "    VALUES 1, 2 " +
                        ") " +
                        "SELECT * " +
                        "FROM ( " +
                        "    SELECT t.k, if(t.k = 1, 1 / t.v) AS r " +
                        "    FROM t JOIN u ON t.k = u.k " +
                        ") " +
                        "WHERE k = 1 AND r <> 0",
                "VALUES (1, 1)");

        assertions.assertQuery(
                "WITH t (k, v) AS ( " +
                        "    VALUES " +
                        "        (1, 1), " +
                        "        (2, 0) " +
                        "), " +
                        "u (k) AS ( " +
                        "    VALUES 1, 2 " +
                        ") " +
                        "SELECT * " +
                        "FROM ( " +
                        "    SELECT t.k, if(t.k = 1, 1 / t.v) AS r " +
                        "    FROM t LEFT JOIN u ON t.k = u.k " +
                        ") " +
                        "WHERE k = 1 AND r <> 0",
                "VALUES (1, 1)");
    }
}

Add tests for pedicate pushdown


/**
 * Provides the classes necessary to create and process client request filters.
 *

 * {@link uk.ac.ebi.quickgo.rest.search.filter.RequestFilter} instances are usually created by QuickGO REST endpoints
 * when a client would like to filter down results from a query that (s)he has supplied.
 *

 * The complexity of a request filter is based on the field(s) declared within the filter. Fields may:
 *

 *
Exist in a table/collection of underlying data-source: It is most likely that no complex processing
 *     is necessary, and that the filter can be directly executed from within the data source.
 *

 *
Not exist in table/collection of the underlying data-source: Using this field as a filter will
 *     require extra processing, usually in the form of a join between two tables/collections, or querying other
 *     services for the required information

 *

 * The {@link uk.ac.ebi.quickgo.rest.search.filter.FilterConverterFactory} is the class responsible for deciding how a
 * {@link uk.ac.ebi.quickgo.rest.search.filter.RequestFilter} is to be processed. Note that the factory does not do
 * the actual processing, it delegates this task to {@link uk.ac.ebi.quickgo.rest.search.filter.FilterConverter}.
 * There exist several implementations of the {@link uk.ac.ebi.quickgo.rest.search.filter.FilterConverter} interface,
 * each one tries to obtain the required information in a different way, e.g. contact another service, create a join
 * between two tables/collections or create a simple filter query. Any extra configuration required by the converter
 * is fed to them via the {@link uk.ac.ebi.quickgo.rest.search.filter.FilterExecutionConfig}.
 *
 * @author Ricardo Antunes
 */
package uk.ac.ebi.quickgo.rest.search.filter;

Add a package level Javadoc to try to clarify how the filter solution works.


package com.lucene;

public class LuceneConstants {

	public static final String DATA_DIRECTORY 			= "/Users/Hurricanc/Documents/Projects/WJLucene-Java/MetaData/Data";
	public static final String INDEX_DIRECTORY 			= "/Users/Hurricanc/Documents/Projects/WJLucene-Java/MetaData/Index";

	public static final String DEFAULT_FIELD 			= "core_newsurl";

	public static final String CORE_NEWSURL 			= "core_news_url";
	public static final String CORE_NEWSNUMBER 			= "core_news_number";
	public static final String CORE_NEWSTITLE 			= "core_new_title";
	public static final String CORE_NEWSBODY			= "core_news_body";
	public static final String CORE_NEWSDATE			= "core_news_date";
	public static final String CORE_NEWSSOURCE 			= "core_news_source";

	public static final String COMMENT_ID 				= "comment_id";
	public static final String COMMENT_PARENTID 		= "comment_parentId";
	public static final String COMMENT_COMMENTER 		= "comment_commenter";
	public static final String COMMENT_LOCATION 		= "comment_location";
	public static final String COMMENT_DATE 			= "comment_date";
	public static final String COMMENT_LIKECOMMENT 		= "comment_like_comment";
	public static final String COMMENT_DISLIKECOMMENT	= "comment_dislike_comment";
	public static final String COMMENT_RESPONSECOUNT 	= "comment_response_count";
	public static final String COMMENT_BODY 			= "comment_body";

	public static final String CATEGORY_NEWS 			= "core_category";
	public static final String LABEL_NEWS 				= "core_label";

	public static final String FILE_NAME				= "filename";
	public static final String FILE_PATH				= "filepath";

	public static final String FILE_PATH_CORENEWS 		= "/Users/Hurricanc/Documents/Projects/WJLucene-Java/MetaData/Data/Core.xls";
	public static final String FILE_PATH_COMMENTS		= "/Users/Hurricanc/Documents/Projects/WJLucene-Java/MetaData/Data/Comments.xls";
	public static final String FILE_PATH_CATEGORY		= "/Users/Hurricanc/Documents/Projects/WJLucene-Java/MetaData/Data/Category.xls";
	public static final String FILE_PATH_LABELS			= "/Users/Hurricanc/Documents/Projects/WJLucene-Java/MetaData/Data/Label.xls";

	public static final int MAX_SEARCH = 50000;

	public static final String MESSAGE_INDEXING 		= "Wait for Merging raw data and Indexing!";
	public static final String MESSAGE_INDEXED 			= "Ready to Use, Give it a try!";
	public static final String MESSAGE_SEARCH 			= " Documents Found in ";

}

Create Constants Class for All Hardcoded Texts and URLs