<commit_before>/**
 * @license
 * Copyright 2013 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

/**
 * @fileoverview Blocks for Puzzle game.
 * @author fraser@google.com (Neil Fraser)
 */
'use strict';

goog.provide('Puzzle.Blocks');

goog.require('Blockly');
goog.require('Blockly.FieldDropdown');
goog.require('Blockly.FieldImage');
goog.require('BlocklyGames');
goog.require('BlocklyGames.Msg');

/**
 * Common HSV hue for all animal blocks.
 */
Puzzle.Blocks.ANIMAL_HUE = 120;

/**
 * Common HSV hue for all picture blocks.
 */
Puzzle.Blocks.PICTURE_HUE = 30;

/**
 * Common HSV hue for all trait blocks.
 */
Puzzle.Blocks.TRAIT_HUE = 290;

Blockly.Blocks['animal'] = {
  /**
   * Block to represent an animal.
   * @this {Blockly.Block}
   */
  init: function() {
    this.setColour(Puzzle.Blocks.ANIMAL_HUE);
    this.appendDummyInput()
        .appendField('', 'NAME');
    this.appendValueInput('PIC')
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField(BlocklyGames.Msg['Puzzle.picture']);
    this.appendDummyInput()
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField(BlocklyGames.Msg['Puzzle.legs'])
        .appendField(new Blockly.FieldDropdown(Puzzle.legs), 'LEGS');
    this.appendStatementInput('TRAITS')
        .appendField(BlocklyGames.Msg['Puzzle.traits']);
    this.setInputsInline(false);
  },
  /**
   * Save the animal number.
   * @return {!Element} XML storage element.
   * @this {Blockly.Block}
   */
  mutationToDom: function() {
    const container = document.createElement('mutation');
    container.setAttribute('animal', this.animal);
    return container;
  },
  /**
   * Restore the animal number.
   * @param {!Element} xmlElement XML storage element.
   * @this {Blockly.Block}
   */
  domToMutation: function(xmlElement) {
    this.populate(parseInt(xmlElement.getAttribute('animal'), 10));
  },
  animal: 0,
  /**
   * Set the animal.
   * @param {number} n Animal number.
   * @this {Blockly.Block}
   */
  populate: function(n) {
    this.animal = n;
    this.setFieldValue(Puzzle.data[n - 1].name, 'NAME');
    this.helpUrl = Puzzle.data[n - 1].helpUrl;
  },
  /**
   * Evaluate the correctness of this block.
   * @this {Blockly.Block}
   */
  isCorrect: function() {
    return this.getFieldValue('LEGS') === this.animal;
  }
};

Blockly.Blocks['picture'] = {
  /**
   * Block to represent a picture.
   * @this {Blockly.Block}
   */
  init: function() {
    this.setColour(Puzzle.Blocks.PICTURE_HUE);
    this.appendDummyInput('PIC');
    this.setOutput(true);
    this.setTooltip('');
  },
  mutationToDom: Blockly.Blocks['animal'].mutationToDom,
  domToMutation: Blockly.Blocks['animal'].domToMutation,
  animal: 0,
  /**
   * Set the animal and picture.
   * @param {number} n Animal number.
   * @this {Blockly.Block}
   */
  populate: function(n) {
    this.animal = n;
    const pic = 'puzzle/' + Puzzle.data[n - 1].pic;
    const picHeight = Puzzle.data[n - 1].picHeight;
    const picWidth = Puzzle.data[n - 1].picWidth;
    this.getInput('PIC')
        .appendField(new Blockly.FieldImage(pic, picWidth, picHeight));
  },
  /**
   * Evaluate the correctness of this block.
   * @this {Blockly.Block}
   */
  isCorrect: function() {
    const parent = this.getParent();
    return parent && (parent.animal === this.animal);
  }
};

Blockly.Blocks['trait'] = {
  /**
   * Block to represent a trait.
   * @this {Blockly.Block}
   */
  init: function() {
    this.setColour(Puzzle.Blocks.TRAIT_HUE);
    this.appendDummyInput().appendField('', 'NAME');
    this.setPreviousStatement(true);
    this.setNextStatement(true);
  },
  /**
   * Save the animal and trait numbers.
   * @return {!Element} XML storage element.
   * @this {Blockly.Block}
   */
  mutationToDom: function() {
    const container = document.createElement('mutation');
    container.setAttribute('animal', this.animal);
    container.setAttribute('trait', this.trait);
    return container;
  },
  /**
   * Restore the animal and trait numbers.
   * @param {!Element} xmlElement XML storage element.
   * @this {Blockly.Block}
   */
  domToMutation: function(xmlElement) {
    this.populate(parseInt(xmlElement.getAttribute('animal'), 10),
                  parseInt(xmlElement.getAttribute('trait'), 10));
  },
  animal: 0,
  trait: 0,
  /**
   * Set the animal and trait.
   * @param {number} n Animal number.
   * @param {string} m Trait number.
   * @this {Blockly.Block}
   */
  populate: function(n, m) {
    this.animal = n;
    this.trait = m;
    // Set the trait name.
    this.setFieldValue(Puzzle.data[n - 1].traits[m - 1], 'NAME');
  },
  /**
   * Evaluate the correctness of this block.
   * @this {Blockly.Block}
   */
  isCorrect: function() {
    const parent = this.getSurroundParent();
    return parent && (parent.animal === this.animal);
  }
};
<commit_msg>Fix legs on puzzle game<commit_after>/**
 * @license
 * Copyright 2013 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

/**
 * @fileoverview Blocks for Puzzle game.
 * @author fraser@google.com (Neil Fraser)
 */
'use strict';

goog.provide('Puzzle.Blocks');

goog.require('Blockly');
goog.require('Blockly.FieldDropdown');
goog.require('Blockly.FieldImage');
goog.require('BlocklyGames');
goog.require('BlocklyGames.Msg');

/**
 * Common HSV hue for all animal blocks.
 */
Puzzle.Blocks.ANIMAL_HUE = 120;

/**
 * Common HSV hue for all picture blocks.
 */
Puzzle.Blocks.PICTURE_HUE = 30;

/**
 * Common HSV hue for all trait blocks.
 */
Puzzle.Blocks.TRAIT_HUE = 290;

Blockly.Blocks['animal'] = {
  /**
   * Block to represent an animal.
   * @this {Blockly.Block}
   */
  init: function() {
    this.setColour(Puzzle.Blocks.ANIMAL_HUE);
    this.appendDummyInput()
        .appendField('', 'NAME');
    this.appendValueInput('PIC')
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField(BlocklyGames.Msg['Puzzle.picture']);
    this.appendDummyInput()
        .setAlign(Blockly.ALIGN_RIGHT)
        .appendField(BlocklyGames.Msg['Puzzle.legs'])
        .appendField(new Blockly.FieldDropdown(Puzzle.legs), 'LEGS');
    this.appendStatementInput('TRAITS')
        .appendField(BlocklyGames.Msg['Puzzle.traits']);
    this.setInputsInline(false);
  },
  /**
   * Save the animal number.
   * @return {!Element} XML storage element.
   * @this {Blockly.Block}
   */
  mutationToDom: function() {
    const container = document.createElement('mutation');
    container.setAttribute('animal', this.animal);
    return container;
  },
  /**
   * Restore the animal number.
   * @param {!Element} xmlElement XML storage element.
   * @this {Blockly.Block}
   */
  domToMutation: function(xmlElement) {
    this.populate(parseInt(xmlElement.getAttribute('animal'), 10));
  },
  animal: 0,
  /**
   * Set the animal.
   * @param {number} n Animal number.
   * @this {Blockly.Block}
   */
  populate: function(n) {
    this.animal = n;
    this.setFieldValue(Puzzle.data[n - 1].name, 'NAME');
    this.helpUrl = Puzzle.data[n - 1].helpUrl;
  },
  /**
   * Evaluate the correctness of this block.
   * @this {Blockly.Block}
   */
  isCorrect: function() {
    return Number(this.getFieldValue('LEGS')) === this.animal;
  }
};

Blockly.Blocks['picture'] = {
  /**
   * Block to represent a picture.
   * @this {Blockly.Block}
   */
  init: function() {
    this.setColour(Puzzle.Blocks.PICTURE_HUE);
    this.appendDummyInput('PIC');
    this.setOutput(true);
    this.setTooltip('');
  },
  mutationToDom: Blockly.Blocks['animal'].mutationToDom,
  domToMutation: Blockly.Blocks['animal'].domToMutation,
  animal: 0,
  /**
   * Set the animal and picture.
   * @param {number} n Animal number.
   * @this {Blockly.Block}
   */
  populate: function(n) {
    this.animal = n;
    const pic = 'puzzle/' + Puzzle.data[n - 1].pic;
    const picHeight = Puzzle.data[n - 1].picHeight;
    const picWidth = Puzzle.data[n - 1].picWidth;
    this.getInput('PIC')
        .appendField(new Blockly.FieldImage(pic, picWidth, picHeight));
  },
  /**
   * Evaluate the correctness of this block.
   * @this {Blockly.Block}
   */
  isCorrect: function() {
    const parent = this.getParent();
    return parent && (parent.animal === this.animal);
  }
};

Blockly.Blocks['trait'] = {
  /**
   * Block to represent a trait.
   * @this {Blockly.Block}
   */
  init: function() {
    this.setColour(Puzzle.Blocks.TRAIT_HUE);
    this.appendDummyInput().appendField('', 'NAME');
    this.setPreviousStatement(true);
    this.setNextStatement(true);
  },
  /**
   * Save the animal and trait numbers.
   * @return {!Element} XML storage element.
   * @this {Blockly.Block}
   */
  mutationToDom: function() {
    const container = document.createElement('mutation');
    container.setAttribute('animal', this.animal);
    container.setAttribute('trait', this.trait);
    return container;
  },
  /**
   * Restore the animal and trait numbers.
   * @param {!Element} xmlElement XML storage element.
   * @this {Blockly.Block}
   */
  domToMutation: function(xmlElement) {
    this.populate(parseInt(xmlElement.getAttribute('animal'), 10),
                  parseInt(xmlElement.getAttribute('trait'), 10));
  },
  animal: 0,
  trait: 0,
  /**
   * Set the animal and trait.
   * @param {number} n Animal number.
   * @param {string} m Trait number.
   * @this {Blockly.Block}
   */
  populate: function(n, m) {
    this.animal = n;
    this.trait = m;
    // Set the trait name.
    this.setFieldValue(Puzzle.data[n - 1].traits[m - 1], 'NAME');
  },
  /**
   * Evaluate the correctness of this block.
   * @this {Blockly.Block}
   */
  isCorrect: function() {
    const parent = this.getSurroundParent();
    return parent && (parent.animal === this.animal);
  }
};
<|endoftext|>


<commit_before>var colors = [
	['#D0E78F', '#F6B759','#EC432E', '#9AD2E2', '#584050', '#2D4C7A'],
	['#C9E8EB', '#54DCE8', '#2792D6', '#E0D2D2', '#254540', '#F3EBE8'],
	['#EEE0C6', '#F0A48A', '#6A917C', '#A4C9A7', '#CCE6CB', '#3E3634'],
	['#E9E7EC', '#F8DEDD', '#FACC74', '#FD8C6A', '#D14747', '#B6D4A2'],
	['#FDC680', '#D9654C', '#6195A0', '#C9C9C9', '#422F21', '#68275D'],
	['#F8E8AF', '#F16766', '#D3003F', '#CDE58F', '#3C1452', '#4E6B4E'],
	['#F0E0E3', '#EEB8C9', '#D55395', '#D4E4AF', '#952E4B', '#81675C']
];

function randomFrom(min, max) {
	return Math.floor(Math.random() * (max - min + 1) + min);
}

function randomizeColor() {
	var randomColors = colors[randomFrom(0, colors.length - 1)];

	$('.color-space').each(function(i) {
		var delay = 500;
		$(this).css('background-color', randomColors[i]).delay(delay * i).fadeIn('slow');
	});
}

Template.colors.rendered = function () {
	randomizeColor();
};
<commit_msg>added a colors<commit_after>var colors = [
	['#D0E78F', '#F6B759','#EC432E', '#9AD2E2', '#584050', '#2D4C7A'],
	['#C9E8EB', '#54DCE8', '#2792D6', '#E0D2D2', '#254540', '#F3EBE8'],
	['#EEE0C6', '#F0A48A', '#6A917C', '#A4C9A7', '#CCE6CB', '#3E3634'],
	['#E9E7EC', '#F8DEDD', '#FACC74', '#FD8C6A', '#D14747', '#B6D4A2'],
	['#FDC680', '#D9654C', '#6195A0', '#C9C9C9', '#422F21', '#68275D'],
	['#F8E8AF', '#F16766', '#D3003F', '#CDE58F', '#3C1452', '#4E6B4E'],
	['#F0E0E3', '#EEB8C9', '#D55395', '#D4E4AF', '#952E4B', '#81675C'],
	['#FDE5B5', '#E1A88B', '#E5D2C3', '#9F8995', '#6B4C52']
];

function randomFrom(min, max) {
	return Math.floor(Math.random() * (max - min + 1) + min);
}

function randomizeColor() {
	var randomColors = colors[randomFrom(0, colors.length - 1)];

	$('.color-space').each(function(i) {
		var delay = 500;
		$(this).css('background-color', randomColors[i]).delay(delay * i).fadeIn('slow');
	});
}

Template.colors.rendered = function () {
	randomizeColor();
};
<|endoftext|>


<commit_before>import { Class } from '../../core/Core';
import '../../core/Number';  // For Number#limit
import { bind } from '../../foundation/Binding';
import '../../foundation/ComputedProps';  // For Function#property, #nocache
import '../../foundation/RunLoop';  // For Function#queue
import ScrollView from '../containers/ScrollView';
import View from '../View';
import ViewEventsController from '../ViewEventsController';

const ListKBFocusView = Class({

    Extends: View,

    selection: null,
    singleSelection: null,

    index: bind( 'singleSelection*index' ),
    record: bind( 'singleSelection*record' ),

    itemHeight: 32,

    keys: {
        j: 'goNext',
        k: 'goPrev',
        x: 'select',
        X: 'select',
        o: 'trigger',
        Enter: 'trigger',
        s: 'star',
    },

    className: 'v-ListKBFocus',

    positioning: 'absolute',

    layoutIndex: function () {
        const index = this.get( 'index' );
        const list = this.get( 'singleSelection' ).get( 'content' );
        if ( index > -1 && list &&
                list.getObjectAt( index ) !== this.get( 'record' ) ) {
            return -1;
        }
        return index;
    }.property( 'index', 'record' ),

    layout: function () {
        const itemHeight = this.get( 'itemHeight' );
        const index = this.get( 'layoutIndex' );
        return {
            visibility: index < 0 ? 'hidden' : 'visible',
            top: index < 0 ? 0 : itemHeight * index,
            height: itemHeight,
        };
    }.property( 'itemHeight', 'layoutIndex' ),

    didEnterDocument () {
        const keys = this.get( 'keys' );
        const shortcuts = ViewEventsController.kbShortcuts;
        for ( const key in keys ) {
            shortcuts.register( key, this, keys[ key ] );
        }
        this.checkInitialScroll();
        return ListKBFocusView.parent.didEnterDocument.call( this );
    },
    willLeaveDocument () {
        const keys = this.get( 'keys' );
        const shortcuts = ViewEventsController.kbShortcuts;
        for ( const key in keys ) {
            shortcuts.deregister( key, this, keys[ key ] );
        }
        return ListKBFocusView.parent.willLeaveDocument.call( this );
    },

    // Scroll to centre widget on screen with no animation
    checkInitialScroll: function () {
        if ( this.get( 'distanceFromVisRect' ) ) {
            this.scrollIntoView( 0, false );
        }
    }.queue( 'after' ),

    checkScroll: function () {
        const distance = this.get( 'distanceFromVisRect' );
        if ( distance ) {
            this.scrollIntoView( distance < 0 ? -0.6 : 0.6, true );
        }
    }.queue( 'after' ).observes( 'record' ),

    distanceFromVisRect: function () {
        const layoutIndex = this.get( 'layoutIndex' );
        const scrollView = this.getParent( ScrollView );
        if ( scrollView && layoutIndex > -1 &&
                this.get( 'isInDocument' ) && !this._needsRedraw ) {
            const scrollTop = scrollView.get( 'scrollTop' );
            const position = this.getPositionRelativeTo( scrollView );
            const top = position.top;
            const above = top - scrollTop;

            if ( above < 0 ) {
                return above;
            }

            const scrollHeight = scrollView.get( 'pxHeight' );
            const below = top + this.get( 'pxHeight' ) -
                scrollTop - scrollHeight;

            if ( below > 0 ) {
                return below;
            }
        }
        return 0;
    }.property().nocache(),

    scrollIntoView ( offset, withAnimation ) {
        const scrollView = this.getParent( ScrollView );
        if ( scrollView ) {
            const scrollHeight = scrollView.get( 'pxHeight' );
            const itemHeight = this.get( 'pxHeight' );
            const top = this.getPositionRelativeTo( scrollView ).top;

            if ( offset && -1 <= offset && offset <= 1 ) {
                offset = ( offset * ( scrollHeight - itemHeight ) ) >> 1;
            }
            scrollView.scrollTo( 0,
                Math.max( 0,
                    top +
                    ( ( itemHeight - scrollHeight ) >> 1 ) +
                    ( offset || 0 )
                ),
                withAnimation
            );
        }
    },

    go ( delta ) {
        const index = this.get( 'index' );
        const singleSelection = this.get( 'singleSelection' );
        const list = singleSelection.get( 'content' );
        const length = list && list.get( 'length' ) || 0;
        if ( delta === 1 && index > -1 && list &&
                list.getObjectAt( index ) !== this.get( 'record' ) ) {
            delta = 0;
        }
        if ( delta ) {
            singleSelection.set( 'index',
                ( index + delta ).limit( 0, length - 1 ) );
        } else {
            singleSelection.propertyDidChange( 'index' );
        }
    },
    goNext () {
        this.go( 1 );
    },
    goPrev () {
        this.go( -1 );
    },
    select ( event ) {
        const index = this.get( 'index' );
        const selection = this.get( 'selection' );
        const record = this.get( 'record' );
        // Check it's next to a loaded record.
        if ( selection && record ) {
            selection.selectIndex( index,
                !selection.isStoreKeySelected( record.get( 'storeKey' ) ),
                event.shiftKey );
        }
    },
    trigger () {},
    star () {},
});

export default ListKBFocusView;
<commit_msg>Only check initial list scroll if record changed<commit_after>import { Class } from '../../core/Core';
import '../../core/Number';  // For Number#limit
import { bind } from '../../foundation/Binding';
import '../../foundation/ComputedProps';  // For Function#property, #nocache
import '../../foundation/RunLoop';  // For Function#queue
import ScrollView from '../containers/ScrollView';
import View from '../View';
import ViewEventsController from '../ViewEventsController';

const ListKBFocusView = Class({

    Extends: View,

    selection: null,
    singleSelection: null,

    index: bind( 'singleSelection*index' ),
    record: bind( 'singleSelection*record' ),

    itemHeight: 32,

    keys: {
        j: 'goNext',
        k: 'goPrev',
        x: 'select',
        X: 'select',
        o: 'trigger',
        Enter: 'trigger',
        s: 'star',
    },

    className: 'v-ListKBFocus',

    positioning: 'absolute',

    layoutIndex: function () {
        const index = this.get( 'index' );
        const list = this.get( 'singleSelection' ).get( 'content' );
        if ( index > -1 && list &&
                list.getObjectAt( index ) !== this.get( 'record' ) ) {
            return -1;
        }
        return index;
    }.property( 'index', 'record' ),

    layout: function () {
        const itemHeight = this.get( 'itemHeight' );
        const index = this.get( 'layoutIndex' );
        return {
            visibility: index < 0 ? 'hidden' : 'visible',
            top: index < 0 ? 0 : itemHeight * index,
            height: itemHeight,
        };
    }.property( 'itemHeight', 'layoutIndex' ),

    didEnterDocument () {
        const keys = this.get( 'keys' );
        const shortcuts = ViewEventsController.kbShortcuts;
        for ( const key in keys ) {
            shortcuts.register( key, this, keys[ key ] );
        }
        return ListKBFocusView.parent.didEnterDocument.call( this );
    },
    willLeaveDocument () {
        const keys = this.get( 'keys' );
        const shortcuts = ViewEventsController.kbShortcuts;
        for ( const key in keys ) {
            shortcuts.deregister( key, this, keys[ key ] );
        }
        return ListKBFocusView.parent.willLeaveDocument.call( this );
    },

    // Scroll to centre widget on screen with no animation
    recordDidChange: function () {
        this._animateIntoView = this.get( 'isInDocument' );
        this.checkScroll();
    }.observes( 'record' ),

    checkScroll: function () {
        const distance = this.get( 'distanceFromVisRect' );
        const animateIntoView = this._animateIntoView;
        if ( distance ) {
            this.scrollIntoView(
                !animateIntoView ? 0 : distance < 0 ? -0.6 : 0.6,
                animateIntoView
            );
        }
    }.queue( 'after' ),

    distanceFromVisRect: function () {
        const layoutIndex = this.get( 'layoutIndex' );
        const scrollView = this.getParent( ScrollView );
        if ( scrollView && layoutIndex > -1 &&
                this.get( 'isInDocument' ) && !this._needsRedraw ) {
            const scrollTop = scrollView.get( 'scrollTop' );
            const position = this.getPositionRelativeTo( scrollView );
            const top = position.top;
            const above = top - scrollTop;

            if ( above < 0 ) {
                return above;
            }

            const scrollHeight = scrollView.get( 'pxHeight' );
            const below = top + this.get( 'pxHeight' ) -
                scrollTop - scrollHeight;

            if ( below > 0 ) {
                return below;
            }
        }
        return 0;
    }.property().nocache(),

    scrollIntoView ( offset, withAnimation ) {
        const scrollView = this.getParent( ScrollView );
        if ( scrollView ) {
            const scrollHeight = scrollView.get( 'pxHeight' );
            const itemHeight = this.get( 'pxHeight' );
            const top = this.getPositionRelativeTo( scrollView ).top;

            if ( offset && -1 <= offset && offset <= 1 ) {
                offset = ( offset * ( scrollHeight - itemHeight ) ) >> 1;
            }
            scrollView.scrollTo( 0,
                Math.max( 0,
                    top +
                    ( ( itemHeight - scrollHeight ) >> 1 ) +
                    ( offset || 0 )
                ),
                withAnimation
            );
        }
    },

    go ( delta ) {
        const index = this.get( 'index' );
        const singleSelection = this.get( 'singleSelection' );
        const list = singleSelection.get( 'content' );
        const length = list && list.get( 'length' ) || 0;
        if ( delta === 1 && index > -1 && list &&
                list.getObjectAt( index ) !== this.get( 'record' ) ) {
            delta = 0;
        }
        if ( delta ) {
            singleSelection.set( 'index',
                ( index + delta ).limit( 0, length - 1 ) );
        } else {
            singleSelection.propertyDidChange( 'index' );
        }
    },
    goNext () {
        this.go( 1 );
    },
    goPrev () {
        this.go( -1 );
    },
    select ( event ) {
        const index = this.get( 'index' );
        const selection = this.get( 'selection' );
        const record = this.get( 'record' );
        // Check it's next to a loaded record.
        if ( selection && record ) {
            selection.selectIndex( index,
                !selection.isStoreKeySelected( record.get( 'storeKey' ) ),
                event.shiftKey );
        }
    },
    trigger () {},
    star () {},
});

export default ListKBFocusView;
<|endoftext|>


<commit_before>(function() {

var checkVersion = Dagaz.Model.checkVersion;

Dagaz.Model.checkVersion = function(design, name, value) {
  if (name != "cyclic-checkers-restrictions") {
      checkVersion(design, name, value);
  }
}

var isTarget = function(design, board, pos, dir, piece) {
  var p = design.navigate(1, pos, dir);
  if (piece.type == 1) {
      while (p !== null) {
          if (board.getPiece(p) !== null) break;
          p = design.navigate(1, p, dir);
      }
  }
  if (p === null) return false;
  var x = board.getPiece(p);
  if (x === null) return false;
  if (x.player == board.player) return false;
  p = design.navigate(1, p, dir);
  if (p === null) return false;
  return board.getPiece(p) === null;
}

var CheckInvariants = Dagaz.Model.CheckInvariants;

Dagaz.Model.CheckInvariants = function(board) {
  var design = Dagaz.Model.design;
  _.each(board.moves, function(move) {
      var piece = null; var target = null;
      for (var i = 0; i < move.actions.length; i++) {
           if (piece === null) {
               if ((move.actions[i][0] !== null) && (move.actions[i][1] !== null)) {
                    piece = board.getPiece(move.actions[i][0][0]);
                    if (piece === null) return;
               }
           }
           if (target !== null) {
               if ((move.actions[i][0] !== null) && (move.actions[i][1] !== null)) {
                    var pos = move.actions[i][0][0];
                    _.each([0, 1, 2, 3], function(dir) {
                        if (isTarget(design, board, pos, dir, piece)) move.failed = true;
                    });
               }
               target = null;
           }
           if ((move.actions[i][0] !== null) && (move.actions[i][1] === null)) {
               target = board.getPiece(move.actions[i][0][0]);
               if (target.player != board.player) {
                   target = null;
               }
           }
      }
  });
  CheckInvariants(board);
}

})();
<commit_msg>Cyclic Checkers (restrictions fixed)<commit_after>(function() {

var checkVersion = Dagaz.Model.checkVersion;

Dagaz.Model.checkVersion = function(design, name, value) {
  if (name != "cyclic-checkers-restrictions") {
      checkVersion(design, name, value);
  }
}

var isTarget = function(design, board, pos, dir, piece, captured) {
  var p = design.navigate(1, pos, dir);
  if (piece.type == 1) {
      while (p !== null) {
          if (board.getPiece(p) !== null) break;
          p = design.navigate(1, p, dir);
      }
  }
  if (p === null) return false;
  if (_.indexOf(captured, p) >= 0) return false;
  var x = board.getPiece(p);
  if (x === null) return false;
  if (x.player == board.player) return false;
  p = design.navigate(1, p, dir);
  if (p === null) return false;
  return board.getPiece(p) === null;
}

var CheckInvariants = Dagaz.Model.CheckInvariants;

Dagaz.Model.CheckInvariants = function(board) {
  var design = Dagaz.Model.design;
  _.each(board.moves, function(move) {
      var piece = null; var target = null;
      var captured = [];
      for (var i = 0; i < move.actions.length; i++) {
           if ((move.actions[i][0] !== null) && (move.actions[i][1] === null)) {
                captured.push(move.actions[i][0][0]);
           }
      }
      for (var i = 0; i < move.actions.length; i++) {
           if (piece === null) {
               if ((move.actions[i][0] !== null) && (move.actions[i][1] !== null)) {
                    piece = board.getPiece(move.actions[i][0][0]);
                    if (piece === null) return;
               }
           }
           if (target !== null) {
               if ((move.actions[i][0] !== null) && (move.actions[i][1] !== null)) {
                    var pos = move.actions[i][0][0];
                    _.each([0, 1, 2, 3], function(dir) {
                        if (isTarget(design, board, pos, dir, piece, captured)) move.failed = true;
                    });
               }
               target = null;
           }
           if ((move.actions[i][0] !== null) && (move.actions[i][1] === null)) {
               target = move.actions[i][0][0];
               var x = board.getPiece(target);
               if ((x === null) || (x.player != board.player)) {
                   target = null;
               }
           }
      }
  });
  CheckInvariants(board);
}

})();
<|endoftext|>


<commit_before>/*
 * Order champions by approximate player skill
 */

var utils = require("../../utils"),
	StaticData = require("../StaticData").data;

var addFactor = (result, data, factor) => {
	for(var champion_key in data) {
		var champion = data[champion_key];

		result[champion.id] += ((data.length - champion_key) * factor);
	}
};

function formatChampionInfo(input) {
	var output = {};

	for(var key in input) {
		output[key] = {};
		output[key].info = input[key].info;
		output[key].youtube_link = input[key].youtube_link;
		output[key].spells = input[key].spells;
	}

	return output;
}

function evaluateBasedOnTag(tag, tag_priority, championMasteryPoints, championRankedStats) {
	var result = 0;

	switch(tag) {
		case "Melee": // Shen is special for some reason...
		case "Fighter":
			result += championRankedStats.kills.averageKills * 0.8;
			result += championRankedStats.kills.averageDeaths * -0.4;
			result += championRankedStats.kills.averageAssists * 0.2;
			result += (championRankedStats.damage.averageDealt / 3000) * 0.6;
			result += (championRankedStats.damage.averageTaken / 3000) * -0.3;
			result += (championRankedStats.gold.average / 1000) * 0.1;
		break;
		case "Support":
			result += championRankedStats.kills.averageKills * 0.3;
			result += championRankedStats.kills.averageDeaths * -0.1;
			result += championRankedStats.kills.averageAssists * 0.6;
			result += (championRankedStats.damage.averageDealt / 3000) * 0.3;
			result += (championRankedStats.damage.averageTaken / 3000) * -0.2;
			result += (championRankedStats.gold.average / 1000) * 0.1;
			result = result * 1.05;
		break;
		case "Tank":
			result += championRankedStats.kills.averageKills * 0.4;
			result += championRankedStats.kills.averageDeaths * -0.2;
			result += championRankedStats.kills.averageAssists * 0.3;
			result += (championRankedStats.damage.averageDealt / 3000) * 0.4;
			result += (championRankedStats.gold.average / 1000) * 0.1;
		break;
		case "Assassin":
			result += championRankedStats.kills.averageKills;
			result += championRankedStats.kills.averageDeaths * -0.4;
			result += championRankedStats.kills.averageAssists * 0.2;
			result += (championRankedStats.damage.averageDealt / 3000) * 0.4;
			result += (championRankedStats.damage.averageTaken / 3000) * -0.3;
			result += (championRankedStats.gold.average / 1000) * 0.1;
			result = result * 0.95;
		break;
		case "Mage":
			result += championRankedStats.kills.averageKills * 0.6;
			result += championRankedStats.kills.averageDeaths * -0.3;
			result += championRankedStats.kills.averageAssists * 0.4;
			result += (championRankedStats.damage.averageDealt / 3000) * 0.5;
			result += (championRankedStats.damage.averageTaken / 3000) * -0.3;
			result += (championRankedStats.gold.average / 1000) * 0.1;
		break;
		case "Marksman":
			result += championRankedStats.kills.averageKills * 0.9;
			result += championRankedStats.kills.averageDeaths * -0.5;
			result += championRankedStats.kills.averageAssists * 0.4;
			result += (championRankedStats.damage.averageDealt / 3000) * 0.6;
			result += (championRankedStats.damage.averageTaken / 3000) * -0.5;
			result += (championRankedStats.gold.average / 1000) * 0.1;
			result = result * 0.95;
	}

	result = result * ((championRankedStats.outcome.rate + 1) / 2);
	result = result * (championMasteryPoints / 21600);
	if(tag_priority === 0)
		result = result * 0.6;
	else if(tag_priority === 1)
		result = result * 0.4;

	return result;
}

// Create object for champion mastery data with key of champion ID
function sortChampionMastery(championMasteryData) {
	var result = {};

	for(var champion of championMasteryData)
		result[champion.championId] = champion;

	return result;
}

module.exports = (ranked_stats, champion_mastery) => {
	var result = {};

	champion_mastery = sortChampionMastery(champion_mastery);

	var aggregateStats = {
		outcome: {
			won: 0,
			lost: 0,
			played: 0
		},
		kills: {
			kills: 0,
			deaths: 0,
			assists: 0
		},
		damage: {
			dealt: 0,
			taken: 0
		},
		gold: 0
	};

	for(var champion_id in ranked_stats) {
		var champion = ranked_stats[champion_id],
			masteryScore = champion_mastery[champion_id].championPoints;

		result[champion.id] = 0;
		aggregateStats.outcome.won += champion.outcome.won;
		aggregateStats.outcome.lost += champion.outcome.lost;
		aggregateStats.outcome.played += champion.outcome.played;
		aggregateStats.kills.kills += champion.kills.kills;
		aggregateStats.kills.deaths += champion.kills.deaths;
		aggregateStats.kills.assists += champion.kills.assists;
		aggregateStats.damage.dealt += champion.damage.dealt;
		aggregateStats.damage.taken += champion.damage.taken;
		aggregateStats.gold += champion.gold.total;

		ranked_stats[champion_id].mastery = champion_mastery[champion_id];

		for(var tag_priority in champion.tags)
			result[champion.id] += evaluateBasedOnTag(champion.tags[tag_priority], champion.tags.length === 1 ? -1 : tag_priority, masteryScore, champion);
	}

	result = Object.keys(result).sort((a, b) => {
		return result[b] - result[a]
	});

	var result_populated = [];

	for(var key in result) {
		var val = result[key];
		result_populated.push(ranked_stats[val]);
	}

	return {
		champions: result_populated,
		aggregateStats: aggregateStats,
		championInfo: formatChampionInfo(ranked_stats),
		baseURL: StaticData.realm.cdn + "/"+ StaticData.realm.v
	};
};<commit_msg>Default 0 for champion mastery points<commit_after>/*
 * Order champions by approximate player skill
 */

var utils = require("../../utils"),
	StaticData = require("../StaticData").data;

var addFactor = (result, data, factor) => {
	for(var champion_key in data) {
		var champion = data[champion_key];

		result[champion.id] += ((data.length - champion_key) * factor);
	}
};

function formatChampionInfo(input) {
	var output = {};

	for(var key in input) {
		output[key] = {};
		output[key].info = input[key].info;
		output[key].youtube_link = input[key].youtube_link;
		output[key].spells = input[key].spells;
	}

	return output;
}

function evaluateBasedOnTag(tag, tag_priority, championMasteryPoints, championRankedStats) {
	var result = 0;

	switch(tag) {
		case "Melee": // Shen is special for some reason...
		case "Fighter":
			result += championRankedStats.kills.averageKills * 0.8;
			result += championRankedStats.kills.averageDeaths * -0.4;
			result += championRankedStats.kills.averageAssists * 0.2;
			result += (championRankedStats.damage.averageDealt / 3000) * 0.6;
			result += (championRankedStats.damage.averageTaken / 3000) * -0.3;
			result += (championRankedStats.gold.average / 1000) * 0.1;
		break;
		case "Support":
			result += championRankedStats.kills.averageKills * 0.3;
			result += championRankedStats.kills.averageDeaths * -0.1;
			result += championRankedStats.kills.averageAssists * 0.6;
			result += (championRankedStats.damage.averageDealt / 3000) * 0.3;
			result += (championRankedStats.damage.averageTaken / 3000) * -0.2;
			result += (championRankedStats.gold.average / 1000) * 0.1;
			result = result * 1.05;
		break;
		case "Tank":
			result += championRankedStats.kills.averageKills * 0.4;
			result += championRankedStats.kills.averageDeaths * -0.2;
			result += championRankedStats.kills.averageAssists * 0.3;
			result += (championRankedStats.damage.averageDealt / 3000) * 0.4;
			result += (championRankedStats.gold.average / 1000) * 0.1;
		break;
		case "Assassin":
			result += championRankedStats.kills.averageKills;
			result += championRankedStats.kills.averageDeaths * -0.4;
			result += championRankedStats.kills.averageAssists * 0.2;
			result += (championRankedStats.damage.averageDealt / 3000) * 0.4;
			result += (championRankedStats.damage.averageTaken / 3000) * -0.3;
			result += (championRankedStats.gold.average / 1000) * 0.1;
			result = result * 0.95;
		break;
		case "Mage":
			result += championRankedStats.kills.averageKills * 0.6;
			result += championRankedStats.kills.averageDeaths * -0.3;
			result += championRankedStats.kills.averageAssists * 0.4;
			result += (championRankedStats.damage.averageDealt / 3000) * 0.5;
			result += (championRankedStats.damage.averageTaken / 3000) * -0.3;
			result += (championRankedStats.gold.average / 1000) * 0.1;
		break;
		case "Marksman":
			result += championRankedStats.kills.averageKills * 0.9;
			result += championRankedStats.kills.averageDeaths * -0.5;
			result += championRankedStats.kills.averageAssists * 0.4;
			result += (championRankedStats.damage.averageDealt / 3000) * 0.6;
			result += (championRankedStats.damage.averageTaken / 3000) * -0.5;
			result += (championRankedStats.gold.average / 1000) * 0.1;
			result = result * 0.95;
	}

	result = result * ((championRankedStats.outcome.rate + 1) / 2);
	result = result * (championMasteryPoints / 21600);
	if(tag_priority === 0)
		result = result * 0.6;
	else if(tag_priority === 1)
		result = result * 0.4;

	return result;
}

// Create object for champion mastery data with key of champion ID
function sortChampionMastery(championMasteryData) {
	var result = {};

	for(var champion of championMasteryData)
		result[champion.championId] = champion;

	return result;
}

module.exports = (ranked_stats, champion_mastery) => {
	var result = {};

	champion_mastery = sortChampionMastery(champion_mastery);

	var aggregateStats = {
		outcome: {
			won: 0,
			lost: 0,
			played: 0
		},
		kills: {
			kills: 0,
			deaths: 0,
			assists: 0
		},
		damage: {
			dealt: 0,
			taken: 0
		},
		gold: 0
	};

	for(var champion_id in ranked_stats) {
		var champion = ranked_stats[champion_id],
			masteryScore = champion_mastery[champion_id] ? champion_mastery[champion_id].championPoints : 0;

		result[champion.id] = 0;
		aggregateStats.outcome.won += champion.outcome.won;
		aggregateStats.outcome.lost += champion.outcome.lost;
		aggregateStats.outcome.played += champion.outcome.played;
		aggregateStats.kills.kills += champion.kills.kills;
		aggregateStats.kills.deaths += champion.kills.deaths;
		aggregateStats.kills.assists += champion.kills.assists;
		aggregateStats.damage.dealt += champion.damage.dealt;
		aggregateStats.damage.taken += champion.damage.taken;
		aggregateStats.gold += champion.gold.total;

		ranked_stats[champion_id].mastery = champion_mastery[champion_id];

		for(var tag_priority in champion.tags)
			result[champion.id] += evaluateBasedOnTag(champion.tags[tag_priority], champion.tags.length === 1 ? -1 : tag_priority, masteryScore, champion);
	}

	result = Object.keys(result).sort((a, b) => {
		return result[b] - result[a]
	});

	var result_populated = [];

	for(var key in result) {
		var val = result[key];
		result_populated.push(ranked_stats[val]);
	}

	return {
		champions: result_populated,
		aggregateStats: aggregateStats,
		championInfo: formatChampionInfo(ranked_stats),
		baseURL: StaticData.realm.cdn + "/"+ StaticData.realm.v
	};
};<|endoftext|>


<commit_before>/*
---
name: Stacker
description: A z-index manager for ART widgets.
requires: [Core/Class.Extras, Core/Element.Event, Core/Element.Style, More/Keyboard]
provides: Stacker
...
*/

/*
	Manages z-index ordering of objects as well as their focused state.
*/

var Stacker = new Class({

	Implements: [Options, Events],

	options: {
		//the base z-index for the first item in the stack; every other item is incrementally higher
		zIndexBase: 0,
		//when cascading, the offset to use
		offset: {
			x: 20,
			y: 10
		}
	},

	instances: [],

	initialize: function(options) {
		this.setOptions(options);
		this.layers = $H();
		this.setLayer('default');
	},

	/*
		sets / creates a layer and assigns it a zIndex
		zIndex defaults to the one in the options.
		a layer an object w/ a zIndex, name, and an array of the instance in that layer
	*/

	setLayer: function(name, zIndex) {
		zIndex = zIndex == undefined ? this.options.zIndexBase : zIndex;
		if (this.layers[name]) {
			this.layers[name].zIndex = zIndex;
		} else {
			this.layers[name] = {
				zIndex: zIndex,
				name: name,
				instances: []
			};
		}
		return this.getLayer(name);
	},

	//retrieves a layer given a name; will create it if not found
	//if passed a layer it returns it
	getLayer: function(layer, defaultZIndex) {
		if ($type(layer) == "string" && !this.layers[layer]) this.setLayer(layer, defaultZIndex);
		return this.layers[layer] || layer;
	},

	//registers an instance on a layer (registers it in the default layer if none specified)
	register: function(instance, layer){
		layer = layer || 'default';
		//if the instance was previously registered, move it to the new layer
		var registered = this.instances.contains(instance);
		if (registered && this.getLayerForInstance(instance)) {
			var instanceLayer = this.getLayerForInstance(instance);
			if (instanceLayer == layer) return;
			instanceLayer.instances.erase(instance);
		} else  {
			document.id(instance).addEvent('mousedown', function(){
				if (!instance.getState('focused')) this.focus(instance);
			}.bind(this));
			this.instances.include(instance);
		}
		if (!this.layers[layer]) this.getLayer(layer, this.options.zIndexBase);
		this.layers[layer].instances.include(instance);
	},

	//removes an instance from this stacker's control
	unregister: function(instance) {
		var refocus = this.focused == instance;
		var iLayer = this.getLayerForInstance(instance);
		if (!iLayer) return;
		this.instances.erase(instance);
		this.layers.each(function(layer) {
			if (layer.instances.contains(instance)) layer.instances.erase(instance);
		});
		if (refocus) {
			if (iLayer.instances.length) this.focus(iLayer.instances[iLayer.instances.length -1]);
			else if (this.instances.length) this.focus(this.instances[this.instances.length -1]);
		}
	},

	//retrieves the layer for a given instance
	getLayerForInstance: function(instance) {
		var ret;
		this.layers.each(function(layer) {
			if (layer.instances.contains(instance)) ret = layer;
		});
		return ret;
	},

	//z-index orders a layer so that a specific instance is on top
	bringToFront: function(instance){
		if (!instance || (instance == this.focused && instance._stacked)) return;
		this.layers.each(function(layer) {
			var i = 0;
			if (!layer.instances.contains(instance)) return;
			layer.instances.erase(instance).push(instance);
			this.stack(layer);
		}, this);
	},

	//assigns the zindex order for all the instances in a layer based on their order
	stack: function(layer) {
		layer.instances.each(function(win, i){
			document.id(win).setStyle('z-index', layer.zIndex + (i*2));
			win._stacked = true;
		}, this);
	},

	focusTop: function(layer) {
		layer = this.getLayer(layer || "default");
		var instance;

		for (var i = layer.instances.length - 1; i > 0; i = i-1) {
			if (document.id(layer.instances[i]).getStyle('display') != 'none') {
				instance = layer.instances[i];
				break;
			}
		}

		if (instance) this.focus(instance);
	},

	//cycles the zIndex for a given layer forward or back
	cycle: function(direction, layerName) {
		direction = direction || 'forward';
		var instances = this.layers[layerName].instances;
		if (!instances.length) return;
		if (direction == 'forward') instances.push(instances.shift());
		else instances.unshift(instances.pop());
		this.stack(this.layers[layerName]);
		this.focus(instances[instances.length -1], true);
	},

	//focus an instance, (optionally) bringing it to front
	focus: function(instance, noOrder){
		if (!instance || (instance == this.focused && instance._stacked && instance.getState('focused'))) return;
		if (this.focused && this.focused != instance) this.focused.blur();
		if (instance.getState('disabled')) return;
		if (!noOrder) this.bringToFront(instance);
		instance._focus();
		this.focused = instance;
	},

	//moves all the instances to be in a cascaded line
	cascade: function(layer, x, y){
		x = $pick(x, this.options.offset.x);
		y = $pick(y, this.options.offset.y);
		this.layers[layer].instances.each(function(current, i){
			var styles = {top: (y * i) + y, left: (x * i) + x};
			document.id(current).setStyles(styles);
		});
	},

	//positions new instances based on the current location of the focused instance
	positionNew: function(instance, options){
		var pos = true;
		//if there are no instances other than this one, or one instance
		//or the position is not set or is equal to the focused instances options
		//then return; and let the window be positioned as the class would normally.
		var current;
		var instances = this.getLayerForInstance(instance).instances.filter(function(instance){
			return !instance.getState('hidden') && document.id(instance);
		});
		instances.reverse().some(function(win){
			if (win != instance && document.id(win) && document.id(win).getStyle('display') != 'none') {
				current = win;
				return true;
			}
		});
		if (options) {
			//if the position is not defined in the options
			//or, if it is, the position is the same as the focused instance's options
			//such that opening with the same options will place them on top of each other
			//(assuming the first one hasn't moved)
			pos = ['top', 'left', 'edge', 'position', 'relativeTo'].every(function(opt){
				curOpt = current ? current.options[opt] : null;
				return curOpt == options[opt];
			}, this);
		}
		this.focus(instance);
		if (instances.length < 1 || !pos || !current) return false;
		var instanceEl = document.id(instance);
		//position near the focused instance, with an offset as defined in the options
                if(current instanceof ART.Popup) current = current.parentWidget;
		instanceEl.position({
			relativeTo: document.id(current),
			offset: this.options.offset,
			edge: 'upperLeft',
			position: 'upperLeft'
		});
		pos = instanceEl.getPosition();
		var size = instanceEl.getSize();
		var bottom = pos.y + size.y;
		var right = pos.x + size.x;
		var containerSize = document.id(document.body).getSize();
		if (bottom > containerSize.y || right > containerSize.x) {
			instanceEl.position({
				relativeTo: instance.options.inject.target,
				offset: this.options.offset,
				edge: 'upperLeft',
				position: 'upperLeft'
			});
		}

		return true;
	}

});<commit_msg>Only get parentWidget if it exists<commit_after>/*
---
name: Stacker
description: A z-index manager for ART widgets.
requires: [Core/Class.Extras, Core/Element.Event, Core/Element.Style, More/Keyboard]
provides: Stacker
...
*/

/*
	Manages z-index ordering of objects as well as their focused state.
*/

var Stacker = new Class({

	Implements: [Options, Events],

	options: {
		//the base z-index for the first item in the stack; every other item is incrementally higher
		zIndexBase: 0,
		//when cascading, the offset to use
		offset: {
			x: 20,
			y: 10
		}
	},

	instances: [],

	initialize: function(options) {
		this.setOptions(options);
		this.layers = $H();
		this.setLayer('default');
	},

	/*
		sets / creates a layer and assigns it a zIndex
		zIndex defaults to the one in the options.
		a layer an object w/ a zIndex, name, and an array of the instance in that layer
	*/

	setLayer: function(name, zIndex) {
		zIndex = zIndex == undefined ? this.options.zIndexBase : zIndex;
		if (this.layers[name]) {
			this.layers[name].zIndex = zIndex;
		} else {
			this.layers[name] = {
				zIndex: zIndex,
				name: name,
				instances: []
			};
		}
		return this.getLayer(name);
	},

	//retrieves a layer given a name; will create it if not found
	//if passed a layer it returns it
	getLayer: function(layer, defaultZIndex) {
		if ($type(layer) == "string" && !this.layers[layer]) this.setLayer(layer, defaultZIndex);
		return this.layers[layer] || layer;
	},

	//registers an instance on a layer (registers it in the default layer if none specified)
	register: function(instance, layer){
		layer = layer || 'default';
		//if the instance was previously registered, move it to the new layer
		var registered = this.instances.contains(instance);
		if (registered && this.getLayerForInstance(instance)) {
			var instanceLayer = this.getLayerForInstance(instance);
			if (instanceLayer == layer) return;
			instanceLayer.instances.erase(instance);
		} else  {
			document.id(instance).addEvent('mousedown', function(){
				if (!instance.getState('focused')) this.focus(instance);
			}.bind(this));
			this.instances.include(instance);
		}
		if (!this.layers[layer]) this.getLayer(layer, this.options.zIndexBase);
		this.layers[layer].instances.include(instance);
	},

	//removes an instance from this stacker's control
	unregister: function(instance) {
		var refocus = this.focused == instance;
		var iLayer = this.getLayerForInstance(instance);
		if (!iLayer) return;
		this.instances.erase(instance);
		this.layers.each(function(layer) {
			if (layer.instances.contains(instance)) layer.instances.erase(instance);
		});
		if (refocus) {
			if (iLayer.instances.length) this.focus(iLayer.instances[iLayer.instances.length -1]);
			else if (this.instances.length) this.focus(this.instances[this.instances.length -1]);
		}
	},

	//retrieves the layer for a given instance
	getLayerForInstance: function(instance) {
		var ret;
		this.layers.each(function(layer) {
			if (layer.instances.contains(instance)) ret = layer;
		});
		return ret;
	},

	//z-index orders a layer so that a specific instance is on top
	bringToFront: function(instance){
		if (!instance || (instance == this.focused && instance._stacked)) return;
		this.layers.each(function(layer) {
			var i = 0;
			if (!layer.instances.contains(instance)) return;
			layer.instances.erase(instance).push(instance);
			this.stack(layer);
		}, this);
	},

	//assigns the zindex order for all the instances in a layer based on their order
	stack: function(layer) {
		layer.instances.each(function(win, i){
			document.id(win).setStyle('z-index', layer.zIndex + (i*2));
			win._stacked = true;
		}, this);
	},

	focusTop: function(layer) {
		layer = this.getLayer(layer || "default");
		var instance;

		for (var i = layer.instances.length - 1; i > 0; i = i-1) {
			if (document.id(layer.instances[i]).getStyle('display') != 'none') {
				instance = layer.instances[i];
				break;
			}
		}

		if (instance) this.focus(instance);
	},

	//cycles the zIndex for a given layer forward or back
	cycle: function(direction, layerName) {
		direction = direction || 'forward';
		var instances = this.layers[layerName].instances;
		if (!instances.length) return;
		if (direction == 'forward') instances.push(instances.shift());
		else instances.unshift(instances.pop());
		this.stack(this.layers[layerName]);
		this.focus(instances[instances.length -1], true);
	},

	//focus an instance, (optionally) bringing it to front
	focus: function(instance, noOrder){
		if (!instance || (instance == this.focused && instance._stacked && instance.getState('focused'))) return;
		if (this.focused && this.focused != instance) this.focused.blur();
		if (instance.getState('disabled')) return;
		if (!noOrder) this.bringToFront(instance);
		instance._focus();
		this.focused = instance;
	},

	//moves all the instances to be in a cascaded line
	cascade: function(layer, x, y){
		x = $pick(x, this.options.offset.x);
		y = $pick(y, this.options.offset.y);
		this.layers[layer].instances.each(function(current, i){
			var styles = {top: (y * i) + y, left: (x * i) + x};
			document.id(current).setStyles(styles);
		});
	},

	//positions new instances based on the current location of the focused instance
	positionNew: function(instance, options){
		var pos = true;
		//if there are no instances other than this one, or one instance
		//or the position is not set or is equal to the focused instances options
		//then return; and let the window be positioned as the class would normally.
		var current;
		var instances = this.getLayerForInstance(instance).instances.filter(function(instance){
			return !instance.getState('hidden') && document.id(instance);
		});
		instances.reverse().some(function(win){
			if (win != instance && document.id(win) && document.id(win).getStyle('display') != 'none') {
				current = win;
				return true;
			}
		});
		if (options) {
			//if the position is not defined in the options
			//or, if it is, the position is the same as the focused instance's options
			//such that opening with the same options will place them on top of each other
			//(assuming the first one hasn't moved)
			pos = ['top', 'left', 'edge', 'position', 'relativeTo'].every(function(opt){
				curOpt = current ? current.options[opt] : null;
				return curOpt == options[opt];
			}, this);
		}
		this.focus(instance);
		if (instances.length < 1 || !pos || !current) return false;
		var instanceEl = document.id(instance);
		//position near the focused instance, with an offset as defined in the options
                if(current instanceof ART.Popup && current.parentWidget) current = current.parentWidget;
		instanceEl.position({
			relativeTo: document.id(current),
			offset: this.options.offset,
			edge: 'upperLeft',
			position: 'upperLeft'
		});
		pos = instanceEl.getPosition();
		var size = instanceEl.getSize();
		var bottom = pos.y + size.y;
		var right = pos.x + size.x;
		var containerSize = document.id(document.body).getSize();
		if (bottom > containerSize.y || right > containerSize.x) {
			instanceEl.position({
				relativeTo: instance.options.inject.target,
				offset: this.options.offset,
				edge: 'upperLeft',
				position: 'upperLeft'
			});
		}

		return true;
	}

});<|endoftext|>


<commit_before>Template.tierRow.rendered = function() {
   $("[data-toggle='tooltip']").tooltip();
};

Template.tierRow.helpers({
  prizeLoop: function (prizes) {
    var tierId = this._id;
    var prizeList = [];
    var i = 1;
    var sortedPrizes = _.sortBy(prizes, function(p) {return p.pos;});

    // fill unused spaces with empty prizes
    // TODO make better
    _.each(sortedPrizes, function (p) {
      while (p.pos > i) {
        prizeList.push({_id: Random.id(), pos: i, prize: null, tierId: tierId});
        i++;
      }
      prizeList.push(_.extend({}, p, {tierId: tierId}));
      i++;
    });
    while (i < 11) {
      prizeList.push({_id: Random.id(), pos: i, prize: null, tierId: tierId});
      i++;
    }
    return prizeList;
  },
  isLottoOpen: function() {
    return !Lottos.findOne().closed;
  },
  attributes: function() {
    if (!!this.winner) {
      return { class: "winner" };
    }
    return {};
  },
  whichever: function(name1, name2) {
    if (!!name1) return name1;
    return name2;
  },
  winnerName: function() {
    var winnerPrize = _.find(this.prizes, function(p) {return !!p.winner;});
    if (winnerPrize) {
      var that = this;
      var entry = _.find(Lottos.findOne().entries, function(e) { return e.amount === that.tier && e.winner;});
      return GWUsers.findOne(entry.gwuserId).alts[0];
    }
  },
  winnerItem: function() {
    var winnerPrize = _.find(this.prizes, function(p) {return !!p.winner;});
    if (winnerPrize) {
      return winnerPrize.name;
    }
  }
});

Template.tierRow.events({
  'click .tier-number': function (e) {
    e.preventDefault();
    if (Session.equals('SelectedTier', this.tier)) {
      Session.set('SelectedTier', null);
    }
    else {
      Session.set('SelectedTier', this.tier);
    }
  },
  'click .prize-row > td': function (e) {
    e.preventDefault();
    if (Session.equals('SelectedPrize', this._id)) {
      Session.set('SelectedPrize', null);
    }
    else {
      Session.set('SelectedPrize', this._id);
    }
  }
});
<commit_msg>Added template helpers to tier_row to get info about entries<commit_after>Template.tierRow.rendered = function() {
   $("[data-toggle='tooltip']").tooltip();
};

Template.tierRow.helpers({
  prizeLoop: function (prizes) {
    var tierId = this._id;
    var prizeList = [];
    var i = 1;
    var sortedPrizes = _.sortBy(prizes, function(p) {return p.pos;});

    // fill unused spaces with empty prizes
    // TODO make better
    _.each(sortedPrizes, function (p) {
      while (p.pos > i) {
        prizeList.push({_id: Random.id(), pos: i, prize: null, tierId: tierId});
        i++;
      }
      prizeList.push(_.extend({}, p, {tierId: tierId}));
      i++;
    });
    while (i < 11) {
      prizeList.push({_id: Random.id(), pos: i, prize: null, tierId: tierId});
      i++;
    }
    return prizeList;
  },
  isLottoOpen: function() {
    return !Lottos.findOne().closed;
  },
  attributes: function() {
    if (!!this.winner) {
      return { class: "winner" };
    }
    return {};
  },
  whichever: function(name1, name2) {
    if (!!name1) return name1;
    return name2;
  },
  hasNoWinner: function() {
    return !_.any(this.prizes, function(p) { return !!p.winner; });
  },
  entriesLength: function() {
    return _.filter(Lottos.findOne().entries, (e) => e.amount === this.tier).length;
  },
  hasEntries: function() {
    return _.any(Lottos.findOne().entries, (e) => e.amount === this.tier);
  },
  hasOne: function() {
    return _.filter(Lottos.findOne().entries, (e) => e.amount === this.tier).length === 1;
  },
  winnerName: function() {
    var winnerPrize = _.find(this.prizes, function(p) { return !!p.winner; });
    if (winnerPrize) {
      var that = this;
      var entry = _.find(Lottos.findOne().entries, function(e) { return e.amount === that.tier && e.winner;});
      return GWUsers.findOne(entry.gwuserId).alts[0];
    }
  },
  winnerItem: function() {
    var winnerPrize = _.find(this.prizes, function(p) {return !!p.winner;});
    if (winnerPrize) {
      return winnerPrize.name;
    }
  }
});

Template.tierRow.events({
  'click .tier-number': function (e) {
    e.preventDefault();
    if (Session.equals('SelectedTier', this.tier)) {
      Session.set('SelectedTier', null);
    }
    else {
      Session.set('SelectedTier', this.tier);
    }
  },
  'click .prize-row > td': function (e) {
    e.preventDefault();
    if (Session.equals('SelectedPrize', this._id)) {
      Session.set('SelectedPrize', null);
    }
    else {
      Session.set('SelectedPrize', this._id);
    }
  }
});
<|endoftext|>


<commit_before>import User from '../models/user';
import is from '../helpers/is';
import NError from '../libs/NError';
import _ from 'lodash';

export default {
  async get(req, res, next) {
    try {
      if (!is.objectId(req.params.id)) {
        throw new NError(400, 'invalid_parameter', 'Invalid parameter');
      }
      const user = await User.findOne({ _id: req.params.id });
      if (!user) {
        throw new NError(404, 'not_found', 'User not found');
      }
      // Render component with user
    } catch (err) {
      return next(err);
    }
  },

  async post(req, res, next) {
    try {
      if (req.body.id) {
        if (!is.objectId(req.body.id)) throw new HError(400, 'invalid_parameter', 'Invalid parameter');
      }
      const user = await User.findOne({ _id: req.body.id });
      if (user) {
        throw new NError(409, 'conflict', 'User already exist');
      }
      const createdUser = User.create(_.pick(req.body, ['id', 'name', 'login', 'avatar', 'location', 'rank', 'email', 'creation_date', 'followers']));
      // Render component with user
    } catch (err) {
      return next(err);
    }
  },

  async delete(req, res, next) {
    try {

    } catch (err) {
      return next(err);
    }
  },

  async list(req, res, next) {
    try {

    } catch (err) {
      return next(err);
    }
  }
}<commit_msg>before list<commit_after>import User from '../models/user';
import is from '../helpers/is';
import NError from '../libs/NError';
import _ from 'lodash';

export default {
  async get(req, res, next) {
    try {
      if (!is.objectId(req.params.id)) {
        throw new NError(400, 'invalid_parameter', 'Invalid parameter');
      }
      const user = await User.findOne({ _id: req.params.id });
      if (!user) {
        throw new NError(404, 'not_found', 'User not found');
      }
      // Render component with user
    } catch (err) {
      return next(err);
    }
  },

  async post(req, res, next) {
    try {
      if (req.body.id) {
        if (!is.objectId(req.body.id)) throw new HError(400, 'invalid_parameter', 'Invalid parameter');
      }
      const user = await User.findOne({ _id: req.body.id });
      if (user) {
        throw new NError(409, 'conflict', 'User already exist');
      }
      const createdUser = User.create(_.pick(req.body, ['id', 'name', 'login', 'avatar', 'location', 'rank', 'email', 'creation_date', 'followers']));
      // Render component with user
    } catch (err) {
      return next(err);
    }
  },

  async delete(req, res, next) {
    try {
      if (req.body.id) {
        if (!is.objectId(req.body.id)) throw new HError(400, 'invalid_parameter', 'Invalid parameter');
      }
      const user = await User.findOne({ _id: req.body.id })
      if (!user) {
        throw new NError(404, 'not_found', 'User not found');
      }
      await user.delegate();
      // Render component as true
    } catch (err) {
      return next(err);
    }
  },

  async list(req, res, next) {
    try {

    } catch (err) {
      return next(err);
    }
  }
}<|endoftext|>


<commit_before><commit_msg>Add Date.js file haders to make packager happy<commit_after>/*
---

script: Date.js

description: Date picker

license: MIT-style license.

authors: Yaroslaff Fedin

requires:
- ART.Widget.Input

provides: [ART.Widget.Input.Date]

...
*/

ART.Widget.Input.Date = new Class({
  Includes: [
    Widget.Trait.Input
  ],

  name: 'input'
});<|endoftext|>


<commit_before>define(['util'], (util) => {

  // Compare two arrays, each representing a semantic version in the form of [0,1,2]
  // Returns -1, 0, 1. Returns null if they're malformed
  function semverCompare(v1, v2) {
    for (var i = 0; i < 3; i++) {
      var token1 = Number(v1[i]);
      var token2 = Number(v2[i]);
      if (token1 > token2)
        return 1;
      if (token2 > token1)
        return -1;
      if (isNaN(token1) || isNaN(token2))
        return null;
    }
    return 0;
  }

  // Turn a string version (e.g. "1.1.20170411" or just "20170411") into a backward
  // compatible version array (e.g ["1","1","20170411"]).
  // If the version doesn't have MAJOR and MINOR components (old behavior), then
  // treat it as only the PATCH part of a semver. Hard code prefix to 0.5 to match
  // the old version strings, so that clients do not get inconsistent numbers
  function strToSemver(versionStr) {
    let semver = versionStr.toString().split('.').map(x => +x);
    if (semver.length !== 1 && semver.length !== 3) {
      util.debug.log('Malformed current version string. Found:', versionStr);
      return null;
    }
    // If only one component was found, it's the PATCH part
    if (semver.length === 1) {
      semver = [0, 5].concat(Number(semver[0]));
    }
    return semver;
  }

  function checkVersion(latestVersion) {
    // Current version is sent as part of the HTML template document from the notebook server
    var currentVersion = document.body.getAttribute('data-version-id');
    if (currentVersion === undefined || latestVersion === undefined) {
      util.debug.log('Failed to get current or latest version string.');
      return;
    }
    currentSemver = strToSemver(currentVersion);
    latestSemver = strToSemver(latestVersion.latest);
    lastSemver = strToSemver(latestVersion.last);

    // Compare, if current version is greater than or equal to latest, we're done
    if (semverCompare(currentSemver, latestSemver) > -1) {
      return;
    }

    // Old client. Display message to recommend update
    var optional = semverCompare(currentSemver, lastSemver) > -1;
    var messageDiv = document.getElementById('updateMessageArea');
    var message = 'You are using DataLab ' + currentSemver.join('.') + '. ' +
        (optional ? 'An optional' : 'A recommended') + ' update (' + latestSemver.join('.') +
        ') is available (see what\'s new).'
    messageDiv.innerHTML = message;
    messageDiv.classList.add('alert');
    messageDiv.classList.add(optional ? 'alert-warning' : 'alert-danger');
    messageDiv.style.display = 'block';
  }

  function postLoad(notebookList, newNotebook, dialog) {
    function addNotebook(e) {
      newNotebook.new_notebook();
      e.target.blur();

      var event = {
        'event': 'concordEvent',
        'pagePath': '/virtual/datalab/createNotebook',
        'eventType': 'datalab',
        'eventName': 'createNotebook',
      }
      util.reportEvent(event);
    }

    function addFolder(e) {
      notebookList.contents.new_untitled(notebookList.notebook_path || '', {type: 'directory'})
        .then(function(){
          notebookList.load_list();
        }).catch(function (e) {
          dialog.modal({
              title: 'Creating Folder Failed',
              body: $('
')
                      .text("An error occurred while creating a new folder.")
                      .append($('
')
                      .addClass('alert alert-danger')
                      .text(e.message || e)),
              buttons: {
                OK: { 'class': 'btn-primary' }
              }
          });
        });
      e.target.blur();
    }

    function addTerminal(e) {
      let newWindow = window.open(undefined, IPython._target);
      let addTerminalUrl = util.datalabLink('/api/terminals');
      let settings = {
        type : 'POST',
        dataType: 'json',
        success: (data, status, jqXHR) => {
          newWindow.location = util.datalabLink('/terminals/' + encodeURIComponent(data.name));
        },
        error : function(jqXHR, status, error){
          newWindow.close();
          util.debug.log(jqXHR, status, error);
        },
      };
      util.debug.log('Sending terminal request to ' + addTerminalUrl);
      $.ajax(addTerminalUrl, settings);
    }

    function openEditor(e) {
      Jupyter.notebook_list.selected.forEach(notebook => {
        window.open(util.datalabLink('/edit/' + notebook.path), '_blank');
      });
    }

    // Extend the selection changed method to show/hide the editor button
    notebookSelectedFn = notebookList._selection_changed;
    notebookList._selection_changed = function() {
      notebookSelectedFn.apply(this, arguments);
      if (notebookList.selected.length === 1 && notebookList.selected[0].type !== 'directory')
        $('#editorButton').show();
      else
        $('#editorButton').hide();
    }

    document.getElementById('addNotebookButton').addEventListener('click', addNotebook, false);
    document.getElementById('addFolderButton').addEventListener('click', addFolder, false);
    document.getElementById('addTerminalButton').addEventListener('click', addTerminal, false);
    document.getElementById('editorButton').addEventListener('click', openEditor, false);

    (function buildBreadcrumbContent() {
      var path = util.datalabSubPath(location.pathname);
      util.debug.log('Building breadcrumbs off of ' + path);

      // Strip off leading /tree and trailing / if present
      if (path.indexOf('/tree') == 0) {
        path = path.substr(5);
      }
      if (path.substr(-1) == '/') {
        path = path.substr(0, path.length - 1);
      }
      if (!path) {
        return;
      }

      var html = [];
      html.push('
');
      html.push('
home
');

      var segments = [];

      // Split the path into its segments, and convert into list items, ignoring the first
      // empty segment. Intermediate segments are also generated as navigation links.
      var pathParts = path.split('/');
      for (var i = 1; i < pathParts.length; i++) {
        var pathPart = pathParts[i];
        segments.push(pathPart);
        pathPart = decodeURIComponent(pathPart);

        var element;
        if (i == pathParts.length - 1) {
          element = '
' + pathPart + '
';
        }
        else {
          element = '
' + pathPart + '
';
        }

        html.push(element);
      }

      html.push('
');

      document.getElementById('project_name').innerHTML = html.join('');

    })();

    fileSearchPath = util.datalabLink('/_filesearch?');

    searchDiv = $('#tree-filter');
    $.getJSON(fileSearchPath, (result) => {
      if (result.tooManyFiles === true || !result.indexingEnabled) {
        searchDiv.prop('placeholder', 'File finder disabled');
        searchDiv.prop('disabled', true);
      } else {
        searchDiv.autocomplete({
          appendTo: '.tree-filter-complete',
          position: { of: '.tree-filter-complete' },
          source: (request, response) => {

            pattern = encodeURIComponent(searchDiv.val());
            patternSearchPath = fileSearchPath + 'pattern=' + pattern;

            if (patternSearchPath !== '') {
              $.getJSON(patternSearchPath, (result) => {
                response(result.files);
                if (result.fullResultSize > 20) {
                  $('.ui-autocomplete').append('
Showing 20 out of ' +
                    result.fullResultSize + ' results
');
                }
                if (result.tooManyFiles === true) {
                  $('.ui-autocomplete').prepend(
                    '
Too many files found. Showing partial results
');
                } else if (result.indexReady === false) {
                  $('.ui-autocomplete').prepend(
                    '
Indexing files.. Showing partial results
');
                }
              });
            }
          },
          select: (e, selected) => {
            var path = selected.item.value;
            if (path.endsWith('.ipynb')) {
              window.open(util.datalabLink("/notebooks/" + path));
            } else {
              window.open(util.datlabLink("/edit/" + path));
            }
          },
          delay: 500,
          messages: {
            noResults: '',
            results: function() {}
          }
        });
      }
    });

    checkVersion(window.datalab.versions);
  }

  return {
    postLoad: postLoad,
    _semverCompare: semverCompare,
    _strToSemver: strToSemver,
    _checkVersion: checkVersion
  };
});
<commit_msg>Breadcrumb links should use the configured base path. (#1451)<commit_after>define(['util'], (util) => {

  // Compare two arrays, each representing a semantic version in the form of [0,1,2]
  // Returns -1, 0, 1. Returns null if they're malformed
  function semverCompare(v1, v2) {
    for (var i = 0; i < 3; i++) {
      var token1 = Number(v1[i]);
      var token2 = Number(v2[i]);
      if (token1 > token2)
        return 1;
      if (token2 > token1)
        return -1;
      if (isNaN(token1) || isNaN(token2))
        return null;
    }
    return 0;
  }

  // Turn a string version (e.g. "1.1.20170411" or just "20170411") into a backward
  // compatible version array (e.g ["1","1","20170411"]).
  // If the version doesn't have MAJOR and MINOR components (old behavior), then
  // treat it as only the PATCH part of a semver. Hard code prefix to 0.5 to match
  // the old version strings, so that clients do not get inconsistent numbers
  function strToSemver(versionStr) {
    let semver = versionStr.toString().split('.').map(x => +x);
    if (semver.length !== 1 && semver.length !== 3) {
      util.debug.log('Malformed current version string. Found:', versionStr);
      return null;
    }
    // If only one component was found, it's the PATCH part
    if (semver.length === 1) {
      semver = [0, 5].concat(Number(semver[0]));
    }
    return semver;
  }

  function checkVersion(latestVersion) {
    // Current version is sent as part of the HTML template document from the notebook server
    var currentVersion = document.body.getAttribute('data-version-id');
    if (currentVersion === undefined || latestVersion === undefined) {
      util.debug.log('Failed to get current or latest version string.');
      return;
    }
    currentSemver = strToSemver(currentVersion);
    latestSemver = strToSemver(latestVersion.latest);
    lastSemver = strToSemver(latestVersion.last);

    // Compare, if current version is greater than or equal to latest, we're done
    if (semverCompare(currentSemver, latestSemver) > -1) {
      return;
    }

    // Old client. Display message to recommend update
    var optional = semverCompare(currentSemver, lastSemver) > -1;
    var messageDiv = document.getElementById('updateMessageArea');
    var message = 'You are using DataLab ' + currentSemver.join('.') + '. ' +
        (optional ? 'An optional' : 'A recommended') + ' update (' + latestSemver.join('.') +
        ') is available (see what\'s new).'
    messageDiv.innerHTML = message;
    messageDiv.classList.add('alert');
    messageDiv.classList.add(optional ? 'alert-warning' : 'alert-danger');
    messageDiv.style.display = 'block';
  }

  function postLoad(notebookList, newNotebook, dialog) {
    function addNotebook(e) {
      newNotebook.new_notebook();
      e.target.blur();

      var event = {
        'event': 'concordEvent',
        'pagePath': '/virtual/datalab/createNotebook',
        'eventType': 'datalab',
        'eventName': 'createNotebook',
      }
      util.reportEvent(event);
    }

    function addFolder(e) {
      notebookList.contents.new_untitled(notebookList.notebook_path || '', {type: 'directory'})
        .then(function(){
          notebookList.load_list();
        }).catch(function (e) {
          dialog.modal({
              title: 'Creating Folder Failed',
              body: $('
')
                      .text("An error occurred while creating a new folder.")
                      .append($('
')
                      .addClass('alert alert-danger')
                      .text(e.message || e)),
              buttons: {
                OK: { 'class': 'btn-primary' }
              }
          });
        });
      e.target.blur();
    }

    function addTerminal(e) {
      let newWindow = window.open(undefined, IPython._target);
      let addTerminalUrl = util.datalabLink('/api/terminals');
      let settings = {
        type : 'POST',
        dataType: 'json',
        success: (data, status, jqXHR) => {
          newWindow.location = util.datalabLink('/terminals/' + encodeURIComponent(data.name));
        },
        error : function(jqXHR, status, error){
          newWindow.close();
          util.debug.log(jqXHR, status, error);
        },
      };
      util.debug.log('Sending terminal request to ' + addTerminalUrl);
      $.ajax(addTerminalUrl, settings);
    }

    function openEditor(e) {
      Jupyter.notebook_list.selected.forEach(notebook => {
        window.open(util.datalabLink('/edit/' + notebook.path), '_blank');
      });
    }

    // Extend the selection changed method to show/hide the editor button
    notebookSelectedFn = notebookList._selection_changed;
    notebookList._selection_changed = function() {
      notebookSelectedFn.apply(this, arguments);
      if (notebookList.selected.length === 1 && notebookList.selected[0].type !== 'directory')
        $('#editorButton').show();
      else
        $('#editorButton').hide();
    }

    document.getElementById('addNotebookButton').addEventListener('click', addNotebook, false);
    document.getElementById('addFolderButton').addEventListener('click', addFolder, false);
    document.getElementById('addTerminalButton').addEventListener('click', addTerminal, false);
    document.getElementById('editorButton').addEventListener('click', openEditor, false);

    (function buildBreadcrumbContent() {
      var path = util.datalabSubPath(location.pathname);
      util.debug.log('Building breadcrumbs off of ' + path);

      // Strip off leading /tree and trailing / if present
      if (path.indexOf('/tree') == 0) {
        path = path.substr(5);
      }
      if (path.substr(-1) == '/') {
        path = path.substr(0, path.length - 1);
      }
      if (!path) {
        return;
      }

      var html = [];
      var basePath = util.datalabLink('/tree')
      html.push('
');
      html.push('
home
');

      var segments = [];

      // Split the path into its segments, and convert into list items, ignoring the first
      // empty segment. Intermediate segments are also generated as navigation links.
      var pathParts = path.split('/');
      for (var i = 1; i < pathParts.length; i++) {
        var pathPart = pathParts[i];
        segments.push(pathPart);
        pathPart = decodeURIComponent(pathPart);

        var element;
        if (i == pathParts.length - 1) {
          element = '
' + pathPart + '
';
        }
        else {
          element = '
' + pathPart + '
';
        }

        html.push(element);
      }

      html.push('
');

      document.getElementById('project_name').innerHTML = html.join('');

    })();

    fileSearchPath = util.datalabLink('/_filesearch?');

    searchDiv = $('#tree-filter');
    $.getJSON(fileSearchPath, (result) => {
      if (result.tooManyFiles === true || !result.indexingEnabled) {
        searchDiv.prop('placeholder', 'File finder disabled');
        searchDiv.prop('disabled', true);
      } else {
        searchDiv.autocomplete({
          appendTo: '.tree-filter-complete',
          position: { of: '.tree-filter-complete' },
          source: (request, response) => {

            pattern = encodeURIComponent(searchDiv.val());
            patternSearchPath = fileSearchPath + 'pattern=' + pattern;

            if (patternSearchPath !== '') {
              $.getJSON(patternSearchPath, (result) => {
                response(result.files);
                if (result.fullResultSize > 20) {
                  $('.ui-autocomplete').append('
Showing 20 out of ' +
                    result.fullResultSize + ' results
');
                }
                if (result.tooManyFiles === true) {
                  $('.ui-autocomplete').prepend(
                    '
Too many files found. Showing partial results
');
                } else if (result.indexReady === false) {
                  $('.ui-autocomplete').prepend(
                    '
Indexing files.. Showing partial results
');
                }
              });
            }
          },
          select: (e, selected) => {
            var path = selected.item.value;
            if (path.endsWith('.ipynb')) {
              window.open(util.datalabLink("/notebooks/" + path));
            } else {
              window.open(util.datlabLink("/edit/" + path));
            }
          },
          delay: 500,
          messages: {
            noResults: '',
            results: function() {}
          }
        });
      }
    });

    checkVersion(window.datalab.versions);
  }

  return {
    postLoad: postLoad,
    _semverCompare: semverCompare,
    _strToSemver: strToSemver,
    _checkVersion: checkVersion
  };
});
<|endoftext|>


<commit_before>/*************
 *   CRANE   *
 *************/

var spawn = require('child_process').spawn,
    fs    = require('fs'),
    path  = require('path'),
    uuid  = require('node-uuid'),
    async = require('async'),
    _     = require('lodash');

var playerDirectory = path.resolve(path.dirname(require.main.filename), './players');

module.exports.setPlayersDirectory = function(filename) {
    playerDirectory = filename;
}

var TIMEOUT_LENGTH = 1000; //milliseconds

//------- API -----

//client receives: first word is a command, second is data
//commands: filename, player
//controller receives: first word is return command, second is status, third is data

var Player = function(playerName, shell) {
  var pl = this;

  pl.name = playerName;
  pl.shell = shell;
  pl.messageTable = [];

  this.getName = function() {
    return pl.name;
  }

  this.shell.stdout.on('data', function(res) {
    if(res.toString().substr(0, 4) === 'log ') {
      console.log('Log from client ' + pl.getName() + ': ' + res.toString().substr(4));
    } else if(res.toString().substr(0, 4) === 'err ') {
      throw new Error('Error from client ' + pl.getName() + ': ' + res.toString().substr(4));
    } else {
      res = res.toString().trim();

      var lines = res.split('\n');

      for(var i = 0; i < lines.length; i++) {
          processOutput(lines[i]);
      }
    }
  });

  function processOutput(res) {
      if(res.length > 0) {

        var dataSplit = res.split(' ');

        if(dataSplit.length < 2) {
          throw new Error('client response from ' + pl.getName() + ' too short: ' + res);
        }

        var messageId = dataSplit[0];
        var status    = dataSplit[1];
        var data      = dataSplit.length >= 3 ? dataSplit.slice(2).join(' ') : null;

        if(!pl.messageTable[messageId]) {
            throw new Error('client response from ' + pl.getName() + ' with unrecognized message id ' + messageId);
        }

        pl.messageTable[messageId].done = true;

        if(parseInt(status) === 200) {
            var callback = pl.messageTable[messageId].callback;
            if(callback) { callback(data); }
        } else {
            throw new Error('client response from ' + pl.getName() + ' with status ' + status + ' and error ' + data + '.');
        }

      }
  }

  //err
  this.shell.stderr.on('data', function(data) {
    throw new Error('Error from player ' + pl.getName() + ': ' + data);
  });

  //close
  this.shell.on('close', function(code) {
    console.log('Player ' + pl.getName() + ' closing with code: ' + code);
  });

  //end
  this.shell.on('end', function() {
    process.stdout.end();
  });

  //private - takes a command and data, passes it on to the client
  function sendRaw(command, data, cb) {

      var messageId = uuid.v1();
      var messageString = [messageId, command, data].join(' ');

      pl.messageTable[messageId] = {
              callback: cb,
              message: messageString,
              done: false
          };

      pl.shell.stdin.write(messageString + "\n"); //newline to ensure it doesn't get buffered

      if(TIMEOUT_LENGTH > 0) { //otherwise no timeout
        setTimeout(function() {
          if(!pl.messageTable[messageId].done) {
            throw new Error('Player ' + pl.name + ' timed out responding to ' + messageString);
            pl.messageTable[messageId].done = true;
          }
        }, TIMEOUT_LENGTH);
      }

  }

  //public - takes an object with required data string, and passes it on to the player (through the client)
  this.send = function(data, callback) {
      sendRaw("player", data, callback);
  }

}

//crane
module.exports.setTimeoutLength = function(timeout) {
    if(!isNaN(timeout) && isFinite(timeout) && timeout >= 0) {
        TIMEOUT_LENGTH = timeout;
    } else {
        throw new Error('timeout not valid');
    }
}

module.exports.readPlayers = function(manualPlayersList) {
  var rawPlayers;
  var players = [];

  if(manualPlayersList && manualPlayersList.length > 0) { //we need at least 1 player
    rawPlayers = manualPlayersList;
  } else {
    rawPlayers = fs.readdirSync(playerDirectory);
  }

  for(var i = 0; i < rawPlayers.length; i++) {
    var fullFile = rawPlayers[i];
    var dot = fullFile.lastIndexOf('.');

    var shortName = fullFile.substring(0, dot); //e.g. player-1
    var filePathNoExtension = playerDirectory + '/' + shortName //e.g. players/player-1
    var extension = fullFile.substring(dot+1); //eg js

    var command = "";
    var args = [];

    if(extension === "js") {
      command = "node";
      args.push("client/client.js");
      args.push(filePathNoExtension)
    } else if(extension === "py") {
      command = "python3"
      args.push("-u");
      args.push("client/client.py"); // -u to disable output buffering
      args.push(filePathNoExtension)
    } else if(extension === "class") {
      command = "java";
      args.push("-classpath"); args.push("client");
      args.push("Client");
      args.push(filePathNoExtension)
    }
    if(command) { //else not a player, so ignore
      players.push( new Player(shortName, spawn(command, args, {cwd: __dirname}) ) );
    }
  }

  return players;
}

function choose(set, number) {
    //?
}

module.exports.play = function(callback, options) {
    players = module.exports.readAllPlayers( options.players ? options.players : '' );
    //for each combination of two players
    combinations = choose(players, 2);
    for(var i = 0; i < combinations.length; i++) {
        callback(combinations);
    }
};

module.exports.playAllMatches = function(players, numMatches, eachMatch, callback) {
    var index = 0;
    var matches = [];
    for(var i = 0; i < players.length; i++) {
      for(var j = i; j < players.length; j++) {
        if(i !== j) { //don't play a bot against itself
            matches.push({
                players: _.shuffle([players[i], players[j]]),
                index: ++index
            });
        }
      }
    }

    async.eachSeries(matches, eachMatch, callback);
};

function getBaseLog(x, y) {
  return Math.log(y) / Math.log(x);
}

function nearestTwo(x) {
  return Math.pow(2,Math.ceil(getBaseLog(2, x)));
}

module.exports.playTournament = function(players) {
  var size = nearestTwo(players.length);
  var numByes = size - players.length;
};
<commit_msg>Removed erroneous stream closing thing<commit_after>/*************
 *   CRANE   *
 *************/

var spawn = require('child_process').spawn,
    fs    = require('fs'),
    path  = require('path'),
    uuid  = require('node-uuid'),
    async = require('async'),
    _     = require('lodash');

var playerDirectory = path.resolve(path.dirname(require.main.filename), './players');

module.exports.setPlayersDirectory = function(filename) {
    playerDirectory = filename;
}

var TIMEOUT_LENGTH = 1000; //milliseconds

//------- API -----

//client receives: first word is a command, second is data
//commands: filename, player
//controller receives: first word is return command, second is status, third is data

var Player = function(playerName, shell) {
  var pl = this;

  pl.name = playerName;
  pl.shell = shell;
  pl.messageTable = [];

  this.getName = function() {
    return pl.name;
  }

  this.shell.stdout.on('data', function(res) {
    if(res.toString().substr(0, 4) === 'log ') {
      console.log('Log from client ' + pl.getName() + ': ' + res.toString().substr(4));
    } else if(res.toString().substr(0, 4) === 'err ') {
      throw new Error('Error from client ' + pl.getName() + ': ' + res.toString().substr(4));
    } else {
      res = res.toString().trim();

      var lines = res.split('\n');

      for(var i = 0; i < lines.length; i++) {
          processOutput(lines[i]);
      }
    }
  });

  function processOutput(res) {
      if(res.length > 0) {

        var dataSplit = res.split(' ');

        if(dataSplit.length < 2) {
          throw new Error('client response from ' + pl.getName() + ' too short: ' + res);
        }

        var messageId = dataSplit[0];
        var status    = dataSplit[1];
        var data      = dataSplit.length >= 3 ? dataSplit.slice(2).join(' ') : null;

        if(!pl.messageTable[messageId]) {
            throw new Error('client response from ' + pl.getName() + ' with unrecognized message id ' + messageId);
        }

        pl.messageTable[messageId].done = true;

        if(parseInt(status) === 200) {
            var callback = pl.messageTable[messageId].callback;
            if(callback) { callback(data); }
        } else {
            throw new Error('client response from ' + pl.getName() + ' with status ' + status + ' and error ' + data + '.');
        }

      }
  }

  //err
  this.shell.stderr.on('data', function(data) {
    throw new Error('Error from player ' + pl.getName() + ': ' + data);
  });

  //close
  this.shell.on('close', function(code) {
    console.log('Player ' + pl.getName() + ' closing with code: ' + code);
  });

  //private - takes a command and data, passes it on to the client
  function sendRaw(command, data, cb) {

      var messageId = uuid.v1();
      var messageString = [messageId, command, data].join(' ');

      pl.messageTable[messageId] = {
              callback: cb,
              message: messageString,
              done: false
          };

      pl.shell.stdin.write(messageString + "\n"); //newline to ensure it doesn't get buffered

      if(TIMEOUT_LENGTH > 0) { //otherwise no timeout
        setTimeout(function() {
          if(!pl.messageTable[messageId].done) {
            throw new Error('Player ' + pl.name + ' timed out responding to ' + messageString);
            pl.messageTable[messageId].done = true;
          }
        }, TIMEOUT_LENGTH);
      }

  }

  //public - takes an object with required data string, and passes it on to the player (through the client)
  this.send = function(data, callback) {
      sendRaw("player", data, callback);
  }

}

//crane
module.exports.setTimeoutLength = function(timeout) {
    if(!isNaN(timeout) && isFinite(timeout) && timeout >= 0) {
        TIMEOUT_LENGTH = timeout;
    } else {
        throw new Error('timeout not valid');
    }
}

module.exports.readPlayers = function(manualPlayersList) {
  var rawPlayers;
  var players = [];

  if(manualPlayersList && manualPlayersList.length > 0) { //we need at least 1 player
    rawPlayers = manualPlayersList;
  } else {
    rawPlayers = fs.readdirSync(playerDirectory);
  }

  for(var i = 0; i < rawPlayers.length; i++) {
    var fullFile = rawPlayers[i];
    var dot = fullFile.lastIndexOf('.');

    var shortName = fullFile.substring(0, dot); //e.g. player-1
    var filePathNoExtension = playerDirectory + '/' + shortName //e.g. players/player-1
    var extension = fullFile.substring(dot+1); //eg js

    var command = "";
    var args = [];

    if(extension === "js") {
      command = "node";
      args.push("client/client.js");
      args.push(filePathNoExtension)
    } else if(extension === "py") {
      command = "python3"
      args.push("-u");
      args.push("client/client.py"); // -u to disable output buffering
      args.push(filePathNoExtension)
    } else if(extension === "class") {
      command = "java";
      args.push("-classpath"); args.push("client");
      args.push("Client");
      args.push(filePathNoExtension)
    }
    if(command) { //else not a player, so ignore
      players.push( new Player(shortName, spawn(command, args, {cwd: __dirname}) ) );
    }
  }

  return players;
}

function choose(set, number) {
    //?
}

module.exports.play = function(callback, options) {
    players = module.exports.readAllPlayers( options.players ? options.players : '' );
    //for each combination of two players
    combinations = choose(players, 2);
    for(var i = 0; i < combinations.length; i++) {
        callback(combinations);
    }
};

module.exports.playAllMatches = function(players, numMatches, eachMatch, callback) {
    var index = 0;
    var matches = [];
    for(var i = 0; i < players.length; i++) {
      for(var j = i; j < players.length; j++) {
        if(i !== j) { //don't play a bot against itself
            matches.push({
                players: _.shuffle([players[i], players[j]]),
                index: ++index
            });
        }
      }
    }

    async.eachSeries(matches, eachMatch, callback);
};

function getBaseLog(x, y) {
  return Math.log(y) / Math.log(x);
}

function nearestTwo(x) {
  return Math.pow(2,Math.ceil(getBaseLog(2, x)));
}

module.exports.playTournament = function(players) {
  var size = nearestTwo(players.length);
  var numByes = size - players.length;
};
<|endoftext|>


<commit_before>var _ = require('lodash');
var utils = require('./utils.js');

console.log(1.0000000000000000, 'USD');

_.each([
	'EURUSD',
	'NZDUSD',
	'GBPUSD',
	'AUDUSD',
	'USDCAD',
	'USDJPY',
	'USDCHF'
], function(currency) {
	utils.download({
		currency: currency,
		timeScale: '1440',
		periodLength: 1,
		periodUnits: 'week'
	}, function(err, rows) {
		var closePrice = rows[0][3]
		var openPrice = rows[0][3]
		_.each(rows, function(row) {
			openPrice = row[3]
		});

		var invertPercentChange = [
			'USDJPY',
			'USDCHF',
			'USDCAD'
		];
		var percentChange = _.includes(invertPercentChange, currency)
			? (closePrice/openPrice)
			: (openPrice/closePrice);

		console.log(percentChange, currency.replace('USD', ''));
	});
})
<commit_msg>feat: add REPORT_DATE for heatmap<commit_after>var _ = require('lodash');
var utils = require('./utils.js');

console.log(1.0000000000000000, 'USD');

_.each([
	'EURUSD',
	'NZDUSD',
	'GBPUSD',
	'AUDUSD',
	'USDCAD',
	'USDJPY',
	'USDCHF'
], function(currency) {
	utils.download({
		endDate: process.env.REPORT_DATE,
		currency: currency,
		timeScale: '1440',
		periodLength: 1,
		periodUnits: 'week'
	}, function(err, rows) {
		var closePrice = rows[0][3]
		var openPrice = rows[0][3]
		_.each(rows, function(row) {
			openPrice = row[3]
		});

		var invertPercentChange = [
			'USDJPY',
			'USDCHF',
			'USDCAD'
		];
		var percentChange = _.includes(invertPercentChange, currency)
			? (closePrice/openPrice)
			: (openPrice/closePrice);

		console.log(percentChange, currency.replace('USD', ''));
	});
})
<|endoftext|>