package gov.nasa.arc.mct.scenario.component;

import gov.nasa.arc.mct.components.AbstractComponent;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

public class TimelineComponent extends CostFunctionComponent {

	public String getDisplay(){
		return this.getDisplayName();
	}

	private Set<AbstractComponent> modifiedObjects = new HashSet<AbstractComponent>();
	public void addToModifiedObjects(AbstractComponent ac) {
		modifiedObjects.add(ac);
	}
	@Override
	public Set<AbstractComponent> getAllModifiedObjects() {
		return modifiedObjects;
	}

	@Override
	public void notifiedSaveAllSuccessful() {
		modifiedObjects.clear();
	}
}

package gov.nasa.arc.mct.scenario.component;

import gov.nasa.arc.mct.components.AbstractComponent;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

public class TimelineComponent extends CostFunctionComponent implements DurationCapability {

	public String getDisplay(){
		return this.getDisplayName();
	}

	private Set<AbstractComponent> modifiedObjects = new HashSet<AbstractComponent>();

	@Override
	protected <T> T handleGetCapability(Class<T> capability) {
		if (capability.isAssignableFrom(getClass())) {
			return capability.cast(this);
		}
		return super.handleGetCapability(capability);
	}

	public void addToModifiedObjects(AbstractComponent ac) {
		modifiedObjects.add(ac);
	}
	@Override
	public Set<AbstractComponent> getAllModifiedObjects() {
		return modifiedObjects;
	}

	@Override
	public void notifiedSaveAllSuccessful() {
		modifiedObjects.clear();
	}

	@Override
	public long getStart() {
		return 0;
	}
	@Override
	public long getEnd() {
		// The end of a Timeline is the end of its last activity
		long end = 0;
		for (AbstractComponent child : getComponents()) {
			DurationCapability dc = child.getCapability(DurationCapability.class);
			if (dc != null) {
				long childEnd = dc.getEnd();
				if (childEnd > end) {
					end = childEnd;
				}
			}
		}
		return end;
	}
	@Override
	public void setStart(long start) {
		// TODO Auto-generated method stub

	}
	@Override
	public void setEnd(long end) {
		// TODO Auto-generated method stub

	}
}

Support DurationCapability in Timeline view


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

package com.tdunning.math.stats;

public class BigCountTreeDigest extends BigCount {
    @Override
    public TDigest createDigest() {
        return new AVLTreeDigest(20);
    }
}

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

package com.tdunning.math.stats;

public class BigCountTreeDigest extends BigCount {
    @Override
    public TDigest createDigest() {
        return new AVLTreeDigest(100);
    }
}

Update to modern meaning of compression factor


package net.md_5.bungee.connection;

import lombok.RequiredArgsConstructor;
import net.md_5.bungee.api.Callback;
import net.md_5.bungee.api.ServerPing;
import net.md_5.bungee.api.config.ServerInfo;
import net.md_5.bungee.netty.ChannelWrapper;
import net.md_5.bungee.netty.PacketHandler;
import net.md_5.bungee.protocol.packet.PacketFFKick;

@RequiredArgsConstructor
public class PingHandler extends PacketHandler
{

    private final ServerInfo target;
    private final Callback<ServerPing> callback;
    private static final byte[] pingBuf = new byte[]
    {
        (byte) 0xFE, (byte) 0x01
    };

    @Override
    public void connected(ChannelWrapper channel) throws Exception
    {
        channel.write( pingBuf );
    }

    @Override
    public void exception(Throwable t) throws Exception
    {
        callback.done( null, t );
    }

    @Override
    public void handle(PacketFFKick kick) throws Exception
    {
        String[] split = kick.getMessage().split( "\00" );
        ServerPing ping = new ServerPing( Byte.parseByte( split[1] ), split[2], split[3], Integer.parseInt( split[4] ), Integer.parseInt( split[5] ) );
        callback.done( ping, null );
    }

    @Override
    public String toString()
    {
        return "[Ping Handler] -> " + target.getName();
    }
}

package net.md_5.bungee.connection;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import lombok.RequiredArgsConstructor;
import net.md_5.bungee.api.Callback;
import net.md_5.bungee.api.ServerPing;
import net.md_5.bungee.api.config.ServerInfo;
import net.md_5.bungee.netty.ChannelWrapper;
import net.md_5.bungee.netty.PacketHandler;
import net.md_5.bungee.protocol.packet.PacketFFKick;

@RequiredArgsConstructor
public class PingHandler extends PacketHandler
{

    private final ServerInfo target;
    private final Callback<ServerPing> callback;
    // TODO: Update this to 1.6.2 style!
    private static final ByteBuf pingBuf = Unpooled.wrappedBuffer( new byte[]
    {
        (byte) 0xFE, (byte) 0x01
    } );

    @Override
    public void connected(ChannelWrapper channel) throws Exception
    {
        channel.write( pingBuf );
    }

    @Override
    public void exception(Throwable t) throws Exception
    {
        callback.done( null, t );
    }

    @Override
    public void handle(PacketFFKick kick) throws Exception
    {
        String[] split = kick.getMessage().split( "\00" );
        ServerPing ping = new ServerPing( Byte.parseByte( split[1] ), split[2], split[3], Integer.parseInt( split[4] ), Integer.parseInt( split[5] ) );
        callback.done( ping, null );
    }

    @Override
    public String toString()
    {
        return "[Ping Handler] -> " + target.getName();
    }
}

Write down a supported message type (ByteBuf) when using the ping handler.


/*
 * Copyright (c) 2017 General Electric Company. All rights reserved.
 *
 * The copyright to the computer software herein is the property of General Electric Company.
 * The software may be used and/or copied only with the written permission of
 * General Electric Company or in accordance with the terms and conditions stipulated in the
 * agreement/contract under which the software has been supplied.
 */

package org.axonframework.sample.axonbank.myaxonbank;

import org.axonframework.commandhandling.CommandBus;
import org.axonframework.sample.axonbank.myaxonbank.coreapi.CreateAccountCommand;
import org.axonframework.sample.axonbank.myaxonbank.coreapi.WithdrawMoneyCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import static org.axonframework.commandhandling.GenericCommandMessage.asCommandMessage;

@RestController
public class MyController {

  @Autowired
  private CommandBus commandBus;

  @RequestMapping(value = "/hello")
  public String say() {
    System.out.println("Command Bus>>>>" + commandBus);
    commandBus.dispatch(asCommandMessage(new CreateAccountCommand("1234", 1000)));
    commandBus.dispatch(asCommandMessage(new WithdrawMoneyCommand("1234", 800)));
    return "Hello!";

  }
}

/*
 * Copyright (c) 2017 General Electric Company. All rights reserved.
 *
 * The copyright to the computer software herein is the property of General Electric Company.
 * The software may be used and/or copied only with the written permission of
 * General Electric Company or in accordance with the terms and conditions stipulated in the
 * agreement/contract under which the software has been supplied.
 */

package org.axonframework.sample.axonbank.myaxonbank;

import org.axonframework.commandhandling.gateway.CommandGateway;
import org.axonframework.sample.axonbank.myaxonbank.coreapi.CreateAccountCommand;
import org.axonframework.sample.axonbank.myaxonbank.coreapi.WithdrawMoneyCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

  @Autowired
  private CommandGateway commandGateway;

  @RequestMapping(value = "/hello")
  public String say() {
    commandGateway.send(new CreateAccountCommand("1234", 1000));
    commandGateway.send(new WithdrawMoneyCommand("1234", 800));
    commandGateway.send(new WithdrawMoneyCommand("1234", 500));
    return "Hello!";

  }
}

Use command gateway instead of command bus to generate commands


/*
 * Copyright 2015 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.tooling;

import org.gradle.api.Incubating;
import org.gradle.api.Nullable;

/**
 * Describes a test.
 *
 * @since 2.4
 */
@Incubating
public interface TestDescriptor {

    /**
     * Returns the name of the test.
     *
     * @return the name of the test, never null
     */
    String getName();

    /**
     * Returns the name of the test class, if any.
     *
     * @return the name of the test class, can be null
     */
    String getClassName();

    /**
     * Returns the parent of this test, if any.
     *
     * @return the parent of this test, can be null
     */
    @Nullable
    TestDescriptor getParent();

}

/*
 * Copyright 2015 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.tooling;

import org.gradle.api.Incubating;

/**
 * Describes a test.
 *
 * @since 2.4
 */
@Incubating
public interface TestDescriptor {

    /**
     * Returns the name of the test.
     *
     * @return the name of the test, never null
     */
    String getName();

    /**
     * Returns the name of the test class, if any.
     *
     * @return the name of the test class, can be null
     */
    String getClassName();

    /**
     * Returns the parent of this test, if any.
     *
     * @return the parent of this test, can be null
     */
    TestDescriptor getParent();

}

Revert "Annotate getParent with @Nullable"

This reverts commit 1bdb91ce87ec473fa5ef78cd3b3565337b400e84.


/*
 * Copyright 2016-2020 52°North Initiative for Geospatial Open Source
 * Software GmbH
 *
 * 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.n52.javaps.rest.model;

import org.springframework.validation.annotation.Validated;

import java.util.ArrayList;
import java.util.Objects;

/**
 * AllowedValues
 */
@Validated
public class AllowedValues extends ArrayList<Object> {

    @Override
    public boolean equals(java.lang.Object o) {
        if (this == o) {
            return true;
        }
        return o != null && getClass() == o.getClass();
    }

    @Override
    public int hashCode() {
        return Objects.hash(super.hashCode());
    }

    @Override
    public String toString() {
        return String.format("AllowedValues {%s}", super.toString());
    }
}

/*
 * Copyright 2016-2020 52°North Initiative for Geospatial Open Source
 * Software GmbH
 *
 * 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.n52.javaps.rest.model;

import org.springframework.validation.annotation.Validated;

import java.util.ArrayList;
import java.util.Objects;

/**
 * AllowedValues
 */
@Validated
public class AllowedValues extends ArrayList<Object> {

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

    @Override
    public boolean equals(java.lang.Object o) {
        if (this == o) {
            return true;
        }
        return o != null && getClass() == o.getClass();
    }

    @Override
    public int hashCode() {
        return Objects.hash(super.hashCode());
    }

    @Override
    public String toString() {
        return String.format("AllowedValues {%s}", super.toString());
    }
}

Add generated serial version UUID

Add generated serial version UUID


package hwo.kurjatturskat.core.message;

public enum MessageType {

    // NOTE: Enums must be in small letter for json to be outputted correctly
    carPositions("carPositions"), yourCar("yourCar"), join("join"), gameInit(
            "gameInit"), gameStart("gameStart"), throttle("throttle"), switchLane(
            "switchLane"), unknown("unknown"), lapFinished("lapFinished"), spawn(
            "spawn"), crash("crash"), finish("finish"), gameEnd("gameEnd");

    private final String type;

    MessageType(String type) {
        this.type = type;
    }

    public String getType() {
        return this.type;
    }

    public static MessageType get(String type) {
        for (MessageType enumType : MessageType.values()) {
            if (enumType.getType().equals(type)) {
                return enumType;
            }
        }
        return unknown;
    }

}

package hwo.kurjatturskat.core.message;

public enum MessageType {

    // NOTE: Enums must be in small letter and match to the msgType field value
    // in the messages. Otherwise gson cannot map them
    carPositions, yourCar, join, gameInit, gameStart, throttle, switchLane, unknown, lapFinished, spawn, crash, finish, gameEnd;

}

Remove the parameterized enum as it could not be used with gson


/*
 * Copyright 2019, TeamDev. All rights reserved.
 *
 * Redistribution and use in source and/or binary forms, with or without
 * modification, must retain the above copyright notice and the following
 * disclaimer.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package io.spine.system.server;

import io.spine.server.aggregate.Aggregate;
import io.spine.server.aggregate.AggregateRepository;
import io.spine.server.route.EventRoute;

/**
 * Abstract base for system aggregate repositories.
 *
 * <p>System repositories dispatch imported events using the first event message field.
 */
abstract class SystemRepository<I, A extends Aggregate<I, ?, ?>>
        extends AggregateRepository<I, A> {

    SystemRepository() {
        super();
        eventImportRouting().replaceDefault(EventRoute.byFirstMessageField());
    }
}

/*
 * Copyright 2019, TeamDev. All rights reserved.
 *
 * Redistribution and use in source and/or binary forms, with or without
 * modification, must retain the above copyright notice and the following
 * disclaimer.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package io.spine.system.server;

import io.spine.server.aggregate.Aggregate;
import io.spine.server.aggregate.AggregateRepository;
import io.spine.server.entity.EventFilter;
import io.spine.server.route.EventRoute;

/**
 * Abstract base for system aggregate repositories.
 *
 * <p>System repositories dispatch imported events using the first event message field.
 */
abstract class SystemRepository<I, A extends Aggregate<I, ?, ?>>
        extends AggregateRepository<I, A> {

    SystemRepository() {
        super();
        eventImportRouting().replaceDefault(EventRoute.byFirstMessageField());
    }

    @Override
    protected EventFilter eventFilter() {
        return EventFilter.allowAll();
    }
}

Make system entities post any kind of events.


package com.levien.synthesizer.android.ui;

import android.os.Bundle;
import android.preference.PreferenceActivity;

import com.levien.synthesizer.R;

public class SettingsActivity extends PreferenceActivity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);
  }
}

package com.levien.synthesizer.android.ui;

import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;

import com.levien.synthesizer.R;

public class SettingsActivity extends PreferenceActivity {
  @SuppressWarnings("deprecation")
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);
    ListPreference keyboardTypePref = (ListPreference)findPreference("keyboard_type");
    updateListSummary(keyboardTypePref, keyboardTypePref.getValue());
    keyboardTypePref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
      public boolean onPreferenceChange(Preference pref, Object newVal) {
        updateListSummary(pref, newVal.toString());
        return true;
      }
    });
  }

  private void updateListSummary(Preference pref, String newVal) {
    ListPreference lp = (ListPreference)pref;
    int index = lp.findIndexOfValue(newVal);
    lp.setSummary(lp.getEntries()[index]);
  }
}

Make keyboard type show up in preferences list

Show the actual current setting of the preference in the summary.


package interviewquestions;

/**
 * Given an array of integers (positive and negative) find the
 * largest continuous sum
 */
public class ContinuousSum extends TestCase {
  public static int largestSum(int[] array) {
    assert(array.length > 0);
    int maxsum = array[0];
    int current = array[0];
    for (int i = 1; i < array.length; i++) {
      current = Math.max(current + array[i], array[i]);
      maxsum = Math.max(current, maxsum);
    }
    return maxsum;
  }

  public static void main(String[] args) {
    assertEquals(21, largestSum(new int[] { 1, 2, 3, 4, 5, 6 }));
    assertEquals(15, largestSum(new int[] { 1, 2, -3, 4, 5, 6 }));
    assertEquals(102, largestSum(new int[] { 100, 2, -300, 4, 5, 6 }));
    assertEquals(1, largestSum(new int[] { -1, -2, -3, 1, -5, -6 }));
  }
}

package interviewquestions;

/**
 * Given an array of integers (positive and negative) find the
 * largest continuous sum
 */
public class ContinuousSum extends TestCase {
  public static int largestSum(int[] array) {
    assert(array.length > 0);
    int maxsum = array[0];
    int current = array[0];
    for (int i = 1; i < array.length; i++) {
      current = Math.max(current + array[i], array[i]);
      maxsum = Math.max(current, maxsum);
    }
    return maxsum;
  }

  public static void main(String[] args) {
    assertEquals(21, largestSum(new int[] { 1, 2, 3, 4, 5, 6 }));
    assertEquals(15, largestSum(new int[] { 1, 2, -3, 4, 5, 6 }));
    assertEquals(102, largestSum(new int[] { 100, 2, -300, 4, 5, 6 }));
    assertEquals(1, largestSum(new int[] { -1, -2, -3, 1, -5, -6 }));
    assertEquals(0, largestSum(new int[] { 0, 0, 0, 0 }));
    assertEquals(-10, largestSum(new int[] { -15, -10, -20, -30 }));
  }
}

Test edge cases on largest sum

Test edge cases on largest sum


package at.splendit.example.hibernate.domain;

import java.io.Serializable;

import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.Transient;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;

@MappedSuperclass
public abstract class AbstractEntityObject<T> implements Serializable {

	protected static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	protected T id;

	public T getId() {
		return id;
	}

	public void setId(T id) {
		this.id = id;
	}

	@Override
	@Transient
	public int hashCode() {
		return HashCodeBuilder.reflectionHashCode(17, 37, this, false, AbstractEntityObject.class);
	}

	@Override
	@Transient
	public boolean equals(Object obj) {
		return EqualsBuilder.reflectionEquals(this, obj, false, AbstractEntityObject.class);
	}

	@Override
	@Transient
	public String toString() {
		return ReflectionToStringBuilder.toString(this, null, false, false, AbstractEntityObject.class);
	}

}

package at.splendit.example.hibernate.domain;

import java.io.Serializable;

import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.Transient;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;

@MappedSuperclass
public abstract class AbstractEntityObject<T extends Serializable> implements Serializable {

	protected static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	protected T id;

	public T getId() {
		return id;
	}

	public void setId(T id) {
		this.id = id;
	}

	@Override
	@Transient
	public int hashCode() {
		return HashCodeBuilder.reflectionHashCode(17, 37, this, false, AbstractEntityObject.class);
	}

	@Override
	@Transient
	public boolean equals(Object obj) {
		return EqualsBuilder.reflectionEquals(this, obj, false, AbstractEntityObject.class);
	}

	@Override
	@Transient
	public String toString() {
		return ReflectionToStringBuilder.toString(this, null, false, false, AbstractEntityObject.class);
	}

}

ADD id must be implement Serializable

ADD id must be implement Serializable


package scoutmgr.server.test.util;

import scoutmgr.server.entity.ScoutmgrPersistenceUnit;
import org.realityforge.guiceyloops.server.glassfish.GlassFishContainer;
import org.realityforge.guiceyloops.server.glassfish.GlassFishContainerUtil;

public final class AppServer
{
  private static final String APP_NAME = "scoutmgr";
  private static final String CONTEXT_ROOT = "/" + APP_NAME;
  private static GlassFishContainer c_glassfish;
  private static String c_baseHttpURL;

  private AppServer()
  {
  }

  protected static String getServiceURL( final String service )
  {
    return c_baseHttpURL + "/api/soap/Scoutmgr/Scoutmgr/" + service;
  }

  protected static String getSiteURL()
  {
    return c_baseHttpURL + CONTEXT_ROOT;
  }

  static void setUpAppServer()
    throws Exception
  {
    if ( null == c_glassfish )
    {
      c_glassfish = new GlassFishContainer();
      c_glassfish.start();
      c_glassfish.createSqlServerJdbcResource( ScoutmgrPersistenceUnit.RESOURCE_NAME );
      c_glassfish.deploy( CONTEXT_ROOT, APP_NAME, GlassFishContainerUtil.getWarFile() );

      c_baseHttpURL = c_glassfish.getBaseHttpURL();
    }
  }

  static void tearDownAppServer()
  {
    if ( null != c_glassfish )
    {
      c_glassfish.stop();
      c_glassfish = null;
      c_baseHttpURL = null;
    }
  }
}

package scoutmgr.server.test.util;

import scoutmgr.server.entity.ScoutmgrPersistenceUnit;
import org.realityforge.guiceyloops.server.glassfish.GlassFishContainer;
import org.realityforge.guiceyloops.server.glassfish.GlassFishContainerUtil;

public final class AppServer
{
  private static final String APP_NAME = "scoutmgr";
  private static final String CONTEXT_ROOT = "/" + APP_NAME;
  private static GlassFishContainer c_glassfish;
  private static String c_baseHttpURL;

  private AppServer()
  {
  }

  protected static String getServiceURL( final String service )
  {
    return c_baseHttpURL + "/api/soap/Scoutmgr/Scoutmgr/" + service;
  }

  protected static String getSiteURL()
  {
    return c_baseHttpURL + CONTEXT_ROOT;
  }

  static void setUpAppServer()
    throws Exception
  {
    if ( null == c_glassfish )
    {
      c_glassfish = new GlassFishContainer();
      c_glassfish.start();
      c_glassfish.createPostgresJdbcResource( ScoutmgrPersistenceUnit.RESOURCE_NAME );
      c_glassfish.deploy( CONTEXT_ROOT, APP_NAME, GlassFishContainerUtil.getWarFile() );

      c_baseHttpURL = c_glassfish.getBaseHttpURL();
    }
  }

  static void tearDownAppServer()
  {
    if ( null != c_glassfish )
    {
      c_glassfish.stop();
      c_glassfish = null;
      c_baseHttpURL = null;
    }
  }
}

Create postgres jdbc resource, not mssql


/*
 * Copyright 2014 Guidewire Software, Inc.
 */
package gw.internal.gosu.parser.expressions;

import gw.internal.gosu.parser.Expression;
import gw.lang.parser.IExpression;
import gw.lang.parser.expressions.ILiteralExpression;
import gw.lang.parser.expressions.ITypeAsExpression;
import gw.lang.reflect.IType;
import gw.lang.reflect.java.JavaTypes;

/**
 * The root (marker) class for all Literal expressions.
 */
public class DefaultArgLiteral extends Expression implements ILiteralExpression
{
  private IExpression _expr;

  public DefaultArgLiteral( IType type, IExpression expr )
  {
    setType( type );
    _expr = expr;
  }

  public Object getValue()
  {
    if( getType() == JavaTypes.BIG_DECIMAL() || getType() == JavaTypes.BIG_INTEGER() )
    {
      return _expr.evaluate().toString();
    }
    else
    {
      return _expr.evaluate();
    }
  }

  public IExpression getExpression()
  {
    return _expr;
  }

  @Override
  public boolean isCompileTimeConstant()
  {
    return _expr.isCompileTimeConstant();
  }

  @Override
  public Object evaluate() {
    return _expr.evaluate();
  }

  @Override
  public String toString()
  {
    return "Named Arg Value: " + _expr.toString();
  }

}

/*
 * Copyright 2014 Guidewire Software, Inc.
 */
package gw.internal.gosu.parser.expressions;

import gw.internal.gosu.parser.Expression;
import gw.lang.parser.IExpression;
import gw.lang.parser.expressions.ILiteralExpression;
import gw.lang.parser.expressions.ITypeAsExpression;
import gw.lang.reflect.IType;
import gw.lang.reflect.java.JavaTypes;

/**
 * The root (marker) class for all Literal expressions.
 */
public class DefaultArgLiteral extends Expression implements ILiteralExpression
{
  private IExpression _expr;

  public DefaultArgLiteral( IType type, IExpression expr )
  {
    setType( type );
    _expr = expr;
  }

  public Object getValue()
  {
    if( !(_expr instanceof NullExpression) && getType() == JavaTypes.BIG_DECIMAL() || getType() == JavaTypes.BIG_INTEGER() )
    {
      return _expr.evaluate().toString();
    }
    else
    {
      return _expr.evaluate();
    }
  }

  public IExpression getExpression()
  {
    return _expr;
  }

  @Override
  public boolean isCompileTimeConstant()
  {
    return _expr.isCompileTimeConstant();
  }

  @Override
  public Object evaluate() {
    return _expr.evaluate();
  }

  @Override
  public String toString()
  {
    return "Named Arg Value: " + _expr.toString();
  }

}

Fix NPE when we compile a null default BigDecimal or BigInteger literal


package ru.noties.markwon.core;

import android.support.annotation.NonNull;

import org.commonmark.node.Node;

import ru.noties.markwon.MarkwonVisitor;

/**
 * A {@link ru.noties.markwon.MarkwonVisitor.NodeVisitor} that ensures that a markdown
 * block starts with a new line, all children are visited and if further content available
 * ensures a new line after self. Does not render any spans
 *
 * @since 3.0.0
 */
public class SimpleBlockNodeVisitor implements MarkwonVisitor.NodeVisitor<Node> {
    @Override
    public void visit(@NonNull MarkwonVisitor visitor, @NonNull Node node) {

        visitor.ensureNewLine();

        visitor.visitChildren(node);

        if (visitor.hasNext(node)) {
            visitor.ensureNewLine();
            visitor.forceNewLine();
        }
    }
}

package ru.noties.markwon.core;

import android.support.annotation.NonNull;

import org.commonmark.node.Node;

import ru.noties.markwon.MarkwonVisitor;

/**
 * A {@link ru.noties.markwon.MarkwonVisitor.NodeVisitor} that ensures that a markdown
 * block starts with a new line, all children are visited and if further content available
 * ensures a new line after self. Does not render any spans
 *
 * @since 3.0.0
 */
public class SimpleBlockNodeVisitor implements MarkwonVisitor.NodeVisitor<Node> {
    @Override
    public void visit(@NonNull MarkwonVisitor visitor, @NonNull Node node) {

        // @since 3.0.1-SNAPSHOT we keep track of start in order to apply spans (optionally)
        final int length = visitor.length();

        visitor.ensureNewLine();

        visitor.visitChildren(node);

        // @since 3.0.1-SNAPSHOT we apply optional spans
        visitor.setSpansForNodeOptional(node, length);

        if (visitor.hasNext(node)) {
            visitor.ensureNewLine();
            visitor.forceNewLine();
        }
    }
}

Add optional spans for list blocks

Add optional spans for list blocks


package butterknife.lint;

import com.android.tools.lint.client.api.IssueRegistry;
import com.android.tools.lint.detector.api.Issue;
import com.google.common.collect.ImmutableList;
import java.util.List;

/**
 * Contains references to all custom lint checks for butterknife.
 */
public class LintRegistry extends IssueRegistry {

  @Override public List<Issue> getIssues() {
    return ImmutableList.of(InvalidR2UsageDetector.ISSUE);
  }
}

package butterknife.lint;

import com.android.tools.lint.client.api.IssueRegistry;
import com.android.tools.lint.detector.api.ApiKt;
import com.android.tools.lint.detector.api.Issue;
import com.google.common.collect.ImmutableList;
import java.util.List;

/**
 * Contains references to all custom lint checks for butterknife.
 */
public class LintRegistry extends IssueRegistry {

  @Override public List<Issue> getIssues() {
    return ImmutableList.of(InvalidR2UsageDetector.ISSUE);
  }

  @Override public int getApi() {
    return ApiKt.CURRENT_API;
  }
}

Update Lint checks to new APIs

Update Lint checks to new APIs


package com.semperos.screwdriver.pipeline;

/**
 * Created with IntelliJ IDEA.
 * User: semperos
 * Date: 2/6/13
 * Time: 4:43 PM
 * To change this template use File | Settings | File Templates.
 */
public class PipelineEnvironmentTest {
    public void testGetAssetPaths() throws Exception {

    }

    public void testGetAssetExtensions() throws Exception {

    }

    public void testGetAllAssets() throws Exception {

    }
}

package com.semperos.screwdriver.pipeline;

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

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

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

/**
 * Created with IntelliJ IDEA.
 * User: semperos
 * Date: 2/6/13
 * Time: 4:43 PM
 * To change this template use File | Settings | File Templates.
 */
public class PipelineEnvironmentTest {
    private PipelineEnvironment pe;
    @Before
    public void setUp() throws Exception {
        this.pe = new PipelineEnvironment(new File(
                System.getProperty("user.dir"),
                /**
                 * @todo Set base path up correctly
                 */
                "src/test/resources/com/semperos/screwdriver/sample"));
    }

    @Test
    public void testGetAssetPaths() throws Exception {
        HashMap<AssetType, ArrayList<File>> allPaths = pe.getAssetPaths();
        assertTrue(allPaths.size() >= 3);
        for (Map.Entry<AssetType, ArrayList<File>> path : allPaths.entrySet()) {
            for (File f : path.getValue()) {
                assertTrue(f.exists());
            }
        }
    }

    @Test
    public void testGetAssetExtensions() throws Exception {
        HashMap<AssetType, ArrayList<String>> extensions = pe.getAssetExtensions();
        assertTrue(extensions.size() >= 2);
    }

    @Test
    public void testGetAllAssets() throws Exception {
        ArrayList assets = pe.getAllAssets(AssetType.JAVASCRIPT);
        assertTrue(assets.size() >= 2);
    }
}

Add elementary tests for PipelineEnvironment asset paths


package com.mindoo.domino.jna.test;

import com.mindoo.domino.jna.NotesDatabase;
import com.mindoo.domino.jna.NotesDatabase.SignCallback;
import com.mindoo.domino.jna.NotesViewEntryData;
import com.mindoo.domino.jna.internal.NotesCAPI;

import lotus.domino.Session;

/**
 * Tests cases for database searches
 *
 * @author Karsten Lehmann
 */
public class TestSignDb extends BaseJNATestClass {

	//commented out; requires native reading of DESIGN view collation structure
	//@Test
	public void testDbSearch_search() {

		runWithSession(new IDominoCallable<Object>() {

			@Override
			public Object call(Session session) throws Exception {
				NotesDatabase db = new NotesDatabase(session, "", "test/signtest.nsf");
				db.signAll(NotesCAPI.NOTE_CLASS_ALLNONDATA, new SignCallback() {

					@Override
					public boolean shouldSign(NotesViewEntryData noteData, String currSigner) {
						return true;
					}

					@Override
					public Action noteSigned(NotesViewEntryData noteData) {
						System.out.println("Note signed: ID="+noteData.getNoteId()+", data="+noteData.getColumnDataAsMap());
						return Action.Continue;
					}

				});

				return null;
			}
		});
	}

}

package com.mindoo.domino.jna.test;

import com.mindoo.domino.jna.NotesDatabase;
import com.mindoo.domino.jna.NotesDatabase.SignCallback;
import com.mindoo.domino.jna.NotesViewEntryData;
import com.mindoo.domino.jna.internal.NotesCAPI;

import lotus.domino.Session;

/**
 * Tests cases for database searches
 *
 * @author Karsten Lehmann
 */
public class TestSignDb extends BaseJNATestClass {

	//commented out; requires native reading of DESIGN view collation structure
	//@Test
	public void testSignDb() {

		runWithSession(new IDominoCallable<Object>() {

			@Override
			public Object call(Session session) throws Exception {
				NotesDatabase db = new NotesDatabase(session, "", "test/signtest.nsf");
				db.signAll(NotesCAPI.NOTE_CLASS_ALLNONDATA, new SignCallback() {

					@Override
					public boolean shouldSign(NotesViewEntryData noteData, String currSigner) {
						return true;
					}

					@Override
					public Action noteSigned(NotesViewEntryData noteData) {
						System.out.println("Note signed: ID="+noteData.getNoteId()+", data="+noteData.getColumnDataAsMap());
						return Action.Continue;
					}

				});

				return null;
			}
		});
	}

}

Test case commented out; needs more work


package com.github.cstroe.sqs.repository;

public class RepositoryFactory {
    public static NotebookRepository notebook() {
        return new NotebookRepository();
    }
    public static NoteRepository note() {
        return new NoteRepository();
    }
}

package com.github.cstroe.sqs.repository;

public class RepositoryFactory {
}

Remove mentions to old repositories.

Remove mentions to old repositories.


package com.techern.minecraft.pathomania.proxy;

import com.techern.minecraft.pathomania.PathomaniaMod;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.model.ModelResourceLocation;
import net.minecraft.item.Item;

/**
 * An implementation of {@link CommonProxy} for use on the client {@link net.minecraftforge.fml.relauncher.Side}
 *
 * @since 0.0.1
 */
public class ClientProxy extends CommonProxy {

    /**
     * Registers a {@link Block}'s inventory model
     *
     * @param block The {@link Block} being registered
     * @param metadata The {@link Integer} used to store metadata
     * @param modelName A {@link String} depicting the name of the model
     *
     * @since 0.0.1
     */
    public void registerBlockInventoryModel(Block block, int metadata, String modelName) {
        PathomaniaMod.LOGGER.trace("Got a request to register inventory model for " + block.getLocalizedName() + ", doing so");

        Minecraft.getMinecraft().getRenderItem().getItemModelMesher().register(Item.getItemFromBlock(block), metadata, new ModelResourceLocation("pathomania:" + modelName, "inventory"));

    }

}

package com.techern.minecraft.pathomania.proxy;

import com.techern.minecraft.pathomania.PathomaniaMod;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.model.ModelResourceLocation;
import net.minecraft.item.Item;

/**
 * An implementation of {@link CommonProxy} for use on the client {@link net.minecraftforge.fml.relauncher.Side}
 *
 * @since 0.0.1
 */
public class ClientProxy extends CommonProxy {

    /**
     * Registers a {@link Block}'s inventory model
     *
     * @param block The {@link Block} being registered
     * @param metadata The {@link Integer} used to store metadata
     * @param modelName A {@link String} depicting the name of the model
     *
     * @since 0.0.1
     */
    public void registerBlockInventoryModel(Block block, int metadata, String modelName) {
        PathomaniaMod.LOGGER.trace("Got a request to register inventory model for " + block.getLocalizedName() + ", doing so");

        Minecraft.getMinecraft().getRenderItem().getItemModelMesher().register(Item.getItemFromBlock(block).setHasSubtypes(true), metadata, new ModelResourceLocation("pathomania:" + modelName, "inventory"));

    }

}

Fix subtypes of middle-clicked paths combining on drop

Fixes #8


package com.google.maps.android.utils.demo;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;

public abstract class BaseDemoActivity extends FragmentActivity {
    private GoogleMap mMap;

    protected int getLayoutId() {
        return R.layout.map;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        setUpMapIfNeeded();
    }

    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();
        startDemo();
    }

    private void setUpMapIfNeeded() {
        if (mMap != null) {
            return;
        }
        mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
    }

    /**
     * Run the demo-specific code.
     */
    protected abstract void startDemo();

    protected GoogleMap getMap() {
        setUpMapIfNeeded();
        return mMap;
    }
}

package com.google.maps.android.utils.demo;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;

public abstract class BaseDemoActivity extends FragmentActivity {
    private GoogleMap mMap;

    protected int getLayoutId() {
        return R.layout.map;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        setUpMapIfNeeded();
    }

    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();
        if (getMap() != null) {
          startDemo();
        }
    }

    private void setUpMapIfNeeded() {
        if (mMap != null) {
            return;
        }
        mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
    }

    /**
     * Run the demo-specific code.
     */
    protected abstract void startDemo();

    protected GoogleMap getMap() {
        setUpMapIfNeeded();
        return mMap;
    }
}

Check if mMap is null before running demo. Necessary to show the "Play services is out of date" button.


package com.insightfullogic.java8.answers.chapter3;

import java.util.Comparator;
import java.util.List;
import java.util.Optional;

public class StringExercises {

    // Question 7
    public static int countLowercaseLetters(String string) {
        return (int) string.chars()
                           .filter(Character::isLowerCase)
                           .count();
    }

    // Question 8
    public static Optional<String> mostLowercaseString(List<String> strings) {
        return strings.stream()
                      .max(Comparator.comparing(StringExercises::countLowercaseLetters));
    }

}

package com.insightfullogic.java8.answers.chapter3;

import java.util.Comparator;
import java.util.List;
import java.util.Optional;

public class StringExercises {

    // Question 6
    public static int countLowercaseLetters(String string) {
        return (int) string.chars()
                           .filter(Character::isLowerCase)
                           .count();
    }

    // Question 7
    public static Optional<String> mostLowercaseString(List<String> strings) {
        return strings.stream()
                      .max(Comparator.comparing(StringExercises::countLowercaseLetters));
    }

}

Change the serial number of the problem

Change the serial number of the problem

Change the serial number of the problem


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

import java.util.AbstractList;

public class InsertionCountList<T> extends AbstractList<T> {
    int size = 0;

    @Override
    public void add(int index, T element) {
        size++;
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public T get(int index) {
        return null;
    }
};

Remove trailing ; at end of class declaration.

git-svn-id: d2a93f579bd4835921162e9a69396c846e49961c@1226974 13f79535-47bb-0310-9956-ffa450edef68


import java.util.Arrays;

public class ConvertArray {

	public int getOriginalIndex(int currentIndex, int length) {
		return (currentIndex % 3) * length + currentIndex/3;
	}

	public int[] convert(int[] input) {
		for (int i = 0; i < input.length; ++i) {
			int originalIndex = getOriginalIndex(i, input.length/3);
			while (originalIndex < i) {
				originalIndex = getOriginalIndex(originalIndex, input.length/3);
			}
			int temp = input[i];
			input[i] = input[originalIndex];
			input[originalIndex] = temp;
		}
		return input;
	}

	public static void main(String[] args) {
		ConvertArray c = new ConvertArray();
		int[] test1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
		System.out.println(Arrays.toString(c.convert(test1)));

	}
}

import java.util.Arrays;

public class ConvertArray {

	public int getOriginalIndex(int currentIndex, int length) {
		return (currentIndex % 3) * length + currentIndex/3;
	}

	public int[] convert(int[] input) {
	  // When array size is less than 3, returns an error.
	  if (input.length % 3 != 0 ) {
			System.out.println("Error! Array cannot be divided into three equal parts");
			return;
		}
		for (int i = 0; i < input.length; ++i) {
			int originalIndex = getOriginalIndex(i, input.length/3);
			while (originalIndex < i) {
				originalIndex = getOriginalIndex(originalIndex, input.length/3);
			}
			int temp = input[i];
			input[i] = input[originalIndex];
			input[originalIndex] = temp;
		}
		return input;
	}

	public static void main(String[] args) {
		ConvertArray c = new ConvertArray();
		int[] test1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
		System.out.println(Arrays.toString(c.convert(test1)));

	}
}

Update to handle an edge case

Update to handle an edge case

Added an update to handle the case when array size is not a multiple of 3.
Without this the program will run into an infinite loop!


package gouravexample.popularmoviesstage1;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;

import com.squareup.picasso.Picasso;

import java.util.List;

/**
 * Created by GOURAV on 17-08-2016.
 */
public class ViewAdapter extends ArrayAdapter<MovieItem>{

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

    public ViewAdapter(Context context, int resource, List<MovieItem> objects) {
        super(context, resource, objects);
    }

    public View getView(int position, View convertView, ViewGroup parent){

        if(convertView == null){
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.grid_item_movie,null);
        }

        ImageView imageView = (ImageView) convertView.findViewById(R.id.image);
        MovieItem item = (MovieItem)getItem(position);

        Log.d(LOG_TAG,item.getPosterPath());
//        imageView.setImageResource(getContext().getResources().getIdentifier((String)getItem(position), "drawable", getContext().getPackageName()));
        Picasso.with(getContext())
                .load(item.getPosterPath())
                .placeholder(R.drawable.circular)
//                .resize(185,278)
//                .centerCrop()
                .into(imageView);

        return convertView;
    }
}

package gouravexample.popularmoviesstage1;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;

import com.squareup.picasso.Picasso;

import java.util.List;

/**
 * Created by GOURAV on 17-08-2016.
 */
public class ViewAdapter extends ArrayAdapter<MovieItem>{

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

    public ViewAdapter(Context context, int resource, List<MovieItem> objects) {
        super(context, resource, objects);
    }

    public View getView(int position, View convertView, ViewGroup parent){

        if(convertView == null){
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.grid_item_movie,null);
        }

        ImageView imageView = (ImageView) convertView.findViewById(R.id.image);
        MovieItem item = (MovieItem)getItem(position);

        Log.d(LOG_TAG,item.getPosterPath());
//        imageView.setImageResource(getContext().getResources().getIdentifier((String)getItem(position), "drawable", getContext().getPackageName()));
        Picasso.with(getContext())
                .load(item.getPosterPath())
//                .placeholder(R.drawable.circular)
//                .resize(185,278)
//                .centerCrop()
                .into(imageView);

        return convertView;
    }
}

Remove Interstellar poster as placeholder.


package com.jraska.github.client.data.users;

import com.jraska.github.client.users.UsersRepository;
import dagger.Module;
import dagger.Provides;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

import javax.inject.Singleton;

@Module
public final class UsersModule {
  @Provides @Singleton UsersRepository provideUsersRepository(GitHubUsersApi gitHubUsersApi,
                                                              GitHubUserDetailApi detailApi) {
    return new GitHubApiUsersRepository(gitHubUsersApi, detailApi);
  }

  @Provides @Singleton GitHubUsersApi provideGitHubUsersApi(Retrofit retrofit) {
    return retrofit.create(GitHubUsersApi.class);
  }

  @Provides @Singleton GitHubUserDetailApi provideGitHubUserDetailApi(Retrofit retrofit) {
    return retrofit.create(GitHubUserDetailApi.class);
  }

  @Provides @Singleton Retrofit provideRetrofit(OkHttpClient okHttpClient) {
    Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://api.github.com")
        .validateEagerly(true) // TODO: 17/08/16 AppConfig
        .client(okHttpClient)
        .addConverterFactory(GsonConverterFactory.create())
        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
        .build();

    return retrofit;
  }
}

package com.jraska.github.client.data.users;

import com.jraska.github.client.common.AppBuildConfig;
import com.jraska.github.client.users.UsersRepository;
import dagger.Module;
import dagger.Provides;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

import javax.inject.Singleton;

@Module
public final class UsersModule {
  @Provides @Singleton UsersRepository provideUsersRepository(Retrofit retrofit) {
    GitHubUsersApi usersApi = retrofit.create(GitHubUsersApi.class);
    GitHubUserDetailApi detailApi = retrofit.create(GitHubUserDetailApi.class);

    return new GitHubApiUsersRepository(usersApi, detailApi);
  }

  @Provides @Singleton Retrofit provideRetrofit(OkHttpClient okHttpClient, AppBuildConfig config) {
    Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://api.github.com")
        .validateEagerly(config.debug)
        .client(okHttpClient)
        .addConverterFactory(GsonConverterFactory.create())
        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
        .build();

    return retrofit;
  }
}

Remove extra methods for API clients

Remove extra methods for API clients


package com.yahoo.searchdefinition;

import com.yahoo.vespa.model.AbstractService;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class RankExpressionFiles {
    private final Map<String, RankExpressionFile> expressions = new HashMap<>();

    public void add(RankExpressionFile expression) {
        expression.validate();
        String name = expression.getName();
        if (expressions.containsKey(name))
            throw new IllegalArgumentException("Rank expression file '" + name + "' defined twice");
        expressions.put(name, expression);
    }

    /** Returns the ranking constant with the given name, or null if not present */
    public RankExpressionFile get(String name) {
        return expressions.get(name);
    }

    /** Returns a read-only map of the ranking constants in this indexed by name */
    public Map<String, RankExpressionFile> asMap() {
        return Collections.unmodifiableMap(expressions);
    }

    /** Initiate sending of these constants to some services over file distribution */
    public void sendTo(Collection<? extends AbstractService> services) {
        expressions.values().forEach(constant -> constant.sendTo(services));
    }
}

package com.yahoo.searchdefinition;

import com.yahoo.vespa.model.AbstractService;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class RankExpressionFiles {
    private final Map<String, RankExpressionFile> expressions = new HashMap<>();

    public void add(RankExpressionFile expression) {
        expression.validate();
        String name = expression.getName();
        if (expressions.containsKey(name))
            throw new IllegalArgumentException("Rank expression file '" + name + "' defined twice");
        expressions.put(name, expression);
    }

    /** Returns the ranking constant with the given name, or null if not present */
    public RankExpressionFile get(String name) {
        return expressions.get(name);
    }

    /** Returns a read-only map of the ranking constants in this indexed by name */
    public Map<String, RankExpressionFile> asMap() {
        return Collections.unmodifiableMap(expressions);
    }

    /** Initiate sending of these constants to some services over file distribution */
    public void sendTo(Collection<? extends AbstractService> services) {
        // TODO Disabled until issues resolved
        // expressions.values().forEach(constant -> constant.sendTo(services));
    }
}

Disable distribution of rank-expression files.


package com.swandiggy.poe4j.gui.log;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;

/**
 * @author Jacob Swanson
 * @since 12/10/2015
 */
public class ObservableLogAppender extends AppenderBase<ILoggingEvent> {

    public static ObservableList<ILoggingEvent> events = FXCollections.observableArrayList();

    @Override
    protected void append(ILoggingEvent event) {
        Platform.runLater(() -> {
            events.add(event);

            if (events.size() > 500) {
                events.remove(events.size() - 1);
            }
        });
    }
}

package com.swandiggy.poe4j.gui.log;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;

/**
 * @author Jacob Swanson
 * @since 12/10/2015
 */
public class ObservableLogAppender extends AppenderBase<ILoggingEvent> {

    public static ObservableList<ILoggingEvent> events = FXCollections.observableArrayList();

    @Override
    protected void append(ILoggingEvent event) {
        Platform.runLater(() -> {
            events.add(event);

            if (events.size() > 500) {
                events.remove(0);
            }
        });
    }
}

Fix log not appending in gui

Fix log not appending in gui


package org.opennms.web.svclayer;

import java.util.Date;

public interface DistributedStatusService {
    public SimpleWebTable createStatusTable(String locationName, String applicationLabel);

    public SimpleWebTable createFacilityStatusTable(Date startDate, Date endDate);
}

package org.opennms.web.svclayer;

import java.util.Date;

import org.springframework.transaction.annotation.Transactional;

@Transactional(readOnly=true)
public interface DistributedStatusService {
    public SimpleWebTable createStatusTable(String locationName, String applicationLabel);

    public SimpleWebTable createFacilityStatusTable(Date startDate, Date endDate);
}

Make the service layer transactional (and read-only)


/*
 * #%L
 * Wildfly Swarm :: Examples :: Camel Mail
 * %%
 * Copyright (C) 2016 RedHat
 * %%
 * 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.
 * #L%
 */
package org.wildfly.swarm.examples.camel.mail;

import org.wildfly.swarm.Swarm;
import org.wildfly.swarm.mail.MailFraction;

public class Main {
    public static void main(String... args) throws Exception {
        MailFraction fraction = MailFraction.defaultFraction();
        Swarm swarm = new Swarm();

        // Configure mock mail server SMTP session
        swarm.fraction(fraction.smtpServer("greenmail", s -> s.host("localhost").port("10110").username("user1@localhost").password("password")));

        // Deploy mock mail server
        swarm.start(true);
        swarm.deploy(Swarm.artifact("com.icegreen:greenmail-webapp:war:1.4.1"));
        swarm.deploy();
    }
}

/*
 * #%L
 * Wildfly Swarm :: Examples :: Camel Mail
 * %%
 * Copyright (C) 2016 RedHat
 * %%
 * 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.
 * #L%
 */
package org.wildfly.swarm.examples.camel.mail;

import org.wildfly.swarm.Swarm;
import org.wildfly.swarm.mail.MailFraction;

public class Main {
    public static void main(String... args) throws Exception {
        Swarm swarm = new Swarm();

        // Configure mock mail server SMTP session
        swarm.fraction(new MailFraction().smtpServer("greenmail", s -> s.host("localhost").port(10110).username("user1@localhost").password("password")));

        // Deploy mock mail server
        swarm.start(true);
        swarm.deploy(Swarm.artifact("com.icegreen:greenmail-webapp:war:1.4.1"));
        swarm.deploy();
    }
}

Change Camel-Mail example to - not create 2 SMTP servers. - use an integer instead of an integer-shaped string.


package com.xtremelabs.robolectric.shadows;

import android.app.Activity;
import android.app.Application;
import android.content.res.Resources;
import com.xtremelabs.robolectric.R;
import com.xtremelabs.robolectric.Robolectric;
import com.xtremelabs.robolectric.WithTestDefaultsRunner;
import com.xtremelabs.robolectric.res.ResourceLoader;

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

import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.notNullValue;

import java.io.File;
import static com.xtremelabs.robolectric.util.TestUtil.resourceFile;

@RunWith(WithTestDefaultsRunner.class)
public class ResourcesTest {

	@Before
	public void setUp() throws Exception {
        Robolectric.bindDefaultShadowClasses();
        Robolectric.application = ShadowApplication.bind(new Application(), new ResourceLoader(R.class, new File("test/res")));
	}

    @Test(expected = Resources.NotFoundException.class)
    public void getStringArray_shouldThrowExceptionIfNotFound() throws Exception {
        Robolectric.bindDefaultShadowClasses();
        Robolectric.application = ShadowApplication.bind(new Application(), new ResourceLoader(R.class, resourceFile("res"), resourceFile("assets")));

        new Activity().getResources().getStringArray(-1);
    }

    @Test
    public void testConfiguration() {
        assertThat( new Activity().getResources().getConfiguration(), notNullValue() );
    }
}

package com.xtremelabs.robolectric.shadows;

import android.app.Activity;
import android.app.Application;
import android.content.res.Resources;
import com.xtremelabs.robolectric.R;
import com.xtremelabs.robolectric.Robolectric;
import com.xtremelabs.robolectric.WithTestDefaultsRunner;
import com.xtremelabs.robolectric.res.ResourceLoader;

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

import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.notNullValue;

import java.io.File;
import static com.xtremelabs.robolectric.util.TestUtil.resourceFile;

@RunWith(WithTestDefaultsRunner.class)
public class ResourcesTest {

	@Before
	public void setUp() throws Exception {
        Robolectric.bindDefaultShadowClasses();
        Robolectric.application = ShadowApplication.bind(new Application(), new ResourceLoader(R.class, new File("test/res"), new File("test/assets")));
	}

    @Test(expected = Resources.NotFoundException.class)
    public void getStringArray_shouldThrowExceptionIfNotFound() throws Exception {
        Robolectric.bindDefaultShadowClasses();
        Robolectric.application = ShadowApplication.bind(new Application(), new ResourceLoader(R.class, resourceFile("res"), resourceFile("assets")));

        new Activity().getResources().getStringArray(-1);
    }

    @Test
    public void testConfiguration() {
        assertThat( new Activity().getResources().getConfiguration(), notNullValue() );
    }
}

Fix signature for ResourceLoader constructor


package com.furnaghan.home.component.metrics.statsd;

import com.furnaghan.home.component.Component;
import com.furnaghan.home.component.metrics.MetricsType;
import com.timgroup.statsd.NonBlockingStatsDClient;
import com.timgroup.statsd.StatsDClient;

public class StatsDMetricsComponent extends Component<MetricsType.Listener> implements MetricsType {

    private static String sanitize(final String name) {
        return name.replaceAll("[^a-zA-Z0-9\\s]", "").replaceAll("\\s", "_");
    }

    private final StatsDClient statsd;

    public StatsDMetricsComponent(final StatsDMetricsConfiguration configuration) {
        statsd = new NonBlockingStatsDClient(configuration.getPrefix(), configuration.getAddress().getHostText(),
                configuration.getAddress().getPortOrDefault(StatsDMetricsConfiguration.DEFAULT_PORT));
    }

    @Override
    public void send(final String name, final double value) {
        statsd.gauge(sanitize(name), value);
    }
}

package com.furnaghan.home.component.metrics.statsd;

import com.furnaghan.home.component.Component;
import com.furnaghan.home.component.metrics.MetricsType;
import com.timgroup.statsd.NonBlockingStatsDClient;
import com.timgroup.statsd.StatsDClient;

public class StatsDMetricsComponent extends Component<MetricsType.Listener> implements MetricsType {

    private static String sanitize(final String name) {
        return name.replaceAll("[^a-zA-Z0-9\\s\\.]", "").replaceAll("\\s", "_");
    }

    private final StatsDClient statsd;

    public StatsDMetricsComponent(final StatsDMetricsConfiguration configuration) {
        statsd = new NonBlockingStatsDClient(configuration.getPrefix(), configuration.getAddress().getHostText(),
                configuration.getAddress().getPortOrDefault(StatsDMetricsConfiguration.DEFAULT_PORT));
    }

    @Override
    public void send(final String name, final double value) {
        statsd.gauge(sanitize(name), value);
    }
}

Allow periods in statsd names

Allow periods in statsd names


/*
 *
 * CODENVY CONFIDENTIAL
 * ________________
 *
 * [2012] - [2014] Codenvy, S.A.
 * All Rights Reserved.
 * NOTICE: All information contained herein is, and remains
 * the property of Codenvy S.A. and its suppliers,
 * if any. The intellectual and technical concepts contained
 * herein are proprietary to Codenvy S.A.
 * and its suppliers and may be covered by U.S. and Foreign Patents,
 * patents in process, and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Codenvy S.A..
 */
package com.codenvy.analytics.metrics;

/** @author Anatoliy Bazko */
public class RunnerTotalTime extends AbstractLongValueResulted {

    private static final String TIME = "time";

    protected RunnerTotalTime() {
        super(MetricType.RUNNER_TOTAL_TIME);
    }

    @Override
    public String[] getTrackedFields() {
        return new String[]{TIME};
    }

    @Override
    public String getDescription() {
        return "The total time of runners";
    }
}

/*
 *
 * CODENVY CONFIDENTIAL
 * ________________
 *
 * [2012] - [2014] Codenvy, S.A.
 * All Rights Reserved.
 * NOTICE: All information contained herein is, and remains
 * the property of Codenvy S.A. and its suppliers,
 * if any. The intellectual and technical concepts contained
 * herein are proprietary to Codenvy S.A.
 * and its suppliers and may be covered by U.S. and Foreign Patents,
 * patents in process, and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Codenvy S.A..
 */
package com.codenvy.analytics.metrics;

/** @author Anatoliy Bazko */
public class RunnerTotalTime extends AbstractLongValueResulted {

    private static final String TIME = "time";

    public RunnerTotalTime() {
        super(MetricType.RUNNER_TOTAL_TIME);
    }

    @Override
    public String[] getTrackedFields() {
        return new String[]{TIME};
    }

    @Override
    public String getDescription() {
        return "The total time of runners";
    }
}

Add bunch of new events

DASHB-204: Add bunch of new events


package keywhiz.service.resources;

import com.codahale.metrics.health.HealthCheck;
import com.codahale.metrics.health.HealthCheckRegistry;
import io.dropwizard.setup.Environment;
import java.util.TreeMap;
import javax.ws.rs.InternalServerErrorException;
import org.junit.Before;
import org.junit.Test;

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

public class StatusResponseTest {
  HealthCheckRegistry registry;
  Environment environment;
  StatusResource status;

  @Before
  public void setUp() throws Exception {
    this.registry = mock(HealthCheckRegistry.class);
    this.environment = mock(Environment.class);
    this.status = new StatusResource(environment);

    when(environment.healthChecks()).thenReturn(registry);
  }

  @Test
  public void testStatusOk() throws Exception {
    when(registry.runHealthChecks()).thenReturn(new TreeMap<>());
    status.get();
  }

  @Test(expected = InternalServerErrorException.class)
  public void testStatusWarn() throws Exception {
    TreeMap<String, HealthCheck.Result> map = new TreeMap<>();
    map.put("test", HealthCheck.Result.unhealthy("failing"));

    when(registry.runHealthChecks()).thenReturn(map);
    status.get();
  }
}

package keywhiz.service.resources;

import com.codahale.metrics.health.HealthCheck;
import com.codahale.metrics.health.HealthCheckRegistry;
import io.dropwizard.setup.Environment;
import java.util.TreeMap;
import javax.ws.rs.InternalServerErrorException;
import javax.ws.rs.core.Response;
import org.junit.Before;
import org.junit.Test;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class StatusResponseTest {
  HealthCheckRegistry registry;
  Environment environment;
  StatusResource status;

  @Before
  public void setUp() throws Exception {
    this.registry = mock(HealthCheckRegistry.class);
    this.environment = mock(Environment.class);
    this.status = new StatusResource(environment);

    when(environment.healthChecks()).thenReturn(registry);
  }

  @Test
  public void testStatusOk() throws Exception {
    when(registry.runHealthChecks()).thenReturn(new TreeMap<>());
    Response r = status.get();
    assertThat(r.getStatus()).isEqualTo(200);
  }

  @Test
  public void testStatusWarn() throws Exception {
    TreeMap<String, HealthCheck.Result> map = new TreeMap<>();
    map.put("test", HealthCheck.Result.unhealthy("failing"));

    when(registry.runHealthChecks()).thenReturn(map);
    Response r = status.get();
    assertThat(r.getStatus()).isEqualTo(500);
  }
}

Fix tests to check status code, and not expect exception


/*
 * Altimos JUtil
 *
 * Copyright (C) 2010-2011 Jan Graichen <jan.graichen@gmx.de>
 *
 * 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.
 *
 * See the NOTICE file distributed along with this work for further
 * information.
 */
package de.altimos.util.res.basic;

import de.altimos.util.res.ResourceKey;

/**
 * A basic ResourceKey implementation using a string as name.
 *
 * @author Jan Graichen
 */
public class BasicResourceKey implements ResourceKey {

	private String name;

	/**
	 * Creates new BasicResourceKey with given name.
	 *
	 * @param name of resource this key identifies.
	 */
	public BasicResourceKey(String name) {
		this.name = name;
	}

	@Override
	public String getName() {
		return name;
	}

}

/*
 * Altimos JUtil
 *
 * Copyright (C) 2010-2011 Jan Graichen <jan.graichen@gmx.de>
 *
 * 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.
 *
 * See the NOTICE file distributed along with this work for further
 * information.
 */
package de.altimos.util.res.basic;

import de.altimos.util.res.ResourceKey;

/**
 * A basic ResourceKey implementation using a string as name.
 *
 * @author Jan Graichen
 */
public class BasicResourceKey implements ResourceKey {

	private String name;

	/**
	 * Creates new BasicResourceKey with given name.
	 *
	 * @param name of resource this key identifies.
	 */
	public BasicResourceKey(String name) {
		this.name = name;
	}

	@Override
	public String getName() {
		return name;
	}

	@Override
	public String toString() {
		return getClass().getSimpleName() + "[" + name + "]";
	}
}

Add toString method to basic resource key.

git-svn-id: ddbd9cf08712f046fd96251fb76032477531c99f@83 2c5795a3-9673-4752-9eb2-864809377e00


// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
@ExportPackage
@PublicApi
package com.yahoo.config.provision;

import com.yahoo.api.annotations.PublicApi;
import com.yahoo.osgi.annotation.ExportPackage;

// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
@ExportPackage
package com.yahoo.config.provision;

import com.yahoo.api.annotations.PublicApi;
import com.yahoo.osgi.annotation.ExportPackage;

Remove this from public packages

Remove this from public packages

By our contract this requires a major release, but we should
make an exception because:
- This is not useful outside the cloud environment
- On the cloud environment there are just 2 usages, both of which are legacy
  and won't be impacted (as we're still exporting the packages).

The replacement is ai.vespa.cloud.SystemInfo


package <%=packageName%>.repository;

import <%=packageName%>.domain.PersistentAuditEvent;
import org.joda.time.LocalDateTime;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

/**
 * Spring Data JPA repository for the PersistentAuditEvent entity.
 */
public interface PersistenceAuditEventRepository extends JpaRepository<PersistentAuditEvent, String> {

    List<PersistentAuditEvent> findByPrincipal(String principal);

    List<PersistentAuditEvent> findByPrincipalAndAuditEventDateGreaterThan(String principal, LocalDateTime after);

    List<PersistentAuditEvent> findByAuditEventDateBetween(LocalDateTime fromDate, LocalDateTime toDate);
}

package <%=packageName%>.repository;

import <%=packageName%>.domain.PersistentAuditEvent;
import org.joda.time.LocalDateTime;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

/**
 * Spring Data JPA repository for the PersistentAuditEvent entity.
 */
public interface PersistenceAuditEventRepository extends JpaRepository<PersistentAuditEvent, String> {

    List<PersistentAuditEvent> findByPrincipal(String principal);

    List<PersistentAuditEvent> findByPrincipalAndAuditEventDateGreaterThan(String principal, LocalDateTime after);

    @Query("select p from PersistentAuditEvent p where p.auditEventDate >= ?1 and p.auditEventDate <= ?2")
    List<PersistentAuditEvent> findByDates(LocalDateTime fromDate, LocalDateTime toDate);
}

Change the definition of the find by dates method


package org.usfirst.frc.team2503.r2016.input;

import org.usfirst.frc.team2503.r2016.input.gamepad.Gamepad;
import org.usfirst.frc.team2503.r2016.input.joystick.Joystick;

public class MadCatzV1JoystickMadCatzV1JoystickLogitechF310GamepadControlLayout extends JoystickJoystickGamepadControlLayout {

	public Data getData() {
		Data data = super.getData();

		return data;
	}

	public MadCatzV1JoystickMadCatzV1JoystickLogitechF310GamepadControlLayout(Joystick left, Joystick right, Gamepad gamepad) {
		super(left, right, gamepad);
	}

}

package org.usfirst.frc.team2503.r2016.input;

import org.usfirst.frc.team2503.r2016.input.gamepad.Gamepad;
import org.usfirst.frc.team2503.r2016.input.joystick.Joystick;

public class MadCatzV1JoystickMadCatzV1JoystickLogitechF310GamepadControlLayout extends JoystickJoystickGamepadControlLayout {

	public Data getData() {
		Data data = super.getData();

		// Any modifications to be made should be done here.

		return data;
	}

	public MadCatzV1JoystickMadCatzV1JoystickLogitechF310GamepadControlLayout(Joystick left, Joystick right, Gamepad gamepad) {
		super(left, right, gamepad);
	}

}

Clean up a couple of whitespace errors, add a comment


package fr.univnantes.termsuite.ui.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Scanner;

import com.google.common.base.Splitter;
import com.google.common.io.ByteStreams;

public class FileUtil {

	public static String toString(File file) throws FileNotFoundException {
		Scanner scanner = new Scanner(file);
		String next = scanner.useDelimiter("\\Z").next();
		scanner.close();
		return next;
	}

	public static void mkdirs(File file) {
		if (file.isDirectory()) {
			file.mkdirs();
		} else {
			file.getParentFile().mkdirs();
		}
	}

	public static void inputStreamToFile(InputStream is, File targetFile) throws IOException {
		byte[] buffer = ByteStreams.toByteArray(is);
		OutputStream outStream = new FileOutputStream(targetFile);
		outStream.write(buffer);
		outStream.flush();
		outStream.close();
	}

	public static String getFilename(String path) {
		List<String> list = Splitter.on(File.separator).splitToList(path);
		return list.get(list.size() - 1);
	}
}

package fr.univnantes.termsuite.ui.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Scanner;

import com.google.common.base.Splitter;
import com.google.common.io.ByteStreams;

public class FileUtil {

	public static String toString(File file) throws FileNotFoundException {
		Scanner scanner = new Scanner(file, "UTF-8");
		String next = scanner.useDelimiter("\\Z").next();
		scanner.close();
		return next;
	}

	public static void mkdirs(File file) {
		if (file.isDirectory()) {
			file.mkdirs();
		} else {
			file.getParentFile().mkdirs();
		}
	}

	public static void inputStreamToFile(InputStream is, File targetFile) throws IOException {
		byte[] buffer = ByteStreams.toByteArray(is);
		OutputStream outStream = new FileOutputStream(targetFile);
		outStream.write(buffer);
		outStream.flush();
		outStream.close();
	}

	public static String getFilename(String path) {
		List<String> list = Splitter.on(File.separator).splitToList(path);
		return list.get(list.size() - 1);
	}
}

Load file as UTF-8 as default

Load file as UTF-8 as default


package guitests;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

import seedu.address.logic.commands.UndoCommand;
import seedu.address.testutil.TestTask;
import seedu.address.testutil.TestUtil;

public class UndoCommandTest extends TaskManagerGuiTest {

    private TestTask[] expectedList = td.getTypicalTasks();

    /**
     * Tries to undo an add command
     */
    @Test
    public void undoAdd() {
        TestTask taskToAdd = td.alice;
        commandBox.runCommand(taskToAdd.getAddCommand());
        assertUndoSuccess(expectedList);
    }

    private void assertUndoSuccess(TestTask[] expectedList) {
        commandBox.runCommand(UndoCommand.COMMAND_WORD);
        assertTrue(taskListPanel.isListMatching(expectedList));
        assertResultMessage(String.format(UndoCommand.MESSAGE_SUCCESS));

    }

}

package guitests;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

import seedu.address.logic.commands.UndoCommand;
import seedu.address.testutil.TestTask;
import seedu.address.logic.commands.DeleteCommand;

public class UndoCommandTest extends TaskManagerGuiTest {

    private TestTask[] expectedList = td.getTypicalTasks();

    /**
     * Tries to undo an add command
     */
    @Test
    public void undoAdd() {
        TestTask taskToAdd = td.alice;
        commandBox.runCommand(taskToAdd.getAddCommand());
        assertUndoSuccess(expectedList);
    }

    /**
     * Tries to undo a delete command
     */
    @Test
    public void undoDelete() {
        int targetIndex = 1;
        commandBox.runCommand(DeleteCommand.COMMAND_WORD + " " + targetIndex);

        assertUndoSuccess(expectedList);
    }

    private void assertUndoSuccess(TestTask[] expectedList) {
        commandBox.runCommand(UndoCommand.COMMAND_WORD);
        assertTrue(taskListPanel.isListMatching(expectedList));
        assertResultMessage(String.format(UndoCommand.MESSAGE_SUCCESS));

    }

}

Add test case for undo delete command

Add test case for undo delete command


package de.fernunihagen.dna.jkn.scalephant.storage;

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

public class StorageInterface {

	private static Map<String, StorageManager> instances;

	/**
	 * Get the storage manager for a given table. If the storage manager does not
	 * exist, it will be created
	 *
	 * @return
	 */
	public static synchronized StorageManager getStorageManager(final String table) {

		if(instances == null) {
			instances = new HashMap<String, StorageManager>();
		}

		if(instances.containsKey(table)) {
			return instances.get(table);
		}

		final StorageConfiguration storageConfiguration = new StorageConfiguration();
		final StorageManager storageManager = new StorageManager(table, storageConfiguration);
		storageManager.init();

		instances.put(table, storageManager);

		return storageManager;
	}

	@Override
	protected void finalize() throws Throwable {
		super.finalize();

		if(instances != null) {
			for(final String table : instances.keySet()) {
				final StorageManager storageManager = instances.get(table);
				storageManager.shutdown();
			}
		}
	}
}

package de.fernunihagen.dna.jkn.scalephant.storage;

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

public class StorageInterface {

	/**
	 * A map with all created storage instances
	 */
	protected static Map<String, StorageManager> instances;

	/**
	 * The used storage configuration
	 */
	protected static StorageConfiguration storageConfiguration;

	static {
		storageConfiguration = new StorageConfiguration();
	}

	/**
	 * Get the storage manager for a given table. If the storage manager does not
	 * exist, it will be created
	 *
	 * @return
	 */
	public static synchronized StorageManager getStorageManager(final String table) {

		if(instances == null) {
			instances = new HashMap<String, StorageManager>();
		}

		if(instances.containsKey(table)) {
			return instances.get(table);
		}

		final StorageManager storageManager = new StorageManager(table, storageConfiguration);
		storageManager.init();

		instances.put(table, storageManager);

		return storageManager;
	}

	@Override
	protected void finalize() throws Throwable {
		super.finalize();

		if(instances != null) {
			for(final String table : instances.keySet()) {
				final StorageManager storageManager = instances.get(table);
				storageManager.shutdown();
			}
		}
	}

	/**
	 * Get the current storage configuration
	 * @return
	 */
	public static StorageConfiguration getStorageConfiguration() {
		return storageConfiguration;
	}

	/**
	 * Set a new storage configuration
	 * @param storageConfiguration
	 */
	public static void setStorageConfiguration(
			StorageConfiguration storageConfiguration) {
		StorageInterface.storageConfiguration = storageConfiguration;
	}
}

Allow to change the default storage configuration


package tests;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

@RunWith(Suite.class)
@SuiteClasses({
	CECConfiguratorTests.class,
	EmailBuilderTests.class,
	EmailSortingTests.class,
	EmailTests.class,
	FolderFactoryTests.class })

public class AllTests {
}

package tests;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

@RunWith(Suite.class)
@SuiteClasses({
	CECConfiguratorTests.class,
	EmailBuilderTests.class,
	EmailSortingTests.class,
	EmailTests.class,
	FolderFactoryTests.class,
	FolderTests.class })

public class AllTests {
}

Include the folder tests in the test suite


package com.novoda.downloadmanager;

import android.app.Notification;
import android.content.Context;
import android.support.annotation.DrawableRes;
import android.support.v4.app.NotificationCompat;

class DownloadBatchNotification implements NotificationCreator {

    private static final int ID = 1;
    private static final boolean NOT_INDETERMINATE = false;

    private final Context context;
    private final int iconDrawable;

    DownloadBatchNotification(Context context, @DrawableRes int iconDrawable) {
        this.context = context.getApplicationContext();
        this.iconDrawable = iconDrawable;
    }

    @Override
    public NotificationInformation createNotification(DownloadBatchTitle downloadBatchTitle,
                                                      int percentageDownloaded,
                                                      int bytesFileSize,
                                                      int bytesDownloaded) {
        String title = downloadBatchTitle.asString();
        String content = percentageDownloaded + "% downloaded";

        Notification notification = new NotificationCompat.Builder(context)
                .setProgress(bytesFileSize, bytesDownloaded, NOT_INDETERMINATE)
                .setSmallIcon(iconDrawable)
                .setContentTitle(title)
                .setContentText(content)
                .build();
        return new DownloadBatchNotificationInformation(ID, notification);
    }

    private static class DownloadBatchNotificationInformation implements NotificationInformation {
        private final int id;
        private final Notification notification;

        DownloadBatchNotificationInformation(int id, Notification notification) {
            this.id = id;
            this.notification = notification;
        }

        @Override
        public int getId() {
            return id;
        }

        @Override
        public Notification getNotification() {
            return notification;
        }
    }
}

package com.novoda.downloadmanager;

import android.app.Notification;
import android.content.Context;
import android.support.annotation.DrawableRes;
import android.support.v4.app.NotificationCompat;

class DownloadBatchNotification implements NotificationCreator {

    private static final boolean NOT_INDETERMINATE = false;
    private static final String CHANNEL_ID = "download_manager";

    private final Context context;
    private final int iconDrawable;

    DownloadBatchNotification(Context context, @DrawableRes int iconDrawable) {
        this.context = context.getApplicationContext();
        this.iconDrawable = iconDrawable;
    }

    @Override
    public NotificationInformation createNotification(DownloadBatchTitle downloadBatchTitle,
                                                      int percentageDownloaded,
                                                      int bytesFileSize,
                                                      int bytesDownloaded) {
        String title = downloadBatchTitle.asString();
        String content = percentageDownloaded + "% downloaded";

        Notification notification = new NotificationCompat.Builder(context, CHANNEL_ID)
                .setProgress(bytesFileSize, bytesDownloaded, NOT_INDETERMINATE)
                .setSmallIcon(iconDrawable)
                .setContentTitle(title)
                .setContentText(content)
                .build();

        return new DownloadBatchNotificationInformation(downloadBatchTitle.hashCode(), notification);
    }

    private static class DownloadBatchNotificationInformation implements NotificationInformation {
        private final int id;
        private final Notification notification;

        DownloadBatchNotificationInformation(int id, Notification notification) {
            this.id = id;
            this.notification = notification;
        }

        @Override
        public int getId() {
            return id;
        }

        @Override
        public Notification getNotification() {
            return notification;
        }
    }
}

Introduce a more reliable id and channel for Notifications.


package net.openhft.chronicle.queue.impl;

import net.openhft.chronicle.core.Jvm;

import java.io.File;

public enum StoreFileListeners implements StoreFileListener {
    NO_OP {
        @Override
        public void onReleased(int cycle, File file) {
        }
    },
    DEBUG {
        @Override
        public void onReleased(int cycle, File file) {
            if (Jvm.isDebugEnabled(getClass()))
                Jvm.debug().on(getClass(), "File released " + file);
        }
    }
}

package net.openhft.chronicle.queue.impl;

import net.openhft.chronicle.core.Jvm;

import java.io.File;

public enum StoreFileListeners implements StoreFileListener {
    NO_OP {
        @Override
        public void onReleased(int cycle, File file) {
        }

        @Override
        public boolean isActive() {
            return false;
        }
    },
    DEBUG {
        @Override
        public void onReleased(int cycle, File file) {
            if (Jvm.isDebugEnabled(getClass()))
                Jvm.debug().on(getClass(), "File released " + file);
        }

        @Override
        public boolean isActive() {
            return Jvm.isDebugEnabled(getClass());
        }
    }
}

Resolve merge issues re StoreFIleListeners


package rx.android.eventbus;

import rx.Observer;
import rx.Subscription;
import rx.subjects.Subject;

public interface EventBus {

    /**
     * Subscribes observer to queue.
     *

     * This variant always delivers notifications on the Android main thread.
     */
    <T> Subscription subscribe(Queue<T> queue, Observer<T> observer);

    /**
     * Subscribes observer to queue.
     *

     * Unlike {@link #subscribe(Queue, rx.Observer)}, this variant delivers notifications
     * on the same thread as the event source.
     */
    <T> Subscription subscribeImmediate(Queue<T> queue, Observer<T> observer);

    /**
     * Publishes an event by putting it on the given queue.
     */
    <T> void publish(Queue<T> queue, T event);

    /**
     * @return The Rx {@link rx.subjects.Subject} backing the given event queue.
     */
    <T> Subject<T, T> queue(Queue<T> queue);
}

Remove self-closing tags in JavaDoc

Remove self-closing tags in JavaDoc


package protocolsupport.protocol.typeremapper.basic;

import protocolsupport.protocol.typeremapper.utils.RemappingRegistry.EnumRemappingRegistry;
import protocolsupport.protocol.typeremapper.utils.RemappingTable.EnumRemappingTable;
import protocolsupport.protocol.types.WindowType;
import protocolsupport.protocol.utils.ProtocolVersionsHelper;
import protocolsupportbuildprocessor.Preload;

@Preload
public class GenericIdRemapper {

	public static final EnumRemappingRegistry<WindowType, EnumRemappingTable<WindowType>> INVENTORY = new EnumRemappingRegistry<WindowType, EnumRemappingTable<WindowType>>() {
		{
			registerRemapEntry(WindowType.BLAST_FURNACE, WindowType.FURNACE, ProtocolVersionsHelper.BEFORE_1_14);
			registerRemapEntry(WindowType.SMOKER, WindowType.FURNACE, ProtocolVersionsHelper.BEFORE_1_14);
			registerRemapEntry(WindowType.SHULKER_BOX, WindowType.GENERIC_9X4, ProtocolVersionsHelper.BEFORE_1_11);
		}
		@Override
		protected EnumRemappingTable<WindowType> createTable() {
			return new EnumRemappingTable<>(WindowType.class);
		}
	};

}

package protocolsupport.protocol.typeremapper.basic;

import protocolsupport.protocol.typeremapper.utils.RemappingRegistry.EnumRemappingRegistry;
import protocolsupport.protocol.typeremapper.utils.RemappingTable.EnumRemappingTable;
import protocolsupport.protocol.types.WindowType;
import protocolsupport.protocol.utils.ProtocolVersionsHelper;
import protocolsupportbuildprocessor.Preload;

@Preload
public class GenericIdRemapper {

	public static final EnumRemappingRegistry<WindowType, EnumRemappingTable<WindowType>> INVENTORY = new EnumRemappingRegistry<WindowType, EnumRemappingTable<WindowType>>() {
		{
			registerRemapEntry(WindowType.BLAST_FURNACE, WindowType.FURNACE, ProtocolVersionsHelper.BEFORE_1_14);
			registerRemapEntry(WindowType.SMOKER, WindowType.FURNACE, ProtocolVersionsHelper.BEFORE_1_14);
			registerRemapEntry(WindowType.SHULKER_BOX, WindowType.GENERIC_9X3, ProtocolVersionsHelper.BEFORE_1_11);
		}
		@Override
		protected EnumRemappingTable<WindowType> createTable() {
			return new EnumRemappingTable<>(WindowType.class);
		}
	};

}

Fix shulker box inventory remap.

Fix shulker box inventory remap.


/**
 * Copyright 2017 Pivotal Software, Inc.
 *

 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *

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

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.micrometer.core.instrument.simple;

import io.micrometer.core.instrument.step.StepRegistryConfig;

import java.time.Duration;

public interface SimpleConfig extends StepRegistryConfig {
    SimpleConfig DEFAULT = k -> null;

    // Useful in tests
    Duration DEFAULT_STEP = Duration.ofSeconds(10);

    @Override
    default String prefix() {
        return "simple";
    }

    /**
     * Returns the step size (reporting frequency) to use. The default is 10 seconds.
     */
    default Duration step() {
        String v = get(prefix() + ".step");
        return v == null ? DEFAULT_STEP : Duration.parse(v);
    }
}

/**
 * Copyright 2017 Pivotal Software, Inc.
 *

 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *

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

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.micrometer.core.instrument.simple;

import io.micrometer.core.instrument.step.StepRegistryConfig;

import java.time.Duration;

public interface SimpleConfig extends StepRegistryConfig {
    SimpleConfig DEFAULT = k -> null;

    // Useful in tests
    Duration DEFAULT_STEP = Duration.ofMinutes(1);

    @Override
    default String prefix() {
        return "simple";
    }

    /**
     * Returns the step size (reporting frequency) to use. The default is 10 seconds.
     */
    default Duration step() {
        String v = get(prefix() + ".step");
        return v == null ? DEFAULT_STEP : Duration.parse(v);
    }
}

Change default SimpleMeterRegistry step to 1 minute


package com.stefanhoth.ropasclisp.achievements;

import com.stefanhoth.ropasclisp.games_sdk.PlayGamesClient;

public class AchievementObserver {

    private final PlayGamesClient playGamesClient;
    private final boolean firstSessionToday;

    public AchievementObserver(PlayGamesClient playGamesClient, boolean firstSessionToday) {
        this.playGamesClient = playGamesClient;
        this.firstSessionToday = firstSessionToday;
    }

    public void onGameStart() {
        // first game start ever
        playGamesClient.unlockAchievement(ACHIEVEMENT.HELLO_THERE);

        // on X game starts per day
        if(! firstSessionToday){
            playGamesClient.unlockAchievement(ACHIEVEMENT.CONNOISSEUR);
            playGamesClient.unlockAchievement(ACHIEVEMENT.ADDICT);
        }
    }

    public void onGameWin() {
        playGamesClient.unlockAchievement(ACHIEVEMENT.GOTCHA);
        playGamesClient.unlockAchievement(ACHIEVEMENT.ON_A_ROLL);
        playGamesClient.unlockAchievement(ACHIEVEMENT.POKER_FACE);
    }
}

package com.stefanhoth.ropasclisp.achievements;

import android.content.Context;

import com.stefanhoth.ropasclisp.games_sdk.PlayGamesClient;

public class AchievementObserver {

    private final PlayGamesClient playGamesClient;
    private final Context context;

    public AchievementObserver(PlayGamesClient playGamesClient, final Context context) {
        this.playGamesClient = playGamesClient;
        this.context = context;
    }

    public void onGameStart() {
        // first game start ever
        playGamesClient.unlockAchievement(ACHIEVEMENT.HELLO_THERE);

        DAILY_STATE dailyState = DAILY_STATE.with(context);

        // on X game starts per day
        if (!dailyState.isTodaysFirstStart()) {

            final int todaysStarts = dailyState.getTodaysStarts();
            if (ACHIEVEMENT.ADDICT.isGoalReached(todaysStarts)) {
                playGamesClient.unlockAchievement(ACHIEVEMENT.ADDICT);
            }
            if (ACHIEVEMENT.CONNOISSEUR.isGoalReached(todaysStarts)) {
                playGamesClient.unlockAchievement(ACHIEVEMENT.CONNOISSEUR);
            }

        }
    }

    public void onGameWin() {
        playGamesClient.unlockAchievement(ACHIEVEMENT.GOTCHA);
        playGamesClient.unlockAchievement(ACHIEVEMENT.ON_A_ROLL);
        playGamesClient.unlockAchievement(ACHIEVEMENT.POKER_FACE);
    }
}

Correct behavior for daily start awards

Correct behavior for daily start awards


package org.nwapw.abacus;

public class Abacus {

    public static void main(String[] args){
        System.out.println("Hello world!");
    }

}

package org.nwapw.abacus;

import org.nwapw.abacus.window.Window;

import javax.swing.*;

public class Abacus {

    private Window mainUi;

    public Abacus(){
        init();
    }

    private void init() {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException | InstantiationException | UnsupportedLookAndFeelException | IllegalAccessException e) {
            e.printStackTrace();
        }
        mainUi = new Window();
        mainUi.setVisible(true);
    }

    public static void main(String[] args){
        new Abacus();
    }

}

Make the program actually create the UI.