package com.example.octoissues;

import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

public class EditOwnerRepoDialog extends DialogFragment implements OnEditorActionListener{

	public interface EditRepoDialogListener {
		void onFinishEditDialog(String inputText);
	}

	private EditText editOwner;
	private EditText editRepo;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_owner_repo, container);
        editOwner = (EditText) view.findViewById(R.id.owner_name);
        editRepo = (EditText) view.findViewById(R.id.repo_name);
        getDialog().setTitle("Enter Owner and Repo");

        return view;
    }

	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		// TODO Auto-generated method stub
		return false;
	}

}

package com.example.octoissues;

import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

public class EditOwnerRepoDialog extends DialogFragment implements OnEditorActionListener{

	public interface EditRepoDialogListener {
		void onFinishEditDialog(String owner, String repo);
	}

	private EditText editOwner;
	private EditText editRepo;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_owner_repo, container);
        editOwner = (EditText) view.findViewById(R.id.owner_name);
        editRepo = (EditText) view.findViewById(R.id.repo_name);
        getDialog().setTitle("Enter Owner and Repo");

        return view;
    }

	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		if (EditorInfo.IME_ACTION_DONE == actionId) {
			//Send input owner name and repo name to activity
			EditRepoDialogListener activity = (EditRepoDialogListener) getActivity();
			activity.onFinishEditDialog(editOwner.getText().toString(), editRepo.getText().toString());
			this.dismiss();
			return true;
		}
		return false;
	}
}

Send owner and repo info to enclosing activity when done


class Str2 {
	public static void main (String args[]) {
		String a = "1";
		a += "2";
		System.out.println(a);
		System.out.println("abc".indexOf("", -32));
		System.out.println("abc".indexOf("", 100));
		System.out.println("abc".lastIndexOf("", -32));
		System.out.println("abc".lastIndexOf("", 100));
	}
}

/* Expected Output:
12
0
-1
-1
3
*/

class Str2 {
	public static void main (String args[]) {
		String a = "1";
		a += "2";
		System.out.println(a);
		System.out.println("abc".indexOf("", -99999999));
		System.out.println("abc".indexOf("", 99999999));
		System.out.println("".indexOf("a"));
		System.out.println("".indexOf(""));
		System.out.println("abc".lastIndexOf("", -99999999));
		System.out.println("abc".lastIndexOf("", 99999999));
		System.out.println("".lastIndexOf("a"));
		System.out.println("".lastIndexOf(""));
	}
}

/* Expected Output:
12
0
-1
-1
0
-1
3
-1
0
*/

Add a couple more tests.

Add a couple more tests.


package me.devsaki.hentoid.activities.sources;

import me.devsaki.hentoid.enums.Site;

public class PorncomixActivity extends BaseWebActivity {

    //    private static final String DOMAIN_FILTER = "porncomixonline.net";
    private static final String[] GALLERY_FILTER = {
            "//www.porncomixonline.net/manga/[A-Za-z0-9\\-]+/[A-Za-z0-9\\-]+$",
            "//www.porncomixonline.net/[A-Za-z0-9\\-]+/$",
            "//porncomicszone.net/[0-9]+/[A-Za-z0-9\\-]+/[0-9]+/$",
            "//porncomixinfo.com/manga-comics/[A-Za-z0-9\\-]+/[A-Za-z0-9\\-]+/$",
            "//bestporncomix.com/gallery/[A-Za-z0-9\\-]+/$"
    };

    Site getStartSite() {
        return Site.PORNCOMIX;
    }

    @Override
    protected CustomWebViewClient getWebClient() {
        return new CustomWebViewClient(GALLERY_FILTER, this);
    }
}

package me.devsaki.hentoid.activities.sources;

import me.devsaki.hentoid.enums.Site;

public class PorncomixActivity extends BaseWebActivity {

    //    private static final String DOMAIN_FILTER = "porncomixonline.net";
    private static final String[] GALLERY_FILTER = {
            "//www.porncomixonline.net/manga/[A-Za-z0-9\\-]+/[A-Za-z0-9\\-]+$",
            "//www.porncomixonline.net/[A-Za-z0-9\\-]+/$",
            "//porncomicszone.net/[0-9]+/[A-Za-z0-9\\-]+/[0-9]+/$",
            "//porncomixinfo.com/manga-comics/[A-Za-z0-9\\-]+/[A-Za-z0-9\\-]+/$",
            "//bestporncomix.com/gallery/[A-Za-z0-9\\-]+/$"
    };
    private static final String[] DIRTY_ELEMENTS = {"iframe[name^='spot']"};

    Site getStartSite() {
        return Site.PORNCOMIX;
    }

    @Override
    protected CustomWebViewClient getWebClient() {
        addDirtyElements(DIRTY_ELEMENTS);
        return new CustomWebViewClient(GALLERY_FILTER, this);
    }
}

Remove ads from porncomixonline's main page


/*
 * Copyright (c) 2015 Brocade Communications Systems, Inc. and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */
package org.opendaylight.controller.cluster.notifications;

import java.io.Serializable;

/**
 * A message initiated internally from the RaftActor when some state of a leader has changed
 *
 * @author Thomas Pantelis
 */
public class LeaderStateChanged implements Serializable {
    private static final long serialVersionUID = 1L;

    private final String memberId;
    private final String leaderId;

    public LeaderStateChanged(String memberId, String leaderId) {
        this.memberId = memberId;
        this.leaderId = leaderId;
    }

    public String getMemberId() {
        return memberId;
    }

    public String getLeaderId() {
        return leaderId;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("LeaderStateChanged [memberId=").append(memberId).append(", leaderId=").append(leaderId)
                .append("]");
        return builder.toString();
    }
}

/*
 * Copyright (c) 2015 Brocade Communications Systems, Inc. and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */
package org.opendaylight.controller.cluster.notifications;

import com.google.common.base.Preconditions;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
 * A local message initiated internally from the RaftActor when some state of a leader has changed.
 *
 * @author Thomas Pantelis
 */
public class LeaderStateChanged {
    private final String memberId;
    private final String leaderId;

    public LeaderStateChanged(@Nonnull String memberId, @Nullable String leaderId) {
        this.memberId = Preconditions.checkNotNull(memberId);
        this.leaderId = leaderId;
    }

    public @Nonnull String getMemberId() {
        return memberId;
    }

    public @Nullable String getLeaderId() {
        return leaderId;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("LeaderStateChanged [memberId=").append(memberId).append(", leaderId=").append(leaderId)
                .append("]");
        return builder.toString();
    }
}

Return local shard tree from FindPrimaryShard

Added a new ShardLeaderStateChanged message that includes the Shard's
DataTree as an Optional. If the shard is the leader, it returns it's
local DataTree, oherwise returns absent.

The ShardManager now returns a LocalPrimaryShardFound response to
FindPrimary if the shard's DataTree is present. Otherwise it returns
RemotePrimaryShardFound (renamed from PrimaryFound).

Change-Id: I4413aacfff3d3d2ee89df7c4a3a1d7f7c3d2c486
Signed-off-by: Tom Pantelis <8fc992100aff336363d341c5498f75ab4da389ae@brocade.com>
(cherry picked from commit fdddb482b07c3ee2f3ca853d09ee9a6ecdd7eb2a)


//@@author A0143409J

package seedu.address.logic.parser;

import static org.junit.Assert.assertEquals;
import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;

import java.lang.reflect.Field;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import seedu.address.logic.commands.IncorrectCommand;
import seedu.address.logic.commands.FinishCommand;

public class FinishCommandParserTest {

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void nullTest() throws Exception {
        thrown.expect(NullPointerException.class);
        FinishCommandParser.parse(null);
    }

    @Test
    public void validTest() throws Exception {
        Field field = FinishCommand.class.getDeclaredField("targetIndex");
        field.setAccessible(true);

        FinishCommand finishCommand = (FinishCommand) FinishCommandParser.parse("1");
        assertEquals(field.get(finishCommand), 1);
    }

    @Test
    public void invalidTest() throws Exception {
        Field field = IncorrectCommand.class.getDeclaredField("feedbackToUser");
        field.setAccessible(true);

        IncorrectCommand incorrectCommand = (IncorrectCommand) FinishCommandParser.parse("+");
        assertEquals(field.get(incorrectCommand),
                String.format(MESSAGE_INVALID_COMMAND_FORMAT, FinishCommand.MESSAGE_USAGE));
    }
}

//@@author A0143409J

package seedu.address.logic.parser;

import static org.junit.Assert.assertEquals;
import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;

import java.lang.reflect.Field;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import seedu.address.logic.commands.FinishCommand;
import seedu.address.logic.commands.IncorrectCommand;

public class FinishCommandParserTest {

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void nullTest() throws Exception {
        thrown.expect(NullPointerException.class);
        FinishCommandParser.parse(null);
    }

    @Test
    public void validTest() throws Exception {
        Field field = FinishCommand.class.getDeclaredField("targetIndex");
        field.setAccessible(true);

        FinishCommand finishCommand = (FinishCommand) FinishCommandParser.parse("1");
        assertEquals(field.get(finishCommand), 1);
    }

    @Test
    public void invalidTest() throws Exception {
        Field field = IncorrectCommand.class.getDeclaredField("feedbackToUser");
        field.setAccessible(true);

        IncorrectCommand incorrectCommand = (IncorrectCommand) FinishCommandParser.parse("+");
        assertEquals(field.get(incorrectCommand),
                String.format(MESSAGE_INVALID_COMMAND_FORMAT, FinishCommand.MESSAGE_USAGE));
    }
}

Modify to match lexicographical order

[V0.4][Travis] Modify to match lexicographical order


package com.battlelancer.seriesguide.util;

import android.support.v4.view.ViewPager.OnPageChangeListener;

import net.simonvt.menudrawer.MenuDrawer;

/**
 * {@link OnPageChangeListener} which allows to open a {@link MenuDrawer} by
 * swiping once more to the left if displaying the first page.
 */
public class MenuOnPageChangeListener implements OnPageChangeListener {

    private MenuDrawer mMenuDrawer;

    public MenuOnPageChangeListener(MenuDrawer menuDrawer) {
        mMenuDrawer = menuDrawer;
    }

    @Override
    public void onPageScrollStateChanged(int arg0) {
    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
    }

    @Override
    public void onPageSelected(int position) {
        mMenuDrawer.setTouchMode(position == 0
                ? MenuDrawer.TOUCH_MODE_FULLSCREEN
                : MenuDrawer.TOUCH_MODE_NONE);
    }

}

package com.battlelancer.seriesguide.util;

import android.support.v4.view.ViewPager.OnPageChangeListener;

import net.simonvt.menudrawer.MenuDrawer;

/**
 * {@link OnPageChangeListener} which allows to open a {@link MenuDrawer} by
 * swiping once more to the left if displaying the first page.
 */
public class MenuOnPageChangeListener implements OnPageChangeListener {

    private MenuDrawer mMenuDrawer;

    public MenuOnPageChangeListener(MenuDrawer menuDrawer) {
        mMenuDrawer = menuDrawer;
    }

    @Override
    public void onPageScrollStateChanged(int arg0) {
    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
    }

    @Override
    public void onPageSelected(int position) {
        mMenuDrawer.setTouchMode(position == 0
                ? MenuDrawer.TOUCH_MODE_FULLSCREEN
                : MenuDrawer.TOUCH_MODE_BEZEL);
    }

}

Use bezel touch mode inside view pager.

Use bezel touch mode inside view pager.


package org.apache.ddlutils.platform;

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

import java.io.IOException;

import org.apache.ddlutils.PlatformInfo;
import org.apache.ddlutils.model.Table;

/**
 * The SQL Builder for the HsqlDb database.
 *
 * @author James Strachan
 * @author Thomas Dudziak
 * @version $Revision$
 */
public class HsqlDbBuilder extends SqlBuilder
{
    /**
     * Creates a new builder instance.
     *
     * @param info The platform info
     */
    public HsqlDbBuilder(PlatformInfo info)
    {
        super(info);
    }

    /**
     * {@inheritDoc}
     */
    public void dropTable(Table table) throws IOException
    {
        print("DROP TABLE ");
        printIdentifier(getTableName(table));
        print(" IF EXISTS");
        printEndOfStatement();
    }
}

package org.apache.ddlutils.platform;

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

import java.io.IOException;

import org.apache.ddlutils.PlatformInfo;
import org.apache.ddlutils.model.Table;

/**
 * The SQL Builder for the HsqlDb database.
 *
 * @author James Strachan
 * @author Thomas Dudziak
 * @version $Revision$
 */
public class HsqlDbBuilder extends SqlBuilder
{
    /**
     * Creates a new builder instance.
     *
     * @param info The platform info
     */
    public HsqlDbBuilder(PlatformInfo info)
    {
        super(info);
    }

    /**
     * {@inheritDoc}
     */
    public void dropTable(Table table) throws IOException
    {
        print("DROP TABLE ");
        printIdentifier(getTableName(table));
        print(" IF EXISTS");
        printEndOfStatement();
    }

    /**
     * @see org.apache.ddlutils.platform.SqlBuilder#getSelectLastInsertId(org.apache.ddlutils.model.Table)
     */
    public String getSelectLastInsertId(Table table)
    {
        return "CALL IDENTITY()";
    }

}

Add call identity to hsqldb.

Add call identity to hsqldb.

git-svn-id: 9ba7b058a3825ad085cc988a898da8cc978da7ce@330902 13f79535-47bb-0310-9956-ffa450edef68


package fr.coding.tools;

import android.webkit.HttpAuthHandler;
import android.webkit.WebView;
import java.util.List;
import fr.coding.tools.model.HostAuth;
import fr.coding.tools.model.SslByPass;

/**
 * Created by Matthieu on 03/10/2015.
 */
public class AutoAuthSslWebView extends SslWebView {

    public CallbackResult<HostAuth, HostAuth> AuthAsked;

    protected List<HostAuth> allowedHosts;
    public void setAllowedHosts(List<HostAuth> hosts) {
        allowedHosts = hosts;
    }

    public List<HostAuth> getAllowedHosts() {
        return allowedHosts;
    }

    @Override
    public void onReceivedHttpAuthRequest(WebView webView, HttpAuthHandler handler, String host, String realm) {
        if (allowedHosts != null) {
            for (HostAuth ha :
                    allowedHosts) {
                if (host.equals(ha.Host)) {
                    handler.proceed(ha.Login, ha.Password);
                    return;
                }
            }
        }
        if (AuthAsked != null) {
            HostAuth hostAuth = new HostAuth();
            hostAuth.Host = host;
            HostAuth ret = AuthAsked.onCallback(hostAuth);
            if (ret != null) {
                handler.proceed(ret.Login, ret.Password);
                return;
            }
        }
        super.onReceivedHttpAuthRequest(webView, handler, host, realm);
    }
}

package fr.coding.tools;

import android.webkit.HttpAuthHandler;
import android.webkit.WebView;

import java.util.Date;
import java.util.List;
import fr.coding.tools.model.HostAuth;
import fr.coding.tools.model.SslByPass;

/**
 * Created by Matthieu on 03/10/2015.
 */
public class AutoAuthSslWebView extends SslWebView {

    public CallbackResult<HostAuth, HostAuth> AuthAsked;

    protected List<HostAuth> allowedHosts;
    public void setAllowedHosts(List<HostAuth> hosts) {
        allowedHosts = hosts;
    }

    public List<HostAuth> getAllowedHosts() {
        return allowedHosts;
    }

    public long AutoTestedDate = 0;

    @Override
    public void onReceivedHttpAuthRequest(WebView webView, HttpAuthHandler handler, String host, String realm) {
        if ((allowedHosts != null)&&(AutoTestedDate < (new Date().getTime()-(15000)))) {
            for (HostAuth ha :
                    allowedHosts) {
                if (host.equals(ha.Host)) {
                    AutoTestedDate = new Date().getTime();
                    handler.proceed(ha.Login, ha.Password);
                    return;
                }
            }
        }
        if (AuthAsked != null) {
            HostAuth hostAuth = new HostAuth();
            hostAuth.Host = host;
            HostAuth ret = AuthAsked.onCallback(hostAuth);
            if (ret != null) {
                handler.proceed(ret.Login, ret.Password);
                return;
            }
        }
        super.onReceivedHttpAuthRequest(webView, handler, host, realm);
    }
}

Correct cycling bug when password is updated server side


package org.jetbrains.kotlin.ui.launch;

import org.eclipse.core.expressions.PropertyTester;
import org.eclipse.core.resources.IFile;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.jetbrains.jet.lang.psi.JetFile;
import org.jetbrains.jet.lang.resolve.BindingContext;
import org.jetbrains.jet.plugin.MainFunctionDetector;
import org.jetbrains.kotlin.core.builder.KotlinPsiManager;
import org.jetbrains.kotlin.core.resolve.KotlinAnalyzer;

public class KotlinLaunchableTester extends PropertyTester {
    @Override
    public boolean test(Object receiver, String property, Object[] args, Object expectedValue) {
        if (receiver instanceof IFile) {
            IFile eclipseFile = (IFile) receiver;
            JetFile jetFile = KotlinPsiManager.getKotlinParsedFile(eclipseFile);
            if (jetFile == null) {
                return false;
            }

            IJavaProject javaProject = JavaCore.create(eclipseFile.getProject());
            BindingContext bindingContext = KotlinAnalyzer.analyzeDeclarations(javaProject).getBindingContext();
            return new MainFunctionDetector(bindingContext).hasMain(jetFile.getDeclarations());
        }

        return false;
    }
}

package org.jetbrains.kotlin.ui.launch;

import org.eclipse.core.expressions.PropertyTester;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.jetbrains.jet.lang.psi.JetFile;
import org.jetbrains.jet.lang.resolve.BindingContext;
import org.jetbrains.jet.plugin.MainFunctionDetector;
import org.jetbrains.kotlin.core.builder.KotlinPsiManager;
import org.jetbrains.kotlin.core.resolve.KotlinAnalyzer;

public class KotlinLaunchableTester extends PropertyTester {
    @Override
    public boolean test(Object receiver, String property, Object[] args, Object expectedValue) {
        if (receiver instanceof IAdaptable) {
            IFile file = (IFile) ((IAdaptable) receiver).getAdapter(IFile.class);
            if (file != null) {
                JetFile jetFile = KotlinPsiManager.getKotlinParsedFile(file);
                if (jetFile == null) {
                    return false;
                }

                IJavaProject javaProject = JavaCore.create(file.getProject());
                BindingContext bindingContext = KotlinAnalyzer.analyzeDeclarations(javaProject).getBindingContext();
                return new MainFunctionDetector(bindingContext).hasMain(jetFile.getDeclarations());
            }
        }

        return false;
    }
}

Return ability to launch kotlin from editor


package io.selendroid.server.util;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;

/**
 * A helper class for working with intents
 */
public class Intents {
    /**
     * Create an intent to start an activity, for both ServerInstrumentation and LightweightInstrumentation
     */
    public static Intent createStartActivityIntent(Context context, String mainActivityName) {
        Intent intent = new Intent();
        intent.setClassName(context, mainActivityName);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT
                | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.setAction(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        return intent;
    }

    /**
     * Create an implicit intent based on the given URI.
     */
    public static Intent createUriIntent(String intentUri) {
        return new Intent(Intent.ACTION_VIEW, Uri.parse(intentUri));
    }
}

package io.selendroid.server.util;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;

/**
 * A helper class for working with intents
 */
public class Intents {
    /**
     * Create an intent to start an activity, for both ServerInstrumentation and LightweightInstrumentation
     */
    public static Intent createStartActivityIntent(Context context, String mainActivityName) {
        Intent intent = new Intent();
        intent.setClassName(context, mainActivityName);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT
                | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.setAction(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        return intent;
    }

    /**
     * Create an implicit intent based on the given URI.
     */
    public static Intent createUriIntent(String intentUri) {
        return new Intent(Intent.ACTION_VIEW, Uri.parse(intentUri))
                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT
                        | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    }
}

Add flags to the intent so it is launched correctly.


import java.util.*;
import org.xbill.DNS.*;

public class lookup {

public static void
printAnswer(String name, Lookup lookup) {
	System.out.print(name + ":");
	int result = lookup.getResult();
	if (result != Lookup.SUCCESSFUL)
		System.out.print(" " + lookup.getErrorString());
	System.out.println();
	if (lookup.getResult() == Lookup.SUCCESSFUL) {
		Record [] answers = lookup.getAnswers();
		for (int i = 0; i < answers.length; i++)
			System.out.println(answers[i]);
	}
}

public static void
main(String [] args) throws Exception {
	short type = Type.A;
	int start = 0;
	if (args.length > 2 && args[0].equals("-t")) {
		type = Type.value(args[1]);
		if (type < 0)
			throw new IllegalArgumentException("invalid type");
		start = 2;
	}
	for (int i = start; i < args.length; i++) {
		Lookup l = new Lookup(args[i], type);
		l.run();
		printAnswer(args[i], l);
	}
}

}

import java.util.*;
import org.xbill.DNS.*;

public class lookup {

public static void
printAnswer(String name, Lookup lookup) {
	System.out.print(name + ":");
	int result = lookup.getResult();
	if (result != Lookup.SUCCESSFUL)
		System.out.print(" " + lookup.getErrorString());
	System.out.println();
	Name [] aliases = lookup.getAliases();
	if (aliases.length > 0) {
		System.out.print("# aliases: ");
		for (int i = 0; i < aliases.length; i++) {
			System.out.print(aliases[i]);
			if (i < aliases.length - 1)
				System.out.print(" ");
		}
		System.out.println();
	}
	if (lookup.getResult() == Lookup.SUCCESSFUL) {
		Record [] answers = lookup.getAnswers();
		for (int i = 0; i < answers.length; i++)
			System.out.println(answers[i]);
	}
}

public static void
main(String [] args) throws Exception {
	short type = Type.A;
	int start = 0;
	if (args.length > 2 && args[0].equals("-t")) {
		type = Type.value(args[1]);
		if (type < 0)
			throw new IllegalArgumentException("invalid type");
		start = 2;
	}
	for (int i = start; i < args.length; i++) {
		Lookup l = new Lookup(args[i], type);
		l.run();
		printAnswer(args[i], l);
	}
}

}

Print a list of aliases, if any exist.

Print a list of aliases, if any exist.


package com.axelor.dms.db.repo;

import java.util.Map;

import org.joda.time.LocalDateTime;

import com.axelor.db.JpaRepository;
import com.axelor.dms.db.DMSFile;

public class DMSFileRepository extends JpaRepository<DMSFile> {

	public DMSFileRepository() {
		super(DMSFile.class);
	}

	@Override
	public Map<String, Object> populate(Map<String, Object> json) {
		final Object id = json.get("id");
		if (id == null) {
			return json;
		}
		final DMSFile file = find((Long) id);
		if (file == null) {
			return json;
		}

		boolean isFile = file.getIsDirectory() != Boolean.TRUE;
		LocalDateTime dt = file.getUpdatedOn();
		if (dt == null) {
			dt = file.getCreatedOn();
		}

		json.put("typeIcon", isFile ? "fa fa-file" : "fa fa-folder");
		json.put("lastModified", dt);

		return json;
	}
}

package com.axelor.dms.db.repo;

import java.util.List;
import java.util.Map;

import org.joda.time.LocalDateTime;

import com.axelor.db.JpaRepository;
import com.axelor.dms.db.DMSFile;

public class DMSFileRepository extends JpaRepository<DMSFile> {

	public DMSFileRepository() {
		super(DMSFile.class);
	}

	@Override
	public void remove(DMSFile entity) {
		// remove all children
		if (entity.getIsDirectory() == Boolean.TRUE) {
			final List<DMSFile> children = all().filter("self.parent.id = ?", entity.getId()).fetch();
			for (DMSFile child : children) {
				if (child != entity) {
					remove(child);;
				}
			}
		}
		super.remove(entity);
	}

	@Override
	public Map<String, Object> populate(Map<String, Object> json) {
		final Object id = json.get("id");
		if (id == null) {
			return json;
		}
		final DMSFile file = find((Long) id);
		if (file == null) {
			return json;
		}

		boolean isFile = file.getIsDirectory() != Boolean.TRUE;
		LocalDateTime dt = file.getUpdatedOn();
		if (dt == null) {
			dt = file.getCreatedOn();
		}

		json.put("typeIcon", isFile ? "fa fa-file" : "fa fa-folder");
		json.put("lastModified", dt);

		return json;
	}
}

Delete children when deleting dms folder


package abra;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class Reference {

	private Map<String, StringBuffer> refMap = new HashMap<String, StringBuffer>();

	public Reference(String reference) throws IOException {

		BufferedReader refReader = new BufferedReader(new FileReader(reference));
		String line = refReader.readLine();

		String key = null;
		StringBuffer seq = null;

		while (line != null) {

			if (line.startsWith(">")) {
				if (key != null) {
					refMap.put(key, seq);
				}
				key = line.substring(1, line.length());
				seq = new StringBuffer();
			} else {
				seq.append(line);
			}

			line = refReader.readLine();
		}

		if (key != null) {
			refMap.put(key, seq);
		}

		refReader.close();
	}

	public String getSequence(String chromosome, int position, int length) {
		StringBuffer ref = refMap.get(chromosome);

		if (ref == null) {
			System.out.println("No ref for chromosome: " + chromosome);
		}

		position -= 1;

		return ref.substring(position, Math.min(position + length, ref.length()));
	}
}

package abra;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class Reference {

	private Map<String, StringBuffer> refMap = new HashMap<String, StringBuffer>();

	public Reference(String reference) throws IOException {

		BufferedReader refReader = new BufferedReader(new FileReader(reference));
		String line = refReader.readLine();

		String key = null;
		StringBuffer seq = null;

		while (line != null) {

			if (line.startsWith(">")) {
				if (key != null) {
					refMap.put(key, seq);
				}

				int endIdx = line.indexOf(' ');
				if (endIdx < 0) {
					endIdx = line.length();
				}
				key = line.substring(1, endIdx);
				seq = new StringBuffer();
			} else {
				seq.append(line);
			}

			line = refReader.readLine();
		}

		if (key != null) {
			refMap.put(key, seq);
		}

		refReader.close();
	}

	public String getSequence(String chromosome, int position, int length) {
		StringBuffer ref = refMap.get(chromosome);

		if (ref == null) {
			System.out.println("No ref for chromosome: " + chromosome);
		}

		position -= 1;

		return ref.substring(Math.max(position, 0), Math.min(position + length, ref.length()));
	}
}

Handle reference with description. Don't sub index past beginning of reference sequence.


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

package org.gradle.api.tasks.testing;

import org.gradle.api.reporting.ConfigureableReport;
import org.gradle.api.reporting.DirectoryReport;
import org.gradle.api.reporting.ReportContainer;

/**
 * The reports produced by the {@link Test} task.
 */
public interface TestReports extends ReportContainer<ConfigureableReport> {

    DirectoryReport getHtml();

    DirectoryReport getJunitXml();

}

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

package org.gradle.api.tasks.testing;

import org.gradle.api.reporting.ConfigurableReport;
import org.gradle.api.reporting.DirectoryReport;
import org.gradle.api.reporting.ReportContainer;

/**
 * The reports produced by the {@link Test} task.
 */
public interface TestReports extends ReportContainer<ConfigurableReport> {

    DirectoryReport getHtml();

    DirectoryReport getJunitXml();

}

Fix compile error due to class rename.

Fix compile error due to class rename.


package com.palominolabs.benchpress.worker;

import com.google.inject.AbstractModule;
import com.palominolabs.benchpress.ipc.IpcHttpClientModule;
import com.palominolabs.benchpress.ipc.IpcJsonModule;
import com.palominolabs.benchpress.job.registry.JobRegistryModule;
import com.palominolabs.benchpress.job.task.TaskPluginRegistryModule;
import com.palominolabs.benchpress.task.reporting.TaskProgressClientModule;
import com.palominolabs.benchpress.worker.http.WorkerResourceModule;
import com.palominolabs.benchpress.curator.CuratorModule;
import com.palominolabs.config.ConfigModule;
import com.palominolabs.config.ConfigModuleBuilder;
import org.apache.commons.configuration.SystemConfiguration;

public final class WorkerMainModule extends AbstractModule {
    @Override
    protected void configure() {
        binder().requireExplicitBindings();
        bind(WorkerMain.class);

        install(new WorkerResourceModule());
        install(new ConfigModuleBuilder().addConfiguration(new SystemConfiguration()).build());

        install(new CuratorModule());

        install(new IpcHttpClientModule());
        install(new IpcJsonModule());
        install(new TaskProgressClientModule());
        install(new JobRegistryModule());
        install(new QueueProviderModule());

        bind(PartitionRunner.class);

        ConfigModule.bindConfigBean(binder(), WorkerConfig.class);

        install(new TaskPluginRegistryModule());
    }

}

package com.palominolabs.benchpress.worker;

import com.google.inject.AbstractModule;
import com.palominolabs.benchpress.ipc.IpcHttpClientModule;
import com.palominolabs.benchpress.ipc.IpcJsonModule;
import com.palominolabs.benchpress.jersey.JerseySupportModule;
import com.palominolabs.benchpress.job.registry.JobRegistryModule;
import com.palominolabs.benchpress.job.task.TaskPluginRegistryModule;
import com.palominolabs.benchpress.task.reporting.TaskProgressClientModule;
import com.palominolabs.benchpress.worker.http.WorkerResourceModule;
import com.palominolabs.benchpress.curator.CuratorModule;
import com.palominolabs.config.ConfigModule;
import com.palominolabs.config.ConfigModuleBuilder;
import org.apache.commons.configuration.SystemConfiguration;

public final class WorkerMainModule extends AbstractModule {
    @Override
    protected void configure() {
        binder().requireExplicitBindings();
        bind(WorkerMain.class);

        install(new WorkerResourceModule());
        install(new ConfigModuleBuilder().addConfiguration(new SystemConfiguration()).build());

        install(new CuratorModule());

        install(new JerseySupportModule());

        install(new IpcHttpClientModule());
        install(new IpcJsonModule());
        install(new TaskProgressClientModule());
        install(new JobRegistryModule());
        install(new QueueProviderModule());

        bind(PartitionRunner.class);

        ConfigModule.bindConfigBean(binder(), WorkerConfig.class);

        install(new TaskPluginRegistryModule());
    }

}

Fix worker service: needs jersey binding


package ca.earthgrazer.codereviewer.service;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import ca.earthgrazer.codereviewer.model.ReviewFile;
import ca.earthgrazer.codereviewer.repository.ReviewRepository;

@Service
public class ReviewManagementServiceImpl implements ReviewManagementService {

	@Autowired private ReviewRepository reviewRepo;

	Map<String, List<ReviewFile>> reviewMap = new HashMap<>();

	@Override
	public String createReviewUnit(List<ReviewFile> fileList) {
		return reviewRepo.createReviewUnit(fileList);
	}

	@Override
	public List<ReviewFile> getReviewUnit(String refId) {
		return reviewRepo.getReviewUnit(refId);
	}

}

package ca.earthgrazer.codereviewer.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import ca.earthgrazer.codereviewer.model.ReviewFile;
import ca.earthgrazer.codereviewer.repository.ReviewRepository;

@Service
public class ReviewManagementServiceImpl implements ReviewManagementService {

	@Autowired private ReviewRepository reviewRepo;

	Map<String, List<ReviewFile>> reviewMap = new HashMap<>();

	@Override
	public String createReviewUnit(List<ReviewFile> fileList) {
		// filter out empty files
		List<ReviewFile> filteredList = fileList.stream()
												.filter(f -> !f.fileName.isEmpty() ||
															 !f.fileContent.isEmpty() ||
															 !f.fileDiff.isEmpty() ||
															 !f.fileComment.isEmpty())
												.collect(Collectors.toList());

		return reviewRepo.createReviewUnit(filteredList);
	}

	@Override
	public List<ReviewFile> getReviewUnit(String refId) {
		return reviewRepo.getReviewUnit(refId);
	}

}

Add filtering for empty review files

Add filtering for empty review files

Resolves issue #4


package guitests;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class CommandBoxTest extends TaskBookGuiTest {

    @Test
    public void commandBox_commandSucceeds_textCleared() {
        commandBox.runCommand(td.todo1.getAddCommand());
        assertEquals(commandBox.getCommandInput(), "");
    }

    @Test
    public void commandBox_commandFails_textStays(){
        commandBox.runCommand("invalid command");
        assertEquals(commandBox.getCommandInput(), "invalid command");
        //TODO: confirm the text box color turns to red
    }

}

package guitests;

import org.junit.Test;

import seedu.oneline.testutil.TypicalTestTasks;

import static org.junit.Assert.assertEquals;

public class CommandBoxTest extends TaskBookGuiTest {

    @Test
    public void commandBox_commandSucceeds_textCleared() {
        commandBox.runCommand(TypicalTestTasks.todo1.getAddCommand());
        assertEquals(commandBox.getCommandInput(), "");
    }

    @Test
    public void commandBox_commandFails_textStays(){
        commandBox.runCommand("invalid command");
        assertEquals(commandBox.getCommandInput(), "invalid command");
        //TODO: confirm the text box color turns to red
    }

}

Modify test case to assess fields statically


package com.nirima.jenkins.plugins.docker.utils;

import com.nirima.docker.client.DockerException;
import hudson.model.TaskListener;
import hudson.slaves.ComputerLauncher;
import hudson.slaves.DelegatingComputerLauncher;
import hudson.slaves.SlaveComputer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class RetryingComputerLauncher extends DelegatingComputerLauncher {

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

    /**
     * How many times to retry the launch?
     */
    private final int retries = 3;

    /**
     * time (ms) to back off between retries?
     */
    private final int pause   = 5000;

    public RetryingComputerLauncher(ComputerLauncher delegate) {
        super(delegate);
    }

    @Override
    public void launch(SlaveComputer computer, TaskListener listener) throws IOException, InterruptedException {

        for( int i=0;i<retries;i++) {
            try {
                super.launch(computer, listener);
                return;
            } catch(Exception ex) {
                log.info("Launch failed on attempt {}", i);
            }
            Thread.sleep(pause);
        }
        throw new IOException("SSH Launch failed");
    }
}

package com.nirima.jenkins.plugins.docker.utils;

import com.nirima.docker.client.DockerException;
import hudson.model.TaskListener;
import hudson.slaves.ComputerLauncher;
import hudson.slaves.DelegatingComputerLauncher;
import hudson.slaves.SlaveComputer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class RetryingComputerLauncher extends DelegatingComputerLauncher {

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

    /**
     * time (ms) to back off between retries?
     */
    private final int pause   = 5000;

    /**
     * Let us know when to pause the launch.
     */
    private boolean hasTried = false;

    public RetryingComputerLauncher(ComputerLauncher delegate) {
        super(delegate);
    }

    @Override
    public void launch(SlaveComputer computer, TaskListener listener) throws IOException, InterruptedException {
        if (hasTried) {
            log.info("Launch failed, pausing before retry.");
            Thread.sleep(pause);
        }
        super.launch(computer, listener);
        hasTried = true;
    }
}

Check if we have tried, pause if we have


package hudson.node_monitors;

import org.jvnet.hudson.test.HudsonTestCase;
import hudson.slaves.DumbSlave;
import hudson.slaves.SlaveComputer;
import hudson.util.ClockDifference;
import hudson.util.TimeUnit2;

/**
 * @author Richard Mortimer
 */
public class ClockMonitorDescriptorTest extends HudsonTestCase {
    /**
     * Makes sure that it returns sensible values.
     */
    public void testClockMonitor() throws Exception {
        DumbSlave s = createSlave();
        SlaveComputer c = s.getComputer();
        c.connect(false).get(); // wait until it's connected
        if(c.isOffline())
            fail("Slave failed to go online: "+c.getLog());

        ClockDifference cd = ClockMonitor.DESCRIPTOR.monitor(c);
        long diff = cd.diff;
        assertTrue(diff < TimeUnit2.SECONDS.toMillis(5));
        assertTrue(diff > TimeUnit2.SECONDS.toMillis(-5));
        assertTrue(cd.abs() >= 0);
        assertTrue(cd.abs() < TimeUnit2.SECONDS.toMillis(5));
        assertFalse(cd.isDangerous());
        assertTrue("html output too short", cd.toHtml().length() > 0);
    }
}

package hudson.node_monitors;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import hudson.slaves.DumbSlave;
import hudson.slaves.SlaveComputer;
import hudson.util.ClockDifference;
import hudson.util.TimeUnit2;

import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;

/**
 * @author Richard Mortimer
 */
public class ClockMonitorDescriptorTest {

    @Rule
    public JenkinsRule jenkins = new  JenkinsRule();

    /**
     * Makes sure that it returns sensible values.
     */
    @Test
    public void testClockMonitor() throws Exception {
        DumbSlave s = jenkins.createOnlineSlave();
        SlaveComputer c = s.getComputer();
        if(c.isOffline())
            fail("Slave failed to go online: "+c.getLog());

        ClockDifference cd = ClockMonitor.DESCRIPTOR.monitor(c);
        long diff = cd.diff;
        assertTrue(diff < TimeUnit2.SECONDS.toMillis(5));
        assertTrue(diff > TimeUnit2.SECONDS.toMillis(-5));
        assertTrue(cd.abs() >= 0);
        assertTrue(cd.abs() < TimeUnit2.SECONDS.toMillis(5));
        assertFalse(cd.isDangerous());
        assertTrue("html output too short", cd.toHtml().length() > 0);
    }
}

Use JenkinsRule instead of deprecated HudsonTestCase


package reborncore.mixin.implementations.asmInjector;

import javassist.ByteArrayClassPath;
import javassist.LoaderClassPath;
import reborncore.mixin.MixinManager;
import reborncore.mixin.implementations.prebaker.MixinPrebaker;
import reborncore.mixin.transformer.MixinTransformer;

/**
 * Used by asm injector to load mixins into a jar at build time
 */
public class ASMInjectorSetupClass {

	static {
		MixinManager.logger = System.out::println;
	}

	public static void main() {
		MixinManager.logger = System.out::println;
		MixinManager.logger.log("Loading mixin manager");
		MixinManager.logger.log("Using dummy remapper");
		MixinManager.mixinRemaper = new MixinPrebaker.DummyRemapper();
		MixinManager.load();
	}
	public static void setClassLoader(ClassLoader classLoader) {
		MixinManager.logger = System.out::println;
		MixinManager.logger.log("Setting class loader");
		MixinTransformer.cp.appendClassPath(new LoaderClassPath(classLoader));
	}

	public static void loadClass(String name, byte[] bytes) {
		MixinTransformer.cp.insertClassPath(new ByteArrayClassPath(name, bytes));
		MixinTransformer.preLoadedClasses.add(name);
	}

}

package reborncore.mixin.implementations.asmInjector;

import javassist.ByteArrayClassPath;
import javassist.LoaderClassPath;
import reborncore.mixin.MixinManager;
import reborncore.mixin.implementations.prebaker.MixinPrebaker;
import reborncore.mixin.transformer.MixinTransformer;

/**
 * Used by asm injector to load mixins into a jar at build time
 */
public class ASMInjectorSetupClass {

	public static void main() {
		MixinManager.logger = System.out::println;
		MixinManager.logger.log("Loading mixin manager");
		MixinManager.logger.log("Using dummy remapper");
		MixinManager.mixinRemaper = new MixinPrebaker.DummyRemapper();
		MixinManager.load();
	}
	public static void setClassLoader(ClassLoader classLoader) {
		System.out.println("Setting logger");
		MixinManager.logger = System.out::println;
		MixinManager.logger.log("Setting class loader");
		MixinTransformer.cp.appendClassPath(new LoaderClassPath(classLoader));
	}

	public static void loadClass(String name, byte[] bytes) {
		MixinTransformer.cp.insertClassPath(new ByteArrayClassPath(name, bytes));
		MixinTransformer.preLoadedClasses.add(name);
	}

}

Add some debug code to try and track the issue down


package info.evanchik.maven.project;

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

import org.apache.maven.project.DefaultProjectDependenciesResolver;
import org.apache.maven.project.DependencyResolutionException;
import org.apache.maven.project.DependencyResolutionRequest;
import org.apache.maven.project.DependencyResolutionResult;
import org.apache.maven.project.ProjectDependenciesResolver;

import org.codehaus.plexus.component.annotations.Component;

/**
 * @author Stephen Evanchik
 */
@Component( role = ProjectDependenciesResolver.class )
public class SynchronizedProjectDependenciesResolver extends DefaultProjectDependenciesResolver
{

    private Object lock = new Object();

    public DependencyResolutionResult resolve( DependencyResolutionRequest request )
        throws DependencyResolutionException
    {
        synchronized (lock)
        {
            return super.resolve( request );
        }
    }
}

package info.evanchik.maven.project;

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

import org.apache.maven.project.DefaultProjectDependenciesResolver;
import org.apache.maven.project.DependencyResolutionException;
import org.apache.maven.project.DependencyResolutionRequest;
import org.apache.maven.project.DependencyResolutionResult;
import org.apache.maven.project.ProjectDependenciesResolver;

import org.codehaus.plexus.component.annotations.Component;

/**
 * @author Stephen Evanchik
 */
@Component( role = ProjectDependenciesResolver.class )
public class SynchronizedProjectDependenciesResolver extends DefaultProjectDependenciesResolver
{

    public DependencyResolutionResult resolve( DependencyResolutionRequest request )
        throws DependencyResolutionException
    {
        synchronized ( SynchronizedProjectDependenciesResolver.class )
        {
            return super.resolve( request );
        }
    }
}

Use the .class as the lock

locking: Use the .class as the lock


package org.ethereum.listener;

import org.ethereum.core.*;
import org.ethereum.net.eth.message.StatusMessage;
import org.ethereum.net.message.Message;
import org.ethereum.net.p2p.HelloMessage;
import org.ethereum.net.rlpx.Node;
import org.ethereum.net.server.Channel;
import org.ethereum.vm.program.InternalTransaction;

import java.util.List;
import java.util.Set;

/**
 * @author Roman Mandeleil
 * @since 27.07.2014
 */
public interface EthereumListener {

    enum PendingTransactionState {
        DROPPED,
        PENDING,
        INCLUDED
    }

    void trace(String output);

    void onNodeDiscovered(Node node);

    void onHandShakePeer(Channel channel, HelloMessage helloMessage);

    void onEthStatusUpdated(Channel channel, StatusMessage status);

    void onRecvMessage(Channel channel, Message message);

    void onSendMessage(Channel channel, Message message);

    void onBlock(Block block, List<TransactionReceipt> receipts);

    void onPeerDisconnect(String host, long port);

    void onPendingTransactionsReceived(List<Transaction> transactions);

    void onPendingTransactionUpdate(TransactionReceipt txReceipt, PendingTransactionState state, Block block);

    void onPendingStateChanged(PendingState pendingState);

    void onSyncDone();

    void onNoConnections();

    void onVMTraceCreated(String transactionHash, String trace);

    void onTransactionExecuted(TransactionExecutionSummary summary);

    void onPeerAddedToSyncPool(Channel peer);
}

package org.ethereum.listener;

import org.ethereum.core.*;
import org.ethereum.net.eth.message.StatusMessage;
import org.ethereum.net.message.Message;
import org.ethereum.net.p2p.HelloMessage;
import org.ethereum.net.rlpx.Node;
import org.ethereum.net.server.Channel;
import org.ethereum.vm.program.InternalTransaction;

import java.util.List;
import java.util.Set;

/**
 * @author Roman Mandeleil
 * @since 27.07.2014
 */
public interface EthereumListener {

    enum PendingTransactionState {
        NEW,
        DROPPED,
        PENDING,
        INCLUDED
    }

    void trace(String output);

    void onNodeDiscovered(Node node);

    void onHandShakePeer(Channel channel, HelloMessage helloMessage);

    void onEthStatusUpdated(Channel channel, StatusMessage status);

    void onRecvMessage(Channel channel, Message message);

    void onSendMessage(Channel channel, Message message);

    void onBlock(Block block, List<TransactionReceipt> receipts);

    void onPeerDisconnect(String host, long port);

    void onPendingTransactionsReceived(List<Transaction> transactions);

    void onPendingTransactionUpdate(TransactionReceipt txReceipt, PendingTransactionState state, Block block);

    void onPendingStateChanged(PendingState pendingState);

    void onSyncDone();

    void onNoConnections();

    void onVMTraceCreated(String transactionHash, String trace);

    void onTransactionExecuted(TransactionExecutionSummary summary);

    void onPeerAddedToSyncPool(Channel peer);
}

Add NEW pending tx state

Add NEW pending tx state


import ij.*;
import ij.gui.*;
import ij.process.*;
import ij.plugin.frame.*;
import ij.plugin.filter.*;
import java.awt.*;

public class Cell_Segmentation implements PlugInFilter {

  // External
  public ImagePlus  imp;
  public RoiManager roiMgr;

  public int setup(String arg, ImagePlus imp) {
    this.imp = imp;

    // Open ROI Manager
    roiMgr = RoiManager.getInstance();
    if (roiMgr == null)
      roiMgr = new RoiManager();

    return DOES_ALL;
  }

  public void run(ImageProcessor ip) {
    // Put this line to validate
    ip.invert();
  }

}

import ij.*;
import ij.gui.*;
import ij.process.*;
import ij.plugin.frame.*;
import ij.plugin.filter.*;
import java.awt.*;

public class Cell_Segmentation implements PlugInFilter {

  // External
  public RoiManager     roiMgr;
  public ImagePlus      imp;
  public ImageProcessor ip;

  public int setup(String arg, ImagePlus imp) {
    // Open ROI Manager
    roiMgr = RoiManager.getInstance();
    if (roiMgr == null)
    roiMgr = new RoiManager();

    return DOES_ALL;
  }

  public void run(ImageProcessor ip) {
    // Create a copy in Gray8 format
    create_gray8_copy(ip);
  }

  public void create_gray8_copy(ImageProcessor _ip) {
    ip = _ip.convertToByte(true);
    imp = new ImagePlus("Cell Segmentation", ip);
    imp.show();
    imp.updateAndDraw();
  }

}

Create a copy in Gray8 format

Create a copy in Gray8 format


package editor.serialization;

import java.lang.reflect.Type;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

import editor.database.card.Card;
import editor.gui.MainFrame;

/**
 * A JSON serializer and deserializer for {@link Card} using its
 * {@link Card#multiverseid()}.  Since this doesn't serialize the fields of
 * Card itself, it is intended to be used to serialize structures containing
 * them after the database has been loaded.
 *
 * @author Alec Roelke
 */
public class CardAdapter implements JsonSerializer<Card>, JsonDeserializer<Card>
{
    @Override
    public Card deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
    {
        if (MainFrame.inventory().contains(json.getAsLong()))
            return MainFrame.inventory().get(json.getAsLong());
        else
            throw new JsonParseException("no card with multiverseid " + json.getAsLong() + " exists");
    }

    @Override
    public JsonElement serialize(Card src, Type typeOfSrc, JsonSerializationContext context)
    {
        return new JsonPrimitive(src.multiverseid().get(0));
    }

}

package editor.serialization;

import java.lang.reflect.Type;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

import editor.database.card.Card;
import editor.gui.MainFrame;

/**
 * A JSON serializer and deserializer for {@link Card} using its
 * {@link Card#multiverseid()}.  Since this doesn't serialize the fields of
 * Card itself, it is intended to be used to serialize structures containing
 * them after the database has been loaded.
 *
 * @author Alec Roelke
 */
public class CardAdapter implements JsonSerializer<Card>, JsonDeserializer<Card>
{
    @Override
    public Card deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
    {
        JsonObject obj = json.getAsJsonObject();

        long multiverseid = obj.get("multiverseid").getAsLong();

        if (MainFrame.inventory().contains(multiverseid))
            return MainFrame.inventory().get(multiverseid);
        else
            throw new JsonParseException("no card with multiverseid " + multiverseid + " exists");
    }

    @Override
    public JsonElement serialize(Card src, Type typeOfSrc, JsonSerializationContext context)
    {
        JsonObject card = new JsonObject();
        card.addProperty("multiverseid", src.multiverseid().get(0));
        card.addProperty("name", src.unifiedName());
        card.addProperty("expansion", src.expansion().name);
        return card;
    }

}

Add more fields for IDing cards

Add more fields for IDing cards

They aren't used yet; still just multiverseid


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package hudson.plugins.emailext;

import java.util.Collection;
import java.util.Collections;

import hudson.Extension;
import hudson.model.AbstractProject;
import hudson.model.Action;
import hudson.model.TransientProjectActionFactory;

/**
 *
 * @author acearl
 */
@Extension
public class EmailExtTemplateActionFactory extends TransientProjectActionFactory {

    @Override
    public Collection<? extends Action> createFor(AbstractProject target) {
        boolean hasEmailExt = false;
        for(Object p : target.getPublishersList()) {
            if(p instanceof ExtendedEmailPublisher) {
                hasEmailExt = true;
                break;
            }
        }

        if(hasEmailExt) {
            return Collections.singletonList(new EmailExtTemplateAction(target));
        }
        return Collections.EMPTY_LIST;
    }
}

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package hudson.plugins.emailext;

import java.util.Collection;
import java.util.Collections;

import hudson.Extension;
import hudson.model.AbstractProject;
import hudson.model.Action;
import hudson.model.TransientProjectActionFactory;

/**
 *
 * @author acearl
 */
@Extension
public class EmailExtTemplateActionFactory extends TransientProjectActionFactory {

    @Override
    public Collection<? extends Action> createFor(AbstractProject target) {
        boolean hasEmailExt = false;
        if (target.getPublishersList() != null) {
            for(Object p : target.getPublishersList()) {
                if(p instanceof ExtendedEmailPublisher) {
                    hasEmailExt = true;
                    break;
                }
            }
        }

        if(hasEmailExt) {
            return Collections.singletonList(new EmailExtTemplateAction(target));
        }
        return Collections.EMPTY_LIST;
    }
}

[JENKINS-25940] Add workaround to prevent NPE in Maven projects


package me.nithanim.mmf4j;

import io.netty.buffer.ByteBuf;
import io.netty.util.CharsetUtil;
import java.io.IOException;

public class Main {
    public static void main(String[] args) throws IOException {
        MemoryMap mm = MemoryMapFactory.getInstance();
        mm.openFile("./test.txt");
        mm.openMapping(1000);
        ByteBuf b = mm.mapView(20, 30);
        b.writeBytes("Hallo".getBytes(CharsetUtil.UTF_8));
        //mm.truncateFile(30);
        b.writerIndex(0);
        b.writeBytes("World".getBytes(CharsetUtil.UTF_8));
        b.setBytes(0, "Java".getBytes(CharsetUtil.UTF_8));

        ByteBuf c = b.copy();
        c.setBytes(0, "AAAA".getBytes(CharsetUtil.UTF_8));

        byte[] bytes = new byte[5];
        b.getBytes(0, bytes);
        System.out.println(new String(bytes, CharsetUtil.UTF_8));

        b.release();
        mm.truncateFile(25);
        mm.resize(50);
        mm.close();
    }
}

package me.nithanim.mmf4j;

import com.sun.jna.Platform;
import io.netty.buffer.ByteBuf;
import io.netty.util.CharsetUtil;
import java.io.IOException;

public class Main {
    public static void main(String[] args) throws IOException {
        MemoryMap mm = MemoryMapFactory.getInstance();
        mm.openFile(Platform.isWindows() ? "./test.txt" : "~/test.txt");
        mm.openMapping(1000);
        ByteBuf b = mm.mapView(20, 30);
        b.writeBytes("Hallo".getBytes(CharsetUtil.UTF_8));
        //mm.truncateFile(30);
        b.writerIndex(0);
        b.writeBytes("World".getBytes(CharsetUtil.UTF_8));
        b.setBytes(0, "Java".getBytes(CharsetUtil.UTF_8));

        ByteBuf c = b.copy();
        c.setBytes(0, "AAAA".getBytes(CharsetUtil.UTF_8));

        byte[] bytes = new byte[5];
        b.getBytes(0, bytes);
        System.out.println(new String(bytes, CharsetUtil.UTF_8));

        b.release();
        mm.truncateFile(25);
        mm.resize(50);
        mm.close();
    }
}

Fix for my test environment for linux

Fix for my test environment for linux


package protocolsupport.protocol.packet.middleimpl.serverbound.play.v_6_7;

import io.netty.buffer.ByteBuf;
import protocolsupport.protocol.packet.middle.serverbound.play.MiddleEntityAction;
import protocolsupport.utils.CollectionsUtils.ArrayMap;

public class EntityAction extends MiddleEntityAction {

	private static final ArrayMap<Action> actionById = new ArrayMap<>(
		new ArrayMap.Entry<>(1, Action.START_SNEAK), new ArrayMap.Entry<>(2, Action.STOP_SNEAK),
		new ArrayMap.Entry<>(3, Action.LEAVE_BED),
		new ArrayMap.Entry<>(4, Action.START_SPRINT), new ArrayMap.Entry<>(5, Action.STOP_SPRINT),
		new ArrayMap.Entry<>(6, Action.STOP_JUMP) //this won't work now anyway, but still map it
	);

	@Override
	public void readFromClientData(ByteBuf clientdata) {
		entityId = clientdata.readInt();
		action = actionById.get(clientdata.readByte());
		jumpBoost = clientdata.readInt();
	}

}

package protocolsupport.protocol.packet.middleimpl.serverbound.play.v_6_7;

import io.netty.buffer.ByteBuf;
import protocolsupport.protocol.packet.middle.serverbound.play.MiddleEntityAction;
import protocolsupport.utils.CollectionsUtils.ArrayMap;

public class EntityAction extends MiddleEntityAction {

	private static final ArrayMap<Action> actionById = new ArrayMap<>(
		new ArrayMap.Entry<>(1, Action.START_SNEAK), new ArrayMap.Entry<>(2, Action.STOP_SNEAK),
		new ArrayMap.Entry<>(3, Action.LEAVE_BED),
		new ArrayMap.Entry<>(4, Action.START_SPRINT), new ArrayMap.Entry<>(5, Action.STOP_SPRINT),
		new ArrayMap.Entry<>(6, Action.STOP_JUMP),
		new ArrayMap.Entry<>(7, Action.OPEN_HORSE_INV)
	);

	@Override
	public void readFromClientData(ByteBuf clientdata) {
		entityId = clientdata.readInt();
		action = actionById.get(clientdata.readByte());
		jumpBoost = clientdata.readInt();
	}

}

Add missing entity action mapping for horse inventory open for 1.6-1.7


// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.athenz.client.zms.bindings;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;

import java.util.List;

/**
 * @author olaa
 */
@JsonIgnoreProperties(ignoreUnknown = true)
public class PolicyEntity {

    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    private final List<AssertionEntity> assertions;
    private final String name;

    public PolicyEntity(@JsonProperty("name") String name,
                        @JsonProperty("assertions") List<AssertionEntity> assertions) {
        this.name = name;
        this.assertions = assertions;
    }

    public String getName() {
        return name;
    }

    public List<AssertionEntity> getAssertions() {
        return assertions;
    }
}

// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.athenz.client.zms.bindings;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author olaa
 */
@JsonIgnoreProperties(ignoreUnknown = true)
public class PolicyEntity {
    private static final Pattern namePattern = Pattern.compile("^(?<domain>[^:]+):policy\\.(?<name>.*)$");

    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    private final List<AssertionEntity> assertions;
    private final String name;

    public PolicyEntity(@JsonProperty("name") String name,
                        @JsonProperty("assertions") List<AssertionEntity> assertions) {
        this.name = nameFromResourceString(name);
        this.assertions = assertions;
    }

    private static String nameFromResourceString(String resource) {
        Matcher matcher = namePattern.matcher(resource);
        if (!matcher.matches())
            throw new IllegalArgumentException("Could not find policy name from resource string: " + resource);
        return matcher.group("name");
    }

    public String getName() {
        return name;
    }

    public List<AssertionEntity> getAssertions() {
        return assertions;
    }
}

Read policy from resource name

Read policy from resource name


package com.pr0gramm.app.ui.base;

import android.support.annotation.NonNull;

import com.pr0gramm.app.util.BackgroundScheduler;
import com.trello.rxlifecycle.LifecycleTransformer;

import rx.Completable;
import rx.Observable;
import rx.Single;
import rx.android.schedulers.AndroidSchedulers;

/**
 */
class AsyncLifecycleTransformer<T> implements LifecycleTransformer<T> {
    private final LifecycleTransformer<T> transformer;

    AsyncLifecycleTransformer(LifecycleTransformer<T> transformer) {
        this.transformer = transformer;
    }

    @NonNull
    @Override
    public <U> Single.Transformer<U, U> forSingle() {
        return single -> single.toObservable().compose((Observable.Transformer) this).toSingle();
    }

    @NonNull
    @Override
    public Completable.Transformer forCompletable() {
        return completable -> completable.<T>toObservable().compose(this).toCompletable();
    }

    @Override
    public Observable<T> call(Observable<T> observable) {
        return observable
                .subscribeOn(BackgroundScheduler.instance())
                .unsubscribeOn(BackgroundScheduler.instance())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(transformer);
    }
}

package com.pr0gramm.app.ui.base;

import android.support.annotation.NonNull;

import com.pr0gramm.app.util.BackgroundScheduler;
import com.trello.rxlifecycle.LifecycleTransformer;

import rx.Completable;
import rx.Observable;
import rx.Single;
import rx.android.schedulers.AndroidSchedulers;

/**
 */
class AsyncLifecycleTransformer<T> implements LifecycleTransformer<T> {
    private final LifecycleTransformer<T> transformer;

    AsyncLifecycleTransformer(LifecycleTransformer<T> transformer) {
        this.transformer = transformer;
    }

    @NonNull
    @Override
    public <U> Single.Transformer<U, U> forSingle() {
        return single -> single
                .subscribeOn(BackgroundScheduler.instance())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(transformer.forSingle());
    }

    @NonNull
    @Override
    public Completable.Transformer forCompletable() {
        return completable -> completable
                .subscribeOn(BackgroundScheduler.instance())
                .unsubscribeOn(BackgroundScheduler.instance())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(transformer.forCompletable());
    }

    @Override
    public Observable<T> call(Observable<T> observable) {
        return observable
                .subscribeOn(BackgroundScheduler.instance())
                .unsubscribeOn(BackgroundScheduler.instance())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(transformer);
    }
}

Remove redundant single -> observable -> single transformation


/*
 * MIT Licence
 * Copyright (c) 2017 Simon Frankenberger
 *
 * Please see LICENCE.md for complete licence text.
 */
package eu.fraho.spring.securityJwt.hibernate.dto;

import lombok.*;

import javax.persistence.*;
import java.time.ZonedDateTime;

@Entity
@Table(name = "jwt_refresh")
@Getter
@Setter
@EqualsAndHashCode(of = {"userId", "username", "token"})
@ToString(of = {"id", "userId", "username", "token"})
@NoArgsConstructor
public class RefreshTokenEntity {
    @Id
    @GeneratedValue
    @Setter(AccessLevel.NONE)
    private Long id = 0L;

    @Column(updatable = false)
    @Setter(AccessLevel.NONE)
    @Convert(converter = ZonedDateTimeConverter.class)
    private ZonedDateTime created = ZonedDateTime.now();

    private Long userId;

    private String username;

    @Column(unique = true)
    private String token;

    @Builder
    private RefreshTokenEntity(Long userId, String username, String token) {
        this.userId = userId;
        this.username = username;
        this.token = token;
    }
}

/*
 * MIT Licence
 * Copyright (c) 2017 Simon Frankenberger
 *
 * Please see LICENCE.md for complete licence text.
 */
package eu.fraho.spring.securityJwt.hibernate.dto;

import lombok.*;

import javax.persistence.*;
import java.time.ZonedDateTime;

@Entity
@Table(name = "jwt_refresh")
@Getter
@Setter
@EqualsAndHashCode(of = {"userId", "username", "token"})
@ToString(of = {"id", "userId", "username", "token"})
@NoArgsConstructor
public class RefreshTokenEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Setter(AccessLevel.NONE)
    private Long id = 0L;

    @Column(updatable = false)
    @Setter(AccessLevel.NONE)
    @Convert(converter = ZonedDateTimeConverter.class)
    private ZonedDateTime created = ZonedDateTime.now();

    private Long userId;

    private String username;

    @Column(unique = true)
    private String token;

    @Builder
    private RefreshTokenEntity(Long userId, String username, String token) {
        this.userId = userId;
        this.username = username;
        this.token = token;
    }
}

Use IDENTITY as strategy for entity

hibernate: Use IDENTITY as strategy for entity


/*
 * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
 * (the "License"). You may not use this work except in compliance with the License, which is
 * available at www.apache.org/licenses/LICENSE-2.0
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied, as more fully set forth in the License.
 *
 * See the NOTICE file distributed with this work for information regarding copyright ownership.
 */

package alluxio.util;

import alluxio.Constants;

import java.io.File;
import java.io.FileFilter;

import javax.annotation.concurrent.ThreadSafe;

/**
 * Utility functions for working with extensions.
 */
@ThreadSafe
public final class ExtensionUtils {

  private static final File[] EMPTY_EXTENSIONS_LIST = new File[0];

  /**
   * List extension jars from the configured extensions directory.
   *
   * @param extensionDir the directory containing extensions
   * @return an array of files (one file per jar)
   */
  public static File[] listExtensions(String extensionDir) {
    File[] extensions = new File(extensionDir).listFiles(new FileFilter() {
      public boolean accept(File file) {
        return file.getPath().toLowerCase().endsWith(Constants.EXTENSION_JAR);
      }
    });
    if (extensions == null) {
      // Directory does not exist
      return EMPTY_EXTENSIONS_LIST;
    }
    return extensions;
  }

  private ExtensionUtils() {} // prevent instantiation
}

/*
 * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
 * (the "License"). You may not use this work except in compliance with the License, which is
 * available at www.apache.org/licenses/LICENSE-2.0
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied, as more fully set forth in the License.
 *
 * See the NOTICE file distributed with this work for information regarding copyright ownership.
 */

package alluxio.util;

import alluxio.Constants;

import java.io.File;

import javax.annotation.concurrent.ThreadSafe;

/**
 * Utility functions for working with extensions.
 */
@ThreadSafe
public final class ExtensionUtils {

  private static final File[] EMPTY_EXTENSIONS_LIST = new File[0];

  /**
   * List extension jars from the configured extensions directory.
   *
   * @param extensionDir the directory containing extensions
   * @return an array of files (one file per jar)
   */
  public static File[] listExtensions(String extensionDir) {
    File[] extensions = new File(extensionDir)
        .listFiles(file -> file.getPath().toLowerCase().endsWith(Constants.EXTENSION_JAR));
    if (extensions == null) {
      // Directory does not exist
      return EMPTY_EXTENSIONS_LIST;
    }
    return extensions;
  }

  private ExtensionUtils() {} // prevent instantiation
}

Replace anonymous type with lambda

[SMALLFIX] Replace anonymous type with lambda

Java 8 Improvement: replace anonymous type with lambda in
alluxio/core/common/src/main/java/alluxio/util/ExtensionUtils.java#listExtensions

pr-link: Alluxio/alluxio#8651
change-id: cid-c2f89e9233c853cdf9b027254a33aa93f9297217


/*
 * Copyright 2011 James Moger.
 *
 * 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.iciql;

/**
 * Iciql constants.
 */
public class Constants {

	public static final String NAME = "iciql";

	// The build script extracts this exact line so be careful editing it
	// and only use A-Z a-z 0-9 .-_ in the string.
	public static final String VERSION = "1.0.0";

	// The build script extracts this exact line so be careful editing it
	// and only use A-Z a-z 0-9 .-_ in the string.
	public static final String VERSION_DATE = "2012-07-14";

	// The build script extracts this exact line so be careful editing it
	// and only use A-Z a-z 0-9 .-_ in the string.
	public static final String API_CURRENT = "15";

}

/*
 * Copyright 2011 James Moger.
 *
 * 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.iciql;

/**
 * Iciql constants.
 */
public class Constants {

	public static final String NAME = "iciql";

	// The build script extracts this exact line so be careful editing it
	// and only use A-Z a-z 0-9 .-_ in the string.
	public static final String VERSION = "1.0.1-SNAPSHOT";

	// The build script extracts this exact line so be careful editing it
	// and only use A-Z a-z 0-9 .-_ in the string.
	public static final String VERSION_DATE = "PENDING";

	// The build script extracts this exact line so be careful editing it
	// and only use A-Z a-z 0-9 .-_ in the string.
	public static final String API_CURRENT = "15";

}

Reset build identifiers for next release


/**
 * This package contains mock implementations of the OSGi framework
 * similar to what's found in Apache Sling OSGi mocks
 * and in Spring OSGi mocks.
 *
 *
The implemented classes implement basic service registration, and retrieval,
 * service notification and callback registration.
 */
/**
 * @author Steinar Bang
 *
 */
package no.steria.osgi.mocks;

/**
 * This package contains mock implementations of the OSGi framework
 * similar to what's found in Apache Sling OSGi mocks
 * and in Spring OSGi mocks.
 *
 *
The implemented classes implement basic service registration, and retrieval,
 * service notification and callback registration.
 *
 * @author Steinar Bang
 *
 */
package no.steria.osgi.mocks;

Make package description show up in javadoc.


package com.proxerme.library.parameters;

import android.support.annotation.IntDef;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Class of the SeasonParameter. This includes the possible yearly seasons.
 *
 * @author Desnoo
 */
public final class SeasonParameter {

    public static final int WINTER = 1;
    public static final int SPRING = 2;
    public static final int SUMMER = 3;
    public static final int AUTUMN = 4;

    private SeasonParameter() {
    }

    /**
     * An annotation that represents the possible season.
     */
    @IntDef({SPRING, SUMMER, AUTUMN, WINTER})
    @Retention(value = RetentionPolicy.SOURCE)
    @Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})
    public @interface SeasonConstraint {
    }
}

package com.proxerme.library.parameters;

import android.support.annotation.IntDef;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Class of the SeasonParameter. This includes the possible yearly seasons.
 *
 * @author Desnoo
 */
public final class SeasonParameter {

    public static final int WINTER = 1;
    public static final int SPRING = 2;
    public static final int SUMMER = 3;
    public static final int AUTUMN = 4;
    public static final int UNSPECIFIED = 5;

    private SeasonParameter() {
    }

    /**
     * An annotation that represents the possible season.
     */
    @IntDef({SPRING, SUMMER, AUTUMN, WINTER, UNSPECIFIED})
    @Retention(value = RetentionPolicy.SOURCE)
    @Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})
    public @interface SeasonConstraint {
    }
}

Add UNSPECIFIED to the seasons. For example present in Test123 MOVIE


/*
 * JBoss, Home of Professional Open Source
 * Copyright 2010, Red Hat, Inc., and individual contributors
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * 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.jboss.weld.tests.enterprise;

import javax.ejb.Stateless;

@Stateless
public class Castle {

    private boolean pinged;

    public boolean isPinged() {
        return pinged;
    }

    public void ping() {
        this.pinged = true;
    }

}

/*
 * JBoss, Home of Professional Open Source
 * Copyright 2010, Red Hat, Inc., and individual contributors
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * 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.jboss.weld.tests.enterprise;

import javax.ejb.Stateful;

@Stateful
public class Castle {

    private boolean pinged;

    public boolean isPinged() {
        return pinged;
    }

    public void ping() {
        this.pinged = true;
    }

}

Change EnterpriseBeanTest not to rely on @Stateless beans preserving state


package forklift.consumer;

public enum ProcessStep {
	Pending,
	Validating,
	Invalid,
	Processing,
	Error,
	Complete
}

package forklift.consumer;

public enum ProcessStep {
	Pending,
	Validating,
	Invalid,
	Processing,
	Retrying,
	Error,
	Complete
}

Add the retrying process step to indicate a message is being attempted for the nth time.


package jenkins.util;

import org.junit.Test;

import java.util.concurrent.TimeUnit;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;

import static jenkins.util.TimeDuration.*;

public class TimeDurationTest {

    @Test
    public void fromString() throws Exception {
        assertEquals(1, TimeDuration.fromString("1").getTimeInMillis());

        assertEquals(1000, TimeDuration.fromString("1sec").getTimeInMillis());
        assertEquals(1000, TimeDuration.fromString("1secs").getTimeInMillis());
        assertEquals(1000, TimeDuration.fromString("1 secs ").getTimeInMillis());
        assertEquals(1000, TimeDuration.fromString(" 1 secs ").getTimeInMillis());
        assertEquals(1, TimeDuration.fromString(" 1 secs ").getTimeInSeconds());

        assertEquals(21000, TimeDuration.fromString(" 21  secs ").getTimeInMillis());
        assertEquals(21, TimeDuration.fromString(" 21  secs ").getTimeInSeconds());
    }

}

package jenkins.util;

import org.junit.Test;
import org.jvnet.hudson.test.Issue;

import java.util.concurrent.TimeUnit;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;

import static jenkins.util.TimeDuration.*;

@Issue("JENKINS-44052")
public class TimeDurationTest {

    @Test
    public void fromString() throws Exception {
        assertEquals(1, TimeDuration.fromString("1").getTimeInMillis());

        assertEquals(1000, TimeDuration.fromString("1sec").getTimeInMillis());
        assertEquals(1000, TimeDuration.fromString("1secs").getTimeInMillis());
        assertEquals(1000, TimeDuration.fromString("1 secs ").getTimeInMillis());
        assertEquals(1000, TimeDuration.fromString(" 1 secs ").getTimeInMillis());
        assertEquals(1, TimeDuration.fromString(" 1 secs ").getTimeInSeconds());

        assertEquals(21000, TimeDuration.fromString(" 21  secs ").getTimeInMillis());
        assertEquals(21, TimeDuration.fromString(" 21  secs ").getTimeInSeconds());
    }

}

Add @Issue to reference JENKINS-44052

Add @Issue to reference JENKINS-44052


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

import static org.junit.jupiter.api.condition.OS.LINUX;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.openqa.selenium.firefox.FirefoxDriver;

import io.github.bonigarcia.wdm.test.base.VersionTestParent;

/**
 * Test asserting Firefox versions.
 *
 * @author Boni Garcia
 * @since 1.5.0
 */
@EnabledOnOs(LINUX)
class FirefoxVersionTest extends VersionTestParent {

    @BeforeEach
    void setup() {
        driverClass = FirefoxDriver.class;
        specificVersions = new String[] { "0.8.0", "0.19.1" };
    }

}

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

import static org.junit.jupiter.api.condition.OS.LINUX;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.openqa.selenium.firefox.FirefoxDriver;

import io.github.bonigarcia.wdm.test.base.VersionTestParent;

/**
 * Test asserting Firefox versions.
 *
 * @author Boni Garcia
 * @since 1.5.0
 */
@EnabledOnOs(LINUX)
class FirefoxVersionTest extends VersionTestParent {

    @BeforeEach
    void setup() {
        driverClass = FirefoxDriver.class;
        specificVersions = new String[] { "0.20.0", "0.29.0" };
    }

}

Update geckodriver versions in test

Update geckodriver versions in test


package org.ebayopensource.fidouaf.stats;

public class Info {
	public String description = "Example UAF server";
	public String regRequestEndpoint = "/fidouaf/v1/public/regRequest/{user}";
	public String regResponseEndpoint = "/fidouaf/v1/public/regResponse";
	public String authRequestEndpoint = "/fidouaf/v1/public/authRequest";
	public String authResponseEndpoint = "/fidouaf/v1/public/authResponse";
	public String whitelistuuidEndpoint = "/fidouaf/v1/whitelistuuid/{ure_encodedd_uuid}";
	public String whitelistfacetidEndpoint = "/fidouaf/v1/whitelistfacetid/{url_encoded_facedid}";
	public String historyEndpoint = "/fidouaf/v1/hystory";
	public String registrationsEndpoint = "/fidouaf/v1/registrations";
}

package org.ebayopensource.fidouaf.stats;

public class Info {
	public String description = "Example UAF server";
	public String regRequestEndpoint = "/fidouaf/v1/public/regRequest/{user}";
	public String regResponseEndpoint = "/fidouaf/v1/public/regResponse";
	public String authRequestEndpoint = "/fidouaf/v1/public/authRequest";
	public String authResponseEndpoint = "/fidouaf/v1/public/authResponse";
	public String whitelistuuidEndpoint = "/fidouaf/v1/whitelistuuid/{ure_encodedd_uuid}";
	public String whitelistfacetidEndpoint = "/fidouaf/v1/whitelistfacetid/{url_encoded_facedid}";
	public String historyEndpoint = "/fidouaf/v1/history";
	public String registrationsEndpoint = "/fidouaf/v1/registrations";
}

Correct typo for history endpoint

Correct typo for history endpoint


package com.sensirion.libble.devices;

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

public enum KnownDevices {

    /**
     * Devices that returns Humidity and Temperature data.
     * Notification interface: {@link com.sensirion.libble.listeners.services.RHTListener}
     */
    RHT_GADGETS {
        @Override
        public List<String> getAdvertisedNames() {
            final List<String> deviceNames = new ArrayList<>(4);
            deviceNames.add("SHTC1 smart gadget"); // Official device name is not capitalized like the following one.
            deviceNames.add("SHT31 Smart Gadget");
            deviceNames.add("Smart Humigadget");
            deviceNames.add("SensorTag");
            return deviceNames;
        }
    };

    /**
     * Returns a {@link java.util.List} of {@link java.lang.String} of the valid advertised names of the gadget.
     *
     * @return {@link java.util.List} with the advertised names of compatible devices.
     */
    @SuppressWarnings("unused")
    public abstract List<String> getAdvertisedNames();
}

package com.sensirion.libble.devices;

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

public enum KnownDevices {

    /**
     * Devices that returns Humidity and Temperature data.
     * Notification interface: {@link com.sensirion.libble.listeners.services.RHTListener}
     */
    RHT_GADGETS {
        @Override
        public List<String> getAdvertisedNames() {
            final List<String> deviceNames = new ArrayList<>(4);
            deviceNames.add("SHTC1 smart gadget"); // Official device name is not capitalized like the following one.
            deviceNames.add("SHT31 Smart Gadget");
            deviceNames.add("Smart Humigadget");
            deviceNames.add("SensorTag");
            return deviceNames;
        }
    },

    /**
     * Devices that returns Temperature data.
     * Notification interface: {@link com.sensirion.libble.listeners.services.TemperatureListener}
     */
    TEMPERATURE_GADGETS {
        @Override
        public List<String> getAdvertisedNames() {
            return RHT_GADGETS.getAdvertisedNames();
        }
    },

    /**
     * Devices that returns Humidity data.
     * Notification interface: {@link com.sensirion.libble.listeners.services.HumidityListener}
     */
    HUMIDITY_GADGETS {
        @Override
        public List<String> getAdvertisedNames() {
            return RHT_GADGETS.getAdvertisedNames();
        }
    };

    /**
     * Returns a {@link java.util.List} of {@link java.lang.String} of the valid advertised names of the gadget.
     *
     * @return {@link java.util.List} with the advertised names of compatible devices.
     */
    @SuppressWarnings("unused")
    public abstract List<String> getAdvertisedNames();
}

Add RHT gadgets to Known Devices

Add RHT gadgets to Known Devices

Change-Id: Ib83f04b07cd27ff9e2dbf0bdbf5d66016352b6ee


package com.cube.storm.ui.model.property;

import android.os.Parcel;

import lombok.Getter;

/**
 * Text property class. This class has a content string which can either be a language coded string
 * or a string. If a language manager is set, the string is replaced with it's lookup equivalent from
 * the language manager, else it is left. Do not set a language manager to disable this behaviour.
 *
 * @author Callum Taylor
 * @project LightningUi
 */
public class TextProperty extends Property
{
	@Getter protected String content;

	@Override public int describeContents()
	{
		return 0;
	}

	@Override public void writeToParcel(Parcel dest, int flags)
	{

	}
}

package com.cube.storm.ui.model.property;

import android.os.Parcel;

import lombok.Getter;

/**
 * Text property class. This class has a content string which can either be a language coded string
 * or a string. If a language manager is set, the string is replaced with it's lookup equivalent from
 * the language manager, else it is left. Do not set a language manager to disable this behaviour.
 *
 * @author Callum Taylor
 * @project LightningUi
 */
public class TextProperty extends Property
{
	@Getter public String content;

	@Override public int describeContents()
	{
		return 0;
	}

	@Override public void writeToParcel(Parcel dest, int flags)
	{

	}
}

Make 'content' public until future merge of property constructors


package com.trello.navi;

import com.trello.navi.internal.NaviEmitter;
import org.junit.Test;

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

public class EventHandlingTest {
  @Test public void handlesEventsNone() {
    NaviComponent component = NaviEmitter.createActivityEmitter();
    assertTrue(component.handlesEvents());
  }

  @Test public void handlesEventsSingle() {
    NaviComponent component = NaviEmitter.createActivityEmitter();
    assertTrue(component.handlesEvents(Event.CREATE));
    assertFalse(component.handlesEvents(Event.CREATE_VIEW));
  }

  @Test public void handlesEventsMultiple() {
    NaviComponent component = NaviEmitter.createActivityEmitter();
    assertTrue(component.handlesEvents(Event.CREATE, Event.START, Event.RESUME));
    assertFalse(component.handlesEvents(Event.ATTACH, Event.CREATE_VIEW));
    assertFalse(component.handlesEvents(Event.CREATE, Event.CREATE_VIEW));
  }
}

package com.trello.navi;

import com.trello.navi.internal.NaviEmitter;
import org.junit.Test;

import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
import static org.mockito.Mockito.mock;

public class EventHandlingTest {
  @Test public void handlesEventsNone() {
    NaviComponent component = NaviEmitter.createActivityEmitter();
    assertTrue(component.handlesEvents());
  }

  @Test public void handlesEventsSingle() {
    NaviComponent component = NaviEmitter.createActivityEmitter();
    assertTrue(component.handlesEvents(Event.CREATE));
    assertFalse(component.handlesEvents(Event.CREATE_VIEW));
  }

  @Test public void handlesEventsMultiple() {
    NaviComponent component = NaviEmitter.createActivityEmitter();
    assertTrue(component.handlesEvents(Event.CREATE, Event.START, Event.RESUME));
    assertFalse(component.handlesEvents(Event.ATTACH, Event.CREATE_VIEW));
    assertFalse(component.handlesEvents(Event.CREATE, Event.CREATE_VIEW));
  }

  @Test(expected = IllegalArgumentException.class) public void throwOnRemoveUnsupportedListener()
      throws Exception {
    final NaviEmitter emitter = NaviEmitter.createActivityEmitter();
    emitter.removeListener(Event.DETACH, mock(Listener.class));
  }

  @Test(expected = IllegalArgumentException.class) public void throwOnAddUnsupportedListener()
      throws Exception {
    final NaviEmitter emitter = NaviEmitter.createActivityEmitter();
    emitter.addListener(Event.DETACH, mock(Listener.class));
  }
}

Add Tests for Exception when adding/removing a listener for an unsupported event


/*
 * Copyright 2019 Google LLC
 *
 * 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
 *
 *     https://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.google.android.gnd.persistence.local.room;

import androidx.room.Dao;
import androidx.room.Query;
import io.reactivex.Completable;
import io.reactivex.Single;
import java.util.List;

/** Data access object for database operations related to {@link ObservationMutationEntity}. */
@Dao
public interface ObservationMutationDao extends BaseDao<ObservationMutationEntity> {

  @Query("DELETE FROM observation_mutation WHERE id IN (:ids)")
  Completable deleteAll(List<Long> ids);

  @Query("SELECT * FROM observation_mutation WHERE observation_id = :featureId")
  Single<List<ObservationMutationEntity>> findByFeatureId(String featureId);

  @Query("SELECT * FROM observation_mutation WHERE observation_id = :observationId")
  Single<List<ObservationMutationEntity>> findByObservationId(String observationId);
}

/*
 * Copyright 2019 Google LLC
 *
 * 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
 *
 *     https://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.google.android.gnd.persistence.local.room;

import androidx.room.Dao;
import androidx.room.Query;
import io.reactivex.Completable;
import io.reactivex.Single;
import java.util.List;

/** Data access object for database operations related to {@link ObservationMutationEntity}. */
@Dao
public interface ObservationMutationDao extends BaseDao<ObservationMutationEntity> {

  @Query("DELETE FROM observation_mutation WHERE id IN (:ids)")
  Completable deleteAll(List<Long> ids);

  @Query("SELECT * FROM observation_mutation WHERE feature_id = :featureId")
  Single<List<ObservationMutationEntity>> findByFeatureId(String featureId);

  @Query("SELECT * FROM observation_mutation WHERE observation_id = :observationId")
  Single<List<ObservationMutationEntity>> findByObservationId(String observationId);
}

Fix incorrect observation mutation DAO query