package at.ac.tuwien.inso.controller.student;

import at.ac.tuwien.inso.entity.Course;
import at.ac.tuwien.inso.service.CoursesService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/student/courses")
public class StudentCoursesController {

    @Autowired
    private CoursesService coursesService;

    @ModelAttribute("allCourses")
    private List<Course> getAllCourses() {
        return coursesService.findForCurrentSemester();
    }

    @GetMapping
    public String courses() {
        return "/student/courses";
    }
}

package at.ac.tuwien.inso.controller.student;

import at.ac.tuwien.inso.entity.Course;
import at.ac.tuwien.inso.service.CoursesService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

@Controller
@RequestMapping("/student/courses")
public class StudentCoursesController {

    @Autowired
    private CoursesService coursesService;

    @ModelAttribute("allCourses")
    private List<Course> getAllCourses(@RequestParam(value = "search", required = false) String search) {
        final String searchString = getSearchString(search);
        return coursesService.findCourseForCurrentSemesterWithName(searchString);
    }

    @ModelAttribute("searchString")
    private String getSearchString(@RequestParam(value = "search", required = false) String search) {
        if (search != null && !search.isEmpty()) {
            return search;
        }

        return "";
    }

    @GetMapping
    public String courses() {
        return "/student/courses";
    }

}

Add search string, filter for name

Add search string, filter for name


package com.craftminecraft.bungee.bungeeban.command;

import com.craftminecraft.bungee.bungeeban.BanManager;

import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.plugin.Command;

public class ReloadBansCommand extends Command {

	public ReloadBansCommand() {
		super("reloadbans", "bungeeban.command.reloadbans");
	}

	@Override
	public void execute(CommandSender sender, String[] args) {
		BanManager.reload();
	}
}

package com.craftminecraft.bungee.bungeeban.command;

import com.craftminecraft.bungee.bungeeban.BanManager;

import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.plugin.Command;

public class ReloadBansCommand extends Command {

	public ReloadBansCommand() {
		super("reloadbans", "bungeeban.command.reloadbans");
	}

	@Override
	public void execute(CommandSender sender, String[] args) {
		BanManager.reload();
		sender.sendMessage(ChatColor.RED + "Reloaded banlist.");
	}
}

Add a message on banlist reload

Add a message on banlist reload


package uk.ac.edukapp.renderer;

public class GadgetRenderer {

	private static GadgetRenderer renderer = new GadgetRenderer();

	private GadgetRenderer() {
	}

	public static GadgetRenderer getInstance() {
		return renderer;
	}

	public String render(String uri, int width, int height) {

		String html = "";
		html += "<iframe src=\"http://widgets.open.ac.uk:8080/shindig/gadgets/ifr?url="
				+ uri + "\"";
		html += " width=\"" + "500" + "\"";
		html += " height=\"" + "300" + "\"";
		html += "></iframe>";
		return html;
	}

	public String render(String uri) {
		return render(uri, 500, 300);
	}
}

package uk.ac.edukapp.renderer;

import uk.ac.edukapp.server.configuration.StoreConfiguration;

public class GadgetRenderer {

	private static GadgetRenderer renderer = new GadgetRenderer();

	private GadgetRenderer() {
	}

	public static GadgetRenderer getInstance() {
		return renderer;
	}

	public String render(String uri, int width, int height) {

		String html = "";

		html += "<iframe src=\""+StoreConfiguration.getInstance().getShindigLocation()+"/gadgets/ifr?url="
				+ uri + "\"";
		html += " width=\"" + "500" + "\"";
		html += " height=\"" + "300" + "\"";
		html += "></iframe>";
		return html;
	}

	public String render(String uri) {
		return render(uri, 500, 300);
	}
}

Use StoreConfiguration to determine gadget render info


package org.wikipedia.descriptions;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;

import org.wikipedia.activity.SingleFragmentActivity;

public class DescriptionEditTutorialActivity
        extends SingleFragmentActivity<DescriptionEditTutorialFragment>
        implements DescriptionEditTutorialFragment.Callback {

    public static Intent newIntent(@NonNull Context context) {
        return new Intent(context, DescriptionEditTutorialActivity.class);
    }

    @TargetApi(18) @Override public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Setting this in the manifest will not suffice since any manifest screenOrientation
        // setting is overridden by the call to ActivityUtil.requestFullUserOrientation() in the
        // base ActionBarActivity's onCreate().
        setRequestedOrientation(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2
                ? ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT
                : ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

    @Override protected DescriptionEditTutorialFragment createFragment() {
        return DescriptionEditTutorialFragment.newInstance();
    }

    @Override public void onStartEditingClick() {
        setResult(RESULT_OK);
        finish();
    }
}

package org.wikipedia.descriptions;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.WindowManager;

import org.wikipedia.activity.SingleFragmentActivity;

public class DescriptionEditTutorialActivity
        extends SingleFragmentActivity<DescriptionEditTutorialFragment>
        implements DescriptionEditTutorialFragment.Callback {

    public static Intent newIntent(@NonNull Context context) {
        return new Intent(context, DescriptionEditTutorialActivity.class);
    }

    @TargetApi(18) @Override public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Setting this in the manifest will not suffice since any manifest screenOrientation
        // setting is overridden by the call to ActivityUtil.requestFullUserOrientation() in the
        // base ActionBarActivity's onCreate().
        setRequestedOrientation(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2
                ? ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT
                : ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

    @Override protected DescriptionEditTutorialFragment createFragment() {
        return DescriptionEditTutorialFragment.newInstance();
    }

    @Override public void onStartEditingClick() {
        setResult(RESULT_OK);
        finish();
    }
}

Fix status bar translucency in description editing tutorial

Somewhere along the line, the status bar in the description editing
tutorial lost its translucency.  This puts it back.

Change-Id: Id3b1134416afd19e6f397f4a5fa84cc9b57eb89f


package com.algorithms.stack;

/**
 * Created by Sumit on 01-Jul-17.
 */
public class ResizingArrayStackOfStrings {
}

package com.algorithms.stack;

public class ResizingArrayStackOfStrings {

    private String[] stack;
    private int N = 0;

    public ResizingArrayStackOfStrings() {
        stack = new String[1];
    }

    public boolean isEmpty() {
        return (N == 0);
    }

    public void push(String item) {
        if (N == stack.length) resize(stack.length * 2);
        stack[N++] = item;
    }

    public String pop() {
        String item = stack[--N];
        stack[N] = null;

        if (N > 0 && N == (stack.length / 4)) resize(stack.length / 2);
        return item;
    }

    private void resize(int capacity) {
        String[] copy = new String[capacity];
        for (int i = 0; i < N; i++) {
            copy[i] = stack[i];
        }
        stack = copy;
    }
}

Add resizing array implementation of stack of strings


package arez.processor;

import java.util.Objects;
import javax.annotation.Nonnull;
import javax.lang.model.element.Element;

final class ProcessorException
  extends RuntimeException
{
  @Nonnull
  private final Element _element;

  ProcessorException( @Nonnull final String message, @Nonnull final Element element )
  {
    super( message );
    _element = Objects.requireNonNull( element );
  }

  @Nonnull
  Element getElement()
  {
    return _element;
  }
}

package arez.processor;

import java.util.Objects;
import javax.annotation.Nonnull;
import javax.lang.model.element.Element;

public final class ProcessorException
  extends RuntimeException
{
  @Nonnull
  private final Element _element;

  public ProcessorException( @Nonnull final String message, @Nonnull final Element element )
  {
    super( message );
    _element = Objects.requireNonNull( element );
  }

  @Nonnull
  public Element getElement()
  {
    return _element;
  }
}

Make class public in preparation for moving to a separate library


package tv.mapper.roadstuff.network;

import java.util.function.Supplier;

import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.network.PacketBuffer;
import net.minecraftforge.fml.network.NetworkEvent;
import tv.mapper.roadstuff.item.ItemBrush;

public class BrushPacket
{
    private int pattern;
    private int paint;

    public BrushPacket(int pattern, int paint)
    {
        this.pattern = pattern;
        this.paint = paint;
    }

    public static void encode(BrushPacket packet, PacketBuffer buffer)
    {
        buffer.writeInt(packet.pattern);
        buffer.writeInt(packet.paint);
    }

    public static BrushPacket decode(PacketBuffer buffer)
    {
        int pattern = buffer.readInt();
        int paint = buffer.readInt();
        BrushPacket instance = new BrushPacket(pattern, paint);
        return instance;
    }

    public static void handle(BrushPacket packet, Supplier<NetworkEvent.Context> context)
    {
        context.get().setPacketHandled(true);
        EntityPlayerMP sender = context.get().getSender();
        ItemStack item = sender.getHeldItemMainhand();

        if(item.getItem() instanceof ItemBrush)
            sender.getHeldItemMainhand().getTag().setInt("pattern", packet.pattern);
    }
}

package tv.mapper.roadstuff.network;

import java.util.function.Supplier;

import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.network.PacketBuffer;
import net.minecraftforge.fml.network.NetworkEvent;
import tv.mapper.roadstuff.item.ItemBrush;

public class BrushPacket
{
    private int pattern;
    private int paint;

    public BrushPacket(int pattern, int paint)
    {
        this.pattern = pattern;
        this.paint = paint;
    }

    public static void encode(BrushPacket packet, PacketBuffer buffer)
    {
        buffer.writeInt(packet.pattern);
        buffer.writeInt(packet.paint);
    }

    public static BrushPacket decode(PacketBuffer buffer)
    {
        int pattern = buffer.readInt();
        int paint = buffer.readInt();
        BrushPacket instance = new BrushPacket(pattern, paint);
        return instance;
    }

    public static void handle(BrushPacket packet, Supplier<NetworkEvent.Context> context)
    {
        context.get().setPacketHandled(true);
        EntityPlayerMP sender = context.get().getSender();

        if(sender.getHeldItemMainhand().getItem() instanceof ItemBrush)
            sender.getHeldItemMainhand().getTag().setInt("pattern", packet.pattern);
        else if(sender.getHeldItemOffhand().getItem() instanceof ItemBrush)
            sender.getHeldItemOffhand().getTag().setInt("pattern", packet.pattern);
    }
}

Fix brush settings not saved with offhand.


package org.threadly.test.concurrent;

import org.threadly.util.Clock;

/**
 *
Generic tools to be used in unit testing.

 *
 * @author jent - Mike Jensen
 * @since 1.0.0
 */
public class TestUtils {
  private TestUtils() {
    // don't construct
  }

  /**
   * Since sleeps are sometimes necessary, this makes an easy way to ignore InterruptedException's.
   *
   * @param time time in milliseconds to make the thread to sleep
   */
  public static void sleep(long time) {
    try {
      Thread.sleep(time);
    } catch (InterruptedException e) {
      // reset interrupted status
      Thread.currentThread().interrupt();
    }
  }

  /**
   * Blocks until the System clock advances at least 1 millisecond.  This will also ensure that
   * the {@link Clock} class's representation of time has advanced.
   */
  public static void blockTillClockAdvances() {
    new TestCondition() {
      private static final int TIMEOUT_IN_MS = 1000;
      private static final int POLL_INTERVAL_IN_MS = 1;

      private final long startTime = Clock.accurateTimeMillis();

      @Override
      public boolean get() {
        return Clock.accurateTimeMillis() != startTime;
      }

      @Override
      public void blockTillTrue() {
        blockTillTrue(TIMEOUT_IN_MS, POLL_INTERVAL_IN_MS);
      }
    }.blockTillTrue();
  }
}

package org.threadly.test.concurrent;

import org.threadly.util.Clock;

/**
 *
Generic tools to be used in unit testing.

 *
 * @author jent - Mike Jensen
 * @since 1.0.0
 */
public class TestUtils {
  private TestUtils() {
    // don't construct
  }

  /**
   * Since sleeps are sometimes necessary, this makes an easy way to ignore InterruptedException's.
   *
   * @param time time in milliseconds to make the thread to sleep
   */
  public static void sleep(long time) {
    try {
      Thread.sleep(time);
    } catch (InterruptedException e) {
      // reset interrupted status
      Thread.currentThread().interrupt();
    }
  }

  /**
   * Blocks until the System clock advances at least 1 millisecond.  This will also ensure that
   * the {@link Clock} class's representation of time has advanced.
   */
  public static void blockTillClockAdvances() {
    new TestCondition() {
      private static final int TIMEOUT_IN_MS = 1000;
      private static final int POLL_INTERVAL_IN_MS = 1;

      private final long startTime = Clock.accurateTimeMillis();
      private final long alwaysProgressingStartTime = Clock.alwaysProgressingAccurateTimeMillis();

      @Override
      public boolean get() {
        return Clock.accurateTimeMillis() > startTime &&
                 Clock.alwaysProgressingAccurateTimeMillis() > alwaysProgressingStartTime;
      }

      @Override
      public void blockTillTrue() {
        blockTillTrue(TIMEOUT_IN_MS, POLL_INTERVAL_IN_MS);
      }
    }.blockTillTrue();
  }
}

Fix for unit test regressions Because the alwaysProgressing time is based off nanoseconds, it may not have progressed forward even though the accurateTimeMillis has progressed forwrad.


package com.uxxu.konashi.lib.action;

import android.bluetooth.BluetoothGattService;

import com.uxxu.konashi.lib.KonashiUUID;
import com.uxxu.konashi.lib.KonashiUtils;
import com.uxxu.konashi.lib.store.UartStore;
import com.uxxu.konashi.lib.util.UartUtils;

import java.util.UUID;

/**
 * Created by e10dokup on 2015/09/23
 **/
public class UartModeAction extends UartAction {
    private static final String TAG = UartModeAction.class.getSimpleName();
    private final UartModeAction self = this;

    private static final UUID UUID = KonashiUUID.UART_CONFIG_UUID;

    private int mMode;

    public UartModeAction(BluetoothGattService service, int mode, UartStore store) {
        super(service, UUID, store, true);
        mMode = mode;
    }

    @Override
    protected void setValue() {
        getCharacteristic().setValue(KonashiUtils.int2bytes(mMode));
    }

    @Override
    protected boolean hasValidParams() {
        return UartUtils.isValidMode(mMode);
    }
}

package com.uxxu.konashi.lib.action;

import android.bluetooth.BluetoothGattService;

import com.uxxu.konashi.lib.KonashiUUID;
import com.uxxu.konashi.lib.KonashiUtils;
import com.uxxu.konashi.lib.store.UartStore;
import com.uxxu.konashi.lib.util.UartUtils;

import java.util.UUID;

/**
 * Created by e10dokup on 2015/09/23
 **/
public class UartModeAction extends UartAction {
    private static final String TAG = UartModeAction.class.getSimpleName();
    private final UartModeAction self = this;

    private static final UUID UUID = KonashiUUID.UART_CONFIG_UUID;

    private int mMode;

    public UartModeAction(BluetoothGattService service, int mode, UartStore store) {
        super(service, UUID, store, true);
        mMode = mode;
    }

    @Override
    protected void setValue() {
        getCharacteristic().setValue(new byte[]{KonashiUtils.int2bytes(mMode)[0]});
    }

    @Override
    protected boolean hasValidParams() {
        return UartUtils.isValidMode(mMode);
    }
}

Use only 1byte on setValue

Use only 1byte on setValue


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

package org.voltdb.sqlgenerator;

import org.voltdb.*;

@ProcInfo (
    partitionInfo = "P1.ID: 0",
    singlePartition = true
)

public class StubProcedure extends VoltProcedure {
    public final SQLStmt getInfo = new SQLStmt(
            "SELECT * FROM P1;"
    );

    public VoltTable[] run(long id) {
        voltQueueSQL(getInfo, id);
        return voltExecuteSQL();
    }
}

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

package org.voltdb.sqlgenerator;

import org.voltdb.*;

@ProcInfo (
    partitionInfo = "P1.ID: 0",
    singlePartition = true
)

public class StubProcedure extends VoltProcedure {
    public final SQLStmt getInfo = new SQLStmt(
            "SELECT * FROM P1;"
    );

    public VoltTable[] run(int id) {
        voltQueueSQL(getInfo, id);
        return voltExecuteSQL();
    }
}

Fix SQL Coverage stub procedure parameter type mismatch.


package org.beryl.intents;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.webkit.MimeTypeMap;

public class IntentHelper {

	public static boolean canHandleIntent(final Context context, final Intent intent) {

		if (intent != null) {
			final PackageManager pm = context.getPackageManager();
			if (pm != null) {
				if (pm.queryIntentActivities(intent, 0).size() > 0) {
					return true;
				}
			}
		}

		return false;
	}

	public static String getMimeTypeFromUrl(Uri url) {
		return getMimeTypeFromUrl(url.getPath());
	}

	public static String getMimeTypeFromUrl(String url) {
		final MimeTypeMap mimeMap = MimeTypeMap.getSingleton();
		final String extension = MimeTypeMap.getFileExtensionFromUrl(url);
		return mimeMap.getMimeTypeFromExtension(extension);
	}

	public static final Intent getContentByType(String mimeType) {
		final Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		intent.setType(mimeType);
		return intent;
	}
}

package org.beryl.intents;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.webkit.MimeTypeMap;

public class IntentHelper {

	public static boolean canHandleIntent(final Context context, final Intent intent) {

		if (intent != null) {
			final PackageManager pm = context.getPackageManager();
			if (pm != null) {
				if (pm.queryIntentActivities(intent, 0).size() > 0) {
					return true;
				}
			}
		}

		return false;
	}

	public static String getMimeTypeFromUrl(Uri url) {
		return getMimeTypeFromUrl(url.getPath());
	}

	public static String getMimeTypeFromUrl(String url) {
		final MimeTypeMap mimeMap = MimeTypeMap.getSingleton();
		final String extension = MimeTypeMap.getFileExtensionFromUrl(url);
		return mimeMap.getMimeTypeFromExtension(extension);
	}

	public static final Intent getContentByType(String mimeType) {
		final Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		intent.setType(mimeType);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
		return intent;
	}
}

Clear activity on pick image intents.

Clear activity on pick image intents.


package com.scaleset.geo.geojson;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.Point;
import org.junit.Assert;
import org.junit.Test;

import java.io.IOException;

public class GeoJsonModuleTest extends Assert {

    private GeometryFactory factory = new GeometryFactory();
    private ObjectMapper mapper = new ObjectMapper().registerModule(new GeoJsonModule());

    @Test
    public void testSerializePoint() throws IOException {
        Point point = factory.createPoint(new Coordinate(-78, 39));
        String json = mapper.writeValueAsString(point);
        assertEquals("{\"type\":\"Point\",\"coordinates\":[-78.0,39.0]}", json);
    }

    @Test
    public void testDeserializePolygon() throws IOException {
        String json = "{\"point\": {\"type\":\"Point\",\"coordinates\":[-78.0,39.0]}}";
        HasGeometry hasGeometry = mapper.readValue(json, HasGeometry.class);
        assertNotNull(hasGeometry);
    }

    @JsonIgnoreProperties(ignoreUnknown = true)
    static class HasGeometry {
        public Point point;
    }
}

package com.scaleset.geo.geojson;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.scaleset.geo.Feature;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.Point;
import org.junit.Assert;
import org.junit.Test;

import java.io.IOException;

public class GeoJsonModuleTest extends Assert {

    private GeometryFactory factory = new GeometryFactory();
    private ObjectMapper mapper = new ObjectMapper().registerModule(new GeoJsonModule());

    @Test
    public void testSerializePoint() throws IOException {
        Point point = factory.createPoint(new Coordinate(-78, 39));
        String json = mapper.writeValueAsString(point);
        assertEquals("{\"type\":\"Point\",\"coordinates\":[-78.0,39.0]}", json);
        Point p2 = mapper.readValue(json, Point.class);
        assertEquals(point, p2);
    }

    @Test
    public void testSimpleFeature() throws IOException {
        Point point = factory.createPoint(new Coordinate(-78, 39));
        Feature feature = new Feature();
        feature.setGeometry(point);
        feature.getProperties().put("title", "Simple Point Feature");
        String json = mapper.writeValueAsString(feature);
    }

    @Test
    public void testDeserializePoint() throws IOException {
        String json = "{\"point\": {\"type\":\"Point\",\"coordinates\":[-78.0,39.0]}}";
        HasGeometry hasGeometry = mapper.readValue(json, HasGeometry.class);
        assertNotNull(hasGeometry);
    }

    @JsonIgnoreProperties(ignoreUnknown = true)
    static class HasGeometry {
        public Point point;
    }
}

Add example of using Feature class

Add example of using Feature class


class ReverseString {

    String reverse() {
        throw new UnsupportedOperationException("Delete this statement and write your own implementation.");
    }

}

class ReverseString {

    String reverse(String stringToReverse) {
        throw new UnsupportedOperationException("Delete this statement and write your own implementation.");
    }

}

Change method reverse method signature to follow tests reqs


package jp.mixi.triaina.webview.bridges;

import com.google.inject.Inject;

import android.os.Vibrator;
import jp.mixi.triaina.commons.utils.ArrayUtils;
import jp.mixi.triaina.webview.annotation.Bridge;
import jp.mixi.triaina.webview.entity.device.VibratorVibrateParams;

public class VibratorBridge implements BridgeObject {
	@Inject
	private Vibrator mVibrator;

	@Bridge("system.vibrator.vibrate")
	public void doVibrate(VibratorVibrateParams params) {
		Integer r = params.getRepeat();
		if (r == null)
			mVibrator.vibrate(params.getMsec());
		else
			mVibrator.vibrate(ArrayUtils.convert(params.getPattern()), r == null ? -1 : r.intValue());
	}

	@Bridge("system.vibrator.cancel")
	public void doCancel() {
		mVibrator.cancel();
	}

	@Override
	public void onResume() {
	}

	@Override
	public void onPause() {
		doCancel();
	}

	@Override
	public void onDestroy() {
	}
}

package jp.mixi.triaina.webview.bridges;

import com.google.inject.Inject;

import android.os.Vibrator;
import jp.mixi.triaina.commons.utils.ArrayUtils;
import jp.mixi.triaina.webview.annotation.Bridge;
import jp.mixi.triaina.webview.entity.device.VibratorVibrateParams;

public class VibratorBridge implements BridgeObject {
    @Inject
    private Vibrator mVibrator;

    private boolean mIsEnable;

    @Bridge("system.vibrator.vibrate")
    public void doVibrate(VibratorVibrateParams params) {
        mIsEnable = true;

        Integer r = params.getRepeat();
        if (r == null)
            mVibrator.vibrate(params.getMsec());
        else
            mVibrator.vibrate(ArrayUtils.convert(params.getPattern()), r == null ? -1 : r.intValue());
    }

    @Bridge("system.vibrator.cancel")
    public void doCancel() {
        if (mIsEnable) {
            mVibrator.cancel();
            mIsEnable = false;
        }
    }

    @Override
    public void onResume() {
    }

    @Override
    public void onPause() {
        doCancel();
    }

    @Override
    public void onDestroy() {
    }
}

[WebViewBridge] Fix a issue that requires a android.permission.VIBRATE

https://github.com/hnakagawa/triaina/issues/2 reported by fumiz


// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.banners;

import org.chromium.base.VisibleForTesting;

/**
 * Fetches data about the given app.
 */
public abstract class AppDetailsDelegate {
    /**
     * Class to inform when the app's details have been retrieved.
     */
    public interface Observer {
        /**
         * Called when the task has finished.
         * @param data Data about the requested package.  Will be null if retrieval failed.
         */
        @VisibleForTesting
        public void onAppDetailsRetrieved(AppData data);
    }

    /**
     * Retrieves information about the given package asynchronously.  When details have been
     * retrieved, the observer is alerted.
     * @param observer    Informed when the app details have been received.
     * @param url         URL of the page requesting a banner.
     * @param packageName Name of the app's package.
     * @param iconSize    Size of the icon to retrieve.
     */
    protected abstract void getAppDetailsAsynchronously(
            Observer observer, String url, String packageName, int iconSize);

    /**
     * Destroy the delegate, cleaning up any open hooks.
     */
    public abstract void destroy();
}

// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.banners;

import org.chromium.base.VisibleForTesting;

/**
 * Fetches data about the given app.
 */
public abstract class AppDetailsDelegate {
    /**
     * Class to inform when the app's details have been retrieved.
     */
    public interface Observer {
        /**
         * Called when the task has finished.
         * @param data Data about the requested package.  Will be null if retrieval failed.
         */
        @VisibleForTesting
        public void onAppDetailsRetrieved(AppData data);
    }

    /**
     * Retrieves information about the given package asynchronously.  When details have been
     * retrieved, the observer is alerted.
     * @param observer    Informed when the app details have been received.
     * @param url         URL of the page requesting a banner.
     * @param packageName Name of the app's package.
     * @param iconSize    Size of the icon to retrieve.
     */
    protected void getAppDetailsAsynchronously(
            Observer observer, String url, String packageName, int iconSize) { }

    /**
     * Retrieves information about the given package asynchronously.  When details have been
     * retrieved, the observer is alerted.
     * @param observer    Informed when the app details have been received.
     * @param url         URL of the page requesting a banner.
     * @param packageName Name of the app's package.
     * @param referrer    Referrer specified by the page requesting a banner.
     * @param iconSize    Size of the icon to retrieve.
     */
    protected void getAppDetailsAsynchronously(
            Observer observer, String url, String packageName, String referrer, int iconSize) { }

    /**
     * Destroy the delegate, cleaning up any open hooks.
     */
    public abstract void destroy();
}

Add a referrer parameter to the app details fetcher.

This is the first part of a three-sided patch which will allow
developers to specify a referrer in the URL of a manifest related
application. The referrer will then be added to the app details
fetch and sent to the relevant store (currently just the Play Store).

The outdated method and dummy implementations will be removed in the
third side of this patch once the relevant downstream method is updated.

BUG=503226

Review URL: https://codereview.chromium.org/1277743003

Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#342236}


package org.zalando.nakadi.annotations.validation;

import javax.validation.Constraint;
import javax.validation.Payload;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({
        ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE,
        ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
@Size(max = 1000)
@Pattern(regexp = "^([a-zA-Z0-9]([a-zA-Z0-9_.-]*[a-zA-Z0-9])?)?$", message = "Should contain only allowed symbols")
@Constraint(validatedBy = {})
public @interface LabelValue {
    String message() default "{org.zalando.nakadi.annotations.validation.LabelValue.message}}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

package org.zalando.nakadi.annotations.validation;

import javax.validation.Constraint;
import javax.validation.Payload;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({
        ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE,
        ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
@Size(max = 63)
@Pattern(regexp = "^([a-zA-Z0-9]([a-zA-Z0-9_.-]*[a-zA-Z0-9])?)?$", message = "Should contain only allowed symbols")
@Constraint(validatedBy = {})
public @interface LabelValue {
    String message() default "{org.zalando.nakadi.annotations.validation.LabelValue.message}}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

Correct size for label value

Correct size for label value

Co-authored-by: burimshala <fbe1da75ceff9686eaf909d9a76b100da3b76719@gmail.com>


package com.capitalone.dashboard.model;

/**
 * CollectorItem extension to store the instance, build job and build url.
 */
public class HudsonJob extends CollectorItem {
    private static final String INSTANCE_URL = "instanceUrl";
    private static final String JOB_NAME = "jobName";
    private static final String JOB_URL = "jobUrl";

    public String getInstanceUrl() {
        return (String) getOptions().get(INSTANCE_URL);
    }

    public void setInstanceUrl(String instanceUrl) {
        getOptions().put(INSTANCE_URL, instanceUrl);
    }

    public String getJobName() {
        return (String) getOptions().get(JOB_NAME);
    }

    public void setJobName(String jobName) {
        getOptions().put(JOB_NAME, jobName);
    }

    public String getJobUrl() {
        return (String) getOptions().get(JOB_URL);
    }

    public void setJobUrl(String jobUrl) {
        getOptions().put(JOB_URL, jobUrl);
    }

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

        HudsonJob hudsonJob = (HudsonJob) o;

        return getInstanceUrl().equals(hudsonJob.getInstanceUrl()) && getJobName().equals(hudsonJob.getJobName());
    }

    @Override
    public int hashCode() {
        int result = getInstanceUrl().hashCode();
        result = 31 * result + getJobName().hashCode();
        return result;
    }
}

package com.capitalone.dashboard.model;

/**
 * CollectorItem extension to store the instance, build job and build url.
 */
public class HudsonJob extends JobCollectorItem {

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

        HudsonJob hudsonJob = (HudsonJob) o;

        return getInstanceUrl().equals(hudsonJob.getInstanceUrl()) && getJobName().equals(hudsonJob.getJobName());
    }

    @Override
    public int hashCode() {
        int result = getInstanceUrl().hashCode();
        result = 31 * result + getJobName().hashCode();
        return result;
    }
}

Fix build - missed a class when refactoring


package com.stolets.rxdiffutil.diffrequest;

import android.support.annotation.NonNull;

import com.stolets.rxdiffutil.di.FragmentScope;

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

import static com.stolets.rxdiffutil.internal.Preconditions.checkNotNull;

/**
 * Manages the diff requests lifecycle.
 */
@FragmentScope
public final class DiffRequestManager {
    @NonNull
    private Map<String, DiffRequest> mPendingRequests = new HashMap<>();

    /**
     * Adds a new {@link DiffRequest} to the pending list.
     * @param diffRequest A new {@link DiffRequest}.
     *                    Note: if a request with the same tag is already exists it will be replaced.
     */
    public void addPendingRequest(@NonNull final DiffRequest diffRequest) {
        checkNotNull(diffRequest, "diffRequest must not be null!");
        mPendingRequests.put(diffRequest.getTag(), diffRequest);
    }

    /**
     * @return A map holding all pending requests. Note: the returned map is unmodifiable.
     */
    @NonNull
    public Map<String, DiffRequest> getPendingRequests() {
        return Collections.unmodifiableMap(mPendingRequests);
    }
}

package com.stolets.rxdiffutil.diffrequest;

import android.support.annotation.NonNull;

import com.stolets.rxdiffutil.di.FragmentScope;

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

import static com.stolets.rxdiffutil.internal.Preconditions.checkNotNull;

/**
 * Manages the diff requests lifecycle.
 */
@FragmentScope
public final class DiffRequestManager {
    @NonNull
    private Map<String, DiffRequest> mPendingRequests = new HashMap<>();

    /**
     * Adds a new {@link DiffRequest} to the pending list.
     * @param diffRequest A new {@link DiffRequest}.
     *                    Note: if a request with the same tag is already exists it will be replaced.
     */
    void addPendingRequest(@NonNull final DiffRequest diffRequest) {
        checkNotNull(diffRequest, "diffRequest must not be null!");
        mPendingRequests.put(diffRequest.getTag(), diffRequest);
    }

    /**
     * @return A map holding all pending requests. Note: the returned map is unmodifiable.
     */
    @NonNull
    Map<String, DiffRequest> getPendingRequests() {
        return Collections.unmodifiableMap(mPendingRequests);
    }
}

Remove unneeded public visibility modifier


package android.view;

import com.google.gwt.resources.client.TextResource;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Widget;

import android.content.Context;

public class LayoutInflater {

	public static LayoutInflater from(Context context) {
		return new LayoutInflater();
	}

	public View inflate(TextResource layout, Context ctx) {
		return new View((new HTML(layout.getText())).getElement());
	}

	public View inflate(Widget widget, Context ctx) {
		return new View(widget);
	}

	public View inflate(Widget widget, ViewGroup container, boolean something) {
		return new View(widget);
	}

}

package android.view;

import android.content.res.Resources;
import com.google.gwt.resources.client.TextResource;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Widget;

import android.content.Context;

public class LayoutInflater {

	public static LayoutInflater from(Context context) {
		return new LayoutInflater();
	}

	public View inflate(TextResource layout, Context ctx) {
		return new View((new HTML(layout.getText())).getElement());
	}

	public View inflate(int resId, Context ctx) {
		return new View(Resources.getResourceResolver().getLayout(resId));
	}

    public View inflate(Widget widget, Context ctx) {
        return new View(widget);
    }

	public View inflate(int resId, ViewGroup container, boolean something) {
		return new View(Resources.getResourceResolver().getLayout(resId));
	}

    public View inflate(Widget widget, ViewGroup container, boolean something) {
        return new View(widget);
    }
}

Inflate also from Layout Resource ID

Inflate also from Layout Resource ID


package io.leangen.graphql.metadata.strategy.input;

import com.google.gson.FieldNamingPolicy;
import com.google.gson.FieldNamingStrategy;

import java.lang.reflect.Field;

/**
 * Created by bojan.tomic on 5/25/16.
 */
public class GsonFieldNamingStrategy implements FieldNamingStrategy {

    private FieldNameGenerator fieldNameGenerator;
    private FieldNamingStrategy fallback;

    public GsonFieldNamingStrategy() {
        this(new AnnotationBasedFieldNameGenerator(), FieldNamingPolicy.IDENTITY);
    }

    public GsonFieldNamingStrategy(FieldNameGenerator fieldNameGenerator, FieldNamingStrategy fallback) {
        this.fieldNameGenerator = fieldNameGenerator;
        this.fallback = fallback;
    }

    @Override
    public String translateName(Field field) {
        return fieldNameGenerator.generateFieldName(field).orElse(fallback.translateName(field));
    }
}

package io.leangen.graphql.metadata.strategy.input;

import com.google.gson.FieldNamingPolicy;
import com.google.gson.FieldNamingStrategy;
import io.leangen.graphql.util.ClassUtils;

import java.lang.reflect.Field;
import java.util.Optional;

/**
 * Created by bojan.tomic on 5/25/16.
 */
public class GsonFieldNamingStrategy implements FieldNamingStrategy {

    private FieldNameGenerator fieldNameGenerator;
    private FieldNamingStrategy fallback;

    public GsonFieldNamingStrategy() {
        this(new AnnotationBasedFieldNameGenerator(), FieldNamingPolicy.IDENTITY);
    }

    public GsonFieldNamingStrategy(FieldNameGenerator fieldNameGenerator, FieldNamingStrategy fallback) {
        this.fieldNameGenerator = fieldNameGenerator;
        this.fallback = fallback;
    }

    @Override
    public String translateName(Field field) {
        return fieldNameGenerator.generateFieldName(field)
                .orElse(nameFromGetter(field)
                        .orElse(fallback.translateName(field)));
    }

    private Optional<String> nameFromGetter(Field field) {
        try {
            return fieldNameGenerator.generateFieldName(ClassUtils.findGetter(field.getType(), field.getName()));
        } catch (NoSuchMethodException e) {
            return Optional.empty();
        }
    }
}

Fix deserialization with annotated getters


package com.yammer.dropwizard.config;

import java.io.File;

/**
 * An exception thrown where there is an error parsing a configuration object.
 */
public class ConfigurationException extends Exception {
    private static final long serialVersionUID = 5325162099634227047L;

    /**
     * Creates a new {@link ConfigurationException} for the given file with the given errors.
     *
     * @param file      the bad configuration file
     * @param errors    the errors in the file
     */
    public ConfigurationException(File file, Iterable<String> errors) {
        super(formatMessage(file, errors));
    }

    private static String formatMessage(File file, Iterable<String> errors) {
        final StringBuilder msg = new StringBuilder(file.toString())
                .append(" has the following errors:\n");
        for (String error : errors) {
            msg.append("  * ").append(error);
        }
        return msg.toString();
    }
}

package com.yammer.dropwizard.config;

import java.io.File;

/**
 * An exception thrown where there is an error parsing a configuration object.
 */
public class ConfigurationException extends Exception {
    private static final long serialVersionUID = 5325162099634227047L;

    /**
     * Creates a new {@link ConfigurationException} for the given file with the given errors.
     *
     * @param file      the bad configuration file
     * @param errors    the errors in the file
     */
    public ConfigurationException(File file, Iterable<String> errors) {
        super(formatMessage(file, errors));
    }

    private static String formatMessage(File file, Iterable<String> errors) {
        final StringBuilder msg = new StringBuilder(file.toString())
                .append(" has the following errors:\n");
        for (String error : errors) {
            msg.append("  * ").append(error).append('\n');
        }
        return msg.toString();
    }
}

Fix formatting of config errors.

Fix formatting of config errors.


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

/**
 * Created by drfish on 27/05/2017.
 */
public class _095UniqueBinarySearchTreesII {
    public List<TreeNode> generateTrees(int n) {
        List<TreeNode> result = genTrees(1, n);
        if (result.get(0) == null) {
            return new ArrayList<>();
        } else {
            return result;
        }
    }

    private List<TreeNode> genTrees(int start, int end) {
        List<TreeNode> result = new ArrayList<>();
        if (start > end) {
            result.add(null);
        }
        for (int i = start; i <= end; i++) {
            List<TreeNode> leftTrees = genTrees(start, i - 1);
            List<TreeNode> rightTrees = genTrees(i + 1, end);
            for (TreeNode leftTree : leftTrees) {
                for (TreeNode rightTree : rightTrees) {
                    TreeNode root = new TreeNode(i);
                    root.left = leftTree;
                    root.right = rightTree;
                    result.add(root);
                }
            }
        }
        return result;
    }
}

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

/**
 * Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1...n.
 *

 * For example,
 * Given n = 3, your program should return all 5 unique BST's shown below.
 *

 * 1         3     3      2      1
 *  \       /     /      / \      \
 *   3     2     1      1   3      2
 *  /     /       \                 \
 * 2     1         2                 3
 *

 * Created by drfish on 27/05/2017.
 */
public class _095UniqueBinarySearchTreesII {
    public List<TreeNode> generateTrees(int n) {
        List<TreeNode> result = genTrees(1, n);
        if (result.get(0) == null) {
            return new ArrayList<>();
        } else {
            return result;
        }
    }

    private List<TreeNode> genTrees(int start, int end) {
        List<TreeNode> result = new ArrayList<>();
        if (start > end) {
            result.add(null);
        }
        for (int i = start; i <= end; i++) {
            List<TreeNode> leftTrees = genTrees(start, i - 1);
            List<TreeNode> rightTrees = genTrees(i + 1, end);
            for (TreeNode leftTree : leftTrees) {
                for (TreeNode rightTree : rightTrees) {
                    TreeNode root = new TreeNode(i);
                    root.left = leftTree;
                    root.right = rightTree;
                    result.add(root);
                }
            }
        }
        return result;
    }
}

Add description for java 95

Add description for java 95


/*
 * HeadsUp Agile
 * Copyright 2014 Heads Up Development Ltd.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.headsupdev.agile.web.wicket;

import org.apache.wicket.util.convert.converters.AbstractConverter;
import org.headsupdev.agile.storage.issues.Duration;

import java.util.Locale;

/**
 * Created by Gordon Edwards on 02/07/2014.
 */
public class DurationConverter
        extends AbstractConverter
{
    @Override
    protected Class<?> getTargetType()
    {
        return Duration.class;
    }

    @Override
    public Object convertToObject( String value, Locale locale )
    {
        Duration duration = null;
        try
        {
            duration = Duration.fromString( value );
        }
        catch ( Exception e )
        {
            throw newConversionException( "Invalid", value, locale );
        }
        return duration;
    }
}

/*
 * HeadsUp Agile
 * Copyright 2014 Heads Up Development Ltd.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.headsupdev.agile.web.wicket;

import org.apache.wicket.util.convert.converters.AbstractConverter;
import org.headsupdev.agile.storage.issues.Duration;
import org.headsupdev.support.java.StringUtil;

import java.util.Locale;

/**
 * Created by Gordon Edwards on 02/07/2014.
 *
 * @since 2.1
 */
public class DurationConverter
        extends AbstractConverter
{
    @Override
    protected Class<?> getTargetType()
    {
        return Duration.class;
    }

    @Override
    public Object convertToObject( String value, Locale locale )
    {
        if ( StringUtil.isEmpty( value ) )
        {
            return null;
        }

        try
        {
            return Duration.fromString( value );
        }
        catch ( Exception e )
        {
            throw newConversionException( "Invalid", value, locale );
        }
    }
}

Support a null duration worked - setRequired can be used if we need non-null - fixes issue:89


package org.udg.pds.simpleapp_javaee.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;
import java.io.Serializable;

@Entity
// This tells JAXB that it has to ignore getters and setters and only use fields for JSON marshaling/unmarshaling
public class Tag implements Serializable {
  /**
   * Default value included to remove warning. Remove or modify at will.
   **/
  private static final long serialVersionUID = 1L;

  public Tag() {
  }

  public Tag(String name, String description) {
    this.name = name;
    this.description = description;
  }

  // This tells JAXB that this field can be used as ID
  // Since XmlID can only be used on Strings, we need to use LongAdapter to transform Long <-> String
  @Id
  // Don't forget to use the extra argument "strategy = GenerationType.IDENTITY" to get AUTO_INCREMENT
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @NotNull
  private String name;

  @NotNull
  private String description;

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public Long getId() {
    return id;
  }
}

package org.udg.pds.simpleapp_javaee.model;

import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.udg.pds.simpleapp_javaee.rest.serializer.JsonDateSerializer;
import org.udg.pds.simpleapp_javaee.rest.serializer.JsonTagSerializer;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;
import java.io.Serializable;

@JsonSerialize(using = JsonTagSerializer.class)
@Entity
// This tells JAXB that it has to ignore getters and setters and only use fields for JSON marshaling/unmarshaling
public class Tag implements Serializable {
  /**
   * Default value included to remove warning. Remove or modify at will.
   **/
  private static final long serialVersionUID = 1L;

  public Tag() {
  }

  public Tag(String name, String description) {
    this.name = name;
    this.description = description;
  }

  // This tells JAXB that this field can be used as ID
  // Since XmlID can only be used on Strings, we need to use LongAdapter to transform Long <-> String
  @Id
  // Don't forget to use the extra argument "strategy = GenerationType.IDENTITY" to get AUTO_INCREMENT
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @NotNull
  private String name;

  @NotNull
  private String description;

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public Long getId() {
    return id;
  }

    public String getDescription() {
        return description;
    }
}

Add custom serializer. Add getter for description


package com.slugterra.biomes;

import com.slugterra.biomes.BiomeRegistry;

import net.minecraft.world.biome.BiomeGenBase;
import net.minecraft.world.gen.layer.GenLayer;
import net.minecraft.world.gen.layer.IntCache;

public class SlugterraGenLayerBiome extends GenLayer {

	protected BiomeGenBase[] allowedBiomes = {BiomeRegistry.undertowCavern, BiomeRegistry.snowdanceCavern, BiomeRegistry.deadWeed, BiomeRegistry.bullseyeCavern, BiomeRegistry.quietlawnCavern, BiomeRegistry.hideoutCavern};

	public SlugterraGenLayerBiome(long seed, GenLayer genlayer) {
		super(seed);
		this.parent = genlayer;
	}

	public SlugterraGenLayerBiome(long seed) {
		super(seed);
	}

	@Override
	public int[] getInts(int x, int z, int width, int depth)
	{
		int[] dest = IntCache.getIntCache(width*depth);

		for (int dz=0; dz<depth; dz++)
		{
			for (int dx=0; dx<width; dx++)
			{
				this.initChunkSeed(dx+x, dz+z);
				dest[(dx+dz*width)] = this.allowedBiomes[nextInt(this.allowedBiomes.length)].biomeID;
			}
		}
		return dest;
	}
}

package com.slugterra.biomes;

import net.minecraft.world.biome.Biome;
import net.minecraft.world.gen.layer.GenLayer;
import net.minecraft.world.gen.layer.IntCache;

public class SlugterraGenLayerBiome extends GenLayer {

	protected Biome[] allowedBiomes = {BiomeRegistry.undertowCavern, BiomeRegistry.snowdanceCavern, BiomeRegistry.deadWeed, BiomeRegistry.bullseyeCavern, BiomeRegistry.quietlawnCavern, BiomeRegistry.hideoutCavern};

	public SlugterraGenLayerBiome(long seed, GenLayer genlayer) {
		super(seed);
		this.parent = genlayer;
	}

	public SlugterraGenLayerBiome(long seed) {
		super(seed);
	}

	@Override
	public int[] getInts(int x, int z, int width, int depth)
	{
		int[] dest = IntCache.getIntCache(width*depth);

		for (int dz=0; dz<depth; dz++)
		{
			for (int dx=0; dx<width; dx++)
			{
				this.initChunkSeed(dx+x, dz+z);
				dest[(dx+dz*width)] = Biome.getIdForBiome(this.allowedBiomes[nextInt(this.allowedBiomes.length)]);
			}
		}
		return dest;
	}
}

Change allowedBiomes from BiomeGenBase[] to Biome[]


package base.course;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;

@RestController
@RequestMapping("/course")
public class CourseController {

    @Autowired
    private CourseRepository courseRepository;

    @GetMapping
    public ArrayList<Course> listAll() {
        ArrayList<Course> courses = new ArrayList<>();
        courseRepository.findAll().forEach(course -> courses.add(course));
        return courses;
    }

    @GetMapping("{name}")
    public Course find(@PathVariable String name) {
        return courseRepository.findByName(name.toUpperCase());
    }

    @GetMapping("/prefix/{prefix}")
    public ArrayList<Course> listAllPrefix(@PathVariable String prefix) {
        ArrayList<Course> courses = new ArrayList<>();
        courseRepository.findByPrefix(prefix.toUpperCase()).forEach(course -> courses.add(course));
        return courses;
    }

}

package base.course;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;

@RestController
@RequestMapping("/course")
public class CourseController {

    @Autowired
    private CourseRepository courseRepository;

    @GetMapping
    public ResponseEntity<ArrayList<Course>> listAll() {
        ArrayList<Course> courses = new ArrayList<>();
        courseRepository.findAll().forEach(course -> courses.add(course));

        if (courses.size() == 0) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        } else {
            return new ResponseEntity<>(courses, HttpStatus.OK);
        }
    }

    @GetMapping("{name}")
    public ResponseEntity<Course> find(@PathVariable String name) {
        Course course = courseRepository.findByName(name.toUpperCase());

        if (course == null) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        } else {
            return new ResponseEntity<>(course, HttpStatus.OK);
        }
    }

    @GetMapping("/prefix/{prefix}")
    public ResponseEntity<ArrayList<Course>> listAllPrefix(@PathVariable String prefix) {
        ArrayList<Course> courses = new ArrayList<>();
        courseRepository.findByPrefix(prefix.toUpperCase()).forEach(course -> courses.add(course));

        if (courses.size() == 0) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        } else {
            return new ResponseEntity<>(courses, HttpStatus.OK);
        }
    }

}

Add HttpStatus 404 return for courses not found


package bio.terra.cli.command;

import bio.terra.cli.context.GlobalContext;
import bio.terra.cli.context.WorkspaceContext;
import java.nio.file.FileAlreadyExistsException;
import java.util.concurrent.Callable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import picocli.CommandLine.Command;

/** This class corresponds to the second-level "terra status" command. */
@Command(name = "status", description = "Print details about the current workspace.")
public class Status implements Callable<Integer> {
  private static final Logger logger = LoggerFactory.getLogger(Status.class);

  @Override
  public Integer call() throws FileAlreadyExistsException {
    GlobalContext globalContext = GlobalContext.readFromFile();
    WorkspaceContext workspaceContext = WorkspaceContext.readFromFile();

    System.out.println("Terra server: " + globalContext.server.name);

    // check if current workspace is defined
    if (workspaceContext.isEmpty()) {
      System.out.println("There is no current Terra workspace defined.");
    } else {
      System.out.println("Terra workspace: " + workspaceContext.getWorkspaceId());
      System.out.println("Google project: " + workspaceContext.getGoogleProject());
    }

    return 0;
  }
}

package bio.terra.cli.command;

import bio.terra.cli.context.GlobalContext;
import bio.terra.cli.context.WorkspaceContext;
import java.nio.file.FileAlreadyExistsException;
import java.util.concurrent.Callable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import picocli.CommandLine.Command;

/** This class corresponds to the second-level "terra status" command. */
@Command(name = "status", description = "Print details about the current workspace.")
public class Status implements Callable<Integer> {
  private static final Logger logger = LoggerFactory.getLogger(Status.class);

  @Override
  public Integer call() {
    GlobalContext globalContext = GlobalContext.readFromFile();
    WorkspaceContext workspaceContext = WorkspaceContext.readFromFile();

    System.out.println("Terra server: " + globalContext.server.name);

    // check if current workspace is defined
    if (workspaceContext.isEmpty()) {
      System.out.println("There is no current Terra workspace defined.");
    } else {
      System.out.println("Terra workspace: " + workspaceContext.getWorkspaceId());
      System.out.println("Google project: " + workspaceContext.getGoogleProject());
    }

    return 0;
  }
}

Remove exception used for debugging.

Remove exception used for debugging.


package ua.anironglass.template.ui.activities.main;

import android.os.Bundle;

import javax.inject.Inject;

import timber.log.Timber;
import ua.anironglass.template.R;
import ua.anironglass.template.ui.activities.base.BaseActivity;

public class MainActivity extends BaseActivity implements MainMvpView {

    @Inject MainPresenter mainPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Timber.d("Create MainActivity");
        getComponent().inject(this);
        setContentView(R.layout.activity_main);

        initializeView();
    }

    @Override
    public void onResume() {
        Timber.i("Resume MainActivity");
        super.onResume();
    }

    @Override
    protected void onPause() {
        Timber.i("Pause MainActivity");
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        Timber.i("Destroy MainActivity");
        super.onDestroy();
        mainPresenter.detachView();
    }

    private void initializeView() {
        mainPresenter.attachView(this);
    }

}

package ua.anironglass.template.ui.activities.main;

import android.os.Bundle;

import javax.inject.Inject;

import timber.log.Timber;
import ua.anironglass.template.R;
import ua.anironglass.template.ui.activities.base.BaseActivity;

public class MainActivity extends BaseActivity implements MainMvpView {

    @Inject MainPresenter mainPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Timber.d("Create MainActivity");
        getComponent().inject(this);
        setContentView(R.layout.activity_main);

        initializeView();
    }

    @Override
    public void onResume() {
        Timber.d("Resume MainActivity");
        super.onResume();
    }

    @Override
    protected void onPause() {
        Timber.d("Pause MainActivity");
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        Timber.d("Destroy MainActivity");
        super.onDestroy();
        mainPresenter.detachView();
    }

    private void initializeView() {
        mainPresenter.attachView(this);
    }

}

Change info log to debug

Change info log to debug


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

import javax.sound.midi.Instrument;
import javax.sound.midi.Patch;
import javax.sound.midi.Soundbank;

public class NullInstrument extends Instrument
{
    NullInstrument(Soundbank soundbank, Patch patch, String name, Class<?> dataClass)
    {
        super(soundbank, patch, name, dataClass);
    }

    @Override
    public Object getData()
    {
        return null;
    }
}

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

import javax.annotation.Nullable;
import javax.sound.midi.Instrument;
import javax.sound.midi.Patch;
import javax.sound.midi.Soundbank;

public class NullInstrument extends Instrument
{
    NullInstrument(@Nullable Soundbank soundbank, Patch patch, String name, Class<?> dataClass)
    {
        super(soundbank, patch, name, dataClass);
    }

    @Nullable
    @Override
    public Object getData()
    {
        return null;
    }
}

Clean up per sonarcloud and IntelliJ.

Clean up per sonarcloud and IntelliJ.


package cn.mutils.app.ui;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.GridView;

public class GridViewer extends GridView {

	/** 设置是否高度全部显示 */
	protected boolean mShowAll = false;

	public GridViewer(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public GridViewer(Context context) {
		super(context);
	}

	public GridViewer(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	public boolean isShowAll() {
		return mShowAll;
	}

	public void setShowAll(boolean showAll) {
		this.mShowAll = showAll;
	}

	@Override
	public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		if (mShowAll) {
			heightMeasureSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE, MeasureSpec.AT_MOST);
		}
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
	}

}

package cn.mutils.app.ui;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.GridView;

public class GridViewer extends GridView {

	/** 设置是否高度全部显示 */
	protected boolean mShowAll = false;

	public GridViewer(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public GridViewer(Context context) {
		super(context);
	}

	public GridViewer(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	public boolean isShowAll() {
		return mShowAll;
	}

	public void setShowAll(boolean showAll) {
		this.mShowAll = showAll;
	}

	@Override
	public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		if (mShowAll) {
			heightMeasureSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
		}
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
	}

}

Fix bug on HUAWEI phone.

Fix bug on HUAWEI phone.


package com.bungleton.yarrgs.parser;

import java.lang.reflect.Field;

import com.bungleton.yarrgs.Positional;

public class PositionalParser extends ArgumentParser
{
    public final boolean optional;

    public PositionalParser (Field field)
    {
        super(field);
        optional = field.getAnnotation(Positional.class).optional();
    }

    @Override
    public String getBasic ()
    {
        return optional ? "[" + field.getName() + "]" : field.getName();
    }

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

package com.bungleton.yarrgs.parser;

import java.lang.reflect.Field;

import com.bungleton.yarrgs.Positional;

public class PositionalParser extends ArgumentParser
{
    public final boolean optional;

    public PositionalParser (Field field)
    {
        super(field);
        optional = field.getAnnotation(Positional.class).optional();
    }

    @Override
    public String getBasic ()
    {
        return optional ? "[" + field.getName() + "]" : field.getName();
    }

    @Override
    public String getDetail ()
    {
        return field.getName() + " " + getUsage();
    }
}

Fix detail for positional args

Fix detail for positional args


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

package com.applivery.applvsdklib.domain.appconfig.update;

import com.applivery.applvsdklib.AppliverySdk;

/**
 * Created by Sergio Martinez Rodriguez
 * Date 11/1/16.
 */
public class AppConfigChecker {

  private final LastConfigReader lastConfigReader;

  public AppConfigChecker(LastConfigReader lastConfigReader) {
    this.lastConfigReader = lastConfigReader;
  }

  public boolean shouldCheckAppConfigForUpdate() {

    if (AppliverySdk.isSdkFirstTime()) {
      AppliverySdk.setSdkFirstTimeFalse();
      AppliverySdk.setSdkRestartedFalse();
      return false;
    }

    if (AppliverySdk.isSdkRestarted()) {
      AppliverySdk.setSdkRestartedFalse();
      return true;
    }

    if (lastConfigReader.notExistsLastConfig()) {
      return true;
    }

    return AppliverySdk.getCheckForUpdatesBackground();
  }
}

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

package com.applivery.applvsdklib.domain.appconfig.update;

import com.applivery.applvsdklib.AppliverySdk;

/**
 * Created by Sergio Martinez Rodriguez
 * Date 11/1/16.
 */
public class AppConfigChecker {

  private final LastConfigReader lastConfigReader;

  public AppConfigChecker(LastConfigReader lastConfigReader) {
    this.lastConfigReader = lastConfigReader;
  }

  public boolean shouldCheckAppConfigForUpdate() {

    if (AppliverySdk.isSdkFirstTime()) {
      AppliverySdk.setSdkFirstTimeFalse();
      return false;
    }

    if (AppliverySdk.isSdkRestarted()) {
      AppliverySdk.setSdkRestartedFalse();
      return true;
    }

    if (lastConfigReader.notExistsLastConfig()) {
      return true;
    }

    return AppliverySdk.getCheckForUpdatesBackground();
  }
}

Revert "Fix sdk restarted true bug"

Revert "Fix sdk restarted true bug"

This reverts commit 2a4aa086345ce960fbc1d62e03ca4e0974b317b7.


package org.jboss.as.test.shared.util;

import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.function.Supplier;

import org.junit.Assume;

/**
 * Helper methods which help to skip tests for feature which is not yet fully working. Put the call of the method directly into
 * the failing test method, or if you want to skip whole test class, then put the method call into method annotated with
 * {@link org.junit.BeforeClass}.
 *
 * @author Josef Cacek
 */
public class AssumeTestGroupUtil {

    /**
     * Assume for test failures when running with Elytron profile enabled. It skips test in case the {@code '-Delytron'} Maven
     * argument is used (for Elytron profile activation). For legacy-security only tests.
     */
    public static void assumeElytronProfileEnabled() {
        assumeCondition("Tests failing in Elytron profile are disabled", () -> System.getProperty("elytron") == null);
    }

    private static void assumeCondition(final String message, final Supplier<Boolean> assumeTrueCondition) {
        AccessController.doPrivileged(new PrivilegedAction<Void>() {
            @Override
            public Void run() {
                Assume.assumeTrue(message, assumeTrueCondition.get());
                return null;
            }
        });
    }

}

package org.jboss.as.test.shared.util;

import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.function.Supplier;

import org.junit.Assume;

/**
 * Helper methods which help to skip tests for feature which is not yet fully working. Put the call of the method directly into
 * the failing test method, or if you want to skip whole test class, then put the method call into method annotated with
 * {@link org.junit.BeforeClass}.
 *
 * @author Josef Cacek
 */
public class AssumeTestGroupUtil {

    /**
     * Assume for test failures when running with Elytron profile enabled. It skips test in case the {@code '-Delytron'} Maven
     * argument is used (for Elytron profile activation). For legacy-security only tests.
     */
    public static void assumeElytronProfileEnabled() {
        assumeCondition("Tests failing in Elytron profile are disabled", () -> System.getProperty("elytron") == null);
    }

    /**
     * Assume for tests that fail when the security manager is enabled. This should be used sparingly and issues should
     * be filed for failing tests so a proper fix can be done.
     */
    public static void assumeSecurityManagerDisabled() {
        assumeCondition("Tests failing if the security manager is enabled.", () -> System.getSecurityManager() != null);
    }

    private static void assumeCondition(final String message, final Supplier<Boolean> assumeTrueCondition) {
        AccessController.doPrivileged(new PrivilegedAction<Void>() {
            @Override
            public Void run() {
                Assume.assumeTrue(message, assumeTrueCondition.get());
                return null;
            }
        });
    }

}

[WFLY-11556] Add a utility to skip tests if the security manager is enabled.


package com.funnyhatsoftware.spacedock.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v4.app.Fragment;

import com.funnyhatsoftware.spacedock.fragment.DetailsFragment;

public class DetailsActivity extends SinglePaneActivity {
    private static final String EXTRA_TYPE = "browsetype";
    private static final String EXTRA_ITEM = "displayitem";

    public static Intent getIntent(Context context, String itemType, String itemId) {
        if (itemType == null || itemId == null) {
            throw new IllegalArgumentException();
        }

        Intent intent = new Intent(context, DetailsActivity.class);
        intent.putExtra(EXTRA_TYPE, itemType);
        intent.putExtra(EXTRA_ITEM, itemId);
        return intent;
    }

    public Fragment getFragment() {
        String itemType = getIntent().getStringExtra(EXTRA_TYPE);
        String itemId = getIntent().getStringExtra(EXTRA_ITEM);
        return DetailsFragment.newInstance(itemType, itemId);
    }
}

package com.funnyhatsoftware.spacedock.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v4.app.Fragment;

import com.funnyhatsoftware.spacedock.fragment.DetailsFragment;
import com.funnyhatsoftware.spacedock.holder.ExpansionHolder;

public class DetailsActivity extends SinglePaneActivity {
    private static final String EXTRA_TYPE = "browsetype";
    private static final String EXTRA_ITEM = "displayitem";

    public static Intent getIntent(Context context, String itemType, String itemId) {
        if (itemType == null || itemId == null) {
            throw new IllegalArgumentException();
        }

        if (itemType.equals(ExpansionHolder.TYPE_STRING)) {
            return ExpansionDetailsActivity.getIntent(context, itemId);
        }

        Intent intent = new Intent(context, DetailsActivity.class);
        intent.putExtra(EXTRA_TYPE, itemType);
        intent.putExtra(EXTRA_ITEM, itemId);
        return intent;
    }

    public Fragment getFragment() {
        String itemType = getIntent().getStringExtra(EXTRA_TYPE);
        String itemId = getIntent().getStringExtra(EXTRA_ITEM);
        return DetailsFragment.newInstance(itemType, itemId);
    }
}

Fix expansion detail display on phones

Fix expansion detail display on phones


package org.jctools.queues;

import org.jctools.util.JvmInfo;
import org.jctools.util.UnsafeRefArrayAccess;

public final class PaddedCircularArrayOffsetCalculator {
    static final int REF_BUFFER_PAD;
    static final long REF_ARRAY_BASE;
    static {
        // 2 cache lines pad
        REF_BUFFER_PAD = (JvmInfo.CACHE_LINE_SIZE * 2) >> UnsafeRefArrayAccess.REF_ELEMENT_SHIFT;
        // Including the buffer pad in the array base offset
        final int paddingOffset = REF_BUFFER_PAD << UnsafeRefArrayAccess.REF_ELEMENT_SHIFT;
        REF_ARRAY_BASE = UnsafeRefArrayAccess.REF_ARRAY_BASE + paddingOffset;
    }

    private PaddedCircularArrayOffsetCalculator() {
    }

    @SuppressWarnings("unchecked")
    public static <E> E[] allocate(int capacity) {
        return (E[]) new Object[capacity + REF_BUFFER_PAD * 2];
    }

    /**
     * @param index desirable element index
     * @param mask
     * @return the offset in bytes within the array for a given index.
     */
    protected static long calcElementOffset(long index, long mask) {
        return REF_ARRAY_BASE + ((index & mask) << UnsafeRefArrayAccess.REF_ELEMENT_SHIFT);
    }
}

package org.jctools.queues;

import org.jctools.util.InternalAPI;
import org.jctools.util.JvmInfo;
import org.jctools.util.UnsafeRefArrayAccess;

@InternalAPI
public final class PaddedCircularArrayOffsetCalculator
{
    static final int REF_BUFFER_PAD;
    static final long REF_ARRAY_BASE;

    static
    {
        // 2 cache lines pad
        REF_BUFFER_PAD = (JvmInfo.CACHE_LINE_SIZE * 2) >> UnsafeRefArrayAccess.REF_ELEMENT_SHIFT;
        // Including the buffer pad in the array base offset
        final int paddingOffset = REF_BUFFER_PAD << UnsafeRefArrayAccess.REF_ELEMENT_SHIFT;
        REF_ARRAY_BASE = UnsafeRefArrayAccess.REF_ARRAY_BASE + paddingOffset;
    }

    @SuppressWarnings("unchecked")
    public static <E> E[] allocate(int capacity)
    {
        return (E[]) new Object[capacity + REF_BUFFER_PAD * 2];
    }

    /**
     * @param index desirable element index
     * @param mask
     * @return the offset in bytes within the array for a given index.
     */
    protected static long calcElementOffset(long index, long mask)
    {
        return REF_ARRAY_BASE + ((index & mask) << UnsafeRefArrayAccess.REF_ELEMENT_SHIFT);
    }
}

Format and mark as InternalAPI

Format and mark as InternalAPI


package com.apruve;

/**
 * @author Robert Nelson
 * @since 0.1
 */
public enum ApruveEnvironment {
	PROD("https://www.apruve.com"), TEST("https://test.apruve.com"), DEV("http://localhost:3000");

	private static final String API_V3_PATH = "/api/v3";
	private static final String JS_PATH = "/js/apruve.js";

	private String baseUrl;

	private ApruveEnvironment(String baseURL) {
		this.baseUrl = baseURL;
	}

	public String getBaseUrl() {
		return baseUrl;
	}

	/**
	 * @return The root URL for making API calls in the environment
	 */
	public String getApiV3Url() {
		return getBaseUrl() + API_V3_PATH;
	}

	/**
	 * @return The apruve.js URL for the environment
	 */
	public String getJsUrl() {
		return getBaseUrl() + JS_PATH;
	}

	/**
	 * @return HTML tag that will include apruve.js in a page
	 */
	public String getJsTag() {
		return "<script src=\"" + getJsUrl()
				+ "\" type=\"text/javascript\"></script>";
	}
}

package com.apruve;

/**
 * @author Robert Nelson
 * @since 0.1
 */
public enum ApruveEnvironment {
	PROD("https://app.apruve.com"), TEST("https://test.apruve.com"), DEV("http://localhost:3000");

	private static final String API_V3_PATH = "/api/v3";
	private static final String JS_PATH = "/js/apruve.js";

	private String baseUrl;

	private ApruveEnvironment(String baseURL) {
		this.baseUrl = baseURL;
	}

	public String getBaseUrl() {
		return baseUrl;
	}

	/**
	 * @return The root URL for making API calls in the environment
	 */
	public String getApiV3Url() {
		return getBaseUrl() + API_V3_PATH;
	}

	/**
	 * @return The apruve.js URL for the environment
	 */
	public String getJsUrl() {
		return getBaseUrl() + JS_PATH;
	}

	/**
	 * @return HTML tag that will include apruve.js in a page
	 */
	public String getJsTag() {
		return "<script src=\"" + getJsUrl()
				+ "\" type=\"text/javascript\"></script>";
	}
}

Use app.apruve.com as the prod environment URL


package com.example.crystalgame.communication;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

/**
 * The service responsible for the management of communication
 * @author Balazs Pete, Shen Chen
 *
 */
public class CommunicationService extends Service {

	public void onCreate() {
		super.onCreate();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		startService(intent);

		// TODO: remove
		Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();

		return START_NOT_STICKY;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

}

package com.example.crystalgame.communication;

import com.example.crystalgame.library.communication.Communication;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

/**
 * The service responsible for the management of communication
 * @author Balazs Pete, Shen Chen
 *
 */
public class CommunicationService extends Service {

	private Communication communication;

	public void onCreate() {
		super.onCreate();
		ClientCommunicationManager manager = new ClientCommunicationManager("192.168.1.8", 3000);
		communication = new Communication(manager);
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		startService(intent);
		return START_STICKY;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

}

Move the service initialisation creation to onCreate


package com.github.kpavlov.jreactive8583.netty.pipeline;

import com.github.kpavlov.jreactive8583.IsoMessageListener;
import com.github.kpavlov.jreactive8583.iso.MessageFactory;
import com.solab.iso8583.IsoMessage;
import io.netty.channel.ChannelHandlerContext;

/**
 *
 */
public class EchoMessageListener<T extends IsoMessage> implements IsoMessageListener<T> {

    private final MessageFactory<T> isoMessageFactory;

    public EchoMessageListener(final MessageFactory<T> isoMessageFactory) {
        this.isoMessageFactory = isoMessageFactory;
    }

    @Override
    public boolean applies(final IsoMessage isoMessage) {
        return isoMessage != null && isoMessage.getType() == 0x800;
    }

    /**
     * Sends EchoResponse message. Always returns false.
     *
     * @param isoMessage a message to handle
     * @return false - message should not be handled by any other handler.
     */
    @Override
    public boolean onMessage(final ChannelHandlerContext ctx, final T isoMessage) {
        final IsoMessage echoResponse = isoMessageFactory.createResponse(isoMessage);
        ctx.writeAndFlush(echoResponse);
        return false;
    }
}

package com.github.kpavlov.jreactive8583.netty.pipeline;

import com.github.kpavlov.jreactive8583.IsoMessageListener;
import com.github.kpavlov.jreactive8583.iso.MessageClass;
import com.github.kpavlov.jreactive8583.iso.MessageFactory;
import com.solab.iso8583.IsoMessage;
import io.netty.channel.ChannelHandlerContext;

/**
 *
 */
public class EchoMessageListener<T extends IsoMessage> implements IsoMessageListener<T> {

    private final MessageFactory<T> isoMessageFactory;

    public EchoMessageListener(final MessageFactory<T> isoMessageFactory) {
        this.isoMessageFactory = isoMessageFactory;
    }

    @Override
    public boolean applies(final IsoMessage isoMessage) {
        return isoMessage != null && (isoMessage.getType() & MessageClass.NETWORK_MANAGEMENT.value()) != 0;
    }

    /**
     * Sends EchoResponse message. Always returns false.
     *
     * @param isoMessage a message to handle
     * @return false - message should not be handled by any other handler.
     */
    @Override
    public boolean onMessage(final ChannelHandlerContext ctx, final T isoMessage) {
        final IsoMessage echoResponse = isoMessageFactory.createResponse(isoMessage);
        ctx.writeAndFlush(echoResponse);
        return false;
    }
}

Fix echo request identification and support all ISO-8583 versions


package org.mysociety.FixMyStreet;

import android.os.Bundle;
import org.apache.cordova.*;

public class AndroidActivity extends DroidGap {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setIntegerProperty("splashscreen", R.drawable.splash);
        super.loadUrl("file:///android_asset/www/src/index.html", 30000);
    }
}

package org.mysociety.FixMyStreet;

import android.os.Bundle;
import android.view.WindowManager;

import org.apache.cordova.*;

public class AndroidActivity extends DroidGap {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        /* yes, we are using a magic number here but the version constants aren't defined
           until the relevant release so if you want to check against a version that's
           after your minimum target version you have to use the number :(
           in this case 11 is Honeycomb / 3.0 */
        if (android.os.Build.VERSION.SDK_INT <= 11) {
            /* If we leave the default on for android 2 then on the details screen it scrolls
               the details screen in such a way that you can't see where you are typing so
               we switch back to adjustPan. We don't want to use that all the time as adjustPan
               stops you scrolling the screen when the softKeyboard is displayed which is what
               we'd like to be able to do so people can scroll to see if there are other
               fields. */
        	getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        }
        super.setIntegerProperty("splashscreen", R.drawable.splash);
        super.loadUrl("file:///android_asset/www/src/index.html", 30000);
    }
}

Resolve details screen scrolling issues on Android 2

Set Android 2 to use adjustPan when the soft keyboard is visible as this
stops the details screen scrolling in such a way that the cursor is off
the top of the screen. Leave the default for other versions as then
the screen is scrollable.

Fixes #128


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

interface Permission {

    String getPermissionPath();

    PermissionLevel getTrustLevel();

    // todo: or String[] ?
    String getSourcePlugin();

    String getDescription();
}

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

public interface Permission {

    String getPermissionPath();

    PermissionLevel getTrustLevel();

    // todo: or String[] ?
    String getSourcePlugin();

    String getDescription();
}

Make that public so it is actually useable.


package com.fewlaps.quitnowcache;

import java.util.concurrent.TimeUnit;

public class QNCacheBuilder {
    private boolean caseSensitiveKeys = true;
    private Integer autoReleaseInSeconds = null;
    private long defaultKeepaliveInMillis = QNCache.KEEPALIVE_FOREVER;

    public QNCacheBuilder setCaseSensitiveKeys(boolean caseSensitiveKeys) {
        this.caseSensitiveKeys = caseSensitiveKeys;
        return this;
    }

    public QNCacheBuilder setAutoRelease(int units, TimeUnit timeUnit) {
        this.autoReleaseInSeconds = Math.toIntExact(timeUnit.toSeconds(units));
        return this;
    }

    public QNCacheBuilder setAutoReleaseInSeconds(Integer autoReleaseInSeconds) {
        this.autoReleaseInSeconds = autoReleaseInSeconds;
        return this;
    }

    public QNCacheBuilder setDefaultKeepalive(int units, TimeUnit timeUnit) {
        this.defaultKeepaliveInMillis = timeUnit.toMillis(units);
        return this;
    }

    public QNCacheBuilder setDefaultKeepaliveInMillis(long defaultKeepaliveInMillis) {
        this.defaultKeepaliveInMillis = defaultKeepaliveInMillis;
        return this;
    }

    public <T> QNCache<T> createQNCache() {
        return new QNCache<T>(caseSensitiveKeys, autoReleaseInSeconds, defaultKeepaliveInMillis);
    }
}

package com.fewlaps.quitnowcache;

import java.util.concurrent.TimeUnit;

public class QNCacheBuilder {
    private boolean caseSensitiveKeys = true;
    private Integer autoReleaseInSeconds = null;
    private long defaultKeepaliveInMillis = QNCache.KEEPALIVE_FOREVER;

    public QNCacheBuilder setCaseSensitiveKeys(boolean caseSensitiveKeys) {
        this.caseSensitiveKeys = caseSensitiveKeys;
        return this;
    }

    public QNCacheBuilder setAutoRelease(int units, TimeUnit timeUnit) {
        this.autoReleaseInSeconds = Long.valueOf(timeUnit.toSeconds(units)).intValue();
        return this;
    }

    public QNCacheBuilder setAutoReleaseInSeconds(Integer autoReleaseInSeconds) {
        this.autoReleaseInSeconds = autoReleaseInSeconds;
        return this;
    }

    public QNCacheBuilder setDefaultKeepalive(int units, TimeUnit timeUnit) {
        this.defaultKeepaliveInMillis = timeUnit.toMillis(units);
        return this;
    }

    public QNCacheBuilder setDefaultKeepaliveInMillis(long defaultKeepaliveInMillis) {
        this.defaultKeepaliveInMillis = defaultKeepaliveInMillis;
        return this;
    }

    public <T> QNCache<T> createQNCache() {
        return new QNCache<T>(caseSensitiveKeys, autoReleaseInSeconds, defaultKeepaliveInMillis);
    }
}

Replace Math.toIntExact() with a simple .intValue() 'cause toIntExact() is not abailable at Java 6


package app.android.gambit.test;

import app.android.gambit.local.Card;

public class CardTests extends DatabaseTestCase
{
	private static final String DECK_TITLE = "Title";
	private static final String CARD_BACK_SIDE_TEXT = "Back text";
	private static final String CARD_FRONT_SIDE_TEXT = "Front text";

	private Card card;

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

		card = decks.createDeck(DECK_TITLE).createCard(CARD_FRONT_SIDE_TEXT, CARD_BACK_SIDE_TEXT);
	}

	public void testGetFrontSideText() {
		assertEquals(CARD_FRONT_SIDE_TEXT, card.getFrontSideText());
	}

	public void testGetBackSideText() {
		assertEquals(CARD_BACK_SIDE_TEXT, card.getBackSideText());
	}

	public void testSetFrontSideText() {
		String newFrontSideText = "New front side text";

		card.setFrontSideText(newFrontSideText);

		assertEquals(newFrontSideText, card.getFrontSideText());
	}

	public void testSetBackSideText() {
		String newBackSideText = "New back side text";

		card.setBackSideText(newBackSideText);

		assertEquals(newBackSideText, card.getBackSideText());
	}
}

package app.android.gambit.test;

import app.android.gambit.local.Card;

public class CardTests extends DatabaseTestCase
{
	private static final String DECK_TITLE = "deck";
	private static final String CARD_BACK_SIDE_TEXT = "back side text";
	private static final String CARD_FRONT_SIDE_TEXT = "front side text";

	private Card card;

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

		card = decks.createDeck(DECK_TITLE).createCard(CARD_FRONT_SIDE_TEXT, CARD_BACK_SIDE_TEXT);
	}

	public void testGetId() {
		long cardId = card.getId();

		assertTrue(cardId >= 0);
	}

	public void testGetFrontSideText() {
		assertEquals(CARD_FRONT_SIDE_TEXT, card.getFrontSideText());
	}

	public void testGetBackSideText() {
		assertEquals(CARD_BACK_SIDE_TEXT, card.getBackSideText());
	}

	public void testSetFrontSideText() {
		String newFrontSideText = String.format("new %s", CARD_FRONT_SIDE_TEXT);

		card.setFrontSideText(newFrontSideText);

		assertEquals(newFrontSideText, card.getFrontSideText());
	}

	public void testSetBackSideText() {
		String newBackSideText = String.format("new %s", CARD_BACK_SIDE_TEXT);

		card.setBackSideText(newBackSideText);

		assertEquals(newBackSideText, card.getBackSideText());
	}
}

Add id testing for card and change card text generation a bit.


package guitests;

import javafx.scene.input.KeyCode;
import org.junit.Test;
import ui.listpanel.ListPanelCell;

import static org.junit.Assert.assertEquals;
import static org.loadui.testfx.Assertions.assertNodeExists;
import static org.loadui.testfx.controls.Commons.hasText;

public class LabelPickerTests extends UITest {

    public static final int EVENT_DELAY = 500;

    @Test
    public void showLabelPickerTest() {
        click("#dummy/dummy_col0_9");
        push(KeyCode.L);
        sleep(EVENT_DELAY);
        assertNodeExists(hasText("Issue #9: Issue 9"));
        push(KeyCode.ENTER);
    }

    @Test
    public void addAndRemoveLabelTest() {
        ListPanelCell listPanelCell = find("#dummy/dummy_col0_9");
        click(listPanelCell);
        assertEquals(1, listPanelCell.getIssueLabels().size());
        push(KeyCode.L);
        sleep(EVENT_DELAY);
        type("3 ");
        push(KeyCode.ENTER);
        listPanelCell = find("#dummy/dummy_col0_9");
        sleep(EVENT_DELAY);
        assertEquals(2, listPanelCell.getIssueLabels().size());
        push(KeyCode.L);
        sleep(EVENT_DELAY);
        type("3 ");
        push(KeyCode.ENTER);
        listPanelCell = find("#dummy/dummy_col0_9");
        sleep(EVENT_DELAY);
        assertEquals(1, listPanelCell.getIssueLabels().size());
    }

}

package guitests;

import javafx.scene.input.KeyCode;
import org.junit.Test;
import ui.listpanel.ListPanelCell;

import static org.junit.Assert.assertEquals;
import static org.loadui.testfx.Assertions.assertNodeExists;
import static org.loadui.testfx.controls.Commons.hasText;

public class LabelPickerTests extends UITest {

    public static final int EVENT_DELAY = 500;

    @Test
    public void showLabelPickerTest() {
        click("#dummy/dummy_col0_9");
        push(KeyCode.L);
        sleep(EVENT_DELAY);
        assertNodeExists(hasText("Issue #9: Issue 9"));
        push(KeyCode.ENTER);
    }

    @Test
    public void addAndRemoveLabelTest() {
        ListPanelCell listPanelCell = find("#dummy/dummy_col0_9");
        click(listPanelCell);
        assertEquals(1, listPanelCell.getIssueLabels().size());
        push(KeyCode.L);
        sleep(EVENT_DELAY);
        type("3 ");
        push(KeyCode.ENTER);
        sleep(EVENT_DELAY);
        assertEquals(2, listPanelCell.getIssueLabels().size());
        push(KeyCode.L);
        sleep(EVENT_DELAY);
        type("3 ");
        push(KeyCode.ENTER);
        sleep(EVENT_DELAY);
        assertEquals(1, listPanelCell.getIssueLabels().size());
    }

}

Revert "Re-search for listPanelCell in addAndRemoveLabelTest"

This reverts commit f1e2b41afb4623ff35771d028fbd79810e80dece.