package com.spaceout;

import android.app.Activity;

import android.content.Intent;

import android.os.Bundle;

import android.util.Log;

import android.view.View;

public class MainActivity extends Activity {
    private static final int REQUEST_CODE = 1;

    private String ipAddress;

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

    public void setNetwork(View view) {
        Intent networkIntent = new Intent(this, NetworkActivity.class);
        networkIntent.putExtra("ipAddress", this.ipAddress);
        startActivityForResult(networkIntent, REQUEST_CODE);
    }

    @Override
    public void onDestroy() {
        stopService(new Intent(this, NeuralAlertnessService.class));

        super.onDestroy();
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // Check which request we're responding to
        if (requestCode == REQUEST_CODE) {
            // Make sure the request was successful
            if (resultCode == RESULT_OK) {
                this.ipAddress = data.getStringExtra("ipAddress");
                Log.d("SPACEOUT", "ip address of server set to " + this.ipAddress);

                // restart the service with the new ip address
                stopService(new Intent(this, NeuralAlertnessService.class));
                Intent serviceIntent = new Intent(this, NeuralAlertnessService.class);
                serviceIntent.putExtra("ipAddress", this.ipAddress);
                startService(serviceIntent);
            }
        }
    }

}

package com.spaceout;

import android.app.Activity;

import android.content.Intent;

import android.os.Bundle;

import android.util.Log;

import android.view.View;

import android.widget.TextView;

public class MainActivity extends Activity {
    private static final int REQUEST_CODE = 1;

    private String ipAddress;

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

    public void setNetwork(View view) {
        Intent networkIntent = new Intent(this, NetworkActivity.class);
        networkIntent.putExtra("ipAddress", this.ipAddress);
        startActivityForResult(networkIntent, REQUEST_CODE);
    }

    @Override
    public void onDestroy() {
        stopService(new Intent(this, NeuralAlertnessService.class));

        super.onDestroy();
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // Check which request we're responding to
        if (requestCode == REQUEST_CODE) {
            // Make sure the request was successful
            if (resultCode == RESULT_OK) {
                this.ipAddress = data.getStringExtra("ipAddress");
                Log.d("SPACEOUT", "ip address of server set to " + this.ipAddress);

                // restart the service with the new ip address
                stopService(new Intent(this, NeuralAlertnessService.class));
                Intent serviceIntent = new Intent(this, NeuralAlertnessService.class);
                serviceIntent.putExtra("ipAddress", this.ipAddress);
                startService(serviceIntent);

                TextView subtitles = (TextView) findViewById(R.id.subtitles);
                subtitles.setText("IP address: " + ipAddress + "\n\n---\n\n");
            }
        }
    }

}

Clear subtitles and display ip address when network settings are changed


package fr.oni.gaagaa.api;

import java.util.List;

import fr.oni.gaagaa.model.twitter.Authenticated;
import fr.oni.gaagaa.model.twitter.Tweet;
import fr.oni.gaagaa.model.twitter.TwitterUser;
import retrofit.http.Body;
import retrofit.http.Field;
import retrofit.http.FormUrlEncoded;
import retrofit.http.GET;
import retrofit.http.Header;
import retrofit.http.Headers;
import retrofit.http.POST;
import retrofit.http.Query;

public interface TwitterApi {

    @FormUrlEncoded
    @POST("/oauth2/token")
    Authenticated authorizeUser(@Header("Authorization") String authorization,
                                @Field("grant_type") String grantType);

    @Headers({
            "Content-Type: application/json"
    })
    @GET("/1.1/lists/statuses.json")
    List<Tweet> getTwitterStream(@Query("slug") String slug,
                                 @Query("owner_screen_name") String screenName);

    @GET("/1.1/account/verify_credentials.json")
    TwitterUser verifyCredentials(@Header("Authorization") String authorization);

    @POST("/1.1/statuses/update.json")
    Tweet sendUpdate(@Header("Authorization") String authorization, @Body String status);

    @GET("/statuses/user_timeline.json")
    List<Tweet> getUserTimeline(@Query("screen_name") String screenName, @Query("count") int count);
}

package fr.oni.gaagaa.api;

import java.util.List;

import fr.oni.gaagaa.model.twitter.Authenticated;
import fr.oni.gaagaa.model.twitter.Tweet;
import fr.oni.gaagaa.model.twitter.TwitterUser;
import retrofit.http.Body;
import retrofit.http.Field;
import retrofit.http.FormUrlEncoded;
import retrofit.http.GET;
import retrofit.http.Header;
import retrofit.http.Headers;
import retrofit.http.POST;
import retrofit.http.Query;

public interface TwitterApi {

    @GET("/lists/statuses.json")
    List<Tweet> getTwitterStream(@Query("slug") String slug,
                                 @Query("owner_screen_name") String screenName);

    @GET("/account/verify_credentials.json")
    TwitterUser verifyCredentials(@Header("Authorization") String authorization);

    @POST("/statuses/update.json")
    Tweet sendUpdate(@Header("Authorization") String authorization, @Body String status);

    @GET("/statuses/user_timeline.json")
    List<Tweet> getUserTimeline(@Query("screen_name") String screenName, @Query("count") int count);
}

Change paths for twitter API

Change paths for twitter API


/*
 * Copyright (c) 2015 Hewlett Packard Enterprise Development LP.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */

package org.opendaylight.nic.listeners.impl;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import static org.junit.Assert.assertNotNull;

@PrepareForTest({LinkDeletedImpl.class})
@RunWith(PowerMockRunner.class)
/**
 * Created by yrineu on 12/01/16.
 */
public class LinkDeletedImplTest {

    private LinkDeletedImpl linkDeletedMock;

    @Before
    public void setUp() {
        linkDeletedMock = PowerMockito.spy(new LinkDeletedImpl());
    }

    @Test
    public void testTimestampNotNull() {
        assertNotNull(linkDeletedMock.getTimeStamp());
    }

}

/*
 * Copyright (c) 2015 Hewlett Packard Enterprise Development LP.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */

package org.opendaylight.nic.listeners.impl;

import org.junit.Before;
import org.junit.Test;
import org.powermock.api.mockito.PowerMockito;

import static org.junit.Assert.assertNotNull;

/**
 * Created by yrineu on 12/01/16.
 */
public class LinkDeletedImplTest {

    private LinkDeletedImpl linkDeletedMock;

    @Before
    public void setUp() {
        linkDeletedMock = PowerMockito.spy(new LinkDeletedImpl());
    }

    @Test
    public void testTimestampNotNull() {
        assertNotNull(linkDeletedMock.getTimeStamp());
    }
}

Increase intent-listeners coverage on LinkDeletedImpl.

Change-Id: Ibddecf61379ef34f2d2fd90adc1a512188583fbd
Signed-off-by: Victor Mota <a399842758ce81a1b2704ada69a36369cee4aa4d@atlantico.com.br>


package ru.ydn.wicket.wicketorientdb.model;

import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;

import com.orientechnologies.orient.core.type.ODocumentWrapper;

/**
 * {@link IModel} for a {@link ODocumentWrapper}s
 *
 * @param <T> {@link ODocumentWrapper} type
 */
public class ODocumentWrapperModel<T extends ODocumentWrapper> extends Model<T> {
	private static final long serialVersionUID = 1L;

	private boolean needToReload=false;

	public ODocumentWrapperModel() {
		super();
	}

	public ODocumentWrapperModel(T object) {
		super(object);
		needToReload=false;
	}

	@Override
	public T getObject() {
		T ret = super.getObject();
		if(ret != null && needToReload) {
			ret.load();
			needToReload = false;
		}
		return ret;
	}

	@Override
	public void setObject(T object) {
		super.setObject(object);
		needToReload = false;
	}

	@Override
	public void detach() {
		T ret = getObject();
		if (ret != null && !ret.getDocument().getIdentity().isNew()) {
			needToReload = true;
		}
		super.detach();
	}

}

package ru.ydn.wicket.wicketorientdb.model;

import com.orientechnologies.orient.core.exception.ORecordNotFoundException;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;

import com.orientechnologies.orient.core.type.ODocumentWrapper;

/**
 * {@link IModel} for a {@link ODocumentWrapper}s
 *
 * @param <T> {@link ODocumentWrapper} type
 */
public class ODocumentWrapperModel<T extends ODocumentWrapper> extends Model<T> {
	private static final long serialVersionUID = 1L;

	private boolean needToReload=false;

	public ODocumentWrapperModel() {
		super();
	}

	public ODocumentWrapperModel(T object) {
		super(object);
		needToReload=false;
	}

	@Override
	public T getObject() {
		try {
			T ret = super.getObject();
			if(ret != null && needToReload) {
				ret.load();
				needToReload = false;
			}
			return ret;
		} catch (ORecordNotFoundException e) {
			return null;
		}
	}

	@Override
	public void setObject(T object) {
		super.setObject(object);
		needToReload = false;
	}

	@Override
	public void detach() {
		T ret = getObject();
		if (ret != null && !ret.getDocument().getIdentity().isNew()) {
			needToReload = true;
		}
		super.detach();
	}

}

Return null if record doesn't exists in database


package org.knowm.xchange.kucoin.service;

import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.service.trade.params.TradeHistoryParamCurrencyPair;
import org.knowm.xchange.service.trade.params.TradeHistoryParamPaging;

public class KucoinTradeHistoryParams implements TradeHistoryParamCurrencyPair, TradeHistoryParamPaging {

  private CurrencyPair currencyPair;
  private Integer pageLength;
  private Integer pageNumber;

  @Override
  public Integer getPageLength() {
    return pageLength;
  }

  @Override
  public void setPageLength(Integer pageLength) {

    this.pageLength = pageLength;
  }

  @Override
  public Integer getPageNumber() {

    return pageNumber;
  }

  @Override
  public void setPageNumber(Integer pageNumber) {

    this.pageNumber = pageNumber;
  }

  @Override
  public CurrencyPair getCurrencyPair() {

    return currencyPair;
  }

  @Override
  public void setCurrencyPair(CurrencyPair pair) {

    this.currencyPair = pair;
  }

}

package org.knowm.xchange.kucoin.service;

import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.service.trade.params.TradeHistoryParamCurrencyPair;
import org.knowm.xchange.service.trade.params.TradeHistoryParamPaging;
import org.knowm.xchange.service.trade.params.TradeHistoryParamsTimeSpan;

import java.util.Date;

public class KucoinTradeHistoryParams implements
  TradeHistoryParamCurrencyPair, TradeHistoryParamPaging, TradeHistoryParamsTimeSpan
{

  private CurrencyPair currencyPair;
  private Integer pageLength;
  private Integer pageNumber;
  private Date startTime;
  private Date endTime;

  @Override
  public Integer getPageLength() {
    return pageLength;
  }

  @Override
  public void setPageLength(Integer pageLength) {

    this.pageLength = pageLength;
  }

  @Override
  public Integer getPageNumber() {

    return pageNumber;
  }

  @Override
  public void setPageNumber(Integer pageNumber) {

    this.pageNumber = pageNumber;
  }

  @Override
  public CurrencyPair getCurrencyPair() {

    return currencyPair;
  }

  @Override
  public void setCurrencyPair(CurrencyPair pair) {

    this.currencyPair = pair;
  }

  @Override
  public Date getStartTime() {

    return startTime;
  }

  @Override
  public void setStartTime(Date startTime) {

    this.startTime = startTime;
  }

  @Override
  public Date getEndTime() {

    return endTime;
  }

  @Override
  public void setEndTime(Date endTime) {

    this.endTime = endTime;
  }

}

[kucoin] Allow to specify (optional) timespan on trade history params.


package com.github.aureliano.edocs.secure.hash;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.xml.bind.DatatypeConverter;

import com.github.aureliano.edocs.secure.model.PasswordEncryptionModel;

public final class PasswordHashGenerator {

	private PasswordHashGenerator() {}

	public static final String generate(PasswordEncryptionModel pwd) {
		String text = pwd.getPassword() + pwd.getSalt();

		try {
			for (short i = 0; i < pwd.getHashIterations(); i++) {
				text = hash(text, pwd.getAlgorithm().getLabel());
			}
		} catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) {
			throw new SecurityException(ex);
		}

		return text;
	}

	private static String hash(String text, String algorithm) throws NoSuchAlgorithmException, UnsupportedEncodingException {
		MessageDigest md = MessageDigest.getInstance(algorithm);
		md.update(text.getBytes("UTF-8"));

		byte bytes[] = md.digest();
		String hash = DatatypeConverter.printBase64Binary(bytes);

		return hash;
	}
}

package com.github.aureliano.edocs.secure.hash;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.xml.bind.DatatypeConverter;

import com.github.aureliano.edocs.common.config.AppConfiguration;
import com.github.aureliano.edocs.common.config.ConfigurationSingleton;
import com.github.aureliano.edocs.common.config.SecureConfiguration;
import com.github.aureliano.edocs.secure.model.Algorithm;
import com.github.aureliano.edocs.secure.model.PasswordEncryptionModel;

public final class PasswordHashGenerator {

	private PasswordHashGenerator() {}

	public static final String generate(PasswordEncryptionModel pwd) {
		String text = pwd.getPassword() + pwd.getSalt();

		try {
			for (short i = 0; i < pwd.getHashIterations(); i++) {
				text = hash(text, pwd.getAlgorithm().getLabel());
			}
		} catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) {
			throw new SecurityException(ex);
		}

		return text;
	}

	public static final String generateFromAppConfiguration(String password) {
		AppConfiguration appConfiguration = ConfigurationSingleton.instance().getAppConfiguration();
		SecureConfiguration configuration = appConfiguration.getSecureConfiguration();

		return PasswordHashGenerator.generate(new PasswordEncryptionModel()
			.withAlgorithm(Algorithm.valueOf(configuration.getAlgorithm()))
			.withHashIterations(configuration.getHashIterations())
			.withSalt(configuration.getSalt())
			.withPassword(password));
	}

	private static String hash(String text, String algorithm) throws NoSuchAlgorithmException, UnsupportedEncodingException {
		MessageDigest md = MessageDigest.getInstance(algorithm);
		md.update(text.getBytes("UTF-8"));

		byte bytes[] = md.digest();
		String hash = DatatypeConverter.printBase64Binary(bytes);

		return hash;
	}
}

Add method to generate passowrd hash with configuration properties.


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

import org.vanilladb.bench.remote.SutResultSet;
import org.vanilladb.core.remote.storedprocedure.SpResultSet;
import org.vanilladb.core.sql.Record;

public class VanillaDbSpResultSet implements SutResultSet {
	private String message;
	private boolean isCommitted;

	public VanillaDbSpResultSet(SpResultSet result) {
		Record[] records = result.getRecords();
		message = records[0].toString();
		isCommitted = result.isCommitted();
	}

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

	@Override
	public String outputMsg() {
		return message;
	}
}

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

import org.vanilladb.bench.remote.SutResultSet;
import org.vanilladb.core.remote.storedprocedure.SpResultSet;
import org.vanilladb.core.sql.Record;

public class VanillaDbSpResultSet implements SutResultSet {
	private String message;
	private boolean isCommitted;

	public VanillaDbSpResultSet(SpResultSet result) {
		Record[] records = result.getRecords();
		if (records.length > 0)
			message = records[0].toString();
		else
			message = "";
		isCommitted = result.isCommitted();
	}

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

	@Override
	public String outputMsg() {
		return message;
	}
}

Add a check for printing results

Add a check for printing results


/**
 * Copyright (c) 2005-2012 https://github.com/zhangkaitao
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.huntering.common.plugin.entity;

/**
 * <p>实体实现该接口，表示需要进行状态管理
 */
public interface Stateable<T extends Enum<? extends Stateable.Status>> {

    public void setStatus(T status);

    public T getStatus();

    /**
     * 标识接口，所有状态实现，需要实现该状态接口
     */
    public static interface Status {
    }

    /**
     * 审核状态
     */
    public static enum RegisterStatus implements Status {
        waiting("等待审核"), fail("审核失败"), success("审核成功");
        private final String info;

        private RegisterStatus(String info) {
            this.info = info;
        }

        public String getInfo() {
            return info;
        }
    }

    /**
     * 是否显示
     */
    public static enum ShowStatus implements Status {
        hide("不显示"), show("显示");
        private final String info;

        private ShowStatus(String info) {
            this.info = info;
        }

        public String getInfo() {
            return info;
        }
    }

    public static enum AuditStatus implements Status {
    	ACTIVE,
		DELETED,
		DISABLED
    }

    public static enum MessageType implements Status {
    	RESUME,
		ACTIVITY
    }

    public static enum PeopleRole implements Status {
    	INTERVIEWER,
		INTERVIEE,
		PARTICIPANT
    }
}

/**
 * Copyright (c) 2005-2012 https://github.com/zhangkaitao
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.huntering.common.plugin.entity;

/**
 * <p>实体实现该接口，表示需要进行状态管理
 */
public interface Stateable<T extends Enum<? extends Stateable.Status>> {

    public void setStatus(T status);

    public T getStatus();

    /**
     * 标识接口，所有状态实现，需要实现该状态接口
     */
    public static interface Status {
    }

    /**
     * 审核状态
     */
    public static enum RegisterStatus implements Status {
        waiting("等待审核"), fail("审核失败"), success("审核成功");
        private final String info;

        private RegisterStatus(String info) {
            this.info = info;
        }

        public String getInfo() {
            return info;
        }
    }

    /**
     * 是否显示
     */
    public static enum ShowStatus implements Status {
        hide("不显示"), show("显示");
        private final String info;

        private ShowStatus(String info) {
            this.info = info;
        }

        public String getInfo() {
            return info;
        }
    }

    public static enum AuditStatus implements Status {
    	ACTIVE,
		DELETED,
		DISABLED
    }

    public static enum MessageType implements Status {
    	RESUME,
		ACTIVITY
    }

    public static enum PeopleRole implements Status {
    	INTERVIEWER,
    	INTERVIEWEE,
		PARTICIPANT
    }
}

Modify the people role enum

Modify the people role enum


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

package com.google.sps.servlets;

import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/** Servlet that takes in audio stream and retrieves
 ** user input string to display. */

@WebServlet("/audio-input")
public class AudioInputServlet extends HttpServlet {

  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setContentType("text/html;");
    response.getWriter().println("
Hello world!
");
  }
}

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

package com.google.sps.servlets;
import java.util.*;

import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/** Servlet that takes in audio stream and retrieves
 ** user input string to display. */

@WebServlet("/audio-input")
public class AudioInputServlet extends HttpServlet {

  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    Object formdata = request.getParameter("file");
    System.out.println(formdata);
    System.out.println("Got to servlet");
    //response.setContentType("text/html;");
    //response.getWriter().println("
Hello world!
");
  }
}

Add get retrieval of FormData

Add get retrieval of FormData


package org.springframework.cloud.commons.util;

import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;

import lombok.Data;

/**
 * @author Spencer Gibb
 */
@Data
@ConfigurationProperties(InetUtilsProperties.PREFIX)
public class InetUtilsProperties {
	public static final String PREFIX = "spring.cloud.inetutils";

	/**
	 * The default hostname. Used in case of errors.
	 */
	private String defaultHostname = "localhost";

	/**
	 * The default ipaddress. Used in case of errors.
	 */
	private String defaultIpAddress = "127.0.0.1";

	/**
	 * Timeout in seconds for calculating hostname.
	 */
	@Value("${spring.util.timeout.sec:${SPRING_UTIL_TIMEOUT_SEC:1}}")
	private int timeoutSeconds = 1;

	/**
	 * List of Java regex expressions for network interfaces that will be ignored.
	 */
	private List<String> ignoredInterfaces = new ArrayList<>();

	/**
	 * Use only interfaces with site local addresses. See {@link InetAddress#isSiteLocalAddress()} for more details.
	 */
	private boolean useOnlySiteLocalInterfaces = false;

	/**
	 * List of Java regex expressions for network addresses that will be ignored.
	 */
	private List<String> preferredNetworks = new ArrayList<>();
}

package org.springframework.cloud.commons.util;

import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;

import lombok.Data;

/**
 * @author Spencer Gibb
 */
@Data
@ConfigurationProperties(InetUtilsProperties.PREFIX)
public class InetUtilsProperties {
	public static final String PREFIX = "spring.cloud.inetutils";

	/**
	 * The default hostname. Used in case of errors.
	 */
	private String defaultHostname = "localhost";

	/**
	 * The default ipaddress. Used in case of errors.
	 */
	private String defaultIpAddress = "127.0.0.1";

	/**
	 * Timeout in seconds for calculating hostname.
	 */
	@Value("${spring.util.timeout.sec:${SPRING_UTIL_TIMEOUT_SEC:1}}")
	private int timeoutSeconds = 1;

	/**
	 * List of Java regex expressions for network interfaces that will be ignored.
	 */
	private List<String> ignoredInterfaces = new ArrayList<>();

	/**
	 * Use only interfaces with site local addresses. See {@link InetAddress#isSiteLocalAddress()} for more details.
	 */
	private boolean useOnlySiteLocalInterfaces = false;

	/**
	 * List of Java regex expressions for network addresses that will be preferred.
	 */
	private List<String> preferredNetworks = new ArrayList<>();
}

Update javadoc term to fix copy/paste error


package com.devskiller.friendly_id.spring;

import java.util.UUID;

import com.fasterxml.jackson.databind.Module;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.devskiller.friendly_id.FriendlyId;
import com.devskiller.friendly_id.jackson.FriendlyIdModule;

@Configuration
public class FriendlyIdConfiguration extends WebMvcConfigurerAdapter {

	@Override
	public void addFormatters(FormatterRegistry registry) {
		registry.addConverter(new StringToUuidConverter());
		super.addFormatters(registry);
	}

	@Bean
	public Module friendlyIdModule() {
		return new FriendlyIdModule();
	}

	//FIXME: make this public
	public static class StringToUuidConverter implements Converter<String, UUID> {

		@Override
		public UUID convert(String id) {
			return FriendlyId.toUuid(id);
		}
	}
}

package com.devskiller.friendly_id.spring;

import java.util.UUID;

import com.fasterxml.jackson.databind.Module;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.devskiller.friendly_id.FriendlyId;
import com.devskiller.friendly_id.jackson.FriendlyIdModule;

@Configuration
public class FriendlyIdConfiguration extends WebMvcConfigurerAdapter {

	@Override
	public void addFormatters(FormatterRegistry registry) {
		registry.addConverter(new StringToUuidConverter());
		registry.addConverter(new UuidToStringConverter());
		super.addFormatters(registry);
	}

	@Bean
	public Module friendlyIdModule() {
		return new FriendlyIdModule();
	}

	//FIXME: make this public
	public static class StringToUuidConverter implements Converter<String, UUID> {

		@Override
		public UUID convert(String id) {
			return FriendlyId.toUuid(id);
		}
	}

	public static class UuidToStringConverter implements Converter<UUID, String> {

		@Override
		public String convert(UUID id) {
			return FriendlyId.toFriendlyId(id);
		}
	}
}

Add UUID to string Spring converter

Add UUID to string Spring converter


package com.fundynamic.d2tm.math;

import com.fundynamic.d2tm.game.map.Cell;
import com.fundynamic.d2tm.game.terrain.Terrain;

import java.util.List;

public class Random {

    /**
     * Returns value between min *until* max, not including max.
     *
     * Example, if you want a number between 0 or 1, you do: getRandomBetween(0, 2)
     *
     * @param min
     * @param max
     * @return
     */
    public static int getRandomBetween(int min, int max) {
        final int maxForRandom = max - min;
        return (min + getInt(maxForRandom));
    }

    public static int getInt(int max) {
        return (int) (Math.random() * max);
    }

    /**
     * Given a list of T, returns a random item from the list.
     * @param list
     * @param <T>
     * @return
     */
    public static <T> T getRandomItem(List<T> list) {
        if (list.isEmpty()) return null;
        return list.get(getInt(list.size()));
    }
}

package com.fundynamic.d2tm.math;

import java.util.List;

public class Random {

    private static java.util.Random random = new java.util.Random();
    /**
     * Returns value between min *until* max, not including max.
     *
     * Example, if you want a number between 0 or 1, you do: getRandomBetween(0, 2)
     *
     * @param min
     * @param max
     * @return
     */
    public static int getRandomBetween(int min, int max) {
        final int maxForRandom = max - min;
        return (min + getInt(maxForRandom));
    }

    public static int getInt(int max) {
        return random.nextInt(max);
    }

    /**
     * Given a list of T, returns a random item from the list.
     * @param list
     * @param <T>
     * @return
     */
    public static <T> T getRandomItem(List<T> list) {
        if (list.isEmpty()) return null;
        return list.get(getInt(list.size()));
    }
}

Make it more random as suggested by Mark Platvoet


package chapter_5;

public class Insertion {
  public String insertMIntoN(int m, int n, int i, int j) {
    int result = clearBits(n, i, j);
    return Integer.toBinaryString(result | (m << i));
  }

  private int clearBits(int n, int i, int j) {
    int val = Integer.MAX_VALUE >>> (31 - j - 1);
    int val2 = Integer.MAX_VALUE << i;
    int mask = val & val2;
    return n & ~(mask);
  }
}

package chapter_5;

public class Insertion {
  public String insertMIntoN(int m, int n, int i, int j) {
    int result = clearBits(n, i, j);
    return Integer.toBinaryString(result | (m << i));
  }

  private int clearBits(int n, int i, int j) {
    int val = ~(0) >>> (31 - j);
    int val2 = ~(0) << i;
    int mask = val & val2;
    return n & ~(mask);
  }
}

Use ~0 instead of integer max value, Use Logical right shift which is important here


package nl.jft.logic.match.event;

import nl.jft.logic.match.Match;
import nl.jft.logic.match.event.impl.GoalRemovedEvent;
import nl.jft.logic.match.event.impl.GoalScoredEvent;
import nl.jft.logic.match.event.impl.MatchStatusChangedEvent;

/**
 * A {@code MatchListener} can be used to get notified about certain events in a {@link Match}.
 *
 * @author Lesley
 */
public interface MatchListener {

    void onMatchStatusChanged(MatchStatusChangedEvent event);

    void onGoalScored(GoalScoredEvent event);

    void onGoalRemoved(GoalRemovedEvent event);

}

package nl.jft.logic.match.event;

import nl.jft.logic.match.Match;
import nl.jft.logic.match.event.impl.GoalRemovedEvent;
import nl.jft.logic.match.event.impl.GoalScoredEvent;
import nl.jft.logic.match.event.impl.MatchStatusChangedEvent;

/**
 * A {@code MatchListener} can be used to get notified about certain events in a {@link Match}.
 *
 * @author Lesley
 */
public interface MatchListener {

    /**
     * The {@code onMatchStatusChanged} method gets called whenever a {@link nl.jft.logic.match.MatchStatus}
     * change occurs in a {@link Match}. This method blocks, so make sure to keep the return time as low as possible.
     *
     * @param event The {@link MatchStatusChangedEvent} that occurred in the {@code Match}.
     */
    void onMatchStatusChanged(MatchStatusChangedEvent event);

    /**
     * The {@code onGoalScored} method gets called whenever a {@link nl.jft.logic.match.Goal}
     * is scored in a {@link Match}. This method blocks, so make sure to keep the return time as low as possible.
     *
     * @param event The {@link GoalScoredEvent} that occurred in the {@code Match}.
     */
    void onGoalScored(GoalScoredEvent event);

    /**
     * The {@code onGoalRemoved} method gets called whenever a {@link nl.jft.logic.match.Goal}
     * is removed from a {@link Match}. This method blocks, so make sure to keep the return time as low as possible.
     *
     * @param event The {@link GoalRemovedEvent} that occurred in the {@code Match}.
     */
    void onGoalRemoved(GoalRemovedEvent event);

}

Add missing documentation to interface.

Add missing documentation to interface.


package seedu.address.logic;

import javafx.collections.ObservableList;
import seedu.address.logic.commands.CommandResult;
import seedu.address.logic.commands.exceptions.CommandException;
import seedu.address.model.task.ReadOnlyTask;

/**
 * API of the Logic component
 */
public interface Logic {
    /**
     * Executes the command and returns the result.
     * @param commandText The command as entered by the user.
     * @return the result of the command execution.
     * @throws CommandException If an error occurs during command execution.
     */
    CommandResult execute(String commandText) throws CommandException;

    /** Returns the filtered list of tasks */
    ObservableList<ReadOnlyTask> getFilteredTaskList();

}

package seedu.address.logic;

import javafx.collections.ObservableList;
import seedu.address.logic.commands.CommandResult;
import seedu.address.logic.commands.exceptions.CommandException;
import seedu.address.model.task.ReadOnlyTask;

/**
 * API of the Logic component
 */
public interface Logic {
    /**
     * Executes the command and returns the result.
     * @param commandText The command as entered by the user.
     * @return the result of the command execution.
     * @throws CommandException If an error occurs during command execution.
     */
    CommandResult execute(String commandText) throws CommandException;

    /** Returns the filtered list of tasks */
    ObservableList<ReadOnlyTask> getFilteredTaskList();

    /** Returns the filtered list of incomplete tasks */
    ObservableList<ReadOnlyTask> getFilteredIncompleteTaskList();
}

Add methods to get incomplete task only

Add methods to get incomplete task only


package com.github.aureliano.achmed.helper;

import java.lang.reflect.Method;

public final class ReflectionHelper {

	private ReflectionHelper() {
		throw new InstantiationError(this.getClass().getName() + " cannot be instantiated.");
	}

    public static String getSimpleAccessMethodName(Method method) {
    	String name = method.getName().replaceFirst("^(get|is|set|with)", "");
    	return Character.toLowerCase(name.charAt(0)) + name.substring(1);
    }
}

package com.github.aureliano.achmed.helper;

import java.lang.reflect.Method;

import com.github.aureliano.achmed.exception.AchmedException;

public final class ReflectionHelper {

	private ReflectionHelper() {
		throw new InstantiationError(this.getClass().getName() + " cannot be instantiated.");
	}

    public static Object callMethod(Object object, String methodName, Class<?>[] parametersType, Object[] methodParameters) {
    	Class<?> clazz = object.getClass();
    	try {
    		Method method = clazz.getMethod(methodName, parametersType);
    		return method.invoke(object, methodParameters);
    	} catch (Exception ex) {
    		throw new AchmedException(ex);
    	}
    }

    public static String getSimpleAccessMethodName(Method method) {
    	String name = method.getName().replaceFirst("^(get|is|set|with)", "");
    	return Character.toLowerCase(name.charAt(0)) + name.substring(1);
    }
}

Add method to call method through reflection.


package com.xtremelabs.robolectric.shadows;

import android.content.res.Resources;
import android.content.res.TypedArray;
import com.xtremelabs.robolectric.Robolectric;
import com.xtremelabs.robolectric.internal.Implementation;
import com.xtremelabs.robolectric.internal.Implements;

@SuppressWarnings({"UnusedDeclaration"})
@Implements(TypedArray.class)
public class ShadowTypedArray {
    @Implementation
    public Resources getResources() {
        return Robolectric.application.getResources();
    }
}

package com.xtremelabs.robolectric.shadows;

import android.content.res.Resources;
import android.content.res.TypedArray;
import com.xtremelabs.robolectric.Robolectric;
import com.xtremelabs.robolectric.internal.Implementation;
import com.xtremelabs.robolectric.internal.Implements;

@SuppressWarnings({"UnusedDeclaration"})
@Implements(TypedArray.class)
public class ShadowTypedArray {
    @Implementation
    public Resources getResources() {
        return Robolectric.application.getResources();
    }

    @Implementation
    public int getInt(int index, int defValue) {
        return defValue;
    }
}

Return the default value from TypedArray getInt calls


package adapters;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import converters.JsonConverter;
import datamodel.EventHubMessage;
import datamodel.Measurement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Date;

public class EventHubAdapter implements Adapter {
    private static final Logger logger = LoggerFactory.getLogger(EventHubAdapter.class);

    public String adaptMessage(String filteredJson, Measurement measurement) {
        String command = measurement.getCommand();
        String usedTool = command.substring(0, command.indexOf(' '));

        ObjectMapper mapper = new ObjectMapper();
        JsonNode data = null;

        try {
            data = mapper.readTree(filteredJson);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }

        EventHubMessage eventHubMessage = new EventHubMessage();
        eventHubMessage.setComponent(null);
        eventHubMessage.setObject(usedTool);
        eventHubMessage.setLabels(new String[]{"userId-" + measurement.getClientId()});
        eventHubMessage.setType(null);
        eventHubMessage.setData(data);
        eventHubMessage.setTimestamp(Long.toString((new Date().getTime()) / 1000));
        return JsonConverter.objectToJsonString(eventHubMessage);
    }
}

package adapters;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import converters.JsonConverter;
import datamodel.EventHubMessage;
import datamodel.Measurement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;

public class EventHubAdapter implements Adapter {
    private static final Logger logger = LoggerFactory.getLogger(EventHubAdapter.class);
    public static final UUID uuid = UUID.randomUUID();

    public String adaptMessage(String filteredJson, Measurement measurement) {
        String command = measurement.getCommand();
        String usedTool = command.substring(0, command.indexOf(' '));

        ObjectMapper mapper = new ObjectMapper();
        JsonNode data = null;

        try {
            data = mapper.readTree(filteredJson);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }

        EventHubMessage eventHubMessage = new EventHubMessage();
        eventHubMessage.setComponent(uuid.toString());
        eventHubMessage.setObject(usedTool);
        eventHubMessage.setLabels(new String[]{"userId-" + measurement.getClientId()});
        eventHubMessage.setType(null);
        eventHubMessage.setData(data);
        eventHubMessage.setTimestamp((new Date().getTime()) / 1000);
        return JsonConverter.objectToJsonString(eventHubMessage);
    }
}

Use a uuid to identify component.

Use a uuid to identify component.


/*****************************************************************************
 ** Copyright (c) 2010 - 2012 Ushahidi Inc
 ** All rights reserved
 ** Contact: team@ushahidi.com
 ** Website: http://www.ushahidi.com
 **
 ** GNU Lesser General Public License Usage
 ** This file may be used under the terms of the GNU Lesser
 ** General Public License version 3 as published by the Free Software
 ** Foundation and appearing in the file LICENSE.LGPL included in the
 ** packaging of this file. Please review the following information to
 ** ensure the GNU Lesser General Public License version 3 requirements
 ** will be met: http://www.gnu.org/licenses/lgpl.html.
 **
 **
 ** If you have questions regarding the use of this file, please contact
 ** Ushahidi developers at team@ushahidi.com.
 **
 *****************************************************************************/

package com.crowdmap.java.sdk.json;

/**
 * The class represents the Main response returned as a result of a Crowdmap
 * api call.
 *
 * @author eyedol
 *
 */
public class ResponseJson {

	public String next;

	public String curr;

	public String prev;

	public boolean success;

	public int status;

}

/*****************************************************************************
 ** Copyright (c) 2010 - 2012 Ushahidi Inc
 ** All rights reserved
 ** Contact: team@ushahidi.com
 ** Website: http://www.ushahidi.com
 **
 ** GNU Lesser General Public License Usage
 ** This file may be used under the terms of the GNU Lesser
 ** General Public License version 3 as published by the Free Software
 ** Foundation and appearing in the file LICENSE.LGPL included in the
 ** packaging of this file. Please review the following information to
 ** ensure the GNU Lesser General Public License version 3 requirements
 ** will be met: http://www.gnu.org/licenses/lgpl.html.
 **
 **
 ** If you have questions regarding the use of this file, please contact
 ** Ushahidi developers at team@ushahidi.com.
 **
 *****************************************************************************/

package com.crowdmap.java.sdk.json;

/**
 * The class represents the Main response returned as a result of a Crowdmap api
 * call.
 *
 *
 */
public class ResponseJson {

	public String next;

	public String curr;

	public String prev;

	public boolean success;

	public int status;

	public String timestamp;

	public int qcount;

}

Add missing properties to response json

Add missing properties to response json


package ml.duncte123.skybot.config;

import com.google.gson.*;
import org.apache.commons.text.translate.UnicodeUnescaper;

import java.io.*;

public class ConfigLoader {

    /**
     * This will attempt to load the config and create it if it is not there
     * @param file the file to load
     * @return the loaded config
     * @throws Exception if something goes wrong
     */
    public static Config getConfig(final File file) throws Exception{
        if (!file.exists()) {
            file.createNewFile();
            final FileWriter writer = new FileWriter(file);
            writer.write("{}");
            writer.close();
        }
        return new BlankConfig(file);
    }

    public static class BlankConfig extends Config {

        private final File configFile;

        BlankConfig(final File file) throws Exception {
            super(null, new JsonParser().parse(new FileReader(file)).getAsJsonObject());
            this.configFile = file;
        }

        @Override
        public File getConfigFile()
        {
            return this.configFile;
        }

        @Override
        public void save() throws Exception {
            final Gson gson = new GsonBuilder().serializeNulls().setPrettyPrinting().serializeSpecialFloatingPointValues().create();
            final String json = gson.toJson(this.config);
            try {
                final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(this.configFile), "UTF-8"));
                new UnicodeUnescaper().translate(json, writer);
                writer.close();
            }
            catch (final IOException e)  {
                e.printStackTrace();
            }
        }

    }
}

package ml.duncte123.skybot.config;

import com.google.gson.*;
import org.apache.commons.text.translate.UnicodeUnescaper;

import java.io.*;

public class ConfigLoader {

    /**
     * This will attempt to load the config and create it if it is not there
     * @param file the file to load
     * @return the loaded config
     * @throws Exception if something goes wrong
     */
    public static Config getConfig(final File file) throws Exception{
        if (!file.exists()) {
            file.createNewFile();
            final FileWriter writer = new FileWriter(file);
            writer.write("{}");
            writer.close();
        }
        return new MainConfig(file);
    }

    public static class MainConfig extends Config {

        private final File configFile;

        MainConfig(final File file) throws Exception {
            super(null, new JsonParser().parse(new FileReader(file)).getAsJsonObject());
            this.configFile = file;
        }

        @Override
        public File getConfigFile()
        {
            return this.configFile;
        }

        @Override
        public void save() throws Exception {
            final Gson gson = new GsonBuilder().serializeNulls().setPrettyPrinting().serializeSpecialFloatingPointValues().create();
            final String json = gson.toJson(this.config);
            try {
                final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(this.configFile), "UTF-8"));
                new UnicodeUnescaper().translate(json, writer);
                writer.close();
            }
            catch (final IOException e)  {
                e.printStackTrace();
            }
        }

    }
}

Rename BlankConfig to something that makes more sense


package de.sldk.mc.metrics;

import io.prometheus.client.Gauge;
import org.bukkit.World;
import org.bukkit.plugin.Plugin;

public class LoadedChunks extends WorldMetric {

    private static final Gauge LOADED_CHUNKS = Gauge.build()
            .name(prefix("loaded_chunks_total"))
            .help("Chunks loaded per world")
            .labelNames("world")
            .create();

    public LoadedChunks(Plugin plugin) {
        super(plugin, LOADED_CHUNKS);
    }

    @Override
    protected void clear() {
    }

    @Override
    public void collect(World world) {
        LOADED_CHUNKS.labels(world.getName()).set(world.getLoadedChunks().length);
    }
}

package de.sldk.mc.metrics;

import io.prometheus.client.Gauge;
import org.bukkit.World;
import org.bukkit.plugin.Plugin;

public class LoadedChunks extends WorldMetric {

    private static final Gauge LOADED_CHUNKS = Gauge.build()
            .name(prefix("loaded_chunks_total"))
            .help("Chunks loaded per world")
            .labelNames("world")
            .create();

    public LoadedChunks(Plugin plugin) {
        super(plugin, LOADED_CHUNKS);
    }

    @Override
    protected void clear() {
		LOADED_CHUNKS.clear();
    }

    @Override
    public void collect(World world) {
        LOADED_CHUNKS.labels(world.getName()).set(world.getLoadedChunks().length);
    }
}

Reset world chunks metric to fix accumulating unloaded worlds

Signed-off-by: Byron Marohn <72c48d57fac8949117d5a1dd58341ee30497c114@live.com>


package me.coley.recaf.search;

/**
 * Type of query, useful for switching over query implementation types.
 *
 * @author Matt
 */
public enum QueryType {
	/**
	 * Match a class if it matches a given name.
	 */
	CLASS_NAME,
	/**
	 * Match a class if it inherits a given class.
	 */
	CLASS_INHERITANCE,
	/**
	 * Match a member if it matches a given definition.
	 */
	MEMBER_DEFINITION,
	/**
	 * TODO: Remove
	 *  - Outdated since people can do overlapping results of CLASS_INHERITANCE/MEMBER_DEF
	 */
	MEMBER_INHERITANCE,
	/**
	 * Match an instruction if it references a given definition.
	 */
	USAGE,
	/**
	 * Match an instruction / field-constant if it's string value matches a given pattern.
	 */
	STRING,
	/**
	 * Match an instruction if it contains a given value.
	 */
	VALUE,
	/**
	 * Match a method if it contains the given sequence of instruction patterns.
	 */
	INSTRUCTION_TEXT
}

package me.coley.recaf.search;

/**
 * Type of query, useful for switching over query implementation types.
 *
 * @author Matt
 */
public enum QueryType {
	/**
	 * Match a class if it matches a given name.
	 */
	CLASS_NAME,
	/**
	 * Match a class if it inherits a given class.
	 */
	CLASS_INHERITANCE,
	/**
	 * Match a member if it matches a given definition.
	 */
	MEMBER_DEFINITION,
	/**
	 * Match an instruction if it references a given definition.
	 */
	USAGE,
	/**
	 * Match an instruction / field-constant if it's string value matches a given pattern.
	 */
	STRING,
	/**
	 * Match an instruction if it contains a given value.
	 */
	VALUE,
	/**
	 * TODO: Implement this
	 *  - Will need to support multiple consecutive insns that are incomplete
	 *  - Pass a List<String>? <br>
	 * Match a method if it contains the given sequence of instruction patterns.
	 */
	INSTRUCTION_TEXT
}

Remove unused query-type, see old removal note


package be.digitalia.fosdem.api;

import java.util.Locale;

/**
 * This class contains all FOSDEM Urls
 *
 * @author Christophe Beyls
 *
 */
public class FosdemUrls {

	// private static final String SCHEDULE_URL = "https://fosdem.org/schedule/xml";
	private static final String SCHEDULE_URL = "https://archive.fosdem.org/2013/schedule/xml";
	private static final String EVENT_URL_FORMAT = "https://fosdem.org/%1$d/schedule/event/%2$s/";
	private static final String PERSON_URL_FORMAT = "https://fosdem.org/%1$d/schedule/speaker/%2$s/";

	public static String getSchedule() {
		return SCHEDULE_URL;
	}

	public static String getEvent(String slug, int year) {
		return String.format(Locale.US, EVENT_URL_FORMAT, year, slug);
	}

	public static String getPerson(String slug, int year) {
		return String.format(Locale.US, PERSON_URL_FORMAT, year, slug);
	}
}

package be.digitalia.fosdem.api;

import java.util.Locale;

/**
 * This class contains all FOSDEM Urls
 *
 * @author Christophe Beyls
 *
 */
public class FosdemUrls {

	private static final String SCHEDULE_URL = "https://fosdem.org/schedule/xml";
	private static final String EVENT_URL_FORMAT = "https://fosdem.org/%1$d/schedule/event/%2$s/";
	private static final String PERSON_URL_FORMAT = "https://fosdem.org/%1$d/schedule/speaker/%2$s/";

	public static String getSchedule() {
		return SCHEDULE_URL;
	}

	public static String getEvent(String slug, int year) {
		return String.format(Locale.US, EVENT_URL_FORMAT, year, slug);
	}

	public static String getPerson(String slug, int year) {
		return String.format(Locale.US, PERSON_URL_FORMAT, year, slug);
	}
}

Switch to current year's database URL

Switch to current year's database URL


package com.mcbans.firestar.mcbans;

import com.mcbans.firestar.mcbans.permission.Perms;

public enum BanType {
    GLOBAL  ("globalBan", Perms.BAN_GLOBAL),
    LOCAL   ("localBan", Perms.BAN_GLOBAL),
    TEMP    ("tempBan", Perms.BAN_TEMP),

    UNBAN   ("unBan", Perms.UNBAN),
    ;

    final private String actionName;
    final private Perms permission;

    private BanType(final String actionName, final Perms permission){
        this.actionName = actionName;
        this.permission = permission;
    }

    public String getActionName(){
        return this.actionName;
    }

    public Perms getPermission(){
        return this.permission;
    }
}

package com.mcbans.firestar.mcbans;

import com.mcbans.firestar.mcbans.permission.Perms;

public enum BanType {
    GLOBAL  ("globalBan", Perms.BAN_GLOBAL),
    LOCAL   ("localBan", Perms.BAN_LOCAL),
    TEMP    ("tempBan", Perms.BAN_TEMP),

    UNBAN   ("unBan", Perms.UNBAN),
    ;

    final private String actionName;
    final private Perms permission;

    private BanType(final String actionName, final Perms permission){
        this.actionName = actionName;
        this.permission = permission;
    }

    public String getActionName(){
        return this.actionName;
    }

    public Perms getPermission(){
        return this.permission;
    }
}

Fix local ban permission node

Fix local ban permission node


package com.optimaize.command4j.ext.extensions.logging.customlogging;

import com.google.common.base.Optional;
import com.optimaize.command4j.Command;
import com.optimaize.command4j.ExecutionContext;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;

/**
 * You are encouraged to override the methods to change the logging.
 * You may also override the {@link #before} method with an empty one to not log before at all.
 *
 * @author Fabian Kessler
 */
public class CommandExecutionLoggerImpl<A,R> implements CommandExecutionLogger<A, R> {

    @NotNull
    private final Logger logger;

    public CommandExecutionLoggerImpl(@NotNull Logger logger) {
        this.logger = logger;
    }

    @Override
    public void before(@NotNull Command<A, R> command, @NotNull ExecutionContext ec, @NotNull Optional<A> arg) {
        logger.info("Before {0} with arg {1}", command, arg);
    }

    @Override
    public void afterSuccess(@NotNull Command<A, R> command, @NotNull ExecutionContext ec, @NotNull Optional<A> arg, @Nullable R result) {
        logger.info("After success {0} result: {1}", command, result);
    }

    @Override
    public void afterFailure(@NotNull Command<A, R> command, @NotNull ExecutionContext ec, @NotNull Optional<A> arg, @NotNull Exception exception) {
        logger.info("After failure {0} exception: {1}", command, exception);
    }
}

package com.optimaize.command4j.ext.extensions.logging.customlogging;

import com.google.common.base.Optional;
import com.optimaize.command4j.Command;
import com.optimaize.command4j.ExecutionContext;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;

/**
 * You are encouraged to override the methods to change the logging.
 * You may also override the {@link #before} method with an empty one to not log before at all.
 *
 * @author Fabian Kessler
 */
public class CommandExecutionLoggerImpl<A,R> implements CommandExecutionLogger<A, R> {

    @NotNull
    private final Logger logger;

    public CommandExecutionLoggerImpl(@NotNull Logger logger) {
        this.logger = logger;
    }

    @Override
    public void before(@NotNull Command<A, R> command, @NotNull ExecutionContext ec, @NotNull Optional<A> arg) {
        logger.info("Before {} with arg {}", command, arg);
    }

    @Override
    public void afterSuccess(@NotNull Command<A, R> command, @NotNull ExecutionContext ec, @NotNull Optional<A> arg, @Nullable R result) {
        logger.info("After success {} result: {}", command, result);
    }

    @Override
    public void afterFailure(@NotNull Command<A, R> command, @NotNull ExecutionContext ec, @NotNull Optional<A> arg, @NotNull Exception exception) {
        logger.info("After failure {} exception: {}", command, exception);
    }
}

Fix for last commit: using correct logger template syntax {} not {0}.


package com.uwetrottmann.thetvdb.services;

import com.uwetrottmann.thetvdb.BaseTestCase;
import com.uwetrottmann.thetvdb.entities.LoginData;
import com.uwetrottmann.thetvdb.entities.Token;
import org.junit.Ignore;
import org.junit.Test;

public class AuthenticationTest extends BaseTestCase {

    private static final String API_KEY = "";

    @Ignore
    @Test
    public void test_login() {
        if (API_KEY.length() == 0) {
            throw new IllegalArgumentException("Set your TheTVDB API key to test login.");
        }

        Token token = getTheTvdb().authentication().login(new LoginData(API_KEY));
        System.out.println("Retrieved token: " + token.token + " (valid for 1 hour)");
    }

    @Ignore
    @Test
    public void test_refreshToken() {
        Token token = getTheTvdb().authentication().refreshToken();
        System.out.println("Refreshed token: " + token.token + " (valid for 1 hour)");
    }

}

package com.uwetrottmann.thetvdb.services;

import com.uwetrottmann.thetvdb.BaseTestCase;
import com.uwetrottmann.thetvdb.entities.LoginData;
import com.uwetrottmann.thetvdb.entities.Token;
import org.junit.Test;

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

public class AuthenticationTest extends BaseTestCase {

    private static final String API_KEY = "";

    @Test
    public void test_login() {
        if (API_KEY.length() == 0) {
            throw new IllegalArgumentException("Set your TheTVDB API key to test /login.");
        }

        // remove existing auth
        getTheTvdb().setJsonWebToken(null);

        Token token = getTheTvdb().authentication().login(new LoginData(API_KEY));
        System.out.println("Retrieved token: " + token.token + " (valid for 1 hour)");
    }

    @Test
    public void test_refreshToken() {
        if (API_KEY.length() == 0) {
            throw new IllegalArgumentException("Set your TheTVDB API key to test /refresh_token.");
        }

        // remove existing auth
        getTheTvdb().setJsonWebToken(null);

        // authenticate with API key
        Token token = getTheTvdb().authentication().login(new LoginData(API_KEY));
        getTheTvdb().setJsonWebToken(token.token);

        Token refreshedToken = getTheTvdb().authentication().refreshToken();
        assertThat(refreshedToken.token).isNotEqualTo(token.token);
        System.out.println("Refreshed token: " + refreshedToken.token + " (valid for 1 hour)");
    }

}

Set up auth tests properly so they can always run.


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

import java.io.PrintStream;

import org.apache.felix.shell.Command;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;

public class VersionCommandImpl implements Command
{
    private BundleContext m_context = null;

    public VersionCommandImpl(BundleContext context)
    {
        m_context = context;
    }

    public String getName()
    {
        return "version";
    }

    public String getUsage()
    {
        return "version";
    }

    public String getShortDescription()
    {
        return "display version of framework.";
    }

    public void execute(String s, PrintStream out, PrintStream err)
    {
        out.println(m_context.getBundle(0).getHeaders(Constants.BUNDLE_VERSION));
    }
}

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

import java.io.PrintStream;

import org.apache.felix.shell.Command;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;

public class VersionCommandImpl implements Command
{
    private BundleContext m_context = null;

    public VersionCommandImpl(BundleContext context)
    {
        m_context = context;
    }

    public String getName()
    {
        return "version";
    }

    public String getUsage()
    {
        return "version";
    }

    public String getShortDescription()
    {
        return "display version of framework.";
    }

    public void execute(String s, PrintStream out, PrintStream err)
    {
        out.println(m_context.getBundle(0).getHeaders().get(Constants.BUNDLE_VERSION));
    }
}

Fix bug in getting version. (FELIX-1699)

git-svn-id: e057f57e93a604d3b43d277ae69bde5ebf332112@821494 13f79535-47bb-0310-9956-ffa450edef68


import org.junit.*;

public class HashTableTest {

  @Test
  public void testInsertEntry() {
    HashTable ht = new HashTable(17);
    ht.hashFunctionMod("5");
  }

  @Test
  public void testFindKeyLast() {
    HashTable ht = new HashTable(17);
    ht.hashFunctionMod("35");
    ht.hashFunctionMod("40");
    ht.hashFunctionMod("45");
    ht.hashFunctionMod("50");
    ht.hashFunctionMod("55");
  }

  @Test
  public void testFindKeyFirst() {
    HashTable ht = new HashTable(17);
    ht.hashFunctionMod("35");
    ht.hashFunctionMod("40");
    ht.hashFunctionMod("45");
    ht.hashFunctionMod("50");
    ht.hashFunctionMod("55");
  }

}

import org.junit.*;

public class HashTableTest {

  private HashTable ht;

  @Before
  public void init() {
    ht = new HashTable(17);
  }

  @After
  public void clear() {
    ht = null;
  }

  @Test
  public void testInsertEntry() {
    ht.hashFunctionMod("5");

    // Assert here
  }

  @Test
  public void testFindKeyLast() {
    ht.hashFunctionMod("35");
    ht.hashFunctionMod("40");
    ht.hashFunctionMod("45");
    ht.hashFunctionMod("50");
    ht.hashFunctionMod("55");

    // Assert here
  }

  @Test
  public void testFindKeyFirst() {
    ht.hashFunctionMod("35");
    ht.hashFunctionMod("40");
    ht.hashFunctionMod("45");
    ht.hashFunctionMod("50");
    ht.hashFunctionMod("55");

    // Assert here
  }

}

Add setup and teardown to hash table test suite.


package bobby;

import java.awt.Graphics;
import java.util.ArrayList;
import javax.swing.JApplet;

/**
 *
 * @author Kiarash Korki <kiarash96@users.sf.net>
 */
public class SceneManager extends Thread {

	private final JApplet parent;
	private ArrayList<SceneObject> list;

	public SceneManager(JApplet parent) {
		list = new ArrayList<>();
		this.parent = parent;
	}

	public void draw(Graphics g) {
		// TODO: implement double buffering
		for (SceneObject sobject : list)
			sobject.draw(g);
	}

	@Override
	public void run() {
		while (true)
			parent.repaint();
	}

	public void add(SceneObject so) {
		list.add(so);
	}

	public void remove(SceneObject so) {
		list.remove(so);
	}

}

package bobby;

import java.awt.Color;
import java.awt.Graphics;
import java.util.ArrayList;
import javax.swing.JApplet;

/**
 *
 * @author Kiarash Korki <kiarash96@users.sf.net>
 */
public class SceneManager extends Thread {

	private final JApplet parent;
	private ArrayList<SceneObject> list;

	public SceneManager(JApplet parent) {
		list = new ArrayList<>();
		this.parent = parent;
	}

	public void draw(Graphics g) {
		// TODO: implement double buffering

		// clear the screen
		g.setColor(Color.WHITE);
		g.fillRect(0, 0, parent.getWidth(), parent.getHeight());

		for (SceneObject sobject : list)
			sobject.draw(g);

		// TODO: sleep
	}

	@Override
	public void run() {
		while (true)
			parent.repaint();
	}

	public void add(SceneObject so) {
		list.add(so);
	}

	public void remove(SceneObject so) {
		list.remove(so);
	}

}

Clear the screen before drawing

Clear the screen before drawing


package com.rehivetech.beeeon;

import android.text.TextUtils;

import java.util.Comparator;

public class IdentifierComparator implements Comparator<IIdentifier> {

	@Override
	public int compare(IIdentifier lhs, IIdentifier rhs) {
		return compareNumericIds(lhs, rhs);
	}

	public static int compareNumericIds(IIdentifier lhs, IIdentifier rhs) {
		String lhsId = lhs.getId();
		String rhsId = rhs.getId();

		if (TextUtils.isDigitsOnly(lhsId) && TextUtils.isDigitsOnly(rhsId)) {
			// Numeric comparison
			return Integer.valueOf(lhsId).compareTo(Integer.valueOf(rhsId));
		} else {
			// String comparison
			return lhsId.compareTo(rhsId);
		}
	}

}

package com.rehivetech.beeeon;

import android.text.TextUtils;

import java.util.Comparator;

public class IdentifierComparator implements Comparator<IIdentifier> {

	@Override
	public int compare(IIdentifier lhs, IIdentifier rhs) {
		return compareNumericIds(lhs, rhs);
	}

	public static int compareNumericIds(IIdentifier lhs, IIdentifier rhs) {
		String lhsId = lhs.getId();
		String rhsId = rhs.getId();

		if (TextUtils.isDigitsOnly(lhsId) && TextUtils.isDigitsOnly(rhsId)) {
			// Numeric comparison
			return Long.valueOf(lhsId).compareTo(Long.valueOf(rhsId));
		} else {
			// String comparison
			return lhsId.compareTo(rhsId);
		}
	}

}

Fix overflow of device ids

Fix overflow of device ids


/**
 * Created by loomisdf on 4/10/2016.
 */

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Main {

    static DatabaseFrame dbFrame;

    public static void main(String[] args) {
        dbFrame = new DatabaseFrame();
        // load the sqlite-JDBC driver using the current class loader
        try {
            Class.forName("org.sqlite.JDBC");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        Connection connection = null;
        try {
            // create a database connection
            connection = DriverManager.getConnection("jdbc:sqlite:data.db");
            Statement statement = connection.createStatement();
            statement.setQueryTimeout(30);  // set timeout to 30 sec.

            ResultSet rs = statement.executeQuery("SELECT * FROM GAME");
            while (rs.next()) {
                // read the result set
                System.out.println("Id = " + rs.getInt("id"));
                System.out.println("Title = " + rs.getString("name"));
                System.out.println("Price = " + rs.getInt("price"));
                System.out.println();
            }
        } catch (SQLException e) {
            // if the error message is "out of memory",
            // it probably means no database file is found
            System.err.println(e.getMessage());
        } finally {
            try {
                if (connection != null)
                    connection.close();
            } catch (SQLException e) {
                // connection close failed.
                System.err.println(e);
            }
        }
    }
}

/**
 * Created by loomisdf on 4/10/2016.
 */

public class Main {

    static DatabaseFrame dbFrame;

    public static void main(String[] args) {
        dbFrame = new DatabaseFrame();
        // load the sqlite-JDBC driver using the current class loader
        try {
            Class.forName("org.sqlite.JDBC");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        Game g = new Game();
        g.id = 1;
        g.name = "Brink";
        g.price = (float)19.99;

        System.out.println(g.reviews());
    }
}

Update main to use models

Update main to use models


package org.kaaproject.kaa.client.notification;

import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;

import org.kaaproject.kaa.common.endpoint.gen.Topic;

public class TopicListHashCalculator {
    public static final Integer NULL_LIST_HASH = 0;
    public static final Integer EMPTRY_LIST_HASH = 1;

    public static Integer calculateTopicListHash(List<Topic> topics) {
        if (topics == null)
            return NULL_LIST_HASH;

        int result = EMPTRY_LIST_HASH;
        if (!topics.isEmpty()) {
            List<Topic> newTopics = new LinkedList<>(topics);
            Collections.sort(newTopics, new Comparator<Topic>() {
                @Override
                public int compare(Topic o1, Topic o2) {
                    return o1.getId() < o2.getId() ? -1 : (o1.getId() < o2.getId() ) ? 1 : 0;
                }
            });

            for (Topic topic : newTopics) {
                long topicId = topic.getId();
                int elementHash = (int)(topicId ^ (topicId >>> 32));
                result = 31 * result + elementHash;
            }
        }

        return result;
    }
}

package org.kaaproject.kaa.client.notification;

import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;

import org.kaaproject.kaa.common.endpoint.gen.Topic;

public class TopicListHashCalculator {
    public static final Integer NULL_LIST_HASH = 0;
    public static final Integer EMPTRY_LIST_HASH = 1;

    public static Integer calculateTopicListHash(List<Topic> topics) {
        if (topics == null)
            return NULL_LIST_HASH;

        int result = EMPTRY_LIST_HASH;
        if (!topics.isEmpty()) {
            List<Topic> newTopics = new LinkedList<>(topics);
            Collections.sort(newTopics, new Comparator<Topic>() {
                @Override
                public int compare(Topic o1, Topic o2) {
                    return o1.getId() < o2.getId() ? -1 : (o1.getId() > o2.getId() ) ? 1 : 0;
                }
            });

            for (Topic topic : newTopics) {
                long topicId = topic.getId();
                int elementHash = (int)(topicId ^ (topicId >>> 32));
                result = 31 * result + elementHash;
            }
        }

        return result;
    }
}

KAA-823: Fix topic list hash calculation algorithm.


package org.exist.collections;

import static org.junit.Assert.*;

import org.junit.Test;

public class CollectionURITest {

	@Test
	public void append() {
		CollectionURI uri = new CollectionURI("/db");
		uri.append("test1");
		assertTrue(uri.equals(new CollectionURI("/db/test1")));
		assertEquals(uri.toString(), "/db/test1");
        assertEquals(uri.hashCode(), new String("/db/test1").hashCode());
        uri.append("test2");
        assertTrue(uri.equals(new CollectionURI("/db/test1/test2")));
		assertEquals(uri.toString(), "/db/test1/test2");
        assertEquals(uri.hashCode(), new String("/db/test1/test2").hashCode());
    }

    @Test
    public void remove() {
        CollectionURI uri = new CollectionURI("/db/test1/test2");
        uri.removeLastSegment();
        assertTrue(uri.equals(new CollectionURI("/db/test1")));
        assertEquals(uri.toString(), "/db/test1");
        uri.removeLastSegment();
        assertTrue(uri.equals(new CollectionURI("/db")));
        assertEquals(uri.toString(), "/db");

        uri.append("testMe");
        assertTrue(uri.equals(new CollectionURI("/db/testMe")));
        assertEquals(uri.toString(), "/db/testMe");

        uri.removeLastSegment();
        assertTrue(uri.equals(new CollectionURI("/db")));
        assertEquals(uri.toString(), "/db");
    }
}

package org.exist.collections;

import static org.junit.Assert.*;

import org.junit.Test;

public class CollectionURITest {

	@Test
	public void append() {
		CollectionURI uri = new CollectionURI("/db");
		uri.append("test1");
		assertTrue(uri.equals(new CollectionURI("/db/test1")));
		assertEquals(uri.toString(), "/db/test1");
        assertEquals(uri.hashCode(), new String("/db/test1").hashCode());
        uri.append("test2");
        assertTrue(uri.equals(new CollectionURI("/db/test1/test2")));
		assertEquals(uri.toString(), "/db/test1/test2");
        assertEquals(uri.hashCode(), new String("/db/test1/test2").hashCode());

        uri = new CollectionURI("/db/system/config");
        uri.append("/db/test");
        assertEquals(uri.toString(), "/db/system/config/db/test");
        assertTrue(uri.equals(new CollectionURI("/db/system/config/db/test")));
    }

    @Test
    public void remove() {
        CollectionURI uri = new CollectionURI("/db/test1/test2");
        uri.removeLastSegment();
        assertTrue(uri.equals(new CollectionURI("/db/test1")));
        assertEquals(uri.toString(), "/db/test1");
        uri.removeLastSegment();
        assertTrue(uri.equals(new CollectionURI("/db")));
        assertEquals(uri.toString(), "/db");

        uri.append("testMe");
        assertTrue(uri.equals(new CollectionURI("/db/testMe")));
        assertEquals(uri.toString(), "/db/testMe");

        uri.removeLastSegment();
        assertTrue(uri.equals(new CollectionURI("/db")));
        assertEquals(uri.toString(), "/db");
    }
}

Improve performance of CollectionConfigurationManager by replacing XmldbURI with CollectionURI.

svn path=/trunk/eXist/; revision=6526


package org.jetbrains.kotlin.ui.tests.editors.quickfix.autoimport;

import org.junit.Test;

public class KotlinAbstractModifierQuickFixTest extends KotlinQuickFixTestCase {
    @Override
    protected String getTestDataRelativePath() {
        return "../common_testData/ide/quickfix/abstract/";
    }

    @Test
    public void abstractFunctionInNonAbstractClass() {
        doAutoTest();
    }

    @Test
    public void abstractPropertyInNonAbstractClass1() {
        doAutoTest();
    }

    @Test
    public void abstractPropertyInNonAbstractClass2() {
        doAutoTest();
    }

    @Test
    public void abstractPropertyInNonAbstractClass3() {
        doAutoTest();
    }

    @Test
    public void abstractPropertyInPrimaryConstructorParameters() {
        doAutoTest();
    }

    @Test
    public void abstractPropertyNotInClass() {
        doAutoTest();
    }

    @Test
    public void abstractPropertyWithGetter1() {
        doAutoTest();
    }

    @Test
    public void abstractPropertyWithInitializer1() {
        doAutoTest();
    }

    @Test
    public void abstractPropertyWithSetter() {
        doAutoTest();
    }

    @Test
    public void mustBeInitializedOrBeAbstract() {
        doAutoTest();
    }

    @Test
    public void nonMemberAbstractFunction() {
        doAutoTest();
    }

    @Test
    public void notImplementedMember() {
        doAutoTest();
    }

    @Test
    public void notImplementedMemberFromAbstractClass() {
        doAutoTest();
    }

    @Test
    public void redundantAbstract() {
        doAutoTest();
    }

    @Test
    public void replaceOpen() {
        doAutoTest();
    }
}

package org.jetbrains.kotlin.ui.tests.editors.quickfix.autoimport;

import org.junit.Test;

public class KotlinAbstractModifierQuickFixTest extends KotlinQuickFixTestCase {
    @Override
    protected String getTestDataRelativePath() {
        return "../common_testData/ide/quickfix/abstract/";
    }

    @Test
    public void abstractFunctionInNonAbstractClass() {
        doAutoTest();
    }

    @Test
    public void abstractPropertyInNonAbstractClass1() {
        doAutoTest();
    }

    @Test
    public void abstractPropertyInNonAbstractClass2() {
        doAutoTest();
    }

    @Test
    public void abstractPropertyInNonAbstractClass3() {
        doAutoTest();
    }

    @Test
    public void abstractPropertyInPrimaryConstructorParameters() {
        doAutoTest();
    }

    @Test
    public void abstractPropertyNotInClass() {
        doAutoTest();
    }

    @Test
    public void abstractPropertyWithGetter1() {
        doAutoTest();
    }

    @Test
    public void abstractPropertyWithInitializer1() {
        doAutoTest();
    }

    @Test
    public void abstractPropertyWithSetter() {
        doAutoTest();
    }

    @Test
    public void mustBeInitializedOrBeAbstract() {
        doAutoTest();
    }

    @Test
    public void nonMemberAbstractFunction() {
        doAutoTest();
    }

    @Test
    public void notImplementedMember() {
        doAutoTest();
    }

    @Test
    public void notImplementedMemberFromAbstractClass() {
        doAutoTest();
    }

    @Test
    public void replaceOpen() {
        doAutoTest();
    }
}

Remove test that was removed with 'redundant abstract' diagnostic


/*******************************************************************************
 * Copyright (c) 2011, 2016 Eurotech and/or its affiliates and others
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Eurotech - initial API and implementation
 *
 *******************************************************************************/
package org.eclipse.kapua.service.authentication.credential;

import org.eclipse.kapua.model.KapuaEntityFactory;
import org.eclipse.kapua.model.KapuaObjectFactory;
import org.eclipse.kapua.model.id.KapuaId;

/**
 * Credential factory service definition.
 *
 * @since 1.0
 *
 */
public interface CredentialFactory extends KapuaEntityFactory<Credential, CredentialCreator, CredentialQuery, CredentialListResult>
{

    /**
     * Create a new {@link Credential}
     *
     * @param scopeId
     * @param userId
     * @param credentialType
     * @param credentialKey
     * @return
     */
    public Credential newCredential(KapuaId scopeId, KapuaId userId, CredentialType credentialType, String credentialKey);

    /**
     * Create a new {@link CredentialCreator} for the specific credential type
     *
     * @param scopeId
     * @param userId
     * @param credentialType
     * @param credentialKey
     * @return
     */
    public CredentialCreator newCreator(KapuaId scopeId, KapuaId userId, CredentialType credentialType, String credentialKey);

}

/*******************************************************************************
 * Copyright (c) 2011, 2016 Eurotech and/or its affiliates and others
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Eurotech - initial API and implementation
 *
 *******************************************************************************/
package org.eclipse.kapua.service.authentication.credential;

import org.eclipse.kapua.model.KapuaEntityFactory;
import org.eclipse.kapua.model.id.KapuaId;

/**
 * Credential factory service definition.
 *
 * @since 1.0
 *
 */
public interface CredentialFactory extends KapuaEntityFactory<Credential, CredentialCreator, CredentialQuery, CredentialListResult> {

    /**
     * Create a new {@link Credential}
     *
     * @param scopeId
     * @param userId
     * @param credentialType
     * @param credentialKey
     * @return
     */
    public Credential newCredential(KapuaId scopeId, KapuaId userId, CredentialType credentialType, String credentialKey);

    /**
     * Create a new {@link CredentialCreator} for the specific credential type
     *
     * @param scopeId
     * @param userId
     * @param credentialType
     * @param credentialKey
     * @return
     */
    public CredentialCreator newCreator(KapuaId scopeId, KapuaId userId, CredentialType credentialType, String credentialKey);

}

Fix warnings and apply code style

Fix warnings and apply code style


package com.querydsl.sql.types;

import java.sql.*;
import java.time.Instant;

import javax.annotation.Nullable;

import org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement;

/**
 * JSR310InstantType maps {@linkplain java.time.Instant} to
 * {@linkplain java.sql.Timestamp} on the JDBC level
 *
 */
@IgnoreJRERequirement //conditionally included
public class JSR310InstantType extends AbstractJSR310DateTimeType<Instant>  {

    public JSR310InstantType() {
        super(Types.TIMESTAMP);
    }

    public JSR310InstantType(int type) {
        super(type);
    }

    @Override
    public String getLiteral(Instant value) {
        return dateTimeFormatter.format(value);
    }

    @Override
    public Class<Instant> getReturnedClass() {
        return Instant.class;
    }

    @Nullable
    @Override
    public Instant getValue(ResultSet rs, int startIndex) throws SQLException {
        Timestamp timestamp = rs.getTimestamp(startIndex, utc());
        return timestamp != null ? timestamp.toInstant() : null;
    }

    @Override
    public void setValue(PreparedStatement st, int startIndex, Instant value) throws SQLException {
        st.setTimestamp(startIndex, Timestamp.from(value), utc());
    }
}

package com.querydsl.sql.types;

import java.sql.*;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;

import javax.annotation.Nullable;

import org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement;

/**
 * JSR310InstantType maps {@linkplain java.time.Instant} to
 * {@linkplain java.sql.Timestamp} on the JDBC level
 *
 */
@IgnoreJRERequirement //conditionally included
public class JSR310InstantType extends AbstractJSR310DateTimeType<Instant>  {

    public JSR310InstantType() {
        super(Types.TIMESTAMP);
    }

    public JSR310InstantType(int type) {
        super(type);
    }

    @Override
    public String getLiteral(Instant value) {
        return dateTimeFormatter.format(LocalDateTime.ofInstant(value, ZoneId.of("Z")));
    }

    @Override
    public Class<Instant> getReturnedClass() {
        return Instant.class;
    }

    @Nullable
    @Override
    public Instant getValue(ResultSet rs, int startIndex) throws SQLException {
        Timestamp timestamp = rs.getTimestamp(startIndex, utc());
        return timestamp != null ? timestamp.toInstant() : null;
    }

    @Override
    public void setValue(PreparedStatement st, int startIndex, Instant value) throws SQLException {
        st.setTimestamp(startIndex, Timestamp.from(value), utc());
    }
}

Fix formatting of propertyless java.time.Instant


package com.minelittlepony.client.gui.hdskins;

public final class IndirectHDSkins {
    public static void initialize() {
        try {
            Class<?> mlphd = Class.forName("com.minelittlepony.client.hdskins.MineLPHDSkins");
            mlphd.getConstructor().newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

package com.minelittlepony.client.gui.hdskins;

import org.apache.logging.log4j.LogManager;

public final class IndirectHDSkins {
    public static void initialize() {
        try {
            Class.forName("com.minelittlepony.client.hdskins.MineLPHDSkins").getConstructor().newInstance();
        } catch (Exception e) {
            LogManager.getLogger().warn("Failed to initialize hooks for hdskins", e);
        }
    }
}

Remove usage of IModUtilities from hdskins.


package net.mcft.copy.betterstorage.inventory;

import net.mcft.copy.betterstorage.item.ItemBackpack;
import net.mcft.copy.betterstorage.utils.DirectionUtils;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.player.EntityPlayer;

public class InventoryBackpackEquipped extends InventoryWrapper {

	public final EntityPlayer player;
	public final EntityLiving carrier;

	public InventoryBackpackEquipped(EntityPlayer player, EntityLiving carrier) {
		super(ItemBackpack.getBackpackItems(carrier).contents);
		this.player = player;
		this.carrier = carrier;
	}

	@Override
	public boolean isUseableByPlayer(EntityPlayer player) {
		if (!carrier.isEntityAlive() || player.getDistanceToEntity(carrier) > 1.5) return false;
		double direction = DirectionUtils.angleBetween(carrier, player);
		direction = DirectionUtils.angleDifference(carrier.renderYawOffset + 90.0F, direction);
		return (Math.abs(direction) > 135);
	}

}

package net.mcft.copy.betterstorage.inventory;

import net.mcft.copy.betterstorage.item.ItemBackpack;
import net.mcft.copy.betterstorage.utils.DirectionUtils;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.player.EntityPlayer;

public class InventoryBackpackEquipped extends InventoryWrapper {

	public final EntityPlayer player;
	public final EntityLiving carrier;

	public InventoryBackpackEquipped(EntityPlayer player, EntityLiving carrier) {
		super(ItemBackpack.getBackpackItems(carrier).contents);
		this.player = player;
		this.carrier = carrier;
	}

	@Override
	public boolean isUseableByPlayer(EntityPlayer player) {
		boolean carriesBackpack = (ItemBackpack.getBackpackItems(carrier).contents == allContents[0]);
		double distance = player.getDistanceToEntity(carrier);
		double direction = DirectionUtils.angleDifference(carrier.renderYawOffset + 90.0F,
		                                                  DirectionUtils.angleBetween(carrier, player));
		return (carrier.isEntityAlive() && carriesBackpack &&
		        (distance < 1.5) && (Math.abs(direction) > 135));
	}

}

Fix unequipping backpack not closing GUI


package com.yahoo.concurrent.classlock;

import java.util.HashMap;
import java.util.Map;
import java.util.function.BooleanSupplier;

/**
 * @author valerijf
 */
public class ClassLocking {
    private final Map<Class<?>, ClassLock> classLocks = new HashMap<>();
    private final Object monitor = new Object();

    public ClassLock lock(Class<?> clazz) {
        return lockWhile(clazz, () -> true);
    }

    public ClassLock lockWhile(Class<?> clazz, BooleanSupplier interruptCondition) {
        synchronized (monitor) {
            while (classLocks.containsKey(clazz)) {
                try {
                    monitor.wait();
                } catch (InterruptedException ignored) {
                }

                if (!interruptCondition.getAsBoolean()) {
                    throw new LockInterruptException();
                }
            }

            ClassLock classLock = new ClassLock(this, clazz);
            classLocks.put(clazz, classLock);
            return classLock;
        }
    }

    void unlock(Class<?> clazz, ClassLock classLock) {
        synchronized (monitor) {
            if (classLock.equals(classLocks.get(clazz))) {
                classLocks.remove(clazz);
                monitor.notifyAll();
            } else {
                throw new IllegalArgumentException("Lock has already been released");
            }
        }
    }

    public void interrupt() {
        synchronized (monitor) {
            monitor.notifyAll();
        }
    }
}

package com.yahoo.concurrent.classlock;

import java.util.HashMap;
import java.util.Map;
import java.util.function.BooleanSupplier;

/**
 * @author valerijf
 */
public class ClassLocking {
    private final Map<String, ClassLock> classLocks = new HashMap<>();
    private final Object monitor = new Object();

    public ClassLock lock(Class<?> clazz) {
        return lockWhile(clazz, () -> true);
    }

    public ClassLock lockWhile(Class<?> clazz, BooleanSupplier interruptCondition) {
        synchronized (monitor) {
            while (classLocks.containsKey(clazz.getName())) {
                try {
                    monitor.wait();
                } catch (InterruptedException ignored) {
                }

                if (!interruptCondition.getAsBoolean()) {
                    throw new LockInterruptException();
                }
            }

            ClassLock classLock = new ClassLock(this, clazz);
            classLocks.put(clazz.getName(), classLock);
            return classLock;
        }
    }

    void unlock(Class<?> clazz, ClassLock classLock) {
        synchronized (monitor) {
            if (classLock.equals(classLocks.get(clazz.getName()))) {
                classLocks.remove(clazz.getName());
                monitor.notifyAll();
            } else {
                throw new IllegalArgumentException("Lock has already been released");
            }
        }
    }

    public void interrupt() {
        synchronized (monitor) {
            monitor.notifyAll();
        }
    }
}

Use String as lock key

Use String as lock key


package editor.gui.ccp.handler;

import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import java.util.Arrays;
import java.util.stream.Collectors;

import javax.swing.TransferHandler;

import editor.database.card.Card;
import editor.gui.ccp.data.DataFlavors;
import editor.gui.editor.EditorFrame;

@SuppressWarnings("serial")
public class CardImportHandler extends TransferHandler implements ImportHandler
{
    private final EditorFrame editor;
    private final int id;

    public CardImportHandler(EditorFrame e, int i)
    {
        editor = e;
        id = i;
    }

    @Override
    public DataFlavor supportedFlavor()
    {
        return DataFlavors.cardFlavor;
    }

    @Override
    public boolean canImport(TransferSupport supp)
    {
        return supp.isDataFlavorSupported(supportedFlavor());
    }

    @Override
    public boolean importData(TransferSupport supp)
    {
        if (!canImport(supp))
            return false;
        else
        {
            try
            {
                var data = Arrays.stream((Card[])supp.getTransferable().getTransferData(supportedFlavor())).collect(Collectors.toSet());
                return editor.addCards(id, data, 1);
            }
            catch (UnsupportedFlavorException | IOException e)
            {
                return false;
            }
        }
    }
}

package editor.gui.ccp.handler;

import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import java.util.Arrays;
import java.util.stream.Collectors;

import javax.swing.TransferHandler;

import editor.database.card.Card;
import editor.gui.ccp.data.DataFlavors;
import editor.gui.editor.EditorFrame;

/**
 * Import handler for importing a list of single copies of cards.
 */
@SuppressWarnings("serial")
public class CardImportHandler extends TransferHandler implements ImportHandler
{
    /** Editor frame that is importing the cards. */
    private final EditorFrame editor;
    /** ID of the list to import cards to. */
    private final int id;

    /**
     * Create a new card import handler.
     *
     * @param e editor frame containing the deck to import cards into
     * @param i ID of the list in the deck to import into
     */
    public CardImportHandler(EditorFrame e, int i)
    {
        editor = e;
        id = i;
    }

    @Override
    public DataFlavor supportedFlavor()
    {
        return DataFlavors.cardFlavor;
    }

    @Override
    public boolean canImport(TransferSupport supp)
    {
        return supp.isDataFlavorSupported(supportedFlavor());
    }

    @Override
    public boolean importData(TransferSupport supp)
    {
        if (!canImport(supp))
            return false;
        else
        {
            try
            {
                var data = Arrays.stream((Card[])supp.getTransferable().getTransferData(supportedFlavor())).collect(Collectors.toSet());
                return editor.addCards(id, data, 1);
            }
            catch (UnsupportedFlavorException | IOException e)
            {
                return false;
            }
        }
    }
}

Add documentation to card import handler


package net.silentchaos512.gems.entity;

import java.util.List;

import com.google.common.collect.Lists;

import net.minecraft.entity.EnumCreatureType;
import net.minecraft.init.Biomes;
import net.minecraftforge.fml.common.registry.EntityRegistry;
import net.silentchaos512.lib.registry.SRegistry;

public class ModEntities {

  public static List<Class> nodePacketClasses = Lists.newArrayList();

  public static void init(SRegistry reg) {

    reg.registerEntity(EntityChaosProjectile.class, "ChaosProjectile", 64, 4, true);
    reg.registerEntity(EntityChaosProjectileHoming.class, "ChaosProjectileHoming", 64, 4, true);
    reg.registerEntity(EntityChaosProjectileSweep.class, "ChaosProjectileSweep", 64, 4, true);

    reg.registerEntity(EntityThrownTomahawk.class, "ThrownTomahawk");

    reg.registerEntity(EntityEnderSlime.class, "EnderSlime", 64, 4, false, 0x003333, 0xAA00AA);
    EntityRegistry.addSpawn(EntityEnderSlime.class, 50, 1, 4, EnumCreatureType.MONSTER, Biomes.SKY);
  }
}

package net.silentchaos512.gems.entity;

import java.util.List;

import com.google.common.collect.Lists;

import net.minecraft.entity.EnumCreatureType;
import net.minecraft.init.Biomes;
import net.minecraftforge.fml.common.registry.EntityRegistry;
import net.silentchaos512.lib.registry.SRegistry;

public class ModEntities {

  public static List<Class> nodePacketClasses = Lists.newArrayList();

  public static void init(SRegistry reg) {

    reg.registerEntity(EntityChaosProjectile.class, "ChaosProjectile", 64, 4, true);
    reg.registerEntity(EntityChaosProjectileHoming.class, "ChaosProjectileHoming", 64, 4, true);
    reg.registerEntity(EntityChaosProjectileSweep.class, "ChaosProjectileSweep", 64, 4, true);

    reg.registerEntity(EntityThrownTomahawk.class, "ThrownTomahawk");

    reg.registerEntity(EntityEnderSlime.class, "EnderSlime", 64, 4, false, 0x003333, 0xAA00AA);
    EntityRegistry.addSpawn(EntityEnderSlime.class, 10, 1, 4, EnumCreatureType.MONSTER, Biomes.SKY);
  }
}

Make ender slime spawn rate more sane

Make ender slime spawn rate more sane


package org.babblelang.engine.impl.natives.java;

import org.babblelang.engine.impl.Callable;
import org.babblelang.engine.impl.Interpreter;
import org.babblelang.engine.impl.Namespace;
import org.babblelang.engine.impl.Scope;
import org.babblelang.parser.BabbleParser;

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

public class ImportFunction implements Callable<JavaPackage> {
    private final Map<String, JavaPackage> packages = new HashMap<>();

    public Namespace bindParameters(Interpreter interpreter, BabbleParser.CallContext callSite, Namespace parent, Parameters parameters) {
        Namespace namespace = parent.enter(null);
        Object first = parameters.values().iterator().next();
        namespace.define("name", true).set(first);
        return namespace;
    }

    public JavaPackage call(Interpreter interpreter, BabbleParser.CallContext callSite, Scope scope) {
        String name = (String) scope.get("name").get();
        return getPackage(name);
    }

    public JavaPackage getPackage(String name) {
        JavaPackage result = packages.computeIfAbsent(name, name -> new JavaPackage(this, name));
        return result;
    }
}

package org.babblelang.engine.impl.natives.java;

import org.babblelang.engine.impl.Callable;
import org.babblelang.engine.impl.Interpreter;
import org.babblelang.engine.impl.Namespace;
import org.babblelang.engine.impl.Scope;
import org.babblelang.parser.BabbleParser;

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

public class ImportFunction implements Callable<JavaPackage> {
    private final Map<String, JavaPackage> packages = new HashMap<>();

    public Namespace bindParameters(Interpreter interpreter, BabbleParser.CallContext callSite, Namespace parent, Parameters parameters) {
        Namespace namespace = parent.enter(null);
        Object first = parameters.values().iterator().next();
        namespace.define("name", true).set(first);
        return namespace;
    }

    public JavaPackage call(Interpreter interpreter, BabbleParser.CallContext callSite, Scope scope) {
        String name = (String) scope.get("name").get();
        return getPackage(name);
    }

    public JavaPackage getPackage(String name) {
        return packages.computeIfAbsent(name, n -> new JavaPackage(this, n));
    }
}

Fix redeclaration of name in use of Map.computeIfAbsent.


package com.choonster.testmod3.tests;

/**
 * Runs this mod's tests.
 *
 * @author Choonster
 */
public class Tests {
	public static void runTests() {
		OreDictUtilTests.INSTANCE.test();
		NBTTagEndTests.INSTANCE.test();
	}
}

package com.choonster.testmod3.tests;

/**
 * Runs this mod's tests.
 *
 * @author Choonster
 */
public class Tests {
	public static void runTests() {
		OreDictUtilTests.INSTANCE.test();
//		NBTTagEndTests.INSTANCE.test();
	}
}

Disable NBT Tag End tests

Disable NBT Tag End tests

-- The NBTTagEnd constructor seems to be inaccessible in non-development
1.8.9, not entirely sure why