<commit_before>var $select;

Template.bookmarkPage.events({
  'submit form': function(events) {
    events.preventDefault();
    var user = Meteor.user();
    if (user !== null) {
      var tags = ParsedTags($(events.target).find('[name=tags]').val());
      var tabGroup = [];
      if ($select) {
        for (var i = 0; i < $select[0].selectize.items.length; i++) {
          tabGroup.push($select[0].selectize.getItem($select[0].selectize.items[i]).text());
        };
      }
      var groups = ParsedGroups(tabGroup);
      var bookmark = {
        url: $(events.target).find('[name=url]').val(),
        title: $(events.target).find('[name=title]').val(),
        description: $(events.target).find('[name=description]').val(),
        thumbnail: $(events.target).find('[name=thumbnail]').val(),
        tags: tags,
        groups: groups,
        dateCreated: this.dateCreated,
        dateModified: new Date(),
        counterView: this.counterView,
        counterClick: this.counterView,
        summary: this.summary,
        userId: this.userId
      };
      if (bookmark.url.indexOf("://") == -1) bookmark.url = "http://" + bookmark.url;
      CreatedTags(tags);
      if (this.url == bookmark.url || Bookmarks.find({
        url: bookmark.url,
        userId: bookmark.userId
      }).count() == 0) {
        Meteor.call('bookmarkUpdate', bookmark, this._id, function(error, result) {
          if (error) return alert(error.reason);
          if (!result.success) {
            DisplayErrorSubmit(result.message);
            return;
          }
          Router.go('/home');
        });
      } else {
        DisplayErrorSubmit("Url already use.");
      }
    } else {
      DisplayErrorSubmit("You need to be connected.");
    }
  },

  'click .btnDelete': function(e) {
    e.preventDefault();
    var idDelete = this._id;
    bootbox.dialog({
      message: "Do you want delete this bookmark",
      title: "Warning",
      buttons: {
        main: {
          label: "Cancel",
          className: "btn-primary"
        },
        danger: {
          label: "Delete",
          className: "btn-danger",
          callback: function() {
            Meteor.call("removeBookmark", idDelete);
            Router.go('/home');
          }
        }
      }
    });
  },

  'click .refreshView': function(e) {
    e.preventDefault();
    $("#nuage").css("color", "rgb(65, 65, 178)");

    var retry = 0;
    var new_bookmark = this;
    var _id = new_bookmark._id;
    new_bookmark = _.omit(new_bookmark, '_id');

    Meteor.call("analyzeText", new_bookmark.url, function(error, result) {
      var id = result;

      var check = function(id) {
        Meteor.call("getText", id, function(error, result) {
          retry++;
          if (retry >= 10) {

            console.log("analyzeText Failed");
            $("#nuage").css("color", "rgb(188, 0, 0)");

          } else if (result.status == "finished") {

            new_bookmark.summary = result;
            Meteor.call("bookmarkUpdate", new_bookmark, _id, function(error, result) {
              if (error != undefined) $("#nuage").css("color", "rgb(188, 0, 0)");
              else $("#nuage").css("color", "");
              console.log(error);
            });

          } else {
            Meteor.setTimeout(function() {
              check(id);
            }, 4000);
          }
        });
      }
      Meteor.setTimeout(function() {
        check(id);
      }, 4000);
    });
  }
});

Template.bookmarkPage.helpers({
  domain: function() {
    var url = this.url;
    var matches = url.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i);
    var domain = matches && matches[1];
    return domain;
  },
  favicon: function() {
    var url = this.url;
    pathArray = url.split('/');
    var protocol = pathArray[0];
    var host = pathArray[2];
    var domain = protocol + '//' + host;
    return domain + "/favicon.ico";
  },
  ownBookmark: function() {
    return this.userId === Meteor.userId();
  }
});

Handlebars.registerHelper("prettifyDate", function(timestamp) {
  return new Date(timestamp).toLocaleDateString();
});

Handlebars.registerHelper("prettifyTags", function(tags) {
  var tagString = '';
  _.each(tags, function(tag) {
    tagString = '#' + tag + ' ' + tagString;
  })
  return tagString.trim();
});

Template.bookmarkPage.rendered = function() {

  $select = $('#groups').selectize({
    maxItems: null,
    valueField: 'id',
    labelField: 'title',
    searchField: 'title',
    options: [],
    create: false
  });

  var control = $select[0].selectize;

  var groups = Groups.find().fetch();

  for (var x = 0; x < groups.length; x++) {
    control.addOption({
      id: x,
      title: "@" + groups[x].name
    });
    var searchTerm = groups[x]._id,
      index = -1;
    for (var i = 0, len = this.data.groups.length; i < len; i++) {
      if (this.data.groups[i]._id === searchTerm) {
        index = i;
        break;
      }
    }

    if (index != -1) {
      control.addItem(x);
    }
  }
};<commit_msg>fixed group edition<commit_after>var $select;

Template.bookmarkPage.events({
  'submit form': function(events) {
    events.preventDefault();
    var user = Meteor.user();
    if (user !== null) {
      var tags = ParsedTags($(events.target).find('[name=tags]').val());
      var tabGroup = [];
      if ($select) {
        for (var i = 0; i < $select[0].selectize.items.length; i++) {
          tabGroup.push($select[0].selectize.getItem($select[0].selectize.items[i]).text());
        };
      }
      var groups = ParsedGroups(tabGroup);
      var bookmark = {
        url: $(events.target).find('[name=url]').val(),
        title: $(events.target).find('[name=title]').val(),
        description: $(events.target).find('[name=description]').val(),
        thumbnail: $(events.target).find('[name=thumbnail]').val(),
        tags: tags,
        groups: groups,
        dateCreated: this.dateCreated,
        dateModified: new Date(),
        counterView: this.counterView,
        counterClick: this.counterView,
        summary: this.summary,
        userId: this.userId
      };
      if (bookmark.url.indexOf("://") == -1) bookmark.url = "http://" + bookmark.url;
      CreatedTags(tags);
      if (this.url == bookmark.url || Bookmarks.find({
          url: bookmark.url,
          userId: bookmark.userId
        }).count() == 0) {
        Meteor.call('bookmarkUpdate', bookmark, this._id, function(error, result) {
          if (error) return alert(error.reason);
          if (!result.success) {
            DisplayErrorSubmit(result.message);
            return;
          }
          Router.go('/home');
        });
      } else {
        DisplayErrorSubmit("Url already use.");
      }
    } else {
      DisplayErrorSubmit("You need to be connected.");
    }
  },

  'click .btnDelete': function(e) {
    e.preventDefault();
    var idDelete = this._id;
    bootbox.dialog({
      message: "Do you want delete this bookmark",
      title: "Warning",
      buttons: {
        main: {
          label: "Cancel",
          className: "btn-primary"
        },
        danger: {
          label: "Delete",
          className: "btn-danger",
          callback: function() {
            Meteor.call("removeBookmark", idDelete);
            Router.go('/home');
          }
        }
      }
    });
  },

  'click .refreshView': function(e) {
    e.preventDefault();
    $("#nuage").css("color", "rgb(65, 65, 178)");

    var retry = 0;
    var new_bookmark = this;
    var _id = new_bookmark._id;
    new_bookmark = _.omit(new_bookmark, '_id');

    Meteor.call("analyzeText", new_bookmark.url, function(error, result) {
      var id = result;

      var check = function(id) {
        Meteor.call("getText", id, function(error, result) {
          retry++;
          if (retry >= 10) {

            console.log("analyzeText Failed");
            $("#nuage").css("color", "rgb(188, 0, 0)");

          } else if (result.status == "finished") {

            new_bookmark.summary = result;
            Meteor.call("bookmarkUpdate", new_bookmark, _id, function(error, result) {
              if (error != undefined) $("#nuage").css("color", "rgb(188, 0, 0)");
              else $("#nuage").css("color", "");
              console.log(error);
            });

          } else {
            Meteor.setTimeout(function() {
              check(id);
            }, 4000);
          }
        });
      }
      Meteor.setTimeout(function() {
        check(id);
      }, 4000);
    });
  }
});

Template.bookmarkPage.helpers({
  domain: function() {
    var url = this.url;
    var matches = url.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i);
    var domain = matches && matches[1];
    return domain;
  },
  favicon: function() {
    var url = this.url;
    pathArray = url.split('/');
    var protocol = pathArray[0];
    var host = pathArray[2];
    var domain = protocol + '//' + host;
    return domain + "/favicon.ico";
  },
  ownBookmark: function() {
    return this.userId === Meteor.userId();
  }
});

Handlebars.registerHelper("prettifyDate", function(timestamp) {
  return new Date(timestamp).toLocaleDateString();
});

Handlebars.registerHelper("prettifyTags", function(tags) {
  var tagString = '';
  _.each(tags, function(tag) {
    tagString = '#' + tag + ' ' + tagString;
  })
  return tagString.trim();
});

Template.bookmarkPage.rendered = function() {

  $select = $('#groups').selectize({
    maxItems: null,
    valueField: 'id',
    labelField: 'title',
    searchField: 'title',
    options: [],
    create: false
  });

  var control = $select[0].selectize;

  var groups = Groups.find().fetch();

  for (var x = 0; x < groups.length; x++) {
    control.addOption({
      id: x,
      title: "@" + groups[x].name
    });
    var searchTerm = groups[x]._id,
      index = -1;

    if (this.data.groups) {
      for (var i = 0, len = this.data.groups.length; i < len; i++) {
        if (this.data.groups[i]._id === searchTerm) {
          index = i;
          break;
        }
      }

      if (index != -1) {
        control.addItem(x);
      }
    }
  }
};<|endoftext|>


<commit_before>/****************************************************************************
 * Copyleft lostpassword                                                    *
 * [gdb.lost@gmail.com]                                                                                *
 *                                                                          *
 *                                                                          *
 * misTET is free software: you can redistribute it and/or modify           *
 * it under the terms of the GNU General Public License as published by     *
 * the Free Software Foundation, either version 3 of the License, or        *
 * (at your option) any later version.                                      *
 *                                                                          *
 * misTET is distributed in the hope that it will be useful,                *
 * but WITHOUT ANY WARRANTY; without even the implied warranty of           *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            *
 * GNU General Public License for more details.                             *
 *                                                                          *
 * You should have received a copy of the GNU General Public License        *
 * along with misTET.  If not, see <http://www.gnu.org/licenses/>.          *
 ****************************************************************************/

misTET.resources.modules.create("SyntaxHighlighter", {

    version: "0.1.1",

    initialize: function () {

        misTET.utils.include(this.root + "/scripts/shCore.js");
        misTET.utils.insertCSS(this.root + "/styles/shCore.css");
        misTET.utils.insertCSS(this.root + "/styles/shThemeEclipse.css");

        Event.observe(document, ":change", function () {
            misTET.modules.SyntaxHighlighter.execute();
        });
    },

    loadBrush: function (name) {
        if (misTET.utils.include(this.root+"/scripts/shBrush"+name+".js")) {

            SyntaxHighlighter.vars.discoveredBrushes = {};

            for (var brush in SyntaxHighlighter.brushes) {
                var aliases = SyntaxHighlighter.brushes[brush].aliases;

                    if (!aliases) {
                        continue;
                    }

                    aliases.each(function (alias) {
                        SyntaxHighlighter.vars.discoveredBrushes[alias] = brush;
                    });
            }
        }

    },

    execute: function(args) {

        var langs = {
                            'bash' : 'Bash',
                            'cpp' : 'Cpp',
                            'c' : 'Cpp',
                            'c#' : 'CSharp',
                            'css' : 'Css',
                            'delphi' : 'Delphi',
                            'java' : 'Java',
                            'js' : 'JScript',
                            'jscript' : 'JScript',
                            'javascript' : 'JSCript',
                            'php' : 'Php',
                            'python' : 'Python',
                            'py' : 'Python',
                            'ruby' : 'Ruby',
                            'rb' : 'Ruby',
                            'sql' : 'Sql',
                            'vb' : 'Vb',
                            'xml' : 'Xml'
            };

            if (!Object.isset(args)) {

                var re = new RegExp(/lan=(\w+)/)

                var pre = document.getElementsByTagName('pre');
                for (var i = 0; i < pre.length; i++) {
                    var current = pre[i].id;
                    var matches = current.match(re);
                    if (matches) {
                        var lan = matches[1];
                        pre[i].setAttribute("class", "brush: "+lan);
                                                pre[i].innerHTML = this.textFilter(pre[i]);
                        this.loadBrush(langs[lan]);
                        SyntaxHighlighter.highlight();
                    }
                }
                } else {
                    if (Object.isset(args['lan'])) {
                        SyntaxHighlighter.defaults["brush"] = args["lang"];
                        this.loadBrush(args['lan']);
                    }
                }

    },

    textFilter: function (element) {
        var text = element.innerHTML;
        text = text.replace(/</g, '<').replace(/>/g, '>');
        return text;
    }

});
<commit_msg>hating geany<commit_after>/****************************************************************************
 * Copyleft lostpassword                                                    *
 * [gdb.lost@gmail.com]                                                                                *
 *                                                                          *
 *                                                                          *
 * misTET is free software: you can redistribute it and/or modify           *
 * it under the terms of the GNU General Public License as published by     *
 * the Free Software Foundation, either version 3 of the License, or        *
 * (at your option) any later version.                                      *
 *                                                                          *
 * misTET is distributed in the hope that it will be useful,                *
 * but WITHOUT ANY WARRANTY; without even the implied warranty of           *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            *
 * GNU General Public License for more details.                             *
 *                                                                          *
 * You should have received a copy of the GNU General Public License        *
 * along with misTET.  If not, see <http://www.gnu.org/licenses/>.          *
 ****************************************************************************/

misTET.resources.modules.create("SyntaxHighlighter", {

    version: "0.1.1",

    initialize: function () {

        misTET.utils.include(this.root + "/scripts/shCore.js");
        misTET.utils.insertCSS(this.root + "/styles/shCore.css");
        misTET.utils.insertCSS(this.root + "/styles/shThemeEclipse.css");

        Event.observe(document, ":change", function () {
            misTET.modules.SyntaxHighlighter.execute();
        });
    },

    loadBrush: function (name) {
        if (misTET.utils.include(this.root+"/scripts/shBrush"+name+".js")) {

            SyntaxHighlighter.vars.discoveredBrushes = {};

            for (var brush in SyntaxHighlighter.brushes) {
                var aliases = SyntaxHighlighter.brushes[brush].aliases;

                    if (!aliases) {
                        continue;
                    }

                    aliases.each(function (alias) {
                        SyntaxHighlighter.vars.discoveredBrushes[alias] = brush;
                    });
            }
        }

    },

    execute: function(args) {

        var langs = {
                            'bash' : 'Bash',
                            'cpp' : 'Cpp',
                            'c' : 'Cpp',
                            'c#' : 'CSharp',
                            'css' : 'Css',
                            'delphi' : 'Delphi',
                            'java' : 'Java',
                            'js' : 'JScript',
                            'jscript' : 'JScript',
                            'javascript' : 'JSCript',
                            'php' : 'Php',
                            'python' : 'Python',
                            'py' : 'Python',
                            'ruby' : 'Ruby',
                            'rb' : 'Ruby',
                            'sql' : 'Sql',
                            'vb' : 'Vb',
                            'xml' : 'Xml'
            };

            if (!Object.isset(args)) {

                var re = new RegExp(/lan=(\w+)/)

                var pre = document.getElementsByTagName('pre');
                for (var i = 0; i < pre.length; i++) {
                    var current = pre[i].id;
                    var matches = current.match(re);
                    if (matches) {
                        var lan = matches[1];
                        pre[i].setAttribute("class", "brush: "+lan);
                        pre[i].innerHTML = this.textFilter(pre[i]);
                        this.loadBrush(langs[lan]);
                        SyntaxHighlighter.highlight();
                    }
                }
                } else {
                    if (Object.isset(args['lan'])) {
                        SyntaxHighlighter.defaults["brush"] = args["lang"];
                        this.loadBrush(args['lan']);
                    }
                }

    },

    textFilter: function (element) {
        var text = element.innerHTML;
        text = text.replace(/</g, '<').replace(/>/g, '>');
        return text;
    }

});
<|endoftext|>


<commit_before>import * as I     from 'immutable';
import * as THREE from 'three';
import * as React from 'react';

import * as F from '../arithmetic/float';
import _V from '../arithmetic/vector';
const V = _V(F, 0);

import * as surface from '../geometry/surface';

import Display3d from './Display3d';

const geometry = function geometry(vertices, faces) {
  const geom = new THREE.Geometry();

  vertices.forEach(v => {
    geom.vertices.push(new THREE.Vector3(v[0], v[1], v[2]));
  });

  faces.forEach(function(f) {
    f.forEach(function(v, i) {
      if (i > 0 && i+1 < f.length)
        geom.faces.push(new THREE.Face3(f[0], f[i], f[i+1]));
    });
  });

  geom.computeFaceNormals();
  geom.computeVertexNormals();
  return geom;
};

const model = material => {
  const s0 = {
    pos: I.fromJS([[0,0,0], [0,0,1], [0,1,0], [0,1,1],
                   [1,0,0], [1,0,1], [1,1,0], [1,1,1]]).map(V.make),
    faces: I.fromJS([[0,1,3,2],[5,4,6,7],
                     [1,0,4,5],[2,3,7,6],
                     [0,2,6,4],[3,1,5,7]]),
    isFixed: I.Range(0, 8).map(i => i < 4)
  };
  const s = I.Range(0, 3).reduce(s => surface.subD(s), s0);

  return new THREE.Mesh(
    geometry(s.pos.map(v => v.data.toJS()), s.faces.toJS()),
    material);
};

const light = function(color, x, y, z) {
  const light = new THREE.PointLight(color);

  light.position.set(x, y, z);

  return light;
};

const apply = function(v, A) {
  return V.make(M.times(M.make([v.data]), A).data.first());
};

const makeScene = function() {
  const scene  = new THREE.Scene();

  const material = new THREE.MeshPhongMaterial({
    color    : 0x0000ff,
    shininess: 50
  });

  const distance = 3;
  const camera = new THREE.PerspectiveCamera(25, 1, 0.1, 10000);
  camera.name = 'camera';
  camera.position.z = 5*distance;

  camera.add(light(0xffffff,  3*distance,  5*distance, distance));
  camera.add(light(0x666666, -5*distance, -5*distance, distance));

  const m = model(material);

  scene.add(m);
  scene.add(new THREE.WireframeHelper(m, 0x00ff00));
  scene.add(camera);

  return scene;
};

const App = React.createClass({
  displayName: 'App',

  getInitialState() {
    const scene = makeScene();
    const camera = scene.getObjectByName('camera');
    return {
      scene: scene,
      camera: camera,
      cameraParameters: { distance: camera.position.z }
    };
  },

  handleResize(data) {
    this.setState({
      width: window.innerWidth,
      height: window.innerHeight
    });
  },

  componentDidMount() {
    this.handleResize();
    window.addEventListener('resize', this.handleResize);
  },

  componentWillUnmount() {
    window.removeEventListener('resize', this.handleResize);
  },

  render() {
    return React.DOM.div(
      null,
      React.createElement(Display3d, {
        scene           : this.state.scene,
        camera          : this.state.camera,
        cameraParameters: this.state.cameraParameters,
        width           : this.state.width - 20,
        height          : this.state.height - 20
      }));
  }
});

React.render(React.createElement(App), document.getElementById('react-main'));
<commit_msg>use a diamond tile in subD surface drawing test<commit_after>import * as I     from 'immutable';
import * as THREE from 'three';
import * as React from 'react';

import * as F from '../arithmetic/float';
import _V from '../arithmetic/vector';
const V = _V(F, 0);

import * as surface from '../geometry/surface';

import Display3d from './Display3d';

const geometry = function geometry(vertices, faces) {
  const geom = new THREE.Geometry();

  vertices.forEach(v => {
    geom.vertices.push(new THREE.Vector3(v[0], v[1], v[2]));
  });

  faces.forEach(function(f) {
    f.forEach(function(v, i) {
      if (i > 0 && i+1 < f.length)
        geom.faces.push(new THREE.Face3(f[0], f[i], f[i+1]));
    });
  });

  geom.computeFaceNormals();
  geom.computeVertexNormals();
  return geom;
};

const diamond = {
  pos: I.fromJS([
    [-1,-1,-1], [-1,+1,+1], [+1,-1,+1], [+1,+1,-1],
    [-2, 0, 0], [ 0,-2, 0], [ 0, 0,-2],
    [+2, 0, 0], [ 0,+2, 0], [ 0, 0,+2]
  ]).map(V.make),

  faces: I.fromJS([
    [0, 4, 1, 8, 3, 6], [1, 4, 0, 5, 2, 9],
    [3, 8, 1, 9, 2, 7], [0, 6, 3, 7, 2, 5]
  ]),

  isFixed: I.Range(0, 10).map(i => true)
};

const split = ({ pos, faces, isFixed }) => {
  const rpos    = faces.flatMap(is => is.map(i => pos.get(i)));
  const rfixed  = faces.flatMap(is => is.map(i => isFixed.get(i)));
  const offsets = faces
    .reduce((a, is) => a.push(a.last() + is.size), I.List([0]));
  const rfaces  = faces
    .map((_, i) => I.List(I.Range(offsets.get(i), offsets.get(i+1))));

  return {
    pos    : rpos,
    isFixed: rfixed,
    faces  : rfaces
  };
};

const model = material => {
  const s = I.Range(0, 3).reduce(s => surface.subD(s), split(diamond));

  return new THREE.Mesh(
    geometry(s.pos.map(v => v.data.toJS()), s.faces.toJS()),
    material);
};

const light = function(color, x, y, z) {
  const light = new THREE.PointLight(color);

  light.position.set(x, y, z);

  return light;
};

const apply = function(v, A) {
  return V.make(M.times(M.make([v.data]), A).data.first());
};

const makeScene = function() {
  const scene  = new THREE.Scene();

  const material = new THREE.MeshPhongMaterial({
    color    : 0x0000ff,
    shininess: 50
  });

  const distance = 3;
  const camera = new THREE.PerspectiveCamera(25, 1, 0.1, 10000);
  camera.name = 'camera';
  camera.position.z = 5*distance;

  camera.add(light(0xffffff,  3*distance,  5*distance, distance));
  camera.add(light(0x666666, -5*distance, -5*distance, distance));

  const m = model(material);

  scene.add(m);
  scene.add(new THREE.WireframeHelper(m, 0x00ff00));
  scene.add(camera);

  return scene;
};

const App = React.createClass({
  displayName: 'App',

  getInitialState() {
    const scene = makeScene();
    const camera = scene.getObjectByName('camera');
    return {
      scene: scene,
      camera: camera,
      cameraParameters: { distance: camera.position.z }
    };
  },

  handleResize(data) {
    this.setState({
      width: window.innerWidth,
      height: window.innerHeight
    });
  },

  componentDidMount() {
    this.handleResize();
    window.addEventListener('resize', this.handleResize);
  },

  componentWillUnmount() {
    window.removeEventListener('resize', this.handleResize);
  },

  render() {
    return React.DOM.div(
      null,
      React.createElement(Display3d, {
        scene           : this.state.scene,
        camera          : this.state.camera,
        cameraParameters: this.state.cameraParameters,
        width           : this.state.width - 20,
        height          : this.state.height - 20
      }));
  }
});

React.render(React.createElement(App), document.getElementById('react-main'));
<|endoftext|>


<commit_before>import getScrollbarSize from 'dom-helpers/util/scrollbarSize';
import getDaysInMonth from 'date-fns/get_days_in_month';
import getDay from 'date-fns/get_day';

export const keyCodes = {
  command: 91,
  control: 17,
  down: 40,
  enter: 13,
  escape: 27,
  left: 37,
  right: 39,
  shift: 16,
  up: 38,
};

export function getMonth(year, month, weekStartsOn) {
  const rows = [];
  const monthDate = new Date(year, month, 1);
  const daysInMonth = getDaysInMonth(monthDate);
  const weekEndsOn = getEndOfWeekIndex(weekStartsOn);

  let dow = getDay(new Date(year, month, 1));
  let week = 0;

  for (let day = 1; day <= daysInMonth; day++) {
    if (!rows[week]) {
      rows[week] = [];
    }

    rows[week].push(day);

    if (dow === weekEndsOn) {
      week++;
    }

    dow = dow < 6 ? dow + 1 : 0;
  }

  return {
    date: monthDate,
    rows,
  };
}

function getWeek(year, date, weekStartsOn) {
  const yearStart = new Date(year, 0, 1); // 1st Jan of the Year

  return Math.ceil(
    ((date - yearStart) / 86400000 + yearStart.getDay() + 1 - weekStartsOn) / 7
  );
}

export function getWeeksInMonth(
  month,
  year = new Date().getFullYear(),
  weekStartsOn
) {
  const weekEndsOn = getEndOfWeekIndex(weekStartsOn);

  const firstOfMonth = new Date(year, month, 1);
  const firstWeekNumber = getWeek(year, firstOfMonth, weekStartsOn);

  const lastOfMonth = new Date(year, month + 1, 0); // Last date of the Month
  const lastWeekNumber = getWeek(year, lastOfMonth, weekStartsOn);

  let rowCount = lastWeekNumber - firstWeekNumber;

  // If the last week contains 7 days, we need to add an extra row
  if (lastOfMonth.getDay() === weekEndsOn) {
    rowCount++;
  }

  return rowCount;
}

function getEndOfWeekIndex(weekStartsOn) {
  const weekEndsOn = (weekStartsOn === 0) ? 6 : weekStartsOn - 1;

  return weekEndsOn;
}

export function getScrollSpeed(
  settings = {
    delay: 50, // in ms, higher means lower fidelity
  }
) {
  let lastPos;
  let newPos;
  let timer;
  let delta;

  function clear() {
    lastPos = null;
    delta = 0;
  }

  clear();

  return function(scrollY) {
    newPos = scrollY;
    if (lastPos != null) {
      delta = newPos - lastPos;
    }
    lastPos = newPos;
    clearTimeout(timer);
    timer = setTimeout(clear, settings.delay);
    return delta;
  };
}

export const scrollbarSize = getScrollbarSize();

export function emptyFn() { /* no-op */ }
<commit_msg>Refactoring and documenting utils<commit_after>import getScrollbarSize from 'dom-helpers/util/scrollbarSize';
import getDaysInMonth from 'date-fns/get_days_in_month';
import getDay from 'date-fns/get_day';

export const keyCodes = {
  command: 91,
  control: 17,
  down: 40,
  enter: 13,
  escape: 27,
  left: 37,
  right: 39,
  shift: 16,
  up: 38,
};

/**
 * Given a year and a month, returns the rows for that month to be iterated over
 * @param {Number} year - the year number
 * @param {Number} month - the index of the month
 * @param {Number} weekStartsOn - the index of the first day of the week (from 0 to 6)
 * @return {Object} - Returns the first day of the month and the rows of that month
 */
export function getMonth(year, month, weekStartsOn) {
  const rows = [];
  const monthDate = new Date(year, month, 1);
  const daysInMonth = getDaysInMonth(monthDate);
  const weekEndsOn = getEndOfWeekIndex(weekStartsOn);

  let dow = getDay(new Date(year, month, 1));
  let week = 0;

  for (let day = 1; day <= daysInMonth; day++) {
    if (!rows[week]) {
      rows[week] = [];
    }

    rows[week].push(day);

    if (dow === weekEndsOn) {
      week++;
    }

    dow = dow < 6 ? dow + 1 : 0;
  }

  return {
    date: monthDate,
    rows,
  };
}

/**
 * Get the localized week number of a given month based on the first day of the week
 * @param {Number} year - the year number
 * @param {Date} date - the date for which we're trying to get the week number
 * @param {Number} weekStartsOn - the index of the first day of the week (from 0 to 6)
 * @return {Object} - Returns the week index for that date
 */
function getWeek(year, date, weekStartsOn) {
  const yearStart = new Date(year, 0, 1); // 1st Jan of the Year

  return Math.ceil(
    ((date - yearStart) / (60 * 60 * 24 * 1000) +
      yearStart.getDay() +
      1 -
      weekStartsOn) /
      7,
  );
}

/**
 * Get the number of weeks in a given month to be able to calculate the height of that month
 * @param {Number} year - the year number
 * @param {Number} month - the index of the month
 * @param {Number} weekStartsOn - the index of the first day of the week (from 0 to 6)
 * @return {Number} - Returns the number of weeks for the given month
 */
export function getWeeksInMonth(
  month,
  year = new Date().getFullYear(),
  weekStartsOn,
) {
  const weekEndsOn = getEndOfWeekIndex(weekStartsOn);

  const firstOfMonth = new Date(year, month, 1);
  const firstWeekNumber = getWeek(year, firstOfMonth, weekStartsOn);

  const lastOfMonth = new Date(year, month + 1, 0); // Last date of the Month
  const lastWeekNumber = getWeek(year, lastOfMonth, weekStartsOn);

  let rowCount = lastWeekNumber - firstWeekNumber;

  // If the last week contains 7 days, we need to add an extra row
  if (lastOfMonth.getDay() === weekEndsOn) {
    rowCount++;
  }

  return rowCount;
}

/**
 * Helper to find out what day the week ends on given the localized start of the week
 * @param {Number} weekStartsOn - the index of the first day of the week (from 0 to 6)
 * @return {Number} - Returns the index of the day the week ends on
 */
function getEndOfWeekIndex(weekStartsOn) {
  const weekEndsOn = weekStartsOn === 0 ? 6 : weekStartsOn - 1;

  return weekEndsOn;
}

export class ScrollSpeed {
  clear = () => {
    this.lastPosition = null;
    this.delta = 0;
  };
  getScrollSpeed(scrollOffset) {
    if (this.lastPosition != null) {
      this.delta = scrollOffset - this.lastPosition;
    }
    this.lastPosition = scrollOffset;

    clearTimeout(this._timeout);
    this._timeout = setTimeout(this.clear, 50);

    return this.delta;
  }
}

export const scrollbarSize = getScrollbarSize();

export function emptyFn() {
  /* no-op */
}
<|endoftext|>


<commit_before>import cloneDeep from 'lodash/cloneDeep';
import defaultsDeep from 'lodash/defaultsDeep';
import set from 'lodash/set';
import isPlainObject from 'lodash/isPlainObject';

export * from './populate';

export function flatten(obj, parentPath) {
  return Object.keys(obj || {}).reduce((result, k) => {
    if ( ! obj.hasOwnProperty(k)) return result;
    const currentPath = parentPath ? parentPath + '.' + k : k;
    const currentProp = obj[k];

    //if (Array.isArray(currentProp)) {
      //const arrayResult = currentProp.map((value, i) => {
        //const arrayPath = `${currentPath}[${i}]`;
        //if (isPlainObject(value)) return flatten(value, arrayPath);
        //return { [arrayPath] : value };
      //});
      //return Object.assign({}, result, ...arrayResult);
    //}
    if (isPlainObject(currentProp)) {
      return {
        ...result,
        ...flatten(currentProp, currentPath),
      };
    }

    return {
      ...result,
      [currentPath]: currentProp,
    };
  }, {});
}

export function defaultTo(obj, defaults) {
  return defaultsDeep(cloneDeep(obj), defaults);
}

export function update(obj, newData) {
  const flattenedData = flatten(newData);
  return Object.keys(flattenedData).reduce((result, k) => {
    return set(result, k, flattenedData[k]);
  }, cloneDeep(obj));
}

export function arrayFrom(value) {
  return Array.isArray(value) ? value : [value];
}

export function log(value) {
  console.log(value);
  return value;
}
<commit_msg>Remove old populate code<commit_after>import cloneDeep from 'lodash/cloneDeep';
import defaultsDeep from 'lodash/defaultsDeep';
import set from 'lodash/set';
import isPlainObject from 'lodash/isPlainObject';

export function flatten(obj, parentPath) {
  return Object.keys(obj || {}).reduce((result, k) => {
    if ( ! obj.hasOwnProperty(k)) return result;
    const currentPath = parentPath ? parentPath + '.' + k : k;
    const currentProp = obj[k];

    //if (Array.isArray(currentProp)) {
      //const arrayResult = currentProp.map((value, i) => {
        //const arrayPath = `${currentPath}[${i}]`;
        //if (isPlainObject(value)) return flatten(value, arrayPath);
        //return { [arrayPath] : value };
      //});
      //return Object.assign({}, result, ...arrayResult);
    //}
    if (isPlainObject(currentProp)) {
      return {
        ...result,
        ...flatten(currentProp, currentPath),
      };
    }

    return {
      ...result,
      [currentPath]: currentProp,
    };
  }, {});
}

export function defaultTo(obj, defaults) {
  return defaultsDeep(cloneDeep(obj), defaults);
}

export function update(obj, newData) {
  const flattenedData = flatten(newData);
  return Object.keys(flattenedData).reduce((result, k) => {
    return set(result, k, flattenedData[k]);
  }, cloneDeep(obj));
}

export function arrayFrom(value) {
  return Array.isArray(value) ? value : [value];
}

export function log(value) {
  console.log(value);
  return value;
}
<|endoftext|>


<commit_before>import { actionTypes } from '../constants'

const { INIT_BY_PATH } = actionTypes

export const getWatchPath = (event, path) =>
  `${event}:${((path.substring(0, 1) === '/') ? '' : '/')}${path}`

/**
 * @description Set a new watcher
 * @param {Object} firebase - Internal firebase object
 * @param {String} event - Type of event to watch for
 * @param {String} path - Path to watch with watcher
 * @param {String} queryId - Id of query
 */
export const setWatcher = (firebase, event, path, queryId = undefined) => {
    const id = queryId || getQueryIdFromPath(path) || getWatchPath(event, path)

    if (event!='once'){
        if (firebase._.watchers[id]) {
            firebase._.watchers[id]++
        } else {
            firebase._.watchers[id] = 1
        }
    }

  return firebase._.watchers[id]
}

/**
 * @description Get count of currently attached watchers
 * @param {Object} firebase - Internal firebase object
 * @param {String} event - Type of event to watch for
 * @param {String} path - Path to watch with watcher
 * @param {String} queryId - Id of query
 */
export const getWatcherCount = (firebase, event, path, queryId = undefined) => {
  const id = queryId || getQueryIdFromPath(path) || getWatchPath(event, path)
  return firebase._.watchers[id]
}

/**
 * @description Remove/Unset a watcher
 * @param {Object} firebase - Internal firebase object
 * @param {String} event - Type of event to watch for
 * @param {String} path - Path to watch with watcher
 * @param {String} queryId - Id of query
 */
export const unsetWatcher = (firebase, dispatch, event, path, queryId = undefined) => {
  const id = queryId || getQueryIdFromPath(path) || getWatchPath(event, path)
  path = path.split('#')[0]

  if (firebase._.watchers[id] <= 1) {
    delete firebase._.watchers[id]
      if (event!='once'){
          firebase.database().ref().child(path).off(event)
          dispatch({
              type: INIT_BY_PATH,
              path
          })
      }
  } else if (firebase._.watchers[id]) {
    firebase._.watchers[id]--
  }
}

/**
 * @description Get query id from query path
 * @param {String} path - Path from which to get query id
 */
export const getQueryIdFromPath = (path) => {
    const origPath = path
    let pathSplitted = path.split('#')
    path = pathSplitted[0]

    const isQuery = pathSplitted.length > 1
    const queryParams = isQuery ? pathSplitted[1].split('&') : []
    const queryId = isQuery ? queryParams.map((param) => {
        let splittedParam = param.split('=')
        if (splittedParam[0] === 'queryId') {
            return splittedParam[1]
        }
    }).filter(q => q) : undefined
    return (queryId && queryId.length > 0)
        ? queryId[0]
        : ((isQuery) ? origPath : undefined)
}

/**
 * @description Modify query to include methods based on query parameters (such as orderByChild)
 * @param {Array} queryParams - Array of query parameters to apply to query
 * @param {Object} query - Query object on which to apply query parameters
 */
export const applyParamsToQuery = (queryParams, query) => {
  let doNotParse = false
  if (queryParams) {
    queryParams.forEach(param => {
      param = param.split('=')
      switch (param[0]) {
        case 'orderByValue':
          query = query.orderByValue()
          doNotParse = true
          break
        case 'orderByPriority':
          query = query.orderByPriority()
          doNotParse = true
          break
        case 'orderByKey':
          query = query.orderByKey()
          doNotParse = true
          break
        case 'orderByChild':
          query = query.orderByChild(param[1])
          break
        case 'limitToFirst':
          // TODO: Handle number not being passed as param
          query = query.limitToFirst(parseInt(param[1], 10))
          break
        case 'limitToLast':
          // TODO: Handle number not being passed as param
          query = query.limitToLast(parseInt(param[1], 10))
          break
        case 'equalTo':
          let equalToParam = !doNotParse ? parseInt(param[1], 10) || param[1] : param[1]
          equalToParam = equalToParam === 'null' ? null : equalToParam
          query = param.length === 3
            ? query.equalTo(equalToParam, param[2])
            : query.equalTo(equalToParam)
          break
        case 'startAt':
          let startAtParam = !doNotParse ? parseInt(param[1], 10) || param[1] : param[1]
          startAtParam = startAtParam === 'null' ? null : startAtParam
          query = param.length === 3
            ? query.startAt(startAtParam, param[2])
            : query.startAt(startAtParam)
          break
        case 'endAt':
          let endAtParam = !doNotParse ? parseInt(param[1], 10) || param[1] : param[1]
          endAtParam = endAtParam === 'null' ? null : endAtParam
          query = param.length === 3
            ? query.endAt(endAtParam, param[2])
            : query.endAt(endAtParam)
          break
      }
    })
  }

  return query
}
<commit_msg>add event to queued for watchers<commit_after>import { actionTypes } from '../constants'

const { INIT_BY_PATH } = actionTypes

export const getWatchPath = (event, path) =>
  `${event}:${((path.substring(0, 1) === '/') ? '' : '/')}${path}`

/**
 * @description Set a new watcher
 * @param {Object} firebase - Internal firebase object
 * @param {String} event - Type of event to watch for
 * @param {String} path - Path to watch with watcher
 * @param {String} queryId - Id of query
 */
export const setWatcher = (firebase, event, path, queryId = undefined) => {
    const id = queryId+'_'+event || getQueryIdFromPath(path,event) || getWatchPath(event, path)

    if (event!='once'){
        if (firebase._.watchers[id]) {
            firebase._.watchers[id]++
        } else {
            firebase._.watchers[id] = 1
        }
    }

  return firebase._.watchers[id]
}

/**
 * @description Get count of currently attached watchers
 * @param {Object} firebase - Internal firebase object
 * @param {String} event - Type of event to watch for
 * @param {String} path - Path to watch with watcher
 * @param {String} queryId - Id of query
 */
export const getWatcherCount = (firebase, event, path, queryId = undefined) => {
    const id = queryId+'_'+event || getQueryIdFromPath(path,event) || getWatchPath(event, path)
    return firebase._.watchers[id]
}

/**
 * @description Remove/Unset a watcher
 * @param {Object} firebase - Internal firebase object
 * @param {String} event - Type of event to watch for
 * @param {String} path - Path to watch with watcher
 * @param {String} queryId - Id of query
 */
export const unsetWatcher = (firebase, dispatch, event, path, queryId = undefined) => {
    const id = queryId+'_'+event || getQueryIdFromPath(path,event) || getWatchPath(event, path)
    path = path.split('#')[0]

  if (firebase._.watchers[id] <= 1) {
    delete firebase._.watchers[id]
      if (event!='once'){
          firebase.database().ref().child(path).off(event)
          dispatch({
              type: INIT_BY_PATH,
              path
          })
      }
  } else if (firebase._.watchers[id]) {
    firebase._.watchers[id]--
  }
}

/**
 * @description Get query id from query path
 * @param {String} path - Path from which to get query id
 */
export const getQueryIdFromPath = (path,event=undefined) => {
    const origPath = path
    let pathSplitted = path.split('#')
    path = pathSplitted[0]

    const isQuery = pathSplitted.length > 1
    const queryParams = isQuery ? pathSplitted[1].split('&') : []
    const queryId = isQuery ? queryParams.map((param) => {
        let splittedParam = param.split('=')
        if (splittedParam[0] === 'queryId') {
            return splittedParam[1]
        }
    }).filter(q => q) : undefined
    return (queryId && queryId.length > 0)
        ? (event ? queryId[0]+'_'+event : queryId[0])
        : ((isQuery) ? origPath : undefined)
}

/**
 * @description Modify query to include methods based on query parameters (such as orderByChild)
 * @param {Array} queryParams - Array of query parameters to apply to query
 * @param {Object} query - Query object on which to apply query parameters
 */
export const applyParamsToQuery = (queryParams, query) => {
  let doNotParse = false
  if (queryParams) {
    queryParams.forEach(param => {
      param = param.split('=')
      switch (param[0]) {
        case 'orderByValue':
          query = query.orderByValue()
          doNotParse = true
          break
        case 'orderByPriority':
          query = query.orderByPriority()
          doNotParse = true
          break
        case 'orderByKey':
          query = query.orderByKey()
          doNotParse = true
          break
        case 'orderByChild':
          query = query.orderByChild(param[1])
          break
        case 'limitToFirst':
          // TODO: Handle number not being passed as param
          query = query.limitToFirst(parseInt(param[1], 10))
          break
        case 'limitToLast':
          // TODO: Handle number not being passed as param
          query = query.limitToLast(parseInt(param[1], 10))
          break
        case 'equalTo':
          let equalToParam = !doNotParse ? parseInt(param[1], 10) || param[1] : param[1]
          equalToParam = equalToParam === 'null' ? null : equalToParam
          query = param.length === 3
            ? query.equalTo(equalToParam, param[2])
            : query.equalTo(equalToParam)
          break
        case 'startAt':
          let startAtParam = !doNotParse ? parseInt(param[1], 10) || param[1] : param[1]
          startAtParam = startAtParam === 'null' ? null : startAtParam
          query = param.length === 3
            ? query.startAt(startAtParam, param[2])
            : query.startAt(startAtParam)
          break
        case 'endAt':
          let endAtParam = !doNotParse ? parseInt(param[1], 10) || param[1] : param[1]
          endAtParam = endAtParam === 'null' ? null : endAtParam
          query = param.length === 3
            ? query.endAt(endAtParam, param[2])
            : query.endAt(endAtParam)
          break
      }
    })
  }

  return query
}
<|endoftext|>


<commit_before>fullscreen = function() {
	screenfull.toggle();
}

Polymer('character-card', {
	response: "",
	character: {
		"Might":"",
		"Speed":"",
		"Knowledge":"",
		"Sanity":"",
		"MightIndex":"",
		"SpeedIndex":"",
		"KnowledgeIndex":"",
		"SanityIndex":""
	},

	updateStat: function(attribute, direction) {
		switch(attribute) {
			case "might":
				switch(direction) {
					case "up":
						console.log("up");
						if(this.character.MightIndex < 8) {
							document.querySelector("character-card::shadow #might-score").innerHTML = this.character.Might[++this.character.MightIndex];
						}
						break;
					case "down":
						console.log("down");
						if(this.character.MightIndex > 0) {
							document.querySelector("character-card::shadow #might-score").innerHTML = this.character.Might[--this.character.MightIndex];
						}
						if(!this.character.MightIndex) {
							alert("You've died.");
						}
						break;
				}
				document.querySelector("character-card::shadow #might-index").innerHTML = this.character.MightIndex;
				break;
			case "speed":
				switch(direction) {
					case "up":
						console.log("up");
						if(this.character.SpeedIndex < 8) {
							document.querySelector("character-card::shadow #speed-score").innerHTML = this.character.Speed[++this.character.SpeedIndex];
						}
						break;
					case "down":
						console.log("down");
						if(this.character.SpeedIndex > 0) {
							document.querySelector("character-card::shadow #speed-score").innerHTML = this.character.Speed[--this.character.SpeedIndex];
						}
						if(!this.character.SpeedIndex) {
							alert("You've died.");
						}
						break;
				}
				document.querySelector("character-card::shadow #speed-index").innerHTML = this.character.SpeedIndex;
				break;
			case "knowledge":
				switch(direction) {
					case "up":
						console.log("up");
						if(this.character.KnowledgeIndex < 8) {
							document.querySelector("character-card::shadow #knowledge-score").innerHTML = this.character.Knowledge[++this.character.KnowledgeIndex];
						}
						break;
					case "down":
						console.log("down");
						if(this.character.KnowledgeIndex > 0) {
							document.querySelector("character-card::shadow #knowledge-score").innerHTML = this.character.Knowledge[--this.character.KnowledgeIndex];
						}
						if(!this.character.KnowledgeIndex) {
							alert("You've died.");
						}
						break;
				}
				document.querySelector("character-card::shadow #knowledge-index").innerHTML = this.character.KnowledgeIndex;
				break;
			case "sanity":
				switch(direction) {
					case "up":
						console.log("up");
						if(this.character.SanityIndex < 8) {
							document.querySelector("character-card::shadow #sanity-score").innerHTML = this.character.Sanity[++this.character.SanityIndex];
						}
						break;
					case "down":
						console.log("down");
						if(this.character.SanityIndex > 0) {
							document.querySelector("character-card::shadow #sanity-score").innerHTML = this.character.Sanity[--this.character.SanityIndex];
						}
						if(!this.character.SanityIndex) {
							alert("You've died.");
						}
						break;
				}
				document.querySelector("character-card::shadow #sanity-index").innerHTML = this.character.SanityIndex;
				break;
		}
	},

	clickHandler(event) {
		attribute = event.target.attributes['name'].value;
		direction = event.target.attributes['class'].value;
		self.updateStat(attribute, direction);
	}

	setHeader: function(character) {
		switch(character) {
			case "ox-bellows":
			case "darrin-flash-williams":
				color = "#F44336";
				break;
			case "father-rhinehardt":
			case "professor-longfellow":
				color = "#9E9E9E";
				break;
			case "vivian-lopez":
			case "madame-zostra":
				color = "#3F51B5";
				break;
			case "peter-akimoto":
			case "brandon-jaspers":
				color = "#8BC34A";
				break;
			case "missy-dobourde":
			case "zoe-ingstrom":
				color = "#FFC107";
				break;
			case "jenny-leclerc":
			case "heather-granville":
				color = "#9C27B0";
				break;
			default:
				color = "#000000";
		}

		document.querySelector("character-card::shadow #character-name").style.backgroundColor = color;
	},

	setCardValues: function(character) {
		characters = [
				"ox-bellows",
				"father-rhinehardt",
				"vivian-lopez",
				"peter-akimoto",
				"missy-dobourde",
				"jenny-leclerc",
				"darrin-flash-williams",
				"professor-longfellow",
				"madame-zostra",
				"brandon-jaspers",
				"zoe-ingstrom",
				"heather-granville"
		]

		selection = this.response.Characters[characters.indexOf(character)];

		document.querySelector("character-card::shadow #character-name").innerHTML = selection.Name;
		document.querySelector("character-card::shadow #age").innerHTML = selection.Age;
		document.querySelector("character-card::shadow #height").innerHTML = selection.Height;
		document.querySelector("character-card::shadow #weight").innerHTML = selection.Weight;
		document.querySelector("character-card::shadow #birthday").innerHTML = selection.Birthday;
		document.querySelector("character-card::shadow #hobbies").innerHTML = selection.Hobbies;
		document.querySelector("character-card::shadow #might-score").innerHTML = selection.Might[selection.BaseMightIndex];
		document.querySelector("character-card::shadow #speed-score").innerHTML = selection.Speed[selection.BaseSpeedIndex];
		document.querySelector("character-card::shadow #knowledge-score").innerHTML = selection.Knowledge[selection.BaseKnowledgeIndex];
		document.querySelector("character-card::shadow #sanity-score").innerHTML = selection.Sanity[selection.BaseSanityIndex];
		document.querySelector("character-card::shadow #might-index").innerHTML = selection.BaseMightIndex;
		document.querySelector("character-card::shadow #speed-index").innerHTML = selection.BaseSpeedIndex;
		document.querySelector("character-card::shadow #knowledge-index").innerHTML = selection.BaseKnowledgeIndex;
		document.querySelector("character-card::shadow #sanity-index").innerHTML = selection.BaseSanityIndex;

		this.character.Might = selection.Might;
		this.character.Speed = selection.Speed;
		this.character.Knowledge = selection.Knowledge;
		this.character.Sanity = selection.Sanity;
		this.character.MightIndex = selection.BaseMightIndex
		this.character.SpeedIndex = selection.BaseSpeedIndex
		this.character.KnowledgeIndex = selection.BaseKnowledgeIndex
		this.character.SanityIndex = selection.BaseSanityIndex
	},

	getCharacter: function(character) {
		self = this;

		this.setHeader(character);

		request = new XMLHttpRequest();
		request.open("GET", "/polymer-character-card/elements/character-card/characters.json", true);

		response = "";
		request.onreadystatechange = function() {
			if(request.readyState === request.DONE) {
				status = request.status;

				if((status >= 200 && status < 300) || status === 304 || status === 0) {
					self.response = JSON.parse(request.responseText);
					self.setCardValues(character);
				}
			}
		};
		request.send();
	},

	attached: function() {
		self = this;

		ups = document.querySelectorAll("character-card::shadow .up");

		for (var i = ups.length - 1; i >= 0; i--) {
			ups[i].addEventListener("click", clickHandler);
		};

		downs = document.querySelectorAll("character-card::shadow .down");

		for (var j = downs.length - 1; j >= 0; j--) {
			downs[j].addEventListener("click", clickHandler);
		};

		//this.getCharacter("darrin-flash-williams");
	},
});
<commit_msg>Update character-card.js<commit_after>fullscreen = function() {
	screenfull.toggle();
}

Polymer('character-card', {
	response: "",
	character: {
		"Might":"",
		"Speed":"",
		"Knowledge":"",
		"Sanity":"",
		"MightIndex":"",
		"SpeedIndex":"",
		"KnowledgeIndex":"",
		"SanityIndex":""
	},

	updateStat: function(attribute, direction) {
		switch(attribute) {
			case "might":
				switch(direction) {
					case "up":
						console.log("up");
						if(this.character.MightIndex < 8) {
							document.querySelector("character-card::shadow #might-score").innerHTML = this.character.Might[++this.character.MightIndex];
						}
						break;
					case "down":
						console.log("down");
						if(this.character.MightIndex > 0) {
							document.querySelector("character-card::shadow #might-score").innerHTML = this.character.Might[--this.character.MightIndex];
						}
						if(!this.character.MightIndex) {
							alert("You've died.");
						}
						break;
				}
				document.querySelector("character-card::shadow #might-index").innerHTML = this.character.MightIndex;
				break;
			case "speed":
				switch(direction) {
					case "up":
						console.log("up");
						if(this.character.SpeedIndex < 8) {
							document.querySelector("character-card::shadow #speed-score").innerHTML = this.character.Speed[++this.character.SpeedIndex];
						}
						break;
					case "down":
						console.log("down");
						if(this.character.SpeedIndex > 0) {
							document.querySelector("character-card::shadow #speed-score").innerHTML = this.character.Speed[--this.character.SpeedIndex];
						}
						if(!this.character.SpeedIndex) {
							alert("You've died.");
						}
						break;
				}
				document.querySelector("character-card::shadow #speed-index").innerHTML = this.character.SpeedIndex;
				break;
			case "knowledge":
				switch(direction) {
					case "up":
						console.log("up");
						if(this.character.KnowledgeIndex < 8) {
							document.querySelector("character-card::shadow #knowledge-score").innerHTML = this.character.Knowledge[++this.character.KnowledgeIndex];
						}
						break;
					case "down":
						console.log("down");
						if(this.character.KnowledgeIndex > 0) {
							document.querySelector("character-card::shadow #knowledge-score").innerHTML = this.character.Knowledge[--this.character.KnowledgeIndex];
						}
						if(!this.character.KnowledgeIndex) {
							alert("You've died.");
						}
						break;
				}
				document.querySelector("character-card::shadow #knowledge-index").innerHTML = this.character.KnowledgeIndex;
				break;
			case "sanity":
				switch(direction) {
					case "up":
						console.log("up");
						if(this.character.SanityIndex < 8) {
							document.querySelector("character-card::shadow #sanity-score").innerHTML = this.character.Sanity[++this.character.SanityIndex];
						}
						break;
					case "down":
						console.log("down");
						if(this.character.SanityIndex > 0) {
							document.querySelector("character-card::shadow #sanity-score").innerHTML = this.character.Sanity[--this.character.SanityIndex];
						}
						if(!this.character.SanityIndex) {
							alert("You've died.");
						}
						break;
				}
				document.querySelector("character-card::shadow #sanity-index").innerHTML = this.character.SanityIndex;
				break;
		}
	},

	clickHandler(event) {
		attribute = event.target.attributes['name'].value;
		direction = event.target.attributes['class'].value;
		self.updateStat(attribute, direction);
	},

	setHeader: function(character) {
		switch(character) {
			case "ox-bellows":
			case "darrin-flash-williams":
				color = "#F44336";
				break;
			case "father-rhinehardt":
			case "professor-longfellow":
				color = "#9E9E9E";
				break;
			case "vivian-lopez":
			case "madame-zostra":
				color = "#3F51B5";
				break;
			case "peter-akimoto":
			case "brandon-jaspers":
				color = "#8BC34A";
				break;
			case "missy-dobourde":
			case "zoe-ingstrom":
				color = "#FFC107";
				break;
			case "jenny-leclerc":
			case "heather-granville":
				color = "#9C27B0";
				break;
			default:
				color = "#000000";
		}

		document.querySelector("character-card::shadow #character-name").style.backgroundColor = color;
	},

	setCardValues: function(character) {
		characters = [
				"ox-bellows",
				"father-rhinehardt",
				"vivian-lopez",
				"peter-akimoto",
				"missy-dobourde",
				"jenny-leclerc",
				"darrin-flash-williams",
				"professor-longfellow",
				"madame-zostra",
				"brandon-jaspers",
				"zoe-ingstrom",
				"heather-granville"
		]

		selection = this.response.Characters[characters.indexOf(character)];

		document.querySelector("character-card::shadow #character-name").innerHTML = selection.Name;
		document.querySelector("character-card::shadow #age").innerHTML = selection.Age;
		document.querySelector("character-card::shadow #height").innerHTML = selection.Height;
		document.querySelector("character-card::shadow #weight").innerHTML = selection.Weight;
		document.querySelector("character-card::shadow #birthday").innerHTML = selection.Birthday;
		document.querySelector("character-card::shadow #hobbies").innerHTML = selection.Hobbies;
		document.querySelector("character-card::shadow #might-score").innerHTML = selection.Might[selection.BaseMightIndex];
		document.querySelector("character-card::shadow #speed-score").innerHTML = selection.Speed[selection.BaseSpeedIndex];
		document.querySelector("character-card::shadow #knowledge-score").innerHTML = selection.Knowledge[selection.BaseKnowledgeIndex];
		document.querySelector("character-card::shadow #sanity-score").innerHTML = selection.Sanity[selection.BaseSanityIndex];
		document.querySelector("character-card::shadow #might-index").innerHTML = selection.BaseMightIndex;
		document.querySelector("character-card::shadow #speed-index").innerHTML = selection.BaseSpeedIndex;
		document.querySelector("character-card::shadow #knowledge-index").innerHTML = selection.BaseKnowledgeIndex;
		document.querySelector("character-card::shadow #sanity-index").innerHTML = selection.BaseSanityIndex;

		this.character.Might = selection.Might;
		this.character.Speed = selection.Speed;
		this.character.Knowledge = selection.Knowledge;
		this.character.Sanity = selection.Sanity;
		this.character.MightIndex = selection.BaseMightIndex
		this.character.SpeedIndex = selection.BaseSpeedIndex
		this.character.KnowledgeIndex = selection.BaseKnowledgeIndex
		this.character.SanityIndex = selection.BaseSanityIndex
	},

	getCharacter: function(character) {
		self = this;

		this.setHeader(character);

		request = new XMLHttpRequest();
		request.open("GET", "/polymer-character-card/elements/character-card/characters.json", true);

		response = "";
		request.onreadystatechange = function() {
			if(request.readyState === request.DONE) {
				status = request.status;

				if((status >= 200 && status < 300) || status === 304 || status === 0) {
					self.response = JSON.parse(request.responseText);
					self.setCardValues(character);
				}
			}
		};
		request.send();
	},

	attached: function() {
		self = this;

		ups = document.querySelectorAll("character-card::shadow .up");

		for (var i = ups.length - 1; i >= 0; i--) {
			ups[i].addEventListener("click", clickHandler);
		};

		downs = document.querySelectorAll("character-card::shadow .down");

		for (var j = downs.length - 1; j >= 0; j--) {
			downs[j].addEventListener("click", clickHandler);
		};

		//this.getCharacter("darrin-flash-williams");
	},
});
<|endoftext|>


<commit_before>const queue = require('../../workers/queue');
const models = require("../../../models");
const i18n = require('../../utils/i18n');
const async = require('async');
const moment = require('moment');
const log = require('../../utils/logger');
const _ = require('lodash');

const moderationItemsActionMaster = (req, res, options) => {
  options.model.find({
    where: {
      id: req.params.itemId
    },
    include: options.includes
  }).then(item => {
    if (item) {
      if (options.actionType==='delete') {
        item.deleted = true;
      } else if (options.actionType==='approve') {
        item.status = 'published';
        item.counter_flags = 0;
      } else if (options.actionType==='clearFlags') {
        item.counter_flags = 0;
      }
      item.save().then( () => {
        res.sendStatus(200);
      }).catch( error => {
        log.error("Error deleting moderated item", { error });
        res.sendStatus(500);
      });
    }
  }).catch(error => {
    log.error("Error deleting moderated item", { error });
    res.sendStatus(500);
  })
};

const domainIncludes = (domainId) => {
  return [
    {
      model: models.Group,
      required: true,
      include: [
        {
          model: models.Community,
          required: true,
          include: [
            {
              model: models.Domain,
              where: {
                id: domainId
              },
              required: true
            }
          ]
        }
      ]
    }
  ];
};

const communityIncludes = (communityId) => {
  return [
    {
      model: models.Group,
      required: true,
      include: [
        {
          model: models.Community,
          required: true,
          where: {
            id: communityId
          }
        }
      ]
    }
  ];
};

const groupIncludes = (groupId) => {
  return [
    {
      model: models.Group,
      required: true,
      where: {
        id: groupId
      }
    }
  ];
};

const userIncludes = (userId) => {
  return [
    {
      model: models.User,
      required: true,
      where: {
        id: userId
      }
    }
  ];
};

const moderationItemsActionDomain = (req, res, model, actionType) => {
  moderationItemsActionMaster(req, res, { model, actionType, includes: domainIncludes(req.params.domainId) });
};

const moderationItemsActionCommunity = (req, res, model, actionType) => {
  moderationItemsActionMaster(req, res, { model, actionType, includes: communityIncludes(req.params.communityId) });
};

const moderationItemsActionGroup = (req, res, model, actionType) => {
  moderationItemsActionMaster(req, res, { model, actionType, includes: groupIncludes(req.params.groupId) });
};

const moderationItemsActionUser = (req, res, model, actionType) => {
  moderationItemsActionMaster(req, res, { model, actionType, includes: userIncludes(req.params.userId) });
};

const _toPercent = number => {
  if (number) {
    return Math.round(number*100)+'%';
  }
};

const getPushItem = (type, model) => {
  let source, toxicityScore, latestContent = null, severeToxicityScore, lastReportedAt;

  if (model.data && model.data.moderation) {
    const moderation = model.data.moderation;

    if (moderation.toxicityScore) {
      toxicityScore = _toPercent(moderation.toxicityScore);
    }

    if (moderation.severeToxicityScore) {
      severeToxicityScore = _toPercent(moderation.severeToxicityScore);
    }
    if (moderation.lastReportedBy &&
      moderation.lastReportedBy.length > 0) {
      source = moderation.lastReportedBy[0].source;
      lastReportedAtDate = moderation.lastReportedBy[moderation.lastReportedBy.length-1].date;
    }
  }

  if (type==='point') {
    latestContent = model.PointRevisions[model.PointRevisions.length-1].content;
  }

  return {
    id: model.id,
    created_at: model.created_at,
    formatted_date: moment(model.created_at).format("DD/MM/YY HH:mm"),
    type: type,
    counter_flags: model.counter_flags,
    status: model.status,
    user_id: model.user_id,
    toxicityScore: toxicityScore,
    severeToxicityScore: severeToxicityScore,
    source: source,
    lastReportedAtDate: lastReportedAtDate ? moment(lastReportedAtDate).format("DD/MM/YY HH:mm") : null,
    user_email: model.User.email,
    cover_media_type: model.cover_media_type,
    is_post: type==='post',
    is_point: type==='point',
    title: model.name,
    post_id: model.post_id,
    Group: model.Group,
    language: model.language,
    name: model.name,
    description: model.description,
    moderation_data: { moderation: model.data ? model.data.moderation : null },
    content: type==='post' ? (model.name + ' ' + model.description) : model.content,
    PostVideos: model.PostVideos,
    PostAudios: model.PostAudios,
    PostHeaderImages: model.PostHeaderImages,
    PointVideos: model.PointVideos,
    PointAudios: model.PointAudios,
    PointRevisions: model.PointRevisions,
    latestContent: latestContent
  };
};

const getItems = (posts, points) => {
  let items = [];
  _.forEach(posts, post => {
    items.push(getPushItem('post', post));
  });
  _.forEach(points, point => {
    items.push(getPushItem('point', point));
  });
  items = _.orderBy(items,['status', 'counter_flags', 'created_at'], ['asc','desc','asc']);
  return items;
};

const getModelModeration = (options, callback) => {
  options.model.unscoped().findAll({
    where: {
      deleted: false,
      $or: [
        {
          counter_flags: {
            $gt: options.allContent ? -1 : 0
          },
        },
        {
          status: "in_moderation_queue"
        }
      ],
    },
    order: options.order,
    include: options.includes
  }).then(items => {
    callback(null, items);
  }).catch(error => {
    callback(error);
  })
};

const getAllModeratedItemsByMaster = (options, callback) => {
  let posts, points;

  const postBaseIncludes = _.cloneDeep(options.includes);
  const pointBaseIncludes = _.cloneDeep(options.includes);

  async.series([
    parallelCallback => {
      let postIncludes = postBaseIncludes.concat([
        {
          model: models.Image,
          required: false,
          as: 'PostHeaderImages'
        },
        {
          model: models.Video,
          required: false,
          attributes: ['id','formats','updated_at','viewable','public_meta'],
          as: 'PostVideos',
          include: [
            {
              model: models.Image,
              as: 'VideoImages',
              attributes:["formats",'updated_at'],
              required: false
            },
          ]
        },
        {
          model: models.Audio,
          required: false,
          attributes: ['id','formats','updated_at','listenable'],
          as: 'PostAudios',
        }
      ]);

      if (!options.userId) {
        postIncludes = postIncludes.concat([ { model: models.User }]);
      } else {
        postIncludes = postIncludes.concat([ { model: models.Group }]);
      }

      const order = [
        [ { model: models.Image, as: 'PostHeaderImages' } ,'updated_at', 'asc' ],
        [ { model: models.Video, as: "PostVideos" }, 'updated_at', 'desc' ],
        [ { model: models.Audio, as: "PostAudios" }, 'updated_at', 'desc' ],
        [ { model: models.Video, as: "PostVideos" }, { model: models.Image, as: 'VideoImages' } ,'updated_at', 'asc' ]
      ];

      getModelModeration(_.merge(_.cloneDeep(options), {model: models.Post, includes: postIncludes, order }), (error, postsIn) => {
        parallelCallback(error);
        posts = postsIn;
      })
    },
    parallelCallback => {
      let pointIncludes = pointBaseIncludes.concat([
        {
          model: models.Video,
          required: false,
          attributes: ['id','formats','updated_at','viewable','public_meta'],
          as: 'PointVideos',
          include: [
            {
              model: models.Image,
              as: 'VideoImages',
              attributes:["formats",'updated_at'],
              required: false
            },
          ]
        },
        {
          model: models.Audio,
          required: false,
          attributes: ['id','formats','updated_at','listenable'],
          as: 'PointAudios'
        },
        {
          model: models.PointRevision,
          attributes: { exclude: ['ip_address', 'user_agent'] },
          required: false
        }
      ]);

      if (!options.userId) {
        pointIncludes = pointIncludes.concat([ { model: models.User }]);
      }

      const order = [
        [ { model: models.Video, as: "PointVideos" }, 'updated_at', 'desc' ],
        [ { model: models.Audio, as: "PointAudios" }, 'updated_at', 'desc' ],
        [ models.PointRevision, 'created_at', 'asc' ],
        [ { model: models.Video, as: "PointVideos" }, { model: models.Image, as: 'VideoImages' } ,'updated_at', 'asc' ]
      ];

      getModelModeration(_.merge(_.cloneDeep(options), {model: models.Point, includes: pointIncludes, order }), (error, pointsIn) => {
        points = pointsIn;
        parallelCallback(error);
      })
    }
  ], error => {
    callback(error, getItems(posts, points));
  });
};

const getAllModeratedItemsByDomain = (options, callback) => {
  getAllModeratedItemsByMaster(_.merge(options, {includes: domainIncludes(options.domainId) }), callback);
};

const getAllModeratedItemsByCommunity = (options, callback) => {
  getAllModeratedItemsByMaster(_.merge(options, {includes: communityIncludes(options.communityId) }), callback);
};

const getAllModeratedItemsByGroup = (options, callback) => {
  getAllModeratedItemsByMaster(_.merge(options, {includes: groupIncludes(options.groupId) }), callback);
};

const getAllModeratedItemsByUser = (options, callback) => {
  getAllModeratedItemsByMaster(_.merge(options, {includes: userIncludes(options.userId) }), callback);
};

module.exports = {
  moderationItemsActionDomain,
  moderationItemsActionCommunity,
  moderationItemsActionGroup,
  getAllModeratedItemsByDomain,
  getAllModeratedItemsByUser,
  getAllModeratedItemsByCommunity,
  getAllModeratedItemsByGroup
};<commit_msg>Work on moderation<commit_after>const queue = require('../../workers/queue');
const models = require("../../../models");
const i18n = require('../../utils/i18n');
const async = require('async');
const moment = require('moment');
const log = require('../../utils/logger');
const _ = require('lodash');

const moderationItemsActionMaster = (req, res, options) => {
  options.model.find({
    where: {
      id: req.params.itemId
    },
    include: options.includes
  }).then(item => {
    if (item) {
      if (options.actionType==='delete') {
        item.deleted = true;
      } else if (options.actionType==='approve') {
        item.status = 'published';
        item.counter_flags = 0;
      } else if (options.actionType==='block') {
        item.status = 'blocked';
        item.counter_flags = 0;
      } else if (options.actionType==='clearFlags') {
        item.counter_flags = 0;
      }
      item.save().then( () => {
        res.sendStatus(200);
      }).catch( error => {
        log.error("Error deleting moderated item", { error });
        res.sendStatus(500);
      });
    }
  }).catch(error => {
    log.error("Error deleting moderated item", { error });
    res.sendStatus(500);
  })
};

const domainIncludes = (domainId) => {
  return [
    {
      model: models.Group,
      required: true,
      include: [
        {
          model: models.Community,
          required: true,
          include: [
            {
              model: models.Domain,
              where: {
                id: domainId
              },
              required: true
            }
          ]
        }
      ]
    }
  ];
};

const communityIncludes = (communityId) => {
  return [
    {
      model: models.Group,
      required: true,
      include: [
        {
          model: models.Community,
          required: true,
          where: {
            id: communityId
          }
        }
      ]
    }
  ];
};

const groupIncludes = (groupId) => {
  return [
    {
      model: models.Group,
      required: true,
      where: {
        id: groupId
      }
    }
  ];
};

const userIncludes = (userId) => {
  return [
    {
      model: models.User,
      required: true,
      where: {
        id: userId
      }
    }
  ];
};

const moderationItemsActionDomain = (req, res, model, actionType) => {
  moderationItemsActionMaster(req, res, { model, actionType, includes: domainIncludes(req.params.domainId) });
};

const moderationItemsActionCommunity = (req, res, model, actionType) => {
  moderationItemsActionMaster(req, res, { model, actionType, includes: communityIncludes(req.params.communityId) });
};

const moderationItemsActionGroup = (req, res, model, actionType) => {
  moderationItemsActionMaster(req, res, { model, actionType, includes: groupIncludes(req.params.groupId) });
};

const moderationItemsActionUser = (req, res, model, actionType) => {
  moderationItemsActionMaster(req, res, { model, actionType, includes: userIncludes(req.params.userId) });
};

const _toPercent = number => {
  if (number) {
    return Math.round(number*100)+'%';
  }
};

const getPushItem = (type, model) => {
  let source, toxicityScore, latestContent = null,
      severeToxicityScore,
      lastReportedAtDate = null, firstReportedDate = null;

  if (model.data && model.data.moderation) {
    const moderation = model.data.moderation;

    if (moderation.toxicityScore) {
      toxicityScore = _toPercent(moderation.toxicityScore);
    }

    if (moderation.severeToxicityScore) {
      severeToxicityScore = _toPercent(moderation.severeToxicityScore);
    }
    if (moderation.lastReportedBy &&
      moderation.lastReportedBy.length > 0) {
      source = moderation.lastReportedBy[0].source;
      firstReportedDate = moderation.lastReportedBy[moderation.lastReportedBy.length-1].date;
      lastReportedAtDate = moderation.lastReportedBy[0].date;

      if (moderation.lastReportedBy.length > 1) {
        const a =  moderation.lastReportedBy;
        const b = a;
      }
    }
  }

  if (!firstReportedDate)
    firstReportedDate = model.created_at;

  if (!lastReportedAtDate)
    lastReportedAtDate = model.created_at;

  if (type==='point') {
    latestContent = model.PointRevisions[model.PointRevisions.length-1].content;
  }

  return {
    id: model.id,
    created_at: model.created_at,
    formatted_date: moment(model.created_at).format("DD/MM/YY HH:mm"),
    type: type,
    counter_flags: model.counter_flags,
    status: model.status,
    user_id: model.user_id,
    toxicityScore: toxicityScore,
    severeToxicityScore: severeToxicityScore,
    source: source,
    lastReportedAtDate: lastReportedAtDate,
    firstReportedDate: firstReportedDate,
    lastReportedAtDateFormatted: lastReportedAtDate ? moment(lastReportedAtDate).format("DD/MM/YY HH:mm") : null,
    firstReportedDateFormatted:  firstReportedDate ? moment(firstReportedDate).format("DD/MM/YY HH:mm") : null,
    user_email: model.User.email,
    cover_media_type: model.cover_media_type,
    is_post: type==='post',
    is_point: type==='point',
    title: model.name,
    post_id: model.post_id,
    Group: model.Group,
    language: model.language,
    name: model.name,
    description: model.description,
    moderation_data: { moderation: model.data ? model.data.moderation : null },
    content: type==='post' ? (model.name + ' ' + model.description) : model.content,
    PostVideos: model.PostVideos,
    PostAudios: model.PostAudios,
    PostHeaderImages: model.PostHeaderImages,
    PointVideos: model.PointVideos,
    PointAudios: model.PointAudios,
    PointRevisions: model.PointRevisions,
    latestContent: latestContent
  };
};

const getItems = (posts, points) => {
  let items = [];
  _.forEach(posts, post => {
    items.push(getPushItem('post', post));
  });
  _.forEach(points, point => {
    items.push(getPushItem('point', point));
  });
  items = _.orderBy(items,['status', 'counter_flags', 'created_at'], ['asc','desc','asc']);
  return items;
};

const getModelModeration = (options, callback) => {
  options.model.unscoped().findAll({
    where: {
      deleted: false,
      $or: [
        {
          counter_flags: {
            $gt: options.allContent ? -1 : 0
          },
        },
        {
          status: "in_moderation_queue"
        }
      ],
    },
    order: options.order,
    include: options.includes
  }).then(items => {
    callback(null, items);
  }).catch(error => {
    callback(error);
  })
};

const getAllModeratedItemsByMaster = (options, callback) => {
  let posts, points;

  const postBaseIncludes = _.cloneDeep(options.includes);
  const pointBaseIncludes = _.cloneDeep(options.includes);

  async.series([
    parallelCallback => {
      let postIncludes = postBaseIncludes.concat([
        {
          model: models.Image,
          required: false,
          as: 'PostHeaderImages'
        },
        {
          model: models.Video,
          required: false,
          attributes: ['id','formats','updated_at','viewable','public_meta'],
          as: 'PostVideos',
          include: [
            {
              model: models.Image,
              as: 'VideoImages',
              attributes:["formats",'updated_at'],
              required: false
            },
          ]
        },
        {
          model: models.Audio,
          required: false,
          attributes: ['id','formats','updated_at','listenable'],
          as: 'PostAudios',
        }
      ]);

      if (!options.userId) {
        postIncludes = postIncludes.concat([ { model: models.User }]);
      } else {
        postIncludes = postIncludes.concat([ { model: models.Group }]);
      }

      const order = [
        [ { model: models.Image, as: 'PostHeaderImages' } ,'updated_at', 'asc' ],
        [ { model: models.Video, as: "PostVideos" }, 'updated_at', 'desc' ],
        [ { model: models.Audio, as: "PostAudios" }, 'updated_at', 'desc' ],
        [ { model: models.Video, as: "PostVideos" }, { model: models.Image, as: 'VideoImages' } ,'updated_at', 'asc' ]
      ];

      getModelModeration(_.merge(_.cloneDeep(options), {model: models.Post, includes: postIncludes, order }), (error, postsIn) => {
        parallelCallback(error);
        posts = postsIn;
      })
    },
    parallelCallback => {
      let pointIncludes = pointBaseIncludes.concat([
        {
          model: models.Video,
          required: false,
          attributes: ['id','formats','updated_at','viewable','public_meta'],
          as: 'PointVideos',
          include: [
            {
              model: models.Image,
              as: 'VideoImages',
              attributes:["formats",'updated_at'],
              required: false
            },
          ]
        },
        {
          model: models.Audio,
          required: false,
          attributes: ['id','formats','updated_at','listenable'],
          as: 'PointAudios'
        },
        {
          model: models.PointRevision,
          attributes: { exclude: ['ip_address', 'user_agent'] },
          required: false
        }
      ]);

      if (!options.userId) {
        pointIncludes = pointIncludes.concat([ { model: models.User }]);
      }

      const order = [
        [ { model: models.Video, as: "PointVideos" }, 'updated_at', 'desc' ],
        [ { model: models.Audio, as: "PointAudios" }, 'updated_at', 'desc' ],
        [ models.PointRevision, 'created_at', 'asc' ],
        [ { model: models.Video, as: "PointVideos" }, { model: models.Image, as: 'VideoImages' } ,'updated_at', 'asc' ]
      ];

      getModelModeration(_.merge(_.cloneDeep(options), {model: models.Point, includes: pointIncludes, order }), (error, pointsIn) => {
        points = pointsIn;
        parallelCallback(error);
      })
    }
  ], error => {
    callback(error, getItems(posts, points));
  });
};

const getAllModeratedItemsByDomain = (options, callback) => {
  getAllModeratedItemsByMaster(_.merge(options, {includes: domainIncludes(options.domainId) }), callback);
};

const getAllModeratedItemsByCommunity = (options, callback) => {
  getAllModeratedItemsByMaster(_.merge(options, {includes: communityIncludes(options.communityId) }), callback);
};

const getAllModeratedItemsByGroup = (options, callback) => {
  getAllModeratedItemsByMaster(_.merge(options, {includes: groupIncludes(options.groupId) }), callback);
};

const getAllModeratedItemsByUser = (options, callback) => {
  getAllModeratedItemsByMaster(_.merge(options, {includes: userIncludes(options.userId) }), callback);
};

module.exports = {
  moderationItemsActionDomain,
  moderationItemsActionCommunity,
  moderationItemsActionGroup,
  getAllModeratedItemsByDomain,
  getAllModeratedItemsByUser,
  getAllModeratedItemsByCommunity,
  getAllModeratedItemsByGroup
};<|endoftext|>


<commit_before>import remark from 'remark'
import html from 'remark-html'

export default async function markdownToHtml(markdown) {
  const result = await remark().use(html).process(markdown)
  return result.toString()
}
<commit_msg>bugfix: remark/webpack conflict (#29180)<commit_after>import { remark } from 'remark'
import html from 'remark-html'

export default async function markdownToHtml(markdown) {
  const result = await remark().use(html).process(markdown)
  return result.toString()
}
<|endoftext|>


<commit_before>import React from 'react'

export default () =>
b

<commit_msg>Update b.js<commit_after>export default () =>
b

<|endoftext|>


<commit_before>/*
 * Mathematical transformations for color
 * @author Martin Chaov
 *
 * Some solutions are coming directly from the web
 * others are implementing formulas from Wikipedia.
 * Further reading:
 * https://www.cs.rit.edu/~ncs/color/t_convert.html
 * http://www.rapidtables.com/convert/color/hsv-to-rgb.htm
 *
 */

var ColorLab = (function () {
    'use strict';

    function ColorLab()
    {
        Object.defineProperties(this, {
            '_shorthandHEXRegEx': {
                writable: false,
                enumerable: false,
                configurable: false,
                value: /^#?([a-f\d])([a-f\d])([a-f\d])$/i
            },
            '_HEXExpand': {
                writable: false,
                enumerable: false,
                configurable: false,
                value: function(m, r, g, b)
                {
                    return r + r + g + g + b + b;
                }
            },
            '_HEXRegEx': {
                writable: false,
                enumerable: false,
                configurable: false,
                value: /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i
            },
            '_hueTransform': {
                writable: false,
                enumerable: false,
                configurable: false,
                value: function (p, q, t)
                {
                    if (t < 0)
                    {
                        t += 1;
                    }

                    if (t > 1)
                    {
                        t -= 1;
                    }

                    if (t < 1 / 6)
                    {
                        return p + (q - p) * 6 * t;
                    }

                    if (t < 1 / 2)
                    {
                        return q;
                    }

                    if (t < 2 / 3)
                    {
                        return p + (q - p) * (2 / 3 - t) * 6;
                    }

                    return p;
                }
            },
            'RGB2HSL': {
                writable: false,
                enumerable: false,
                configurable: false,
                value: function (r, g, b)
                {
                    r /= 255, g /= 255, b /= 255;

                    var max = Math.max(r, g, b),
                        min = Math.min(r, g, b),
                        h, d, s, l = (max + min) / 2;

                    if (max == min)
                    {
                        h = s = 0;
                    }
                    else
                    {
                        d = max - min;
                        s = l > 0.5 ? d / (2 - max - min) : d / (max + min);

                        switch (max)
                        {
                            case r:
                                h = (g - b) / d + (g < b ? 6 : 0);
                                break;

                            case g:
                                h = (b - r) / d + 2;
                                break;

                            case b:
                                h = (r - g) / d + 4;
                                break;
                        }
                        h /= 6;
                    }

                    return {
                        h: Math.round(h * 360),
                        s: Math.round(s * 100),
                        l: Math.round(l * 100)
                    };
                }
            },
            'HSL2RGB': {
                writable: false,
                enumerable: false,
                configurable: false,
                value: function (h, s, l)
                {
                    h /= 360, s /= 100, l /= 100;

                    var r, g, b, q, p;

                    if (s === 0)
                    {
                        r = g = b = l;
                    }
                    else
                    {
                        q = l < 0.5 ? l * (1 + s) : l + s - l * s,
                        p = 2 * l - q;

                        r = this._hueTransform(p, q, h + 1 / 3);
                        g = this._hueTransform(p, q, h);
                        b = this._hueTransform(p, q, h - 1 / 3);
                    }

                    return {
                        r: Math.round(r * 255),
                        g: Math.round(g * 255),
                        b: Math.round(b * 255),
                    };
                }
            },
            'RGB2HEX': {
                writable: false,
                enumerable: false,
                configurable: false,
                value: function (r, g, b)
                {
                    return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
                }
            },
            'HEX2RGB': {
                writable: false,
                enumerable: false,
                configurable: false,
                value: function (hex)
                {
                    (hex.length < 7) && (hex = hex.replace(this._shorthandHEXRegEx, this._HEXExpand));

                    var result = this._HEXRegEx.exec(hex);
                    return result ? {
                        r: parseInt(result[1], 16),
                        g: parseInt(result[2], 16),
                        b: parseInt(result[3], 16)
                    } : null;
                }
            }
        });

        return this;
    }

    return new ColorLab();
}());<commit_msg>added random color method<commit_after>/*
 * Mathematical transformations for color
 * @author Martin Chaov
 *
 * Some solutions are coming directly from the web
 * others are implementing formulas from Wikipedia.
 * Further reading:
 * https://www.cs.rit.edu/~ncs/color/t_convert.html
 * http://www.rapidtables.com/convert/color/hsv-to-rgb.htm
 *
 */

var ColorLab = (function () {
    'use strict';

    function ColorLab()
    {
        Object.defineProperties(this, {
            '_shorthandHEXRegEx': {
                writable: false,
                enumerable: false,
                configurable: false,
                value: /^#?([a-f\d])([a-f\d])([a-f\d])$/i
            },
            '_HEXExpand': {
                writable: false,
                enumerable: false,
                configurable: false,
                value: function(m, r, g, b)
                {
                    return r + r + g + g + b + b;
                }
            },
            '_HEXRegEx': {
                writable: false,
                enumerable: false,
                configurable: false,
                value: /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i
            },
            '_hueTransform': {
                writable: false,
                enumerable: false,
                configurable: false,
                value: function (p, q, t)
                {
                    if (t < 0)
                    {
                        t += 1;
                    }

                    if (t > 1)
                    {
                        t -= 1;
                    }

                    if (t < 1 / 6)
                    {
                        return p + (q - p) * 6 * t;
                    }

                    if (t < 1 / 2)
                    {
                        return q;
                    }

                    if (t < 2 / 3)
                    {
                        return p + (q - p) * (2 / 3 - t) * 6;
                    }

                    return p;
                }
            },
            'random': {
                writable: false,
                enumerable: false,
                configurable: false,
                value: function (type)
                {
                    var type = type || '',
                        randColor = '#' + Math.floor(Math.random() * 16777215).toString(16);

                    switch (type.toLowerCase())
                    {
                        case 'rgb':
                            return this.HEX2RGB(randColor);

                        case 'hsl':
                            var rgb = this.HEX2RGB(randColor);
                            return this.RGB2HSL(rgb.r, rgb.g, rgb.b);

                        default:
                            return randColor;

                    }
                }
            },
            'RGB2HSL': {
                writable: false,
                enumerable: false,
                configurable: false,
                value: function (r, g, b)
                {
                    r /= 255, g /= 255, b /= 255;

                    var max = Math.max(r, g, b),
                        min = Math.min(r, g, b),
                        h, d, s, l = (max + min) / 2;

                    if (max == min)
                    {
                        h = s = 0;
                    }
                    else
                    {
                        d = max - min;
                        s = l > 0.5 ? d / (2 - max - min) : d / (max + min);

                        switch (max)
                        {
                            case r:
                                h = (g - b) / d + (g < b ? 6 : 0);
                                break;

                            case g:
                                h = (b - r) / d + 2;
                                break;

                            case b:
                                h = (r - g) / d + 4;
                                break;
                        }
                        h /= 6;
                    }

                    return {
                        h: Math.round(h * 360),
                        s: Math.round(s * 100),
                        l: Math.round(l * 100)
                    };
                }
            },
            'HSL2RGB': {
                writable: false,
                enumerable: false,
                configurable: false,
                value: function (h, s, l)
                {
                    h /= 360, s /= 100, l /= 100;

                    var r, g, b, q, p;

                    if (s === 0)
                    {
                        r = g = b = l;
                    }
                    else
                    {
                        q = l < 0.5 ? l * (1 + s) : l + s - l * s,
                        p = 2 * l - q;

                        r = this._hueTransform(p, q, h + 1 / 3);
                        g = this._hueTransform(p, q, h);
                        b = this._hueTransform(p, q, h - 1 / 3);
                    }

                    return {
                        r: Math.round(r * 255),
                        g: Math.round(g * 255),
                        b: Math.round(b * 255),
                    };
                }
            },
            'RGB2HEX': {
                writable: false,
                enumerable: false,
                configurable: false,
                value: function (r, g, b)
                {
                    return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
                }
            },
            'HEX2RGB': {
                writable: false,
                enumerable: false,
                configurable: false,
                value: function (hex)
                {
                    (hex.length < 7) && (hex = hex.replace(this._shorthandHEXRegEx, this._HEXExpand));

                    var result = this._HEXRegEx.exec(hex);
                    return result ? {
                        r: parseInt(result[1], 16),
                        g: parseInt(result[2], 16),
                        b: parseInt(result[3], 16)
                    } : null;
                }
            }
        });

        return this;
    }

    return new ColorLab();
}());<|endoftext|>