<commit_before>enyo.kind({
	name: "moon.sample.SliderSample",
	fit: true,
	classes: "moon moon-sample-padded enyo-unselectable",
	components: [
		{kind: "enyo.Spotlight"},
		{tag:"br"},
		{classes:"moon-sample-divider", content:"Slider 1: Default"},
		{kind: "moon.Slider", value: 25, bgProgress: 35, onChanging:"sliderChanging", onChange:"sliderChanged"},
		{tag:"br"},
		{classes:"moon-sample-divider", content:"Slider 2: not locked bar"},
		{kind: "moon.Slider", lockBar: false, value: 75, bgProgress: 65, progress: 30, onChanging:"sliderChanging", onChange:"sliderChanged"},
		{tag:"br"},
		{classes:"moon-sample-divider", content:"Slider 3: Disabled"},
		{name: "disabledSlider", kind: "moon.Slider", value: 50, disabled: true, onChanging:"sliderChanging", onChange:"sliderChanged"},
		{tag:"br"},
		{components: [
			{kind: "moon.InputDecorator", style:"margin-right:10px;", components: [
				{kind: "moon.Input", type: "number", placeholder: "Value", style: "width:50px;", value: 20}
			]},
			{kind: "moon.Button", content:"Set", ontap:"changeValue"},
			{kind: "moon.Button", content:"-", ontap:"decValue"},
			{kind: "moon.Button", content:"+", ontap:"incValue"},
			{tag: "br"},
			{style: "width:340px;", components: [
				{name:"animateSetting", kind: "moon.LabeledCheckbox", checked: true, content: "Animated", onActivate: "animateActivate"}
			]},
			{kind: "FittableColumns", components: [
				{name:"incrementSetting", kind: "moon.LabeledCheckbox", checked: true, content: "increment by number", style: "width:340px; display:inline-block;", onActivate: "changeIncrement"},
				{name:"intPicker", kind: "moon.IntegerPicker", min: 1, max: 25, value: 5, onChange:"changeIncrement"}
			]},
			{tag: "br"},
			{name:"result", style:"font-size:20px;font-family:PreludeWGL Light", content:"No slider moved yet."}
		]}
	],
	//* @protected
	create: function() {
		this.inherited(arguments);
		//* FIXME : intial 'value' in moon.IntegerPicker is not applied
		this.$.intPicker.setValue(5);
	},
	changeValue: function(inSender, inEvent) {
		for (var i in this.$) {
			if (this.$[i].kind == "moon.Slider") {
				if (this.$.animateSetting.getChecked()) {
					this.$[i].animateTo(this.$.input.getValue());
				} else {
					this.$[i].setValue(this.$.input.getValue());
				}
			}
		}
	},
	incValue: function() {
		this.$.input.setValue(Math.min(parseInt(this.$.input.getValue() || 0) + 10, 100));
		this.changeValue();
	},
	decValue: function() {
		this.$.input.setValue(Math.max(parseInt(this.$.input.getValue() || 0) - 10, 0));
		this.changeValue();
	},
	sliderChanging: function(inSender, inEvent) {
		this.$.result.setContent(inSender.name + " changing: " + Math.round(inSender.getValue()));
	},
	sliderChanged: function(inSender, inEvent) {
		this.$.result.setContent(inSender.name + " changed to " + Math.round(inSender.getValue()) + ".");
	},
	animateActivate: function(inSender, inEvent) {
		var ck = inSender.getChecked();

		for (var i in this.$) {
			if (this.$[i].kind == "moon.Slider") {
				this.$[i].setAnimate(ck);
			}
		}
		return true;
	},
	changeIncrement: function(inSender, inEvent) {
		var v = this.$.intPicker.getValue();
		if (!this.$.incrementSetting.getChecked()) {
			v = 0;
		}

		for (var i in this.$) {
			if (this.$[i].kind == "moon.Slider") {
				this.$[i].setIncrement(v);
			}
		}
		return true;
	}
});<commit_msg>GF-1835: moonraker: slidersample: slider 2: the blue hightlight bar doesn't follow the orange bubble's move<commit_after>enyo.kind({
	name: "moon.sample.SliderSample",
	fit: true,
	classes: "moon moon-sample-padded enyo-unselectable",
	components: [
		{kind: "enyo.Spotlight"},
		{tag:"br"},
		{classes:"moon-sample-divider", content:"Slider 1: Default"},
		{kind: "moon.Slider", value: 25, bgProgress: 35, onChanging:"sliderChanging", onChange:"sliderChanged"},
		{tag:"br"},
		{classes:"moon-sample-divider", content:"Slider 2: not locked bar"},
		{style: "width:340px;", components: [
			{name:"lockBar", kind: "moon.LabeledToggleButton", checked: false, content: "lock bar", onchange: "lockbarChanged"}
		]},
		{name: "slider2", kind: "moon.Slider", lockBar: false, value: 75, bgProgress: 65, progress: 30, onChanging:"sliderChanging", onChange:"sliderChanged"},
		{tag:"br"},
		{classes:"moon-sample-divider", content:"Slider 3: Disabled"},
		{name: "disabledSlider", kind: "moon.Slider", value: 50, disabled: true, onChanging:"sliderChanging", onChange:"sliderChanged"},
		{tag:"br"},
		{components: [
			{kind: "moon.InputDecorator", style:"margin-right:10px;", components: [
				{kind: "moon.Input", type: "number", placeholder: "Value", style: "width:50px;", value: 20}
			]},
			{kind: "moon.Button", content:"Set", ontap:"changeValue"},
			{kind: "moon.Button", content:"-", ontap:"decValue"},
			{kind: "moon.Button", content:"+", ontap:"incValue"},
			{tag: "br"},
			{style: "width:340px;", components: [
				{name:"animateSetting", kind: "moon.LabeledCheckbox", checked: true, content: "Animated", onActivate: "animateActivate"}
			]},
			{kind: "FittableColumns", components: [
				{name:"incrementSetting", kind: "moon.LabeledCheckbox", checked: true, content: "increment by number", style: "width:340px; display:inline-block;", onActivate: "changeIncrement"},
				{name:"intPicker", kind: "moon.IntegerPicker", min: 1, max: 25, value: 5, onChange:"changeIncrement"}
			]},
			{tag: "br"},
			{name:"result", style:"font-size:20px;font-family:PreludeWGL Light", content:"No slider moved yet."}
		]}
	],
	//* @protected
	create: function() {
		this.inherited(arguments);
		//* FIXME : intial 'value' in moon.IntegerPicker is not applied
		this.$.intPicker.setValue(5);
	},
	changeValue: function(inSender, inEvent) {
		for (var i in this.$) {
			if (this.$[i].kind == "moon.Slider") {
				if (this.$.animateSetting.getChecked()) {
					this.$[i].animateTo(this.$.input.getValue());
				} else {
					this.$[i].setValue(this.$.input.getValue());
				}
			}
		}
	},
	incValue: function() {
		this.$.input.setValue(Math.min(parseInt(this.$.input.getValue() || 0) + 10, 100));
		this.changeValue();
	},
	decValue: function() {
		this.$.input.setValue(Math.max(parseInt(this.$.input.getValue() || 0) - 10, 0));
		this.changeValue();
	},
	sliderChanging: function(inSender, inEvent) {
		this.$.result.setContent(inSender.name + " changing: " + Math.round(inSender.getValue()));
	},
	sliderChanged: function(inSender, inEvent) {
		this.$.result.setContent(inSender.name + " changed to " + Math.round(inSender.getValue()) + ".");
	},
	lockbarChanged: function(inSender, inEvent) {
		this.$.slider2.setLockBar(this.$.lockBar.getChecked());
	},
	animateActivate: function(inSender, inEvent) {
		var ck = inSender.getChecked();

		for (var i in this.$) {
			if (this.$[i].kind == "moon.Slider") {
				this.$[i].setAnimate(ck);
			}
		}
		return true;
	},
	changeIncrement: function(inSender, inEvent) {
		var v = this.$.intPicker.getValue();
		if (!this.$.incrementSetting.getChecked()) {
			v = 0;
		}

		for (var i in this.$) {
			if (this.$[i].kind == "moon.Slider") {
				this.$[i].setIncrement(v);
			}
		}
		return true;
	}
});<|endoftext|>


<commit_before>'use strict';
const morgan = require('morgan');
const express = require('express');
const mongoose = require('mongoose');
const Promise = require('bluebird');
const createError = require('http-errors');
const debug = require('debug')('server');
const cors = require('cors');

const handleError = require('./lib/handle-error');
const authRouter = require('./router/auth-router');
const userRouter = require('./router/user-router');
const educationRouter = require('./router/education-router');
const experienceRouter = require('./router/experience-router');
const skillRouter = require('./router/skill-router');
const imageRouter = require('./router/image-router');

const app = express();
const port = process.env.PORT || 3000;
const mongoDbUri = process.env.MONGODB_URI || 'mongodb://localhost/backenddev';

mongoose.Promise = Promise;
mongoose.connect(mongoDbUri);

app.use(morgan('dev'));
app.use(cors());

app.use('/api', authRouter);
app.use('/api/users', userRouter);
app.use('/api/education', educationRouter);
app.use('/api/experience', experienceRouter);
app.use('/api/skill', skillRouter);
app.use('/api/image', imageRouter);

app.all('*', function(req, res, next) {
  debug('hit 404 route');
  next(createError(404, `ERROR: ${req.method} :: ${req.url} is not a route`));
});

app.use(handleError);

app.listen(port, function() {
  debug(`server up :: ${port}`);
});
<commit_msg>fixed spacing issue<commit_after>'use strict';

const morgan = require('morgan');
const express = require('express');
const mongoose = require('mongoose');
const Promise = require('bluebird');
const createError = require('http-errors');
const debug = require('debug')('server');
const cors = require('cors');

const handleError = require('./lib/handle-error');
const authRouter = require('./router/auth-router');
const userRouter = require('./router/user-router');
const educationRouter = require('./router/education-router');
const experienceRouter = require('./router/experience-router');
const skillRouter = require('./router/skill-router');
const imageRouter = require('./router/image-router');

const app = express();
const port = process.env.PORT || 3000;
const mongoDbUri = process.env.MONGODB_URI || 'mongodb://localhost/backenddev';

mongoose.Promise = Promise;
mongoose.connect(mongoDbUri);

app.use(morgan('dev'));
app.use(cors());

app.use('/api', authRouter);
app.use('/api/users', userRouter);
app.use('/api/education', educationRouter);
app.use('/api/experience', experienceRouter);
app.use('/api/skill', skillRouter);
app.use('/api/image', imageRouter);

app.all('*', function(req, res, next) {
  debug('hit 404 route');
  next(createError(404, `ERROR: ${req.method} :: ${req.url} is not a route`));
});

app.use(handleError);

app.listen(port, function() {
  debug(`server up :: ${port}`);
});
<|endoftext|>


<commit_before>/*jshint esversion: 6 */
/* global __dirname */

(function() {
  'use strict';

  const _ = require('lodash');
  const util = require('util');
  const moment = require('moment');
  const cheerio = require('cheerio');
  const Promise = require('bluebird');
  const Common = require(__dirname + '/../common');

  module.exports = (app, config, ModulesClass) => {

    function findImageByType(images, type) {
      for (let i = 0; i < images.length; i++) {
        if (images[i].type === type) {
          return images[i];
        }
      }
    }

    app.get('/ajax/menuSearch', (req, res) => {
      const search = Common.processFreeTextSearch(req.query.search);
      const preferLanguages = req.headers['accept-language'];

      new ModulesClass(config)
        .pages.search(search, preferLanguages, 0, Common.SEARCH_RESULTS_PER_TYPE)
        .files.search(search, 0, Common.SEARCH_RESULTS_PER_TYPE)
        .news.search(search, 0, Common.SEARCH_RESULTS_PER_TYPE)
        .callback((data) => {
          const pages = data[0];
          const files = data[1];
          const newsArticles = data[2];

          res.render('ajax/menu-search.pug', {
            pages: pages,
            files: files,
            newsArticles: newsArticles
          });
        });
    });

    app.get('/ajax/search/pages', (req, res) => {
      const perPage = Common.SEARCH_PAGES_PER_PAGE;
      const search = Common.processFreeTextSearch(req.query.search);
      const preferLanguages = req.headers['accept-language'];
      const page = parseInt(req.query.page)||0;

      new ModulesClass(config)
        .pages.search(search, preferLanguages, page * perPage, (perPage + 1))
        .callback((data) => {
          const lastPage = data[0].length < perPage + 1;
          let pages = data[0].splice(0, perPage);

          const pagesModule = new ModulesClass(config);
          for (let i = 0; i < pages.length; i++) {
            const pageId = pages[i].id;
            pagesModule.pages.getContent(pageId, preferLanguages);
            pagesModule.pages.listImages(pageId);
          }

          pagesModule.callback((datas) => {
            for (let i = 0; i < pages.length; i++) {
              const content = datas[i * 2];
              const images =  datas[(i * 2) + 1];

              let image = findImageByType(images, 'featured');
              if (!image && images.length) {
                image = images[0];
              }

              pages[i] = Object.assign(pages[i], {
                excerpt: _.truncate(Common.htmlToText(content), {
                  length: 500
                }),
                imageSrc: image ? util.format('/pageImages/%s/%s', pages[i].id, image.id) : null
              });
            }

            res.render('ajax/search-pages.pug', {
              pages: pages,
              page: page,
              lastPage: lastPage
            });
          });
        });
    });

    app.get('/ajax/search/files', (req, res) => {
      const perPage = Common.SEARCH_FILES_PER_PAGE;
      const search = Common.processFreeTextSearch(req.query.search);
      const page = parseInt(req.query.page)||0;

      new ModulesClass(config)
        .files.search(search, page * perPage, (perPage + 1))
        .callback((data) => {
          const lastPage = data[0].length < perPage + 1;
          const files = data[0].splice(0, perPage);
          res.render('ajax/search-files.pug', {
            files: files,
            page: page,
            lastPage: lastPage
          });
        });
    });

    app.get('/ajax/search/news', (req, res) => {
      const perPage = Common.SEARCH_NEWS_PER_PAGE;
      const search = Common.processFreeTextSearch(req.query.search);
      const page = parseInt(req.query.page)||0;

      new ModulesClass(config)
        .news.search(search, page * perPage, (perPage + 1))
        .callback((data) => {
          const lastPage = data[0].length < perPage + 1;
          const newsArticles = data[0].splice(0, perPage).map(newsArticle => {
            return Object.assign(newsArticle, {
              "shortDate": moment(newsArticle.published).format("D.M.YYYY"),
              "imageSrc": newsArticle.imageId ? util.format('/newsArticleImages/%s/%s', newsArticle.id, newsArticle.imageId) : null,
              "abstract": Common.htmlToText(newsArticle.abstract)
            });
          });

          res.render('ajax/search-news.pug', {
            newsArticles: newsArticles,
            page: page,
            lastPage: lastPage
          });
        });
    });

    app.get(util.format('%s/', Common.SEARCH_PATH), (req, res, next) => {
      const bannerSrc = '/gfx/layout/mikkeli-page-banner-default.jpg';
      const search = req.query.search;

      res.render('pages/search.pug', Object.assign(req.kuntaApi.data, {
        bannerSrc: bannerSrc,
        search: search,
        breadcrumbs : [{path: util.format('%s/', Common.SEARCH_PATH), title: 'Haku'}]
      }));
    });

  };

}).call(this);<commit_msg>Added html entity decode<commit_after>/*jshint esversion: 6 */
/* global __dirname */

(function() {
  'use strict';

  const _ = require('lodash');
  const util = require('util');
  const moment = require('moment');
  const cheerio = require('cheerio');
  const Promise = require('bluebird');
  const Common = require(__dirname + '/../common');
  const Entities = require('html-entities').AllHtmlEntities;
  const entities = new Entities();

  module.exports = (app, config, ModulesClass) => {

    function findImageByType(images, type) {
      for (let i = 0; i < images.length; i++) {
        if (images[i].type === type) {
          return images[i];
        }
      }
    }

    app.get('/ajax/menuSearch', (req, res) => {
      const search = Common.processFreeTextSearch(req.query.search);
      const preferLanguages = req.headers['accept-language'];

      new ModulesClass(config)
        .pages.search(search, preferLanguages, 0, Common.SEARCH_RESULTS_PER_TYPE)
        .files.search(search, 0, Common.SEARCH_RESULTS_PER_TYPE)
        .news.search(search, 0, Common.SEARCH_RESULTS_PER_TYPE)
        .callback((data) => {
          const pages = data[0].map((page) => {
            page.title = entities.decode(page.title);
            return page;
          });

          const files = data[1];

          const newsArticles = data[2].map((newsArticle) => {
            newsArticle.title = entities.decode(newsArticle.title);
            return newsArticle;
          });

          res.render('ajax/menu-search.pug', {
            pages: pages,
            files: files,
            newsArticles: newsArticles
          });
        });
    });

    app.get('/ajax/search/pages', (req, res) => {
      const perPage = Common.SEARCH_PAGES_PER_PAGE;
      const search = Common.processFreeTextSearch(req.query.search);
      const preferLanguages = req.headers['accept-language'];
      const page = parseInt(req.query.page)||0;

      new ModulesClass(config)
        .pages.search(search, preferLanguages, page * perPage, (perPage + 1))
        .callback((data) => {
          const lastPage = data[0].length < perPage + 1;
          let pages = data[0].splice(0, perPage);

          const pagesModule = new ModulesClass(config);
          for (let i = 0; i < pages.length; i++) {
            const pageId = pages[i].id;
            pagesModule.pages.getContent(pageId, preferLanguages);
            pagesModule.pages.listImages(pageId);
          }

          pagesModule.callback((datas) => {
            for (let i = 0; i < pages.length; i++) {
              const content = datas[i * 2];
              const images =  datas[(i * 2) + 1];

              let image = findImageByType(images, 'featured');
              if (!image && images.length) {
                image = images[0];
              }

              pages[i] = Object.assign(pages[i], {
                excerpt: _.truncate(Common.htmlToText(content), {
                  length: 500
                }),
                imageSrc: image ? util.format('/pageImages/%s/%s', pages[i].id, image.id) : null
              });
            }

            res.render('ajax/search-pages.pug', {
              pages: pages,
              page: page,
              lastPage: lastPage
            });
          });
        });
    });

    app.get('/ajax/search/files', (req, res) => {
      const perPage = Common.SEARCH_FILES_PER_PAGE;
      const search = Common.processFreeTextSearch(req.query.search);
      const page = parseInt(req.query.page)||0;

      new ModulesClass(config)
        .files.search(search, page * perPage, (perPage + 1))
        .callback((data) => {
          const lastPage = data[0].length < perPage + 1;
          const files = data[0].splice(0, perPage);
          res.render('ajax/search-files.pug', {
            files: files,
            page: page,
            lastPage: lastPage
          });
        });
    });

    app.get('/ajax/search/news', (req, res) => {
      const perPage = Common.SEARCH_NEWS_PER_PAGE;
      const search = Common.processFreeTextSearch(req.query.search);
      const page = parseInt(req.query.page)||0;

      new ModulesClass(config)
        .news.search(search, page * perPage, (perPage + 1))
        .callback((data) => {
          const lastPage = data[0].length < perPage + 1;
          const newsArticles = data[0].splice(0, perPage).map(newsArticle => {
            return Object.assign(newsArticle, {
              "shortDate": moment(newsArticle.published).format("D.M.YYYY"),
              "imageSrc": newsArticle.imageId ? util.format('/newsArticleImages/%s/%s', newsArticle.id, newsArticle.imageId) : null,
              "abstract": Common.htmlToText(newsArticle.abstract)
            });
          });

          res.render('ajax/search-news.pug', {
            newsArticles: newsArticles,
            page: page,
            lastPage: lastPage
          });
        });
    });

    app.get(util.format('%s/', Common.SEARCH_PATH), (req, res, next) => {
      const bannerSrc = '/gfx/layout/mikkeli-page-banner-default.jpg';
      const search = req.query.search;

      res.render('pages/search.pug', Object.assign(req.kuntaApi.data, {
        bannerSrc: bannerSrc,
        search: search,
        breadcrumbs : [{path: util.format('%s/', Common.SEARCH_PATH), title: 'Haku'}]
      }));
    });

  };

}).call(this);<|endoftext|>


<commit_before>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2014 Broad Institute
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

var igv = (function (igv) {

    igv.GtexSelection = function (gene, snp) {

        this.geneColors = {};
        this.gene = null;
        this.snp = null;
        this.genesCount = 0;

        if (gene) {
            this.gene = gene.toUpperCase();
            this.geneColors[this.gene] = brewer[this.genesCount++];

        }
        if (snp) {
            this.snp = snp.toUpperCase();
        }

    }

    igv.GtexSelection.prototype.addGene = function (geneName) {
        if (!this.geneColors[geneName.toUpperCase()]) {
            this.geneColors[geneName.toUpperCase()] = brewer[this.genesCount++];
        }
    }

    igv.GtexSelection.prototype.colorForGene = function (geneName) {
        return this.geneColors[geneName.toUpperCase()];
    }

    var brewer = new Array();
// Set +!
    brewer.push("rgb(228,26,28)");
    brewer.push("rgb(55,126,184)");
    brewer.push("rgb(77,175,74)");
    brewer.push("rgb(166,86,40)");
    brewer.push("rgb(152,78,163)");
    brewer.push("rgb(255,127,0)");
    brewer.push("rgb(247,129,191)");
    brewer.push("rgb(153,153,153)");
    brewer.push("rgb(255,255,51)");

// #Set 2
    brewer.push("rgb(102, 194, 165");
    brewer.push("rgb(252, 141, 98");
    brewer.push("rgb(141, 160, 203");
    brewer.push("rgb(231, 138, 195");
    brewer.push("rgb(166, 216, 84");
    brewer.push("rgb(255, 217, 47");
    brewer.push("rgb(229, 196, 148");
    brewer.push("rgb(179, 179, 179");

//#Set 3
    brewer.push("rgb( 141, 211, 199");
    brewer.push("rgb(255, 255, 179");
    brewer.push("rgb(190, 186, 218");
    brewer.push("rgb(251, 128, 114");
    brewer.push("rgb(128, 177, 211");
    brewer.push("rgb(253, 180, 98");
    brewer.push("rgb(179, 222, 105");
    brewer.push("rgb(252, 205, 229");
    brewer.push("rgb(217, 217, 217");
    brewer.push("rgb(188, 128, 189");
    brewer.push("rgb(204, 235, 197");
    brewer.push("rgb(255, 237, 111");

    igv.GtexUtils = {

        getTissueInfo: function(datasetId) {

            datasetId = datasetId || "gtex_v7";

            let url = "https://gtexportal.org/rest/v1/dataset/tissueInfo?format=json&datasetId=" + datasetId;

            return igv.xhr.loadJson(url, {})
        }

    }

    return igv;

})
(igv || {});
<commit_msg>update GTEx tissue info API.<commit_after>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2014 Broad Institute
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

var igv = (function (igv) {

    igv.GtexSelection = function (gene, snp) {

        this.geneColors = {};
        this.gene = null;
        this.snp = null;
        this.genesCount = 0;

        if (gene) {
            this.gene = gene.toUpperCase();
            this.geneColors[this.gene] = brewer[this.genesCount++];

        }
        if (snp) {
            this.snp = snp.toUpperCase();
        }

    }

    igv.GtexSelection.prototype.addGene = function (geneName) {
        if (!this.geneColors[geneName.toUpperCase()]) {
            this.geneColors[geneName.toUpperCase()] = brewer[this.genesCount++];
        }
    }

    igv.GtexSelection.prototype.colorForGene = function (geneName) {
        return this.geneColors[geneName.toUpperCase()];
    }

    var brewer = new Array();
// Set +!
    brewer.push("rgb(228,26,28)");
    brewer.push("rgb(55,126,184)");
    brewer.push("rgb(77,175,74)");
    brewer.push("rgb(166,86,40)");
    brewer.push("rgb(152,78,163)");
    brewer.push("rgb(255,127,0)");
    brewer.push("rgb(247,129,191)");
    brewer.push("rgb(153,153,153)");
    brewer.push("rgb(255,255,51)");

// #Set 2
    brewer.push("rgb(102, 194, 165");
    brewer.push("rgb(252, 141, 98");
    brewer.push("rgb(141, 160, 203");
    brewer.push("rgb(231, 138, 195");
    brewer.push("rgb(166, 216, 84");
    brewer.push("rgb(255, 217, 47");
    brewer.push("rgb(229, 196, 148");
    brewer.push("rgb(179, 179, 179");

//#Set 3
    brewer.push("rgb( 141, 211, 199");
    brewer.push("rgb(255, 255, 179");
    brewer.push("rgb(190, 186, 218");
    brewer.push("rgb(251, 128, 114");
    brewer.push("rgb(128, 177, 211");
    brewer.push("rgb(253, 180, 98");
    brewer.push("rgb(179, 222, 105");
    brewer.push("rgb(252, 205, 229");
    brewer.push("rgb(217, 217, 217");
    brewer.push("rgb(188, 128, 189");
    brewer.push("rgb(204, 235, 197");
    brewer.push("rgb(255, 237, 111");

    igv.GtexUtils = {

        getTissueInfo: function(datasetId) {

            datasetId = datasetId || "gtex_v7";

            // let depricated_url = 'https://gtexportal.org/rest/v1/dataset/tissueInfo?format=json&datasetId=' + datasetId;

            let url = 'https://gtexportal.org/rest/v1/dataset/tissueSummary?datasetId=' + datasetId;

            return igv.xhr.loadJson(url, {})
        }

    }

    return igv;

})
(igv || {});
<|endoftext|>


<commit_before>var path = require('path');
var extendConfig = require('./extendConfig');

function projectPath (config) {
  // Legacy mode, if the cwd is the backstop module
  if (config.backstop === process.cwd()) {
    console.log('BackstopJS is running in legacy mode.');
    return path.join(__dirname, '../../../..');
  }
  return process.cwd();
}

function loadProjectConfig (command, options, config) {
  // TEST REPORT FILE NAME
  var customTestReportFileName = options && (options.testReportFileName || null);
  if (customTestReportFileName) {
    config.testReportFileName = options.testReportFileName || null;
  }

  var customConfigPath = options && (options.backstopConfigFilePath || options.configPath);

  if(options && typeof options.config === "string"){
    customConfigPath = options.config;
  }

  if (customConfigPath) {
    if (path.isAbsolute(customConfigPath)) {
      config.backstopConfigFileName = customConfigPath;
    } else {
      config.backstopConfigFileName = path.join(config.projectPath, customConfigPath);
    }
  } else {
    config.backstopConfigFileName = path.join(config.projectPath, 'backstop.json');
  }

  var userConfig = {};
  var CMD_REQUIRES_CONFIG = command !== 'genConfig';
  if (CMD_REQUIRES_CONFIG) {
    if (options && typeof options.config === 'object') {
      console.log('BackstopJS uses a passed object as config');
      userConfig = options.config;
    } else if (config.backstopConfigFileName) {
      try {
        console.log('BackstopJS loading config: ', config.backstopConfigFileName, '\n');
        userConfig = require(config.backstopConfigFileName);
      } catch (e) {
        console.error('Error ' + e);
        process.exit(1);
      }
    }
  }

  return userConfig;
}

function makeConfig (command, options) {
  var config = {};

  config.args = options || {};

  config.backstop = path.join(__dirname, '../..');
  config.projectPath = projectPath(config);

  var userConfig = loadProjectConfig(command, options, config);

  return extendConfig(config, userConfig);
}

module.exports = makeConfig;
<commit_msg>Revert "options.config type check readded. Fixes #415"<commit_after>var path = require('path');
var extendConfig = require('./extendConfig');

function projectPath (config) {
  // Legacy mode, if the cwd is the backstop module
  if (config.backstop === process.cwd()) {
    console.log('BackstopJS is running in legacy mode.');
    return path.join(__dirname, '../../../..');
  }
  return process.cwd();
}

function loadProjectConfig (command, options, config) {
  // TEST REPORT FILE NAME
  var customTestReportFileName = options && (options.testReportFileName || null);
  if (customTestReportFileName) {
    config.testReportFileName = options.testReportFileName || null;
  }

  var customConfigPath = options && (options.backstopConfigFilePath || options.configPath || options.config);
  if (customConfigPath) {
    if (path.isAbsolute(customConfigPath)) {
      config.backstopConfigFileName = customConfigPath;
    } else {
      config.backstopConfigFileName = path.join(config.projectPath, customConfigPath);
    }
  } else {
    config.backstopConfigFileName = path.join(config.projectPath, 'backstop.json');
  }

  var userConfig = {};
  var CMD_REQUIRES_CONFIG = command !== 'genConfig';
  if (CMD_REQUIRES_CONFIG) {
    if (options && typeof options.config === 'object') {
      console.log('BackstopJS uses a passed object as config');
      userConfig = options.config;
    } else if (config.backstopConfigFileName) {
      try {
        console.log('BackstopJS loading config: ', config.backstopConfigFileName, '\n');
        userConfig = require(config.backstopConfigFileName);
      } catch (e) {
        console.error('Error ' + e);
        process.exit(1);
      }
    }
  }

  return userConfig;
}

function makeConfig (command, options) {
  var config = {};

  config.args = options || {};

  config.backstop = path.join(__dirname, '../..');
  config.projectPath = projectPath(config);

  var userConfig = loadProjectConfig(command, options, config);

  return extendConfig(config, userConfig);
}

module.exports = makeConfig;
<|endoftext|>


<commit_before>'use strict';
window.addEventListener('DOMContentLoaded', function() {

//Variables
  var diskHold = null;
  var nbDisk = 7;
  var minMoves = Math.pow(2,nbDisk)-1;
  var gameBoard = document.querySelector('#gameBoard');
  var restart = document.querySelector('#restartGamePanel');
  var congrats = document.querySelector('#congratulationPanel')
  var towers = document.querySelectorAll('.tower');
  var nbMoves = document.querySelector('#nbMoves'); //get elemnt with id nbMoves
  var nbMovesFinal = document.querySelector('#nbMovesFinal');
  var unnecessaryMoves = document.querySelector('#nbUnnecessaryMoves');
  var moves; // moves count
  var confirmNewGame = document.querySelector('#confirmNewGame');
  var newGame = document.querySelector('#newGame');
  var continueGame = document.querySelector('#continueGame');

// Game initialisation

  function initGame(tower){
    // clear potential existing disks
    var existingDisks = document.querySelectorAll('.disk'); // returns a NodeList or null
    console.log(existingDisks);
    if(existingDisks){
      // .map can't be called directly on a NodeList so we call the map method of arrays on the NodeList
      Array.prototype.map.call(existingDisks, function(element){
        console.log(element);
        console.log(element.parentElement);
        element.parentElement.removeChild(element);
      });
    }
    tower.innerhtml = '';
    moves = 0;
    nbMoves.innerhtml = '0';
    for (var i=nbDisk; i>= 1; i--){
      var li = document.createElement("li");
      li.classList.add("disk", "disk"+i);
      li.dataset.value = i;
      tower.append(li);
    }
  }

//Game end
  function stateGame(){
    moves ++;
    nbMoves.innerHTML = moves;
    if (towers[1].children.length === nbDisk || towers[2].children.length === nbDisk){
      congrats.classList.toggle('hidden');
      var finalMoveCount = moves;
      nbMovesFinal.innerHTML = finalMoveCount;
      if (finalMoveCount == minMoves){
        var perfectScoreP = document.querySelector('#perfectornot')
        perfectScoreP.innerHTML = "Vous avez fait un score parfait!";
      } else{
        unnecessaryMoves.innerHTML = finalMoveCount - minMoves;
      }
    }
  }

// Game Turn

  function gameMove(tower){
    var disks = tower.children;
    console.log(disks);
    var topDisk;
    var topDiskValue;
    var towerIsEmpty = false;
    if (!tower.lastChild){
      towerIsEmpty = true;
    } else{
      // get the "higher" disk of the tower = the last one in the collection
      topDisk = tower.lastChild;
      // get the data-value attribute of this disk
      topDiskValue = topDisk.getAttribute('data-value');
      console.log(topDiskValue);
    }
    if (diskHold){
      var diskHoldValue = diskHold.getAttribute('data-value');
      console.log("j'ai un disque en main je veux le poser sa valeur est" + diskHoldValue);
      if (topDiskValue === diskHoldValue){
        diskHold.classList.remove('selected');
        diskHold = null;
      } else if (towerIsEmpty // if the destination tower is empty
                  ||topDiskValue > diskHoldValue //if the disk on the destination tower is bigger
                ){
        tower.appendChild(diskHold);
        diskHold.classList.remove('selected');
        diskHold = null;
        stateGame(); // increment the move counter & check if the player won or not
      }
    } else{
        topDisk.classList.add('selected');
        diskHold = topDisk;
    }
  }

  initGame(towers[0]);

  // Event Handlers

  // handle clicks on disks / towers
  function onClickTower(event){
    var myClassList = event.target.classList;
    console.log(myClassList);
    if(myClassList.contains('disk')){
      var tower = event.target.parentElement;
      gameMove(tower);
    } else if(myClassList.contains('tower')){
      gameMove(event.target);
    }
  }

  gameBoard.addEventListener("click", onClickTower);

  // handle game reset
  confirmNewGame.addEventListener("click", function(){restart.classList.toggle('hidden');});

  function onClickNewGame(){
    initGame(towers[0]);
    restart.classList.toggle('hidden');
  }

  newGame.addEventListener("click", onClickNewGame);

  // handle continue game
  continueGame.addEventListener("click", function(){restart.classList.toggle('hidden');});

});
<commit_msg>fixed counter of moves not resetting to 0<commit_after>'use strict';
window.addEventListener('DOMContentLoaded', function() {

//Variables
  var diskHold = null;
  var nbDisk = 7;
  var minMoves = Math.pow(2,nbDisk)-1;
  var gameBoard = document.querySelector('#gameBoard');
  var restart = document.querySelector('#restartGamePanel');
  var congrats = document.querySelector('#congratulationPanel')
  var towers = document.querySelectorAll('.tower');
  var nbMoves = document.querySelector('#nbMoves'); //get elemnt with id nbMoves
  var nbMovesFinal = document.querySelector('#nbMovesFinal');
  var unnecessaryMoves = document.querySelector('#nbUnnecessaryMoves');
  var moves; // moves count
  var confirmNewGame = document.querySelector('#confirmNewGame');
  var newGame = document.querySelector('#newGame');
  var continueGame = document.querySelector('#continueGame');

// Game initialisation

  function initGame(tower){
    // clear potential existing disks
    var existingDisks = document.querySelectorAll('.disk'); // returns a NodeList or null
    if(existingDisks){
      // .map can't be called directly on a NodeList so we call the map method of arrays on the NodeList
      Array.prototype.map.call(existingDisks, function(element){
        element.parentElement.removeChild(element);
      });
    }
    tower.innerHTML = '';
    moves = 0;
    nbMoves.innerHTML = '0';
    for (var i=nbDisk; i>= 1; i--){
      var li = document.createElement("li");
      li.classList.add("disk", "disk"+i);
      li.dataset.value = i;
      tower.append(li);
    }
  }

//Game end
  function stateGame(){
    moves ++;
    nbMoves.innerHTML = moves;
    if (towers[1].children.length === nbDisk || towers[2].children.length === nbDisk){
      congrats.classList.toggle('hidden');
      var finalMoveCount = moves;
      nbMovesFinal.innerHTML = finalMoveCount;
      if (finalMoveCount == minMoves){
        var perfectScoreP = document.querySelector('#perfectornot')
        perfectScoreP.innerHTML = "Vous avez fait un score parfait!";
      } else{
        unnecessaryMoves.innerHTML = finalMoveCount - minMoves;
      }
    }
  }

// Game Turn

  function gameMove(tower){
    var disks = tower.children;
    var topDisk;
    var topDiskValue;
    var towerIsEmpty = false;
    if (!tower.lastChild){
      towerIsEmpty = true;
    } else{
      // get the "higher" disk of the tower = the last one in the collection
      topDisk = tower.lastChild;
      // get the data-value attribute of this disk
      topDiskValue = topDisk.getAttribute('data-value');
    }
    if (diskHold){
      var diskHoldValue = diskHold.getAttribute('data-value');
      if (topDiskValue === diskHoldValue){
        diskHold.classList.remove('selected');
        diskHold = null;
      } else if (towerIsEmpty // if the destination tower is empty
                  ||topDiskValue > diskHoldValue //if the disk on the destination tower is bigger
                ){
        tower.appendChild(diskHold);
        diskHold.classList.remove('selected');
        diskHold = null;
        stateGame(); // increment the move counter & check if the player won or not
      }
    } else{
        topDisk.classList.add('selected');
        diskHold = topDisk;
    }
  }

  initGame(towers[0]);

  // Event Handlers

  // handle clicks on disks / towers
  function onClickTower(event){
    var myClassList = event.target.classList;
    if(myClassList.contains('disk')){
      var tower = event.target.parentElement;
      gameMove(tower);
    } else if(myClassList.contains('tower')){
      gameMove(event.target);
    }
  }

  gameBoard.addEventListener("click", onClickTower);

  // handle game reset
  confirmNewGame.addEventListener("click", function(){restart.classList.toggle('hidden');});

  function onClickNewGame(){
    initGame(towers[0]);
    restart.classList.toggle('hidden');
  }

  newGame.addEventListener("click", onClickNewGame);

  // handle continue game
  continueGame.addEventListener("click", function(){restart.classList.toggle('hidden');});

});
<|endoftext|>


<commit_before>// TODO: add play/pause/next/previous functionality to all algorithms

const fs = require("fs");

let network;

const container = $("#tree-simple")[0];
const options = {
  autoResize: true,
  layout: {
    hierarchical: {
      enabled: true,
      parentCentralization: true,
      sortMethod: "directed",
      edgeMinimization: true
    }
  },
  interaction: {
    navigationButtons: true
  },
  physics: {
    enabled: false
  }
};

$(document).ready(function() {
  $("#insert-btn").click(function() {
    addHeapNode();
  });

  $("#delete-btn").click(function() {
    deleteItem();
  });

  $("#random-btn").click(function() {
    const numberOfNodes = Math.floor(Math.random() * 30 + 10);
    if (network !== null) {
      network.destroy();
    }
    const data = getFreeScaleNetworkWithWeights(numberOfNodes);
    network = new Vis.Network(container, data, options);
  });
});

let nodes = [];
let edges = [];

network = new Vis.Network(container, [], options);

function insertItem(item) {
  let node = new HeapNode();

  unHighlightAllHeapCodeLines();

  $("#insert-function-call").css("color", "red");

  unHighlightHeapCodeLine("insert", 1);
  unHighlightHeapCodeLine("insert", 2);
  highlightHeapCodeLine("insert", 0);

  node.label = item;
  node.id = nodes.length;
  setTimeout(
    function() {
      if (nodes.length === 0) {
        node.root = true;
        node.color = "red";
        nodes.push(node);
        network = rebuildHeap(nodes, edges);
      } else {
        unHighlightHeapCodeLine("insert", 0);
        highlightHeapCodeLine("insert", 1);
        node.setParentNode(nodes[Math.floor((nodes.length - 1) / 2)]);
        node.getParentNode().addChild(node);
        const edge = {
          from: node.parent.id,
          to: node.id
        };

        edges.push(edge);
        nodes.push(node);

        node.color = "red";
        nodes[0].color = "#009688";

        network = rebuildHeap(nodes, edges);
        const steps = getInsertSteps(node);
        let cursor = nodes[nodes.length - 1];
        let prev = null;
        for (let index = 0; index < steps; index++) {
          (function(i) {
            highlightHeapCodeLine("insert", 2);
            setTimeout(
              function() {
                if (prev) {
                  prev.color = "#009688";
                }
                prev = cursor;
                let tempLabel = cursor.label;
                cursor.label = cursor.parent.label;
                cursor.parent.label = tempLabel;

                cursor.color = "red";
                cursor.parent.color = "red";

                cursor = cursor.parent;

                network = rebuildHeap(nodes, edges);
              },
              1000 + i * 1000
            );
          })(index);
        }
        setTimeout(
          function() {
            resetAllHeapNodesColors();
          },
          1000 * (steps + 1)
        );
      }
    },
    1000
  );
}

function deleteItem() {
  unHighlightAllHeapCodeLines();

  $("#delete-function-call").css("color", "red");

  highlightHeapCodeLine("delete", 0);
  nodes[0].color = "red";
  nodes[nodes.length - 1].color = "red";
  network = rebuildHeap(nodes, edges);

  setTimeout(
    function() {
      let tempLabel = nodes[0].label;
      nodes[0].label = nodes[nodes.length - 1].label;
      nodes[nodes.length - 1].label = tempLabel;
      network = rebuildHeap(nodes, edges);
    },
    1000
  );

  setTimeout(
    function() {
      unHighlightHeapCodeLine("delete", 0);
      highlightHeapCodeLine("delete", 1);
      nodes[nodes.length - 1].parent.children.pop();
      nodes.pop();
      network = rebuildHeap(nodes, edges);
    },
    2000
  );

  setTimeout(
    function() {
      unHighlightHeapCodeLine("delete", 1);
      highlightHeapCodeLine("delete", 2);
      impose(nodes[0]);
    },
    3000
  );
}

function impose(item) {
  unHighlightAllHeapCodeLines();
  $("#impose-function-call").css("color", "red");
  highlightHeapCodeLine("impose", 0);

  let cursor = item;
  const steps = getImposeSteps();

  for (let index = 0; index < steps; index++) {
    (function(i) {
      let prev = null;
      highlightHeapCodeLine("impose", 1);
      setTimeout(
        function() {
          if (prev) {
            prev.color = "#009688";
          }
          prev = cursor;

          let largerValue;

          if (cursor.children.length === 1) {
            largerValue = cursor.children[0];
          }
          else {
            if (cursor.children[0].label > cursor.children[1].label) {
                largerValue = cursor.children[0];
            } else {
                largerValue = cursor.children[1];
            }
          }

          cursor.color = "red";
          largerValue.color = "red";

          let temp = cursor.label;
          cursor.label = largerValue.label;
          largerValue.label = temp;

          cursor = largerValue;

          network = rebuildHeap(nodes, edges);
        },
        1000 * i
      );
    })(index);
  }
  setTimeout(
    function() {
      resetAllHeapNodesColors();
    },
    1000 * (steps + 1)
  );
}

function addHeapNode() {
  $("#insert-node-label-text").removeClass("is-empty");
  document.getElementById(
    "insert-node-saveButton"
  ).onclick = saveInsertNode.bind(this);
  document.getElementById(
    "insert-node-cancelButton"
  ).onclick = cancelInsertNode.bind(this);
  document.getElementById("insert-close-x1").onclick = cancelInsertNode.bind(
    this
  );
  $("#insert-node-popUp").css("display", "block");
}

function clearInsertNodePopUp() {
  $("#insert-node-saveButton").click(null);
  $("#insert-node-cancelButton").click(null);
  $("#insert-close-x1").click(null);
  $("#insert-node-popUp").css("display", "none");
}

function cancelInsertNode() {
  clearInsertNodePopUp();
}

function saveInsertNode() {
  const nodeLabel = parseInt($("#insert-node-label").val());
  if (!checkIfLabelExists(nodeLabel, network.body.data.nodes.get())) {
    clearInsertNodePopUp();
    $("#insert-n-label-text").text("Change node label");
    insertItem(nodeLabel);
  } else {
    $("#insert-node-label-text").addClass("has-error");
    $("#insert-n-label-text").text(
      "Label already exists - please input another one"
    );
  }
}

function rebuildHeap(nodes, edges) {
  const data = {
    nodes: nodes,
    edges: edges
  };
  network.destroy();
  network = new Vis.Network(container, data, options);
  return network;
}

function getInsertSteps() {
  let cursorOne = nodes[nodes.length - 1];
  const originalLabel = cursorOne.label;
  let numberOfSteps = 0;

  while (cursorOne != nodes[0] && originalLabel > cursorOne.parent.label) {
    cursorOne = cursorOne.parent;
    numberOfSteps++;
  }
  return numberOfSteps;
}

function getImposeSteps() {
  let imposeSteps = 0;
  let cursorOne = nodes[0];
  const originalLabel = nodes[0].label;

  while (
    cursorOne.children.length > 0
  ) {
    let largerValue;
    if (cursorOne.children.length === 1) {
      largerValue = cursorOne.children[0];
    }
    else {
      if (cursorOne.children[0].label > cursorOne.children[1].label) {
          largerValue = cursorOne.children[0];
      } else {
          largerValue = cursorOne.children[1];
      }
    }
    if (originalLabel >= largerValue.label) {
        break;
    }
    cursorOne = largerValue;
    imposeSteps++;
  }
  return imposeSteps;
}

function resetAllHeapNodesColors() {
  for (let i = 0; i < nodes.length; i++) {
    nodes[i].color = "#009688";
  }
  network = rebuildHeap(nodes, edges);
}

<commit_msg>unhighlighting all code lines in heap when algo is finished<commit_after>// TODO: add play/pause/next/previous functionality to all algorithms

const fs = require("fs");

let network;

const container = $("#tree-simple")[0];
const options = {
  autoResize: true,
  layout: {
    hierarchical: {
      enabled: true,
      parentCentralization: true,
      sortMethod: "directed",
      edgeMinimization: true
    }
  },
  interaction: {
    navigationButtons: true
  },
  physics: {
    enabled: false
  }
};

$(document).ready(function() {
  $("#insert-btn").click(function() {
    addHeapNode();
  });

  $("#delete-btn").click(function() {
    deleteItem();
  });

  $("#random-btn").click(function() {
    const numberOfNodes = Math.floor(Math.random() * 30 + 10);
    if (network !== null) {
      network.destroy();
    }
    const data = getFreeScaleNetworkWithWeights(numberOfNodes);
    network = new Vis.Network(container, data, options);
  });
});

let nodes = [];
let edges = [];

network = new Vis.Network(container, [], options);

function insertItem(item) {
  let node = new HeapNode();

  unHighlightAllHeapCodeLines();

  $("#insert-function-call").css("color", "red");

  unHighlightHeapCodeLine("insert", 1);
  unHighlightHeapCodeLine("insert", 2);
  highlightHeapCodeLine("insert", 0);

  node.label = item;
  node.id = nodes.length;
  setTimeout(
    function() {
      if (nodes.length === 0) {
        node.root = true;
        node.color = "red";
        nodes.push(node);
        network = rebuildHeap(nodes, edges);
      } else {
        unHighlightHeapCodeLine("insert", 0);
        highlightHeapCodeLine("insert", 1);
        node.setParentNode(nodes[Math.floor((nodes.length - 1) / 2)]);
        node.getParentNode().addChild(node);
        const edge = {
          from: node.parent.id,
          to: node.id
        };

        edges.push(edge);
        nodes.push(node);

        node.color = "red";
        nodes[0].color = "#009688";

        network = rebuildHeap(nodes, edges);
        const steps = getInsertSteps(node);
        let cursor = nodes[nodes.length - 1];
        let prev = null;
        for (let index = 0; index < steps; index++) {
          (function(i) {
            highlightHeapCodeLine("insert", 2);
            setTimeout(
              function() {
                if (prev) {
                  prev.color = "#009688";
                }
                prev = cursor;
                let tempLabel = cursor.label;
                cursor.label = cursor.parent.label;
                cursor.parent.label = tempLabel;

                cursor.color = "red";
                cursor.parent.color = "red";

                cursor = cursor.parent;

                network = rebuildHeap(nodes, edges);
              },
              1000 + i * 1000
            );
          })(index);
        }
        setTimeout(
          function() {
            resetAllHeapNodesColors();
            unHighlightAllHeapCodeLines();
          },
          1000 * (steps + 1)
        );
      }
    },
    1000
  );
}

function deleteItem() {
  unHighlightAllHeapCodeLines();

  $("#delete-function-call").css("color", "red");

  highlightHeapCodeLine("delete", 0);
  nodes[0].color = "red";
  nodes[nodes.length - 1].color = "red";
  network = rebuildHeap(nodes, edges);

  setTimeout(
    function() {
      let tempLabel = nodes[0].label;
      nodes[0].label = nodes[nodes.length - 1].label;
      nodes[nodes.length - 1].label = tempLabel;
      network = rebuildHeap(nodes, edges);
    },
    1000
  );

  setTimeout(
    function() {
      unHighlightHeapCodeLine("delete", 0);
      highlightHeapCodeLine("delete", 1);
      nodes[nodes.length - 1].parent.children.pop();
      nodes.pop();
      network = rebuildHeap(nodes, edges);
    },
    2000
  );

  setTimeout(
    function() {
      unHighlightHeapCodeLine("delete", 1);
      highlightHeapCodeLine("delete", 2);
      impose(nodes[0]);
    },
    3000
  );
}

function impose(item) {
  unHighlightAllHeapCodeLines();
  $("#impose-function-call").css("color", "red");
  highlightHeapCodeLine("impose", 0);

  let cursor = item;
  const steps = getImposeSteps();

  for (let index = 0; index < steps; index++) {
    (function(i) {
      let prev = null;
      highlightHeapCodeLine("impose", 1);
      setTimeout(
        function() {
          if (prev) {
            prev.color = "#009688";
          }
          prev = cursor;

          let largerValue;

          if (cursor.children.length === 1) {
            largerValue = cursor.children[0];
          }
          else {
            if (cursor.children[0].label > cursor.children[1].label) {
                largerValue = cursor.children[0];
            } else {
                largerValue = cursor.children[1];
            }
          }

          cursor.color = "red";
          largerValue.color = "red";

          let temp = cursor.label;
          cursor.label = largerValue.label;
          largerValue.label = temp;

          cursor = largerValue;

          network = rebuildHeap(nodes, edges);
        },
        1000 * i
      );
    })(index);
  }
  setTimeout(
    function() {
      resetAllHeapNodesColors();
      unHighlightAllHeapCodeLines();
    },
    1000 * (steps + 1)
  );
}

function addHeapNode() {
  $("#insert-node-label-text").removeClass("is-empty");
  document.getElementById(
    "insert-node-saveButton"
  ).onclick = saveInsertNode.bind(this);
  document.getElementById(
    "insert-node-cancelButton"
  ).onclick = cancelInsertNode.bind(this);
  document.getElementById("insert-close-x1").onclick = cancelInsertNode.bind(
    this
  );
  $("#insert-node-popUp").css("display", "block");
}

function clearInsertNodePopUp() {
  $("#insert-node-saveButton").click(null);
  $("#insert-node-cancelButton").click(null);
  $("#insert-close-x1").click(null);
  $("#insert-node-popUp").css("display", "none");
}

function cancelInsertNode() {
  clearInsertNodePopUp();
}

function saveInsertNode() {
  const nodeLabel = parseInt($("#insert-node-label").val());
  if (!checkIfLabelExists(nodeLabel, network.body.data.nodes.get())) {
    clearInsertNodePopUp();
    $("#insert-n-label-text").text("Change node label");
    insertItem(nodeLabel);
  } else {
    $("#insert-node-label-text").addClass("has-error");
    $("#insert-n-label-text").text(
      "Label already exists - please input another one"
    );
  }
}

function rebuildHeap(nodes, edges) {
  const data = {
    nodes: nodes,
    edges: edges
  };
  network.destroy();
  network = new Vis.Network(container, data, options);
  return network;
}

function getInsertSteps() {
  let cursorOne = nodes[nodes.length - 1];
  const originalLabel = cursorOne.label;
  let numberOfSteps = 0;

  while (cursorOne !== nodes[0] && originalLabel > cursorOne.parent.label) {
    cursorOne = cursorOne.parent;
    numberOfSteps++;
  }
  return numberOfSteps;
}

function getImposeSteps() {
  let imposeSteps = 0;
  let cursorOne = nodes[0];
  const originalLabel = nodes[0].label;

  while (
    cursorOne.children.length > 0
  ) {
    let largerValue;
    if (cursorOne.children.length === 1) {
      largerValue = cursorOne.children[0];
    }
    else {
      if (cursorOne.children[0].label > cursorOne.children[1].label) {
          largerValue = cursorOne.children[0];
      } else {
          largerValue = cursorOne.children[1];
      }
    }
    if (originalLabel >= largerValue.label) {
        break;
    }
    cursorOne = largerValue;
    imposeSteps++;
  }
  return imposeSteps;
}

function resetAllHeapNodesColors() {
  for (let i = 0; i < nodes.length; i++) {
    nodes[i].color = "#009688";
  }
  network = rebuildHeap(nodes, edges);
}

<|endoftext|>


<commit_before>define(function (require, exports, module) {
  'use strict';

  var Repository = app.getModule('core/Repository');
  var ProjectManager = app.getModule('engine/ProjectManager');
  var Engine = app.getModule('engine/Engine');
  var FileSystem = app.getModule('filesystem/FileSystem');
  var FileUtils = app.getModule('file/FileUtils');
  var Async = app.getModule('utils/Async');
  var UML = app.getModule('uml/UML');

  var CodeGenUtils = require('code-generator-utils');

  function RubyCodeGenerator(baseModel, basePath) {
    this.baseModel = baseModel;
    this.basePath = basePath;
  }

  RubyCodeGenerator.prototype.getIndentString = function (options) {
    var indent = [];
    var length = options.indentSpaces;

    if (options.useTabs) {
      return '\t';
    } else {
      var indent = [];
      var length = options.indentSpaces;
      for (var i = 0; i < length; i++) {
        indent.push(' ');
      }

      return indent.join('');
    }
  };

  RubyCodeGenerator.prototype.generate = function (element, path, options) {
    var result = new $.Deferred();
    var fullPath;
    var directory;
    var codeWriter;
    var file;

    if (element instanceof type.UMLPackage) {
      fullPath = path + '/' + element.name;
      directory = FileSystem.getDirectoryForPath(fullPath);
      directory.create(function (error, stat) {
        if (!error) {
          Async.doSequentially(element.ownedElements, function (child) {
            return generate(child, fullPath, options);
          }, false).then(result.resolve, result.reject);
        } else {
          result.reject(error);
        }
      });
    } else if (element instanceof type.UMLClass) {
      if (element.stereotype === 'annotationType') {
        codeWriter = new CodeGenUtils.CodeWriter(this.getIndentString(options));
        codeWriter.writeLine();
        codeWriter.writeLine('this is annotation');
        codeWriter.writeLine();
        fullPath = path + '/' + element.name + '.rb';
        file = FileSystem.getFileForPath(fullPath);
        FileUtils.writeText(file, codeWriter.getData(), true).then(result.resolve, result.reject);
      } else {
        codeWriter = new CodeGenUtils.CodeWriter(this.getIndentString(options));
        this.writeClass(codeWriter, element, options);
        fullPath = path + '/' + codeWriter.fileName(element.name) + '.rb';
        file = FileSystem.getFileForPath(fullPath);
        FileUtils.writeText(file, codeWriter.getData(), true).then(result.resolve, result.reject);
      }
    } else {
      result.resolve();
    }

    return result.promise();
  };

  RubyCodeGenerator.prototype.getVisibility = function (element) {
    switch (element.visibility) {
      case UML.VK_PUBLIC:
        return 'public';
      case UML.VK_PROTECTED:
        return 'protected';
      case UML.VK_PRIVATE:
        return 'private';
    }

    return null;
  };

  RubyCodeGenerator.prototype.getSuperClasses = function (element) {
    var inheritances = Repository.getRelationshipsOf(element, function (relationship) {
      return (relationship instanceof type.UMLGeneralization && relationship.source === element);
    });
    return _.map(inheritances, function (inherit) {
      return inherit.target;
    });
  };

  RubyCodeGenerator.prototype.writeConstructor = function (codeWriter, element, options) {
    if (element.name.length) {
      var terms = [];
      var len = element.attributes.length;

      terms.push('def initialize(');
      for (var i = 0; i < len; i++) {
        terms.push(element.attributes[i].name);
        if (i !== len - 1) {
          terms.push(', ');
        }
      }

      codeWriter.writeLine(terms.join('') + ')');
      codeWriter.indent();
      for (var j = 0; j < len; j++) {
        codeWriter.writeLine('@' + element.attributes[j].name + ' = ' + element.attributes[j].name);
      }

      codeWriter.outdent();
      codeWriter.writeLine('end');
    }
  };

  RubyCodeGenerator.prototype.writeAttributeAccessor = function (type, codeWriter, element, options) {
    var terms = [];

    if (element.name.length) {
      var i;
      var len = element.attributes.length;

      if (type === 'short') {
        terms.push('attr_accessor ');
        for (i = 0; i < len; i++) {
          terms.push(':' + element.attributes[i].name);
          if (i !== len - 1) {
            terms.push(', ');
          }
        }

        codeWriter.writeLine(terms.join(''));
      } else if (type === 'long') {
        for (i = 0; i < len; i++) {
          codeWriter.writeLine('def ' + element.attributes[i].name);
          codeWriter.indent();
          codeWriter.writeLine('@' + element.attributes[i].name);
          codeWriter.outdent();
          codeWriter.writeLine('end');
          codeWriter.writeLine();
          codeWriter.writeLine('def ' + element.attributes[i].name + '=(value)');
          codeWriter.indent();
          codeWriter.writeLine('@' + element.attributes[i].name + ' = value');
          codeWriter.outdent();
          codeWriter.writeLine('end');
          if (i !== len - 1) {
            codeWriter.writeLine();
          }
        }
      }
    }
  };

  RubyCodeGenerator.prototype.constructMethod = function (codeWriter, element, options) {
    if (element.name.length) {
      var parameters = element.getNonReturnParameters();
      var len = parameters.length;
      var methodVisibility = this.getVisibility(element);
      var indentationSpaces = this.getIndentString(options);
      var terms = '';

      terms += indentationSpaces;
      terms += 'def ' + element.name;
      if (len !== 0) {
        terms += '(';
        for (var i = 0; i < len; i++) {
          terms += parameters[i].name;
          if (i !== len - 1) {
            terms += ', ';
          } else {
            terms += ')';
          }
        }
      }

      terms += '\n';
      if (methodVisibility === 'public') {
        terms += indentationSpaces + 'end';
      } else {
        terms += indentationSpaces;
        terms += indentationSpaces + 'end';
      }
    }

    return terms;
  }

  RubyCodeGenerator.prototype.writeToStringMethod = function (codeWriter) {
    codeWriter.indent();
    codeWriter.writeLine('def to_s');
    codeWriter.indent();
    codeWriter.writeLine('\"{Your string representation of the object will be written here}\"');
    codeWriter.outdent();
    codeWriter.writeLine('end');
  }

  RubyCodeGenerator.prototype.writeMethod = function (codeWriter, publicTerms, protectedTerms, privateTerms, options) {
    if (publicTerms.length) {
      codeWriter.writeLine();
      codeWriter.writeLine(publicTerms);
    }

    if (protectedTerms.length) {
      codeWriter.indent();
      codeWriter.writeLine('protected');
      codeWriter.writeLine();
      codeWriter.writeLine(protectedTerms);
      codeWriter.outdent();
    }

    if (privateTerms.length) {
      codeWriter.indent();
      codeWriter.writeLine('private');
      codeWriter.writeLine();
      codeWriter.writeLine(privateTerms);
      codeWriter.outdent();
    }

    if (options.rubyToStringMethod) {
      codeWriter.writeLine();
      this.writeToStringMethod(codeWriter);
    }
  };

  RubyCodeGenerator.prototype.writeClass = function (codeWriter, element, options) {
    var terms = [];

    terms.push('class');
    terms.push(element.name);

    var _inheritance = this.getSuperClasses(element);
    if (_inheritance.length) {
      terms.push('< ' + _inheritance[0].name);
    }

    codeWriter.writeLine(terms.join(' '));
    codeWriter.indent();

    if (options.useAttributeAccessor) {
      this.writeAttributeAccessor('short', codeWriter, element, options);
      codeWriter.writeLine();
    }

    if (options.initializeMethod) {
      this.writeConstructor(codeWriter, element, options);
    }

    if (!options.useAttributeAccessor) {
      codeWriter.writeLine();
      this.writeAttributeAccessor('long', codeWriter, element, options);
    }

    codeWriter.outdent();

    var len = element.operations.length;
    var publicTerms = '';
    var protectedTerms = '';
    var privateTerms = '';

    for (var i = 0; i < len; i++) {
      var methodVisibility = this.getVisibility(element.operations[i]);
      var methodString = this.constructMethod(codeWriter, element.operations[i], options);

      if (i !== len - 1) {
        if (methodVisibility === 'public') {
          publicTerms += methodString;
          publicTerms += '\n\n';
        } else if (methodVisibility === 'protected') {
          protectedTerms += methodString;
          protectedTerms += '\n\n';
        } else if (methodVisibility === 'private') {
          privateTerms += methodString;
          privateTerms += '\n\n';
        }
      } else {
        if (methodVisibility === 'public') {
          publicTerms += methodString;
        } else if (methodVisibility === 'protected') {
          protectedTerms += methodString;
        } else if (methodVisibility === 'private') {
          privateTerms += methodString;
        }
      }
    }

    this.writeMethod(codeWriter, publicTerms, protectedTerms, privateTerms, options);
    codeWriter.outdent();
    codeWriter.writeLine('end');
  };

  function generate(baseModel, basePath, options) {
    var result = new $.Deferred();
    var rubyCodeGenerator = new RubyCodeGenerator(baseModel, basePath);
    return rubyCodeGenerator.generate(baseModel, basePath, options);
  }

  exports.generate = generate;
});
<commit_msg>Fix typo in using tab instead of spaces option<commit_after>define(function (require, exports, module) {
  'use strict';

  var Repository = app.getModule('core/Repository');
  var ProjectManager = app.getModule('engine/ProjectManager');
  var Engine = app.getModule('engine/Engine');
  var FileSystem = app.getModule('filesystem/FileSystem');
  var FileUtils = app.getModule('file/FileUtils');
  var Async = app.getModule('utils/Async');
  var UML = app.getModule('uml/UML');

  var CodeGenUtils = require('code-generator-utils');

  function RubyCodeGenerator(baseModel, basePath) {
    this.baseModel = baseModel;
    this.basePath = basePath;
  }

  RubyCodeGenerator.prototype.getIndentString = function (options) {
    var indent = [];
    var length = options.indentSpaces;

    if (options.useTab) {
      return '\t';
    } else {
      var indent = [];
      var length = options.indentSpaces;
      for (var i = 0; i < length; i++) {
        indent.push(' ');
      }

      return indent.join('');
    }
  };

  RubyCodeGenerator.prototype.generate = function (element, path, options) {
    var result = new $.Deferred();
    var fullPath;
    var directory;
    var codeWriter;
    var file;

    if (element instanceof type.UMLPackage) {
      fullPath = path + '/' + element.name;
      directory = FileSystem.getDirectoryForPath(fullPath);
      directory.create(function (error, stat) {
        if (!error) {
          Async.doSequentially(element.ownedElements, function (child) {
            return generate(child, fullPath, options);
          }, false).then(result.resolve, result.reject);
        } else {
          result.reject(error);
        }
      });
    } else if (element instanceof type.UMLClass) {
      if (element.stereotype === 'annotationType') {
        codeWriter = new CodeGenUtils.CodeWriter(this.getIndentString(options));
        codeWriter.writeLine();
        codeWriter.writeLine('this is annotation');
        codeWriter.writeLine();
        fullPath = path + '/' + element.name + '.rb';
        file = FileSystem.getFileForPath(fullPath);
        FileUtils.writeText(file, codeWriter.getData(), true).then(result.resolve, result.reject);
      } else {
        codeWriter = new CodeGenUtils.CodeWriter(this.getIndentString(options));
        this.writeClass(codeWriter, element, options);
        fullPath = path + '/' + codeWriter.fileName(element.name) + '.rb';
        file = FileSystem.getFileForPath(fullPath);
        FileUtils.writeText(file, codeWriter.getData(), true).then(result.resolve, result.reject);
      }
    } else {
      result.resolve();
    }

    return result.promise();
  };

  RubyCodeGenerator.prototype.getVisibility = function (element) {
    switch (element.visibility) {
      case UML.VK_PUBLIC:
        return 'public';
      case UML.VK_PROTECTED:
        return 'protected';
      case UML.VK_PRIVATE:
        return 'private';
    }

    return null;
  };

  RubyCodeGenerator.prototype.getSuperClasses = function (element) {
    var inheritances = Repository.getRelationshipsOf(element, function (relationship) {
      return (relationship instanceof type.UMLGeneralization && relationship.source === element);
    });
    return _.map(inheritances, function (inherit) {
      return inherit.target;
    });
  };

  RubyCodeGenerator.prototype.writeConstructor = function (codeWriter, element, options) {
    if (element.name.length) {
      var terms = [];
      var len = element.attributes.length;

      terms.push('def initialize(');
      for (var i = 0; i < len; i++) {
        terms.push(element.attributes[i].name);
        if (i !== len - 1) {
          terms.push(', ');
        }
      }

      codeWriter.writeLine(terms.join('') + ')');
      codeWriter.indent();
      for (var j = 0; j < len; j++) {
        codeWriter.writeLine('@' + element.attributes[j].name + ' = ' + element.attributes[j].name);
      }

      codeWriter.outdent();
      codeWriter.writeLine('end');
    }
  };

  RubyCodeGenerator.prototype.writeAttributeAccessor = function (type, codeWriter, element, options) {
    var terms = [];

    if (element.name.length) {
      var i;
      var len = element.attributes.length;

      if (type === 'short') {
        terms.push('attr_accessor ');
        for (i = 0; i < len; i++) {
          terms.push(':' + element.attributes[i].name);
          if (i !== len - 1) {
            terms.push(', ');
          }
        }

        codeWriter.writeLine(terms.join(''));
      } else if (type === 'long') {
        for (i = 0; i < len; i++) {
          codeWriter.writeLine('def ' + element.attributes[i].name);
          codeWriter.indent();
          codeWriter.writeLine('@' + element.attributes[i].name);
          codeWriter.outdent();
          codeWriter.writeLine('end');
          codeWriter.writeLine();
          codeWriter.writeLine('def ' + element.attributes[i].name + '=(value)');
          codeWriter.indent();
          codeWriter.writeLine('@' + element.attributes[i].name + ' = value');
          codeWriter.outdent();
          codeWriter.writeLine('end');
          if (i !== len - 1) {
            codeWriter.writeLine();
          }
        }
      }
    }
  };

  RubyCodeGenerator.prototype.constructMethod = function (codeWriter, element, options) {
    if (element.name.length) {
      var parameters = element.getNonReturnParameters();
      var len = parameters.length;
      var methodVisibility = this.getVisibility(element);
      var indentationSpaces = this.getIndentString(options);
      var terms = '';

      terms += indentationSpaces;
      terms += 'def ' + element.name;
      if (len !== 0) {
        terms += '(';
        for (var i = 0; i < len; i++) {
          terms += parameters[i].name;
          if (i !== len - 1) {
            terms += ', ';
          } else {
            terms += ')';
          }
        }
      }

      terms += '\n';
      if (methodVisibility === 'public') {
        terms += indentationSpaces + 'end';
      } else {
        terms += indentationSpaces;
        terms += indentationSpaces + 'end';
      }
    }

    return terms;
  }

  RubyCodeGenerator.prototype.writeToStringMethod = function (codeWriter) {
    codeWriter.indent();
    codeWriter.writeLine('def to_s');
    codeWriter.indent();
    codeWriter.writeLine('\"{Your string representation of the object will be written here}\"');
    codeWriter.outdent();
    codeWriter.writeLine('end');
  }

  RubyCodeGenerator.prototype.writeMethod = function (codeWriter, publicTerms, protectedTerms, privateTerms, options) {
    if (publicTerms.length) {
      codeWriter.writeLine();
      codeWriter.writeLine(publicTerms);
    }

    if (protectedTerms.length) {
      codeWriter.indent();
      codeWriter.writeLine('protected');
      codeWriter.writeLine();
      codeWriter.writeLine(protectedTerms);
      codeWriter.outdent();
    }

    if (privateTerms.length) {
      codeWriter.indent();
      codeWriter.writeLine('private');
      codeWriter.writeLine();
      codeWriter.writeLine(privateTerms);
      codeWriter.outdent();
    }

    if (options.rubyToStringMethod) {
      codeWriter.writeLine();
      this.writeToStringMethod(codeWriter);
    }
  };

  RubyCodeGenerator.prototype.writeClass = function (codeWriter, element, options) {
    var terms = [];

    terms.push('class');
    terms.push(element.name);

    var _inheritance = this.getSuperClasses(element);
    if (_inheritance.length) {
      terms.push('< ' + _inheritance[0].name);
    }

    codeWriter.writeLine(terms.join(' '));
    codeWriter.indent();

    if (options.useAttributeAccessor) {
      this.writeAttributeAccessor('short', codeWriter, element, options);
      codeWriter.writeLine();
    }

    if (options.initializeMethod) {
      this.writeConstructor(codeWriter, element, options);
    }

    if (!options.useAttributeAccessor) {
      codeWriter.writeLine();
      this.writeAttributeAccessor('long', codeWriter, element, options);
    }

    codeWriter.outdent();

    var len = element.operations.length;
    var publicTerms = '';
    var protectedTerms = '';
    var privateTerms = '';

    for (var i = 0; i < len; i++) {
      var methodVisibility = this.getVisibility(element.operations[i]);
      var methodString = this.constructMethod(codeWriter, element.operations[i], options);

      if (i !== len - 1) {
        if (methodVisibility === 'public') {
          publicTerms += methodString;
          publicTerms += '\n\n';
        } else if (methodVisibility === 'protected') {
          protectedTerms += methodString;
          protectedTerms += '\n\n';
        } else if (methodVisibility === 'private') {
          privateTerms += methodString;
          privateTerms += '\n\n';
        }
      } else {
        if (methodVisibility === 'public') {
          publicTerms += methodString;
        } else if (methodVisibility === 'protected') {
          protectedTerms += methodString;
        } else if (methodVisibility === 'private') {
          privateTerms += methodString;
        }
      }
    }

    this.writeMethod(codeWriter, publicTerms, protectedTerms, privateTerms, options);
    codeWriter.outdent();
    codeWriter.writeLine('end');
  };

  function generate(baseModel, basePath, options) {
    var result = new $.Deferred();
    var rubyCodeGenerator = new RubyCodeGenerator(baseModel, basePath);
    return rubyCodeGenerator.generate(baseModel, basePath, options);
  }

  exports.generate = generate;
});
<|endoftext|>


<commit_before>/*
 * collection.js - Utilities for wrapping collection operations so that
 *                 operations will not directly be applied to the server's
 *                 underlying MongoDB database, but instead will be sent
 *                 through the distributed database.
 */

Meteor.collections = {};

wrap_insert = function (collection, getUserId, onflict_resolution) {
  Meteor.collections[collection._name] = collection;
  if (Meteor.isServer) {
    if (!conflict_resolution || !(conflict_resolution instanceof Function)) {
      // Default conflict resolution is to take the object with the latest
      // timestamp.
      conflict_resolution = function (doc1, doc2) {
        return (doc1._ts >= doc2._ts ? doc1 : doc2);
      }
    }
    collection.localFindOne = collection.findOne;
    collection.localUpdate = collection.update;
    var localInsert = collection.insert;
    localInsert = Meteor._wrapAsync(Meteor.bindEnvironment(localInsert, Meteor._debug, collection));
    collection.localPut = Meteor._wrapAsync(function (doc, callback) {
      console.log(collection._name + ".localPut defined");
      // If an object currently exists, find it, perform conflict
      // resolution, and update the document.
      // Otherwise, insert the new document.
      var docCurrent = collection.localFindOne({_id: doc._id});
      if (docCurrent) {
        doc = conflict_resolution(docCurrent, doc);
        return collection.localUpdate(doc._id, doc, function (error) { return callback(error, doc._id); });
      }
      else {
        return localInsert(doc, callback);
      }
    });
    console.log(collection._name + ".localPut defined");
    collection.localRemove = collection.remove;
    collection.remove = Meteor._wrapAsync(function (id, callback) {
      console.log(collection._name + ".remove redefined");
      // We need to keep track of deleted objects. So a remove is actually
      // just overwriting the object with an empty object.
      return collection.insert({_id: id}, function (error) { return callback(error, 1); });
    });
    console.log(collection._name + ".remove redefined");
    collection.insert = Meteor._wrapAsync(function (doc, callback) {
      console.log(collection._name + ".insert redefined");
      // The server method that gets called by the client. Instead of
      // inserting directly into MongoDB, call out to the distributed
      // database. But first, give the object an _id (so that all replicas
      // will get the same _id for this object) and a timestamp (for
      // conflict resolution).
      doc = _.clone(doc);
      if (!doc._id) {
        doc._id = Random.id();
      }
      doc._ts = new Date();
      reply = CoordinatorPut(collection._name, getUserId(doc), doc._id, doc);
      console.log("about to finish collection.insert with " + reply);
      if ("OK" === reply) {
        return collection.localPut(doc, callback);
      }
    });
    console.log(collection._name + ".insert redefined");
  }
  else if (Meteor.isClient) {
    _.each(["update", "upsert"], function (name) {
      collection[name] = function () {
        throw new Meteor.Error(405, "Method Not Allowed",
                               collection._name+"."+name+"() not allowed. " +
                               "Instead call "+collection._name+".insert().");
      }
    });
  }
};

wrap_insert(
  Meteor.users,
  function (doc) { return doc._id; },
  function (doc1, doc2) {
    // use the latest version, but always keep the certificate
    var doc = _.clone(doc1._ts >= doc2._ts ? doc1 : doc2);
    var other = (doc1._ts >= doc2._ts ? doc2 : doc1);
    if (!doc._pubkey_cert) {
      doc._pubkey_cert = other._pubkey_cert;
      doc.emails[0].verified = other.emails[0].verified;
    }
});

wrap_insert(Principals, function (doc) { return doc.name; });

// not WrappedKeys, Certs, PrincType PrincType doesn't need duplication (the
// objects are static for an application), and the others aren't supported.
<commit_msg>bugfix<commit_after>/*
 * collection.js - Utilities for wrapping collection operations so that
 *                 operations will not directly be applied to the server's
 *                 underlying MongoDB database, but instead will be sent
 *                 through the distributed database.
 */

Meteor.collections = {};

wrap_insert = function (collection, getUserId, onflict_resolution) {
  Meteor.collections[collection._name] = collection;
  if (Meteor.isServer) {
    if (!conflict_resolution || !(conflict_resolution instanceof Function)) {
      // Default conflict resolution is to take the object with the latest
      // timestamp.
      conflict_resolution = function (doc1, doc2) {
        return (doc1._ts >= doc2._ts ? doc1 : doc2);
      }
    }
    collection.localFindOne = collection.findOne;
    collection._collection.localUpdate = collection._collection.update;
    var localInsert = collection._collection.insert;
    localInsert = Meteor._wrapAsync(Meteor.bindEnvironment(localInsert, Meteor._debug, collection._collection));
    collection.localPut = Meteor._wrapAsync(function (doc, callback) {
      console.log(collection._name + ".localPut defined");
      // If an object currently exists, find it, perform conflict
      // resolution, and update the document.
      // Otherwise, insert the new document.
      var docCurrent = collection.localFindOne({_id: doc._id});
      if (docCurrent) {
        doc = conflict_resolution(docCurrent, doc);
        return collection._collection.localUpdate(doc._id, doc, function (error) { return callback(error, doc._id); });
      }
      else {
        return localInsert(doc, callback);
      }
    });
    console.log(collection._name + ".localPut defined");
    collection._collection.localRemove = collection._collection.remove;
    collection._collection.remove = Meteor._wrapAsync(function (id, callback) {
      console.log(collection._name + ".remove redefined");
      // We need to keep track of deleted objects. So a remove is actually
      // just overwriting the object with an empty object.
      return collection._collection.insert({_id: id}, function (error) { return callback(error, 1); });
    });
    console.log(collection._name + ".remove redefined");
    collection._collection.insert = Meteor._wrapAsync(function (doc, callback._collection) {
      console.log(collection._name + ".insert redefined");
      // The server method that gets called by the client. Instead of
      // inserting directly into MongoDB, call out to the distributed
      // database. But first, give the object an _id (so that all replicas
      // will get the same _id for this object) and a timestamp (for
      // conflict resolution).
      doc = _.clone(doc);
      if (!doc._id) {
        doc._id = Random.id();
      }
      doc._ts = new Date();
      reply = CoordinatorPut(collection._name, getUserId(doc), doc._id, doc);
      console.log("about to finish collection.insert with " + reply);
      if ("OK" === reply) {
        return collection.localPut(doc, callback);
      }
    });
    console.log(collection._name + ".insert redefined");
  }
  else if (Meteor.isClient) {
    _.each(["update", "upsert"], function (name) {
      collection[name] = function () {
        throw new Meteor.Error(405, "Method Not Allowed",
                               collection._name+"."+name+"() not allowed. " +
                               "Instead call "+collection._name+".insert().");
      }
    });
  }
};

wrap_insert(
  Meteor.users,
  function (doc) { return doc._id; },
  function (doc1, doc2) {
    // use the latest version, but always keep the certificate
    var doc = _.clone(doc1._ts >= doc2._ts ? doc1 : doc2);
    var other = (doc1._ts >= doc2._ts ? doc2 : doc1);
    if (!doc._pubkey_cert) {
      doc._pubkey_cert = other._pubkey_cert;
      doc.emails[0].verified = other.emails[0].verified;
    }
});

wrap_insert(Principals, function (doc) { return doc.name; });

// not WrappedKeys, Certs, PrincType PrincType doesn't need duplication (the
// objects are static for an application), and the others aren't supported.
<|endoftext|>


<commit_before>import totpCheck from './totpCheck';

function getPrevWindowOption(options, windowCount) {
  return Object.assign(options, {
    epoch: options.epoch - (options.step * windowCount)
  });
}

/**
 * Checks the provided OTP token against system generated token
 * with support for checking previous x time-step windows
 *
 * @module otplib-core/totpCheck
 * @param {string} token - the OTP token to check
 * @param {string} secret - your secret that is used to generate the token
 * @param {object} options - options which was used to generate it originally
 * @return {boolean}
 */
function totpCheckWithWindow(token, secret, options) {
  let opt = Object.assign({}, options);
  const rounds = Math.floor(opt.window || 0) + 1;

  for (let i = 0; i < rounds; i++) {
    opt = getPrevWindowOption(opt, i);

    if (totpCheck(token, secret, opt)) {
      return true;
    }
  }

  return false;
}

export default totpCheckWithWindow;
<commit_msg>update jsdoc module name in totpCheckWithWindow<commit_after>import totpCheck from './totpCheck';

function getPrevWindowOption(options, windowCount) {
  return Object.assign(options, {
    epoch: options.epoch - (options.step * windowCount)
  });
}

/**
 * Checks the provided OTP token against system generated token
 * with support for checking previous x time-step windows
 *
 * @module otplib-core/totpCheckWithWindow
 * @param {string} token - the OTP token to check
 * @param {string} secret - your secret that is used to generate the token
 * @param {object} options - options which was used to generate it originally
 * @return {boolean}
 */
function totpCheckWithWindow(token, secret, options) {
  let opt = Object.assign({}, options);
  const rounds = Math.floor(opt.window || 0) + 1;

  for (let i = 0; i < rounds; i++) {
    opt = getPrevWindowOption(opt, i);

    if (totpCheck(token, secret, opt)) {
      return true;
    }
  }

  return false;
}

export default totpCheckWithWindow;
<|endoftext|>