<commit_before>/*
 * changes to previous injection implementations
 * - no support for data-injection anymore, switch to new data-inject
 * - no support for data-href-next anymore, switch to data-inject: next-href
 * - XXX: add support for forms, see remnants in inject1 and ajaxify
 */
define([
    "jquery",
    "../core/parser",
    "../lib/ajax",
    "../lib/inject",
    "../logging",
    "../registry",
    "../3rdparty/URI"
], function($, Parser, ajax, injectlib, logging, registry) {
    var log = logging.getLogger('inject'),
        parser = new Parser("inject");

    parser.add_argument('source');
    parser.add_argument('target');
    parser.add_argument('replace');
    parser.add_argument('replacetagwithcontent');
    parser.add_argument('pre');
    parser.add_argument('post');
    parser.add_argument('prepend');
    parser.add_argument('append');
    parser.add_argument('url');
    parser.add_argument('method', 'content');
    parser.add_argument('type');
    parser.add_argument('next-href');

    var _ = {
        name: "inject",
        trigger: "a.pat-inject, form.pat-inject",
        init: function($el, opts) {
            return $el.each(function() {
                var $el = $(this),
                    cfg = _.extractConfig($el, opts);
                $el.data('patterns.inject', cfg);

                // In case next-href is specified the anchor's href will
                // be set to it after the injection is triggered. In case
                // the next href already exists, we do not activate the
                // injection but instead just change the anchors href.
                //
                // XXX: This is used in only one project for linked
                // fullcalendars, it's sanity is wonky and we should
                // probably solve it differently.
                var $nexthref = $(cfg.nextHref);
                if ($el.is('a') && $nexthref.length > 0) {
                    log.debug('Skipping as next href already exists', $nexthref);
                    // XXX: reconsider how the injection enters exhausted state
                    return $el.attr({href: cfg.nextHref});
                }

                // setup event handlers
                if ($el.is('a'))
                    $el.on("click.pat-inject", _.onClick);
                return $el;
            });
        },
        destroy: function($el) {
            $el.off('.pat-inject');
            $el.data('patterns.inject', null);
            return $el;
        },

        onClick: function(ev) {
            var $el = $(this),
                cfg = $el.data('patterns.inject');

            if (ev)
                ev.preventDefault();

            // modals are special
            if ($el.is('.modal')) {
                if (cfg.slice) {
                    log.error('Multi injection not supported for modals');
                    return;
                }
                cfg.target = '#modal';
                cfg.method = "replace";
                cfg.modal = true;
            }

            cfg.forEach(function(cfg) {
                cfg.$targets = $(cfg.target);

                // create non-existing targets
                if (cfg.$targets.length === 0) {
                    if (cfg.target.slice(0,1) !== '#') {
                        log.error('only id supported for non-existing target');
                    }
                    cfg.$targets = $('
').attr({id: cfg.target.slice(1)});
                    $('body').append(cfg.$targets);
                }
            });
            _.execute(cfg);
        },
        // XXX: this should be over in expandable
        onFolderOpen: function(ev) {
            if (ev && ev.target !== ev.currentTarget) return;
            var cfg = $(this).data('patterns.inject');
            if (Array.prototype.isArray.call(cfg)) {
                log.error('Multi injection not supported for .folder');
                return;
            }
            cfg.$targets = $.children('ul', this);
            _.execute(cfg);
        },

        extractConfig: function($el, opts) {
            var cfg = {}, urlparts,
                url = $el.attr('href') || $el.attr('action');

            cfg = parser.parse($el, opts, true);

            cfg.forEach(function(cfg) {
                if (!cfg.url) cfg.url = url;

                // Check for source id as part of url
                urlparts = cfg.url.split('#');
                cfg.url = urlparts[0];
                cfg.source = cfg.source || urlparts[1] ? '#' + urlparts[1] : "";
                if (urlparts.length > 2) {
                    log.warn('Ignoring additional source ids:', urlparts.slice(2));
                }

                // XXX: this syntax is under discussion
                // injection method
                ["replace", "replacetagwithcontent", "pre", "post",
                 "append", "prepend"
                ].forEach(function(method) {
                    if (cfg[method]) {
                        cfg.target = cfg[method];
                        cfg.method = method;
                    }
                });

                // target defaults to source, source needed in this case
                if (!cfg.target) {
                    if (!cfg.source) {
                        log.error('Need source!');
                    }
                    cfg.target = cfg.source;
                }
            });
            return cfg;
        },

        execute: function(cfg) {
            var $this = $(this);

            // sanity checks
            var url = cfg[0].url;
            if (!cfg.every(function(opts) {
                return opts.url === url;
            })) {
                log.error('Unsupported different urls for multi-inject');
                return;
            };
            if (!cfg.every(function(opts) {
                return opts.$targets.length;
            })) {
                log.error('Missing targets, aborting');
                return;
            }

            cfg.forEach(function(cfg) {
                cfg.method = cfg.method || 'content';
                cfg.source = cfg.source || 'body';
                cfg.classes = 'injecting injecting-' + cfg.method;
                cfg.$targets.addClass(cfg.classes);
            });

            var successHandler = function(data, status, jqxhr) {
                var uri,
                    $data = $('
').html(
                        data.replace(/


<commit_before>const path = require('path');
const jsonServer = require('json-server');
const fs = require('fs-extra');
const faker = require('faker');
const express = require('express');
const { now } = require('./time-now');
const { fe_port, be_port } = require('./ports');
const server = jsonServer.create();
const os = require('os');

faker.seed(12345);

server.all('/*', function(req, res, next) {
  res.setHeader('X-App-Date', now);
  res.setHeader('Access-Control-Expose-Headers', 'X-App-Date');
  next();  // call next() here to move on to next middleware/router
});

const DB = path.join(os.tmpdir(), 'tutor-test-server/backend/db.json');
fs.copySync(path.join(__dirname, './backend/db.json'), DB);

const router = jsonServer.router(DB);
const middlewares = jsonServer.defaults({
  logger: false,
});
const log = require('./log');
server.use(express.json());
server.use(middlewares);
const GET_HANDLERS = {
  setrole: {
    setRole() {  },
    handler(req, resp) { setRole(req.query.role); resp.json({ ok: true }); },
  },
  bootstrap: require('./backend/bootstrap'),
  offerings: require('./backend/offerings'),
  'courses/:courseId/dashboard': require('./backend/dashboard'),
  'courses/:courseId/performance': require('./backend/performance'),
  'courses/:courseId/guide': require('./backend/performance-forecast'),
  'ecosystems/:ecosystemId/readings': require('./backend/readings'),
  'ecosystems/:ecosystemId/exercises/homework_core': require('./backend/exercises'),
};

const MULTI_HANDLERS = [
  require('./backend/grading-templates'),
  require('./backend/task-plans'),
  require('./backend/courses'),
  require('./backend/tasks'),
];

// routes that have custom logic
for (let route in GET_HANDLERS) {
  server.get(`/api/${route}`, GET_HANDLERS[route].handler);
}
MULTI_HANDLERS.forEach((handler) => {
  handler.route(server);
});

server.use(jsonServer.rewriter({
  '/api/user/ui_settings': '/ui-settings',
  '/api/log/entry': '/log',
  '/api/log/event/onboarding/:id': '/onboarding',
  '/api/user/tours/:id': '/tours',
  '/api/:key': '/:key',
  '/api/courses/:courseId/plans*': '/previousTaskPlans',
}));
server.use(router);

function setRole(role) {
  for (let route in GET_HANDLERS) {
    GET_HANDLERS[route].setRole(role);
  }
  MULTI_HANDLERS.forEach((handler) => { handler.setRole(role); });
}

server.listen(be_port, () => {
  log('READY', true);
});

process.on('message', (msg) => {
  if (msg.role) {
    setRole(msg.role);
  }
});
<commit_msg>add api in test sserver for reading exercises<commit_after>const path = require('path');
const jsonServer = require('json-server');
const fs = require('fs-extra');
const faker = require('faker');
const express = require('express');
const { now } = require('./time-now');
const { fe_port, be_port } = require('./ports');
const server = jsonServer.create();
const os = require('os');

faker.seed(12345);

server.all('/*', function(req, res, next) {
  res.setHeader('X-App-Date', now);
  res.setHeader('Access-Control-Expose-Headers', 'X-App-Date');
  next();  // call next() here to move on to next middleware/router
});

const DB = path.join(os.tmpdir(), 'tutor-test-server/backend/db.json');
fs.copySync(path.join(__dirname, './backend/db.json'), DB);

const router = jsonServer.router(DB);
const middlewares = jsonServer.defaults({
  logger: false,
});
const log = require('./log');
server.use(express.json());
server.use(middlewares);
const GET_HANDLERS = {
  setrole: {
    setRole() {  },
    handler(req, resp) { setRole(req.query.role); resp.json({ ok: true }); },
  },
  bootstrap: require('./backend/bootstrap'),
  offerings: require('./backend/offerings'),
  'courses/:courseId/dashboard': require('./backend/dashboard'),
  'courses/:courseId/performance': require('./backend/performance'),
  'courses/:courseId/guide': require('./backend/performance-forecast'),
  'ecosystems/:ecosystemId/readings': require('./backend/readings'),
  'ecosystems/:ecosystemId/exercises/homework_core': require('./backend/exercises'),
  'ecosystems/:ecosystemId/exercises': require('./backend/exercises'),
};

const MULTI_HANDLERS = [
  require('./backend/grading-templates'),
  require('./backend/task-plans'),
  require('./backend/courses'),
  require('./backend/tasks'),
];

// routes that have custom logic
for (let route in GET_HANDLERS) {
  server.get(`/api/${route}`, GET_HANDLERS[route].handler);
}
MULTI_HANDLERS.forEach((handler) => {
  handler.route(server);
});

server.use(jsonServer.rewriter({
  '/api/user/ui_settings': '/ui-settings',
  '/api/log/entry': '/log',
  '/api/log/event/onboarding/:id': '/onboarding',
  '/api/user/tours/:id': '/tours',
  '/api/:key': '/:key',
  '/api/courses/:courseId/plans*': '/previousTaskPlans',
}));
server.use(router);

function setRole(role) {
  for (let route in GET_HANDLERS) {
    GET_HANDLERS[route].setRole(role);
  }
  MULTI_HANDLERS.forEach((handler) => { handler.setRole(role); });
}

server.listen(be_port, () => {
  log('READY', true);
});

process.on('message', (msg) => {
  if (msg.role) {
    setRole(msg.role);
  }
});
<|endoftext|>


<commit_before>import { React, PropTypes, observer, action, cn } from '../../helpers/react';
import { Col } from 'react-bootstrap';
import { ArbitraryHtmlAndMath } from 'shared';
import Breadcrumb from '../../components/breadcrumb';
import UX from './ux';

@observer
class Milestone extends React.Component {

  static propTypes = {
    //ux: PropTypes.instanceOf(UX).isRequired,
    goToStep: PropTypes.func.isRequired,
    step: PropTypes.object.isRequired,
    currentStep: PropTypes.number.isRequired,
    stepIndex: PropTypes.number,
  };

  @action.bound goToStep() {
    this.props.goToStep(
      this.props.stepIndex, this.props.step
    );
  }

  render() {
    const { step, currentStep, stepIndex } = this.props;
    const active = stepIndex === currentStep;
    const classes = cn('milestone', `milestone-${step.type}`, { active });

    const preview = (step.type === 'exercise') ?
      <ArbitraryHtmlAndMath block={true}
        className="milestone-preview"
        html={step.preview}
      /> :
{step.preview}
;

    return (
      <Col xs={3} lg={2} className="milestone-wrapper">

          <Breadcrumb
            step={step}
            stepIndex={stepIndex}
            data-label={step.label}
            goToStep={this.goToStep}
            currentStep={currentStep}
            isCurrent={active}
            key={`breadstep-${step.type}-${stepIndex}`}
          />
          {preview}

      </Col>
    );
  }
}

class Milestones extends React.Component {

  static propTypes = {
    ux: PropTypes.instanceOf(UX).isRequired,
    onHide: PropTypes.func.isRequired,
  }

  @action.bound goToStep(index) {
    this.props.ux.goToStep(index);
    this.props.onHide();
  }

  render() {
    const { ux } = this.props;

    return (

          {ux.steps.map( (step, stepIndex) =>
            <Milestone
              key={`step-wrapper-${stepIndex}`}
              step={step}
              goToStep={this.goToStep}
              stepIndex={stepIndex}
              currentStep={ux.currentStepIndex}
            />)}

    );
  }

}

export { Milestones, Milestone };
<commit_msg>only render completed steps<commit_after>import { React, PropTypes, observer, action, cn } from '../../helpers/react';
import { Col } from 'react-bootstrap';
import { ArbitraryHtmlAndMath } from 'shared';
import Breadcrumb from '../../components/breadcrumb';
import UX from './ux';

@observer
class Milestone extends React.Component {

  static propTypes = {
    goToStep: PropTypes.func.isRequired,
    step: PropTypes.object.isRequired,
    currentStep: PropTypes.number.isRequired,
    stepIndex: PropTypes.number,
  };

  @action.bound goToStep() {
    this.props.goToStep(
      this.props.stepIndex, this.props.step
    );
  }

  render() {
    const { step, currentStep, stepIndex } = this.props;
    const active = stepIndex === currentStep;
    const classes = cn('milestone', `milestone-${step.type}`, { active });

    const preview = (step.type === 'exercise') ?
      <ArbitraryHtmlAndMath block={true}
        className="milestone-preview"
        html={step.preview}
      /> :
{step.preview}
;

    return (
      <Col xs={3} lg={2} className="milestone-wrapper">

          <Breadcrumb
            step={step}
            stepIndex={stepIndex}
            data-label={step.label}
            goToStep={this.goToStep}
            currentStep={currentStep}
            isCurrent={active}
            key={`breadstep-${step.type}-${stepIndex}`}
          />
          {preview}

      </Col>
    );
  }
}

class Milestones extends React.Component {

  static propTypes = {
    ux: PropTypes.instanceOf(UX).isRequired,
    onHide: PropTypes.func.isRequired,
  }

  @action.bound goToStep(index) {
    this.props.ux.goToStep(index);
    this.props.onHide();
  }

  render() {
    const { ux } = this.props;

    return (

          {ux.milestoneSteps.map( (step, stepIndex) =>
            <Milestone
              key={`step-wrapper-${stepIndex}`}
              step={step}
              goToStep={this.goToStep}
              stepIndex={stepIndex}
              currentStep={ux.currentStepIndex}
            />)}

    );
  }

}

export { Milestones, Milestone };
<|endoftext|>


<commit_before>var connect = require('connect');
connect.createServer(
    connect.static(__dirname+"/../")
).listen(8000);
console.log("webnes started");).listen(8000);
console.log("webnes started")<commit_msg>fix server.js<commit_after>var connect = require('connect');
connect.createServer(
    connect.static(__dirname+"/../")
).listen(8000);
console.log("webnes started");<|endoftext|>


<commit_before>/* jshint -W097 */
"use strict";

var data = {};

/**
 * Dummy definition for IDE support. These objects are
 * generally read from the web socket connection.
 * @constructor
 */
function SourceSection() {
  this.firstIndex = 0;
  this.sourceText = "";
  this.shortName  = "";
}

/**
 * Dummy definition for IDE support. These objects are
 * generally read from the web socket connection.
 * @constructor
 */
function InvocationProfile() {
  this.invocations = 0;
  this.somTypes = [];
}

/**
 * Dummy definition for IDE support. These objects are
 * generally read from the web socket connection.
 * @constructor
 */
function CountingProfile() {
  this.count = 0;
}

function Actor(id, name, typeName) {
  this.id       = id;
  this.name     = name;
  this.typeName = typeName;
}

function MessageHistory(messages, actors) {
  this.messages = messages; // per actor
  this.actors   = actors;
}

function Message(id, sender, receiver) {
  this.id       = id;
  this.sender   = sender;
  this.receiver = receiver;
}

function countNumberOfLines(str) {
  var cnt = 1;
  for (var i = 0; i < str.length; i++) {
    if (str[i] == "\n") {
      cnt += 1;
    }
  }
  return cnt;
}

function loadAndProcessFile(f) {
  var reader = new FileReader();
  reader.onload = (function(theFile) {

    function receivedFile(e) {
      var o = JSON.parse(e.target.result);
      data[theFile.name] = o;
      displaySources(o);
    }

    return receivedFile;
  })(f);

  reader.readAsText(f);
}

/**
 * @param {DragEvent} e
 */
function handleFileSelect(e) {
  e.stopPropagation();
  e.preventDefault();

  var files = e.dataTransfer.files; // FileList object.

  // files is a FileList of File objects. List some properties.
  var output = [];
  for (var i = 0; i < files.length; i++) {
    loadAndProcessFile(files[i]);
  }
}

var accessProfiles = [],
  maxAccessCount = -1;

function Breakpoint(source, line, lineNumSpan) {
  this.source      = source;
  this.line        = line;
  this.enabled     = false;
  this.lineNumSpan = lineNumSpan;
  this.checkbox    = null;
}

Breakpoint.prototype.toggle = function () {
  this.enabled = !this.enabled;
};

Breakpoint.prototype.isEnabled = function () {
  return this.enabled;
};

function handleDragOver(evt) {
  evt.stopPropagation();
  evt.preventDefault();
  evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
}

function dbgLog(msg) {
  var tzOffset = (new Date()).getTimezoneOffset() * 60000; // offset in milliseconds
  var localISOTime = (new Date(Date.now() - tzOffset)).toISOString().slice(0,-1);

  $("#debugger-log").html(localISOTime + ": " + msg + "
" + $("#debugger-log").html());
}

function Debugger() {
  this.suspended = false;
  this.lastSuspendEventId = null;
  this.sourceObjects = {};
  this.breakpoints = {};
}

Debugger.prototype.getSource = function (id) {
  for (var fileName in this.sourceObjects) {
    if (this.sourceObjects[fileName].id === id) {
      return this.sourceObjects[fileName];
    }
  }
  return null;
};

Debugger.prototype.addSources = function (msg) {
  for (var sId in msg.sources) {
    this.sourceObjects[msg.sources[sId].name] = msg.sources[sId];
  }
};

Debugger.prototype.getBreakpoint = function (source, line, clickedSpan) {
  if (!this.breakpoints[source]) {
    this.breakpoints[source] = {};
  }

  var bp = this.breakpoints[source][line];
  if (!bp) {
    bp = new Breakpoint(source, line, clickedSpan);
    this.breakpoints[source][line] = bp;
  }
  return bp;
};

Debugger.prototype.setSuspended = function(eventId) {
  console.assert(!this.suspended);
  this.suspended = true;
  this.lastSuspendEventId = eventId;
};

Debugger.prototype.setResumed = function () {
  console.assert(this.suspended);
  this.suspended = false;
};

Debugger.prototype.updateUIForContinuingExecution = function() {

};

Debugger.prototype.resume = function() {
  console.assert(this.suspended);

  this.updateUIForContinuingExecution();

};
Debugger.prototype.pause = function() {
  console.assert(!this.suspended);

};
Debugger.prototype.stop = function() {
  console.assert(!this.suspended);

};

Debugger.prototype.stepInto = function() {
  console.assert(this.suspended);

  this.updateUIForContinuingExecution();

};
Debugger.prototype.stepOver = function() {
  console.assert(this.suspended);

  this.socket.send(JSON.stringify({
    action:'stepOver',
    suspendEvent: this.lastSuspendEventId}));
};
Debugger.prototype.return = function() {
  console.assert(this.suspended);

};

/* globals View, Controller, VmConnection */
var ctrl;

function init() {
  var view = new View(),
    vmConnection = new VmConnection(),
    dbg = new Debugger();
  ctrl = new Controller(dbg, view, vmConnection);
  ctrl.toggleConnection();

  // Init drag and drop
  var fileDrop = document.getElementById('file-drop');
  fileDrop.addEventListener('dragover', handleDragOver,   false);
  fileDrop.addEventListener('drop',     handleFileSelect, false);
}

function blobToFile(blob, name) {
  blob.lastModifiedDate = new Date();
  blob.name = name;
  return blob;
}

function getFileObjectFromPath(pathOrUrl, callback) {
  var request = new XMLHttpRequest();
  request.open("GET", pathOrUrl);
  request.responseType = "blob";
  request.addEventListener('load', function () {
    callback(blobToFile(request.response, pathOrUrl));
  });
  request.send();
}

function loadStandardFile() {
  getFileObjectFromPath("highlight.json",
    function(file) {
      loadAndProcessFile(file);
    });
}
<commit_msg>Remove unused code<commit_after>/* jshint -W097 */
"use strict";

var data = {};

/**
 * Dummy definition for IDE support. These objects are
 * generally read from the web socket connection.
 * @constructor
 */
function SourceSection() {
  this.firstIndex = 0;
  this.sourceText = "";
  this.shortName  = "";
}

/**
 * Dummy definition for IDE support. These objects are
 * generally read from the web socket connection.
 * @constructor
 */
function InvocationProfile() {
  this.invocations = 0;
  this.somTypes = [];
}

/**
 * Dummy definition for IDE support. These objects are
 * generally read from the web socket connection.
 * @constructor
 */
function CountingProfile() {
  this.count = 0;
}

function Actor(id, name, typeName) {
  this.id       = id;
  this.name     = name;
  this.typeName = typeName;
}

function MessageHistory(messages, actors) {
  this.messages = messages; // per actor
  this.actors   = actors;
}

function Message(id, sender, receiver) {
  this.id       = id;
  this.sender   = sender;
  this.receiver = receiver;
}

function countNumberOfLines(str) {
  var cnt = 1;
  for (var i = 0; i < str.length; i++) {
    if (str[i] == "\n") {
      cnt += 1;
    }
  }
  return cnt;
}

function loadAndProcessFile(f) {
  var reader = new FileReader();
  reader.onload = (function(theFile) {

    function receivedFile(e) {
      var o = JSON.parse(e.target.result);
      data[theFile.name] = o;
      displaySources(o);
    }

    return receivedFile;
  })(f);

  reader.readAsText(f);
}

/**
 * @param {DragEvent} e
 */
function handleFileSelect(e) {
  e.stopPropagation();
  e.preventDefault();

  var files = e.dataTransfer.files; // FileList object.

  // files is a FileList of File objects. List some properties.
  var output = [];
  for (var i = 0; i < files.length; i++) {
    loadAndProcessFile(files[i]);
  }
}

var accessProfiles = [],
  maxAccessCount = -1;

function Breakpoint(source, line, lineNumSpan) {
  this.source      = source;
  this.line        = line;
  this.enabled     = false;
  this.lineNumSpan = lineNumSpan;
  this.checkbox    = null;
}

Breakpoint.prototype.toggle = function () {
  this.enabled = !this.enabled;
};

Breakpoint.prototype.isEnabled = function () {
  return this.enabled;
};

function handleDragOver(evt) {
  evt.stopPropagation();
  evt.preventDefault();
  evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
}

function dbgLog(msg) {
  var tzOffset = (new Date()).getTimezoneOffset() * 60000; // offset in milliseconds
  var localISOTime = (new Date(Date.now() - tzOffset)).toISOString().slice(0,-1);

  $("#debugger-log").html(localISOTime + ": " + msg + "
" + $("#debugger-log").html());
}

function Debugger() {
  this.suspended = false;
  this.lastSuspendEventId = null;
  this.sourceObjects = {};
  this.breakpoints = {};
}

Debugger.prototype.getSource = function (id) {
  for (var fileName in this.sourceObjects) {
    if (this.sourceObjects[fileName].id === id) {
      return this.sourceObjects[fileName];
    }
  }
  return null;
};

Debugger.prototype.addSources = function (msg) {
  for (var sId in msg.sources) {
    this.sourceObjects[msg.sources[sId].name] = msg.sources[sId];
  }
};

Debugger.prototype.getBreakpoint = function (source, line, clickedSpan) {
  if (!this.breakpoints[source]) {
    this.breakpoints[source] = {};
  }

  var bp = this.breakpoints[source][line];
  if (!bp) {
    bp = new Breakpoint(source, line, clickedSpan);
    this.breakpoints[source][line] = bp;
  }
  return bp;
};

Debugger.prototype.setSuspended = function(eventId) {
  console.assert(!this.suspended);
  this.suspended = true;
  this.lastSuspendEventId = eventId;
};

Debugger.prototype.setResumed = function () {
  console.assert(this.suspended);
  this.suspended = false;
};

/* globals View, Controller, VmConnection */
var ctrl;

function init() {
  var view = new View(),
    vmConnection = new VmConnection(),
    dbg = new Debugger();
  ctrl = new Controller(dbg, view, vmConnection);
  ctrl.toggleConnection();

  // Init drag and drop
  var fileDrop = document.getElementById('file-drop');
  fileDrop.addEventListener('dragover', handleDragOver,   false);
  fileDrop.addEventListener('drop',     handleFileSelect, false);
}

function blobToFile(blob, name) {
  blob.lastModifiedDate = new Date();
  blob.name = name;
  return blob;
}

function getFileObjectFromPath(pathOrUrl, callback) {
  var request = new XMLHttpRequest();
  request.open("GET", pathOrUrl);
  request.responseType = "blob";
  request.addEventListener('load', function () {
    callback(blobToFile(request.response, pathOrUrl));
  });
  request.send();
}

function loadStandardFile() {
  getFileObjectFromPath("highlight.json",
    function(file) {
      loadAndProcessFile(file);
    });
}
<|endoftext|>


<commit_before>export default function({ variants }) {
  return function({ addUtilities }) {
    addUtilities(
      {
        '.visible': { visibility: 'visible' },
        '.invisible': { visibility: 'hidden' },
      },
      variants
    )
  }
}
<commit_msg>Source visibility options from config<commit_after>export default function() {
  return function({ addUtilities, config }) {
    addUtilities(
      {
        '.visible': { visibility: 'visible' },
        '.invisible': { visibility: 'hidden' },
      },
      config('variants.visibility')
    )
  }
}
<|endoftext|>


<commit_before>const debug = process.env.DEBUG;

exports.config = {
    host: "127.0.0.1",
    port: 4444,
    specs: [ "./dist/e2e/**/*.spec.js" ],
    maxInstances: debug ? 1 : 5,
    capabilities: [ {
        maxInstances: debug ? 1 : 5,
        browserName: "chrome"
    } ],
    sync: true,
    logLevel: "silent",
    coloredLogs: true,
    bail: 0,
    screenshotPath: "dist/wdio/",
    baseUrl: debug ? "http://localhost:8080/" : "https://booleansliderwidge.mxapps.io/",
    waitforTimeout: 10000,
    connectionRetryTimeout: 90000,
    connectionRetryCount: 0,
    services: [ "selenium-standalone" ],

    framework: "jasmine",
    reporters: [ "spec" ],
    execArgv: debug ? [ "--inspect" ] : undefined,
    // Options to be passed to Jasmine.
    jasmineNodeOpts: {
        defaultTimeoutInterval: debug ? (60 * 60 * 1000) : (10 * 1000),
        expectationResultHandler: function(passed, assertion) {
            if (passed) {
                return;
            }
            browser.saveScreenshot(
                "dist/wdio/assertionError_" + assertion.error.message + ".png"
            );
        }
    }
};
<commit_msg>Increase timeout e2e test<commit_after>const debug = process.env.DEBUG;

exports.config = {
    host: "127.0.0.1",
    port: 4444,
    specs: [ "./dist/e2e/**/*.spec.js" ],
    maxInstances: debug ? 1 : 5,
    capabilities: [ {
        maxInstances: debug ? 1 : 5,
        browserName: "chrome"
    } ],
    sync: true,
    logLevel: "silent",
    coloredLogs: true,
    bail: 0,
    screenshotPath: "dist/wdio/",
    baseUrl: debug ? "http://localhost:8080/" : "https://booleansliderwidge.mxapps.io/",
    waitforTimeout: 10000,
    connectionRetryTimeout: 90000,
    connectionRetryCount: 0,
    services: [ "selenium-standalone" ],

    framework: "jasmine",
    reporters: [ "spec" ],
    execArgv: debug ? [ "--inspect" ] : undefined,
    // Options to be passed to Jasmine.
    jasmineNodeOpts: {
        defaultTimeoutInterval: debug ? (60 * 60 * 1000) : (30 * 1000),
        expectationResultHandler: function(passed, assertion) {
            if (passed) {
                return;
            }
            browser.saveScreenshot(
                "dist/wdio/assertionError_" + assertion.error.message + ".png"
            );
        }
    }
};
<|endoftext|>


<commit_before>"use strict";

module.exports = {
  "*.{js,jsx}": [
    "prettier --list-different",
    "eslint --report-unused-disable-directives",
    "git add"
  ],
  "*.{md,markdown,mdown,mkdn,mkd,mdwn,mkdown,ron}": [
    "prettier --list-different",
    "remark -f -q",
    "git add"
  ],
  "*.{yml,yaml}": ["prettier --list-different", "git add"]
};
<commit_msg>style(lint staged): update code style<commit_after>"use strict";

module.exports = {
  "*.{js,jsx}": [
    "prettier --list-different",
    "eslint --report-unused-disable-directives",
    "git add",
  ],
  "*.{md,markdown,mdown,mkdn,mkd,mdwn,mkdown,ron}": [
    "prettier --list-different",
    "remark -f -q",
    "git add",
  ],
  "*.{yml,yaml}": ["prettier --list-different", "git add"],
};
<|endoftext|>


<commit_before>var path = require('path');
var url = require('url');
var fs = require('fs');
var uuid = require('uuid');
var S = require('string');
var async = require('async');
var _ = require('lodash');
var pkg = require('./package.json');
var debug = require('debug')(pkg.name);
var http = require('http');
var soap = require('soap');

var util = require('any2api-util');

var preInvokeCode = process.env.PRE_INVOKE || '';
var preInvokeTplPath = path.join(__dirname, 'pre-invoke.js.tpl');
var preInvokeScrPath = path.join(__dirname, 'pre-invoke.js');
fs.writeFileSync(preInvokeScrPath, _.template(fs.readFileSync(preInvokeTplPath, 'utf8'))({ code: preInvokeCode }), 'utf8');
var preInvoke = require('./pre-invoke');

var port = process.env.PORT || 3000;
var baseAddress = process.env.BASE_ADDRESS || 'http://0.0.0.0:' + port;
var timeout = process.env.TIMEOUT || 5 * 60 * 1000; // 5mins

var rawWsdl = fs.readFileSync(path.resolve(__dirname, 'spec.wsdl'), 'utf8');
var wsdl = rawWsdl.replace(/{{baseAddress}}/g, baseAddress);

var apiSpec;

//TODO: use any2api-instancedb-redis

var invoke = function(input, executableName, invokerName, callback) {
  input = input || {};

  var instance = input.instance || {};
  instance.id = uuid.v4();
  instance.parameters = {};

  var executable = apiSpec.executables[executableName];
  var invoker = apiSpec.invokers[invokerName];

  var item = executable || invoker;

  //TODO: run util.persistEmbeddedExecutable _if_ invokerName && input.executable

  // Map parameters
  async.eachSeries(_.keys(input.parameters), function(wsdlName, callback) {
    var name = item.wsdlParamsMap[wsdlName];
    var value = input.parameters[wsdlName];
    var paramDef = item.parameters_schema[name];

    if (!paramDef) return callback();

    if (S(paramDef.type).toLowerCase().contains('json')) {
      try {
        instance.parameters[name] = JSON.parse(value);
      } catch (err) {
        err.soapText = 'Parameter value ' + name + ' is not valid JSON: ';
        err.soapText += err.message || err.toString();

        return callback(err);
      }
    } else {
      instance.parameters[name] = value;
    }

    callback();
  }, function(err) {
    if (err) return callback(err);

    preInvoke(instance, executable, invoker, function(err, instance) {
      if (err) return callback(err);

      debug('instance', instance);

      // Invoke executable
      util.invokeExecutable({ apiSpec: apiSpec,
                              instance: instance,
                              executable_name: executableName,
                              invoker_name: invokerName }, function(err, instance) {
        if (err) return callback(err);

        //TODO: we're affected by this bug: https://github.com/vpulim/node-soap/issues/613

        // Map results
        var output = { instance: instance, results: {} };

        _.each(instance.results, function(value, name) {
          var resultDef = item.results_schema[name];

          if (!resultDef) return;

          var wsdlName = item.results_schema[name].wsdl_name;

          if (S(resultDef.type).toLowerCase().contains('json')) {
            output.results[wsdlName] = JSON.stringify(value, null, 2);
          } else if (S(resultDef.type).toLowerCase().contains('binary') && Buffer.isBuffer(value)) {
            output.results[wsdlName] = value.toString('base64');
          } else {
            output.results[wsdlName] = value;
          }
        });

        delete instance.parameters;
        delete instance.results;

        callback(null, output);
      });
    });
  });
};

var toSoapError = function(err) {
  console.error(err);

  return {
    Fault: {
      Code: {
        Value: "soap:Sender"
        //, Subcode: { value: "soap:Error" }
      },
      Reason: { Text: err.soapText || err.message || err.toString() }
    }
  };
};

// Initialize server
var server = http.createServer(function(req, res) {
  var parsedUrl = url.parse(req.url);

  if (parsedUrl.pathname === '/') {
    res.setHeader('Content-Type', 'application/xml');

    var tailoredWsdl = wsdl;

    if (!process.env.BASE_ADDRESS) {
      tailoredWsdl = rawWsdl.replace(/{{baseAddress}}/g, 'http://' + req.headers.host);
    }

    res.write(tailoredWsdl);
  } else {
    res.write('404 Not Found: ' + req.url);
  }

  res.end();
});

server.setTimeout(timeout);
server.log = console.log;
server.on('error', function(err) {
  if (err) throw err;
});
//soap.listen(server, '/', port, wsdl);

// Read API spec
util.readInput({ specPath: path.join(__dirname, 'apispec.json') }, function(err, as) {
  if (err) throw err;

  apiSpec = as;

  // Initialize endpoints defined by WSDL ports
  _.each([ 'executables', 'invokers' ], function(collection) {
    _.each(apiSpec[collection], function(item, name) {
      var context = { executableName: null, invokerName: null };

      if (collection === 'executables') context.executableName = name;
      else if (collection === 'invokers') context.invokerName = name;

      item.wsdlParamsMap = {};

      _.each(item.parameters_schema, function(param, name) {
        item.wsdlParamsMap[param.wsdl_name] = name;
      });

      var port = {};
      port[item.wsdl_service_name] = {};
      port[item.wsdl_service_name][item.wsdl_port_name] = {
        invoke: _.bind(function(input, callback, headers) {
          debug('wsdl_name', item.wsdl_name);
          debug('input', input);
          debug('context', this);

          invoke(input, this.executableName, this.invokerName, function(err, output) {
            if (err) {
              err = toSoapError(err);

              throw err;
            }

            debug('output', output);

            callback(output);
          });
        }, context)
      };

      soap.listen(server, '/' + item.wsdl_url_path, port, wsdl);
    });
  });

  server.listen(port, function(err) {
    if (err) throw err;
  });
});

module.exports = server;
<commit_msg>comment added re existing bug of node-soap<commit_after>var path = require('path');
var url = require('url');
var fs = require('fs');
var uuid = require('uuid');
var S = require('string');
var async = require('async');
var _ = require('lodash');
var pkg = require('./package.json');
var debug = require('debug')(pkg.name);
var http = require('http');
var soap = require('soap');

var util = require('any2api-util');

var preInvokeCode = process.env.PRE_INVOKE || '';
var preInvokeTplPath = path.join(__dirname, 'pre-invoke.js.tpl');
var preInvokeScrPath = path.join(__dirname, 'pre-invoke.js');
fs.writeFileSync(preInvokeScrPath, _.template(fs.readFileSync(preInvokeTplPath, 'utf8'))({ code: preInvokeCode }), 'utf8');
var preInvoke = require('./pre-invoke');

var port = process.env.PORT || 3000;
var baseAddress = process.env.BASE_ADDRESS || 'http://0.0.0.0:' + port;
var timeout = process.env.TIMEOUT || 5 * 60 * 1000; // 5mins

var rawWsdl = fs.readFileSync(path.resolve(__dirname, 'spec.wsdl'), 'utf8');
var wsdl = rawWsdl.replace(/{{baseAddress}}/g, baseAddress);

var apiSpec;

//TODO: use any2api-instancedb-redis

var invoke = function(input, executableName, invokerName, callback) {
  input = input || {};

  var instance = input.instance || {};
  instance.id = uuid.v4();
  instance.parameters = {};

  var executable = apiSpec.executables[executableName];
  var invoker = apiSpec.invokers[invokerName];

  var item = executable || invoker;

  //TODO: run util.persistEmbeddedExecutable _if_ invokerName && input.executable

  // Map parameters
  async.eachSeries(_.keys(input.parameters), function(wsdlName, callback) {
    var name = item.wsdlParamsMap[wsdlName];
    var value = input.parameters[wsdlName];
    var paramDef = item.parameters_schema[name];

    if (!paramDef) return callback();

    if (S(paramDef.type).toLowerCase().contains('json')) {
      try {
        instance.parameters[name] = JSON.parse(value);
      } catch (err) {
        err.soapText = 'Parameter value ' + name + ' is not valid JSON: ';
        err.soapText += err.message || err.toString();

        return callback(err);
      }
    } else {
      instance.parameters[name] = value;
    }

    callback();
  }, function(err) {
    if (err) return callback(err);

    preInvoke(instance, executable, invoker, function(err, instance) {
      if (err) return callback(err);

      debug('instance', instance);

      // Invoke executable
      util.invokeExecutable({ apiSpec: apiSpec,
                              instance: instance,
                              executable_name: executableName,
                              invoker_name: invokerName }, function(err, instance) {
        if (err) return callback(err);

        //TODO: we're affected by this bug: https://github.com/vpulim/node-soap/issues/613
        //      errors that occur here are not sent back to the client as SOAP faults

        // Map results
        var output = { instance: instance, results: {} };

        _.each(instance.results, function(value, name) {
          var resultDef = item.results_schema[name];

          if (!resultDef) return;

          var wsdlName = item.results_schema[name].wsdl_name;

          if (S(resultDef.type).toLowerCase().contains('json')) {
            output.results[wsdlName] = JSON.stringify(value, null, 2);
          } else if (S(resultDef.type).toLowerCase().contains('binary') && Buffer.isBuffer(value)) {
            output.results[wsdlName] = value.toString('base64');
          } else {
            output.results[wsdlName] = value;
          }
        });

        delete instance.parameters;
        delete instance.results;

        callback(null, output);
      });
    });
  });
};

var toSoapError = function(err) {
  console.error(err);

  return {
    Fault: {
      Code: {
        Value: "soap:Sender"
        //, Subcode: { value: "soap:Error" }
      },
      Reason: { Text: err.soapText || err.message || err.toString() }
    }
  };
};

// Initialize server
var server = http.createServer(function(req, res) {
  var parsedUrl = url.parse(req.url);

  if (parsedUrl.pathname === '/') {
    res.setHeader('Content-Type', 'application/xml');

    var tailoredWsdl = wsdl;

    if (!process.env.BASE_ADDRESS) {
      tailoredWsdl = rawWsdl.replace(/{{baseAddress}}/g, 'http://' + req.headers.host);
    }

    res.write(tailoredWsdl);
  } else {
    res.write('404 Not Found: ' + req.url);
  }

  res.end();
});

server.setTimeout(timeout);
server.log = console.log;
server.on('error', function(err) {
  if (err) throw err;
});
//soap.listen(server, '/', port, wsdl);

// Read API spec
util.readInput({ specPath: path.join(__dirname, 'apispec.json') }, function(err, as) {
  if (err) throw err;

  apiSpec = as;

  // Initialize endpoints defined by WSDL ports
  _.each([ 'executables', 'invokers' ], function(collection) {
    _.each(apiSpec[collection], function(item, name) {
      var context = { executableName: null, invokerName: null };

      if (collection === 'executables') context.executableName = name;
      else if (collection === 'invokers') context.invokerName = name;

      item.wsdlParamsMap = {};

      _.each(item.parameters_schema, function(param, name) {
        item.wsdlParamsMap[param.wsdl_name] = name;
      });

      var port = {};
      port[item.wsdl_service_name] = {};
      port[item.wsdl_service_name][item.wsdl_port_name] = {
        invoke: _.bind(function(input, callback, headers) {
          debug('wsdl_name', item.wsdl_name);
          debug('input', input);
          debug('context', this);

          invoke(input, this.executableName, this.invokerName, function(err, output) {
            if (err) {
              err = toSoapError(err);

              throw err;
            }

            debug('output', output);

            callback(output);
          });
        }, context)
      };

      soap.listen(server, '/' + item.wsdl_url_path, port, wsdl);
    });
  });

  server.listen(port, function(err) {
    if (err) throw err;
  });
});

module.exports = server;
<|endoftext|>


<commit_before>import F from '../funcifyr.js';
import { expect, assert } from 'chai';

describe('and', () => {

  it('should return true if both predicate functions evaluate to true', () => {

    const isString = (s) => typeof s === 'string';
    const isLongerThanSix = (n) => n.length > 6;
    const isStringAndLongerThanSix = F.and(isString, isLongerThanSix)('Hello world!');

    expect( isStringAndLongerThanSix ).to.be.true;

  });

});

describe('arrayify', () => {

  it('should turn an array-like collection into a real array', () => {

    // Can't test a DOM collection so we'll run test on arguments object
    const returnArgs = () => arguments;
    const argumentsObjectToArray = F.arrayify(returnArgs('string', 3));
    const testIfArray = Array.isArray(argumentsObjectToArray);

    expect( testIfArray ).to.be.true;

  });

});

describe('chunkBy', () => {

  it('should return a function', () => {

    const actual = typeof F.chunkBy(3);
    const expected = 'function';

    assert.equal(actual, expected);

  });

  it('should slice an array of values into chunks of 2', () => {

    const chunkBy2 = F.chunkBy(2);

    const actual = JSON.stringify( chunkBy2([1,2,3,4,5,6,7,8]) );
    const expected = "[[1,2],[3,4],[5,6],[7,8]]";

    assert.equal(actual, expected);

  });

  it('should slice a string into chunks of 3 characters each', () => {

    const chunkBy3 = F.chunkBy(3);

    const actual = JSON.stringify( chunkBy3('Hello world') );
    const expected = '["Hel","lo ","wor","ld"]';

    assert.equal(actual, expected);

  });

  it('should throw an error if value passed is not a string or an array', () => {

    const chunkBy3 = F.chunkBy(3);

    expect( () => chunkBy3(undefined) ).to.throw(TypeError);

  });

});

describe('compose', () => {

  it('should return a function', () => {

    const actual = typeof F.compose();
    const expected = 'function';

    assert.equal(actual, expected);

  });

});

describe('curry', () => {

  const add = (a, b) => a + b;

  it('should return a function that returns a function', () => {

    const curriedFunction = F.curry(add);

    expect( curriedFunction ).to.be.a('function');

  });

  it('should return the correct result of a curried function', () => {

    const curriedAdd = F.curry(add);
    const add5 = curriedAdd(5);

    const actual = add5(6);
    const expected = 11;

    assert.equal(actual, expected);

  });

});

describe('fill', () => {

  let obj = { name: null, email: null, address: null, friends: [] };
  let userDataTemplate = F.fill(obj, 10);

  it('Should return an array', () => {

    expect( Array.isArray(userDataTemplate) ).to.be.true;

  });

  it('Should return an array with a length of 10', () => {

    const actual = userDataTemplate.length;
    const expected = 10;

    assert.equal(actual, expected);

  });

});

describe('flatten', () => {

  let arr = [1, 2, ['3'], true, [[false, 'a'], 'b'], 'c'];
  let flattenedArray = F.flatten(arr);

  it('Should return an array', () => {

    expect( Array.isArray(flattenedArray) ).to.be.true;

  });

  it('Should return a flattened array that contains no nested arrays', () => {

    const containsNoNestedArrays = flattenedArray.every(v => !Array.isArray(v));

    expect( containsNoNestedArrays ).to.be.true;

  });

});

describe('groupBy', () => {

  let data = [
    { name: 'Osiris', location: 'New York' },
    { name: 'Ishtar', location: 'New York' },
    { name: 'Zeus', location: 'California' },
    { name: 'Venus', location: 'New York' },
    { name: 'Maat', location: 'California' },
  ];
  const groupByLocation = F.groupBy('location');
  const dataByLocation = groupByLocation(data);

  it('Should return an object...', () => {

    const actual = typeof dataByLocation;
    const expected = 'object';

    assert.equal(actual, expected);

  });

  it('...and object should have a length of 2...', () => {

    const actual = Object.keys(dataByLocation).length;
    const expected = 2;

    assert.equal(actual, expected);

  });

  it('...and length of property value array of "New York" key should be 3', () => {

    const actual = dataByLocation['New York'].length;
    const expected = 3;

    assert.equal(actual, expected);

  });

});

describe('is', () => {

  it('Should create a function that correctly evaluates value as type boolean', () => {

    const isBoolean = F.is('boolean');

    expect( isBoolean(false) ).to.be.true;

  });

  it('Should create a function that correctly evaluates value as type string', () => {

    const isString = F.is('string');

    expect( isString('This is a string.') ).to.be.true;

  });

  it('Should create a function that correctly evaluates value as type number', () => {

    const isNumber = F.is('number');

    expect( isNumber(89) ).to.be.true;

  });

});

describe('negate', () => {

  it('Should return a predicate function that is the opposite of original function', () => {

    const isTrue = () => true;
    const isFalse = F.negate(isTrue);

    expect( isFalse() === !isTrue() ).to.be.true;

  });

});

describe('shuffle', () => {

  it('Should pass randomness test', () => {

    const oneTo100 = Array.from({length: 100}, (_,i) => i + 1);
    let results = [];

    for (let i = 0; i < 100; i++) {
      const shuffled = F.shuffle( oneTo100.slice() );
      results.push( JSON.stringify(shuffled) );
    }

    const uniqueResultsCount = new Set(results).size;

    expect( uniqueResultsCount > 90 ).to.be.true;

  });

});

describe('tally', () => {

  let data = [
    { name: 'Dave', position: 'Front-End Developer' },
    { name: 'Jen', position: 'Front-End Developer' },
    { name: 'Kim', position: 'Front-End Developer' },
    { name: 'Jon', position: 'Back-End Developer' },
    { name: 'Sue', position: 'Dev Ops' }
  ];
  const tallyByPosition = F.tally('position');
  let positionTally = tallyByPosition(data)

  it('Should return an object as result', () => {

    expect( positionTally ).to.be.an('object');

  });

  it('Should return a value of 3 for the key "Front-End Developer"', () => {

    const actual = positionTally['Front-End Developer'];
    const expected = 3;

    assert.equal(actual, expected);

  });

});
<commit_msg>Add tests for range<commit_after>import F from '../funcifyr.js';
import { expect, assert } from 'chai';

describe('and', () => {

  it('should return true if both predicate functions evaluate to true', () => {

    const isString = (s) => typeof s === 'string';
    const isLongerThanSix = (n) => n.length > 6;
    const isStringAndLongerThanSix = F.and(isString, isLongerThanSix)('Hello world!');

    expect( isStringAndLongerThanSix ).to.be.true;

  });

});

describe('arrayify', () => {

  it('should turn an array-like collection into a real array', () => {

    // Can't test a DOM collection so we'll run test on arguments object
    const returnArgs = () => arguments;
    const argumentsObjectToArray = F.arrayify(returnArgs('string', 3));
    const testIfArray = Array.isArray(argumentsObjectToArray);

    expect( testIfArray ).to.be.true;

  });

});

describe('chunkBy', () => {

  it('should return a function', () => {

    const actual = typeof F.chunkBy(3);
    const expected = 'function';

    assert.equal(actual, expected);

  });

  it('should slice an array of values into chunks of 2', () => {

    const chunkBy2 = F.chunkBy(2);

    const actual = JSON.stringify( chunkBy2([1,2,3,4,5,6,7,8]) );
    const expected = "[[1,2],[3,4],[5,6],[7,8]]";

    assert.equal(actual, expected);

  });

  it('should slice a string into chunks of 3 characters each', () => {

    const chunkBy3 = F.chunkBy(3);

    const actual = JSON.stringify( chunkBy3('Hello world') );
    const expected = '["Hel","lo ","wor","ld"]';

    assert.equal(actual, expected);

  });

  it('should throw an error if value passed is not a string or an array', () => {

    const chunkBy3 = F.chunkBy(3);

    expect( () => chunkBy3(undefined) ).to.throw(TypeError);

  });

});

describe('compose', () => {

  it('should return a function', () => {

    const actual = typeof F.compose();
    const expected = 'function';

    assert.equal(actual, expected);

  });

});

describe('curry', () => {

  const add = (a, b) => a + b;

  it('should return a function that returns a function', () => {

    const curriedFunction = F.curry(add);

    expect( curriedFunction ).to.be.a('function');

  });

  it('should return the correct result of a curried function', () => {

    const curriedAdd = F.curry(add);
    const add5 = curriedAdd(5);

    const actual = add5(6);
    const expected = 11;

    assert.equal(actual, expected);

  });

});

describe('fill', () => {

  const row = F.fill(0, 5);
  const matrix = F.fill(row, 5);

  it('Should return an array', () => {

    expect( Array.isArray(matrix) ).to.be.true;

  });

  it('Should return an array with a length of 5', () => {
    const actual = matrix.length;
    const expected = 5;

    assert.equal(actual, expected);

  });

});

describe('flatten', () => {

  const arr = [1, 2, ['3'], true, [[false, 'a'], 'b'], 'c'];
  const flattenedArray = F.flatten(arr);

  it('Should return an array', () => {

    expect( Array.isArray(flattenedArray) ).to.be.true;

  });

  it('Should return a flattened array that contains no nested arrays', () => {

    const containsNoNestedArrays = flattenedArray.every(v => !Array.isArray(v));

    expect( containsNoNestedArrays ).to.be.true;

  });

});

describe('groupBy', () => {

  const data = [
    { name: 'Osiris', location: 'New York' },
    { name: 'Ishtar', location: 'New York' },
    { name: 'Zeus', location: 'California' },
    { name: 'Venus', location: 'New York' },
    { name: 'Maat', location: 'California' },
  ];
  const groupByLocation = F.groupBy('location');
  const dataByLocation = groupByLocation(data);

  it('Should return an object...', () => {

    const actual = typeof dataByLocation;
    const expected = 'object';

    assert.equal(actual, expected);

  });

  it('...and object should have a length of 2...', () => {

    const actual = Object.keys(dataByLocation).length;
    const expected = 2;

    assert.equal(actual, expected);

  });

  it('...and length of property value array of "New York" key should be 3', () => {

    const actual = dataByLocation['New York'].length;
    const expected = 3;

    assert.equal(actual, expected);

  });

});

describe('is', () => {

  it('Should create a function that correctly evaluates value as type boolean', () => {

    const isBoolean = F.is('boolean');

    expect( isBoolean(false) ).to.be.true;

  });

  it('Should create a function that correctly evaluates value as type string', () => {

    const isString = F.is('string');

    expect( isString('This is a string.') ).to.be.true;

  });

  it('Should create a function that correctly evaluates value as type number', () => {

    const isNumber = F.is('number');

    expect( isNumber(89) ).to.be.true;

  });

});

describe('negate', () => {

  it('Should return a predicate function that is the opposite of original function', () => {

    const isTrue = () => true;
    const isFalse = F.negate(isTrue);

    expect( isFalse() === !isTrue() ).to.be.true;

  });

});

describe('range', () => {

  it('Should return a range of numbers from 1 to 10 if passed just one argument (10)', () => {

    const actual = JSON.stringify( F.range(10) );
    const expected = "[1,2,3,4,5,6,7,8,9,10]";

    assert.equal(actual, expected);

  });

  it('Should return a range of numbers from 90 to 95 if passed two arguments (90, 95)', () => {

    const actual = JSON.stringify( F.range(90, 95) );
    const expected = "[90,91,92,93,94,95]";

    assert.equal(actual, expected);

  });

  it('Should return a range of numbers from 0 to 20 in steps of 5 if passed three arguments (0, 20, 5)', () => {

    const actual = JSON.stringify( F.range(0, 20, 5) );
    const expected = "[0,5,10,15,20]";

    assert.equal(actual, expected);

  });

});

describe('shuffle', () => {

  it('Should pass randomness test', () => {

    const oneTo100 = Array.from({length: 100}, (_,i) => i + 1);
    const results = [];

    for (let i = 0; i < 100; i++) {
      const shuffled = F.shuffle( oneTo100.slice() );
      results.push( JSON.stringify(shuffled) );
    }

    const uniqueResultsCount = new Set(results).size;

    expect( uniqueResultsCount > 90 ).to.be.true;

  });

});

describe('tally', () => {

  const data = [
    { name: 'Dave', position: 'Front-End Developer' },
    { name: 'Jen', position: 'Front-End Developer' },
    { name: 'Kim', position: 'Front-End Developer' },
    { name: 'Jon', position: 'Back-End Developer' },
    { name: 'Sue', position: 'Dev Ops' }
  ];
  const tallyByPosition = F.tally('position');
  const positionTally = tallyByPosition(data)

  it('Should return an object as result', () => {

    expect( positionTally ).to.be.an('object');

  });

  it('Should return a value of 3 for the key "Front-End Developer"', () => {

    const actual = positionTally['Front-End Developer'];
    const expected = 3;

    assert.equal(actual, expected);

  });

});
<|endoftext|>


<commit_before>var http = require("http");
var fs = require('fs');

function writeAwsConfigFile(rootPath, json) {

	if (!fs.existsSync(rootPath + '/.aws')) {
	    fs.mkdirSync(rootPath + '/.aws');
	}

	var fd = fs.openSync(rootPath + '/.aws/config', 'w+');
	fs.writeSync(fd, '[default]\n');
	fs.writeSync(fd, 'aws_access_key_id=');
	fs.writeSync(fd, json.AccessKeyId + '\n');
	fs.writeSync(fd, 'aws_secret_access_key=');
	fs.writeSync(fd, json.SecretAccessKey + '\n');
	fs.writeSync(fd, 'region=eu-central-1\n');
	fs.closeSync(fd);

}

function getIamRole(callback) {
	http.get('http://169.254.169.254/latest/meta-data/iam/info', function (res) {
		var data = '';
		res.on('data', function (chunk) {
		    data += chunk.toString();
		});
		res.on("end", function () {
		    var json = JSON.parse(data);
			callback(json.InstanceProfileArn.substr(json.InstanceProfileArn.lastIndexOf('/') + 1));
		});
	});
}

function getCredentials(iamRole, callback) {
	http.get('http://169.254.169.254/latest/meta-data/iam/security-credentials/' + iamRole, function(res) {
		var data = '';
		res.on('data', function (chunk) {
		    data += chunk.toString();
		});
		res.on("end", function () {
		    var json = JSON.parse(data);
			callback(json);
		});
	});
}

getIamRole(function(role) {
	getCredentials(role, function(json) {
		writeAwsConfigFile('/home/ubuntu', json);
		writeAwsConfigFile('/root', json);
	})
});<commit_msg>Added missing session token to config file<commit_after>var http = require("http");
var fs = require('fs');

function writeAwsConfigFile(rootPath, json) {

	if (!fs.existsSync(rootPath + '/.aws')) {
	    fs.mkdirSync(rootPath + '/.aws');
	}

	var fd = fs.openSync(rootPath + '/.aws/config', 'w+');
	fs.writeSync(fd, '[default]\n');
	fs.writeSync(fd, 'region=eu-central-1\n');
	fs.writeSync(fd, 'aws_access_key_id=');
	fs.writeSync(fd, json.AccessKeyId + '\n');
	fs.writeSync(fd, 'aws_secret_access_key=');
	fs.writeSync(fd, json.SecretAccessKey + '\n');
	fs.writeSync(fd, 'aws_session_token=');
	fs.writeSync(fd, json.Token + '\n');
	fs.closeSync(fd);

}

function getIamRole(callback) {
	http.get('http://169.254.169.254/latest/meta-data/iam/info', function (res) {
		var data = '';
		res.on('data', function (chunk) {
		    data += chunk.toString();
		});
		res.on("end", function () {
		    var json = JSON.parse(data);
			callback(json.InstanceProfileArn.substr(json.InstanceProfileArn.lastIndexOf('/') + 1));
		});
	});
}

function getCredentials(iamRole, callback) {
	http.get('http://169.254.169.254/latest/meta-data/iam/security-credentials/' + iamRole, function(res) {
		var data = '';
		res.on('data', function (chunk) {
		    data += chunk.toString();
		});
		res.on("end", function () {
		    var json = JSON.parse(data);
			callback(json);
		});
	});
}

getIamRole(function(role) {
	getCredentials(role, function(json) {
		writeAwsConfigFile(process.argv[2], json);
	})
});<|endoftext|>


<commit_before>//  Copyright (C) 2013  The IPython Development Team
//
//  Distributed under the terms of the BSD License.  The full license is in
//  the file COPYING, distributed as part of this software.
//----------------------------------------------------------------------------

// assign dedent to shift-tab

var shift_tab_extension = (function() {

    var dedentKey = { "Shift-Tab":"indentLess" };
    var key   = IPython.utils.keycodes;

    /**
     * Concatenate associative array objects
     *
     * Source: http://stackoverflow.com/questions/2454295/javascript-concatenate-properties-from-multiple-objects-associative-array
     */
    function collect() {
    var ret = {};
    var len = arguments.length;
    for (var i=0; i<len; i++) {
        for (p in arguments[i]) {
            if (arguments[i].hasOwnProperty(p)) {
                ret[p] = arguments[i][p];
            }
        }
    }
    return ret;
}

    /**
     * Intercept codemirror onKeyEvent in codecell
     *
     * @return {Boolean} returns false if hotkey is found, otherwise call original function
     */
    var intercept_codemirror_keyevent = function (cm, event) {

        /* Dummy for shift+Tab, who knows why */
        if (event.type == 'keydown' && event.which == key.TAB && event.shiftKey) {
            return false;
        };
        return this.handle_codemirror_keyevent(cm,event);
    }

    function assign_key(cell) {
        var keys = cell.code_mirror.getOption('extraKeys');
        cell.code_mirror.setOption('onKeyEvent',$.proxy(intercept_codemirror_keyevent,cell));
        cell.code_mirror.setOption('extraKeys', collect(keys, dedentKey ));
    }

    /**
     * Initialize newly created cell
     *
     * @param {Object} event
     * @param {Object} nbcell notebook cell
     */
    create_cell = function (event,nbcell,nbindex) {
        var cell = nbcell.cell;
        if ((cell instanceof IPython.CodeCell)) { assign_key(cell); }
    };

    /**
     * Initialize all cells
     *
     */
    var cells = IPython.notebook.get_cells();
    for(var i in cells){
        var cell = cells[i];
        if ((cell instanceof IPython.CodeCell)) { assign_key(cell); }
    };

    $([IPython.events]).on('create.Cell',create_cell);
})();
<commit_msg>Update keycodes<commit_after>//  Copyright (C) 2013  The IPython Development Team
//
//  Distributed under the terms of the BSD License.  The full license is in
//  the file COPYING, distributed as part of this software.
//----------------------------------------------------------------------------

// assign dedent to shift-tab

var shift_tab_extension = (function() {

    var dedentKey = { "Shift-Tab":"indentLess" };
    var key   = IPython.keyboard.keycodes;

    /**
     * Concatenate associative array objects
     *
     * Source: http://stackoverflow.com/questions/2454295/javascript-concatenate-properties-from-multiple-objects-associative-array
     */
    function collect() {
    var ret = {};
    var len = arguments.length;
    for (var i=0; i<len; i++) {
        for (p in arguments[i]) {
            if (arguments[i].hasOwnProperty(p)) {
                ret[p] = arguments[i][p];
            }
        }
    }
    return ret;
}

    /**
     * Intercept codemirror onKeyEvent in codecell
     *
     * @return {Boolean} returns false if hotkey is found, otherwise call original function
     */
    var intercept_codemirror_keyevent = function (cm, event) {
        /* Dummy for shift+Tab, who knows why */
        if (event.type == 'keydown' && event.which == key.tab && event.shiftKey) {
            return false;
        };
        return this.handle_codemirror_keyevent(cm,event);
    }

    function assign_key(cell) {
        var keys = cell.code_mirror.getOption('extraKeys');
        cell.code_mirror.setOption('onKeyEvent',$.proxy(intercept_codemirror_keyevent,cell));
        cell.code_mirror.setOption('extraKeys', collect(keys, dedentKey ));
    }

    /**
     * Initialize newly created cell
     *
     * @param {Object} event
     * @param {Object} nbcell notebook cell
     */
    create_cell = function (event,nbcell,nbindex) {
        var cell = nbcell.cell;
        if ((cell instanceof IPython.CodeCell)) { assign_key(cell); }
    };

    /**
     * Initialize all cells
     *
     */
    var cells = IPython.notebook.get_cells();
    for(var i in cells){
        var cell = cells[i];
        if ((cell instanceof IPython.CodeCell)) { assign_key(cell); }
    };

    $([IPython.events]).on('create.Cell',create_cell);
})();
<|endoftext|>


<commit_before>/*globals fdom:true, Blob, ArrayBuffer, Promise */
/*jslint indent:2, white:true, node:true, sloppy:true, browser:true */
if (typeof fdom === 'undefined') {
  fdom = {};
}
fdom.proxy = fdom.proxy || {};

fdom.proxy.ApiInterface = function(def, onMsg, emit) {
  var inflight = {},
      events = null,
      emitter = null,
      reqId = 0;

  fdom.util.eachProp(def, function(prop, name) {
    switch(prop.type) {
    case 'method':
      this[name] = function() {
        // Note: inflight should be registered before message is passed
        // in order to prepare for synchronous in-window pipes.
        var thisReq = reqId,
            promise = new Promise(function(resolve, reject) {
              inflight[thisReq] = [resolve, reject];
            });
        reqId += 1;
        emit({
          action: 'method',
          type: name,
          reqId: thisReq,
          value: fdom.proxy.conform(prop.value, arguments)
        });
        return promise;
      };
      break;
    case 'event':
      if(!events) {
        fdom.util.handleEvents(this);
        emitter = this.emit;
        delete this.emit;
        events = {};
      }
      events[name] = prop;
      break;
    case 'constant':
      Object.defineProperty(this, name, {
        value: fdom.proxy.recursiveFreezeObject(prop.value),
        writable: false
      });
      break;
    }
  }.bind(this));

  onMsg(this, function(type, msg) {
    if (type === 'close') {
      this.off();
      delete this.inflight;
      return;
    }
    if (!msg) {
      return;
    }
    if (msg.type === 'method') {
      if (inflight[msg.reqId]) {
        var resolve = inflight[msg.reqId];
        delete inflight[msg.reqId];
        if (msg.error) {
          resolve[1](msg.error);
        } else {
          resolve[0](msg.value);
        }
      } else {
        fdom.debug.warn('Dropped response message with id ' + msg.reqId);
      }
    } else if (msg.type === 'event') {
      if (events[msg.name]) {
        emitter(msg.name, fdom.proxy.conform(events[msg.name].value, msg.value));
      }
    }
  }.bind(this));

  emit({
    'type': 'construct'
  });
};

/**
 * Force a collection of values to look like the types and length of an API template.
 */
fdom.proxy.conform = function(template, value) {
  /* jshint -W086 */
  if (typeof(value) === 'function') {
    value = undefined;
  }
  switch(template) {
  case 'string':
    return String('') + value;
  case 'number':
    return Number(1) * value;
  case 'bool':
    return Boolean(value === true);
  case 'object':
    // TODO(willscott): Allow removal if sandboxing enforces this.
    return JSON.parse(JSON.stringify(value));
  case 'blob':
    if (value instanceof Blob) {
      return value;
    } else {
      fdom.debug.warn('conform expecting Blob, sees ' + (typeof value));
      return new Blob([]);
    }
  case 'buffer':
    if (value instanceof ArrayBuffer) {
      return value;
    } else {
      fdom.debug.warn('conform expecting ArrayBuffer, sees ' + (typeof value));
      //TODO(ryscheng): bug in Chrome where passing Array Buffers over iframes loses this
      return new ArrayBuffer(0);
    }
  case 'data':
    // TODO(willscott): should be opaque to non-creator.
    return value;
  case 'proxy':
    if (Array.isArray(value)) {
      return value;
    } else {
      // TODO: make proxy.
      return value;
    }
  }
  var val, i;
  if (Array.isArray(template)) {
    val = [];
    i = 0;
    if (template.length === 2 && template[0] === 'array') {
      //console.log("template is array, value is " + JSON.stringify(value));
      for (i = 0; i < value.length; i += 1) {
        val.push(fdom.proxy.conform(template[1], value[i]));
      }
    } else {
      for (i = 0; i < template.length; i += 1) {
        if (value[i] === null || value[i]) {
          val.push(fdom.proxy.conform(template[i], value[i]));
        } else {
          val.push(undefined);
        }
      }
    }
    return val;
  } else if (typeof template === 'object') {
    val = {};
    fdom.util.eachProp(template, function(prop, name) {
      if (value[name]) {
        val[name] = fdom.proxy.conform(prop, value[name]);
      }
    });
    return val;
  }
  fdom.debug.log('Conform ignoring value for template:' + template);
  fdom.debug.log(value);
};

/**
 * Recursively traverse a [nested] object and freeze its keys from being writable.
 * Note, the result can have new keys added to it, but existing ones cannot be overwritten.
 * Doesn't do anything for arrays or other collections.
 *
 * @method recursiveFreezeObject
 * @static
 * @param {Object} obj - object to be frozen
 * @return {Object} obj
 **/
fdom.proxy.recursiveFreezeObject = function(obj) {
  var k, ret = {};
  if (typeof obj !== 'object') {
    return obj;
  }
  for (k in obj) {
    if (obj.hasOwnProperty(k)) {
      Object.defineProperty(ret, k, {
        value: fdom.proxy.recursiveFreezeObject(obj[k]),
        writable: false
      });
    }
  }
  return ret;
};
<commit_msg>Reasonable fix for #28<commit_after>/*globals fdom:true, Blob, ArrayBuffer, Promise */
/*jslint indent:2, white:true, node:true, sloppy:true, browser:true */
if (typeof fdom === 'undefined') {
  fdom = {};
}
fdom.proxy = fdom.proxy || {};

fdom.proxy.ApiInterface = function(def, onMsg, emit) {
  var inflight = {},
      events = null,
      emitter = null,
      reqId = 0;

  fdom.util.eachProp(def, function(prop, name) {
    switch(prop.type) {
    case 'method':
      this[name] = function() {
        // Note: inflight should be registered before message is passed
        // in order to prepare for synchronous in-window pipes.
        var thisReq = reqId,
            promise = new Promise(function(resolve, reject) {
              inflight[thisReq] = [resolve, reject];
            });
        reqId += 1;
        emit({
          action: 'method',
          type: name,
          reqId: thisReq,
          value: fdom.proxy.conform(prop.value, arguments)
        });
        return promise;
      };
      break;
    case 'event':
      if(!events) {
        fdom.util.handleEvents(this);
        emitter = this.emit;
        delete this.emit;
        events = {};
      }
      events[name] = prop;
      break;
    case 'constant':
      Object.defineProperty(this, name, {
        value: fdom.proxy.recursiveFreezeObject(prop.value),
        writable: false
      });
      break;
    }
  }.bind(this));

  onMsg(this, function(type, msg) {
    if (type === 'close') {
      this.off();
      delete this.inflight;
      return;
    }
    if (!msg) {
      return;
    }
    if (msg.type === 'method') {
      if (inflight[msg.reqId]) {
        var resolve = inflight[msg.reqId];
        delete inflight[msg.reqId];
        if (msg.error) {
          resolve[1](msg.error);
        } else {
          resolve[0](msg.value);
        }
      } else {
        fdom.debug.warn('Dropped response message with id ' + msg.reqId);
      }
    } else if (msg.type === 'event') {
      if (events[msg.name]) {
        emitter(msg.name, fdom.proxy.conform(events[msg.name].value, msg.value));
      }
    }
  }.bind(this));

  emit({
    'type': 'construct'
  });
};

/**
 * Force a collection of values to look like the types and length of an API template.
 */
fdom.proxy.conform = function(template, value) {
  /* jshint -W086 */
  if (typeof(value) === 'function') {
    value = undefined;
  }
  switch(template) {
  case 'string':
    return String('') + value;
  case 'number':
    return Number(1) * value;
  case 'bool':
    return Boolean(value === true);
  case 'object':
    // TODO(willscott): Allow removal if sandboxing enforces this.
    return JSON.parse(JSON.stringify(value));
  case 'blob':
    if (value instanceof Blob) {
      return value;
    } else {
      fdom.debug.warn('conform expecting Blob, sees ' + (typeof value));
      return new Blob([]);
    }
  case 'buffer':
    if (value instanceof ArrayBuffer) {
      return value;
    } else if (value.constructor.name === "ArrayBuffer" &&
        typeof value.prototype === "undefined") {
      // Workaround for webkit origin ownership issue.
      // https://github.com/UWNetworksLab/freedom/issues/28
      return new DataView(value).buffer;
    } else {
      fdom.debug.warn('conform expecting ArrayBuffer, sees ' + (typeof value));
      return new ArrayBuffer(0);
    }
  case 'data':
    // TODO(willscott): should be opaque to non-creator.
    return value;
  case 'proxy':
    if (Array.isArray(value)) {
      return value;
    } else {
      // TODO: make proxy.
      return value;
    }
  }
  var val, i;
  if (Array.isArray(template)) {
    val = [];
    i = 0;
    if (template.length === 2 && template[0] === 'array') {
      //console.log("template is array, value is " + JSON.stringify(value));
      for (i = 0; i < value.length; i += 1) {
        val.push(fdom.proxy.conform(template[1], value[i]));
      }
    } else {
      for (i = 0; i < template.length; i += 1) {
        if (value[i] === null || value[i]) {
          val.push(fdom.proxy.conform(template[i], value[i]));
        } else {
          val.push(undefined);
        }
      }
    }
    return val;
  } else if (typeof template === 'object') {
    val = {};
    fdom.util.eachProp(template, function(prop, name) {
      if (value[name]) {
        val[name] = fdom.proxy.conform(prop, value[name]);
      }
    });
    return val;
  }
  fdom.debug.log('Conform ignoring value for template:' + template);
  fdom.debug.log(value);
};

/**
 * Recursively traverse a [nested] object and freeze its keys from being writable.
 * Note, the result can have new keys added to it, but existing ones cannot be overwritten.
 * Doesn't do anything for arrays or other collections.
 *
 * @method recursiveFreezeObject
 * @static
 * @param {Object} obj - object to be frozen
 * @return {Object} obj
 **/
fdom.proxy.recursiveFreezeObject = function(obj) {
  var k, ret = {};
  if (typeof obj !== 'object') {
    return obj;
  }
  for (k in obj) {
    if (obj.hasOwnProperty(k)) {
      Object.defineProperty(ret, k, {
        value: fdom.proxy.recursiveFreezeObject(obj[k]),
        writable: false
      });
    }
  }
  return ret;
};
<|endoftext|>


<commit_before>var m = require('mithril');
var chessground = require('chessground');
var partial = chessground.util.partial;
var classSet = chessground.util.classSet;
var renderConfig = require('./explorerConfig').view;

function resultBar(move) {
  var sum = move.white + move.draws + move.black;
  var section = function(key) {
    return move[key] === 0 ? null : m('span', {
      class: key,
      style: {
        width: (Math.round(move[key] * 1000 / sum) / 10) + '%'
      },
    }, Math.round(move[key] * 100 / sum) + '%');
  }
  return m('div.bar', ['white', 'draws', 'black'].map(section));
}

var lastShow = null;

function show(ctrl) {
  var data = ctrl.explorer.current();
  if (data) {
    lastShow = data.moves.length ? m('div.data', [
      m('table', [
        m('thead', [
          m('tr', [
            m('th', 'Move'),
            m('th', 'Games'),
            m('th', 'White / Draw / Black')
          ])
        ]),
        m('tbody', {
          onclick: function(e) {
            var $tr = $(e.target).parents('tr');
            if ($tr.length) ctrl.explorerMove($tr[0].getAttribute('data-uci'));
          },
          onmouseover: function(e) {
            var $tr = $(e.target).parents('tr');
            if ($tr.length) ctrl.explorer.setHoveringUci($tr[0].getAttribute('data-uci'));
          },
          onmouseout: function(e) {
            ctrl.explorer.setHoveringUci(null);
          }
        }, data.moves.map(function(move) {
          return m('tr', {
            key: move.uci,
            'data-uci': move.uci
          }, [
            m('td', move.san),
            m('td', move.total),
            m('td', resultBar(move))
          ]);
        }))
      ])
    ]) : m('div.data.empty', 'No game found');
  }
  return lastShow;
}

function showConfig(ctrl) {
  return m('div.config', [
    m('div.title', ctrl.data.game.variant.name + ' opening explorer'),
    renderConfig(ctrl.explorer.config)
  ]);
}

var overlay = m('div.overlay', m.trust(lichess.spinnerHtml));

function failing() {
  return m('div.failing.message', [
      m('i[data-icon=,]'),
      m('h3', 'Oops, sorry!'),
      m('p', 'The explorer is temporarily'),
      m('p', 'out of service. Try again soon!')
  ]);
}

module.exports = {
  renderExplorer: function(ctrl) {
    if (!ctrl.explorer.enabled()) return;
    var config = ctrl.explorer.config;
    var configOpened = config.data.open();
    var loading = !configOpened && (ctrl.explorer.loading() || (!ctrl.explorer.current() && !ctrl.explorer.failing()));
    return m('div', {
      class: classSet({
        explorer_box: true,
        loading: loading,
        config: configOpened
      })
    }, [
      overlay,
      configOpened ? showConfig(ctrl) : (ctrl.explorer.failing() ? failing() : show(ctrl)),
      m('span.toconf', {
        'data-icon': configOpened ? 'L' : '%',
        onclick: config.toggleOpen
      })
    ]);
  }
};
<commit_msg>format explorer numbers<commit_after>var m = require('mithril');
var chessground = require('chessground');
var partial = chessground.util.partial;
var classSet = chessground.util.classSet;
var renderConfig = require('./explorerConfig').view;

function resultBar(move) {
  var sum = move.white + move.draws + move.black;
  var section = function(key) {
    return move[key] === 0 ? null : m('span', {
      class: key,
      style: {
        width: (Math.round(move[key] * 1000 / sum) / 10) + '%'
      },
    }, Math.round(move[key] * 100 / sum) + '%');
  }
  return m('div.bar', ['white', 'draws', 'black'].map(section));
}

var lastShow = null;

function show(ctrl) {
  var data = ctrl.explorer.current();
  if (data) {
    lastShow = data.moves.length ? m('div.data', [
      m('table', [
        m('thead', [
          m('tr', [
            m('th', 'Move'),
            m('th', 'Games'),
            m('th', 'White / Draw / Black')
          ])
        ]),
        m('tbody', {
          onclick: function(e) {
            var $tr = $(e.target).parents('tr');
            if ($tr.length) ctrl.explorerMove($tr[0].getAttribute('data-uci'));
          },
          onmouseover: function(e) {
            var $tr = $(e.target).parents('tr');
            if ($tr.length) ctrl.explorer.setHoveringUci($tr[0].getAttribute('data-uci'));
          },
          onmouseout: function(e) {
            ctrl.explorer.setHoveringUci(null);
          }
        }, data.moves.map(function(move) {
          return m('tr', {
            key: move.uci,
            'data-uci': move.uci
          }, [
            m('td', move.san),
            m('td', lichess.numberFormat(move.total)),
            m('td', resultBar(move))
          ]);
        }))
      ])
    ]) : m('div.data.empty', 'No game found');
  }
  return lastShow;
}

function showConfig(ctrl) {
  return m('div.config', [
    m('div.title', ctrl.data.game.variant.name + ' opening explorer'),
    renderConfig(ctrl.explorer.config)
  ]);
}

var overlay = m('div.overlay', m.trust(lichess.spinnerHtml));

function failing() {
  return m('div.failing.message', [
    m('i[data-icon=,]'),
    m('h3', 'Oops, sorry!'),
    m('p', 'The explorer is temporarily'),
    m('p', 'out of service. Try again soon!')
  ]);
}

module.exports = {
  renderExplorer: function(ctrl) {
    if (!ctrl.explorer.enabled()) return;
    var config = ctrl.explorer.config;
    var configOpened = config.data.open();
    var loading = !configOpened && (ctrl.explorer.loading() || (!ctrl.explorer.current() && !ctrl.explorer.failing()));
    return m('div', {
      class: classSet({
        explorer_box: true,
        loading: loading,
        config: configOpened
      })
    }, [
      overlay,
      configOpened ? showConfig(ctrl) : (ctrl.explorer.failing() ? failing() : show(ctrl)),
      m('span.toconf', {
        'data-icon': configOpened ? 'L' : '%',
        onclick: config.toggleOpen
      })
    ]);
  }
};
<|endoftext|>


<commit_before>'use strict';

var catalogAppConfig = {
    form: {
        viewRecipe: {
            entries: [
                {
					'name': 'recipe',
					'label': 'Recipe',
					'type': 'jsoneditor',
					'height': '450px',
                    'fixedHeight': true,
					'value': {},
					'required': true
				}
            ]
        },
        addRecipe: {
            entries: [
                {
                    'name': 'template',
					'label': 'Existing Recipe Template',
					'type': 'select',
					'value': [],
					'required': true
                },
                {
					'name': 'recipe',
					'label': 'Recipe',
					'type': 'jsoneditor',
					'height': '450px',
                    'fixedHeight': true,
					'value': {},
					'required': true
				}
            ]
        }
    },
    templates: {
        recipe: {
            "name": "",
            "type": "",
            "description": "",
            "recipe": {
                "deployOptions": {
                    "image": {
                        "prefix": "",
                        "name": "",
                        "tag": "",
                        "pullPolicy": ""
                    },
                    "readinessProbe": {
                        "httpGet": {
                            "path": "",
                            "port": ""
                        },
                        "initialDelaySeconds": 0,
                        "timeoutSeconds": 0,
                        "periodSeconds": 0,
                        "successThreshold": 0,
                        "failureThreshold": 0
                    },
                    "ports": [],
                    "voluming": {
                        "volumes": [],
                        "volumeMounts": []
                    }
                },
                "buildOptions": {
                    "env": {
                        "NODE_ENV": "production",
                    },
                    "cmd": {
                        "pre_deploy": [],
                        "post_deploy": []
                    }
                }
            }
        }
    },
    permissions: {
		list: ['dashboard', '/catalog/recipes/list', 'get'],
		add: ['dashboard', '/catalog/recipes/add', 'post'],
		update: ['dashboard', '/catalog/recipes/update', 'put'],
		delete: ['dashboard', '/catalog/recipes/delete', 'delete']
	}

};
<commit_msg>Updated catalog recipe template<commit_after>'use strict';

var catalogAppConfig = {
    form: {
        viewRecipe: {
            entries: [
                {
					'name': 'recipe',
					'label': 'Recipe',
					'type': 'jsoneditor',
					'height': '450px',
                    'fixedHeight': true,
					'value': {},
					'required': true
				}
            ]
        },
        addRecipe: {
            entries: [
                {
                    'name': 'template',
					'label': 'Existing Recipe Template',
					'type': 'select',
					'value': [],
					'required': true
                },
                {
					'name': 'recipe',
					'label': 'Recipe',
					'type': 'jsoneditor',
					'height': '450px',
                    'fixedHeight': true,
					'value': {},
					'required': true
				}
            ]
        }
    },
    templates: {
        recipe: {
            "name": "",
            "type": "",
            "description": "",
            "recipe": {
                "deployOptions": {
                    "image": {
                        "prefix": "",
                        "name": "",
                        "tag": "",
                        "pullPolicy": ""
                    },
                    "readinessProbe": {
                        "httpGet": {
                            "path": "",
                            "port": ""
                        },
                        "initialDelaySeconds": 0,
                        "timeoutSeconds": 0,
                        "periodSeconds": 0,
                        "successThreshold": 0,
                        "failureThreshold": 0
                    },
                    "ports": [],
                    "voluming": {
                        "volumes": [],
                        "volumeMounts": []
                    },
                    "restartPolicy": {
                        "condition": "",
                        "maxAttempts": 0
                    },
                    "container": {
                        "network": "",
                        "workingDir": ""
                    }
                },
                "buildOptions": {
                    "settings": {
                        "accelerateDeployment": true
                    },
                    "env": {
                        "NODE_ENV": "production",
                    },
                    "cmd": {
                        "pre_deploy": [],
                        "post_deploy": []
                    }
                }
            }
        }
    },
    permissions: {
		list: ['dashboard', '/catalog/recipes/list', 'get'],
		add: ['dashboard', '/catalog/recipes/add', 'post'],
		update: ['dashboard', '/catalog/recipes/update', 'put'],
		delete: ['dashboard', '/catalog/recipes/delete', 'delete']
	}

};
<|endoftext|>


<commit_before><commit_msg>发布工具更新： 1.支持namespace相关的d.ts解析 2.调整type类型解析逻辑<commit_after><|endoftext|>


<commit_before>var m = require('mithril');
var chessground = require('chessground');
var partial = chessground.util.partial;
var classSet = chessground.util.classSet;
var renderConfig = require('./explorerConfig').view;

function resultBar(move) {
  var sum = move.white + move.draws + move.black;
  var section = function(key) {
    var percent = move[key] * 100 / sum;
    return percent === 0 ? null : m('span', {
      class: key,
      style: {
        width: (Math.round(move[key] * 1000 / sum) / 10) + '%'
      },
    }, percent > 12 ? Math.round(percent) + '%' : null);
  }
  return m('div.bar', ['white', 'draws', 'black'].map(section));
}

var lastShow = null;

function show(ctrl) {
  var data = ctrl.explorer.current();
  if (data) {
    lastShow = data.moves.length ? m('div.data', [
      m('table', [
        m('thead', [
          m('tr', [
            m('th', 'Move'),
            m('th', 'Games'),
            m('th', 'White / Draw / Black')
          ])
        ]),
        m('tbody', {
          onclick: function(e) {
            var $tr = $(e.target).parents('tr');
            if ($tr.length) ctrl.explorerMove($tr[0].getAttribute('data-uci'));
          },
          onmouseover: function(e) {
            var $tr = $(e.target).parents('tr');
            if ($tr.length) ctrl.explorer.setHoveringUci($tr[0].getAttribute('data-uci'));
          },
          onmouseout: function(e) {
            ctrl.explorer.setHoveringUci(null);
          }
        }, data.moves.map(function(move) {
          return m('tr', {
            key: move.uci,
            'data-uci': move.uci
          }, [
            m('td', move.san),
            m('td', lichess.numberFormat(move.total)),
            m('td', resultBar(move))
          ]);
        }))
      ])
    ]) : m('div.data.empty', 'No game found');
  }
  return lastShow;
}

function showConfig(ctrl) {
  return m('div.config', [
    m('div.title', ctrl.data.game.variant.name + ' opening explorer'),
    renderConfig(ctrl.explorer.config, ctrl.data.game.variant)
  ]);
}

var overlay = m('div.overlay', m.trust(lichess.spinnerHtml));

function failing() {
  return m('div.failing.message', [
    m('i[data-icon=,]'),
    m('h3', 'Oops, sorry!'),
    m('p', 'The explorer is temporarily'),
    m('p', 'out of service. Try again soon!')
  ]);
}

module.exports = {
  renderExplorer: function(ctrl) {
    if (!ctrl.explorer.enabled()) return;
    var config = ctrl.explorer.config;
    var configOpened = config.data.open();
    var loading = !configOpened && (ctrl.explorer.loading() || (!ctrl.explorer.current() && !ctrl.explorer.failing()));
    return m('div', {
      class: classSet({
        explorer_box: true,
        loading: loading,
        config: configOpened
      })
    }, [
      overlay,
      configOpened ? showConfig(ctrl) : (ctrl.explorer.failing() ? failing() : show(ctrl)),
      m('span.toconf', {
        'data-icon': configOpened ? 'L' : '%',
        onclick: config.toggleOpen
      })
    ]);
  }
};
<commit_msg>hack around hovering/DOM changes bugs in the explorer<commit_after>var m = require('mithril');
var chessground = require('chessground');
var partial = chessground.util.partial;
var classSet = chessground.util.classSet;
var renderConfig = require('./explorerConfig').view;

function resultBar(move) {
  var sum = move.white + move.draws + move.black;
  var section = function(key) {
    var percent = move[key] * 100 / sum;
    return percent === 0 ? null : m('span', {
      class: key,
      style: {
        width: (Math.round(move[key] * 1000 / sum) / 10) + '%'
      },
    }, percent > 12 ? Math.round(percent) + '%' : null);
  }
  return m('div.bar', ['white', 'draws', 'black'].map(section));
}

var lastShow = null;

function $trUci($tr) {
  return $tr[0] ? $tr[0].getAttribute('data-uci') : null;
}

function show(ctrl) {
  var data = ctrl.explorer.current();
  if (data) {
    lastShow = data.moves.length ? m('div.data', [
      m('table', [
        m('thead', [
          m('tr', [
            m('th', 'Move'),
            m('th', 'Games'),
            m('th', 'White / Draw / Black')
          ])
        ]),
        m('tbody', {
          config: function(el, isUpdate, ctx) {
            if (!isUpdate || ctx.lastFen === ctrl.vm.step.fen) return;
            ctx.lastFen = ctrl.vm.step.fen;
            setTimeout(function() {
              ctrl.explorer.setHoveringUci($trUci($(el).find('tr:hover')));
            }, 100);
          },
          onclick: function(e) {
            var $tr = $(e.target).parents('tr');
            if ($tr.length) ctrl.explorerMove($trUci($tr));
          },
          onmouseover: function(e) {
            var $tr = $(e.target).parents('tr');
            ctrl.explorer.setHoveringUci($trUci($tr));
          },
          onmouseout: function(e) {
            ctrl.explorer.setHoveringUci(null);
          }
        }, data.moves.map(function(move) {
          return m('tr', {
            key: move.uci,
            'data-uci': move.uci
          }, [
            m('td', move.san),
            m('td', lichess.numberFormat(move.total)),
            m('td', resultBar(move))
          ]);
        }))
      ])
    ]) : m('div.data.empty', 'No game found');
  }
  return lastShow;
}

function showConfig(ctrl) {
  return m('div.config', [
    m('div.title', ctrl.data.game.variant.name + ' opening explorer'),
    renderConfig(ctrl.explorer.config, ctrl.data.game.variant)
  ]);
}

var overlay = m('div.overlay', m.trust(lichess.spinnerHtml));

function failing() {
  return m('div.failing.message', [
    m('i[data-icon=,]'),
    m('h3', 'Oops, sorry!'),
    m('p', 'The explorer is temporarily'),
    m('p', 'out of service. Try again soon!')
  ]);
}

module.exports = {
  renderExplorer: function(ctrl) {
    if (!ctrl.explorer.enabled()) return;
    var config = ctrl.explorer.config;
    var configOpened = config.data.open();
    var loading = !configOpened && (ctrl.explorer.loading() || (!ctrl.explorer.current() && !ctrl.explorer.failing()));
    return m('div', {
      class: classSet({
        explorer_box: true,
        loading: loading,
        config: configOpened
      })
    }, [
      overlay,
      configOpened ? showConfig(ctrl) : (ctrl.explorer.failing() ? failing() : show(ctrl)),
      m('span.toconf', {
        'data-icon': configOpened ? 'L' : '%',
        onclick: config.toggleOpen
      })
    ]);
  }
};
<|endoftext|>