text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.atomique.ksar.Linux;

import java.awt.Color;
import javax.swing.tree.DefaultMutableTreeNode;
import net.atomique.ksar.AllGraph;
import net.atomique.ksar.GraphDescription;
import net.atomique.ksar.kSar;
import net.atomique.ksar.kSarConfig;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.CombinedDomainXYPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.StandardXYItemRenderer;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.data.time.Second;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.XYDataset;

/**
 *
 * @author alex
 */
public class PidCpuSar extends AllGraph {

    public PidCpuSar(kSar hissar, String prog, String pid) {
        super(hissar);
        mypid = pid;
        Title = new String("Cpu PID " + pid + " " + prog);
        t_usr = new TimeSeries("%User", org.jfree.data.time.Second.class);
        mysar.dispo.put("PID " + pid + " " + prog + " %User", t_usr);
        t_sys = new TimeSeries("%System", org.jfree.data.time.Second.class);
        mysar.dispo.put("PID " + pid + " " + prog + " %System", t_sys);
        t_percent = new TimeSeries("%CPU", org.jfree.data.time.Second.class);
        mysar.dispo.put("PID " + pid + " " + prog + " %CPU", t_percent);

    }

    public void add(Second now, Float val1, Float val2, Float val3) {
        this.t_usr.add(now, val1, do_notify());
        this.t_sys.add(now, val2, do_notify());
        this.t_percent.add(now, val3, do_notify());
        number_of_sample++;
    }

    public XYDataset createused() {
        TimeSeriesCollection graphcollection = new TimeSeriesCollection();
        graphcollection.addSeries(this.t_percent);
        return graphcollection;
    }

    public XYDataset createUser() {
        TimeSeriesCollection graphcollection = new TimeSeriesCollection();
        graphcollection.addSeries(this.t_usr);
        return graphcollection;
    }

    public XYDataset createSystem() {
        TimeSeriesCollection graphcollection = new TimeSeriesCollection();
        graphcollection.addSeries(this.t_sys);
        return graphcollection;
    }

    public void addtotree(DefaultMutableTreeNode myroot) {
        mynode = new DefaultMutableTreeNode(new GraphDescription(this, "LINUXPIDCPU", this.Title, null));
        mysar.add2tree(myroot, mynode);
    }

    public String getMypid() {
        return mypid;
    }

    public JFreeChart makegraph(Second g_start, Second g_end) {
        // used
        XYDataset xydataset1 = this.createused();
        XYPlot subplot1;
        NumberAxis usedaxis = new NumberAxis("% used cpu");
        if (mysar.show100axiscpu) {
            usedaxis.setRange(0.0D, 100D);
        }
        XYItemRenderer minichart1 = new StandardXYItemRenderer();
        minichart1.setBaseStroke(kSarConfig.DEFAULT_STROKE);
        minichart1.setSeriesPaint(0, kSarConfig.color1);
        subplot1 = new XYPlot(xydataset1, null, usedaxis, minichart1);
        // user
        XYDataset idleset = this.createUser();
        XYItemRenderer minichart2 = new StandardXYItemRenderer();
        minichart2.setSeriesPaint(0, kSarConfig.color2);
        minichart2.setBaseStroke(kSarConfig.DEFAULT_STROKE);
        XYPlot subplot2 = new XYPlot(idleset, null, new NumberAxis("% User"), minichart2);
        // nice
        XYDataset niceset = this.createSystem();
        XYItemRenderer minichart3 = new StandardXYItemRenderer();
        minichart3.setSeriesPaint(0, kSarConfig.color3);
        minichart3.setBaseStroke(kSarConfig.DEFAULT_STROKE);
        XYPlot subplot3 = new XYPlot(niceset, null, new NumberAxis("% System"), minichart3);
        // the graph
        CombinedDomainXYPlot plot = new CombinedDomainXYPlot(new DateAxis(""));
        plot.add(subplot1, 2);
        plot.add(subplot3, 1);
        plot.add(subplot2, 1);
        plot.setOrientation(PlotOrientation.VERTICAL);
        // the graph
        JFreeChart mychart = new JFreeChart(this.getGraphTitle(), kSarConfig.DEFAULT_FONT, plot, true);
        if (g_start != null) {
            DateAxis dateaxis1 = (DateAxis) mychart.getXYPlot().getDomainAxis();
            dateaxis1.setRange(g_start.getStart(), g_end.getEnd());
        }
        if (setbackgroundimage(mychart) == 1) {
            subplot1.setBackgroundPaint(null);
            subplot2.setBackgroundPaint(null);
            subplot3.setBackgroundPaint(null);
        }
        return mychart;
    }

    private String mypid;
    private TimeSeries t_usr;
    private TimeSeries t_sys;
    private TimeSeries t_percent;
    }


text:
/**
 * Class to update the UI when a new sound is loaded
 * @constructor
 */
var UiUpdater = function() {
    var controlPanel = document.getElementById('controlPanel');
    var trackInfoPanel = document.getElementById('trackInfoPanel');
    var infoImage = document.getElementById('infoImage');
    var infoArtist = document.getElementById('infoArtist');
    var infoTrack = document.getElementById('infoTrack');
    var messageBox = document.getElementById('messageBox');

    this.clearInfoPanel = function() {
        // first clear the current contents
        infoArtist.innerHTML = "";
        infoTrack.innerHTML = "";
        trackInfoPanel.className = 'hidden';
    };
    this.update = function(loader) {
        // update the track and artist into in the controlPanel
        var artistLink = document.createElement('a');
        artistLink.setAttribute('href', loader.sound.user.permalink_url);
        artistLink.innerHTML = loader.sound.user.username;
        var trackLink = document.createElement('a');
        trackLink.setAttribute('href', loader.sound.permalink_url);

        if(loader.sound.kind=="playlist"){
            trackLink.innerHTML = "
" + loader.sound.tracks[loader.streamPlaylistIndex].title + "
" + "
"+loader.sound.title+"
";
        }else{
            trackLink.innerHTML = loader.sound.title;
        }

        var image = loader.sound.artwork_url ? loader.sound.artwork_url : loader.sound.user.avatar_url; // if no track artwork exists, use the user's avatar.
        infoImage.setAttribute('src', image);

        infoArtist.innerHTML = '';
        infoArtist.appendChild(artistLink);

        infoTrack.innerHTML = '';
        infoTrack.appendChild(trackLink);

        // display the track info panel
        trackInfoPanel.className = '';

        // add a hash to the URL so it can be shared or saved
        var trackToken = loader.sound.permalink_url.substr(22);
        window.location = '#' + trackToken;
    };
    this.toggleControlPanel = function() {
        if (controlPanel.className.indexOf('hidden') === 0) {
            controlPanel.className = '';
        } else {
            controlPanel.className = 'hidden';
        }
    };
    this.displayMessage = function(title, message) {
        messageBox.innerHTML = ''; // reset the contents

        var titleElement = document.createElement('h3');
        titleElement.innerHTML = title;

        var messageElement = document.createElement('p');
        messageElement.innerHTML = message;

        var closeButton = document.createElement('a');
        closeButton.setAttribute('href', '#');
        closeButton.innerHTML = 'close';
        closeButton.addEventListener('click', function(e) {
            e.preventDefault();
            messageBox.className = 'hidden';
        });

        messageBox.className = '';
        // stick them into the container div
        messageBox.appendChild(titleElement);
        messageBox.appendChild(messageElement);
        messageBox.appendChild(closeButton);
    };
};

 // var visualizer = new Visualizer();
    var player =  document.getElementById('player');
    var uiUpdater = new UiUpdater();
    var loader = new SoundcloudLoader(player,uiUpdater);

    var audioSource = new SoundCloudAudioSource(player);
    var form = document.getElementById('form');
    var loadAndUpdate = function(trackUrl) {
        loader.loadStream(trackUrl,
            function() {
                uiUpdater.clearInfoPanel();
                audioSource.playStream(loader.streamUrl());
                uiUpdater.update(loader);
            },
            function() {
                uiUpdater.displayMessage("Error", loader.errorMessage);
            });
    };
    uiUpdater.toggleControlPanel();
    // on load, check to see if there is a track token in the URL, and if so, load that automatically
    if (window.location.hash) {
        var trackUrl = 'https://soundcloud.com/' + window.location.hash.substr(1);
        loadAndUpdate(trackUrl);
    }

    // handle the form submit event to load the new URL
    form.addEventListener('submit', function(e) {
        e.preventDefault();
        var trackUrl = document.getElementById('input').value;
        loadAndUpdate(trackUrl);
    });
    var toggleButton = document.getElementById('toggleButton')
    toggleButton.addEventListener('click', function(e) {
        e.preventDefault();
        uiUpdater.toggleControlPanel();
    });

    window.addEventListener("keydown", keyControls, false);

    function keyControls(e) {
        switch(e.keyCode) {
            case 32:
                // spacebar pressed
                loader.directStream('toggle');
                break;
            case 37:
                // left key pressed
                loader.directStream('backward');
                break;
            case 39:
                // right key pressed
                loader.directStream('forward');
                break;
        }
    }

redpajama_set_name: RedPajamaGithub


text:
package com.microsoft.bingads.v10.api.test.operations.bulk_download_operation;

import com.microsoft.bingads.AuthorizationData;
import com.microsoft.bingads.PasswordAuthentication;
import com.microsoft.bingads.v10.api.test.operations.FakeApiTest;
import com.microsoft.bingads.v10.bulk.ArrayOfKeyValuePairOfstringstring;
import com.microsoft.bingads.v10.bulk.BulkDownloadOperation;
import com.microsoft.bingads.v10.bulk.GetBulkDownloadStatusResponse;
import com.microsoft.bingads.v10.bulk.IBulkService;

public class BulkDownloadOperationTest extends FakeApiTest {

    protected IBulkService service;

    private static AuthorizationData createUserData() {
        AuthorizationData authorizationData = new AuthorizationData();
        authorizationData.setAuthentication(new PasswordAuthentication("user", "pass"));
        authorizationData.setAccountId(123L);
        authorizationData.setCustomerId(456L);
        authorizationData.setDeveloperToken("dev");

        return authorizationData;
    }

    protected BulkDownloadOperation createBulkDownloadOperation(Integer statusCheckIntervalInMs) {
        BulkDownloadOperation operation = new BulkDownloadOperation("request123", createUserData());

        if (statusCheckIntervalInMs != null) {
            operation.setStatusPollIntervalInMilliseconds(statusCheckIntervalInMs);
        }

        return operation;
    }

    protected GetBulkDownloadStatusResponse createStatusResponse(Integer percentComplete, String status, String resultFileUrl) {
        GetBulkDownloadStatusResponse response = new GetBulkDownloadStatusResponse();
        response.setForwardCompatibilityMap(new ArrayOfKeyValuePairOfstringstring());
        response.setPercentComplete(percentComplete);
        response.setRequestStatus(status);
        response.setResultFileUrl(resultFileUrl);

        return response;
    }

    public BulkDownloadOperationTest() {
        super();
    }

}


text:
import Panel from '../';
import i18next from 'i18next';
const {findRenderedDOMComponentWithClass, renderIntoDocument, Simulate} = TestUtils;

describe('<Panel />', () => {
    describe('when mounted with no props', () => {
        let reactComponent, domNode;
        before(() => {
            reactComponent = renderIntoDocument(<Panel />);
            domNode = ReactDOM.findDOMNode(reactComponent);
        });
        it('should render data-focus attribute', () => {
            expect(reactComponent).to.exist;
            expect(reactComponent).to.be.an('object');
            expect(domNode.tagName).to.equal('DIV');
            expect(domNode.getAttribute('data-focus')).to.equal('panel');
            expect(domNode.getAttribute('data-spy')).not.to.be.null;
            expect(domNode.getAttribute('data-spy')).not.to.be.undefined;
        });
        it('should have a data-spy attribute', () => {
            expect(domNode.getAttribute('data-spy')).not.to.be.null;
            expect(domNode.getAttribute('data-spy')).not.to.be.undefined;
        });
        it('should be material designed', () => {
            expect(domNode.getAttribute('class')).to.equal('mdl-card mdl-card--border mdl-shadow--4dp');
        });
        it('should have a title section', () => {
            const titleSection = domNode.querySelector('[data-focus="panel-title"]');
            expect(titleSection).to.exist;
        });
        it('should have a content section', () => {
            const contentSection = domNode.querySelector('[data-focus="panel-content"]');
            expect(contentSection).to.exist;
        });
        it('should not have a top actions', () => {
            const topActions = domNode.querySelector('[data-focus="panel-title"] .buttons');
            expect(topActions).to.exist;
        });
        it('should not have a bottom actions section', () => {
            const bottomSection = domNode.querySelector('[data-focus="panel-actions"]');
            expect(bottomSection).not.to.exist;
        });
    });
    describe('when mounted with title props', () => {
        i18next.init({resources: {translation: {panel: {title: 'This is a title'}}}}, () => {
            let reactComponent, domNode;
            const title = 'panel.title';
            before(() => {
                reactComponent = renderIntoDocument(<Panel title={title} />);
                domNode = ReactDOM.findDOMNode(reactComponent);
            });
            it('should display a title', () => {
                const titleContent = domNode.querySelector('[data-focus="panel-title"] h3');
                expect(titleContent).to.exist;
                expect(titleContent.tagName).to.equal('H3');
                expect(titleContent.getAttribute('data-spy-title')).to.exist;
                expect(titleContent.innerHTML).to.equal(i18next.t(title));
            });
        });
    });
    describe('when mounted with actions props', () => {
        let domNode, reactComponent;
        const actions = () => <span>{'actions'}</span>;
        describe('by default', () => {
            before(() => {
                reactComponent = renderIntoDocument(<Panel Buttons={actions} />);
                domNode = ReactDOM.findDOMNode(reactComponent);
            });
            it('should display actions top by default', () => {
                const topActions = domNode.querySelector('[data-focus="panel-title"] .buttons');
                expect(topActions).to.exist;
            });
            it('should not have a bottom actions section', () => {
                const bottomSection = domNode.querySelector('[data-focus="panel-actions"]');
                expect(bottomSection).not.to.exist;
            });
        });
        describe('with buttonsPosition top', () => {
            before(() => {
                reactComponent = renderIntoDocument(<Panel Buttons={actions} buttonsPosition='top' />);
                domNode = ReactDOM.findDOMNode(reactComponent);
            });
            it('should display actions at the top', () => {
                const topActions = domNode.querySelector('[data-focus="panel-title"] .buttons');
                expect(topActions).to.exist;
            });
            it('should not display action at the bottom', () => {
                const bottomSection = domNode.querySelector('[data-focus="panel-actions"]');
                expect(bottomSection).not.to.exist;
            });
        });
        describe('with buttonsPosition bottom', () => {
            before(() => {
                reactComponent = renderIntoDocument(<Panel Buttons={actions} buttonsPosition='bottom' />);
                domNode = ReactDOM.findDOMNode(reactComponent);
            });
            it('should not display actions at the top', () => {
                const topActions = domNode.querySelector('[data-focus="panel-title"] .buttons');
                expect(topActions).not.to.exist;
            });
            it('should display action at the bottom', () => {
                const bottomSection = domNode.querySelector('[data-focus="panel-actions"]');
                expect(bottomSection).to.exist;
            });
        });
        describe('with buttonsPosition both', () => {
            before(() => {
                reactComponent = renderIntoDocument(<Panel Buttons={actions} buttonsPosition='both' />);
                domNode = ReactDOM.findDOMNode(reactComponent);
            });
            it('should display actions at the top', () => {
                const topActions = domNode.querySelector('[data-focus="panel-title"] .buttons');
                expect(topActions).to.exist;
            });
            it('should display action at the bottom', () => {
                const bottomSection = domNode.querySelector('[data-focus="panel-actions"]');
                expect(bottomSection).to.exist;
            });
        });
    });
});


text: import { Accounts } from 'meteor/accounts-base';


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

/**
 * UserTeamAssociationServiceInterface.java
 *
 * This file was auto-generated from WSDL
 * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
 */

package com.google.api.ads.admanager.axis.v202205;

public interface UserTeamAssociationServiceInterface extends java.rmi.Remote {

    /**
     * Creates new {@link UserTeamAssociation} objects.
     */
    public com.google.api.ads.admanager.axis.v202205.UserTeamAssociation[] createUserTeamAssociations(com.google.api.ads.admanager.axis.v202205.UserTeamAssociation[] userTeamAssociations) throws java.rmi.RemoteException, com.google.api.ads.admanager.axis.v202205.ApiException;

    /**
     * Gets a {@link UserTeamAssociationPage} of {@link UserTeamAssociation}
     * objects that satisfy the given {@link Statement#query}. The following
     * fields are supported for filtering:
     *
     *

     *

     *         PQL Property	 Object Property
     *

     *

     *         {@code userId}
     *         {@link UserTeamAssociation#userId}
     *

     *

     *         {@code teamId}
     *         {@link UserTeamAssociation#teamId}
     *

     *

     */
    public com.google.api.ads.admanager.axis.v202205.UserTeamAssociationPage getUserTeamAssociationsByStatement(com.google.api.ads.admanager.axis.v202205.Statement filterStatement) throws java.rmi.RemoteException, com.google.api.ads.admanager.axis.v202205.ApiException;

    /**
     * Performs actions on {@link UserTeamAssociation} objects that
     * match the
     *         given {@link Statement#query}.
     */
    public com.google.api.ads.admanager.axis.v202205.UpdateResult performUserTeamAssociationAction(com.google.api.ads.admanager.axis.v202205.UserTeamAssociationAction userTeamAssociationAction, com.google.api.ads.admanager.axis.v202205.Statement statement) throws java.rmi.RemoteException, com.google.api.ads.admanager.axis.v202205.ApiException;

    /**
     * Updates the specified {@link UserTeamAssociation} objects.
     */
    public com.google.api.ads.admanager.axis.v202205.UserTeamAssociation[] updateUserTeamAssociations(com.google.api.ads.admanager.axis.v202205.UserTeamAssociation[] userTeamAssociations) throws java.rmi.RemoteException, com.google.api.ads.admanager.axis.v202205.ApiException;
}


text:
package org.apache.archiva.proxy.model;

import org.apache.archiva.repository.storage.StorageAsset;

/**
 * A result from a proxy fetch operation.
 *
 * @since 2.1.2
 */
public class ProxyFetchResult
{

    //The file returned
    private StorageAsset file;

    //Was the local file modified by the fetch?
    private boolean modified;

    public ProxyFetchResult( StorageAsset file, boolean modified )
    {
        this.file = file;
        this.modified = modified;
    }

    public StorageAsset getFile()
    {
        return file;
    }

    public boolean isModified()
    {
        return modified;
    }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CSvnBranchLocker
{
    public partial class FormLogin : Form
    {
        public FormLogin(string szPassword)
        {
            InitializeComponent();
            this.tbPassword.Text = szPassword;
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            base.DialogResult = DialogResult.OK;
        }
    }
}


text:
A meal planning app written entirely in Javascript.  [Node.js](http://nodejs.org) on the backend, [AngularJS](http://angularjs.org) and [RequireJS](http://requirejs.org) on the front end, and [MongoDB](http://mongodb.org) for the database.

## Production Site
You can visit the live site at [hasslefreemeals.net](http://www.hasslefreemeals.net).  Feel free
to mess around and report any bugs on Github Issues.

## Installation
All installation steps assume that you have [Homebrew](http://mxcl.github.com/homebrew/) installed.

### NodeJS
```
$ brew install node
```
### MongoDB
```
$ brew install mongodb
```
### App
```
$ git clone git://github.com/danielberkompas/meal-planner.git
$ cd meal-planner/
$ npm install
$ node app
```
Now visit `http://localhost:3000` and everything should be set up!

## Contributing
1. Fork the repo
2. Make your changes, submit pull request **including screenshots**. Use OSX's built in screenshot feature or [Skitch](http://evernote.com/skitch).
3. If you want attribution, include an update to the CHANGELOG.md file.  The project uses [Semantic Versioning](http://semver.org).

If you update the changelog, your update should look like this:

```
## Version X.X.X
2013/03/22

* @yourgithubhandle: {describe the change you made.}
```

You should also update the `package.json` to match the new version number.  Continuous integration is set up, so your pull request will be pushed live after it is approved automatically, which makes some of these steps necessary.


text:
#ifndef _APS3_ETH_H
#define _APS3_ETH_H

//Dependencies
#include "core/nic.h"

//Number of TX buffers
#ifndef APS3_ETH_TX_BUFFER_COUNT
   #define APS3_ETH_TX_BUFFER_COUNT 4
#elif (APS3_ETH_TX_BUFFER_COUNT < 1)
   #error APS3_ETH_TX_BUFFER_COUNT parameter is not valid
#endif

//TX buffer size
#ifndef APS3_ETH_TX_BUFFER_SIZE
   #define APS3_ETH_TX_BUFFER_SIZE 1536
#elif (APS3_ETH_TX_BUFFER_SIZE != 1536)
   #error APS3_ETH_TX_BUFFER_SIZE parameter is not valid
#endif

//Number of RX buffers
#ifndef APS3_ETH_RX_BUFFER_COUNT
   #define APS3_ETH_RX_BUFFER_COUNT 4
#elif (APS3_ETH_RX_BUFFER_COUNT < 1)
   #error APS3_ETH_RX_BUFFER_COUNT parameter is not valid
#endif

//RX buffer size
#ifndef APS3_ETH_RX_BUFFER_SIZE
   #define APS3_ETH_RX_BUFFER_SIZE 1536
#elif (APS3_ETH_RX_BUFFER_SIZE != 1536)
   #error APS3_ETH_RX_BUFFER_SIZE parameter is not valid
#endif

//Ethernet interrupt priority
#ifndef APS3_ETH_IRQ_PRIORITY
   #define APS3_ETH_IRQ_PRIORITY 0
#elif (APS3_ETH_IRQ_PRIORITY < 0)
   #error APS3_ETH_IRQ_PRIORITY parameter is not valid
#endif

//tx_irq_mask register
#define TX_IRQ_MASK_TRANSMIT_ERROR      0x0001
#define TX_IRQ_MASK_EXCESSIVE_DEFERRAL  0x0002
#define TX_IRQ_MASK_EXCESSIVE_COLLISION 0x0004
#define TX_IRQ_MASK_LATE_COLLISION      0x0008
#define TX_IRQ_MASK_FRAME_TOO_LONG      0x0010
#define TX_IRQ_MASK_MEMORY_ERROR        0x0020
#define TX_IRQ_MASK_FRAME_SENT          0x0040
#define TX_IRQ_MASK_MEMORY_AVAILABLE    0x0080
#define TX_IRQ_MASK_THRESHOLD_REACHED   0x0100
#define TX_IRQ_MASK_MEMORY_EMPTY        0x0200

//rx_irq_mask register
#define RX_IRQ_MASK_RECEIVE_ERROR       0x0001
#define RX_IRQ_MASK_LENGTH_FIELD_ERROR  0x0002
#define RX_IRQ_MASK_FRAME_TOO_LONG      0x0004
#define RX_IRQ_MASK_SHORT_FRAME         0x0008
#define RX_IRQ_MASK_ODD_NIBBLE_COUNT    0x0010
#define RX_IRQ_MASK_INVALID_ADDRESS     0x0020
#define RX_IRQ_MASK_PHY_ERROR           0x0040
#define RX_IRQ_MASK_CRC_ERROR           0x0080
#define RX_IRQ_MASK_MEMORY_ERROR        0x0100
#define RX_IRQ_MASK_WAKEUP_ON_LAN       0x0200
#define RX_IRQ_MASK_FRAME_READY         0x0400
#define RX_IRQ_MASK_THRESHOLD_REACHED   0x0800
#define RX_IRQ_MASK_FRAME_OVERFLOW      0x1000

//Transmit DMA descriptor flags
#define TX_DESC_TRANSMIT_ERROR          0x0001
#define TX_DESC_EXCESSIVE_DEFERRAL      0x0002
#define TX_DESC_EXCESSIVE_COLLISION     0x0003
#define TX_DESC_LATE_COLLISION          0x0004
#define TX_DESC_FRAME_TOO_LONG          0x0010
#define TX_DESC_MEMORY_ERROR            0x0020

//Receive DMA descriptor flags
#define RX_DESC_RECEIVE_ERROR           0x0001
#define RX_DESC_LENGTH_FIELD_ERROR      0x0002
#define RX_DESC_FRAME_TOO_LONG          0x0003
#define RX_DESC_SHORT_FRAME             0x0004
#define RX_DESC_ODD_NIBBLE_COUNT        0x0010
#define RX_DESC_INVALID_ADDRESS         0x0020
#define RX_DESC_PHY_ERROR               0x0040
#define RX_DESC_CRC_ERROR               0x0080
#define RX_DESC_MEMORY_ERROR            0x0100

/**
 * @brief TX DMA descriptor
 **/

typedef struct
{
   uint32_t addr;
   uint32_t size : 16;
   uint32_t status : 16;
} Aps3TxDmaDesc;

/**
 * @brief RX DMA descriptor
 **/

typedef struct
{
   uint32_t addr;
   uint32_t size : 16;
   uint32_t status : 16;
} Aps3RxDmaDesc;

//Cortus APS3 Ethernet MAC driver
extern const NicDriver aps3EthDriver;

//Cortus APS3 Ethernet MAC related functions
error_t aps3EthInit(NetInterface *interface);
void aps3EthInitDmaDesc(NetInterface *interface);

void aps3EthTick(NetInterface *interface);

void aps3EthEnableIrq(NetInterface *interface);
void aps3EthDisableIrq(NetInterface *interface);
void aps3EthEventHandler(NetInterface *interface);

error_t aps3EthSetMacFilter(NetInterface *interface);

error_t aps3EthSendPacket(NetInterface *interface,
   const NetBuffer *buffer, size_t offset);

error_t aps3EthReceivePacket(NetInterface *interface,
   uint8_t *buffer, size_t size, size_t *length);

void aps3EthWritePhyReg(uint8_t phyAddr, uint8_t regAddr, uint16_t data);
uint16_t aps3EthReadPhyReg(uint8_t phyAddr, uint8_t regAddr);

uint32_t aps3EthCalcCrc(const void *data, size_t length);

#endif


text:
function solve(args) {
    console.log(lastDigitToWord(args[0]));

    function lastDigitToWord(number) {
        var digits =
            ["zero", "one", "two", "three",
                "four", "five", "six", "seven",
                "eight", "nine"];

        return digits[number.toString().split('').pop()];
    }
}


text:
module Main where

import FFI
import Uri
import Prelude

main :: Fay ()
main = do
  let uri = newUri "http://user:pass@www.example.com:80/ppp?a=b#c"
  putStrLn . toString . newUri =<< currentUri
  print uri
  putStrLn "--"
  mapM_ (putStrLn . ($ uri)) $
    toString : map (fromNullable .) [protocol, host, port, path, query, anchor]
  putStrLn "--"
  mapM_ (putStrLn . toString . ($ uri))
    [withProtocol "https", withUserInfo "foo:bar", withHost "example.net", withPort "90", withPath "path", withQuery "e=f", withAnchor "g"]
  putStrLn "--"
  mapM_ (putStrLn . toString . ($ uri))
    [removeProtocol, removeUserInfo, removeHost, removePort, removePath, removeQuery, removeAnchor]
  putStrLn "--"
  mapM_ (putStrLn . toString . ($ uri))
    [addQueryParam "c" "d", replaceQueryParam "a" "e", replaceQueryParamValue "a" "b" "f"
    ,deleteQueryParam "a", deleteQueryParamValue "a" "b"]
  putStrLn "--"
  mapM_ (putStrLn . ($ uri)) $ map (fromNullable .)
    [protocol . removeProtocol
    ,userInfo . removeUserInfo
    ,host     . removeHost
    ,port     . removePort
    ,path     . removePath
    ,query    . removeQuery
    ,anchor   . removeAnchor]

fromNullable :: Nullable String -> String
fromNullable Null = "null"
fromNullable (Nullable s) = "'" ++ s ++ "'"


text:
package com.adaptris.core.services.routing;

import static org.junit.Assert.assertTrue;
import org.junit.Test;

public class AlwaysMatchSyntaxIdentifierTest {

  public static final String LINE = "The quick brown fox jumps over the lazy dog";

  public AlwaysMatchSyntaxIdentifier createIdentifier() {
    return new AlwaysMatchSyntaxIdentifier();
  }

  @Test
  public void testMatch() throws Exception {
    AlwaysMatchSyntaxIdentifier ident = createIdentifier();
    assertTrue("Matches regexp", ident.isThisSyntax(LINE));
  }

}


text:
title: Elizabeth Esty, Connecticut Congressperson
name: Elizabeth Esty
avatar: /ui/img/avatars/Elizabeth_Esty.jpg
party: democrat
state: connecticut
type: congressperson
lasthall: 2017-03-05
phone: 202-225-4535
never:
twitter: RepEsty
---


text:
<?php

if (!User::isAdmin())
{
	Common::responseCode(403);
	user_error('Forbidden access', ERROR);
}

if (API::action('enable_module') || API::action('disable_module'))
{
	if (!API::has('module_name'))
		user_error('No module name set', ERROR);

	Db::exec("
	UPDATE module SET enabled = '" . Db::escape(API::action('enable_module') ? '1' : '0') . "'
	WHERE module_name = '" . Db::escape(API::get('module_name')) . "';");
	API::finish();
}
else if (API::action('reinstall_module'))
{
	if (!API::has('module_name') || !is_file('modules/' . API::get('module_name') . '/admin/setup.php'))
		user_error('No module name set or module doesn\'t exist', ERROR);

	include_once('modules/' . API::get('module_name') . '/admin/setup.php');
	API::finish();
}
else if (API::action('get_modules'))
{
	$modules = array();
	$table = Db::query("SELECT * FROM module ORDER BY module_name ASC;");
	while ($row = $table->fetch())
	{
		$config = new Config('modules/' . $row['module_name'] . '/module.conf');
		$row['module_id'] = count($modules);
		$row['title'] = $config->get('title');
		$row['author'] = $config->get('author');
		$row['description'] = $config->get('description');
		$modules[] = $row;
	}
	API::set('modules', $modules);
	API::finish();
}


text:
namespace clang {
namespace clangd {
namespace {

// Deduces the FunctionDecl from a selection. Requires either the function body
// or the function decl to be selected. Returns null if none of the above
// criteria is met.
// FIXME: This is shared with define inline, move them to a common header once
// we have a place for such.
const FunctionDecl *getSelectedFunction(const SelectionTree::Node *SelNode) {
  if (!SelNode)
    return nullptr;
  const ast_type_traits::DynTypedNode &AstNode = SelNode->ASTNode;
  if (const FunctionDecl *FD = AstNode.get<FunctionDecl>())
    return FD;
  if (AstNode.get<CompoundStmt>() &&
      SelNode->Selected == SelectionTree::Complete) {
    if (const SelectionTree::Node *P = SelNode->Parent)
      return P->ASTNode.get<FunctionDecl>();
  }
  return nullptr;
}

llvm::Optional<Path> getSourceFile(llvm::StringRef FileName,
                                   const Tweak::Selection &Sel) {
  if (auto Source = getCorrespondingHeaderOrSource(
          std::string(FileName),
          &Sel.AST->getSourceManager().getFileManager().getVirtualFileSystem()))
    return *Source;
  return getCorrespondingHeaderOrSource(std::string(FileName), *Sel.AST,
                                        Sel.Index);
}

// Synthesize a DeclContext for TargetNS from CurContext. TargetNS must be empty
// for global namespace, and endwith "::" otherwise.
// Returns None if TargetNS is not a prefix of CurContext.
llvm::Optional<const DeclContext *>
findContextForNS(llvm::StringRef TargetNS, const DeclContext *CurContext) {
  assert(TargetNS.empty() || TargetNS.endswith("::"));
  // Skip any non-namespace contexts, e.g. TagDecls, functions/methods.
  CurContext = CurContext->getEnclosingNamespaceContext();
  // If TargetNS is empty, it means global ns, which is translation unit.
  if (TargetNS.empty()) {
    while (!CurContext->isTranslationUnit())
      CurContext = CurContext->getParent();
    return CurContext;
  }
  // Otherwise we need to drop any trailing namespaces from CurContext until
  // we reach TargetNS.
  std::string TargetContextNS =
      CurContext->isNamespace()
          ? llvm::cast<NamespaceDecl>(CurContext)->getQualifiedNameAsString()
          : "";
  TargetContextNS.append("::");

  llvm::StringRef CurrentContextNS(TargetContextNS);
  // If TargetNS is not a prefix of CurrentContext, there's no way to reach
  // it.
  if (!CurrentContextNS.startswith(TargetNS))
    return llvm::None;

  while (CurrentContextNS != TargetNS) {
    CurContext = CurContext->getParent();
    // These colons always exists since TargetNS is a prefix of
    // CurrentContextNS, it ends with "::" and they are not equal.
    CurrentContextNS = CurrentContextNS.take_front(
        CurrentContextNS.drop_back(2).rfind("::") + 2);
  }
  return CurContext;
}

// Returns source code for FD after applying Replacements.
// FIXME: Make the function take a parameter to return only the function body,
// afterwards it can be shared with define-inline code action.
llvm::Expected<std::string>
getFunctionSourceAfterReplacements(const FunctionDecl *FD,
                                   const tooling::Replacements &Replacements) {
  const auto &SM = FD->getASTContext().getSourceManager();
  auto OrigFuncRange = toHalfOpenFileRange(
      SM, FD->getASTContext().getLangOpts(), FD->getSourceRange());
  if (!OrigFuncRange)
    return llvm::createStringError(llvm::inconvertibleErrorCode(),
                                   "Couldn't get range for function.");
  // Include template parameter list.
  if (auto *FTD = FD->getDescribedFunctionTemplate())
    OrigFuncRange->setBegin(FTD->getBeginLoc());

  // Get new begin and end positions for the qualified function definition.
  unsigned FuncBegin = SM.getFileOffset(OrigFuncRange->getBegin());
  unsigned FuncEnd = Replacements.getShiftedCodePosition(
      SM.getFileOffset(OrigFuncRange->getEnd()));

  // Trim the result to function definition.
  auto QualifiedFunc = tooling::applyAllReplacements(
      SM.getBufferData(SM.getMainFileID()), Replacements);
  if (!QualifiedFunc)
    return QualifiedFunc.takeError();
  return QualifiedFunc->substr(FuncBegin, FuncEnd - FuncBegin + 1);
}

// Creates a modified version of function definition that can be inserted at a
// different location, qualifies return value and function name to achieve that.
// Contains function signature, except defaulted parameter arguments, body and
// template parameters if applicable. No need to qualify parameters, as they are
// looked up in the context containing the function/method.
// FIXME: Drop attributes in function signature.
llvm::Expected<std::string>
getFunctionSourceCode(const FunctionDecl *FD, llvm::StringRef TargetNamespace,
                      const syntax::TokenBuffer &TokBuf) {
  auto &AST = FD->getASTContext();
  auto &SM = AST.getSourceManager();
  auto TargetContext = findContextForNS(TargetNamespace, FD->getDeclContext());
  if (!TargetContext)
    return llvm::createStringError(
        llvm::inconvertibleErrorCode(),
        "define outline: couldn't find a context for target");

  llvm::Error Errors = llvm::Error::success();
  tooling::Replacements DeclarationCleanups;

  // Finds the first unqualified name in function return type and name, then
  // qualifies those to be valid in TargetContext.
  findExplicitReferences(FD, [&](ReferenceLoc Ref) {
    // It is enough to qualify the first qualifier, so skip references with a
    // qualifier. Also we can't do much if there are no targets or name is
    // inside a macro body.
    if (Ref.Qualifier || Ref.Targets.empty() || Ref.NameLoc.isMacroID())
      return;
    // Only qualify return type and function name.
    if (Ref.NameLoc != FD->getReturnTypeSourceRange().getBegin() &&
        Ref.NameLoc != FD->getLocation())
      return;

    for (const NamedDecl *ND : Ref.Targets) {
      if (ND->getDeclContext() != Ref.Targets.front()->getDeclContext()) {
        elog("Targets from multiple contexts: {0}, {1}",
             printQualifiedName(*Ref.Targets.front()), printQualifiedName(*ND));
        return;
      }
    }
    const NamedDecl *ND = Ref.Targets.front();
    const std::string Qualifier = getQualification(
        AST, *TargetContext, SM.getLocForStartOfFile(SM.getMainFileID()), ND);
    if (auto Err = DeclarationCleanups.add(
            tooling::Replacement(SM, Ref.NameLoc, 0, Qualifier)))
      Errors = llvm::joinErrors(std::move(Errors), std::move(Err));
  });

  // Get rid of default arguments, since they should not be specified in
  // out-of-line definition.
  for (const auto *PVD : FD->parameters()) {
    if (PVD->hasDefaultArg()) {
      // Deletion range initially spans the initializer, excluding the `=`.
      auto DelRange = CharSourceRange::getTokenRange(PVD->getDefaultArgRange());
      // Get all tokens before the default argument.
      auto Tokens = TokBuf.expandedTokens(PVD->getSourceRange())
                        .take_while([&SM, &DelRange](const syntax::Token &Tok) {
                          return SM.isBeforeInTranslationUnit(
                              Tok.location(), DelRange.getBegin());
                        });
      // Find the last `=` before the default arg.
      auto Tok =
          llvm::find_if(llvm::reverse(Tokens), [](const syntax::Token &Tok) {
            return Tok.kind() == tok::equal;
          });
      assert(Tok != Tokens.rend());
      DelRange.setBegin(Tok->location());
      if (auto Err =
              DeclarationCleanups.add(tooling::Replacement(SM, DelRange, "")))
        Errors = llvm::joinErrors(std::move(Errors), std::move(Err));
    }
  }

  auto DelAttr = [&](const Attr *A) {
    if (!A)
      return;
    auto AttrTokens =
        TokBuf.spelledForExpanded(TokBuf.expandedTokens(A->getRange()));
    assert(A->getLocation().isValid());
    if (!AttrTokens || AttrTokens->empty()) {
      Errors = llvm::joinErrors(
          std::move(Errors),
          llvm::createStringError(
              llvm::inconvertibleErrorCode(),
              llvm::StringRef("define outline: Can't move out of line as "
                              "function has a macro `") +
                  A->getSpelling() + "` specifier."));
      return;
    }
    CharSourceRange DelRange =
        syntax::Token::range(SM, AttrTokens->front(), AttrTokens->back())
            .toCharRange(SM);
    if (auto Err =
            DeclarationCleanups.add(tooling::Replacement(SM, DelRange, "")))
      Errors = llvm::joinErrors(std::move(Errors), std::move(Err));
  };

  DelAttr(FD->getAttr<OverrideAttr>());
  DelAttr(FD->getAttr<FinalAttr>());

  auto DelKeyword = [&](tok::TokenKind Kind, SourceRange FromRange) {
    bool FoundAny = false;
    for (const auto &Tok : TokBuf.expandedTokens(FromRange)) {
      if (Tok.kind() != Kind)
        continue;
      FoundAny = true;
      auto Spelling = TokBuf.spelledForExpanded(llvm::makeArrayRef(Tok));
      if (!Spelling) {
        Errors = llvm::joinErrors(
            std::move(Errors),
            llvm::createStringError(
                llvm::inconvertibleErrorCode(),
                llvm::formatv("define outline: couldn't remove `{0}` keyword.",
                              tok::getKeywordSpelling(Kind))));
        break;
      }
      CharSourceRange DelRange =
          syntax::Token::range(SM, Spelling->front(), Spelling->back())
              .toCharRange(SM);
      if (auto Err =
              DeclarationCleanups.add(tooling::Replacement(SM, DelRange, "")))
        Errors = llvm::joinErrors(std::move(Errors), std::move(Err));
    }
    if (!FoundAny) {
      Errors = llvm::joinErrors(
          std::move(Errors),
          llvm::createStringError(
              llvm::inconvertibleErrorCode(),
              llvm::formatv(
                  "define outline: couldn't find `{0}` keyword to remove.",
                  tok::getKeywordSpelling(Kind))));
    }
  };

  if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
    if (MD->isVirtualAsWritten())
      DelKeyword(tok::kw_virtual, {FD->getBeginLoc(), FD->getLocation()});
    if (MD->isStatic())
      DelKeyword(tok::kw_static, {FD->getBeginLoc(), FD->getLocation()});
  }

  if (Errors)
    return std::move(Errors);
  return getFunctionSourceAfterReplacements(FD, DeclarationCleanups);
}

struct InsertionPoint {
  std::string EnclosingNamespace;
  size_t Offset;
};
// Returns the most natural insertion point for \p QualifiedName in \p Contents.
// This currently cares about only the namespace proximity, but in feature it
// should also try to follow ordering of declarations. For example, if decls
// come in order `foo, bar, baz` then this function should return some point
// between foo and baz for inserting bar.
llvm::Expected<InsertionPoint> getInsertionPoint(llvm::StringRef Contents,
                                                 llvm::StringRef QualifiedName,
                                                 const LangOptions &LangOpts) {
  auto Region = getEligiblePoints(Contents, QualifiedName, LangOpts);

  assert(!Region.EligiblePoints.empty());
  // FIXME: This selection can be made smarter by looking at the definition
  // locations for adjacent decls to Source. Unfortunately pseudo parsing in
  // getEligibleRegions only knows about namespace begin/end events so we
  // can't match function start/end positions yet.
  auto Offset = positionToOffset(Contents, Region.EligiblePoints.back());
  if (!Offset)
    return Offset.takeError();
  return InsertionPoint{Region.EnclosingNamespace, *Offset};
}

// Returns the range that should be deleted from declaration, which always
// contains function body. In addition to that it might contain constructor
// initializers.
SourceRange getDeletionRange(const FunctionDecl *FD,
                             const syntax::TokenBuffer &TokBuf) {
  auto DeletionRange = FD->getBody()->getSourceRange();
  if (auto *CD = llvm::dyn_cast<CXXConstructorDecl>(FD)) {
    const auto &SM = TokBuf.sourceManager();
    // AST doesn't contain the location for ":" in ctor initializers. Therefore
    // we find it by finding the first ":" before the first ctor initializer.
    SourceLocation InitStart;
    // Find the first initializer.
    for (const auto *CInit : CD->inits()) {
      // We don't care about in-class initializers.
      if (CInit->isInClassMemberInitializer())
        continue;
      if (InitStart.isInvalid() ||
          SM.isBeforeInTranslationUnit(CInit->getSourceLocation(), InitStart))
        InitStart = CInit->getSourceLocation();
    }
    if (InitStart.isValid()) {
      auto Toks = TokBuf.expandedTokens(CD->getSourceRange());
      // Drop any tokens after the initializer.
      Toks = Toks.take_while([&TokBuf, &InitStart](const syntax::Token &Tok) {
        return TokBuf.sourceManager().isBeforeInTranslationUnit(Tok.location(),
                                                                InitStart);
      });
      // Look for the first colon.
      auto Tok =
          llvm::find_if(llvm::reverse(Toks), [](const syntax::Token &Tok) {
            return Tok.kind() == tok::colon;
          });
      assert(Tok != Toks.rend());
      DeletionRange.setBegin(Tok->location());
    }
  }
  return DeletionRange;
}

/// Moves definition of a function/method to an appropriate implementation file.
///
/// Before:
/// a.h
///   void foo() { return; }
/// a.cc
///   #include "a.h"
///
/// ----------------
///
/// After:
/// a.h
///   void foo();
/// a.cc
///   #include "a.h"
///   void foo() { return; }
class DefineOutline : public Tweak {
public:
  const char *id() const override;

  bool hidden() const override { return false; }
  Intent intent() const override { return Intent::Refactor; }
  std::string title() const override {
    return "Move function body to out-of-line.";
  }

  bool prepare(const Selection &Sel) override {
    // Bail out if we are not in a header file.
    // FIXME: We might want to consider moving method definitions below class
    // definition even if we are inside a source file.
    if (!isHeaderFile(Sel.AST->getSourceManager().getFilename(Sel.Cursor),
                      Sel.AST->getLangOpts()))
      return false;

    Source = getSelectedFunction(Sel.ASTSelection.commonAncestor());
    // Bail out if the selection is not a in-line function definition.
    if (!Source || !Source->doesThisDeclarationHaveABody() ||
        Source->isOutOfLine())
      return false;

    // Bail out in templated classes, as it is hard to spell the class name, i.e
    // if the template parameter is unnamed.
    if (auto *MD = llvm::dyn_cast<CXXMethodDecl>(Source)) {
      if (MD->getParent()->isTemplated())
        return false;
    }

    // Note that we don't check whether an implementation file exists or not in
    // the prepare, since performing disk IO on each prepare request might be
    // expensive.
    return true;
  }

  Expected<Effect> apply(const Selection &Sel) override {
    const SourceManager &SM = Sel.AST->getSourceManager();
    auto MainFileName =
        getCanonicalPath(SM.getFileEntryForID(SM.getMainFileID()), SM);
    if (!MainFileName)
      return llvm::createStringError(
          llvm::inconvertibleErrorCode(),
          "Couldn't get absolute path for mainfile.");

    auto CCFile = getSourceFile(*MainFileName, Sel);
    if (!CCFile)
      return llvm::createStringError(
          llvm::inconvertibleErrorCode(),
          "Couldn't find a suitable implementation file.");

    auto &FS =
        Sel.AST->getSourceManager().getFileManager().getVirtualFileSystem();
    auto Buffer = FS.getBufferForFile(*CCFile);
    // FIXME: Maybe we should consider creating the implementation file if it
    // doesn't exist?
    if (!Buffer)
      return llvm::createStringError(Buffer.getError(),
                                     Buffer.getError().message());
    auto Contents = Buffer->get()->getBuffer();
    auto LangOpts = format::getFormattingLangOpts(
        getFormatStyleForFile(*CCFile, Contents, &FS));
    auto InsertionPoint = getInsertionPoint(
        Contents, Source->getQualifiedNameAsString(), LangOpts);
    if (!InsertionPoint)
      return InsertionPoint.takeError();

    auto FuncDef = getFunctionSourceCode(
        Source, InsertionPoint->EnclosingNamespace, Sel.AST->getTokens());
    if (!FuncDef)
      return FuncDef.takeError();

    SourceManagerForFile SMFF(*CCFile, Contents);
    const tooling::Replacement InsertFunctionDef(
        *CCFile, InsertionPoint->Offset, 0, *FuncDef);
    auto Effect = Effect::mainFileEdit(
        SMFF.get(), tooling::Replacements(InsertFunctionDef));
    if (!Effect)
      return Effect.takeError();

    // FIXME: We should also get rid of inline qualifier.
    const tooling::Replacement DeleteFuncBody(
        Sel.AST->getSourceManager(),
        CharSourceRange::getTokenRange(*toHalfOpenFileRange(
            SM, Sel.AST->getLangOpts(),
            getDeletionRange(Source, Sel.AST->getTokens()))),
        ";");
    auto HeaderFE = Effect::fileEdit(SM, SM.getMainFileID(),
                                     tooling::Replacements(DeleteFuncBody));
    if (!HeaderFE)
      return HeaderFE.takeError();

    Effect->ApplyEdits.try_emplace(HeaderFE->first,
                                   std::move(HeaderFE->second));
    return std::move(*Effect);
  }

private:
  const FunctionDecl *Source = nullptr;
};

REGISTER_TWEAK(DefineOutline)

} // namespace
} // namespace clangd
} // namespace clang


text:
#include "Component.hpp"

Component::Component(ID componentID) :
    componentID(componentID)
{
}

Component::ID Component::getID() const
{
    return this->componentID;
}

std::istringstream& operator>>(std::istringstream& iStream, Component& component)
{
    return component.readStream(iStream);
}


text:
/** @file untnd.cpp
 *  Tool to extract TND archives.
 */

#include <cstdio>
#include <cstring>

#include <list>
#include <string>
#include <fstream>

#include "common/util.h"
#include "common/version.h"

struct FileInfo {
	char name[13];
	uint32 offset;
	uint32 size;

	FileInfo(const char *n = "", uint32 o = 0, uint32 s = 0) : offset(o), size(s) {
		strncpy(name, n, 12);
		name[12] = '\0';
	}
};

enum Command {
	kCommandNone    = -1,
	kCommandList        ,
	kCommandExtract     ,
	kCommandMAX
};

const char *kCommandChar[kCommandMAX] = { "l", "x" };

void printUsage(FILE *stream, const char *name);
bool parseCommandLine(int argc, char **argv, int &returnValue, Command &command, std::string &file);

void readFileList(std::istream &stream, std::list<FileInfo> &files, uint32 count);

void listFiles(std::istream &tnd);
void extractFiles(std::istream &tnd);

int main(int argc, char **argv) {
	int returnValue;
	Command command;
	std::string file;
	if (!parseCommandLine(argc, argv, returnValue, command, file))
		return returnValue;

	std::ifstream tnd;

	tnd.open(file.c_str());

	if (!tnd.is_open()) {
		std::printf("Error opening file \"%s\"\n", file.c_str());
		return 2;
	}

	uint32 tndSize    = Common::readUint32BE(tnd);
	uint32 streamSize = Common::getSize(tnd);

	if ((streamSize == 0xFFFFFFFF) || (tndSize != streamSize)) {
		std::printf("Not a valid TND file\n");
		return 3;
	}

	if      (command == kCommandList)
		listFiles(tnd);
	else if (command == kCommandExtract)
		extractFiles(tnd);

	tnd.close();

	return 0;
}

bool parseCommandLine(int argc, char **argv, int &returnValue, Command &command, std::string &file) {
	file.clear();

	// No command, just display the help
	if (argc == 1) {
		printUsage(stdout, argv[0]);
		returnValue = 0;

		return false;
	}

	// Wrong number of arguments, display the help
	if (argc != 3) {
		printUsage(stderr, argv[0]);
		returnValue = 1;

		return false;
	}

	// Find out what we should do
	command = kCommandNone;
	for (int i = 0; i < kCommandMAX; i++)
		if (!strcmp(argv[1], kCommandChar[i]))
			command = (Command) i;

	// Unknown command
	if (command == kCommandNone) {
		printUsage(stderr, argv[0]);
		returnValue = 1;

		return false;
	}

	// This is the file to use
	file = argv[2];

	return true;
}

void printUsage(FILE *stream, const char *name) {
	std::fprintf(stream, "Dark Seed II TND archive extractor\n");
	std::fprintf(stream, "\n");
	std::fprintf(stream, "%s\n", DS2TOOLS_NAMEVERSION);
	std::fprintf(stream, "Copyright (c) %s, %s\n", DS2TOOLS_COPYRIGHTYEAR, DS2TOOLS_COPYRIGHTAUTHOR);
	std::fprintf(stream, "%s\n", DS2TOOLS_URL);
	std::fprintf(stream, "\n");
	std::fprintf(stream, "Usage: %s <command> <file>\n\n", name);
	std::fprintf(stream, "Commands:\n");
	std::fprintf(stream, "  l          List archive contents\n");
	std::fprintf(stream, "  x          Extract files to current directory\n");
}

void readFileList(std::istream &stream, std::list<FileInfo> &files, uint32 count) {
	// Offset to the start of the data area, directly after the file list
	//                        (name + size + offset) + TND size + number of files
	int startOffset = count * (  8  +   4  +    4  ) +     4    +      4;

	while (count-- > 0) {
		FileInfo file;

		Common::readFixedString(stream, file.name, 8);
		strcat(file.name, ".TXT");

		file.size   = Common::readUint32BE(stream);
		file.offset = Common::readUint32BE(stream) + startOffset;

		files.push_back(file);
	}
}

void listFiles(std::istream &tnd) {
	uint32 fileCount = Common::readUint32BE(tnd);

	std::list<FileInfo> files;
	readFileList(tnd, files, fileCount);

	std::printf("Number of files: %u\n\n", fileCount);

	std::printf(" Filename    | Size\n");
	std::printf("=============|===========\n");

	for (std::list<FileInfo>::const_iterator f = files.begin(); f != files.end(); ++f)
		std::printf("%12s | %10d\n", f->name, f->size);
}

void extractFiles(std::istream &tnd) {
	uint32 fileCount = Common::readUint32BE(tnd);

	std::list<FileInfo> files;
	readFileList(tnd, files, fileCount);

	std::printf("Number of files: %u\n\n", fileCount);

	uint i = 1;
	for (std::list<FileInfo>::const_iterator f = files.begin(); f != files.end(); ++f, ++i) {
		std::printf("Extracting %u/%u: \"%s\"... ", i, fileCount, f->name);
		std::fflush(stdout);

		if (Common::dumpToFile(tnd, f->offset, f->size, f->name))
			std::printf("done\n");
		else
			std::printf("FAILED\n");
	}
}


text:
package transformations.semanticsAware;

import generators.data.AbstractAsynchronousWorker;
import generators.data.sesamemodelbuilders.SesameBuilder;
import main.TestDriver;

import org.openrdf.model.Literal;
import org.openrdf.model.Model;
import org.openrdf.model.Statement;
import org.openrdf.model.impl.LinkedHashModel;

import properties.Configurations;
import transformations.InvalidTransformation;
import transformations.Transformation;
import transformations.TransformationsCall;
import util.RandomUtil;

public class InverseFunctionalProperty implements Transformation{

	public InverseFunctionalProperty(AbstractAsynchronousWorker worker){ }
	@Override
	public Object execute(Object arg) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String print() {
		// TODO Auto-generated method stub
		return null;
	}

	@SuppressWarnings("finally")
	@Override
	public Model executeStatement(Statement arg) {
		//System.out.println("InverseFunctionalProperty");
		Statement s = (Statement)arg;
		Model model = new LinkedHashModel();

	    if(arg instanceof Statement){
	    	if(TransformationsCall.inverseFunctionalProperty.contains(s.getPredicate().stringValue())){
	    		if(!(s.getObject() instanceof Literal)){
//		    		int index = (int)(Math.random()*(TransformationsCall.inverseFunctionalProperty.get(s.getPredicate().stringValue()).toArray().length-1));
//		    		model.add(SesameBuilder.sesameValueFactory.createURI(s.getObject().stringValue()), SesameBuilder.sesameValueFactory.createURI(TransformationsCall.inverseFunctionalPropertyMap.get(s.getPredicate().stringValue()).toArray()[index].toString()),SesameBuilder.sesameValueFactory.createURI(s.getSubject().stringValue()),s.getContext());
	    			RandomUtil ru = new RandomUtil();
		    		String newObject = TestDriver.getConfigurations().getString(Configurations.NEW_URI_NAMESPACE) + ru.randomChars(30);
					model.add(SesameBuilder.sesameValueFactory.createURI(s.getObject().stringValue()),s.getPredicate(),SesameBuilder.sesameValueFactory.createURI(newObject),s.getContext());
	    		}
	    	}
//	    	else{
//	    		model.add(s);
//			}
	    }
	    else{
			try {
				throw new InvalidTransformation();
			} catch (InvalidTransformation e) {
				e.printStackTrace();
			}finally{
				return model;
			}
	}
	return model;

//		Statement s = (Statement)arg;
//		PropertyInverseFunct = ontology.getInverseFunctionalProperties(s.getPredicate().stringValue());
//		Model model = new LinkedHashModel();
//		if(arg instanceof Statement){
//			if(!PropertyInverseFunct.isEmpty()){
//				//Generate number between 0-PropertyInverseFunct size
//				int index = (int)(Math.random()*(PropertyInverseFunct.size()-1));
//				model.add(SesameBuilder.sesameValueFactory.createURI(s.getObject().stringValue()), SesameBuilder.sesameValueFactory.createURI(PropertyInverseFunct.toArray()[index].toString()),s.getSubject(),s.getContext());
//				//need to change subject in sesamemodel
//	    	}
////			else{
////				model.add(s);
////			}
//	    }
//	    else{
//			try {
//				throw new InvalidTransformation();
//			} catch (InvalidTransformation e) {
//				e.printStackTrace();
//			}finally{
//				return model;
//			}
//		}
//	return model;
	}

}


text:
npm update
npm install
npm start


text:
// Copyright (c) 2013-2016 Jae-jun Kang
// See the file LICENSE for details.

using System;
using System.Collections;

namespace x2
{
    /// <summary>
    /// Abstract base class for concrete event handlers.
    /// </summary>
    public abstract class Handler
    {
        /// <summary>
        /// Gets the underlying delegate of this handler.
        /// </summary>
        public abstract Delegate Action { get; }

        /// <summary>
        /// Determines whether the specified object is equal to the current
        /// object.
        /// </summary>
        public override bool Equals(object obj)
        {
            if (Object.ReferenceEquals(this, obj))
            {
                return true;
            }
            if (obj == null || GetType() != obj.GetType())
            {
                return false;
            }

            Handler other = (Handler)obj;
            return Action.Equals(other.Action);
        }

        /// <summary>
        /// Returns the hash code for the current object.
        /// </summary>
        public override int GetHashCode()
        {
            return Action.GetHashCode();
        }

        /// <summary>
        /// Invokes the underlying delegate of this handler with the specified
        /// event.
        /// </summary>
        public abstract void Invoke(Event e);
    }

    /// <summary>
    /// Represents a generic method handler.
    /// </summary>
    public class MethodHandler<T> : Handler
        where T : Event
    {
        protected readonly Action<T> action;

        public override Delegate Action { get { return action; } }

        public MethodHandler(Action<T> action)
        {
            this.action = action;
        }

        public override void Invoke(Event e)
        {
            action((T)e);
        }
    }

    /// <summary>
    /// Represents a coroutine method handler.
    /// </summary>
    public class CoroutineHandler<T> : Handler
        where T : Event
    {
        protected readonly Func<Coroutine, T, IEnumerator> action;

        public override Delegate Action { get { return action; } }

        public CoroutineHandler(Func<Coroutine, T, IEnumerator> action)
        {
            this.action = action;
        }

        public override void Invoke(Event e)
        {
            Coroutine coroutine = new Coroutine();
            coroutine.Start(action(coroutine, (T)e));
        }
    }

    /// <summary>
    /// Represents a conditional generic method handler.
    /// </summary>
    public class ConditionalMethodHandler<T> : MethodHandler<T>
        where T : Event
    {
        private readonly Predicate<T> predicate;

        public ConditionalMethodHandler(Action<T> action, Predicate<T> predicate)
            : base(action)
        {
            this.predicate = predicate;
        }

        public override void Invoke(Event e)
        {
            if (predicate((T)e))
            {
                base.Invoke((T)e);
            }
        }
    }

    /// <summary>
    /// Represents a conditional coroutine method handler.
    /// </summary>
    public class ConditionalCoroutineHandler<T> : CoroutineHandler<T>
        where T : Event
    {
        private readonly Predicate<T> predicate;

        public ConditionalCoroutineHandler(Func<Coroutine, T, IEnumerator> action,
            Predicate<T> predicate) : base(action)
        {
            this.predicate = predicate;
        }

        public override void Invoke(Event e)
        {
            if (predicate((T)e))
            {
                base.Invoke((T)e);
            }
        }
    }
}


text:
export const API_URL = 'http://www.bestridaapp.com/';
export const CLIENT_ID = 9169;


text:
/** @internal
 ** @file     KDForest.c
 ** @brief    KDForest MEX utilities
 ** @author   Andrea Vedaldi
 **/

#include "mex.h"
#include <mexutils.h>
#include <vl/kdtree.h>

/** ------------------------------------------------------------------
 ** @interan@brief Hepler function
 ** @param tree KDForest object to process
 ** @param nodeIndex index of the KDForest node to start from
 ** @param numNodesToVisit total number of nodes to visit.
 **
 ** The function visits in depth first order the tree's nodes starting
 ** from the root, restoring the node parent pointers.
 **
 ** It also chekcs for tree consistency, aborting the MEX file in case
 ** of inconsistencies. Loops are detected by counting how many nodes
 ** have been visited so far compared to the total number of nodes in
 ** the tree.
 **/

void
restore_parent_recursively (VlKDTree * tree, int nodeIndex, int * numNodesToVisit)
{
  VlKDTreeNode * node = tree->nodes + nodeIndex ;
  int lowerChild = node->lowerChild ;
  int upperChild = node->upperChild ;

  if (*numNodesToVisit == 0) {
    vlmxError (vlmxErrInconsistentData,
              "FOREST.TREES has an inconsitsent tree structure.") ;
  }

  *numNodesToVisit -= 1 ;

  if (lowerChild >= 0) {
    VlKDTreeNode * child = tree->nodes + lowerChild ;
    child->parent = nodeIndex ;
    restore_parent_recursively (tree, lowerChild, numNodesToVisit) ;
  }
  if (upperChild >= 0) {
    VlKDTreeNode * child = tree->nodes + upperChild ;
    child->parent = nodeIndex ;
    restore_parent_recursively (tree, upperChild, numNodesToVisit) ;
  }
}

/** ------------------------------------------------------------------
 ** @internal @brief Builds a MEX array representing a VlKDForest object
 ** @param tree object to convert.
 ** @return MEX representation of the tree.
 **
 ** The KDForest object returned encapsulates the data (no copies are made).
 ** Recall that a KDForest object by design does not own the data.
 **
 ** In case of error, the function aborts by calling ::mxErrMsgTxt.
 **/

static mxArray *
new_array_from_kdforest (VlKDForest const * forest)
{
  vl_uindex ti ;
  mwSize dims [] = {1,1} ;
  mwSize treeDims [] = {1,0} ;
  char const * fieldNames [] = {
    "dimension",
    "numData",
    "trees"
  } ;
  char const * treeFieldNames [] = {
    "nodes",
    "dataIndex"
  } ;
  char const * nodesFieldNames [] = {
    "lowerChild",
    "upperChild",
    "splitDimension",
    "splitThreshold"
  } ;
  mxArray * forest_array ;
  mxArray * trees_array ;

  treeDims [0] = 1 ;
  treeDims [1] = forest->numTrees ;
  trees_array = mxCreateStructArray (2, treeDims,
                                     sizeof(treeFieldNames) / sizeof(treeFieldNames[0]),
                                     treeFieldNames) ;

  /*
    FOREST.NUMDIMENSIONS
    FOREST.NUMDATA
   */

  forest_array = mxCreateStructArray (2, dims, sizeof(fieldNames) / sizeof(fieldNames[0]), fieldNames) ;
  mxSetField (forest_array, 0, "dimension", vlmxCreatePlainScalar (forest->dimension)) ;
  mxSetField (forest_array, 0, "numData", vlmxCreatePlainScalar (forest->numData)) ;
  mxSetField (forest_array, 0, "trees", trees_array) ;

  for (ti = 0 ; ti < forest->numTrees ; ++ ti) {
    VlKDTree * tree = forest->trees[ti] ;
    mxArray * nodes_array = mxCreateStructArray (2, dims, sizeof(nodesFieldNames) / sizeof(nodesFieldNames[0]), nodesFieldNames) ;
    mxArray * dataIndex_array = mxCreateNumericMatrix (1, forest->numData, mxUINT32_CLASS, mxREAL) ;
    mxSetField (trees_array, ti, "nodes", nodes_array) ;
    mxSetField (trees_array, ti, "dataIndex", dataIndex_array) ;

    /*
     FOREST.TREES.NODES.LOWERCHILD
     FOREST.TREES.NODES.UPPERCHILD
     FOREST.TREES.NODES.SPLITDIMENSION
     FOREST.TREES.NODES.SPLITTHRESHOLD
     */
    {
      mxArray * lowerChild_array = mxCreateNumericMatrix (1, tree->numUsedNodes, mxINT32_CLASS, mxREAL) ;
      mxArray * upperChild_array = mxCreateNumericMatrix (1, tree->numUsedNodes, mxINT32_CLASS, mxREAL) ;
      mxArray * splitDimension_array = mxCreateNumericMatrix (1, tree->numUsedNodes, mxUINT32_CLASS, mxREAL) ;
      mxArray * splitThreshold_array = mxCreateNumericMatrix (1, tree->numUsedNodes, mxDOUBLE_CLASS, mxREAL) ;

      vl_uint32 * upperChild = mxGetData (upperChild_array) ;
      vl_uint32 * lowerChild = mxGetData (lowerChild_array) ;
      vl_uint32 * splitDimension = mxGetData (splitDimension_array) ;
      double * splitThreshold = mxGetData (splitThreshold_array) ;
      vl_uindex ni ;

      for (ni = 0 ; ni < tree -> numUsedNodes ; ++ ni) {
        VlKDTreeNode const * node = tree -> nodes + ni ;
        int a = node->upperChild ;
        int b = node->lowerChild ;
        upperChild [ni] = (a>=0) ? a + 1 : a ;
        lowerChild [ni] = (b>=0) ? b + 1 : b ;
        splitDimension [ni] = node->splitDimension + 1 ;
        splitThreshold [ni] = node->splitThreshold ;
      }
      mxSetField (nodes_array, 0, "lowerChild", lowerChild_array) ;
      mxSetField (nodes_array, 0, "upperChild", upperChild_array) ;
      mxSetField (nodes_array, 0, "splitDimension", splitDimension_array) ;
      mxSetField (nodes_array, 0, "splitThreshold", splitThreshold_array) ;
    }

    /* FOREST.TREEE.DATAINDEX */
    {
      vl_uint32 * dataIndex = mxGetData (dataIndex_array) ;
      vl_uindex di ;
      for (di = 0 ; di < forest->numData ; ++ di) {
        dataIndex [di] = forest->trees[ti]->dataIndex[di].index + 1 ;
      }
    }
  }
  return forest_array  ;
}

/** ------------------------------------------------------------------
 ** @internal @brief Builds a VlKDForest from MEX parameters
 ** @param forest_array MEX array representing the kd-tree
 ** @param data_array MEX array representing the kd-tree data
 ** @return KDForest object instance.
 **
 ** The KDForest object returned encapsulates the data (no copies are made).
 ** Recall that a KDForest object by design does not own the data.
 **
 ** In case of error, the function aborts by calling ::mxErrMsgTxt.
 **/

static VlKDForest *
new_kdforest_from_array (mxArray const * forest_array, mxArray const * data_array)
{
  VlKDForest * forest ;
  mxArray const * dimension_array ;
  mxArray const * numData_array ;
  mxArray const * trees_array ;
  mxArray const * nodes_array ;
  mxArray const * dataIndex_array ;
  mxArray const * lowerChild_array ;
  mxArray const * upperChild_array ;
  mxArray const * splitDimension_array ;
  mxArray const * splitThreshold_array ;

  vl_int32 const * lowerChild ;
  vl_int32 const * upperChild ;
  vl_uint32 const * splitDimension ;
  double const * splitThreshold ;

  vl_uindex ti ;
  int unsigned dimension ;
  vl_size numData ;
  vl_size numUsedNodes ;
  vl_size numTrees ;

  vl_type dataType ;

  /*
    FOREST.NUMDIMENSIONS
    FOREST.NUMDATA
    FOREST.DATA
    FOREST.TREES
   */
  if (! mxIsStruct (forest_array) ||
      mxGetNumberOfElements (forest_array) != 1) {
    vlmxError (vlmxErrInconsistentData,
              "FOREST must be a 1 x 1 structure.") ;
  }
  dimension_array = mxGetField (forest_array, 0, "dimension") ;
  if (! dimension_array ||
      ! vlmxIsPlainScalar (dimension_array) ||
      (dimension = mxGetScalar (dimension_array)) < 1) {
    vlmxError(vlmxErrInconsistentData,
             "FOREST.NUMDIMENSIONS must be a poisitve integer.") ;
  }
  numData_array = mxGetField (forest_array, 0, "numData") ;
  if (! numData_array ||
      ! vlmxIsPlainScalar (numData_array) ||
      (numData = mxGetScalar (numData_array)) < 1) {
    vlmxError(vlmxErrInconsistentData,
             "FOREST.NUMDATA must be a poisitve integer.") ;
  }
  trees_array = mxGetField (forest_array, 0, "trees") ;
  if (! mxIsStruct (trees_array)) {
    vlmxError(vlmxErrInconsistentData,
             "FOREST.TREES must be a structure array.") ;
  }
  numTrees = mxGetNumberOfElements (trees_array) ;
  if (numTrees < 1) {
    vlmxError(vlmxErrInconsistentData,
             "FOREST.TREES must have at least one element.") ;
  }

  if (! vlmxIsMatrix (data_array, dimension, numData)) {
    vlmxError(vlmxErrInconsistentData,
             "DATA dimensions are not compatible with TREE.") ;
  }
  if (! vlmxIsReal (data_array)) {
    vlmxError(vlmxErrInvalidArgument,
             "DATA must be real.") ;
  }
  switch (mxGetClassID (data_array)) {
    case mxSINGLE_CLASS : dataType = VL_TYPE_FLOAT ; break ;
    case mxDOUBLE_CLASS : dataType = VL_TYPE_DOUBLE ; break ;
    default :
      vlmxError(vlmxErrInvalidArgument,
               "DATA must be either SINGLE or DOUBLE.") ;
  }

  forest = vl_kdforest_new (dataType, dimension, numTrees) ;
  forest->numData = numData ;
  forest->trees = vl_malloc (sizeof(VlKDTree*) * numTrees) ;
  forest->data = mxGetData (data_array) ;

  /*
   FOREST.TREES.NODES
   FOREST.TREES.DATAINDEX
   */
  for (ti = 0 ; ti < numTrees ; ++ ti) {
    VlKDTree * tree = vl_malloc (sizeof(VlKDTree)) ;
    nodes_array = mxGetField (trees_array, ti, "nodes") ;
    dataIndex_array = mxGetField (trees_array, ti, "dataIndex") ;

    if (! nodes_array ||
        ! mxIsStruct (nodes_array)) {
      vlmxError(vlmxErrInconsistentData,
               "FOREST.TREES(%d).NODES must be a struct array.", ti+1) ;
    }

    /*
     FOREST.TREES.NODES.LOWERCHILD
     FOREST.TREES.NODES.UPPERCHILD
     FOREST.TREES.NODES.SPLITTHRESHOLD
     FOREST.TREES.NODES.SPLITDIMENSION
     */

    lowerChild_array = mxGetField (nodes_array, 0, "lowerChild") ;
    upperChild_array = mxGetField (nodes_array, 0, "upperChild") ;
    splitDimension_array = mxGetField (nodes_array, 0, "splitDimension") ;
    splitThreshold_array = mxGetField (nodes_array, 0, "splitThreshold") ;

    numUsedNodes = mxGetN (lowerChild_array) ;

    if (! lowerChild_array ||
        ! vlmxIsMatrix (lowerChild_array, 1, numUsedNodes) ||
        mxGetClassID (lowerChild_array) != mxINT32_CLASS) {
      vlmxError(vlmxErrInconsistentData,
               "FOREST.TREES(%d).NODES.LOWERCHILD must be a 1 x NUMNODES INT32 array.",ti+1) ;
    }
    if (! upperChild_array ||
        ! vlmxIsMatrix (upperChild_array, 1, numUsedNodes) ||
        mxGetClassID (upperChild_array) != mxINT32_CLASS) {
      vlmxError(vlmxErrInconsistentData,
               "FOREST.TREES(%d).NODES.UPPERCHILD must be a 1 x NUMNODES INT32 array.",ti+1) ;
    }
    if (! splitDimension_array ||
        ! vlmxIsMatrix (splitDimension_array, 1, numUsedNodes) ||
        mxGetClassID (splitDimension_array) != mxUINT32_CLASS) {
      vlmxError(vlmxErrInconsistentData,
               "FOREST.TREES(%d).NODES.SPLITDIMENSION must be a 1 x NUMNODES UINT32 array",ti+1) ;
    }
    if (! splitThreshold_array ||
        ! vlmxIsMatrix (splitThreshold_array, 1, numUsedNodes) ||
        mxGetClassID (splitThreshold_array) != mxDOUBLE_CLASS) {
      vlmxError(vlmxErrInconsistentData,
               "FOREST.TREES(%d).NODES.SPLITTHRESHOLD must be a 1 x NUMNODES DOUBLE array",ti+1) ;
    }
    lowerChild = (vl_int32*) mxGetData (lowerChild_array) ;
    upperChild = (vl_int32*) mxGetData (upperChild_array) ;
    splitDimension = (vl_uint32*) mxGetData (splitDimension_array) ;
    splitThreshold = (double*) mxGetData (splitThreshold_array) ;

    if (! dataIndex_array ||
        ! vlmxIsMatrix (dataIndex_array, 1, numData) ||
        mxGetClassID (dataIndex_array) != mxUINT32_CLASS) {
      vlmxError(vlmxErrInconsistentData,
               "FOREST.TREES(%d).DATAINDEX must be a 1 x NUMDATA array of class UINT32.",ti+1) ;
    }

    tree->numAllocatedNodes = numUsedNodes ;
    tree->numUsedNodes = numUsedNodes ;
    tree->nodes = vl_malloc (sizeof(VlKDTreeNode) * numUsedNodes) ;
    tree->dataIndex = vl_malloc (sizeof(VlKDTreeDataIndexEntry) * numData) ;

    {
      vl_uindex ni ;
      for (ni = 0 ; ni < numUsedNodes ; ++ ni) {
        vl_int32 lc = lowerChild [ni] ;
        vl_int32 uc = upperChild [ni] ;
        vl_uint32 d = splitDimension [ni] ;

        if (uc < - (signed)numData - 1 || uc > (signed)numUsedNodes) {
          vlmxError (vlmxErrInconsistentData,
                    "TREE.NODES.UPPERCHILD(%d)=%d out of bounds",
                    ni+1,uc) ;
        }
        if (lc < - (signed)numData || lc > (signed)numUsedNodes) {
          vlmxError (vlmxErrInconsistentData,
                    "TREE.NODES.LOWERCHILD(%d)=%d out of bounds",
                    ni+1,lc) ;
        }
        if (d > dimension) {
          vlmxError (vlmxErrInconsistentData,
                    "TREE.NODES.SPLITDIMENSION(%d)=%d out of bounds",
                    ni+1,d) ;
        }

        tree->nodes[ni].parent = 0 ;
        tree->nodes[ni].upperChild = (uc >= 1) ? uc-1 : uc ;
        tree->nodes[ni].lowerChild = (lc >= 1) ? lc-1 : lc ;
        tree->nodes[ni].splitDimension = d - 1 ;
        tree->nodes[ni].splitThreshold = splitThreshold[ni] ;
      }
    }

    {
      vl_uindex di ;
      vl_uint32 * dataIndex = mxGetData (dataIndex_array) ;
      for (di = 0 ; di < numData ; ++ di) {
        tree->dataIndex[di].index = dataIndex [di] - 1 ;
      }
    }

    {
      int numNodesToVisit = tree->numUsedNodes ;
      restore_parent_recursively (tree, 0, &numNodesToVisit) ;
      if (numNodesToVisit != 0) {
        vlmxError (vlmxErrInconsistentData,
                  "TREE has an inconsitsent tree structure.") ;
      }
    }

    forest->trees[ti] = tree ;
  }
  return forest ;
}


text:
#ifndef ALKES_TESTDRIVER_GRAPHICS2D_TEST_DRIVER_H_INCLUDED_
#define ALKES_TESTDRIVER_GRAPHICS2D_TEST_DRIVER_H_INCLUDED_

#include "alkes/testdriver/GraphicsTestDriver.h"

namespace alkes {

class AL_TD_EXPORT Graphics2DTestDriver
    : public GraphicsTestDriver
{
public:
    Graphics2DTestDriver(IGraphics2DDevice* device);
    virtual ~Graphics2DTestDriver();

    void testDefaultRenderTarget2D();
    void testCreateDecoderFactory();

private:
    intrusive_ptr<IGraphics2DDevice> device2d_;
};

}

#endif


text:
package org.araneaframework.uilib.list.util;

import java.text.MessageFormat;
import java.util.MissingResourceException;
import org.araneaframework.framework.LocalizationContext;
import org.araneaframework.uilib.form.Control;
import org.araneaframework.uilib.form.Data;
import org.araneaframework.uilib.form.FormElement;
import org.araneaframework.uilib.list.structure.filter.FilterContext;
import org.araneaframework.uilib.support.UiLibMessages;
import org.araneaframework.uilib.util.Event;

/**
 * List filters form utils.
 *
 * @author Rein Raudjärv (rein@araneaframework.org)
 */
public class FilterFormUtil {

  public static final String TEMPORARY_LABEL = "";

  public static final String DO_NOT_LOCALIZE_PREFIX = "#";

  @SuppressWarnings("unchecked")
  public static <C, D> FormElement<C, D> createElement(FilterContext ctx, String id) {
    Class<?> type = ctx.getFieldType(id);
    FormElement<C, D> result = (FormElement<C, D>) FormUtil.createElement(TEMPORARY_LABEL,
        FormUtil.createControl(type), FormUtil.createData(type), false);
    setLabel(ctx, result, id);
    return result;
  }

  @SuppressWarnings("unchecked")
  public static <C, D> FormElement<C, D> createElement(FilterContext ctx, String id, Control<C> control) {
    FormElement<C, D> result = (FormElement<C, D>) FormUtil.createElement(TEMPORARY_LABEL, control, FormUtil.createData(ctx
        .getFieldType(id)), false);
    setLabel(ctx, result, id);
    return result;
  }

  public static <C, D> FormElement<C, D> createElement(FilterContext ctx, String id, Control<C> control, Data<D> data) {
    FormElement<C, D> result = FormUtil.createElement(TEMPORARY_LABEL, control, data, false);
    setLabel(ctx, result, id);
    return result;
  }

  public static String getLabelForLowField(LocalizationContext loc, String fieldLabelId) {
    return DO_NOT_LOCALIZE_PREFIX + format(localize(loc, UiLibMessages.LOW_OF), localize(loc, fieldLabelId));
  }

  public static String getLabelForHighField(LocalizationContext loc, String fieldLabelId) {
    return DO_NOT_LOCALIZE_PREFIX + format(localize(loc, UiLibMessages.HIGH_OF), localize(loc, fieldLabelId));
  }

  private static String format(String pattern, String arg) {
    return MessageFormat.format(pattern, new Object[] { arg });
  }

  private static String localize(LocalizationContext loc, String key) {
    try {
      return loc.localize(key);
    } catch (MissingResourceException e) {
      return key;
    }
  }

  public static void setLabel(final FilterContext ctx, final FormElement<?, ?> formElement, final String fieldId) {
    ctx.addInitEvent(new Event() {

      public void run() {
        formElement.setLabel(ctx.getFieldLabel(fieldId));
      }
    });
  }
}


text:
RES=0

mkdir -p /zap/wrk/output

echo "Automation Framework context tests"
echo

# Automation Framework context tests
echo "Running the tests..."
/zap/zap.sh -cmd -script /zap/wrk/configs/scripts/af_context_tests.js -config "dirs=/zap/wrk/configs/scripts"

# Diff the originals with the generated files

cd /zap/wrk/configs/plans/contexts/

for file in *.context
do
	echo
	echo "Context: $file"
	if [ ! -f /zap/wrk/output/$file ]
	then
	    echo "ERROR: /zap/wrk/output/$file not generated"
		RES=1
	else
		# Nasty sed expression to remove the user IDs which will change each time
		DIFF=$(diff <(sed 's/user>.*;/user>x;/g' $file) <(sed 's/user>.*;/user>x;/g' /zap/wrk/output/$file))
		if [ "$DIFF" != "" ]
		then
		    echo "ERROR: differences:"
		    echo "$DIFF"
			RES=1
		else
	    	echo "PASS"
		fi
	fi
done

# Tidy up
rm ~/.ZAP_D/config.xml

echo "End result: $RES"
exit $RES


text:
"""
    MoinMoin - MoinMoin.macro StatsChart tested

    @copyright: 2008 MoinMoin:ReimarBauer
    @license: GNU GPL, see COPYING for details.
"""
import os

from MoinMoin import caching, macro
from MoinMoin.logfile import eventlog
from MoinMoin.PageEditor import PageEditor
from MoinMoin.Page import Page
from MoinMoin._tests import become_trusted, create_page, make_macro, nuke_page

class TestStatsCharts:
    """StartsChart: testing StatsChart macro """
    pagename = u'AutoCreatedMoinMoinTemporaryTestPageStatsChart'

    def setup_class(self):
        become_trusted(self.request)
        self.page = create_page(self.request, self.pagename, u"Foo!")
        # clean page scope cache entries
        for key in ['text_html', 'pagelinks', ]:
            caching.CacheEntry(self.request, self.page, key, scope='item').remove()

    def teardown_class(self):
        nuke_page(self.request, self.pagename)

    def _test_macro(self, name, args):
        m = make_macro(self.request, self.page)
        return m.execute(name, args)

    def testStatsChart_useragents(self):
        """ macro StatsChart useragents test: 'tests useragents' and clean page scope cache """
        result = self._test_macro(u'StatsChart', u'useragents')
        expected = u'<form action="/AutoCreatedMoinMoinTemporaryTestPageStatsChart" method="GET"'
        assert expected in result

    def testStatsChart_hitcounts(self):
        """ macro StatsChart hitcounts test: 'tests hitcounts' and clean page scope cache  """
        result = self._test_macro(u'StatsChart', u'hitcounts')
        expected = u'<form action="/AutoCreatedMoinMoinTemporaryTestPageStatsChart" method="GET"'
        assert expected in result

    def testStatsChart_languages(self):
        """ macro StatsChart languages test: 'tests languages' and clean page scope cache  """
        result = self._test_macro(u'StatsChart', u'hitcounts')
        expected = u'<form action="/AutoCreatedMoinMoinTemporaryTestPageStatsChart" method="GET"'
        assert expected in result

coverage_modules = ['MoinMoin.stats']


text:
This simple flask app parses the ESPN BottomLine score feed and returns JSON right to your doorstep. There are certainly more sophisticated and robust sports data APIs available, but this has the advantage of being simple, free, and easy to modify for whatever you're working on. You can see a working version of the app at [http://scorehub.herokuapp.com](http://scorehub.herokuapp.com).

## Endpoints
#### Current
```
/ping
```

If the app is working, ```/ping``` returns a 200 response. Nothing more, nothing less.

```
/ncaaf
```

Returns a json response object of this week's NCAA DIV-I football scores. No historical data is available.

#### Planned
```/mlb```: MLB score data

```/nba```: NBA score data

```/nfl```: NFL score data

```/ncaab```: NCAA Basketball score data

## Deploying
This code is MIT licensed, so you can do pretty much whatever you want with it. Clone this repository to your local machine. Then, from the application directory, run ```heroku create your-app-name``` and ```git push heroku master```.

The final step is to enable a caching solution so that results are cached. I've used memcachier (```heroku addons:add memcachier```) for my own deploy, but I've included the flask-heroku-cacheify extension, so you should be able to use just about any other heroku caching add-on with no additional configuration.

## Version History

##### Current Version 0.1.0
- NCAAF and PING endpoints are functional
- Results are returned as json objects
- App can easily be deployed to Heroku without configuration
- Results are cached for 5 minutes. Caching does not account for time-delay of results.


text:
import Core from '_core.js';
import Item from 'components/global-nav/top-nav/project-account-switcher/_item/item';
import Icon from 'basics/icon/icon';
import Template from './target.html';
import './target.scss';

/**
 * Creates an Target
 *
 * @class
 */

class Target extends Core {
  constructor(options) {
    super(options);
    this._render(Template, options);
    this.item = new Item(options);
  }

  _componentDidMount() {
    this.mountPartialToComment('ITEM', this.item);
    this._setIcon();
  }

  setLabel(label) {
    this.item.setLabel(label);
  }

  setImage(imageUrl) {
    this.item.setImage(imageUrl);
  }

  setType(type) {
    this.item._setType(type);
  }

  onClick(fn) {
    return this._attachListener('click', this.el, this.el, fn);
  }

  addCaret() {
    this._findDOMEl(
      '.hig__global-nav__top-nav__project-account-switcher__target__caret',
      this.el
    ).classList.remove(
      'hig__global-nav__top-nav__project-account-switcher__target__caret--hide'
    );
  }

  removeCaret() {
    this._findDOMEl(
      '.hig__global-nav__top-nav__project-account-switcher__target__caret',
      this.el
    ).classList.add(
      'hig__global-nav__top-nav__project-account-switcher__target__caret--hide'
    );
  }

  _setIcon() {
    const mountEl = this._findDOMEl('.hig__global-nav__top-nav__project-account-switcher__target__caret', this.el);
    this._findOrCreateIconComponent(mountEl).setNameOrSVG('caret');
  }

  _findOrCreateIconComponent(mountElOrSelector, name = 'icon') {
    if (this[name]) {
      return this[name];
    }
    this[name] = new Icon({});
    this[name].mount(mountElOrSelector);
    return this[name];
  }
}

Target._interface = {
  methods: {
    setLabel: {},
    setImage: {},
    setType: {},
    onClick: {},
    addCaret: {},
    removeCaret: {}
  }
};
Target._defaults = {};
Target._partials = {};

export default Target;


text:
category: classicos
title: 'Aristófanes (2004)'

layout: nil
---

## Aristófanes (2004). As rãs. Coimbra: FESTEA Tema Clássico.

Palavras-chave: Aristófanes. Rãs.


text:
package example.cloudplugs.rest;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.cloudplugs.rest.*;
import com.cloudplugs.rest.android.RestClient;
import example.cloudplugs.R;

/**
 * @brief Basic Activity example.
 * Publish a random number to a predefined channel each time the button is pressed.
 */
public class BasicExample extends Activity implements RestCallback
{
	// TODO: put here your prototype PlugID
	private final static String AUTH_PLUGID = "dev-XXXXXXXXXXXXXXXXXXXXXXXX";
	// TODO: put here your password
	private final static String AUTH_PASS = "password";
	// leave true for using your account password (or set it to false for using the specific prototype password)
	private final static boolean AUTH_MASTER = true;

	// the channel name used for publishing data
	private final static String CHANNEL = "temperature";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.basic_example);
		handler = new Handler();

		// this text view will contain logged messages
		textView = (TextView)findViewById(R.id.textView);
		textView.setMovementMethod(new ScrollingMovementMethod());	// enable text view scrolling

		// the button to press for publishing data
		button = (Button)findViewById(R.id.button);
		button.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				publishData();
			}
		});

		// create the main RestClient
		RestClient.create(this, new RestClient.Listener() {
			@Override
			public void onReady(RestClient rc) {
				restClient  = rc;
				restManager = rc.getManager(new Opts().setAuth(AUTH_PLUGID, AUTH_PASS, AUTH_MASTER));
				log("==== CloudPlugs RestClient is ready");
			}
		});
	}

	@Override
	public void onDestroy() {
		// application is quitting: stop the RestClient and release all associated resources
		if(restClient != null) {
			restClient.destroy();
			restClient  = null;
			restManager = null;
		}
		super.onDestroy();
	}

	private void publishData() {
		// check if the RestClient instance has been created
		if(restManager != null) {
			// the RestClient has been created: let's publish data
			double data = getDataToPublish();
			int id = restManager.execPublishData(CHANNEL, data, null, this);
			log("<<<< [ request "+id+" ] publishing data to channel '"+CHANNEL+"': "+data);
		} else {
			// the RestClient instance has not been created yet
			log("**** Please wait until RestClient becomes ready");
		}
	}

	private void log(final String msg) {
		// log the message to the text view and to the standard Android log system
		Log.d(TAG, msg);
		handler.post(new Runnable() {
			@Override
			public void run() {
				textView.append(msg + "\n");
			}
		});
	}

	// retrieve the data to publish in the cloud
	private static double getDataToPublish() {
		return Math.random() * 100;
	}

	/**
	 * Implementation of com.cloudplugs.rest.RestCallback .
	 * It will be automatically called after each executed request.
	 * @param request the generated request
	 * @param response the received response from the server
	 */
	@Override
	public void on(Request request, Response response) {
		// just log the result
		String state = null;
		if(!response.isCompleted())   state = "interrupted";
		else if(response.isSuccess()) state = "successful";
		else if(response.isPartial()) state = "partially completed";
		else if(response.isFailed())  state = "failed";
		log(">>>> [ request " + request.getId() + " ] " + state + ", response is: " + response);
	}

	private RestClient  restClient  = null;
	private RestManager restManager = null;

	private Handler  handler;
	private TextView textView;
	private Button   button;

	private static final String TAG = BasicExample.class.getSimpleName();
}


text:
package org.mrgeo.hdfs.partitioners;

import org.apache.hadoop.conf.Configuration;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.mrgeo.core.Defs;
import org.mrgeo.data.DataProviderFactory;
import org.mrgeo.data.DataProviderFactory.AccessMode;
import org.mrgeo.data.KVIterator;
import org.mrgeo.data.image.MrsImageDataProvider;
import org.mrgeo.data.tile.MrsTileReader;
import org.mrgeo.data.tile.TileIdWritable;
import org.mrgeo.junit.UnitTest;
import org.mrgeo.utils.HadoopUtils;

import java.awt.image.Raster;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.Properties;

@SuppressWarnings("static-method")
public class TileIdPartitionerTest {
	// this one has four partitions
	String allOnesImage = Defs.CWD + "/" + Defs.INPUT + "all-ones/10";

	// this one has only one partition
	String smallElevationImage = Defs.CWD + "/" + Defs.INPUT + "small-elevation";

	MrsTileReader<Raster> reader;

	@Before
	public void setUp() throws IOException
	{
	  MrsImageDataProvider provider = DataProviderFactory.getMrsImageDataProvider(smallElevationImage,
	      AccessMode.READ, (Properties)null);
		reader = provider.getMrsTileReader(10);
	}

	@After
	public void tearDown()
	{
		reader.close();
	}

	@Test
	@Category(UnitTest.class)
	public void testNonExistentSplitFile() throws URISyntaxException
	{
		File file = new File(new java.net.URI(smallElevationImage));
		boolean imageExists = file.exists();
		Assert.assertEquals(true, imageExists);

		// Make sure neither splits file exists in the source...
		String splitPath = "file://" + file.getAbsolutePath() + "/splits.txt";
		File splitFile = new File(splitPath);
		boolean splitExists = splitFile.exists();
		Assert.assertEquals(false, splitExists);

    splitPath = "file://" + file.getAbsolutePath() + "/splits";
    splitFile = new File(splitPath);
    splitExists = splitFile.exists();
    Assert.assertEquals(false, splitExists);

		int numEntries = read(Long.MIN_VALUE, Long.MAX_VALUE);
		Assert.assertEquals(numEntries,12);
	}

	@Test
	@Category(UnitTest.class)
	public void testFindPartition() {
		// tests to see if we have two partitions - 10 and 20, then keys 1, 10, 11, 20, 21 are
		// assigned to partitions 0, 0, 1, 1, and 2
		// this covers all cases of keys on the split points, between split points, etc.

		// start with two partitions
		TileIdWritable[] array = new TileIdWritable[]{new TileIdWritable(10),new TileIdWritable(20)};

		// left extreme is assigned to 0
		Assert.assertEquals(0, findPartition(new TileIdWritable(1),array));

		// on the first split point is assigned to 0
		Assert.assertEquals(0, findPartition(new TileIdWritable(10),array));

		// between two split points is assigned to 1
		Assert.assertEquals(1, findPartition(new TileIdWritable(11),array));

		// on the second split point is assigned to 1
		Assert.assertEquals(1, findPartition(new TileIdWritable(20),array));

		// right extreme is assigned to 2
		Assert.assertEquals(2, findPartition(new TileIdWritable(21),array));
	}

	@Test
	@Category(UnitTest.class)
	public void testSetSplitFileWithoutScheme() throws URISyntaxException {
		// no file:// scheme in the path
	  java.net.URI u = new java.net.URI(allOnesImage + "/splits");
		String splitFilePath = u.getPath();
		final int numSplits = 4;

		TileIdPartitioner<?, ?> partitioner = new TileIdPartitioner<Object, Object>();
		Configuration conf = HadoopUtils.createConfiguration();
		partitioner.setConf(conf);
		TileIdPartitioner.setSplitFile(splitFilePath, conf);

		TileIdWritable key = new TileIdWritable();

		// without scheme, getPartition will end up defaulting to empty splitPointArray, which
		// would always result in the partition=0, obviously incorrectly
		key.set(210835);
		Assert.assertEquals(0, partitioner.getPartition(key, null, numSplits));
	}
	@Test
	@Category(UnitTest.class)
	public void testSetSplitFileWithScheme() throws URISyntaxException {
		// has three splits, so four part directories
		final int numSplits = 3;
		String splitFilePath = allOnesImage + "/splits";
		java.net.URI u = new java.net.URI(splitFilePath);
		File splitFile = new File(u);
		boolean splitFileExists = splitFile.exists();
		Assert.assertEquals(true, splitFileExists);

		final String splitFilePathWithScheme = "file://" + splitFile.getAbsolutePath();

		TileIdPartitioner<?, ?> partitioner = new TileIdPartitioner<Object, Object>();
		Configuration conf = HadoopUtils.createConfiguration();
		partitioner.setConf(conf);
		TileIdPartitioner.setSplitFile(splitFilePathWithScheme, conf);

		TileIdWritable key = new TileIdWritable();

		key.set(208787);
		Assert.assertEquals(0, partitioner.getPartition(key, null, numSplits));

		key.set(208789);
		Assert.assertEquals(0, partitioner.getPartition(key, null, numSplits));

		key.set(209811);
		Assert.assertEquals(1, partitioner.getPartition(key, null, numSplits));

		key.set(210835);
		Assert.assertEquals(2, partitioner.getPartition(key, null, numSplits));

		key.set(211859);
		Assert.assertEquals(3, partitioner.getPartition(key, null, numSplits));

		// beyond image, but still in the last partition
		key.set(211862);
		Assert.assertEquals(3, partitioner.getPartition(key, null, numSplits));

	}

	private static int findPartition(TileIdWritable key, TileIdWritable[] array) {
		// find the bin for the range, and guarantee it is positive
		int index = Arrays.binarySearch(array, key);
		index = index < 0 ? (index + 1) * -1 : index;

		return index;
	}

	private int read(long start, long end) {
		TileIdWritable startKey = new TileIdWritable(start);
		TileIdWritable endKey = new TileIdWritable(end);
		int numEntries = 0;

    KVIterator<TileIdWritable, Raster> iter = reader.get(startKey, endKey);

    while (iter.hasNext())
    {
      numEntries++;
      iter.next();
    }

		return numEntries;
	}
}


text:
'use strict';

/* global module: 0 */
// Wrapper for client interface to feathers-service-verify-reset

function VerifyReset(app) {
  // eslint-disable-line no-unused-vars
  if (!(this instanceof VerifyReset)) {
    return new VerifyReset(app);
  }

  var verifyReset = app.service('verifyReset');

  this.checkUnique = function (uniques, ownId, ifErrMsg, cb) {
    return verifyReset.create({
      action: 'checkUnique',
      value: uniques,
      ownId: ownId,
      meta: { noErrMsg: ifErrMsg }
    }, {}, cb);
  };

  this.resendVerifySignup = function (emailOrToken, notifierOptions, cb) {
    return verifyReset.create({
      action: 'resendVerifySignup',
      value: emailOrToken,
      notifierOptions: notifierOptions
    }, {}, cb);
  };

  this.verifySignupLong = function (token, cb) {
    return verifyReset.create({
      action: 'verifySignupLong',
      value: token
    }, {}, cb);
  };

  this.verifySignupShort = function (token, userFind, cb) {
    return verifyReset.create({
      action: 'verifySignupShort',
      value: { token: token, user: userFind }
    }, {}, cb);
  };

  this.sendResetPwd = function (email, notifierOptions, cb) {
    return verifyReset.create({
      action: 'sendResetPwd',
      value: email,
      notifierOptions: notifierOptions
    }, {}, cb);
  };

  this.resetPwdLong = function (token, password, cb) {
    return verifyReset.create({
      action: 'resetPwdLong',
      value: { token: token, password: password }
    }, {}, cb);
  };

  this.resetPwdShort = function (token, userFind, password, cb) {
    return verifyReset.create({
      action: 'resetPwdShort',
      value: { token: token, password: password, user: userFind }
    }, {}, cb);
  };

  this.passwordChange = function (oldPassword, password, user, cb) {
    return verifyReset.create({
      action: 'passwordChange',
      value: { oldPassword: oldPassword, password: password }
    }, { user: user }, cb);
  };

  this.emailChange = function (password, email, user, cb) {
    return verifyReset.create({
      action: 'emailChange',
      value: { password: password, email: email }
    }, { user: user }, cb);
  };

  this.checkResetLongTokenValid = function (token, cb) {
    return verifyReset.create({
      action: 'checkResetLongTokenValid',
      value: token
    }, {}, cb);
  };

  this.authenticate = function (email, password, cb) {
    var cbCalled = false;

    return app.authenticate({ type: 'local', email: email, password: password }).then(function (result) {
      var user = result.data;

      if (!user || !user.isVerified) {
        app.logout();
        return cb(new Error(user ? 'User\'s email is not verified.' : 'No user returned.'));
      }

      if (cb) {
        cbCalled = true;
        return cb(null, user);
      }

      return user;
    }).catch(function (err) {
      if (!cbCalled) {
        cb(err);
      }
    });
  };

  // backwards compatability
  this.unique = this.checkUnique;
  this.resend = this.resendVerifySignup;
  this.verifySignUp = this.verifySignupLong;
  this.sendResetPassword = this.sendResetPwd;
  this.saveResetPassword = this.resetPwdLong;
  this.changePassword = this.passwordChange;
  this.changeEmail = this.emailChange;
}

if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
  module.exports = VerifyReset;
}


text:
namespace map {

PickupTarget::PickupTarget( int32_t Id, int32_t typeId, int32_t contentId )
    : ITarget( Id )
    , mCursorId( Id )
    , mActorId( Id )
    , mTypeId( typeId )
    , mContentId( contentId )
    , mScene( Scene::Get() )
{

}

void PickupTarget::Update( double DeltaTime )
{

}

int32_t PickupTarget::GetCursorId() const
{
    return mCursorId;
}

int32_t PickupTarget::GetActorId() const
{
    return mActorId;
}

void PickupTarget::PutTarget( glm::vec2 position )
{
    std::auto_ptr<MapElement> mapElement( MapElementFactory::Get()( AutoId( "respawn_actor" ) ) );
    Opt<RespawnActorMapElement> spawnActor( static_cast<RespawnActorMapElement*>( mapElement.get() ) );
    spawnActor->GetInputNodeId( RespawnActorMapElement::SpawnNodeId() )( 1 );
    {
        int32_t componentId = AutoId( "position_component" );
        ComponentLoaderFactory& componentLoaderFactory = ComponentLoaderFactory::Get();
        std::auto_ptr<PropertyLoaderBase<Component> > compLoader = componentLoaderFactory( componentId );
        Opt<PositionComponentLoader> positionCompLoader( static_cast<PositionComponentLoader*>( compLoader.get() ) );
        positionCompLoader->Bind<double>( &PositionComponent::SetX, position.x );
        positionCompLoader->Bind<double>( &PositionComponent::SetY, position.y );
        spawnActor->AddComponentLoader( componentId, compLoader );
    }
    {
        int32_t componentId = AutoId( "pickup_collision_component" );
        ComponentLoaderFactory& componentLoaderFactory = ComponentLoaderFactory::Get();
        std::auto_ptr<PropertyLoaderBase<Component> > compLoader = componentLoaderFactory( componentId );
        Opt<PickupCollisionComponentLoader> pickupCompLoader( static_cast<PickupCollisionComponentLoader*>( compLoader.get() ) );
        pickupCompLoader->Bind<int32_t>( &PickupCollisionComponent::SetPickupContent, mContentId );
        pickupCompLoader->Bind<ItemType::Type>( &PickupCollisionComponent::SetItemType, ItemType::Get()( mTypeId ) );
        spawnActor->AddComponentLoader( componentId, compLoader );
    }
    spawnActor->SetActorID( EditorTargetSystem::Get()->GetTarget().GetActorId() );
    mapElement->SetIdentifier( EditorTargetSystem::Get()->GetNextUID() );
    spawnActor->SetSecsToRespawnOriginal( 15 );
    MapSystem::Get()->GetMapElementList().insert( Opt<MapElement>( mapElement.release() ) );
}

std::auto_ptr<Actor> PickupTarget::GetCursor()
{
    std::auto_ptr<Actor> pickup( ActorFactory::Get()( mCursorId ) );
    Opt<PickupCollisionComponent> pickupCC( pickup->Get<ICollisionComponent>() );
    pickupCC->SetPickupContent( mContentId );
    pickupCC->SetItemType( ItemType::Get()( mTypeId ) );
    return pickup;
}

} // namespace map