text:
package org.jeecgframework.web.cgform.entity.enhance;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.hibernate.annotations.GenericGenerator;

/**
 * @Title: Entity
 * @Description: JS增强
 * @author 张代浩
 * @date 2013-08-11 09:47:30
 * @version V1.0
 *
 */
@Entity
@Table(name = "cgform_enhance_js", schema = "")
@SuppressWarnings("serial")
public class CgformEnhanceJsEntity implements java.io.Serializable {
	/**id*/
	private java.lang.String id;
	/**formId*/
	private java.lang.String formId;
	/**js增强类型(form/list)*/
	private java.lang.String cgJsType;
	/**增强js*/
	private byte[] cgJs;

	/**增强js Str*/
	private String cgJsStr;

	/**描述*/
	private java.lang.String content;

	/**
	 *方法: 取得java.lang.String
	 *@return: java.lang.String  id
	 */

	@Id
	@GeneratedValue(generator = "paymentableGenerator")
	@GenericGenerator(name = "paymentableGenerator", strategy = "uuid")
	@Column(name ="ID",nullable=false,length=32)
	public java.lang.String getId(){
		return this.id;
	}

	/**
	 *方法: 设置java.lang.String
	 *@param: java.lang.String  id
	 */
	public void setId(java.lang.String id){
		this.id = id;
	}
	/**
	 *方法: 取得java.lang.String
	 *@return: java.lang.String  formId
	 */
	@Column(name ="FORM_ID",nullable=true,length=32)
	public java.lang.String getFormId(){
		return this.formId;
	}

	/**
	 *方法: 设置java.lang.String
	 *@param: java.lang.String  formId
	 */
	public void setFormId(java.lang.String formId){
		this.formId = formId;
	}
	/**
	 *方法: 取得java.lang.String
	 *@return: java.lang.String  js增强类型(form/list)
	 */
	@Column(name ="CG_JS_TYPE",nullable=true,length=20)
	public java.lang.String getCgJsType(){
		return this.cgJsType;
	}

	/**
	 *方法: 设置java.lang.String
	 *@param: java.lang.String  js增强类型(form/list)
	 */
	public void setCgJsType(java.lang.String cgJsType){
		this.cgJsType = cgJsType;
	}
	/**
	 *方法: 取得byte[]
	 *@return: byte[]  增强js
	 */
	@Column(name ="CG_JS",nullable=true,length=65535)
	public byte[] getCgJs(){
		return this.cgJs;
	}

	/**
	 *方法: 设置byte[]
	 *@param: byte[]  增强js
	 */
	public void setCgJs(byte[] cgJs){
		this.cgJs = cgJs;
	}
	/**
	 *方法: 取得java.lang.String
	 *@return: java.lang.String  描述
	 */
	@Column(name ="CONTENT",nullable=true,length=1000)
	public java.lang.String getContent(){
		return this.content;
	}

	/**
	 *方法: 设置java.lang.String
	 *@param: java.lang.String  描述
	 */
	public void setContent(java.lang.String content){
		this.content = content;
	}

	@Transient
	public String getCgJsStr() {
		if(cgJs!=null){
			cgJsStr = new String(cgJs);
		}
		return cgJsStr;
	}

	public void setCgJsStr(String cgJsStr) {
		this.cgJsStr = cgJsStr;
		if(cgJsStr!=null){
		this.cgJs = cgJsStr.getBytes();
		}
	}

	/**
	 * 深度复制
	 * @return
	 * @throws Exception
	 */
	public CgformEnhanceJsEntity deepCopy() throws Exception{
        //将该对象序列化成流,因为写在流里的是对象的一个拷贝,而原对象仍然存在于JVM里面。所以利用这个特性可以实现对象的深拷贝
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(this);

        //将流序列化成对象
        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bis);
        return (CgformEnhanceJsEntity) ois.readObject();
    }
}


text:
package com.fincatto.documentofiscal.nfe400.classes.evento.cancelamento;

import com.fincatto.documentofiscal.DFBase;
import com.fincatto.documentofiscal.nfe400.classes.evento.NFEventoRetorno;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Namespace;
import org.simpleframework.xml.Root;

@Root(name = "procEventoNFe")
@Namespace(reference = "http://www.portalfiscal.inf.br/nfe")
public class NFProtocoloEventoCancelamento extends DFBase {
    private static final long serialVersionUID = 8058424887014735846L;

    @Attribute(name = "versao")
    private String versao;

    @Element(name = "evento")
    private NFEventoCancelamento evento;

    @Element(name = "retEvento")
    private NFEventoRetorno eventoRetorno;

    public NFEventoCancelamento getEvento() {
        return this.evento;
    }

    public void setEvento(final NFEventoCancelamento evento) {
        this.evento = evento;
    }

    public NFEventoRetorno getInfoEventoRetorno() {
        return this.eventoRetorno;
    }

    public void setEventoRetorno(final NFEventoRetorno infoEventoRetorno) {
        this.eventoRetorno = infoEventoRetorno;
    }

    public String getVersao() {
        return this.versao;
    }

    public void setVersao(final String versao) {
        this.versao = versao;
    }
}

redpajama_set_name: RedPajamaGithub


text:
[C++] ECS library for learning purpose

[WORK IN PROGRESS / LEARNING PURPOSE]

Requirements:
- GCC 7.1+
- Boost 1.63+

Ressources:
- http://www.randygaul.net/ by [Randy Gaul](https://github.com/RandyGaul)
- Modern C++ Design by [Andrei Alexandrescu](https://github.com/andralex)
- [Boost.Hana](https://github.com/boostorg/hana) by [Louis Dionne](https://github.com/ldionne)
- [Entityx](https://github.com/alecthomas/entityx) as my first example of ECS implementation, by [Alec Thomas](https://github.com/alecthomas)

I discovered a lot of them because I saw [Vittorio Romeo](https://github.com/SuperV1234) conference.
And he's working on a pro ECS library so go use it : [ecst](https://github.com/SuperV1234/ecst)


text:
using ClumsyBat;
using ClumsyBat.Objects;
using System.Collections.Generic;
using UnityEngine;

public class CaveHandler : MonoBehaviour {

    private Rigidbody2D caveBody;

    private GameObject startPiece;
    private GameObject endPiece;
    private List<GameObject> topCavePieces = new List<GameObject>();
    private List<GameObject> bottomCavePieces = new List<GameObject>();

    private int _cavePieceCounter;
    private GameObject caveEnd;

    private GameObject caveParent;

    private bool bPaused;

    public enum CaveStates
    {
        Start,
        Middle,
        End,
        Final
    }
    public CaveStates State;

    private float caveZLayer;
    private float tileSizeX;

    private void Start()
    {
        caveZLayer = Toolbox.Instance.ZLayers["Cave"];
        tileSizeX = Toolbox.TileSizeX;

        var levelObj = GameStatics.GameManager.LevelObject.transform;
        caveParent = new GameObject("Caves");
        caveParent.transform.SetParent(levelObj);

        caveBody = caveParent.AddComponent<Rigidbody2D>();
        caveBody.isKinematic = true;
    }

    public void SetupCave(LevelContainer.CaveType[] caveList)
    {
        for (int i = 0; i < caveList.Length; i++)
        {
            GeneratePresetLevelCave(caveList[i], i);
        }
    }

    public void PauseGame(bool paused)
    {
        bPaused = paused;
    }

    public GameObject GetEndCave()
    {
        return caveEnd;
    }

    public void SetVelocity(float speed)
    {
        if (State == CaveStates.Final) { return; }
        if (bPaused)
            caveBody.velocity = Vector2.zero;
        else
            caveBody.velocity = new Vector2(-speed, 0);
    }

    private void GeneratePresetLevelCave(LevelContainer.CaveType cave, int index)
    {
        GameObject caveTop;

        if (cave.TopIndex == Toolbox.CaveStartIndex)
        {
            if (startPiece == null)
            {
                startPiece = (GameObject)Instantiate(Resources.Load("Caves/CaveEntrance"), caveParent.transform);
                startPiece.name = "CaveEntrance";
            }
            caveTop = startPiece;
        }
        else if (cave.TopIndex == Toolbox.CaveEndIndex)
        {
            if (endPiece == null)
            {
                endPiece = (GameObject)Instantiate(Resources.Load("Caves/CaveExit"), caveParent.transform);
                endPiece.name = "CaveExit";
            }
            caveTop = caveEnd = endPiece;
        }
        else
        {
            string caveBottomName = "CaveBottom" + (cave.bBottomSecretPath ? "Exit" : "") + (cave.BottomIndex + 1);
            string caveTopName = "CaveTop" + (cave.bTopSecretPath ? "Exit" : "") + (cave.TopIndex + 1);
            GameObject caveBottom = (GameObject)Instantiate(Resources.Load("Caves/" + caveBottomName), caveParent.transform);
            caveTop = (GameObject)Instantiate(Resources.Load("Caves/" + caveTopName), caveParent.transform);
            caveBottom.name = caveBottomName;
            caveTop.name = caveTopName;
            caveBottom.transform.position = new Vector3(tileSizeX * index, 0f, caveZLayer);

            topCavePieces.Add(caveTop);
            bottomCavePieces.Add(caveBottom);

            SecretPath path = caveBottom.GetComponentInChildren<SecretPath>();
            if (path == null) path = caveTop.GetComponentInChildren<SecretPath>();
            if (path != null)
            {
                if (!cave.bSecretPathHasBlock) Destroy(path.gameObject);
                path.RequiresBlueMoth = cave.bSecretPathRequiresMoth;
            }
        }
        caveTop.transform.position = new Vector3(tileSizeX * index, 0f, caveZLayer);
    }

    public void ClearExistingCave()
    {
        for (int i = topCavePieces.Count - 1; i >= 0; i--)
        {
            Destroy(topCavePieces[i]);
        }
        for (int i = bottomCavePieces.Count - 1; i >= 0; i--)
        {
            Destroy(bottomCavePieces[i]);
        }

        topCavePieces.Clear();
        bottomCavePieces.Clear();

        if (startPiece != null)
        {
            startPiece.transform.position = new Vector3(0, 10000, 0);
        }

        if (endPiece != null)
        {
            endPiece.transform.position = new Vector3(0, 10000, 0);
        }
    }
}


text:
package org.hisp.dhis.commons.action;

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

import org.hisp.dhis.dataset.DataSet;
import org.hisp.dhis.dataset.DataSetService;
import org.hisp.dhis.dataset.Section;
import org.hisp.dhis.indicator.Indicator;
import org.hisp.dhis.paging.ActionPagingSupport;

public class GetSectionIndicatorsAction
    extends ActionPagingSupport<Indicator>
{
    // -------------------------------------------------------------------------
    // Dependencies
    // -------------------------------------------------------------------------

    private DataSetService dataSetService;

    public void setDataSetService( DataSetService dataSetService )
    {
        this.dataSetService = dataSetService;
    }

    // -------------------------------------------------------------------------
    // Input & Output
    // -------------------------------------------------------------------------

    private Integer dataSetId;

    public void setDataSetId( Integer dataSetId )
    {
        this.dataSetId = dataSetId;
    }

    private List<Indicator> indicators = new ArrayList<>();

    public List<Indicator> getIndicators()
    {
        return indicators;
    }

    // -------------------------------------------------------------------------
    // Action Implementation
    // -------------------------------------------------------------------------

    @Override
    public String execute()
        throws Exception
    {
        if ( dataSetId == null )
        {
            return SUCCESS;
        }

        DataSet dataSet = dataSetService.getDataSet( dataSetId );

        indicators = new ArrayList<>( dataSet.getIndicators() );

        for ( Section section : dataSet.getSections() )
        {
            indicators.removeAll( section.getIndicators() );
        }

        Collections.sort( indicators );

        return SUCCESS;
    }
}


text:
using Atlassian.Stash.Api.Api;
using Atlassian.Stash.Api.Workers;

namespace Atlassian.Stash.Api
{
    public class StashClient
    {
        private HttpCommunicationWorker _httpWorker;

        public StashClient(string baseUrl, string base64Auth = null)
        {
            _httpWorker = new HttpCommunicationWorker(baseUrl, base64Auth);
            InjectDependencies();
        }

        public StashClient(string baseUrl, string username, string password)
        {
            _httpWorker = new HttpCommunicationWorker(baseUrl, username, password);
            InjectDependencies();
        }

        private void InjectDependencies()
        {
            this.Projects = new Projects(_httpWorker);
            this.Groups = new Groups(_httpWorker);
            this.Users = new Users(_httpWorker);
            this.Repositories = new Repositories(_httpWorker);
            this.Branches = new Branches(_httpWorker);
            this.Commits = new Commits(_httpWorker);
            this.PullRequests = new PullRequests(_httpWorker);
            this.Forks = new Forks(_httpWorker);
        }

        public Projects Projects { get; private set; }
        public Groups Groups { get; set; }
        public Users Users { get; private set; }
        public Repositories Repositories { get; private set; }
        public Branches Branches { get; private set; }
        public Commits Commits { get; private set; }
        public PullRequests PullRequests { get; private set; }
        public Forks Forks { get; private set; }

    }
}


text:
<resources>

    <!-- Base application theme. -->
    <style name="AppBaseThemeLight" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">@color/color_primary</item>
        <item name="colorPrimaryDark">@color/color_primary_dark</item>
        <item name="colorAccent">@color/color_primary</item>
        <item name="android:textColorPrimary">@color/textcolor_light</item>
    </style>

    <style name="AppBaseThemeDark" parent="Theme.AppCompat.NoActionBar">
        <item name="colorPrimary">@color/color_primary</item>
        <item name="colorPrimaryDark">@color/color_primary_dark</item>
        <item name="colorAccent">@color/color_primary</item>
        <item name="android:textColorPrimary">@color/textcolor_dark</item>
    </style>

    <style name="AppThemeLight" parent="AppBaseThemeLight" />

    <style name="AppThemeDark" parent="AppBaseThemeDark" />

    <style name="AppThemeActionBarLight" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="colorPrimary">@color/color_primary</item>
        <item name="colorPrimaryDark">@color/color_primary_dark</item>
        <item name="colorAccent">@color/color_primary</item>
        <item name="android:textColorPrimary">@color/textcolor_light</item>
        <item name="android:windowContentOverlay">@null</item>
    </style>

    <style name="AppThemeActionBarDark" parent="Theme.AppCompat">
        <item name="colorPrimary">@color/color_primary</item>
        <item name="colorPrimaryDark">@color/color_primary_dark</item>
        <item name="colorAccent">@color/color_primary</item>
        <item name="android:textColorPrimary">@color/textcolor_dark</item>
        <item name="android:windowContentOverlay">@null</item>
    </style>

    <style name="SwitchCompat">
        <item name="colorControlActivated">@android:color/white</item>
    </style>

    <style name="ActionBarStyle" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
        <item name="colorAccent">@color/white</item>
    </style>

    <style name="ToolbarTitle" parent="@style/TextAppearance.Widget.AppCompat.Toolbar.Title">
        <item name="android:textSize">20sp</item>
    </style>

    <style name="Divider">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">1dp</item>
        <item name="android:background">@color/divider_background_light</item>
    </style>

    <style name="menu_labels_style">
        <item name="android:textColor">@color/white</item>
        <item name="android:background">@drawable/fab_label_background</item>
    </style>

</resources>


text:
package org.apereo.cas.authentication;

import org.apereo.cas.authentication.exceptions.UnresolvedPrincipalException;
import org.apereo.cas.authentication.handler.DefaultAuthenticationHandlerResolver;
import org.apereo.cas.authentication.handler.RegisteredServiceAuthenticationHandlerResolver;
import org.apereo.cas.authentication.handler.support.SimpleTestUsernamePasswordAuthenticationHandler;
import org.apereo.cas.authentication.policy.AllCredentialsValidatedAuthenticationPolicy;
import org.apereo.cas.authentication.policy.AtLeastOneCredentialValidatedAuthenticationPolicy;
import org.apereo.cas.authentication.policy.RequiredAuthenticationHandlerAuthenticationPolicy;
import org.apereo.cas.authentication.principal.PrincipalFactoryUtils;
import org.apereo.cas.authentication.principal.PrincipalResolver;
import org.apereo.cas.authentication.principal.Service;
import org.apereo.cas.services.ServicesManager;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.springframework.context.ConfigurableApplicationContext;

import javax.security.auth.login.FailedLoginException;
import java.security.GeneralSecurityException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;

/**
 * Unit test for {@link DefaultAuthenticationManager}.
 *
 * @author Marvin S. Addison
 * @since 4.0.0
 */
@Tag("Authentication")
@Slf4j
public class DefaultAuthenticationManagerTests {
    private static final String HANDLER_A = "HandlerA";

    private static final String HANDLER_B = "HandlerB";

    private final AuthenticationTransaction transaction = new DefaultAuthenticationTransactionFactory()
        .newTransaction(CoreAuthenticationTestUtils.getService(),
            mock(Credential.class, withSettings().serializable()),
            mock(Credential.class, withSettings().serializable()));

    protected static ServicesManager mockServicesManager() {
        val svc = mock(ServicesManager.class);
        val reg = CoreAuthenticationTestUtils.getRegisteredService();
        when(svc.findServiceBy(any(Service.class))).thenReturn(reg);
        when(svc.getAllServices()).thenReturn(List.of(reg));
        return svc;
    }

    /**
     * Creates a new mock authentication handler that either
     * successfully validates all credentials or fails to
     * validate all credentials.
     *
     * @param success True to authenticate all credentials, false to fail all credentials.
     * @return New mock authentication handler instance.
     */
    private static AuthenticationHandler newMockHandler(final boolean success) {
        return newMockHandler(success, false);
    }

    /**
     * Creates a new mock authentication handler that either successfully validates all credentials or fails to
     * validate all credentials.
     *
     * @param success True to authenticate all credentials, false to fail all credentials.
     * @param error   True if the handle has an error, false if not.
     * @return New mock authentication handler instance.
     */
    private static AuthenticationHandler newMockHandler(final boolean success, final boolean error) {
        val name = "MockAuthenticationHandler" + UUID.randomUUID().toString();
        return newMockHandler(name, success, error);
    }

    /**
     * Creates a new named mock authentication handler that either successfully validates all credentials or fails to
     * validate all credentials.
     *
     * @param name    Authentication handler name.
     * @param success True to authenticate all credentials, false to fail all credentials.
     * @return New mock authentication handler instance.
     */
    private static AuthenticationHandler newMockHandler(final String name, final boolean success) {
        return newMockHandler(name, success, false);
    }

    /**
     * Creates a new named mock authentication handler that either successfully validates all credentials or fails to
     * validate all credentials.
     *
     * @param name    Authentication handler name.
     * @param success True to authenticate all credentials, false to fail all credentials.
     * @param error   True if the handle has an error, false if not.
     * @return New mock authentication handler instance.
     */
    @SneakyThrows
    private static AuthenticationHandler newMockHandler(final String name, final boolean success, final boolean error) {
        val mock = mock(AuthenticationHandler.class);
        when(mock.getName()).thenReturn(name);
        when(mock.supports(any(Credential.class))).thenReturn(true);
        when(mock.getState()).thenCallRealMethod();
        if (success) {
            val p = PrincipalFactoryUtils.newPrincipalFactory().createPrincipal("nobody");

            val result = new DefaultAuthenticationHandlerExecutionResult(mock, mock(CredentialMetaData.class), p);
            when(mock.authenticate(any(Credential.class))).thenReturn(result);
        } else if (!error) {
            when(mock.authenticate(any(Credential.class))).thenThrow(new FailedLoginException());
        } else {
            when(mock.authenticate(any(Credential.class))).thenThrow(new PreventedException("failure"));
        }
        return mock;
    }

    private static AuthenticationEventExecutionPlan getAuthenticationExecutionPlan(final Map<AuthenticationHandler, PrincipalResolver> map) {
        val plan = new DefaultAuthenticationEventExecutionPlan(CoreAuthenticationTestUtils.getAuthenticationSystemSupport());
        plan.registerAuthenticationHandlerWithPrincipalResolver(map);
        plan.registerAuthenticationHandlerResolver(new RegisteredServiceAuthenticationHandlerResolver(mockServicesManager(),
            new DefaultAuthenticationServiceSelectionPlan(new DefaultAuthenticationServiceSelectionStrategy())));
        plan.registerAuthenticationHandlerResolver(new DefaultAuthenticationHandlerResolver());
        plan.registerAuthenticationPostProcessor((builder, transaction) -> LOGGER.trace("Running authentication post processor"));
        return plan;
    }

    @Test
    public void verifyAuthenticateFailsPreProcessor() {
        val map = new HashMap<AuthenticationHandler, PrincipalResolver>();
        map.put(newMockHandler(true), null);
        map.put(newMockHandler(false), null);

        val authenticationExecutionPlan = getAuthenticationExecutionPlan(map);
        authenticationExecutionPlan.registerAuthenticationPreProcessor(transaction -> false);
        val manager = new DefaultAuthenticationManager(authenticationExecutionPlan,
            false, mock(ConfigurableApplicationContext.class));
        assertThrows(AuthenticationException.class, () -> manager.authenticate(transaction));
    }

    @Test
    public void verifyNoHandlers() {
        val map = new HashMap<AuthenticationHandler, PrincipalResolver>();
        val authenticationExecutionPlan = getAuthenticationExecutionPlan(map);
        val manager = new DefaultAuthenticationManager(authenticationExecutionPlan,
            false, mock(ConfigurableApplicationContext.class));
        assertThrows(AuthenticationException.class, () -> manager.authenticate(transaction));
    }

    @Test
    public void verifyTransactionWithAuthnHistoryAndAuthnPolicy() {
        val map = new LinkedHashMap<AuthenticationHandler, PrincipalResolver>();
        map.put(newMockHandler(true), null);

        val authenticationExecutionPlan = getAuthenticationExecutionPlan(map);
        val policy = new RequiredAuthenticationHandlerAuthenticationPolicy(
            SimpleTestUsernamePasswordAuthenticationHandler.class.getSimpleName());
        authenticationExecutionPlan.registerAuthenticationPolicy(policy);
        val manager = new DefaultAuthenticationManager(authenticationExecutionPlan,
            false, mock(ConfigurableApplicationContext.class));

        val testTransaction = new DefaultAuthenticationTransactionFactory()
            .newTransaction(CoreAuthenticationTestUtils.getService(), mock(Credential.class, withSettings().serializable()));
        testTransaction.collect(List.of(CoreAuthenticationTestUtils.getAuthentication()));
        assertNotNull(manager.authenticate(testTransaction));
    }

    @Test
    public void verifyBlockingAuthnPolicy() throws Exception {
        val map = new LinkedHashMap<AuthenticationHandler, PrincipalResolver>();
        map.put(newMockHandler(false, true), null);
        map.put(newMockHandler(true), null);

        val authenticationExecutionPlan = getAuthenticationExecutionPlan(map);
        val policy = mock(AuthenticationPolicy.class);
        when(policy.isSatisfiedBy(any(), any(), any(), any()))
            .thenReturn(AuthenticationPolicyExecutionResult.success());
        when(policy.shouldResumeOnFailure(any())).thenReturn(Boolean.FALSE);

        authenticationExecutionPlan.registerAuthenticationPolicy(policy);
        val manager = new DefaultAuthenticationManager(authenticationExecutionPlan,
            false, mock(ConfigurableApplicationContext.class));

        val testTransaction = new DefaultAuthenticationTransactionFactory().newTransaction(CoreAuthenticationTestUtils.getService(),
            mock(Credential.class, withSettings().serializable()));

        assertThrows(AuthenticationException.class, () -> manager.authenticate(testTransaction));
    }

    @Test
    public void verifyResolverFails() {
        val map = new HashMap<AuthenticationHandler, PrincipalResolver>();
        val resolver = mock(PrincipalResolver.class);
        when(resolver.supports(any())).thenReturn(Boolean.FALSE);

        map.put(newMockHandler(true), resolver);
        val authenticationExecutionPlan = getAuthenticationExecutionPlan(map);
        val manager = new DefaultAuthenticationManager(authenticationExecutionPlan,
            false, mock(ConfigurableApplicationContext.class));
        assertThrows(UnresolvedPrincipalException.class, () -> manager.authenticate(transaction));

        when(resolver.supports(any())).thenReturn(Boolean.TRUE);
        when(resolver.resolve(any(), any(), any())).thenThrow(new RuntimeException("Fails"));
        assertThrows(UnresolvedPrincipalException.class, () -> manager.authenticate(transaction));
    }

    @Test
    public void verifyResolverFailsAsFatal() {
        val map = new HashMap<AuthenticationHandler, PrincipalResolver>();
        val resolver = mock(PrincipalResolver.class);
        when(resolver.supports(any())).thenReturn(Boolean.FALSE);

        map.put(newMockHandler(true), resolver);
        val authenticationExecutionPlan = getAuthenticationExecutionPlan(map);
        val manager = new DefaultAuthenticationManager(authenticationExecutionPlan,
            true, mock(ConfigurableApplicationContext.class));
        assertThrows(UnresolvedPrincipalException.class, () -> manager.authenticate(transaction));
    }

    @Test
    public void verifyAuthWithNoCreds() {
        val map = new HashMap<AuthenticationHandler, PrincipalResolver>();
        map.put(newMockHandler(true), null);
        val authenticationExecutionPlan = getAuthenticationExecutionPlan(map);
        val manager = new DefaultAuthenticationManager(authenticationExecutionPlan,
            true, mock(ConfigurableApplicationContext.class));
        assertThrows(AuthenticationException.class, () -> manager.authenticate(new DefaultAuthenticationTransactionFactory().newTransaction()));
    }

    @Test
    public void verifyAuthenticateAnySuccess() {
        val map = new HashMap<AuthenticationHandler, PrincipalResolver>();
        map.put(newMockHandler(true), null);
        map.put(newMockHandler(false), null);

        val authenticationExecutionPlan = getAuthenticationExecutionPlan(map);
        authenticationExecutionPlan.registerAuthenticationPolicy(new AtLeastOneCredentialValidatedAuthenticationPolicy());
        val manager = new DefaultAuthenticationManager(authenticationExecutionPlan,
            false, mock(ConfigurableApplicationContext.class));

        val auth = manager.authenticate(transaction);
        assertEquals(1, auth.getSuccesses().size());
        assertEquals(2, auth.getCredentials().size());
    }

    @Test
    public void verifyAuthenticateAnyButTryAllSuccess() {
        val map = new HashMap<AuthenticationHandler, PrincipalResolver>();
        map.put(newMockHandler(true), null);
        map.put(newMockHandler(false), null);
        val authenticationExecutionPlan = getAuthenticationExecutionPlan(map);
        authenticationExecutionPlan.registerAuthenticationPolicy(new AtLeastOneCredentialValidatedAuthenticationPolicy(true));
        val manager = new DefaultAuthenticationManager(authenticationExecutionPlan,
            false, mock(ConfigurableApplicationContext.class));

        val auth = manager.authenticate(transaction);
        assertEquals(1, auth.getSuccesses().size());
        assertEquals(1, auth.getFailures().size());
        assertEquals(2, map.size());
    }

    @Test
    public void verifyAuthenticateAnyFailure() {
        val map = new LinkedHashMap<AuthenticationHandler, PrincipalResolver>();
        map.put(newMockHandler(false), null);
        map.put(newMockHandler(false), null);

        val authenticationExecutionPlan = getAuthenticationExecutionPlan(map);
        authenticationExecutionPlan.registerAuthenticationPolicy(new AtLeastOneCredentialValidatedAuthenticationPolicy());
        val manager = new DefaultAuthenticationManager(authenticationExecutionPlan,
            false, mock(ConfigurableApplicationContext.class));

        assertThrows(AuthenticationException.class, () -> manager.authenticate(transaction));
    }

    @Test
    public void verifyAuthenticateAnyFailureWithError() {
        val map = new LinkedHashMap<AuthenticationHandler, PrincipalResolver>();
        map.put(newMockHandler(false, true), null);
        map.put(newMockHandler(false, true), null);

        val authenticationExecutionPlan = getAuthenticationExecutionPlan(map);
        authenticationExecutionPlan.registerAuthenticationPolicy(new AtLeastOneCredentialValidatedAuthenticationPolicy());
        val manager = new DefaultAuthenticationManager(authenticationExecutionPlan,
            false, mock(ConfigurableApplicationContext.class));

        assertThrows(AuthenticationException.class, () -> manager.authenticate(transaction));
    }

    @Test
    public void verifyAuthenticateAllSuccess() {
        val map = new LinkedHashMap<AuthenticationHandler, PrincipalResolver>();
        map.put(newMockHandler(true), null);
        map.put(newMockHandler(true), null);

        val authenticationExecutionPlan = getAuthenticationExecutionPlan(map);
        authenticationExecutionPlan.registerAuthenticationPolicy(new AllCredentialsValidatedAuthenticationPolicy());
        val manager = new DefaultAuthenticationManager(authenticationExecutionPlan,
            false, mock(ConfigurableApplicationContext.class));

        val auth = manager.authenticate(transaction);
        assertEquals(2, auth.getSuccesses().size());
        assertEquals(0, auth.getFailures().size());
        assertEquals(2, auth.getCredentials().size());
    }

    @Test
    public void verifyAuthenticatePolicyFailsGeneric() throws Exception {
        val map = new LinkedHashMap<AuthenticationHandler, PrincipalResolver>();
        map.put(newMockHandler(true), null);

        val authenticationExecutionPlan = getAuthenticationExecutionPlan(map);
        val policy = mock(AuthenticationPolicy.class);
        when(policy.isSatisfiedBy(any(), any(), any(), any()))
            .thenThrow(new GeneralSecurityException(new FailedLoginException()));
        authenticationExecutionPlan.registerAuthenticationPolicy(policy);
        val manager = new DefaultAuthenticationManager(authenticationExecutionPlan,
            false, mock(ConfigurableApplicationContext.class));

        assertThrows(AuthenticationException.class, () -> manager.authenticate(transaction));
    }

    @Test
    public void verifyAuthenticatePolicyFails() throws Exception {
        val map = new LinkedHashMap<AuthenticationHandler, PrincipalResolver>();
        map.put(newMockHandler(true), null);

        val authenticationExecutionPlan = getAuthenticationExecutionPlan(map);
        val policy = mock(AuthenticationPolicy.class);
        when(policy.isSatisfiedBy(any(), any(), any(), any()))
            .thenThrow(new IllegalArgumentException());
        authenticationExecutionPlan.registerAuthenticationPolicy(policy);
        val manager = new DefaultAuthenticationManager(authenticationExecutionPlan,
            false, mock(ConfigurableApplicationContext.class));

        assertThrows(AuthenticationException.class, () -> manager.authenticate(transaction));
    }

    @Test
    public void verifyAuthenticateAllFailure() {
        val map = new LinkedHashMap<AuthenticationHandler, PrincipalResolver>();
        map.put(newMockHandler(false), null);
        map.put(newMockHandler(false), null);

        val authenticationExecutionPlan = getAuthenticationExecutionPlan(map);
        authenticationExecutionPlan.registerAuthenticationPolicy(new AllCredentialsValidatedAuthenticationPolicy());
        val manager = new DefaultAuthenticationManager(authenticationExecutionPlan,
            false, mock(ConfigurableApplicationContext.class));

        assertThrows(AuthenticationException.class, () -> manager.authenticate(transaction));
    }

    @Test
    public void verifyAuthenticateRequiredHandlerSuccess() {
        val map = new LinkedHashMap<AuthenticationHandler, PrincipalResolver>();
        map.put(newMockHandler(HANDLER_A, true), null);
        map.put(newMockHandler(HANDLER_B, false), null);

        val authenticationExecutionPlan = getAuthenticationExecutionPlan(map);
        authenticationExecutionPlan.registerAuthenticationPolicy(new RequiredAuthenticationHandlerAuthenticationPolicy(HANDLER_A));
        val manager = new DefaultAuthenticationManager(authenticationExecutionPlan,
            false, mock(ConfigurableApplicationContext.class));

        val auth = manager.authenticate(transaction);
        assertEquals(1, auth.getSuccesses().size());
        assertEquals(2, auth.getCredentials().size());
    }

    @Test
    public void verifyAuthenticateRequiredHandlerFailure() {
        val map = new LinkedHashMap<AuthenticationHandler, PrincipalResolver>();
        map.put(newMockHandler(HANDLER_A, true), null);
        map.put(newMockHandler(HANDLER_B, false), null);

        val authenticationExecutionPlan = getAuthenticationExecutionPlan(map);
        authenticationExecutionPlan.registerAuthenticationPolicy(new RequiredAuthenticationHandlerAuthenticationPolicy(HANDLER_B));
        val manager = new DefaultAuthenticationManager(authenticationExecutionPlan,
            false, mock(ConfigurableApplicationContext.class));

        assertThrows(AuthenticationException.class, () -> manager.authenticate(transaction));
    }

    @Test
    public void verifyAuthenticateRequiredHandlerTryAllSuccess() {
        val map = new LinkedHashMap<AuthenticationHandler, PrincipalResolver>();
        map.put(newMockHandler(HANDLER_A, true), null);
        map.put(newMockHandler(HANDLER_B, false), null);

        val authenticationExecutionPlan = getAuthenticationExecutionPlan(map);
        authenticationExecutionPlan.registerAuthenticationPolicy(new RequiredAuthenticationHandlerAuthenticationPolicy(Set.of(HANDLER_A), true));
        val manager = new DefaultAuthenticationManager(authenticationExecutionPlan, false,
            mock(ConfigurableApplicationContext.class));

        val auth = manager.authenticate(transaction);
        assertEquals(1, auth.getSuccesses().size());
        assertEquals(1, auth.getFailures().size());
        assertEquals(2, auth.getCredentials().size());
    }
}


text:
cask 'runjs' do
  version '1.9.0'
  sha256 'd81e6af3048dbdf1130cfd0fc7b28c445b3c05f533c199f2243cb7ead664fc25'

  # github.com/lukehaas/runjs/ was verified as official when first introduced to the cask
  url "https://github.com/lukehaas/runjs/releases/download/v#{version}/RunJS-#{version}.dmg"
  appcast 'https://github.com/lukehaas/runjs/releases.atom'
  name 'RunJS'
  homepage 'https://projects.lukehaas.me/runjs/'

  app 'RunJS.app'
end


text:
package com.dangdang.ddframe.job.console.util;

public final class JobNodePath {

    private JobNodePath() {
    }

    public static String getConfigNodePath(final String jobName, final String nodeName) {
        return String.format("/%s/config/%s", jobName, nodeName);
    }

    public static String getServerNodePath(final String jobName) {
        return String.format("/%s/servers", jobName);
    }

    public static String getServerNodePath(final String jobName, final String serverIp, final String nodeName) {
        return String.format("%s/%s/%s", getServerNodePath(jobName), serverIp, nodeName);
    }

    public static String getExecutionNodePath(final String jobName) {
        return String.format("/%s/execution", jobName);
    }

    public static String getExecutionNodePath(final String jobName, final String item, final String nodeName) {
        return String.format("%s/%s/%s", getExecutionNodePath(jobName), item, nodeName);
    }

    public static String getLeaderNodePath(final String jobName, final String nodeName) {
        return String.format("/%s/leader/%s", jobName, nodeName);
    }
}


text:
package org.assertj.core.util.introspection;

import static java.lang.String.format;
import static java.lang.reflect.Modifier.isPublic;
import static java.util.Locale.ENGLISH;
import static org.assertj.core.util.Preconditions.*;
import static org.assertj.core.util.Strings.quote;

import java.beans.*;
import java.lang.reflect.Method;

/**
 * Utility methods related to <a
 * href="http://java.sun.com/docs/books/tutorial/javabeans/introspection/index.html">JavaBeans Introspection</a>.
 *
 * @author Alex Ruiz
 */
public final class Introspection {
  /**
   * Returns a {@link PropertyDescriptor} for a property matching the given name in the given object.
   *
   * @param propertyName the given property name.
   * @param target the given object.
   * @return a {@code PropertyDescriptor} for a property matching the given name in the given object.
   * @throws NullPointerException if the given property name is {@code null}.
   * @throws IllegalArgumentException if the given property name is empty.
   * @throws NullPointerException if the given object is {@code null}.
   * @throws IntrospectionError if a matching property cannot be found or accessed.
   */
  public static PropertyDescriptor getProperty(String propertyName, Object target) {
    checkNotNullOrEmpty(propertyName);
    checkNotNull(target);
    BeanInfo beanInfo = null;
    Class<?> type = target.getClass();
    try {
      beanInfo = Introspector.getBeanInfo(type);
    } catch (Throwable t) {
      throw new IntrospectionError(format("Unable to get BeanInfo for type %s", type.getName()), t);
    }
    for (PropertyDescriptor descriptor : beanInfo.getPropertyDescriptors()) {
      if (propertyName.equals(descriptor.getName())) {
        return descriptor;
      }
    }
    throw new IntrospectionError(propertyNotFoundErrorMessage(propertyName, target));
  }

  private static String propertyNotFoundErrorMessage(String propertyName, Object target) {
    String targetTypeName = target.getClass().getName();
    String property = quote(propertyName);
    Method getter = findGetter(propertyName, target);
    if (getter == null) {
      return format("No getter for property %s in %s", property, targetTypeName);
    }
    if (!isPublic(getter.getModifiers())) {
      return format("No public getter for property %s in %s", property, targetTypeName);
    }
    return format("Unable to find property %s in %s", property, targetTypeName);
  }

  private static Method findGetter(String propertyName, Object target) {
    String capitalized = propertyName.substring(0, 1).toUpperCase(ENGLISH) + propertyName.substring(1);
    // try to find getProperty
    Method getter = findMethod("get" + capitalized, target);
    if (getter != null) {
      return getter;
    }
    // try to find isProperty for boolean properties
    return findMethod("is" + capitalized, target);
  }

  private static Method findMethod(String name, Object target) {
    // TODO walk class hierarchy to check if any superclass declares the method we are looking for.
    try {
      return target.getClass().getDeclaredMethod(name);
    } catch (Throwable t) {
      return null;
    }
  }

  private Introspection() {}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="gameSettingsCategoryTitle">"Game Settings"</string>
  <string name="modifiersScreenTitle">"Modifiers"</string>
  <string name="modifiersScreenDesc">"Modifiers affecting the notes data or appearances"</string>
  <string name="gameplayCategoryTitle">"Gameplay"</string>
  <string name="notesCategoryTitle">"Notes"</string>
  <string name="displaySettingsCategoryTitle">"Display Settings"</string>
  <string name="hardwareAccelerationTitle">Hardware Acceleration</string>
  <string name="hardwareAccelerationDesc">May improve FPS</string>
  <string name="gameScreenTitle">"Game Screen"</string>
  <string name="gameScreenDesc">"Screen during gameplay"</string>
  <string name="interfaceCategoryTitle">"Game Interface"</string>
  <string name="backgroundCategoryTitle">"Game Background"</string>
  <string name="tapSettingsCategoryTitle">"Tap Settings"</string>
  <string name="vibrateScreenTitle">"Vibrations"</string>
  <string name="vibrateScreenDesc">"Vibration/haptic feedback settings"</string>
  <string name="machineSettingsCategoryTitle">"Machine Settings"</string>
  <string name="miscCategoryTitle">"Misc"</string>
  <string name="infoScreenTitle">"Info"</string>
  <string name="infoScreenDesc">"Links and info about Beats"</string>
  <string name="linksCategoryTitle">"Links"</string>
  <string name="infoCategoryTitle">"Info"</string>
  <string name="thanksCategoryTitle">"Thanks"</string>
  <string name="advancedScreenTitle">"Advanced Settings"</string>
  <string name="advancedScreenDesc">"More settings for customizing Beats to your heart\'s desire!"</string>
  <string name="tweaksCategoryTitle">"Tweaks"</string>
  <string name="filebrowserCategoryTitle">"Song Browsing"</string>
  <string name="debuggingCategoryTitle">"Debugging"</string>
  <string name="websiteTitle">"Website"</string>
  <string name="websiteDesc">"Read the latest updates at Beats\' official website http://beatsportable.com"</string>
  <string name="forumsTitle">"Forums"</string>
  <string name="forumsDesc">"Discussion and support forums for Beats"</string>
  <string name="tutorialTitle">"Tutorial"</string>
  <string name="tutorialDesc">"Video tutorial demonstrating various features of Beats"</string>
  <string name="demoTitle">"Demo"</string>
  <string name="demoDesc">"Video gameplay demo of Beats"</string>
  <string name="todoTitle">"To-Do List"</string>
  <string name="todoDesc">"Updated To-Do List forum thread for the next release"</string>
  <string name="changelogTitle">"Changelog"</string>
  <string name="changelogDesc">"Updated Changelog forum thread for the next release"</string>
  <string name="donateTitle">"Donate"</string>
  <string name="donateDesc">"Show thanks to the poor univ students! Donations keep our website up and running"</string>
  <string name="creditsTitle">"Credits"</string>
  <string name="creditsDesc">"A bit about the devs and all others to thank"</string>
  <string name="difficultyLevelTitle">"Difficulty Level"</string>
  <string name="difficultyLevelDesc">"Default difficulty level of song"</string>
  <string name="speedMultiplierTitle">"Speed"</string>
  <string name="speedMultiplierDesc">"Falling speed of notes"</string>
  <string name="gameModeTitle">"Game Mode"</string>
  <string name="gameModeDesc">"Mode of displaying notes"</string>
  <string name="noteAppearanceTitle">"Appearance"</string>
  <string name="noteAppearanceDesc">"Visibility of notes"</string>
  <string name="darkTitle">"Dark"</string>
  <string name="darkDesc">"Hide tap arrows"</string>
  <string name="holdsTitle">"Holds"</string>
  <string name="holdsDesc">"Notes that have to be held down"</string>
  <string name="jumpsTitle">"Jumps"</string>
  <string name="jumpsDesc">"Multiple notes per line"</string>
  <string name="randomizeTitle">"Randomize"</string>
  <string name="randomizeDesc">"Randomize note patterns (ignores holds)"</string>
  <string name="accuracyLevelTitle">"Judgement"</string>
  <string name="accuracyLevelDesc">"Strictness of accuracy scoring"</string>
  <string name="autoPlayTitle">"Auto-Play"</string>
  <string name="autoPlayDesc">"Use auto-play for learning song patterns (or for the lolz!)"</string>
  <string name="fullscreenTitle">"Fullscreen"</string>
  <string name="fullscreenDesc">"Hide status and title bars"</string>
  <string name="backgroundShowTitle">"Show Background"</string>
  <string name="backgroundShowDesc">"Draw the background image"</string>
  <string name="backgroundBrightnessTitle">"Background Brightness"</string>
  <string name="backgroundBrightnessDesc">"Background image brightness"</string>
  <string name="backgroundSongTitle">"Load Song Background"</string>
  <string name="backgroundSongDesc">"Load song-specific background image"</string>
  <string name="noteskinTitle">"Note Skin"</string>
  <string name="noteskinDesc">"Note graphics to load"</string>
  <string name="backgroundImageTitle">"Menu Background"</string>
  <string name="backgroundImageDesc">"Background image for main menu and stepfiles without one"</string>
  <string name="orientationTitle">"Screen Orientation"</string>
  <string name="orientationDesc">"Default screen orientation during gameplay"</string>
  <string name="tapboxLayoutTitle">"Tapbox Layout"</string>
  <string name="tapboxLayoutDesc">"Arrangement of tapboxes"</string>
  <string name="tapboxFadingTitle">"Tapbox Fading"</string>
  <string name="tapboxFadingDesc">"Transparency of tapboxes"</string>
  <string name="tapboxOverlapTitle">"Tapbox Overlap"</string>
  <string name="tapboxOverlapDesc">"Horizontal overlap of adjacent tapboxes"</string>
  <string name="tapboxYOffsetTitle">"Tapbox Placement"</string>
  <string name="tapboxYOffsetDesc">"Vertical shift of tapboxes"</string>
  <string name="vibrateTapTitle">"Vibrate on Tap"</string>
  <string name="vibrateTapDesc">"Vibrations when tapping arrows"</string>
  <string name="vibrateHoldTitle">"Vibrate on Holds"</string>
  <string name="vibrateHoldDesc">"Keep vibrating during hold arrows"</string>
  <string name="vibrateMissTitle">"Vibrate on Miss"</string>
  <string name="vibrateMissDesc">"Vibrations on a note Miss or Auto-Play tap"</string>
  <string name="vibrateTouchSenseTitle">"Vibrate with UHL"</string>
  <string name="vibrateTouchSenseDesc">"Haptic feedback with Immersion\'s Universal Haptic Layer (UHL) technology"</string>
  <string name="manualOffsetTitle">"Music Offset"</string>
  <string name="manualOffsetDesc">"Manually adjust this only if timing is off-sync"</string>
  <string name="manualOGGOffsetTitle">"OGG Offset"</string>
  <string name="manualOGGOffsetDesc">"Manually adjust this if .ogg music is off-sync (I use -0.325s)"</string>
  <string name="showPercentTitle">"Display Percentage"</string>
  <string name="showPercentDesc">"Display percent instead of letter grade in scoreboard"</string>
  <string name="showFPSTitle">"Show FPS"</string>
  <string name="showFPSDesc">"Display current and average framerate (# of frames updates/sec)"</string>
  <string name="screenshotModeTitle">"Screenshot Mode"</string>
  <string name="screenshotModeDesc">"Enable this to take a screenshot when you pause the game"</string>
  <string name="backgroundFilteringTitle">"Background Filtering"</string>
  <string name="backgroundFilteringDesc">"Smoothen background image (enabling may reduce framerate)"</string>
  <string name="syncDurationTitle">"Audio Re-sync"</string>
  <string name="syncDurationDesc">"Notes-audio sync duration for startup and pause/resume"</string>
  <string name="appPriorityTitle">"Application Priority"</string>
  <string name="appPriorityDesc">"Increase to reduce lag, may cause instability issues"</string>
  <string name="healthPenaltyTitle">"Health Penalty"</string>
  <string name="healthPenaltyDesc">"Health loss per note missed"</string>
  <string name="healthMaxTitle">"Health Total"</string>
  <string name="healthMaxDesc">"Maximum health value"</string>
  <string name="additionalVibrationsTitle">"Additional Vibrations"</string>
  <string name="additionalVibrationsDesc">"App and song startup vibrations"</string>
  <string name="autoStartTitle">"Auto-Start"</string>
  <string name="autoStartDesc">"Automatically start game upon stepfile selection"</string>
  <string name="useShortDirNamesTitle">"Shorten Folder Names"</string>
  <string name="useShortDirNamesDesc">"Remove (...) and [...] tags from folder entries in \'SELECT MUSIC\'"</string>
  <string name="stepfileFolderCheckTitle">"Stepfile Folder Checking"</string>
  <string name="stepfileFolderCheckDesc">"Disable to directly open directories with stepfiles"</string>
  <string name="betaNotesTitle">"Beta Notes"</string>
  <string name="betaNotesDesc">"Display beta notes on next startup"</string>
  <string name="debugTimeTitle">"Timing Debugging"</string>
  <string name="debugTimeDesc">"Display exact note and sync time diffs"</string>
  <string name="debugLogCatTitle">"LogCat Debugging"</string>
  <string name="debugLogCatDesc">"Print warning/error messages to LogCat"</string>
  <string name="debugTapboxTitle">"Tapbox Debugging"</string>
  <string name="debugTapboxDesc">"Draw exact tapbox boxes"</string>
  <string name="languageTitle">"Language"</string>
  <string name="languageDesc">"Change displayed language"</string>
  <string name="installSamplesTitle">"Install Sample Songs"</string>
  <string name="installSamplesDesc">"Re-install sample songs on next startup"</string>
  <string name="resetHighScoresTitle">"Reset High Scores"</string>
  <string name="resetHighScoresDesc">"Reset all high scores on next game"</string>
  <string name="resetSettingsTitle">"Reset All Settings"</string>
  <string name="resetSettingsDesc">"Reset all settings to default values on next startup"</string>
</resources>


text:
package org.jenkinsci.plugins.SemanticVersioning;

public class InvalidBuildFileFormatException extends Exception {
	private static final long serialVersionUID = 1L;

	public InvalidBuildFileFormatException(String message) {
        super(message);
    }
}


text:
package exceptions;

public class InvalidArgumentsException extends ParsingException {

    /**
     *
     */
    private static final long serialVersionUID = -3534124694409416195L;

    public InvalidArgumentsException() {
	super();
    }

    public InvalidArgumentsException(Exception e) {
	super(e);
    }

    public InvalidArgumentsException(String s) {
	super(s);
    }

    @Override
    public String printMessage() {
	return "Invalid Argument Exception";
    }
}


text:
package org.apache.camel.component.bean;

import org.apache.camel.ContextTestSupport;
import org.apache.camel.builder.RouteBuilder;
import org.junit.Test;

/**
 *
 */
public class BeanInvokeToStringMethodTest extends ContextTestSupport {

    @Test
    public void testInvokeToString() throws Exception {
        getMockEndpoint("mock:result").expectedBodiesReceived("MyFooBean");

        template.sendBody("direct:start", "Hello World");

        assertMockEndpointsSatisfied();
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:start")
                    .bean(MyFooBean.class, "toString")
                    .to("mock:result");
            }
        };
    }
}


text:
require_relative '../base/subsubcmd'
require_relative '../base/subsubmgr'

class Trepan::Subcommand::ShowHighlight < Trepan::ShowBoolSubcommand
  unless defined?(HELP)
    Trepanning::Subcommand.set_name_prefix(__FILE__, self)
    HELP         = 'Show whether we use terminal highlighting'
    MIN_ABBREV   = 'high'.size
  end

  def run(args)
    val = :term == @proc.settings[:highlight]
    onoff = show_onoff(val)
    msg("%s is %s." % [@name, onoff])
  end
end

if __FILE__ == $0
  require_relative '../../mock'
  cmd = MockDebugger::sub_setup(Trepan::Subcommand::ShowHighlight, false)
  cmd.run(cmd.prefix)
end


text:
package com.afterkraft.kraftrpg.api.role.aspect;

import java.util.List;

import static com.google.common.base.Preconditions.checkNotNull;

import org.spongepowered.api.item.ItemType;
import org.spongepowered.api.item.inventory.ItemStack;

import com.google.common.collect.Lists;

import com.afterkraft.kraftrpg.api.role.RoleAspect;

/**
 * Represents a {@link RoleAspect} that determines whether an {@link ItemStack} or {@link ItemType}
 * is equippable as weapon and/or armor.
 */
public final class EquipmentAspect implements RoleAspect {
    private final ItemType[] allowedWeapons;
    private final ItemType[] allowedArmor;

    private EquipmentAspect(EquipmentAspectBuilder builder) {
        this.allowedArmor = builder.allowedArmor
                .toArray(new ItemType[builder.allowedArmor.size()]);
        this.allowedWeapons = builder.allowedWeapons
                .toArray(new ItemType[builder.allowedWeapons.size()]);
    }

    /**
     * Gets a builder for an EquipmentAspect aspect.
     *
     * @return A new builder
     */
    public static EquipmentAspectBuilder builder() {
        return new EquipmentAspectBuilder();
    }

    /**
     * Checks if the material type is considered to be an equipable Weapon for this role.
     *
     * @param itemStack The itemstack itself
     *
     * @return True if the material is allowed as a weapon
     */
    boolean isWeaponEquippable(ItemStack itemStack) {
        return isWeaponEquippable(itemStack.getItem());
    }

    /**
     * Checks if the material type is considered to be an equipable Weapon for this role.
     *
     * @param itemType The type of material to check
     *
     * @return True if the material is allowed as a weapon
     */
    boolean isWeaponEquippable(ItemType itemType) {
        checkNotNull(itemType);
        for (ItemType item : this.allowedWeapons) {
            if (itemType.equals(item)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Checks if the material type is considered to be a wearable Armor piece for this role.
     *
     * @param itemStack The type of material to check
     *
     * @return True if the material is allowed as an armor piece
     */
    boolean isArmorEquippable(ItemStack itemStack) {
        return isArmorEquippable(itemStack.getItem());
    }

    /**
     * Checks if the material type is considered to be a wearable Armor piece for this role.
     *
     * @param itemType The type of material to check
     *
     * @return True if the material is allowed as an armor piece
     */
    boolean isArmorEquippable(ItemType itemType) {
        checkNotNull(itemType);
        for (ItemType item : this.allowedArmor) {
            if (itemType.equals(item)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Represents a builder for an EquipmentAspect aspect
     */
    public static class EquipmentAspectBuilder {

        List<ItemType> allowedWeapons = Lists.newArrayList();
        List<ItemType> allowedArmor = Lists.newArrayList();

        private EquipmentAspectBuilder() {

        }

        /**
         * Adds the specified ItemType type to the allowed armor for this role. Armor can restricted
         * to different roles.
         *
         * @param type Type of armor material
         *
         * @return This builder for chaining
         */
        @SuppressWarnings("unused")
        public EquipmentAspectBuilder addAllowedArmor(ItemType type) {
            checkNotNull(type);
            this.allowedArmor.add(type);
            return this;
        }

        /**
         * Adds the given item type as an allowed weapon.
         *
         * @param type The item type
         *
         * @return This buidler for chaining
         */
        @SuppressWarnings("unused")
        public EquipmentAspectBuilder addAllowedWeapon(ItemType type) {
            checkNotNull(type);
            this.allowedWeapons.add(type);
            return this;
        }

        /**
         * Clears this builder of all settings ready for new data.
         *
         * @return This bulider for chaining
         */
        public EquipmentAspectBuilder reset() {
            this.allowedArmor = Lists.newArrayList();
            this.allowedWeapons = Lists.newArrayList();
            return this;
        }

        /**
         * Returns a new {@link EquipmentAspect}.
         *
         * @return A new equipment aspect
         */
        public EquipmentAspect build() {
            return new EquipmentAspect(this);
        }
    }
}


text:
ActiveRecord::Schema.define(version: 20150312053655) do

  create_table "goals", force: :cascade do |t|
    t.datetime "date"
    t.string   "token"
    t.integer  "value"
    t.boolean  "visible"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "marks", force: :cascade do |t|
    t.datetime "date"
    t.integer  "goal_id"
    t.integer  "value"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  add_index "marks", ["goal_id"], name: "index_marks_on_goal_id"

end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace eXtensoft.XF.Core
{
    public static class AppConstants
    {
        public const string EndpointsFilepath = "endpoints.xml";

        public static class Special
        {
            public const string Format = "{0}{1}{2}{3}{4}{5}{6}";
            public const int FormatIndex = 0;
            public const int FormatLength = 11;
            public const int YueIndex = 13;
            public const int Yue = 3;
            public const int TianIndex = 18;
            public const int Tian = 4;
            public const int XingQiIndex = 23;
            public const int XingQi = 13;

        }
    }
}


text:
"""
Heterogeneous GraphSAGE and compatible aggregator layers

"""
__all__ = ["HinSAGE", "MeanHinAggregator"]

import tensorflow as tf
from tensorflow.keras.layers import Layer
from tensorflow.keras import backend as K, Input
from tensorflow.keras.layers import Lambda, Dropout, Reshape
from tensorflow.keras.utils import Sequence
from tensorflow.keras import activations, initializers, regularizers, constraints
from typing import List, Callable, Tuple, Dict, Union, AnyStr
import itertools as it
import operator as op
import warnings

from .misc import deprecated_model_function
from ..mapper import HinSAGENodeGenerator, HinSAGELinkGenerator

HinSAGEAggregator = Layer

class MeanHinAggregator(HinSAGEAggregator):
    """Mean Aggregator for HinSAGE implemented with Keras base layer

    Args:
        output_dim (int): Output dimension
        bias (bool): Use bias in layer or not (Default False)
        act (Callable or str): name of the activation function to use (must be a Keras
            activation function), or alternatively, a TensorFlow operation.
        kernel_initializer (str or func): The initialiser to use for the weights
        kernel_regularizer (str or func): The regulariser to use for the weights
        kernel_constraint (str or func): The constraint to use for the weights
        bias_initializer (str or func): The initialiser to use for the bias
        bias_regularizer (str or func): The regulariser to use for the bias
        bias_constraint (str or func): The constraint to use for the bias
    """

    def __init__(
        self,
        output_dim: int = 0,
        bias: bool = False,
        act: Union[Callable, AnyStr] = "relu",
        kernel_initializer="glorot_uniform",
        kernel_regularizer=None,
        kernel_constraint=None,
        bias_initializer="zeros",
        bias_regularizer=None,
        bias_constraint=None,
        **kwargs,
    ):
        self.output_dim = output_dim
        if output_dim % 2 != 0:
            raise ValueError("The output_dim must be a multiple of two.")
        self.half_output_dim = output_dim // 2
        self.has_bias = bias
        self.act = activations.get(act)
        self.nr = None
        self.w_neigh = []
        self.w_self = None
        self.bias = None

        self.kernel_initializer = initializers.get(kernel_initializer)
        self.kernel_regularizer = regularizers.get(kernel_regularizer)
        self.kernel_constraint = constraints.get(kernel_constraint)
        self.bias_initializer = initializers.get(bias_initializer)
        self.bias_regularizer = regularizers.get(bias_regularizer)
        self.bias_constraint = constraints.get(bias_constraint)

        super().__init__(**kwargs)

    def get_config(self):
        """
        Gets class configuration for Keras serialization

        """
        config = {
            "output_dim": self.output_dim,
            "bias": self.has_bias,
            "act": activations.serialize(self.act),
            "kernel_initializer": initializers.serialize(self.kernel_initializer),
            "kernel_regularizer": regularizers.serialize(self.kernel_regularizer),
            "kernel_constraint": constraints.serialize(self.kernel_constraint),
            "bias_initializer": initializers.serialize(self.bias_initializer),
            "bias_regularizer": regularizers.serialize(self.bias_regularizer),
            "bias_constraint": constraints.serialize(self.bias_constraint),
        }
        base_config = super().get_config()
        return {**base_config, **config}

    def build(self, input_shape):
        """
        Builds layer

        Args:
            input_shape (list of list of int): Shape of input per neighbour type.

        """
        # Weight matrix for each type of neighbour
        # If there are no neighbours (input_shape[x][2]) for an input
        # then do not create weights as they are not used.
        self.nr = len(input_shape) - 1
        self.w_neigh = [
            self.add_weight(
                name="w_neigh_" + str(r),
                shape=(int(input_shape[1 + r][3]), self.half_output_dim),
                initializer=self.kernel_initializer,
                regularizer=self.kernel_regularizer,
                constraint=self.kernel_constraint,
                trainable=True,
            )
            if input_shape[1 + r][2] > 0
            else None
            for r in range(self.nr)
        ]

        # Weight matrix for self
        self.w_self = self.add_weight(
            name="w_self",
            shape=(int(input_shape[0][2]), self.half_output_dim),
            initializer=self.kernel_initializer,
            regularizer=self.kernel_regularizer,
            constraint=self.kernel_constraint,
            trainable=True,
        )

        # Optional bias
        if self.has_bias:
            self.bias = self.add_weight(
                name="bias",
                shape=[self.output_dim],
                initializer=self.bias_initializer,
                regularizer=self.bias_regularizer,
                constraint=self.bias_constraint,
                trainable=True,
            )

        super().build(input_shape)

    def call(self, x, **kwargs):
        """
        Apply MeanAggregation on input tensors, x

        Args:
          x: List of Keras Tensors with the following elements

            - x[0]: tensor of self features shape (n_batch, n_head, n_feat)
            - x[1+r]: tensors of neighbour features each of shape (n_batch, n_head, n_neighbour[r], n_feat[r])

        Returns:
            Keras Tensor representing the aggregated embeddings in the input.

        """
        # Calculate the mean vectors over the neigbours of each relation (edge) type
        neigh_agg_by_relation = []
        for r in range(self.nr):
            # The neighbour input tensors for relation r
            z = x[1 + r]

            # If there are neighbours aggregate over them
            if z.shape[2] > 0:
                z_agg = K.dot(K.mean(z, axis=2), self.w_neigh[r])

            # Otherwise add a synthetic zero vector
            else:
                z_shape = K.shape(z)
                w_shape = self.half_output_dim
                z_agg = tf.zeros((z_shape[0], z_shape[1], w_shape))

            neigh_agg_by_relation.append(z_agg)

        # Calculate the self vector shape (n_batch, n_head, n_out_self)
        from_self = K.dot(x[0], self.w_self)

        # Sum the contributions from all neighbour averages shape (n_batch, n_head, n_out_neigh)
        from_neigh = sum(neigh_agg_by_relation) / self.nr

        # Concatenate self + neighbour features, shape (n_batch, n_head, n_out)
        total = K.concatenate(
            [from_self, from_neigh], axis=2
        )  # YT: this corresponds to concat=Partial
        # TODO: implement concat=Full and concat=False

        return self.act((total + self.bias) if self.has_bias else total)

    def compute_output_shape(self, input_shape):
        """
        Computes the output shape of the layer.
        Assumes that the layer will be built to match that input shape provided.

        Args:
            input_shape (tuple of int)
                Shape tuples can include `None` for free dimensions, instead of an integer.

        Returns:
            An input shape tuple.
        """
        return input_shape[0][0], input_shape[0][1], self.output_dim

def _require_without_generator(value, name):
    if value is not None:
        return value
    else:
        raise ValueError(
            f"{name}: expected a value for 'input_neighbor_tree', 'n_samples', 'input_dim', and "
            f"'multiplicity' when 'generator' is not provided, found {name}=None."
        )

class HinSAGE:
    """
    Implementation of the GraphSAGE algorithm extended for heterogeneous graphs with Keras layers.

    To use this class as a Keras model, the features and graph should be supplied using the
    :class:`.HinSAGENodeGenerator` class for node inference models or the
    :class:`.HinSAGELinkGenerator` class for link inference models.  The `.in_out_tensors` method should
    be used to create a Keras model from the `GraphSAGE` object.

    Currently the class supports node or link prediction models which are built depending on whether
    a `HinSAGENodeGenerator` or `HinSAGELinkGenerator` object is specified.
    The models are built for a single node or link type. For example if you have nodes of types 'A' and 'B'
    you can build a link model for only a single pair of node types, for example ('A', 'B'), which should
    be specified in the `HinSAGELinkGenerator`.

    If you feed links into the model that do not have these node types (in correct order) an error will be
    raised.

    Examples:
        Creating a two-level GrapSAGE node classification model on nodes of type 'A' with hidden node sizes of 8 and 4
        and 10 neighbours sampled at each layer using an existing :class:`.StellarGraph` object `G`
        containing the graph and node features::

            generator = HinSAGENodeGenerator(
                G, batch_size=50, num_samples=[10,10], head_node_type='A'
                )
            gat = HinSAGE(
                    layer_sizes=[8, 4],
                    activations=["relu","softmax"],
                    generator=generator,
                )
            x_inp, predictions = gat.in_out_tensors()

        Creating a two-level GrapSAGE link classification model on nodes pairs of type ('A', 'B')
        with hidden node sizes of 8 and 4 and 5 neighbours sampled at each layer::

            generator = HinSAGELinkGenerator(
                G, batch_size=50, num_samples=[5,5], head_node_types=('A','B')
                )
            gat = HinSAGE(
                    layer_sizes=[8, 4],
                    activations=["relu","softmax"],
                    generator=generator,
                )
            x_inp, predictions = gat.in_out_tensors()

    Note that passing a `NodeSequence` or `LinkSequence` object from the `generator.flow(...)` method
    as the `generator=` argument is now deprecated and the base generator object should be passed instead.

    .. seealso::

       Examples using HinSAGE:

       - `link prediction <https://stellargraph.readthedocs.io/en/stable/demos/link-prediction/hinsage-link-prediction.html>`__
       - `unsupervised representation learning with Deep Graph Infomax <https://stellargraph.readthedocs.io/en/stable/demos/embeddings/deep-graph-infomax-embeddings.html>`__

       Appropriate data generators: :class:`.HinSAGENodeGenerator`, :class:`.HinSAGELinkGenerator`.

       Related models:

       - :class:`.GraphSAGE` for homogeneous graphs
       - :class:`.DirectedGraphSAGE` for homogeneous directed graphs
       - :class:`.DeepGraphInfomax` for unsupervised training

       Aggregators: :class:`.MeanHinAggregator`.

       The `Heterogeneous GraphSAGE (HinSAGE) <https://stellargraph.readthedocs.io/en/stable/hinsage.html>`__ explanatory document has more theoretical details.

    Args:
        layer_sizes (list): Hidden feature dimensions for each layer
        generator (HinSAGENodeGenerator or HinSAGELinkGenerator):
            If specified, required model arguments such as the number of samples
            will be taken from the generator object. See note below.
        aggregator (HinSAGEAggregator): The HinSAGE aggregator to use; defaults to the `MeanHinAggregator`.
        bias (bool): If True (default), a bias vector is learnt for each layer.
        dropout (float): The dropout supplied to each layer; defaults to no dropout.
        normalize (str): The normalization used after each layer; defaults to L2 normalization.
        activations (list): Activations applied to each layer's output;
            defaults to ``['relu', ..., 'relu', 'linear']``.
        kernel_initializer (str or func, optional): The initialiser to use for the weights of each layer.
        kernel_regularizer (str or func, optional): The regulariser to use for the weights of each layer.
        kernel_constraint (str or func, optional): The constraint to use for the weights of each layer.
        bias_initializer (str or func, optional): The initialiser to use for the bias of each layer.
        bias_regularizer (str or func, optional): The regulariser to use for the bias of each layer.
        bias_constraint (str or func, optional): The constraint to use for the bias of each layer.
        n_samples (list, optional): The number of samples per layer in the model.
        input_neighbor_tree (list of tuple, optional): A list of (node_type, [children]) tuples that
            specify the subtree to be created by the HinSAGE model.
        input_dim (dict, optional): The input dimensions for each node type as a dictionary of the form
            ``{node_type: feature_size}``.
        multiplicity (int, optional): The number of nodes to process at a time. This is 1 for a node
            inference and 2 for link inference (currently no others are supported).

    .. note::
        The values for ``n_samples``, ``input_neighbor_tree``, ``input_dim``, and ``multiplicity`` are
        obtained from the provided ``generator`` by default. The additional keyword arguments for these
        parameters provide an alternative way to specify them if a generator cannot be supplied.
    """

    def __init__(
        self,
        layer_sizes,
        generator=None,
        aggregator=None,
        bias=True,
        dropout=0.0,
        normalize="l2",
        activations=None,
        kernel_initializer="glorot_uniform",
        kernel_regularizer=None,
        kernel_constraint=None,
        bias_initializer="zeros",
        bias_regularizer=None,
        bias_constraint=None,
        n_samples=None,
        input_neighbor_tree=None,
        input_dim=None,
        multiplicity=None,
    ):
        # Set the aggregator layer used in the model
        if aggregator is None:
            self._aggregator = MeanHinAggregator
        elif issubclass(aggregator, Layer):
            self._aggregator = aggregator
        else:
            raise TypeError("Aggregator should be a subclass of Keras Layer")

        # Set the normalization layer used in the model
        if normalize == "l2":
            self._normalization = Lambda(lambda x: K.l2_normalize(x, axis=-1))

        elif normalize is None or normalize == "none" or normalize == "None":
            self._normalization = Lambda(lambda x: x)

        else:
            raise ValueError(
                "Normalization should be either 'l2' or 'none'; received '{}'".format(
                    normalize
                )
            )

        # Get the sampling tree, input_dim, and num_samples from the generator
        # if no generator these must be supplied in kwargs
        if generator is not None:
            self._get_sizes_from_generator(generator)
        else:
            self.subtree_schema = _require_without_generator(
                input_neighbor_tree, "input_neighbor_tree"
            )
            self.n_samples = _require_without_generator(n_samples, "n_samples")
            self.input_dims = _require_without_generator(input_dim, "input_dim")
            self.multiplicity = _require_without_generator(multiplicity, "multiplicity")

        # Set parameters for the model
        self.n_layers = len(self.n_samples)
        self.bias = bias
        self.dropout = dropout

        # Neighbourhood info per layer
        self.neigh_trees = self._eval_neigh_tree_per_layer(
            [li for li in self.subtree_schema if len(li[1]) > 0]
        )

        # Depth of each input tensor i.e. number of hops from root nodes
        self._depths = [
            self.n_layers
            + 1
            - sum([1 for li in [self.subtree_schema] + self.neigh_trees if i < len(li)])
            for i in range(len(self.subtree_schema))
        ]

        # Dict of {node type: dimension} per layer
        self.dims = [
            dim
            if isinstance(dim, dict)
            else {k: dim for k, _ in ([self.subtree_schema] + self.neigh_trees)[layer]}
            for layer, dim in enumerate([self.input_dims] + layer_sizes)
        ]

        # Activation function for each layer
        if activations is None:
            activations = ["relu"] * (self.n_layers - 1) + ["linear"]
        elif len(activations) != self.n_layers:
            raise ValueError(
                "Invalid number of activations; require one function per layer"
            )
        self.activations = activations

        # Aggregator functions for each layer
        self._aggs = [
            {
                node_type: self._aggregator(
                    output_dim,
                    bias=self.bias,
                    act=self.activations[layer],
                    kernel_initializer=kernel_initializer,
                    kernel_regularizer=kernel_regularizer,
                    kernel_constraint=kernel_constraint,
                    bias_initializer=bias_initializer,
                    bias_regularizer=bias_regularizer,
                    bias_constraint=bias_constraint,
                )
                for node_type, output_dim in self.dims[layer + 1].items()
            }
            for layer in range(self.n_layers)
        ]

    def _get_sizes_from_generator(self, generator):
        """
        Sets n_samples and input_feature_size from the generator.
        Args:
             generator: The supplied generator.
        """
        if not isinstance(generator, (HinSAGELinkGenerator, HinSAGENodeGenerator)):
            errmsg = "Generator should be an instance of HinSAGELinkGenerator or HinSAGENodeGenerator"
            if isinstance(generator, (NodeSequence, LinkSequence)):
                errmsg = (
                    "Passing a Sequence object as the generator to HinSAGE is no longer supported. "
                    + errmsg
                )
            raise TypeError(errmsg)

        self.n_samples = generator.num_samples
        self.subtree_schema = generator.schema.type_adjacency_list(
            generator.head_node_types, len(self.n_samples)
        )
        self.input_dims = generator.graph.node_feature_sizes()
        self.multiplicity = generator.multiplicity

    @staticmethod
    def _eval_neigh_tree_per_layer(input_tree):
        """
        Function to evaluate the neighbourhood tree structure for every layer. The tree
        structure at each layer is a truncated version of the previous layer.

        Args:
            input_tree: Neighbourhood tree for the input batch

        Returns:
            List of neighbourhood trees

        """
        reduced = [
            li
            for li in input_tree
            if all(li_neigh < len(input_tree) for li_neigh in li[1])
        ]
        return (
            [input_tree]
            if len(reduced) == 0
            else [input_tree] + HinSAGE._eval_neigh_tree_per_layer(reduced)
        )

    def __call__(self, xin: List):
        """
        Apply aggregator layers

        Args:
            x (list of Tensor): Batch input features

        Returns:
            Output tensor
        """

        def apply_layer(x: List, layer: int):
            """
            Compute the list of output tensors for a single HinSAGE layer

            Args:
                x (List[Tensor]): Inputs to the layer
                layer (int): Layer index

            Returns:
                Outputs of applying the aggregators as a list of Tensors

            """
            layer_out = []
            for i, (node_type, neigh_indices) in enumerate(self.neigh_trees[layer]):
                # The shape of the head node is used for reshaping the neighbour inputs
                head_shape = K.int_shape(x[i])[1]

                # Aplly dropout and reshape neighbours per node per layer
                neigh_list = [
                    Dropout(self.dropout)(
                        Reshape(
                            (
                                head_shape,
                                self.n_samples[self._depths[i]],
                                self.dims[layer][self.subtree_schema[neigh_index][0]],
                            )
                        )(x[neigh_index])
                    )
                    for neigh_index in neigh_indices
                ]

                # Apply dropout to head inputs
                x_head = Dropout(self.dropout)(x[i])

                # Apply aggregator to head node and reshaped neighbour nodes
                layer_out.append(self._aggs[layer][node_type]([x_head] + neigh_list))

            return layer_out

        # Form HinSAGE layers iteratively
        self.layer_tensors = []
        h_layer = xin
        for layer in range(0, self.n_layers):
            h_layer = apply_layer(h_layer, layer)
            self.layer_tensors.append(h_layer)

        # Remove neighbourhood dimension from output tensors
        # note that at this point h_layer contains the output tensor of the top (last applied) layer of the stack
        h_layer = [
            Reshape(K.int_shape(x)[2:])(x) for x in h_layer if K.int_shape(x)[1] == 1
        ]

        # Return final layer output tensor with optional normalization
        return (
            self._normalization(h_layer[0])
            if len(h_layer) == 1
            else [self._normalization(xi) for xi in h_layer]
        )

    def _input_shapes(self) -> List[Tuple[int, int]]:
        """
        Returns the input shapes for the tensors of the supplied neighbourhood type tree

        Returns:
            A list of tuples giving the shape (number of nodes, feature size) for
            the corresponding item in the neighbourhood type tree (self.subtree_schema)
        """
        neighbor_sizes = list(it.accumulate([1] + self.n_samples, op.mul))

        def get_shape(stree, cnode, level=0):
            adj = stree[cnode][1]
            size_dict = {
                cnode: (neighbor_sizes[level], self.input_dims[stree[cnode][0]])
            }
            if len(adj) > 0:
                size_dict.update(
                    {
                        k: s
                        for a in adj
                        for k, s in get_shape(stree, a, level + 1).items()
                    }
                )
            return size_dict

        input_shapes = dict()
        for ii in range(len(self.subtree_schema)):
            input_shapes_ii = get_shape(self.subtree_schema, ii)
            # Update input_shapes if input_shapes_ii.keys() are not already in input_shapes.keys():
            if (
                len(set(input_shapes_ii.keys()).intersection(set(input_shapes.keys())))
                == 0
            ):
                input_shapes.update(input_shapes_ii)

        return [input_shapes[ii] for ii in range(len(self.subtree_schema))]

    def in_out_tensors(self):
        """
        Builds a HinSAGE model for node or link/node pair prediction, depending on the generator used to construct
        the model (whether it is a node or link/node pair generator).

        Returns:
            tuple: ``(x_inp, x_out)``, where ``x_inp`` is a list of Keras input tensors
                for the specified HinSAGE model (either node or link/node pair model) and ``x_out`` contains
                model output tensor(s) of shape (batch_size, layer_sizes[-1]).

        """

        # Create tensor inputs
        x_inp = [Input(shape=s) for s in self._input_shapes()]

        # Output from HinSAGE model
        x_out = self(x_inp)

        return x_inp, x_out

    def default_model(self, flatten_output=True):
        warnings.warn(
            "The .default_model() method is deprecated. Please use .in_out_tensors() method instead.",
            DeprecationWarning,
            stacklevel=2,
        )
        return self.in_out_tensors()

    build = deprecated_model_function(in_out_tensors, "build")


text:
<?php

/**
 * Classloader for User Model
 * @param String $classname
 */
function UserModelClassLoader($classname)
{
    // Handle setting the path if there is one set - such as for PHPUnit
    if (isset($GLOBALS['path']))
    {
        $prefix = $GLOBALS['path'] . "/";
    }
    else
    {
        $prefix = "";
    }

    // User Model
    if (file_exists($prefix . "Models/UserModel/" . $classname . ".php"))
    {
        require_once $prefix . "Models/UserModel/" . $classname . ".php";
    }
    elseif (file_exists($prefix . "Models/UserModel/AuthenticationModules/" . $classname . ".php"))
    {
        require_once $prefix . "Models/UserModel/AuthenticationModules/" . $classname . ".php";
    }
 }


text:
layout: page
title:
permalink: /contact/
---


text:
// headed to implement Advanced Encryption Standard - Rijndael2
#ifndef _AES_H
#define _AES_H
#include <string.h>

/* USAGE:
        1. Create a AES class (or more as necessary)
        2. Call class method SetParameters
        3. To encrypt, call method StartEncryption with the key, and then
                call method Encrypt with enough space to store the proper size blocks.
        4. To decrypt, call method StartDecryption with the key, and then
                call method Decrypt with enough space to store the proper size blocks.

   Alternatively, you can call EncryptBlock and DecryptBlock block to process blocksize
   (default to 16 bytes) bytes at a time. It is recommended to use the Encrypt function
   for multiple block encryption since it uses chaining modes that make the overall
   stream much more secure than the default block based encryption, which by default would
   be mode ECB.

   EXAMPLE: want to encrypt 37 bytes of data with 192 bit key, which will use 3 16 byte blocks
   AES aes;
   aes.SetParameters(192);
   aes.StartEncryption(key);
   aes.Encrypt(data,output,3); // note data and output must be at least 48 bytes!
 */

// todo - replace all types with u1byte, u4byte, etc

class AES
{
public:
    // the constructor - makes sure local things are initialized
    // it if fails, throws the string "Tables failed to initialize"
    AES(void);

    // multiple block encryption/decryption modes
    // See http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation
    enum BlockMode {
        ECB = 0,         // Electronic CodeBook	  - each block independent, weak
        CBC = 1          // Cipher Block Chaining - most secure
              // todo - CFB = 2, // Cipher FeedBack       - secure
              // todo - OFB = 3, // Output FeedBack		  - secure
              // todo - CTR = 4,  // Counter				  - allows midstream decryption, somewhat secure
              // todo - EAX = 5, - http://www.cs.berkeley.edu/~daw/papers/eprint-short-ae.pdf
              // todo - GCM = 6, - http://www.cryptobarn.com/papers/gcm-spec.pdf
    };

    // block and key size are in bits, legal values are 128, 192, and 256 independently.
    // NOTE: the AES standard only uses a blocksize of 128, so we default to that
    void SetParameters(int keylength, int blocklength = 128);

    // call this before any encryption with the key to use
    void StartEncryption(const unsigned char *key);

    // encrypt a single block (default 128 bits, or unsigned char[16]) of data
    void EncryptBlock(const unsigned char *datain, unsigned char *dataout);

    // Call this to encrypt any length data. Note the size is in BLOCKS, so you must
    // have enough space in datain and dataout to accomodate this. Pad your data before
    // calling, preferably using the padding methods listed below.
    // Decryption must use the same mode as the encryption.
    void Encrypt(const unsigned char *datain, unsigned char *dataout, unsigned int numBlocks, BlockMode mode = CBC);

    // call this before any decryption with the key to use
    void StartDecryption(const unsigned char *key);

    // decrypt a single block (default 128 bits, or unsigned char[16]) of data
    void DecryptBlock(const unsigned char *datain, unsigned char *dataout);

    // Call this to decrypt any length data. Note the size is in BLOCKS, so you must
    // have enough space in datain and dataout to accomodate this. Pad your data before
    // calling, preferably using the padding methods listed below. You must know the desired
    // length of the output data, since all the blocks are returned decrypted.
    // Encryption must use the same mode as the decryption.
    void Decrypt(const unsigned char *datain, unsigned char *dataout, unsigned int numBlocks, BlockMode mode = CBC);

    int bsize;
private:
    int Nb, Nk;                  // block and key length / 32, should be 4,6,or 8
    int Nr;                      // number of rounds

    unsigned char W[4 * 8 * 15]; // the expanded key

    // Key expansion code - makes local copy
    void KeyExpansion(const unsigned char *key);
};         // class AES

/* PADDING:
    The AES (Rijndael) encryption algorithm pads encrypted data to a multiple of 16 bytes by default.
        Other blocksizes are similar. Methods:
    1. RFC 1423 padding scheme:
           Each padding byte is set to the number of padding bytes. If the data is already a multiple
           of 16 bytes, 16 additional bytes are added, each having the value 0x10.
    2. FIPS81 (Federal Information Processing Standards 81):
           The last byte contains the number of padding bytes, including itself,
           and the other padding bytes are set to random values.
    3. Each padding byte is set to a random value. The decryptor must know how many bytes are in the original unencrypted data.
 */

/* TODO
   The Encrypt() function is used to encrypt larger blocks of data. The block size has to be a multiple of the method's block size.
   This function can operate in the following modes: ECB, CBC or CFB. ECB mode is not using chaining. If the same block is encrypted
   twice with the same key, the resulting ciphertext blocks are the same. In CBC mode, a ciphertext block is obtained by first XORing
   the plaintext block with the previous ciphertext block, and encrypting the resulting value. In CFB mode, a ciphertext block is
   obtained by encrypting the previous ciphertext block and XORing the resulting value with the plaintext. The operation mode is
   specified in the iMode parameter with ECB being the default value.

 */
#endif //  _AES_H
// end - AES.h


text:
@protocol MFNetworkIndicatorDelegate <NSObject>

- (void)showNetworkIndicator;
- (void)hideNetworkIndicator;

@end


text:
namespace MassTransit.Tests.Middleware
{
    namespace Rescues
    {
        using System;
        using System.Threading;
        using System.Threading.Tasks;
        using MassTransit.Middleware;
        using NUnit.Framework;
        using TestFramework;

        [TestFixture]
        public class RescueContext_Specs
        {
            [Test]
            public async Task Should_invoke_the_rescue_pipe()
            {
                var count = 0;
                IPipe<SomeContext> pipe = Pipe.New<SomeContext>(x =>
                {
                    x.UseRescue((cxt, ex) => (SomeRescueContext)new SomeRescueContextImpl(cxt, ex), r =>
                    {
                        r.UseExecute(c => Interlocked.Increment(ref count));

                        r.Handle<IntentionalTestException>();
                    });

                    x.UseExecute(cxt =>
                    {
                        throw new IntentionalTestException("Kaboom!");
                    });
                });

                var context = new SomeContextImpl();

                await pipe.Send(context);

                Assert.That(count, Is.EqualTo(1));
            }
        }

        interface SomeContext :
            PipeContext
        {
        }

        class SomeContextImpl :
            BasePipeContext,
            SomeContext
        {
        }

        interface SomeRescueContext :
            SomeContext
        {
            Exception Exception { get; }
        }

        class SomeRescueContextImpl :
            ProxyPipeContext,
            SomeRescueContext
        {
            public SomeRescueContextImpl(SomeContext context, Exception exception)
                : base(context)
            {
                Exception = exception;
            }

            public Exception Exception { get; }
        }
    }
}


text:
<!DOCTYPE html>

		<title>Material Admin - Charts</title>

		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<meta name="keywords" content="your,keywords">
		<meta name="description" content="Short explanation about this website">

		<link href='http://fonts.googleapis.com/css?family=Roboto:300italic,400italic,300,400,500,700,900' rel='stylesheet' type='text/css'/>
		<link type="text/css" rel="stylesheet" href="../../assets/css/theme-default/bootstrap.css?1422792965" />
		<link type="text/css" rel="stylesheet" href="../../assets/css/theme-default/materialadmin.css?1425466319" />
		<link type="text/css" rel="stylesheet" href="../../assets/css/theme-default/font-awesome.min.css?1422529194" />
		<link type="text/css" rel="stylesheet" href="../../assets/css/theme-default/material-design-iconic-font.min.css?1421434286" />
		<link type="text/css" rel="stylesheet" href="../../assets/css/theme-default/libs/morris/morris.core.css?1420463396" />
		<link type="text/css" rel="stylesheet" href="../../assets/css/theme-default/libs/rickshaw/rickshaw.css?1422792967" />

									MATERIAL ADMIN

							<form class="navbar-search" role="search">

									<input type="text" class="form-control" name="headerSearch" placeholder="Enter your keyword">

								<button type="submit" class="btn btn-icon-toggle ink-reaction"></button>
							</form>

								4

Today's messages

										Alex Anistor

										Testing functionality...

										Alicia Adell

										Reviewing last changes...

Options

View all messages

Mark as read

Server load

											Server load Today
											93%

											Server load Yesterday
											30%

											Server load Lastweek
											74%

									Daniel Johnson
									Administrator

Config

My profile

My blog 16

My appointments

 Lock

 Logout

Charts

Flot charts

Examples

										Attractive JavaScript plotting for jQuery.
										Flot is a pure JavaScript plotting library for jQuery, with a focus on simple usage, attractive looks and interactive features.

								Interactive linechart

								Realtime chart

Rickshaw charts

Examples

										Rickshaw is a JavaScript toolkit for creating interactive time series graphs.

								 Interactive Real-Time Data (Dig into continuously updating data)

								 Multiple Renderers (Bars, lines, area, and scatterplot graphs all in one setting)

Knob charts

Examples

										Knob charts are a downward compatible, touchable, jQuery dial.
										Material Admin has added serveral classes for easy styling with theme colors.

<input type="text" class="dial" data-min="0" data-max="100" data-thickness=.1 value="40" data-readOnly=true>

								Thin knob chart

<input type="text" class="dial" data-min="0" data-max="100" data-thickness=.1 value="40" data-readOnly=true>

								Thin knob chart with alternative colors

<input type="text" class="dial" data-min="0" data-max="365" data-cursor=true value="90">

								Interactive knob chart

<input type="text" class="dial" value="56" data-angleOffset=-125 data-angleArc=250 data-readOnly=true>

								Gauge style knob chart

Sparkline charts

Examples

										This jQuery plugin generates sparklines (small inline charts) directly in the browser using data supplied either inline in the HTML, or via javascript.

											Lorem ipsum dolor 1,1,2, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna 4,6,7,7,4,3,2,1,4,4. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate 1,4,4,7,5,9,10 cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa 1,4,4,7,5,9,10 qui officia deserunt mollit anim id est laborum.

											Curabitur 4,27,34,52,54,59,61,68,78,82,85,87,91,93,100 tincidunt lacus. Nulla gravida orci a odio. Nullam varius, turpis et commodo pharetra, est eros bibendum elit, nec luctus magna felis sollicitudin mauris. Integer in mauris eu nibh euismod gravida. Duis 10,12,12,9,7 ac tellus et risus vulputate vehicula. Donec lobortis risus a elit. 1,1,0,1,-1,-1,1,-1,0,0,1,1 Etiam tempor.

								Sparkline work perfectly in large parts of text

										With Sparklines you can also create larger charts as you can see below.

								Large sparkline

								Large sparkline

Morris charts

Area chart

										Create an area chart using Morris.Area(options).
										Area charts take all the same options as line charts, and the following extras: behaveLikeLine

								Area chart

Bar charts

										Create bar charts using Morris.Bar(options).

								Grouped bar chart

Stacked bar charts

Create a stacked bar chart by using stacked:true

								Stacked bar chart

Donut chart

This really couldn't be easier. Create a Donut chart using Morris.Donut(options)

								Donut chart

Morris Line chart

							The public API is terribly simple. It's just one function: Morris.Line(options), where options is an object containing some of the following configuration options.

							MATERIAL ADMIN

								Dashboard

								Email

Inbox

Compose

Reply

View message

								Layouts

								UI elements

Colors

Typography

Cards

Buttons

Lists

Tabs

Accordions

Messages

Off-canvas

Grid

										Icons

Material Design Icons

Font Awesome

Glyphicons

Skycons

								Tables

Static Tables

Dynamic Tables

Responsive Table

								Forms

Form basic

Form advanced

Form layouts

Editors

Form validation

Form wizard

								Pages

										Contacts

Search

Contact card

Insert contact

										Search

Results - Text

Results - Text and Image

										Blog

Blog masonry

Blog list

Blog post

										Error pages

404 page

500 page

User profile42

Invoice

Calendar

Pricing

Timeline

Maps

Lock screen

Login

Blank page

								Charts

								Menu levels demo

Item 1

Item 1

										Open level 2

Item 2

												Open level 3

Item 3

Item 3

														Open level 4

Item 4

																Open level 5

Item 5

Item 5

							Copyright © 2014 CodeCovers

						Search

A

										Alex Nelson
										123-123-3210

										Ann Laurens
										123-123-3210

J

										Jessica Cruise
										123-123-3210

										Jim Peters
										123-123-3210

M

										Mabel Logan
										123-123-3210

										Mary Peterson
										123-123-3210

										Mike Alba
										123-123-3210

N

										Nathan Peterson
										123-123-3210

P

										Philip Ericsson
										123-123-3210

S

										Samuel Parsons
										123-123-3210

						Chat with Ann Laurens

						<form class="form">

								<textarea name="sidebarChatMessage" id="sidebarChatMessage" class="form-control autosize" rows="1"></textarea>
								Leave a message

						</form>

										Yes, it is indeed very beautiful.
										10:03 pm

										Did you see the changes?
										10:02 pm

										I just arrived at work, it was quite busy.
										06:44pm

										I will take look in a minute.
										06:45pm

										The colors are much better now.

										The colors are brighter than before.
										I have already sent an example.
										This will make it look sharper.
										Mon

										Are the colors of the logo already adapted?
										Last week


text:
layout: page
title: About
comments: yes
permalink: /about/
---

### Hi There

Hi, I'm Frank TAO. I'm an ERP/CRM Consultant, a developer, a husband and a father.

### Projects

### Books

### Courses

### The Profile about the Frank Tao.

Please find personal cv or pdf version.