text:
/**
 * This class specifies the definition for a column inside a {@link Ext.grid.Grid}. It
 * encompasses both the grid header configuration as well as displaying data within the
 * grid itself.
 *
 * In general an array of column configurations will be passed to the grid:
 *
 *     @example
 *     Ext.create('Ext.data.Store', {
 *         storeId: 'employeeStore',
 *         fields: ['firstname', 'lastname', 'seniority', 'dep', 'hired'],
 *         data: [
 *             {firstname:"Michael", lastname:"Scott", seniority:7, dep:"Management", hired:"01/10/2004"},
 *             {firstname:"Dwight", lastname:"Schrute", seniority:2, dep:"Sales", hired:"04/01/2004"},
 *             {firstname:"Jim", lastname:"Halpert", seniority:3, dep:"Sales", hired:"02/22/2006"},
 *             {firstname:"Kevin", lastname:"Malone", seniority:4, dep:"Accounting", hired:"06/10/2007"},
 *             {firstname:"Angela", lastname:"Martin", seniority:5, dep:"Accounting", hired:"10/21/2008"}
 *         ]
 *     });
 *
 *     var grid = Ext.create('Ext.grid.Grid', {
 *         title: 'Column Demo',
 *         store: Ext.data.StoreManager.lookup('employeeStore'),
 *         columns: [
 *             {text: 'First Name',  dataIndex:'firstname'},
 *             {text: 'Last Name',  dataIndex:'lastname'},
 *             {text: 'Hired Month',  dataIndex:'hired', xtype:'datecolumn', format:'M'},
 *             {text: 'Department (Yrs)', xtype:'templatecolumn', tpl:'{dep} ({seniority})'}
 *         ],
 *         width: 400
 *     });
 *     Ext.ViewPort.add(grid);
 *
 * # Convenience Subclasses
 *
 * There are several column subclasses that provide default rendering for various data types
 *
 *  - {@link Ext.grid.column.Boolean}: Renders for boolean values
 *  - {@link Ext.grid.column.Date}: Renders for date values
 *  - {@link Ext.grid.column.Number}: Renders for numeric values
 *
 * For more information about configuring cell content, see {@link Ext.grid.Grid}.
 *
 * # Setting Sizes
 *
 * The columns can be only be given an explicit width value. If no width is specified the
 * grid will automatically the size the column to 20px.
 *
 * # Header Options
 *
 *  - {@link #text}: Sets the header text for the column
 *  - {@link #sortable}: Specifies whether the column can be sorted by clicking the header
 *    or using the column menu
 *
 * # Data Options
 *
 *  - {@link #dataIndex}: The dataIndex is the field in the underlying {@link Ext.data.Store}
 *    to use as the value for the column.
 *  - {@link #renderer}: Allows the underlying store value to be transformed before being
 *    displayed in the grid.
 */
Ext.define('Ext.grid.column.Column', {
    extend: 'Ext.Component',
    alternateClassName: 'Ext.grid.column.Template',

    xtype: [ 'column', 'templatecolumn' ],

    config: {
        /**
         * @cfg {String} align
         * Sets the alignment of the header and rendered columns.
         * Possible values are: `'left'`, `'center'`, and `'right'`.
         */
        align: 'left',

        /**
         * @cfg {Object} cell
         * The config object used to create {@link Ext.grid.cell.Base cells} for this column.
         * By default, cells use the {@link Ext.grid.cell.Cell gridcell} `xtype`. To create
         * a different type of cell, simply provide this config and the desired `xtype`.
         */
        cell: {
            xtype: 'gridcell'
        },

        /**
         * @cfg {String} dataIndex
         * The name of the field in the grid's {@link Ext.data.Store}'s {@link Ext.data.Model} definition from
         * which to draw the column's value. **Required.**
         */
        dataIndex: null,

        /**
         * @cfg {String} text
         * The header text to be used as innerHTML (html tags are accepted) to display in the Grid.
         * **Note**: to have a clickable header with no text displayed you can use the default of ` ` aka ` `.
         */
        text: ' ',

        /**
         * @cfg {Boolean} sortable
         * False to disable sorting of this column. Whether local/remote sorting is used is specified in
         * `{@link Ext.data.Store#remoteSort}`.
         */
        sortable: true,

        /**
         * @cfg {Boolean} groupable
         * If the grid is {@link Ext.grid.Grid#grouped grouped}, and uses a
         * {@link Ext.grid.plugin.ViewOptions ViewOptions} plugin this option may be used to
         * disable the option to group by this column. By default, the group option is enabled.
         */
        groupable: true,

        /**
         * @cfg {Boolean} resizable
         * False to prevent the column from being resizable.
         * Note that this configuration only works when the {@link Ext.grid.plugin.ColumnResizing ColumnResizing} plugin
         * is enabled on the {@link Ext.grid.Grid Grid}.
         */
        resizable: true,

        /**
         * @cfg {Boolean} hideable
         * False to prevent the user from hiding this column.
         * TODO: Not implemented yet
         * @private
         */
        hideable: true,

        /**
         * @cfg {Function/String} renderer
         * A renderer is a method which can be used to transform data (value, appearance, etc.)
         * before it is rendered.
         *
         * For example:
         *
         *      {
         *          text: 'Some column',
         *          dataIndex: 'fieldName',
         *
         *          renderer: function (value, record) {
         *              if (value === 1) {
         *                  return '1 person';
         *              }
         *              return value + ' people';
         *          }
         *      }
         *
         * If a string is supplied, it should be the name of a renderer method from the
         * appropriate {@link Ext.app.ViewController}.
         *
         * This config is only processed if the {@link #cell} type is the default of
         * {@link Ext.grid.cell.Cell gridcell}.
         *
         * **Note** See {@link Ext.grid.Grid} documentation for other, better alternatives
         * to rendering cell content.
         *
         * @cfg {Object} renderer.value The data value for the current cell.
         * @cfg {Ext.data.Model} renderer.record The record for the current row.
         * @cfg {Number} renderer.dataIndex The dataIndex of the current column.
         * @cfg {Ext.grid.cell.Base} renderer.cell The current cell.
         * @cfg {Ext.grid.column.Column} renderer.column The current column.
         * @cfg {String} renderer.return The HTML string to be rendered.
         */
        renderer: false,

        /**
         * @cfg {Object} scope
         * The scope to use when calling the {@link #renderer} function.
         */
        scope: null,

        /**
         * @cfg {Boolean} editable
         * Set this to true to make this column editable.
         * Only applicable if the grid is using an {@link Ext.grid.plugin.Editable Editable} plugin.
         * @type {Boolean}
         */
        editable: false,

        /**
         * @cfg {Object/String} editor
         * An optional xtype or config object for a {@link Ext.field.Field Field} to use for editing.
         * Only applicable if the grid is using an {@link Ext.grid.plugin.Editable Editable} plugin.
         * Note also that {@link #editable} has to be set to true if you want to make this column editable.
         * If this configuration is not set, and {@link #editable} is set to true, the {@link #defaultEditor} is used.
         */
        editor: null,

        /**
         * @cfg {Object/Ext.field.Field}
         * An optional config object that should not really be modified. This is used to create
         * a default editor used by the {@link Ext.grid.plugin.Editable Editable} plugin when no
         * {@link #editor} is specified.
         * @type {Object}
         */
        defaultEditor: {
            xtype: 'textfield',
            required: true
        },

        /**
         * @cfg {Boolean} ignore
         * This configuration should be left alone in most cases. This is used to prevent certain columns
         * (like the MultiSelection plugin column) to show up in plugins (like the {@link Ext.grid.plugin.ViewOptions} plugin).
         */
        ignore: false,

        /**
         * @cfg {String/Function} summaryType
         * This configuration specifies the type of summary. There are several built in
         * summary types. These call underlying methods on the store:
         *
         *  - {@link Ext.data.Store#count count}
         *  - {@link Ext.data.Store#sum sum}
         *  - {@link Ext.data.Store#min min}
         *  - {@link Ext.data.Store#max max}
         *  - {@link Ext.data.Store#average average}
         *
         * Any other name is assumed to be the name of a method on the associated
         * {@link Ext.app.ViewController view controller}.
         *
         * Note that this configuration only works when the grid has the
         * {@link Ext.grid.plugin.SummaryRow SummaryRow} plugin enabled.
         */
        summaryType: null,

        /**
         * @cfg {String/Function} summaryRenderer
         * This summaryRenderer is called before displaying a value in the SummaryRow. The
         * function is optional, if not specified the default calculated value is shown. The
         * summaryRenderer is called with:
         *
         *  - value {Object} - The calculated value.
         *
         * Note that this configuration only works when the grid has the
         * {@link Ext.grid.plugin.SummaryRow SummaryRow} plugin enabled.
         */
        summaryRenderer: null,

        minWidth: 20,
        baseCls: Ext.baseCSSPrefix + 'grid-column',
        sortedCls: Ext.baseCSSPrefix + 'column-sorted',
        sortDirection: null,

        /**
         * @cfg {String/String[]/Ext.XTemplate} tpl
         * An {@link Ext.XTemplate XTemplate}, or an XTemplate *definition string* to use
         * to process a {@link Ext.data.Model records} data to produce a cell's rendered
         * value.
         *
         *     @example
         *     Ext.create('Ext.data.Store', {
         *         storeId:'employeeStore',
         *         fields:['firstname', 'lastname', 'seniority', 'department'],
         *         groupField: 'department',
         *         data:[
         *             { firstname: "Michael", lastname: "Scott",   seniority: 7, department: "Management" },
         *             { firstname: "Dwight",  lastname: "Schrute", seniority: 2, department: "Sales" },
         *             { firstname: "Jim",     lastname: "Halpert", seniority: 3, department: "Sales" },
         *             { firstname: "Kevin",   lastname: "Malone",  seniority: 4, department: "Accounting" },
         *             { firstname: "Angela",  lastname: "Martin",  seniority: 5, department: "Accounting" }
         *         ]
         *     });
         *
         *     Ext.create('Ext.grid.Panel', {
         *         title: 'Column Template Demo',
         *         store: Ext.data.StoreManager.lookup('employeeStore'),
         *         columns: [{
         *             text: 'Full Name',
         *             tpl: '{firstname} {lastname}'
         *         }, {
         *             text: 'Department (Yrs)',
         *             tpl: '{department} ({seniority})'
         *         }],
         *         height: 200,
         *         width: 300,
         *         renderTo: Ext.getBody()
         *     });
         *
         * This config is only processed if the {@link #cell} type is the default of
         * {@link Ext.grid.cell.Cell gridcell}.
         *
         * **Note** See {@link Ext.grid.Grid} documentation for other, better alternatives
         * to rendering cell content.
         */
        tpl: null
    },

    applyTpl: function (tpl) {
        if (!tpl || !tpl.isXTemplate) {
            tpl = new Ext.XTemplate(tpl);
        }

        return tpl;
    },

    updateAlign: function(align, oldAlign) {
        var prefix = Ext.baseCSSPrefix + 'grid-column-align-';
        if (oldAlign) {
            this.removeCls(prefix + align);
        }
        if (align) {
            this.addCls(prefix + align);
        }
    },

    initialize: function() {
        this.callParent();

        this.element.on({
            tap: 'onColumnTap',
            longpress: 'onColumnLongPress',
            scope: this
        });
    },

    onColumnTap: function(e) {
        this.fireEvent('tap', this, e);
    },

    onColumnLongPress: function(e) {
        this.fireEvent('longpress', this, e);
    },

    updateText: function(text) {
        this.setHtml(text || ' ');
    },

    updateWidth: function(width, oldWidth) {
        this.callParent([width, oldWidth]);
        this.fireEvent('columnresize', this, width);
    },

    updateDataIndex: function(dataIndex) {
        var editor = this.getEditor();
        if (editor) {
            editor.name = dataIndex;
        } else {
            this.getDefaultEditor().name = dataIndex;
        }
    },

    updateSortDirection: function(direction, oldDirection) {
        if (!this.getSortable()) {
            return;
        }

        var sortedCls = this.getSortedCls();

        if (oldDirection) {
            this.element.removeCls(sortedCls + '-' + oldDirection.toLowerCase());
        }

        if (direction) {
            this.element.addCls(sortedCls + '-' + direction.toLowerCase());
        }

        this.fireEvent('sort', this, direction, oldDirection);
    }
});


text:
<?php

use yii\helpers\Html;

/* @var $this yii\web\View */
/* @var $model app\modules\catalog\models\Details */

$this->title = Yii::t('app', 'Добавление');
$this->params['breadcrumbs'][] = ['label' => 'Редактирование: '.$model->product->title, 'url' => ['product/update','id'=>$model->productId]];
$this->params['breadcrumbs'][] = $this->title;
?>

<?= Html::encode($this->title) ?>

    <?php $form = \yii\bootstrap\ActiveForm::begin([
        'enableClientValidation' => false,
//        'enableAjaxValidation'=>true,
        'validateOnSubmit' => true,
    ]); ?>

    <?= \app\modules\core\widgets\LanguageTabs::widget([
        'models' => $models,
        'form' => $form,
        'view' => $this,
        'template' => '_form',
    ]) ?>

        <?= Html::submitButton('Добавить', ['class' => 'btn btn-success']) ?>

    <?php \yii\bootstrap\ActiveForm::end(); ?>

redpajama_set_name: RedPajamaGithub


text:
[![Build Status](https://travis-ci.org/cmercer/ignite-demo.svg?branch=master)](https://travis-ci.org/cmercer/ignite-demo)
# ignite-demo
Demo of Apache Ignite mainly built around testing using Spring and Spring Boot with Apache Ignite and being able to distribute jobs around to particular servers


text:
{% for section, _ in sections.items() %}

{% set underline = underlines[0] %}{% if section %}{{section}}
{{ underline * section|length }}{% set underline = underlines[1] %}

{% endif %}

{% if sections[section] %}
{% for category, val in definitions.items() if category in sections[section]%}
{{ definitions[category]['name'] }}
{{ underline * definitions[category]['name']|length }}

{% if definitions[category]['showcontent'] %}
{% for text, values in sections[section][category].items() %}
- {{ text }}
  {{ values|join(',\n  ') }}
{% endfor %}

{% else %}
- {{ sections[section][category]['']|join(', ') }}

{% endif %}
{% if sections[section][category]|length == 0 %}
No significant changes.

{% else %}
{% endif %}

{% endfor %}
{% else %}
No significant changes.

{% endif %}
{% endfor %}
----


text:
package cfvbaibai.cardfantasy.engine.feature;

import java.util.List;

import cfvbaibai.cardfantasy.data.Feature;
import cfvbaibai.cardfantasy.engine.CardInfo;
import cfvbaibai.cardfantasy.engine.FeatureEffect;
import cfvbaibai.cardfantasy.engine.FeatureEffectType;
import cfvbaibai.cardfantasy.engine.FeatureInfo;
import cfvbaibai.cardfantasy.engine.FeatureResolver;
import cfvbaibai.cardfantasy.engine.Player;

public final class HeroKillerFeature {

    private HeroKillerFeature() {
    }

    public static void apply(FeatureResolver resolver, FeatureInfo featureInfo, CardInfo attacker, Player victim) {
        Feature feature = featureInfo.getFeature();
        int adj = attacker.getLevel1AT() * feature.getImpact() / 100;
        resolver.getStage().getUI().useSkill(attacker, feature, true);
        resolver.getStage().getUI().adjustAT(attacker, attacker, adj, feature);
        attacker.addEffect(new FeatureEffect(FeatureEffectType.ATTACK_CHANGE, featureInfo, adj, false));
    }

    public static void remove(FeatureResolver resolver, FeatureInfo feature, CardInfo card) {
        List<FeatureEffect> effects = card.getEffectsCausedBy(feature);
        for (FeatureEffect effect : effects) {
            resolver.getStage().getUI().loseAdjustATEffect(card, effect);
            card.removeEffect(effect);
        }
    }
}


text:
package edu.mit.dig.saveface.model.Work;

/*
import com.hp.hpl.jena.datatypes.xsd.*;
import com.hp.hpl.jena.datatypes.xsd.impl.*;
import com.hp.hpl.jena.rdf.model.*;
import com.ibm.adtech.jastor.*;
import java.util.*;
import java.math.*;
*/

/**
 * Implementations of this listener may be registered with instances of edu.mit.dig.saveface.model.Work.Work to
 * receive notification when properties changed, added or removed.
 * <br>
 */
public interface WorkListener extends com.ibm.adtech.jastor.ThingListener {

	/**
	 * Called when a value of position has been added
	 * @param source the affected instance of edu.mit.dig.saveface.model.Work.Work
	 * @param newValue the object representing the new value
	 */
	public void positionAdded(edu.mit.dig.saveface.model.Work.Work source, com.ibm.adtech.jastor.Thing newValue);

	/**
	 * Called when a value of position has been removed
	 * @param source the affected instance of edu.mit.dig.saveface.model.Work.Work
	 * @param oldValue the object representing the removed value
	 */
	public void positionRemoved(edu.mit.dig.saveface.model.Work.Work source, com.ibm.adtech.jastor.Thing oldValue);

	/**
	 * Called when a value of employer has been added
	 * @param source the affected instance of edu.mit.dig.saveface.model.Work.Work
	 * @param newValue the object representing the new value
	 */
	public void employerAdded(edu.mit.dig.saveface.model.Work.Work source, com.ibm.adtech.jastor.Thing newValue);

	/**
	 * Called when a value of employer has been removed
	 * @param source the affected instance of edu.mit.dig.saveface.model.Work.Work
	 * @param oldValue the object representing the removed value
	 */
	public void employerRemoved(edu.mit.dig.saveface.model.Work.Work source, com.ibm.adtech.jastor.Thing oldValue);

	/**
	 * Called when a value of location has been added
	 * @param source the affected instance of edu.mit.dig.saveface.model.Work.Work
	 * @param newValue the object representing the new value
	 */
	public void locationAdded(edu.mit.dig.saveface.model.Work.Work source, com.ibm.adtech.jastor.Thing newValue);

	/**
	 * Called when a value of location has been removed
	 * @param source the affected instance of edu.mit.dig.saveface.model.Work.Work
	 * @param oldValue the object representing the removed value
	 */
	public void locationRemoved(edu.mit.dig.saveface.model.Work.Work source, com.ibm.adtech.jastor.Thing oldValue);

	/**
	 * Called when a value of startDate has been added
	 * @param source the affected instance of edu.mit.dig.saveface.model.Work.Work
	 * @param newValue the object representing the new value
	 */
	public void startDateAdded(edu.mit.dig.saveface.model.Work.Work source, com.hp.hpl.jena.datatypes.xsd.XSDDateTime newValue);

	/**
	 * Called when a value of startDate has been removed
	 * @param source the affected instance of edu.mit.dig.saveface.model.Work.Work
	 * @param oldValue the object representing the removed value
	 */
	public void startDateRemoved(edu.mit.dig.saveface.model.Work.Work source, com.hp.hpl.jena.datatypes.xsd.XSDDateTime oldValue);

	/**
	 * Called when a value of endDate has been added
	 * @param source the affected instance of edu.mit.dig.saveface.model.Work.Work
	 * @param newValue the object representing the new value
	 */
	public void endDateAdded(edu.mit.dig.saveface.model.Work.Work source, com.hp.hpl.jena.datatypes.xsd.XSDDateTime newValue);

	/**
	 * Called when a value of endDate has been removed
	 * @param source the affected instance of edu.mit.dig.saveface.model.Work.Work
	 * @param oldValue the object representing the removed value
	 */
	public void endDateRemoved(edu.mit.dig.saveface.model.Work.Work source, com.hp.hpl.jena.datatypes.xsd.XSDDateTime oldValue);

}


text:
package jalse.entities;

import java.util.UUID;

import jalse.actions.ActionEngine;

/**
 * An entity factory is used to control the creation, transfer and killing of {@link Entity}. This
 * should only be used by {@link EntityContainer}s and only at the parent level of the
 * {@link Entity} they are managing.

 *

 * The main aim of the factory is to ensure the {@link Entity} (and sub-tree) state is maintained.
 * It should be the aim of the {@link EntityContainer} calling the factory to ensure references are
 * removed at their level.
 *
 * @author Elliot Ford
 *
 * @see DefaultEntityContainer
 * @see DefaultEntityFactory
 *
 */
public interface EntityFactory {

    /**
     * Exports an entity (removing all references).
     *
     * @param e
     *            Entity to detach.
     */
    void exportEntity(Entity e);

    /**
     * Creates a new entity with the specified ID and parent container.
     *
     * @param id
     *            Entity ID.
     * @param target
     *            Parent container.
     * @return Newly created entity.
     */
    Entity newEntity(UUID id, EntityContainer target);

    /**
     * Sets the engine to supply to new entities.
     *
     * @param engine
     *            Action engine.
     */
    void setEngine(ActionEngine engine);

    /**
     * Imports the entity into the factory.
     *
     * @param e
     *            Entity to import.
     * @param target
     *            Target container.
     * @return Whether the entity was imported.
     */
    boolean tryImportEntity(Entity e, EntityContainer target);

    /**
     * Kills the specified entity.
     *
     * @param e
     *            Entity to kill.
     * @return Whether the entity was killed.
     */
    boolean tryKillEntity(Entity e);

    /**
     * Tries to take the entity from within the tree if possible.
     *
     * @param e
     *            Entity to take.
     * @param target
     *            Target container.
     * @return Whether the entity could be taken from within the tree.
     */
    boolean tryTakeFromTree(Entity e, EntityContainer target);

    /**
     * Checks if the two containers are within the same tree (for in tree transfer or export).
     *
     * @param source
     *            Source container.
     * @param target
     *            Target container.
     * @return Whether they're within the same tree.
     */
    boolean withinSameTree(EntityContainer source, EntityContainer target);
}


text:
import {Injectable} from '@angular/core/src/di';
import {
  inject,
  describe,
  ddescribe,
  it,
  iit,
  xit,
  xdescribe,
  expect,
  beforeEach,
} from '@angular/core/testing/testing_internal';
import {AsyncTestCompleter, SpyObject} from '@angular/core/testing/testing_internal';
import {Testability} from '@angular/core/src/testability/testability';
import {NgZone} from '@angular/core/src/zone/ng_zone';
import {normalizeBlank, scheduleMicroTask} from '../../src/facade/lang';
import {PromiseWrapper, EventEmitter, ObservableWrapper} from '../../src/facade/async';

// Schedules a microtasks (using a resolved promise .then())
function microTask(fn: Function): void {
  scheduleMicroTask(() => {
    // We do double dispatch so that we  can wait for scheduleMicrotas in the Testability when
    // NgZone becomes stable.
    scheduleMicroTask(fn);
  });
}

@Injectable()
class MockNgZone extends NgZone {
  _onUnstableStream: EventEmitter<any>;
  get onUnstable() { return this._onUnstableStream; }

  _onStableStream: EventEmitter<any>;
  get onStable() { return this._onStableStream; }

  constructor() {
    super({enableLongStackTrace: false});
    this._onUnstableStream = new EventEmitter(false);
    this._onStableStream = new EventEmitter(false);
  }

  unstable(): void { ObservableWrapper.callEmit(this._onUnstableStream, null); }

  stable(): void { ObservableWrapper.callEmit(this._onStableStream, null); }
}

export function main() {
  describe('Testability', () => {
    var testability: Testability;
    var execute: any;
    var execute2: any;
    var ngZone: MockNgZone;

    beforeEach(() => {
      ngZone = new MockNgZone();
      testability = new Testability(ngZone);
      execute = new SpyObject().spy('execute');
      execute2 = new SpyObject().spy('execute');
    });

    describe('Pending count logic', () => {
      it('should start with a pending count of 0',
         () => { expect(testability.getPendingRequestCount()).toEqual(0); });

      it('should fire whenstable callbacks if pending count is 0',
         inject([AsyncTestCompleter], (async) => {
           testability.whenStable(execute);
           microTask(() => {
             expect(execute).toHaveBeenCalled();
             async.done();
           });
         }));

      it('should not fire whenstable callbacks synchronously if pending count is 0', () => {
        testability.whenStable(execute);
        expect(execute).not.toHaveBeenCalled();
      });

      it('should not call whenstable callbacks when there are pending counts',
         inject([AsyncTestCompleter], (async) => {
           testability.increasePendingRequestCount();
           testability.increasePendingRequestCount();
           testability.whenStable(execute);

           microTask(() => {
             expect(execute).not.toHaveBeenCalled();
             testability.decreasePendingRequestCount();

             microTask(() => {
               expect(execute).not.toHaveBeenCalled();
               async.done();
             });
           });
         }));

      it('should fire whenstable callbacks when pending drops to 0',
         inject([AsyncTestCompleter], (async) => {
           testability.increasePendingRequestCount();
           testability.whenStable(execute);

           microTask(() => {
             expect(execute).not.toHaveBeenCalled();
             testability.decreasePendingRequestCount();

             microTask(() => {
               expect(execute).toHaveBeenCalled();
               async.done();
             });
           });
         }));

      it('should not fire whenstable callbacks synchronously when pending drops to 0', () => {
        testability.increasePendingRequestCount();
        testability.whenStable(execute);
        testability.decreasePendingRequestCount();

        expect(execute).not.toHaveBeenCalled();
      });

      it('should fire whenstable callbacks with didWork if pending count is 0',
         inject([AsyncTestCompleter], (async) => {
           testability.whenStable(execute);
           microTask(() => {
             expect(execute).toHaveBeenCalledWith(false);
             async.done();
           });
         }));

      it('should fire whenstable callbacks with didWork when pending drops to 0',
         inject([AsyncTestCompleter], (async) => {
           testability.increasePendingRequestCount();
           testability.whenStable(execute);

           microTask(() => {
             testability.decreasePendingRequestCount();

             microTask(() => {
               expect(execute).toHaveBeenCalledWith(true);
               testability.whenStable(execute2);

               microTask(() => {
                 expect(execute2).toHaveBeenCalledWith(false);
                 async.done();
               });
             });
           });
         }));
    });

    describe('NgZone callback logic', () => {
      it('should fire whenstable callback if event is already finished',
         inject([AsyncTestCompleter], (async) => {
           ngZone.unstable();
           ngZone.stable();
           testability.whenStable(execute);

           microTask(() => {
             expect(execute).toHaveBeenCalled();
             async.done();
           });
         }));

      it('should not fire whenstable callbacks synchronously if event is already finished', () => {
        ngZone.unstable();
        ngZone.stable();
        testability.whenStable(execute);

        expect(execute).not.toHaveBeenCalled();
      });

      it('should fire whenstable callback when event finishes',
         inject([AsyncTestCompleter], (async) => {
           ngZone.unstable();
           testability.whenStable(execute);

           microTask(() => {
             expect(execute).not.toHaveBeenCalled();
             ngZone.stable();

             microTask(() => {
               expect(execute).toHaveBeenCalled();
               async.done();
             });
           });
         }));

      it('should not fire whenstable callbacks synchronously when event finishes', () => {
        ngZone.unstable();
        testability.whenStable(execute);
        ngZone.stable();

        expect(execute).not.toHaveBeenCalled();
      });

      it('should not fire whenstable callback when event did not finish',
         inject([AsyncTestCompleter], (async) => {
           ngZone.unstable();
           testability.increasePendingRequestCount();
           testability.whenStable(execute);

           microTask(() => {
             expect(execute).not.toHaveBeenCalled();
             testability.decreasePendingRequestCount();

             microTask(() => {
               expect(execute).not.toHaveBeenCalled();
               ngZone.stable();

               microTask(() => {
                 expect(execute).toHaveBeenCalled();
                 async.done();
               });
             });
           });
         }));

      it('should not fire whenstable callback when there are pending counts',
         inject([AsyncTestCompleter], (async) => {
           ngZone.unstable();
           testability.increasePendingRequestCount();
           testability.increasePendingRequestCount();
           testability.whenStable(execute);

           microTask(() => {
             expect(execute).not.toHaveBeenCalled();
             ngZone.stable();

             microTask(() => {
               expect(execute).not.toHaveBeenCalled();
               testability.decreasePendingRequestCount();

               microTask(() => {
                 expect(execute).not.toHaveBeenCalled();
                 testability.decreasePendingRequestCount();

                 microTask(() => {
                   expect(execute).toHaveBeenCalled();
                   async.done();
                 });
               });
             });
           });
         }));

      it('should fire whenstable callback with didWork if event is already finished',
         inject([AsyncTestCompleter], (async) => {
           ngZone.unstable();
           ngZone.stable();
           testability.whenStable(execute);

           microTask(() => {
             expect(execute).toHaveBeenCalledWith(true);
             testability.whenStable(execute2);

             microTask(() => {
               expect(execute2).toHaveBeenCalledWith(false);
               async.done();
             });
           });
         }));

      it('should fire whenstable callback with didwork when event finishes',
         inject([AsyncTestCompleter], (async) => {
           ngZone.unstable();
           testability.whenStable(execute);

           microTask(() => {
             ngZone.stable();

             microTask(() => {
               expect(execute).toHaveBeenCalledWith(true);
               testability.whenStable(execute2);

               microTask(() => {
                 expect(execute2).toHaveBeenCalledWith(false);
                 async.done();
               });
             });
           });
         }));
    });
  });
}


text:
<?php

if (!defined('SMF'))
	die('Hacking attempt...');

/*	This file is concerned pretty entirely, as you see from its name, with
	logging in and out members, and the validation of that.  It contains:

	void Login()
		- shows a page for the user to type in their username and password.
		- caches the referring URL in $_SESSION['login_url'].
		- uses the Login template and language file with the login sub
		  template.
		- if you are using a wireless device, uses the protocol_login sub
		  template in the Wireless template.
		- accessed from ?action=login.

	void Login2()
		- actually logs you in and checks that login was successful.
		- employs protection against a specific IP or user trying to brute
		  force a login to an account.
		- on error, uses the same templates Login() uses.
		- upgrades password encryption on login, if necessary.
		- after successful login, redirects you to $_SESSION['login_url'].
		- accessed from ?action=login2, by forms.

	void Logout(bool internal = false)
		- logs the current user out of their account.
		- requires that the session hash is sent as well, to prevent automatic
		  logouts by images or javascript.
		- doesn't check the session if internal is true.
		- redirects back to $_SESSION['logout_url'], if it exists.
		- accessed via ?action=logout;session_var=...

	string md5_hmac(string data, string key)
		- old style SMF 1.0.x/YaBB SE 1.5.x hashing.
		- returns the HMAC MD5 of data with key.

	string phpBB3_password_check(string passwd, string passwd_hash)
		- custom encryption for phpBB3 based passwords.

	void validatePasswordFlood(id_member, password_flood_value = false, was_correct = false)
		- this function helps protect against brute force attacks on a member's password.
*/

// Ask them for their login information.
function Login()
{
	global $txt, $context, $scripturl;

	// In wireless?  If so, use the correct sub template.
	if (WIRELESS)
		$context['sub_template'] = WIRELESS_PROTOCOL . '_login';
	// Otherwise, we need to load the Login template/language file.
	else
	{
		loadLanguage('Login');
		loadTemplate('Login');
		$context['sub_template'] = 'login';
	}

	// Get the template ready.... not really much else to do.
	$context['page_title'] = $txt['login'];
	$context['default_username'] = &$_REQUEST['u'];
	$context['default_password'] = '';
	$context['never_expire'] = false;

	// Add the login chain to the link tree.
	$context['linktree'][] = array(
		'url' => $scripturl . '?action=login',
		'name' => $txt['login'],
	);

	// Set the login URL - will be used when the login process is done (but careful not to send us to an attachment).
	if (isset($_SESSION['old_url']) && strpos($_SESSION['old_url'], 'dlattach') === false && preg_match('~(board|topic)[=,]~', $_SESSION['old_url']) != 0)
		$_SESSION['login_url'] = $_SESSION['old_url'];
	else
		unset($_SESSION['login_url']);
}

// Perform the actual logging-in.
function Login2()
{
	global $txt, $scripturl, $user_info, $user_settings, $smcFunc;
	global $cookiename, $maintenance, $modSettings, $context, $sc, $sourcedir;

	// Load cookie authentication stuff.
	require_once($sourcedir . '/Subs-Auth.php');

	if (isset($_GET['sa']) && $_GET['sa'] == 'salt' && !$user_info['is_guest'])
	{
		if (isset($_COOKIE[$cookiename]) && preg_match('~^a:[34]:\{i:0;(i:\d{1,6}|s:[1-8]:"\d{1,8}");i:1;s:(0|40):"([a-fA-F0-9]{40})?";i:2;[id]:\d{1,14};(i:3;i:\d;)?\}$~', $_COOKIE[$cookiename]) === 1)
			list (, , $timeout) = @unserialize($_COOKIE[$cookiename]);
		elseif (isset($_SESSION['login_' . $cookiename]))
			list (, , $timeout) = @unserialize($_SESSION['login_' . $cookiename]);
		else
			trigger_error('Login2(): Cannot be logged in without a session or cookie', E_USER_ERROR);

		$user_settings['password_salt'] = substr(md5(mt_rand()), 0, 4);
		updateMemberData($user_info['id'], array('password_salt' => $user_settings['password_salt']));

		setLoginCookie($timeout - time(), $user_info['id'], sha1($user_settings['passwd'] . $user_settings['password_salt']));

		redirectexit('action=login2;sa=check;member=' . $user_info['id'], $context['server']['needs_login_fix']);
	}
	// Double check the cookie...
	elseif (isset($_GET['sa']) && $_GET['sa'] == 'check')
	{
		// Strike!  You're outta there!
		if ($_GET['member'] != $user_info['id'])
			fatal_lang_error('login_cookie_error', false);

		// Some whitelisting for login_url...
		if (empty($_SESSION['login_url']))
			redirectexit();
		else
		{
			// Best not to clutter the session data too much...
			$temp = $_SESSION['login_url'];
			unset($_SESSION['login_url']);

			redirectexit($temp);
		}
	}

	// Beyond this point you are assumed to be a guest trying to login.
	if (!$user_info['is_guest'])
		redirectexit();

	// Are you guessing with a script?
	spamProtection('login');

	// Set the login_url if it's not already set (but careful not to send us to an attachment).
	if (empty($_SESSION['login_url']) && isset($_SESSION['old_url']) && strpos($_SESSION['old_url'], 'dlattach') === false && preg_match('~(board|topic)[=,]~', $_SESSION['old_url']) != 0)
		$_SESSION['login_url'] = $_SESSION['old_url'];

	// Been guessing a lot, haven't we?
	if (isset($_SESSION['failed_login']) && $_SESSION['failed_login'] >= $modSettings['failed_login_threshold'] * 3)
		fatal_lang_error('login_threshold_fail', 'critical');

	// Set up the cookie length.  (if it's invalid, just fall through and use the default.)
	if (isset($_POST['cookieneverexp']) || (!empty($_POST['cookielength']) && $_POST['cookielength'] == -1))
		$modSettings['cookieTime'] = 3153600;
	elseif (!empty($_POST['cookielength']) && ($_POST['cookielength'] >= 1 || $_POST['cookielength'] <= 525600))
		$modSettings['cookieTime'] = (int) $_POST['cookielength'];

	loadLanguage('Login');
	// Load the template stuff - wireless or normal.
	if (WIRELESS)
		$context['sub_template'] = WIRELESS_PROTOCOL . '_login';
	else
	{
		loadTemplate('Login');
		$context['sub_template'] = 'login';
	}

	// Set up the default/fallback stuff.
	$context['default_username'] = isset($_POST['user']) ? preg_replace('~&#(\\d{1,7}|x[0-9a-fA-F]{1,6});~', '&#\\1;', htmlspecialchars($_POST['user'])) : '';
	$context['default_password'] = '';
	$context['never_expire'] = $modSettings['cookieTime'] == 525600 || $modSettings['cookieTime'] == 3153600;
	$context['login_errors'] = array($txt['error_occured']);
	$context['page_title'] = $txt['login'];

	// Add the login chain to the link tree.
	$context['linktree'][] = array(
		'url' => $scripturl . '?action=login',
		'name' => $txt['login'],
	);

	if (!empty($_POST['openid_identifier']) && !empty($modSettings['enableOpenID']))
	{
		require_once($sourcedir . '/Subs-OpenID.php');
		if (($open_id = smf_openID_validate($_POST['openid_identifier'])) !== 'no_data')
			return $open_id;
	}

	// You forgot to type your username, dummy!
	if (!isset($_POST['user']) || $_POST['user'] == '')
	{
		$context['login_errors'] = array($txt['need_username']);
		return;
	}

	// Hmm... maybe 'admin' will login with no password. Uhh... NO!
	if ((!isset($_POST['passwrd']) || $_POST['passwrd'] == '') && (!isset($_POST['hash_passwrd']) || strlen($_POST['hash_passwrd']) != 40))
	{
		$context['login_errors'] = array($txt['no_password']);
		return;
	}

	// No funky symbols either.
	if (preg_match('~[<>&"\'=\\\]~', preg_replace('~(&#(\\d{1,7}|x[0-9a-fA-F]{1,6});)~', '', $_POST['user'])) != 0)
	{
		$context['login_errors'] = array($txt['error_invalid_characters_username']);
		return;
	}

	// Are we using any sort of integration to validate the login?
	if (in_array('retry', call_integration_hook('integrate_validate_login', array($_POST['user'], isset($_POST['hash_passwrd']) && strlen($_POST['hash_passwrd']) == 40 ? $_POST['hash_passwrd'] : null, $modSettings['cookieTime'])), true))
	{
		$context['login_errors'] = array($txt['login_hash_error']);
		$context['disable_login_hashing'] = true;
		return;
	}

	// Load the data up!
	$request = $smcFunc['db_query']('', '
		SELECT passwd, id_member, id_group, lngfile, is_activated, email_address, additional_groups, member_name, password_salt,
			openid_uri, passwd_flood
		FROM {db_prefix}members
		WHERE ' . ($smcFunc['db_case_sensitive'] ? 'LOWER(member_name) = LOWER({string:user_name})' : 'member_name = {string:user_name}') . '
		LIMIT 1',
		array(
			'user_name' => $smcFunc['db_case_sensitive'] ? strtolower($_POST['user']) : $_POST['user'],
		)
	);
	// Probably mistyped or their email, try it as an email address. (member_name first, though!)
	if ($smcFunc['db_num_rows']($request) == 0)
	{
		$smcFunc['db_free_result']($request);

		$request = $smcFunc['db_query']('', '
			SELECT passwd, id_member, id_group, lngfile, is_activated, email_address, additional_groups, member_name, password_salt, openid_uri,
			passwd_flood
			FROM {db_prefix}members
			WHERE email_address = {string:user_name}
			LIMIT 1',
			array(
				'user_name' => $_POST['user'],
			)
		);
		// Let them try again, it didn't match anything...
		if ($smcFunc['db_num_rows']($request) == 0)
		{
			$context['login_errors'] = array($txt['username_no_exist']);
			return;
		}
	}

	$user_settings = $smcFunc['db_fetch_assoc']($request);
	$smcFunc['db_free_result']($request);

	// Figure out the password using SMF's encryption - if what they typed is right.
	if (isset($_POST['hash_passwrd']) && strlen($_POST['hash_passwrd']) == 40)
	{
		// Needs upgrading?
		if (strlen($user_settings['passwd']) != 40)
		{
			$context['login_errors'] = array($txt['login_hash_error']);
			$context['disable_login_hashing'] = true;
			unset($user_settings);
			return;
		}
		// Challenge passed.
		elseif ($_POST['hash_passwrd'] == sha1($user_settings['passwd'] . $sc))
			$sha_passwd = $user_settings['passwd'];
		else
		{
			// Don't allow this!
			validatePasswordFlood($user_settings['id_member'], $user_settings['passwd_flood']);

			$_SESSION['failed_login'] = @$_SESSION['failed_login'] + 1;

			if ($_SESSION['failed_login'] >= $modSettings['failed_login_threshold'])
				redirectexit('action=reminder');
			else
			{
				log_error($txt['incorrect_password'] . ' - ' . $user_settings['member_name'] . '', 'user');

				$context['disable_login_hashing'] = true;
				$context['login_errors'] = array($txt['incorrect_password']);
				unset($user_settings);
				return;
			}
		}
	}
	else
		$sha_passwd = sha1(strtolower($user_settings['member_name']) . un_htmlspecialchars($_POST['passwrd']));

	// Bad password!  Thought you could fool the database?!
	if ($user_settings['passwd'] != $sha_passwd)
	{
		// Let's be cautious, no hacking please. thanx.
		validatePasswordFlood($user_settings['id_member'], $user_settings['passwd_flood']);

		// Maybe we were too hasty... let's try some other authentication methods.
		$other_passwords = array();

		// None of the below cases will be used most of the time (because the salt is normally set.)
		if ($user_settings['password_salt'] == '')
		{
			// YaBB SE, Discus, MD5 (used a lot), SHA-1 (used some), SMF 1.0.x, IkonBoard, and none at all.
			$other_passwords[] = crypt($_POST['passwrd'], substr($_POST['passwrd'], 0, 2));
			$other_passwords[] = crypt($_POST['passwrd'], substr($user_settings['passwd'], 0, 2));
			$other_passwords[] = md5($_POST['passwrd']);
			$other_passwords[] = sha1($_POST['passwrd']);
			$other_passwords[] = md5_hmac($_POST['passwrd'], strtolower($user_settings['member_name']));
			$other_passwords[] = md5($_POST['passwrd'] . strtolower($user_settings['member_name']));
			$other_passwords[] = md5(md5($_POST['passwrd']));
			$other_passwords[] = $_POST['passwrd'];

			// This one is a strange one... MyPHP, crypt() on the MD5 hash.
			$other_passwords[] = crypt(md5($_POST['passwrd']), md5($_POST['passwrd']));

			// Snitz style - SHA-256.  Technically, this is a downgrade, but most PHP configurations don't support sha256 anyway.
			if (strlen($user_settings['passwd']) == 64 && function_exists('mhash') && defined('MHASH_SHA256'))
				$other_passwords[] = bin2hex(mhash(MHASH_SHA256, $_POST['passwrd']));

			// phpBB3 users new hashing.  We now support it as well ;).
			$other_passwords[] = phpBB3_password_check($_POST['passwrd'], $user_settings['passwd']);

			// APBoard 2 Login Method.
			$other_passwords[] = md5(crypt($_POST['passwrd'], 'CRYPT_MD5'));
		}
		// The hash should be 40 if it's SHA-1, so we're safe with more here too.
		elseif (strlen($user_settings['passwd']) == 32)
		{
			// vBulletin 3 style hashing?  Let's welcome them with open arms \o/.
			$other_passwords[] = md5(md5($_POST['passwrd']) . $user_settings['password_salt']);

			// Hmm.. p'raps it's Invision 2 style?
			$other_passwords[] = md5(md5($user_settings['password_salt']) . md5($_POST['passwrd']));

			// Some common md5 ones.
			$other_passwords[] = md5($user_settings['password_salt'] . $_POST['passwrd']);
			$other_passwords[] = md5($_POST['passwrd'] . $user_settings['password_salt']);
		}
		elseif (strlen($user_settings['passwd']) == 40)
		{
			// Maybe they are using a hash from before the password fix.
			$other_passwords[] = sha1(strtolower($user_settings['member_name']) . un_htmlspecialchars($_POST['passwrd']));

			// BurningBoard3 style of hashing.
			$other_passwords[] = sha1($user_settings['password_salt'] . sha1($user_settings['password_salt'] . sha1($_POST['passwrd'])));

			// Perhaps we converted to UTF-8 and have a valid password being hashed differently.
			if ($context['character_set'] == 'utf8' && !empty($modSettings['previousCharacterSet']) && $modSettings['previousCharacterSet'] != 'utf8')
			{
				// Try iconv first, for no particular reason.
				if (function_exists('iconv'))
					$other_passwords['iconv'] = sha1(strtolower(iconv('UTF-8', $modSettings['previousCharacterSet'], $user_settings['member_name'])) . un_htmlspecialchars(iconv('UTF-8', $modSettings['previousCharacterSet'], $_POST['passwrd'])));

				// Say it aint so, iconv failed!
				if (empty($other_passwords['iconv']) && function_exists('mb_convert_encoding'))
					$other_passwords[] = sha1(strtolower(mb_convert_encoding($user_settings['member_name'], 'UTF-8', $modSettings['previousCharacterSet'])) . un_htmlspecialchars(mb_convert_encoding($_POST['passwrd'], 'UTF-8', $modSettings['previousCharacterSet'])));
			}
		}

		// SMF's sha1 function can give a funny result on Linux (Not our fault!). If we've now got the real one let the old one be valid!
		if (strpos(strtolower(PHP_OS), 'win') !== 0)
		{
			require_once($sourcedir . '/Subs-Compat.php');
			$other_passwords[] = sha1_smf(strtolower($user_settings['member_name']) . un_htmlspecialchars($_POST['passwrd']));
		}

		// Whichever encryption it was using, let's make it use SMF's now ;).
		if (in_array($user_settings['passwd'], $other_passwords))
		{
			$user_settings['passwd'] = $sha_passwd;
			$user_settings['password_salt'] = substr(md5(mt_rand()), 0, 4);

			// Update the password and set up the hash.
			updateMemberData($user_settings['id_member'], array('passwd' => $user_settings['passwd'], 'password_salt' => $user_settings['password_salt'], 'passwd_flood' => ''));
		}
		// Okay, they for sure didn't enter the password!
		else
		{
			// They've messed up again - keep a count to see if they need a hand.
			$_SESSION['failed_login'] = @$_SESSION['failed_login'] + 1;

			// Hmm... don't remember it, do you?  Here, try the password reminder ;).
			if ($_SESSION['failed_login'] >= $modSettings['failed_login_threshold'])
				redirectexit('action=reminder');
			// We'll give you another chance...
			else
			{
				// Log an error so we know that it didn't go well in the error log.
				log_error($txt['incorrect_password'] . ' - ' . $user_settings['member_name'] . '', 'user');

				$context['login_errors'] = array($txt['incorrect_password']);
				return;
			}
		}
	}
	elseif (!empty($user_settings['passwd_flood']))
	{
		// Let's be sure they weren't a little hacker.
		validatePasswordFlood($user_settings['id_member'], $user_settings['passwd_flood'], true);

		// If we got here then we can reset the flood counter.
		updateMemberData($user_settings['id_member'], array('passwd_flood' => ''));
	}

	// Correct password, but they've got no salt; fix it!
	if ($user_settings['password_salt'] == '')
	{
		$user_settings['password_salt'] = substr(md5(mt_rand()), 0, 4);
		updateMemberData($user_settings['id_member'], array('password_salt' => $user_settings['password_salt']));
	}

	// Check their activation status.
	if (!checkActivation())
		return;

	DoLogin();
}

function checkActivation()
{
	global $context, $txt, $scripturl, $user_settings, $modSettings;

	if (!isset($context['login_errors']))
		$context['login_errors'] = array();

	// What is the true activation status of this account?
	$activation_status = $user_settings['is_activated'] > 10 ? $user_settings['is_activated'] - 10 : $user_settings['is_activated'];

	// Check if the account is activated - COPPA first...
	if ($activation_status == 5)
	{
		$context['login_errors'][] = $txt['coppa_no_concent'] . ' ' . $txt['coppa_need_more_details'] . '';
		return false;
	}
	// Awaiting approval still?
	elseif ($activation_status == 3)
		fatal_lang_error('still_awaiting_approval', 'user');
	// Awaiting deletion, changed their mind?
	elseif ($activation_status == 4)
	{
		if (isset($_REQUEST['undelete']))
		{
			updateMemberData($user_settings['id_member'], array('is_activated' => 1));
			updateSettings(array('unapprovedMembers' => ($modSettings['unapprovedMembers'] > 0 ? $modSettings['unapprovedMembers'] - 1 : 0)));
		}
		else
		{
			$context['disable_login_hashing'] = true;
			$context['login_errors'][] = $txt['awaiting_delete_account'];
			$context['login_show_undelete'] = true;
			return false;
		}
	}
	// Standard activation?
	elseif ($activation_status != 1)
	{
		log_error($txt['activate_not_completed1'] . ' - ' . $user_settings['member_name'] . '', false);

		$context['login_errors'][] = $txt['activate_not_completed1'] . ' ' . $txt['activate_not_completed2'] . '';
		return false;
	}
	return true;
}

function DoLogin()
{
	global $txt, $scripturl, $user_info, $user_settings, $smcFunc;
	global $cookiename, $maintenance, $modSettings, $context, $sourcedir;

	// Load cookie authentication stuff.
	require_once($sourcedir . '/Subs-Auth.php');

	// Call login integration functions.
	call_integration_hook('integrate_login', array($user_settings['member_name'], isset($_POST['hash_passwrd']) && strlen($_POST['hash_passwrd']) == 40 ? $_POST['hash_passwrd'] : null, $modSettings['cookieTime']));

	// Get ready to set the cookie...
	$username = $user_settings['member_name'];
	$user_info['id'] = $user_settings['id_member'];

	// Bam!  Cookie set.  A session too, just in case.
	setLoginCookie(60 * $modSettings['cookieTime'], $user_settings['id_member'], sha1($user_settings['passwd'] . $user_settings['password_salt']));

	// Reset the login threshold.
	if (isset($_SESSION['failed_login']))
		unset($_SESSION['failed_login']);

	$user_info['is_guest'] = false;
	$user_settings['additional_groups'] = explode(',', $user_settings['additional_groups']);
	$user_info['is_admin'] = $user_settings['id_group'] == 1 || in_array(1, $user_settings['additional_groups']);

	// Are you banned?
	is_not_banned(true);

	// An administrator, set up the login so they don't have to type it again.
	if ($user_info['is_admin'] && isset($user_settings['openid_uri']) && empty($user_settings['openid_uri']))
	{
		$_SESSION['admin_time'] = time();
		unset($_SESSION['just_registered']);
	}

	// Don't stick the language or theme after this point.
	unset($_SESSION['language'], $_SESSION['id_theme']);

	// First login?
	$request = $smcFunc['db_query']('', '
		SELECT last_login
		FROM {db_prefix}members
		WHERE id_member = {int:id_member}
			AND last_login = 0',
		array(
			'id_member' => $user_info['id'],
		)
	);
	if ($smcFunc['db_num_rows']($request) == 1)
		$_SESSION['first_login'] = true;
	else
		unset($_SESSION['first_login']);
	$smcFunc['db_free_result']($request);

	// You've logged in, haven't you?
	updateMemberData($user_info['id'], array('last_login' => time(), 'member_ip' => $user_info['ip'], 'member_ip2' => $_SERVER['BAN_CHECK_IP']));

	// Get rid of the online entry for that old guest....
	$smcFunc['db_query']('', '
		DELETE FROM {db_prefix}log_online
		WHERE session = {string:session}',
		array(
			'session' => 'ip' . $user_info['ip'],
		)
	);
	$_SESSION['log_time'] = 0;

	// Just log you back out if it's in maintenance mode and you AREN'T an admin.
	if (empty($maintenance) || allowedTo('admin_forum'))
		redirectexit('action=login2;sa=check;member=' . $user_info['id'], $context['server']['needs_login_fix']);
	else
		redirectexit('action=logout;' . $context['session_var'] . '=' . $context['session_id'], $context['server']['needs_login_fix']);
}

// Log the user out.
function Logout($internal = false, $redirect = true)
{
	global $sourcedir, $user_info, $user_settings, $context, $modSettings, $smcFunc;

	// Make sure they aren't being auto-logged out.
	if (!$internal)
		checkSession('get');

	require_once($sourcedir . '/Subs-Auth.php');

	if (isset($_SESSION['pack_ftp']))
		$_SESSION['pack_ftp'] = null;

	// They cannot be open ID verified any longer.
	if (isset($_SESSION['openid']))
		unset($_SESSION['openid']);

	// It won't be first login anymore.
	unset($_SESSION['first_login']);

	// Just ensure they aren't a guest!
	if (!$user_info['is_guest'])
	{
		// Pass the logout information to integrations.
		call_integration_hook('integrate_logout', array($user_settings['member_name']));

		// If you log out, you aren't online anymore :P.
		$smcFunc['db_query']('', '
			DELETE FROM {db_prefix}log_online
			WHERE id_member = {int:current_member}',
			array(
				'current_member' => $user_info['id'],
			)
		);
	}

	$_SESSION['log_time'] = 0;

	// Empty the cookie! (set it in the past, and for id_member = 0)
	setLoginCookie(-3600, 0);

	// And some other housekeeping while we're at it.
	session_destroy();
	if (!empty($user_info['id']))
		updateMemberData($user_info['id'], array('password_salt' => substr(md5(mt_rand()), 0, 4)));

	// Off to the merry board index we go!
	if ($redirect)
	{
		if (empty($_SESSION['logout_url']))
			redirectexit('', $context['server']['needs_login_fix']);
		else
		{
			$temp = $_SESSION['logout_url'];
			unset($_SESSION['logout_url']);

			redirectexit($temp, $context['server']['needs_login_fix']);
		}
	}
}

// MD5 Encryption used for older passwords.
function md5_hmac($data, $key)
{
	$key = str_pad(strlen($key) <= 64 ? $key : pack('H*', md5($key)), 64, chr(0x00));
	return md5(($key ^ str_repeat(chr(0x5c), 64)) . pack('H*', md5(($key ^ str_repeat(chr(0x36), 64)) . $data)));
}

// Special encryption used by phpBB3.
function phpBB3_password_check($passwd, $passwd_hash)
{
	// Too long or too short?
	if (strlen($passwd_hash) != 34)
		return;

	// Range of characters allowed.
	$range = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';

	// Tests
	$strpos = strpos($range, $passwd_hash[3]);
	$count = 1 << $strpos;
	$count2 = $count;
	$salt = substr($passwd_hash, 4, 8);

	// Things are done differently for PHP 5.
	if (@version_compare(PHP_VERSION, '5') >= 0)
	{
		$hash = md5($salt . $passwd, true);
		for (; $count != 0; --$count)
			$hash = md5($hash . $passwd, true);
	}
	else
	{
		$hash = pack('H*', md5($salt . $passwd));
		for (; $count != 0; --$count)
			$hash = pack('H*', md5($hash . $passwd));
	}

	$output = substr($passwd_hash, 0, 12);
	$i = 0;
	while ($i < 16)
	{
		$value = ord($hash[$i++]);
		$output .= $range[$value & 0x3f];

		if ($i < 16)
			$value |= ord($hash[$i]) << 8;

		$output .= $range[($value >> 6) & 0x3f];

		if ($i++ >= 16)
			break;

		if ($i < 16)
			$value |= ord($hash[$i]) << 16;

		$output .= $range[($value >> 12) & 0x3f];

		if ($i++ >= 16)
			break;

		$output .= $range[($value >> 18) & 0x3f];
	}

	// Return now.
	return $output;
}

// This protects against brute force attacks on a member's password. Importantly even if the password was right we DON'T TELL THEM!
function validatePasswordFlood($id_member, $password_flood_value = false, $was_correct = false)
{
	global $smcFunc, $cookiename, $sourcedir;

	// As this is only brute protection, we allow 5 attempts every 10 seconds.

	// Destroy any session or cookie data about this member, as they validated wrong.
	require_once($sourcedir . '/Subs-Auth.php');
	setLoginCookie(-3600, 0);

	if (isset($_SESSION['login_' . $cookiename]))
		unset($_SESSION['login_' . $cookiename]);

	// We need a member!
	if (!$id_member)
	{
		// Redirect back!
		redirectexit();

		// Probably not needed, but still make sure...
		fatal_lang_error('no_access', false);
	}

	// Right, have we got a flood value?
	if ($password_flood_value !== false)
		@list ($time_stamp, $number_tries) = explode('|', $password_flood_value);

	// Timestamp or number of tries invalid?
	if (empty($number_tries) || empty($time_stamp))
	{
		$number_tries = 0;
		$time_stamp = time();
	}

	// They've failed logging in already
	if (!empty($number_tries))
	{
		// Give them less chances if they failed before
		$number_tries = $time_stamp < time() - 20 ? 2 : $number_tries;

		// They are trying too fast, make them wait longer
		if ($time_stamp < time() - 10)
			$time_stamp = time();
	}

	$number_tries++;

	// Broken the law?
	if ($number_tries > 5)
		fatal_lang_error('login_threshold_brute_fail', 'critical');

	// Otherwise set the members data. If they correct on their first attempt then we actually clear it, otherwise we set it!
	updateMemberData($id_member, array('passwd_flood' => $was_correct && $number_tries == 1 ? '' : $time_stamp . '|' . $number_tries));

}

?>


text:
import React, { PropTypes } from 'react';
import classNames from 'classnames'
import Select from 'react-select';
import 'react-select/dist/react-select.css';
import Msg from '../i18n/Msg'

RFReactSelect.defaultProps = {
  multi: false,
  className: ""
};

// RFReactSelect.propTypes = {
//   input: PropTypes.shape({
//     name: PropTypes.string.isRequired,
//     value: PropTypes.string.isRequired,
//     onBlur: PropTypes.func.isRequired,
//     onChange: PropTypes.func.isRequired,
//     onFocus: PropTypes.func.isRequired,
//   }).isRequired,
//   options: PropTypes.array.isRequired,
//   multi: PropTypes.bool,
//   className: PropTypes.string
// };

//https://github.com/erikras/redux-form/issues/1185
export default function RFReactSelect({ input , options, multi, className, label, disabled, meta: {asyncValidating, touched, error, warning} }) {
  const { name, value, onBlur, onChange, onFocus } = input;
  const transformedValue = transformValue(value, options, multi);
  return (

      {label==""?"":<Msg phrase={label}/>}
      <Select
        valueKey="value"
        name={name}
        value={transformedValue}
        multi={multi}
        disabled={disabled}
        options={options}
        onChange={multi
          ? multiChangeHandler(onChange)
          : singleChangeHandler(onChange)
        }
        onBlur={() => input.onBlur(input.value)}
        onFocus={onFocus}
        className={className}
      />
      {touched && ((error && <Msg phrase={error}/>) || (warning && <Msg phrase={warning}/>))}

  );
}

/**
 * onChange from Redux Form Field has to be called explicity.
 */
function singleChangeHandler(func) {
  return function handleSingleChange(value) {
    func(value ? value.value : '');
  };
}

/**
 * onBlur from Redux Form Field has to be called explicity.
 */
function multiChangeHandler(func) {

  return function handleMultiHandler(values) {
    func(values.map(value => ''+value.value));
  };
}

/**
 * For single select, Redux Form keeps the value as a string, while React Select
 * wants the value in the form { value: "grape", label: "Grape" }
 *
 * * For multi select, Redux Form keeps the value as array of strings, while React Select
 * wants the array of values in the form [{ value: "grape", label: "Grape" }]
 */
function transformValue(value, options, multi) {

  if (multi && typeof value === 'string') return [];
   //console.log('transformValue(value, options, multi) ', value, options, multi)
  const filteredOptions = options.filter(option => {
    return multi
      ? value.indexOf(option.value) !== -1
      : option.value === value;
  });
  //console.log('  multi) ', multi)
  //console.log(filteredOptions);
  return multi ? filteredOptions : filteredOptions[0];
}


text:
/*
  +----------------------------------------------------------------------+
  | Swoole                                                               |
  +----------------------------------------------------------------------+
  | This source file is subject to version 2.0 of the Apache license,    |
  | that is bundled with this package in the file LICENSE, and is        |
  | available through the world-wide-web at the following url:           |
  | http://www.apache.org/licenses/LICENSE-2.0.html                      |
  | If you did not receive a copy of the Apache2.0 license and are unable|
  | to obtain it through the world-wide-web, please send a note to       |
  | license@php.net so we can mail you a copy immediately.               |
  +----------------------------------------------------------------------+
  | Author: Tianfeng Han  <mikan.tenny@gmail.com>                        |
  +----------------------------------------------------------------------+
*/

#include "swoole.h"

/**
 * clear all singal
 */
void swSignal_none(void)
{
	sigset_t mask;
	sigfillset(&mask);
	int ret = pthread_sigmask(SIG_BLOCK, &mask, NULL);
	if (ret < 0)
	{
		swWarn("pthread_sigmask fail: %s", strerror(ret));
	}
}

/**
 * setup signal
 */
swSignalFunc swSignal_set(int sig, swSignalFunc func, int restart, int mask)
{
	struct sigaction act, oact;
	act.sa_handler = func;
	if (mask)
	{
		sigfillset(&act.sa_mask);
	}
	else
	{
		sigemptyset(&act.sa_mask);
	}
	act.sa_flags = 0;
	if (sigaction(sig, &act, &oact) < 0)
	{
		return NULL;
	}
	return oact.sa_handler;
}

void swSignal_add(int signo, swSignalFunc func)
{
#ifdef HAVE_SIGNALFD
	if (SwooleG.use_signalfd)
	{
		swSignalfd_add(signo, func);
	}
	else
#endif
	{
		if (func == NULL)
		{
			func = SIG_IGN;
		}
		swSignal_set(signo, func, 1, 0);
	}
}

#ifdef HAVE_SIGNALFD
/**
 * signalfd
 */
#include <sys/signalfd.h>

#define SW_SIGNAL_INIT_NUM    8

static int swSignalfd_onSignal(swReactor *reactor, swEvent *event);

static sigset_t swoole_signalfd_mask;
static int swoole_signalfd = 0;

typedef struct
{
	__sighandler_t callback;
	int signo;
} swSignal_item;

typedef struct
{
	swSignal_item *items;
	uint16_t num;
	uint16_t size;
} swSignal;

static swSignal object;

void swSignalfd_init()
{
	sigemptyset(&swoole_signalfd_mask);
	object.items = sw_calloc(SW_SIGNAL_INIT_NUM, sizeof(swSignal_item));
	if (object.items == NULL)
	{
		swError("malloc for swSignal_item failed.");
	}
	object.size = SW_SIGNAL_INIT_NUM;
	object.num = 0;
}

void swSignalfd_add(int signo, __sighandler_t callback)
{
	if (object.num == object.size)
	{
		object.items = sw_realloc(object.items, sizeof(swSignal_item) * object.size * 2);
		if (object.items == NULL)
		{
			swError("realloc for swSignal_item failed.");
			return;
		}
		object.size = object.size * 2;
	}
	sigaddset(&swoole_signalfd_mask, signo);
	object.items[object.num].callback = callback;
	object.items[object.num].signo = signo;
	object.num ++;
}

int swSignalfd_setup(swReactor *reactor)
{
	if (swoole_signalfd == 0)
	{
		swoole_signalfd = signalfd(-1, &swoole_signalfd_mask, SFD_NONBLOCK | SFD_CLOEXEC);
		if (swoole_signalfd < 0)
		{
			swWarn("signalfd() failed. Error: %s[%d]", strerror(errno), errno);
			return SW_ERR;
		}
		SwooleG.signal_fd = swoole_signalfd;
		if (sigprocmask(SIG_BLOCK, &swoole_signalfd_mask, NULL) == -1)
		{
			swWarn("sigprocmask() failed. Error: %s[%d]", strerror(errno), errno);
			return SW_ERR;
		}
		reactor->setHandle(reactor, SW_FD_SIGNAL, swSignalfd_onSignal);
		reactor->add(reactor, swoole_signalfd, SW_FD_SIGNAL);
		return SW_OK;
	}
	else
	{
		swWarn("signalfd has been created");
		return SW_ERR;
	}
}

static int swSignalfd_onSignal(swReactor *reactor, swEvent *event)
{
	int n, i;
	struct signalfd_siginfo siginfo;
	n = read(event->fd, &siginfo, sizeof(siginfo));
	if (n < 0)
	{
		swWarn("read from signalfd failed. Error: %s[%d]", strerror(errno), errno);
		return SW_ERR;
	}
	for(i = 0; i < object.num; i++)
	{
		if (siginfo.ssi_signo == object.items[i].signo && object.items[i].callback)
		{
			object.items[i].callback(siginfo.ssi_signo);
		}
	}
	return SW_OK;
}

#endif


text:
package org.apache.skywalking.apm.collector.core.graph;

/**
 * @author wusheng
 */
public class NodeNotFoundException extends RuntimeException {
    public NodeNotFoundException(String message) {
        super(message);
    }
}


text:
#include "config.h"
#include "StorageTask.h"

#include "StorageThread.h"
#include "StorageAreaSync.h"
#include "StorageTracker.h"

namespace WebCore {

StorageTask::StorageTask(Type type, StorageAreaSync* area)
    : m_type(type)
    , m_area(area)
    , m_thread(0)
{
    ASSERT(m_area);
    ASSERT(m_type == AreaImport || m_type == AreaSync || m_type == DeleteEmptyDatabase);
}

StorageTask::StorageTask(Type type, StorageThread* thread)
    : m_type(type)
    , m_area(0)
    , m_thread(thread)
{
    ASSERT(m_thread);
    ASSERT(m_type == TerminateThread);
}

StorageTask::StorageTask(Type type)
    : m_type(type)
    , m_area(0)
    , m_thread(0)
{
    ASSERT(m_type == ImportOrigins || m_type == DeleteAllOrigins);
}

StorageTask::StorageTask(Type type, const String& originIdentifier)
    : m_type(type)
    , m_area(0)
    , m_thread(0)
    , m_originIdentifier(originIdentifier)
{
    ASSERT(m_type == DeleteOrigin);
}

StorageTask::StorageTask(Type type, const String& originIdentifier, const String& databaseFilename)
    : m_type(type)
    , m_area(0)
    , m_thread(0)
    , m_originIdentifier(originIdentifier)
    , m_databaseFilename(databaseFilename)
{
    ASSERT(m_type == SetOriginDetails);
}

StorageTask::~StorageTask()
{
}

void StorageTask::performTask()
{
    switch (m_type) {
        case AreaImport:
            m_area->performImport();
            break;
        case AreaSync:
            m_area->performSync();
            break;
        case SetOriginDetails:
            StorageTracker::tracker().syncSetOriginDetails(m_originIdentifier, m_databaseFilename);
            break;
        case ImportOrigins:
            StorageTracker::tracker().syncImportOriginIdentifiers();
            break;
        case DeleteAllOrigins:
            StorageTracker::tracker().syncDeleteAllOrigins();
            break;
        case DeleteOrigin:
            StorageTracker::tracker().syncDeleteOrigin(m_originIdentifier);
            break;
        case DeleteEmptyDatabase:
            m_area->deleteEmptyDatabase();
            break;
        case TerminateThread:
            m_thread->performTerminate();
            break;
    }
}

}