<commit_before>var x_timer;
$('#search').bind("keyup blur", function (event){

var exclud = [13,27,37,38,39,40];
clearTimeout(x_timer);

//if (event.keyCode != '13' && event.keyCode != '40' && event.keyCode != '39' && event.keyCode != '38' && event.keyCode != '37') {
	x_timer = setTimeout(function(){
	if (exclud.indexOf(event.which) === -1) {
    $.ajax({
      url: "https://api.soundcloud.com/tracks.json?" + $('#search').serialize(),
      dataType: 'json',
      beforeSend:
        function(data){
          $('#sounds').empty();
        },
      success:
        function(data){
          $('#sounds').html('')
          var items = [];
		  var i=0;
          $.each(data, function(key, val){
            items.push("

"+check(val.artwork_url)+"
"+val.title+"
\
            " + val.user.username +   " -  " + msToTime(val.duration)  +  "

");
          i++;
		  });
          $('#sounds').html(items.join(' '));
          trackClick();

        }
    });
}
}, 300);
});
window.onload = function() {
  document.getElementById("q").focus();
};

var clientid = 'client_id=2010872379d388118fe90f01ace38d03';

function msToTime(duration) {
          var milliseconds = parseInt((duration%1000)/100)
              , seconds = parseInt((duration/1000)%60)
              , minutes = parseInt((duration/(1000*60))%60)
              , hours = parseInt((duration/(1000*60*60))%24);

          hours = (hours < 10) ? "0" + hours : hours;
          minutes = (minutes < 10) ? "0" + minutes : minutes;
          seconds = (seconds < 10) ? "0" + seconds : seconds;
          if(hours == "00")
            return minutes + ":" + seconds;
          else
            return hours + ":" + minutes + ":" + seconds;
        }

function trackClick(){
  $('.go').click(function(){
    var url= $(this).data('url') +"?"+ clientid;
    var title= $(this).data('title');
    var artist = $(this).data('artist');
    $(this).addClass('playedSong');
    $('#navbar h2').html(title);
	var next = ($(this).data('index'))+1;
    var audioPlayer = document.getElementById('player');
  audioPlayer.src = url;
  audioPlayer.load();
  document.getElementById('player').play();
	$("#player").bind("ended", function(){
	playnext(next);
	});
  document.title="Playing " + title;
  $(this).before(function() {
  $(".download").remove();
  $(this).prev('img').remove();
  return "";
});
    return false;
  });
}
function playnext(id){
var next = id+1;
var url = $('a[data-index="'+id+'"]').data('url') +"?"+ clientid;
var title= $('a[data-index="'+id+'"]').data('title');
$('a[data-index="'+id+'"]').addClass('playedSong');
$('#navbar h2').html(title);
var audioPlayer = document.getElementById('player');
  audioPlayer.src = url;
  audioPlayer.load();
$("#player").bind("ended", function(){
	playnext(next);
	});
  document.title="Playing " + title;
  document.getElementById('player').play();
}
function check(kima){
if (kima === undefined || kima === null) {
return '';
} else {
return '';
}
}
/*$( "#pause" ).click(function() {
 $("#player").trigger('pause');
});*/
$('#pause').click(function() {
var audioPlayer = document.getElementById('player');
  if (audioPlayer.paused == false) {
      audioPlayer.pause();
	  $( ".icon" ).remove;
      $( ".icon" ).html('');
  } else {
      audioPlayer.play();
	  $( ".icon" ).remove;
      $( ".icon" ).html('');
  }
});
/*$("#volume").slider({
    value : 75,
    step  : 1,
    range : 'min',
    min   : 0,
    max   : 100,
    slide : function(){
        var value = $("#volume").slider("value");
        document.getElementById("#player").volume = (value / 100);
    }
});*/
<commit_msg>Update script2.js<commit_after>var x_timer;
$('#search').bind("keyup blur", function (event){

var exclud = [13,27,37,38,39,40];
clearTimeout(x_timer);

//if (event.keyCode != '13' && event.keyCode != '40' && event.keyCode != '39' && event.keyCode != '38' && event.keyCode != '37') {
	x_timer = setTimeout(function(){
	if (exclud.indexOf(event.which) === -1) {
    $.ajax({
      url: "https://api.soundcloud.com/tracks.json?" + $('#search').serialize(),
      dataType: 'json',
      beforeSend:
        function(data){
          $('#sounds').empty();
        },
      success:
        function(data){
          $('#sounds').html('')
          var items = [];
		  var i=0;
          $.each(data, function(key, val){
            items.push("

"+check(val.artwork_url)+"
"+val.title+"
\
            " + val.user.username +   " -  " + msToTime(val.duration)  +  "

");
          i++;
		  });
          $('#sounds').html(items.join(' '));
          trackClick();

        }
    });
}
}, 300);
});
window.onload = function() {
  document.getElementById("q").focus();
};

var clientid = 'client_id=2010872379d388118fe90f01ace38d03';

function msToTime(duration) {
          var milliseconds = parseInt((duration%1000)/100)
              , seconds = parseInt((duration/1000)%60)
              , minutes = parseInt((duration/(1000*60))%60)
              , hours = parseInt((duration/(1000*60*60))%24);

          hours = (hours < 10) ? "0" + hours : hours;
          minutes = (minutes < 10) ? "0" + minutes : minutes;
          seconds = (seconds < 10) ? "0" + seconds : seconds;
          if(hours == "00")
            return minutes + ":" + seconds;
          else
            return hours + ":" + minutes + ":" + seconds;
        }

function trackClick(){
  $('.go').click(function(){
    var url= $(this).data('url') +"?"+ clientid;
    var title= $(this).data('title');
    var artist = $(this).data('artist');
    $(this).addClass('playedSong');
    $('#navbar h2').html(title);
	var next = ($(this).data('index'))+1;
    var audioPlayer = document.getElementById('player');
  audioPlayer.src = url;
  audioPlayer.load();
  document.getElementById('player').play();
	$("#player").bind("ended", function(){
	playnext(next);
	});
  document.title="Playing " + title;
  $(this).before(function() {
  $(".download").remove();
  $(this).prev('img').remove();
  return "";
});
    return false;
  });
}
function playnext(id){
var next = id+1;
var url = $('a[data-index="'+id+'"]').data('url') +"?"+ clientid;
var title= $('a[data-index="'+id+'"]').data('title');
$('a[data-index="'+id+'"]').addClass('playedSong');
$('#navbar h2').html(title);
var audioPlayer = document.getElementById('player');
  audioPlayer.src = url;
  audioPlayer.load();
$("#player").bind("ended", function(){
	playnext(next);
	});
  document.title="Playing " + title;
  document.getElementById('player').play();
}
function check(kima){
if (kima === undefined || kima === null) {
return '';
} else {
return '';
}
}
/*$( "#pause" ).click(function() {
 $("#player").trigger('pause');
});*/
$('#pause').click(function() {
var audioPlayer = document.getElementById('player');
  if (audioPlayer.paused == false) {
      audioPlayer.pause();
	  $( ".icon" ).remove;
      $( ".icon" ).html('');
  } else {
      audioPlayer.play();
	  $( ".icon" ).remove;
      $( ".icon" ).html('');
  }
});
/*$("#volume").slider({
    value : 75,
    step  : 1,
    range : 'min',
    min   : 0,
    max   : 100,
    slide : function(){
        var value = $("#volume").slider("value");
        document.getElementById("#player").volume = (value / 100);
    }
});*/
<|endoftext|>


<commit_before>import _ from 'lodash';
import $ from 'jquery';
import React, {Component, PropTypes} from 'react';
import classNames from 'classnames';
import META from 'src/utils/Meta';

export default class Form extends Component {
  static propTypes = {
    children: PropTypes.node,
    className: PropTypes.string,
    settings: PropTypes.object,
  };

  componentDidMount() {
    this.element = $(this.refs.element);
    this.element.form(this.props.settings);
  }

  componentWillUnmount() {
    this.element.off();
  }

  plugin() {
    return this.element.form(...arguments);
  }

  serializeJson = () => {
    const form = this.refs.form;
    const json = {};

    _.each(['input', 'textarea', 'select'], (tag) => {
      _.each(form.getElementsByTagName(tag), (node, index, arr) => {
        const name = node.getAttribute('name');

        switch (node.getAttribute('type')) {
          case 'checkbox':
            json[name] = {checked: node.checked};
            break;

          case 'radio':
            json[name] = {
              value: _.find(arr, {name, checked: true}).value
            };
            break;

          default:
            json[name] = {value: node.value};
            break;
        }
      });
    });

    return json;
  };

  static _meta = {
    library: META.library.semanticUI,
    name: 'Form',
    type: META.type.collection,
  };

  render() {
    const classes = classNames(
      'sd-form',
      'ui',
      this.props.className,
      'form'
    );
    return (
      <form {...this.props} className={classes} ref='element'>
        {this.props.children}
      </form>
    );
  }
}
<commit_msg>change ref to element<commit_after>import _ from 'lodash';
import $ from 'jquery';
import React, {Component, PropTypes} from 'react';
import classNames from 'classnames';
import META from 'src/utils/Meta';

export default class Form extends Component {
  static propTypes = {
    children: PropTypes.node,
    className: PropTypes.string,
    settings: PropTypes.object,
  };

  componentDidMount() {
    this.element = $(this.refs.element);
    this.element.form(this.props.settings);
  }

  componentWillUnmount() {
    this.element.off();
  }

  plugin() {
    return this.element.form(...arguments);
  }

  serializeJson = () => {
    const form = this.refs.element;
    const json = {};

    _.each(['input', 'textarea', 'select'], (tag) => {
      _.each(form.getElementsByTagName(tag), (node, index, arr) => {
        const name = node.getAttribute('name');

        switch (node.getAttribute('type')) {
          case 'checkbox':
            json[name] = {checked: node.checked};
            break;

          case 'radio':
            json[name] = {
              value: _.find(arr, {name, checked: true}).value
            };
            break;

          default:
            json[name] = {value: node.value};
            break;
        }
      });
    });

    return json;
  };

  static _meta = {
    library: META.library.semanticUI,
    name: 'Form',
    type: META.type.collection,
  };

  render() {
    const classes = classNames(
      'sd-form',
      'ui',
      this.props.className,
      'form'
    );
    return (
      <form {...this.props} className={classes} ref='element'>
        {this.props.children}
      </form>
    );
  }
}
<|endoftext|>


<commit_before>/* eslint-disable no-console */

// <%= name %>-model.js - A KnexJS
//
// See http://knexjs.org/
// for more of what you can do here.
module.exports = function (app) {
  const db = app.get('knexClient');

  db.schema.createTableIfNotExists('<%= kebabName %>', table => {
    table.increments('id');
  <% if(authentication.strategies.indexOf('local') !== -1) { %>
    table.string('email').unique();
    table.string('password');
  <% } %>
  <% authentication.oauthProviders.forEach(provider => { %>
    table.string('<%= provider.name %>Id');
  <% }); %>
  })
  .then(() => console.log('Updated <%= kebabName %> table'))
  .catch(e => console.error('Error updating <%= kebabName %> table', e));

  return db;
};
<commit_msg>Update Knex user model to create table properly (#233)<commit_after>/* eslint-disable no-console */

// <%= name %>-model.js - A KnexJS
//
// See http://knexjs.org/
// for more of what you can do here.
module.exports = function (app) {
  const db = app.get('knexClient');

    db.schema.hasTable('<%= kebabName %>').then(exists => {
      if(!exists) {
        db.schema.createTable('<%= kebabName %>', table => {
          table.increments('id');
        <% if(authentication.strategies.indexOf('local') !== -1) { %>
          table.string('email').unique();
          table.string('password');
        <% } %>
        <% authentication.oauthProviders.forEach(provider => { %>
          table.string('<%= provider.name %>Id');
        <% }); %>
        })
        .then(
          () => console.log('Updated <%= kebabName %> table'),
          e => console.error('Error updating <%= kebabName %> table', e)
        );
      }
    });

  return db;
};
<|endoftext|>


<commit_before>(function () {
  /**************************************************************************************
  *
  * GasL - Google Apps Script Loging-framework
  *
  * Support log to Spreadsheet / Logger / LogEntries(next version) ,
  * and very easy to extended to others.
  *
  * Github: https://github.com/zixia/gasl
  *
  * Example:
        ```javascript
        var gasLogLib='https://raw.githubusercontent.com/zixia/gasl/master/gas-log.js'
        var GasLog = eval(UrlFetchApp.fetch(gasLogLib).getContentText())

        var log = new GasLog()

        log('Hello, %s!', 'World')

        ```
  *
  ***************************************************************************************/

  var PRIORITIES = { EMERG:    0
                    , ALERT:   1
                    , CRIT:    2
                    , ERR:     3
                    , WARNING: 4
                    , NOTICE:  5
                    , INFO:    6
                    , DEBUG:   7
                   }

  /****************************************************
  *
  * GasLog Constructor
  *
  ****************************************************/
  var gasLog_ = function (options) {
    var logPriority = PRIORITIES.INFO
    var logPrinter = new LoggerPrinter()

    if (options && options.priority) {
      logPriority = loadPriority(options.priority)
    }

    if (options && options.printer) {
      logPrinter = options.printer

      if (!logPrinter.isPrinter()) {
        throw Error('options.printer ' + printer + ' is not a GasLog printer!')
      }
    }

    /*****************************************
    *
    * Instance Methods Export
    *
    *****************************************/

    for (var logName in PRIORITIES) {
       doLog[logName] = PRIORITIES[logName]
    }
    doLog.PRIORITIES = PRIORITIES

    doLog.getPriority = getPriority
    doLog.setPriority = setPriority

    /**********************************
    *
    * Constructor initialize finished
    *
    ***********************************/
    return doLog

    //////////////////////////////////////////////////////////////
    // Instance Methods Implementions
    //////////////////////////////////////////////////////////////

    /**
    *
    * Log Level Getter & Setter
    *
    */
    function getPriority() { return logPriority }
    function setPriority(priorityName) {
      logPriority = loadPriority(priorityName)
      return this
    }

    /**
    *
    *
    * log(priority, msg, params...)
    * or just log(msg)
    *
    *
    */
    function doLog() {

      // make a shiftable array from arguments
      var args = Array.prototype.slice.call(arguments)

      var priority = logPriority // set to default before we parse params

      switch (typeof args[0]) {
        case 'number':
          /**
          *
          * determine priority.
          * if the 1st param is a valid log priority(a Integer), then use it as logPriority
          * otherwise, set logPriority to default(priority in instance)
          *
          */
          priority = loadPriority(args.shift())
          break;

        case 'string':
          break;

        default:
          throw Error('doLog(' + args[0] + ') need 1st param either be string or number!')
          break;
      }

      // no log for lower priority messages than logPriority
      if (priority > logPriority) return

      /**
      *
      * build log string & log
      *
      */

      var message = ''
      try {
        message = Utilities.formatString.apply(null, args);
      } catch (e) {
        message = args.join(' !!! ')
      }

      logPrinter(priority, message)

    }
  }

  /********************************
  *
  * Class Static Methods Export
  *
  *********************************/
  gasLog_.Printer = {}
  gasLog_.Printer.Logger = LoggerPrinter
  gasLog_.Printer.Spreadsheet = SpreadsheetPrinter

  return gasLog_

  ///////////////////////////////////////////////////////////////////////////////
  // Class Static Method Implementations
  ///////////////////////////////////////////////////////////////////////////////

  function LoggerPrinter() {
    var loggerPrinter_ = function (priority, message) {
      return Logger.log(message)
    }

    loggerPrinter_.isPrinter = function () { return 'Logger' }
    return loggerPrinter_
  }

  /**
  *
  * @param Object options
  *   options.id        - Spreadsheet ID
  *   options.url       - Spreadsheet URL
  *   options.sheetName - Tab name of a sheet
  *   options.clear     - true for clear all log sheet. default false
  *   options.scroll    - 'DOWN' or 'UP', default DOWN
  *
  */
  function SpreadsheetPrinter(options) {

    if(typeof options != 'object') throw Error('options must set for Spreadsheet Printer')

    var sheetName = options.sheetName || 'GasLogs'
    var clear = options.clear || false
    var scroll = options.scroll || 'DOWN'

    var url = options.url
    var id = options.id

    var ss // Spreadsheet

    if (id) {
      ss = SpreadsheetApp.openById(id)
    } else if(url) {
      ss = SpreadsheetApp.openByUrl(url)
    } else {
      throw Error('options must set url or id! for get the spreadsheet')
    }

    if (!ss) throw Error('SpreadsheetPrinter open ' + id + url + ' failed!')

    // Sheet for logging
    var sheet = ss.getSheetByName(sheetName)
    if (!sheet) {
      sheet = ss.insertSheet(sheetName)
      if (!sheet) throw Error('SpreadsheetPrint insertSheet ' + sheetName + ' failed!')
    }

    /**
    * initialize headers if not exist in sheet
    */
    var range = sheet.getRange(1, 1, 1, 4)
    var h = range.getValues()[0]
    if (!h[0] && !h[1] && !h[2]) {
      range.setValues([['Date', 'Level', 'Message', 'Powered by GasL - Google Apps Script Logging-framework - https://github.com/zixia/gasl']])
    }

    if (clear) {
      // keep header row (the 1st row)
      sheet.getRange(2, 1, sheet.getLastRow(), sheet.getLastColumn()).clearContent()
    }

    var spreadsheetPrinter_ = function (priority, message) {
      if (scroll=='UP') {
        sheet
        .insertRowBefore(2)
        .getRange(2, 1, 1, 3)
        .setValues([[new Date(), priority, message]])
      } else { // scroll DOWN
        sheet.appendRow([new Date(), priority, message])
      }
    }

    spreadsheetPrinter_.isPrinter = function () { return 'Spreadsheet' }

    return spreadsheetPrinter_
  }

  /**
  *
  *
  */
  function loadPriority(priority) {
    if (priority % 1 === 0) {

      return priority

    } else if (typeof priority == 'string') {
      priority = priority.toUpperCase()
      if (priority in PRIORITIES) {

        return PRIORITIES[priority]

      }
    }

    throw Error('options.priority[' + priority + '] illegel')
  }

}())
<commit_msg>support ident log<commit_after>(function () {
  /**************************************************************************************
  *
  * GasL - Google Apps Script Loging-framework
  *
  * Support log to Spreadsheet / Logger / LogEntries(next version) ,
  * and very easy to extended to others.
  *
  * Github: https://github.com/zixia/gasl
  *
  * Example:
        ```javascript
        var gasLogLib='https://raw.githubusercontent.com/zixia/gasl/master/gas-log.js'
        var GasLog = eval(UrlFetchApp.fetch(gasLogLib).getContentText())

        var log = new GasLog()

        log('Hello, %s!', 'World')

        ```
  *
  ***************************************************************************************/

  var PRIORITIES = { EMERG:    0
                    , ALERT:   1
                    , CRIT:    2
                    , ERR:     3
                    , WARNING: 4
                    , NOTICE:  5
                    , INFO:    6
                    , DEBUG:   7
                   }

  /****************************************************
  *
  * GasLog Constructor
  *
  ****************************************************/
  var gasLog_ = function (options) {
    var logPriority = PRIORITIES.INFO
    var logPrinter = new LoggerPrinter()
    var logIdent = 'GasL'

    if (options && options.ident) {
      logIdent = options.ident
    }

    if (options && options.priority) {
      logPriority = loadPriority(options.priority)
    }

    if (options && options.printer) {
      logPrinter = options.printer

      if (!logPrinter.isPrinter()) {
        throw Error('options.printer ' + logPrinter + ' is not a GasLog Printer!')
      }
    }

    /*****************************************
    *
    * Instance Methods Export
    *
    *****************************************/

    for (var logName in PRIORITIES) {
       doLog[logName] = PRIORITIES[logName]
    }
    doLog.PRIORITIES = PRIORITIES

    doLog.getPriority = getPriority
    doLog.setPriority = setPriority

    /**********************************
    *
    * Constructor initialize finished
    *
    ***********************************/
    return doLog

    //////////////////////////////////////////////////////////////
    // Instance Methods Implementions
    //////////////////////////////////////////////////////////////

    /**
    *
    * Log Level Getter & Setter
    *
    */
    function getPriority() { return logPriority }
    function setPriority(priorityName) {
      logPriority = loadPriority(priorityName)
      return this
    }

    /**
    *
    *
    * log(priority, msg, params...)
    * or just log(msg)
    *
    *
    */
    function doLog() {

      // make a shiftable array from arguments
      var args = Array.prototype.slice.call(arguments)

      var priority = logPriority // set to default before we parse params

      switch (typeof args[0]) {
        case 'number':
          /**
          *
          * determine priority.
          * if the 1st param is a valid log priority(a Integer), then use it as logPriority
          * otherwise, set logPriority to default(priority in instance)
          *
          */
          priority = loadPriority(args.shift())
          break;

        case 'string':
          break;

        default:
          throw Error('doLog(' + args[0] + ') need 1st param either be string or number!')
          break;
      }

      // no log for lower priority messages than logPriority
      if (priority > logPriority) return

      /**
      *
      * build log string & log
      *
      */

      var message = ''
      try {
        message = Utilities.formatString.apply(null, args);
      } catch (e) {
        message = args.join(' !!! ')
      }

      logPrinter.call(this, priority, message)

    }
  }

  /********************************
  *
  * Class Static Methods Export
  *
  *********************************/
  gasLog_.Printer = {}
  gasLog_.Printer.Logger = LoggerPrinter
  gasLog_.Printer.Spreadsheet = SpreadsheetPrinter

  return gasLog_

  ///////////////////////////////////////////////////////////////////////////////
  // Class Static Method Implementations
  ///////////////////////////////////////////////////////////////////////////////

  function LoggerPrinter() {
    var loggerPrinter_ = function (priority, message) {
      return Logger.log(message)
    }

    loggerPrinter_.isPrinter = function () { return 'Logger' }
    return loggerPrinter_
  }

  /**
  *
  * @param Object options
  *   options.id        - Spreadsheet ID
  *   options.url       - Spreadsheet URL
  *   options.sheetName - Tab name of a sheet
  *   options.clear     - true for clear all log sheet. default false
  *   options.scroll    - 'DOWN' or 'UP', default DOWN
  *
  */
  function SpreadsheetPrinter(options) {

    if(typeof options != 'object') throw Error('options must set for Spreadsheet Printer')

    var sheetName = options.sheetName || 'GasLogs'
    var clear = options.clear || false
    var scroll = options.scroll || 'DOWN'

    var url = options.url
    var id = options.id

    var ss // Spreadsheet

    if (id) {
      ss = SpreadsheetApp.openById(id)
    } else if(url) {
      ss = SpreadsheetApp.openByUrl(url)
    } else {
      throw Error('options must set url or id! for get the spreadsheet')
    }

    if (!ss) throw Error('SpreadsheetPrinter open ' + id + url + ' failed!')

    // Sheet for logging
    var sheet = ss.getSheetByName(sheetName)
    if (!sheet) {
      sheet = ss.insertSheet(sheetName)
      if (!sheet) throw Error('SpreadsheetPrint insertSheet ' + sheetName + ' failed!')
    }

    /**
    * initialize headers if not exist in sheet
    */
    var range = sheet.getRange(1, 1, 1, 5)
    var h = range.getValues()[0]
    if (!h[0] && !h[1] && !h[2] && !h[3]) {
      range.setValues([['Date', 'Ident', 'Priority', 'Message', 'Powered by GasL - Google Apps Script Logging-framework - https://github.com/zixia/gasl']])
    }

    if (clear) {
      // keep header row (the 1st row)
      sheet.getRange(2, 1, sheet.getLastRow(), sheet.getLastColumn()).clearContent()
    }

    var spreadsheetPrinter_ = function (priority, message) {
      if (scroll=='UP') {
        sheet
        .insertRowBefore(2)
        .getRange(2, 1, 1, 4)
        .setValues([[new Date(), this.logIdent, priority, message]])
      } else { // scroll DOWN
        sheet.appendRow([new Date(), priority, message])
      }
    }

    spreadsheetPrinter_.isPrinter = function () { return 'Spreadsheet' }

    return spreadsheetPrinter_
  }

  /**
  *
  *
  */
  function loadPriority(priority) {
    if (priority % 1 === 0) {

      return priority

    } else if (typeof priority == 'string') {
      priority = priority.toUpperCase()
      if (priority in PRIORITIES) {

        return PRIORITIES[priority]

      }
    }

    throw Error('options.priority[' + priority + '] illegel')
  }

}())
<|endoftext|>


<commit_before>var RLS = require('./util/RequestLocalStorage').getNamespace()
,	Q = require("q")
,	Cache = require("./ReactServerAgent/Cache")
,	Request = require("./ReactServerAgent/Request")
,	Plugins = require("./ReactServerAgent/Plugins")
;

// wrapper for superagent
function makeRequest (method, url) {
	return new Request(method, url, API.cache());
}

const BUNDLE_CACHE     = {};
const BUNDLE_PARAMETER = '_react_server_preload_bundle';
const BUNDLE_OPTS      = {[BUNDLE_PARAMETER]: 1};

var API = {

	BUNDLE_PARAMETER,

	get (url, data) {
		var req = makeRequest('GET', url);
		if (data) req.query(data);
		return req;
	},

	head (url, data) {
		var req = makeRequest('HEAD', url);
		if (data) req.send(data);
		return req;
	},

	del (url) {
		return makeRequest('DELETE', url);
	},

	patch (url, data) {
		var req = makeRequest('PATCH', url);
		if (data) req.send(data);
		return req;
	},

	post (url, data) {
		var req = makeRequest('POST', url);
		if (data) req.send(data);
		return req;
	},

	put (url, data) {
		var req = makeRequest('PUT', url);
		if (data) req.send(data);
		return req;
	},

	/**
	 * Exposes the ReactServerAgent request data cache from RequestLocalStorage.
	 */
	cache () {
		var cache = RLS().cache;
		if (!cache) {
			cache = RLS().cache = new Cache();
		}
		return cache;
	},

	_clearCache () {
		delete RLS().cache;
	},

	/**
	 * Adds a plugin function that can be used to modify the Request
	 * object before the request is actually
	 * triggered.
	 *
	 * The callback function will take the Request instance as a parameter:
	 * ```
	 * var defaultHeaders = { ... };
	 * ReactServerAgent.plugRequest(function (request) {
	 *     // e.g.
	 *     request.set(defaultHeaders)
	 * })
	 * ```
	 */
	plugRequest (pluginFunc) {
		Plugins.forRequest().add(pluginFunc);
	},

	/**
	 * Adds a plugin function that can be used to modify the response
	 * object before it is passed the caller's callback.
	 *
	 * The callback function will take err and response as parameters
	 * (like the callback to `end()`), and the request as well:
	 * ```
	 * ReactServerAgent.plugResponse(function (err, response, request) {
	 *     // e.g.
	 *     console.log("Response received!", res.body);
	 *     res.wasLogged = true; // or whatever
	 * })
	 * ```
	 */
	plugResponse (pluginFunc) {
		Plugins.forResponse().add(pluginFunc);
	},

	preloadDataForURL (url) {
		if (SERVER_SIDE) throw new Error("Can't preload server-side");
		if (!BUNDLE_CACHE[url]){
			BUNDLE_CACHE[url] = this.get(url, BUNDLE_OPTS)
				.then(data => data.body);

		}
		return BUNDLE_CACHE[url];
	},

	_rehydratePreloadData(url) {
		// If we don't have any then we can't use it.
		if (!BUNDLE_CACHE[url]) return Q();

		return BUNDLE_CACHE[url]
			.then(data => API.cache().rehydrate(data));
	},

}

module.exports = API;
<commit_msg>Pull out preload bundle fetcher<commit_after>var RLS = require('./util/RequestLocalStorage').getNamespace()
,	Q = require("q")
,	Cache = require("./ReactServerAgent/Cache")
,	Request = require("./ReactServerAgent/Request")
,	Plugins = require("./ReactServerAgent/Plugins")
;

// wrapper for superagent
function makeRequest (method, url) {
	return new Request(method, url, API.cache());
}

const BUNDLE_CACHE     = {};
const BUNDLE_PARAMETER = '_react_server_preload_bundle';
const BUNDLE_OPTS      = {[BUNDLE_PARAMETER]: 1};

var API = {

	BUNDLE_PARAMETER,

	get (url, data) {
		var req = makeRequest('GET', url);
		if (data) req.query(data);
		return req;
	},

	head (url, data) {
		var req = makeRequest('HEAD', url);
		if (data) req.send(data);
		return req;
	},

	del (url) {
		return makeRequest('DELETE', url);
	},

	patch (url, data) {
		var req = makeRequest('PATCH', url);
		if (data) req.send(data);
		return req;
	},

	post (url, data) {
		var req = makeRequest('POST', url);
		if (data) req.send(data);
		return req;
	},

	put (url, data) {
		var req = makeRequest('PUT', url);
		if (data) req.send(data);
		return req;
	},

	/**
	 * Exposes the ReactServerAgent request data cache from RequestLocalStorage.
	 */
	cache () {
		var cache = RLS().cache;
		if (!cache) {
			cache = RLS().cache = new Cache();
		}
		return cache;
	},

	_clearCache () {
		delete RLS().cache;
	},

	/**
	 * Adds a plugin function that can be used to modify the Request
	 * object before the request is actually
	 * triggered.
	 *
	 * The callback function will take the Request instance as a parameter:
	 * ```
	 * var defaultHeaders = { ... };
	 * ReactServerAgent.plugRequest(function (request) {
	 *     // e.g.
	 *     request.set(defaultHeaders)
	 * })
	 * ```
	 */
	plugRequest (pluginFunc) {
		Plugins.forRequest().add(pluginFunc);
	},

	/**
	 * Adds a plugin function that can be used to modify the response
	 * object before it is passed the caller's callback.
	 *
	 * The callback function will take err and response as parameters
	 * (like the callback to `end()`), and the request as well:
	 * ```
	 * ReactServerAgent.plugResponse(function (err, response, request) {
	 *     // e.g.
	 *     console.log("Response received!", res.body);
	 *     res.wasLogged = true; // or whatever
	 * })
	 * ```
	 */
	plugResponse (pluginFunc) {
		Plugins.forResponse().add(pluginFunc);
	},

	preloadDataForURL (url) {
		if (SERVER_SIDE) throw new Error("Can't preload server-side");
		if (!BUNDLE_CACHE[url]){
			BUNDLE_CACHE[url] = API._fetchPreloadData(url);
		}
		return BUNDLE_CACHE[url];
	},

	_fetchPreloadData(url) {
		return this.get(url, BUNDLE_OPTS).then(data => data.body);
	},

	_rehydratePreloadData(url) {
		// If we don't have any then we can't use it.
		if (!BUNDLE_CACHE[url]) return Q();

		return BUNDLE_CACHE[url]
			.then(data => API.cache().rehydrate(data));
	},

}

module.exports = API;
<|endoftext|>


<commit_before>'use strict'

const date = new Date();

module.exports = {

// Utility Functions for Bot.js

/**
  * normalizes input from chat for grimoire card searches
  * - converts all characters to lowercase
  * - removes any colons found in chat input
  * - removes any spaces and replaces with slug "-"
  */
normalizeCardInput: function (msg) {
    let lowercaseify = msg.toLowerCase();
    let removeColon = lowercaseify.replace(":", "");
    let output = removeColon.replace(/\s+/g, "-");

    return output;
},

/**
  * Normalizes input from chat for item searches
  * - converts all characters to lower case
  * - removes any semi-colons
  * - removes any spaces and replaces with slug "-"
  */
normalizeItemInput: function (msg) {
    let lowercaseify = msg.toLowerCase();
    let stripApostrophe = lowercaseify.replace("'", "");
    let output = stripApostrophe.replace(/\s+/g, "-");

    return output;
},

/**
  * Reads array of quotes and picks one at random
  */
randomQuote: function (list) {
    return list[Math.round(Math.random()*(list.length-1))];
},

// Returns the current day of the week
curDay: function() {
  return date.getDate();
},
// Returns the current of month of the year
curMonth: function() {
  let month = date.getMonth();
  const months = [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December"
  ];
  return months[month];
}

}
<commit_msg>add minor spacing<commit_after>'use strict'

const date = new Date();

module.exports = {

// Utility Functions for Bot.js

/**
  * normalizes input from chat for grimoire card searches
  * - converts all characters to lowercase
  * - removes any colons found in chat input
  * - removes any spaces and replaces with slug "-"
  */
normalizeCardInput: function (msg) {
    let lowercaseify = msg.toLowerCase();
    let removeColon = lowercaseify.replace(":", "");
    let output = removeColon.replace(/\s+/g, "-");

    return output;
},

/**
  * Normalizes input from chat for item searches
  * - converts all characters to lower case
  * - removes any semi-colons
  * - removes any spaces and replaces with slug "-"
  */
normalizeItemInput: function (msg) {
    let lowercaseify = msg.toLowerCase();
    let stripApostrophe = lowercaseify.replace("'", "");
    let output = stripApostrophe.replace(/\s+/g, "-");

    return output;
},

/**
  * Reads array of quotes and picks one at random
  */
randomQuote: function (list) {
    return list[Math.round(Math.random()*(list.length-1))];
},

// Returns the current day of the week
curDay: function() {
  return date.getDate();
},

// Returns the current of month of the year
curMonth: function() {
  let month = date.getMonth();
  const months = [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December"
  ];
  return months[month];
}

}
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import enUS from 'antd/lib/locale-provider/en_US';
import { LocaleProvider, message, Modal, Spin } from 'antd';
import { ErrorBoundary } from '../common';
import { TabsBar, SidePanel, SidePanelResizer } from './';
import DialogPlace from '../rekit-cmds/DialogPlace';
import { fetchProjectData } from './redux/actions';

/*
  This is the root component of your app. Here you define the overall layout
  and the container of the react router. The default one is a two columns layout.
  You should adjust it acording to the type of your app.
*/

export class App extends Component {
  static propTypes = {
    home: PropTypes.object.isRequired,
    actions: PropTypes.object.isRequired,
    children: PropTypes.node.isRequired,
  };

  componentDidMount() {
    this.props.actions.fetchProjectData().catch(err => {
      Modal.error({
        title: 'Failed to load project data',
        content: err && (err.message || err.toString()),
      });
    });
  }

  componentWillReceiveProps(nextProps) {
    if (
      nextProps.home.projectDataNeedReload &&
      !nextProps.home.fetchProjectDataError &&
      !nextProps.home.fetchProjectDataPending
    ) {
      this.props.actions
        .fetchProjectData()
        .catch(e => {
          console.log('failed to fetch project data: ', e);
          message.error('Failed to refresh project data');
        });
    }
  }

  renderLoading() {
    return (

        <Spin />
        Loading...

    );
  }

  render() {
    if (!this.props.home.features) {
      return this.renderLoading();
    }

    return (
      <LocaleProvider locale={enUS}>

          <SidePanel />
          <TabsBar />
          <SidePanelResizer />
          <div id="page-container" className="page-container" style={{ left: `${this.props.home.sidePanelWidth}px` }}>
            <ErrorBoundary>{this.props.children}</ErrorBoundary>

          <DialogPlace />

      </LocaleProvider>
    );
  }
}

function mapStateToProps(state) {
  return {
    home: state.home,
  };
}

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators({ fetchProjectData }, dispatch),
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(App);
<commit_msg>Show studio title as project name<commit_after>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import enUS from 'antd/lib/locale-provider/en_US';
import { LocaleProvider, message, Modal, Spin } from 'antd';
import { ErrorBoundary } from '../common';
import { TabsBar, SidePanel, SidePanelResizer } from './';
import DialogPlace from '../rekit-cmds/DialogPlace';
import { fetchProjectData } from './redux/actions';

/*
  This is the root component of your app. Here you define the overall layout
  and the container of the react router. The default one is a two columns layout.
  You should adjust it acording to the type of your app.
*/

export class App extends Component {
  static propTypes = {
    home: PropTypes.object.isRequired,
    actions: PropTypes.object.isRequired,
    children: PropTypes.node.isRequired,
  };

  componentDidMount() {
    this.props.actions.fetchProjectData().then(() => {
      document.title = this.props.home.projectName;
    }).catch(err => {
      Modal.error({
        title: 'Failed to load project data',
        content: err && (err.message || err.toString()),
      });
    });
  }

  componentWillReceiveProps(nextProps) {
    if (
      nextProps.home.projectDataNeedReload &&
      !nextProps.home.fetchProjectDataError &&
      !nextProps.home.fetchProjectDataPending
    ) {
      this.props.actions
        .fetchProjectData()
        .catch(e => {
          console.log('failed to fetch project data: ', e);
          message.error('Failed to refresh project data');
        });
    }
  }

  renderLoading() {
    return (

        <Spin />
        Loading...

    );
  }

  render() {
    if (!this.props.home.features) {
      return this.renderLoading();
    }

    return (
      <LocaleProvider locale={enUS}>

          <SidePanel />
          <TabsBar />
          <SidePanelResizer />
          <div id="page-container" className="page-container" style={{ left: `${this.props.home.sidePanelWidth}px` }}>
            <ErrorBoundary>{this.props.children}</ErrorBoundary>

          <DialogPlace />

      </LocaleProvider>
    );
  }
}

function mapStateToProps(state) {
  return {
    home: state.home,
  };
}

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators({ fetchProjectData }, dispatch),
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(App);
<|endoftext|>


<commit_before>(function($) {
	define([], function() {
		$.extend({
			postGo: function(url, params) {
				var csrftoken = $.cookie('csrftoken');
				var $form = $("<form>").attr("method", "post").attr("action", url);
				params['csrfmiddlewaretoken'] = csrftoken;
				$.each(params, function(name, value) {
					$("<input type='hidden'>").attr("name", name).attr("value", value).appendTo($form);
				});
				$form.appendTo("body");
				$form.submit();
			}
		});
	});
})(jQuery);<commit_msg>Removing post.js because it isnt necessary with the current design.<commit_after><|endoftext|>


<commit_before>var util = require('util'),
    extendWithGettersAndSetters = require('../util/extendWithGettersAndSetters'),
    Asset = require('./Asset');

var dprMatcher = /(?:@(\d+(?:[\.,]\d+)?)x)?$/;

function Image(config) {
    Asset.call(this, config);

    if (this._fileName) {
        var dpr = this._fileName.replace(this._extension, '').match(dprMatcher)[1];

        if (dpr) {
            this.devicePixelRatio = dpr;
        }
    }
}

util.inherits(Image, Asset);

extendWithGettersAndSetters(Image.prototype, {
    /**
     * image.isImage
     * ===========
     *
     * Property that's true for all Image instances. Avoids reliance on
     * the `instanceof` operator and enables you to query for all
     * image types:
     *
     *     var imageAssets = assetGraph.findAssets({isImage: true});
     */

    notDefaultForContentType: true, // Avoid reregistering application/octet-stream

    defaultEncoding: null,

    get defaultDevicePixelRatio() {
        return 1;
    },

    get devicePixelRatio() {
        if (typeof this._devicePixelRatio !== 'undefined') {
            return this._devicePixelRatio;
        } else {
            return this.defaultDevicePixelRatio;
        }
    },

    set devicePixelRatio(ratio) {
        if (!/^\d+(?:[\.,]\d+)?$/.test(ratio.toString())) {
            throw new Error('Image device pixel ratio: May only contain digits, comma and dot');
        }

        ratio = Number(ratio.toString().replace(',', '.'));

        if (ratio <= 0) {
            throw new Error('Image device pixel ratio: Must be a larger than 0');
        }

        if (ratio === Infinity) {
            throw new Error('Image device pixel ratio: Cannot be infinite');
        }

        this._devicePixelRatio = ratio;
    },

    get fileName() {
        return Asset.prototype.__lookupGetter__('fileName').call(this);
    },

    set fileName(fileName) {
        var dpr = fileName.replace(this._extension, '').match(dprMatcher)[1];

        if (dpr) {
            this.devicePixelRatio = dpr;
        }

        Asset.prototype.__lookupSetter__('fileName').call(this, fileName);
    },

    get url() {
        return Asset.prototype.__lookupGetter__('url').call(this);
    },

    set url(url) {
        Asset.prototype.__lookupSetter__('url').call(this, url);

        var dpr = this._fileName.replace(this._extension, '').match(dprMatcher)[1];

        if (dpr) {
            this.devicePixelRatio = dpr;
        }
    }
});

module.exports = Image;
<commit_msg>Add back Image.isImage property that got lost by accident<commit_after>var util = require('util'),
    extendWithGettersAndSetters = require('../util/extendWithGettersAndSetters'),
    Asset = require('./Asset');

var dprMatcher = /(?:@(\d+(?:[\.,]\d+)?)x)?$/;

function Image(config) {
    Asset.call(this, config);

    if (this._fileName) {
        var dpr = this._fileName.replace(this._extension, '').match(dprMatcher)[1];

        if (dpr) {
            this.devicePixelRatio = dpr;
        }
    }
}

util.inherits(Image, Asset);

extendWithGettersAndSetters(Image.prototype, {
    /**
     * image.isImage
     * ===========
     *
     * Property that's true for all Image instances. Avoids reliance on
     * the `instanceof` operator and enables you to query for all
     * image types:
     *
     *     var imageAssets = assetGraph.findAssets({isImage: true});
     */
    isImage: true,

    notDefaultForContentType: true, // Avoid reregistering application/octet-stream

    defaultEncoding: null,

    get defaultDevicePixelRatio() {
        return 1;
    },

    get devicePixelRatio() {
        if (typeof this._devicePixelRatio !== 'undefined') {
            return this._devicePixelRatio;
        } else {
            return this.defaultDevicePixelRatio;
        }
    },

    set devicePixelRatio(ratio) {
        if (!/^\d+(?:[\.,]\d+)?$/.test(ratio.toString())) {
            throw new Error('Image device pixel ratio: May only contain digits, comma and dot');
        }

        ratio = Number(ratio.toString().replace(',', '.'));

        if (ratio <= 0) {
            throw new Error('Image device pixel ratio: Must be a larger than 0');
        }

        if (ratio === Infinity) {
            throw new Error('Image device pixel ratio: Cannot be infinite');
        }

        this._devicePixelRatio = ratio;
    },

    get fileName() {
        return Asset.prototype.__lookupGetter__('fileName').call(this);
    },

    set fileName(fileName) {
        var dpr = fileName.replace(this._extension, '').match(dprMatcher)[1];

        if (dpr) {
            this.devicePixelRatio = dpr;
        }

        Asset.prototype.__lookupSetter__('fileName').call(this, fileName);
    },

    get url() {
        return Asset.prototype.__lookupGetter__('url').call(this);
    },

    set url(url) {
        Asset.prototype.__lookupSetter__('url').call(this, url);

        var dpr = this._fileName.replace(this._extension, '').match(dprMatcher)[1];

        if (dpr) {
            this.devicePixelRatio = dpr;
        }
    }
});

module.exports = Image;
<|endoftext|>


<commit_before>define(
  [
    'underscore',
    'dispatchers/dispatcher',
    'stores/store',
    'rsvp',
    'constants/ProjectVolumeConstants',
    'controllers/notifications',
    'models/volume',
    'backbone',
    'globals'
  ],
  function (_, Dispatcher, Store, RSVP, ProjectVolumeConstants, NotificationController, Volume, Backbone, globals) {

    var _projectVolumes = {};
    var _isFetching = false;

    //
    // Project Volume Model
    // Mainly a helper for generating add/remove urls
    //

    var ProjectVolume = Backbone.Model.extend({
      urlRoot: function() {
        return globals.API_ROOT + "/project/" + this.project.id + "/volume";
      },

      url: function () {
        var url = Backbone.Model.prototype.url.apply(this) + globals.slash();
        return url;
      },

      initialize: function(options){
        this.volume = options.volume;
        this.project = options.project;
        this.set("id", this.volume.id);
      }
    });

    var ProjectVolumeCollection = Backbone.Collection.extend({
      model: Volume,

      url: function () {
        var url = globals.API_ROOT + "/project/" + this.project.id + "/volume" + globals.slash();
        return url;
      },

      initialize: function(models, options){
        this.project = options.project;
      }
    });

    //
    // CRUD Operations
    //

    var fetchProjectVolumes = function (project) {
      _isFetching = true;
      var promise = new RSVP.Promise(function (resolve, reject) {
        var projectVolumes = new ProjectVolumeCollection(null, {
          project: project
        });
        projectVolumes.fetch().done(function () {
          _isFetching = false;
          _projectVolumes[project.id] = projectVolumes;
          resolve();
        });
      });
      return promise;
    };

    function addVolumeToProject(volume, project){
      var projectVolume = new ProjectVolume({
        volume: volume,
        project: project
      });

      projectVolume.save().done(function(){
        var successMessage = "Volume '" + volume.get('name') + "' added to Project '" + project.get('name') + "'";
        NotificationController.success(message);
      }).fail(function(){
        var failureMessage = "Error adding Volume '" + volume.get('name') + "' to Project '" + project.get('name') + "' :(  Please let Support know.";
        NotificationController.danger(failureMessage);
        _projectVolumes[project.id].remove(volume);
      });
      _projectVolumes[project.id].add(volume);
    }

    function removeVolumeFromProject(volume, project){
      var projectVolume = new ProjectVolume({
        volume: volume,
        project: project
      });

      projectVolume.destroy().done(function(){
        var successMessage = "Volume '" + volume.get('name') + "' removed from Project '" + project.get('name') + "'";
        NotificationController.success(successMessage);
      }).fail(function(){
        var failureMessage = "Error removing Volume '" + volume.get('name') + "' from Project '" + project.get('name') + "' :(  Please let Support know.";
        NotificationController.danger(failureMessage);
        _projectVolumes[project.id].add(volume);
      });
      _projectVolumes[project.id].remove(volume);
    }

    //
    // Project Volume Store
    //

    var ProjectVolumeStore = {

      getVolumesInProject: function (project) {
        var projectVolumes = _projectVolumes[project.id];
        if(!projectVolumes) {
          fetchProjectVolumes(project).then(function(){
            ProjectVolumeStore.emitChange();
          }.bind(this));
        }
        return projectVolumes;
      }

    };

    Dispatcher.register(function (payload) {
      var action = payload.action;

      switch (action.actionType) {
        case ProjectVolumeConstants.ADD_VOLUME_TO_PROJECT:
          addVolumeToProject(action.volume, action.project);
          break;

        case ProjectVolumeConstants.REMOVE_VOLUME_FROM_PROJECT:
          removeVolumeFromProject(action.volume, action.project);
          break;

        default:
          return true;
      }

      ProjectVolumeStore.emitChange();

      return true;
    });

    _.extend(ProjectVolumeStore, Store);

    return ProjectVolumeStore;
  });
<commit_msg>correct variable name<commit_after>define(
  [
    'underscore',
    'dispatchers/dispatcher',
    'stores/store',
    'rsvp',
    'constants/ProjectVolumeConstants',
    'controllers/notifications',
    'models/volume',
    'backbone',
    'globals'
  ],
  function (_, Dispatcher, Store, RSVP, ProjectVolumeConstants, NotificationController, Volume, Backbone, globals) {

    var _projectVolumes = {};
    var _isFetching = false;

    //
    // Project Volume Model
    // Mainly a helper for generating add/remove urls
    //

    var ProjectVolume = Backbone.Model.extend({
      urlRoot: function() {
        return globals.API_ROOT + "/project/" + this.project.id + "/volume";
      },

      url: function () {
        var url = Backbone.Model.prototype.url.apply(this) + globals.slash();
        return url;
      },

      initialize: function(options){
        this.volume = options.volume;
        this.project = options.project;
        this.set("id", this.volume.id);
      }
    });

    var ProjectVolumeCollection = Backbone.Collection.extend({
      model: Volume,

      url: function () {
        var url = globals.API_ROOT + "/project/" + this.project.id + "/volume" + globals.slash();
        return url;
      },

      initialize: function(models, options){
        this.project = options.project;
      }
    });

    //
    // CRUD Operations
    //

    var fetchProjectVolumes = function (project) {
      _isFetching = true;
      var promise = new RSVP.Promise(function (resolve, reject) {
        var projectVolumes = new ProjectVolumeCollection(null, {
          project: project
        });
        projectVolumes.fetch().done(function () {
          _isFetching = false;
          _projectVolumes[project.id] = projectVolumes;
          resolve();
        });
      });
      return promise;
    };

    function addVolumeToProject(volume, project){
      var projectVolume = new ProjectVolume({
        volume: volume,
        project: project
      });

      projectVolume.save().done(function(){
        var successMessage = "Volume '" + volume.get('name') + "' added to Project '" + project.get('name') + "'";
        NotificationController.success(successMessage);
      }).fail(function(){
        var failureMessage = "Error adding Volume '" + volume.get('name') + "' to Project '" + project.get('name') + "' :(  Please let Support know.";
        NotificationController.danger(failureMessage);
        _projectVolumes[project.id].remove(volume);
      });
      _projectVolumes[project.id].add(volume);
    }

    function removeVolumeFromProject(volume, project){
      var projectVolume = new ProjectVolume({
        volume: volume,
        project: project
      });

      projectVolume.destroy().done(function(){
        var successMessage = "Volume '" + volume.get('name') + "' removed from Project '" + project.get('name') + "'";
        NotificationController.success(successMessage);
      }).fail(function(){
        var failureMessage = "Error removing Volume '" + volume.get('name') + "' from Project '" + project.get('name') + "' :(  Please let Support know.";
        NotificationController.danger(failureMessage);
        _projectVolumes[project.id].add(volume);
      });
      _projectVolumes[project.id].remove(volume);
    }

    //
    // Project Volume Store
    //

    var ProjectVolumeStore = {

      getVolumesInProject: function (project) {
        var projectVolumes = _projectVolumes[project.id];
        if(!projectVolumes) {
          fetchProjectVolumes(project).then(function(){
            ProjectVolumeStore.emitChange();
          }.bind(this));
        }
        return projectVolumes;
      }

    };

    Dispatcher.register(function (payload) {
      var action = payload.action;

      switch (action.actionType) {
        case ProjectVolumeConstants.ADD_VOLUME_TO_PROJECT:
          addVolumeToProject(action.volume, action.project);
          break;

        case ProjectVolumeConstants.REMOVE_VOLUME_FROM_PROJECT:
          removeVolumeFromProject(action.volume, action.project);
          break;

        default:
          return true;
      }

      ProjectVolumeStore.emitChange();

      return true;
    });

    _.extend(ProjectVolumeStore, Store);

    return ProjectVolumeStore;
  });
<|endoftext|>


<commit_before>var iterableProps = [
    'body', 'expression', 'arguments', 'value', 'properties', 'declarations', 'init', 'callee',
    'left', 'right', 'object', 'property'
];

module.exports = function iterateAst(node, cb, acc) {
    if((acc = cb(node, acc)) === false) {
        return false;
    }

    var i = 0, prop, nodeProp,
        j, arrNode;
    while(prop = iterableProps[i++]) {
        if(typeof (nodeProp = node[prop]) === 'object') {
            if(Array.isArray(nodeProp)) {
                j = 0;
                while(arrNode = nodeProp[j++]) {
                    if(arrNode && typeof arrNode === 'object' && iterateAst(arrNode, cb, acc) === false) {
                        return false;
                    }
                }
            }
            else {
                if(nodeProp && iterateAst(nodeProp, cb, acc) === false) {
                    return false;
                }
            }
        }
    }
};
<commit_msg>visit `callee` before `arguments`<commit_after>var iterableProps = [
    'body', 'expression', 'callee', 'arguments', 'value', 'properties',
    'declarations', 'init', 'left', 'right', 'object', 'property'
];

module.exports = function iterateAst(node, cb, acc) {
    if((acc = cb(node, acc)) === false) {
        return false;
    }

    var i = 0, prop, nodeProp,
        j, arrNode;
    while(prop = iterableProps[i++]) {
        if(typeof (nodeProp = node[prop]) === 'object') {
            if(Array.isArray(nodeProp)) {
                j = 0;
                while(arrNode = nodeProp[j++]) {
                    if(arrNode && typeof arrNode === 'object' && iterateAst(arrNode, cb, acc) === false) {
                        return false;
                    }
                }
            }
            else {
                if(nodeProp && iterateAst(nodeProp, cb, acc) === false) {
                    return false;
                }
            }
        }
    }
};
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { Confirm, Message } from 'semantic-ui-react';
import moment from 'moment';
import axios from 'axios';

import requests from '../utils/requests';
import MapWithEvents from '../components/mapWithEvents';
import AddEventModal from '../components/admin/addEventModal';

class AdminMapContainer extends Component {
  state = {
    position: [4.814278, -75.694558],
    events: [],
    openConfirmation: false,
    openEventModal: false,
    newEventLatlng: {},
    municipalityOpts: [],
    activityOpts: [],
    modalEventObj: {},
    eventFormData: {
      name: '',
      description: '',
      date: moment.utc(),
      municipality: '',
      activity: '',
      contactEmail: '',
      contactNumber: '',
      contactLink: ''
    },
    error: {
      state: false,
      message: '',
      header: ''
    }
  };

  componentDidMount() {
    this.fetchDropdownOpts();
    this.fetchEvents();
  }

  fetchDropdownOpts = () => {
    axios
      .all([requests.getActivities(), requests.getMunicipalities()])
      .then(
        axios.spread((activities, municipalities) => {
          const activityOpts = activities.data.map(act => {
            return { key: act, value: act, text: act };
          });

          const municipalityOpts = municipalities.data.map(muni => {
            return { key: muni, value: muni, text: muni };
          });
          this.setState({ activityOpts, municipalityOpts });
        })
      )
      .catch(err => {
        this.addError({
          header: 'Algo ha salido mal',
          message:
            'No se pudo traer cierta información de tu cuenta, intentalo más tarde'
        });
      });
  };

  fetchEvents = () => {
    requests
      .getEvents()
      .then(events => {
        console.log(events);
        this.setState({ events: events.data });
      })
      .catch(err => {
        this.addError({
          header: 'Algo ha salido mal',
          message: 'No se pudieron traer los eventos, intentalo más tarde.'
        });
      });
  };

  handleConfirm = () =>
    this.setState({
      openConfirmation: false,
      openEventModal: true,
      modalMode: 'creation'
    });

  // Use for confirmation cancel and modal close
  handleCancel = () =>
    this.setState({
      openConfirmation: false,
      newEventLatlng: {},
      openEventModal: false,
      modalEventObj: {}
    });

  onMapClick = e => {
    // here is displayed a modal, with fields to create a new event,
    // Preserving the clicked coordinate
    this.setState({ openConfirmation: true, newEventLatlng: e.latlng });
  };

  handleInputChange = (ev, data) => {
    const { name, value } = data;
    this.setState(prevState => {
      prevState.eventFormData[name] = value;
      return prevState;
    });
  };

  handleDateChange = date => {
    this.setState(prevState => {
      prevState.eventFormData.date = date;
      return prevState;
    });
  };

  handleSubmit = ev => {
    ev.preventDefault();
    const body = Object.assign({}, this.state.eventFormData);
    body.date = body.date.toString();
    console.log('Body to submit', body);
    let submitRequest;
    if (this.state.modalMode === 'creation') {
      body.coordinates = {
        latitude: this.state.newEventLatlng.lat,
        longitude: this.state.newEventLatlng.lng
      };
      submitRequest = requests.createEvent;
    } else {
      submitRequest = requests.updateEvent;
      body.eventId = this.state.modalEventObj._id;
      body.coordinates = this.state.modalEventObj.coordinates;
    }
    requests
      .findChannel(body)
      .then(submitRequest)
      .then(res => {
        this.handleCancel(); // cleans modal and confirmation
        this.cleanFormData();
        this.fetchEvents(); // to update map markers
      })
      .catch(err => {
        this.addError({
          header: 'Algo salio mal creando el nuevo evento',
          message:
            'Revisa que tengas permisos sobre el municipio o actividad seleccionados'
        });
        this.cleanFormData();
        this.fetchEvents(); // to update map markers
      });
  };

  addError = body => {
    this.setState({
      error: {
        state: true,
        header: body.header,
        message: body.message
      }
    });
  };

  handleEdit = event => {
    console.log('editing');
    this.setState({
      openEventModal: true,
      modalMode: 'edition',
      modalEventObj: event,
      eventFormData: {
        name: event.name,
        description: event.description,
        date: moment.utc(event.date),
        municipality: event.channel.municipality,
        activity: event.channel.activity,
        contactEmail: event.contactEmail || '',
        contactNumber: event.contactNumber || '',
        contactLink: event.contactLink || ''
      }
    });
  };

  cleanFormData = () => {
    this.setState({
      modalMode: '',
      modalEventObj: {},
      eventFormData: {
        name: '',
        description: '',
        date: moment.utc(),
        municipality: '',
        activity: '',
        contactEmail: '',
        contactNumber: '',
        contactLink: ''
      }
    });
  };

  render() {
    const {
      position,
      events,
      openConfirmation,
      openEventModal,
      eventFormData,
      modalMode
    } = this.state;

    const dropdownOpts = {
      activities: this.state.activityOpts,
      municipalities: this.state.municipalityOpts
    };

    return (

        <Message negative hidden={!this.state.error.state}>
          <Message.Header>
            {this.state.error.header}
          </Message.Header>

{this.state.error.message}

        </Message>
        <Confirm
          header="Añadir un nuevo evento"
          content="Quieres añadir un evento en este punto"
          cancelButton="Cancelar"
          confirmButton="Si!"
          open={openConfirmation}
          onCancel={this.handleCancel}
          onConfirm={this.handleConfirm}
        />
        <AddEventModal
          open={openEventModal}
          mode={modalMode}
          handleClose={this.handleCancel}
          handleInputChange={this.handleInputChange}
          eventFormData={eventFormData}
          handleDateChange={this.handleDateChange}
          handleSubmit={this.handleSubmit}
          dropdownOpts={dropdownOpts}
        />
        <MapWithEvents
          position={position}
          events={events}
          editable={true}
          handleMapClick={this.onMapClick}
          onEdit={this.handleEdit}
        />

    );
  }
}

export default AdminMapContainer;
<commit_msg>Minor change<commit_after>import React, { Component } from 'react';
import { Confirm, Message } from 'semantic-ui-react';
import moment from 'moment';
import axios from 'axios';

import requests from '../utils/requests';
import MapWithEvents from '../components/mapWithEvents';
import AddEventModal from '../components/admin/addEventModal';

class AdminMapContainer extends Component {
  state = {
    position: [4.814278, -75.694558],
    events: [],
    openConfirmation: false,
    openEventModal: false,
    newEventLatlng: {},
    municipalityOpts: [],
    activityOpts: [],
    modalEventObj: {},
    eventFormData: {
      name: '',
      description: '',
      date: moment.utc(),
      municipality: '',
      activity: '',
      contactEmail: '',
      contactNumber: '',
      contactLink: ''
    },
    error: {
      state: false,
      message: '',
      header: ''
    }
  };

  componentDidMount() {
    this.fetchDropdownOpts();
    this.fetchEvents();
  }

  fetchDropdownOpts = () => {
    axios
      .all([requests.getActivities(), requests.getMunicipalities()])
      .then(
        axios.spread((activities, municipalities) => {
          const activityOpts = activities.data.map(act => {
            return { key: act, value: act, text: act };
          });

          const municipalityOpts = municipalities.data.map(muni => {
            return { key: muni, value: muni, text: muni };
          });
          this.setState({ activityOpts, municipalityOpts });
        })
      )
      .catch(err => {
        this.addError({
          header: 'Algo ha salido mal',
          message:
            'No se pudo traer cierta información de tu cuenta, intentalo más tarde'
        });
      });
  };

  fetchEvents = () => {
    requests
      .getEvents()
      .then(events => {
        this.setState({ events: events.data });
      })
      .catch(err => {
        this.addError({
          header: 'Algo ha salido mal',
          message: 'No se pudieron traer los eventos, intentalo más tarde.'
        });
      });
  };

  handleConfirm = () =>
    this.setState({
      openConfirmation: false,
      openEventModal: true,
      modalMode: 'creation'
    });

  // Use for confirmation cancel and modal close
  handleCancel = () =>
    this.setState({
      openConfirmation: false,
      newEventLatlng: {},
      openEventModal: false,
      modalEventObj: {}
    });

  onMapClick = e => {
    // here is displayed a modal, with fields to create a new event,
    // Preserving the clicked coordinate
    this.setState({ openConfirmation: true, newEventLatlng: e.latlng });
  };

  handleInputChange = (ev, data) => {
    const { name, value } = data;
    this.setState(prevState => {
      prevState.eventFormData[name] = value;
      return prevState;
    });
  };

  handleDateChange = date => {
    this.setState(prevState => {
      prevState.eventFormData.date = date;
      return prevState;
    });
  };

  handleSubmit = ev => {
    ev.preventDefault();
    const body = Object.assign({}, this.state.eventFormData);
    body.date = body.date.toString();
    console.log('Body to submit', body);
    let submitRequest;
    if (this.state.modalMode === 'creation') {
      body.coordinates = {
        latitude: this.state.newEventLatlng.lat,
        longitude: this.state.newEventLatlng.lng
      };
      submitRequest = requests.createEvent;
    } else {
      submitRequest = requests.updateEvent;
      body.eventId = this.state.modalEventObj._id;
      body.coordinates = this.state.modalEventObj.coordinates;
    }
    requests
      .findChannel(body)
      .then(submitRequest)
      .then(res => {
        this.handleCancel(); // cleans modal and confirmation
        this.cleanFormData();
        this.fetchEvents(); // to update map markers
      })
      .catch(err => {
        this.addError({
          header: 'Algo salio mal creando el nuevo evento',
          message:
            'Revisa que tengas permisos sobre el municipio o actividad seleccionados'
        });
        this.cleanFormData();
        this.fetchEvents(); // to update map markers
      });
  };

  addError = body => {
    this.setState({
      error: {
        state: true,
        header: body.header,
        message: body.message
      }
    });
  };

  handleEdit = event => {
    console.log('editing');
    this.setState({
      openEventModal: true,
      modalMode: 'edition',
      modalEventObj: event,
      eventFormData: {
        name: event.name,
        description: event.description,
        date: moment.utc(event.date),
        municipality: event.channel.municipality,
        activity: event.channel.activity,
        contactEmail: event.contactEmail || '',
        contactNumber: event.contactNumber || '',
        contactLink: event.contactLink || ''
      }
    });
  };

  cleanFormData = () => {
    this.setState({
      modalMode: '',
      modalEventObj: {},
      eventFormData: {
        name: '',
        description: '',
        date: moment.utc(),
        municipality: '',
        activity: '',
        contactEmail: '',
        contactNumber: '',
        contactLink: ''
      }
    });
  };

  render() {
    const {
      position,
      events,
      openConfirmation,
      openEventModal,
      eventFormData,
      modalMode
    } = this.state;

    const dropdownOpts = {
      activities: this.state.activityOpts,
      municipalities: this.state.municipalityOpts
    };

    return (

        <Message negative hidden={!this.state.error.state}>
          <Message.Header>
            {this.state.error.header}
          </Message.Header>

{this.state.error.message}

        </Message>
        <Confirm
          header="Añadir un nuevo evento"
          content="Quieres añadir un evento en este punto"
          cancelButton="Cancelar"
          confirmButton="Si!"
          open={openConfirmation}
          onCancel={this.handleCancel}
          onConfirm={this.handleConfirm}
        />
        <AddEventModal
          open={openEventModal}
          mode={modalMode}
          handleClose={this.handleCancel}
          handleInputChange={this.handleInputChange}
          eventFormData={eventFormData}
          handleDateChange={this.handleDateChange}
          handleSubmit={this.handleSubmit}
          dropdownOpts={dropdownOpts}
        />
        <MapWithEvents
          position={position}
          events={events}
          editable={true}
          handleMapClick={this.onMapClick}
          onEdit={this.handleEdit}
        />

    );
  }
}

export default AdminMapContainer;
<|endoftext|>


<commit_before>/**
 * Entry point to horizontal-pager example.
 *
 * Copyright (c) 2017 Alex Grant (@localnerve), LocalNerve LLC
 * Copyrights licensed under the BSD License. See the accompanying LICENSE file for terms.
 */
/* global document */
/* eslint-disable import/no-unresolved */
import createHorizontalPager from './horizontal-pager';

/**
 * HorizontalPager callback to update the page indicator bubbles.
 *
 * @param {Number} direction - +1 for forward (left), -1 for back (right)
 */
function updateBubble (direction) {
  const selectedBbl = document.querySelector('.bbl.selected');
  const nextSibling = direction > 0 ?
    selectedBbl.nextElementSibling : selectedBbl.previousElementSibling;

  selectedBbl.classList.remove('selected');
  nextSibling.classList.add('selected');
}

let horizontalPager;

document.addEventListener('DOMContentLoaded', () => {
  horizontalPager = createHorizontalPager({
    targetClass: 'page-item',
    willComplete: updateBubble
  });
}, {
  once: true
});

document.addEventListener('unload', () => horizontalPager && horizontalPager.destroy(), {
  once: true
});
<commit_msg>update w/new instance API<commit_after>/**
 * Entry point to horizontal-pager example.
 *
 * Copyright (c) 2017 Alex Grant (@localnerve), LocalNerve LLC
 * Copyrights licensed under the BSD License. See the accompanying LICENSE file for terms.
 */
/* global document */
/* eslint-disable import/no-unresolved */
import createHorizontalPager from './horizontal-pager';

/**
 * HorizontalPager callback to update the page indicator bubbles.
 *
 * @param {Number} direction - +1 for forward (left), -1 for back (right)
 */
function updateBubble (direction) {
  const selectedBbl = document.querySelector('.bbl.selected');
  const nextSibling = direction > 0 ?
    selectedBbl.nextElementSibling : selectedBbl.previousElementSibling;

  selectedBbl.classList.remove('selected');
  nextSibling.classList.add('selected');
}

let horizontalPager;

document.addEventListener('DOMContentLoaded', () => {
  horizontalPager = createHorizontalPager({
    targetClass: 'page-item',
    willComplete: updateBubble
  });
  horizontalPager.initialize();
}, {
  once: true
});

document.addEventListener('unload', () => horizontalPager && horizontalPager.destroy(), {
  once: true
});
<|endoftext|>


<commit_before>import {TraceService} from '../traceService/trace-service';

export class HtmlViewer {

    constructor(eventAggregator) {
        this.eventAggregator = eventAggregator;
        this.subscribe();
        this.traceService  = new TraceService(eventAggregator);
        this.div = 'htmlView';
    }

    attached() {
      this.addConsoleLogging(this.eventAggregator);
      this.addErrorLogging(this.eventAggregator);
    }

    subscribe() {
      let ea = this.eventAggregator;
      let traceService = this.traceService;

      ea.subscribe('onHtmlEditorChanged', payload => {
        this.html = payload;
        this.addHtml();
      });

      ea.subscribe('onCssEditorChanged', payload => {
        this.css = payload;
        this.addCss();
      });

      ea.subscribe('onJsEditorChanged', payload => {
        let editorText = payload.js;

        let instrumentationPayload = traceService.getInstrumentation(editorText);

        if (traceService.isValid(instrumentationPayload)) {
          this.js = instrumentationPayload.data;
        } else {
          console.log(JSON.stringify(instrumentationPayload));
          this.js = editorText;
        }

        this.addJs();
      });
    }

    addJs() {
      let ea = this.eventAggregator;
      let traceService = this.traceService;
      let traceDataContainer = traceService.traceModel.traceDataContainer;

      let doc = this.getContentDocument();
      let script = doc.createElement('script');
      script.textContent = this.js;

      let result = undefined;

      try {
        ea.publish(traceService.executionEvents.running.event);

        doc.body.appendChild(script);

        result = JSON.parse(doc.getElementById(traceDataContainer).innerHTML);

        ea.publish(
          traceService.executionEvents.finished.event, {
            data: result
        });
      } catch(e) {
        let error = e.toString();

        try {
          result = JSON.parse(doc.getElementById(traceDataContainer).innerHTML);
        } catch (jsonError) {
          error += " " + jsonError.toString();
        }

        ea.publish(
          traceService.executionEvents.failed.event, {
            data: result,
            error: error
          });
      }
    }

    addCss() {
      let doc = this.getContentDocument();
      let style = doc.createElement('style');
      style.textContent = this.css;

      doc.head.appendChild(style);
    }

    addHtml() {
      let doc = this.getContentDocument();
      doc.body.innerHTML = this.html;
    }

    getContentDocument() {
      return document.getElementById(this.div)
                     .contentDocument;
    }

    addErrorLogging(eventAggregator) {
      let ea = eventAggregator;
      let window = this.getContentWindow();

      window.onerror = function publishErrors(err) {
        ea.publish('iframeError', {
          err: err
        });
      };
    }

    addConsoleLogging(eventAggregator) {
      let ea = eventAggregator;
      let window = this.getContentWindow();

      window.console.log = function publishConsoleLog() {
        ea.publish('iframeConsoleLog', {
          log: Array.prototype.slice.call(arguments)[0]
        });
	    };
    }

    getContentWindow() {
      return document.getElementById(this.div)
                     .contentWindow;
    }
}<commit_msg>fixed undefined bug<commit_after>import {TraceService} from '../traceService/trace-service';

export class HtmlViewer {

    constructor(eventAggregator) {
        this.eventAggregator = eventAggregator;
        this.traceService = new TraceService(eventAggregator);
        this.div = 'htmlView';
        this.subscribe();
    }

    attached() {
      this.addConsoleLogging(this.eventAggregator);
      this.addErrorLogging(this.eventAggregator);
    }

    subscribe() {
      let ea = this.eventAggregator;
      let traceService = this.traceService;

      ea.subscribe('onHtmlEditorChanged', payload => {
        this.html = payload;
        this.addHtml();
      });

      ea.subscribe('onCssEditorChanged', payload => {
        this.css = payload;
        this.addCss();
      });

      ea.subscribe('onJsEditorChanged', payload => {
        let editorText = payload.js;

        let instrumentationPayload = this.traceService.getInstrumentation(editorText);

        if (traceService.isValid(instrumentationPayload)) {
          this.js = instrumentationPayload.data;
        } else {
          console.log(JSON.stringify(instrumentationPayload));
          this.js = editorText;
        }

        this.addJs();
      });
    }

    addJs() {
      let ea = this.eventAggregator;
      let traceService = this.traceService;
      let traceDataContainer = traceService.traceModel.traceDataContainer;

      let doc = this.getContentDocument();
      let script = doc.createElement('script');
      script.textContent = this.js;

      let result = undefined;

      try {
        ea.publish(traceService.executionEvents.running.event);

        doc.body.appendChild(script);

        result = JSON.parse(doc.getElementById(traceDataContainer).innerHTML);

        ea.publish(
          traceService.executionEvents.finished.event, {
            data: result
        });
      } catch(e) {
        let error = e.toString();

        try {
          result = JSON.parse(doc.getElementById(traceDataContainer).innerHTML);
        } catch (jsonError) {
          error += " " + jsonError.toString();
        }

        ea.publish(
          traceService.executionEvents.failed.event, {
            data: result,
            error: error
          });
      }
    }

    addCss() {
      let doc = this.getContentDocument();
      let style = doc.createElement('style');
      style.textContent = this.css;

      doc.head.appendChild(style);
    }

    addHtml() {
      let doc = this.getContentDocument();
      doc.body.innerHTML = this.html;
    }

    getContentDocument() {
      return document.getElementById(this.div)
                     .contentDocument;
    }

    addErrorLogging(eventAggregator) {
      let ea = eventAggregator;
      let window = this.getContentWindow();

      window.onerror = function publishErrors(err) {
        ea.publish('iframeError', {
          err: err
        });
      };
    }

    addConsoleLogging(eventAggregator) {
      let ea = eventAggregator;
      let window = this.getContentWindow();

      window.console.log = function publishConsoleLog() {
        ea.publish('iframeConsoleLog', {
          log: Array.prototype.slice.call(arguments)[0]
        });
	    };
    }

    getContentWindow() {
      return document.getElementById(this.div)
                     .contentWindow;
    }
}<|endoftext|>


<commit_before>var m = require('mithril');
var classSet = require('common').classSet;
var plural = require('../../util').plural;
var enrichText = require('../studyComments').enrichText;

var firstRender = true;

function selector(data) {
  if (!firstRender && m.redraw.strategy() === 'diff') return {
    subtree: 'retain'
  };
  firstRender = false;
  return m('select.selector', {
    onchange: function(e) {
      location.href = '/practice/' + e.target.value;
    }
  }, [
    m('option[disabled][selected]', 'Practice list'),
    data.structure.map(function(section) {
      return m('optgroup', {
        label: section.name
      }, section.studies.map(function(study) {
        return m('option', {
          value: '/' + section.id + '/' + study.slug + '/' + study.id
        }, study.name);
      }));
    })
  ]);
};

function renderGoal(practice, inMoves) {
  var goal = practice.goal();
  switch (goal.result) {
    case 'mate':
      return 'Checkmate the opponent';
    case 'mateIn':
      return 'Checkmate the opponent in ' + plural('move', inMoves);
    case 'drawIn':
      return 'Hold the draw for ' + plural('more move', inMoves);
    case 'equalIn':
      return 'Equalize in ' + plural('move', inMoves);
    case 'evalIn':
      if (practice.isWhite() === (goal.cp >= 0))
        return 'Get a winning position in ' + plural('move', inMoves);
      return 'Defend for ' + plural('move', inMoves);
    case 'promotion':
      return 'Safely promote your pawn';
  }
}

module.exports = {
  underboard: function(ctrl) {
    if (ctrl.vm.loading) return m('div.feedback', m.trust(lichess.spinnerHtml));
    var p = ctrl.practice;
    switch (p.success()) {
      case true:
        return m('a.feedback.win[href=/practice]', [
          m('span', 'Success!'),
          p.nextChapter() ? null : 'Back to practice menu'
        ]);
      case false:
        return m('a.feedback.fail', {
          onclick: p.reset
        }, [
          m('span', renderGoal(p, p.goal().moves)),
          m('strong', 'Click to retry')
        ]);
      default:
        return m('div.feedback.ongoing', [
          m('div.goal', renderGoal(p, p.goal().moves - p.nbMoves())),
          p.comment() ? m('div.comment', enrichText(p.comment(), true)) : null
        ]);
    }
  },
  main: function(ctrl) {

    var current = ctrl.currentChapter();
    var data = ctrl.practice.data;

    return [
      m('div.title', [
        m('i.practice.icon.' + data.study.id),
        m('div.text', [
          m('h1', data.study.name),
          m('em', data.study.desc)
        ])
      ]),
      m('div', {
        key: 'chapters',
        class: 'list chapters',
        config: function(el, isUpdate) {
          if (!isUpdate)
            el.addEventListener('click', function(e) {
              e.preventDefault();
              var id = e.target.parentNode.getAttribute('data-id') || e.target.getAttribute('data-id');
              if (id) ctrl.setChapter(id, true);
              return false;
            });
        }
      }, [
        ctrl.chapters.list().map(function(chapter, i) {
          var loading = ctrl.vm.loading && chapter.id === ctrl.vm.nextChapterId;
          var active = !ctrl.vm.loading && current && current.id === chapter.id;
          var completion = data.completion[chapter.id] ? 'done' : 'ongoing';
          return [
            m('a', {
              href: data.url + '/' + chapter.id,
              key: chapter.id,
              'data-id': chapter.id,
              class: 'elem chapter ' + classSet({
                active: active,
                loading: loading
              })
            }, [
              m('span', {
                'data-icon': ((loading || active) && completion === 'ongoing') ? 'G' : 'E',
                class: 'status ' + completion
              }),
              m('h3', chapter.name)
            ])
          ];
        })
      ]),
      m('div.finally', [
        m('a.back', {
          'data-icon': 'I',
          href: '/practice',
          title: 'More practice'
        }),
        selector(data)
      ])
    ];
  }
};
<commit_msg>fixes #3181<commit_after>var m = require('mithril');
var classSet = require('common').classSet;
var plural = require('../../util').plural;
var enrichText = require('../studyComments').enrichText;

var firstRender = true;

function selector(data) {
  if (!firstRender && m.redraw.strategy() === 'diff') return {
    subtree: 'retain'
  };
  firstRender = false;
  return m('select.selector', {
    onchange: function(e) {
      location.href = '/practice/' + e.target.value;
    }
  }, [
    m('option[disabled][selected]', 'Practice list'),
    data.structure.map(function(section) {
      return m('optgroup', {
        label: section.name
      }, section.studies.map(function(study) {
        return m('option', {
          value: section.id + '/' + study.slug + '/' + study.id
        }, study.name);
      }));
    })
  ]);
};

function renderGoal(practice, inMoves) {
  var goal = practice.goal();
  switch (goal.result) {
    case 'mate':
      return 'Checkmate the opponent';
    case 'mateIn':
      return 'Checkmate the opponent in ' + plural('move', inMoves);
    case 'drawIn':
      return 'Hold the draw for ' + plural('more move', inMoves);
    case 'equalIn':
      return 'Equalize in ' + plural('move', inMoves);
    case 'evalIn':
      if (practice.isWhite() === (goal.cp >= 0))
        return 'Get a winning position in ' + plural('move', inMoves);
      return 'Defend for ' + plural('move', inMoves);
    case 'promotion':
      return 'Safely promote your pawn';
  }
}

module.exports = {
  underboard: function(ctrl) {
    if (ctrl.vm.loading) return m('div.feedback', m.trust(lichess.spinnerHtml));
    var p = ctrl.practice;
    switch (p.success()) {
      case true:
        return m('a.feedback.win[href=/practice]', [
          m('span', 'Success!'),
          p.nextChapter() ? null : 'Back to practice menu'
        ]);
      case false:
        return m('a.feedback.fail', {
          onclick: p.reset
        }, [
          m('span', renderGoal(p, p.goal().moves)),
          m('strong', 'Click to retry')
        ]);
      default:
        return m('div.feedback.ongoing', [
          m('div.goal', renderGoal(p, p.goal().moves - p.nbMoves())),
          p.comment() ? m('div.comment', enrichText(p.comment(), true)) : null
        ]);
    }
  },
  main: function(ctrl) {

    var current = ctrl.currentChapter();
    var data = ctrl.practice.data;

    return [
      m('div.title', [
        m('i.practice.icon.' + data.study.id),
        m('div.text', [
          m('h1', data.study.name),
          m('em', data.study.desc)
        ])
      ]),
      m('div', {
        key: 'chapters',
        class: 'list chapters',
        config: function(el, isUpdate) {
          if (!isUpdate)
            el.addEventListener('click', function(e) {
              e.preventDefault();
              var id = e.target.parentNode.getAttribute('data-id') || e.target.getAttribute('data-id');
              if (id) ctrl.setChapter(id, true);
              return false;
            });
        }
      }, [
        ctrl.chapters.list().map(function(chapter, i) {
          var loading = ctrl.vm.loading && chapter.id === ctrl.vm.nextChapterId;
          var active = !ctrl.vm.loading && current && current.id === chapter.id;
          var completion = data.completion[chapter.id] ? 'done' : 'ongoing';
          return [
            m('a', {
              href: data.url + '/' + chapter.id,
              key: chapter.id,
              'data-id': chapter.id,
              class: 'elem chapter ' + classSet({
                active: active,
                loading: loading
              })
            }, [
              m('span', {
                'data-icon': ((loading || active) && completion === 'ongoing') ? 'G' : 'E',
                class: 'status ' + completion
              }),
              m('h3', chapter.name)
            ])
          ];
        })
      ]),
      m('div.finally', [
        m('a.back', {
          'data-icon': 'I',
          href: '/practice',
          title: 'More practice'
        }),
        selector(data)
      ])
    ];
  }
};
<|endoftext|>


<commit_before>function createXML(height, width, mapString) {
    return [
        '<?xml version="1.0" encoding="UTF-8"?>',
        '<map height="' + width + '" width="' + height + '">',
        '    <game seed="9977882" rounds="2000"/>',
        '    <symbols>',
        '        <symbol terrain="LAND" type="TERRAIN" character="."/>',
        '        <symbol team="NEUTRAL" type="MINE" character="3"/>',
        '        <symbol team="NEUTRAL" type="ENCAMPMENT" character="@"/>',
        '        <symbol team="A" type="HQ" character="a"/>',
        '        <symbol team="B" type="HQ" character="b"/>',
        '    </symbols>',
        '    <data>',
        '<![CDATA[',
        mapString,
        ']]>',
        '    </data>',
        '</map>'
    ].join('\n')
}

module.exports = createXML;<commit_msg>Better random seed<commit_after>function createXML(height, width, mapString) {
    return [
        '<?xml version="1.0" encoding="UTF-8"?>',
        '<map height="' + width + '" width="' + height + '">',
        '    <game seed="' + parseInt(Math.random() * 1000000) + '" rounds="2000"/>',
        '    <symbols>',
        '        <symbol terrain="LAND" type="TERRAIN" character="."/>',
        '        <symbol team="NEUTRAL" type="MINE" character="3"/>',
        '        <symbol team="NEUTRAL" type="ENCAMPMENT" character="@"/>',
        '        <symbol team="A" type="HQ" character="a"/>',
        '        <symbol team="B" type="HQ" character="b"/>',
        '    </symbols>',
        '    <data>',
        '<![CDATA[',
        mapString,
        ']]>',
        '    </data>',
        '</map>'
    ].join('\n')
}

module.exports = createXML;<|endoftext|>


<commit_before>/**
 ## Data Grid Widget

 Includes: [Base Mixin](#base-mixin)

 Data grid is a simple widget designed to list crossfilter focused data set (items being filtered) and provide you a simple way to define how each data item is displayed.
 fashion.

 Examples:
 * [List of members of the european parliament ](http://europarl.me/dc.js/web/ep/index.html)

 #### dc.dataGrid(parent[, chartGroup])
 Create a data grid widget instance and attach it to the given parent element.

 Parameters:
 * parent : string - any valid d3 single selector representing typically a dom block element such as a div.
 * chartGroup : string (optional) - name of the chart group this chart instance should be placed in. Once a chart is placed
 in a certain chart group then any interaction with such instance will only trigger events and redraw within the same
 chart group.
 * html (item): function - return the html fragment for each item in the dataset. you can use a templating library or build the html directly.
 Return:
 A newly created data grid widget instance

 **/
dc.dataGrid = function(parent, chartGroup) {
    var LABEL_CSS_CLASS = "dc-grid-label";
    var ITEM_CSS_CLASS = "dc-grid-item";
    var GROUP_CSS_CLASS = "dc-grid-group";
    var GRID_CSS_CLASS = "dc-grid-top";

    var _chart = dc.baseMixin({});

    var _size = 999; // shouldn't be needed, but you might
    var _html = function (d) { return "you need to provide an html() handling param:  " + JSON.stringify(d); };
    var _sortBy = function(d) {
        return d;
    };
    var _order = d3.ascending;

    var _htmlGroup = function (d) {
        return "

"+
            _chart.keyAccessor()(d)+"

";
    };

    _chart._doRender = function() {
        _chart.selectAll("div."+ GRID_CSS_CLASS).remove();

        renderItems(renderGroups());

        return _chart;
    };

    function renderGroups() {
        var groups = _chart.root().selectAll("div."+ GRID_CSS_CLASS)
                .data(nestEntries(), function(d) {
                    return _chart.keyAccessor()(d);
                });

        var itemGroup = groups
                .enter()
                .append("div")
                .attr("class", GRID_CSS_CLASS);

        if (_htmlGroup) {
            itemGroup
                .html(function(d) {
                    return _htmlGroup(d);
                });
        }

        groups.exit().remove();
        return itemGroup;
    }

    function nestEntries() {
        var entries = _chart.dimension().top(_size);

        return d3.nest()
            .key(_chart.group())
            .sortKeys(_order)
            .entries(entries.sort(function(a, b){
                return _order(_sortBy(a), _sortBy(b));
            }));
    }

    function renderItems(groups) {
        var items = groups.order()
                .selectAll("div." + ITEM_CSS_CLASS)
                .data(function(d) {
                    return d.values;
                });

        items.enter()
            .append("div")
            .attr("class", ITEM_CSS_CLASS)
            .html(function(d) {
                return _html(d);
            });

        items.exit().remove();

        return items;
    }

    _chart._doRedraw = function() {
        return _chart._doRender();
    };

    /**
     #### .size([size])
     Get or set the grid size which determines the number of items displayed by the widget.

     **/
    _chart.size = function(s) {
        if (!arguments.length) return _size;
        _size = s;
        return _chart;
    };

    /**
     #### .html( function (data) { return ""; })
     Get or set the function that formats an item. Data grid widget uses a function to generate dynamic html. Use your favourite templating engine or generate the string directly
     ```js
     chart.html(function (d) { return "<div class='item "+data.exampleCategory+"'>"+data.exampleString+"</div>";});
     ```

     **/
    _chart.html = function(_) {
        if (!arguments.length) return _html;
        _html = _;
        return _chart;
    };

    /**
     #### .htmlGroup( function (data) { return ""; })
     Get or set the function that formats a group label. The provided example uses handlebar templating libary, but feel free to do it the way you want
     ```js
     chart.htmlGroup (function (d) { return "<h2>".d.key . "with " . d.values.length ." items</h2>"});
     ```

     **/

    _chart.htmlGroup = function(_) {
        if (!arguments.length) return _htmlGroup;
        _htmlGroup = _;
        return _chart;
    };
    /**
     #### .sortBy([sortByFunction])
     Get or set sort-by function. This function works as a value accessor at item level and returns a particular field to be sorted
     by. Default value: ``` function(d) {return d;}; ```

     ```js
     chart.sortBy(function(d) {
     return d.date;
     });
     ```

     **/
    _chart.sortBy = function(_) {
        if (!arguments.length) return _sortBy;
        _sortBy = _;
        return _chart;
    };

    /**
     #### .order([order])
     Get or set sort order. Default value: ``` d3.ascending ```

     ```js
     chart.order(d3.descending);
     ```

     **/
    _chart.order = function(_) {
        if (!arguments.length) return _order;
        _order = _;
        return _chart;
    };

    return _chart.anchor(parent, chartGroup);
};
<commit_msg>minor documentation fixes<commit_after>/**
 ## Data Grid Widget

 Includes: [Base Mixin](#base-mixin)

 Data grid is a simple widget designed to list the filtered records, providing
 a simple way to define how the items are displayed.

 Examples:
 * [List of members of the european parliament ](http://europarl.me/dc.js/web/ep/index.html)

 #### dc.dataGrid(parent[, chartGroup])
 Create a data grid widget instance and attach it to the given parent element.

 Parameters:
 * parent : string - any valid d3 single selector representing typically a dom block element such as a div.
 * chartGroup : string (optional) - name of the chart group this chart instance should be
 placed in. Once a chart is placed in a chart group then any interaction with the chart
 will only trigger events and redraw within the same chart group.
 * html (item): function - return the html fragment for each item in the dataset.
 You can use a templating library or build the html directly.
 Return:
 A newly created data grid widget instance

 **/
dc.dataGrid = function(parent, chartGroup) {
    var LABEL_CSS_CLASS = "dc-grid-label";
    var ITEM_CSS_CLASS = "dc-grid-item";
    var GROUP_CSS_CLASS = "dc-grid-group";
    var GRID_CSS_CLASS = "dc-grid-top";

    var _chart = dc.baseMixin({});

    var _size = 999; // shouldn't be needed, but you might
    var _html = function (d) { return "you need to provide an html() handling param:  " + JSON.stringify(d); };
    var _sortBy = function(d) {
        return d;
    };
    var _order = d3.ascending;

    var _htmlGroup = function (d) {
        return "

"+
            _chart.keyAccessor()(d)+"

";
    };

    _chart._doRender = function() {
        _chart.selectAll("div."+ GRID_CSS_CLASS).remove();

        renderItems(renderGroups());

        return _chart;
    };

    function renderGroups() {
        var groups = _chart.root().selectAll("div."+ GRID_CSS_CLASS)
                .data(nestEntries(), function(d) {
                    return _chart.keyAccessor()(d);
                });

        var itemGroup = groups
                .enter()
                .append("div")
                .attr("class", GRID_CSS_CLASS);

        if (_htmlGroup) {
            itemGroup
                .html(function(d) {
                    return _htmlGroup(d);
                });
        }

        groups.exit().remove();
        return itemGroup;
    }

    function nestEntries() {
        var entries = _chart.dimension().top(_size);

        return d3.nest()
            .key(_chart.group())
            .sortKeys(_order)
            .entries(entries.sort(function(a, b){
                return _order(_sortBy(a), _sortBy(b));
            }));
    }

    function renderItems(groups) {
        var items = groups.order()
                .selectAll("div." + ITEM_CSS_CLASS)
                .data(function(d) {
                    return d.values;
                });

        items.enter()
            .append("div")
            .attr("class", ITEM_CSS_CLASS)
            .html(function(d) {
                return _html(d);
            });

        items.exit().remove();

        return items;
    }

    _chart._doRedraw = function() {
        return _chart._doRender();
    };

    /**
     #### .size([size])
     Get or set the grid size which determines the number of items displayed by the widget.

     **/
    _chart.size = function(s) {
        if (!arguments.length) return _size;
        _size = s;
        return _chart;
    };

    /**
     #### .html( function (data) { return ""; })
     Get or set the function that formats an item. The data grid widget uses a
     function to generate dynamic html. Use your favourite templating engine or
     generate the string directly.
     ```js
     chart.html(function (d) { return "<div class='item "+data.exampleCategory+"'>"+data.exampleString+"</div>";});
     ```

     **/
    _chart.html = function(_) {
        if (!arguments.length) return _html;
        _html = _;
        return _chart;
    };

    /**
     #### .htmlGroup( function (data) { return ""; })
     Get or set the function that formats a group label.
     ```js
     chart.htmlGroup (function (d) { return "<h2>".d.key . "with " . d.values.length ." items</h2>"});
     ```

     **/

    _chart.htmlGroup = function(_) {
        if (!arguments.length) return _htmlGroup;
        _htmlGroup = _;
        return _chart;
    };
    /**
     #### .sortBy([sortByFunction])
     Get or set sort-by function. This function works as a value accessor at the item
     level and returns a particular field to be sorted.
     by. Default value: ``` function(d) {return d;}; ```

     ```js
     chart.sortBy(function(d) {
     return d.date;
     });
     ```

     **/
    _chart.sortBy = function(_) {
        if (!arguments.length) return _sortBy;
        _sortBy = _;
        return _chart;
    };

    /**
     #### .order([order])
     Get or set sort order function. Default value: ``` d3.ascending ```

     ```js
     chart.order(d3.descending);
     ```

     **/
    _chart.order = function(_) {
        if (!arguments.length) return _order;
        _order = _;
        return _chart;
    };

    return _chart.anchor(parent, chartGroup);
};
<|endoftext|>