<commit_before>define([
  'root/analysis/restoration-charts',
  'root/analysis/compute-histogram',
  'esri/geometry/geometryEngine',
  'root/analysis/analysisConfig',
  'root/analysis/ethiopiaConfig',
  'root/analysis/constants',
  'dojo/promise/all',
  'dojo/dom-class'
], function (charts, computeHistogram, geometryEngine, analysisConfig, ethiopiaConfig, KEYS, all, domClass) {

  /**
  * parse the counts from the histograms, remove the first value from the counts
  * array as it contains the null?( or unmatched) values from the request
  */
  var getCounts = function getCounts (histograms) {
    return histograms.length === 0 ? histograms : histograms[0].counts;
  };

  /**
  * computeHistgrams truncates remaining 0's, if a value is not present in counts for this reason
  * pad the end of the counts array with 0's
  */
  var padResults = function padResults(counts, expectedLength) {
    if (counts.length === expectedLength) { return counts; }
    var results = [];
    for (var i = 0; i < expectedLength; i++) {
      results[i] = counts[i] || 0;
    }
    return results;
  };

  /**
  * Put data into the format highcharts wants, and then filter out any data with a value of 0
  * or data in the No Data category
  */
  var formatData = function formatData (data, labels, colors) {
    return data.map(function (datum, index) {
      return {
        name: labels[index],
        data: [datum],
        color: colors[index]
      };
    }).filter(function (record) {
      return record.data[0] !== 0 && record.name !== 'No Data';
    });
  };

  return {

    performRestorationAnalysis: function (graphic, optionIndex) {
      var config = ethiopiaConfig.options[optionIndex];
      var geometry = graphic.geometry;
      var rasterId = config.id;
      var promises = {};
      // Individual Configs
      var slopeConfig = analysisConfig[KEYS.SLOPE];
      var lcConfig = analysisConfig[KEYS.LAND_COVER];
      var popConfig = analysisConfig[KEYS.POPULATION];
      var tcConfig = analysisConfig[KEYS.TREE_COVER];
      // Individual Results
      var slopeData;
      var lcData;
      var popData;
      var tcData;

      var simplifiedGeometry = geometryEngine.simplify(geometry);

      promises[KEYS.SLOPE] = computeHistogram.multiplyRasters(slopeConfig.id, rasterId, simplifiedGeometry);
      promises[KEYS.LAND_COVER] = computeHistogram.multiplyRasters(lcConfig.id, rasterId, simplifiedGeometry);
      promises[KEYS.POPULATION] = computeHistogram.multiplyRasters(popConfig.id, rasterId, simplifiedGeometry);
      promises[KEYS.TREE_COVER] = computeHistogram.multiplyRasters(tcConfig.id, rasterId, simplifiedGeometry);

      all(promises).always(function (results) {
        // Hide the loader, prepare the containers by clearing the current one and putting 4 nodes in place
        // for the different types of analysis
        domClass.add('analysis-loader', 'hidden');
        charts.prepareContainer(config.name);

        if (results.code && results.message) {
          charts.showError(KEYS.SLOPE_CHART_ID, slopeConfig.name);
          charts.showError(KEYS.LAND_COVER_CHART_ID, lcConfig.name);
          charts.showError(KEYS.POPULATION_CHART_ID, popConfig.name);
          charts.showError(KEYS.TREE_COVER_CHART_ID, tcConfig.name);
          return;
        }

        console.log(results);

        // Get an array of data with the same length as the classes by parsing counts and padding the array with 0's
        slopeData = padResults(getCounts(results[KEYS.SLOPE].histograms), slopeConfig.classes.length);
        lcData = padResults(getCounts(results[KEYS.LAND_COVER].histograms), lcConfig.classes.length);
        popData = padResults(getCounts(results[KEYS.POPULATION].histograms), popConfig.classes.length);
        tcData = padResults(getCounts(results[KEYS.TREE_COVER].histograms), tcConfig.classes.length);
        // Format the results into highcharts expected format { name, data, color }
        slopeData = formatData(slopeData, slopeConfig.classes, slopeConfig.colors);
        lcData = formatData(lcData, lcConfig.classes, lcConfig.colors);
        popData = formatData(popData, popConfig.classes, popConfig.colors);
        tcData = formatData(tcData, tcConfig.classes, tcConfig.colors);
        // title, chartId, name for axis, data
        charts.makeChart(KEYS.SLOPE_CHART_ID, slopeConfig.name, slopeData);
        charts.makeChart(KEYS.LAND_COVER_CHART_ID, lcConfig.name, lcData);
        charts.makeChart(KEYS.POPULATION_CHART_ID, popConfig.name, popData);
        charts.makeChart(KEYS.TREE_COVER_CHART_ID, tcConfig.name, tcData);
        // Debugging
        console.log(KEYS.SLOPE, results[KEYS.SLOPE].histograms);
        console.log(KEYS.LAND_COVER, results[KEYS.LAND_COVER].histograms);
        console.log(KEYS.POPULATION, results[KEYS.POPULATION].histograms);
        console.log(KEYS.TREE_COVER, results[KEYS.TREE_COVER].histograms);
      });
    }

  };

});
<commit_msg>Removed console statements<commit_after>define([
  'root/analysis/restoration-charts',
  'root/analysis/compute-histogram',
  'esri/geometry/geometryEngine',
  'root/analysis/analysisConfig',
  'root/analysis/ethiopiaConfig',
  'root/analysis/constants',
  'dojo/promise/all',
  'dojo/dom-class'
], function (charts, computeHistogram, geometryEngine, analysisConfig, ethiopiaConfig, KEYS, all, domClass) {

  /**
  * parse the counts from the histograms, remove the first value from the counts
  * array as it contains the null?( or unmatched) values from the request
  */
  var getCounts = function getCounts (histograms) {
    return histograms.length === 0 ? histograms : histograms[0].counts;
  };

  /**
  * computeHistgrams truncates remaining 0's, if a value is not present in counts for this reason
  * pad the end of the counts array with 0's
  */
  var padResults = function padResults(counts, expectedLength) {
    if (counts.length === expectedLength) { return counts; }
    var results = [];
    for (var i = 0; i < expectedLength; i++) {
      results[i] = counts[i] || 0;
    }
    return results;
  };

  /**
  * Put data into the format highcharts wants, and then filter out any data with a value of 0
  * or data in the No Data category
  */
  var formatData = function formatData (data, labels, colors) {
    return data.map(function (datum, index) {
      return {
        name: labels[index],
        data: [datum],
        color: colors[index]
      };
    }).filter(function (record) {
      return record.data[0] !== 0 && record.name !== 'No Data';
    });
  };

  return {

    performRestorationAnalysis: function (graphic, optionIndex) {
      var config = ethiopiaConfig.options[optionIndex];
      var geometry = graphic.geometry;
      var rasterId = config.id;
      var promises = {};
      // Individual Configs
      var slopeConfig = analysisConfig[KEYS.SLOPE];
      var lcConfig = analysisConfig[KEYS.LAND_COVER];
      var popConfig = analysisConfig[KEYS.POPULATION];
      var tcConfig = analysisConfig[KEYS.TREE_COVER];
      // Individual Results
      var slopeData;
      var lcData;
      var popData;
      var tcData;

      var simplifiedGeometry = geometryEngine.simplify(geometry);

      promises[KEYS.SLOPE] = computeHistogram.multiplyRasters(slopeConfig.id, rasterId, simplifiedGeometry);
      promises[KEYS.LAND_COVER] = computeHistogram.multiplyRasters(lcConfig.id, rasterId, simplifiedGeometry);
      promises[KEYS.POPULATION] = computeHistogram.multiplyRasters(popConfig.id, rasterId, simplifiedGeometry);
      promises[KEYS.TREE_COVER] = computeHistogram.multiplyRasters(tcConfig.id, rasterId, simplifiedGeometry);

      all(promises).always(function (results) {
        // Hide the loader, prepare the containers by clearing the current one and putting 4 nodes in place
        // for the different types of analysis
        domClass.add('analysis-loader', 'hidden');
        charts.prepareContainer(config.name);

        if (results.code && results.message) {
          charts.showError(KEYS.SLOPE_CHART_ID, slopeConfig.name);
          charts.showError(KEYS.LAND_COVER_CHART_ID, lcConfig.name);
          charts.showError(KEYS.POPULATION_CHART_ID, popConfig.name);
          charts.showError(KEYS.TREE_COVER_CHART_ID, tcConfig.name);
          return;
        }

        // Get an array of data with the same length as the classes by parsing counts and padding the array with 0's
        slopeData = padResults(getCounts(results[KEYS.SLOPE].histograms), slopeConfig.classes.length);
        lcData = padResults(getCounts(results[KEYS.LAND_COVER].histograms), lcConfig.classes.length);
        popData = padResults(getCounts(results[KEYS.POPULATION].histograms), popConfig.classes.length);
        tcData = padResults(getCounts(results[KEYS.TREE_COVER].histograms), tcConfig.classes.length);
        // Format the results into highcharts expected format { name, data, color }
        slopeData = formatData(slopeData, slopeConfig.classes, slopeConfig.colors);
        lcData = formatData(lcData, lcConfig.classes, lcConfig.colors);
        popData = formatData(popData, popConfig.classes, popConfig.colors);
        tcData = formatData(tcData, tcConfig.classes, tcConfig.colors);
        // title, chartId, name for axis, data
        charts.makeChart(KEYS.SLOPE_CHART_ID, slopeConfig.name, slopeData);
        charts.makeChart(KEYS.LAND_COVER_CHART_ID, lcConfig.name, lcData);
        charts.makeChart(KEYS.POPULATION_CHART_ID, popConfig.name, popData);
        charts.makeChart(KEYS.TREE_COVER_CHART_ID, tcConfig.name, tcData);
        // Debugging
        // console.log(KEYS.SLOPE, results[KEYS.SLOPE].histograms);
        // console.log(KEYS.LAND_COVER, results[KEYS.LAND_COVER].histograms);
        // console.log(KEYS.POPULATION, results[KEYS.POPULATION].histograms);
        // console.log(KEYS.TREE_COVER, results[KEYS.TREE_COVER].histograms);
      });
    }

  };

});
<|endoftext|>


<commit_before>var openElement = '.js-nav-open'
var closeElement = '.js-nav-close'
var overlayElement = '.js-nav-overlay'
var activeClass = 'is-active'
var el = document.querySelectorAll('.js-nav-container, .js-nav-push, .js-nav-overlay, html, body')

var init = function () {
  document.querySelector(openElement).addEventListener('click', function (e) {
    open()
  })

  document.querySelector(closeElement).addEventListener('click', function (e) {
    close()
  })

  document.querySelector(overlayElement).addEventListener('click', function (e) {
    close()
  })
}

var open = function () {
  var i

  for (i = 0; i < el.length; ++i) {
    el[i].classList.add(activeClass)
  }
}

var close = function () {
  var i

  for (i = 0; i < el.length; ++i) {
    el[i].classList.remove(activeClass)
  }
}

module.exports = {
  init: init,
  open: open,
  close: close
}
<commit_msg>sily js change<commit_after>var openElement = '.js-nav-open'
var closeElement = '.js-nav-close'
var overlayElement = '.js-nav-overlay'
var activeClass = 'is-active'
var el = document.querySelectorAll('.js-nav-container, .js-nav-push, .js-nav-overlay, html, body')

var init = function () {
  document.querySelector(openElement).addEventListener('click', function (e) {
    open()
  })

  document.querySelector(closeElement).addEventListener('click', function (e) {
    close()
  })

  document.querySelector(overlayElement).addEventListener('click', function (e) {
    close()
  })
}

var open = function () {
  var i

  for (i = 0; i < el.length; ++i) {
    el[i].classList.add(activeClass)
  }
}

var close = function () {
  var i

  for (i = 0; i < el.length; ++i) {
    el[i].classList.remove(activeClass)
  }
}

module.exports = {
  init: init,
  open: open,
  close: close
}

console.log('hello; nothing to see here...')
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015 SONATA-NFV [, ANY ADDITIONAL AFFILIATION]
 * ALL RIGHTS RESERVED.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Neither the name of the SONATA-NFV [, ANY ADDITIONAL AFFILIATION]
 * nor the names of its contributors may be used to endorse or promote
 * products derived from this software without specific prior written
 * permission.
 *
 * This work has been performed in the framework of the SONATA project,
 * funded by the European Commission under Grant number 671517 through
 * the Horizon 2020 and 5G-PPP programmes. The authors would like to
 * acknowledge the contributions of their colleagues of the SONATA
 * partner consortium (www.sonata-nfv.eu).* dirPagination - AngularJS module for paginating (almost) anything.
 */

describe('SonataBSS Instantiates a Service', function() {

    var requestId;

    beforeEach(function() {
        browser.get('http://localhost:1337/#/NSDs');
    });

    it('services list must not be empty', function() {

        var count = element.all(by.repeater('nSD in nSDs')).count();
        expect(count).toBeGreaterThan(0);
    });

    it('when clicked: "request service instantiation" instantiates a new service', function() {

        var inst_el = element.all(by.css('.btn-danger')).get(0);

        inst_el.click();

        var parent = element(by.id('instantiateNSD'));
        var child = parent.element(by.binding('childBinding'));

        var yes_el = parent.element(by.css('.btn-success'));

        yes_el.click();
        browser.sleep(1500);

        parent = element(by.id('instantiateRequest'));
        expect(parent.isDisplayed()).toBe(true);

        parent.element(by.id('requestId')).getText().then(function(text) {
            requestId = text;
        });

    });

    it('instantiation request must be in the list', function() {

        browser.get('http://localhost:1337/#/InstantiationRequests');

        var query = element(by.model('InstantiationRequestsSearch'));
        query.sendKeys(requestId);

        var data = element.all(by.repeater("InstantiationRequest in InstantiationRequests"));

        expect(data.count()).toBe(1);

    });

	it('request must be ready after service instantiation process', function() {

		browser.get('http://localhost:1337/#/InstantiationRequests');

		var query = element(by.model('InstantiationRequestsSearch'));
		query.sendKeys(requestId);

		var EC = protractor.ExpectedConditions;
		browser.wait(EC.textToBePresentInElement(element(by.repeater("InstantiationRequest in InstantiationRequests").column('status')) ,'ready', 60000));

    });

});<commit_msg>Changing E2E test timeout - 4 min<commit_after>/**
 * Copyright (c) 2015 SONATA-NFV [, ANY ADDITIONAL AFFILIATION]
 * ALL RIGHTS RESERVED.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Neither the name of the SONATA-NFV [, ANY ADDITIONAL AFFILIATION]
 * nor the names of its contributors may be used to endorse or promote
 * products derived from this software without specific prior written
 * permission.
 *
 * This work has been performed in the framework of the SONATA project,
 * funded by the European Commission under Grant number 671517 through
 * the Horizon 2020 and 5G-PPP programmes. The authors would like to
 * acknowledge the contributions of their colleagues of the SONATA
 * partner consortium (www.sonata-nfv.eu).* dirPagination - AngularJS module for paginating (almost) anything.
 */

describe('SonataBSS Instantiates a Service', function() {

    var requestId;

    beforeEach(function() {
        browser.get('http://localhost:1337/#/NSDs');
    });

    it('services list must not be empty', function() {

        var count = element.all(by.repeater('nSD in nSDs')).count();
        expect(count).toBeGreaterThan(0);
    });

    it('when clicked: "request service instantiation" instantiates a new service', function() {

        var inst_el = element.all(by.css('.btn-danger')).get(0);

        inst_el.click();

        var parent = element(by.id('instantiateNSD'));
        var child = parent.element(by.binding('childBinding'));

        var yes_el = parent.element(by.css('.btn-success'));

        yes_el.click();
        browser.sleep(1500);

        parent = element(by.id('instantiateRequest'));
        expect(parent.isDisplayed()).toBe(true);

        parent.element(by.id('requestId')).getText().then(function(text) {
            requestId = text;
        });

    });

    it('instantiation request must be in the list', function() {

        browser.get('http://localhost:1337/#/InstantiationRequests');

        var query = element(by.model('InstantiationRequestsSearch'));
        query.sendKeys(requestId);

        var data = element.all(by.repeater("InstantiationRequest in InstantiationRequests"));

        expect(data.count()).toBe(1);

    });

	it('request must be ready after service instantiation process', function() {

		browser.get('http://localhost:1337/#/InstantiationRequests');

		var query = element(by.model('InstantiationRequestsSearch'));
		query.sendKeys(requestId);

		var EC = protractor.ExpectedConditions;
		browser.wait(EC.textToBePresentInElement(element(by.repeater("InstantiationRequest in InstantiationRequests").column('status')) ,'ready', 240000));

    });

});<|endoftext|>


<commit_before>"use strict";
document.addEventListener('DOMContentLoaded', function(){
  var $ = new Game({
    width: window.innerWidth,
    height: window.innerHeight/ 2,
  });

  $.init('canvas', 'webgl')

  var menu = new Scene();
  menu.addListener('update', function(dt){
    if (menu.parent && menu.parent.keys[32]) {
      console.log('[MENU] Space pressed!');
    }

    if (menu.parent && menu.parent.touch){
      console.log('[MENU] Touched!');
    }
  });

  $.addScene(menu);

  // Add game scene.
  var gameScene = new Scene();
  gameScene.addListener('update', function(dt){
    if (gameScene.parent && gameScene.parent.keys[32]) {
      console.log('Space pressed!');
    }

    if (gameScene.parent && gameScene.parent.touch){
      //console.log('Touched!');
    }
  });

  var player = new Player();
  player.position = {x: $.width / 2, y: $.height / 2};

  gameScene.addEntity(player);

  var glitches = [];

  for (var i = 0; i < 50; i++) {
    var glitch = new Glitch();
    //glitch.position = {x: Math.random() * 100, y: Math.random() * $.height};
    glitch.position = {x: Math.random() * $.width, y: Math.random() * $.height};

    glitch.addCollisionTest(player, 'emp', function(origin, collision){
      if (collision.target.exploding) {
        gameScene.entities.splice(gameScene.entities.indexOf(origin), 1);
      }

      if (!collision.target.exploding && !collision.target.arming) {
        collision.target.die();
        collision.target.expanding = false;
        collision.target.stopExpanding();
        //console.log('Kill player!');
      }

    });

    glitch.addCollisionTest(player, 'player', function(origin, collision){
      if (!collision.target.exploding && !collision.target.arming) {
        collision.target.die();
        collision.target.colliding = true;
        collision.target.life -= 0.1;
        console.log(collision.target.life);
        //gameScene.entities.splice(gameScene.entities.indexOf(origin), 1);
      }
    });

    gameScene.addEntity(glitch);
  }

  $.addScene(gameScene);

  $.activeScene = 1;
});
<commit_msg>Add glitch spawn routines to gameplay.<commit_after>"use strict";
//document.addEventListener('DOMContentLoaded', function(){
  var $ = new Game({
    width: window.innerWidth,
    height: window.innerHeight/ 2,
  });

  $.init('canvas', 'webgl')

  var menu = new Scene();
  menu.addListener('update', function(dt){
    if (menu.parent && menu.parent.keys[32]) {
      console.log('[MENU] Space pressed!');
    }

    if (menu.parent && menu.parent.touch){
      console.log('[MENU] Touched!');
    }
  });

  $.addScene(menu);

  // Add game scene.
  var gameScene = new Scene();
  gameScene.timer = 0;
  gameScene.addListener('update', function(dt){
    if (gameScene.parent && gameScene.parent.keys[32]) {
      console.log('Space pressed!');
    }

    if (gameScene.parent && gameScene.parent.touch){
      //console.log('Touched!');
    }

    gameScene.timer += dt * 20;

    // Every now and then, throw a new glitch.
    var interval = 50 - parseInt(gameScene.timer) / 10;
    if (interval < 0) {
      gameScene.timer = 0;
      interval = 50 - parseInt(gameScene.timer) / 10;
    }
    if (parseInt(gameScene.timer) % interval == 0) {
      var glitch = createGlitch();
      gameScene.addEntity(glitch);
      console.log('Another glitch');
    }

    // Every now and then, throw a free arming.
    if (parseInt(gameScene.timer) % 500 == 0) {
      console.log('Here comes salvation!');
      // var glitch = createGlitch();
      // gameScene.addEntity(glitch);
    }

    //console.log(gameScene.timer);
  });

  gameScene.addListener('spawn-glitches', function(){
    $.applyBlur();
  });

  var kills = 0;

  var player = new Player();
  player.position = {x: $.width / 2, y: $.height / 2};
  gameScene.addEntity(player);

  function createGlitch(){
    var glitch = new Glitch();
    //glitch.position = {x: Math.random() * 100, y: Math.random() * $.height};
    glitch.position = {
      x: Math.random() * 10 + (parseInt(Math.random() * 2) == 0?$.width - 10:0),
      y: Math.random() * 10 + (parseInt(Math.random() * 2) == 0?$.height - 10:0),
    };

    glitch.addCollisionTest(player, 'explosion', function(origin, collision){
      if (collision.target.exploding) {
        // origin.position = {
        //   x: Math.random() * 10 + (parseInt(Math.random() * 2) == 0?$.width - 10:0),
        //   y: Math.random() * 10 + (parseInt(Math.random() * 2) == 0?$.height - 10:0),
        // };
        origin.die();
        kills++;
        gameScene.entities.splice(gameScene.entities.indexOf(origin), 1);
      }
    });

    glitch.addCollisionTest(player, 'emp', function(origin, collision){
      if (!collision.target.exploding && !collision.target.arming && !collision.target.dying && !collision.target.spawning) {
        collision.target.die();
        collision.target.expanding = false;
        collision.target.stopExpanding();
      }
    });

    glitch.addCollisionTest(player, 'player', function(origin, collision){
      if (!collision.target.exploding && !collision.target.arming && !collision.target.dying && !collision.target.spawning) {
        collision.target.die();
        collision.target.colliding = true;
        //collision.target.life -= 0.1;
        //gameScene.entities.splice(gameScene.entities.indexOf(origin), 1);
      }
    });

    return glitch;
  }

  for (var i = 0; i < 50; i++) {
    var glitch = createGlitch();
    gameScene.addEntity(glitch);
  }

  $.addScene(gameScene);

  var ui = new UI();
  gameScene.addEntity(ui);
  player.addListener('die', function(player){
    ui.lives = player.lives;
  });

  player.addListener('start-explosion', function(player){
    kills = 0;
  });

  player.addListener('end-explosion', function(player){
    ui.score += kills + (kills * parseInt(kills / 2));
    ui.displayKills(kills, player.position.x, player.position.y);
  });

  $.activeScene = 1;
//});
<|endoftext|>


<commit_before>import moment from 'moment';
import createDebug from 'debug';
import config from 'config';

import Mailer from '../../lib/mailer';

export function sendEventsDigestEmail(user, events, users, groups, digestInterval) {
  // TODO: const subject = config.mailer.notificationDigestEmailSubject
  const debug = createDebug('freefeed:sendEmails');
  let emailBody = '';

  for (const event of events) {
    const eventData = getEventPayload(event, users, groups);
    const template = notificationTemplates[event.event_type];

    if (template) {
      const eventText = template(eventData);
      const eventMarkup = getEventMarkup(eventText);
      emailBody += `${eventMarkup}\n`;
    } else {
      debug(`Template not found for event type ${event.event_type}`);
    }
  }

  return Mailer.sendMail(
    user,
    'Notifications digest',
    {
      digest: {
        body: emailBody,
        interval: digestInterval,
      },
      recipient: user,
      baseUrl: config.host,
    },
    `${config.appRoot}/app/scripts/views/mailer/notificationsDigest.ejs`,
    true,
  );
}

function getEventPayload(event, users, groups) {
  const creator = users.find((u) => {
    return u.id === event.created_user_id;
  });
  const affectedUser = users.find((u) => {
    return u.id === event.affected_user_id;
  });
  const postAuthor = users.find((u) => {
    return u.id === event.post_author_id;
  });
  const group = groups.find((g) => {
    return g.id === event.group_id;
  });
  return {
    creator,
    affectedUser,
    postAuthor,
    commentId: event.comment_id,
    postId: event.post_id,
    group,
    createdAt: moment(event.date),
  };
}

const notificationTemplates = {
  mention_in_post: (eventData) => {
    const postAuthorLink = makeUserLink(eventData.postAuthor);
    const postLink = makePostLink(eventData.postId, eventData.postAuthor);
    const groupLink = eventData.group ? makeUserLink(eventData.group) : null;
    const eventTime = eventData.createdAt.format('HH:MM');
    return `
      ${postAuthorLink} mentioned you in the ${postLink}${
      groupLink ? ` [in ${groupLink}]` : ''
    }

      ${eventTime}
    `;
  },
  mention_in_comment: (eventData) => {
    const commentAuthorLink = makeUserLink(eventData.creator);
    const postLink = makePostLink(eventData.postId, eventData.postAuthor);
    const commentLink = makeCommentLink(
      eventData.postId,
      eventData.commentId,
      eventData.postAuthor,
      'comment',
    );
    const groupLink = eventData.group ? makeUserLink(eventData.group) : null;
    const eventTime = eventData.createdAt.format('HH:MM');
    return `
      ${commentAuthorLink} mentioned you in a ${commentLink} to the ${postLink}${
      groupLink ? ` [in ${groupLink}]` : ''
    }

      ${eventTime}
    `;
  },
  mention_comment_to: (eventData) => {
    const commentAuthorLink = makeUserLink(eventData.creator);
    const postLink = makePostLink(eventData.postId, eventData.postAuthor);
    const commentLink = makeCommentLink(
      eventData.postId,
      eventData.commentId,
      eventData.postAuthor,
      'replied',
    );
    const groupLink = eventData.group ? makeUserLink(eventData.group) : null;
    const eventTime = eventData.createdAt.format('HH:MM');
    return `
      ${commentAuthorLink} ${commentLink} to you in the  ${postLink}${
      groupLink ? ` [in ${groupLink}]` : ''
    }

      ${eventTime}
    `;
  },
  direct: (eventData) => {
    const postAuthorLink = makeUserLink(eventData.postAuthor);
    const postLink = makePostLink(eventData.postId, eventData.postAuthor, true);
    const eventTime = eventData.createdAt.format('HH:MM');
    return `
      You received a ${postLink} from ${postAuthorLink}

      ${eventTime}
    `;
  },
  direct_comment: (eventData) => {
    const postAuthorLink = makeUserLink(eventData.postAuthor);
    const postLink = makePostLink(eventData.postId, eventData.postAuthor, true);
    const commentLink = makeCommentLink(
      eventData.postId,
      eventData.commentId,
      eventData.postAuthor,
      'comment',
    );
    const eventTime = eventData.createdAt.format('HH:MM');
    return `
      New ${commentLink} was posted to a ${postLink} from ${postAuthorLink}

      ${eventTime}
    `;
  },
  subscription_requested: (eventData) => {
    const subscriberLink = makeUserLink(eventData.creator);
    const eventTime = eventData.createdAt.format('HH:MM');
    return `
      ${subscriberLink} sent you a subscription request

      ${eventTime}
    `;
  },
  user_subscribed: (eventData) => {
    const subscriberLink = makeUserLink(eventData.creator);
    const eventTime = eventData.createdAt.format('HH:MM');
    return `
      ${subscriberLink} subscribed to your feed

      ${eventTime}
    `;
  },
  user_unsubscribed: () => {
    return '';
  },
  subscription_request_approved: (eventData) => {
    const approverLink = makeUserLink(eventData.creator);
    const eventTime = eventData.createdAt.format('HH:MM');
    return `
      Your subscription request to ${approverLink} was approved

      ${eventTime}
    `;
  },
  subscription_request_rejected: (eventData) => {
    const rejecterLink = makeUserLink(eventData.creator);
    const eventTime = eventData.createdAt.format('HH:MM');
    return `
      Your subscription request to ${rejecterLink} was rejected

      ${eventTime}
    `;
  },
  subscription_request_revoked: (eventData) => {
    const revokerLink = makeUserLink(eventData.creator);
    const eventTime = eventData.createdAt.format('HH:MM');
    return `
      ${revokerLink} revoked subscription request to you

      ${eventTime}
    `;
  },
  group_subscription_requested: (eventData) => {
    const requesterLink = makeUserLink(eventData.creator);
    const groupLink = makeUserLink(eventData.group);
    const eventTime = eventData.createdAt.format('HH:MM');
    return `
      ${requesterLink} sent a subscription request to join ${groupLink} that you admin

      ${eventTime}
    `;
  },
  group_admin_promoted: (eventData) => {
    const adminUserLink = makeUserLink(eventData.creator);
    const affectedUserLink = makeUserLink(eventData.affectedUser);
    const groupLink = makeUserLink(eventData.group);
    const eventTime = eventData.createdAt.format('HH:MM');
    return `
      ${adminUserLink} promoted ${affectedUserLink} to admin in the group ${groupLink}

      ${eventTime}
    `;
  },
  group_admin_demoted: (eventData) => {
    const adminUserLink = makeUserLink(eventData.creator);
    const affectedUserLink = makeUserLink(eventData.affectedUser);
    const groupLink = makeUserLink(eventData.group);
    const eventTime = eventData.createdAt.format('HH:MM');
    return `
      ${adminUserLink} revoked admin privileges from ${affectedUserLink} in group ${groupLink}

      ${eventTime}
    `;
  },
  managed_group_subscription_approved: (eventData) => {
    const adminUserLink = makeUserLink(eventData.creator);
    const affectedUserLink = makeUserLink(eventData.affectedUser);
    const groupLink = makeUserLink(eventData.group);
    const eventTime = eventData.createdAt.format('HH:MM');
    return `
      ${affectedUserLink} subscription request to join ${groupLink} was approved by ${adminUserLink}

      ${eventTime}
    `;
  },
  managed_group_subscription_rejected: (eventData) => {
    const affectedUserLink = makeUserLink(eventData.affectedUser);
    const groupLink = makeUserLink(eventData.group);
    const eventTime = eventData.createdAt.format('HH:MM');
    return `
      ${affectedUserLink} subscription request to join ${groupLink} was rejected

      ${eventTime}
    `;
  },
  group_subscription_approved: (eventData) => {
    const groupLink = makeUserLink(eventData.group);
    const eventTime = eventData.createdAt.format('HH:MM');
    return `
      Your request to join group ${groupLink} was approved

      ${eventTime}
    `;
  },
  group_subscription_request_revoked: (eventData) => {
    const requesterLink = makeUserLink(eventData.creator);
    const groupLink = makeUserLink(eventData.group);
    const eventTime = eventData.createdAt.format('HH:MM');
    return `
      ${requesterLink} revoked subscription request to ${groupLink}

      ${eventTime}
    `;
  },
  group_subscription_rejected: (eventData) => {
    const groupLink = makeUserLink(eventData.group);
    const eventTime = eventData.createdAt.format('HH:MM');
    return `
      Your request to join group ${groupLink} was rejected

      ${eventTime}
    `;
  },
  group_subscribed: (eventData) => {
    const subscriberLink = makeUserLink(eventData.creator);
    const groupLink = makeUserLink(eventData.group);
    const eventTime = eventData.createdAt.format('HH:MM');
    return `
      ${subscriberLink} subscribed to ${groupLink}

      ${eventTime}
    `;
  },
  group_unsubscribed: (eventData) => {
    const unsubscriberLink = makeUserLink(eventData.creator);
    const groupLink = makeUserLink(eventData.group);
    const eventTime = eventData.createdAt.format('HH:MM');
    return `
      ${unsubscriberLink} unsubscribed from ${groupLink}

      ${eventTime}
    `;
  },
};

function makeUserLink(user) {
  return `<a href="${config.host}/${user.username}" style="color:#555599;">@${user.username}</a>`;
}

function makePostLink(postId, postAuthor, isDirect = false) {
  const postLink = `${config.host}/${postAuthor.username}/${postId}`;
  return `<a href="${postLink}" style="color:#555599;">${isDirect ? 'direct message' : 'post'}</a>`;
}

function makeCommentLink(postId, commentId, postAuthor, linkText) {
  const postLink = `${config.host}/${postAuthor.username}/${postId}#comment-${commentId}`;
  return `<a href="${postLink}" style="color:#555599;">${linkText}</a>`;
}

function getEventMarkup(eventText) {
  return `

          ${eventText}

`;
}
<commit_msg>Handle deleted posts/comments/users in the notification emails<commit_after>import moment from 'moment';
import createDebug from 'debug';
import config from 'config';

import Mailer from '../../lib/mailer';

export function sendEventsDigestEmail(user, events, users, groups, digestInterval) {
  // TODO: const subject = config.mailer.notificationDigestEmailSubject
  const debug = createDebug('freefeed:sendEmails');
  let emailBody = '';

  for (const event of events) {
    const eventData = getEventPayload(event, users, groups);
    const template = notificationTemplates[event.event_type];

    if (template) {
      const eventText = template(eventData);
      const eventMarkup = getEventMarkup(eventText);
      emailBody += `${eventMarkup}\n`;
    } else {
      debug(`Template not found for event type ${event.event_type}`);
    }
  }

  return Mailer.sendMail(
    user,
    'Notifications digest',
    {
      digest: {
        body: emailBody,
        interval: digestInterval,
      },
      recipient: user,
      baseUrl: config.host,
    },
    `${config.appRoot}/app/scripts/views/mailer/notificationsDigest.ejs`,
    true,
  );
}

function getEventPayload(event, users, groups) {
  const creator = users.find((u) => {
    return u.id === event.created_user_id;
  });
  const affectedUser = users.find((u) => {
    return u.id === event.affected_user_id;
  });
  const postAuthor = users.find((u) => {
    return u.id === event.post_author_id;
  });
  const group = groups.find((g) => {
    return g.id === event.group_id;
  });
  return {
    creator,
    affectedUser,
    postAuthor,
    commentId: event.comment_id,
    postId: event.post_id,
    group,
    createdAt: moment(event.date),
  };
}

const notificationTemplates = {
  mention_in_post: (eventData) => {
    const postAuthorLink = makeUserLink(eventData.postAuthor);
    const postLink = makePostLink(eventData.postId, eventData.postAuthor);
    const groupLink = eventData.group ? makeUserLink(eventData.group) : null;
    const eventTime = eventData.createdAt.format('HH:MM');
    return `
      ${postAuthorLink} mentioned you in the ${postLink}${
      groupLink ? ` [in ${groupLink}]` : ''
    }

      ${eventTime}
    `;
  },
  mention_in_comment: (eventData) => {
    const commentAuthorLink = makeUserLink(eventData.creator);
    const postLink = makePostLink(eventData.postId, eventData.postAuthor);
    const commentLink = makeCommentLink(
      eventData.postId,
      eventData.commentId,
      eventData.postAuthor,
      'comment',
    );
    const groupLink = eventData.group ? makeUserLink(eventData.group) : null;
    const eventTime = eventData.createdAt.format('HH:MM');
    return `
      ${commentAuthorLink} mentioned you in a ${commentLink} to the ${postLink}${
      groupLink ? ` [in ${groupLink}]` : ''
    }

      ${eventTime}
    `;
  },
  mention_comment_to: (eventData) => {
    const commentAuthorLink = makeUserLink(eventData.creator);
    const postLink = makePostLink(eventData.postId, eventData.postAuthor);
    const commentLink = makeCommentLink(
      eventData.postId,
      eventData.commentId,
      eventData.postAuthor,
      'replied',
    );
    const groupLink = eventData.group ? makeUserLink(eventData.group) : null;
    const eventTime = eventData.createdAt.format('HH:MM');
    return `
      ${commentAuthorLink} ${commentLink} to you in the  ${postLink}${
      groupLink ? ` [in ${groupLink}]` : ''
    }

      ${eventTime}
    `;
  },
  direct: (eventData) => {
    const postAuthorLink = makeUserLink(eventData.postAuthor);
    const postLink = makePostLink(eventData.postId, eventData.postAuthor, true);
    const eventTime = eventData.createdAt.format('HH:MM');
    return `
      You received a ${postLink} from ${postAuthorLink}

      ${eventTime}
    `;
  },
  direct_comment: (eventData) => {
    const postAuthorLink = makeUserLink(eventData.postAuthor);
    const postLink = makePostLink(eventData.postId, eventData.postAuthor, true);
    const commentLink = makeCommentLink(
      eventData.postId,
      eventData.commentId,
      eventData.postAuthor,
      'comment',
    );
    const eventTime = eventData.createdAt.format('HH:MM');
    return `
      New ${commentLink} was posted to a ${postLink} from ${postAuthorLink}

      ${eventTime}
    `;
  },
  subscription_requested: (eventData) => {
    const subscriberLink = makeUserLink(eventData.creator);
    const eventTime = eventData.createdAt.format('HH:MM');
    return `
      ${subscriberLink} sent you a subscription request

      ${eventTime}
    `;
  },
  user_subscribed: (eventData) => {
    const subscriberLink = makeUserLink(eventData.creator);
    const eventTime = eventData.createdAt.format('HH:MM');
    return `
      ${subscriberLink} subscribed to your feed

      ${eventTime}
    `;
  },
  user_unsubscribed: () => {
    return '';
  },
  subscription_request_approved: (eventData) => {
    const approverLink = makeUserLink(eventData.creator);
    const eventTime = eventData.createdAt.format('HH:MM');
    return `
      Your subscription request to ${approverLink} was approved

      ${eventTime}
    `;
  },
  subscription_request_rejected: (eventData) => {
    const rejecterLink = makeUserLink(eventData.creator);
    const eventTime = eventData.createdAt.format('HH:MM');
    return `
      Your subscription request to ${rejecterLink} was rejected

      ${eventTime}
    `;
  },
  subscription_request_revoked: (eventData) => {
    const revokerLink = makeUserLink(eventData.creator);
    const eventTime = eventData.createdAt.format('HH:MM');
    return `
      ${revokerLink} revoked subscription request to you

      ${eventTime}
    `;
  },
  group_subscription_requested: (eventData) => {
    const requesterLink = makeUserLink(eventData.creator);
    const groupLink = makeUserLink(eventData.group);
    const eventTime = eventData.createdAt.format('HH:MM');
    return `
      ${requesterLink} sent a subscription request to join ${groupLink} that you admin

      ${eventTime}
    `;
  },
  group_admin_promoted: (eventData) => {
    const adminUserLink = makeUserLink(eventData.creator);
    const affectedUserLink = makeUserLink(eventData.affectedUser);
    const groupLink = makeUserLink(eventData.group);
    const eventTime = eventData.createdAt.format('HH:MM');
    return `
      ${adminUserLink} promoted ${affectedUserLink} to admin in the group ${groupLink}

      ${eventTime}
    `;
  },
  group_admin_demoted: (eventData) => {
    const adminUserLink = makeUserLink(eventData.creator);
    const affectedUserLink = makeUserLink(eventData.affectedUser);
    const groupLink = makeUserLink(eventData.group);
    const eventTime = eventData.createdAt.format('HH:MM');
    return `
      ${adminUserLink} revoked admin privileges from ${affectedUserLink} in group ${groupLink}

      ${eventTime}
    `;
  },
  managed_group_subscription_approved: (eventData) => {
    const adminUserLink = makeUserLink(eventData.creator);
    const affectedUserLink = makeUserLink(eventData.affectedUser);
    const groupLink = makeUserLink(eventData.group);
    const eventTime = eventData.createdAt.format('HH:MM');
    return `
      ${affectedUserLink} subscription request to join ${groupLink} was approved by ${adminUserLink}

      ${eventTime}
    `;
  },
  managed_group_subscription_rejected: (eventData) => {
    const affectedUserLink = makeUserLink(eventData.affectedUser);
    const groupLink = makeUserLink(eventData.group);
    const eventTime = eventData.createdAt.format('HH:MM');
    return `
      ${affectedUserLink} subscription request to join ${groupLink} was rejected

      ${eventTime}
    `;
  },
  group_subscription_approved: (eventData) => {
    const groupLink = makeUserLink(eventData.group);
    const eventTime = eventData.createdAt.format('HH:MM');
    return `
      Your request to join group ${groupLink} was approved

      ${eventTime}
    `;
  },
  group_subscription_request_revoked: (eventData) => {
    const requesterLink = makeUserLink(eventData.creator);
    const groupLink = makeUserLink(eventData.group);
    const eventTime = eventData.createdAt.format('HH:MM');
    return `
      ${requesterLink} revoked subscription request to ${groupLink}

      ${eventTime}
    `;
  },
  group_subscription_rejected: (eventData) => {
    const groupLink = makeUserLink(eventData.group);
    const eventTime = eventData.createdAt.format('HH:MM');
    return `
      Your request to join group ${groupLink} was rejected

      ${eventTime}
    `;
  },
  group_subscribed: (eventData) => {
    const subscriberLink = makeUserLink(eventData.creator);
    const groupLink = makeUserLink(eventData.group);
    const eventTime = eventData.createdAt.format('HH:MM');
    return `
      ${subscriberLink} subscribed to ${groupLink}

      ${eventTime}
    `;
  },
  group_unsubscribed: (eventData) => {
    const unsubscriberLink = makeUserLink(eventData.creator);
    const groupLink = makeUserLink(eventData.group);
    const eventTime = eventData.createdAt.format('HH:MM');
    return `
      ${unsubscriberLink} unsubscribed from ${groupLink}

      ${eventTime}
    `;
  },
};

function makeUserLink(user) {
  return user
    ? `<a href="${config.host}/${user.username}" style="color:#555599;">@${user.username}</a>`
    : 'unknown user';
}

function makePostLink(postId, postAuthor, isDirect = false) {
  if (!postId || !postAuthor) {
    return `deleted ${isDirect ? 'direct message' : 'post'}`;
  }

  const postLink = `${config.host}/${postAuthor.username}/${postId}`;
  return `<a href="${postLink}" style="color:#555599;">${isDirect ? 'direct message' : 'post'}</a>`;
}

function makeCommentLink(postId, commentId, postAuthor, linkText) {
  if (!postId || !postAuthor || !commentId) {
    return `${linkText} (deleted)`;
  }

  const postLink = `${config.host}/${postAuthor.username}/${postId}#comment-${commentId}`;
  return `<a href="${postLink}" style="color:#555599;">${linkText}</a>`;
}

function getEventMarkup(eventText) {
  return `

          ${eventText}

`;
}
<|endoftext|>


<commit_before>/*======================================================
************   XHR   ************
======================================================*/
// XHR Caching
app.cache = [];
app.removeFromCache = function (url) {
    var index = false;
    for (var i = 0; i < app.cache.length; i++) {
        if (app.cache[i].url === url) index = i;
    }
    if (index !== false) app.cache.splice(index, 1);
};

// XHR
app.xhr = false;
app.get = function (url, callback) {
    if (app.params.cache) {
        // Check is the url cached
        for (var i = 0; i < app.cache.length; i++) {
            if (app.cache[i].url === url) {
                // Check expiration
                if ((new Date()).getTime() - app.cache[i].time < app.params.cacheDuration) {
                    // Load from cache
                    callback(app.cache[i].data);
                    return false;
                }
            }
        }
    }
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.onload = function (e) {
        if (callback) {
            if (this.status === 200) {
                callback(this.responseText, false);
                if (app.params.cache) {
                    app.removeFromCache(url);
                    app.cache.push({
                        url: url,
                        time: (new Date()).getTime(),
                        data: this.responseText
                    });
                }
            }
            else {
                callback(this.responseText, true);
            }
        }
    };
    xhr.send();
    app.xhr = xhr;
    return xhr;
};<commit_msg>Local file XHR fix<commit_after>/*======================================================
************   XHR   ************
======================================================*/
// XHR Caching
app.cache = [];
app.removeFromCache = function (url) {
    var index = false;
    for (var i = 0; i < app.cache.length; i++) {
        if (app.cache[i].url === url) index = i;
    }
    if (index !== false) app.cache.splice(index, 1);
};

// XHR
app.xhr = false;
app.get = function (url, callback) {
    if (app.params.cache) {
        // Check is the url cached
        for (var i = 0; i < app.cache.length; i++) {
            if (app.cache[i].url === url) {
                // Check expiration
                if ((new Date()).getTime() - app.cache[i].time < app.params.cacheDuration) {
                    // Load from cache
                    callback(app.cache[i].data);
                    return false;
                }
            }
        }
    }
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.onload = function (e) {
        if (callback) {
            if (this.status === 200 || this.status === 0) {
                callback(this.responseText, false);
                if (app.params.cache) {
                    app.removeFromCache(url);
                    app.cache.push({
                        url: url,
                        time: (new Date()).getTime(),
                        data: this.responseText
                    });
                }
            }
            else {
                callback(this.responseText, true);
            }
        }
    };
    xhr.send();
    app.xhr = xhr;
    return xhr;
};<|endoftext|>


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

/**
 * @fileoverview
 * Registers a language handler for the Nemerle language.
 * http://nemerle.org
 * @author Zimin A.V.
 */
(function () {
  var keywords = 'abstract|and|as|base|catch|class|def|delegate|enum|event|extern|false|finally|'
         + 'fun|implements|interface|internal|is|macro|match|matches|module|mutable|namespace|new|'
         + 'null|out|override|params|partial|private|protected|public|ref|sealed|static|struct|'
         + 'syntax|this|throw|true|try|type|typeof|using|variant|virtual|volatile|when|where|with|'
         + 'assert|assert2|async|break|checked|continue|do|else|ensures|for|foreach|if|late|lock|new|nolate|'
         + 'otherwise|regexp|repeat|requires|return|surroundwith|unchecked|unless|using|while|yield';

  PR['registerLangHandler'](PR['createSimpleLexer'](
      // shortcutStylePatterns
      [
        [PR['PR_STRING'], /^(?:\'(?:[^\\\'\r\n]|\\.)*\'|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/, null, '"'],
        [PR['PR_COMMENT'], /^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\r\n]*)/, null, '#'],
        [PR['PR_PLAIN'], /^\s+/, null, ' \r\n\t\xA0']
      ],
      // fallthroughStylePatterns
      [
        [PR['PR_STRING'], /^@\"(?:[^\"]|\"\")*(?:\"|$)/, null],
        [PR['PR_STRING'], /^<#(?:[^#>])*(?:#>|$)/, null],
        [PR['PR_STRING'], /^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/, null],
        [PR['PR_COMMENT'], /^\/\/[^\r\n]*/, null],
        [PR['PR_COMMENT'], /^\/\*[\s\S]*?(?:\*\/|$)/, null],
        [PR['PR_KEYWORD'], new RegExp('^(?:' + keywords + ')\\b'), null],
        [PR['PR_TYPE'], /^(?:array|bool|byte|char|decimal|double|float|int|list|long|object|sbyte|short|string|ulong|uint|ufloat|ulong|ushort|void)\b/, null],
        [PR['PR_LITERAL'], /^@[a-z_$][a-z_$@0-9]*/i, null],
        [PR['PR_TYPE'], /^@[A-Z]+[a-z][A-Za-z_$@0-9]*/, null],
        [PR['PR_PLAIN'], /^'?[A-Za-z_$][a-z_$@0-9]*/i, null],
        [PR['PR_LITERAL'], new RegExp(
             '^(?:'
  // A hex number
             + '0x[a-f0-9]+'
  // or an octal or decimal number,
             + '|(?:\\d(?:_\\d+)*\\d*(?:\\.\\d*)?|\\.\\d\\+)'
  // possibly in scientific notation
             + '(?:e[+\\-]?\\d+)?'
             + ')'
  // with an optional modifier like UL for unsigned long
             + '[a-z]*', 'i'), null, '0123456789'],

        [PR['PR_PUNCTUATION'], /^.[^\s\w\.$@\'\"\`\/\#]*/, null]
      ],
      ['n', 'nemerle']));
})();
<commit_msg>fixed bug: wrong arguments passed to registerLangHandler in nemerle language extension<commit_after>// Copyright (C) 2011 Zimin A.V.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview
 * Registers a language handler for the Nemerle language.
 * http://nemerle.org
 * @author Zimin A.V.
 */
(function () {
  var keywords = 'abstract|and|as|base|catch|class|def|delegate|enum|event|extern|false|finally|'
         + 'fun|implements|interface|internal|is|macro|match|matches|module|mutable|namespace|new|'
         + 'null|out|override|params|partial|private|protected|public|ref|sealed|static|struct|'
         + 'syntax|this|throw|true|try|type|typeof|using|variant|virtual|volatile|when|where|with|'
         + 'assert|assert2|async|break|checked|continue|do|else|ensures|for|foreach|if|late|lock|new|nolate|'
         + 'otherwise|regexp|repeat|requires|return|surroundwith|unchecked|unless|using|while|yield';

  PR['registerLangHandler'](PR['createSimpleLexer'](
      // shortcutStylePatterns
      [
        [PR['PR_STRING'], /^(?:\'(?:[^\\\'\r\n]|\\.)*\'|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/, null, '"'],
        [PR['PR_COMMENT'], /^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\r\n]*)/, null, '#'],
        [PR['PR_PLAIN'], /^\s+/, null, ' \r\n\t\xA0']
      ],
      // fallthroughStylePatterns
      [
        [PR['PR_STRING'], /^@\"(?:[^\"]|\"\")*(?:\"|$)/, null],
        [PR['PR_STRING'], /^<#(?:[^#>])*(?:#>|$)/, null],
        [PR['PR_STRING'], /^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/, null],
        [PR['PR_COMMENT'], /^\/\/[^\r\n]*/, null],
        [PR['PR_COMMENT'], /^\/\*[\s\S]*?(?:\*\/|$)/, null],
        [PR['PR_KEYWORD'], new RegExp('^(?:' + keywords + ')\\b'), null],
        [PR['PR_TYPE'], /^(?:array|bool|byte|char|decimal|double|float|int|list|long|object|sbyte|short|string|ulong|uint|ufloat|ulong|ushort|void)\b/, null],
        [PR['PR_LITERAL'], /^@[a-z_$][a-z_$@0-9]*/i, null],
        [PR['PR_TYPE'], /^@[A-Z]+[a-z][A-Za-z_$@0-9]*/, null],
        [PR['PR_PLAIN'], /^'?[A-Za-z_$][a-z_$@0-9]*/i, null],
        [PR['PR_LITERAL'], new RegExp(
             '^(?:'
  // A hex number
             + '0x[a-f0-9]+'
  // or an octal or decimal number,
             + '|(?:\\d(?:_\\d+)*\\d*(?:\\.\\d*)?|\\.\\d\\+)'
  // possibly in scientific notation
             + '(?:e[+\\-]?\\d+)?'
             + ')'
  // with an optional modifier like UL for unsigned long
             + '[a-z]*', 'i'), null, '0123456789'],

        [PR['PR_PUNCTUATION'], /^.[^\s\w\.$@\'\"\`\/\#]*/, null]
      ]),
      ['n', 'nemerle']);
})();
<|endoftext|>


<commit_before>ne.util.defineNamespace('ne.component');

ne.component.Layout = ne.util.defineClass({
	init: function(opitons, $element) {
		this.$element = $element;
		this._makeGroup(opitons.grouplist);
		this._makeDragAndDrop(opitons.guideHTML);
		this._setEvents();
	},

	/**
	 * make group
	 * @param {array} grouplist list of group options
	 **/
	_makeGroup: function(grouplist) {
		var group;
		this.groups = {};

		ne.util.forEach(grouplist, function(item) {
			group = this.groups[item.id] = new ne.component.Layout.Group(item);
			this.$element.append(group.$element);
		}, this);
	},

	/**
	 * @param {(string|object)} object group item id or information to find group
	 **/
	_getGroup: function(group) {
		if (ne.util.isObject(group)) {
			if (group.attr('data-group')) {
				group = group.attr('data-group');
			} else {
				group = group.parent().attr('data-group');
			}
		}
		return this.groups[group];
	},

	/**
	 * make drag and drop event
	 * @param {string} [guideHTML] guide element html
	 **/
	_makeDragAndDrop: function(guideHTML) {
		this._drag = new ne.component.Layout.Drag({
			guideHTML: guideHTML
		});
	},

	/**
	 * set Events
	 **/
	_setEvents: function() {
		this.onMouseDown = $.proxy(this._onMouseDown, this);
		this.onMouseMove = $.proxy(this._onMouseMove, this);
		this.onMouseUp = $.proxy(this._onMouseUp, this);
		$('.drag-item-move').on('mousedown', this.onMouseDown);
	},

	/**
	 * mouse down event handler
	 * @param {JqueryEvent} e event object
	 **/
	_onMouseDown: function(e) {
		var initPos = {
			x: e.clientX + this.getX() + 10,
			y: e.clientY + this.getY() + 10
		},
		itemId = $(e.target).attr('data-item'),
		$moveEl = $('#' + itemId);
		this._drag.ready(initPos);
		this._drag.setMoveElement($moveEl);
		this.$temp = $moveEl;
		this.$temp.addClass('drag-clone');
		$(document).on('mousemove', this.onMouseMove);
		$(document).on('mouseup', this.onMouseUp);
	},

	/**
	 * mouse move handler
	 * @param {JqueryEvent} e event object
	 **/
	_onMouseMove: function(e) {
		var parent = $(e.target).parent(),
			x = this.getX(),
			y = this.getY(),
			pointX = e.clientX + this.getX(),
			pointY = e.clientY + this.getY(),
			drag = this._drag,
			group = parent.attr('data-group'),
			groupInst,
			$before;

		this._moveGuide(pointX, pointY);

		if (!group) {
			return;
		}

		groupInst = this._getGroup(group);

		if (ne.util.isEmpty(groupInst.list)) {
			parent.append(this.$temp);
			this.$temp.way = 'after';
			this.$temp.index = 0;
		} else {
			$before = this._detectTargetByPosition({
				x: pointX,
				y: pointY
			}, groupInst);

			if ($before && $before.way) {
				$before[$before.way](this.$temp);
				this.$temp.way = $before.way;
				this.$temp.index = $before.attr('data-index');
			}
		}
	},

	/**
	 * move drag effect element
	 * @param {number} x move position x
	 * @param {number} y move position y
	 **/
	_moveGuide: function(x, y) {
		this._drag.moveTo({
			x: x + 10 + 'px',
			y: y + 10 + 'px'
		});
	},

	/**
	 * detect target by move element position
	 * @param {object} pos position to detect
	 * @param {object} group  group that has child
	 * @return {object} target detected target
	 **/
	_detectTargetByPosition: function(pos, group) {
		var target,
			bound,
			bottom,
			top,
			height;

		ne.util.forEach(group.list, function(item) {
			if (!this._isValidItem(item)) {
				return;
			}

			bound = item.$element[0].getBoundingClientRect();
			bottom = this._getBottom(item, group);
			height = item.$element.height();
			// 요소 높이의 반을 기준으로 타겟을 선정한
			top = this.getY() + bound.top;
			if (pos.y > top && pos.y <= top + (height / 2)) {
				target = item.$element;
				target.way = 'before';
			} else if (pos.y > top + (height / 2) && pos.y < bottom) {
				target = item.$element;
				target.way = 'after';
			}

		}, this);

		return target;
	},

	/**
	 * check is Vaild item
	 **/
	_isValidItem: function(item) {
		return !!(item.$element[0] !== this.$temp[0]);
	},

	/**
	 * 다음요소가 있을 경우, 비교할 bottom 값으로 다음요소 top값을 넣어줌, 다음요소가 없으면 마지막 요소로 판단하여 limit(그룹의 bottom)값을 넣어줌
	 * @param {object} item
	 * @param {object} group
	 **/
	_getBottom: function(item, group) {
		var next = item.$element.next(),
			bottom,
			gbound = group.$element[0].getBoundingClientRect(),
			limit = this.getY() + gbound.top + group.$element.height();
		if (next.hasClass(DIMMED_LAYER_CLASS)) {
			bottom = limit;
		} else {
			bottom = this.getY() + next[0].getBoundingClientRect().top;
		}
		return bottom;
	},

	/**
	 * get add index by $temp, $temp.way
	 **/
	_getAddIndex: function() {
		var temp = this.$temp,
			index = parseInt(temp.index, 10);
		if (temp.way === 'after') {
			index += 1;
		}
		return index;
	},

	/**
	 * get scrollX
	 **/
	getX: function() {
		return (window.scrollX || $(window).scrollLeft());
	},

	/**
	 * get scrollY
	 **/
	getY: function() {
		return (window.scrollY || $(window).scrollTop());
	},

	/**
	 * mouse up handler
	 * @param {JqueryEvent} e event object
	 **/
	_onMouseUp: function(e) {
		var drag = this._drag,
			temp = this.$temp,
			oldGroup = this._getGroup(temp.attr('data-groupInfo')),
			targetGroup = this._getGroup(temp.parent()),
			removeIndex = parseInt(temp.attr('data-index'), 10),
			addIndex = this._getAddIndex(),
			item = oldGroup.list[removeIndex];

		if (addIndex) {
			oldGroup.remove(removeIndex);
			targetGroup.add(item, addIndex);
			targetGroup.render();
			oldGroup.render();
		}

		drag.finish();

		$(document).off('mousemove', this.onMouseMove);
		$(document).off('mouseup', this.onMouseUp);
	}
});<commit_msg>layout<commit_after>ne.util.defineNamespace('ne.component');

ne.component.Layout = ne.util.defineClass({
	init: function(opitons, $element) {
		this.$element = $element;
		this._makeGroup(opitons.grouplist);
		this._makeDragAndDrop(opitons.guideHTML);
		this._setEvents();
	},

	/**
	 * make group
	 * @param {array} grouplist list of group options
	 **/
	_makeGroup: function(grouplist) {
		var group;
		this.groups = {};

		ne.util.forEach(grouplist, function(item) {
			group = this.groups[item.id] = new ne.component.Layout.Group(item);
			this.$element.append(group.$element);
		}, this);
	},

	/**
	 * @param {(string|object)} object group item id or information to find group
	 **/
	_getGroup: function(group) {
		if (ne.util.isObject(group)) {
			if (group.attr('data-group')) {
				group = group.attr('data-group');
			} else {
				group = group.parent().attr('data-group');
			}
		}
		return this.groups[group];
	},

	/**
	 * make drag and drop event
	 * @param {string} [guideHTML] guide element html
	 **/
	_makeDragAndDrop: function(guideHTML) {
		this._drag = new ne.component.Layout.Drag({
			guideHTML: guideHTML
		});
	},

	/**
	 * set Events
	 **/
	_setEvents: function() {
		this.onMouseDown = $.proxy(this._onMouseDown, this);
		this.onMouseMove = $.proxy(this._onMouseMove, this);
		this.onMouseUp = $.proxy(this._onMouseUp, this);
		$('.drag-item-move').on('mousedown', this.onMouseDown);
	},

	/**
	 * mouse down event handler
	 * @param {JqueryEvent} e event object
	 **/
	_onMouseDown: function(e) {
		var initPos = {
			x: e.clientX + this.getX() + 10,
			y: e.clientY + this.getY() + 10
		},
		itemId = $(e.target).attr('data-item'),
		$moveEl = $('#' + itemId);
		this._drag.ready(initPos);
		this._drag.setMoveElement($moveEl);
		this.$temp = $moveEl;
		this.$temp.addClass('drag-clone');
		$(document).on('mousemove', this.onMouseMove);
		$(document).on('mouseup', this.onMouseUp);
	},

	/**
	 * mouse move handler
	 * @param {JqueryEvent} e event object
	 **/
	_onMouseMove: function(e) {
		var parent = $(e.target).parent(),
			pointX = e.clientX + this.getX(),
			pointY = e.clientY + this.getY(),
			group = parent.attr('data-group'),
			groupInst,
			$before;

		this._moveGuide(pointX, pointY);

		if (!group) {
			return;
		}

		groupInst = this._getGroup(group);

		if (ne.util.isEmpty(groupInst.list)) {
			parent.append(this.$temp);
			this.$temp.way = 'after';
			this.$temp.index = 0;
		} else {
			$before = this._detectTargetByPosition({
				x: pointX,
				y: pointY
			}, groupInst);

			if ($before && $before.way) {
				$before[$before.way](this.$temp);
				this.$temp.way = $before.way;
				this.$temp.index = $before.attr('data-index');
			}
		}
	},

	/**
	 * move drag effect element
	 * @param {number} x move position x
	 * @param {number} y move position y
	 **/
	_moveGuide: function(x, y) {
		this._drag.moveTo({
			x: x + 10 + 'px',
			y: y + 10 + 'px'
		});
	},

	/**
	 * detect target by move element position
	 * @param {object} pos position to detect
	 * @param {object} group  group that has child
	 * @return {object} target detected target
	 **/
	_detectTargetByPosition: function(pos, group) {
		var target,
			bound,
			bottom,
			top,
			height;

		ne.util.forEach(group.list, function(item) {
			if (!this._isValidItem(item)) {
				return;
			}

			bound = item.$element[0].getBoundingClientRect();
			bottom = this._getBottom(item, group);
			height = item.$element.height();
			// 요소 높이의 반을 기준으로 타겟을 선정한
			top = this.getY() + bound.top;
			if (pos.y > top && pos.y <= top + (height / 2)) {
				target = item.$element;
				target.way = 'before';
			} else if (pos.y > top + (height / 2) && pos.y < bottom) {
				target = item.$element;
				target.way = 'after';
			}

		}, this);

		return target;
	},

	/**
	 * check is Vaild item
	 **/
	_isValidItem: function(item) {
		return !!(item.$element[0] !== this.$temp[0]);
	},

	/**
	 * 다음요소가 있을 경우, 비교할 bottom 값으로 다음요소 top값을 넣어줌, 다음요소가 없으면 마지막 요소로 판단하여 limit(그룹의 bottom)값을 넣어줌
	 * @param {object} item
	 * @param {object} group
	 **/
	_getBottom: function(item, group) {
		var next = item.$element.next(),
			bottom,
			gbound = group.$element[0].getBoundingClientRect(),
			limit = this.getY() + gbound.top + group.$element.height();
		if (next.hasClass(DIMMED_LAYER_CLASS)) {
			bottom = limit;
		} else {
			bottom = this.getY() + next[0].getBoundingClientRect().top;
		}
		return bottom;
	},

	/**
	 * get add index by $temp, $temp.way
	 **/
	_getAddIndex: function() {
		var temp = this.$temp,
			index = parseInt(temp.index, 10);
		if (temp.way === 'after') {
			index += 1;
		}
		return index;
	},

	/**
	 * get scrollX
	 **/
	getX: function() {
		return (window.scrollX || $(window).scrollLeft());
	},

	/**
	 * get scrollY
	 **/
	getY: function() {
		return (window.scrollY || $(window).scrollTop());
	},

	/**
	 * mouse up handler
	 * @param {JqueryEvent} e event object
	 **/
	_onMouseUp: function(e) {
		var drag = this._drag,
			temp = this.$temp,
			oldGroup = this._getGroup(temp.attr('data-groupInfo')),
			targetGroup = this._getGroup(temp.parent()),
			removeIndex = parseInt(temp.attr('data-index'), 10),
			addIndex = this._getAddIndex(),
			item = oldGroup.list[removeIndex];

		if (addIndex) {
			oldGroup.remove(removeIndex);
			targetGroup.add(item, addIndex);
			targetGroup.render();
			oldGroup.render();
		}

		drag.finish();

		$(document).off('mousemove', this.onMouseMove);
		$(document).off('mouseup', this.onMouseUp);
	}
});<|endoftext|>


<commit_before>import { h, Component } 				from 'preact/preact';
import Shallow							from 'shallow/shallow';

import ContentLoading					from 'com/content-loading/loading';
import SVGIcon							from 'com/svg-icon/icon';
import IMG2								from 'com/img2/img2';

import ButtonLink						from 'com/button-link/link';

import $Node							from '../../shrub/js/node/node';

export default class ContentBox extends Component {
	constructor( props ) {
		super(props);

		this.state = {
			'authors': null,
			'parent': null,
		};
	}

	componentDidMount() {
		this.getParent(this.props);
	}

	componentWillReceiveProps( nextProps ) {
		if ( Shallow.Diff(this.props, nextProps) ) {
			this.getParent(nextProps);
		}
	}

	getParent( props ) {
		var node = props.node;

		if ( node && node.parent ) {
			return $Node.Get(node.parent)
				.then(r => {
					if ( r && r.node && r.node.length ) {
						var Parent = r.node[0];
						this.setState({'parent': Parent});
					}
				});
		}
		return Promise.resolve({});
	}

	getAuthors() {

	}

	render( props, state ) {
		props = Object.assign({}, props);

		var node = props.node;
		var user = props.user;
		var path = props.path;
		var extra = props.extra;

		if ( node /* && state.authors */ ) {
			var Class = ["content-box"];

			var Title = node.name;

			var CoverFail = '///content/internal/tvfail.png';
			var Cover = (node.meta && node.meta.cover) ? node.meta.cover : CoverFail;
			var HoverCover = (node.meta && node.meta['hover-cover']) ? node.meta['hover-cover'] : CoverFail;

//			Cover += '.320x256.fit.jpg';
//			Cover += '.640x512.fit.jpg';
			Cover += '.480x384.fit.jpg';

			var ShowHoverCover = null;
			if ( node.meta['cover-hover'] ) {
				ShowHoverCover = <IMG2 class="-cover-hover" src={HoverCover} failsrc={CoverFail} />;
			}

			var ShowEvent = null;
			if ( !props.noevent && state.parent && state.parent.name ) {
				ShowEvent =
{state.parent.name}
;
			}

			var ShowSubEvent = null;
			var SubEventClass = null;
			if ( !props.nosubevent && node.subtype ) {
				if ( !node.published ) {
					ShowSubEvent =
<SVGIcon baseline small>cross</SVGIcon>
;
				}
				else if ( node.subtype == 'game' ) {
					ShowSubEvent =
GAME
;
					if ( node.subsubtype ) {
						if ( node.subsubtype == 'jam' ) {
							ShowSubEvent =
JAM
;
							SubEventClass = '-col-a';
						}
						else if ( node.subsubtype == 'compo' ) {
							ShowSubEvent =
COMPO
;
							SubEventClass = '-col-ab';
						}
						else if ( node.subsubtype == 'craft' ) {
							ShowSubEvent =
CRAFT
;
							SubEventClass = '-col-b';
						}
						else if ( node.subsubtype == 'release' ) {
							ShowSubEvent =
RELEASE
;
							SubEventClass = '-col-ca';
						}
						else if ( node.subsubtype == 'unfinished' ) {
							ShowSubEvent =
<SVGIcon baseline small>cross</SVGIcon>
;
						}
					}
				}
				else if ( node.subtype == 'tool' ) {
					ShowSubEvent =
TOOL
;
					SubEventClass = '-col-c';
				}
			}

			let ShowTrophies = null;
			if ( node.magic ) {
				ShowTrophies = [];

				for ( let key in node.magic ) {
					let parts = key.split('-');
					if ( /*ShowTrophies.length < 6 &&*/ parts.length == 3 && parts[0] == 'grade' && parts[2] == 'result' ) {
						if ( node.magic[key] == 1 )
							ShowTrophies.push(<SVGIcon>trophy</SVGIcon>);
						else if ( node.magic[key] == 2 )
							ShowTrophies.push(<SVGIcon>trophy</SVGIcon>);
						else if ( node.magic[key] == 3 )
							ShowTrophies.push(<SVGIcon>trophy</SVGIcon>);
					}
				}
				ShowTrophies.sort(function(a, b) {
					sortOrder = ['-first', '-second', '-third'];
					regexPattern = /class=\"([^\"]+)/;
					return sortOrder.indexOf(regexPattern.exec(a)[1]) - sortOrder.indexOf(regexPattern.exec(b)[1]);
				});
			}

			return (
				<ButtonLink class={cN(Class, props.class)} href={node.path}>
					{ShowHoverCover}
					<IMG2 class="-cover" src={Cover} failsrc={CoverFail} />

						{ShowEvent}

						{ShowSubEvent}

						{ShowTrophies}

{Title}

				</ButtonLink>
			);
		}
		else {
			return <ContentLoading />;
		}
	}
}
<commit_msg>disabled trophy sort<commit_after>import { h, Component } 				from 'preact/preact';
import Shallow							from 'shallow/shallow';

import ContentLoading					from 'com/content-loading/loading';
import SVGIcon							from 'com/svg-icon/icon';
import IMG2								from 'com/img2/img2';

import ButtonLink						from 'com/button-link/link';

import $Node							from '../../shrub/js/node/node';

export default class ContentBox extends Component {
	constructor( props ) {
		super(props);

		this.state = {
			'authors': null,
			'parent': null,
		};
	}

	componentDidMount() {
		this.getParent(this.props);
	}

	componentWillReceiveProps( nextProps ) {
		if ( Shallow.Diff(this.props, nextProps) ) {
			this.getParent(nextProps);
		}
	}

	getParent( props ) {
		var node = props.node;

		if ( node && node.parent ) {
			return $Node.Get(node.parent)
				.then(r => {
					if ( r && r.node && r.node.length ) {
						var Parent = r.node[0];
						this.setState({'parent': Parent});
					}
				});
		}
		return Promise.resolve({});
	}

	getAuthors() {

	}

	render( props, state ) {
		props = Object.assign({}, props);

		var node = props.node;
		var user = props.user;
		var path = props.path;
		var extra = props.extra;

		if ( node /* && state.authors */ ) {
			var Class = ["content-box"];

			var Title = node.name;

			var CoverFail = '///content/internal/tvfail.png';
			var Cover = (node.meta && node.meta.cover) ? node.meta.cover : CoverFail;
			var HoverCover = (node.meta && node.meta['hover-cover']) ? node.meta['hover-cover'] : CoverFail;

//			Cover += '.320x256.fit.jpg';
//			Cover += '.640x512.fit.jpg';
			Cover += '.480x384.fit.jpg';

			var ShowHoverCover = null;
			if ( node.meta['cover-hover'] ) {
				ShowHoverCover = <IMG2 class="-cover-hover" src={HoverCover} failsrc={CoverFail} />;
			}

			var ShowEvent = null;
			if ( !props.noevent && state.parent && state.parent.name ) {
				ShowEvent =
{state.parent.name}
;
			}

			var ShowSubEvent = null;
			var SubEventClass = null;
			if ( !props.nosubevent && node.subtype ) {
				if ( !node.published ) {
					ShowSubEvent =
<SVGIcon baseline small>cross</SVGIcon>
;
				}
				else if ( node.subtype == 'game' ) {
					ShowSubEvent =
GAME
;
					if ( node.subsubtype ) {
						if ( node.subsubtype == 'jam' ) {
							ShowSubEvent =
JAM
;
							SubEventClass = '-col-a';
						}
						else if ( node.subsubtype == 'compo' ) {
							ShowSubEvent =
COMPO
;
							SubEventClass = '-col-ab';
						}
						else if ( node.subsubtype == 'craft' ) {
							ShowSubEvent =
CRAFT
;
							SubEventClass = '-col-b';
						}
						else if ( node.subsubtype == 'release' ) {
							ShowSubEvent =
RELEASE
;
							SubEventClass = '-col-ca';
						}
						else if ( node.subsubtype == 'unfinished' ) {
							ShowSubEvent =
<SVGIcon baseline small>cross</SVGIcon>
;
						}
					}
				}
				else if ( node.subtype == 'tool' ) {
					ShowSubEvent =
TOOL
;
					SubEventClass = '-col-c';
				}
			}

			let ShowTrophies = null;
			if ( node.magic ) {
				ShowTrophies = [];

				for ( let key in node.magic ) {
					let parts = key.split('-');
					if ( /*ShowTrophies.length < 6 &&*/ parts.length == 3 && parts[0] == 'grade' && parts[2] == 'result' ) {
						if ( node.magic[key] == 1 )
							ShowTrophies.push(<SVGIcon>trophy</SVGIcon>);
						else if ( node.magic[key] == 2 )
							ShowTrophies.push(<SVGIcon>trophy</SVGIcon>);
						else if ( node.magic[key] == 3 )
							ShowTrophies.push(<SVGIcon>trophy</SVGIcon>);
					}
				}
//				ShowTrophies.sort(function(a, b) {
//					sortOrder = ['-first', '-second', '-third'];
//					regexPattern = /class=\"([^\"]+)/;
//					return sortOrder.indexOf(regexPattern.exec(a)[1]) - sortOrder.indexOf(regexPattern.exec(b)[1]);
//				});
			}

			return (
				<ButtonLink class={cN(Class, props.class)} href={node.path}>
					{ShowHoverCover}
					<IMG2 class="-cover" src={Cover} failsrc={CoverFail} />

						{ShowEvent}

						{ShowSubEvent}

						{ShowTrophies}

{Title}

				</ButtonLink>
			);
		}
		else {
			return <ContentLoading />;
		}
	}
}
<|endoftext|>


<commit_before>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @format
 * @flow strict-local
 */

'use strict';

const React = require('react');

const {
  PermissionsAndroid,
  Picker,
  StyleSheet,
  Text,
  TouchableWithoutFeedback,
  View,
} = require('react-native');

const Item = Picker.Item;

class PermissionsExample extends React.Component<{...}, $FlowFixMeState> {
  state = {
    permission: PermissionsAndroid.PERMISSIONS.CAMERA,
    hasPermission: 'Not Checked',
  };

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.text}>Permission Name:</Text>
        <Picker
          style={styles.picker}
          selectedValue={this.state.permission}
          onValueChange={this._onSelectPermission.bind(this)}>
          <Item
            label={PermissionsAndroid.PERMISSIONS.CAMERA}
            value={PermissionsAndroid.PERMISSIONS.CAMERA}
          />
          <Item
            label={PermissionsAndroid.PERMISSIONS.READ_CALENDAR}
            value={PermissionsAndroid.PERMISSIONS.READ_CALENDAR}
          />
          <Item
            label={PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION}
            value={PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION}
          />
        </Picker>
        <TouchableWithoutFeedback onPress={this._checkPermission}>
          <View>
            <Text style={[styles.touchable, styles.text]}>
              Check Permission
            </Text>
          </View>
        </TouchableWithoutFeedback>
        <Text style={styles.text}>
          Permission Status: {this.state.hasPermission}
        </Text>
        <TouchableWithoutFeedback onPress={this._requestPermission}>
          <View>
            <Text style={[styles.touchable, styles.text]}>
              Request Permission
            </Text>
          </View>
        </TouchableWithoutFeedback>
      </View>
    );
  }

  _onSelectPermission = (permission: string | number) => {
    this.setState({
      permission: permission,
    });
  };

  _checkPermission = async () => {
    let result = await PermissionsAndroid.check(this.state.permission);
    this.setState({
      hasPermission:
        (result ? 'Granted' : 'Revoked') + ' for ' + this.state.permission,
    });
  };

  _requestPermission = async () => {
    let result = await PermissionsAndroid.request(this.state.permission, {
      title: 'Permission Explanation',
      message:
        'The app needs the following permission ' +
        this.state.permission +
        ' because of reasons. Please approve.',
    });

    this.setState({
      hasPermission: result + ' for ' + this.state.permission,
    });
  };
}

exports.displayName = (undefined: ?string);
exports.framework = 'React';
exports.title = 'PermissionsAndroid';
exports.category = 'Android';
exports.description = 'Permissions example for API 23+.';
exports.examples = [
  {
    title: 'Permissions Example',
    description:
      'Short example of how to use the runtime permissions API introduced in Android M.',
    render: (): React.Node => <PermissionsExample />,
  },
];

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
  },
  text: {
    margin: 10,
  },
  touchable: {
    color: '#007AFF',
  },
  picker: {
    flex: 1,
  },
});
<commit_msg>Remove Picker from Android Permissions example<commit_after>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @format
 * @flow strict-local
 */

'use strict';

import * as React from 'react';

import {PermissionsAndroid, StyleSheet, Text, View} from 'react-native';
import RNTOption from '../../components/RNTOption';
import RNTesterButton from '../../components/RNTesterButton';

function PermissionsExample() {
  const [permission, setPermission] = React.useState(
    PermissionsAndroid.PERMISSIONS.CAMERA,
  );
  const [hasPermission, setHasPermission] = React.useState('Not Checked');

  const requestPermission = async () => {
    let result;
    try {
      result = await PermissionsAndroid.request(permission, {
        title: 'Permission Explanation',
        message:
          'The app needs the following permission ' +
          permission +
          ' because of reasons. Please approve.',
      });
      setHasPermission(result + ' for ' + permission);
    } catch (e) {
      throw e;
    }
  };

  const checkPermission = async () => {
    let result;
    try {
      result = await PermissionsAndroid.check(permission);
    } catch (e) {
      throw e;
    }
    setHasPermission(`${result ? 'Granted' : 'Revoked'} for ${permission}`);
  };

  return (
    <View style={styles.container}>
      <View style={styles.block}>
        <Text style={styles.title}>Select Permission</Text>
        <View style={styles.row}>
          <RNTOption
            label={PermissionsAndroid.PERMISSIONS.CAMERA}
            key={PermissionsAndroid.PERMISSIONS.CAMERA}
            onPress={() => setPermission(PermissionsAndroid.PERMISSIONS.CAMERA)}
            selected={permission === PermissionsAndroid.PERMISSIONS.CAMERA}
            style={styles.option}
          />
          <RNTOption
            label={PermissionsAndroid.PERMISSIONS.READ_CALENDAR}
            key={PermissionsAndroid.PERMISSIONS.READ_CALENDAR}
            onPress={() =>
              setPermission(PermissionsAndroid.PERMISSIONS.READ_CALENDAR)
            }
            selected={
              permission === PermissionsAndroid.PERMISSIONS.READ_CALENDAR
            }
            style={styles.option}
          />
          <RNTOption
            label={PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION}
            key={PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION}
            onPress={() =>
              setPermission(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION)
            }
            selected={
              permission === PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION
            }
            style={styles.option}
          />
        </View>
      </View>
      <RNTesterButton onPress={checkPermission}>
        <View>
          <Text style={[styles.touchable, styles.text]}>Check Permission</Text>
        </View>
      </RNTesterButton>
      <RNTesterButton onPress={requestPermission}>
        <View>
          <Text style={[styles.touchable, styles.text]}>
            Request Permission
          </Text>
        </View>
      </RNTesterButton>
      <Text style={styles.text}>Permission Status: {hasPermission}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
  },
  block: {
    borderColor: 'rgba(0,0,0, 0.1)',
    borderBottomWidth: 1,
    padding: 6,
  },
  row: {
    flexDirection: 'row',
    flexWrap: 'wrap',
  },
  title: {
    fontWeight: 'bold',
  },
  text: {
    fontSize: 20,
  },
  touchable: {
    color: '#007AFF',
  },
  option: {
    margin: 6,
  },
});

exports.displayName = (undefined: ?string);
exports.framework = 'React';
exports.title = 'PermissionsAndroid';
exports.category = 'Android';
exports.description = 'Permissions example for API 23+.';
exports.examples = [
  {
    title: 'Permissions Example',
    description:
      'Short example of how to use the runtime permissions API introduced in Android M.',
    render: (): React.Node => <PermissionsExample />,
  },
];
<|endoftext|>