package ru.nsu.ccfit.bogush.message.types;

import ru.nsu.ccfit.bogush.User;
import ru.nsu.ccfit.bogush.message.Message;
import ru.nsu.ccfit.bogush.message.MessageHandler;

public class TextMessage implements Message {
	private User author;
	private String text;

	public TextMessage(User author, String text) {
		this.author = author;
		this.text = text;
	}

	public User getAuthor() {
		return author;
	}

	public String getText() {
		return text;
	}

	public String getVerboseText() {
		return text.replaceAll("\\p{C}", "[]");
	}

	@Override
	public void handleBy(MessageHandler handler) {
		handler.handle(this);
	}

	@Override
	public String toString() {
		return new StringBuilder()
				.append("[")
				.append(getAuthor())
				.append(": \"")
				.append(getVerboseText())
				.append("\"]")
				.toString();
	}
}

package ru.nsu.ccfit.bogush.message.types;

import ru.nsu.ccfit.bogush.User;
import ru.nsu.ccfit.bogush.message.Message;
import ru.nsu.ccfit.bogush.message.MessageHandler;

public class TextMessage implements Message {
	private User author;
	private String text;

	public TextMessage(User author, String text) {
		this.author = author;
		this.text = text;
	}

	public User getAuthor() {
		return author;
	}

	public String getText() {
		return text;
	}

	public String getVerboseText() {
		return text.replaceAll("\\p{C}", "[]");
	}

	@Override
	public void handleBy(MessageHandler handler) {
		handler.handle(this);
	}

	@Override
	public String toString() {
		return "[" +
				getAuthor() +
				": \"" +
				getVerboseText() +
				"\"]";
	}
}

Replace string builder with string concatenation


package mozilla.org.webmaker.activity;

import android.app.ActionBar;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Menu;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import mozilla.org.webmaker.R;
import mozilla.org.webmaker.WebmakerActivity;
import mozilla.org.webmaker.view.WebmakerWebView;

public class Tinker extends WebmakerActivity {
    public Tinker() {
        super("tinker", R.id.tinker_layout, R.layout.tinker_layout, R.menu.menu_tinker);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Custom styles
        ActionBar actionBar = getActionBar();
        ColorDrawable colorOne = new ColorDrawable(Color.parseColor("#ff303250"));
        ColorDrawable colorTwo = new ColorDrawable(Color.parseColor("#ff303250"));
        actionBar.setStackedBackgroundDrawable(colorOne);
        actionBar.setBackgroundDrawable(colorTwo);

        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        window.setStatusBarColor(0xff282733);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
}

package mozilla.org.webmaker.activity;

import android.app.ActionBar;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Menu;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import mozilla.org.webmaker.R;
import mozilla.org.webmaker.WebmakerActivity;
import mozilla.org.webmaker.view.WebmakerWebView;

public class Tinker extends WebmakerActivity {
    public Tinker() {
        super("tinker", R.id.tinker_layout, R.layout.tinker_layout, R.menu.menu_tinker);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Custom styles
        Resources res = getResources();
        int shadowPlum = res.getColor(R.color.shadow_plum);
        int plum = res.getColor(R.color.plum);

        ActionBar actionBar = getActionBar();
        actionBar.setStackedBackgroundDrawable(plum);
        actionBar.setBackgroundDrawable(plum);

        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        window.setStatusBarColor(shadowPlum);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
}

Use plum and shadow_plum from colors.xml


package com.raskasa.metrics.okhttp.sample;

import com.codahale.metrics.ConsoleReporter;
import com.codahale.metrics.MetricRegistry;
import com.raskasa.metrics.okhttp.InstrumentedOkHttpClients;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/** Fetches user information from the GitHub public API */
public final class App {
  public static void main(String[] args) throws Exception {
    MetricRegistry metrics = new MetricRegistry();

    ConsoleReporter reporter = ConsoleReporter.forRegistry(metrics)
        .convertRatesTo(TimeUnit.SECONDS)
        .convertDurationsTo(TimeUnit.MILLISECONDS)
        .build();
    reporter.start(15, TimeUnit.SECONDS);

    OkHttpClient client = InstrumentedOkHttpClients.create(metrics);

    // noinspection InfiniteLoopStatement
    for (;;) {

      Request request = new Request.Builder()
          .url("https://api.github.com/repos/raskasa/metrics-okhttp")
          .build();

      client.newCall(request).enqueue(new Callback() {
        @Override public void onFailure(Call call, IOException e) {
          throw new RuntimeException("call failed");
        }

        @Override public void onResponse(Call call, Response response) throws IOException {
          ResponseBody body = response.body();
          if (body != null) {
            System.out.println(body.string());
          } else {
            throw new RuntimeException("Body not expected to be closed");
          }
        }
      });

      Thread.sleep(15_000);  // 15 seconds
    }
  }
}

package com.raskasa.metrics.okhttp.sample;

import com.codahale.metrics.ConsoleReporter;
import com.codahale.metrics.MetricRegistry;
import com.raskasa.metrics.okhttp.InstrumentedOkHttpClients;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/** Fetches user information from the GitHub public API */
public final class App {
  public static void main(String[] args) throws Exception {
    MetricRegistry metrics = new MetricRegistry();

    ConsoleReporter reporter = ConsoleReporter.forRegistry(metrics)
        .convertRatesTo(TimeUnit.SECONDS)
        .convertDurationsTo(TimeUnit.MILLISECONDS)
        .build();
    reporter.start(15, TimeUnit.SECONDS);

    OkHttpClient client = InstrumentedOkHttpClients.create(metrics);

    // noinspection InfiniteLoopStatement
    for (;;) {

      Request request = new Request.Builder()
          .url("https://api.github.com/repos/raskasa/metrics-okhttp")
          .build();

      Response response = client.newCall(request).execute();

      ResponseBody body = response.body();
      if (body != null) {
        System.out.println(body.string());
      } else {
        throw new RuntimeException("Body not expected to be closed");
      }

      Thread.sleep(15_000);  // 15 seconds
    }
  }
}

Revert "Update sample to use execute async calls."

This reverts commit 1affe46ccaa3f846e86db850024a49fa390d85fa.


package strings;

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;
import static strings.ReplaceAndRemove.replaceAndRemove;

class ReplaceAndRemoveTest {

    private String expected;
    private String input;
    private int k;

    @Test
    void replaceAndRemove1() {
        expected = "dd";
        input = "a ";
        k=1;

        test(expected, input, k);
    }

    @Test
    void replaceAndRemove2() {
        expected = " ";
        input = "b";
        k=1;

        test(expected, input, k);
    }

    @Test
    void replaceAndRemove3() {
        expected = "dd";
        input = "ab";
        k=2;

        test(expected, input, k);
    }

    @Test
    void replaceAndRemove4() {
        expected = "ddddc";
        input = "abac ";
        k=4;

        test(expected, input, k);
    }

    @Test
    void replaceAndRemove5() {
        expected = "ddcdcdd";
        input = "acdbbca";
        k=7;

        test(expected, input, k);
    }

    private void test(String expected, String input, int k) {
        assertEquals(expected, replaceAndRemove(input.toCharArray(), k));
    }
}

package strings;

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;
import static strings.ReplaceAndRemove.replaceAndRemove;

class ReplaceAndRemoveTest {

    private String expected;
    private String input;
    private int k;

    @Test
    void replaceAndRemove1() {
        expected = "dd";
        input = "a ";
        k=1;

        test(expected, input, k);
    }

    @Test
    void replaceAndRemove2() {
        expected = "dd";
        input = "ab";
        k=2;

        test(expected, input, k);
    }

    @Test
    void replaceAndRemove3() {
        expected = "ddddc";
        input = "abac ";
        k=4;

        test(expected, input, k);
    }

    @Test
    void replaceAndRemove4() {
        expected = "ddcdcdd";
        input = "acdbbca";
        k=7;

        test(expected, input, k);
    }

    private void test(String expected, String input, int k) {
        assertEquals(expected, replaceAndRemove(input.toCharArray(), k));
    }
}

Test case with mismatch and array size removed


package com.veyndan.paper.reddit.ui.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;

import com.google.android.flexbox.FlexboxLayout;
import com.veyndan.paper.reddit.databinding.PostFlairBinding;
import com.veyndan.paper.reddit.post.Flair;

import java.util.Collection;

public class PostFlairsLayout extends FlexboxLayout {

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

    public void setFlairs(final Collection<Flair> flairs, final String subreddit) {
        if (flairs.isEmpty()) {
            setVisibility(GONE);
            return;
        }

        for (final Flair flair : flairs) {
            final PostFlairBinding binding = PostFlairBinding.inflate(LayoutInflater.from(getContext()), this, false);
            binding.postFlair.setFlair(flair, subreddit);
            addView(binding.getRoot());
        }

        setVisibility(VISIBLE);
    }
}

package com.veyndan.paper.reddit.ui.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;

import com.google.android.flexbox.FlexboxLayout;
import com.veyndan.paper.reddit.databinding.PostFlairBinding;
import com.veyndan.paper.reddit.post.Flair;

import java.util.Collection;

public class PostFlairsLayout extends FlexboxLayout {

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

    public void setFlairs(final Collection<Flair> flairs, final String subreddit) {
        removeAllViews();

        if (flairs.isEmpty()) {
            setVisibility(GONE);
            return;
        }

        for (final Flair flair : flairs) {
            final PostFlairBinding binding = PostFlairBinding.inflate(LayoutInflater.from(getContext()), this, false);
            binding.postFlair.setFlair(flair, subreddit);
            addView(binding.getRoot());
        }

        setVisibility(VISIBLE);
    }
}

Fix bug where multiple flairs from unrelated posts are shown


// Copyright 2016 Google Inc. All Rights Reserved.
package com.google.copybara.util;

import com.google.common.base.Preconditions;
import com.google.devtools.build.lib.shell.AbnormalTerminationException;
import com.google.devtools.build.lib.shell.Command;
import com.google.devtools.build.lib.shell.CommandResult;

import java.nio.charset.StandardCharsets;

/**
 * An exception that represents a program that did not exit with 0 exit code.
 *
 * <p>The reason for this class is that {@link Command#execute} doesn't populate {@link
 * CommandResult#stderr} when throwing a {@link com.google.devtools.build.lib.shell.BadExitStatusException}
 * exception. This class allows us to collect the error and store in this alternative exception.
 */
public class BadExitStatusWithOutputException extends AbnormalTerminationException {

  private final CommandOutputWithStatus output;

  BadExitStatusWithOutputException(Command command, CommandResult result, String message,
      byte[] stdout, byte[] stderr) {
    super(command, result, message);
    this.output = new CommandOutputWithStatus(result.getTerminationStatus(), stdout, stderr);
  }

  public CommandOutputWithStatus getOutput() {
    return output;
  }
}

// Copyright 2016 Google Inc. All Rights Reserved.
package com.google.copybara.util;

import com.google.devtools.build.lib.shell.AbnormalTerminationException;
import com.google.devtools.build.lib.shell.Command;
import com.google.devtools.build.lib.shell.CommandResult;

/**
 * An exception that represents a program that did not exit with 0 exit code.
 *
 * <p>The reason for this class is that {@link Command#execute} doesn't populate {@link
 * CommandResult#stderr} when throwing a {@link com.google.devtools.build.lib.shell.BadExitStatusException}
 * exception. This class allows us to collect the error and store in this alternative exception.
 */
public class BadExitStatusWithOutputException extends AbnormalTerminationException {

  private final CommandOutputWithStatus output;

  BadExitStatusWithOutputException(Command command, CommandResult result, String message,
      byte[] stdout, byte[] stderr) {
    super(command, result, message);
    this.output = new CommandOutputWithStatus(result.getTerminationStatus(), stdout, stderr);
  }

  public CommandOutputWithStatus getOutput() {
    return output;
  }
}

Fix unused import lint error

Fix unused import lint error

Change-Id: Ib72b049b4991e48b2ac9ffbc3c5585e676edf781


package net.ontopia.presto.jaxb;

import java.util.Collection;

import javax.xml.bind.annotation.XmlRootElement;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

@XmlRootElement
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class TopicPartial {
    private String format = "topic-partial";
    private Collection<TopicView> views;

    public Collection<TopicView> getViews() {
        return views;
    }

    public void setViews(Collection<TopicView> views) {
        this.views = views;
    }

    public String getFormat() {
        return format;
    }

    public void setFormat(String format) {
        this.format = format;
    }

}

package net.ontopia.presto.jaxb;

import java.util.Collection;
import java.util.Map;

import javax.xml.bind.annotation.XmlRootElement;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

@XmlRootElement
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class TopicPartial {
    private String format = "topic-partial";
    private Map<String, Object> params;
    private Collection<TopicView> views;

    public Collection<TopicView> getViews() {
        return views;
    }

    public void setViews(Collection<TopicView> views) {
        this.views = views;
    }

    public String getFormat() {
        return format;
    }

    public void setFormat(String format) {
        this.format = format;
    }

    public Map<String, Object> getParams() {
        return params;
    }

    public void setParams(Map<String, Object> params) {
        this.params = params;
    }

}

Add params to topic partial

Add params to topic partial


package com.ForgeEssentials.afterlife;

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

import net.minecraft.inventory.InventoryBasic;
import net.minecraft.item.ItemStack;

public class InventroyGrave extends InventoryBasic
{
	private Grave	grave;

	public InventroyGrave(Grave grave)
	{
		super(grave.owner + "'s grave.", grave.getSize());
		this.grave = grave;
	}

	@Override
	public void openChest()
	{
		for (int i = 0; i < getSizeInventory(); i++)
		{
			setInventorySlotContents(i, (ItemStack) null);
		}

		for (int i = 0; i < grave.inv.length; i++)
		{
			setInventorySlotContents(i, grave.inv[i].copy());
		}

		super.openChest();
	}

	@Override
	public void closeChest()
	{
		List<ItemStack> list = new ArrayList<ItemStack>();
		for (ItemStack is : inventoryContents)
		{
			if (is != null)
			{
				list.add(is);
			}
		}
		grave.inv = list.toArray(new ItemStack[list.size()]);

		grave.checkGrave();
		super.closeChest();
	}
}

package com.ForgeEssentials.afterlife;

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

import net.minecraft.inventory.InventoryBasic;
import net.minecraft.item.ItemStack;

public class InventroyGrave extends InventoryBasic
{
	private Grave	grave;

	public InventroyGrave(Grave grave)
	{
		super(grave.owner + "'s grave.", grave.getSize());
		this.grave = grave;
	}

	@Override
	public void openChest()
	{
		for (int i = 0; i < getSizeInventory(); i++)
		{
			setInventorySlotContents(i, (ItemStack) null);
		}

		for (int i = 0; i < grave.inv.length; i++)
		{
			setInventorySlotContents(i, grave.inv[i].copy());
		}

		super.openChest();
	}

	@Override
	public void closeChest()
	{
		List<ItemStack> list = new ArrayList<ItemStack>();
		for (int i = 0; i < getSizeInventory(); i++)
		{
			ItemStack is = getStackInSlot(i);
			if (is != null)
			{
				list.add(is);
			}
		}
		grave.inv = list.toArray(new ItemStack[list.size()]);

		grave.checkGrave();
		super.closeChest();
	}
}

Fix private value in Grave

Fix private value in Grave


package com.netcracker.students_project.entity;

import org.hibernate.annotations.Generated;
import org.hibernate.annotations.GenerationTime;

import javax.persistence.*;

@Entity
@Table(name = "teg", schema = "netcracker", catalog = "nc_student_project")
public class TegEntity {
    private int id;
    private String text;

    @Id
    @Column(name = "id", columnDefinition = "serial")
    @Generated(GenerationTime.INSERT)
    public int getId() {
        return id;
    }

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

    @Basic
    @Column(name = "text")
    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

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

        TegEntity tegEntity = (TegEntity) o;

        if (id != tegEntity.id) return false;
        if (text != null ? !text.equals(tegEntity.text) : tegEntity.text != null) return false;

        return true;
    }

    @Override
    public String toString() {
        return "TegEntity{" +
                "id=" + id +
                ", text='" + text + '\'' +
                '}';
    }

    @Override
    public int hashCode() {
        int result = id;
        result = 31 * result + (text != null ? text.hashCode() : 0);
        return result;
    }
}

package com.netcracker.students_project.entity;

import javax.persistence.*;

@Entity
@Table(name = "teg", schema = "netcracker", catalog = "nc_student_project")
public class TegEntity {
    private int id;
    private String text;

    @Id
    @Column(name = "id", columnDefinition = "serial")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public int getId() {
        return id;
    }

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

    @Basic
    @Column(name = "text")
    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

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

        TegEntity tegEntity = (TegEntity) o;

        if (id != tegEntity.id) return false;
        if (text != null ? !text.equals(tegEntity.text) : tegEntity.text != null) return false;

        return true;
    }

    @Override
    public String toString() {
        return "TegEntity{" +
                "id=" + id +
                ", text='" + text + '\'' +
                '}';
    }

    @Override
    public int hashCode() {
        int result = id;
        result = 31 * result + (text != null ? text.hashCode() : 0);
        return result;
    }
}

Revert "it's work!!! for tegEnity"

Revert "it's work!!! for tegEnity"

This reverts commit b66c557ffab584ed1f8083857fd67732fce21bc1.


package imagej.gui;

import imagej.data.Types;
import imagej.dataset.Dataset;
import imagej.dataset.PlanarDatasetFactory;
import imagej.plugin.ij2.IPlugin;
import imagej.plugin.ij2.Parameter;
import imagej.plugin.ij2.Plugin;

@Plugin(
  menuPath="Process>Gradient"
)
public class GradientImage implements IPlugin {

	@Parameter private int width = 512;
	@Parameter	private int height = 512;

	@Parameter(output=true)
	private Dataset dataset;

	@Override
	public void run() {

		byte[] data = new byte[ this.width * this.height ];

		for(int x = 0; x < width; x++)
			for(int y = 0; y < height; y++)
			{
				int index = y*width+x;
				data[index] = (byte) (x+y);
			}

		PlanarDatasetFactory planarDatasetFactory = new PlanarDatasetFactory();
		dataset = planarDatasetFactory.createDataset( Types.findType( "8=bit unsigned"), new int[] { this.width, this.height } );
		dataset.setData( data );
  }
}

package imagej.gui;

import imagej.data.UnsignedByteType;
import imagej.dataset.Dataset;
import imagej.dataset.DatasetFactory;
import imagej.dataset.PlanarDatasetFactory;
import imagej.plugin.ij2.IPlugin;
import imagej.plugin.ij2.Parameter;
import imagej.plugin.ij2.Plugin;

@Plugin(
  menuPath="Process>Gradient"
)
public class GradientImage implements IPlugin {

	@Parameter
	private int width = 512;

	@Parameter
	private int height = 512;

	@Parameter(output=true)
	private Dataset dataset;

	@Override
	public void run() {
		byte[] data = new byte[width * height];
		for (int x = 0; x < width; x++) {
			for (int y = 0; y < height; y++) {
				int index = y * width + x;
				data[index] = (byte) (x + y);
			}
		}

		final DatasetFactory datasetFactory = new PlanarDatasetFactory();
		final int[] dims = {width, height};
		dataset = datasetFactory.createDataset(new UnsignedByteType(), dims);
		dataset.setData(data);
  }

}

Clean up gradient image plugin code.

Clean up gradient image plugin code.

This used to be revision r1904.


package com.veyndan.redditclient;

import android.graphics.Rect;
import android.support.annotation.Px;
import android.support.v7.widget.RecyclerView;
import android.view.View;

public class MarginItemDecoration extends RecyclerView.ItemDecoration {

    private final int margin;

    public MarginItemDecoration(@Px final int margin) {
        this.margin = margin;
    }

    @Override
    public void getItemOffsets(final Rect outRect, final View view, final RecyclerView parent,
                               final RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);

        outRect.bottom += margin;
        outRect.left += margin;
        outRect.right += margin;

        if (parent.getChildAdapterPosition(view) == 0) {
            outRect.top += margin;
        }
    }
}

package com.veyndan.redditclient;

import android.graphics.Rect;
import android.support.annotation.Px;
import android.support.v7.widget.RecyclerView;
import android.view.View;

public class MarginItemDecoration extends RecyclerView.ItemDecoration {

    private final int margin;

    public MarginItemDecoration(@Px final int margin) {
        this.margin = margin;
    }

    @Override
    public void getItemOffsets(final Rect outRect, final View view, final RecyclerView parent,
                               final RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);

        outRect.bottom = margin;
        outRect.left = margin;
        outRect.right = margin;

        if (parent.getChildAdapterPosition(view) == 0) {
            outRect.top = margin;
        }
    }
}

Replace '+=' with '=' for outRect offsets to eliminate any ideas that outRect bounds isn't initially 0


package com.x1unix.avi.dashboard;

import com.x1unix.avi.R;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.x1unix.avi.model.KPMovie;
import com.x1unix.avi.storage.MoviesRepository;
import java.util.ArrayList;

public class FavoritesTabFragment extends DashboardTabFragment {

    @Override
    protected ArrayList<KPMovie> getContentItems() {
        return moviesRepository.getFavoritesMovies();
    }

    @Override
    protected int getTabView() {
        return R.layout.tab_favorites;
    }

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    public static DashboardTabFragment getInstance(MoviesRepository m) {
        return (new FavoritesTabFragment()).setMoviesRepository(m);
    }
}

package com.x1unix.avi.dashboard;

import com.x1unix.avi.R;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.x1unix.avi.model.KPMovie;
import com.x1unix.avi.storage.MoviesRepository;
import java.util.ArrayList;

public class FavoritesTabFragment extends DashboardTabFragment {

    @Override
    protected ArrayList<KPMovie> getContentItems() {
        return moviesRepository.getFavoritesMovies();
    }

    @Override
    protected int getTabView() {
        return R.layout.tab_favorites;
    }

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

    @Override
    protected String getPlaylistGenitivusName() {
        return getResources().getString(R.string.playlist_genitivus_favorites);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    public static DashboardTabFragment getInstance(MoviesRepository m) {
        return (new FavoritesTabFragment()).setMoviesRepository(m);
    }
}

Set name for favs tab

Set name for favs tab


package com.thaiopensource.relaxng;

import org.xml.sax.Locator;
import com.thaiopensource.datatype.Datatype;

class ValuePattern extends SimplePattern {
  String str;
  Datatype dt;

  ValuePattern(Datatype dt, String str, Locator locator) {
    super(combineHashCode(VALUE_HASH_CODE, str.hashCode()), locator);
    this.str = str;
  }

  boolean matches(Atom a) {
    return a.matchesDatatypeValue(dt, str);
  }

  boolean samePattern(Pattern other) {
    if (getClass() != other.getClass())
      return false;
    return (dt.equals(((ValuePattern)other).dt)
	    && str.equals(((ValuePattern)other).str));
  }

  void accept(PatternVisitor visitor) {
    visitor.visitValue(dt, str);
  }
}

package com.thaiopensource.relaxng;

import org.xml.sax.Locator;
import com.thaiopensource.datatype.Datatype;

class ValuePattern extends SimplePattern {
  String str;
  Datatype dt;

  ValuePattern(Datatype dt, String str, Locator locator) {
    super(combineHashCode(VALUE_HASH_CODE, str.hashCode()), locator);
    this.dt = dt;
    this.str = str;
  }

  boolean matches(Atom a) {
    return a.matchesDatatypeValue(dt, str);
  }

  boolean samePattern(Pattern other) {
    if (getClass() != other.getClass())
      return false;
    if (!(other instanceof ValuePattern))
      return false;
    return (dt.equals(((ValuePattern)other).dt)
	    && str.equals(((ValuePattern)other).str));
  }

  void accept(PatternVisitor visitor) {
    visitor.visitValue(dt, str);
  }
}

Fix a couple of bugs.

Fix a couple of bugs.

git-svn-id: ca8e9bb6f3f9b50a093b443c23951d3c25ca0913@45 369101cc-9a96-11dd-8e58-870c635edf7a


package org.pdxfinder.graph.dao;

import org.junit.Test;

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

import static org.junit.Assert.*;

public class SampleTest {

    @Test public void equals_givenIdenticalObjects_symmetricallyEqual() {
        Sample x = new Sample("id");
        Sample y = new Sample("id");
        assertTrue(x.equals(y) && y.equals(x));
    }

    @Test public void equals_givenIdenticalObjects_hashCodeIsEqual() {
        Sample x = new Sample("id");
        Sample y = new Sample("id");
        assertEquals(x.hashCode(), y.hashCode());
    }

    @Test public void hashCode_givenObjectPutInMap_identicalKeyRetrievesTheValue() {
        Sample x = new Sample("id");
        Sample y = new Sample("id");
        Map<Sample, String> map = new HashMap<>();
        map.put(x, "this");
        assertEquals("this", map.get(y));
    }

}

package org.pdxfinder.graph.dao;

import org.junit.Test;

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

import static org.junit.Assert.*;

public class SampleTest {
/*
    @Test public void equals_givenIdenticalObjects_symmetricallyEqual() {
        Sample x = new Sample("id");
        Sample y = new Sample("id");
        assertTrue(x.equals(y) && y.equals(x));
    }

    @Test public void equals_givenIdenticalObjects_hashCodeIsEqual() {
        Sample x = new Sample("id");
        Sample y = new Sample("id");
        assertEquals(x.hashCode(), y.hashCode());
    }

    @Test public void hashCode_givenObjectPutInMap_identicalKeyRetrievesTheValue() {
        Sample x = new Sample("id");
        Sample y = new Sample("id");
        Map<Sample, String> map = new HashMap<>();
        map.put(x, "this");
        assertEquals("this", map.get(y));
    }
*/
}

Disable testing equals on samples

Disable testing equals on samples


package javax.webbeans;

import java.lang.annotation.Annotation;
import java.util.Set;

/**
 * Argh, this is not the name in the spec but then we have two classes called
 * Component
 */
public abstract class ComponentInstance<T>
{

   public abstract Set<Class> getTypes();
   public abstract Set<Annotation> getBindingTypes();
   public abstract Annotation getScopeType();
   public abstract Annotation getComponentType();
   public abstract String getName();

   public abstract T create(Container container);
   public abstract void destroy(Container container, T instance);

}

package javax.webbeans;

import java.lang.annotation.Annotation;
import java.util.Set;

/**
 * Argh, this is not the name in the spec but then we have two classes called
 * Component
 */
public abstract class ComponentInstance<T>
{

   public abstract Set<Class> getTypes();
   public abstract Set<Annotation> getBindingTypes();
   public abstract Annotation getScopeType();
   public abstract Annotation getDeploymentType();
   public abstract String getName();

   public abstract T create(Container container);
   public abstract void destroy(Container container, T instance);

}

Change name to deployment type (might be wrong)

git-svn-id: 811cd8a17a8c3c0c263af499002feedd54a892d0@25 1c488680-804c-0410-94cd-c6b725194a0e


package ryhma57.references;

import java.util.EnumSet;
import ryhma57.backend.BibtexReferenceField;
import static ryhma57.backend.BibtexReferenceField.*;

public class Book extends Reference {
    private static EnumSet<BibtexReferenceField> existingFields;
    private static EnumSet<BibtexReferenceField> requiredFields, optionalFields;

    static {
        Book.requiredFields = Reference.createFieldSet(AUTHOR,
                TITLE, YEAR, PUBLISHER);
        Book.optionalFields = Reference.createFieldSet(VOLUME,
                NUMBER, SERIES, ADDRESS, EDITION, MONTH, NOTE);
        Book.existingFields = Reference.createExistingSet(
                Book.requiredFields, Book.optionalFields);
    }

    public Book(String id, String author, String title, String year, String publisher) {
        super(existingFields, requiredFields, "book");
        setID(id);
        setField(AUTHOR, author);
        setField(TITLE, title);
        setField(YEAR, year);
        setField(PUBLISHER, publisher);
    }
    public Book() {
        super(existingFields, requiredFields, "book");
    }
}

package ryhma57.references;

import java.util.EnumSet;
import ryhma57.backend.BibtexReferenceField;
import static ryhma57.backend.BibtexReferenceField.*;

public class Book extends Reference {
    private static EnumSet<BibtexReferenceField> existingFields;
    private static EnumSet<BibtexReferenceField> requiredFields, optionalFields;

    static {
        Book.requiredFields = Reference.createFieldSet(AUTHOR,
                EDITOR, TITLE, YEAR, PUBLISHER);
        Book.optionalFields = Reference.createFieldSet(VOLUME,
                NUMBER, SERIES, ADDRESS, EDITION, MONTH, NOTE);
        Book.existingFields = Reference.createExistingSet(
                Book.requiredFields, Book.optionalFields);
    }

    public Book(String id, String author, String title, String year, String publisher) {
        super(existingFields, requiredFields, "book");
        setID(id);
        setField(AUTHOR, author);
        setField(TITLE, title);
        setField(YEAR, year);
        setField(PUBLISHER, publisher);
    }
    public Book() {
        super(existingFields, requiredFields, "book");
    }
}

Add the editor field to the required fields at the book ref.


package pl.rspective.voucherify.android.client;

public interface Constants {

    // HTTP constants
    String SCHEME_HTTP = "http";
    String SCHEME_HTTPS = "https";
    String HTTP_HEADER_CLIENT_ID = "X-Client-Application-Id";
    String HTTP_HEADER_CLIENT_TOKEN = "X-Client-Token";
    String HTTP_HEADER_ORIGIN = "origin";

    // Configuration
    String ENDPOINT_VOUCHERIFY = "voucherify-bouncer.herokuapp.com/v1";

}

package pl.rspective.voucherify.android.client;

public interface Constants {

    // HTTP constants
    String SCHEME_HTTP = "http";
    String SCHEME_HTTPS = "https";
    String HTTP_HEADER_CLIENT_ID = "X-Client-Application-Id";
    String HTTP_HEADER_CLIENT_TOKEN = "X-Client-Token";
    String HTTP_HEADER_ORIGIN = "origin";

    // Configuration
    String ENDPOINT_VOUCHERIFY = "voucherify-bouncer.herokuapp.com";

}

Update default voucherify endpoint URL

Update default voucherify endpoint URL


package org.andstatus.todoagenda.task;

import android.app.Activity;
import android.content.Context;

import org.andstatus.todoagenda.EventProvider;
import org.andstatus.todoagenda.prefs.ApplicationPreferences;
import org.andstatus.todoagenda.task.dmfs.DmfsOpenTasksProvider;
import org.andstatus.todoagenda.task.samsung.SamsungTasksProvider;

import java.util.List;

public class TaskProvider extends EventProvider {

    private static final String PROVIDER_DMFS = "DMFS_OPEN_TASKS";
    private static final String PROVIDER_SAMSUNG = "SAMSUNG";

    public TaskProvider(Context context, int widgetId) {
        super(context, widgetId);
    }

    public List<TaskEvent> getEvents() {
        AbstractTaskProvider provider = getProvider();
        return provider.getTasks();
    }

    public boolean hasPermission() {
        AbstractTaskProvider provider = getProvider();
        return provider.hasPermission();
    }

    public void requestPermission(Activity activity) {
        AbstractTaskProvider provider = getProvider();
        provider.requestPermission(activity);
    }

    private AbstractTaskProvider getProvider() {
        String taskSource = ApplicationPreferences.getTaskSource(context);
        if (PROVIDER_DMFS.equals(taskSource)) {
            return new DmfsOpenTasksProvider(context, widgetId);
        }
        if (PROVIDER_SAMSUNG.equals(taskSource)) {
            return new SamsungTasksProvider(context, widgetId);
        }

        return new EmptyTaskProvider(context, widgetId);
    }
}

package org.andstatus.todoagenda.task;

import android.app.Activity;
import android.content.Context;

import org.andstatus.todoagenda.EventProvider;
import org.andstatus.todoagenda.task.dmfs.DmfsOpenTasksProvider;
import org.andstatus.todoagenda.task.samsung.SamsungTasksProvider;

import java.util.List;

public class TaskProvider extends EventProvider {

    private static final String PROVIDER_DMFS = "DMFS_OPEN_TASKS";
    private static final String PROVIDER_SAMSUNG = "SAMSUNG";

    public TaskProvider(Context context, int widgetId) {
        super(context, widgetId);
    }

    public List<TaskEvent> getEvents() {
        AbstractTaskProvider provider = getProvider();
        return provider.getTasks();
    }

    public boolean hasPermission() {
        AbstractTaskProvider provider = getProvider();
        return provider.hasPermission();
    }

    public void requestPermission(Activity activity) {
        AbstractTaskProvider provider = getProvider();
        provider.requestPermission(activity);
    }

    private AbstractTaskProvider getProvider() {
        String taskSource = getSettings().getTaskSource();
        if (PROVIDER_DMFS.equals(taskSource)) {
            return new DmfsOpenTasksProvider(context, widgetId);
        }
        if (PROVIDER_SAMSUNG.equals(taskSource)) {
            return new SamsungTasksProvider(context, widgetId);
        }

        return new EmptyTaskProvider(context, widgetId);
    }
}

Fix to correctly use per-widget taks source.


package net.onrc.onos.core.topology.serializers;

import java.io.IOException;

import net.onrc.onos.core.topology.Device;
import net.onrc.onos.core.topology.Port;
import net.onrc.onos.core.topology.PortEvent.SwitchPort;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.SerializerProvider;
import org.codehaus.jackson.map.ser.std.SerializerBase;

public class DeviceSerializer extends SerializerBase<Device> {

    public DeviceSerializer() {
        super(Device.class);
    }

    @Override
    public void serialize(Device dev, JsonGenerator jsonGenerator,
        SerializerProvider serializerProvider) throws IOException,
        JsonGenerationException {
        jsonGenerator.writeStartObject();
        jsonGenerator.writeNumberField("mac", dev.getMacAddress().toLong());
        jsonGenerator.writeFieldName("attachmentPoints");
        jsonGenerator.writeStartArray();
        for (Port port : dev.getAttachmentPoints()) {
            SwitchPort sp = new SwitchPort(port.getDpid(), port.getNumber());
            jsonGenerator.writeObject(sp);
        }
        jsonGenerator.writeEndArray();
        jsonGenerator.writeEndObject();
    }

}

package net.onrc.onos.core.topology.serializers;

import java.io.IOException;

import net.onrc.onos.core.topology.Device;
import net.onrc.onos.core.topology.Port;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.SerializerProvider;
import org.codehaus.jackson.map.ser.std.SerializerBase;
import org.openflow.util.HexString;

public class DeviceSerializer extends SerializerBase<Device> {

    public DeviceSerializer() {
        super(Device.class);
    }

    @Override
    public void serialize(Device dev, JsonGenerator jsonGenerator,
        SerializerProvider serializerProvider) throws IOException,
        JsonGenerationException {
        jsonGenerator.writeStartObject();
        jsonGenerator.writeStringField("mac", dev.getMacAddress().toString());
        jsonGenerator.writeFieldName("attachmentPoints");
        jsonGenerator.writeStartArray();
        for (Port port : dev.getAttachmentPoints()) {
            jsonGenerator.writeStartObject();
            jsonGenerator.writeStringField("dpid", HexString.toHexString(port.getDpid()));
            jsonGenerator.writeNumberField("port", port.getNumber());
            jsonGenerator.writeEndObject();
        }
        jsonGenerator.writeEndArray();
        jsonGenerator.writeEndObject();
    }
}

Change device REST API format.

Change device REST API format.

Change-Id: I848c637f5a6d2a224ddceb16d0d27183712ed54a


package com.newsblur.fragment;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.app.DialogFragment;

import com.newsblur.R;
import com.newsblur.util.PrefsUtils;

public class LogoutDialogFragment extends DialogFragment {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage(getResources().getString(R.string.logout_warning));
        builder.setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                PrefsUtils.logout(getActivity());
            }
        });
        builder.setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                LogoutDialogFragment.this.dismiss();
            }
        });
        return builder.create();
    }

}

package com.newsblur.fragment;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.app.DialogFragment;

import com.newsblur.R;
import com.newsblur.util.PrefsUtils;

public class LogoutDialogFragment extends DialogFragment {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage(getResources().getString(R.string.logout_warning));
        builder.setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                PrefsUtils.logout(getActivity());
                // make sure the instance of Main that called us is killed now, or else the system
                // might try to recycle it with a stale login ID, which will cause it to self-destruct
                getActivity().finish();
            }
        });
        builder.setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                LogoutDialogFragment.this.dismiss();
            }
        });
        return builder.create();
    }

}

Fix activity drop after logout/login.

Fix activity drop after logout/login.


package com.kickstarter.models;

import com.google.common.collect.ImmutableMap;

public class DiscoveryParams {

  public enum Sort {
    MAGIC, POPULAR, ENDING_SOON, NEWEST, MOST_FUNDED;
    @Override
    public String toString() {
      switch (this) {
        case MAGIC:       return "magic";
        case POPULAR:     return "popularity";
        case ENDING_SOON: return "end_date";
        case NEWEST:      return "newest";
        case MOST_FUNDED: return "most_funded";
      }
      return "";
    }
  }

  private final Boolean staff_picks;
  private final Sort sort;

  public DiscoveryParams(Boolean staff_picks, Sort sort) {
    this.staff_picks = staff_picks;
    this.sort = sort;
  }

  public ImmutableMap<String, String> queryParams () {
    return ImmutableMap.of(
      "staff_picks", staff_picks.toString(),
      "sort", sort.toString(),
      "include_potd", staff_picks ? "true" : ""
    );
  }
}

package com.kickstarter.models;

import com.google.common.collect.ImmutableMap;

public class DiscoveryParams {

  public enum Sort {
    MAGIC, POPULAR, ENDING_SOON, NEWEST, MOST_FUNDED;
    @Override
    public String toString() {
      switch (this) {
        case MAGIC:       return "magic";
        case POPULAR:     return "popularity";
        case ENDING_SOON: return "end_date";
        case NEWEST:      return "newest";
        case MOST_FUNDED: return "most_funded";
      }
      throw new AssertionError("Unhandled sort");
    }
  }

  private final Boolean staff_picks;
  private final Sort sort;

  public DiscoveryParams(Boolean staff_picks, Sort sort) {
    this.staff_picks = staff_picks;
    this.sort = sort;
  }

  public ImmutableMap<String, String> queryParams () {
    return ImmutableMap.of(
      "staff_picks", staff_picks.toString(),
      "sort", sort.toString(),
      "include_potd", staff_picks ? "true" : ""
    );
  }
}

Throw assertion instead of returning empty string.


package com.codecrafters.server;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

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

/**
 * @author Fabian Dietenberger
 */
@RestController()
@RequestMapping("todos")
public class TodoItemRestController {

    private final TodoItemRepository repository;

    @Autowired
    public TodoItemRestController(final TodoItemRepository repository) {
        this.repository = repository;
    }

    @RequestMapping(method = RequestMethod.GET)
    public List<TodoItem> getTodoItems(@RequestParam(value = "text", required = false) String containingText) {
        return repository.findByTextContainingIgnoreCase(Optional.ofNullable(containingText).orElse(""));
    }

    @RequestMapping(method = RequestMethod.PUT)
    public ResponseEntity<String> addTodoItem(@RequestBody final TodoItem item) {
        repository.save(item);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @RequestMapping(method = RequestMethod.DELETE)
    public ResponseEntity<String> removeTodoItem(@RequestBody final TodoItem item) {
        repository.delete(item);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}

package com.codecrafters.server;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.Instant;
import java.util.List;
import java.util.Optional;

/**
 * @author Fabian Dietenberger
 */
@RestController()
@RequestMapping("todos")
public class TodoItemRestController {

    private final TodoItemRepository repository;

    @Autowired
    public TodoItemRestController(final TodoItemRepository repository) {
        this.repository = repository;
    }

    @RequestMapping(method = RequestMethod.GET)
    public ResponseEntity<List<TodoItem>> getTodoItems(@RequestParam(value = "text", required = false) String containingText) {
        final List<TodoItem> items = repository.findByTextContainingIgnoreCase(Optional.ofNullable(containingText).orElse(""));
        return ResponseEntity.ok()
                .lastModified(Instant.now().toEpochMilli()) // if we dont return this timestamp the browser could cache the request
                .body(items);
    }

    @RequestMapping(method = RequestMethod.PUT)
    public ResponseEntity<String> addTodoItem(@RequestBody final TodoItem item) {
        repository.save(item);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @RequestMapping(method = RequestMethod.DELETE)
    public ResponseEntity<String> removeTodoItem(@RequestBody final TodoItem item) {
        repository.delete(item);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}

Return last-modified in the /todos response.

This closes #1


package ch.tkuhn.bel2nanopub;

public class Bel2Nanopub {

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

}

package ch.tkuhn.bel2nanopub;

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

import org.openbel.bel.model.BELParseErrorException;
import org.openbel.framework.common.bel.parser.BELParseResults;
import org.openbel.framework.common.bel.parser.BELParser;

public class Bel2Nanopub {

	public static void main(String[] args) {
		String belDoc = getResourceAsString("/examples/pubmed11340296.bel");
		BELParseResults result = BELParser.parse(belDoc);
		for (BELParseErrorException ex : result.getSyntaxErrors()) {
			System.err.println(ex.getMessage());
		}
	}

	private static String getResourceAsString(String resourceName) {
		try {
			StringBuffer sb = new StringBuffer();
			InputStream is = Bel2Nanopub.class.getResourceAsStream(resourceName);
			BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
			for (int c = br.read(); c != -1; c = br.read()) {
				sb.append((char) c);
			}
			return sb.toString();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return null;
	}

}

Read exemplary BEL document (leads to errors...)


package com.sometrik.framework;

import android.content.Context;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class FWLayout extends LinearLayout implements NativeMessageHandler{

  private Context context;

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

  @Override
  public void handleMessage(NativeMessage message) {

    switch(message.getMessage()){
    case CREATE_BUTTON:
      Button button = new Button(context);
      button.setId(message.getChildInternalId());
      this.addView(button);
      break;

    case CREATE_PICKER:
      break;

    case CREATE_LINEAR_LAYOUT:
      LinearLayout layout = new LinearLayout(context);
      layout.setId(message.getChildInternalId());
      this.addView(layout);
      break;

    case CREATE_OPENGL_VIEW:
      break;

    case CREATE_TEXTFIELD:
      TextView textView = new TextView(context);
      textView.setId(message.getChildInternalId());
      this.addView(textView);
      break;

    case CREATE_TEXTLABEL:
      break;

    case SET_ATTRIBUTE:
      break;

    default:
      break;
    }
  }

}

package com.sometrik.framework;

import android.content.Context;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

public class FWLayout extends LinearLayout implements NativeMessageHandler{

  private Context context;

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

  @Override
  public void handleMessage(NativeMessage message) {

    switch(message.getMessage()){
    case CREATE_BUTTON:
      Button button = new Button(context);
      button.setId(message.getChildInternalId());
      this.addView(button);
      break;

    case CREATE_PICKER:
      Spinner spinner = new Spinner(context);
      spinner.setId(message.getChildInternalId());
      this.addView(spinner);
      break;

    case CREATE_LINEAR_LAYOUT:
      LinearLayout layout = new LinearLayout(context);
      layout.setId(message.getChildInternalId());
      this.addView(layout);
      break;

    case CREATE_OPENGL_VIEW:
      break;

    case CREATE_TEXTFIELD:
      EditText editText = new EditText(context);
      editText.setId(message.getChildInternalId());
      this.addView(editText);
      break;

    case CREATE_TEXTLABEL:
      TextView textView = new TextView(context);
      textView.setId(message.getChildInternalId());
      this.addView(textView);
      break;

    case SET_ATTRIBUTE:
      break;

    default:
      System.out.println("Message couldn't be handled by Element");
      break;
    }
  }

}

Add cases for picker, textField and textlabel creation


package com.erakk.lnreader.helper;

import com.erakk.lnreader.Constants;
import com.erakk.lnreader.DisplayImageActivity;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class BakaTsukiWebViewClient extends WebViewClient {
	@Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
//        if (Uri.parse(url).getHost().equals("www.example.com")) {
//            // This is my web site, so do not override; let my WebView load the page
//            return false;
//        }

		Log.d("shouldOverrideUrlLoading", url);

		Context context = view.getContext();

		// if image file
		if(url.contains("title=File:")) {
			Intent intent = new Intent(context, DisplayImageActivity.class);
			intent.putExtra(Constants.EXTRA_IMAGE_URL, url);
			context.startActivity(intent);
		}
		else {
			Toast.makeText(context, "Url: " + url, Toast.LENGTH_SHORT).show();
		}
        return true;
    }
}

package com.erakk.lnreader.helper;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.erakk.lnreader.Constants;
import com.erakk.lnreader.DisplayImageActivity;

public class BakaTsukiWebViewClient extends WebViewClient {
	@Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
//        if (Uri.parse(url).getHost().equals("www.example.com")) {
//            // This is my web site, so do not override; let my WebView load the page
//            return false;
//        }

		Log.d("shouldOverrideUrlLoading", url);

		Context context = view.getContext();

		// if image file
		if(url.contains("title=File:")) {
			Intent intent = new Intent(context, DisplayImageActivity.class);
			intent.putExtra(Constants.EXTRA_IMAGE_URL, url);
			context.startActivity(intent);
		}
		else {
			//Toast.makeText(context, "Url: " + url, Toast.LENGTH_SHORT).show();
			Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
			context.startActivity(browserIntent);
			return true;
		}
        return true;
    }
}

Handle other links in content view to browser


package com.commercetools.sunrise.common.template.i18n;

import io.sphere.sdk.models.Base;

/**
 * i18n Identifier, consisting of the message key and the bundle.
 *
 * - {@code bundle}: usually represents a module (e.g. catalog)
 * - {@code messageKey}: can contain multiple path elements (e.g. pagination.next)
 *
 * @see I18nIdentifier
 */
public final class I18nIdentifier extends Base {

    private final String bundle;
    private final String messageKey;

    private I18nIdentifier(final String bundle, final String messageKey) {
        this.bundle = bundle;
        this.messageKey = messageKey;
    }

    public String bundle() {
        return bundle;
    }

    public String messageKey() {
        return messageKey;
    }

    public static I18nIdentifier of(final String bundle, final String key) {
        return new I18nIdentifier(bundle, key);
    }
}

package com.commercetools.sunrise.common.template.i18n;

import io.sphere.sdk.models.Base;

import static com.commercetools.sunrise.common.utils.ArrayUtils.getArrayElement;
import static org.apache.commons.lang3.StringUtils.split;

/**
 * i18n Identifier, consisting of the message key and the bundle.
 *
 * - {@code bundle}: usually represents a module (e.g. catalog)
 * - {@code messageKey}: can contain multiple path elements (e.g. pagination.next)
 *
 * @see I18nIdentifier
 */
public final class I18nIdentifier extends Base {

    private final String bundle;
    private final String messageKey;

    private I18nIdentifier(final String bundle, final String messageKey) {
        this.bundle = bundle;
        this.messageKey = messageKey;
    }

    public String bundle() {
        return bundle;
    }

    public String messageKey() {
        return messageKey;
    }

    public static I18nIdentifier of(final String bundle, final String key) {
        return new I18nIdentifier(bundle, key);
    }

    /**
     * Creates a i18n Identifier, consisting of the message key and the bundle.
     * @param bundleWithKey of the form {@code bundle:key}
     * @return the i18n Identifier for the given input
     * @deprecated use {@link I18nIdentifierFactory} instead
     */
    @Deprecated
    public static I18nIdentifier of(final String bundleWithKey) {
        final String[] parts = split(bundleWithKey, ":", 2);
        final String key = getArrayElement(parts, 1, bundleWithKey);
        final String bundle;
        if (bundleWithKey.equals(key)) {
            bundle = "main";
        } else {
            bundle = getArrayElement(parts, 0, "main");
        }
        return ofBundleAndKey(bundle, key);
    }

    /**
     * @deprecated use {@link #of} instead
     */
    @Deprecated
    public static I18nIdentifier ofBundleAndKey(final String bundle, final String key) {
        return of(bundle, key);
    }
}

Add deprecated messages to i18n identifier methods


package ethanjones.cubes.block;

import ethanjones.cubes.core.IDManager;
import ethanjones.cubes.core.IDManager.GetBlock;
import ethanjones.cubes.item.ItemStack;
import ethanjones.cubes.item.crafting.CraftingManager;
import ethanjones.cubes.item.crafting.CraftingRecipe;

public class Blocks {

  @GetBlock("core:bedrock")
  public static Block bedrock;
  @GetBlock("core:stone")
  public static Block stone;
  @GetBlock("core:dirt")
  public static Block dirt;
  @GetBlock("core:grass")
  public static Block grass;
  @GetBlock("core:log")
  public static Block log;
  @GetBlock("core:leaves")
  public static Block leaves;
  @GetBlock("core:glow")
  public static Block glow;
  @GetBlock("core:glass")
  public static Block glass;

  public static Block chest;

  public static void init() {
    chest = new BlockChest();
    IDManager.register(chest);

    ItemStack c = new ItemStack(chest.getItemBlock());
    ItemStack l = new ItemStack(log.getItemBlock());
    CraftingManager.addRecipe(new CraftingRecipe(c, l, l, l, l, null, l, l, l, l));
  }
}

package ethanjones.cubes.block;

import ethanjones.cubes.core.IDManager;
import ethanjones.cubes.core.IDManager.GetBlock;
import ethanjones.cubes.item.ItemStack;
import ethanjones.cubes.item.crafting.CraftingManager;
import ethanjones.cubes.item.crafting.CraftingRecipe;

public class Blocks {

  @GetBlock("core:bedrock")
  public static Block bedrock;
  @GetBlock("core:stone")
  public static Block stone;
  @GetBlock("core:dirt")
  public static Block dirt;
  @GetBlock("core:grass")
  public static Block grass;
  @GetBlock("core:log")
  public static Block log;
  @GetBlock("core:leaves")
  public static Block leaves;
  @GetBlock("core:glow")
  public static Block glow;
  @GetBlock("core:glass")
  public static Block glass;

  public static Block chest;

  public static void init() {
    chest = new BlockChest();
    IDManager.register(chest);

    ItemStack c = new ItemStack(chest.getItemBlock(), 2);
    ItemStack l = new ItemStack(log.getItemBlock());
    CraftingManager.addRecipe(new CraftingRecipe(c, l, l, l, l, null, l, l, l, l));
  }
}

Change chest recipe to make 2 chests

Change chest recipe to make 2 chests


package org.sagebionetworks.bridge.services.backfill;

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

import com.stormpath.sdk.account.Account;
import com.stormpath.sdk.account.AccountCriteria;
import com.stormpath.sdk.account.AccountList;
import com.stormpath.sdk.application.Application;
import com.stormpath.sdk.impl.account.DefaultAccountCriteria;

class StormpathAccountIterator implements Iterator<List<Account>> {

    private static final int PAGE_SIZE = 50;
    private final Application app;
    private int offset;
    private boolean hasNext;

    StormpathAccountIterator(Application app) {
        this.app = app;
        offset = 0;
        hasNext = true;
    }

    @Override
    public boolean hasNext() {
        return hasNext;
    }

    @Override
    public List<Account> next() {
        AccountCriteria criteria = new DefaultAccountCriteria();
        criteria.offsetBy(offset);
        criteria.limitTo(PAGE_SIZE);
        AccountList list = app.getAccounts(criteria);
        Iterator<Account> iterator = list.iterator();
        List<Account> accountList = new ArrayList<Account>();
        while (iterator.hasNext()) {
            accountList.add(iterator.next());
        }
        hasNext = accountList.size() == PAGE_SIZE;
        offset = offset + PAGE_SIZE;
        return accountList;
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException();
    }
}

package org.sagebionetworks.bridge.services.backfill;

import java.util.Iterator;

import com.stormpath.sdk.account.Account;
import com.stormpath.sdk.account.AccountCriteria;
import com.stormpath.sdk.account.AccountList;
import com.stormpath.sdk.application.Application;
import com.stormpath.sdk.impl.account.DefaultAccountCriteria;

/**
 * Iterates through Stormpath accounts page by page.
 */
class StormpathAccountIterator extends PageIterator<Account> {

    private static final int PAGE_SIZE = 50;
    private final Application app;

    StormpathAccountIterator(Application app) {
        this.app = app;
    }

    @Override
    int pageSize() {
        return PAGE_SIZE;
    }

    @Override
    Iterator<Account> nextPage() {
        AccountCriteria criteria = new DefaultAccountCriteria();
        criteria.offsetBy(pageStart());
        criteria.limitTo(pageSize());
        AccountList list = app.getAccounts(criteria);
        return list.iterator();
    }
}

Test the paginated Stormpath account iterator


package cl.fatman.capital.fund;

import static org.junit.Assert.*;

import java.time.LocalDate;

import org.junit.Test;

public class ExtractFundDataTest {

	@Test
	public void getFundDataTest() {
		ExtractFundData efData = new ExtractFundData("blabla");
		assertNotNull("List with Fund data should not be null", efData.getFundData());
	}

	@Test
	public void getFundRateDataTest() {
		ExtractFundData efData = new ExtractFundData("blabla");
		LocalDate frDate = LocalDate.now();
		assertNotNull("List with Fund Rate data should not be null", efData.getFundRateData(frDate));
	}
}

package cl.fatman.capital.fund;

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

import java.io.IOException;
import java.time.LocalDate;

public class ExtractFundDataTest {

	private static ExtractFundData efData;

	@BeforeClass
	public static void setUp() {
		String link = "http://www.aafm.cl/tecnoera/index.php?clase=informe&metodo=rentabilidad_html&inversion=%&administradora=%&tipo=";
		String userAgent = "Mozilla/5.0 (X11; Fedora; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.108 Safari/537.36";
		efData = new ExtractFundData(link, userAgent);
	}

	@Test
	public void getFundDataTest() throws IOException {
		assertNotNull("List with Fund data should not be null", efData.getFundData(1));
	}

	@Test
	public void getFundRateDataTest() {
		LocalDate frDate = LocalDate.now();
		assertNotNull("List with Fund Rate data should not be null", efData.getFundRateData(frDate));
	}
}

Improve junit code and design.

Improve junit code and design.


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

package org.apache.jmeter.util;

/**
 * @version $Revision$
 */
public final class StringUtilities {
	public static String substitute(String input, String pattern, String sub) {
		StringBuffer ret = new StringBuffer();
		int start = 0;
		int index = -1;
		while ((index = input.indexOf(pattern, start)) >= start) {
			ret.append(input.substring(start, index));
			ret.append(sub);
			start = index + pattern.length();
		}
		ret.append(input.substring(start));
		return ret.toString();
	}

	/**
	 * Private constructor to prevent instantiation.
	 */
	private StringUtilities() {
	}

}

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

package org.apache.jmeter.util;

/**
 * @version $Revision$
 */
public final class StringUtilities {

    /**
     * Private constructor to prevent instantiation.
     */
    private StringUtilities() {
    }

    /**
     * Replace all patterns in a String
     *
     * @see String.replaceAll(regex,replacement) - JDK1.4 only
     *
     * @param input - string to be transformed
     * @param pattern - pattern to replace
     * @param sub - replacement
     * @return the updated string
     */
	public static String substitute(final String input, final String pattern, final String sub) {
		StringBuffer ret = new StringBuffer(input.length());
		int start = 0;
		int index = -1;
        final int length = pattern.length();
		while ((index = input.indexOf(pattern, start)) >= start) {
			ret.append(input.substring(start, index));
			ret.append(sub);
            start = index + length;
		}
		ret.append(input.substring(start));
		return ret.toString();
	}
}

Add documentation and tidy up a bit

Add documentation and tidy up a bit

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

Former-commit-id: 27e9d82281f1ffccef29acba25b279d8ebca551c


package org.clafer.ir;

import org.clafer.ir.IrQuickTest.Solution;
import static org.clafer.ir.Irs.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import solver.constraints.Constraint;
import solver.constraints.set.SCF;
import solver.variables.IntVar;
import solver.variables.SetVar;

/**
 *
 * @author jimmy
 */
@RunWith(IrQuickTest.class)
public class IrMemberTest {

    @Test(timeout = 60000)
    public IrBoolExpr setup(IrIntVar element, IrSetVar set) {
        return member(element, set);
    }

    @Solution
    public Constraint setup(IntVar element, SetVar set) {
        return SCF.member(element, set);
    }
}

package org.clafer.ir;

import org.clafer.choco.constraint.Constraints;
import org.clafer.ir.IrQuickTest.Solution;
import static org.clafer.ir.Irs.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import solver.constraints.Constraint;
import solver.variables.IntVar;
import solver.variables.SetVar;

/**
 *
 * @author jimmy
 */
@RunWith(IrQuickTest.class)
public class IrMemberTest {

    @Test(timeout = 60000)
    public IrBoolExpr setup(IrIntVar element, IrSetVar set) {
        return member(element, set);
    }

    @Solution
    public Constraint setup(IntVar element, SetVar set) {
        return Constraints.member(element, set);
    }
}

Test with custom membership constraints.


/*
 * Copyright 2013-2015 Hewlett-Packard Development Company, L.P.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
 */

package com.autonomy.frontend.testing.mock;

import org.springframework.beans.factory.FactoryBean;
import static org.mockito.Mockito.mock;

/**
 * {@link FactoryBean} for creating Mockito mock objects. This is useful if you're using a test application context
 * written in XML.
 *
 * If your test context uses Java configuration, there is no need to use this method.
 */
public class MocksFactory implements FactoryBean<Object> {

    private Class<?> type;// the created object type

    /**
     * @param type The type of the mock object. This is a required property.
     */
    public void setType(final Class<?> type) {
        this.type = type;
    }

    /**
     * @return A Mockito mock of the given type
     * @throws Exception
     */
    @Override
    public Object getObject() throws Exception {
        return mock(type);
    }

    /**
     * @return The type of the mock object
     */
    @Override
    public Class<?> getObjectType() {
        return type;
    }

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

/*
 * Copyright 2013-2015 Hewlett-Packard Development Company, L.P.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
 */

package com.autonomy.frontend.testing.mock;

import org.springframework.beans.factory.FactoryBean;
import static org.mockito.Mockito.mock;

/**
 * {@link FactoryBean} for creating Mockito mock objects. This is useful if you're using a test application context
 * written in XML.
 *
 * If your test context uses Java configuration, there is no need to use this method.
 */
public class MocksFactory implements FactoryBean<Object> {

    private Class<?> type;// the created object type

    /**
     * @param type The type of the mock object. This is a required property.
     */
    public void setType(final Class<?> type) {
        this.type = type;
    }

    /**
     * @return A Mockito mock of the given type
     * @throws Exception
     */
    @Override
    public Object getObject() throws Exception {
        return mock(type);
    }

    /**
     * @return The type of the mock object
     */
    @Override
    public Class<?> getObjectType() {
        return type;
    }

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

Change isSingleton as we return a new mock every time.


package com.mobilejazz.cacheio.serializer;

import com.google.gson.Gson;
import com.mobilejazz.cacheio.ApplicationTestCase;
import com.mobilejazz.cacheio.GsonSerialiser;
import com.mobilejazz.cacheio.Serialiser;
import org.assertj.core.api.Assertions;
import org.junit.Before;
import org.junit.Test;

public class GsonSerialiserTest extends ApplicationTestCase {

  private Serialiser serialiser;

  @Before public void setUp() throws Exception {
    Gson gson = new Gson();
    serialiser = new GsonSerialiser(gson);
  }

  @Test public void shouldPassTest() throws Exception {
    Assertions.assertThat(true).isTrue();
  }
}

package com.mobilejazz.cacheio.serializer;

import com.google.gson.Gson;
import com.mobilejazz.cacheio.ApplicationTestCase;
import com.mobilejazz.cacheio.GsonSerialiser;
import com.mobilejazz.cacheio.Serialiser;
import com.mobilejazz.cacheio.model.UserTestModel;
import org.assertj.core.api.Assertions;
import org.junit.Before;
import org.junit.Test;

public class GsonSerialiserTest extends ApplicationTestCase {

  private Serialiser serialiser;

  @Before public void setUp() throws Exception {
    Gson gson = new Gson();
    serialiser = new GsonSerialiser(gson);
  }

  @Test public void shouldSerialiseAObject() throws Exception {
    UserTestModel userTestModel = fakeUserTestObject();

    byte[] bytes = serialiser.toBytes(userTestModel);

    Assertions.assertThat(bytes).isNotNull();
    Assertions.assertThat(bytes.length).isGreaterThan(0);
  }

  @Test public void shouldDeserializeAObject() throws Exception {
    UserTestModel userTestModelToDeserialize = fakeUserTestObject();
    byte[] userDeserialized = fakeUserTestBytes(userTestModelToDeserialize);

    UserTestModel userTestModelExpected =
        (UserTestModel) serialiser.fromBytes(userDeserialized, UserTestModel.class);

    Assertions.assertThat(userTestModelExpected).isNotNull();
    Assertions.assertThat(userTestModelExpected.getId())
        .isEqualTo(userTestModelToDeserialize.getId());
    Assertions.assertThat(userTestModelExpected.getName())
        .isEqualTo(userTestModelToDeserialize.getName());
  }

  private UserTestModel fakeUserTestObject() {
    UserTestModel userTestModel = new UserTestModel();
    userTestModel.setId(1);
    userTestModel.setName("Test name");

    return userTestModel;
  }

  private byte[] fakeUserTestBytes(UserTestModel userTestModel) {
    return serialiser.toBytes(userTestModel);
  }
}

Implement test to check that the GsonSerializer is working


package com.perm.kate.api;

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

public class Params {
    TreeMap<String, String> args = new TreeMap<String, String>();
    String method_name;

    public Params(String method_name){
        this.method_name=method_name;
    }

    public void put(String param_name, String param_value) {
        if(param_value==null || param_value.length()==0)
            return;
        args.put(param_name, param_value);
    }

    public void put(String param_name, Long param_value) {
        if(param_value==null)
            return;
        args.put(param_name, Long.toString(param_value));
    }

    public void put(String param_name, Integer param_value) {
        if(param_value==null)
            return;
        args.put(param_name, Integer.toString(param_value));
    }

    public void putDouble(String param_name, double param_value) {
        args.put(param_name, Double.toString(param_value));
    }

    public String getParamsString() {
        String params="";
        for(Entry<String, String> entry:args.entrySet()){
            if(params.length()!=0)
                params+="&";
            params+=(entry.getKey()+"="+URLEncoder.encode(entry.getValue()));
        }
        return params;
    }

}

package com.perm.kate.api;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.TreeMap;
import java.util.Map.Entry;

public class Params {
    TreeMap<String, String> args = new TreeMap<String, String>();
    String method_name;

    public Params(String method_name){
        this.method_name=method_name;
    }

    public void put(String param_name, String param_value) {
        if(param_value==null || param_value.length()==0)
            return;
        args.put(param_name, param_value);
    }

    public void put(String param_name, Long param_value) {
        if(param_value==null)
            return;
        args.put(param_name, Long.toString(param_value));
    }

    public void put(String param_name, Integer param_value) {
        if(param_value==null)
            return;
        args.put(param_name, Integer.toString(param_value));
    }

    public void putDouble(String param_name, double param_value) {
        args.put(param_name, Double.toString(param_value));
    }

    public String getParamsString() {
        String params="";
        try {
            for(Entry<String, String> entry:args.entrySet()){
                if(params.length()!=0)
                    params+="&";
                params+=(entry.getKey()+"="+URLEncoder.encode(entry.getValue(), "utf-8"));
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return params;
    }

}

Fix posting messages with smiles

Fix posting messages with smiles


/*
 * Trident - A Multithreaded Server Alternative
 * Copyright 2014 The TridentSDK Team
 *
 * 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.tridentsdk.effect;

import net.tridentsdk.entity.living.Player;
import net.tridentsdk.util.Vector;

/**
 * Represents effects that can be executed without an entity
 *
 * @author The TridentSDK Team
 * @since 0.4-alpha
 */
public interface RemoteEffect<T> extends Effect<T> {

    /**
     * Execute the effect at the given location for specified player
     *
     * @param player The player to send the effect to
     */
    void apply(Player player);

    /**
     * Set the position of the effect
     *
     * @param vector The vector of the effect
     */
    void setPosition(Vector vector);

}

/*
 * Trident - A Multithreaded Server Alternative
 * Copyright 2014 The TridentSDK Team
 *
 * 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.tridentsdk.effect;

import net.tridentsdk.entity.living.Player;
import net.tridentsdk.util.Vector;

/**
 * Represents effects that can be executed without an entity
 *
 * @author The TridentSDK Team
 * @since 0.4-alpha
 */
public interface RemoteEffect<T> extends Effect<T> {

    /**
     * Execute the effect at the given location
     */
    void apply();

    /**
     * Execute the effect at the given location for specified player
     *
     * @param player The player to send the effect to
     */
    void apply(Player player);

    /**
     * Set the position of the effect
     *
     * @param vector The vector of the effect
     */
    void setPosition(Vector vector);

}

Add method to broadcast to all players

Add method to broadcast to all players


/*
 * Copyright (c) 2017 pCloud AG
 *
 * 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.pcloud.sdk.authentication;

public abstract class Authenticator {

}

/*
 * Copyright (c) 2017 pCloud AG
 *
 * 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.pcloud.sdk.authentication;

public abstract class Authenticator {

    public static Authenticator newOAuthAuthenticator(String accessToken){
        return new AccessTokenAuthenticator(accessToken);
    }
}

feat(Core):  Add a way to access the OAuth token authenticator


package org.eobjects.build;

import java.io.File;

import org.apache.maven.plugin.MojoFailureException;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

public abstract class AbstractDotnetTestMojo extends AbstractDotnetMojo {

    private final ObjectMapper objectMapper = new ObjectMapper();

    public void executeInternal() throws MojoFailureException {
        final PluginHelper helper = getPluginHelper();
        for (File subDirectory : helper.getProjectDirectories()) {
            if (isTestRunnable(subDirectory)) {
                helper.executeCommand(subDirectory, "dotnet", "test", "-c", helper.getBuildConfiguration());
            }
        }
    }

    private boolean isTestRunnable(File subDirectory) {
        // check if there is a 'testRunner' attribute defined in project.json
        final File projectJsonFile = new File(subDirectory, "project.json");
        final ObjectNode root;
        try {
            root = (ObjectNode) objectMapper.readTree(projectJsonFile);
        } catch (Exception e) {
            getLog().warn("Failed to parse '" + projectJsonFile
                    + "' in order to determine if a 'testRunner' attribute is set.");
            return false;
        }
        final JsonNode testRunnerNode = root.get("testRunner");
        return testRunnerNode != null && !testRunnerNode.isMissingNode();
    }
}

package org.eobjects.build;

import java.io.File;

import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Parameter;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

public abstract class AbstractDotnetTestMojo extends AbstractDotnetMojo {

	@Parameter(property = "dotnet.test.outputxml", required = false, defaultValue = "TestResults.xml")
    private String outputXml;

    private final ObjectMapper objectMapper = new ObjectMapper();

    public void executeInternal() throws MojoFailureException {
        final PluginHelper helper = getPluginHelper();
        for (File subDirectory : helper.getProjectDirectories()) {
            if (isTestRunnable(subDirectory)) {
                helper.executeCommand(subDirectory, "dotnet", "test", "-c", helper.getBuildConfiguration(), "-xml", outputXml);
            }
        }
    }

    private boolean isTestRunnable(File subDirectory) {
        // check if there is a 'testRunner' attribute defined in project.json
        final File projectJsonFile = new File(subDirectory, "project.json");
        final ObjectNode root;
        try {
            root = (ObjectNode) objectMapper.readTree(projectJsonFile);
        } catch (Exception e) {
            getLog().warn("Failed to parse '" + projectJsonFile
                    + "' in order to determine if a 'testRunner' attribute is set.");
            return false;
        }
        final JsonNode testRunnerNode = root.get("testRunner");
        return testRunnerNode != null && !testRunnerNode.isMissingNode();
    }
}

Add parameter to allow for output xml flag


package com.elmakers.mine.bukkit.api.spell;

import java.util.Collection;

import org.bukkit.Color;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;

import com.elmakers.mine.bukkit.api.block.MaterialAndData;
import com.elmakers.mine.bukkit.api.effect.EffectPlayer;

/**
 * A Spell template, as defined in the spells configuration files.
 */
public interface SpellTemplate extends Comparable<SpellTemplate>, CostReducer {
    public String getName();
    public String getAlias();
    public String getDescription();
    public String getExtendedDescription();
    public String getKey();
    public Color getColor();
    public long getWorth();
    public SpellCategory getCategory();
    public long getCastCount();
    public String getUsage();
    public MaterialAndData getIcon();
    public boolean hasIcon();
    public boolean hasCastPermission(CommandSender sender);
    public Collection<CastingCost> getCosts();
    public Collection<CastingCost> getActiveCosts();
    public Collection<EffectPlayer> getEffects(SpellResult result);
    public Collection<EffectPlayer> getEffects(String effectsKey);
    public void getParameters(Collection<String> parameters);
    public void getParameterOptions(Collection<String> examples, String parameterKey);
    public long getDuration();
    public long getCooldown();
    public Spell createSpell();
    public void loadTemplate(String key, ConfigurationSection node);
    public String getPermissionNode();
    public boolean isHidden();
}

package com.elmakers.mine.bukkit.api.spell;

import java.util.Collection;

import org.bukkit.Color;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;

import com.elmakers.mine.bukkit.api.block.MaterialAndData;
import com.elmakers.mine.bukkit.api.effect.EffectPlayer;

/**
 * A Spell template, as defined in the spells configuration files.
 */
public interface SpellTemplate extends Comparable<SpellTemplate>, CostReducer {
    public String getName();
    public String getAlias();
    public String getDescription();
    public String getExtendedDescription();
    public String getLevelDescription();
    public int getLevel();
    public String getKey();
    public String getBaseSpellKey();
    public Color getColor();
    public long getWorth();
    public SpellCategory getCategory();
    public long getCastCount();
    public String getUsage();
    public MaterialAndData getIcon();
    public boolean hasIcon();
    public boolean hasCastPermission(CommandSender sender);
    public Collection<CastingCost> getCosts();
    public Collection<CastingCost> getActiveCosts();
    public Collection<EffectPlayer> getEffects(SpellResult result);
    public Collection<EffectPlayer> getEffects(String effectsKey);
    public void getParameters(Collection<String> parameters);
    public void getParameterOptions(Collection<String> examples, String parameterKey);
    public long getDuration();
    public long getCooldown();
    public Spell createSpell();
    public void loadTemplate(String key, ConfigurationSection node);
    public String getPermissionNode();
    public boolean isHidden();
}

Add basic spell levelling API

Add basic spell levelling API


package com.zulip.android;

import com.crashlytics.android.Crashlytics;

public class ZLog {

    public static void logException(Throwable e) {
        if (BuildHelper.shouldLogToCrashlytics()) {
            e.printStackTrace();
        } else {
            Crashlytics.logException(e);
        }
    }

}

package com.zulip.android;

import android.util.Log;

import com.crashlytics.android.Crashlytics;

public class ZLog {

    public static void logException(Throwable e) {
        if (!BuildHelper.shouldLogToCrashlytics()) {
            Log.e("Error", "oops", e);
        } else {
            Crashlytics.logException(e);
        }
    }

}

Fix logic error on logging to crashlytics


package info.u_team.u_team_test.entity.render;

import com.mojang.blaze3d.matrix.MatrixStack;

import net.minecraft.client.renderer.entity.*;
import net.minecraft.entity.monster.ZombieEntity;

public class TestLivingEntityRenderer extends ZombieRenderer {

	public TestLivingEntityRenderer(EntityRendererManager renderManager) {
		super(renderManager);
	}

	@Override
	protected void preRenderCallback(ZombieEntity zombie, MatrixStack matrixStack, float partialTickTime) {
		matrixStack.scale(1.0625F, 1.0625F, 1.0625F);
		super.preRenderCallback(zombie, matrixStack, partialTickTime);
	}

}

package info.u_team.u_team_test.entity.render;

import com.mojang.blaze3d.matrix.MatrixStack;

import info.u_team.u_team_test.TestMod;
import net.minecraft.client.renderer.entity.*;
import net.minecraft.entity.monster.ZombieEntity;
import net.minecraft.util.ResourceLocation;

public class TestLivingEntityRenderer extends ZombieRenderer {

	private static final ResourceLocation TEXTURE = new ResourceLocation(TestMod.MODID, "textures/entity/test_living/test_living.png");

	public TestLivingEntityRenderer(EntityRendererManager renderManager) {
		super(renderManager);
	}

	@Override
	protected void preRenderCallback(ZombieEntity zombie, MatrixStack matrixStack, float partialTickTime) {
		matrixStack.scale(1.0625F, 1.0625F, 1.0625F);
		super.preRenderCallback(zombie, matrixStack, partialTickTime);
	}

	@Override
	public ResourceLocation getEntityTexture(ZombieEntity entity) {
		return TEXTURE;
	}

}

Use texture for test living

Use texture for test living


package jfdi.storage;

import java.nio.file.InvalidPathException;

import jfdi.storage.exceptions.ExistingFilesFoundException;

/**
 * This class serves as the facade of the Storage component.
 *
 * @author Thng Kai Yuan
 */
public class FileStorage implements IStorage {

    // The singleton instance of FileStorage
    private static FileStorage instance = null;

    // Boolean indicating if storage has been initialized
    private boolean isInitialized = false;

    /**
     * This private constructor prevents itself from being called by other
     * components. An instance of FileStorage should be initialized using the
     * getInstance method.
     */
    private FileStorage() {
    }

    /**
     * @return the singleton instance of FileStorage
     */
    public static FileStorage getInstance() {
        if (instance == null) {
            instance = new FileStorage();
        }

        return instance;
    }

    @Override
    public void load(String storageFolderPath) throws InvalidPathException, ExistingFilesFoundException {
        FileManager.prepareDirectory(storageFolderPath);
        RecordManager.setAllFilePaths(storageFolderPath);
        RecordManager.loadAllRecords();
        isInitialized = true;
    }

    @Override
    public void changeDirectory(String newStorageFolderPath) throws InvalidPathException,
            ExistingFilesFoundException, IllegalAccessException {

        if (!isInitialized) {
            throw new IllegalAccessException(Constants.MESSAGE_UNINITIALIZED_STORAGE);
        }

        FileManager.prepareDirectory(newStorageFolderPath);
        FileManager.moveFilesToDirectory(newStorageFolderPath);
        RecordManager.setAllFilePaths(newStorageFolderPath);
        RecordManager.loadAllRecords();
    }

}

package jfdi.storage;

import java.nio.file.InvalidPathException;

import jfdi.storage.exceptions.ExistingFilesFoundException;

/**
 * This class serves as the facade of the Storage component.
 *
 * @author Thng Kai Yuan
 */
public class FileStorage implements IStorage {

    // The singleton instance of FileStorage
    private static FileStorage instance = null;

    // Boolean indicating if storage has been initialized
    private boolean isInitialized = false;

    /**
     * This private constructor prevents itself from being called by other
     * components. An instance of FileStorage should be initialized using the
     * getInstance method.
     */
    private FileStorage() {
    }

    /**
     * @return the singleton instance of FileStorage
     */
    public static FileStorage getInstance() {
        if (instance == null) {
            instance = new FileStorage();
        }

        return instance;
    }

    @Override
    public void load(String storageFolderPath) throws InvalidPathException, ExistingFilesFoundException {
        FileManager.prepareDirectory(storageFolderPath);
        RecordManager.setAllFilePaths(storageFolderPath);
        RecordManager.loadAllRecords();
        isInitialized = true;
    }

    @Override
    public void changeDirectory(String newStorageFolderPath) throws InvalidPathException,
            ExistingFilesFoundException, IllegalAccessException {

        if (!isInitialized) {
            throw new IllegalAccessException(Constants.MESSAGE_UNINITIALIZED_STORAGE);
        }

        FileManager.prepareDirectory(newStorageFolderPath);
        FileManager.moveFilesToDirectory(newStorageFolderPath);
        RecordManager.setAllFilePaths(newStorageFolderPath);
        RecordManager.loadAllRecords();
    }

    /**
     * This method sets the existing instance to null. It should only be used
     * for testing/debugging purposes only.
     */
    public void removeInstance() {
        instance = null;
    }

}

Add removeInstance API for tests

Add removeInstance API for tests


/*
// Licensed to Julian Hyde under one or more contributor license
// agreements. See the NOTICE file distributed with this work for
// additional information regarding copyright ownership.
//
// Julian Hyde licenses this file to you under the Modified BSD License
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at:
//
// http://opensource.org/licenses/BSD-3-Clause
*/
package sqlline;

import java.sql.*;

import sun.misc.*;

/**
 * A signal handler for SqlLine which interprets Ctrl+C as a request to cancel
 * the currently executing query. Adapted from <a
 * href="http://www.smotricz.com/kabutz/Issue043.html">TJSN</a>.
 */
class SunSignalHandler
    implements SqlLineSignalHandler,
        SignalHandler
{
    private DispatchCallback dispatchCallback;

    SunSignalHandler()
    {
        Signal.handle(new Signal("INT"), this);
    }

    @Override
    public void setCallback(DispatchCallback dispatchCallback)
    {
        this.dispatchCallback = dispatchCallback;
    }

    @Override
    public void handle(Signal sig)
    {
        try {
            synchronized (this) {
                if (dispatchCallback != null) {
                    dispatchCallback.forceKillSqlQuery();
                    dispatchCallback.setToCancel();
                }
            }
        } catch (SQLException ex) {
            throw new RuntimeException(ex);
        }
    }
}

/*
// Licensed to Julian Hyde under one or more contributor license
// agreements. See the NOTICE file distributed with this work for
// additional information regarding copyright ownership.
//
// Julian Hyde licenses this file to you under the Modified BSD License
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at:
//
// http://opensource.org/licenses/BSD-3-Clause
*/
package sqlline;

import java.sql.*;

import sun.misc.*;

/**
 * A signal handler for SqlLine which interprets Ctrl+C as a request to cancel
 * the currently executing query. Adapted from <a
 * href="http://www.smotricz.com/kabutz/Issue043.html">TJSN</a>.
 */
class SunSignalHandler
    implements SqlLineSignalHandler,
        SignalHandler
{
    private DispatchCallback dispatchCallback;

    SunSignalHandler()
    {
        Signal.handle(new Signal("INT"), this);
    }

    public void setCallback(DispatchCallback dispatchCallback)
    {
        this.dispatchCallback = dispatchCallback;
    }

    public void handle(Signal sig)
    {
        try {
            synchronized (this) {
                if (dispatchCallback != null) {
                    dispatchCallback.forceKillSqlQuery();
                    dispatchCallback.setToCancel();
                }
            }
        } catch (SQLException ex) {
            throw new RuntimeException(ex);
        }
    }
}

Remove '@Override', to fix compile on JDK 1.5.


package dk.aau.kah.bits.evaluation;

import da.aau.kah.bits.exceptions.InvalidDatabaseConfig;
import dk.aau.kah.bits.database.DatabaseConfig;
import dk.aau.kah.bits.database.DatabaseHandler;

public class ExperimentFactory {

	public ExperimentFactory() {

	}

	public AbstractEvaluationHandler makeEvaluation(DatabaseHandler databaseHandle, DatabaseConfig databaseConfig) throws InvalidDatabaseConfig {
		String datasetType = databaseConfig.getDatasetType();
		AbstractEvaluationHandler evaluationhandler;

		if (datasetType.equals("TPC-H")) {
			evaluationhandler = new EvaluationHandlerTPCH(databaseHandle);
		} else {
			throw new InvalidDatabaseConfig("The Dataset Type "+databaseConfig.getDatasetType()+" is not known, implementation is missing.");
		}
		return evaluationhandler;
	}

}

package dk.aau.kah.bits.evaluation;

import da.aau.kah.bits.exceptions.InvalidDatabaseConfig;
import dk.aau.kah.bits.database.DatabaseConfig;
import dk.aau.kah.bits.database.DatabaseHandler;

public class ExperimentFactory {

	public ExperimentFactory() {

	}

	public AbstractExperimentHandler makeEvaluation(DatabaseHandler databaseHandle, DatabaseConfig databaseConfig) throws InvalidDatabaseConfig {
		String datasetType = databaseConfig.getDatasetType();
		AbstractExperimentHandler evaluationhandler;

		if (datasetType.equals("TPC-H")) {
			evaluationhandler = new ExperimentHandlerTPCH(databaseHandle);
		} else {
			throw new InvalidDatabaseConfig("The Dataset Type "+databaseConfig.getDatasetType()+" is not known, implementation is missing.");
		}
		return evaluationhandler;
	}

}

Rename some functions to experiment instead of evaluation


package com.telus.training.ex1;

public class ClockNeedles {

	public double calculateAngle(int hours, int minutes) {
		double hoursAngle = hours*30;
		double minutesAngle = minutes*6;

		double angle = Math.abs(hoursAngle - minutesAngle);
		if(angle > 180.0) angle = angle - 180.0;
		return angle;
	}
}

package com.telus.training.ex1;

public class ClockNeedles {

	public double calculateAngleBetween(int hours, int minutes) {
		double hoursAngle = convertHoursToAngle(hours);
		double minutesAngle = convertMinutesToAngle(minutes);

		double angle = Math.abs(hoursAngle - minutesAngle);
		return (angle > 180.0) ? (angle - 180.0) : angle;
	}

	private int convertMinutesToAngle(int minutes) {
		if (minutes < 0 || minutes > 60) {
			throw new IllegalArgumentException("Minutes must be between 0 and 60");
		}
		return minutes*6;
	}

	private int convertHoursToAngle(int hours) {
		if(hours < 0 || hours > 12) {
			throw new IllegalArgumentException("Hours must be between 0 and 12");
		}
		return hours*30;
	}
}

Add checks for hours and minutes

Add checks for hours and minutes