package com.salesforce.ide.core.internal.utils;

public final class QuietCloseable<T extends AutoCloseable> implements AutoCloseable {
    private final T resource;

    public QuietCloseable(final T resource){
        this.resource = resource;
    }

    public T get() {
        return this.resource;
    }

    @Override
    public void close() {
        try {
            resource.close();
        } catch (final Exception e) {
            // suppress exception
        }
    }

    public static final <U extends AutoCloseable> QuietCloseable<U> make(final U closable) {
        return new QuietCloseable<>(closable);
    }
}

Manage resources using try-with-resource blocks. Properly close opened resources.


package org.apache.pig.impl.logicalLayer.validators;

import org.apache.pig.impl.logicalLayer.LogicalOperator;
import org.apache.pig.impl.logicalLayer.LogicalPlan;
import org.apache.pig.impl.plan.CompilationMessageCollector;
import org.apache.pig.impl.plan.PlanValidationException;
import org.apache.pig.impl.plan.PlanValidator;

public class SchemaAliasValidator extends PlanValidator<LogicalOperator, LogicalPlan> {
    public SchemaAliasValidator() {
    }

    public void validate(LogicalPlan plan,
                         CompilationMessageCollector msgCollector)
                                        throws PlanValidationException {
        // The first msgCollector is used in visitor
        // The second msgCollector is used by the validator
        super.validateSkipCollectException(new SchemaAliasVisitor(plan),
                                           msgCollector) ;

    }
}

PIG-644: Duplicate column names in foreach do not throw parser error

git-svn-id: 8c49d51cc539c84b28b5042abd6e265f31af12f8@826816 13f79535-47bb-0310-9956-ffa450edef68


package net.ghostrealms.util;

public enum Request {

  TOWN_JOIN(1),
  TOWN_ADD(2),
  FRIEND(3);

  private final int val;

  Request(int val) {
    this.val = val;
  }

  public int getType() {
    return val;
  }
}

Enumerate values of request types stored in the database.


package org.opendroidphp.app.services;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

public class StartServiceAtBootReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {

            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);

            if (preferences.getBoolean("enable_server_on_boot", false)) {

                Intent i = new Intent(context, ServerService.class);
                context.startService(i);
            }
        }
    }
}

Connect to web server when device (re)boot


package org.slc.sli.modeling.rest;

import static org.junit.Assert.*;

import java.util.ArrayList;

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

/**
 * JUnit test for Include class.
 *
 * @author wscott
 *
 */
public class IncludeTest {

    private Include include;

    private static final ArrayList<Documentation> DOC = new ArrayList<Documentation>(0);
    private static final String HREF = "href";

    @Before
    public void setup() throws Exception {
        include = new Include(HREF, DOC);
    }

    @Test
    public void testNullHref() {
        new Include(null, DOC);
    }

    @Test
    public void testGetHref() {
        assertEquals(HREF, include.getHref());
    }

}

Add JUnit test for Include class in rest modeling module.


/*
 * Zorbage: an algebraic data hierarchy for use in numeric processing.
 *
 * Copyright (C) 2016-2018 Barry DeZonia
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
package nom.bdezonia.zorbage.procedure;

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

/**
 *
 * @author Barry DeZonia
 *
 */
public class RamplL<T extends Group<T,U> & Addition<U>,U>
	implements Procedure<U>
{
	private Ramp<T,U> lowerProc;

	public RamplL(T group, U origin, U delta) {
		this.lowerProc = new Ramp<T,U>(group, origin, delta);
	}

	@Override
	@SuppressWarnings("unchecked")
	public void call(U result, U... inputs) {
		lowerProc.call(result);
	}

}

Define a lifted Ramp procedure

Define a lifted Ramp procedure


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

import org.junit.Test;
import static org.junit.Assert.*;

/**
 *
 */
public class FileSizeTest {

    private final static long EXPECTED = 10 * 1024;
    @Test
    public void testFileSize() throws Exception {

        long value = FileSize.parse("10KB", 0);
        assertTrue("unexpected value " + value, value == EXPECTED);
        value = FileSize.parse("10 KB", 0);
        assertTrue("unexpected value " + value, value == EXPECTED);
    }
}

Verify that file sizes are parsed correctly.


/*
 * This file is part of Sponge, licensed under the MIT License (MIT).
 *
 * Copyright (c) SpongePowered <https://www.spongepowered.org>
 * Copyright (c) contributors
 *
 * 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 org.spongepowered.mod.mixin.core.forge;

import net.minecraftforge.common.DungeonHooks;
import org.spongepowered.api.entity.EntityArchetype;
import org.spongepowered.api.entity.EntityType;
import org.spongepowered.api.util.weighted.WeightedObject;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import org.spongepowered.common.SpongeImpl;
import org.spongepowered.common.entity.EntityUtil;
import org.spongepowered.common.registry.type.world.gen.DungeonMobRegistryModule;

import java.util.Optional;

@Mixin(DungeonHooks.class)
public class MixinDungeonHooks {

    @Inject(method = "addDungeonMob(Ljava/lang/String;I)F", at = @At("RETURN"), remap = false)
    protected void onAddDungeonMob(CallbackInfoReturnable<Float> ci, String name, int rarity) {
        Optional<EntityType> type = EntityUtil.fromNameToType(name);
        if (!type.isPresent()) {
            SpongeImpl.getLogger().error("Mod tried to add a DungeonMob for a non existant mob " + name +" !");
            return;
        }

        Float ret = ci.getReturnValue();
        DungeonMobRegistryModule.getInstance().put(type.get(), ret.intValue());
    }

    @Inject(method = "removeDungeonMob(Ljava/lang/String;)I", at = @At("HEAD"), remap = false)
    protected void onRemoveDungeonMob(CallbackInfoReturnable<Integer> ci, String name) {
        Optional<EntityType> type = EntityUtil.fromNameToType(name);
        if (!type.isPresent()) {
            SpongeImpl.getLogger().error("Mod tried to remove a DungeonMob for a non existant mob " + name +" !");
            return;
        }

        DungeonMobRegistryModule.getInstance().remove(type.get());
    }

}

Implement MobSpawnerData for Forge registry


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

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

// https://www.hackerrank.com/challenges/two-strings/problem
public class TwoStrings {

  private static final String YES = "YES";
  private static final String NO = "NO";

  private static Map<Character, Boolean> getMap(String string) {
    Map<Character, Boolean> map = new HashMap();
    for (Character aChar : string.toCharArray()) {
      map.put(aChar, true);
    }
    return map;
  }

  private static String hasSubString(String firstLine, String secondLine) {
    Map<Character, Boolean> chars = getMap(firstLine);
    for (Character aChar : secondLine.toCharArray()) {
      if (chars.getOrDefault(aChar, false)) {
        return YES;
      }
    }
    return NO;
  }

  /*
   * s1 = "hello"
   * s2 = "ae"
   */

  public static void main(String[] args) throws IOException {
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
      int cases = Integer.parseInt(reader.readLine());
      while (cases > 0) {
        String firstLine = reader.readLine();
        String secondLine = reader.readLine();
        String hasSubString = hasSubString(firstLine, secondLine);
        System.out.println(hasSubString);
        cases--;
      }
    }
  }
}

Add solution for 'Two strings' problem.

Add solution for 'Two strings' problem.


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

import org.jnosql.artemis.WeldJUnit4Runner;
import org.jnosql.diana.api.column.ColumnFamilyManager;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;

import javax.inject.Inject;

import static org.junit.Assert.assertNotNull;

@RunWith(WeldJUnit4Runner.class)
public class DefaultColumnRepositoryProducerTest {

    @Inject
    private ColumnRepositoryProducer producer;

    @Test(expected = NullPointerException.class)
    public void shouldReturnErrorWhenColumnFamilyManagerNull() {
        producer.get(null);
    }

    @Test
    public void shouldReturn() {
        ColumnFamilyManager manager = Mockito.mock(ColumnFamilyManager.class);
        ColumnRepository columnRepository = producer.get(manager);
        assertNotNull(columnRepository);
    }
}

Create producer test on column

Create producer test on column


package tools.devnull.trugger.factory;

import org.junit.Test;
import tools.devnull.kodo.TestScenario;
import tools.devnull.trugger.util.factory.Context;
import tools.devnull.trugger.util.factory.DefaultContext;

import java.lang.reflect.Parameter;
import java.util.function.Function;
import java.util.function.Predicate;

import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class DefaultContextTest {

  @Test
  public void testMessages() {
    Function<Parameter, Object> functionA = mock(Function.class);
    Predicate<Parameter> conditionA = mock(Predicate.class);
    Object resultA = new Object();
    when(functionA.apply(any())).thenReturn(resultA);
    when(conditionA.test(any())).thenReturn(false);

    Function<Parameter, Object> functionB = mock(Function.class);
    Predicate<Parameter> conditionB = mock(Predicate.class);
    Object resultB = new Object();
    when(functionB.apply(any())).thenReturn(resultB);
    when(conditionB.test(any())).thenReturn(true);

    TestScenario.given(new DefaultContext())

    context.use(functionA).when(conditionA).
        use(functionB).when(conditionB);

    // don't need an actual parameter since everything here is a mock
    context.resolve(null);
  }

}

Add tests for default context

Add tests for default context


package editor.util;

import java.util.function.Supplier;

public class UndoableAction<U, R>
{
    private final Supplier<R> forward;
    private final Supplier<U> reverse;

    public UndoableAction(final Supplier<R> f, final Supplier<U> r)
    {
        forward = f;
        reverse = r;
    }

    public U undo()
    {
        return reverse.get();
    }

    public R redo()
    {
        return forward.get();
    }
}

Add class for undoing generic actions

Add class for undoing generic actions


/*
 * Zorbage: an algebraic data hierarchy for use in numeric processing.
 *
 * Copyright (C) 2016-2018 Barry DeZonia
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
package nom.bdezonia.zorbage.type.data.universal;

import java.math.BigDecimal;

/**
 *
 * @author Barry DeZonia
 *
 */
public class ScientificNotation {

	/**
	 * Create a numeric value from an scientific notation description.
	 * Works in BigDecimals for accuracy. Can only create Real values.
	 * Result must support UniversalRepresentation.
	 *
	 * @param fraction
	 * @param base
	 * @param power
	 * @param result
	 */
	public static <U extends UniversalRepresentation>
		void compute(BigDecimal fraction, int base, int power, U result)
	{
		BigDecimal b = BigDecimal.valueOf(base);
		BigDecimal tmp = b.pow(power);
		BigDecimal value = tmp.multiply(fraction);
		OctonionRepresentation v = new OctonionRepresentation();
		v.setR(value);
		TensorOctonionRepresentation rep = new TensorOctonionRepresentation();
		rep.setFirstValue(v);
		result.setSelfFromTensor(rep);
	}
}

Define a way to construct real values via scientific notation


package org.parboiled.examples.doublequotedstring;

import org.parboiled.BaseParser;
import org.parboiled.Parboiled;
import org.parboiled.Rule;
import org.parboiled.annotations.BuildParseTree;
import org.parboiled.errors.ErrorUtils;
import org.parboiled.parserunners.TracingParseRunner;
import org.parboiled.support.ParseTreeUtils;
import org.parboiled.support.ParsingResult;

import java.util.Scanner;

/**
 * A simple, double quoted string matching grammar
 *
 *
This will match inputs such as:

 *
 *

 *
{@code "hello world"};

 *
{@code "hello \"world\""};

 *
{@code ""};

 *
{@code "\""}

 *

 *
 *
and so on.

 *
 *
This parser builds the parse tree (the class is annotated using {@link
 * BuildParseTree}) and uses a {@link TracingParseRunner} so that you can see
 * the parsing process in action.

 *
 *
This parser uses the {@code normal* (special normal*)*} pattern, often
 * used in regexes to "unroll the loop". In this case:

 *
 *

 *
{@code normal} is everything but a backslash or a double quote,

 *
{@code special} is the character sequence {@code '\', '"'}.

 *

 */
@BuildParseTree
public class DoubleQuotedString
    extends BaseParser<Void>
{
    Rule Normal()
    {
        return NoneOf("\\\"");
    }

    Rule Special()
    {
        return String("\\\"");
    }

    Rule NSN()
    {
        return Sequence(
            ZeroOrMore(Normal()),
            ZeroOrMore(Special(), ZeroOrMore(Normal()))
        );
    }

    Rule DoubleQuotedString()
    {
        return Sequence('"', NSN(), '"', EOI);
    }

    public static void main(final String... args)
    {
        final DoubleQuotedString parser
            = Parboiled.createParser(DoubleQuotedString.class);

        final Scanner scanner = new Scanner(System.in);
        ParsingResult<?> result;
        String line;

        while (true) {
            System.out.print("Enter a value to test (empty to quit): ");
            line = scanner.nextLine();
            if (line.isEmpty())
                break;
            result = new TracingParseRunner(parser.DoubleQuotedString())
                .run(line);
            if (result.hasErrors()) {
                System.out.println("Invalid input!");
                System.out.println(ErrorUtils.printParseErrors(result));
            } else {
                System.out.println(ParseTreeUtils.printNodeTree(result));
            }
        }
    }
}

Add a simple double quoted string parser


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

package org.springframework.boot.web.servlet;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;

import org.junit.Test;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;

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

/**
 * Tests for {@link ServletContextInitializerBeans}.
 *
 * @author Andy Wilkinson
 */
public class ServletContextInitializerBeansTests {

	private ConfigurableApplicationContext context;

	@Test
	public void servletThatImplementsServletContextInitializerIsOnlyRegisteredOnce() {
		load(ServletConfiguration.class);
		ServletContextInitializerBeans initializerBeans = new ServletContextInitializerBeans(
				this.context.getBeanFactory());
		assertThat(initializerBeans.size()).isEqualTo(1);
		assertThat(initializerBeans.iterator()).hasOnlyElementsOfType(TestServlet.class);
	}

	@Test
	public void filterThatImplementsServletContextInitializerIsOnlyRegisteredOnce() {
		load(FilterConfiguration.class);
		ServletContextInitializerBeans initializerBeans = new ServletContextInitializerBeans(
				this.context.getBeanFactory());
		assertThat(initializerBeans.size()).isEqualTo(1);
		assertThat(initializerBeans.iterator()).hasOnlyElementsOfType(TestFilter.class);
	}

	private void load(Class<?> configuration) {
		this.context = new AnnotationConfigApplicationContext(configuration);
	}

	static class ServletConfiguration {

		@Bean
		public TestServlet testServlet() {
			return new TestServlet();
		}

	}

	static class FilterConfiguration {

		@Bean
		public TestFilter testFilter() {
			return new TestFilter();
		}

	}

	static class TestServlet extends HttpServlet implements ServletContextInitializer {

		@Override
		public void onStartup(ServletContext servletContext) throws ServletException {

		}

	}

	static class TestFilter implements Filter, ServletContextInitializer {

		@Override
		public void onStartup(ServletContext servletContext) throws ServletException {

		}

		@Override
		public void init(FilterConfig filterConfig) throws ServletException {

		}

		@Override
		public void doFilter(ServletRequest request, ServletResponse response,
				FilterChain chain) throws IOException, ServletException {

		}

		@Override
		public void destroy() {

		}

	}

}

Test that double registration of ServletContextInitializers does not happen

Closes gh-4902


package de.philipphager.disclosure.database.util;

import android.database.Cursor;
import com.squareup.sqlbrite.SqlBrite;
import com.squareup.sqldelight.RowMapper;
import java.util.ArrayList;
import java.util.List;
import rx.functions.Func1;

public class CursorListMapper<T> implements Func1<SqlBrite.Query, List<T>> {
  private final RowMapper<T> rowMapper;

  public CursorListMapper(RowMapper<T> rowMapper) {
    this.rowMapper = rowMapper;
  }

  @Override public List<T> call(SqlBrite.Query query) {
    Cursor cursor = query.run();

    boolean cursorPresent = cursor != null;
    int resultSize = cursorPresent ? cursor.getColumnCount() : 0;
    List<T> items = new ArrayList<>(resultSize);

    if (cursorPresent) {
      while (cursor.moveToNext()) {
        items.add(rowMapper.map(cursor));
      }
    }

    return items;
  }
}

Add a util class to convert cursor data to lists.

Generic converter from cursor data to a list of objects.
Uses sqldelight RowMapper helper.


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

import com.github.pedrovgs.problem63.ConstantComplexityOrderStack.Stack1;
import com.github.pedrovgs.problem63.ConstantComplexityOrderStack.Stack2;
import org.junit.Before;
import org.junit.Test;

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

  private Stack1 stack1;
  private Stack2 stack2;

  @Before public void setUp() {
    stack1 = new Stack1();
    stack2 = new Stack2();
  }

  @Test public void shouldReturnMinElementInTheStack1() {
    stack1.push(1);
    stack1.push(2);
    stack1.push(3);
    stack1.push(-1);

    assertEquals(-1, stack1.getMin());
  }

  @Test public void shouldReturnMinElementInTheStack1EvenAfterModifyStackContent() {
    stack1.push(1);
    stack1.push(2);
    stack1.push(3);
    stack1.push(-1);
    stack1.pop();

    assertEquals(1, stack1.getMin());
  }
}

Add some tests to problem 63

Add some tests to problem 63


package org.broadleafcommerce.util;

public class Mod43CheckDigitUtil {

    private final static String CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%";

    public static boolean isValidCheckedValue(String value) {
        boolean valid = false;
        if (value != null && !value.isEmpty()) {
            String code = value.substring(0, value.length() - 1);
            char checkDigit = value.substring(value.length() - 1).charAt(0);
            try {
                if (generateCheckDigit(code) == checkDigit) {
                    valid = true;
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return valid;
    }

    public static char generateCheckDigit(String data) {
        // MOD 43 check digit - take the acsii value of each digit, sum them up, divide by 43. the remainder is the check digit (in ascii)
        int sum = 0;
        for (int i = 0; i < data.length(); ++i) {
            sum += CHARSET.indexOf(data.charAt(i));
        }
        int remainder = sum % 43;
        return CHARSET.charAt(remainder);
    }

    public static void main(String[] args) {
        try {
            System.out.println(generateCheckDigit("TEACH000012345"));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println(isValidCheckedValue("TEACH000012345B"));
    }
}

Add check digit util to framework to support making sure someone isn't randomly trying codes, resulting in db calls (e.g. offers)


package com.peruukki.simplecurrencyconverter;

import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.test.ActivityInstrumentationTestCase2;

import com.peruukki.simplecurrencyconverter.adapters.TabAdapter;
import com.peruukki.simplecurrencyconverter.fragments.ConvertFragment;
import com.peruukki.simplecurrencyconverter.fragments.CurrenciesFragment;

public class MainActivityTest extends ActivityInstrumentationTestCase2<MainActivity> {

    private MainActivity mMainActivity;
    private TabAdapter mTabAdapter;
    private ActionBar mActionBar;

    public MainActivityTest() {
        super(MainActivity.class);
    }

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

        mMainActivity = getActivity();

        ViewPager tabPager = (ViewPager) mMainActivity.findViewById(R.id.pager);
        mTabAdapter = (TabAdapter) tabPager.getAdapter();

        mActionBar = mMainActivity.getSupportActionBar();
    }

    public void testPreconditions() {
        assertNotNull("TabAdapter is null", mTabAdapter);
        assertNotNull("ActionBar is null", mActionBar);
    }

    public void testMainActivity_tabsCreated() {
        assertEquals("TabAdapter doesn't have 2 tabs", 2, mTabAdapter.getCount());
        assertEquals("ActionBar doesn't have 2 tabs", 2, mActionBar.getTabCount());

        assertEquals("1st tab is not instance of ConvertFragment",
            ConvertFragment.class, mTabAdapter.getItem(0).getClass());
        assertEquals("2nd tab is not instance of CurrenciesFragment",
            CurrenciesFragment.class, mTabAdapter.getItem(1).getClass());

        assertEquals("1st tab has unexpected label",
            mMainActivity.getString(R.string.tab_convert), mActionBar.getTabAt(0).getText());
        assertEquals("2nd tab has unexpected label",
            mMainActivity.getString(R.string.tab_currencies), mActionBar.getTabAt(1).getText());
    }
}

Add first tests: test that the tabs are added in MainActivity


package com.codacy.play.tomcatcp.pool;

import com.codacy.play.tomcatcp.metrics.MetricsTracker;
import com.codacy.play.tomcatcp.metrics.MetricsTrackerFactory;
import com.codacy.play.tomcatcp.metrics.PoolStats;
import com.codacy.play.tomcatcp.metrics.dropwizard.CodahaleMetricsTrackerFactory;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.health.HealthCheckRegistry;
import com.zaxxer.hikari.metrics.CodahaleHealthChecker;
import org.apache.tomcat.jdbc.pool.ConnectionPool;
import org.apache.tomcat.jdbc.pool.PoolConfiguration;

import java.sql.SQLException;

import static java.util.concurrent.TimeUnit.SECONDS;

public class TomcatCPPool extends ConnectionPool {
    private boolean isRecordMetrics;
    private MetricsTracker metricsTracker;

    public TomcatCPPool(PoolConfiguration prop) throws SQLException {
        super(prop);
    }

    public void setMetricRegistry(MetricRegistry metricRegistry) {
        this.isRecordMetrics = metricRegistry != null;
        if (isRecordMetrics) {
            setMetricsTrackerFactory(new CodahaleMetricsTrackerFactory(metricRegistry));
        } else {
            setMetricsTrackerFactory(null);
        }
    }

    public void setMetricsTrackerFactory(MetricsTrackerFactory metricsTrackerFactory) {
        this.isRecordMetrics = metricsTrackerFactory != null;
        if (isRecordMetrics) {
            this.metricsTracker = metricsTrackerFactory.create(getName(), getPoolStats());
        } else {
            this.metricsTracker = new MetricsTracker();
        }
    }

    public void setHealthCheckRegistry(HealthCheckRegistry healthCheckRegistry) {
        if (healthCheckRegistry != null) {
            //CodahaleHealthChecker.registerHealthChecks(this, config, healthCheckRegistry);
        }
    }

    @Override
    protected void close(boolean force) {
        try {
            super.close(force);
        } finally {
            metricsTracker.close();
        }
    }

    private PoolStats getPoolStats() {
        return new PoolStats(SECONDS.toMillis(1)) {
            @Override
            protected void update() {
                this.pendingThreads = TomcatCPPool.this.getWaitCount();
                this.idleConnections = TomcatCPPool.this.getIdle();
                this.totalConnections = TomcatCPPool.this.getSize();
                this.activeConnections = TomcatCPPool.this.getActive();
            }
        };
    }
}

Add a wrapper class for the pool

Add a wrapper class for the pool


/**
 * Created by Nathan_Zeplowitz on 4/11/15.
 */
public class PrintOneAsterisk {
    public static void main(String[] args) {
        System.out.println("*");
    }
}

Add First Exercise Print One Astericks

Add First Exercise Print One Astericks


package leetcode.word_break;

import java.util.HashSet;
import java.util.Set;

public class Solution {
	public boolean wordBreak(String s, Set<String> dict, int minlength) {
		if(dict.contains(s)) return true;
		char[] chars = s.toCharArray();
		int len = chars.length;
		for(int i = minlength; i <= len - minlength; i++){
			if(dict.contains(s.substring(i)) && wordBreak(s.substring(0, i), dict, minlength)){
				return true;
			}
		}
		return false;
	}
    public boolean wordBreak(String s, Set<String> dict) {
    	if(dict.size() == 0) return s.length() == 0;
    	int minlength = -1;
    	for(String word : dict){
    		if(minlength == -1 || word.length() < minlength){
    			minlength = word.length();
    		}
    	}
    	return wordBreak(s, dict, minlength);
    }

    public static void main(String[] args){
    	Set<String> input = new HashSet<String>();
    	input.add("leet");
    	input.add("code");
    	input.add("b");
    	System.err.println(new Solution().wordBreak("leetcodea", input));
    }
}

Add java solution for 139. Word Break

Add java solution for 139. Word Break

139. Word Break: https://leetcode.com/problems/word-break/


package ch.deletescape.jterm.commandcontexts;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

import ch.deletescape.jterm.CommandUtils;
import ch.deletescape.jterm.JTerm;
import ch.deletescape.jterm.io.Printer;

public class Reflect extends CommandContext {
  private static final BetterURLClassLoader CL = new BetterURLClassLoader(new URL[0]);

  @Override
  protected void init() {
    CommandUtils.addListener("loadjar", this::load);
    CommandUtils.addListener("class", this::clazz);
  }

  private String load(String args) throws MalformedURLException {
    URL url = JTerm.getCurrPath().resolve(args).toUri().toURL();
    CL._addURL(url);
    return "";
  }

  private String clazz(String arg) throws Exception {
    String[] args = arg.split(" ");
    String classname = args[0];
    Printer.out.println("Loading class %s...", classname);
    Class<?> clazz = CL.loadClass(classname);
    Printer.out.println("   Name: %s", clazz.getSimpleName());
    if (args.length > 1) {
      Printer.out.println(" Creating new instance of %s...", clazz.getSimpleName());
      Constructor<?> constr = clazz.getDeclaredConstructor();
      if (!constr.isAccessible()) {
        Printer.out.println("  Default constructor not accessible, forcing access");
        constr.setAccessible(true);
      }
      Object obj = constr.newInstance();
      Printer.out.println(" Getting method %s...", args[1]);
      Method m = clazz.getDeclaredMethod(args[1]);
      if (!m.isAccessible()) {
        Printer.out.println("    Method not accessible, forcing access...");
        m.setAccessible(true);
      }
      Printer.out.println("    Method accessible...");
      Printer.out.println("  Invoking method \"%s\" on previously created object of %s...", m.toString(),
          clazz.toString());
      Object result = m.invoke(obj);
      Printer.out.println("    Success! --- Result: %s", result);
    }
    return "";
  }

  private static class BetterURLClassLoader extends URLClassLoader {

    public BetterURLClassLoader(URL[] urls) {
      super(urls);
    }

    public void _addURL(URL url) {
      addURL(url);
    }
  }
}

Add a reflection command context

Add a reflection command context

This won't be loaded per default as it is just some playground stuff for
me


package com.example.profbola.bakingtime.ui.widget;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.RemoteViews;
import android.widget.RemoteViewsService;
import android.widget.TextView;

import com.example.profbola.bakingtime.R;
import com.example.profbola.bakingtime.models.Ingredient;
import com.example.profbola.bakingtime.provider.RecipeContract;

/**
 * Created by prof.BOLA on 7/9/2017.
 */

public class IngredientWidgetService extends RemoteViewsService{

    @Override public RemoteViewsFactory onGetViewFactory(Intent intent) {

        int recipeId = intent.getIntExtra(RecipesWidgetProvider.RECIPE_ID, 1);
        return new IngredientAdapterFactory(this.getApplicationContext(), recipeId);

    }
}

class IngredientAdapterFactory implements RemoteViewsService.RemoteViewsFactory {

    private Context mContext;private int mRecipeId;private Cursor mIngredients;

    protected IngredientAdapterFactory(Context context, int recipeId) {

        mContext = context;

        mRecipeId = recipeId;

    }
    @Override
    public RemoteViews getViewAt(int position) {

        if (mIngredients == null || mIngredients.getCount() == 0) return null;

        RemoteViews views = new RemoteViews(mContext.getPackageName(), R.layout.ingredient);

        mIngredients.moveToPosition(position);
        Ingredient ingredient = new Ingredient(mIngredients);
        views.setTextViewText(R.id.ingredient_name, ingredient.ingredient);
        views.setTextViewText(R.id.measure, ingredient.measure);
        views.setTextViewText(R.id.quantity, String.valueOf(ingredient.quantity));

        return views;
    }

    @Override public void onCreate() {

    }
    @Override
    public void onDataSetChanged() {

        if (mIngredients != null) mIngredients.close();

        mIngredients = mContext.getContentResolver().query(
                RecipeContract.IngredientEntry.CONTENT_URI(mRecipeId),
                null,
                null,
                null,
                null
        );

    }

    @Override
    public void onDestroy() {

        if (mIngredients != null) mIngredients.close();

    }

    @Override
    public int getCount() {

        if (mIngredients == null) return 0;
        return mIngredients.getCount();

    }

    @Override
    public RemoteViews getLoadingView() {
        return null;
    }

    @Override
    public int getViewTypeCount() {
        return 1;
    }

    @Override
    public long getItemId(int position) {
        return 1;
    }

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

Add Widget RemoteViews Factory, Service for Ingredients Listing


/*
 * Copyright 2000-2009 JetBrains s.r.o.
 *
 * 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.jetbrains.idea.maven.utils;

import com.intellij.openapi.application.AccessToken;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import org.jetbrains.idea.maven.dom.MavenDomUtil;

public class MavenProblemFileHighlighter implements Condition<VirtualFile> {
  private final Project myProject;

  public MavenProblemFileHighlighter(Project project) {
    myProject = project;
  }

  public boolean value(final VirtualFile file) {
    AccessToken accessToken = ApplicationManager.getApplication().acquireReadActionLock();
    try {
      PsiFile psiFile = PsiManager.getInstance(myProject).findFile(file);
      return psiFile != null && MavenDomUtil.isMavenFile(psiFile);
    }
    finally {
      accessToken.finish();
    }
  }
}

/*
 * Copyright 2000-2009 JetBrains s.r.o.
 *
 * 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.jetbrains.idea.maven.utils;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import org.jetbrains.idea.maven.dom.MavenDomUtil;

public class MavenProblemFileHighlighter implements Condition<VirtualFile> {
  private final Project myProject;

  public MavenProblemFileHighlighter(Project project) {
    myProject = project;
  }

  public boolean value(final VirtualFile file) {
    PsiFile psiFile = PsiManager.getInstance(myProject).findFile(file);
    return psiFile != null && MavenDomUtil.isMavenFile(psiFile);
  }
}

Remove unnecessary getting of read action.


/*******************************************************************************
 * Copyright (C) 2018 Push Technology Ltd.
 *
 * 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.pushtechnology.diffusion.transform.updater;

import java.util.concurrent.CompletableFuture;

import com.pushtechnology.diffusion.client.features.TimeSeries.EventMetadata;

/**
 * Updater for time series topics.
 *
 * @param <V> The type of value updates are provided as
 * @author Push Technology Limited
 */
public interface TimeSeriesUpdater<V> {

    /**
     * Append an event to a time series topic.
     *
     * @param path the path to update
     * @param value the value to append
     * @return future resolving to metadata
     */
    CompletableFuture<EventMetadata> append(String path, V value);

    /**
     * Edit an event of a time series topic.
     *
     * @param path the path to update
     * @param value the value to append
     * @return future resolving to metadata
     */
    CompletableFuture<EventMetadata> edit(String path, long originalSequence, V value);
}

Add an updater interface for time series topics.


package com.mgmtp.jfunk.data.generator.constraint;

import javax.inject.Inject;
import javax.inject.Provider;

import org.jdom.Element;

import com.mgmtp.jfunk.common.random.MathRandom;
import com.mgmtp.jfunk.common.util.Configuration;
import com.mgmtp.jfunk.data.generator.Generator;
import com.mgmtp.jfunk.data.generator.constraint.base.BaseConstraint;
import com.mgmtp.jfunk.data.generator.control.FieldCase;
import com.mgmtp.jfunk.data.generator.util.XMLTags;

/**
 * A constraint that returns a value from the current {@link Configuration}.
 *
 * <pre>
 * {@code
 * <constraint id="c1" class="ConfigValue">
 *   <constant>myConfigKey</constant>
 * </constraint>
 * }
 * </pre>
 *
 * @version $Id$
 */
public class ConfigValue extends BaseConstraint {

	@Inject
	Provider<Configuration> configProvider;

	private final String configKey;

	public ConfigValue(final MathRandom random, final Element element, final Generator generator) {
		super(random, element, generator);
		configKey = element.getChildText(XMLTags.CONSTANT);
	}

	@Override
	public int getMaxLength() {
		return -1;
	}

	@Override
	public void resetValues() {
		//
	}

	@Override
	public int countCases() {
		return 1;
	}

	@Override
	public boolean hasNextCase() {
		return false;
	}

	@Override
	public void resetCase() {
		// no-op
	}

	@Override
	protected String initValuesImpl(final FieldCase c) throws Exception {
		return configProvider.get().get(configKey);
	}
}

MQA-932: Create constraint that retrieves a value from the configuration


package com.christofferklang.pyxl;

import com.jetbrains.python.psi.PyElementType;

public class PyxlTokenTypes {
    private PyxlTokenTypes() {
        // Prevent instantiation
    }

    /** Dummy token to test out custom tokenization */
    public static final PyElementType BANANA_DUMMY = new PyElementType("BANANA DUMMY");

    public static final PyElementType FRAGBEGIN = new PyElementType("PYXL FRAG BEGIN");
    public static final PyElementType BADCHAR = new PyElementType("PYXL BAD CHAR");
    public static final PyElementType FRAGEND = new PyElementType("PYXL FRAG END");
    public static final PyElementType IDENTIFIER = new PyElementType("PYXL IDENTIFIER");
    public static final PyElementType TAGEND = new PyElementType("PYXL TAG END");
    public static final PyElementType TAGCLOSE = new PyElementType("PYXL TAG CLOSE");

    public static final PyElementType TAGENDANDCLOSE = new PyElementType("PYXL TAG END AND CLOSE");
    public static final PyElementType TAGBEGIN = new PyElementType("PYXL TAG BEGIN");
    public static final PyElementType EMBED_START = new PyElementType("PYXL PYTHON EMBED BEGIN");
    public static final PyElementType EMBED_END = new PyElementType("PYXL PYTHON EMBED END");
}

Rename lexer tokens and rename pypyxltokentypes java


package uk.hfox.morphix.transform;

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;

class ConverterTest {

    @Test
    void pullBasic() {
        BasicConverter converter = new BasicConverter();
        converter.pull("key", new Object());
        converter.pull("key", new Object(), null);
    }

    @Test
    void pullValue() {
        ValueConverter converter = new ValueConverter();
        converter.pull("key", new Object());
        converter.pull("key", new Object(), null);
    }

    private static class BasicConverter implements Converter<Object> {

        @Override
        public Object pull(String key, Object entry) {
            assertNotNull(key);
            assertNotNull(entry);
            return null;
        }

        @Override
        public void push(String key, Object entry, Object value) {
            // not interested
        }
    }

    private static class ValueConverter implements Converter<Object> {

        @Override
        public Object pull(String key, Object entry, Object value) {
            assertNotNull(key);
            assertNotNull(entry);
            assertNull(value);
            return null;
        }

        @Override
        public void push(String key, Object entry, Object value) {
            // not interested
        }
    }

}

Add test for default converter methods

Add test for default converter methods


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

/**
 * Control the message delivery guarantee for senders and receivers
 */
public enum DeliveryMode {
    AT_MOST_ONCE,
    AT_LEAST_ONCE
}

Add a delivery mode enum for configuring Sender and Receiver modes


package com.kurento.apps.android.content.demo.rtp;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

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

public class NetworkIP {

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

	public static InetAddress getLocalAddress() {
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface
					.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf
						.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress()
							&& (inetAddress instanceof Inet4Address)) {
						return inetAddress;
					}
				}
			}
		} catch (SocketException e) {
			log.error("Cannot retrieve local address", e);
		}
		return null;
	}
}

Add class to retrieve local address

Add class to retrieve local address

Change-Id: I523e5e6cdb8fed36d8b981918e32f9842e21cf61


/**
 *
 */
package org.objectweb.proactive.extensions.scheduler.examples.docking;

import java.io.IOException;

import javax.swing.JPanel;

import org.objectweb.proactive.extensions.scheduler.common.task.ResultPreview;
import org.objectweb.proactive.extensions.scheduler.common.task.TaskResult;
import org.objectweb.proactive.extensions.scheduler.common.task.util.ResultPreviewTool.SimpleTextPanel;

/**
 * @author cdelbe
 *
 */
public class Mol2FilePreview extends ResultPreview {

	private static final String MATCH_PATTERN = "Produced output file : ";

	@Override
	public JPanel getGraphicalDescription(TaskResult r) {
		try {
			String pathToResult = this.getPathToFile(r.getOuput().getStdoutLogs(false));
			String molEditor = System.getenv("MOL_EDITOR");
			if (molEditor==null){
				// mercury is default (supposed to be in the path)
				molEditor = "mercury";
			}
			String command = molEditor + " " + pathToResult;
			try {
				Runtime.getRuntime().exec(command);
			} catch (IOException e) {
				return new SimpleTextPanel("Unable to open external display : " + e.getMessage());
			}
			return new SimpleTextPanel("External display : " + command);
		} catch (RuntimeException e) {
			return new SimpleTextPanel("Unable to open external display : " + e.getMessage());
		}
	}

	@Override
	public String getTextualDescription(TaskResult r) {
		return "Ouput file : " + this.getPathToFile(r.getOuput().getStdoutLogs(false));
	}

	private String getPathToFile(String output) {
		int pos = output.indexOf(MATCH_PATTERN, 0);
		pos += MATCH_PATTERN.length();
		String extracted = output.substring(pos, output.indexOf(".mol2", pos));
		//extracted = ResultPreviewTool.getSystemCompliantPath(extracted);
		return extracted + ".mol2";
	}

}

Add viewer for .mol2 files (molecular docking demo)

git-svn-id: 9146c88ff6d39b48099bf954d15d68f687b3fa69@8176 28e8926c-6b08-0410-baaa-805c5e19b8d6


package com.udacity.gradle.builditbigger;

import android.support.test.runner.AndroidJUnit4;
import android.util.Log;

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

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

/**
 * Created by KarthicK on 12/4/2016.
 */

@RunWith(AndroidJUnit4.class)
public class EndpointsAsyncTaskTest{

    private static final String LOG_TAG = EndpointsAsyncTaskTest.class.getSimpleName();

    @Test
    public void testJoke(){

        EndpointsAsyncTask.JokeCallBack jokeCallBack = new EndpointsAsyncTask.JokeCallBack(){
            @Override @Test
            public void processJoke(String joke) {
                assertNotNull(joke, "joke returned is null");
                assertTrue("empty joke", jokeValid(joke));
            }
        };

        EndpointsAsyncTask asyncTask = new EndpointsAsyncTask(jokeCallBack);
        try{
            String joke = asyncTask.execute().get();
        }
        catch (Exception e){
            Log.e(LOG_TAG, e.getMessage());
        }
    }

    private static boolean jokeValid(String joke){
        if(joke != null && !joke.equals(""))
            return true;
        return false;
    }

}

Test if joke returned is valid.

feat: Test if joke returned is valid.


// Copyright (c) 2012 Microsoft Corporation.  All rights reserved.
package tlc2.tool.fp;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Random;

import util.TLCRuntime;

public class RecoveredOffHeapDiskFPSetTest extends AbstractFPSetTest {

	private static final String javaUserDir = System.getProperty(RecoveredOffHeapDiskFPSetTest.class.getName() + ".chkpt",
			System.getProperty("user.home"));

	/* (non-Javadoc)
	 * @see tlc2.tool.fp.AbstractFPSetTest#getFPSet(long)
	 */
	@Override
	protected FPSet getFPSet(long freeMemoryInBytes) throws IOException {
		long freeMemoryInFPs = TLCRuntime.getInstance().getNonHeapPhysicalMemory() / (long) FPSet.LongSize;
		return new OffHeapDiskFPSet(freeMemoryInFPs);
	}

	/* (non-Javadoc)
	 * @see tlc2.tool.fp.AbstractFPSetTest#getFPSetInitialized(int)
	 */
	@Override
	protected FPSet getFPSetInitialized(int numThreads) throws IOException {
		final DiskFPSet set = (DiskFPSet) super.getFPSetInitialized(numThreads);

		// Create a new FPSet and recover the .fp file that has been generated
		// by the same Java random (seed). This implies, that contains() should
		// return true for all fingerprints in the set. Ideally, we would know
		// the number of fingerprints in .fp.

		final String fname = "TestFPSet";

		// Create symbolic link to (archived) .chkpt file. One has to create a
		// chkpt file manually by e.g. running testMaxFPSetSizeRnd once. It is
		// important that the chkpt file and this test use the same seed for the
		// RNG though.
		//TODO automagically create the chkpt file or upload to some cloud storage
		final Path link = FileSystems.getDefault().getPath(tmpdir + File.separator + fname + ".fp.chkpt");
		final Path target = FileSystems.getDefault().getPath(javaUserDir + File.separator + fname + ".fp.chkpt");
		Files.createSymbolicLink(link, target);

		// diskfpset prepends .fp.chkpt
		set.recover(fname);

		return set;
	}

	/**
	 * Test is all fingerprints are duplicates. This is the case if the .chkpt file has been created with the same seed.
	 */
	public void testAllDuplicates() throws IOException {
		final Random rnd = new Random(RNG_SEED);
		final FPSet fpSet = getFPSetInitialized();

		for (int i = 0; i < fpSet.size(); i++) {
			long fp = rnd.nextLong();
			assertTrue(fpSet.contains(fp));
		}
	}
}

Add tests that checks if a DiskFPSet correctly recovers from a chkpt.


/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * 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.rendercore.text;

import android.text.SpannableStringBuilder;
import android.view.View;
import java.util.ArrayList;

/**
 * A {@link SpannableStringBuilder} that implements {@link MountableCharSequence} and is aware when
 * the TextRenderUnit using it is mounted and unmounted.
 */
public class MountableSpannableStringBuilder extends SpannableStringBuilder
    implements MountableCharSequence {
  private final ArrayList<MountUnmountListener> mMountUnmountListeners;

  public MountableSpannableStringBuilder(final CharSequence text) {
    super(text);
    mMountUnmountListeners = new ArrayList<>();
  }

  /**
   * This will be called when the TextRenderUnit is mounted.
   *
   * @param parent the parent View the string builder is being mounted to.
   */
  @Override
  public void onMount(View parent) {
    for (final MountUnmountListener mountUnmountListener : mMountUnmountListeners) {
      mountUnmountListener.onMount(parent);
    }
  }

  /**
   * This will be called when the TextRenderUnit is unmounted.
   *
   * @param parent the parent View the string builder is being unmounted from.
   */
  @Override
  public void onUnmount(View parent) {
    for (final MountUnmountListener mountUnmountListener : mMountUnmountListeners) {
      mountUnmountListener.onUnmount(parent);
    }
  }

  /**
   * Adds a listener to the set of listeners that will be notified of mount/unmount events.
   *
   * @param mountUnmountListener The listener to add.
   */
  public void addMountUnmountListener(final MountUnmountListener mountUnmountListener) {
    mMountUnmountListeners.add(mountUnmountListener);
  }

  /** A listener that is notified of mount/unmount events. */
  public interface MountUnmountListener {
    void onMount(final View parent);

    void onUnmount(final View parent);
  }
}

Add a SpannableStringBuilder that understands when it is mounted/unmounted

Summary:
Implementation of a SpannableStringBuilder that is notified when it mounted or unmounted.

This will be used in the Bloks RichText component for rendering Vito ImageSpans. (D35146631)

Differential Revision: D35355353

fbshipit-source-id: 1cca50cebe22e37fd351c3087092b2ba16602625


package org.jetbrains.debugger.memory.action;

import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.Project;
import com.sun.jdi.ReferenceType;
import org.jetbrains.debugger.memory.component.InstancesTracker;

public class ShowNewInstancesAction extends ClassesActionBase {
  @Override
  protected boolean isEnabled(AnActionEvent e) {
    Project project = e.getProject();
    ReferenceType selectedClass = getSelectedClass(e);
    return super.isEnabled(e) && selectedClass != null &&
        project != null && InstancesTracker.getInstance(project).isTracked(selectedClass.name());
  }

  @Override
  protected void perform(AnActionEvent e) {

  }
}

Add "Show New Instances" action to context menu of Classes view


package ca.corefacility.bioinformatics.irida.ria.unit.components;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import ca.corefacility.bioinformatics.irida.ria.utilities.components.ProjectSamplesDataTable;

/**
 * Unit test for (
 */
public class ProjectSamplesDataTableTest {

	@Test
	public void testGetSortStringFromColumnID() {
		assertEquals("Returns expected sort string value for name column", "sample.sampleName",
				ProjectSamplesDataTable.getSortStringFromColumnID(2));
		assertEquals("Returns expected sort string value for created date column", "createdDate",
				ProjectSamplesDataTable.getSortStringFromColumnID(4));
	}
}

Test to ensure that the proper string values are used to sort the project samples datatable.


/*
 * 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 config;

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EtchedBorder;

/**
 *
 * @author evson
 */
public abstract class SwingComponents {
    public static JPanel setPainelBody(JPanel painel) {
        try {
            painel.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED, Color.white, Color.black));
            painel.setPreferredSize(new Dimension(670, 325));
        }
        catch(NullPointerException ex) {
            Logger.getLogger(SwingComponents.class.getName()).log(Level.SEVERE, null, ex);
        }

        return painel;
    }

    public static JPanel setPainel(JPanel painel, Integer width, Integer height) {
        try {
            painel.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED, Color.white, Color.black));
            painel.setPreferredSize(new Dimension(width, height));
        }
        catch(NullPointerException ex) {
            Logger.getLogger(SwingComponents.class.getName()).log(Level.SEVERE, null, ex);
        }

        return painel;
    }

    public static JLabel setFrameTitulo(JLabel label) {
        try {
            label.setPreferredSize(new Dimension(146, 50));
            label.setFont(new Font("dialog", 1, 36));
        }
        catch(NullPointerException ex) {
            Logger.getLogger(SwingComponents.class.getName()).log(Level.SEVERE, null, ex);
        }

        return label;
    }

    public static JFrame setFrame(JFrame frame) {
        try {
            for (Component comp : frame.getContentPane().getComponents()) {
                if (comp.getName().equals("titulo")) {
                    SwingComponents.setFrameTitulo((JLabel) comp);
                }
                else if (comp.getName().equals("body")) {
                    SwingComponents.setPainelBody((JPanel) comp);
                }
            }
        }
        catch(NullPointerException ex) {
            Logger.getLogger(SwingComponents.class.getName()).log(Level.SEVERE, null, ex);
        }

        return frame;
    }
}

Add Config Components for Swing

Add Config Components for Swing


package org.liveontologies.protege.justification.proof.service;

import java.io.IOException;

import org.liveontologies.puli.ProofPrinter;

public class JustificationCompleteProofPrinter {

	public static <C> void print(JustificationCompleteProof<C> proof)
			throws IOException {
		ProofPrinter.print(proof, proof, proof.getGoal());
	}

}

Add a stdout printer for JustificationCompleteProof


/**
 * The {@code topology} package contains neuron grid strategy classes for
 * customizing self-organizing maps.  These classes are intended to be
 * instantiated and immediately given to a SOM.  All classes in this package
 * implement {@link cs437.som.GridType}.
 */
package cs437.som.topology;

Add a package annotation to topology.

Add a package annotation to topology.


package org.deeplearning4j.spark.data;

import org.apache.spark.api.java.JavaRDD;
import org.deeplearning4j.spark.BaseSparkTest;
import org.deeplearning4j.spark.util.SparkUtils;
import org.junit.Test;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.dataset.DataSet;
import org.nd4j.linalg.factory.Nd4j;

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

import static org.junit.Assert.assertEquals;

/**
 * Created by Alex on 06/01/2017.
 */
public class TestShuffleExamples extends BaseSparkTest {

    @Test
    public void testShuffle(){
        List<DataSet> list = new ArrayList<>();
        for( int i=0; i<10; i++ ){
            INDArray f = Nd4j.valueArrayOf(new int[]{10,1}, i);
            INDArray l = f.dup();

            DataSet ds = new DataSet(f,l);
            list.add(ds);
        }

        JavaRDD<DataSet> rdd = sc.parallelize(list);

        JavaRDD<DataSet> shuffled = SparkUtils.shuffleExamples(rdd, 10, 10);

        List<DataSet> shuffledList = shuffled.collect();

        int totalExampleCount = 0;
        for(DataSet ds : shuffledList){
            totalExampleCount += ds.getFeatures().length();
            System.out.println(Arrays.toString(ds.getFeatures().data().asFloat()));

            assertEquals(ds.getFeatures(), ds.getLabels());
        }

        assertEquals(100, totalExampleCount);
    }

}

Add test for spark shuffling

Add test for spark shuffling


package leetcode;

/**
 * https://leetcode.com/problems/search-a-2d-matrix-ii/
 */
public class Problem240 {
    public boolean searchMatrix(int[][] matrix, int target) {
        return false;
    }

    public static void main(String[] args) {
        Problem240 prob = new Problem240();
        int[][] matrix = new int[][] {
            new int[]{ 1,  4,  7, 11, 15},
            new int[]{ 2,  5,  8, 12, 19},
            new int[]{ 3,  6,  9, 16, 22},
            new int[]{10, 13, 14, 17, 24},
            new int[]{18, 21, 23, 26, 30}
        };
        System.out.println(prob.searchMatrix(matrix, 5)); // true
        System.out.println(prob.searchMatrix(matrix, 20)); // false
    }
}

Create a skeleton fo problem 240

Create a skeleton fo problem 240


package leetcode;

/**
 * https://leetcode.com/problems/patching-array/
 */
public class Problem330 {
    public int minPatches(int[] nums, int n) {
        // TODO
        return 0;
    }

    public static void main(String[] args) {
        Problem330 prob = new Problem330();
        System.out.println(prob.minPatches(new int[]{1, 3}, 6)); // 1
        prob.minPatches(new int[]{1, 5, 10}, 20); // 2
        prob.minPatches(new int[]{1, 2, 2}, 5); // 0
    }
}

Create a skeleton for problem 330

Create a skeleton for problem 330


package otld.otld.intermediate;

import org.junit.Test;
import otld.otld.intermediate.exceptions.TypeMismatch;

import static org.junit.Assert.*;

public class OperationSequenceTest {
    Function add = new Function("add", Type.INT, Type.INT, Type.INT);
    Function eq = new Function("eq", Type.INT, Type.INT, Type.BOOL);
    Variable x = Variable.create(Type.INT, "x", null);
    Variable y = Variable.create(Type.INT, "y", null);
    Variable z = Variable.create(Type.BOOL, "z", null);

    @Test
    public void testBehaviour() throws TypeMismatch {
        OperationSequence sequence = new OperationSequence();

        ValueAssignment op1 = x.createValueAssignment(10);
        sequence.add(op1);
        ValueAssignment op2 = x.createValueAssignment(20);
        sequence.add(op2);
        Call op3 = new Call(add, x, y, y);
        sequence.add(op3);
        ValueAssignment op4 = x.createValueAssignment(30);
        sequence.add(op4);
        Call op5 = new Call(eq, x, y, z);
        sequence.add(op5);

        assertEquals(5, sequence.size());

        assertEquals(op1, sequence.get(0));
        assertEquals(op2, sequence.get(1));
        assertEquals(op3, sequence.get(2));
        assertEquals(op4, sequence.get(3));
        assertEquals(op5, sequence.get(4));
    }

}

Add basic test for OperationSequence

Add basic test for OperationSequence


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

package io.undertow.server.handlers;

import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.HeaderMap;
import io.undertow.util.HttpString;
import io.undertow.util.Methods;
import io.undertow.util.PathMatcher;

/**
 * Handler that pushes resources based on a provided URL
 *
 * @author Stuart Douglas
 */
public class PushHandler implements HttpHandler {

    private final PathMatcher<String[]> pathMatcher = new PathMatcher<>();
    private final HttpHandler next;
    private final HeaderMap requestHeaders = new HeaderMap();

    public PushHandler(HttpHandler next) {
        this.next = next;
    }

    @Override
    public void handleRequest(HttpServerExchange exchange) throws Exception {
        if(exchange.getConnection().isPushSupported()) {
            PathMatcher.PathMatch<String[]> result = pathMatcher.match(exchange.getRelativePath());
            if(result != null) {
                String[] value = result.getValue();
                for(int i = 0; i < value.length; ++i) {
                    exchange.getConnection().pushResource(value[i], Methods.GET, requestHeaders, exchange);
                }
            }
        }
        next.handleRequest(exchange);
    }

    public PushHandler addRequestHeader(HttpString name, String value) {
        requestHeaders.put(name, value);
    }

    public PushHandler addRoute(String url, String ... resourcesToPush) {
        if(url.endsWith("/*")) {
            String partial = url.substring(0, url.length() - 1);
            pathMatcher.addPrefixPath(partial, resourcesToPush);
        } else {
            pathMatcher.addExactPath(url, resourcesToPush);
        }
        return this;
    }

}

Add push handler that can push resources for specific URL's


package net;

import java.net.URL;
import java.io.IOException;
import java.io.File;
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.ByteArrayOutputStream;

public class DownloadFile {
    public static void main(String[] args) {

        String picUrl = "https://mazhuang.org/assets/images/qrcode.jpg";

        String tempPath =System.getProperty("java.io.tmpdir");
        String fileName = String.valueOf(System.currentTimeMillis());
        int index = picUrl.lastIndexOf(".");
        String suffix = picUrl.substring(index);
        fileName += suffix;
        String filePath = tempPath + fileName;

        System.out.println("file path: " + filePath);

        boolean result = downloadPicture(picUrl, filePath);
        System.out.println("download result: " + result);
    }

    public static boolean downloadPicture(String picUrl, String filePath) {
        URL url;

        try {
            url = new URL(picUrl);
            DataInputStream dataInputStream = new DataInputStream(url.openStream());

            FileOutputStream fileOutputStream = new FileOutputStream(new File(filePath));
            ByteArrayOutputStream output = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int length;

            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            fileOutputStream.write(output.toByteArray());
            dataInputStream.close();
            fileOutputStream.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return false;
    }
}

Add snippets: download file by Java

Add snippets: download file by Java


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


/*
 *  *
 * ProActive Parallel Suite(TM): The Java(TM) library for
 *    Parallel, Distributed, Multi-Core Computing for
 *    Enterprise Grids & Clouds
 *
 * Copyright (C) 1997-2016 INRIA/University of
 *                 Nice-Sophia Antipolis/ActiveEon
 * Contact: proactive@ow2.org or contact@activeeon.com
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License
 * as published by the Free Software Foundation; version 3 of
 * the License.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * If needed, contact us to obtain a release under GPL Version 2 or 3
 * or a different license than the AGPL.
 *
 *  Initial developer(s):               The ProActive Team
 *                        http://proactive.inria.fr/team_members.htm
 *  Contributor(s):
 *
 *  * $$ACTIVEEON_INITIAL_DEV$$
 */
package org.ow2.proactive.scheduling.api.controller;

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

@Controller
public class ApiController {

    @RequestMapping(value = "v1", method = { RequestMethod.DELETE, RequestMethod.GET, RequestMethod.HEAD,
            RequestMethod.OPTIONS, RequestMethod.POST, RequestMethod.PUT, RequestMethod.TRACE })
    @ResponseBody
    public String v1() {
        return "TODO: forward to /rest/";
    }

    @RequestMapping(value = "v2", method = RequestMethod.GET)
    public String v2() {
        return "/index.html";
    }

}

Add new controller to differentiate API v1 and v2


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

package tachyon.client;

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

/**
 * Tests {@link ClientUtils}.
 */
public final class ClientUtilsTest {

  /**
   * Tests if output of getRandomNonNegativeLong from {@link ClientUtils} is non-negative, allowing for zero.
   */
  @Test
  public void getRandomNonNegativeLongTest() throws Exception {
    Assert.assertTrue(ClientUtils.getRandomNonNegativeLong() > 0);
  }

}

[TACHYON-1559] Add unit test for tachyon.client.ClientUtils.getRandomNonNegativeLong()


package org.simpleframework.xml.core;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamClass;
import java.io.Serializable;
import java.lang.reflect.Method;

import junit.framework.TestCase;

public class ObjectStreamClassTest extends TestCase {

   public static class Tuple implements Serializable{
      private String name;
      private String value;
      public Tuple(String name, String value) {
         this.name = name;
         this.value = value;
      }
   }
   public void testObjectStreamTest() throws Exception {
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      ObjectOutputStream oout = new ObjectOutputStream(out);
      Tuple tuple = new Tuple("a", "b");

      oout.writeObject(tuple);
      byte[] array = out.toByteArray();
      ByteArrayInputStream in = new ByteArrayInputStream(array);
      ObjectInputStream oin = new ObjectInputStream(in);

      tuple = (Tuple)oin.readObject();
   }

   public void testInstantiation() throws Exception {
      ObjectStreamClass factory = ObjectStreamClass.lookup(Tuple.class);
      Method method = ObjectStreamClass.class.getDeclaredMethod("newInstance");

      if(!method.isAccessible()) {
         method.setAccessible(true);
      }
      Tuple tuple = (Tuple)method.invoke(factory);

      assertEquals(tuple.name, null);
      assertEquals(tuple.value, null);
   }

}

Update the object stream test

Update the object stream test

git-svn-id: 4741f78aa2d3279ddd0a34c053c42ca3ce19451b@1158 124fc276-1b20-0410-8d16-dc08e6bff5e9


package de.retest.recheck.review;

import static de.retest.recheck.review.counter.NopCounter.getInstance;
import static org.assertj.core.api.Assertions.assertThat;

import org.junit.jupiter.api.Test;
import org.mockito.Mockito;

import de.retest.recheck.ui.Path;
import de.retest.recheck.ui.descriptors.Element;
import de.retest.recheck.ui.descriptors.IdentifyingAttributes;
import de.retest.recheck.ui.descriptors.MutableAttributes;
import de.retest.recheck.ui.diff.AttributeDifference;

class GlobalIgnoreApplierTest {

	private static class some {
	}

	@Test
	void ignoreElement_should_add_filter() {
		final GlobalIgnoreApplier cut = GlobalIgnoreApplier.create( getInstance() );

		final Element element = Element.create( "myRetestId", Mockito.mock( Element.class ),
				IdentifyingAttributes.create( Path.fromString( "/other[1]/some[1]" ), some.class ),
				new MutableAttributes().immutable() );

		cut.ignoreElement( element );

		assertThat( cut.persist().getIgnores().toString() ).isEqualTo( "[matcher: retestid=myRetestId]" );
	}

	@Test
	void ignoreAttribute_should_add_filter() {
		final GlobalIgnoreApplier cut = GlobalIgnoreApplier.create( getInstance() );

		final Element element = Element.create( "myRetestId", Mockito.mock( Element.class ),
				IdentifyingAttributes.create( Path.fromString( "/other[1]/some[1]" ), some.class ),
				new MutableAttributes().immutable() );

		cut.ignoreAttribute( element, new AttributeDifference( "myAttribute", "expected", "actual" ) );

		assertThat( cut.persist().getIgnores().toString() )
				.isEqualTo( "[matcher: retestid=myRetestId, attribute: myAttribute]" );
	}
}

Add test for the changed behavior

Add test for the changed behavior


package edu.java.cosc111.samples;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.OpenOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

/**
 *
 * @author rlvillacarlos
 */
public class SimpleTextFileReadAndWrite {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {
        Scanner in = new Scanner(System.in);

        System.out.print("Enter path: ");
        Path p = Paths.get(in.nextLine());
        List<String> data = Arrays.asList("1,2,3,4,5,6,7,8,9,10".split(",")) ;
        if(Files.exists(p)){
            System.out.printf("The file %s already exists%n", p.toAbsolutePath());
            System.out.print("Do you want to append? (y/n)");

            if(in.nextLine().substring(0, 1).equalsIgnoreCase("y")){
                System.out.println("--Writing Data--");
                Files.write(p, data,StandardOpenOption.APPEND);
            }
        }else{
            System.out.println("--Writing Data--");
            Files.write(p, data);
        }
        System.out.println("--Reading Data--");
        List<String> contents = Files.readAllLines(p);
        for(String c:contents){
            System.out.println(c);
        }
    }

}

Add sample to test basic creation, writing, and reading text files


/*
 * 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-29
 * Site       : https://www.acmicpc.net/problem/1065
 */

public class Boj1065 {

    public static void main(String[] args) throws IOException {
         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
         int n = Integer.parseInt(br.readLine());
         int count = 0;

         if(n < 100){
             System.out.println(n);
         }else{
             for(int i=100; i<=n; i++){
                 if(i/100 - (i%100)/10 == (i%100)/10 - i%10){
                     count++;
                 }
             }
             System.out.println(count+99);
         }
    }

}

Solve No.1065 from Baekjoon Online Judge


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

package io.undertow.server.handlers.file;

import java.io.File;

import io.undertow.UndertowLogger;
import io.undertow.UndertowMessages;
import io.undertow.server.HttpCompletionHandler;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;

/**
 *
 * Serves files direct from the file system.
 *
 * @author Stuart Douglas
 */
public class FileHandler implements HttpHandler {

    private volatile File base;
    private volatile FileCache fileCache = DirectFileCache.INSTANCE;

    public FileHandler(final File base) {
        if (base == null) {
            throw UndertowMessages.MESSAGES.argumentCannotBeNull();
        }
        this.base = base;
    }

    @Override
    public void handleRequest(final HttpServerExchange exchange, final HttpCompletionHandler completionHandler) {
        final File file = new File(base.getAbsolutePath() + File.separatorChar + exchange.getRelativePath());
        //TODO: is there a better way to do this check
        if(!file.getAbsolutePath().startsWith(base.getAbsolutePath())) {
            UndertowLogger.REQUEST_LOGGER.fileHandlerWithoutCanonicalPathHandler();
            exchange.setResponseCode(500);
            completionHandler.handleComplete();
            return;
        }
        fileCache.serveFile(exchange, completionHandler, file);
    }

    public File getBase() {
        return base;
    }

    public void setBase(final File base) {
        if (base == null) {
            throw UndertowMessages.MESSAGES.argumentCannotBeNull();
        }
        this.base = base;
    }

    public FileCache getFileCache() {
        return fileCache;
    }

    public void setFileCache(final FileCache fileCache) {
        if (fileCache == null) {
            throw UndertowMessages.MESSAGES.argumentCannotBeNull();
        }
        this.fileCache = fileCache;
    }
}

Add handler for serving static files

Add handler for serving static files


package bfs;

/*
	This class defines a vertex for Breadth First Search algorithm.
*/

class Vertex{

	private int name = -1;					// vertex name
	private int parent = -1;				// parent vertex's name in bfs tree
	private int distance = -1;				// shortest distance from source vertex
	private char color = 'w';					// color of vertex

	// Constructs vertex with specified name

	public Vertex(int name){

		this.name = name;
	}

	// Returns name

	public int getName(){

		return name;
	}

	// Returns parent's name

	public int getParent(){

		return parent;
	}

	// Returns distance

	public int getDistance(){

		return distance;
	}

	// Returns color

	public char getColor(){

		return color;
	}

	// Sets parent

	public void setParent(int p){

		parent = p;
	}

	// Sets distance

	public void setDistance(int d){

		distance = d;
	}

	// Sets color

	public void setColor(char c){

		color = c;
	}

}

Add vertex class for bfs

Add vertex class for bfs


/*
 *    Debrief - the Open Source Maritime Analysis Application
 *    http://debrief.info
 *
 *    (C) 2000-2016, Deep Blue C Technology Ltd
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the Eclipse Public License v1.0
 *    (http://www.eclipse.org/legal/epl-v10.html)
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 */
package org.mwc.debrief.lite;

/**
 * @author Ayesha
 *
 */
public class BuildDate
{
  public static final String BUILD_DATE="$DATE_HERE$";
}

Include "template" build date, so we can check it's being updated.


package bzh.ys.javabyexample.pattern.filter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * Description: TODO
 * <p/>
 * Date: 2014-07-23 9:39 PM
 *
 * @author yannig
 */
public class FilterExample {

    public static void main(String[] args) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");

        List<Date> elements = Arrays.asList( new Date[]{format.parse("10-02-1952"),format.parse("5-06-1987"),format.parse("8-07-1983")} );
        Date date = format.parse("10-3-1978");

        System.out.println( elements );

        elements = elements.stream().filter( e -> e.after(date)).collect(Collectors.toList());

        System.out.println( elements );
    }

}

Add some example using filter

Add some example using filter


/**
 * @copyright
 * ====================================================================
 *    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.
 * ====================================================================
 * @endcopyright
 */

package org.apache.subversion.javahl.types;

public class Checksum implements java.io.Serializable
{
    // Update the serialVersionUID when there is a incompatible change
    // made to this class.  See any of the following, depending upon
    // the Java release.
    // http://java.sun.com/j2se/1.3/docs/guide/serialization/spec/version.doc7.html
    // http://java.sun.com/j2se/1.4/pdf/serial-spec.pdf
    // http://java.sun.com/j2se/1.5.0/docs/guide/serialization/spec/version.html#6678
    // http://java.sun.com/javase/6/docs/platform/serialization/spec/version.html#6678
    private static final long serialVersionUID = 1L;

    /**
     * Constructor to be called from the native code
     * @param digest            bytes of the digest
     * @param kind              kind of checksum
     */
    public Checksum(byte[] digest, Kind kind)
    {
        this.digest = digest;
        this.kind = kind;
    }

    /** Digest of the checksum */
    private byte[] digest;

    /** Kind of the Checksum */
    private Kind kind;

    /**
     * Retrieve the digest
     * @return  the digest
     */
    public byte[] getDigest()
    {
        return digest;
    }

    /**
     * Retrieve the kind
     * @return  the kind
     */
    public Kind getKind()
    {
        return kind;
    }

    /**
     * Kinds of checksum
     */
    public enum Kind
    {
        MD5,
        SHA1;
    }
}

Add file missed in r1098736.

Add file missed in r1098736.

* subversion/bindings/javahl/src/org/apache/subversion/javahl/types/Checksum.java: New.

git-svn-id: f8a4e5e023278da1e04e203c7fe051e3c4285d88@1098745 13f79535-47bb-0310-9956-ffa450edef68


package com.github.terma.gigaspacesqlconsole;

import com.github.terma.gigaspacesqlconsole.core.ExecuteRequest;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ExecuteToCsvServlet extends HttpServlet {

    private static final String JSON_PARAMETER = "json";
    private static final String OCTET_STREAM_CONTENT_TYPE = "application/octet-stream";

    private final Gson gson = new Gson();

    @Override
    protected void doPost(final HttpServletRequest request, final HttpServletResponse response)
            throws ServletException, IOException {
        String requestJson = getRequestJson(request);
        final ExecuteRequest req = gson.fromJson(requestJson, ExecuteRequest.class);

        response.setContentType(OCTET_STREAM_CONTENT_TYPE);

        response.getWriter().append(requestJson);

//        try {
//            doProcess(req, res);
//        } catch (final Throwable exception) {
//            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
//            response.getWriter().append(gson.toJson(new ExecuteException(exception)));
//        }
    }

    private static String getRequestJson(final HttpServletRequest request) throws IOException {
        return request.getParameter(JSON_PARAMETER);
    }

}

Add execute to csv button on UI and mock servlet


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

package com.hazelcast.jet.pipeline;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.IntStream;
import org.junit.Test;

import static com.hazelcast.jet.pipeline.test.AssertionSinks.assertOrdered;
import static java.util.stream.Collectors.toList;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

public class SortBatchStageTest extends PipelineTestSupport {

    @Test
    public void sort_withRepeatingItems() {
        // Given
        List<Integer> input = IntStream.range(0, itemCount).map(t -> t / 10).boxed().collect(toList());
        List<Integer> expected = new ArrayList<>(input);
        Collections.shuffle(input);

        // When
        BatchStage<Integer> sorted = batchStageFromList(input).rebalance().sort();

        // Then
        sorted.writeTo(assertOrdered(expected));
        execute();
    }

    @Test
    public void sort_withComparator() {
        // Given
        List<Integer> input = IntStream.range(0, itemCount).boxed().sorted(Collections.reverseOrder()).collect(toList());
        List<Integer> expected = new ArrayList<>(input);
        Collections.shuffle(input);

        // When
        BatchStage<Integer> sorted = batchStageFromList(input).rebalance()
                .sort((a, b) -> b - a);

        // Then
        sorted.writeTo(assertOrdered(expected));
        execute();
    }

    @Test
    public void sort_exceptionDuringComparing() {
        // Given
        List<Integer> input = IntStream.range(0, 20).boxed().collect(toList());

        // When
        BatchStage<Integer> sorted = batchStageFromList(input).rebalance()
                .sort((a, b) -> {
                    if (a == 5 || b == 5) {
                        throw new RuntimeException("expectedFailure");
                    }
                    return a - b;
                });
        sorted.writeTo(Sinks.logger());

        // Then
        assertThatThrownBy(this::execute)
                .hasRootCauseInstanceOf(RuntimeException.class)
                .hasMessageContaining("expectedFailure");
    }

    @Test
    public void sort_lessItemsThanProcessors() {
        // Given
        List<Integer> input = IntStream.range(0, 3).boxed().collect(toList());
        List<Integer> expected = new ArrayList<>(input);
        Collections.shuffle(input);

        // When
        BatchStage<Integer> sorted = batchStageFromList(input).sort();

        // Then
        sorted.writeTo(assertOrdered(expected));
        execute();
    }
}

Add test for sort batch stage

Add test for sort batch stage


package info.noconfuse.modules.cache.support;

import info.noconfuse.modules.cache.MemcachedCache;
import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.MemcachedClientBuilder;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

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

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:context-cache.xml"})
public class MemcachedCacheManagerTest {

    @Autowired
    private MemcachedClientBuilder clientBuilder;

    private MemcachedClient memcachedClient;

    @Before
    public void setUp() throws IOException {
        memcachedClient = clientBuilder.build();
    }

    @Test(expected = IllegalArgumentException.class)
    public void testLoadCachesWithoutCacheNames() {
        MemcachedCacheManager manager = new MemcachedCacheManager();
        manager.setMemcachedClient(memcachedClient);
        manager.loadCaches();
    }

    @Test(expected = IllegalArgumentException.class)
    public void testLoadCachesWithEmptyCacheNames() {
        MemcachedCacheManager manager = new MemcachedCacheManager();
        manager.setCacheNames(Collections.EMPTY_SET);
        manager.setMemcachedClient(memcachedClient);
        manager.loadCaches();
    }

    @Test(expected = IllegalArgumentException.class)
    public void testLoadCachesWithoutClient() {
        MemcachedCacheManager manager = new MemcachedCacheManager();
        manager.setCacheNames(Collections.singleton("hello"));
        manager.loadCaches();
    }

    @Test
    public void testLoadCaches() {
        MemcachedCacheManager manager = new MemcachedCacheManager();
        manager.setCacheNames(Collections.singleton("hello"));
        manager.setMemcachedClient(memcachedClient);
        Set<Cache> caches = (Set<Cache>) manager.loadCaches();
        Assert.assertTrue(caches.size() == 1);
        Cache cache = caches.iterator().next();
        Assert.assertTrue(cache instanceof MemcachedCache);
        Assert.assertTrue(cache.getName().equals("hello"));
    }
}

Create unit test for MemcachedCacheManager


package com.evernote.android.state.test;

import com.evernote.android.state.State;

public class TestInnerClassGeneric<P> {

    public class Inner {
        @State int field;
    }
}

Add test case for inner class with generic issue


package com.ushahidi.android.domain.entity;

import com.ushahidi.android.BuildConfig;

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

import static com.google.common.truth.Truth.assertThat;

/**
 * @author Ushahidi Team <team@ushahidi.com>
 */
@RunWith(RobolectricGradleTestRunner.class)
@Config(sdk = 21, constants = BuildConfig.class)
public class FormAttributeTest {

    @Test
    public void shouldSetFormAttribute() {
        FormAttribute formAttribute = TestFixtures.getFormAttribute();
        assertThat(formAttribute).isNotNull();
        assertThat(formAttribute.getKey()).isEqualTo("test_varchar");
        assertThat(formAttribute.getFormId())
                .isEqualTo(2l);
        assertThat(formAttribute.getKey())
                .isEqualTo("test_varchar");
        assertThat(formAttribute.getLabel())
                .isEqualTo("Test varchar");
        assertThat(formAttribute.getRequired())
                .isTrue();
        assertThat(formAttribute.getPriority())
                .isEqualTo(1);
        assertThat(formAttribute.getCardinality())
                .isEqualTo(1);
        assertThat(formAttribute.getOptions()).isNull();
    }
}

Add test for setting form attribute

Add test for setting form attribute