package com.github.aureliano.achmed.os.service;

import org.apache.log4j.Logger;

import com.github.aureliano.achmed.command.CommandFacade;
import com.github.aureliano.achmed.command.CommandResponse;

public class RedHatService extends LinuxService {

	private static final Logger logger = Logger.getLogger(RedHatService.class);
	private static final String SERVICE = "/sbin/service";

	public RedHatService() {
		super();
	}

	@Override
	public boolean isRunning() {
		if ((super.properties.getHasStatus() != null) && (super.properties.getHasStatus())) {
			CommandResponse res = CommandFacade.executeCommand(SERVICE, super.properties.getName(), "status");
			return (res.getExitStatusCode() == 0);
		}

		return super.isRunning();
	}

	@Override
	public CommandResponse enableBootstrap() {
		throw new UnsupportedOperationException("Not implemented yet.");
	}

	@Override
	public CommandResponse disableBootstrap() {
		throw new UnsupportedOperationException("Not implemented yet.");
	}

	@Override
	public boolean isEnabledInBootstrap() {
		throw new UnsupportedOperationException("Not implemented yet.");
	}
}

package com.github.aureliano.achmed.os.service;

import org.apache.log4j.Logger;

import com.github.aureliano.achmed.command.CommandFacade;
import com.github.aureliano.achmed.command.CommandResponse;
import com.github.aureliano.achmed.helper.StringHelper;

public class RedHatService extends LinuxService {

	private static final Logger logger = Logger.getLogger(RedHatService.class);
	private static final String SERVICE = "/sbin/service";

	public RedHatService() {
		super();
	}

	@Override
	public CommandResponse start() {
		if (this.isRunning()) {
			logger.debug("Service " + super.properties.getName() + " is already running.");
			return null;
		}

		if (StringHelper.isEmpty(super.properties.getBinary())) {
			return CommandFacade.executeCommand(SERVICE, super.properties.getName(), "start");
		}

		return super.start();
	}

	@Override
	public boolean isRunning() {
		if ((super.properties.getHasStatus() != null) && (super.properties.getHasStatus())) {
			CommandResponse res = CommandFacade.executeCommand(SERVICE, super.properties.getName(), "status");
			return (res.getExitStatusCode() == 0);
		}

		return super.isRunning();
	}

	@Override
	public CommandResponse enableBootstrap() {
		throw new UnsupportedOperationException("Not implemented yet.");
	}

	@Override
	public CommandResponse disableBootstrap() {
		throw new UnsupportedOperationException("Not implemented yet.");
	}

	@Override
	public boolean isEnabledInBootstrap() {
		throw new UnsupportedOperationException("Not implemented yet.");
	}
}

Implement method to start service.

Implement method to start service.


// NEC Labs America Inc. CONFIDENTIAL

package com.necla.am.zwutils;

import com.necla.am.zwutils.Misc.Versioning;

public class _Namespace {

	public static final String PRODUCT = "ZWUtils - Jack of All Trades Utility Libraries";
	public static final String COMPONENT = "ZWUtils for Java";
	public static final String VERSION = "@VERSION@";
	public static final String BUILD = "@DATE@ @TIME@";

	static {
		Versioning.Namespace_Init(_Namespace.class);
	}

}

// NEC Labs America Inc. CONFIDENTIAL

package com.necla.am.zwutils;

import com.necla.am.zwutils.Misc.Versioning;

public class _Namespace {

	public static final String PRODUCT = "ZWUtils - Jack of All Trades Utility Libraries";
	public static final String COMPONENT = "ZWUtils for Java";
	public static final String VERSION = "@VERSION@".toString();
	public static final String BUILD = "@DATE@ @TIME@".toString();

	static {
		Versioning.Namespace_Init(_Namespace.class);
	}

}

Improve namespace programmatic access in Eclipse debug mode


/**
 * Waffle (https://github.com/dblock/waffle)
 *
 * Copyright (c) 2010 - 2014 Application Security, Inc.
 *
 * 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
 *
 * Contributors:
 *     Application Security, Inc.
 */
/**
 * Nothing for now, but in the future, this would include:
 *
 * org/eclipse/jetty/security/Authenticator.java

 * org/eclipse/jetty/security/LoginService.java

 */
package waffle.jetty;

/**
 * Waffle (https://github.com/dblock/waffle)
 *
 * Copyright (c) 2010 - 2014 Application Security, Inc.
 *
 * 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
 *
 * Contributors:
 *     Application Security, Inc.
 */
/**
 * Nothing for now, but in the future, this would include:
 *
 *

 *  org/eclipse/jetty/security/Authenticator.java
 *

 *

 *  org/eclipse/jetty/security/LoginService.java
 *

 */
package waffle.jetty;

Fix jetty javadocs so jdk8 builds work.

Fix jetty javadocs so jdk8 builds work.


package com.suse.salt.netapi.datatypes.target;

/**
 * Possible values for the tgt_type or expr_form parameter in salt netapi calls.
 */
public enum TargetType {

    GLOB("glob"),
    PCRE("pcre"),
    LIST("list"),
    GRAIN("grain"),
    GRAIN_PCRE("grain_pcre"),
    PILLAR("pillar"),
    PILLAR_PCRE("pillar_pcre"),
    NODEGROUP("nodegroup"),
    RANGE("range"),
    COMPOUND("compound"),
    IPCIDR("ipcidr");

    private final String value;

    TargetType(String value) { this.value = value; }

    public String getValue() { return value; }
}

package com.suse.salt.netapi.datatypes.target;

/**
 * Possible values for the tgt_type or expr_form parameter in salt netapi calls.
 */
public enum TargetType {

    GLOB("glob"),
    PCRE("pcre"),
    LIST("list"),
    GRAIN("grain"),
    GRAIN_PCRE("grain_pcre"),
    PILLAR("pillar"),
    PILLAR_EXACT("pillar_exact"),
    PILLAR_PCRE("pillar_pcre"),
    NODEGROUP("nodegroup"),
    RANGE("range"),
    COMPOUND("compound"),
    IPCIDR("ipcidr"),
    DATA("data");

    private final String value;

    TargetType(String value) { this.value = value; }

    public String getValue() { return value; }
}

Add missing match types: data and pillar_exact


package net.hexogendev.hexogen.api.network;

import net.hexogendev.hexogen.api.Server;
import net.hexogendev.hexogen.api.entity.alive.player.Player;
import net.hexogendev.hexogen.api.world.Position;

public interface NetworkServer {

	public Server getServer();

	public Object getProtocolServer();

	public int getPort();

	public String getHostAddress();

	public void sendPacketForAll(IPacket packet);

	public void sendPacketDistance(Position pos, IPacket packet, int radius);

	public void sendPacketForAllExpect(IPacket packet, Player expect);

	public void sendPacketDistanceExpect(Position pos, IPacket packet, int radius, Player expect);

	public void shutdown();

}

package net.hexogendev.hexogen.api.network;

import net.hexogendev.hexogen.api.Server;
import net.hexogendev.hexogen.api.entity.alive.player.Player;
import net.hexogendev.hexogen.api.world.Position;
import net.hexogendev.hexogen.api.world.World;

public interface NetworkServer {

	public Server getServer();

	public Object getProtocolServer();

	public int getPort();

	public String getHostAddress();

	public void sendPacketForAll(IPacket packet);

	public void sendPacketForAll(World world, IPacket packet);

	public void sendPacketForAllExpect(IPacket packet, Player expect);

	public void sendPacketForAllExpect(World world, IPacket packet, Player expect);

	public void sendPacketDistance(Position pos, IPacket packet, int radius);

	public void sendPacketDistanceExpect(Position pos, IPacket packet, int radius, Player expect);

	public void shutdown();

}

Add sendPacket for world players

Add sendPacket for world players


/**
 * License Agreement for Jaeksoft OpenSearchServer
 *
 * Copyright (C) 2011 Emmanuel Keller / Jaeksoft
 *
 * http://www.open-search-server.com
 *
 * This file is part of Jaeksoft OpenSearchServer.
 *
 * Jaeksoft OpenSearchServer is free software: you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 * Jaeksoft OpenSearchServer is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with Jaeksoft OpenSearchServer.
 *  If not, see <http://www.gnu.org/licenses/>.
 **/

package com.jaeksoft.searchlib.index;

import com.jaeksoft.searchlib.schema.Schema;

public interface BeforeUpdateInterface {

	public void update(Schema schema, IndexDocument document);
}

/**
 * License Agreement for Jaeksoft OpenSearchServer
 *
 * Copyright (C) 2011 Emmanuel Keller / Jaeksoft
 *
 * http://www.open-search-server.com
 *
 * This file is part of Jaeksoft OpenSearchServer.
 *
 * Jaeksoft OpenSearchServer is free software: you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 * Jaeksoft OpenSearchServer is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with Jaeksoft OpenSearchServer.
 *  If not, see <http://www.gnu.org/licenses/>.
 **/

package com.jaeksoft.searchlib.index;

import com.jaeksoft.searchlib.SearchLibException;
import com.jaeksoft.searchlib.schema.Schema;

public interface BeforeUpdateInterface {

	public void update(Schema schema, IndexDocument document)
			throws SearchLibException;
}

Add beforeupdate interface to writer

Add beforeupdate interface to writer


/*
 * Copyright 2015 Ryan Gilera.
 *
 * 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.github.daytron.revworks.data;

/**
 * Collection of exception messages.
 *
 * @author Ryan Gilera
 */
public enum ExceptionMsg {

    AUTHENTICATION_EXCEPTION_NO_USER("No such user found. Invalid credentials."),
    AUTHENTICATION_EXCEPTION_SYS_ERROR("System error occured "),
    NO_CURRENT_USER_EXCEPTION("No user is login"),
    WRONG_CURRENT_USER_TYPE_EXCEPTION("Wrong user type access."),
    EMPTY_SQL_RESULT("Empty SQL query result.");
    private final String msg;

    private ExceptionMsg(String msg) {
        this.msg = msg;
    }

    public String getMsg() {
        return msg;
    }

}

/*
 * Copyright 2015 Ryan Gilera.
 *
 * 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.github.daytron.revworks.data;

/**
 * Collection of exception messages.
 *
 * @author Ryan Gilera
 */
public enum ExceptionMsg {

    AUTHENTICATION_EXCEPTION_NO_USER("No such user found. Invalid credentials."),
    AUTHENTICATION_EXCEPTION_SYS_ERROR("System error occured "),
    NO_CURRENT_USER_EXCEPTION("No user is login"),
    WRONG_CURRENT_USER_TYPE_EXCEPTION("Wrong user type access."),
    EMPTY_SQL_RESULT("Empty SQL query result."),
    SQL_ERROR_CONNECTION("SQL: Related connection service failed."),
    SQL_NO_RESULT_FOUND("SQL: The last query resulted to empty set."),
    SQL_ERROR_QUERY("SQL: Error query action.");
    private final String msg;

    private ExceptionMsg(String msg) {
        this.msg = msg;
    }

    public String getMsg() {
        return msg;
    }

}

Add custom exception messages for the new exceptions created


package com.pedro.fizzbuzz;

/**
 *
 * FizzBuzzMachine it's a little piece of software created to return a String value if some of the next conditions
 * occurs.
 *
 * If the integer passed as argument it's equals to 3 or multiple of 3 FizzBuzzMachine returns Fizz.
 * If the integer passed as argument it's equals to 5 or multiple of 5 FizzBuzzMachine returns Buzz.
 * If the integer passed as argument it's multiple of 3 and 5 FizzBuzzMachine returns FizzBuzz.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class FizzBuzzMachine {

}

package com.pedro.fizzbuzz;

/**
 *
 * FizzBuzzMachine it's a little piece of software created to return a String value if some of the next conditions
 * occurs.
 *
 * If the integer passed as argument it's equals to 3 or multiple of 3 FizzBuzzMachine returns Fizz.
 * If the integer passed as argument it's equals to 5 or multiple of 5 FizzBuzzMachine returns Buzz.
 * If the integer passed as argument it's multiple of 3 and 5 FizzBuzzMachine returns FizzBuzz.
 * If the integer passed as argument isn't multiple of 3 or 5 returns the number.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class FizzBuzzMachine {

    /**
     * Main FizzBuzzMachine method. This method will check if the number passed as parameter is fulfilling the condition
     * and will return the Fizz, Buzz or FizzBuzz value.
     *
     * @param value to analyze.
     * @return
     *      Fizz if the value is multiple of 3
     *      Buzz if the value is multiple of 5
     *      FizzBuzz if the value is multiple of 3 and 5
     *      the value if the parameter isn't multiple of 3 or 5
     */
    public String execute(int value) {
        return null;
    }
}

Add the default case to the documentation


// Copyright 2014, Kevin Ko <kevin@faveset.com>

package com.faveset.khttp;

class HttpRequest {
    public enum Method {
        OPTIONS,
        GET,
        HEAD,
        POST,
        PUT,
        DELETE,
        TRACE,
        CONNECT
    }

    private Method mMethod;

    private String mUri;

    public HttpRequest() {}

    public Method getMethod() {
        return mMethod;
    }

    public String getUri() {
        return mUri;
    }

    public void setMethod(Method method) {
        mMethod = method;
    }

    public void setUri(String uri) {
        mUri = uri;
    }
}

// Copyright 2014, Kevin Ko <kevin@faveset.com>

package com.faveset.khttp;

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

class HttpRequest {
    public enum Method {
        OPTIONS,
        GET,
        HEAD,
        POST,
        PUT,
        DELETE,
        TRACE,
        CONNECT
    }

    private Method mMethod;

    private String mUri;

    private HashMap<String, List<String>> mHeaders;

    public HttpRequest() {
        mHeaders = new HashMap<String, List<String>>();
    }

    /**
     * Appends value to the mapping list for name, creating a mapping if
     * necessary.
     */
    public void appendHeader(String name, String value) {
        List<String> l = mHeaders.get(name);
        if (l == null) {
            l = new ArrayList<String>();
            mHeaders.put(name, l);
        }

        l.add(value);
    }

    public void clearHeaders() {
        mHeaders.clear();
    }

    /**
     * @return The list of values for the header named name or null if it
     * doesn't exist.  The returned list will always have non-zero length.
     */
    public List<String> getHeader(String name) {
        return mHeaders.get(name);
    }

    /**
     * Convenience method for returning the first header value or null if no
     * mapping exists.
     */
    public String getHeaderFirst(String name) {
        List<String> l = mHeaders.get(name);
        if (l == null) {
            return null;
        }
        return l.get(0);
    }

    public Method getMethod() {
        return mMethod;
    }

    public String getUri() {
        return mUri;
    }

    /**
     * Assigns value to the mapping for name.  This clears any existing list
     * values.
     */
    public void setHeader(String name, String value) {
        List<String> l = new ArrayList<String>();
        l.add(value);

        mHeaders.put(name, l);
    }

    /**
     * Assigns value to the mapping for name.  This overwrites any existing
     * mapping.
     */
    public void setHeaderList(String name, List<String> values) {
        mHeaders.put(name, values);
    }

    public void setMethod(Method method) {
        mMethod = method;
    }

    public void setUri(String uri) {
        mUri = uri;
    }
}

Add header storage and manipulation methods.


package net.stack3.buttonsample;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

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

        Button button1 = (Button)findViewById(R.id.normal_button);
        button1.setOnClickListener(normalButtonOnClickListener);
    }

    private OnClickListener normalButtonOnClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            Button button1 = (Button)v;
            button1.setText(R.string.clicked);
        }
    };

}

package net.stack3.buttonsample;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

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

        Button normalButton = (Button)findViewById(R.id.normal_button);
        normalButton.setOnClickListener(normalButtonOnClickListener);
    }

    private OnClickListener normalButtonOnClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            Button normalButton = (Button)v;
            normalButton.setText(R.string.clicked);
        }
    };

}

Rename variable button1 to normalButton.


package bestcoders.library.services.helpers;

import java.util.stream.Stream;

import bestcoders.library.Library;
import bestcoders.library.loans.LoanRecord;
import bestcoders.library.loans.LoanState;
import bestcoders.library.members.LibraryMember;

public class LibraryStreams {

    private final Library library;

    public LibraryStreams(final Library library) {
	this.library = library;
    }

    public Stream<LoanRecord> getLoansForMember(final Stream<LoanRecord> s, final LibraryMember m) {
	return s.filter(lr -> lr.getMember().equals(m));
    }

    Stream<LoanRecord> getLoansStream() {
	return library.getLoans().stream();
    }

    public Stream<LoanRecord> getOpenLoansStream() {
	return getLoansStream().filter(lr -> lr.getState() == LoanState.OPEN);
    }

}

package bestcoders.library.services.helpers;

import java.util.stream.Stream;

import bestcoders.library.Library;
import bestcoders.library.loans.LoanRecord;
import bestcoders.library.loans.LoanState;
import bestcoders.library.members.LibraryMember;

public class LibraryStreams {

    private final Library library;

    public LibraryStreams(final Library library) {
	this.library = library;
    }

    public Stream<LoanRecord> getLoansForMember(final Stream<LoanRecord> s, final LibraryMember m) {
	return s.filter(lr -> lr != null && lr.getMember().equals(m));
    }

    Stream<LoanRecord> getLoansStream() {
	return library.getLoans().stream();
    }

    public Stream<LoanRecord> getOpenLoansStream() {
	return getLoansStream().filter(lr -> lr != null && lr.getState() == LoanState.OPEN);
    }

}

Add null protection for loan records.

Add null protection for loan records.

Intermittent issue with null loan records being logged.


package org.sphinx;

import org.sphinx.api.ISphinxClient;
import org.sphinx.api.SphinxResult;
import org.sphinx.pool.PooledSphinxDataSource;
import org.testng.annotations.Test;

import static org.testng.Assert.*;

/**
 * SphinxQueryTest
 *
 * @author Brian Cowdery
 * @since 29-05-2015
 */
@Test(enabled = false, description = "Live integration test, not part of automated test suite.")
public class SphinxQueryTest {

    @Test
    public void testSphinxQuery() throws Exception {
        PooledSphinxDataSource dataSource = new PooledSphinxDataSource();
        dataSource.setHost("190.10.14.168");
        dataSource.setPort(9312);
        dataSource.setTestOnBorrow(true);
        dataSource.setTestOnReturn(true);
        dataSource.setMinIdle(0);
        dataSource.setMaxIdle(8);
        dataSource.setMaxTotal(8);

        ISphinxClient client = dataSource.getSphinxClient();
        assertNotNull(client);

        SphinxResult result = client.Query("SELECT name, postdate FROM releases WHERE MATCH('Futurama')");
        assertNotNull(result);
    }
}

package org.sphinx;

import org.sphinx.api.ISphinxClient;
import org.sphinx.api.SphinxResult;
import org.sphinx.pool.PooledSphinxDataSource;
import org.testng.annotations.Test;

import static org.testng.Assert.*;

/**
 * SphinxQueryTest
 *
 * @author Brian Cowdery
 * @since 29-05-2015
 */
@Test(enabled = false, description = "Live integration test, not part of automated test suite.")
public class SphinxQueryTest {
/*
    @Test
    public void testSphinxQuery() throws Exception {
        PooledSphinxDataSource dataSource = new PooledSphinxDataSource();
        dataSource.setHost("190.10.14.168");
        dataSource.setPort(9312);
        dataSource.setTestOnBorrow(true);
        dataSource.setTestOnReturn(true);
        dataSource.setMinIdle(0);
        dataSource.setMaxIdle(8);
        dataSource.setMaxTotal(8);

        ISphinxClient client = dataSource.getSphinxClient();
        assertNotNull(client);

        SphinxResult result = client.Query("SELECT name, postdate FROM releases WHERE MATCH('Futurama')");
        assertNotNull(result);
    }
*/
}

Comment out sphinx test. maven is ignoring eanbled=false


package se.vandmo.textchecker.maven;

import static java.util.Arrays.asList;

import java.io.File;
import java.util.Collection;

import se.vandmo.textchecker.maven.rules.ConsistentLineSeparator;
import se.vandmo.textchecker.maven.rules.EndsWithLineSeparator;
import se.vandmo.textchecker.maven.rules.NoTabs;
import se.vandmo.textchecker.maven.rules.NoTrailingWhitespaceOnNonBlankLines;
import se.vandmo.textchecker.maven.rules.NoWhitespaceOnBlankLines;
import se.vandmo.textchecker.maven.rules.NotExecutable;

public final class RulesResolver {

  public Collection<Rule> getRulesFor(File file) {
    return asList(
      new NoTabs(),
      new NoTrailingWhitespaceOnNonBlankLines(),
      new NoWhitespaceOnBlankLines(),
      new NotExecutable(),
      new ConsistentLineSeparator(),
      new EndsWithLineSeparator());
  }

}

package se.vandmo.textchecker.maven;

import static java.util.Arrays.asList;

import java.io.File;
import java.util.Collection;

import se.vandmo.textchecker.maven.rules.ConsistentLineSeparator;
import se.vandmo.textchecker.maven.rules.EndsWithLineSeparator;
import se.vandmo.textchecker.maven.rules.NoTabs;
import se.vandmo.textchecker.maven.rules.NoTrailingWhitespaceOnNonBlankLines;
import se.vandmo.textchecker.maven.rules.NoWhitespaceOnBlankLines;

public final class RulesResolver {

  public Collection<Rule> getRulesFor(File file) {
    return asList(
      new NoTabs(),
      new NoTrailingWhitespaceOnNonBlankLines(),
      new NoWhitespaceOnBlankLines(),
      new ConsistentLineSeparator(),
      new EndsWithLineSeparator());
  }

}

Remove NotExecutable check, bad on Windows


package com.thaiopensource.resolver;

import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.io.IOException;

/**
 *
 */
public class BasicResolver implements Resolver {
  static private final BasicResolver theInstance = new BasicResolver();

  protected BasicResolver() {
  }

  public static BasicResolver getInstance() {
    return theInstance;
  }

  public void resolve(Identifier id, Input input) throws IOException, ResolverException {
    if (!input.isResolved())
      input.setUri(resolveUri(id));
  }

  public void open(Input input) throws IOException, ResolverException {
    if (!input.isUriDefinitive())
      return;
    URI uri;
    try {
      uri = new URI(input.getUri());
    }
    catch (URISyntaxException e) {
      throw new ResolverException(e);
    }
    if (!uri.isAbsolute())
      throw new ResolverException("cannot open relative URI: " + uri);
    URL url = new URL(uri.toASCIIString());
    // XXX should set the encoding properly
    input.setByteStream(url.openStream());
  }

  public static String resolveUri(Identifier id) throws ResolverException {
    try {
      URI uri = new URI(id.getUriReference());
      String base = id.getBase();
      if (base != null)
        uri = new URI(base).resolve(uri);
      return uri.toString();
    }
    catch (URISyntaxException e) {
      throw new ResolverException(e);
    }
  }
}

package com.thaiopensource.resolver;

import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.io.IOException;

/**
 *
 */
public class BasicResolver implements Resolver {
  static private final BasicResolver theInstance = new BasicResolver();

  protected BasicResolver() {
  }

  public static BasicResolver getInstance() {
    return theInstance;
  }

  public void resolve(Identifier id, Input input) throws IOException, ResolverException {
    if (!input.isResolved())
      input.setUri(resolveUri(id));
  }

  public void open(Input input) throws IOException, ResolverException {
    if (!input.isUriDefinitive())
      return;
    URI uri;
    try {
      uri = new URI(input.getUri());
    }
    catch (URISyntaxException e) {
      throw new ResolverException(e);
    }
    if (!uri.isAbsolute())
      throw new ResolverException("cannot open relative URI: " + uri);
    URL url = new URL(uri.toASCIIString());
    // XXX should set the encoding properly
    // XXX if this is HTTP and we've been redirected, should do input.setURI with the new URI
    input.setByteStream(url.openStream());
  }

  public static String resolveUri(Identifier id) throws ResolverException {
    try {
      URI uri = new URI(id.getUriReference());
      String base = id.getBase();
      if (base != null)
        uri = new URI(base).resolve(uri);
      return uri.toString();
    }
    catch (URISyntaxException e) {
      throw new ResolverException(e);
    }
  }
}

Add note that we need to handle HTTP redirection


package com.seoz.sunshine;

import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * A placeholder fragment containing a simple view.
 */
public class MainActivityFragment extends Fragment {

    public MainActivityFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_main, container, false);
    }
}

package com.seoz.sunshine;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

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

/**
 * A placeholder fragment containing a simple view.
 */
public class MainActivityFragment extends Fragment {

    ArrayAdapter<String> mForecastAdapter;

    public MainActivityFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_main, container, false);

        String[] data = {
                "Mon 6/23 - Sunny - 31/17",
                "Tue 6/24 - Foggy - 21/8",
                "Wed 6/25 - Cloudy - 22/17",
                "Thurs 6/26 - Rainy - 18/11",
                "Fri 6/27 - Foggy - 21/10",
                "Sat 6/28 - TRAPPED IN WEATHERSTATION - 23/18",
                "Sun 6/29 - Sunny - 20/7"
        };
        List<String> weekForecast = new ArrayList<String>(Arrays.asList(data));

        ArrayAdapter<String> mForecastAdapter =
                new ArrayAdapter<String>(
                        getActivity(), // The current context (this activity)
                        R.layout.list_item_forecast, // The name of the layout ID.
                        R.id.list_item_forecast_textview, // The ID of the textview to populate.
                        weekForecast);

        // Get a reference to the ListView, and attach this adapter to it.
        ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast);
        listView.setAdapter(mForecastAdapter);

        return rootView;
    }
}

Add a ListView with dummy data.

Sunshine/MainActivity: Add a ListView with dummy data.


package com.fasterxml.jackson.databind.node;

import com.fasterxml.jackson.databind.*;

public class TestJsonPointer
    extends BaseMapTest
{
    // !!! TODO
}

package com.fasterxml.jackson.databind.node;

import com.fasterxml.jackson.databind.*;

public class TestJsonPointer
    extends BaseMapTest
{
    // !!! TODO
    public void testIt() { }
}

Add a bogus method in otherwise empty test, to prevent build breakage


package com.infonuascape.osrshelper.tracker.rt;

import com.infonuascape.osrshelper.tracker.TrackerTimeEnum;
import com.infonuascape.osrshelper.utils.exceptions.ParserErrorException;
import com.infonuascape.osrshelper.utils.exceptions.PlayerNotFoundException;
import com.infonuascape.osrshelper.utils.players.PlayerSkills;

public class TrackerHelper {
	String userName = null;

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getUserName() {
		return userName;
	}

	public PlayerSkills getPlayerStats() throws PlayerNotFoundException, ParserErrorException {
		TrackerFetcher tf = new TrackerFetcher(getUserName(), TrackerTimeEnum.TrackerTime.Day);
		return tf.getPlayerTracker();
	}

	public PlayerSkills getPlayerStats(TrackerTimeEnum.TrackerTime time) throws PlayerNotFoundException,
			ParserErrorException {
		TrackerFetcher tf = new TrackerFetcher(getUserName(), time);
		return tf.getPlayerTracker();
	}

}

package com.infonuascape.osrshelper.tracker.rt;

import com.infonuascape.osrshelper.tracker.TrackerTimeEnum;
import com.infonuascape.osrshelper.utils.exceptions.APIError;
import com.infonuascape.osrshelper.utils.exceptions.ParserErrorException;
import com.infonuascape.osrshelper.utils.exceptions.PlayerNotFoundException;
import com.infonuascape.osrshelper.utils.players.PlayerSkills;

public class TrackerHelper {
	String userName = null;

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getUserName() {
		return userName;
	}

	public PlayerSkills getPlayerStats() throws PlayerNotFoundException, ParserErrorException, APIError {
		TrackerFetcher tf = new TrackerFetcher(getUserName(), TrackerTimeEnum.TrackerTime.Day);
		return tf.getPlayerTracker();
	}

	public PlayerSkills getPlayerStats(TrackerTimeEnum.TrackerTime time) throws PlayerNotFoundException,
			ParserErrorException, APIError {
		TrackerFetcher tf = new TrackerFetcher(getUserName(), time);
		return tf.getPlayerTracker();
	}

}

Use APIError over ParseError to display proper errors


package ch.ethz.scu.obit.common.version;

public class VersionInfo {

	// Program version
	public static final String version = "0.5.8";

	// Version status: "alpha", "beta", or "" for a stable release
	public static final String status = "";

	// Copyright string
	public static final String copyright = "Copyright " +
			Character.toString('\u00A9') +
			" 2012 - 2015, Single Cell Unit, " +
			"D-BSSE, ETH Zurich (Basel)";

	// Properties (XML) file version
	public static final int propertiesVersion = 4;

}

package ch.ethz.scu.obit.common.version;

public class VersionInfo {

	// Program version
	public static final String version = "0.6.0";

	// Version status: "alpha", "beta", or "" for a stable release
	public static final String status = "beta";

	// Copyright string
	public static final String copyright = "Copyright " +
			Character.toString('\u00A9') +
			" 2012 - 2015, Single Cell Unit, " +
			"D-BSSE, ETH Zurich (Basel)";

	// Properties (XML) file version
	public static final int propertiesVersion = 4;

}

Increase version to 0.6.0 beta.

Increase version to 0.6.0 beta.


package liquibase.datatype.core;

import liquibase.database.Database;
import liquibase.database.core.DerbyDatabase;
import liquibase.database.core.MSSQLDatabase;
import liquibase.database.core.OracleDatabase;
import liquibase.database.core.PostgresDatabase;
import liquibase.datatype.DataTypeInfo;
import liquibase.datatype.DatabaseDataType;
import liquibase.datatype.LiquibaseDataType;

@DataTypeInfo(name="tinyint", aliases = "java.sql.Types.TINYINT", minParameters = 0, maxParameters = 1, priority = LiquibaseDataType.PRIORITY_DEFAULT)
public class TinyIntType  extends LiquibaseDataType {

    private boolean autoIncrement;

    public boolean isAutoIncrement() {
        return autoIncrement;
    }

    public void setAutoIncrement(boolean autoIncrement) {
        this.autoIncrement = autoIncrement;
    }

    @Override
    public DatabaseDataType toDatabaseDataType(Database database) {
        if (database instanceof DerbyDatabase || database instanceof PostgresDatabase) {
            return new DatabaseDataType("SMALLINT");
        }
        if (database instanceof MSSQLDatabase) {
            return new DatabaseDataType("TINYINT");
        }
        if (database instanceof OracleDatabase) {
            return new DatabaseDataType("NUMBER",3);
        }
        return super.toDatabaseDataType(database);
    }
}

package liquibase.datatype.core;

import liquibase.database.Database;
import liquibase.database.core.DerbyDatabase;
import liquibase.database.core.MSSQLDatabase;
import liquibase.database.core.OracleDatabase;
import liquibase.database.core.PostgresDatabase;
import liquibase.datatype.DataTypeInfo;
import liquibase.datatype.DatabaseDataType;
import liquibase.datatype.LiquibaseDataType;

@DataTypeInfo(name="tinyint", aliases = "java.sql.Types.TINYINT", minParameters = 0, maxParameters = 1, priority = LiquibaseDataType.PRIORITY_DEFAULT)
public class TinyIntType  extends LiquibaseDataType {

    private boolean autoIncrement;

    public boolean isAutoIncrement() {
        return autoIncrement;
    }

    public void setAutoIncrement(boolean autoIncrement) {
        this.autoIncrement = autoIncrement;
    }

    @Override
    public DatabaseDataType toDatabaseDataType(Database database) {
        if (database instanceof DerbyDatabase || database instanceof PostgresDatabase || database instanceof FirebirdDatabase) {
            return new DatabaseDataType("SMALLINT");
        }
        if (database instanceof MSSQLDatabase) {
            return new DatabaseDataType("TINYINT");
        }
        if (database instanceof OracleDatabase) {
            return new DatabaseDataType("NUMBER",3);
        }
        return super.toDatabaseDataType(database);
    }
}

Use smallint for Firebird if tinyint is requested


/*
 * Copyright 2016 Philip Cohn-Cort
 *
 * 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.fuzz.indicator;

import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;

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

import static org.junit.Assert.*;

/**
 * Instrumentation test, which will execute on an Android device.
 *
 * @see Testing documentation
 */
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
    @Test
    public void useAppContext() throws Exception {
        // Context of the app under test.
        Context appContext = InstrumentationRegistry.getTargetContext();

        assertEquals("com.cliabhach.emptyhusk", appContext.getPackageName());
    }
}

/*
 * Copyright 2016 Philip Cohn-Cort
 *
 * 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.fuzz.indicator;

import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;

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

import static org.junit.Assert.*;

/**
 * Instrumentation test, which will execute on an Android device.
 *
 * @see Testing documentation
 */
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
    @Test
    public void useAppContext() throws Exception {
        // Context of the app under test.
        Context appContext = InstrumentationRegistry.getTargetContext();

        assertEquals("com.fuzz.emptyhusk", appContext.getPackageName());
    }
}

Correct an app name reference in an example test

Said test may or may not be removed in a future commit - haven't figured that out yet


package org.wikipedia.interlanguage;

import android.support.annotation.NonNull;

public final class AcceptLanguageUtil {
    private static final float APP_LANGUAGE_QUALITY = .9f;
    private static final float SYSTEM_LANGUAGE_QUALITY = .8f;

    /**
     * @return The value that should go in the Accept-Language header.
     */
    @NonNull
    public static String getAcceptLanguage(@NonNull String siteLanguageCode,
                                           @NonNull String appLanguageCode,
                                           @NonNull String systemLanguageCode) {
        String acceptLanguage = siteLanguageCode;
        acceptLanguage = appendToAcceptLanguage(acceptLanguage, appLanguageCode, APP_LANGUAGE_QUALITY);
        acceptLanguage = appendToAcceptLanguage(acceptLanguage, systemLanguageCode, SYSTEM_LANGUAGE_QUALITY);
        return acceptLanguage;
    }

    @NonNull
    private static String appendToAcceptLanguage(@NonNull String acceptLanguage,
                                                 @NonNull String languageCode, float quality) {
        // If accept-language already contains the language, just return accept-language.
        if (acceptLanguage.contains(languageCode)) {
            return acceptLanguage;
        }

        // If accept-language is empty, don't append. Just return the language.
        if (acceptLanguage.isEmpty()) {
            return languageCode;
        }

        // Accept-language is nonempty, append the language.
        return String.format("%s,%s;q=%.1f", acceptLanguage, languageCode, quality);
    }

    private AcceptLanguageUtil() { }
}

package org.wikipedia.interlanguage;

import android.support.annotation.NonNull;

import java.util.Locale;

public final class AcceptLanguageUtil {
    private static final float APP_LANGUAGE_QUALITY = .9f;
    private static final float SYSTEM_LANGUAGE_QUALITY = .8f;

    /**
     * @return The value that should go in the Accept-Language header.
     */
    @NonNull
    public static String getAcceptLanguage(@NonNull String siteLanguageCode,
                                           @NonNull String appLanguageCode,
                                           @NonNull String systemLanguageCode) {
        String acceptLanguage = siteLanguageCode;
        acceptLanguage = appendToAcceptLanguage(acceptLanguage, appLanguageCode, APP_LANGUAGE_QUALITY);
        acceptLanguage = appendToAcceptLanguage(acceptLanguage, systemLanguageCode, SYSTEM_LANGUAGE_QUALITY);
        return acceptLanguage;
    }

    @NonNull
    private static String appendToAcceptLanguage(@NonNull String acceptLanguage,
                                                 @NonNull String languageCode, float quality) {
        // If accept-language already contains the language, just return accept-language.
        if (acceptLanguage.contains(languageCode)) {
            return acceptLanguage;
        }

        // If accept-language is empty, don't append. Just return the language.
        if (acceptLanguage.isEmpty()) {
            return languageCode;
        }

        // Accept-language is nonempty, append the language.
        return String.format(Locale.ROOT, "%s,%s;q=%.1f", acceptLanguage, languageCode, quality);
    }

    private AcceptLanguageUtil() { }
}

Fix issue with Accept-Language header for certain system languages.

The proper Locale was not being used when calling String.format(), which
was causing the resulting HTTP requests to fail.

Bug: T118910
Change-Id: I09e8c57d92eb969de816ed5025ad17f66aec386c


package xyz.igorgee.shapejs;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ShapeJS {

    private static final MediaType MEDIA_TYPE_JPG = MediaType.parse("image/jpg");
    private static final String ENDPOINT = "http://52.90.86.247/image";
    public static final String SHAPE_JS_IMAGE_KEY = "shapeJS_img";

    private final OkHttpClient client = new OkHttpClient.Builder()
            .readTimeout(20, TimeUnit.SECONDS)
            .build();

    public InputStream uploadImage(File image) throws IOException {
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart(SHAPE_JS_IMAGE_KEY, image.getName(),
                        RequestBody.create(MEDIA_TYPE_JPG, image))
                .build();

        Request request = new Request.Builder()
                .url(ENDPOINT)
                .post(requestBody)
                .build();

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

        if (!response.isSuccessful()) throw new IOException("Unsuccessful response");

        return response.body().byteStream();
    }
}

package xyz.igorgee.shapejs;

import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ShapeJS {

    private static final MediaType MEDIA_TYPE_JPG = MediaType.parse("image/jpg");
    private static final String ENDPOINT = "http://52.90.86.247/image";
    public static final String SHAPE_JS_IMAGE_KEY = "shapeJS_img";

    private final OkHttpClient client = new OkHttpClient.Builder()
            .readTimeout(20, TimeUnit.SECONDS)
            .build();

    public InputStream uploadImage(File image) throws IOException {
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart(SHAPE_JS_IMAGE_KEY, image.getName(),
                        RequestBody.create(MEDIA_TYPE_JPG, image))
                .build();

        Request request = new Request.Builder()
                .url(ENDPOINT)
                .post(requestBody)
                .build();

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

        Log.d("RESPONSE HEAD", String.valueOf(response.code()));
        Log.d("RESPONSE MESSAGE", response.message());

        if (!response.isSuccessful()) throw new IOException("Unsuccessful response");
        return response.body().byteStream();
    }
}

Add response logging for upload of image


package de.xikolo.models;

import com.squareup.moshi.Json;

import de.xikolo.models.base.RealmAdapter;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
import moe.banana.jsonapi2.JsonApi;
import moe.banana.jsonapi2.Resource;

public class Quiz extends RealmObject {

    @PrimaryKey
    public String id;

    public String instructions;

    public int timeLimit;

    public int allowedAttempts;

    public boolean showWelcomePage;

    @JsonApi(type = "quizzes")
    public static class JsonModel extends Resource implements RealmAdapter<Quiz> {

        public String instructions;

        @Json(name = "time_limit")
        public int timeLimit;

        @Json(name = "allowed_attempts")
        public int allowedAttempts;

        @Json(name = "max_points")
        public int maxPoints;

        @Json(name = "show_welcome_page")
        public boolean showWelcomePage;

        @Override
        public Quiz convertToRealmObject() {
            Quiz quiz = new Quiz();
            quiz.id = getId();
            quiz.instructions = instructions;
            quiz.timeLimit = timeLimit;
            quiz.allowedAttempts = allowedAttempts;
            quiz.showWelcomePage = showWelcomePage;

            return quiz;
        }

    }

}

package de.xikolo.models;

import com.squareup.moshi.Json;

import de.xikolo.models.base.RealmAdapter;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
import moe.banana.jsonapi2.JsonApi;
import moe.banana.jsonapi2.Resource;

public class Quiz extends RealmObject {

    @PrimaryKey
    public String id;

    public String instructions;

    public int timeLimit;

    public int allowedAttempts;

    public boolean showWelcomePage;

    @JsonApi(type = "quizzes")
    public static class JsonModel extends Resource implements RealmAdapter<Quiz> {

        public String instructions;

        @Json(name = "time_limit")
        public int timeLimit;

        @Json(name = "allowed_attempts")
        public int allowedAttempts;

        @Json(name = "show_welcome_page")
        public boolean showWelcomePage;

        @Override
        public Quiz convertToRealmObject() {
            Quiz quiz = new Quiz();
            quiz.id = getId();
            quiz.instructions = instructions;
            quiz.timeLimit = timeLimit;
            quiz.allowedAttempts = allowedAttempts;
            quiz.showWelcomePage = showWelcomePage;

            return quiz;
        }

    }

}

Remove leftover from APIv4 migration

Remove leftover from APIv4 migration


package com.kickstarter.libs;

import android.os.Parcelable;
import android.support.annotation.Nullable;

import org.joda.time.DateTime;

import auto.parcel.AutoParcel;

@AutoParcel
public abstract class RelativeDateOptions implements Parcelable {
  public abstract boolean abbreviated();
  public abstract boolean absolute();
  public abstract @Nullable DateTime relativeToDateTime();
  public abstract int threshold();

  @AutoParcel.Builder
  public abstract static class Builder {
    public abstract Builder abbreviated(boolean __);
    public abstract Builder absolute(boolean __);
    public abstract Builder relativeToDateTime(DateTime __);
    public abstract Builder threshold(int __);
    public abstract RelativeDateOptions build();
  }

  public static Builder builder() {
    return new AutoParcel_RelativeDateOptions.Builder()
      .abbreviated(false)
      .absolute(false)
      .threshold(THIRTY_DAYS_IN_SECONDS);
  }

  public abstract Builder toBuilder();

  private final static int THIRTY_DAYS_IN_SECONDS = 60 * 60 * 24 * 30;
}

package com.kickstarter.libs;

import android.os.Parcelable;
import android.support.annotation.Nullable;

import org.joda.time.DateTime;

import auto.parcel.AutoParcel;

@AutoParcel
public abstract class RelativeDateOptions implements Parcelable {
  // Abbreviates string, e.g.: "in 1 hr"
  public abstract boolean abbreviated();

  // Don't output tense, e.g.: "1 hour" instead of "in 1 hour"
  public abstract boolean absolute();

  // Compare against this date instead of the current time
  public abstract @Nullable DateTime relativeToDateTime();

  // Number of seconds difference permitted before an attempt to describe the relative date is abandoned.
  // For example, "738 days ago" is not helpful to users. The threshold defaults to 30 days.
  public abstract int threshold();

  @AutoParcel.Builder
  public abstract static class Builder {
    public abstract Builder abbreviated(boolean __);
    public abstract Builder absolute(boolean __);
    public abstract Builder relativeToDateTime(DateTime __);
    public abstract Builder threshold(int __);
    public abstract RelativeDateOptions build();
  }

  public static Builder builder() {
    return new AutoParcel_RelativeDateOptions.Builder()
      .abbreviated(false)
      .absolute(false)
      .threshold(THIRTY_DAYS_IN_SECONDS);
  }

  public abstract Builder toBuilder();

  private final static int THIRTY_DAYS_IN_SECONDS = 60 * 60 * 24 * 30;
}

Add comments explaining relative date options


/*
 * Copyright (C) 2009 JavaRosa
 *
 * 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.javarosa.xpath.parser.ast;

import org.javarosa.xpath.expr.XPathExpression;
import org.javarosa.xpath.expr.XPathFilterExpr;
import org.javarosa.xpath.parser.XPathSyntaxException;

import java.util.Enumeration;
import java.util.Vector;

public class ASTNodeFilterExpr extends ASTNode {
    public ASTNodeAbstractExpr expr;
    public Vector predicates;

    public ASTNodeFilterExpr() {
        predicates = new Vector();
    }

    public Vector getChildren() {
        Vector v = new Vector();
        v.addElement(expr);
        for (Enumeration e = predicates.elements(); e.hasMoreElements(); )
            v.addElement(e.nextElement());
        return v;
    }

    public XPathExpression build() throws XPathSyntaxException {
        XPathExpression[] preds = new XPathExpression[predicates.size()];
        for (int i = 0; i < preds.length; i++)
            preds[i] = ((ASTNode)predicates.elementAt(i)).build();

        return new XPathFilterExpr(expr.build(), preds);
    }
}

package org.javarosa.xpath.parser.ast;

import org.javarosa.xpath.expr.XPathExpression;
import org.javarosa.xpath.expr.XPathFilterExpr;
import org.javarosa.xpath.parser.XPathSyntaxException;

import java.util.Enumeration;
import java.util.Vector;

public class ASTNodeFilterExpr extends ASTNode {
    public ASTNodeAbstractExpr expr;
    public Vector predicates;

    public ASTNodeFilterExpr() {
        predicates = new Vector();
    }

    @Override
    public Vector getChildren() {
        Vector v = new Vector();
        v.addElement(expr);
        for (Enumeration e = predicates.elements(); e.hasMoreElements(); )
            v.addElement(e.nextElement());
        return v;
    }

    @Override
    public XPathExpression build() throws XPathSyntaxException {
        XPathExpression[] preds = new XPathExpression[predicates.size()];
        for (int i = 0; i < preds.length; i++)
            preds[i] = ((ASTNode)predicates.elementAt(i)).build();

        return new XPathFilterExpr(expr.build(), preds);
    }
}

Add override and remove licensing comment


package com.veyndan.redditclient;

import android.app.Application;

import com.squareup.leakcanary.LeakCanary;
import com.twitter.sdk.android.Twitter;
import com.twitter.sdk.android.core.TwitterAuthConfig;

import io.fabric.sdk.android.Fabric;
import timber.log.Timber;

public class RedditClientApp extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        if (BuildConfig.DEBUG) {
            Timber.plant(new Timber.DebugTree());
        }
        final TwitterAuthConfig authConfig = new TwitterAuthConfig(Config.TWITTER_KEY, Config.TWITTER_SECRET);
        Fabric.with(this, new Twitter(authConfig));
        LeakCanary.install(this);
    }
}

package com.veyndan.redditclient;

import android.app.Application;

import com.squareup.leakcanary.LeakCanary;
import com.twitter.sdk.android.Twitter;
import com.twitter.sdk.android.core.TwitterAuthConfig;

import io.fabric.sdk.android.Fabric;
import timber.log.Timber;

public class RedditClientApp extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        if (BuildConfig.DEBUG) {
            Timber.plant(new Timber.DebugTree() {
                @Override
                protected void log(final int priority, final String tag, final String message,
                                   final Throwable t) {
                    super.log(priority, "veyndan_" + tag, message, t);
                }
            });
        }
        final TwitterAuthConfig authConfig = new TwitterAuthConfig(Config.TWITTER_KEY, Config.TWITTER_SECRET);
        Fabric.with(this, new Twitter(authConfig));
        LeakCanary.install(this);
    }
}

Prepend 'veyndan_' tag to each Timber log for easy logcat usage


package edu.teco.dnd.module.messages.loadStartBlock;

import java.util.UUID;

import edu.teco.dnd.module.ModuleApplicationManager;
import edu.teco.dnd.network.ConnectionManager;
import edu.teco.dnd.network.MessageHandler;
import edu.teco.dnd.network.messages.Response;

public class BlockMessageHandler implements MessageHandler<BlockMessage> {
	final ModuleApplicationManager appManager;

	public BlockMessageHandler(ModuleApplicationManager appManager) {
		this.appManager = appManager;
	}

	@Override
	public Response handleMessage(ConnectionManager connMan, UUID remoteUUID, BlockMessage message) {
		if (appManager.scheduleBlock(message.getApplicationID(), message.block, message.scheduleToId)) {
			return new BlockAck();
		} else {
			return new BlockNak();
		}

	}

}

package edu.teco.dnd.module.messages.loadStartBlock;

import java.util.UUID;

import edu.teco.dnd.module.ModuleApplicationManager;
import edu.teco.dnd.network.ConnectionManager;
import edu.teco.dnd.network.MessageHandler;
import edu.teco.dnd.network.messages.Response;

public class BlockMessageHandler implements MessageHandler<BlockMessage> {
	final ModuleApplicationManager appManager;

	public BlockMessageHandler(ModuleApplicationManager appManager) {
		this.appManager = appManager;
	}

	@Override
	public Response handleMessage(ConnectionManager connMan, UUID remoteUUID, BlockMessage message) {
		try {
			appManager.scheduleBlock(message.getApplicationID(), message.block, message.scheduleToId);
		} catch (Exception e) {
			return new BlockNak();
		}
		return new BlockAck();
	}
}

Rewrite handler to work with exceptions instead of returned booleans.


package com.elmakers.mine.bukkit.economy;

import org.bukkit.configuration.ConfigurationSection;

import com.elmakers.mine.bukkit.api.magic.CasterProperties;
import com.elmakers.mine.bukkit.api.magic.Mage;
import com.elmakers.mine.bukkit.api.magic.MageController;

public class SpellPointCurrency extends BaseMagicCurrency {
    private final boolean isValid;

    public SpellPointCurrency(MageController controller, ConfigurationSection configuration) {
        super(controller, "sp", configuration);
        isValid = controller.isSPEnabled();
    }

    @Override
    public double getBalance(Mage mage, CasterProperties caster) {
        return mage.getSkillPoints();
    }

    @Override
    public boolean has(Mage mage, CasterProperties caster, double amount) {
        return mage.getSkillPoints() >= amount;
    }

    @Override
    public void deduct(Mage mage, CasterProperties caster, double amount) {
        mage.addSkillPoints(-getRoundedAmount(amount));
    }

    @Override
    public boolean give(Mage mage, CasterProperties caster, double amount) {
        if (mage.isAtMaxSkillPoints()) {
            return false;
        }
        mage.addSkillPoints(getRoundedAmount(amount));
        return true;
    }

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

    @Override
    public double getDefaultValue() {
        return defaultValue;
    }
}

package com.elmakers.mine.bukkit.economy;

import org.bukkit.configuration.ConfigurationSection;

import com.elmakers.mine.bukkit.api.magic.CasterProperties;
import com.elmakers.mine.bukkit.api.magic.Mage;
import com.elmakers.mine.bukkit.api.magic.MageController;

public class SpellPointCurrency extends CustomCurrency {
    private final boolean isValid;

    public SpellPointCurrency(MageController controller, ConfigurationSection configuration) {
        super(controller, "sp", configuration);
        isValid = controller.isSPEnabled();
    }

    @Override
    public double getBalance(Mage mage, CasterProperties caster) {
        return mage.getSkillPoints();
    }

    @Override
    public boolean has(Mage mage, CasterProperties caster, double amount) {
        return mage.getSkillPoints() >= amount;
    }

    @Override
    public void deduct(Mage mage, CasterProperties caster, double amount) {
        mage.addSkillPoints(-getRoundedAmount(amount));
    }

    @Override
    public boolean give(Mage mage, CasterProperties caster, double amount) {
        if (mage.isAtMaxSkillPoints()) {
            return false;
        }
        mage.addSkillPoints(getRoundedAmount(amount));
        return true;
    }

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

    @Override
    public double getDefaultValue() {
        return defaultValue;
    }
}

Fix recursion issues with spell points

Fix recursion issues with spell points


package org.javersion.object;

import static org.assertj.core.api.Assertions.*;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;

import org.junit.Test;

public class JavaTimeTest {

    @Versionable
    public static class DT {
        final Instant instant = Instant.now();
        final LocalDate localDate = LocalDate.now();
        final LocalDateTime localDateTime = LocalDateTime.now();
    }

    private ObjectSerializer<DT> serializer = new ObjectSerializer<>(DT.class);

    @Test
    public void write_read() {
        final DT dt = new DT();
        DT dtCopy = serializer.fromPropertyMap(serializer.toPropertyMap(dt));
        assertThat(dtCopy.instant).isEqualTo(dt.instant);
        assertThat(dtCopy.localDate).isEqualTo(dt.localDate);
        assertThat(dtCopy.localDateTime).isEqualTo(dt.localDateTime);
    }

}

package org.javersion.object;

import static org.assertj.core.api.Assertions.*;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;

import org.junit.Test;

public class JavaTimeTest {

    @Versionable
    public static class DT {
        private final Instant instant = Instant.now();
        private final LocalDate localDate = LocalDate.now();
        private final LocalDateTime localDateTime = LocalDateTime.now();
    }

    private ObjectSerializer<DT> serializer = new ObjectSerializer<>(DT.class);

    @Test
    public void write_read() {
        final DT dt = new DT();
        DT dtCopy = serializer.fromPropertyMap(serializer.toPropertyMap(dt));
        assertThat(dtCopy.instant).isEqualTo(dt.instant);
        assertThat(dtCopy.localDate).isEqualTo(dt.localDate);
        assertThat(dtCopy.localDateTime).isEqualTo(dt.localDateTime);
    }
}

Verify binding of private final fields

Verify binding of private final fields


package io.smsc.listeners;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import static org.mockito.Mockito.*;

@RunWith(MockitoJUnitRunner.class)
public class EncryptionListenerUnitTest {

    private Object testObject;

    @Before
    public void setUp() {
        testObject = new Object();
    }

    @Mock
    private EncryptionListener listener;

    @Test(expected = IllegalAccessException.class)
    public void testEncryptCall() throws Exception {
        doThrow(IllegalAccessException.class).when(listener).encrypt(testObject);
        listener.encrypt(testObject);
    }

    @Test(expected = IllegalAccessException.class)
    public void testDecryptCall() throws Exception {
        doThrow(IllegalAccessException.class).when(listener).decrypt(testObject);
        listener.decrypt(testObject);
    }
}

package io.smsc.listeners;

import io.smsc.util.EncrypterUtil;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.test.util.ReflectionTestUtils;

import java.awt.event.ActionEvent;

import static org.mockito.Mockito.*;

@RunWith(MockitoJUnitRunner.class)
public class EncryptionListenerUnitTest {

    private Object testObject;

    private EncryptionListener listener;

    private ActionEvent mockEvent;

    @Mock
    private EncryptionListener mockListener;

    @Before
    public void setUp() {
        listener = new EncryptionListener();
        testObject = new Object();
        mockEvent = mock(ActionEvent.class);

        ReflectionTestUtils.setField(EncrypterUtil.class, "secretKey", "smsc.io");
    }

    @Test(expected = IllegalAccessException.class)
    public void testEncryptCallWithException() throws Exception {
        doThrow(IllegalAccessException.class).when(mockListener).encrypt(testObject);

        mockListener.encrypt(testObject);
    }

    @Test(expected = IllegalAccessException.class)
    public void testDecryptCallWithException() throws Exception {
        doThrow(IllegalAccessException.class).when(mockListener).decrypt(testObject);

        mockListener.decrypt(testObject);
    }

    @Test
    public void testEncryptCallWithoutException() throws Exception {
        mockListener.encrypt(testObject);

        verify(mockListener).encrypt(testObject);
    }

    @Test
    public void testDecryptCallWithoutException() throws Exception {
        mockListener.decrypt(testObject);

        verify(mockListener).decrypt(testObject);
    }

    @Test
    public void testEncryptCall() throws Exception {
        listener.encrypt(mockEvent);
    }

    @Test
    public void testDecryptCall() throws Exception {
        listener.decrypt(mockEvent);
    }
}

Add more unit tests for EncryptionListener


package com.kickstarter.ui.views;

import android.content.Context;
import android.util.AttributeSet;
import android.webkit.WebChromeClient;
import android.webkit.WebView;

import com.kickstarter.KsrApplication;
import com.kickstarter.libs.WebViewJavascriptInterface;
import com.kickstarter.services.KickstarterWebViewClient;

import javax.inject.Inject;

public class KickstarterWebView extends WebView {
  @Inject KickstarterWebViewClient client;

  public KickstarterWebView(final Context context) {
    this(context, null);
  }

  public KickstarterWebView(final Context context, final AttributeSet attrs) {
    this(context, attrs, android.R.attr.webViewStyle);
  }

  public KickstarterWebView(final Context context, final AttributeSet attrs, final int defStyle) {
    super(context, attrs, defStyle);

    ((KsrApplication) context.getApplicationContext()).component().inject(this);
    setWebViewClient(client);
    setWebChromeClient(new WebChromeClient());
    getSettings().setJavaScriptEnabled(true);
    getSettings().setAllowFileAccess(false);

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
      setWebContentsDebuggingEnabled(true);
    }

    addJavascriptInterface(new WebViewJavascriptInterface(this.client), "WebViewJavascriptInterface");
  }
}

package com.kickstarter.ui.views;

import android.content.Context;
import android.util.AttributeSet;
import android.webkit.WebChromeClient;
import android.webkit.WebView;

import com.kickstarter.KsrApplication;
import com.kickstarter.libs.WebViewJavascriptInterface;
import com.kickstarter.services.KickstarterWebViewClient;

import javax.inject.Inject;

public class KickstarterWebView extends WebView {
  @Inject KickstarterWebViewClient client;

  public KickstarterWebView(final Context context) {
    this(context, null);
  }

  public KickstarterWebView(final Context context, final AttributeSet attrs) {
    this(context, attrs, android.R.attr.webViewStyle);
  }

  public KickstarterWebView(final Context context, final AttributeSet attrs, final int defStyle) {
    super(context, attrs, defStyle);

    ((KsrApplication) context.getApplicationContext()).component().inject(this);
    setWebViewClient(client);
    setWebChromeClient(new WebChromeClient());
    getSettings().setJavaScriptEnabled(true);
    getSettings().setAllowFileAccess(false);

    if (android.os.Build.VERSION.SDK_INT >= 19) {
      setWebContentsDebuggingEnabled(true);
    }

    addJavascriptInterface(new WebViewJavascriptInterface(this.client), "WebViewJavascriptInterface");
  }
}

Remove another reference to kitkat

Remove another reference to kitkat


package com.suse.salt.netapi.datatypes.target;

/**
 * Matcher based on salt grains
 */
public class Grains extends DictionaryTarget implements Target<String> {

    /**
     * Creates a grains matcher
     *
     * @param target the targeting expression
     */
    public Grains(String target) {
        super(target);
    }

    /**
     * Creates a grains matcher
     *
     * @param target the targeting expression
     * @param delimiter the character to delimit nesting in the grain name
     */
    public Grains(String target, char delimiter) {
        super(target, delimiter);
    }

    /**
     * Creates a grains matcher
     *
     * @param grain the grain name
     * @param value the value to match
     */
    public Grains(String grain, String value) {
        super(grain, value);
    }

    /**
     * Creates a grains matcher
     *
     * @param grain the grain name
     * @param value the value to match
     * @param delimiter the character to delimit nesting in the grain name
     */
    public Grains(String grain, String value, char delimiter) {
        super(grain, value, delimiter);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public TargetType getType() { return TargetType.GRAIN; }

    @Deprecated
    public String getGrain() { return getKey(); }
}

package com.suse.salt.netapi.datatypes.target;

/**
 * Matcher based on salt grains
 */
public class Grains extends DictionaryTarget implements Target<String> {

    /**
     * Creates a grains matcher
     *
     * @param target the targeting expression
     */
    public Grains(String target) {
        super(target);
    }

    /**
     * Creates a grains matcher
     *
     * @param target the targeting expression
     * @param delimiter the character to delimit nesting in the grain name
     */
    public Grains(String target, char delimiter) {
        super(target, delimiter);
    }

    /**
     * Creates a grains matcher
     *
     * @param grain the grain name
     * @param value the value to match
     */
    public Grains(String grain, String value) {
        super(grain, value);
    }

    /**
     * Creates a grains matcher
     *
     * @param grain the grain name
     * @param value the value to match
     * @param delimiter the character to delimit nesting in the grain name
     */
    public Grains(String grain, String value, char delimiter) {
        super(grain, value, delimiter);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public TargetType getType() { return TargetType.GRAIN; }

    /**
     * Return the grain identifier key
     *
     * @deprecated
     * Use {@link #getKey()} instead.
     */
    @Deprecated
    public String getGrain() { return getKey(); }
}

Add JavaDoc for deprecated methods

Add JavaDoc for deprecated methods


package io.github.phantamanta44.shlgl.event;

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

/**
 * Handles the dispatching of events to individual {@link EventStream}s.
 * @author Evan Geng
 */
public class EventBus { // TODO Document

    private final Map<Class<? extends Event>, EventStream<?>> eventStreams;

    public EventBus() {
        eventStreams = new HashMap<>();
        // TODO Register default event types
    }

    public void registerEvent(Class<? extends Event> eventType) {
        eventStreams.put(eventType, new EventStream<>());
    }

    public void post(Event event) {
        eventStreams.entrySet().stream()
                .filter(e -> e.getKey().isAssignableFrom(event.getClass()))
                .forEach(e -> e.getValue().post(event)); // FIXME Cast this somehow
    }

}

package io.github.phantamanta44.shlgl.event;

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

/**
 * Handles the dispatching of events to individual {@link EventStream}s.
 * @author Evan Geng
 */
public class EventBus {

    /**
     * The mapping of event types to {@link EventStream}s.
     */
    private final Map<Class<? extends Event>, EventStream> eventStreams;

    /**
     * Creates and initializes the event bus.
     */
    public EventBus() {
        eventStreams = new HashMap<>();
        // TODO Register default event types
    }

    /**
     * Registers an event type.
     * @param eventType The new event type.
     */
    public void registerEvent(Class<? extends Event> eventType) {
        eventStreams.put(eventType, new EventStream<>());
    }

    /**
     * Dispatches an event to all eligible listeners.
     * @param event The event to post.
     */
    @SuppressWarnings("unchecked")
    public void post(Event event) {
        eventStreams.entrySet().stream()
                .filter(e -> e.getKey().isAssignableFrom(event.getClass()))
                .forEach(e -> e.getValue().post(event));
    }

}

Fix casting issue and document event bus


package org.cryptonit.cloud.timestamping;

import javax.ws.rs.Path;

/**
 * @author Mathias Brossard
 */
@Path("/timestamp")
public class Application {

}

package org.cryptonit.cloud.timestamping;

import javax.ws.rs.Path;
import org.cryptonit.cloud.interfaces.TimestampingAuthorityFactory;

/**
 * @author Mathias Brossard
 */
@Path("/timestamp")
public class Application {
    private static TimestampingAuthorityFactory tsaFactory = null;

    public static void setTimestampingAuthorityFactory(TimestampingAuthorityFactory factory) {
        tsaFactory = factory;
    }
}

Add static method to set TimestampingAuthorityFactory


/*
 * 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 com.lamepancake.chitchat;

/**
 *
 * @author shane
 */
public class ChatManager {

}

/*
 * 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 com.lamepancake.chitchat;

import com.lamepancake.chitchat.mediator.Event;

/**
 *
 * @author shane
 */
public class ChatManager {

    public void handleEvent(Event e)
    {

    }
}

Add PromoteUser flag to Event

Add PromoteUser flag to Event


package biz.paluch.atsoundtrack;

import org.jetbrains.annotations.NotNull;

import com.intellij.codeInsight.completion.CompletionContributor;
import com.intellij.codeInsight.completion.CompletionParameters;
import com.intellij.codeInsight.completion.CompletionResultSet;
import com.intellij.codeInsight.lookup.LookupElement;

/**
 * @author Mark Paluch
 * @since 13.05.15 11:49
 */
public class AtSoundtrackContributor extends CompletionContributor {

    @Override
    public void fillCompletionVariants(CompletionParameters parameters, CompletionResultSet result) {

        if (AtSoundtrack.getName() != null) {
            result.addElement(new LookupElement() {
                @NotNull
                @Override
                public String getLookupString() {
                    return "@soundtrack " + AtSoundtrack.getName();
                }
            });
        }
        super.fillCompletionVariants(parameters, result);
    }
}

package biz.paluch.atsoundtrack;

import static com.intellij.openapi.util.text.StringUtil.*;

import com.intellij.codeInsight.completion.CompletionContributor;
import com.intellij.codeInsight.completion.CompletionParameters;
import com.intellij.codeInsight.completion.CompletionResultSet;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.psi.PsiComment;
import com.intellij.psi.PsiDocCommentBase;
import com.intellij.psi.xml.XmlComment;
import com.intellij.psi.xml.XmlToken;

/**
 * @author Mark Paluch
 * @since 13.05.15 11:49
 */
public class AtSoundtrackContributor extends CompletionContributor {

    @Override
    public void fillCompletionVariants(CompletionParameters parameters, CompletionResultSet result) {

        String prefix = parameters.getOriginalPosition().getText();

        if (!prefix.contains("soundtrack")) {

            if (!isEmpty(AtSoundtrack.getName())) {

                boolean qualified = false;
                if (parameters.getOriginalPosition() instanceof PsiComment
                        || parameters.getOriginalPosition().getContext() instanceof PsiDocCommentBase
                        || parameters.getOriginalPosition().getClass().getName().contains("PsiDocToken")) {

                    qualified = true;
                }
                if (parameters.getOriginalPosition() instanceof XmlToken) {
                    XmlToken xmlToken = (XmlToken) parameters.getOriginalPosition();

                    if (xmlToken instanceof XmlComment || xmlToken.getContext() instanceof XmlComment) {
                        qualified = true;
                    }
                }

                if (qualified) {
                    if (!prefix.contains("@")) {
                        result.addElement(LookupElementBuilder.create("@soundtrack " + AtSoundtrack.getName()));
                    } else {
                        result.addElement(LookupElementBuilder.create("soundtrack " + AtSoundtrack.getName()));
                    }
                }
            }
        }

        super.fillCompletionVariants(parameters, result);
    }
}

Use code completion in multiple places and compatibility with PyCharm, RubyMine, PhpStorm


//
// Copyright (C) 2006 United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration
// (NASA).  All Rights Reserved.
//
// This software is distributed under the NASA Open Source Agreement
// (NOSA), version 1.3.  The NOSA has been approved by the Open Source
// Initiative.  See the file NOSA-1.3-JPF at the top of the distribution
// directory tree for the complete NOSA document.
//
// THE SUBJECT SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY OF ANY
// KIND, EITHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT
// LIMITED TO, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL CONFORM TO
// SPECIFICATIONS, ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR
// A PARTICULAR PURPOSE, OR FREEDOM FROM INFRINGEMENT, ANY WARRANTY THAT
// THE SUBJECT SOFTWARE WILL BE ERROR FREE, OR ANY WARRANTY THAT
// DOCUMENTATION, IF PROVIDED, WILL CONFORM TO THE SUBJECT SOFTWARE.
//
package gov.nasa.jpf.search.heuristic;

import gov.nasa.jpf.Config;
import gov.nasa.jpf.jvm.JVM;

/**
 * breadth first search
 */
public class BFSHeuristic extends SimplePriorityHeuristic {

  public BFSHeuristic (Config config, JVM vm) {
    super(config,vm);
  }

  protected int computeHeuristicValue () {
    int priority = vm.getPathLength();

    return priority;
  }

}

//
// Copyright (C) 2006 United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration
// (NASA).  All Rights Reserved.
//
// This software is distributed under the NASA Open Source Agreement
// (NOSA), version 1.3.  The NOSA has been approved by the Open Source
// Initiative.  See the file NOSA-1.3-JPF at the top of the distribution
// directory tree for the complete NOSA document.
//
// THE SUBJECT SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY OF ANY
// KIND, EITHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT
// LIMITED TO, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL CONFORM TO
// SPECIFICATIONS, ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR
// A PARTICULAR PURPOSE, OR FREEDOM FROM INFRINGEMENT, ANY WARRANTY THAT
// THE SUBJECT SOFTWARE WILL BE ERROR FREE, OR ANY WARRANTY THAT
// DOCUMENTATION, IF PROVIDED, WILL CONFORM TO THE SUBJECT SOFTWARE.
//
package gov.nasa.jpf.search.heuristic;

import gov.nasa.jpf.Config;
import gov.nasa.jpf.jvm.JVM;

/**
 * breadth first search
 */
public class BFSHeuristic extends SimplePriorityHeuristic {

  public BFSHeuristic (Config config, JVM vm) {
  	super(config,vm);
  	System.out.println("BFS Search");
  }

  protected int computeHeuristicValue () {
    int priority = vm.getPathLength();

    return priority;
  }

}

Print BFS Search when you do a BFS Search


/**
 * Copyright © 2011-2012 EMBL - European Bioinformatics Institute
 *
 * 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 uk.ac.ebi.phenotype.util;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

public class CustomizedHostNameVerifier implements HostnameVerifier {

	@Override
	public boolean verify(String hostname, SSLSession session) {
		return true;
	}

}

/**
 * Copyright © 2011-2013 EMBL - European Bioinformatics Institute
 *
 * 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 uk.ac.ebi.phenotype.util;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

/**
 * Provides an SSL certification implementation that claims all certificates
 * are valid -- without actually checking them (!).
 *
 * This is required because, for instance,
 * dev.mousephenotype.org has an invalid SSL cert
 *
 */
public class CustomizedHostNameVerifier implements HostnameVerifier {
	@Override
	public boolean verify(String hostname, SSLSession session) {
		return true;
	}
}

Change copyright in Apache 2 license to 2013


package net.mcft.copy.betterstorage.item.cardboard;

import net.mcft.copy.betterstorage.content.Items;
import net.mcft.copy.betterstorage.item.ItemBetterStorage;
import net.minecraft.item.EnumArmorMaterial;
import net.minecraft.item.EnumToolMaterial;
import net.minecraftforge.common.EnumHelper;

public class ItemCardboardSheet extends ItemBetterStorage {

	public static final EnumToolMaterial toolMaterial =
			EnumHelper.addToolMaterial("cardboard", 0, 48, 2.5F, 0.0F, 18);
	public static final EnumArmorMaterial armorMaterial =
			EnumHelper.addArmorMaterial("cardboard", 3, new int[]{ 1, 2, 2, 1 }, 20);

	static {
		toolMaterial.customCraftingMaterial = Items.cardboardSheet;
		armorMaterial.customCraftingMaterial = Items.cardboardSheet;
	}

	public ItemCardboardSheet(int id) {
		super(id);
		setMaxStackSize(8);
	}

}

package net.mcft.copy.betterstorage.item.cardboard;

import net.mcft.copy.betterstorage.content.Items;
import net.mcft.copy.betterstorage.item.ItemBetterStorage;
import net.minecraft.item.EnumArmorMaterial;
import net.minecraft.item.EnumToolMaterial;
import net.minecraftforge.common.EnumHelper;

public class ItemCardboardSheet extends ItemBetterStorage {

	public static final EnumToolMaterial toolMaterial =
			EnumHelper.addToolMaterial("cardboard", 0, 48, 2.5F, 0.0F, 18);
	public static final EnumArmorMaterial armorMaterial =
			EnumHelper.addArmorMaterial("cardboard", 3, new int[]{ 1, 2, 2, 1 }, 20);

	public ItemCardboardSheet(int id) {
		super(id);
		setMaxStackSize(8);

		toolMaterial.customCraftingMaterial = this;
		armorMaterial.customCraftingMaterial = this;
	}

}

Fix cardboard items being unrepairable

Fix cardboard items being unrepairable


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

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

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

import com.yahoo.osgi.annotation.ExportPackage;

Remove erroneous @PublicApi on com.yahoo.restapi


//
// $Id$
//
// Nexus GWTIO - I/O and network services for Nexus built on GWT and WebSockets
// http://github.com/samskivert/nexus/blob/master/LICENSE

package com.samskivert.nexus.io;

/**
 * A serializer that handles our test classes.
 */
public class TestSerializer extends AbstractSerializer
{
    public TestSerializer ()
    {
        mapStreamer(new Streamer_Widget(), Widget.class);
        mapStreamer(new Streamer_Widget.Wangle(), Widget.Wangle.class);
    }
}

//
// $Id$
//
// Nexus GWTIO - I/O and network services for Nexus built on GWT and WebSockets
// http://github.com/samskivert/nexus/blob/master/LICENSE

package com.samskivert.nexus.io;

/**
 * A serializer that handles our test classes.
 */
public class TestSerializer extends AbstractSerializer
{
    public TestSerializer ()
    {
        mapStreamer(new Streamer_Widget());
        mapStreamer(new Streamer_Widget.Wangle());
    }
}

Use new class-token free streamer registration.


package com.kickstarter.services.apiresponses;

import android.os.Parcelable;

import com.kickstarter.libs.qualifiers.AutoGson;
import com.kickstarter.models.Project;

import java.util.List;

import auto.parcel.AutoParcel;

@AutoGson
@AutoParcel
public abstract class DiscoverEnvelope implements Parcelable {
  public abstract List<Project> projects();
  public abstract UrlsEnvelope urls();

  @AutoGson
  @AutoParcel
  public abstract static class UrlsEnvelope implements Parcelable {
    public abstract ApiEnvelope api();

    @AutoGson
    @AutoParcel
    public abstract static class ApiEnvelope implements Parcelable {
      public abstract String moreProjects();
    }
  }
}

package com.kickstarter.services.apiresponses;

import android.os.Parcelable;

import com.kickstarter.libs.qualifiers.AutoGson;
import com.kickstarter.models.Project;

import java.util.List;

import auto.parcel.AutoParcel;

@AutoGson
@AutoParcel
public abstract class DiscoverEnvelope implements Parcelable {
  public abstract List<Project> projects();
  public abstract UrlsEnvelope urls();

  @AutoGson
  @AutoParcel
  public abstract static class UrlsEnvelope implements Parcelable {
    public abstract ApiEnvelope api();

    @AutoGson
    @AutoParcel
    public abstract static class ApiEnvelope implements Parcelable {
      public abstract String moreProjects();

      @AutoParcel.Builder
      public abstract static class Builder {
        public abstract Builder moreProjects(String __);
        public abstract ApiEnvelope build();
      }

      public static Builder builder() {
        return new AutoParcel_DiscoverEnvelope_UrlsEnvelope_ApiEnvelope.Builder();
      }
    }

    @AutoParcel.Builder
    public abstract static class Builder {
      public abstract Builder api(ApiEnvelope __);
      public abstract UrlsEnvelope build();
    }

    public static Builder builder() {
      return new AutoParcel_DiscoverEnvelope_UrlsEnvelope.Builder();
    }
  }

  @AutoParcel.Builder
  public abstract static class Builder {
    public abstract Builder projects(List<Project> __);
    public abstract Builder urls(UrlsEnvelope __);
    public abstract DiscoverEnvelope build();
  }

  public static Builder builder() {
    return new AutoParcel_DiscoverEnvelope.Builder();
  }

  public abstract Builder toBuilder();
}

Add builders for nested classes

Add builders for nested classes


/**
 * @license
 * Copyright 2017 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

package foam.core;

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

public class MultitonInfo<T>
  implements Axiom, ContextFactory<T>
{
  Map<Object, T> instanceMap = new HashMap<Object, T>();

  String name;
  PropertyInfo p;

  public MultitonInfo(String name, PropertyInfo p) {
    this.name = name;
    this.p = p;
  }

  public String getName() {
    return name;
  }

  public T getInstance(Map<String, Object> args, X x) {
    Object key = args.get(p.getName());
    if ( ! instanceMap.containsKey(key) ) {
      try {
        Class<T> type = (Class<T>)p.getClassInfo().getObjClass();
        T obj = type.newInstance();
        ((ContextAware)obj).setX(x);
        for (Map.Entry<String, Object> entry : args.entrySet()) {
          ((FObject)obj).setProperty(entry.getKey(), entry.getValue());
        }
        instanceMap.put(key, obj);
      } catch (java.lang.Exception e) {
        e.printStackTrace();
        return null;
      }
    }
    return instanceMap.get(key);
  }
}

/**
 * @license
 * Copyright 2017 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

package foam.core;

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

public class MultitonInfo<T>
  implements Axiom, ContextFactory<T>
{
  Map<Object, T> instanceMap = new HashMap<Object, T>();

  String name;
  PropertyInfo p;

  public MultitonInfo(String name, PropertyInfo p) {
    this.name = name;
    this.p = p;
  }

  public String getName() {
    return name;
  }

  public synchronized T getInstance(Map<String, Object> args, X x) {
    Object key = args.get(p.getName());
    if ( ! instanceMap.containsKey(key) ) {
      try {
        Class<T> type = (Class<T>)p.getClassInfo().getObjClass();
        T obj = type.newInstance();
        ((ContextAware)obj).setX(x);
        for ( Map.Entry<String, Object> entry : args.entrySet() ) {
          ((FObject)obj).setProperty(entry.getKey(), entry.getValue());
        }
        instanceMap.put(key, obj);
      } catch (java.lang.Exception e) {
        e.printStackTrace();
        return null;
      }
    }
    return instanceMap.get(key);
  }
}

Make multiton creation thread safe and fix some code style.


//
// $Id$

package com.threerings.gardens.logic;

import com.samskivert.servlet.user.User;
import com.samskivert.servlet.util.ParameterUtil;
import com.samskivert.velocity.InvocationContext;

import com.threerings.gardens.Log;
import com.threerings.gardens.GardensApp;

/**
 * Displays a list of all registered games.
 */
public class browse extends OptionalUserLogic
{
    // documentation inherited
    public void invoke (InvocationContext ctx, GardensApp app, User user)
        throws Exception
    {
        String category = ParameterUtil.getParameter(
            ctx.getRequest(), "category", false);

        if (category.equals("")) {
            // load up the metadata for all of our games
            ctx.put("games", app.getToyBoxRepository().loadGames());

        } else {
            // load up the metadata for the games in this category
            ctx.put("category", category);
            ctx.put("games", app.getToyBoxRepository().loadGames(category));
        }
    }
}

//
// $Id$

package com.threerings.gardens.logic;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import com.samskivert.servlet.user.User;
import com.samskivert.servlet.util.ParameterUtil;
import com.samskivert.velocity.InvocationContext;

import com.threerings.toybox.server.persist.Game;

import com.threerings.gardens.Log;
import com.threerings.gardens.GardensApp;

/**
 * Displays a list of all registered games.
 */
public class browse extends OptionalUserLogic
{
    // documentation inherited
    public void invoke (InvocationContext ctx, GardensApp app, User user)
        throws Exception
    {
        String category = ParameterUtil.getParameter(
            ctx.getRequest(), "category", false);

        ArrayList<Game> games;
        if (category.equals("")) {
            // load up the metadata for all of our games
            games = app.getToyBoxRepository().loadGames();

        } else {
            // load up the metadata for the games in this category
            ctx.put("category", category);
            games = app.getToyBoxRepository().loadGames(category);
        }

        // sort our games by name
        Collections.sort(games, new Comparator<Game>() {
            public int compare (Game g1, Game g2) {
                return g1.name.compareTo(g2.name);
            }
        });
        ctx.put("games", games);
    }
}

Sort the games alphabetically in the listing.


package com.github.cosmo0920.fluentd.flume.plugins;

import java.nio.charset.StandardCharsets;

import org.apache.flume.Sink.Status;
import org.apache.flume.Channel;
import org.apache.flume.Event;
import org.apache.flume.Transaction;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Matchers;
import org.mockito.Mockito.*;

import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TestFluentdSink {
}

package com.github.cosmo0920.fluentd.flume.plugins;

import java.nio.charset.StandardCharsets;

import org.apache.flume.Sink.Status;
import org.apache.flume.Channel;
import org.apache.flume.Event;
import org.apache.flume.Transaction;
import org.apache.flume.EventDeliveryException;

import org.komamitsu.fluency.Fluency;

import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Matchers;
import static org.mockito.Mockito.*;

import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class TestFluentdSink {
	private static final Logger logger = LoggerFactory.getLogger(FluentdSink.class);

	@Test
	public void testShouldCommitSuccessfulTransaction() throws EventDeliveryException {
		Channel mockChannel = mock(Channel.class);
		Transaction mockTransaction = mock(Transaction.class);
		Event mockEvent = mock(Event.class);

		when(mockChannel.getTransaction()).thenReturn(mockTransaction);
		when(mockChannel.take()).thenReturn(mockEvent);
		when(mockEvent.getBody()).thenReturn("test body".getBytes(StandardCharsets.UTF_8));

		FluentdSink sink = new FluentdSink();
		sink.setChannel(mockChannel);

		// TODO: Extract Fluency sender and mock it
		assertTrue(true);
		// Status status = sink.process();
		// assertEquals(status, Status.READY);
	}

}

Write test case skeleton with mockito and junit


package info.puzz.a10000sentences.models;

import com.activeandroid.Model;
import com.activeandroid.annotation.Column;
import com.activeandroid.annotation.Table;

import lombok.Data;
import lombok.ToString;
import lombok.experimental.Accessors;

@Data
@Accessors(chain = true)
@ToString
@Table(name = "sentence")
public class Sentence extends Model {

    @Column(name = "sentence_id", index = true, unique = true, onUniqueConflict = Column.ConflictAction.REPLACE)
    public String sentenceId;

    @Column(name = "collection_id", index = true)
    public String collectionId;

    @Column(name = "known")
    public String knownSentence;

    @Column(name = "target")
    public String targetSentence;

    @Column(name = "status")
    public int status = SentenceStatus.TODO.getStatus();

    @Column(name = "complexity", index = true)
    float complexity;

    public String[] getKnownSentences() {
        return String.valueOf(knownSentence).split("\\|");
    }

    public String getFirstKnownSentence() {
        return getKnownSentences()[0];
    }

    public SentenceStatus getSentenceStatus() {
        return SentenceStatus.fromStatus(status);
    }
}

package info.puzz.a10000sentences.models;

import com.activeandroid.Model;
import com.activeandroid.annotation.Column;
import com.activeandroid.annotation.Table;

import lombok.Data;
import lombok.ToString;
import lombok.experimental.Accessors;

@Data
@Accessors(chain = true)
@ToString
@Table(name = "sentence")
public class Sentence extends Model {

    @Column(name = "sentence_id", index = true, unique = true, onUniqueConflict = Column.ConflictAction.REPLACE)
    public String sentenceId;

    @Column(name = "collection_id", index = true)
    public String collectionId;

    @Column(name = "known")
    public String knownSentence;

    @Column(name = "target")
    public String targetSentence;

    @Column(name = "status")
    public int status = SentenceStatus.TODO.getStatus();

    @Column(name = "complexity", index = true)
    float complexity;

    public String[] getKnownSentences() {
        String[] res = String.valueOf(knownSentence).split("\\|");
        if (res.length == 1) {
            return res;
        }
        for (int i = 0; i < res.length; i++) {
            res[i] += String.format(" [%d/%d]", i+1, res.length);
        }
        return res;
    }

    public String getFirstKnownSentence() {
        return getKnownSentences()[0];
    }

    public SentenceStatus getSentenceStatus() {
        return SentenceStatus.fromStatus(status);
    }
}

Add sentence alternative counter in list


package codechicken.lib.recipe;

import com.google.gson.JsonObject;
import net.minecraft.item.crafting.Ingredient;
import net.minecraft.util.JsonUtils;
import net.minecraftforge.common.crafting.CraftingHelper;
import net.minecraftforge.common.crafting.IIngredientFactory;
import net.minecraftforge.common.crafting.JsonContext;

import javax.annotation.Nonnull;

/**
 * Simple conditional ingredient.
 *
 * Created by covers1624 on 18/10/2017.
 */
public class ConditionalIngredientFactory implements IIngredientFactory {

    @Nonnull
    @Override
    public Ingredient parse(JsonContext context, JsonObject json) {
        if (!CraftingHelper.processConditions(JsonUtils.getJsonArray(json, "conditions"), context)) {
            if (json.has("fail")) {
                CraftingHelper.getIngredient(JsonUtils.getJsonObject(json, "failed_condition"), context);
            }
            return Ingredient.EMPTY;
        }
        return CraftingHelper.getIngredient(JsonUtils.getJsonObject(json, "pass"), context);
    }
}

package codechicken.lib.recipe;

import com.google.gson.JsonObject;
import net.minecraft.item.crafting.Ingredient;
import net.minecraft.util.JsonUtils;
import net.minecraftforge.common.crafting.CraftingHelper;
import net.minecraftforge.common.crafting.IIngredientFactory;
import net.minecraftforge.common.crafting.JsonContext;

import javax.annotation.Nonnull;

/**
 * Simple conditional ingredient.
 *
 * Created by covers1624 on 18/10/2017.
 */
public class ConditionalIngredientFactory implements IIngredientFactory {

    @Nonnull
    @Override
    public Ingredient parse(JsonContext context, JsonObject json) {
        if (!CraftingHelper.processConditions(JsonUtils.getJsonArray(json, "conditions"), context)) {
            if (json.has("fail")) {
                CraftingHelper.getIngredient(JsonUtils.getJsonObject(json, "fail"), context);
            }
            return Ingredient.EMPTY;
        }
        return CraftingHelper.getIngredient(JsonUtils.getJsonObject(json, "pass"), context);
    }
}

Fix CondtionalIngredientFactory parsing of fail ingredient.