package org.jenkinsci.plugins.ansible;

import java.io.IOException;
import java.util.Map;

import hudson.Launcher;
import hudson.model.AbstractBuild;
import hudson.model.BuildListener;
import hudson.util.ArgumentListBuilder;

/**
 * Created with IntelliJ IDEA.
 * User: sirot
 * Date: 23/05/15
 * Time: 22:56
 * To change this template use File | Settings | File Templates.
 */
class CLIRunner
{
    private final Launcher launcher;
    private final AbstractBuild<?, ?> build;
    private final BuildListener listener;

    public CLIRunner(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) {
        this.launcher = launcher;
        this.build = build;
        this.listener = listener;
    }

    public boolean execute(ArgumentListBuilder args, Map<String, String> environment)
            throws IOException, InterruptedException
    {
        return launcher.launch()
                .pwd(build.getWorkspace())
                .envs(environment)
                .cmds(args)
                .stdout(listener).join() != 0;
    }
}

package org.jenkinsci.plugins.ansible;

import java.io.IOException;
import java.util.Map;

import hudson.Launcher;
import hudson.model.AbstractBuild;
import hudson.model.BuildListener;
import hudson.util.ArgumentListBuilder;

/**
 * Created with IntelliJ IDEA.
 * User: sirot
 * Date: 23/05/15
 * Time: 22:56
 * To change this template use File | Settings | File Templates.
 */
class CLIRunner
{
    private final Launcher launcher;
    private final AbstractBuild<?, ?> build;
    private final BuildListener listener;

    public CLIRunner(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) {
        this.launcher = launcher;
        this.build = build;
        this.listener = listener;
    }

    public boolean execute(ArgumentListBuilder args, Map<String, String> environment)
            throws IOException, InterruptedException
    {
        return launcher.launch()
                .pwd(build.getWorkspace())
                .envs(environment)
                .cmds(args)
                .stdout(listener).join() == 0;
    }
}

Fix build steps setting the build status to an incorrect value


package org.numenta.nupic.util;

/**
 * Generates a range of integers while exhibiting the specific behaviors
 * of a Python generator.
 *
 * @author cogmission
 * @see AbstractGenerator
 */
public interface IntGenerator {
    /**
     * Returns an {@link AbstractGenerator} capable of returning a range of integers
     * specified by the lower and upper bound arguments.
     *
     * @param lower     the lower bound (inclusive)
     * @param upper     the upper bound (exclusive)
     * @return  an {@link AbstractGenerator} capable of returning a range of integers
     */
    public static AbstractGenerator<Integer> of(int lower, int upper) {
        /**
         *  Inner implementation of an {@code AbstractGenerator} for {@code Integer}s
         */
        class TerminableGenerator extends AbstractGenerator<Integer> {
            private static final long serialVersionUID = 1L;

            int i = lower;

            @Override
            public void exec() {
                while(i < upper) {
                    yield(Integer.valueOf(i++));
                }
            }

            @Override
            public boolean isConsumed() {
                return i > upper - 1;
            }
        }

        return new TerminableGenerator();
    }
}

package org.numenta.nupic.util;

/**
 * Generates a range of integers while exhibiting the specific behaviors
 * of a Python generator.
 *
 * @author cogmission
 * @see AbstractGenerator
 */
public interface IntGenerator {
    /**
     * Returns an {@link AbstractGenerator} capable of returning a range of integers
     * specified by the lower and upper bound arguments.
     *
     * @param lower     the lower bound (inclusive)
     * @param upper     the upper bound (exclusive)
     * @return  an {@link AbstractGenerator} capable of returning a range of integers
     */
    public static Generator<Integer> of(int lower, int upper) {
        /**
         *  Inner implementation of an {@code AbstractGenerator} for {@code Integer}s
         */
        class TerminableGenerator extends AbstractGenerator<Integer> {
            private static final long serialVersionUID = 1L;

            int i = lower;

            @Override
            public void exec() {
                while(i < upper) {
                    yield(Integer.valueOf(i++));
                }
            }

            @Override
            public boolean isConsumed() {
                return i > upper - 1;
            }
        }

        return new TerminableGenerator();
    }
}

Return interface instead of abstract impl


/*
 *  eXist Open Source Native XML Database
 *  Copyright (C) 2001-03 Wolfgang M. Meier
 *  wolfgang@exist-db.org
 *  http://exist.sourceforge.net
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public License
 *  as published by the Free Software Foundation; either version 2
 *  of the License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 *  $Id$
 */
package org.exist.storage.serializers;

public class EXistOutputKeys {

	public final static String EXPAND_XINCLUDES = "{http://exist-db.org/}expand-xincludes";

	public final static String HIGHLIGHT_MATCHES = "{http://exist-db.org/}highlight-matches";

	public final static String INDENT_SPACES = "{http://exist-db.org/}indent-spaces";
}

/*
 *  eXist Open Source Native XML Database
 *  Copyright (C) 2001-03 Wolfgang M. Meier
 *  wolfgang@exist-db.org
 *  http://exist.sourceforge.net
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public License
 *  as published by the Free Software Foundation; either version 2
 *  of the License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 *  $Id$
 */
package org.exist.storage.serializers;

public class EXistOutputKeys {

	public final static String EXPAND_XINCLUDES = "{http://exist-db.org/}expand-xincludes";

	public final static String HIGHLIGHT_MATCHES = "{http://exist-db.org/}highlight-matches";

	public final static String INDENT_SPACES = "{http://exist-db.org/}indent-spaces";

	public final static String STYLESHEET = "{http://exist-db.org/}stylesheet";

	public final static String STYLESHEET_PARAM = "{http://exist-db.org/}stylesheet-param";

}

Add more ExistOutputKeys (stylesheet and stylesheetparam)

svn path=/trunk/eXist-1.0/; revision=146


/**
 * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
 *
 * Please see distribution for license.
 */
package com.opengamma.livedata.normalization;

import org.fudgemsg.MutableFudgeMsg;

import com.opengamma.livedata.server.FieldHistoryStore;
import com.opengamma.util.ArgumentChecker;

/**
 * Multiplies the value of a {@code Double} field by a constant.
 */
public class UnitChange implements NormalizationRule {

  private final String _field;
  private final double _multiplier;

  public UnitChange(String field, double multiplier) {
    ArgumentChecker.notNull(field, "Field name");
    _field = field;
    _multiplier = multiplier;
  }

  @Override
  public MutableFudgeMsg apply(MutableFudgeMsg msg, String securityUniqueId, FieldHistoryStore fieldHistory) {
    return multiplyField(msg, _field, _multiplier);
  }

  /*package*/ static MutableFudgeMsg multiplyField(MutableFudgeMsg msg, String field, double multiplier) {
    Double value = msg.getDouble(field);
    if (value != null) {
      double newValue = value * multiplier;
      msg.remove(field);
      msg.add(field, newValue);
    }
    return msg;
  }

}

/**
 * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
 *
 * Please see distribution for license.
 */
package com.opengamma.livedata.normalization;

import java.util.Set;

import org.fudgemsg.MutableFudgeMsg;

import com.google.common.collect.ImmutableSet;
import com.opengamma.livedata.server.FieldHistoryStore;
import com.opengamma.util.ArgumentChecker;

/**
 * Multiplies the value of a {@code Double} field by a constant.
 */
public class UnitChange implements NormalizationRule {

  private final Set<String> _fields;
  private final double _multiplier;

  public UnitChange(String field, double multiplier) {
    ArgumentChecker.notNull(field, "Field name");
    _fields = ImmutableSet.of(field);
    _multiplier = multiplier;
  }

  public UnitChange(Set<String> fields, double multiplier) {
    ArgumentChecker.notNull(fields, "Field names");
    _fields = fields;
    _multiplier = multiplier;
  }

  public UnitChange(double multiplier, String... fields) {
    ArgumentChecker.notNull(fields, "fields");
    _fields = ImmutableSet.copyOf(fields);
    _multiplier = multiplier;
  }

  @Override
  public MutableFudgeMsg apply(MutableFudgeMsg msg, String securityUniqueId, FieldHistoryStore fieldHistory) {
    return multiplyFields(msg, _fields, _multiplier);
  }

  private static MutableFudgeMsg multiplyFields(MutableFudgeMsg msg, Set<String> fields, double multiplier) {
    for (String field : fields) {
      Double value = msg.getDouble(field);
      if (value != null) {
        double newValue = value * multiplier;
        msg.remove(field);
        msg.add(field, newValue);
      }
    }
    return msg;
  }

}

Support adjustment of multiple fields

[PLAT-4419] Support adjustment of multiple fields


/*
 * Copyright 2017 Palantir Technologies, Inc. All rights reserved.
 *
 * Licensed under the BSD-3 License (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://opensource.org/licenses/BSD-3-Clause
 *
 * 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.palantir.atlasdb.ete;

import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;

import org.junit.Test;

import com.palantir.timestamp.TimestampService;

public class ServiceExposureEteTest {
    @Test
    public void shouldExposeATimestampServer() {
        TimestampService timestampClient = EteSetup.createClientToAllNodes(TimestampService.class);

        assertThat(timestampClient.getFreshTimestamp(), is(not(nullValue())));
    }
}

/*
 * Copyright 2017 Palantir Technologies, Inc. All rights reserved.
 *
 * Licensed under the BSD-3 License (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://opensource.org/licenses/BSD-3-Clause
 *
 * 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.palantir.atlasdb.ete;

import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;

import org.junit.Test;

import com.palantir.timestamp.TimestampManagementService;
import com.palantir.timestamp.TimestampService;

public class ServiceExposureEteTest {
    @Test
    public void shouldExposeATimestampServer() {
        TimestampService timestampClient = EteSetup.createClientToAllNodes(TimestampService.class);

        assertThat(timestampClient.getFreshTimestamp(), is(not(nullValue())));
    }

    @Test
    public void shouldExposeATimestampManagementServer() {
        TimestampService timestampClient = EteSetup.createClientToAllNodes(TimestampService.class);
        TimestampManagementService timestampManagementClient =
                EteSetup.createClientToAllNodes(TimestampManagementService.class);

        assertThat(timestampClient.getFreshTimestamp(), is(not(nullValue())));

        long newts = timestampClient.getFreshTimestamp() + 10000000;
        timestampManagementClient.fastForwardTimestamp(newts);

        assertThat(timestampClient.getFreshTimestamp(), is(greaterThan(newts)));
    }
}

Check that cassandra nodes expose TMS

Check that cassandra nodes expose TMS


package info.u_team.u_team_core.integration.jei;

//import java.util.List;
//import java.util.stream.Collectors;
//
//import info.u_team.u_team_core.UCoreMod;
//import info.u_team.u_team_core.api.dye.IDyeableItem;
//import mezz.jei.api.*;
//import mezz.jei.api.constants.VanillaTypes;
//import mezz.jei.api.registration.IRecipeRegistration;
//import net.minecraft.item.*;
//import net.minecraft.util.ResourceLocation;
//import net.minecraftforge.registries.ForgeRegistries;
//
//@JeiPlugin
//public class UTeamCoreJeiPlugin implements IModPlugin {
//
//	private final ResourceLocation id = new ResourceLocation(UCoreMod.MODID, "jei");
//
//	@Override
//	public ResourceLocation getPluginUid() {
//		return id;
//	}
//
//	@Override
//	public void registerRecipes(IRecipeRegistration registration) {
//		final List<ItemStack> items = ForgeRegistries.ITEMS.getValues().stream().filter(item -> item instanceof IDyeableItem || item instanceof IDyeableArmorItem).map(ItemStack::new).collect(Collectors.toList());
//		registration.addIngredientInfo(items, VanillaTypes.ITEM, "jei.uteamcore.dyeable.info");
//	}
//
//}

package info.u_team.u_team_core.integration.jei;

// TODO uncomment when jei is available again
//import java.util.List;
//import java.util.stream.Collectors;
//
//import info.u_team.u_team_core.UCoreMod;
//import info.u_team.u_team_core.api.dye.IDyeableItem;
//import mezz.jei.api.*;
//import mezz.jei.api.constants.VanillaTypes;
//import mezz.jei.api.registration.IRecipeRegistration;
//import net.minecraft.item.*;
//import net.minecraft.util.ResourceLocation;
//import net.minecraftforge.registries.ForgeRegistries;
//
//@JeiPlugin
//public class UTeamCoreJeiPlugin implements IModPlugin {
//
//	private final ResourceLocation id = new ResourceLocation(UCoreMod.MODID, "jei");
//
//	@Override
//	public ResourceLocation getPluginUid() {
//		return id;
//	}
//
//	@Override
//	public void registerRecipes(IRecipeRegistration registration) {
//		final List<ItemStack> items = ForgeRegistries.ITEMS.getValues().stream().filter(item -> item instanceof IDyeableItem || item instanceof IDyeableArmorItem).map(ItemStack::new).collect(Collectors.toList());
//		registration.addIngredientInfo(items, VanillaTypes.ITEM, "jei.uteamcore.dyeable.info");
//	}
//
//}

Add todo in jei plugin

Add todo in jei plugin


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

package org.openmhealth.dsu.repository;

import org.openmhealth.dsu.domain.DataPoint;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.Repository;

import java.util.Optional;

/**
 * A repository of data points.
 *
 * @see org.springframework.data.repository.CrudRepository
 * @author Emerson Farrugia
 */
@NoRepositoryBean
public interface DataPointRepository extends Repository<DataPoint, String>, CustomDataPointRepository {

    Optional<DataPoint> findOne(String id);

    Iterable<DataPoint> findAll();

    DataPoint save(DataPoint dataPoint);

    Iterable<DataPoint> save(Iterable<DataPoint> dataPoints);

    Long delete(String id);
}

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

package org.openmhealth.dsu.repository;

import org.openmhealth.dsu.domain.DataPoint;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.Repository;

import java.util.Optional;

/**
 * A repository of data points.
 *
 * @see org.springframework.data.repository.CrudRepository
 * @author Emerson Farrugia
 */
@NoRepositoryBean
public interface DataPointRepository extends Repository<DataPoint, String>, CustomDataPointRepository {

    boolean exists(String id);

    Optional<DataPoint> findOne(String id);

    DataPoint save(DataPoint dataPoint);

    Iterable<DataPoint> save(Iterable<DataPoint> dataPoints);

    void delete(String id);
}

Add exists method to data point repository.


package net.glowstone.entity.monster;

import net.glowstone.entity.GlowCreature;
import org.bukkit.Location;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Monster;

public class GlowMonster extends GlowCreature implements Monster {
    /**
     * Creates a new non-passive mob.
     *
     * @param loc  The location of the non-passive mob.
     * @param type The type of mob.
     * @param maxHealth The max health for this mob.
     */
    public GlowMonster(Location loc, EntityType type, double maxHealth) {
        super(loc, type, maxHealth);
    }
}

package net.glowstone.entity.monster;

import net.glowstone.entity.GlowCreature;
import org.bukkit.Location;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Monster;

public class GlowMonster extends GlowCreature implements Monster {
    /**
     * The range in blocks outside of which the hostile mob will despawn immediately.
     */
    private static final double DESPAWN_RANGE_IMMEDIATE = 128;

    /**
     * Creates a new non-passive mob.
     *
     * @param loc       The location of the non-passive mob.
     * @param type      The type of mob.
     * @param maxHealth The max health for this mob.
     */
    public GlowMonster(Location loc, EntityType type, double maxHealth) {
        super(loc, type, maxHealth);
    }

    /**
     * Whether the hostile mob can despawn immediately.
     *
     * @return true if the mob can despawn immediately, false otherwise
     */
    public boolean canDespawnImmediately() {
        if (isRemoved()) {
            return false;
        }
        if (world.getPlayerCount() == 0) {
            return false;
        }
        if (isCustomNameVisible()) {
            return false;
        }
        boolean hasNearbyPlayer = world.getPlayers().stream()
                .anyMatch(player -> location.distanceSquared(player.getLocation()) <= DESPAWN_RANGE_IMMEDIATE * DESPAWN_RANGE_IMMEDIATE);
        if (hasNearbyPlayer) {
            return false;
        }
        return true;
    }

    @Override
    public void pulse() {
        if (canDespawnImmediately()) {
            remove();
            return;
        }
        super.pulse();
    }
}

Add immediate despawning for out-of-range hostile mobs


package org.strategoxt.imp.runtime.services;

import org.stratego.imp.runtime.services.sidebyside.latest.LatestSidePaneEditorHelper;
import org.stratego.imp.runtime.services.sidebyside.legacy.LegacySidePaneEditorHelper;
import org.stratego.imp.runtime.services.sidebyside.main.SidePaneEditorHelper;
import org.strategoxt.imp.runtime.Environment;

public class SideBySideService {

	private static SidePaneEditorHelper helper;

	public static SidePaneEditorHelper helperInstance() {
		if(helper == null){
			try{
				helper = new LegacySidePaneEditorHelper();
			} catch(Throwable t) {
				Environment.logWarning("Legacy side-by-side not supported. Loading dummy.");
				helper = new LatestSidePaneEditorHelper();
			}
		}
		return helper;
	}

}

package org.strategoxt.imp.runtime.services;

import org.stratego.imp.runtime.services.sidebyside.latest.LatestSidePaneEditorHelper;
import org.stratego.imp.runtime.services.sidebyside.main.SidePaneEditorHelper;

public class SideBySideService {

	private static SidePaneEditorHelper helper;

	public static SidePaneEditorHelper helperInstance() {
		helper = new LatestSidePaneEditorHelper();
		return helper;
	}

}

Remove reference to legacy sidebyside project.


/****************************************************************************
 * Copyright (C) 2014 ecsec GmbH.
 * All rights reserved.
 * Contact: ecsec GmbH (info@ecsec.de)
 *
 * This file is part of the Open eCard App.
 *
 * GNU General Public License Usage
 * This file may be used under the terms of the GNU General Public
 * License version 3.0 as published by the Free Software Foundation
 * and appearing in the file LICENSE.GPL included in the packaging of
 * this file. Please review the following information to ensure the
 * GNU General Public License version 3.0 requirements will be met:
 * http://www.gnu.org/copyleft/gpl.html.
 *
 * Other Usage
 * Alternatively, this file may be used in accordance with the terms
 * and conditions contained in a signed written agreement between
 * you and ecsec GmbH.
 *
 ***************************************************************************/

package org.openecard.binding.tctoken.ex;

import org.openecard.addon.bind.BindingResult;
import org.openecard.addon.bind.BindingResultCode;

/**
 * Specialisation of an ActivationError which does not permit the user to continue after returning to the Browser.
 *
 * @author Tobias Wich
 */
public abstract class FatalActivationError extends ActivationError {

    public FatalActivationError(BindingResultCode code, String msg) {
	super(new BindingResult(code).setResultMessage(msg), msg);
    }

    public FatalActivationError(BindingResultCode code, String msg, Throwable ex) {
	super(new BindingResult(code).setResultMessage(msg), msg, ex);
    }

}

/****************************************************************************
 * Copyright (C) 2014 ecsec GmbH.
 * All rights reserved.
 * Contact: ecsec GmbH (info@ecsec.de)
 *
 * This file is part of the Open eCard App.
 *
 * GNU General Public License Usage
 * This file may be used under the terms of the GNU General Public
 * License version 3.0 as published by the Free Software Foundation
 * and appearing in the file LICENSE.GPL included in the packaging of
 * this file. Please review the following information to ensure the
 * GNU General Public License version 3.0 requirements will be met:
 * http://www.gnu.org/copyleft/gpl.html.
 *
 * Other Usage
 * Alternatively, this file may be used in accordance with the terms
 * and conditions contained in a signed written agreement between
 * you and ecsec GmbH.
 *
 ***************************************************************************/

package org.openecard.binding.tctoken.ex;

import org.openecard.addon.bind.BindingResult;
import org.openecard.addon.bind.BindingResultCode;

/**
 * Specialization of an ActivationError which does not permit the user to continue after returning to the Browser.
 *
 * @author Tobias Wich
 */
public abstract class FatalActivationError extends ActivationError {

    public FatalActivationError(BindingResultCode code, String msg) {
	super(new BindingResult(code).setResultMessage(msg), msg);
    }

    public FatalActivationError(BindingResultCode code, String msg, Throwable ex) {
	super(new BindingResult(code).setResultMessage(msg), msg, ex);
    }

}

Fix typo in java doc.

Fix typo in java doc.


/**
 * Provides classes for hooking into various events that take place as
 * users log into and use the Guacamole web application. These event
 * hooks can be used to take action upon occurence of an event and,
 * in some cases, prevent the web application from allowing the
 * event to continue for the user that triggered it.
 */
package net.sourceforge.guacamole.net.event;

/**
 * Provides classes for hooking into various events that take place as
 * users log into and use the Guacamole web application. These event
 * hooks can be used to take action upon occurrence of an event and,
 * in some cases, prevent the web application from allowing the
 * event to continue for the user that triggered it.
 */
package net.sourceforge.guacamole.net.event.listener;

Fix wrong package and typo.

Fix wrong package and typo.


package valandur.webapi.cache;

import com.fasterxml.jackson.annotation.JsonProperty;
import org.spongepowered.api.command.CommandMapping;
import valandur.webapi.misc.WebAPICommandSource;

import java.util.Optional;

public class CachedCommand extends CachedObject {

    @JsonProperty
    public String name;

    @JsonProperty
    public String description;

    public Object[] aliases;
    public String usage;
    public String help;

    public static CachedCommand copyFrom(CommandMapping cmd) {
        CachedCommand cache = new CachedCommand();

        cache.name = cmd.getPrimaryAlias();
        cache.aliases = cmd.getAllAliases().toArray();
        cache.usage = cmd.getCallable().getUsage(WebAPICommandSource.instance).toPlain();
        cache.description = cmd.getCallable().getShortDescription(WebAPICommandSource.instance).orElse(null).toPlain();
        cache.help = cmd.getCallable().getHelp(WebAPICommandSource.instance).orElse(null).toPlain();

        return cache;
    }

    @Override
    @JsonProperty
    public String getLink() {
        return "/api/cmd/" + name;
    }
}

package valandur.webapi.cache;

import com.fasterxml.jackson.annotation.JsonProperty;
import org.spongepowered.api.command.CommandMapping;
import org.spongepowered.api.text.Text;
import valandur.webapi.misc.WebAPICommandSource;

import java.util.Optional;

public class CachedCommand extends CachedObject {

    @JsonProperty
    public String name;

    @JsonProperty
    public String description;

    public Object[] aliases;
    public String usage;
    public String help;

    public static CachedCommand copyFrom(CommandMapping cmd) {
        CachedCommand cache = new CachedCommand();

        cache.name = cmd.getPrimaryAlias();
        cache.aliases = cmd.getAllAliases().toArray();
        cache.usage = cmd.getCallable().getUsage(WebAPICommandSource.instance).toPlain();
        cache.description = cmd.getCallable().getShortDescription(WebAPICommandSource.instance).orElse(Text.EMPTY).toPlain();
        cache.help = cmd.getCallable().getHelp(WebAPICommandSource.instance).orElse(Text.EMPTY).toPlain();

        return cache;
    }

    @Override
    @JsonProperty
    public String getLink() {
        return "/api/cmd/" + name;
    }
}

fix(cmds): Fix commands without descriptions causing crash on plugin load


package org.ethereum.jsontestsuite.builder;

import org.ethereum.core.Block;
import org.ethereum.core.BlockHeader;
import org.ethereum.jsontestsuite.Utils;
import org.ethereum.jsontestsuite.model.BlockHeaderTck;

import java.math.BigInteger;

import static org.ethereum.jsontestsuite.Utils.parseData;
import static org.ethereum.jsontestsuite.Utils.parseNumericData;

public class BlockHeaderBuilder {

    public static BlockHeader  build(BlockHeaderTck headerTck){

        BlockHeader header = new BlockHeader(
                parseData(headerTck.getParentHash()),
                parseData(headerTck.getUncleHash()),
                parseData(headerTck.getCoinbase()),
                parseData(headerTck.getBloom()),
                parseNumericData(headerTck.getDifficulty()),
                new BigInteger(parseData(headerTck.getNumber())).longValue(),
                parseData(headerTck.getGasLimit()),
                new BigInteger(parseData(headerTck.getGasUsed())).longValue(),
                new BigInteger(parseData(headerTck.getTimestamp())).longValue(),
                parseData(headerTck.getExtraData()),
                parseData(headerTck.getMixHash()),
                parseData(headerTck.getNonce())
        );

        header.setReceiptsRoot(parseData(headerTck.getReceiptTrie()));
        header.setTransactionsRoot(parseData(headerTck.getTransactionsTrie()));
        header.setStateRoot(parseData(headerTck.getStateRoot()));

        return header;
    }

}

package org.ethereum.jsontestsuite.builder;

import org.ethereum.core.Block;
import org.ethereum.core.BlockHeader;
import org.ethereum.jsontestsuite.Utils;
import org.ethereum.jsontestsuite.model.BlockHeaderTck;

import java.math.BigInteger;

import static org.ethereum.jsontestsuite.Utils.parseData;
import static org.ethereum.jsontestsuite.Utils.parseNumericData;

public class BlockHeaderBuilder {

    public static BlockHeader  build(BlockHeaderTck headerTck){

        BlockHeader header = new BlockHeader(
                parseData(headerTck.getParentHash()),
                parseData(headerTck.getUncleHash()),
                parseData(headerTck.getCoinbase()),
                parseData(headerTck.getBloom()),
                parseNumericData(headerTck.getDifficulty()),
                new BigInteger(1, parseData(headerTck.getNumber())).longValue(),
                parseData(headerTck.getGasLimit()),
                new BigInteger(1, parseData(headerTck.getGasUsed())).longValue(),
                new BigInteger(1, parseData(headerTck.getTimestamp())).longValue(),
                parseData(headerTck.getExtraData()),
                parseData(headerTck.getMixHash()),
                parseData(headerTck.getNonce())
        );

        header.setReceiptsRoot(parseData(headerTck.getReceiptTrie()));
        header.setTransactionsRoot(parseData(headerTck.getTransactionsTrie()));
        header.setStateRoot(parseData(headerTck.getStateRoot()));

        return header;
    }

}

Fix JSON test data parsing

Fix JSON test data parsing


package com.formulasearchengine.backend.basex.restd.rest;

import com.formulasearchengine.backend.basex.Client;
import restx.annotations.GET;
import restx.annotations.RestxResource;
import restx.factory.Component;
import restx.security.PermitAll;

@Component @RestxResource
public class BaseXResource {

    /**
     * Say hello to anybody.
     *
     * Does not require authentication.
     *
     * @return a Message to say hello
     */
    @GET("/startup")
    @PermitAll
    public String query(String query) {
        Client client = new Client();
        return client.execute( query ) ;
    }
}

package com.formulasearchengine.backend.basex.restd.rest;

import com.formulasearchengine.backend.basex.Client;
import restx.annotations.GET;
import restx.annotations.RestxResource;
import restx.factory.Component;
import restx.security.PermitAll;

@Component @RestxResource
public class BaseXResource {

    /**
     * Say hello to anybody.
     *
     * Does not require authentication.
     *
     * @return a Message to say hello
     */
    @GET("/xquery")
    @PermitAll
    public String query(String query) {
        Client client = new Client();
        return client.execute( query ) ;
    }
}

Change path for xquery request

Change path for xquery request

Change-Id: Ia7c54b6a87ba504a124247a82256a84421836e49


/*
 * Copyright 2016 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.gradle.testing;

import org.gradle.api.tasks.CacheableTask;

/**
 * Verifies the correct behavior of a feature, as opposed to just a small unit of code.
 * Usually referred to as 'functional tests' in literature, but our code base has historically
 * been using the term 'integration test'.
 */
@CacheableTask
public class IntegrationTest extends DistributionTest {
}

/*
 * Copyright 2016 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.gradle.testing;

/**
 * Verifies the correct behavior of a feature, as opposed to just a small unit of code.
 * Usually referred to as 'functional tests' in literature, but our code base has historically
 * been using the term 'integration test'.
 */
public class IntegrationTest extends DistributionTest {
}

Disable caching for integration tests temporarily

+review REVIEW-6251


package osgi.enroute.trains.controller.api;

import osgi.enroute.trains.cloud.api.Color;

/**
 * This controller controls a SIGNAL Segment
 */
public interface SignalSegmentController extends SegmentController {

	/**
	 * Set the signal to the given color
	 * @param color
	 */
	void signal(Color color);

}

package osgi.enroute.trains.controller.api;

import osgi.enroute.trains.cloud.api.Color;

/**
 * This controller controls a SIGNAL Segment
 */
public interface SignalSegmentController extends SegmentController {

	/**
	 * Set the signal to the given color
	 * @param color
	 */
	void signal(Color color);

	Color getSignal();
}

Add a get method to fetch the current Signal color


package com.elmakers.mine.bukkit.warp;

import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.Warps;
import org.bukkit.Location;
import org.bukkit.plugin.Plugin;

/**
 * Encapsulates Essentials warps
 */
public class EssentialsWarps {
    private final Warps warps;

    private EssentialsWarps(Warps warps) {
        this.warps = warps;
    }

    public static EssentialsWarps create(Plugin plugin) {
        if (plugin instanceof Essentials) {
            Essentials essentials = (Essentials)plugin;
            Warps warps = essentials.getWarps();
            return warps == null ? null : new EssentialsWarps(warps);
        }

        return null;
    }

    public Location getWarp(String warpName) {
        try {
            return warps.getWarp(warpName);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }
}

package com.elmakers.mine.bukkit.warp;

import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.Warps;
import org.bukkit.Location;
import org.bukkit.plugin.Plugin;

/**
 * Encapsulates Essentials warps
 */
public class EssentialsWarps {
    private final Warps warps;

    private EssentialsWarps(Warps warps) {
        this.warps = warps;
    }

    public static EssentialsWarps create(Plugin plugin) {
        if (plugin instanceof Essentials) {
            Essentials essentials = (Essentials)plugin;
            Warps warps = essentials.getWarps();
            return warps == null ? null : new EssentialsWarps(warps);
        }

        return null;
    }

    public Location getWarp(String warpName) {
        try {
            return warps.getWarp(warpName);
        } catch (Exception ex) {

        }
        return null;
    }
}

Remove stack trace from missing Essentials warp


/*
 * Copyright 2014 Danny Baumann
 *
 * 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.gh4a;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class EventReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(intent.getAction())) {
            Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
            downloadManagerIntent.setFlags(
                    Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            context.startActivity(downloadManagerIntent);
        }
    }

}

/*
 * Copyright 2014 Danny Baumann
 *
 * 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.gh4a;

import android.annotation.SuppressLint;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;

public class EventReceiver extends BroadcastReceiver {
    @SuppressLint("InlinedApi")
    @Override
    public void onReceive(Context context, Intent intent) {
        if (DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(intent.getAction())) {
            Intent downloadManagerIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
            downloadManagerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                downloadManagerIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
            }
            context.startActivity(downloadManagerIntent);
        }
    }

}

Fix API usage for API level 10.

Fix API usage for API level 10.


package edu.stuy.commands.auton;

import edu.stuy.Robot;
import edu.wpi.first.wpilibj.command.Command;

/**
 *
 */
public class AutonLiftUpCommand extends Command {

    public AutonLiftUpCommand() {
        // Use requires() here to declare subsystem dependencies
        // eg. requires(chassis);
        requires(Robot.lift);
    }

    // Called just before this Command runs the first time
    protected void initialize() {
    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
        Robot.lift.goUp();
    }

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

    // Called once after isFinished returns true
    protected void end() {
        // No need to stop lift, as Robot.lift.goUp() automatically
        //  stops it once the limit switch is hit.
    }

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

package edu.stuy.commands.auton;

import edu.stuy.Robot;
import edu.wpi.first.wpilibj.command.Command;

/**
 *
 */
public class AutonLiftUpCommand extends Command {

    public AutonLiftUpCommand() {
        // Use requires() here to declare subsystem dependencies
        // eg. requires(chassis);
        requires(Robot.lift);
    }

    // Called just before this Command runs the first time
    protected void initialize() {
    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
        Robot.lift.goUp();
    }

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

    // Called once after isFinished returns true
    protected void end() {
        Robot.lift.stop();
    }

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

Add explicit stop to end of lift command


package uk.ac.ebi.atlas.bioentity.properties;

import com.google.gson.JsonObject;

// Used in bioentity-information.jsp
public class PropertyLink {

    private String text;
    private String url;
    private int relevance;

    PropertyLink(String text, String url, int relevance) {
        this.text = text;
        this.url = url;
        this.relevance = relevance;
    }

    PropertyLink(String text, int relevance) {
        this(text, "", relevance);
    }

    public String getText() {
        return text;
    }

    public String getUrl() {
        return url;
    }

    public JsonObject toJson(){
        JsonObject result = new JsonObject();
        result.addProperty("text", text);
        result.addProperty("url", url);
        result.addProperty("relevance", relevance);
        return result;
    }
}

package uk.ac.ebi.atlas.bioentity.properties;

import com.google.gson.JsonObject;

public class PropertyLink {

    private String text;
    private String url;
    private int relevance;

    PropertyLink(String text, String url, int relevance) {
        this.text = text;
        this.url = url;
        this.relevance = relevance;
    }

    PropertyLink(String text, int relevance) {
        this(text, "", relevance);
    }

    public String getText() {
        return text;
    }

    public String getUrl() {
        return url;
    }

    public JsonObject toJson(){
        JsonObject result = new JsonObject();
        result.addProperty("text", text);
        result.addProperty("url", url);
        result.addProperty("relevance", relevance);
        return result;
    }

}

Remove comment, it’s a lie

Remove comment, it’s a lie


package com.nigorojr.typebest;

import java.util.ArrayList;

import javax.swing.JLabel;
import javax.swing.JPanel;

public class Line extends JPanel {
    private ArrayList<Word> line = new ArrayList<Word>();
    private final JLabel space = new JLabel(" ");

    /**
     * Returns the total width of the words in the line by adding the length of
     * the word and the width of the spaces between them.
     *
     * @return The total width of the words in the line, including the spaces
     *         between the words.
     */
    public int getWordsWidth() {
        int width = 0;
        for (int i = 0; i < line.size(); i++)
            width += line.get(i).getWidth();

        // Add total length of the spaces between words
        width += space.getWidth() * (line.size() - 1);

        return width;
    }

    /**
     * Adds a word to the line. This method also adds a space character to the
     * line in order to separate the words with spaces.
     *
     * @param word
     */
    public void addWord(String word) {
        Word wordPanel = new Word(word);
        line.add(wordPanel);

        // Don't add a space character if it's the first word in the line
        if (!line.isEmpty())
            this.add(space);
        this.add(wordPanel);
    }
}

package com.nigorojr.typebest;

import java.util.ArrayList;

import javax.swing.JLabel;
import javax.swing.JPanel;

public class Line extends JPanel {
    private ArrayList<Word> words = new ArrayList<Word>();
    private final JLabel space = new JLabel(" ");

    /**
     * Returns the total width of the words in the line by adding the length of
     * the word and the width of the spaces between them.
     *
     * @return The total width of the words in the line, including the spaces
     *         between the words.
     */
    public int getLineWidth() {
        int width = 0;
        for (int i = 0; i < words.size(); i++)
            width += words.get(i).getWidth();

        // Add total length of the spaces between words
        width += space.getWidth() * (words.size() - 1);

        return width;
    }

    /**
     * Adds a word to the line. This method also adds a space character to the
     * line in order to separate the words with spaces.
     *
     * @param word
     *            The one word to be added.
     */
    public void addWord(String word) {
        Word wordPanel = new Word(word);
        words.add(wordPanel);

        // Don't add a space character if it's the first word in the line
        if (!words.isEmpty())
            this.add(space);
        this.add(wordPanel);
    }
}

Rename variable "line" to "words"

Rename variable "line" to "words"

Due to the fact that variable name "letters" is used instead of "word" in the
Word class, the variable name in the Line class is also changed for
consistency.


package edu.northwestern.bioinformatics.studycalendar.dao.reporting;

import edu.northwestern.bioinformatics.studycalendar.dao.StudyCalendarDao;
import gov.nih.nci.cabig.ctms.domain.DomainObject;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

import java.util.Collections;
import java.util.List;

/**
 * @author John Dzak
 */
public abstract class ReportDao<F extends ReportFilters, R extends DomainObject> extends StudyCalendarDao<R> {
    @SuppressWarnings("unchecked")
    public List<R> search(final F filters) {
        return getHibernateTemplate().executeFind(new HibernateCallback() {
            @SuppressWarnings("unchecked")
            public Object doInHibernate(Session session) throws HibernateException {
                if (filters.isEmpty()) {
                    logger.debug("No filters selected, skipping search: " + filters);
                    return Collections.emptyList();
                } else {
                    Criteria criteria = session.createCriteria(domainClass());
                    filters.apply(session);
                    return (List<R>) criteria.list();

                }
            }
        });
    }
}

package edu.northwestern.bioinformatics.studycalendar.dao.reporting;

import edu.northwestern.bioinformatics.studycalendar.dao.StudyCalendarDao;
import gov.nih.nci.cabig.ctms.domain.DomainObject;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.springframework.orm.hibernate3.HibernateCallback;

import java.util.Collections;
import java.util.List;

/**
 * @author John Dzak
 */
public abstract class ReportDao<F extends ReportFilters, R extends DomainObject> extends StudyCalendarDao<R> {
    @SuppressWarnings("unchecked")
    public List<R> search(final F filters) {
        return getHibernateTemplate().executeFind(new HibernateCallback() {
            @SuppressWarnings("unchecked")
            public Object doInHibernate(Session session) throws HibernateException {
                if (filters.isEmpty()) {
                    logger.debug("No filters selected, skipping search: " + filters);
                    return Collections.emptyList();
                } else {
                    Criteria criteria = session.createCriteria(domainClass()).addOrder(Order.asc("id"));
                    filters.apply(session);
                    return (List<R>) criteria.list();

                }
            }
        });
    }
}

Sort for testing. Fix for test failures introduced in r3557.


package org.javarosa.xpath.expr;

import org.javarosa.core.model.condition.EvaluationContext;
import org.javarosa.core.model.instance.DataInstance;
import org.javarosa.xpath.XPathNodeset;
import org.javarosa.xpath.XPathTypeMismatchException;
import org.javarosa.xpath.parser.XPathSyntaxException;

public class XPathSumFunc extends XPathFuncExpr {
    public static final String NAME = "sum";
    private static final int EXPECTED_ARG_COUNT = 1;

    public XPathSumFunc() {
        name = NAME;
        expectedArgCount = EXPECTED_ARG_COUNT;
    }

    public XPathSumFunc(XPathExpression[] args) throws XPathSyntaxException {
        super(NAME, args, EXPECTED_ARG_COUNT, true);
    }

    @Override
    public Object evalBody(DataInstance model, EvaluationContext evalContext, Object[] evaluatedArgs) {
        if (evaluatedArgs[0] instanceof XPathNodeset) {
            return sum(((XPathNodeset)evaluatedArgs[0]).toArgList());
        } else {
            throw new XPathTypeMismatchException("not a nodeset");
        }
    }

    /**
     * sum the values in a nodeset; each element is coerced to a numeric value
     */
    private static Double sum(Object argVals[]) {
        double sum = 0.0;
        for (Object argVal : argVals) {
            sum += FunctionUtils.toNumeric(argVal);
        }
        return sum;
    }

}

package org.javarosa.xpath.expr;

import org.javarosa.core.model.condition.EvaluationContext;
import org.javarosa.core.model.instance.DataInstance;
import org.javarosa.xpath.XPathNodeset;
import org.javarosa.xpath.XPathTypeMismatchException;
import org.javarosa.xpath.parser.XPathSyntaxException;

public class XPathSumFunc extends XPathFuncExpr {
    public static final String NAME = "sum";
    private static final int EXPECTED_ARG_COUNT = 1;

    public XPathSumFunc() {
        name = NAME;
        expectedArgCount = EXPECTED_ARG_COUNT;
    }

    public XPathSumFunc(XPathExpression[] args) throws XPathSyntaxException {
        super(NAME, args, EXPECTED_ARG_COUNT, true);
    }

    @Override
    public Object evalBody(DataInstance model, EvaluationContext evalContext, Object[] evaluatedArgs) {
        if (evaluatedArgs[0] instanceof XPathNodeset) {
            return sum(((XPathNodeset)evaluatedArgs[0]).toArgList());
        } else {
            throw new XPathTypeMismatchException("uses an invalid reference inside a sum function");
        }
    }

    /**
     * sum the values in a nodeset; each element is coerced to a numeric value
     */
    private static Double sum(Object argVals[]) {
        double sum = 0.0;
        for (Object argVal : argVals) {
            sum += FunctionUtils.toNumeric(argVal);
        }
        return sum;
    }

}

Update sum error text to be more descriptive


package hu.bme.mit.codemodel.rifle.visualization;

import java.io.File;

public abstract class TestCase {
    protected static final String branchId = "dummyTestExport";
    protected static final String sessionId = "dummyTestExport";
    protected String testFolderPrefix = "";

    protected String getTestResourcesFolderPath(String testMethodName) {
        try {
            String testResourceFolderWithinResources = this.testFolderPrefix + File.separator + this.getClass().getSimpleName() +
                File.separator + testMethodName;
            String path = this.getClass().getClassLoader().getResource(testResourceFolderWithinResources).getPath();
            return path;
        } catch (NullPointerException e) {
            e.printStackTrace();
            return null;
        }
    }
}

package hu.bme.mit.codemodel.rifle.visualization;

import java.io.File;

public abstract class TestCase {
    protected static final String branchId = "dummyTestExport";
    protected static final String sessionId = "dummyTestExport";
    protected String testFolderPrefix = "";

    protected String getTestResourcesFolderPath(String testMethodName) {
        try {
            String testResourceFolderWithinResources = this.getClass().getSimpleName() + File.separator +
                testMethodName;

            if (!this.testFolderPrefix.equals("")) {
                testResourceFolderWithinResources = this.testFolderPrefix + File.separator +
                    testResourceFolderWithinResources;
            }

            String path = this.getClass().getClassLoader().getResource(testResourceFolderWithinResources).getPath();
            return path;
        } catch (NullPointerException e) {
            e.printStackTrace();
            return null;
        }
    }
}

Test folder prefix separator should only be added to the path if prefix is not empty


// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.config.server.maintenance;

import com.yahoo.vespa.config.server.ApplicationRepository;
import com.yahoo.vespa.curator.Curator;
import com.yahoo.vespa.flags.FlagSource;

import java.time.Duration;
import java.util.logging.Level;

/**
 * Removes expired sessions
 * <p>
 * Note: Unit test is in ApplicationRepositoryTest
 *
 * @author hmusum
 */
public class SessionsMaintainer extends ConfigServerMaintainer {
    private final boolean hostedVespa;

    SessionsMaintainer(ApplicationRepository applicationRepository, Curator curator, Duration interval, FlagSource flagSource) {
        super(applicationRepository, curator, flagSource, applicationRepository.clock().instant(), interval, true);
        this.hostedVespa = applicationRepository.configserverConfig().hostedVespa();
    }

    @Override
    protected double maintain() {
        log.log(Level.FINE, () -> "Running " + SessionsMaintainer.class.getSimpleName());
        applicationRepository.deleteExpiredLocalSessions();

        if (hostedVespa) {
            Duration expiryTime = Duration.ofMinutes(90);
            int deleted = applicationRepository.deleteExpiredRemoteSessions(expiryTime);
            log.log(Level.FINE, () -> "Deleted " + deleted + " expired remote sessions older than " + expiryTime);
        }

        return 1.0;
    }

}

// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.config.server.maintenance;

import com.yahoo.vespa.config.server.ApplicationRepository;
import com.yahoo.vespa.curator.Curator;
import com.yahoo.vespa.flags.FlagSource;

import java.time.Duration;
import java.util.logging.Level;

/**
 * Removes expired sessions
 * <p>
 * Note: Unit test is in ApplicationRepositoryTest
 *
 * @author hmusum
 */
public class SessionsMaintainer extends ConfigServerMaintainer {
    private final boolean hostedVespa;

    SessionsMaintainer(ApplicationRepository applicationRepository, Curator curator, Duration interval, FlagSource flagSource) {
        super(applicationRepository, curator, flagSource, applicationRepository.clock().instant(), interval, true);
        this.hostedVespa = applicationRepository.configserverConfig().hostedVespa();
    }

    @Override
    protected double maintain() {
        applicationRepository.deleteExpiredLocalSessions();

        if (hostedVespa) {
            Duration expiryTime = Duration.ofMinutes(90);
            int deleted = applicationRepository.deleteExpiredRemoteSessions(expiryTime);
            log.log(Level.FINE, () -> "Deleted " + deleted + " expired remote sessions older than " + expiryTime);
        }

        return 1.0;
    }

}

Remove log message already produced in superclass


package com.sedmelluq.discord.lavaplayer.demo.jda;

import com.sedmelluq.discord.lavaplayer.player.AudioPlayer;
import com.sedmelluq.discord.lavaplayer.track.playback.AudioFrame;
import net.dv8tion.jda.audio.AudioSendHandler;

/**
 * This is a wrapper around AudioPlayer which makes it behave as an AudioSendHandler for JDA. As JDA calls canProvide
 * before every call to provide20MsAudio(), we pull the frame in canProvide() and use the frame we already pulled in
 * provide20MsAudio().
 */
public class AudioPlayerSendHandler implements AudioSendHandler {
  private final AudioPlayer audioPlayer;
  private AudioFrame lastFrame;

  /**
   * @param audioPlayer Audio player to wrap.
   */
  public AudioPlayerSendHandler(AudioPlayer audioPlayer) {
    this.audioPlayer = audioPlayer;
  }

  @Override
  public boolean canProvide() {
    lastFrame = audioPlayer.provide();
    return lastFrame != null;
  }

  @Override
  public byte[] provide20MsAudio() {
    return lastFrame.data;
  }

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

package com.sedmelluq.discord.lavaplayer.demo.jda;

import com.sedmelluq.discord.lavaplayer.player.AudioPlayer;
import com.sedmelluq.discord.lavaplayer.track.playback.AudioFrame;
import net.dv8tion.jda.audio.AudioSendHandler;

/**
 * This is a wrapper around AudioPlayer which makes it behave as an AudioSendHandler for JDA. As JDA calls canProvide
 * before every call to provide20MsAudio(), we pull the frame in canProvide() and use the frame we already pulled in
 * provide20MsAudio().
 */
public class AudioPlayerSendHandler implements AudioSendHandler {
  private final AudioPlayer audioPlayer;
  private AudioFrame lastFrame;

  /**
   * @param audioPlayer Audio player to wrap.
   */
  public AudioPlayerSendHandler(AudioPlayer audioPlayer) {
    this.audioPlayer = audioPlayer;
  }

  @Override
  public boolean canProvide() {
    if (lastFrame == null) {
      lastFrame = audioPlayer.provide();
    }

    return lastFrame != null;
  }

  @Override
  public byte[] provide20MsAudio() {
    if (lastFrame == null) {
      lastFrame = audioPlayer.provide();
    }

    byte[] data = lastFrame != null ? lastFrame.data : null;
    lastFrame = null;

    return data;
  }

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

Make it safe to call canProvide multiple times (or not at all).


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

public class TrieSTTest {

  @Test
  public void size() {
    TrieST<Integer> st = new TrieST<Integer>();
    assertEquals(0, st.size());
  }

  @Test
  public void isEmpty() {
    TrieST<Integer> st = new TrieST<Integer>();
    assertTrue(st.isEmpty());
  }
}

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

public class TrieSTTest {

  @Test
  public void testSize() {
    TrieST<Integer> st = new TrieST<Integer>();
    assertEquals(0, st.size());
  }

  @Test
  public void testIsEmpty() {
    TrieST<Integer> st = new TrieST<Integer>();
    assertTrue(st.isEmpty());
  }
}

Update functions name to match jUnit convention


package com.fatico.winthing.logging;

import com.fatico.winthing.Application;

import ch.qos.logback.core.PropertyDefinerBase;

public class FileLogEnabler extends PropertyDefinerBase {

	@Override
	public String getPropertyValue() {
		if (Application.APPDEBUG) {
			return "true";
		}

		return "false";
	}
}

package com.fatico.winthing.logging;

import com.fatico.winthing.Application;

import ch.qos.logback.core.PropertyDefinerBase;

public class FileLogEnabler extends PropertyDefinerBase {

	@Override
	public String getPropertyValue() {
		if (Application.debug()) {
			return "true";
		}

		return "false";
	}
}

Change how we find out if debug parameter has been passed


// Copyright 2013 Judson D Neer

package com.singledsoftware.mixmaestro;

import java.io.Serializable;

/**
 * Stores data for an individual channel.
 *
 * @see Serializable
 * @author Judson D Neer
 */
public class Channel implements Serializable, Comparable<Channel> {

    // Unique serializable version ID
    private static final long serialVersionUID = -3705403776567370897L;

    // Unique identifier for the channel
    private final String id;

    // Single character that identifies a channel type
    // TODO make this an enumeration
    private final char type;

    // User-assigned name for the channel
    private final String name;

    /**
     * Constructor.
     *
     * @param i New id
     * @param t New type
     * @param n New name
     */
    public Channel(String i, char t, String n) {
        id = i;
        type = t;
        name = n;
    }

    /**
     * @return The channel identifier
     */
    public String getId() {
        return id;
    }

    /**
     * @see java.io.Serializable#toString()
     */
    @Override
    public String toString() {
        // TODO put id and type in parens?
        if (type == 'A') {
            return name + "(Aux " + id + ")";
        }
        else {
            return name;
        }
    }

    /**
     * @see java.lang.Comparable#compareTo()
     */
    @Override
    public int compareTo(Channel channel) {
        // TODO enhance this once types are fully implemented
        return Integer.parseInt(id) - Integer.parseInt(channel.getId());
    }

}

// Copyright 2013 Judson D Neer

package com.singledsoftware.mixmaestro;

import java.io.Serializable;

/**
 * Stores data for an individual channel.
 *
 * @see Serializable
 * @author Judson D Neer
 */
public class Channel implements Serializable, Comparable<Channel> {

    // Unique serializable version ID
    private static final long serialVersionUID = -3705403776567370897L;

    // Unique identifier for the channel
    private final String id;

    // Single character that identifies a channel type
    // TODO make this an enumeration
    private final char type;

    // User-assigned name for the channel
    private final String name;

    /**
     * Constructor.
     *
     * @param i New id
     * @param t New type
     * @param n New name
     */
    public Channel(String i, char t, String n) {
        id = i;
        type = t;
        name = n;
    }

    /**
     * @return The channel identifier
     */
    public String getId() {
        return id;
    }

    /**
     * @see java.io.Serializable#toString()
     */
    @Override
    public String toString() {
        if (type == 'A') {
            return name + " (Aux " + id + ")";
        }
        else {
            return name;
        }
    }

    /**
     * @see java.lang.Comparable#compareTo()
     */
    @Override
    public int compareTo(Channel channel) {
        // TODO enhance this once types are fully implemented
        return Integer.parseInt(id) - Integer.parseInt(channel.getId());
    }

}

Fix a typo in how aux name is printed.

Fix a typo in how aux name is printed.


package edu.yalestc.yalepublic.news;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import org.xml.sax.SAXException;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import edu.yalestc.yalepublic.R;
import edu.yalestc.yalepublic.news.RssReader;
import edu.yalestc.yalepublic.news.RssFeed;

/**
 * Created by Jason Liu on 10/4/14.
 */

public class NewsReader extends Activity {

    TextView tRSSTitle, tRSSContent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.news_items);
        tRSSTitle = (TextView) findViewById(R.id.tvRSSTitle);
        tRSSContent = (TextView) findViewById(R.id.tvRSSContent);

        URL url = null;
        try {
            url = new URL("http://news.yale.edu/news-rss");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        RssFeed feed = null;
        try {
            feed = RssReader.read(url);
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        ArrayList<RssItem> rssItems = feed.getRssItems();
        for(RssItem rssItem : rssItems) {
            Log.d("RSS Reader", rssItem.getTitle());
        }
    }
}

package edu.yalestc.yalepublic.news;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import org.xml.sax.SAXException;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import edu.yalestc.yalepublic.R;
import edu.yalestc.yalepublic.news.RssReader;
import edu.yalestc.yalepublic.news.RssFeed;

/**
 * Created by Jason Liu on 10/4/14.
 */

public class NewsReader extends Activity {

    TextView tRSSTitle, tRSSContent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.news_items);
        tRSSTitle = (TextView) findViewById(R.id.tvRSSTitle);
        tRSSContent = (TextView) findViewById(R.id.tvRSSContent);

        // TODO: Check for Internet Connectivity first
        NewsDownload start = new NewsDownload();
        start.execute();
    }

}

Move download out of main thread (not allowed)


package org.narwhal.core;

/**
 * Date: 28.02.13
 * Time: 20:28
 * Author: Miron Aseev
 */
public class MyFirstTest {
}

package org.narwhal.core;

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

/**
 * Date: 28.02.13
 * Time: 20:28
 * Author: Miron Aseev
 */
@RunWith(JUnit4.class)
public class MyFirstTest {

    @Test
    public void myFirstTestMethod() {

    }

    @Test
    public void mySecondTestMethod() {

    }
}

Test stub has been implemented

Test stub has been implemented


public class Configuration {
    public static String shape_file  = "shape.png";
    public static String input_file  = "input.txt";
    public static String output_file = "out.png";
    public static int width = 600;
    public static int height = 636;
    public static int minSize = 8;
    public static int maxSize = 34;
}

public class Configuration {
    public static String shape_file  = "shape.png";
    public static String input_file  = "input.txt";
    public static String output_file = "out.png";
    public static int width = 500;
    public static int height = 636;
    public static int minSize = 8;
    public static int maxSize = 34;
}

Update to new shape width

Update to new shape width


package org.gluu.persist.couchbase.model;

import com.couchbase.client.java.query.dsl.Expression;

/**
 * Filter to Expression convertation result
 *
 * @author Yuriy Movchan Date: 06/21/2019
 */
public class ConvertedExpression {

	private Expression expression;
	private boolean consistency;

	private ConvertedExpression(Expression expression) {
		this.expression = expression;
	}

	private ConvertedExpression(Expression expression, boolean consistency) {
		this.expression = expression;
		this.consistency = consistency;
	}

	public static ConvertedExpression build(Expression expression, boolean consistency) {
		return new ConvertedExpression(expression, consistency);
	}

	public Expression expression() {
		return expression;
	}

	public boolean consistency() {
		return consistency;
	}

	public void consistency(boolean consistency) {
		this.consistency = consistency;
	}

}

package org.gluu.persist.couchbase.model;

import com.couchbase.client.java.query.dsl.Expression;

/**
 * Filter to Expression convertation result
 *
 * @author Yuriy Movchan Date: 06/21/2019
 */
public class ConvertedExpression {

	private Expression expression;
	private boolean consistency;

	private ConvertedExpression(Expression expression) {
		this.expression = expression;
	}

	private ConvertedExpression(Expression expression, boolean consistency) {
		this.expression = expression;
		this.consistency = consistency;
	}

	public static ConvertedExpression build(Expression expression, boolean consistency) {
		return new ConvertedExpression(expression, consistency);
	}

	public Expression expression() {
		return expression;
	}

	public boolean consistency() {
		return consistency;
	}

	public void consistency(boolean consistency) {
		this.consistency = consistency;
	}

	@Override
	public String toString() {
		return "ConvertedExpression [expression=" + expression + ", consistency=" + consistency + "]";
	}

}

Add to string to show real expression

Add to string to show real expression


package edu.wustl.bulkoperator.processor;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.beanutils.Converter;
import edu.wustl.bulkoperator.metadata.DateValue;
import edu.wustl.common.util.global.ApplicationProperties;
import edu.wustl.common.util.logger.Logger;

public class CustomDateConverter implements Converter {

	private final static String DEFAULT_FORMAT = ApplicationProperties.getValue("bulk.date.valid.format.withtime");
	private static final Logger logger = Logger.getCommonLogger(CustomDateConverter.class);

	public Object convert(Class type, Object value)
	{
		SimpleDateFormat format = null;
		String dateValue=null;
		Date date=null;
		if (value instanceof DateValue)	{
			format = new SimpleDateFormat(((DateValue) value).getFormat());
			dateValue = ((DateValue) value).getValue();
		} else {
			format = new SimpleDateFormat(DEFAULT_FORMAT);
			dateValue=value.toString();
		}
		 try {
			 	date=format.parse(dateValue);
		} catch (ParseException e) {

			logger.error("Error while parsing date.", e);
		}
		return date;
	}

}

package edu.wustl.bulkoperator.processor;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.beanutils.Converter;
import edu.wustl.bulkoperator.metadata.DateValue;
import edu.wustl.common.util.global.ApplicationProperties;
import edu.wustl.common.util.logger.Logger;

public class CustomDateConverter implements Converter {

	private final static String DEFAULT_FORMAT = ApplicationProperties.getValue("bulk.date.valid.format.withtime");
	private static final Logger logger = Logger.getCommonLogger(CustomDateConverter.class);

	public Object convert(Class type, Object value)
	{
		SimpleDateFormat format = null;
		String dateValue=null;
		Date date=null;
		if (value instanceof DateValue)	{
			format = new SimpleDateFormat(((DateValue) value).getFormat());
			format.setLenient(false);
			dateValue = ((DateValue) value).getValue();
		} else {
			format = new SimpleDateFormat(DEFAULT_FORMAT);
			dateValue=value.toString();
		}
		 try {
			 	date=format.parse(dateValue);
		} catch (ParseException e) {

			logger.error("Error while parsing date.", e);
		}
		return date;
	}

}

Fix for default date format issue.

Fix for default date format issue.

SVN-Revision: 402


package org.lodder.subtools.sublibrary.exception;

import org.lodder.subtools.sublibrary.logging.Logger;
import org.lodder.subtools.sublibrary.model.Release;

public class ReleaseControlException extends Exception {

    public ReleaseControlException(String string, Release release) {
        super(string + ": " + release.toString());
        Logger.instance.trace("ReleaseControlException", "ReleaseControlException", "");
    }

    /**
     *
     */
    private static final long serialVersionUID = 1958337660409078923L;

}

package org.lodder.subtools.sublibrary.exception;

import org.lodder.subtools.sublibrary.model.Release;

public class ReleaseControlException extends Exception {

    public ReleaseControlException(String string, Release release) {
        super(string + ": " + release.toString());
    }

    /**
     *
     */
    private static final long serialVersionUID = 1958337660409078923L;

}

Remove trace logging from ReleaseControlExeption What the point of logging in a Exception class?


package lama.sqlite3.gen;

import lama.Query;
import lama.QueryAdapter;

public class SQLite3AnalyzeGenerator {

	public static Query generateAnalyze() {
		return new QueryAdapter("ANALYZE");
	}

}

package lama.sqlite3.gen;

import lama.Query;
import lama.QueryAdapter;
import lama.Randomly;
import lama.sqlite3.schema.SQLite3Schema;

public class SQLite3AnalyzeGenerator {

	public static Query generateAnalyze(SQLite3Schema newSchema) {
		StringBuilder sb = new StringBuilder("ANALYZE");
		if (Randomly.getBoolean()) {
			sb.append(" ");
			sb.append(newSchema.getRandomTable().getName());
			// TODO index
		}
		return new QueryAdapter(sb.toString());
	}

}

Support ANALYZE for a single table

Support ANALYZE for a single table


package com.sb.util;

import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;

/**
 *
 */
public final class MathUtil
{

    private static MathContext context = MathContext.DECIMAL32;

    public static BigDecimal divide(BigDecimal numerator, BigDecimal denominator)
    {
        return numerator.divide(denominator, context);
    }

    public static BigDecimal divide(BigDecimal numerator, int denominator)
    {
        return divide(numerator, BigDecimal.valueOf(denominator));
    }

    public static BigDecimal divide(int numerator, int denominator)
    {
        return divide(BigDecimal.valueOf(numerator), denominator);
    }

    public static BigDecimal multiply(BigDecimal a, int multiplier)
    {
        return a.multiply(BigDecimal.valueOf(multiplier));
    }

}

package com.sb.util;

import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;

/**
 *
 */
public final class MathUtil
{

    private static MathContext context = MathContext.DECIMAL32;

    public static BigDecimal divide(BigDecimal numerator, BigDecimal denominator)
    {
        return numerator.divide(denominator, context);
    }

    public static BigDecimal divide(BigDecimal numerator, int denominator)
    {
        return divide(numerator, BigDecimal.valueOf(denominator));
    }

    public static BigDecimal divide(BigDecimal numerator, double denominator)
    {
        return divide(numerator, BigDecimal.valueOf(denominator));
    }

    public static BigDecimal divide(int numerator, int denominator)
    {
        return divide(BigDecimal.valueOf(numerator), denominator);
    }

    public static BigDecimal multiply(BigDecimal a, int multiplier)
    {
        return a.multiply(BigDecimal.valueOf(multiplier));
    }

    public static BigDecimal multiply(BigDecimal a, double multiplier)
    {
        return a.multiply(BigDecimal.valueOf(multiplier));
    }

}

Add helpers that allow divisions and multiplication with doubles


package de.chandre.admintool.log4j2;

import java.io.IOException;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@WebListener
@Component
public class AdminToolLog4jSessionListener implements HttpSessionListener {

	private static final Log LOGGER = LogFactory.getLog(AdminToolLog4jSessionListener.class);

	public AdminToolLog4jSessionListener() {
		LOGGER.debug("Session listener to remove useless outputstreams has been initialiezed");
	}

	@Autowired
	private AdminToolLog4j2Util log4jUtil;

	@Override
	public void sessionCreated(HttpSessionEvent sessionEvent) {}

	@Override
	public void sessionDestroyed(HttpSessionEvent sessionEvent) {
		String appenderName = (String) sessionEvent.getSession().getAttribute(AdminToolLog4j2Util.SESSION_APPENDER_NAME);
		try {
			log4jUtil.closeOutputStreamAppender(appenderName);
		} catch (IOException e) {
			LOGGER.error(e.getMessage(), e);
		}
	}

}

package de.chandre.admintool.log4j2;

import java.io.IOException;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Session listener to remove unused outputstream appender to free resources
 * you may have to configure @ServletComponentScan
 * @author André
 *
 */
@WebListener
@Component
public class AdminToolLog4jSessionListener implements HttpSessionListener {

	private static final Log LOGGER = LogFactory.getLog(AdminToolLog4jSessionListener.class);

	public AdminToolLog4jSessionListener() {
		LOGGER.debug("Session listener to remove useless outputstreams has been initialiezed");
	}

	@Autowired
	private AdminToolLog4j2Util log4jUtil;

	@Override
	public void sessionCreated(HttpSessionEvent sessionEvent) {}

	@Override
	public void sessionDestroyed(HttpSessionEvent sessionEvent) {
		String appenderName = (String) sessionEvent.getSession().getAttribute(AdminToolLog4j2Util.SESSION_APPENDER_NAME);
		try {
			if (null != log4jUtil) {
				log4jUtil.closeOutputStreamAppender(appenderName);
			}
		} catch (IOException e) {
			LOGGER.error(e.getMessage(), e);
		}
	}
}

Fix NPE in Log4j SessionListener

Fix NPE in Log4j SessionListener


package com.liuhc.tools.demo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

import com.liuhc.tools.DateFormatHelper;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String date = DateFormatHelper.getCurrentTime(DateFormatHelper.FORMAT_SECOND);
//        Toast.makeText(this, date, Toast.LENGTH_SHORT).show();
    }
}

package com.liuhc.tools.demo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

import com.liuhc.tools.DateFormatHelper;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String date = DateFormatHelper.getCurrentTime(DateFormatHelper.FORMAT_SECOND);
//        Toast.makeText(this, date, Toast.LENGTH_SHORT).show();
    }

    public void one(){

    }
}

Test File Commit And Reset

Test File Commit  And Reset


package com.smcpartners.shape.usecases.inactivate_provider;

import com.smcpartners.shape.shared.dto.common.BooleanValueDTO;
import com.smcpartners.shape.shared.dto.shape.request.IntEntityIdRequestDTO;
import com.smcpartners.shape.shared.usecasecommon.UseCaseException;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

/**
 * Responsible:

 * 1.
 *

 * Created by johndestefano on 11/4/15.
 *

 * Changes:
 */
@Path("admin")
public interface InactivateProviderService {

    @POST
    @Path("/organization/inactivate")
    @Produces("application/json")
    @Consumes("application/json")
    BooleanValueDTO inactivateProvider(IntEntityIdRequestDTO id) throws UseCaseException;
}

package com.smcpartners.shape.usecases.inactivate_provider;

import com.smcpartners.shape.shared.dto.common.BooleanValueDTO;
import com.smcpartners.shape.shared.dto.shape.request.IntEntityIdRequestDTO;
import com.smcpartners.shape.shared.usecasecommon.UseCaseException;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

/**
 * Responsible:

 * 1.
 *

 * Created by johndestefano on 11/4/15.
 *

 * Changes:
 */
@Path("admin")
public interface InactivateProviderService {

    @POST
    @Path("/provider/inactivate")
    @Produces("application/json")
    @Consumes("application/json")
    BooleanValueDTO inactivateProvider(IntEntityIdRequestDTO id) throws UseCaseException;
}

Change typo in inactivate provider service


/*
 * 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.teradata.tempto.internal.fulfillment.table;

import java.util.UUID;

public class TableNameGenerator
{
    private static final String MUTABLE_TABLE_NAME_PREFIX = "tempto_mut_";

    public String generateMutableTableNameInDatabase(String baseTableName)
    {
        String tableSuffix = randomUUID().replace("-", "");
        return MUTABLE_TABLE_NAME_PREFIX + baseTableName + "_" + tableSuffix;
    }

    public boolean isMutableTableName(String tableNameInDatabase)
    {
        return tableNameInDatabase.startsWith(MUTABLE_TABLE_NAME_PREFIX);
    }

    private String randomUUID()
    {
        return UUID.randomUUID().toString();
    }
}

/*
 * 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.teradata.tempto.internal.fulfillment.table;

import static org.apache.commons.lang3.RandomStringUtils.random;

public class TableNameGenerator
{
    private static final String MUTABLE_TABLE_NAME_PREFIX = "tempto_mut_";

    public String generateMutableTableNameInDatabase(String baseTableName)
    {
        return MUTABLE_TABLE_NAME_PREFIX + baseTableName + "_" + random(8);
    }

    public boolean isMutableTableName(String tableNameInDatabase)
    {
        return tableNameInDatabase.startsWith(MUTABLE_TABLE_NAME_PREFIX);
    }
}

Make mutable table suffix shorter

Make mutable table suffix shorter

Pull request: https://github.com/prestodb/tempto/pull/214


class ArrayAccessExpressionTest {
    public static void main(String[] args) {
        int i;
        int[] ia;
        long l;
        long[] la;
        boolean b;
        A cA;
        B cB;

        i = ia[ia]; // INVALID_INDEX_TYPE
        i = ia[l];  // INVALID_INDEX_TYPE
        i = ia[la]; // INVALID_INDEX_TYPE
        i = ia[b];  // INVALID_INDEX_TYPE
        i = ia[cA]; // INVALID_INDEX_TYPE

        l = la[ia];  // INVALID_INDEX_TYPE
        l = la[l];   // INVALID_INDEX_TYPE
        l = la[la];  // INVALID_INDEX_TYPE
        l = la[b];   // INVALID_INDEX_TYPE
        l = la[cA];  // INVALID_INDEX_TYPE

        i = i[i];    // NOT_ARRAY_TYPE
        i = l[i];    // NOT_ARRAY_TYPE
        i = b[i];    // NOT_ARRAY_TYPE
        i = cA[i];   // NOT_ARRAY_TYPE
    }
}
class A {}
class B {}

class ArrayAccessExpressionTest {
    public static void main(String[] args) {
        int i;
        int[] ia;
        long l;
        long[] la;
        boolean b;
        A cA;
        B cB;

        //i = ia[i];// OK!
        i = ia[ia]; // INVALID_INDEX_TYPE
        i = ia[l];  // INVALID_INDEX_TYPE
        i = ia[la]; // INVALID_INDEX_TYPE
        i = ia[b];  // INVALID_INDEX_TYPE
        i = ia[cA]; // INVALID_INDEX_TYPE

        //l = la[i];  // OK!
        l = la[ia];  // INVALID_INDEX_TYPE
        l = la[l];   // INVALID_INDEX_TYPE
        l = la[la];  // INVALID_INDEX_TYPE
        l = la[b];   // INVALID_INDEX_TYPE
        l = la[cA];  // INVALID_INDEX_TYPE

        i = i[i];    // NOT_ARRAY_TYPE
        i = l[i];    // NOT_ARRAY_TYPE
        i = b[i];    // NOT_ARRAY_TYPE
        i = cA[i];   // NOT_ARRAY_TYPE
    }
}
class A {}
class B {}

Add comment about allowed accesses.

Add comment about allowed accesses.


import com.mysql.jdbc.Connection;
import db.DBConnector;

import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by shimin on 9/24/2014.
 */
public class Controller extends DBConnector {

    private double temperature = 0.0;
    private int lighting;
    private int pressure;
    private int humidity;
    private int sound;
    private int sensorID;

    /*
     * A database connection is available through the inherited field 'connection'.
     */

    public double getTemperature(){
        String query =  "SELECT Value FROM TemperatureSample JOIN (" +
                        "SELECT MAX(Date) as MaxDate FROM TemperatureSample AS T1" +
                        ") AS T2 WHERE Date = MaxDate";

        try {
            preparedStatement = connection.prepareStatement(query);
            preparedStatement.execute();
            ResultSet results = preparedStatement.getResultSet();
            results.next();
            temperature = results.getDouble(1);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return temperature;
    }

    public int getLighting(){ return lighting;}

    public int getPressure(){return pressure;}

    public int getHumidity(){return humidity;}

    public int getSound(){return sound;}

    public int getSensorID(){return sensorID;}

    public static void main(String[] args){
        Controller ctrl = new Controller();
        ctrl.connect();
        System.out.println(ctrl.getTemperature());
    }
}

/**
 * Created by shimin on 9/24/2014.
 */
public class Controller {

}

Move responsibility of SQL queries DBManager (different branch)


package org.puller;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.List;

public class Dates {
    public static List<LocalDate> getWednesdays(final LocalDate from, final LocalDate to) {
        final List<LocalDate> wednesdays = new ArrayList<>();

        LocalDate nextWednesday = from.with(TemporalAdjusters.nextOrSame(DayOfWeek.WEDNESDAY));
        while (nextWednesday.isBefore(to) || nextWednesday.isEqual(to)) {
            wednesdays.add(nextWednesday);
            nextWednesday = nextWednesday.with(TemporalAdjusters.next(DayOfWeek.WEDNESDAY));
        }

        return wednesdays;
    }
}

package org.puller;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Period;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Dates {
    public static List<LocalDate> getWednesdays(final LocalDate from, final LocalDate to) {
        final int days = Period.between(from, to).getDays() + 1;
        return Stream.iterate(from, date -> date.plusDays(1))
                .limit(days)
                .filter(date -> date.getDayOfWeek() == DayOfWeek.WEDNESDAY)
                .collect(Collectors.toList());
    }
}

Use stream to generate wednesdays

Use stream to generate wednesdays


package org.knowm.xchange.kucoin.service;

import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.service.trade.params.TradeHistoryParamCurrencyPair;
import org.knowm.xchange.service.trade.params.TradeHistoryParamPaging;

public class KucoinTradeHistoryParams implements TradeHistoryParamCurrencyPair, TradeHistoryParamPaging {

  private CurrencyPair currencyPair;
  private Integer pageLength;
  private Integer pageNumber;

  @Override
  public Integer getPageLength() {
    return pageLength;
  }

  @Override
  public void setPageLength(Integer pageLength) {

    this.pageLength = pageLength;
  }

  @Override
  public Integer getPageNumber() {

    return pageNumber;
  }

  @Override
  public void setPageNumber(Integer pageNumber) {

    this.pageNumber = pageNumber;
  }

  @Override
  public CurrencyPair getCurrencyPair() {

    return currencyPair;
  }

  @Override
  public void setCurrencyPair(CurrencyPair pair) {

    this.currencyPair = pair;
  }

}

package org.knowm.xchange.kucoin.service;

import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.service.trade.params.TradeHistoryParamCurrencyPair;
import org.knowm.xchange.service.trade.params.TradeHistoryParamPaging;
import org.knowm.xchange.service.trade.params.TradeHistoryParamsTimeSpan;

import java.util.Date;

public class KucoinTradeHistoryParams implements
  TradeHistoryParamCurrencyPair, TradeHistoryParamPaging, TradeHistoryParamsTimeSpan
{

  private CurrencyPair currencyPair;
  private Integer pageLength;
  private Integer pageNumber;
  private Date startTime;
  private Date endTime;

  @Override
  public Integer getPageLength() {
    return pageLength;
  }

  @Override
  public void setPageLength(Integer pageLength) {

    this.pageLength = pageLength;
  }

  @Override
  public Integer getPageNumber() {

    return pageNumber;
  }

  @Override
  public void setPageNumber(Integer pageNumber) {

    this.pageNumber = pageNumber;
  }

  @Override
  public CurrencyPair getCurrencyPair() {

    return currencyPair;
  }

  @Override
  public void setCurrencyPair(CurrencyPair pair) {

    this.currencyPair = pair;
  }

  @Override
  public Date getStartTime() {

    return startTime;
  }

  @Override
  public void setStartTime(Date startTime) {

    this.startTime = startTime;
  }

  @Override
  public Date getEndTime() {

    return endTime;
  }

  @Override
  public void setEndTime(Date endTime) {

    this.endTime = endTime;
  }

}

[kucoin] Allow to specify (optional) timespan on trade history params.


package de.gurkenlabs.litiengine.graphics.emitters.particles;

import java.awt.Polygon;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;

public class PolygonParticle extends ShapeParticle {
  private int sides;

  public PolygonParticle(float width, float height, int sides) {
    super(width, height);
    this.sides = sides;
  }

  @Override
  protected Shape getShape(Point2D emitterOrigin) {
    Polygon p = new Polygon();
    float x = this.getAbsoluteX(emitterOrigin) + this.getWidth() / 2;
    float y = this.getAbsoluteY(emitterOrigin) + this.getHeight() / 2;
    float theta = (float) (2 * Math.PI / this.sides);
    for (int i = 0; i < this.sides; i++) {
      p.addPoint(
          (int) (x + this.getWidth() * Math.cos(theta * i)),
          (int) (y + this.getHeight() * Math.sin(theta * i)));
    }
    final AffineTransform rotate =
        AffineTransform.getRotateInstance(
            Math.toRadians(this.getAngle()),
            this.getAbsoluteX(emitterOrigin) + this.getWidth() * 0.5,
            this.getAbsoluteY(emitterOrigin) + this.getHeight() * 0.5);
    return rotate.createTransformedShape(p);
  }
}

package de.gurkenlabs.litiengine.graphics.emitters.particles;

import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.Path2D;
import java.awt.geom.Point2D;

public class PolygonParticle extends ShapeParticle {
  private int sides;

  public PolygonParticle(float width, float height, int sides) {
    super(width, height);
    this.sides = sides;
  }

  @Override
  protected Shape getShape(Point2D emitterOrigin) {
    Path2D path = new Path2D.Double();
    double x = this.getAbsoluteX(emitterOrigin) + this.getWidth() / 2;
    double y = this.getAbsoluteY(emitterOrigin) + this.getHeight() / 2;
    double theta = 2 * Math.PI / this.sides;
    path.moveTo(x + this.getWidth(), y + 0);
    for (int i = 0; i < this.sides; i++) {
      path.lineTo(
          x + this.getWidth() * Math.cos(theta * i),
          y + this.getHeight() * Math.sin(theta * i));
    }
    path.closePath();
    final AffineTransform rotate =
        AffineTransform.getRotateInstance(
            Math.toRadians(this.getAngle()),
            this.getAbsoluteX(emitterOrigin) + this.getWidth() * 0.5,
            this.getAbsoluteY(emitterOrigin) + this.getHeight() * 0.5);
    return rotate.createTransformedShape(path);
  }
}

Fix polygon particle rounding errors

Fix polygon particle rounding errors

Fixes #418


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

import org.jboss.weld.environment.se.bindings.Parameters;
import org.jboss.weld.environment.se.events.ContainerInitialized;

import javax.enterprise.event.Observes;
import javax.inject.Singleton;
import java.util.List;

@Singleton
public class BootStrap {

    public void start(@Observes ContainerInitialized event, @Parameters List<String> parameters) {
        System.out.println("Camel CDI :: Example 1 will be started");
    }

}

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

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.Initialized;
import javax.enterprise.event.Observes;
import javax.inject.Singleton;

@Singleton
public class BootStrap {

    public void start(@Observes @Initialized(ApplicationScoped.class) Object event) {
        System.out.println("Camel CDI :: Example 1 will be started");
    }
}

Use standard CDI lifecycle event

Use standard CDI lifecycle event


package org.vaadin.spring.mvp.autowired;

import org.vaadin.spring.UIScope;
import org.vaadin.spring.annotation.VaadinComponent;
import org.vaadin.spring.mvp.FooView;

@UIScope
@VaadinComponent
public class AnnotatedFooView extends FooView {

    private static final long serialVersionUID = -4497836114697117034L;

}

package org.vaadin.spring.mvp.autowired;

import org.vaadin.spring.annotation.VaadinComponent;
import org.vaadin.spring.annotation.VaadinUIScope;
import org.vaadin.spring.mvp.FooView;

@VaadinUIScope
@VaadinComponent
public class AnnotatedFooView extends FooView {

    private static final long serialVersionUID = -4497836114697117034L;

}

Test Class Update: Changed UIScope => VaadinUIScope


package com.genymobile.scrcpy;

import android.util.Log;

/**
 * Log both to Android logger (so that logs are visible in "adb logcat") and standard output/error (so that they are visible in the terminal
 * directly).
 */
public final class Ln {

    private static final String TAG = "scrcpy";

    enum Level {
        DEBUG,
        INFO,
        WARN,
        ERROR;
    }

    private static final Level THRESHOLD = BuildConfig.DEBUG ? Level.DEBUG : Level.INFO;

    private Ln() {
        // not instantiable
    }

    public static boolean isEnabled(Level level) {
        return level.ordinal() >= THRESHOLD.ordinal();
    }

    public static void d(String message) {
        if (isEnabled(Level.DEBUG)) {
            Log.d(TAG, message);
            System.out.println("DEBUG: " + message);
        }
    }

    public static void i(String message) {
        if (isEnabled(Level.INFO)) {
            Log.i(TAG, message);
            System.out.println("INFO: " + message);
        }
    }

    public static void w(String message) {
        if (isEnabled(Level.WARN)) {
            Log.w(TAG, message);
            System.out.println("WARN: " + message);
        }
    }

    public static void e(String message, Throwable throwable) {
        if (isEnabled(Level.ERROR)) {
            Log.e(TAG, message, throwable);
            System.out.println("ERROR: " + message);
            throwable.printStackTrace();
        }
    }
}

package com.genymobile.scrcpy;

import android.util.Log;

/**
 * Log both to Android logger (so that logs are visible in "adb logcat") and standard output/error (so that they are visible in the terminal
 * directly).
 */
public final class Ln {

    private static final String TAG = "scrcpy";

    enum Level {
        DEBUG,
        INFO,
        WARN,
        ERROR;
    }

    private static final Level THRESHOLD = BuildConfig.DEBUG ? Level.DEBUG : Level.INFO;

    private Ln() {
        // not instantiable
    }

    public static boolean isEnabled(Level level) {
        return level.ordinal() >= THRESHOLD.ordinal();
    }

    public static void d(String message) {
        if (isEnabled(Level.DEBUG)) {
            Log.d(TAG, message);
            System.out.println("DEBUG: " + message);
        }
    }

    public static void i(String message) {
        if (isEnabled(Level.INFO)) {
            Log.i(TAG, message);
            System.out.println("INFO: " + message);
        }
    }

    public static void w(String message) {
        if (isEnabled(Level.WARN)) {
            Log.w(TAG, message);
            System.out.println("WARN: " + message);
        }
    }

    public static void e(String message, Throwable throwable) {
        if (isEnabled(Level.ERROR)) {
            Log.e(TAG, message, throwable);
            System.out.println("ERROR: " + message);
            if (throwable != null) {
                throwable.printStackTrace();
            }
        }
    }

    public static void e(String message) {
        e(message, null);
    }
}

Add method to log error without throwable

Add Ln.e(message) in addition to Ln.e(message, error).