text:
goog.provide('webfont.BrowserInfo');

/**
 * @export
 * @constructor
 * @param {boolean} webfontSupport
 * @param {boolean} webKitFallbackBug
 * @param {boolean} webKitMetricsBug
 */
webfont.BrowserInfo = function (webfontSupport, webKitFallbackBug, webKitMetricsBug) {
  this.webfontSupport_ = webfontSupport;
  this.webKitFallbackBug_ = webKitFallbackBug;
  this.webKitMetricsBug_ = webKitMetricsBug;
};

goog.scope(function () {
  var BrowserInfo = webfont.BrowserInfo;

  /**
   * @export
   * Returns true if the browser supports web fonts.
   *
   * @return {boolean}
   */
  BrowserInfo.prototype.hasWebFontSupport = function () {
    return this.webfontSupport_;
  };

  /**
   * @export
   *
   * Returns true if the browser has the WebKit fallback bug.
   *
   * The bug causes the normal CSS font stack to be ignored while
   * loading web fonts. Instead it picks the generic font family
   * (or the default generic font family) of the first instance
   * the web font is mentioned in CSS. It switches to this font
   * immediately while loading web font, causing two changes in
   * font to occur (compared to other browsers which only change
   * font once the web font has loaded.)
   *
   * The bug has been fixed and is only happens in WebKit versions
   * below 536.11. Even though it is fixed we still have a large
   * percentage of users on older WebKit versions, mostly on mobile
   * platforms.
   *
   * Also see: https://bugs.webkit.org/show_bug.cgi?id=76684
   *
   * @return {boolean}
   */
  BrowserInfo.prototype.hasWebKitFallbackBug = function () {
    return this.webKitFallbackBug_;
  };

  /**
   * @export
   *
   * Returns true if the browser has the WebKit metrics bug
   *
   * The metrics bug causes WebKit to change the height of a font
   * while loading a web font. Other browsers do not modify
   * the width or height of the fallback font while a web font is
   * loading. This caused our width and height check to be incorrect,
   * triggering a false positive.
   *
   * Also see: https://bugs.webkit.org/show_bug.cgi?id=110977
   *
   * @return {boolean}
   */
  BrowserInfo.prototype.hasWebKitMetricsBug = function () {
    return this.webKitMetricsBug_;
  };
});


text:
package com.example.me.websample;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

public class WebSampleTools {
	public static byte[] read(InputStream inStream) throws Exception{
		ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
		byte[] buffer=new byte[1024];
		int len=0;
		while((len=inStream.read(buffer)) !=-1){
			outputStream.write(buffer,0,len);
		}
		inStream.close();
		return outputStream.toByteArray();
	}

}

redpajama_set_name: RedPajamaGithub


text:
namespace Urho3D
{

class HierarchyTab : public Tab
{
    URHO3D_OBJECT(HierarchyTab, Tab)
public:
    ///
    explicit HierarchyTab(Context* context);
    ///
    bool RenderWindowContent() override;
    ///
    void SetProvider(IHierarchyProvider* provider);

protected:
    ea::pair<WeakPtr<RefCounted>, IHierarchyProvider*> provider_;
};

}


text:
<?php

namespace Pan100\MoodLogBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use FOS\UserBundle\Doctrine\UserManager;

use Pan100\MoodLogBundle\Entity\Day;
use Pan100\MoodLogBundle\Entity\Medication;
use Pan100\MoodLogBundle\Entity\Trigger;

class GrantAccessCommand extends ContainerAwareCommand
{
    private $userManager;

    protected function configure()
    {
        $this
            ->setName('mood:grantaccess')
            ->setDescription('grants a medic access to reports of the given patient')
            ->addArgument('medic', InputArgument::REQUIRED, 'Type the username of the medic')
            ->addArgument('patient', InputArgument::REQUIRED, 'Type the username of the patient')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->userManager = $this->getContainer()->get('fos_user.user_manager');

            $medic = $this->userManager->findUserByUsername($input->getArgument('medic'));
            $patient = $this->userManager->findUserByUsername($input->getArgument('patient'));
            $patient->addHasAccessToMe($medic);
            $this->userManager->updateUser($patient);
    }
}


text:
	local suite = test.declare("codelite_workspace")
	local p = premake
	local codelite = p.modules.codelite

--
-- Setup
--

	local wks, prj

	function suite.setup()
		p.action.set("codelite")
		p.escaper(codelite.esc)
		p.indent("  ")
		wks = test.createWorkspace()
	end

	local function prepare()
		wks = test.getWorkspace(wks)
		codelite.workspace.generate(wks)
	end

--
-- Check the basic structure of a workspace.
--

	function suite.onEmptyWorkspace()
		wks.projects = {}
		prepare()
		test.capture [[
<?xml version="1.0" encoding="UTF-8"?>
<CodeLite_Workspace Name="MyWorkspace" Database="" SWTLW="No">
  <BuildMatrix>
    <WorkspaceConfiguration Name="Debug" Selected="yes">
    </WorkspaceConfiguration>
    <WorkspaceConfiguration Name="Release" Selected="yes">
    </WorkspaceConfiguration>
  </BuildMatrix>
</CodeLite_Workspace>
		]]
	end

	function suite.onDefaultWorkspace()
		prepare()
		test.capture [[
<?xml version="1.0" encoding="UTF-8"?>
<CodeLite_Workspace Name="MyWorkspace" Database="" SWTLW="No">
  <Project Name="MyProject" Path="MyProject.project"/>
  <BuildMatrix>
    <WorkspaceConfiguration Name="Debug" Selected="yes">
      <Project Name="MyProject" ConfigName="Debug"/>
    </WorkspaceConfiguration>
    <WorkspaceConfiguration Name="Release" Selected="yes">
      <Project Name="MyProject" ConfigName="Release"/>
    </WorkspaceConfiguration>
  </BuildMatrix>
</CodeLite_Workspace>
		]]
	end

	function suite.onMultipleProjects()
		test.createproject(wks)
		prepare()
		test.capture [[
<?xml version="1.0" encoding="UTF-8"?>
<CodeLite_Workspace Name="MyWorkspace" Database="" SWTLW="No">
  <Project Name="MyProject" Path="MyProject.project"/>
  <Project Name="MyProject2" Path="MyProject2.project"/>
  <BuildMatrix>
    <WorkspaceConfiguration Name="Debug" Selected="yes">
      <Project Name="MyProject" ConfigName="Debug"/>
      <Project Name="MyProject2" ConfigName="Debug"/>
    </WorkspaceConfiguration>
    <WorkspaceConfiguration Name="Release" Selected="yes">
      <Project Name="MyProject" ConfigName="Release"/>
      <Project Name="MyProject2" ConfigName="Release"/>
    </WorkspaceConfiguration>
  </BuildMatrix>
</CodeLite_Workspace>
		]]
	end

--
-- Projects should include relative path from workspace.
--

	function suite.onNestedProjectPath()
		location "MyProject"
		prepare()
		test.capture([[
<?xml version="1.0" encoding="UTF-8"?>
<CodeLite_Workspace Name="MyWorkspace" Database="" SWTLW="No">
  <Project Name="MyProject" Path="MyProject/MyProject.project"/>
  <BuildMatrix>
    <WorkspaceConfiguration Name="Debug" Selected="yes">
      <Project Name="MyProject" ConfigName="Debug"/>
    </WorkspaceConfiguration>
    <WorkspaceConfiguration Name="Release" Selected="yes">
      <Project Name="MyProject" ConfigName="Release"/>
    </WorkspaceConfiguration>
  </BuildMatrix>
</CodeLite_Workspace>
		]])
	end

	function suite.onExternalProjectPath()
		location "../MyProject"
		prepare()
		test.capture([[
<?xml version="1.0" encoding="UTF-8"?>
<CodeLite_Workspace Name="MyWorkspace" Database="" SWTLW="No">
  <Project Name="MyProject" Path="../MyProject/MyProject.project"/>
  <BuildMatrix>
    <WorkspaceConfiguration Name="Debug" Selected="yes">
      <Project Name="MyProject" ConfigName="Debug"/>
    </WorkspaceConfiguration>
    <WorkspaceConfiguration Name="Release" Selected="yes">
      <Project Name="MyProject" ConfigName="Release"/>
    </WorkspaceConfiguration>
  </BuildMatrix>
</CodeLite_Workspace>
		]])
	end

	function suite.onActiveProject()
		workspace("MyWorkspace")
		startproject "MyProject"
		prepare()
		test.capture([[
<?xml version="1.0" encoding="UTF-8"?>
<CodeLite_Workspace Name="MyWorkspace" Database="" SWTLW="No">
  <Project Name="MyProject" Path="MyProject.project" Active="Yes"/>
  <BuildMatrix>
    <WorkspaceConfiguration Name="Debug" Selected="yes">
      <Project Name="MyProject" ConfigName="Debug"/>
    </WorkspaceConfiguration>
    <WorkspaceConfiguration Name="Release" Selected="yes">
      <Project Name="MyProject" ConfigName="Release"/>
    </WorkspaceConfiguration>
  </BuildMatrix>
</CodeLite_Workspace>
		]])
	end

  function suite.onGroupedProjects()
    wks.projects = {}
    project "MyGrouplessProject"
    group "MyGroup"
    project "MyGroupedProject"
    group "My/Nested/Group"
    project "MyNestedGroupedProject"
    prepare()
    test.capture([[
<?xml version="1.0" encoding="UTF-8"?>
<CodeLite_Workspace Name="MyWorkspace" Database="" SWTLW="No">
  <VirtualDirectory Name="My">
    <VirtualDirectory Name="Nested">
      <VirtualDirectory Name="Group">
        <Project Name="MyNestedGroupedProject" Path="MyNestedGroupedProject.project"/>
      </VirtualDirectory>
    </VirtualDirectory>
  </VirtualDirectory>
  <VirtualDirectory Name="MyGroup">
    <Project Name="MyGroupedProject" Path="MyGroupedProject.project"/>
  </VirtualDirectory>
  <Project Name="MyGrouplessProject" Path="MyGrouplessProject.project"/>
  <BuildMatrix>
    <WorkspaceConfiguration Name="Debug" Selected="yes">
      <Project Name="MyNestedGroupedProject" ConfigName="Debug"/>
      <Project Name="MyGroupedProject" ConfigName="Debug"/>
      <Project Name="MyGrouplessProject" ConfigName="Debug"/>
    </WorkspaceConfiguration>
    <WorkspaceConfiguration Name="Release" Selected="yes">
      <Project Name="MyNestedGroupedProject" ConfigName="Release"/>
      <Project Name="MyGroupedProject" ConfigName="Release"/>
      <Project Name="MyGrouplessProject" ConfigName="Release"/>
    </WorkspaceConfiguration>
  </BuildMatrix>
</CodeLite_Workspace>
    ]])
  end


text:
package com.amazonaws.services.config.model;

import java.io.Serializable;
import javax.annotation.Generated;

/**
 *
 * @see AWS API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetAggregateConfigRuleComplianceSummaryResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements
        Serializable, Cloneable {

    /**
     *

     * Groups the result based on ACCOUNT_ID or AWS_REGION.
     *

     */
    private String groupByKey;
    /**
     *

     * Returns a list of AggregateComplianceCounts object.
     *

     */
    private com.amazonaws.internal.SdkInternalList<AggregateComplianceCount> aggregateComplianceCounts;
    /**
     *

     * The nextToken string returned on a previous page that you use to get the next page of results in a
     * paginated response.
     *

     */
    private String nextToken;

    /**
     *

     * Groups the result based on ACCOUNT_ID or AWS_REGION.
     *

     *
     * @param groupByKey
     *        Groups the result based on ACCOUNT_ID or AWS_REGION.
     */

    public void setGroupByKey(String groupByKey) {
        this.groupByKey = groupByKey;
    }

    /**
     *

     * Groups the result based on ACCOUNT_ID or AWS_REGION.
     *

     *
     * @return Groups the result based on ACCOUNT_ID or AWS_REGION.
     */

    public String getGroupByKey() {
        return this.groupByKey;
    }

    /**
     *

     * Groups the result based on ACCOUNT_ID or AWS_REGION.
     *

     *
     * @param groupByKey
     *        Groups the result based on ACCOUNT_ID or AWS_REGION.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetAggregateConfigRuleComplianceSummaryResult withGroupByKey(String groupByKey) {
        setGroupByKey(groupByKey);
        return this;
    }

    /**
     *

     * Returns a list of AggregateComplianceCounts object.
     *

     *
     * @return Returns a list of AggregateComplianceCounts object.
     */

    public java.util.List<AggregateComplianceCount> getAggregateComplianceCounts() {
        if (aggregateComplianceCounts == null) {
            aggregateComplianceCounts = new com.amazonaws.internal.SdkInternalList<AggregateComplianceCount>();
        }
        return aggregateComplianceCounts;
    }

    /**
     *

     * Returns a list of AggregateComplianceCounts object.
     *

     *
     * @param aggregateComplianceCounts
     *        Returns a list of AggregateComplianceCounts object.
     */

    public void setAggregateComplianceCounts(java.util.Collection<AggregateComplianceCount> aggregateComplianceCounts) {
        if (aggregateComplianceCounts == null) {
            this.aggregateComplianceCounts = null;
            return;
        }

        this.aggregateComplianceCounts = new com.amazonaws.internal.SdkInternalList<AggregateComplianceCount>(aggregateComplianceCounts);
    }

    /**
     *

     * Returns a list of AggregateComplianceCounts object.
     *

     *

     * NOTE: This method appends the values to the existing list (if any). Use
     * {@link #setAggregateComplianceCounts(java.util.Collection)} or
     * {@link #withAggregateComplianceCounts(java.util.Collection)} if you want to override the existing values.
     *

     *
     * @param aggregateComplianceCounts
     *        Returns a list of AggregateComplianceCounts object.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetAggregateConfigRuleComplianceSummaryResult withAggregateComplianceCounts(AggregateComplianceCount... aggregateComplianceCounts) {
        if (this.aggregateComplianceCounts == null) {
            setAggregateComplianceCounts(new com.amazonaws.internal.SdkInternalList<AggregateComplianceCount>(aggregateComplianceCounts.length));
        }
        for (AggregateComplianceCount ele : aggregateComplianceCounts) {
            this.aggregateComplianceCounts.add(ele);
        }
        return this;
    }

    /**
     *

     * Returns a list of AggregateComplianceCounts object.
     *

     *
     * @param aggregateComplianceCounts
     *        Returns a list of AggregateComplianceCounts object.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetAggregateConfigRuleComplianceSummaryResult withAggregateComplianceCounts(java.util.Collection<AggregateComplianceCount> aggregateComplianceCounts) {
        setAggregateComplianceCounts(aggregateComplianceCounts);
        return this;
    }

    /**
     *

     * The nextToken string returned on a previous page that you use to get the next page of results in a
     * paginated response.
     *

     *
     * @param nextToken
     *        The nextToken string returned on a previous page that you use to get the next page of results
     *        in a paginated response.
     */

    public void setNextToken(String nextToken) {
        this.nextToken = nextToken;
    }

    /**
     *

     * The nextToken string returned on a previous page that you use to get the next page of results in a
     * paginated response.
     *

     *
     * @return The nextToken string returned on a previous page that you use to get the next page of
     *         results in a paginated response.
     */

    public String getNextToken() {
        return this.nextToken;
    }

    /**
     *

     * The nextToken string returned on a previous page that you use to get the next page of results in a
     * paginated response.
     *

     *
     * @param nextToken
     *        The nextToken string returned on a previous page that you use to get the next page of results
     *        in a paginated response.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public GetAggregateConfigRuleComplianceSummaryResult withNextToken(String nextToken) {
        setNextToken(nextToken);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getGroupByKey() != null)
            sb.append("GroupByKey: ").append(getGroupByKey()).append(",");
        if (getAggregateComplianceCounts() != null)
            sb.append("AggregateComplianceCounts: ").append(getAggregateComplianceCounts()).append(",");
        if (getNextToken() != null)
            sb.append("NextToken: ").append(getNextToken());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof GetAggregateConfigRuleComplianceSummaryResult == false)
            return false;
        GetAggregateConfigRuleComplianceSummaryResult other = (GetAggregateConfigRuleComplianceSummaryResult) obj;
        if (other.getGroupByKey() == null ^ this.getGroupByKey() == null)
            return false;
        if (other.getGroupByKey() != null && other.getGroupByKey().equals(this.getGroupByKey()) == false)
            return false;
        if (other.getAggregateComplianceCounts() == null ^ this.getAggregateComplianceCounts() == null)
            return false;
        if (other.getAggregateComplianceCounts() != null && other.getAggregateComplianceCounts().equals(this.getAggregateComplianceCounts()) == false)
            return false;
        if (other.getNextToken() == null ^ this.getNextToken() == null)
            return false;
        if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getGroupByKey() == null) ? 0 : getGroupByKey().hashCode());
        hashCode = prime * hashCode + ((getAggregateComplianceCounts() == null) ? 0 : getAggregateComplianceCounts().hashCode());
        hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
        return hashCode;
    }

    @Override
    public GetAggregateConfigRuleComplianceSummaryResult clone() {
        try {
            return (GetAggregateConfigRuleComplianceSummaryResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

}


text:
package watching

const (
	// NonRecursiveWatchingSupported indicates whether or not the current
	// platform supports native non-recursive watching.
	NonRecursiveWatchingSupported = false
)

// NonRecursiveMRUWatcher represents a non-recursive native watcher that can
// watch multiple paths and evict old watches on an LRU-basis.
type NonRecursiveMRUWatcher struct {
	// Errors is a buffer channel (with a capacity of one) that will populated
	// with the first internal error that occurs in the watcher. If an error
	// occurs, the watcher should be stopped. It will never be populated on this
	// platform.
	Errors chan error
}

// NewNonRecursiveMRUWatcher creates a new non-recursive watcher that will emit
// event paths on the specified events channel. This function is not implemented
// on this platform and will panic if called.
func NewNonRecursiveMRUWatcher(_ chan string, _ int) (*NonRecursiveMRUWatcher, error) {
	panic("non-recursive watching not supported on this platform")
}

// Watch adds a watch path to the watcher. This method is not implemented on
// this platform and will panic if called.
func (w *NonRecursiveMRUWatcher) Watch(_ string) error {
	panic("non-recursive watching not supported on this platform")
}

// Unwatch removes a watch path from the watcher. This method is not implemented
// on this platform and will panic if called.
func (w *NonRecursiveMRUWatcher) Unwatch(_ string) error {
	panic("non-recursive watching not supported on this platform")
}

// Stop terminates all watches. This method is not implemented on this platform
// and will panic if called.
func (w *NonRecursiveMRUWatcher) Stop() {
	panic("non-recursive watching not supported on this platform")
}


text:
import {Component, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {AuthService} from './auth.service';
import {HeaderComponent} from './header';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.css'],
  //  directives: [HeaderComponent],
  providers: [AuthService]
})
export class AppComponent implements OnInit {
  constructor(private _router: Router, private _auth: AuthService) {}

  ngOnInit() {
    this._auth.userLoggedOut$.subscribe(isLoggedOut => this.onUserLoggedOut(isLoggedOut));
  }

  private onUserLoggedOut(isLoggedOut: boolean) {
    if (isLoggedOut) {
      this._router.navigate(['/login']);
    }
  }
}


text:
import bitcore from 'bitcore-lib'
import definer from '../redux/definer'

const { reduce, exportInitialState } = definer(module.exports)

reduce('SET_PASTED', (state, { payload }) => {
  return Object.assign({}, state, { tx: new bitcore.Transaction(payload) })
})

reduce('START_FETCH_TXINFO', (state, { payload }) => {
  const prev = state.txInfo[payload]
  if (prev && typeof prev !== 'string') {
    return state
  }
  return Object.assign({}, state, { txInfo: { [payload]: 'fetching' } })
})

reduce('FETCHED_TX', (state, { payload }) => {
  return Object.assign({}, state, {
    txInfo: Object.assign({}, state.txInfo, {[payload.hash]: payload})
  })
})

reduce('ERROR_FETCH_TX', (state, { payload, error }) => {
  return Object.assign({}, state, {
    txInfo: Object.assign({}, state.txInfo, {[payload]: error})
  })
})

export default exportInitialState({
  txInfo: {}
})


text:
/*-------------------------------------------------------------------------------------------------*\
 |    I N C L U D E   F I L E S
\*-------------------------------------------------------------------------------------------------*/
#include "common.h"
#include "debugprint.h"
#include "osp-sensors.h"

/*-------------------------------------------------------------------------------------------------*\
 |    E X T E R N A L   V A R I A B L E S   &   F U N C T I O N S
\*-------------------------------------------------------------------------------------------------*/
void RxBytesToBuff( PortInfo *pPort, uint8_t byte );
void I2C_IRQHandler(LPC_I2C_T *pI2C);
void SPISlaveIRQHandler(void);

/*-------------------------------------------------------------------------------------------------*\
 |    P R I V A T E   C O N S T A N T S   &   M A C R O S
\*-------------------------------------------------------------------------------------------------*/

/*-------------------------------------------------------------------------------------------------*\
 |    P R I V A T E   T Y P E   D E F I N I T I O N S
\*-------------------------------------------------------------------------------------------------*/

/*-------------------------------------------------------------------------------------------------*\
 |    S T A T I C   V A R I A B L E S   D E F I N I T I O N S
\*-------------------------------------------------------------------------------------------------*/

/*-------------------------------------------------------------------------------------------------*\
 |    F O R W A R D   F U N C T I O N   D E C L A R A T I O N S
\*-------------------------------------------------------------------------------------------------*/

/*-------------------------------------------------------------------------------------------------*\
 |    P U B L I C   V A R I A B L E S   D E F I N I T I O N S
\*-------------------------------------------------------------------------------------------------*/

/*-------------------------------------------------------------------------------------------------*\
 |    P R I V A T E     F U N C T I O N S
\*-------------------------------------------------------------------------------------------------*/

/*-------------------------------------------------------------------------------------------------*\
 |    P U B L I C     F U N C T I O N S
\*-------------------------------------------------------------------------------------------------*/

/******************************************************************************/
/*            Cortex-M4 Processor Exceptions Handlers                         */
/******************************************************************************/

/**
  * @brief  This function handles NMI exception.
  * @param  None
  * @retval None
  */
void NMI_Handler(void)
{
}

/**
  * @brief  This function handles Hard Fault exception.
  * @param  None
  * @retval None
  */
void HardFault_Handler(void)
{
    printf("!!HARD FAULT!!");
    /* Go to infinite loop when Hard Fault exception occurs */
    while (1)
    {
        __IO U32 i;
        //Fast blink the front LED
        LED_On( HARD_FAULT_LED );
        for (i = 0; i < 500000; i++);
        LED_Off( HARD_FAULT_LED );
        for (i = 0; i < 500000; i++);
    }
}

/**
  * @brief  This function handles Memory Manage exception.
  * @param  None
  * @retval None
  */
void MemManage_Handler(void)
{
    /* Go to infinite loop when Memory Manage exception occurs */
    while (1)
    {
    }
}

/**
  * @brief  This function handles Bus Fault exception.
  * @param  None
  * @retval None
  */
void BusFault_Handler(void)
{
    /* Go to infinite loop when Bus Fault exception occurs */
    while (1)
    {
    }
}

/**
  * @brief  This function handles Usage Fault exception.
  * @param  None
  * @retval None
  */
void UsageFault_Handler(void)
{
    /* Go to infinite loop when Usage Fault exception occurs */
    while (1)
    {
    }
}

/**
  * @brief  This function handles Debug Monitor exception.
  * @param  None
  * @retval None
  */
void DebugMon_Handler(void)
{
}

/**
  * @brief  This function handles DMA interrupts.
  * @param  None
  * @retval None
  */
void DMA_IRQHandler( void )
{
#ifdef UART_DMA_ENABLE
    void *pNewBuf;
    uint8_t *pPrintBuf;
    uint32_t intA;
#endif

    /* Error interrupt on channel */
    if ((Chip_DMA_GetIntStatus(LPC_DMA) & DMA_INTSTAT_ACTIVEERRINT) != 0)
    {
#ifdef UART_DMA_ENABLE
        /* This shouldn't happen normally. We can do an abort. */
        Chip_DMA_DisableChannel(LPC_DMA, gDbgUartPort.DMAChannel);
        while ((Chip_DMA_GetBusyChannels(LPC_DMA) & (1 << gDbgUartPort.DMAChannel)) != 0) {}
        Chip_DMA_AbortChannel(LPC_DMA, gDbgUartPort.DMAChannel);
        Chip_DMA_ClearErrorIntChannel(LPC_DMA, gDbgUartPort.DMAChannel);
        Chip_DMA_EnableChannel(LPC_DMA, gDbgUartPort.DMAChannel);
#endif
    }

    /* Check for active interrupt & clear DMA interrupt for the channel */
    if ((Chip_DMA_GetIntStatus(LPC_DMA) & DMA_INTSTAT_ACTIVEINT) != 0)
    {
#ifdef UART_DMA_ENABLE
        intA = LPC_DMA->DMACOMMON[0].INTA;
        if ( (intA & BIT_POSITION(gDbgUartPort.DMAChannel)) != 0 )
        {
            Chip_DMA_ClearActiveIntAChannel(LPC_DMA, gDbgUartPort.DMAChannel);
            DisableDbgUartDMAChannel();
            /*Get the next print buffer */
            pNewBuf = GetNextBuffer(&gDbgUartPort);
            if (pNewBuf != NULL)
            {
                pPrintBuf = M_GetBuffStart(pNewBuf);
                UartDMAConfiguration(&gDbgUartPort, pPrintBuf, M_GetBuffLen(pNewBuf));
                /* Enable DMA Channel Transfer complete interrupt */
                gDbgUartPort.EnableDMAxferCompleteInt();

                /* Enable DMA Channel for TX */
                gDbgUartPort.EnableDMAChannel();
            }
        }
#endif
    }
}

/**
  * @brief  This function handles UART0 interrupts.
  * @param  None
  * @retval None
  */
void UART0_IRQHandler(void)
{
    uint32_t intsrc;
    uint8_t nextByte;

    /* Determine the interrupt source */
    intsrc = Chip_UART_GetIntStatus(DBG_IF_UART);

    // Receive Data Available or Character time-out
    if (intsrc & UART_INTEN_RXRDY)
    {
        /* Read one byte from the receive data register */
        nextByte = DbgUartReadByte();
        RxBytesToBuff( &gDbgUartPort, nextByte );
    }

#ifndef UART_DMA_ENABLE
    // Transmit Holding Empty
    if (intsrc & UART_INTEN_TXRDY)
    {
        if (GetNextByteToTx( &nextByte ))
        {
            /* Write one byte to the transmit data register */
            DbgUartSendByte(nextByte);
        }
        else
        {
            // Disable Transmit interrupt
            DisableDbgUartTxBufferEmptyInterrupt();
        }
    }
#endif

}

/****************************************************************************************************
 * @fn      ACCEL_IRQHandler
 *          ISR Handler for Accelerometer DRDY input. See hw_setup_xpresso_lpc54102.h for mapping
 *
 ***************************************************************************************************/
void ACCEL_IRQHandler(void)
{
    uint64_t currTime = RTC_GetCounter64();
    Chip_PININT_ClearIntStatus(LPC_PININT, ACCEL_PINT_CH);

    SendDataReadyIndication(ACCEL_INPUT_SENSOR, currTime);

    /* The following logic maybe used to decimate Accel data rate if higher BW signal is required */
    //static uint32_t sampleCount = 0;
    //if ((sampleCount++ % 5) == 0) //Decimate 250Hz to 50Hz
    //{
    //    uint32_t timeStamp = RTC_GetCounter();
    //    SendDataReadyIndication( SENSOR_TYPE_ACCELEROMETER, timeStamp );
    //}
}

/****************************************************************************************************
 * @fn      MAG_IRQHandler
 *          ISR Handler for Magnetometer DRDY input. See hw_setup_xpresso_lpc54102.h for mapping
 *
 ***************************************************************************************************/
void MAG_IRQHandler(void)
{
    uint64_t currTime = RTC_GetCounter64();

    Chip_PININT_ClearIntStatus(LPC_PININT, MAG_PINT_CH);

    SendDataReadyIndication(MAG_INPUT_SENSOR, currTime);
}

/****************************************************************************************************
 * @fn      GYRO_IRQHandler
 *          ISR Handler for Gyro DRDY input. See hw_setup_xpresso_lpc54102.h for mapping
 *
 ***************************************************************************************************/
void GYRO_IRQHandler(void)
{
    uint64_t currTime = RTC_GetCounter64();

    Chip_PININT_ClearIntStatus(LPC_PININT, GYRO_PINT_CH);

    SendDataReadyIndication(GYRO_INPUT_SENSOR, currTime);
}

/****************************************************************************************************
 * @fn      I2C0_IRQHandler
 *          ISR Handler for I2C0 interface
 *
 ***************************************************************************************************/
void I2C0_IRQHandler(void)
{
    I2C_IRQHandler(I2C_SENSOR_BUS);
}

/****************************************************************************************************
 * @fn      SPI1_IRQHandler
 *          ISR Handler for SPI1 interface
 *
 ***************************************************************************************************/
void SPI1_IRQHandler(void)
{
    SPISlaveIRQHandler();
}

/****************************************************************************************************
 * @fn      RTC_COUNTER_IRQHandler
 *          ISR Handler for RTC Counter timer
 *
 ***************************************************************************************************/
void RTC_COUNTER_IRQHandler(void)
{
    if (Chip_TIMER_MatchPending( RTC_COUNTER, RTC_COUNTER_MATCH_IDX ))
    {
        Chip_TIMER_ClearMatch( RTC_COUNTER, RTC_COUNTER_MATCH_IDX );
        RTCTimeExtend++; //Increment extension counter
    }
}

/*-------------------------------------------------------------------------------------------------*\
 |    E N D   O F   F I L E
\*-------------------------------------------------------------------------------------------------*/


text:
<template bindable="router">

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#skeleton-navigation-navbar-collapse">
        Toggle Navigation

      </button>

          ${row.title}

</template>


text:
package org.dynmap.modsupport;

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

/**
 * Record representing a texture mapping for one or more blocks
 */
public interface BlockTextureRecord {
    public static final int METAMASK_ALL = -1;

    /**
     * Add block ID to mapping (in case multiple block IDs use same texture mapping)
     * @param blockID - block ID
     */
    @Deprecated
    public void addBlockID(int blockID);
    /**
     * Get block IDs
     * @return configured IDs
     */
    @Deprecated
    public int[] getBlockIDs();
    /**
     * Add block name to mapping (in case multiple block names use same model)
     * @param blockname - block name
     */
    public void addBlockName(String blockname);
    /**
     * Get block names
     * @return configured names
     */
    public String[] getBlockNames();
    /**
     * Set metadata value : default is for all values (data=*).  Setting other values will match only the values that are set
     * @param data - value to match (-1 = all, 0-15 is meta value to match)
     */
    @Deprecated
    public void setMetaValue(int data);
    /**
     * Get matching metadata value mask
     * @return matching metadata mask: bit N is set if given metadata value matches
     */
    @Deprecated
    public int getMetaValueMask();
    /**
     * Set matching block state mapping
     * Any key-value pairs included must match, while any not included are assumed to match unconditionall
     * @param statemap - map of attribute value pairs
     */
    public void setBlockStateMapping(Map<String, String> statemap);
    /**
     * Get all state mappings accumulated for the block model
     */
    public List<Map<String, String>> getBlockStateMappings();
    /**
     * Set transparency mode for block
     * @param mode - transparency mode
     */
    public void setTransparencyMode(TransparencyMode mode);
    /**
     * Get transparency mode for block
     * @return transparency mode
     */
    public TransparencyMode getTransparencyMode();
    /**
     * Set side texture (standard cube block model)
     * @param txtFileID - texture file ID (first texture in file used)
     * @param side - side to apply texture to
     */
    public void setSideTexture(String txtFileID, BlockSide side);
    /**
     * Set side texture (standard cube block model)
     * @param txtFile - texture file (first texture in file used)
     * @param side - side to apply texture to
     */
    public void setSideTexture(TextureFile txtFile, BlockSide side);
    /**
     * Set side texture (standard cube block model) with given texture index
     * @param txtFileID - texture file ID
     * @param txtIndex - texture index
     * @param side - side to apply texture to
     */
    public void setSideTexture(String txtFileID, int txtIndex, BlockSide side);
    /**
     * Set side texture (standard cube block model) with givcen texture index
     * @param txtFile - texture file
     * @param txtIndex - texture index
     * @param side - side to apply texture to
     */
    public void setSideTexture(TextureFile txtFile, int txtIndex, BlockSide side);
    /**
     * Set side texture (standard cube block model) with texture modifier
     * @param txtFileID - texture file ID (first texture in file used)
     * @param modifier - texture modifier
     * @param side - side to apply texture to
     */
    public void setSideTexture(String txtFileID, TextureModifier modifier, BlockSide side);
    /**
     * Set side texture (standard cube block model) with modifier
     * @param txtFile - texture file (first texture in file used)
     * @param modifier - texture modifier
     * @param side - side to apply texture to
     */
    public void setSideTexture(TextureFile txtFile, TextureModifier modifier, BlockSide side);
    /**
     * Set side texture (standard cube block model) with texture modifier and texture index
     * @param txtFileID - texture file ID
     * @param txtIndex - texture index
     * @param modifier - texture modifier
     * @param side - side to apply texture to
     */
    public void setSideTexture(String txtFileID, int txtIndex, TextureModifier modifier, BlockSide side);
    /**
     * Set side texture (standard cube block model) with texture modifier and texture index
     * @param txtFile - texture file
     * @param txtIndex - texture index
     * @param modifier - texture modifier
     * @param side - side to apply texture to
     */
    public void setSideTexture(TextureFile txtFile, int txtIndex, TextureModifier modifier, BlockSide side);
    /**
     * Set patch texture
     * @param txtFileID - texture file ID (first texture in file used)
     * @param patchIndex - patch index to apply texture to
     */
    public void setPatchTexture(String txtFileID, int patchIndex);
    /**
     * Set patch texture
     * @param txtFile - texture file (first texture in file used)
     * @param patchIndex - patch index to apply texture to
     */
    public void setPatchTexture(TextureFile txtFile, int patchIndex);
    /**
     * Set patch texture with given texture index
     * @param txtFileID - texture file ID
     * @param txtIndex - texture index
     * @param patchIndex - patch index to apply texture to
     */
    public void setPatchTexture(String txtFileID, int txtIndex, int patchIndex);
    /**
     * Set patch texture with givcen texture index
     * @param txtFile - texture file
     * @param txtIndex - texture index
     * @param patchIndex - patch index to apply texture to
     */
    public void setPatchTexture(TextureFile txtFile, int txtIndex, int patchIndex);
    /**
     * Set patch texture with texture modifier
     * @param txtFileID - texture file ID (first texture in file used)
     * @param modifier - texture modifier
     * @param patchIndex - patch index to apply texture to
     */
    public void setPatchTexture(String txtFileID, TextureModifier modifier, int patchIndex);
    /**
     * Set patch texture with modifier
     * @param txtFile - texture file (first texture in file used)
     * @param modifier - texture modifier
     * @param patchIndex - patch index to apply texture to
     */
    public void setPatchTexture(TextureFile txtFile, TextureModifier modifier, int patchIndex);
    /**
     * Set patch texture with texture modifier and texture index
     * @param txtFileID - texture file ID
     * @param txtIndex - texture index
     * @param modifier - texture modifier
     * @param patchIndex - patch index to apply texture to
     */
    public void setPatchTexture(String txtFileID, int txtIndex, TextureModifier modifier, int patchIndex);
    /**
     * Set patch texture with texture modifier and texture index
     * @param txtFile - texture file
     * @param txtIndex - texture index
     * @param modifier - texture modifier
     * @param patchIndex - patch index to apply texture to
     */
    public void setPatchTexture(TextureFile txtFile, int txtIndex, TextureModifier modifier, int patchIndex);
    /**
     * Get texture ID for given side
     * @param side - side
     * @return texture ID
     */
    public String getSideTextureID(BlockSide side);
    /**
     * Get texture modifier for given side
     * @param side - side
     * @return texture modifier
     */
    public TextureModifier getSideTextureModifier(BlockSide side);
    /**
     * Get texture index for given side
     * @param side - side
     * @return texture index
     */
    public int getSideTextureIndex(BlockSide side);
    /**
     * Get texture ID for given patch index
     * @param patchIndex - patch index
     * @return texture ID
     */
    public String getPatchTextureID(int patchIndex);
    /**
     * Get texture modifier for given patch index
     * @param patchIndex - patch index
     * @return texture modifier
     */
    public TextureModifier getPatchTextureModifier(int patchIndex);
    /**
     * Get texture index for given patch index
     * @param patchIndex - patch index
     * @return texture index
     */
    public int getPatchTextureIndex(int patchIndex);

    /**
     * Set block color map
     * @param txtFileID - texture file ID
     */
    public void setBlockColorMapTexture(String txtFileID);
    /**
     * Set block color map
     * @param txtFile - texture file
     */
    public void setBlockColorMapTexture(TextureFile txtFile);

}


text:
"""Tests for contrib.seq2seq.python.seq2seq.beam_search_decoder."""
# pylint: disable=unused-import,g-bad-import-order
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# pylint: enable=unused-import

import numpy as np

from tensorflow.contrib.seq2seq.python.ops import attention_wrapper
from tensorflow.contrib.seq2seq.python.ops import beam_search_decoder
from tensorflow.contrib.seq2seq.python.ops import beam_search_ops
from tensorflow.contrib.seq2seq.python.ops import decoder
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors
from tensorflow.python.framework import ops
from tensorflow.python.layers import core as layers_core
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import nn_ops
from tensorflow.python.ops import rnn_cell
from tensorflow.python.ops import variables
from tensorflow.python.platform import test

# pylint: enable=g-import-not-at-top

class TestGatherTree(test.TestCase):
  """Tests the gather_tree function."""

  def test_gather_tree(self):
    # (max_time = 3, batch_size = 2, beam_width = 3)

    # create (batch_size, max_time, beam_width) matrix and transpose it
    predicted_ids = np.array(
        [[[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[2, 3, 4], [5, 6, 7], [8, 9, 10]]],
        dtype=np.int32).transpose([1, 0, 2])
    parent_ids = np.array(
        [[[0, 0, 0], [0, 1, 1], [2, 1, 2]], [[0, 0, 0], [1, 2, 0], [2, 1, 1]]],
        dtype=np.int32).transpose([1, 0, 2])

    # sequence_lengths is shaped (batch_size = 3)
    max_sequence_lengths = [3, 3]

    expected_result = np.array([[[2, 2, 2], [6, 5, 6], [7, 8, 9]],
                                [[2, 4, 4], [7, 6, 6],
                                 [8, 9, 10]]]).transpose([1, 0, 2])

    res = beam_search_ops.gather_tree(
        predicted_ids,
        parent_ids,
        max_sequence_lengths=max_sequence_lengths,
        end_token=11)

    with self.test_session() as sess:
      res_ = sess.run(res)

    self.assertAllEqual(expected_result, res_)

  def _test_gather_tree_from_array(self,
                                   depth_ndims=0,
                                   merged_batch_beam=False):
    array = np.array(
        [[[1, 2, 3], [4, 5, 6], [7, 8, 9], [0, 0, 0]],
         [[2, 3, 4], [5, 6, 7], [8, 9, 10], [11, 12, 0]]]).transpose([1, 0, 2])
    parent_ids = np.array(
        [[[0, 0, 0], [0, 1, 1], [2, 1, 2], [-1, -1, -1]],
         [[0, 0, 0], [1, 1, 0], [2, 0, 1], [0, 1, 0]]]).transpose([1, 0, 2])
    expected_array = np.array(
        [[[2, 2, 2], [6, 5, 6], [7, 8, 9], [0, 0, 0]],
         [[2, 3, 2], [7, 5, 7], [8, 9, 8], [11, 12, 0]]]).transpose([1, 0, 2])
    sequence_length = [[3, 3, 3], [4, 4, 3]]

    array = ops.convert_to_tensor(
        array, dtype=dtypes.float32)
    parent_ids = ops.convert_to_tensor(
        parent_ids, dtype=dtypes.int32)
    expected_array = ops.convert_to_tensor(
        expected_array, dtype=dtypes.float32)

    max_time = array_ops.shape(array)[0]
    batch_size = array_ops.shape(array)[1]
    beam_width = array_ops.shape(array)[2]

    def _tile_in_depth(tensor):
      # Generate higher rank tensors by concatenating tensor and tensor + 1.
      for _ in range(depth_ndims):
        tensor = array_ops.stack([tensor, tensor + 1], -1)
      return tensor

    if merged_batch_beam:
      array = array_ops.reshape(
          array, [max_time, batch_size * beam_width])
      expected_array = array_ops.reshape(
          expected_array, [max_time, batch_size * beam_width])

    if depth_ndims > 0:
      array = _tile_in_depth(array)
      expected_array = _tile_in_depth(expected_array)

    sorted_array = beam_search_decoder.gather_tree_from_array(
        array, parent_ids, sequence_length)

    with self.test_session() as sess:
      sorted_array = sess.run(sorted_array)
      expected_array = sess.run(expected_array)
      self.assertAllEqual(expected_array, sorted_array)

  def test_gather_tree_from_array_scalar(self):
    self._test_gather_tree_from_array()

  def test_gather_tree_from_array_1d(self):
    self._test_gather_tree_from_array(depth_ndims=1)

  def test_gather_tree_from_array_1d_with_merged_batch_beam(self):
    self._test_gather_tree_from_array(depth_ndims=1, merged_batch_beam=True)

  def test_gather_tree_from_array_2d(self):
    self._test_gather_tree_from_array(depth_ndims=2)

  def test_gather_tree_from_array_complex_trajectory(self):
    # Max. time = 7, batch = 1, beam = 5.
    array = np.expand_dims(np.array(
        [[[25, 12, 114, 89, 97]],
         [[9, 91, 64, 11, 162]],
         [[34, 34, 34, 34, 34]],
         [[2, 4, 2, 2, 4]],
         [[2, 3, 6, 2, 2]],
         [[2, 2, 2, 3, 2]],
         [[2, 2, 2, 2, 2]]]), -1)
    parent_ids = np.array(
        [[[0, 0, 0, 0, 0]],
         [[0, 0, 0, 0, 0]],
         [[0, 1, 2, 3, 4]],
         [[0, 0, 1, 2, 1]],
         [[0, 1, 1, 2, 3]],
         [[0, 1, 3, 1, 2]],
         [[0, 1, 2, 3, 4]]])
    expected_array = np.expand_dims(np.array(
        [[[25, 25, 25, 25, 25]],
         [[9, 9, 91, 9, 9]],
         [[34, 34, 34, 34, 34]],
         [[2, 4, 2, 4, 4]],
         [[2, 3, 6, 3, 6]],
         [[2, 2, 2, 3, 2]],
         [[2, 2, 2, 2, 2]]]), -1)
    sequence_length = [[4, 6, 4, 7, 6]]

    array = ops.convert_to_tensor(
        array, dtype=dtypes.float32)
    parent_ids = ops.convert_to_tensor(
        parent_ids, dtype=dtypes.int32)
    expected_array = ops.convert_to_tensor(
        expected_array, dtype=dtypes.float32)

    sorted_array = beam_search_decoder.gather_tree_from_array(
        array, parent_ids, sequence_length)

    with self.test_session() as sess:
      sorted_array, expected_array = sess.run([sorted_array, expected_array])
      self.assertAllEqual(expected_array, sorted_array)

class TestArrayShapeChecks(test.TestCase):

  def _test_array_shape_dynamic_checks(self, static_shape, dynamic_shape,
                                       batch_size, beam_width, is_valid=True):
    t = array_ops.placeholder_with_default(
        np.random.randn(*static_shape).astype(np.float32),
        shape=dynamic_shape)

    batch_size = array_ops.constant(batch_size)
    check_op = beam_search_decoder._check_batch_beam(t, batch_size, beam_width)  # pylint: disable=protected-access

    with self.test_session() as sess:
      if is_valid:
        sess.run(check_op)
      else:
        with self.assertRaises(errors.InvalidArgumentError):
          sess.run(check_op)

  def test_array_shape_dynamic_checks(self):
    self._test_array_shape_dynamic_checks(
        (8, 4, 5, 10), (None, None, 5, 10), 4, 5, is_valid=True)
    self._test_array_shape_dynamic_checks(
        (8, 20, 10), (None, None, 10), 4, 5, is_valid=True)
    self._test_array_shape_dynamic_checks(
        (8, 21, 10), (None, None, 10), 4, 5, is_valid=False)
    self._test_array_shape_dynamic_checks(
        (8, 4, 6, 10), (None, None, None, 10), 4, 5, is_valid=False)
    self._test_array_shape_dynamic_checks(
        (8, 4), (None, None), 4, 5, is_valid=False)

class TestEosMasking(test.TestCase):
  """Tests EOS masking used in beam search."""

  def test_eos_masking(self):
    probs = constant_op.constant([
        [[-.2, -.2, -.2, -.2, -.2], [-.3, -.3, -.3, 3, 0], [5, 6, 0, 0, 0]],
        [[-.2, -.2, -.2, -.2, 0], [-.3, -.3, -.1, 3, 0], [5, 6, 3, 0, 0]],
    ])

    eos_token = 0
    previously_finished = np.array([[0, 1, 0], [0, 1, 1]], dtype=bool)
    masked = beam_search_decoder._mask_probs(probs, eos_token,
                                             previously_finished)

    with self.test_session() as sess:
      probs = sess.run(probs)
      masked = sess.run(masked)

      self.assertAllEqual(probs[0][0], masked[0][0])
      self.assertAllEqual(probs[0][2], masked[0][2])
      self.assertAllEqual(probs[1][0], masked[1][0])

      self.assertEqual(masked[0][1][0], 0)
      self.assertEqual(masked[1][1][0], 0)
      self.assertEqual(masked[1][2][0], 0)

      for i in range(1, 5):
        self.assertAllClose(masked[0][1][i], np.finfo('float32').min)
        self.assertAllClose(masked[1][1][i], np.finfo('float32').min)
        self.assertAllClose(masked[1][2][i], np.finfo('float32').min)

class TestBeamStep(test.TestCase):
  """Tests a single step of beam search."""

  def setUp(self):
    super(TestBeamStep, self).setUp()
    self.batch_size = 2
    self.beam_width = 3
    self.vocab_size = 5
    self.end_token = 0
    self.length_penalty_weight = 0.6

  def test_step(self):
    dummy_cell_state = array_ops.zeros([self.batch_size, self.beam_width])
    beam_state = beam_search_decoder.BeamSearchDecoderState(
        cell_state=dummy_cell_state,
        log_probs=nn_ops.log_softmax(
            array_ops.ones([self.batch_size, self.beam_width])),
        lengths=constant_op.constant(
            2, shape=[self.batch_size, self.beam_width], dtype=dtypes.int64),
        finished=array_ops.zeros(
            [self.batch_size, self.beam_width], dtype=dtypes.bool))

    logits_ = np.full([self.batch_size, self.beam_width, self.vocab_size],
                      0.0001)
    logits_[0, 0, 2] = 1.9
    logits_[0, 0, 3] = 2.1
    logits_[0, 1, 3] = 3.1
    logits_[0, 1, 4] = 0.9
    logits_[1, 0, 1] = 0.5
    logits_[1, 1, 2] = 2.7
    logits_[1, 2, 2] = 10.0
    logits_[1, 2, 3] = 0.2
    logits = ops.convert_to_tensor(logits_, dtype=dtypes.float32)
    log_probs = nn_ops.log_softmax(logits)

    outputs, next_beam_state = beam_search_decoder._beam_search_step(
        time=2,
        logits=logits,
        next_cell_state=dummy_cell_state,
        beam_state=beam_state,
        batch_size=ops.convert_to_tensor(self.batch_size),
        beam_width=self.beam_width,
        end_token=self.end_token,
        length_penalty_weight=self.length_penalty_weight)

    with self.test_session() as sess:
      outputs_, next_state_, state_, log_probs_ = sess.run(
          [outputs, next_beam_state, beam_state, log_probs])

    self.assertAllEqual(outputs_.predicted_ids, [[3, 3, 2], [2, 2, 1]])
    self.assertAllEqual(outputs_.parent_ids, [[1, 0, 0], [2, 1, 0]])
    self.assertAllEqual(next_state_.lengths, [[3, 3, 3], [3, 3, 3]])
    self.assertAllEqual(next_state_.finished,
                        [[False, False, False], [False, False, False]])

    expected_log_probs = []
    expected_log_probs.append(state_.log_probs[0][[1, 0, 0]])
    expected_log_probs.append(state_.log_probs[1][[2, 1, 0]])  # 0 --> 1
    expected_log_probs[0][0] += log_probs_[0, 1, 3]
    expected_log_probs[0][1] += log_probs_[0, 0, 3]
    expected_log_probs[0][2] += log_probs_[0, 0, 2]
    expected_log_probs[1][0] += log_probs_[1, 2, 2]
    expected_log_probs[1][1] += log_probs_[1, 1, 2]
    expected_log_probs[1][2] += log_probs_[1, 0, 1]
    self.assertAllEqual(next_state_.log_probs, expected_log_probs)

  def test_step_with_eos(self):
    dummy_cell_state = array_ops.zeros([self.batch_size, self.beam_width])
    beam_state = beam_search_decoder.BeamSearchDecoderState(
        cell_state=dummy_cell_state,
        log_probs=nn_ops.log_softmax(
            array_ops.ones([self.batch_size, self.beam_width])),
        lengths=ops.convert_to_tensor(
            [[2, 1, 2], [2, 2, 1]], dtype=dtypes.int64),
        finished=ops.convert_to_tensor(
            [[False, True, False], [False, False, True]], dtype=dtypes.bool))

    logits_ = np.full([self.batch_size, self.beam_width, self.vocab_size],
                      0.0001)
    logits_[0, 0, 2] = 1.9
    logits_[0, 0, 3] = 2.1
    logits_[0, 1, 3] = 3.1
    logits_[0, 1, 4] = 0.9
    logits_[1, 0, 1] = 0.5
    logits_[1, 1, 2] = 5.7  # why does this not work when it's 2.7?
    logits_[1, 2, 2] = 1.0
    logits_[1, 2, 3] = 0.2
    logits = ops.convert_to_tensor(logits_, dtype=dtypes.float32)
    log_probs = nn_ops.log_softmax(logits)

    outputs, next_beam_state = beam_search_decoder._beam_search_step(
        time=2,
        logits=logits,
        next_cell_state=dummy_cell_state,
        beam_state=beam_state,
        batch_size=ops.convert_to_tensor(self.batch_size),
        beam_width=self.beam_width,
        end_token=self.end_token,
        length_penalty_weight=self.length_penalty_weight)

    with self.test_session() as sess:
      outputs_, next_state_, state_, log_probs_ = sess.run(
          [outputs, next_beam_state, beam_state, log_probs])

    self.assertAllEqual(outputs_.parent_ids, [[1, 0, 0], [1, 2, 0]])
    self.assertAllEqual(outputs_.predicted_ids, [[0, 3, 2], [2, 0, 1]])
    self.assertAllEqual(next_state_.lengths, [[1, 3, 3], [3, 1, 3]])
    self.assertAllEqual(next_state_.finished,
                        [[True, False, False], [False, True, False]])

    expected_log_probs = []
    expected_log_probs.append(state_.log_probs[0][[1, 0, 0]])
    expected_log_probs.append(state_.log_probs[1][[1, 2, 0]])
    expected_log_probs[0][1] += log_probs_[0, 0, 3]
    expected_log_probs[0][2] += log_probs_[0, 0, 2]
    expected_log_probs[1][0] += log_probs_[1, 1, 2]
    expected_log_probs[1][2] += log_probs_[1, 0, 1]
    self.assertAllEqual(next_state_.log_probs, expected_log_probs)

class TestLargeBeamStep(test.TestCase):
  """Tests large beam step.

  Tests a single step of beam search in such case that beam size is larger than
  vocabulary size.
  """

  def setUp(self):
    super(TestLargeBeamStep, self).setUp()
    self.batch_size = 2
    self.beam_width = 8
    self.vocab_size = 5
    self.end_token = 0
    self.length_penalty_weight = 0.6

  def test_step(self):

    def get_probs():
      """this simulates the initialize method in BeamSearchDecoder."""
      log_prob_mask = array_ops.one_hot(
          array_ops.zeros([self.batch_size], dtype=dtypes.int32),
          depth=self.beam_width,
          on_value=True,
          off_value=False,
          dtype=dtypes.bool)

      log_prob_zeros = array_ops.zeros(
          [self.batch_size, self.beam_width], dtype=dtypes.float32)
      log_prob_neg_inf = array_ops.ones(
          [self.batch_size, self.beam_width], dtype=dtypes.float32) * -np.Inf

      log_probs = array_ops.where(log_prob_mask, log_prob_zeros,
                                  log_prob_neg_inf)
      return log_probs

    log_probs = get_probs()
    dummy_cell_state = array_ops.zeros([self.batch_size, self.beam_width])

    # pylint: disable=invalid-name
    _finished = array_ops.one_hot(
        array_ops.zeros([self.batch_size], dtype=dtypes.int32),
        depth=self.beam_width,
        on_value=False,
        off_value=True,
        dtype=dtypes.bool)
    _lengths = np.zeros([self.batch_size, self.beam_width], dtype=np.int64)
    _lengths[:, 0] = 2
    _lengths = constant_op.constant(_lengths, dtype=dtypes.int64)

    beam_state = beam_search_decoder.BeamSearchDecoderState(
        cell_state=dummy_cell_state,
        log_probs=log_probs,
        lengths=_lengths,
        finished=_finished)

    logits_ = np.full([self.batch_size, self.beam_width, self.vocab_size],
                      0.0001)
    logits_[0, 0, 2] = 1.9
    logits_[0, 0, 3] = 2.1
    logits_[0, 1, 3] = 3.1
    logits_[0, 1, 4] = 0.9
    logits_[1, 0, 1] = 0.5
    logits_[1, 1, 2] = 2.7
    logits_[1, 2, 2] = 10.0
    logits_[1, 2, 3] = 0.2
    logits = constant_op.constant(logits_, dtype=dtypes.float32)
    log_probs = nn_ops.log_softmax(logits)

    outputs, next_beam_state = beam_search_decoder._beam_search_step(
        time=2,
        logits=logits,
        next_cell_state=dummy_cell_state,
        beam_state=beam_state,
        batch_size=ops.convert_to_tensor(self.batch_size),
        beam_width=self.beam_width,
        end_token=self.end_token,
        length_penalty_weight=self.length_penalty_weight)

    with self.test_session() as sess:
      outputs_, next_state_, _, _ = sess.run(
          [outputs, next_beam_state, beam_state, log_probs])

    self.assertEqual(outputs_.predicted_ids[0, 0], 3)
    self.assertEqual(outputs_.predicted_ids[0, 1], 2)
    self.assertEqual(outputs_.predicted_ids[1, 0], 1)
    neg_inf = -np.Inf
    self.assertAllEqual(
        next_state_.log_probs[:, -3:],
        [[neg_inf, neg_inf, neg_inf], [neg_inf, neg_inf, neg_inf]])
    self.assertEqual((next_state_.log_probs[:, :-3] > neg_inf).all(), True)
    self.assertEqual((next_state_.lengths[:, :-3] > 0).all(), True)
    self.assertAllEqual(next_state_.lengths[:, -3:], [[0, 0, 0], [0, 0, 0]])

class BeamSearchDecoderTest(test.TestCase):

  def _testDynamicDecodeRNN(self, time_major, has_attention,
                            with_alignment_history=False):
    encoder_sequence_length = np.array([3, 2, 3, 1, 1])
    decoder_sequence_length = np.array([2, 0, 1, 2, 3])
    batch_size = 5
    decoder_max_time = 4
    input_depth = 7
    cell_depth = 9
    attention_depth = 6
    vocab_size = 20
    end_token = vocab_size - 1
    start_token = 0
    embedding_dim = 50
    max_out = max(decoder_sequence_length)
    output_layer = layers_core.Dense(vocab_size, use_bias=True, activation=None)
    beam_width = 3

    with self.test_session() as sess:
      batch_size_tensor = constant_op.constant(batch_size)
      embedding = np.random.randn(vocab_size, embedding_dim).astype(np.float32)
      cell = rnn_cell.LSTMCell(cell_depth)
      initial_state = cell.zero_state(batch_size, dtypes.float32)
      if has_attention:
        inputs = array_ops.placeholder_with_default(
            np.random.randn(batch_size, decoder_max_time, input_depth).astype(
                np.float32),
            shape=(None, None, input_depth))
        tiled_inputs = beam_search_decoder.tile_batch(
            inputs, multiplier=beam_width)
        tiled_sequence_length = beam_search_decoder.tile_batch(
            encoder_sequence_length, multiplier=beam_width)
        attention_mechanism = attention_wrapper.BahdanauAttention(
            num_units=attention_depth,
            memory=tiled_inputs,
            memory_sequence_length=tiled_sequence_length)
        initial_state = beam_search_decoder.tile_batch(
            initial_state, multiplier=beam_width)
        cell = attention_wrapper.AttentionWrapper(
            cell=cell,
            attention_mechanism=attention_mechanism,
            attention_layer_size=attention_depth,
            alignment_history=with_alignment_history)
      cell_state = cell.zero_state(
          dtype=dtypes.float32, batch_size=batch_size_tensor * beam_width)
      if has_attention:
        cell_state = cell_state.clone(cell_state=initial_state)
      bsd = beam_search_decoder.BeamSearchDecoder(
          cell=cell,
          embedding=embedding,
          start_tokens=array_ops.fill([batch_size_tensor], start_token),
          end_token=end_token,
          initial_state=cell_state,
          beam_width=beam_width,
          output_layer=output_layer,
          length_penalty_weight=0.0)

      final_outputs, final_state, final_sequence_lengths = (
          decoder.dynamic_decode(
              bsd, output_time_major=time_major, maximum_iterations=max_out))

      def _t(shape):
        if time_major:
          return (shape[1], shape[0]) + shape[2:]
        return shape

      self.assertTrue(
          isinstance(final_outputs,
                     beam_search_decoder.FinalBeamSearchDecoderOutput))
      self.assertTrue(
          isinstance(final_state, beam_search_decoder.BeamSearchDecoderState))

      beam_search_decoder_output = final_outputs.beam_search_decoder_output
      self.assertEqual(
          _t((batch_size, None, beam_width)),
          tuple(beam_search_decoder_output.scores.get_shape().as_list()))
      self.assertEqual(
          _t((batch_size, None, beam_width)),
          tuple(final_outputs.predicted_ids.get_shape().as_list()))

      sess.run(variables.global_variables_initializer())
      sess_results = sess.run({
          'final_outputs': final_outputs,
          'final_state': final_state,
          'final_sequence_lengths': final_sequence_lengths
      })

      max_sequence_length = np.max(sess_results['final_sequence_lengths'])

      # A smoke test
      self.assertEqual(
          _t((batch_size, max_sequence_length, beam_width)),
          sess_results['final_outputs'].beam_search_decoder_output.scores.shape)
      self.assertEqual(
          _t((batch_size, max_sequence_length, beam_width)), sess_results[
              'final_outputs'].beam_search_decoder_output.predicted_ids.shape)

  def testDynamicDecodeRNNBatchMajorNoAttention(self):
    self._testDynamicDecodeRNN(time_major=False, has_attention=False)

  def testDynamicDecodeRNNBatchMajorYesAttention(self):
    self._testDynamicDecodeRNN(time_major=False, has_attention=True)

  def testDynamicDecodeRNNBatchMajorYesAttentionWithAlignmentHistory(self):
    self._testDynamicDecodeRNN(
        time_major=False,
        has_attention=True,
        with_alignment_history=True)

if __name__ == '__main__':
  test.main()


text:
/* jshint node: true */
'use strict';

module.exports = {
  name: 'ember-previewer'
};


text:
/**
 * author:yodfz create:2017-5-27
 * api路由
 * @type {{}}
 */
var createMessage = require('../core/createMessage');
var $config = require('../config');
var controller_api_article = require('../controller/api/article');
var controller_api_upload = require('../controller/api/upload');
var controller_api_photo = require('../controller/api/photo');
var controller_api_system = require('../controller/api/system');
var model = require('../model');
var router = require('koa-router')();
const apiPre = $config.apiPre;
router.get(apiPre + 'article', async (ctx)=> {
    let data = await controller_api_article.list(ctx.request.query.pageIndex || 1, ctx.request.query.key);
    ctx.body = createMessage(data.rows, {total: data.total});
});
router.post(apiPre + 'article/save', async (ctx)=> {
    if (ctx.session.isLogin || true) {
        let data = ctx.request.body;
        let $data = await controller_api_article.save(data);
        if ($data.errorNo == 1) {
            ctx.body = createMessage({}, {}, 2, $data.info);
        } else {
            ctx.body = createMessage($data, {});
        }
    } else {
        ctx.body = '';
        ctx.status = 401;
    }

});
router.post(apiPre + 'article/delete', async (ctx)=> {
    if (!ctx.session.isLogin) {
        ctx.body = '';
        ctx.status = 401;
        return;
    }
    let data = ctx.request.body.idx;
    if (data) {
        let $data = await controller_api_article.delete(data);
        ctx.body = createMessage($data, {});
    } else {
        ctx.body = createMessage({}, {}, 3, '参数idx为空');
    }
});

router.get(apiPre + 'photo', async (ctx)=> {
    let data = await controller_api_photo.list(ctx.request.query.pageIndex || 1, ctx.request.query.key);
    ctx.body = createMessage(data.rows, {total: data.total});
});
router.post(apiPre + 'photo/save', async (ctx)=> {
    if (!ctx.session.isLogin) {
        ctx.body = '';
        ctx.status = 401;
        return;
    }
    let data = ctx.request.body;
    if (!data.url) {
        ctx.body = createMessage({}, {}, 1, '图片不得为空');
        return;
    }
    let $data = await controller_api_photo.save(data);
    if ($data.errorNo == 1) {
        ctx.body = createMessage({}, {}, 2, $data.info);
    } else {
        ctx.body = createMessage($data, {});
    }
});
router.post(apiPre + 'photo/delete', async (ctx)=> {
    if (!ctx.session.isLogin) {
        ctx.body = '';
        ctx.status = 401;
        return;
    }
    let data = ctx.request.body.idx;
    if (data) {
        let $data = await controller_api_photo.delete(data);
        ctx.body = createMessage($data, {});
    } else {
        ctx.body = createMessage({}, {}, 3, '参数idx为空');
    }
});

router.post(apiPre + 'system/updatepassword', async (ctx)=> {
    if (!ctx.session.isLogin) {
        ctx.body = '';
        ctx.status = 401;
        return;
    }
    let data = ctx.request.body;
    if (data.oldPassword && data.newPassword1 && data.newPassword2) {
        if (data.newPassword1 != data.newPassword2) {
            ctx.body = createMessage({}, {}, 1, '两次输入的新密码不一致!');
        } else {
            let user = await model.user.findOne({where: {user: ctx.session.loginUser}});
            if (user && user.pwd === data.oldPassword) {
                $data = await model.user.update({pwd: data.newPassword2}, {
                    where: {idx: user.idx}
                });
                ctx.body = createMessage({}, {}, 0, '修改密码成功');
            } else {
                ctx.body = createMessage({}, {}, 2, '修改密码失败');
            }
        }
    } else {
        ctx.body = createMessage({}, {}, 1, '修改密码失败');
    }
});

router.post(apiPre + 'system/bakDb', async (ctx)=> {
    if (!ctx.session.isLogin) {
        ctx.body = '';
        ctx.status = 401;
        return;
    }
    let $data = await controller_api_system.bakDb();
    ctx.body = createMessage({}, {}, ($data == 'SUCCESS' ? 3 : 0), $data);
});

router.get(apiPre + 'system/dbInfo', async (ctx)=> {
    ctx.body = createMessage(controller_api_system.getDbInfo(), {});
});

router.post(apiPre + 'upload', async (ctx)=> {
    if (!ctx.session.isLogin) {
        ctx.body = '';
        ctx.status = 401;
        return;
    }
    var data = controller_api_upload.index(ctx);
    if (data) {
        ctx.body = createMessage(data.url);
    } else {
        ctx.body = createMessage({}, {}, 1, '图片上传失败');
    }
});

router.post(apiPre + 'login', async (ctx) => {
    var requestData = ctx.request.body.fields;
    if (requestData.username && requestData.password) {
        let user = await model.user.findOne({where: {user: requestData.username}});
        if (user && user.pwd === requestData.password) {
            ctx.session.isLogin = true;
            ctx.session.loginUser = user.user;
            ctx.body = createMessage({
                redirectUrl: '/manage'
            });
            return;
        }
    }
    ctx.body = createMessage({}, {}, '911', '账户名或密码错误');
});

module.exports = router;


text:
import { defineConfig } from 'tsup';

export default defineConfig({
  entry: ['./src'],
  outDir: './lib',
  splitting: true,
  sourcemap: true,
  clean: true,
  dts: true,
  platform: 'node',
  skipNodeModulesBundle: true,
  bundle: false,
  format: ['esm', 'cjs'],
  minify: true,
});


text:
namespace extensions {

namespace {

const char kAuthenticationResultFailed[] =
    "Failed to set AuthenticationResult.";
const char kMalformedFilterDescription[] = "Malformed filter description.";
const char kMalformedFilterDescriptionWithSSID[] =
    "Malformed filter description. Failed to register network with SSID "
    "(hex): *";
const char kUnsupportedNetworkType[] = "Unsupported network type.";

}  // namespace

NetworkingConfigSetNetworkFilterFunction::
    NetworkingConfigSetNetworkFilterFunction() {
}

ExtensionFunction::ResponseAction
NetworkingConfigSetNetworkFilterFunction::Run() {
  parameters_ =
      api::networking_config::SetNetworkFilter::Params::Create(*args_);
  EXTENSION_FUNCTION_VALIDATE(parameters_.get());

  NetworkingConfigService* service =
      NetworkingConfigServiceFactory::GetForBrowserContext(browser_context());
  DCHECK(service);

  // Remove previously registered networks.
  service->UnregisterExtension(extension_id());

  for (linked_ptr<api::networking_config::NetworkInfo>& ni :
       parameters_->networks) {
    // |Type| field must be set to |WiFi|
    if (ni->type != api::networking_config::NETWORK_TYPE_WIFI)
      return RespondNow(Error(kUnsupportedNetworkType));

    // Either |ssid| or |hex_ssid| must be set.
    if (!ni->ssid.get() && !ni->hex_ssid.get())
      return RespondNow(Error(kMalformedFilterDescription));

    std::string hex_ssid;
    if (ni->ssid.get()) {
      auto ssid_field = ni->ssid.get();
      hex_ssid = base::HexEncode(ssid_field->c_str(), ssid_field->size());
    }
    if (ni->hex_ssid.get())
      hex_ssid = *ni->hex_ssid.get();

    if (!service->RegisterHexSsid(hex_ssid, extension_id()))
      return RespondNow(Error(kMalformedFilterDescriptionWithSSID, hex_ssid));
  }

  return RespondNow(NoArguments());
}

NetworkingConfigSetNetworkFilterFunction::
    ~NetworkingConfigSetNetworkFilterFunction() {
}

NetworkingConfigFinishAuthenticationFunction::
    NetworkingConfigFinishAuthenticationFunction() {
}

ExtensionFunction::ResponseAction
NetworkingConfigFinishAuthenticationFunction::Run() {
  parameters_ =
      api::networking_config::FinishAuthentication::Params::Create(*args_);
  EXTENSION_FUNCTION_VALIDATE(parameters_.get());

  NetworkingConfigService* service =
      NetworkingConfigServiceFactory::GetForBrowserContext(browser_context());
  DCHECK(service);

  const NetworkingConfigService::AuthenticationResult& last_result =
      service->GetAuthenticationResult();
  if (last_result.authentication_state != NetworkingConfigService::NOTRY ||
      last_result.guid != parameters_->guid) {
    return RespondNow(Error(kAuthenticationResultFailed));
  }

  // Populate NetworkingCaptivePortalAPI::AuthenticationResult.
  NetworkingConfigService::AuthenticationResult authentication_result = {
      extension_id(), parameters_->guid, NetworkingConfigService::FAILED,
  };
  switch (parameters_->result) {
    case api::networking_config::AUTHENTICATION_RESULT_NONE:
      NOTREACHED();
      break;
    case api::networking_config::AUTHENTICATION_RESULT_UNHANDLED:
      authentication_result.authentication_state =
          NetworkingConfigService::FAILED;
      break;
    case api::networking_config::AUTHENTICATION_RESULT_REJECTED:
      authentication_result.authentication_state =
          NetworkingConfigService::REJECTED;
      break;
    case api::networking_config::AUTHENTICATION_RESULT_FAILED:
      authentication_result.authentication_state =
          NetworkingConfigService::FAILED;
      break;
    case api::networking_config::AUTHENTICATION_RESULT_SUCCEEDED:
      authentication_result.authentication_state =
          NetworkingConfigService::SUCCESS;
      break;
  }
  service->SetAuthenticationResult(authentication_result);
  return RespondNow(NoArguments());
}

NetworkingConfigFinishAuthenticationFunction::
    ~NetworkingConfigFinishAuthenticationFunction() {
}

}  // namespace extensions


text:
package som.interpreter.nodes;

import com.oracle.truffle.api.dsl.NodeChild;
import com.oracle.truffle.api.dsl.Specialization;
import com.oracle.truffle.api.frame.FrameDescriptor;
import com.oracle.truffle.api.frame.FrameSlot;
import com.oracle.truffle.api.frame.FrameSlotKind;
import com.oracle.truffle.api.frame.FrameSlotTypeException;
import com.oracle.truffle.api.frame.VirtualFrame;
import com.oracle.truffle.api.instrumentation.Tag;

import bd.inlining.ScopeAdaptationVisitor;
import bd.tools.nodes.Invocation;
import som.compiler.Variable.Local;
import som.interpreter.nodes.nary.ExprWithTagsNode;
import som.vm.constants.Nil;
import som.vmobjects.SSymbol;
import tools.debugger.Tags.LocalVariableTag;
import tools.dym.Tags.LocalVarRead;
import tools.dym.Tags.LocalVarWrite;

public abstract class LocalVariableNode extends ExprWithTagsNode
    implements Invocation<SSymbol> {
  protected final FrameSlot       slot;
  protected final FrameDescriptor descriptor;
  protected final Local           var;

  // TODO: We currently assume that there is a 1:1 mapping between lexical contexts
  // and frame descriptors, which is apparently not strictly true anymore in Truffle 1.0.0.
  // Generally, we also need to revise everything in this area and address issue #240.
  private LocalVariableNode(final Local var) {
    this.slot = var.getSlot();
    this.descriptor = var.getFrameDescriptor();
    this.var = var;
  }

  public final Local getLocal() {
    return var;
  }

  @Override
  public final SSymbol getInvocationIdentifier() {
    return var.name;
  }

  @Override
  public boolean hasTag(final Class<? extends Tag> tag) {
    if (tag == LocalVariableTag.class) {
      return true;
    } else {
      return super.hasTag(tag);
    }
  }

  public abstract static class LocalVariableReadNode extends LocalVariableNode {

    public LocalVariableReadNode(final Local variable) {
      super(variable);
    }

    public LocalVariableReadNode(final LocalVariableReadNode node) {
      this(node.var);
    }

    @Specialization(guards = "isUninitialized(frame)")
    public final Object doNil(final VirtualFrame frame) {
      return Nil.nilObject;
    }

    protected boolean isBoolean(final VirtualFrame frame) {
      return frame.isBoolean(slot);
    }

    protected boolean isLong(final VirtualFrame frame) {
      return frame.isLong(slot);
    }

    protected boolean isDouble(final VirtualFrame frame) {
      return frame.isDouble(slot);
    }

    protected boolean isObject(final VirtualFrame frame) {
      return frame.isObject(slot);
    }

    @Specialization(guards = {"isBoolean(frame)"}, rewriteOn = {FrameSlotTypeException.class})
    public final boolean doBoolean(final VirtualFrame frame) throws FrameSlotTypeException {
      return frame.getBoolean(slot);
    }

    @Specialization(guards = {"isLong(frame)"}, rewriteOn = {FrameSlotTypeException.class})
    public final long doLong(final VirtualFrame frame) throws FrameSlotTypeException {
      return frame.getLong(slot);
    }

    @Specialization(guards = {"isDouble(frame)"}, rewriteOn = {FrameSlotTypeException.class})
    public final double doDouble(final VirtualFrame frame) throws FrameSlotTypeException {
      return frame.getDouble(slot);
    }

    @Specialization(guards = {"isObject(frame)"},
        replaces = {"doBoolean", "doLong", "doDouble"},
        rewriteOn = {FrameSlotTypeException.class})
    public final Object doObject(final VirtualFrame frame) throws FrameSlotTypeException {
      return frame.getObject(slot);
    }

    protected final boolean isUninitialized(final VirtualFrame frame) {
      return descriptor.getFrameSlotKind(slot) == FrameSlotKind.Illegal;
    }

    @Override
    public boolean hasTag(final Class<? extends Tag> tag) {
      if (tag == LocalVarRead.class) {
        return true;
      } else {
        return super.hasTag(tag);
      }
    }

    @Override
    public String toString() {
      return this.getClass().getSimpleName() + "[" + var.name + "]";
    }

    @Override
    public void replaceAfterScopeChange(final ScopeAdaptationVisitor inliner) {
      inliner.updateRead(var, this, 0);
    }
  }

  @NodeChild(value = "exp", type = ExpressionNode.class)
  public abstract static class LocalVariableWriteNode extends LocalVariableNode {

    public LocalVariableWriteNode(final Local variable) {
      super(variable);
    }

    public LocalVariableWriteNode(final LocalVariableWriteNode node) {
      super(node.var);
    }

    public abstract ExpressionNode getExp();

    @Specialization(guards = "isBoolKind(expValue)")
    public final boolean writeBoolean(final VirtualFrame frame, final boolean expValue) {
      frame.setBoolean(slot, expValue);
      return expValue;
    }

    @Specialization(guards = "isLongKind(expValue)")
    public final long writeLong(final VirtualFrame frame, final long expValue) {
      frame.setLong(slot, expValue);
      return expValue;
    }

    @Specialization(guards = "isDoubleKind(expValue)")
    public final double writeDouble(final VirtualFrame frame, final double expValue) {
      frame.setDouble(slot, expValue);
      return expValue;
    }

    @Specialization(replaces = {"writeBoolean", "writeLong", "writeDouble"})
    public final Object writeGeneric(final VirtualFrame frame, final Object expValue) {
      descriptor.setFrameSlotKind(slot, FrameSlotKind.Object);
      frame.setObject(slot, expValue);
      return expValue;
    }

    // uses expValue to make sure guard is not converted to assertion
    protected final boolean isBoolKind(final boolean expValue) {
      FrameSlotKind kind = descriptor.getFrameSlotKind(slot);
      if (kind == FrameSlotKind.Boolean) {
        return true;
      }
      if (kind == FrameSlotKind.Illegal) {
        descriptor.setFrameSlotKind(slot, FrameSlotKind.Boolean);
        return true;
      }
      return false;
    }

    // uses expValue to make sure guard is not converted to assertion
    protected final boolean isLongKind(final long expValue) {
      FrameSlotKind kind = descriptor.getFrameSlotKind(slot);
      if (kind == FrameSlotKind.Long) {
        return true;
      }
      if (kind == FrameSlotKind.Illegal) {
        descriptor.setFrameSlotKind(slot, FrameSlotKind.Long);
        return true;
      }
      return false;
    }

    // uses expValue to make sure guard is not converted to assertion
    protected final boolean isDoubleKind(final double expValue) {
      FrameSlotKind kind = descriptor.getFrameSlotKind(slot);
      if (kind == FrameSlotKind.Double) {
        return true;
      }
      if (kind == FrameSlotKind.Illegal) {
        descriptor.setFrameSlotKind(slot, FrameSlotKind.Double);
        return true;
      }
      return false;
    }

    @Override
    public boolean hasTag(final Class<? extends Tag> tag) {
      if (tag == LocalVarWrite.class) {
        return true;
      } else {
        return super.hasTag(tag);
      }
    }

    @Override
    public String toString() {
      return this.getClass().getSimpleName() + "[" + var.name + "]";
    }

    @Override
    public void replaceAfterScopeChange(final ScopeAdaptationVisitor inliner) {
      inliner.updateWrite(var, this, getExp(), 0);
    }
  }
}


text:
---
uid: SolidEdgeConstants.SheetSectionTypeConstants
summary: Sheet Section Type Constants
remarks:
---


text:
package io.github.siddharthgoel88.useragents.impl;

import io.github.siddharthgoel88.useragents.UserAgent;

/**
 * UserAgents from latest to oldest for Btbot
 */
public class Btbot extends UserAgent {

	public String[] getAllUserAgentStrings() {
		String [] userAgentStrings = {
			"btbot/0.4 (+http://www.btbot.com/btbot.html)"
		};
		return userAgentStrings;
	}
}


text:
import React from 'react'

const RestartMessage = () => (

    Data cannot be loaded completely, please try again later or  location.reload(true)}>refresh

)

export default RestartMessage


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

public class PatternController : MonoBehaviour {
    public Transform currentPatternWidthRef;
}


text:
let canvas = SVG('#canvas')

// Make the green rectangle
canvas.rect(200, 400).move(200, 400)
  .attr('opacity', 0.3)
  .addClass('green')

// Make the pink rectangle
let a = canvas.rect(200, 400).move(200, 400)
  .attr('opacity', 0.3)
  .addClass('pink')
  .transform({ px: 100, py: 500, origin: 'top-left' })

  a.animate()
  .rotate({ rotate: 500, origin: 'top-right' })

// Put an ellipse where we expect the object to be
canvas.ellipse(30, 30).center(100, 500)
  .attr('opacity', 0.3)
  .addClass('dark-pink')


text:
class Focus:
    """
    This represents a Focus action
    """
    def __init__(self):
        """
        Constructor
        """
        pass


text:
package org.waveprotocol.wave.model.wave;

import org.waveprotocol.wave.model.wave.opbased.ObservableWaveView;

import org.waveprotocol.wave.model.id.IdUtil;
import org.waveprotocol.wave.model.id.WaveId;
import org.waveprotocol.wave.model.id.WaveletId;
import org.waveprotocol.wave.model.util.CollectionUtils;
import org.waveprotocol.wave.model.util.Preconditions;

import java.util.Collections;
import java.util.Map;

/**
 * A read-only ObservableWaveView
 *
 */
public class ReadOnlyWaveView implements ObservableWaveView {
  private final WaveId waveId;
  private final Map<WaveletId, ObservableWavelet> wavelets = CollectionUtils.newHashMap();

  public ReadOnlyWaveView(WaveId waveId) {
    this.waveId = waveId;
  }

  @Override
  public WaveId getWaveId() {
    return waveId;
  }

  /**
   * Returns the conversational root wavelet, if such a wavelet is in view.
   */
  @Override
  public ObservableWavelet getRoot() {
    for (ObservableWavelet w : wavelets.values()) {
      if (IdUtil.isConversationRootWaveletId(w.getId())) {
        return w;
      }
    }
    return null;
  }

  @Override
  public ObservableWavelet createRoot() {
    throw new UnsupportedOperationException("Read only wave views are read-only");
  }

  @Override
  public Iterable<? extends ObservableWavelet> getWavelets() {
    return Collections.unmodifiableCollection(wavelets.values());
  }

  @Override
  public ObservableWavelet getWavelet(WaveletId waveletId) {
    return wavelets.get(waveletId);
  }

  @Override
  public ObservableWavelet createWavelet() {
    throw new UnsupportedOperationException("Read only wave views are read-only");
  }

  /**
   * @throws UnsupportedOperationException always
   */
  @Override
  public ObservableWavelet getUserData() {
    throw new UnsupportedOperationException("Read only wave views don't support"
        + " user data wavelets");
  }

  /**
   * @throws UnsupportedOperationException always
   */
  @Override
  public ObservableWavelet createUserData() {
    throw new UnsupportedOperationException("Read only wave views don't support"
        + " user data wavelets");
  }

  /**
   * Listeners are ignored in this read-only view.
   */
  @Override
  public void addListener(WaveViewListener listener) {
    // Listeners are ignored.
  }

  /**
   * Listeners are ignored in this read-only view.
   */
  @Override
  public void removeListener(WaveViewListener listener) {
    // Listeners are ignored.
  }

  /**
   * Adds a wavelet to this view.
   *
   * @param wavelet the wavelet to add
   * @throws IllegalArgumentException if a wavelet with the same id is already
   *         in the view or the wavelet is from a different wave
   */
  public void addWavelet(ObservableWavelet wavelet) {
    Preconditions.checkArgument(wavelet.getWaveId().equals(waveId),
        "Attempted to add wavelet to wrong view");
    Preconditions.checkArgument(!wavelets.containsKey(wavelet.getId()),
        "Attempted to add duplicate wavelet to view");
    wavelets.put(wavelet.getId(), wavelet);
  }
}


text:
package healthcheck

import (
	"time"

	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/mock"
)

type MockCheck struct {
	mock.Mock
}

func (m *MockCheck) Execute() error {
	args := m.Called()
	return args.Error(0)
}

func TestAgentDefaultConfig(t *testing.T) {
	check := &MockCheck{}
	agnt := NewAgent(check, 0)
	assert.NotNil(t, agnt)
	assert.Equal(t, agnt.(*agent).interval, defaultHealthCheckInterval)
}

func TestAgent(t *testing.T) {
	hc := &MockCheck{}
	hc.On("Execute").Return(nil) // No execute errors.

	expectedCalls := 10                // Number of times that the check's execute function should be called.
	interval := 100 * time.Millisecond // Amount of time between calls.

	agent := NewAgent(hc, interval)
	assert.NotNil(t, agent)

	statusChan := make(chan error)
	agent.Start(statusChan)

	expectedEnd := time.Now().Add(interval * time.Duration(expectedCalls-1))

	// Check the output
	count := 0
	for count < expectedCalls {
		select {
		case err := <-statusChan:
			assert.NoError(t, err)
			count++
		}
	}

	end := time.Now()
	assert.WithinDuration(t, expectedEnd, end, time.Millisecond*50)
	hc.AssertNumberOfCalls(t, "Execute", expectedCalls)

	// Make sure the agent stops calling execute in a timely fashion.
	agent.Stop()
	time.Sleep(2 * interval)
	hc.AssertNumberOfCalls(t, "Execute", expectedCalls)
}


text:
/* global tavJS, undefined, Object */

/**
 * Mount object with value of element
 * @author Helio de Paula Nogueira <helio.nogueir@gmail.com>
 * @version 1.0.0
 *
 * @parameter {HTMLFormElement} elementObject
 * @returns {object} Values of element
 */
tavJS.data.value = function (elementObject) {
    var data = new Object();
    try {
        // Tagname
        data.tagName = null;
        if ((undefined !== elementObject.tagName) && ('' !== elementObject.tagName) && (null !== elementObject.tagName)) {
            data.tagName = elementObject.tagName;
        }
        // Classname
        data.classname = null;
        if ((undefined !== elementObject.className) && ('' !== elementObject.className) && (null !== elementObject.className)) {
            data.classname = elementObject.className;
        }
        // Name
        data.name = null;
        if ((undefined !== elementObject.name) && ('' !== elementObject.name) && (null !== elementObject.name)) {
            data.name = elementObject.name;
        }
        // ID
        data.id = null;
        if ((undefined !== elementObject.id) && ('' !== elementObject.id) && (null !== elementObject.id)) {
            data.id = elementObject.id;
        }
        // Value
        data.value = null;
        if ((undefined !== elementObject.value)) {
            data.value = elementObject.value;
        }
    } catch (ex) {
        console.log(ex);
    }
    return data;
};


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <parent>
  <groupId>org.eclipse.ecf.provider.py4j</groupId>
  <artifactId>org.eclipse.ecf.provider.py4j.parent</artifactId>
   <version>1.0.0-SNAPSHOT</version>
    <relativePath>../../</relativePath>
  </parent>
  <artifactId>org.eclipse.ecf.examples.hello.pythonclient</artifactId>
  <packaging>eclipse-plugin</packaging>
  <version>1.0.1-SNAPSHOT</version>
</project>


text:
from base import *
import random

import bnw.core.bnw_objects as objs

@defer.inlineCallbacks
def bl_internal(user, what, delete, text):
    action = '$pull' if delete else '$addToSet'
    defer.returnValue((yield objs.User.mupdate({'name': user}, {action: {'blacklist': [what, text]}})))

@require_auth
@defer.inlineCallbacks
def cmd_blacklist(request, user="", tag="", club="", delete=""):
    """ Черный список """
    if not delete and len(request.user.get('blacklist', [])) > 2048:
        defer.returnValue(
            dict(ok=False, desc='Stop being a blacklist-faggot.')
        )
    if (user and tag) or (user and club) or (tag and club):
        defer.returnValue(
            dict(ok=False,
                 desc='Complex subscriptions and blacklist aren''t supported.')
        )

    if user:
        user = canonic_user(user)
        _ = yield bl_internal(request.user['name'], 'user', delete, user[:128])
    elif tag:
        _ = yield bl_internal(request.user['name'], 'tag', delete, tag[:256])
    elif club:
        _ = yield bl_internal(request.user['name'], 'club', delete, club[:256])
    else:
        defer.returnValue(
            dict(ok=True, format="blacklist",
                         blacklist=request.user.get('blacklist', []))
        )
    defer.returnValue(
        dict(ok=True, desc='Blacklist updated.')
    )


text:
var _number = 1.5;
%NumberToInteger(_number);


text:
id: a2f1d72d9b908d0bd72bb9f6
title: Make a Person
challengeType: 5
forumTopicId: 16020
---

## Description

Fill in the object constructor with the following methods below:

```js
getFirstName()
getLastName()
getFullName()
setFirstName(first)
setLastName(last)
setFullName(firstAndLast)
```

Run the tests to see the expected output for each method.
The methods that take an argument must accept only one argument and it has to be a string.
These methods must be the only available means of interacting with the object.
Remember to use Read-Search-Ask if you get stuck. Try to pair program. Write your own code.

## Instructions

## Tests

```yml
tests:
  - text: <code>Object.keys(bob).length</code> should return 6.
    testString: assert.deepEqual(Object.keys(bob).length, 6);
  - text: <code>bob instanceof Person</code> should return true.
    testString: assert.deepEqual(bob instanceof Person, true);
  - text: <code>bob.firstName</code> should return undefined.
    testString: assert.deepEqual(bob.firstName, undefined);
  - text: <code>bob.lastName</code> should return undefined.
    testString: assert.deepEqual(bob.lastName, undefined);
  - text: <code>bob.getFirstName()</code> should return "Bob".
    testString: assert.deepEqual(bob.getFirstName(), 'Bob');
  - text: <code>bob.getLastName()</code> should return "Ross".
    testString: assert.deepEqual(bob.getLastName(), 'Ross');
  - text: <code>bob.getFullName()</code> should return "Bob Ross".
    testString: assert.deepEqual(bob.getFullName(), 'Bob Ross');
  - text: <code>bob.getFullName()</code> should return "Haskell Ross" after <code>bob.setFirstName("Haskell")</code>.
    testString: assert.strictEqual((function () { bob.setFirstName("Haskell"); return bob.getFullName(); })(), 'Haskell Ross');
  - text: <code>bob.getFullName()</code> should return "Haskell Curry" after <code>bob.setLastName("Curry")</code>.
    testString: assert.strictEqual((function () { var _bob=new Person('Haskell Ross'); _bob.setLastName("Curry"); return _bob.getFullName(); })(), 'Haskell Curry');
  - text: <code>bob.getFullName()</code> should return "Haskell Curry" after <code>bob.setFullName("Haskell Curry")</code>.
    testString: assert.strictEqual((function () { bob.setFullName("Haskell Curry"); return bob.getFullName(); })(), 'Haskell Curry');
  - text: <code>bob.getFirstName()</code> should return "Haskell" after <code>bob.setFullName("Haskell Curry")</code>.
    testString: assert.strictEqual((function () { bob.setFullName("Haskell Curry"); return bob.getFirstName(); })(), 'Haskell');
  - text: <code>bob.getLastName()</code> should return "Curry" after <code>bob.setFullName("Haskell Curry")</code>.
    testString: assert.strictEqual((function () { bob.setFullName("Haskell Curry"); return bob.getLastName(); })(), 'Curry');

```

## Challenge Seed

```js
var Person = function(firstAndLast) {
  // Complete the method below and implement the others similarly
  this.getFullName = function() {
    return "";
  };
  return firstAndLast;
};

var bob = new Person('Bob Ross');
bob.getFullName();
```

## Solution

```js
var Person = function(firstAndLast) {

  var firstName, lastName;

  function updateName(str) {
    firstName = str.split(" ")[0];
    lastName = str.split(" ")[1];
  }

  updateName(firstAndLast);

  this.getFirstName = function(){
    return firstName;
  };

  this.getLastName = function(){
    return lastName;
  };

  this.getFullName = function(){
    return firstName + " " + lastName;
  };

  this.setFirstName = function(str){
    firstName = str;
  };

  this.setLastName = function(str){
    lastName = str;
  };

  this.setFullName = function(str){
    updateName(str);
  };
};

var bob = new Person('Bob Ross');
bob.getFullName();
```


text:
static NSString * const reuseIdentifierText     = @"AddSportCellText";
static NSString * const reuseIdentifierPciker   = @"AddSportCellPicker";

@interface AddSportController () <UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@end

@implementation AddSportController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"添加运动";

    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.view = self.tableView;

    [self.tableView registerNib:[UINib nibWithNibName:@"AddSportCell" bundle:nil] forCellReuseIdentifier:reuseIdentifierText];
    [self.tableView registerNib:[UINib nibWithNibName:@"AddSportCell" bundle:nil] forCellReuseIdentifier:reuseIdentifierPciker];

    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithTitle:@"确认" style:UIBarButtonItemStylePlain target:self action:@selector(rightBarItemPressed)];
    self.navigationItem.rightBarButtonItem = rightBarItem;
}

#pragma mark - TableView DataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 8;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *identifier = reuseIdentifierText;
    NSInteger index = 0;
    NSString *placeholder = @"";
//    switch (indexPath.row) {
//        case 3:
//            placeholder = @"组";
//            identifier = reuseIdentifierPciker;
//            index = 1;
//            break;
//        case 4:
//            placeholder = @"个";
//            identifier = reuseIdentifierPciker;
//            index = 1;
//            break;
//        case 6:
//            placeholder = @"请选择";
//            identifier = reuseIdentifierPciker;
//            index = 1;
//            break;
//        case 7:
//            placeholder = @"请选择";
//            identifier = reuseIdentifierPciker;
//            index = 1;
//            break;
//        default:
//            break;
//    }
    AddSportCell *addSportCell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
    if (!addSportCell) {
        addSportCell = [[[NSBundle mainBundle] loadNibNamed:@"AddSportCell" owner:self options:nil] objectAtIndex:index];
    }

    return addSportCell;
}

- (void)rightBarItemPressed {

}
@end


text:
<?php
/*
Plugin Name: Galleria
Plugin URI: http://amwhalen.com
Description: Displays a beautiful Galleria slideshow in place of the built-in WordPress image grid. Overrides the default functionality of the [gallery] shortcode.
Version: 1.0.3
Author: Andy Whalen
Author URI: http://amwhalen.com/
License: The MIT License
*/

require_once dirname(__FILE__) . '/amw-galleria/AMWGalleria.php';
$amw_galleria = new AMWGalleria(plugins_url(basename(dirname(__FILE__))));


text:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">

    <TextView
        android:id="@+id/text_error_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="26dp"
        android:gravity="center_horizontal"
        android:text="@string/error_title"
        android:textSize="@dimen/text_headline" />

    <TextView
        android:id="@+id/text_error_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="12dp"
        android:gravity="center_horizontal"
        android:padding="16dp"
        android:text="@string/error_message"
        android:textSize="@dimen/text_body" />

    <Button
        android:id="@+id/button_reload"
        style="@style/ButtonStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:padding="16dp"
        android:text="@string/error_reload" />

</merge>