package yuku.alkitab.test;

import android.test.AndroidTestCase;
import yuku.alkitabintegration.AlkitabIntegrationUtil;
import yuku.alkitabintegration.ConnectionResult;
import yuku.alkitabintegration.provider.VerseProvider;

import java.util.List;

public class ProviderTest extends AndroidTestCase {
	public void test() {
		assertEquals(ConnectionResult.SUCCESS, AlkitabIntegrationUtil.isIntegrationAvailable(getContext()));

		final VerseProvider vp = new VerseProvider(getContext().getContentResolver());
		assertNotNull(vp.getVerse(0x00000101));

		final VerseProvider.VerseRanges vr = new VerseProvider.VerseRanges();
		vr.addRange(0x000201, 0x000220);
		final List<VerseProvider.Verse> verses = vp.getVerses(vr);

		assertEquals(25 /* num of verses in Gen 2 */, verses.size());
	}
}

Add test for content provider

Add test for content provider


package nl.fhict.happynews.api;

import nl.fhict.happynews.api.auth.User;
import nl.fhict.happynews.api.auth.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.Collections;

@Component
public class Setup {

    private static final Logger logger = LoggerFactory.getLogger(Setup.class);

    private final UserRepository userRepository;

    @Autowired
    public Setup(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    /**
     * Run setup when application starts.
     */
    @EventListener(ContextRefreshedEvent.class)
    public void contextRefreshedEvent() {
        logger.info("Running setup");

        if (userRepository.count() == 0) {
            logger.info("No users have been configured, creating default user");
            User user = new User("admin", "password", Collections.singleton("ROLE_" + WebSecurityConfig.Roles.ADMIN));
            userRepository.save(user);
            logger.info("Created user \"{}\" with password \"{}\". Change this password for security reasons!",
                user.getUsername(),
                "password");
        }

        logger.info("Setup completed");
    }
}

Create default user on startup

Create default user on startup


package leetcode.binary_tree_preorder_traversal;

import java.util.ArrayList;

import common.TreeNode;

public class Solution {
    public ArrayList<Integer> preorderTraversal(TreeNode root) {
    	ArrayList<Integer> ans = new ArrayList<Integer>();
    	if(root == null) return ans;
    	ArrayList<TreeNode> stack = new ArrayList<TreeNode>();
    	stack.add(root);
    	while(stack.size() > 0){
    		TreeNode cur = stack.remove(stack.size() - 1);
    		ans.add(cur.val);
    		if(cur.right != null){
    			stack.add(cur.right);
    		}
    		if(cur.left != null){
    			stack.add(cur.left);
    		}
    	}
    	return ans;
    }

    public static void main(String[] args){
    	TreeNode t1 = new TreeNode(1);
    	TreeNode t2 = new TreeNode(2);
    	TreeNode t3 = new TreeNode(3);
    	TreeNode t4 = new TreeNode(4);
    	t1.left = t2;
    	t2.left = t3;
    	t2.right = t4;
    	for(int x : new Solution().preorderTraversal(t1)){
    		System.err.print(x + "->");
    	}
    	System.err.println("");
    }
}

Add java solution for 144. Binary Tree Preorder Traversal

144. Binary Tree Preorder Traversal: https://leetcode.com/problems/binary-tree-preorder-traversal/


/*
 * #%L
 * SciJava Common shared library for SciJava software.
 * %%
 * Copyright (C) 2009 - 2014 Board of Regents of the University of
 * Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck
 * Institute of Molecular Cell Biology and Genetics.
 * %%
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * #L%
 */

package org.scijava;

/**
 * An exception thrown when a {@link Context} is null, but shouldn't be.
 *
 * @author Curtis Rueden
 */
public class NullContextException extends RuntimeException {

	public NullContextException() {
		super();
	}

	public NullContextException(final String s) {
		super(s);
	}

	public NullContextException(final String s, final Throwable cause) {
		super(s, cause);
	}

	public NullContextException(final Throwable cause) {
		super(cause);
	}

}

Add exception to throw for null Context references

This new exception type will be used in a forthcoming
Contextual#context() method, which ensures that either
the Context is null, or throws an exception.


/*******************************************************************************
  * Copyright (c) 2017 DocDoku.
  * All rights reserved. This program and the accompanying materials
  * are made available under the terms of the Eclipse Public License v1.0
  * which accompanies this distribution, and is available at
  * http://www.eclipse.org/legal/epl-v10.html
  *
  * Contributors:
  *    DocDoku - initial API and implementation
  *******************************************************************************/

package org.polarsys.eplmp.server.rest;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;

import static org.mockito.MockitoAnnotations.initMocks;

public class ChangeItemsResourceTest {

    @InjectMocks
    private ChangeItemsResource changeItemsResource = new ChangeItemsResource();

    @Mock
    private ChangeIssuesResource issues;

    @Mock
    private ChangeRequestsResource requests;

    @Mock
    private ChangeOrdersResource orders;

    @Mock
    private MilestonesResource milestones;

    @Before
    public void setup() throws Exception {
        initMocks(this);
    }

    @Test
    public void issuesTest() {
        ChangeIssuesResource _issues = changeItemsResource.issues();
        Assert.assertEquals(issues, _issues);
    }

    @Test
    public void requestsTest() {
        ChangeRequestsResource _requests = changeItemsResource.requests();
        Assert.assertEquals(requests, _requests);
    }

    @Test
    public void ordersTest() {
        ChangeOrdersResource _orders = changeItemsResource.orders();
        Assert.assertEquals(orders, _orders);
    }

    @Test
    public void milestonesTest() {
        MilestonesResource _milestones = changeItemsResource.milestones();
        Assert.assertEquals(milestones, _milestones);
    }

}

Change items resource unit tests

Change items resource unit tests


package org.knowm.xchange.bitmex.service.marketdata;

import org.junit.Before;
import org.junit.Test;
import org.knowm.xchange.ExchangeFactory;
import org.knowm.xchange.bitmex.BitmexExchange;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.dto.marketdata.OrderBook;
import org.knowm.xchange.service.marketdata.MarketDataService;

import java.io.IOException;
import java.math.BigDecimal;

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

public class BitmexOrderBookIntegration {

  public static MarketDataService marketDataService;
  public static BitmexExchange bitmexExchange;

  @Before
  public void setUp() {
    bitmexExchange = (BitmexExchange) ExchangeFactory.INSTANCE.createExchange(BitmexExchange.class.getName());
    marketDataService = bitmexExchange.getMarketDataService();
  }

  @Test
  public void getOrderBookTest() throws IOException {
    CurrencyPair pair = new CurrencyPair("XBT", "M19");
    OrderBook orderBook = marketDataService.getOrderBook(pair);

    assertThat(orderBook).isNotNull();
    assertThat(orderBook.getAsks()).isNotEmpty();
    assertThat(orderBook.getBids()).isNotEmpty();

    assertThat(orderBook.getAsks().get(0).getLimitPrice()).isGreaterThan(BigDecimal.ZERO);
    assertThat(orderBook.getAsks().get(0).getCurrencyPair()).isEqualTo(pair);

    assertThat(orderBook.getBids().get(0).getLimitPrice()).isGreaterThan(BigDecimal.ZERO);
    assertThat(orderBook.getAsks().get(0).getCurrencyPair()).isEqualTo(pair);
  }

}

Add test for order book

[Bitmex] Add test for order book


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

import org.vertx.java.core.json.JsonObject;

import net.kuujo.vertigo.context.InstanceContext;
import net.kuujo.vertigo.function.Function;
import net.kuujo.vertigo.message.JsonMessage;
import net.kuujo.vertigo.splitter.BasicSplitter;
import net.kuujo.vertigo.splitter.Splitter;

/**
 * A Java aggregator verticle implementation.
 *
 * @author Jordan Halterman
 */
public abstract class SplitterVerticle extends VertigoVerticle<Splitter> {
  protected String aggregationField;

  @Override
  protected Splitter createComponent(InstanceContext context) {
    return new BasicSplitter(vertx, container, context);
  }

  @Override
  protected void start(Splitter splitter) {
    splitter.splitFunction(new Function<JsonMessage, Iterable<JsonObject>>() {
      @Override
      public Iterable<JsonObject> call(JsonMessage message) {
        return split(message);
      }
    });
  }

  /**
   * Splits a message into multiple sub-messages.
   *
   * @param message
   *   The message to split.
   * @return
   *   An iterable object containing split message data.
   */
  protected abstract Iterable<JsonObject> split(JsonMessage message);

}

Add splitter Java verticle implementation.


/*
 * Copyright 2017 Daniel Pedraza-Arcega
 *
 * 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.danzx.zekke;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * Application runner.
 *
 * @author Daniel Pedraza-Arcega
 */
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Add spring boot application runner

Add spring boot application runner


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// This file is a part of the 'gewt' project.
// Copyright 2016 Elmar Sonnenschein, esoco GmbH, Flensburg, Germany
//
// 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 de.esoco.ewt.layout;

import com.google.gwt.user.client.ui.CaptionPanel;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.HasWidgets;

/********************************************************************
 * A layout that groups components with an optional title/caption.
 *
 * @author eso
 */
public class GroupLayout extends GenericLayout
{
	//~ Constructors -----------------------------------------------------------

	/***************************************
	 * Creates a new instance that is based on a GWT {@link CaptionPanel}.
	 */
	public GroupLayout()
	{
	}

	//~ Methods ----------------------------------------------------------------

	/***************************************
	 * Returns a new instance of{@link FormPanel}.
	 *
	 * @see GenericLayout#createLayoutContainer()
	 */
	@Override
	public HasWidgets createLayoutContainer()
	{
		return new CaptionPanel();
	}
}

FRAMEWORK-161: Support the usage of external CSS frameworks


package annis.gui.exporter;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.Mockito.mock;

import annis.SingletonBeanStoreRetrievalStrategy;
import annis.gui.AnnisUI;
import com.github.mvysny.kaributesting.v8.MockVaadin;
import com.google.common.eventbus.EventBus;
import com.vaadin.spring.internal.UIScopeImpl;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import org.corpus_tools.annis.api.model.QueryLanguage;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.internal.util.collections.Sets;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.web.WebAppConfiguration;

@SpringBootTest
@ActiveProfiles({"desktop", "test"})
@WebAppConfiguration
@DirtiesContext(classMode = ClassMode.AFTER_CLASS)
class CSVExporterTest {

  @Autowired
  private BeanFactory beanFactory;

  @Autowired
  private CSVExporter exporter;
  private AnnisUI ui;

  @BeforeEach
  void setup() {
    UIScopeImpl.setBeanStoreRetrievalStrategy(new SingletonBeanStoreRetrievalStrategy());
    this.ui = beanFactory.getBean(AnnisUI.class);
    MockVaadin.setup(() -> ui);
  }

  @Test
  void exportFeigenblattQuery() throws IOException {
    EventBus eventBus = mock(EventBus.class);
    Writer out = new StringWriter();

    Exception ex = exporter.convertText("tok=\"Feigenblatt\"", QueryLanguage.AQL, 5, 5,
        Sets.newSet("pcc2"), null,
        "", false, out, eventBus, new HashMap<>(), ui);

    assertNull(ex);

    // Compare the generated CSV file with the ground truth
    out.close();
    String[] lines = out.toString().split("\n");
    assertEquals(3, lines.length);
    assertEquals("1_id\t1_span\t1_anno_tiger::lemma\t1_anno_tiger::morph\t1_anno_tiger::pos",
        lines[0]);
    assertEquals("salt:/pcc2/11299#tok_1\tFeigenblatt\tFeigenblatt\tNom.Sg.Neut\tNN", lines[1]);
    assertEquals("salt:/pcc2/11299#tok_143\tFeigenblatt\tFeigenblatt\tDat.Sg.Neut\tNN", lines[2]);
  }

}

Add more specific test for CSV exporter

Add more specific test for CSV exporter


package leetcode.pascals_triangle;

import java.util.ArrayList;

public class Solution {
    public ArrayList<ArrayList<Integer>> generate(int numRows) {
        ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>();
        for(int i = 0; i < numRows; i++){
        	ArrayList<Integer> tmp = new ArrayList<Integer>();
        	for(int j = 0; j <= i; j++){
        		if(j == 0){
        			tmp.add(1);
        		}else if(j < i){
        			tmp.add(ans.get(i - 1).get(j - 1) + ans.get(i - 1).get(j));
        		}else{
        			tmp.add(1);
        		}
        	}
        	ans.add(tmp);
        }
        return ans;
    }

    public static void main(String[] args){
    	ArrayList<ArrayList<Integer>> ans = new Solution().generate(0);
    	for(ArrayList<Integer> row : ans){
    		for(int x : row){
    			System.err.print(x + ", ");
    		}
    		System.err.println("");
    	}
    }
}

Add java solution for 118. Pascal's Triangle

118. Pascal's Triangle: https://leetcode.com/problems/pascals-triangle/


package au.com.codeka.warworlds.game.starfield;

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

import org.andengine.entity.primitive.DrawMode;
import org.andengine.entity.primitive.Mesh;
import org.andengine.entity.scene.Scene;
import org.andengine.opengl.vbo.VertexBufferObjectManager;

import au.com.codeka.common.PointCloud;
import au.com.codeka.common.Triangle;
import au.com.codeka.common.Vector2;
import au.com.codeka.common.Voronoi;
import au.com.codeka.controlfield.ControlField;
import au.com.codeka.warworlds.model.Sector;

/** Represents the ControlField used by the tactical view. */
class TacticalControlField extends ControlField {
  private ArrayList<Mesh> meshes;

  public TacticalControlField(PointCloud pointCloud, Voronoi voronoi) {
    super(pointCloud, voronoi);
    meshes = new ArrayList<Mesh>();
  }

  public void updateAlpha(boolean visible, float alpha) {
    for (Mesh mesh : meshes) {
      mesh.setVisible(visible);
      mesh.setAlpha(alpha);
    }
  }

  public void addToScene(Scene scene, VertexBufferObjectManager vboManager, int colour,
      float alpha) {
    for (Vector2 pt : mOwnedPoints) {
      List<Triangle> triangles = mVoronoi.getTrianglesForPoint(pt);
      if (triangles == null) {
        continue;
      }

      float[] meshVertices = new float[(triangles.size() + 2) * Mesh.VERTEX_SIZE];
      meshVertices[Mesh.VERTEX_INDEX_X] = (float) pt.x * Sector.SECTOR_SIZE;
      meshVertices[Mesh.VERTEX_INDEX_Y] = (float) pt.y * Sector.SECTOR_SIZE;
      for (int i = 0; i < triangles.size(); i++) {
        meshVertices[(i + 1) * Mesh.VERTEX_SIZE + Mesh.VERTEX_INDEX_X] =
            (float) triangles.get(i).centre.x * Sector.SECTOR_SIZE;
        meshVertices[(i + 1) * Mesh.VERTEX_SIZE + Mesh.VERTEX_INDEX_Y] =
            (float) triangles.get(i).centre.y * Sector.SECTOR_SIZE;
      }
      meshVertices[(triangles.size() + 1) * Mesh.VERTEX_SIZE + Mesh.VERTEX_INDEX_X] =
          (float) triangles.get(0).centre.x * Sector.SECTOR_SIZE;
      meshVertices[(triangles.size() + 1) * Mesh.VERTEX_SIZE + Mesh.VERTEX_INDEX_Y] =
          (float) triangles.get(0).centre.y * Sector.SECTOR_SIZE;

      Mesh mesh = new Mesh(0.0f, 0.0f, meshVertices, triangles.size() + 2, DrawMode.TRIANGLE_FAN,
          vboManager);
      mesh.setColor(colour);
      mesh.setAlpha(alpha);
      scene.attachChild(mesh);
      meshes.add(mesh);
    }
  }
}

Move all the entities into the scene, since the scene will be created in a different thread.


package org.terasology.documentation;

import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import org.terasology.engine.module.ModuleManager;
import org.terasology.input.DefaultBinding;
import org.terasology.input.Input;
import org.terasology.input.InputType;
import org.terasology.input.RegisterBindButton;
import org.terasology.testUtil.ModuleManagerFactory;

import com.google.common.collect.TreeBasedTable;

/**
 * Enumerates all default key bindings and writes them sorted by ID to the console
 */
public class BindingScraper
{
    /**
     * @param args (ignored)
     * @throws Exception if the module environment cannot be loaded
     */
    public static void main(String[] args) throws Exception {
        ModuleManager moduleManager = ModuleManagerFactory.create();

        TreeBasedTable<String, Input, String> keyTable = TreeBasedTable.create(
                String.CASE_INSENSITIVE_ORDER,
                (i1, i2) -> Integer.compare(i1.getId(), i2.getId()));

        for (Class<?> buttonEvent : moduleManager.getEnvironment().getTypesAnnotatedWith(RegisterBindButton.class)) {
            DefaultBinding defBinding = buttonEvent.getAnnotation(DefaultBinding.class);
            if (defBinding != null) {
                if (defBinding.type() == InputType.KEY) {
                    Input input = InputType.KEY.getInput(defBinding.id());

                    RegisterBindButton info = buttonEvent.getAnnotation(RegisterBindButton.class);
                    keyTable.put(info.category(), input, info.description());
                }
            }
        }

        for (String row : keyTable.rowKeySet()) {
            System.out.println("# " + row);
            for (Entry<Input, String> entry : keyTable.row(row).entrySet()) {
                System.out.println("`" + entry.getKey().getDisplayName() + "` : " + entry.getValue());
            }
        }
    }
}

Add utility to extract default bindings from code


package GeeksforGeeksPractice;

/*
 * Link : http://www.geeksforgeeks.org/given-a-binary-tree-how-do-you-remove-all-the-half-nodes/
 */
public class _0055RemoveAllHalfNodes {
	public static void main(String[] args) {
		TreeNode tn=new TreeNode(2);
		tn.left=new TreeNode(7);
		tn.right=new TreeNode(5);
		tn.left.right=new TreeNode(6);
		tn.left.right.left=new TreeNode(1);
		tn.left.right.right=new TreeNode(11);
		tn.right.right=new TreeNode(9);
		tn.right.right.left=new TreeNode(4);
		preOrder(tn);System.out.println();
		tn=removeAllHalfNodes(tn);
		preOrder(tn);
	}

	private static TreeNode removeAllHalfNodes(TreeNode tn) {
		if(tn!=null)
		{
			tn.left=removeAllHalfNodes(tn.left);
			tn.right=removeAllHalfNodes(tn.right);
			if(tn.left==null && tn.right==null)
				return tn;
			if(tn.left==null)
			{
				TreeNode temp=tn.right;
				tn=null;
				return temp;
			}

			if(tn.right==null)
			{
				TreeNode temp=tn.left;
				tn=null;
				return temp;
			}
		}
		return tn;
	}

	private static void preOrder(TreeNode tn) {
		if(tn!=null)
		{
			System.out.print(tn.value+"->");
			preOrder(tn.left);
			preOrder(tn.right);
		}
	}

	static class TreeNode{
		TreeNode left,right;
		int value;
		public TreeNode(int value) {
			this.value=value;
		}
	}

}

Remove all half nodes completed

Remove all half nodes completed


/*
 * 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.facebook.presto.operator.aggregation;

import com.facebook.presto.spi.type.Type;
import com.facebook.presto.util.IterableTransformer;
import com.google.common.base.Predicates;

import java.util.List;

import static com.facebook.presto.operator.aggregation.ApproximateCountColumnAggregations.DOUBLE_APPROXIMATE_COUNT_AGGREGATION;
import static com.facebook.presto.spi.type.BigintType.BIGINT;

public class TestApproximateCountDoubleAggregation
        extends AbstractTestApproximateAggregationFunction
{
    @Override
    protected Type getType()
    {
        return BIGINT;
    }

    @Override
    protected Double getExpectedValue(List<Number> values)
    {
        return (double) IterableTransformer.on(values)
                .select(Predicates.notNull())
                .list()
                .size();
    }

    @Override
    public InternalAggregationFunction getFunction()
    {
        return DOUBLE_APPROXIMATE_COUNT_AGGREGATION;
    }
}

/*
 * 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.facebook.presto.operator.aggregation;

import com.facebook.presto.spi.type.Type;
import com.facebook.presto.util.IterableTransformer;
import com.google.common.base.Predicates;

import java.util.List;

import static com.facebook.presto.operator.aggregation.ApproximateCountColumnAggregations.DOUBLE_APPROXIMATE_COUNT_AGGREGATION;
import static com.facebook.presto.spi.type.DoubleType.DOUBLE;

public class TestApproximateCountDoubleAggregation
        extends AbstractTestApproximateAggregationFunction
{
    @Override
    protected Type getType()
    {
        return DOUBLE;
    }

    @Override
    protected Double getExpectedValue(List<Number> values)
    {
        return (double) IterableTransformer.on(values)
                .select(Predicates.notNull())
                .list()
                .size();
    }

    @Override
    public InternalAggregationFunction getFunction()
    {
        return DOUBLE_APPROXIMATE_COUNT_AGGREGATION;
    }
}

Fix approximate count double test

Fix approximate count double test

Use DoubleType instead of BigintType


/*
 * Copyright 2015 Ryan Gilera.
 *
 * 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.daytron.revworks.service;

import com.vaadin.data.util.sqlcontainer.connection.SimpleJDBCConnectionPool;
import java.sql.SQLException;

/**
 * A singleton class for establishing connection to the database.
 *
 * @author Ryan Gilera
 */
public class SQLConnectionManager {

    private static final long serialVersionUID = 1L;

    private SimpleJDBCConnectionPool jbdcConnectionPool = null;

    private SQLConnectionManager() {
    }

    /**
     * Returns the one and only one object of this class
     *
     * @return SQLConnectionManager object
     */
    public static SQLConnectionManager getInstance() {
        return SQLConnectionManagerHolder.INSTANCE;
    }

    /**
     * Returns {@link SimpleJDBCConnectionPool} object. Creates a new object if
     * no object is attached.
     *
     * @return SimpleJDBCConnectionPool object
     * @throws SQLException occurs whenever something went wrong to the database
     * connection
     */
    public SimpleJDBCConnectionPool connect() throws SQLException {
        if (jbdcConnectionPool == null) {
            jbdcConnectionPool = new SimpleJDBCConnectionPool(
                    "com.mysql.jdbc.Driver",
                    "jdbc:mysql://localhost/appschema",
                    "uservalidator", "sqluserpw", 2, 10);
        }

        return jbdcConnectionPool;
    }

    /**
     * A private inner class that serves as a singleton object container
     */
    private static class SQLConnectionManagerHolder {

        private static final SQLConnectionManager INSTANCE = new SQLConnectionManager();
    }
}

Refactor SQL database connection to a separate singleton class


package de.akquinet.engineering.vaadinator.model;

/**
 * Artifacts which are generated per bean.
 *
 * @author dve
 *
 */
public enum BeanArtifact {
	LIST_VIEW_IMPL, LIST_VIEW, LIST_PRES, LIST_PRES_IMPL, EDIT_VIEW_IMPL, EDIT_VIEW, EDIT_PRES, EDIT_PRES_IMPL, ADD_VIEW, ADD_VIEW_IMPL, ADD_PRES, ADD_PRES_IMPL, CHANGE_VIEW, CHANGE_VIEW_IMP, CHANGE_PRES, CHANGE_PRES_IMPL
}

Add enum for generated artifacts per bean


/*
 * $Url: $
 * $Id: $
 *
 * Copyright 1997-2005 Day Management AG
 * Barfuesserplatz 6, 4001 Basel, Switzerland
 * All Rights Reserved.
 *
 * This software is the confidential and proprietary information of
 * Day Management AG, ("Confidential Information"). You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Day.
 */
package org.apache.jackrabbit.ocm.exception;

/**
 * The InvalidQuerySyntaxException is an
 * ObjectContentManagerException thrown if the query of the
 * {@link org.apache.jackrabbit.ocm.manager.ObjectContentManager#getObjectIterator(String, String)}
 * is invalid. This exception actually wraps a standard JCR
 * javax.jcr.InvalidQueryException to make it an unchecked
 * exception. The cause of this exception will always be the original
 * InvalidQueryException and the message will always be the
 * original exception's message.
 */
public class InvalidQueryException extends ObjectContentManagerException {

    /**
     * Create an exception wrapping the given checked JCR exception
     *
     * @param cause The wrapped JCR InvalidQueryException
     */
    public InvalidQueryException(javax.jcr.query.InvalidQueryException cause) {
        super(cause.getMessage(), cause);
    }
}

/*
 * Copyright 2007 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.jackrabbit.ocm.exception;

/**
 * The InvalidQuerySyntaxException is an
 * ObjectContentManagerException thrown if the query of the
 * {@link org.apache.jackrabbit.ocm.manager.ObjectContentManager#getObjectIterator(String, String)}
 * is invalid. This exception actually wraps a standard JCR
 * javax.jcr.InvalidQueryException to make it an unchecked
 * exception. The cause of this exception will always be the original
 * InvalidQueryException and the message will always be the
 * original exception's message.
 */
public class InvalidQueryException extends ObjectContentManagerException {

    /**
     * Create an exception wrapping the given checked JCR exception
     *
     * @param cause The wrapped JCR InvalidQueryException
     */
    public InvalidQueryException(javax.jcr.query.InvalidQueryException cause) {
        super(cause.getMessage(), cause);
    }
}

Fix License Header (Thanks Christophe).

Fix License Header (Thanks Christophe).

git-svn-id: 02b679d096242155780e1604e997947d154ee04a@572356 13f79535-47bb-0310-9956-ffa450edef68


package com.google.sps.utils;

import com.google.cloud.dialogflow.v2.QueryInput;
import com.google.cloud.dialogflow.v2.QueryResult;
import com.google.cloud.dialogflow.v2.SessionName;
import com.google.cloud.dialogflow.v2.SessionsClient;
import java.io.IOException;
import com.google.cloud.dialogflow.v2.TextInput;
import com.google.cloud.dialogflow.v2.DetectIntentResponse;

/**
 * DialogFlow API Detects Intent with input text.
**/

public class TextUtils {
  public static QueryResult detectIntentStream(String text) {
    QueryResult queryResult = null;

    try (SessionsClient sessionsClient = SessionsClient.create()) {
      // Set the session name using the sessionId (UUID) and projectID (my-project-id)
      SessionName session = SessionName.of("fair-syntax-280601", "1");
        String languageCode = "en-US";

        // Set the text and language code (en-US) for the query
        TextInput.Builder textInput =
            TextInput.newBuilder().setText(text).setLanguageCode(languageCode);

        // Build the query with the TextInput
        QueryInput queryInput = QueryInput.newBuilder().setText(textInput).build();

        // Performs the detect intent request
        DetectIntentResponse response = sessionsClient.detectIntent(session, queryInput);

        // Display the query result
        queryResult = response.getQueryResult();

        System.out.println("====================");
        System.out.format("Query Text: '%s'\n", queryResult.getQueryText());
        System.out.format("Detected Intent: %s (confidence: %f)\n",
            queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence());
        System.out.format("Fulfillment Text: '%s'\n", queryResult.getFulfillmentText());

    } catch (IOException e) {
      e.printStackTrace();
    }
    return queryResult;
  }
}

Add TextUtil class to retrieve QueryResult from Dialogflow


package com.gmail.nossr50.api;

import org.bukkit.entity.Player;

import com.gmail.nossr50.datatypes.AbilityType;
import com.gmail.nossr50.util.Users;

public class AbilityAPI {

    public static boolean berserkEnabled(Player player) {
        return Users.getProfile(player).getAbilityMode(AbilityType.BERSERK);
    }

    public static boolean gigaDrillBreakerEnabled(Player player) {
        return Users.getProfile(player).getAbilityMode(AbilityType.GIGA_DRILL_BREAKER);
    }

    public static boolean greenTerraEnabled(Player player) {
        return Users.getProfile(player).getAbilityMode(AbilityType.GREEN_TERRA);
    }

    public static boolean serratedStrikesEnabled(Player player) {
        return Users.getProfile(player).getAbilityMode(AbilityType.SERRATED_STRIKES);
    }

    public static boolean skullSplitterEnabled(Player player) {
        return Users.getProfile(player).getAbilityMode(AbilityType.SKULL_SPLIITER);
    }

    public static boolean superBreakerEnabled(Player player) {
        return Users.getProfile(player).getAbilityMode(AbilityType.SUPER_BREAKER);
    }

    public static boolean treeFellerEnabled(Player player) {
        return Users.getProfile(player).getAbilityMode(AbilityType.TREE_FELLER);
    }
}

package com.gmail.nossr50.api;

import org.bukkit.entity.Player;

import com.gmail.nossr50.datatypes.AbilityType;
import com.gmail.nossr50.util.Users;

public class AbilityAPI {

    public static boolean berserkEnabled(Player player) {
        return Users.getProfile(player).getAbilityMode(AbilityType.BERSERK);
    }

    public static boolean gigaDrillBreakerEnabled(Player player) {
        return Users.getProfile(player).getAbilityMode(AbilityType.GIGA_DRILL_BREAKER);
    }

    public static boolean greenTerraEnabled(Player player) {
        return Users.getProfile(player).getAbilityMode(AbilityType.GREEN_TERRA);
    }

    public static boolean serratedStrikesEnabled(Player player) {
        return Users.getProfile(player).getAbilityMode(AbilityType.SERRATED_STRIKES);
    }

    public static boolean skullSplitterEnabled(Player player) {
        return Users.getProfile(player).getAbilityMode(AbilityType.SKULL_SPLIITER);
    }

    public static boolean superBreakerEnabled(Player player) {
        return Users.getProfile(player).getAbilityMode(AbilityType.SUPER_BREAKER);
    }

    public static boolean treeFellerEnabled(Player player) {
        return Users.getProfile(player).getAbilityMode(AbilityType.TREE_FELLER);
    }

    public static boolean isAnyAbilityEnabled(Player player) {
        for (AbilityType ability : AbilityType.values()) {
            if (Users.getProfile(player).getAbilityMode(ability)) {
                return true;
            }
        }

        return false;
    }
}

Add ability to check if any ability is enabled.


/*
 * RoIterator.java
 *
 * Author: Ming Tsang
 * Copyright (c) 2015 Ming Tsang
 * Refer to LICENSE for details
 */

package com.nkming.utils.type;

import java.util.Iterator;

/**
 * Hack in case remove is not needed and want to save some lines
 *
 * @param <T>
 */
public abstract class RoIterator<T> implements Iterator<T>
{
	@Override
	public final void remove()
	{
		throw new UnsupportedOperationException();
	}
}

Add RO hack to iterator

Add RO hack to iterator


/*
 * Copyright 2016 Max Thomas. All rights reserved.
 * See LICENSE in the project root directory.
 */
package io.maxthomas.dictum;
/**
 * Interface representing something that has {@link FlatMetadata}.
 */
public interface Metadatable {
  public FlatMetadata getMetadata();
}

Add interface for capturing metadata.

Add interface for capturing metadata.


public class Solution {

    public boolean isIsomorphic(String s, String t) {

        int[] m1 = new int[256];
        int[] m2 = new int[256];

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

            if (m1[s.charAt(i)] != m2[t.charAt(i)]) {
                return false;
            }

            m1[s.charAt(i)] = i + 1;
            m2[t.charAt(i)] = i + 1;

        }

        return true;

    }

}

Create : 205 Isomorphic Strings

Create : 205 Isomorphic Strings


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

// https://www.hackerrank.com/challenges/repeated-string/problem
public class RepeatedString {

    private static int getRepetitions(String string, char someChar) {
        int repetitions = 0;
        for (char c : string.toCharArray()) {
            if (c == someChar) {
                repetitions++;
            }
        }
        return repetitions;
    }

    private static int getRemainderRepetitions(String string, long limit, char targetChar) {
        int length = string.length();
        int remainder = Math.toIntExact(limit % length);
        int remainderRepetitions = 0;
        if (remainder > 0) {
            String substring = string.substring(0, remainder);
            remainderRepetitions = getRepetitions(substring, targetChar);
        }
        return remainderRepetitions;
    }

    public static void main(String[] args) throws IOException {
        // Read input
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String string = reader.readLine();
        long limit = Long.parseLong(reader.readLine());
        // Calculate result
        char targetChar = 'a';
        long repetitions = getRepetitions(string, targetChar);
        long times = (limit / string.length());
        int remainderRepetitions = getRemainderRepetitions(string, limit, targetChar);
        long answer = (repetitions * times) + remainderRepetitions;
        // Print result
        System.out.println(answer);
    }
}

Add solution for Repeated string problem.


/*
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

package com.mpalourdio.proxyserver;

import com.netflix.zuul.ZuulFilter;
import org.springframework.cloud.netflix.zuul.filters.ProxyRequestHelper;
import org.springframework.stereotype.Component;

@Component
public class MyFilter extends ZuulFilter {

    private final ProxyRequestHelper proxyRequestHelper;

    public MyFilter(final ProxyRequestHelper proxyRequestHelper) {
        this.proxyRequestHelper = proxyRequestHelper;
    }

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

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

    @Override
    public Object run() {
        proxyRequestHelper.addIgnoredHeaders("ignore-me");

        return null;
    }
}

Add a zuul filter example

Add a zuul filter example


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

package de.dhbw.vetaraus;

import java.util.Hashtable;
import java.util.Map;

import static org.junit.Assert.*;

public class SanitizeUtilsTest {

    @org.junit.Test
    public void testSanitizeCases() throws Exception {
        Hashtable<String, String> tests = new Hashtable<String, String>() {{
            put("","");
            put("1","_1");
            put("36-49","_36_49");
            put("3000-3999","_3000_3999");
            put(" ","_");
            put("-","_");
            put("ä","ae");
            put("ö","oe");
            put("ü","ue");
            put("ß","ss");
            put("Ä","AE");
            put("Ö","OE");
            put("Ü","UE");
            put("<","LESS");
            put(">","GREATER");
            put("<18","LESS18");
            put("<1000","LESS1000");
            put("5000 und mehr","_5000_und_mehr");
        }};

        for(Map.Entry<String, String> kv : tests.entrySet()) {
            String got = SanitizeUtils.sanitizeRecordValue(kv.getKey());
            assertEquals(got, kv.getValue());
        }
    }
}

Add unit test for SanitizeUtils

Add unit test for SanitizeUtils


import junit.framework.Test;
public class MyTestCase2 extends MyTestCase
{
	public void setUp()
	{
	}

	public void tearDown()
	{
	}

	public Test suite()
	{
		return null;
	}
}

Add a test case where it is important to call super in setUp and tearDown

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


package leetcode;

/**
 * https://leetcode.com/problems/bulb-switcher/
 */
public class Problem319 {
    public int bulbSwitch(int n) {
        // TODO
        return 0;
    }

    public static void main(String[] args) {
        Problem319 prob = new Problem319();
        System.out.println(prob.bulbSwitch(3)); // 1
    }
}

Add a skeleton for problem 319

Add a skeleton for problem 319


package ch.rasc.eds.starter.config;

import java.util.List;

import org.bson.BsonReader;
import org.bson.BsonWriter;
import org.bson.codecs.Codec;
import org.bson.codecs.DecoderContext;
import org.bson.codecs.EncoderContext;
import org.bson.codecs.configuration.CodecProvider;
import org.bson.codecs.configuration.CodecRegistry;

@SuppressWarnings({ "unchecked", "rawtypes" })
public final class ListCodec implements Codec<List> {
	private final CodecRegistry codecRegistry;

	public static class Provider implements CodecProvider {

		@Override
		public <T> Codec<T> get(Class<T> clazz, CodecRegistry registry) {
			if (List.class.isAssignableFrom(clazz)) {
				return (Codec<T>) new ListCodec(registry);
			}
			return null;
		}
	}

	public ListCodec(CodecRegistry codecRegistry) {
		this.codecRegistry = codecRegistry;
	}

	@Override
	public void encode(BsonWriter writer, List value, EncoderContext encoderContext) {
		if (value != null && !value.isEmpty()) {
			writer.writeStartArray();
			for (Object a : value) {
				if (a != null) {
					Codec codec = this.codecRegistry.get(a.getClass());
					encoderContext.encodeWithChildContext(codec, writer, a);
				}
				else {
					writer.writeNull();
				}
			}
			writer.writeEndArray();
		}
		else {
			writer.writeNull();
		}
	}

	@Override
	public List decode(BsonReader reader, DecoderContext decoderContext) {
		throw new UnsupportedOperationException("this codec is only used for encoding");
	}

	@Override
	public Class<List> getEncoderClass() {
		return List.class;
	}
}

Refactor updating user. Use updateOne instead of replaceOne


package problems;

import java.util.Stack;

public class LargestRectangleInHistogram {
    public int largestRectangleArea(int[] height) {
        int max = 0, i = 0;
        Stack<Integer> S = new Stack<Integer>();
        while (i <= height.length) {
            if (i == height.length && S.empty())
                i++;
            else if (i < height.length && (S.empty() || height[S.peek()] < height[i])) {
                S.push(i);
                i++;
            } else {
                int t = S.pop();
                max = Math.max(max, height[t] * (S.empty() ? i : i - S.peek() - 1));
            }
        }
        return max;
    }

    public static void main (String[] args) {
        LargestRectangleInHistogram lr = new LargestRectangleInHistogram();

        int[] height = {2,1,5,6,2,3};

        System.out.println(lr.largestRectangleArea(height));
    }
}

Add Largest Rectangle in Historgram

Add Largest Rectangle in Historgram


import regex.Matcher;
import regex.Pattern;

public class Regex {
  private static void expect(boolean v) {
    if (! v) throw new RuntimeException();
  }

  private static Matcher getMatcher(String regex, String string) {
    return Pattern.compile(regex).matcher(string);
  }

  private static void expectMatch(String regex, String string) {
    expect(getMatcher(regex, string).matches());
  }

  private static void expectNoMatch(String regex, String string) {
    expect(!getMatcher(regex, string).matches());
  }

  public static void main(String[] args) {
    expectMatch("a(bb)?a", "abba");
    expectNoMatch("a(bb)?a", "abbba");
    expectNoMatch("a(bb)?a", "abbaa");
  }
}

Add a unit test for the regular expression engine

We still do not parse the regular expression patterns, but we can at
least test that the hardcoded 'a(bb)+a' works as expected.

This class will be extended as we support more and more features.

Signed-off-by: Johannes Schindelin <53fb8db7833fca1e1746dd8592f61048d350f64c@gmx.de>


package de.ddb.pdc.metadata;

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

/**
 * class for utilities methods of metadata
 */
public class MetadataUtils {

  /**
   * @param string  input for regex
   * @param regex   for use
   * @return        the first string applied by regex or an empty string
   */
  public static String useRegex(String string, String regex) {
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(string);
    if (matcher.find()) {
      return matcher.group(0);
    }
    return "";
  }
}

Change Utitlity to new Class

Change Utitlity to new Class


/*
 * #%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;

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

/**
 * Abstract superclass for {@link FunctionOp} implementations.
 *
 * @author Curtis Rueden
 */
public abstract class AbstractFunctionOp<I, O> implements FunctionOp<I, O> {

	// -- Parameters --

	@Parameter(type = ItemIO.OUTPUT)
	private O out;

	@Parameter
	private I in;

	// -- Runnable methods --

	@Override
	public void run() {
		out = compute(getInput());
	}

	// -- Input methods --

	@Override
	public I getInput() {
		return in;
	}

	@Override
	public void setInput(final I input) {
		in = input;
	}

	// -- Output methods --

	@Override
	public O getOutput() {
		return out;
	}

	// -- Threadable methods --

	@Override
	public FunctionOp<I, O> getIndependentInstance() {
		// NB: We assume the op instance is thread-safe by default.
		// Individual implementations can override this assumption if they
		// have state (such as buffers) that cannot be shared across threads.
		return this;
	}

}

Add abstract base class for FunctionOps

Add abstract base class for FunctionOps


/*
 * 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.
 */

/**
 *
 * @author salifu
 */
//imports
import model.*;
//end of imports
public class Mate {

    public static void main(String args[]){

        Location loc = new Location("loc2323", "Hall 218");
        Comment com = new Comment("com1", "group","I am loving my code!", "5-12-2014");
        System.out.println(loc.getid()+" "+ loc.getname());
        System.out.println();
        loc.setname("Hall 155");
        System.out.println(loc.getid()+" "+ loc.getname());

        System.out.println(com.getkind()+" "+com.getcomment());
        com.setkind("member");
        com.setcomment("I am happy");
        System.out.println(com.getkind()+" "+com.getcomment());

}

}

Test so far show my code works perfectly


//
// $Id: PatchException.java,v 1.1 2003/08/09 00:31:27 mdb Exp $

package com.threerings.resource;

import java.io.IOException;

/**
 * An exception thrown when we fail to patch one or more updated files.
 */
public class PatchException extends IOException
{
    public PatchException (String msg)
    {
        super(msg);
    }
}

Throw a particular exception when we fail to patch bundles.

git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@2757 542714f4-19e9-0310-aa3c-eee0fc999fb1


package co.kaush.mystarterapp.myappmodule.utils;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;

import java.util.List;

public class IntentUtils {

    /**
     * Indicates whether the specified action can be used as an intent. This
     * method queries the package manager for installed packages that can
     * respond to an intent with the specified action. If no suitable package is
     * found, this method returns false.
     *
     * @param context The application's environment.
     * @param action The Intent action to check for availability.
     *
     * @return True if an Intent with the specified action can be sent and
     *         responded to, false otherwise.
     */
    public static boolean isIntentAvailable(Context context, String action) {
        final PackageManager packageManager = context.getPackageManager();
        final Intent intent = new Intent(action);
        List<ResolveInfo> list =
                packageManager.queryIntentActivities(intent,
                                                     PackageManager.MATCH_DEFAULT_ONLY);
        return list.size() > 0;
    }
}

Add an Intent Utils library

feat: Add an Intent Utils library


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

import hudson.Extension;

import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;

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

import jenkins.model.Configuration;
import jenkins.model.Jenkins;

/**
 * {@link Lifecycle} that delegates the responsibility to restart Jenkins to an external
 * watchdog such as SystemD or OpenRC.
 *
 * <p>
 * Restart by exit with specific code.
 *
 * @author Alon Bar-Lev
 */
@Restricted(NoExternalUse.class)
@Extension
public class ExitLifecycle extends Lifecycle {

    private static final Logger LOGGER = Logger.getLogger(ExitLifecycle.class.getName());

    private static final String EXIT_CODE_ON_RESTART = "exitCodeOnRestart";
    private static final String DEFAULT_EXIT_CODE = "5";

    private Integer exitOnRestart;

    public ExitLifecycle() {
        exitOnRestart = Integer.parseInt(Configuration.getStringConfigParameter(EXIT_CODE_ON_RESTART, DEFAULT_EXIT_CODE));
    }

    @Override
    public void restart() {
        Jenkins jenkins = Jenkins.getInstanceOrNull(); // guard against repeated concurrent calls to restart

        try {
            if (jenkins != null) {
                jenkins.cleanUp();
            }
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "Failed to clean up. Restart will continue.", e);
        }

        System.exit(exitOnRestart);
    }
}

[JENKINS-47043] Introduce exit lifecycle to exit instead of restart

If hudson.lifecycle.ExitLifecycle is selected, jenkins will exit when
restart is requested. Exit code is taken out of
jenkins.model.Jenkins.exitCodeOnRestart, default is 5.

This is usable when there is an external watchdog such as SystemD.

SystemD service example:

   ExecStart=@/usr/bin/java jenkins $JAVA_OPTIONS -DJENKINS_HOME=${JENKINS_HOME} -Dhudson.lifecycle=hudson.lifecycle.ExitLifecycle -Djenkins.model.Jenkins.exitCodeOnRestart=55 -jar $JENKINS_WAR --debug=${JENKINS_DEBUG_LEVEL} --httpPort=${JENKINS_PORT} --httpListenAddress=${JENKINS_LISTEN_ADDRESS} $JENKINS_ARGS

Signed-off-by: Alon Bar-Lev <bb308b7fcc6eb1364576b94f9dfcd9006c6c579d@gmail.com>


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

package algorithm.boj;

import java.io.*;

/**
 * Created by haeun on 2017-09-20
 * Site       : https://www.acmicpc.net/problem/2741
 */
public class Boj2741 {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        for(int i=1; i<=n; i++){
            System.out.println(i);
        }
    }

}

Solve No.2741 from Baekjoon Online Judge


package com.battlelancer.seriesguide.beta.test;

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

import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.test.AndroidTestCase;

import com.battlelancer.seriesguide.ui.SeriesGuidePreferences;
import com.battlelancer.seriesguide.util.SimpleCrypto;
import com.battlelancer.seriesguide.util.Utils;

import java.io.File;

public class SimpleCryptoTest extends AndroidTestCase {

    private static final String CLEARTEXT = "This1s@Passw0rd";
    private static final String DATACORE = "datacore";

    public SimpleCryptoTest() {
        super();
    }

    @Override
    protected void setUp() throws Exception {
        super.setUp();

        // Delete seed
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
        prefs.edit().putString(SeriesGuidePreferences.KEY_SECURE, null).commit();

        // Delete keystore file
        getContext().deleteFile(DATACORE);
    }

    @Override
    public void testAndroidTestCaseSetupProperly() {
        super.testAndroidTestCaseSetupProperly();

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
        assertThat(prefs.getString(SeriesGuidePreferences.KEY_SECURE, null)).isNull();

        File filesDir = getContext().getFilesDir();
        File[] listFiles = filesDir.listFiles();
        for (File file : listFiles) {
            if (DATACORE.equals(file.getName())) {
                fail("Keystore file still exists.");
            }
        }
    }

    public void testClearTextEncryption() {
        String encrypted = SimpleCrypto.encrypt(CLEARTEXT, getContext());

        String decrypted = SimpleCrypto.decrypt(encrypted, getContext());

        assertThat(decrypted).isEqualTo(CLEARTEXT);
    }

    public void testHashEncryption() {
        String hash = Utils.toSHA1(CLEARTEXT.getBytes());

        String encrypted = SimpleCrypto.encrypt(hash, getContext());

        String decrypted = SimpleCrypto.decrypt(encrypted, getContext());

        assertThat(decrypted).isEqualTo(hash);
    }
}

Add SimpleCrypto test back, rewritten for new implementation.


package com.techhounds.commands.auton;

import com.techhounds.subsystems.DriveSubsystem;

import edu.wpi.first.wpilibj.PIDController;
import edu.wpi.first.wpilibj.PIDOutput;
import edu.wpi.first.wpilibj.PIDSource;
import edu.wpi.first.wpilibj.PIDSourceType;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.networktables.NetworkTable;

/**
 *
 */
public class VisionAlignToTarget extends Command implements PIDSource, PIDOutput {

	private DriveSubsystem drive;
	private double offAngle = 0;
	private PIDController pid;
	private NetworkTable netTable;

    public VisionAlignToTarget() {
        drive = DriveSubsystem.getInstance();
        requires(drive);

        pid = new PIDController(0, 0, 0, this, this);
        pid.setOutputRange(-1, 1);
    }

    // Called just before this Command runs the first time
    protected void initialize() {
    	NetworkTable.setServerMode();
    	NetworkTable.initialize();
    	netTable = NetworkTable.getTable("SmartDashboard");

    	if(netTable != null) {
    		offAngle = netTable.getNumber("OffCenterDegreesX", 0);
    	}

    	pid.setSetpoint(offAngle);
    	pid.enable();
    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
    }

    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
        return pid.onTarget();
    }

    // Called once after isFinished returns true
    protected void end() {
    	pid.disable();
    }

    // Called when another command which requires one or more of the same
    // subsystems is scheduled to run
    protected void interrupted() {
    }

	@Override
	public void pidWrite(double output) {
		drive.setLeftPower(-output);
		drive.setRightPower(output);
	}

	@Override
	public void setPIDSourceType(PIDSourceType pidSource) {
		// TODO Auto-generated method stub

	}

	@Override
	public PIDSourceType getPIDSourceType() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public double pidGet() {
		return offAngle;
	}

	/*
	 * if angle is positive,
	 * we need to rotate to the left (counterclockwise)
	 * thus left power should be negative, right power should be positive
	 */
}

Add command to align robot based on camera angle


package com.gmail.nossr50.chat;

import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;

import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.party.Party;
import com.gmail.nossr50.events.chat.McMMOPartyChatEvent;
import com.gmail.nossr50.locale.LocaleLoader;

public class PartyChatManager extends ChatManager {
    private Party party;

    protected PartyChatManager(Plugin plugin) {
        super(plugin, Config.getInstance().getPartyDisplayNames(), "Commands.Party.Chat.Prefix");
    }

    public void setParty(Party party) {
        this.party = party;
    }

    @Override
    public void handleChat(String senderName, String displayName, String message, boolean isAsync) {
        handleChat(new McMMOPartyChatEvent(plugin, senderName, displayName, party.getName(), message, isAsync));
    }

    @Override
    protected void sendMessage() {
        for (Player member : party.getOnlineMembers()) {
            member.sendMessage(LocaleLoader.getString("Commands.Party.Chat.Prefix", displayName) + message);
        }

        plugin.getLogger().info("[P](" + party.getName() + ")" + "<" + ChatColor.stripColor(displayName) + "> " + message);
    }
}

package com.gmail.nossr50.chat;

import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;

import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.party.Party;
import com.gmail.nossr50.events.chat.McMMOPartyChatEvent;

public class PartyChatManager extends ChatManager {
    private Party party;

    protected PartyChatManager(Plugin plugin) {
        super(plugin, Config.getInstance().getPartyDisplayNames(), "Commands.Party.Chat.Prefix");
    }

    public void setParty(Party party) {
        this.party = party;
    }

    @Override
    public void handleChat(String senderName, String displayName, String message, boolean isAsync) {
        handleChat(new McMMOPartyChatEvent(plugin, senderName, displayName, party.getName(), message, isAsync));
    }

    @Override
    protected void sendMessage() {
        for (Player member : party.getOnlineMembers()) {
            member.sendMessage(message);
        }

        plugin.getLogger().info("[P]<" + party.getName() + ">" + message);
    }
}

Fix duplicate prefix sending with party chat & logging.


package ie.omk.smpp.event;

import ie.omk.smpp.Connection;
import ie.omk.smpp.message.SMPPPacket;
import junit.framework.TestCase;

/**
 * @version $Id:$
 */
public class SimpleEventDispatcherTest extends TestCase {

    public void testGrowArray() {
        SimpleEventDispatcher dispatcher = new SimpleEventDispatcher();
        assertEquals(SimpleEventDispatcher.INCREMENT, dispatcher.capacity());
        assertEquals(0, dispatcher.size());
        for (int i = 0; i < SimpleEventDispatcher.INCREMENT + 1; i++) {
            dispatcher.addObserver(new TestConnectionObserver());
        }
        assertEquals(
                SimpleEventDispatcher.INCREMENT * 2, dispatcher.capacity());
        assertEquals(SimpleEventDispatcher.INCREMENT + 1, dispatcher.size());
    }

    public void testAddObserver() {
        SimpleEventDispatcher dispatcher = new SimpleEventDispatcher();
        TestConnectionObserver observer = new TestConnectionObserver();
        dispatcher.addObserver(observer);
        assertTrue(dispatcher.contains(observer));
        assertSame(observer, dispatcher.observerIterator().next());
    }

    public void testAddObserverDetectsDuplicates() {
        SimpleEventDispatcher dispatcher = new SimpleEventDispatcher();
        TestConnectionObserver observer = new TestConnectionObserver();
        dispatcher.addObserver(observer);
        assertEquals(1, dispatcher.size());
        dispatcher.addObserver(observer);
        assertEquals(1, dispatcher.size());
    }

    public void testRemove() {
        TestConnectionObserver ob1 = new TestConnectionObserver();
        TestConnectionObserver ob2 = new TestConnectionObserver();
        TestConnectionObserver ob3 = new TestConnectionObserver();
        TestConnectionObserver ob4 = new TestConnectionObserver();

        SimpleEventDispatcher dispatcher = new SimpleEventDispatcher();
        dispatcher.addObserver(ob1);
        dispatcher.addObserver(ob2);
        dispatcher.addObserver(ob3);
        dispatcher.addObserver(ob4);
        assertEquals(4, dispatcher.size());

        dispatcher.removeObserver(ob2);
        dispatcher.removeObserver(ob3);
        assertTrue(dispatcher.contains(ob1));
        assertFalse(dispatcher.contains(ob2));
        assertFalse(dispatcher.contains(ob3));
        assertTrue(dispatcher.contains(ob4));

        dispatcher.removeObserver(ob1);
        assertEquals(1, dispatcher.size());
        assertFalse(dispatcher.contains(ob1));
        assertFalse(dispatcher.contains(ob2));
        assertFalse(dispatcher.contains(ob3));
        assertTrue(dispatcher.contains(ob4));
    }

    private class TestConnectionObserver implements ConnectionObserver {
        public void packetReceived(Connection source, SMPPPacket packet) {
        }
        public void update(Connection source, SMPPEvent event) {
        }
    }
}

Add a unit test for SimpleEventDispatcher.


package io.sigpipe.sing.dataset;

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

import io.sigpipe.sing.dataset.feature.Feature;
import io.sigpipe.sing.stat.RunningStatistics;

public class TickEvaluator {

    private Quantizer quantizer;
    private Map<Feature, RunningStatistics> statMap = new HashMap<>();

    public TickEvaluator(Quantizer quantizer) {
        this.quantizer = quantizer;
    }

    public void train(List<Feature> features) {
        for (Feature feature : features) {
            Feature q = quantizer.quantize(feature);
            RunningStatistics rs = statMap.get(q);
            if (rs == null) {
                rs = new RunningStatistics();
                statMap.put(q, rs);
            }
            rs.put(feature.getDouble());
        }
    }

    public void evaluate(List<Feature> features) {

    }
}

Add class to evaluate tick mark errors

Add class to evaluate tick mark errors


/*
 * 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 java.text;

import org.apache.harmony.luni.util.NotImplementedException;

/**
 * This class provider Unicode Normalization functions, which transform Unicode
 * text into an equivalent composed or decomposed form, allowing for easier
 * sorting and searching of text.
 *
 * @since 1.6
 */
public final class Normalizer {

    /**
     * This enum providers constants of normalization forms defined in Unicode
     * Standard Annex #15 Unicode Normalization Forms.
     *
     * @since 1.6
     */
    public static enum Form {
        /**
         * Canonical decomposition.
         */
        NFD,
        /**
         * Canonical decomposition followed by canonical composition.
         */
        NFC,
        /**
         * Compatibility decomposition.
         */
        NFKD,
        /**
         * Compatibility decomposition followed by canonical composition.
         */
        NFKC
    }

    /**
     * Normalize the given sequence of char src according to the
     * specified normalization form.
     *
     * @param src
     *            The sequence of char values.
     * @param form
     *            The specified normalization form.
     * @return The normalized String
     *
     * @exception NullPointerException
     *                If src or form is null.
     */
    public static String normalize(CharSequence src, Form form) {
        throw new NotImplementedException();
    }

    /**
     * Test wheather the given sequence of char src is normalized
     * according to the specified normalization form.
     *
     * @param src
     *            The sequence of char values.
     * @param form
     *            The specified normalization form.
     * @return true if src is normalized; false otherwise.
     *
     * @exception NullPointerException
     *                If src or form is null.
     */
    public static boolean isNormalized(CharSequence src, Form form) {
        throw new NotImplementedException();
    }
}

Apply for HARMONY-5740,  Sorry for the inconvenience that caused.

svn path=/harmony/; revision=650365


package algorithms.dp;

/**
 * Created by sudharti on 5/26/17.
 */
public class EggDroppingProblem {
  public int minAttemptsRecursive(int floors, int eggs) {
    if (floors == 0 || floors == 1) {
      return floors;
    } else if (eggs == 1) {
      return floors;
    } else {
      int min = Integer.MAX_VALUE;
      for (int i = 1; i <= floors; i++) {
        min = Math.min(min, Math.max(1 + minAttemptsRecursive(i - 1, eggs - 1),
                1 + minAttemptsRecursive(floors - i, eggs)));
      }
      return min;
    }
  }

  public int minAttemptsDP(int floors, int eggs) {
    int[][] results = new int[eggs + 1][floors + 1];
    for (int i = 1; i < results[0].length; i++) {
      results[1][i] = i;
    }

    for (int i = 2; i < (eggs + 1); i++) {
      for (int j = 1; j < (floors + 1); j++) {
        if (i > j) {
          results[i][j] = j;
        } else {
          int min = Integer.MAX_VALUE;
          for (int k = 1; k <= j; k++) {
            min = Math.min(min, Math.max((1 + results[i - 1][k - 1]), (1 + results[i][j - k])));
          }
          results[i][j] = min;
        }
      }
    }

    return results[eggs][floors];
  }
}

Add solution for EggDropping problem

Add solution for EggDropping problem


/*
 * Copyright (C) 2016 Michael Rozumyanskiy
 *
 * 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.michaelrocks.libphonenumber.android;

import android.content.res.AssetManager;

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

public class AssetsMetadataLoader implements MetadataLoader {
  private final AssetManager assetManager;

  public AssetsMetadataLoader(final AssetManager assetManager) {
    this.assetManager = assetManager;
  }

  @Override
  public InputStream loadMetadata(final String metadataFileName) {
    String assetFileName = metadataFileName.substring(1);
    try {
      return assetManager.open(assetFileName);
    } catch (final IOException exception) {
      return null;
    }
  }
}

Add a metadata loader that loads data from assets


package leetcode.pascals_triangle_ii;

import java.util.ArrayList;

public class Solution {
    public ArrayList<Integer> getRow(int rowIndex) {
        ArrayList<Integer> ary = new ArrayList<Integer>();
        long C = 1;
        ary.add((int)C);
        for(int i = 1; i <= rowIndex; i++){
        	C *= rowIndex + 1 - i;
        	C /= i;
        	ary.add((int)C);
        }
        return ary;
    }

    public static void main(String[] args){
    	for(int x : new Solution().getRow(20)){
    		System.err.print(x + ", ");
    	}
    	System.err.println("");
    }
}

Add java solution for 119. Pascal's Triangle II

119. Pascal's Triangle II: https://leetcode.com/problems/pascals-triangle-ii/


/*
 * 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.msbaudiosteganography.text;

/**
 *
 * @author Afina, Meisyal, Irfan
 */

public class TextProcessor {
    public byte[] binaryStringToBytes(String binary) {
        byte[] buffer = new byte[binary.length()];

        for (int i = 0; i < binary.length(); i++) {
            if (binary.charAt(i) == '0') {
                buffer[i] = 0;
            } else {
                buffer[i] = 1;
            }
        }

        return buffer;
    }

    public String stringToBinaryString(String message) {
        String buffer = new String();

        for (int i = 0; i < message.length(); i++) {
            String bit = Integer.toBinaryString(message.charAt(i));

            if (bit.length() < 8) {
                bit = "00000000".substring(0, 8 - bit.length()).concat(bit);
            } else {
                bit = bit.substring(bit.length() - 8);
            }

            buffer = buffer.concat(bit);
        }

        return buffer;
    }

    public byte[] convertBinaryStringToBytes(String message) {
        return binaryStringToBytes(stringToBinaryString(message));
    }
}

Add binary string to byte converter

Add binary string to byte converter


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

package org.jboss.msc.service;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * A utility class for service actions.
 *
 * @author David M. Lloyd
 */
public final class ServiceUtils {

    private ServiceUtils() {
    }

    /**
     * Undeploy all the controllers and call the given runnable task when complete.
     *
     * @param completeTask the complete task
     * @param controllers the controllers to undeploy
     */
    public static void undeployAll(Runnable completeTask, ServiceController<?>... controllers) {
        undeployAll(completeTask, Arrays.asList(controllers));
    }

    /**
     * Undeploy all the controllers and call the given runnable task when complete.  The given controllers list
     * should not be modified while this method runs, or the results will be undefined.
     *
     * @param completeTask the complete task
     * @param controllers the controllers to undeploy
     */
    public static void undeployAll(final Runnable completeTask, final List<ServiceController<?>> controllers) {
        final AtomicInteger cnt = new AtomicInteger(controllers.size());
        final AbstractServiceListener<Object> listener = new AbstractServiceListener<Object>() {
            public void listenerAdded(final ServiceController<? extends Object> serviceController) {
                serviceController.setMode(ServiceController.Mode.NEVER);
            }

            public void serviceStopped(final ServiceController<? extends Object> serviceController) {
                serviceController.remove();
            }

            public void serviceRemoved(final ServiceController<? extends Object> serviceController) {
                if (cnt.decrementAndGet() == 0) {
                    completeTask.run();
                }
            }
        };
        for (ServiceController<?> controller : controllers) {
            controller.addListener(listener);
        }
    }
}

Add util class for services.

Add util class for services.


package model.transform;

/**
 * Base class for image transformation tasks.
 */
public class ImageTransformTask extends TransformTask {

    ImageTransformTask() {
    }

    ImageTransformTask(String name) {
        super(name);
    }
}

Add TransformTask subclass for image transforms


package org.jpos.iso;

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

import org.junit.jupiter.api.Test;

public final class ServiceCodeTest {

    @Test
    public void nullServiceCode() {
        assertThrows(NullPointerException.class, () -> {
            @SuppressWarnings("unused")
            ServiceCode sc = new ServiceCode(null);
        });
    }

    @Test
    public void invalidLengthServiceCode() {
        assertThrows(IllegalArgumentException.class, () -> {
            @SuppressWarnings("unused")
            ServiceCode sc = new ServiceCode("1234");
        });
    }

    @Test
    public void invalidServiceCode12E() {
        assertThrows(IllegalArgumentException.class, () -> {
            @SuppressWarnings("unused")
            ServiceCode sc = new ServiceCode("12E");
        });
    }

    @Test
    public void invalidServiceCodeSign22() {
        assertThrows(IllegalArgumentException.class, () -> {
            @SuppressWarnings("unused")
            ServiceCode sc = new ServiceCode("+22");
        });
    }

    @Test
    public void validLengthServiceCode() {
        @SuppressWarnings("unused")
        ServiceCode sc = new ServiceCode("201");
    }

    @Test
    public void testServiceCode201() {
        ServiceCode sc = new ServiceCode("201");
        assertTrue(sc.isICC(), "Service code should be ICC");
        assertTrue(sc.hasNoRestrictions(), "Service code should have no restrictions");
        assertTrue(sc.isInternational(), "Service code should be international");
        assertTrue(sc.isNormalAuthorization(), "Service code should be normal authorization");
        assertFalse(sc.isPINRequired(), "Service code should not require PIN");
        assertFalse(sc.isPrivate(), "Service code should not be private");
        assertFalse(sc.isNational(), "Service code should not be national");
        assertFalse(sc.isTest(), "Service code should not be test");
        assertFalse(sc.isGoodsAndServicesOnly(), "Service code should not be good and services only");
        assertFalse(sc.isATMOnly(), "Service code should not be ATM only");
        assertFalse(sc.isCashOnly(), "Service code should not be cash only");
    }
}

Add unit tests for 'ServiceCode'.

Add unit tests for 'ServiceCode'.


/**
 * The {@code network} package contains classes implementing self-organizing
 * maps.  These classes all implement
 * {@link cs437.som.TrainableSelfOrganizingMap} in {@link cs437.som}, either
 * directly or indirectly.
 */
package cs437.som.network;

Add a package annotation to network.

Add a package annotation to network.


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

package com.dmdirc.util.validators;

import java.util.function.Function;

/**
 * Validator that uses a function to validate an input.
 */
public class BaseValidator<T> implements Validator<T> {

    private final Function<T, ValidationResponse> function;

    public BaseValidator(final Function<T, ValidationResponse> function) {
        this.function = function;
    }

    @Override
    public ValidationResponse validate(final T object) {
        return function.apply(object);
    }
}

Add a function based validator.

Add a function based validator.


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

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

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

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

  private IsEven isEven;

  @Before public void setUp() {
    isEven = new IsEven();
  }

  @Test public void shouldReturnTrueIfNumberIsZero() {
    assertTrue(isEven.check(0));
  }

  @Test public void shouldReturnTrueIfNumberIsEven() {
    assertTrue(isEven.check(68));
  }

  @Test public void shouldReturnFalseIfNumberIsOdd() {
    assertFalse(isEven.check(99));
  }
}

Add some tests to problem 68

Add some tests to problem 68


package org.apache.jmeter.functions;

import java.util.Collection;
import java.util.LinkedList;

import org.apache.jmeter.engine.util.CompoundVariable;
import org.apache.jmeter.junit.JMeterTestCase;

public class TestXPathFunction extends JMeterTestCase {

    private XPath setupXPath(String file, String expr) throws Exception{
        Collection parms = new LinkedList();
        parms.add(new CompoundVariable(file));
        parms.add(new CompoundVariable(expr));
        XPath xp = new XPath();
        xp.setParameters(parms);
        return xp;
    }

    public void testEmpty() throws Exception{
        XPath xp = setupXPath("","");
        String val=xp.execute();
        assertEquals("",val);
        val=xp.execute();
        assertEquals("",val);
        val=xp.execute();
        assertEquals("",val);
    }

    public void testNoFile() throws Exception{
        XPath xp = setupXPath("no-such-file","");
        String val=xp.execute();
        assertEquals("",val); // TODO - should check that error has been logged...
    }

    public void testFile1() throws Exception{
        XPath xp = setupXPath("testfiles/XPathTest.xml","//user/@username");
        assertEquals("u1",xp.execute());
        assertEquals("u2",xp.execute());
        assertEquals("u1",xp.execute());
    }

    public void testFile2() throws Exception{
        XPath xp1  = setupXPath("testfiles/XPathTest.xml","//user/@username");
        XPath xp1a = setupXPath("testfiles/XPathTest.xml","//user/@username");
        XPath xp2  = setupXPath("testfiles/XPathTest.xml","//user/@password");
        XPath xp2a = setupXPath("testfiles/XPathTest.xml","//user/@password");
        assertEquals("u1",xp1.execute());
        assertEquals("p1",xp2.execute());
        assertEquals("p2",xp2.execute());
        assertEquals("u2",xp1a.execute());
        assertEquals("u1",xp1.execute());
        assertEquals("u2",xp1.execute());
        assertEquals("p1",xp2a.execute());

    }
}

Add some tests for XPath function

Add some tests for XPath function

git-svn-id: https://svn.apache.org/repos/asf/jakarta/jmeter/branches/rel-2-1@379305 13f79535-47bb-0310-9956-ffa450edef68

Former-commit-id: a55023ae1e3c06a43ef86390cd8bec5cb7c4d93b


import java.util.Arrays;

public class Solution {

    public int missingNumber(int[] nums) {

        int left = 0;
        int right = nums.length;

        Arrays.sort(nums);

        while (left < right) {

            int mid = (left + right) / 2;

            if (nums[mid] > mid) {
                right = mid;
            } else {
                left = mid + 1;
            }

        }

        return left;

    }

}

Create : 268 Missing Number

Create : 268 Missing Number


package de.retest.recheck.ui.diff;

import static de.retest.recheck.ui.diff.ElementBuilder.toAttributes;
import static org.mockito.Mockito.mock;

import java.util.TreeSet;

import org.assertj.core.api.Assertions;
import org.junit.Test;

import de.retest.recheck.ui.Path;
import de.retest.recheck.ui.PathElement;
import de.retest.recheck.ui.descriptors.Attributes;
import de.retest.recheck.ui.descriptors.Element;
import de.retest.recheck.ui.descriptors.IdentifyingAttributes;
import de.retest.recheck.ui.descriptors.MutableAttributes;

public class MatchTest {

	public static final double ONE_SIMILARITY = 1.0d / IdentifyingAttributes.PERFECT_SIMILARITY;

	@Test
	public void test_better_comp_always_comes_out_first() {
		final Element comp1 = getElement( comp1.class, 1 );
		final Match match1 = new Match( 0.9d + ONE_SIMILARITY, comp1 );

		final Element comp2 = getElement( comp2.class, 2 );
		final Match match2 = new Match( 0.9d, comp2 );

		final TreeSet<Match> bestMatches = new TreeSet<>();
		bestMatches.add( match1 );
		bestMatches.add( match2 );

		Assertions.assertThat( bestMatches.pollFirst().element ).isSameAs( comp1 );
		Assertions.assertThat( bestMatches.pollFirst().element ).isSameAs( comp2 );
	}

	@Test
	public void same_score_doesnt_overwrite() {
		final Element comp1 = getElement( comp2.class, 2 );
		final Match match1 = new Match( 0.9d, comp1 );

		final Element comp2 = getElement( comp2.class, 2 );
		final Match match2 = new Match( 0.9d, comp2 );

		final TreeSet<Match> bestMatches = new TreeSet<>();
		bestMatches.add( match1 );
		bestMatches.add( match2 );

		Assertions.assertThat( bestMatches.size() ).isEqualTo( 2 );
	}

	private Element getElement( final Class<?> clazz, final int cnt ) {
		return Element.create( "id", mock( Element.class ),
				IdentifyingAttributes.create( Path.path( new PathElement( clazz.getSimpleName(), 1 ) ), clazz ),
				toAttributes( "{color=green}" ) );
	}

	private class comp1 extends Element {
		private static final long serialVersionUID = 1L;
	};

	private class comp2 extends Element {
		private static final long serialVersionUID = 1L;
	};
}

Move tests for Match from review

Move tests for Match from review


/*
 * Copyright 2005 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 to test FileServer methods
 */

package org.apache.jmeter.config;

import java.io.IOException;

import org.apache.jmeter.junit.JMeterTestCase;
import org.apache.jmeter.threads.JMeterContext;
import org.apache.jmeter.threads.JMeterContextService;
import org.apache.jmeter.threads.JMeterVariables;

public class TestCVSDataSet extends JMeterTestCase {

    public TestCVSDataSet() {
        super();
    }

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

    public void tearDown() throws IOException{
    }

    public void testopen() throws Exception {
		JMeterContext jmcx = JMeterContextService.getContext();
		jmcx.setVariables(new JMeterVariables());
		JMeterVariables threadVars = jmcx.getVariables();
    	threadVars.put("b", "value");

    	CSVDataSet csv = new CSVDataSet();
    	csv.setFilename("No.such.filename");
    	csv.setVariableNames("a,b,c");
    	csv.setDelimiter(",");
    	csv.iterationStart(null);
		assertNull(threadVars.get("a"));
		assertEquals("value",threadVars.get("b"));
		assertNull(threadVars.get("c"));

		csv = new CSVDataSet();
    	csv.setFilename("testfiles/testempty.csv");
    	csv.setVariableNames("a,b,c");
    	csv.setDelimiter(",");

    	csv.iterationStart(null);
		assertEquals("",threadVars.get("a"));
		assertEquals("b1",threadVars.get("b"));
		assertEquals("c1",threadVars.get("c"));

    	csv.iterationStart(null);
		assertEquals("a2",threadVars.get("a"));
		assertEquals("",threadVars.get("b"));
		assertEquals("c2",threadVars.get("c"));

		csv.iterationStart(null);
		assertEquals("a3",threadVars.get("a"));
		assertEquals("b3",threadVars.get("b"));
		assertEquals("",threadVars.get("c"));

		csv.iterationStart(null);
		assertEquals("a4",threadVars.get("a"));
		assertEquals("b4",threadVars.get("b"));
		assertEquals("c4",threadVars.get("c"));

    	csv.iterationStart(null); // Restart file
		assertEquals("",threadVars.get("a"));
		assertEquals("b1",threadVars.get("b"));
		assertEquals("c1",threadVars.get("c"));
    }
}

Test for CSV Data Set

Test for CSV Data Set

git-svn-id: https://svn.apache.org/repos/asf/jakarta/jmeter/branches/rel-2-1@348234 13f79535-47bb-0310-9956-ffa450edef68

Former-commit-id: 68db3d1f4154c1969100eedd818508c785992c65


package tachyon.perf.basic;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.log4j.Logger;

import tachyon.perf.conf.PerfConf;
import tachyon.perf.util.SAXConfiguration;

/**
 * Manage the configurations for each task.
 */
public class TaskConfiguration {
  public static final boolean DEFAULT_BOOLEAN = false;
  public static final int DEFAULT_INTEGER = 0;
  public static final long DEFAULT_LONG = 0;
  public static final String DEFAULT_STRING = "";
  private static final Logger LOG = Logger.getLogger("");

  private static TaskConfiguration sTaskConf = null;

  /**
   * Get the configuration.
   *
   * @param type the type of the benchmark task
   * @param fromFile if true, it will load the configuration file, otherwise it return an empty
   *        configuration.
   * @return the task configuration
   */
  public static synchronized TaskConfiguration get(String type, boolean fromFile) {
    if (sTaskConf == null) {
      if (fromFile) {
        try {
          sTaskConf =
              new TaskConfiguration(PerfConf.get().TACHYON_PERF_HOME + "/conf/testSuite/" + type
                  + ".xml");
        } catch (Exception e) {
          LOG.error("Error when parse conf/testSuite/" + type + ".xml", e);
          throw new RuntimeException("Failed to parse conf/testSuite/" + type + ".xml");
        }
      } else {
        sTaskConf = new TaskConfiguration();
      }
    }
    return sTaskConf;
  }

  private Map<String, String> mProperties;

  protected TaskConfiguration() {
    mProperties = new HashMap<String, String>();
  }

  protected TaskConfiguration(String xmlFileName) throws Exception {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    SAXParser saxParser = spf.newSAXParser();
    File xmlFile = new File(xmlFileName);
    SAXConfiguration saxConfiguration = new SAXConfiguration();
    saxParser.parse(xmlFile, saxConfiguration);
    mProperties = saxConfiguration.getProperties();
  }

  public synchronized void addProperty(String name, String value) {
    mProperties.put(name, value);
  }

  public synchronized Map<String, String> getAllProperties() {
    Map<String, String> ret = new HashMap<String, String>(mProperties.size());
    ret.putAll(mProperties);
    return ret;
  }

  public synchronized boolean getBooleanProperty(String property) {
    if (mProperties.containsKey(property)) {
      return Boolean.valueOf(mProperties.get(property));
    }
    return DEFAULT_BOOLEAN;
  }

  public synchronized int getIntProperty(String property) {
    if (mProperties.containsKey(property)) {
      return Integer.valueOf(mProperties.get(property));
    }
    return DEFAULT_INTEGER;
  }

  public synchronized long getLongProperty(String property) {
    if (mProperties.containsKey(property)) {
      return Long.valueOf(mProperties.get(property));
    }
    return DEFAULT_LONG;
  }

  public synchronized String getProperty(String property) {
    if (mProperties.containsKey(property)) {
      return mProperties.get(property);
    }
    return DEFAULT_STRING;
  }
}

Manage the configurations for each task

Manage the configurations for each task


package com.Acrobot.ChestShop.Tests;

import com.Acrobot.ChestShop.Events.PreShopCreationEvent;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import static com.Acrobot.ChestShop.Listeners.PreShopCreation.PriceChecker.onPreShopCreation;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;

/**
 * Created by Andrzej Pomirski (Acrobot)
 */
@RunWith(JUnit4.class)
public class PriceCheckerTest {

    String[] getPriceString(String prices) {
        return new String[]{null, null, prices, null};
    }

    @Test
    public void testPrice() {
        PreShopCreationEvent event = new PreShopCreationEvent(null, null, getPriceString("B 1"));
        onPreShopCreation(event);
        assertFalse(event.isCancelled());

        event = new PreShopCreationEvent(null, null, getPriceString("S 1"));
        onPreShopCreation(event);
        assertFalse(event.isCancelled());

        event = new PreShopCreationEvent(null, null, getPriceString("B 1:S 1"));
        onPreShopCreation(event);
        assertFalse(event.isCancelled());

        event = new PreShopCreationEvent(null, null, getPriceString("BS 1"));
        onPreShopCreation(event);
        assertTrue(event.isCancelled());

        event = new PreShopCreationEvent(null, null, getPriceString("B 1S0"));
        onPreShopCreation(event);
        assertTrue(event.isCancelled());
    }
}

Add a test for price checking

Add a test for price checking


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

package com.google.android.gnd.rx;

import androidx.annotation.NonNull;
import io.reactivex.Single;
import io.reactivex.functions.Consumer;
import javax.annotation.Nullable;

public class Result<T> {
  public enum State {
    SUCCESS,
    ERROR
  }

  private final State state;

  @Nullable private final T value;
  @Nullable private final Throwable error;

  private Result(State state, @Nullable T value, @Nullable Throwable error) {
    this.state = state;
    this.value = value;
    this.error = error;
  }

  public static <T> Result<T> success(@NonNull T result) {
    return new Result<>(State.SUCCESS, result, null);
  }

  public static <T> Result<T> error(@NonNull Throwable t) {
    return new Result<>(State.ERROR, null, t);
  }

  @Nullable
  public State getState() {
    return state;
  }

  @Nullable
  public T get() {
    return value;
  }

  @Nullable
  public Throwable getError() {
    return error;
  }

  public static <T> Single<Result<T>> wrap(Single<T> single) {
    return single.map(Result::success).onErrorReturn(Result::error);
  }

  public static <T> Consumer<? super Result<T>> unwrap(
      Consumer<T> onSuccess, Consumer<Throwable> onError) {
    return result -> {
      switch (result.getState()) {
        case SUCCESS:
          onSuccess.accept(result.get());
          break;
        case ERROR:
          onError.accept(result.getError());
          break;
      }
    };
  }
}

Add simple wrapper for streaming results