<commit_before>//  Created by Juan Corona <juanc@evidentpoint.com>
//  Copyright (c) 2014 Readium Foundation and/or its licensees. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without modification,
//  are permitted provided that the following conditions are met:
//  1. Redistributions of source code must retain the above copyright notice, this
//  list of conditions and the following disclaimer.
//  2. Redistributions in binary form must reproduce the above copyright notice,
//  this list of conditions and the following disclaimer in the documentation and/or
//  other materials provided with the distribution.
//  3. Neither the name of the organization nor the names of its contributors may be
//  used to endorse or promote products derived from this software without specific
//  prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
//  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
//  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
//  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
//  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
//  OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
//  OF THE POSSIBILITY OF SUCH DAMAGE.

//TODO: This could be made into a plugin in the future.
// A plugin would be ideal because we can make a light-weight alternative that doesn't need the FontLoader shim and the CSSOM parser.
define(["jquery", "underscore", "FontLoader", "cssom"], function($, _, FontLoader, CSSOM) {

var FontLoaderFallback = function(document, options) {
    var debug = options.debug;

    var getRestrictedCssRules = function (styleSheet, callback) {
        $.get(styleSheet.href).done(function(data) {
            callback(CSSOM.parse(data).cssRules);
        }).fail(function() {
            callback(null);
        });
    };

    var getUsedFonts = function(callback) {
        var styleSheets = document.styleSheets;
        var fontFamilies = [];
        var fontFamilyRules = [];

        // if no style sheets are found return immediately
        if (!styleSheets || styleSheets.length <= 0) {
            callback([]);
            return;
        }

        var getFontFamilyFromRule = function(rule) {
            if (rule.style && (rule.style.getPropertyValue || rule.style.fontFamily)) {
                return rule.style.getPropertyValue("font-family") || rule.style.fontFamily;
            }
        }

        var returnUsedFonts = function() {
            if (debug) {
                console.log(fontFamilies);
            }
            var usedFontFamilies = [];
            _.each(fontFamilyRules, function(rule) {
                var usedFontFamily = _.find(fontFamilies, function(family) {
                    var fontFamily = getFontFamilyFromRule(rule);
                    if (fontFamily && ~fontFamily.indexOf(family[1])) {
                        return true;
                    }
                });

                if (usedFontFamily && rule.selectorText && !_.contains(usedFontFamilies, usedFontFamily[0]) && document.querySelector(rule.selectorText)) {
                    usedFontFamilies.push(usedFontFamily[0]);
                }
            });

            if (debug) {
                console.log(usedFontFamilies);
            }

            callback(usedFontFamilies);
        };

        var processedCount = 0;
        var processCssRules = function(cssRules) {
            _.each(cssRules, function(rule) {
                var fontFamily = getFontFamilyFromRule(rule);
                if (fontFamily) {
                    if (rule.type === CSSRule.FONT_FACE_RULE) {
                        fontFamilies.push([fontFamily.replace(/(^['"]|['"]$)/g, '').replace(/\\(['"])/g, '$1'), fontFamily]);
                    } else {
                        fontFamilyRules.push(rule);
                    }
                }
            });

            processedCount++;

            if (processedCount >= styleSheets.length) {
                returnUsedFonts();
            }
        };

        _.each(styleSheets, function(styleSheet) {
            var cssRules;
            // Firefox (and possibly IE as well) throw a security exception if the CSS was loaded from a different domain.
            // Other browsers just have null as the value of cssRules for that case.
            try {
                cssRules = styleSheet.cssRules || styleSheet.rules;
            } catch (ignored) {}

            if (!cssRules) {
                getRestrictedCssRules(styleSheet, processCssRules);
            } else {
                processCssRules(cssRules);
            }
        });
    };

    return function(callback) {
        callback = _.once(callback);
        var loadCount = 0;

        getUsedFonts(function(usedFontFamilies){
            var fontLoader = new FontLoader(usedFontFamilies, {
                "fontsLoaded": function(error) {
                    if (debug) {
                        if (error !== null) {
                            // Reached the timeout but not all fonts were loaded
                            console.log("font loader: " + error.message, error.notLoadedFonts);
                        } else {
                            // All fonts were loaded
                            console.log("font loader: all fonts were loaded");
                        }
                    }
                    callback();
                },
                "fontLoaded": function(font) {
                    loadCount++;
                    if (debug) {
                        console.log("font loaded: " + font.family);
                    }
                    if (usedFontFamilies.length > options.minLoadCount && (loadCount / usedFontFamilies.length) >= options.minLoadRatio) {

                        if (debug) {
                            console.log('font loader: early callback');
                        }
                        callback();
                    }
                }
            }, options.timeout, document);

            fontLoader.loadFonts();
        });
    };
};

var FontLoaderNative = function(document, options) {
    var debug = options.debug;

    return function(callback) {
        callback = _.once(callback);
        var loadCount = 0;

        var fontFaceCount = document.fonts.size;
        var fontLoaded = function(font) {
            loadCount++;
            if (debug) {
                console.log("(native) font loaded: " + font.family);
            }
            if (fontFaceCount > options.minLoadCount && (loadCount / fontFaceCount) >= options.minLoadRatio) {

                if (debug) {
                    console.log('(native) font loader: early callback');
                }
                callback();
            }
        }

        var fontIterator = function(font) {
            font.loaded.then(function() {
                fontLoaded(font);
            });
        };

        // For some reason (at this time) Chrome's implementation has a .forEach
        // but it is not Array-like. This is opposite with Firefox's though.
        if (document.fonts.forEach) {
            document.fonts.forEach(fontIterator);
        } else {
            _.each(document.fonts, fontIterator);
        }

        document.fonts.ready.then(function() {
            if (debug) {
                // All fonts were loaded
                console.log("(native) font loader: all fonts were loaded");
            }
            callback();
        });

        window.setTimeout(function() {
            if (debug && loadCount !== fontFaceCount) {
                console.log('(native) font loader: timeout, not all fonts loaded/required');
            } else if (debug) {
                console.log('(native) font loader: timeout');
            }
            callback();
        }, options.timeout);
    }
}

var FontLoaderWrapper = function($iframe, options) {
    options = options || {};

    options.debug = options.debug || false;
    options.timeout = options.timeout || 1500;
    options.minLoadCount = options.minLoadCount || 3;
    options.minLoadRatio = options.minLoadRatio || 0.75;

    var document = $iframe[0].contentDocument;

    // For browsers without CSS Font Loading Module
    var fallbackNeeded = !document.fonts;

    var fontLoader = fallbackNeeded ? FontLoaderFallback : FontLoaderNative;

    this.waitForFonts = fontLoader(document, options);
};

return FontLoaderWrapper;

});
<commit_msg>Font loader, native: FontFaceSet interface on early implementations had ready as a function instead of an attribute This fixes that by supporting both types of invocation<commit_after>//  Created by Juan Corona <juanc@evidentpoint.com>
//  Copyright (c) 2014 Readium Foundation and/or its licensees. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without modification,
//  are permitted provided that the following conditions are met:
//  1. Redistributions of source code must retain the above copyright notice, this
//  list of conditions and the following disclaimer.
//  2. Redistributions in binary form must reproduce the above copyright notice,
//  this list of conditions and the following disclaimer in the documentation and/or
//  other materials provided with the distribution.
//  3. Neither the name of the organization nor the names of its contributors may be
//  used to endorse or promote products derived from this software without specific
//  prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
//  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
//  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
//  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
//  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
//  OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
//  OF THE POSSIBILITY OF SUCH DAMAGE.

//TODO: This could be made into a plugin in the future.
// A plugin would be ideal because we can make a light-weight alternative that doesn't need the FontLoader shim and the CSSOM parser.
define(["jquery", "underscore", "FontLoader", "cssom"], function($, _, FontLoader, CSSOM) {

var FontLoaderFallback = function(document, options) {
    var debug = options.debug;

    var getRestrictedCssRules = function (styleSheet, callback) {
        $.get(styleSheet.href).done(function(data) {
            callback(CSSOM.parse(data).cssRules);
        }).fail(function() {
            callback(null);
        });
    };

    var getUsedFonts = function(callback) {
        var styleSheets = document.styleSheets;
        var fontFamilies = [];
        var fontFamilyRules = [];

        // if no style sheets are found return immediately
        if (!styleSheets || styleSheets.length <= 0) {
            callback([]);
            return;
        }

        var getFontFamilyFromRule = function(rule) {
            if (rule.style && (rule.style.getPropertyValue || rule.style.fontFamily)) {
                return rule.style.getPropertyValue("font-family") || rule.style.fontFamily;
            }
        }

        var returnUsedFonts = function() {
            if (debug) {
                console.log(fontFamilies);
            }
            var usedFontFamilies = [];
            _.each(fontFamilyRules, function(rule) {
                var usedFontFamily = _.find(fontFamilies, function(family) {
                    var fontFamily = getFontFamilyFromRule(rule);
                    if (fontFamily && ~fontFamily.indexOf(family[1])) {
                        return true;
                    }
                });

                if (usedFontFamily && rule.selectorText && !_.contains(usedFontFamilies, usedFontFamily[0]) && document.querySelector(rule.selectorText)) {
                    usedFontFamilies.push(usedFontFamily[0]);
                }
            });

            if (debug) {
                console.log(usedFontFamilies);
            }

            callback(usedFontFamilies);
        };

        var processedCount = 0;
        var processCssRules = function(cssRules) {
            _.each(cssRules, function(rule) {
                var fontFamily = getFontFamilyFromRule(rule);
                if (fontFamily) {
                    if (rule.type === CSSRule.FONT_FACE_RULE) {
                        fontFamilies.push([fontFamily.replace(/(^['"]|['"]$)/g, '').replace(/\\(['"])/g, '$1'), fontFamily]);
                    } else {
                        fontFamilyRules.push(rule);
                    }
                }
            });

            processedCount++;

            if (processedCount >= styleSheets.length) {
                returnUsedFonts();
            }
        };

        _.each(styleSheets, function(styleSheet) {
            var cssRules;
            // Firefox (and possibly IE as well) throw a security exception if the CSS was loaded from a different domain.
            // Other browsers just have null as the value of cssRules for that case.
            try {
                cssRules = styleSheet.cssRules || styleSheet.rules;
            } catch (ignored) {}

            if (!cssRules) {
                getRestrictedCssRules(styleSheet, processCssRules);
            } else {
                processCssRules(cssRules);
            }
        });
    };

    return function(callback) {
        callback = _.once(callback);
        var loadCount = 0;

        getUsedFonts(function(usedFontFamilies){
            var fontLoader = new FontLoader(usedFontFamilies, {
                "fontsLoaded": function(error) {
                    if (debug) {
                        if (error !== null) {
                            // Reached the timeout but not all fonts were loaded
                            console.log("font loader: " + error.message, error.notLoadedFonts);
                        } else {
                            // All fonts were loaded
                            console.log("font loader: all fonts were loaded");
                        }
                    }
                    callback();
                },
                "fontLoaded": function(font) {
                    loadCount++;
                    if (debug) {
                        console.log("font loaded: " + font.family);
                    }
                    if (usedFontFamilies.length > options.minLoadCount && (loadCount / usedFontFamilies.length) >= options.minLoadRatio) {

                        if (debug) {
                            console.log('font loader: early callback');
                        }
                        callback();
                    }
                }
            }, options.timeout, document);

            fontLoader.loadFonts();
        });
    };
};

var FontLoaderNative = function(document, options) {
    var debug = options.debug;

    return function(callback) {
        callback = _.once(callback);
        var loadCount = 0;

        var fontFaceCount = document.fonts.size;
        var fontLoaded = function(font) {
            loadCount++;
            if (debug) {
                console.log("(native) font loaded: " + font.family);
            }
            if (fontFaceCount > options.minLoadCount && (loadCount / fontFaceCount) >= options.minLoadRatio) {

                if (debug) {
                    console.log('(native) font loader: early callback');
                }
                callback();
            }
        }

        var fontIterator = function(font) {
            font.loaded.then(function() {
                fontLoaded(font);
            });
        };

        // For some reason (at this time) Chrome's implementation has a .forEach
        // but it is not Array-like. This is opposite with Firefox's though.
        if (document.fonts.forEach) {
            document.fonts.forEach(fontIterator);
        } else {
            _.each(document.fonts, fontIterator);
        }
        var fontsReady = document.fonts.ready;
        // In older implementations (chromium 35 for example) this is a method not a property
        if (_.isFunction(fontsReady)) {
            fontsReady = fontsReady.call(document.fonts);
        }
        fontsReady.then(function() {
            if (debug) {
                // All fonts were loaded
                console.log("(native) font loader: all fonts were loaded");
            }
            callback();
        });

        window.setTimeout(function() {
            if (debug && loadCount !== fontFaceCount) {
                console.log('(native) font loader: timeout, not all fonts loaded/required');
            } else if (debug) {
                console.log('(native) font loader: timeout');
            }
            callback();
        }, options.timeout);
    }
}

var FontLoaderWrapper = function($iframe, options) {
    options = options || {};

    options.debug = options.debug || false;
    options.timeout = options.timeout || 1500;
    options.minLoadCount = options.minLoadCount || 3;
    options.minLoadRatio = options.minLoadRatio || 0.75;

    var document = $iframe[0].contentDocument;

    // For browsers without CSS Font Loading Module
    var fallbackNeeded = !document.fonts;

    var fontLoader = fallbackNeeded ? FontLoaderFallback : FontLoaderNative;

    this.waitForFonts = fontLoader(document, options);
};

return FontLoaderWrapper;

});
<|endoftext|>


<commit_before>// tooltips

$('a[rel=tooltip]').tooltip({
	'placement': 'bottom'
});

// recent news

function parseRSS(url, callback) {
  $.ajax({
    url: 'http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(url),
    dataType: 'json',
    success: function(data) {
      callback(data.responseData.feed);
    }
  });
}

// smooth scroll

$(document).ready(function() {
  function filterPath(string) {
  return string
    .replace(/^\//,'')
    .replace(/(index|default).[a-zA-Z]{3,4}$/,'')
    .replace(/\/$/,'');
  }
  var locationPath = filterPath(location.pathname);
  var scrollElem = scrollableElement('html', 'body');

  $('a[href*=#]').each(function() {
    var thisPath = filterPath(this.pathname) || locationPath;
    if (  locationPath == thisPath
    && (location.hostname == this.hostname || !this.hostname)
    && this.hash.replace(/#/,'') ) {
      var $target = $(this.hash), target = this.hash;
      if (target) {
        var targetOffset = $target.offset().top;
        $(this).click(function(event) {
          event.preventDefault();
          $(scrollElem).animate({scrollTop: targetOffset}, 400, function() {
            location.hash = target;
          });
        });
      }
    }
  });

  // use the first element that is "scrollable"
  function scrollableElement(els) {
    for (var i = 0, argLength = arguments.length; i <argLength; i++) {
      var el = arguments[i],
          $scrollElement = $(el);
      if ($scrollElement.scrollTop()> 0) {
        return el;
      } else {
        $scrollElement.scrollTop(1);
        var isScrollable = $scrollElement.scrollTop()> 0;
        $scrollElement.scrollTop(0);
        if (isScrollable) {
          return el;
        }
      }
    }
    return [];
  }

});

// subnav

(function ($) {

	$(function(){

		// fix sub nav on scroll
		var $win = $(window),
				$body = $('body'),
				$nav = $('.subnav'),
				navHeight = $('.navbar').first().height(),
				subnavHeight = $('.subnav').first().height(),
				subnavTop = $('.subnav').length && $('.subnav').offset().top - navHeight,
				marginTop = parseInt($body.css('margin-top'), 10);
				isFixed = 0;

		processScroll();

		$win.on('scroll', processScroll);

		function processScroll() {
			var i, scrollTop = $win.scrollTop();

			if (scrollTop >= subnavTop && !isFixed) {
				isFixed = 1;
				$nav.addClass('subnav-fixed');
				$body.css('margin-top', marginTop + subnavHeight + 'px');
			} else if (scrollTop <= subnavTop && isFixed) {
				isFixed = 0;
				$nav.removeClass('subnav-fixed');
				$body.css('margin-top', marginTop + 'px');
			}
		}

	});

})(window.jQuery);<commit_msg>attempt to fix smooth scrolling error<commit_after>// tooltips

$('a[rel=tooltip]').tooltip({
	'placement': 'bottom'
});

// recent news

function parseRSS(url, callback) {
  $.ajax({
    url: 'http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(url),
    dataType: 'json',
    success: function(data) {
      callback(data.responseData.feed);
    }
  });
}

// smooth scroll

$(document).ready(function() {
  function filterPath(string) {
  return string
    .replace(/^\//,'')
    .replace(/(index|default).[a-zA-Z]{3,4}$/,'')
    .replace(/\/$/,'');
  }
  var locationPath = filterPath(location.pathname);
  var scrollElem = scrollableElement('html', 'body');

  $('a[href^=#]').each(function() {
    var thisPath = filterPath(this.pathname) || locationPath;
    if (  locationPath == thisPath
    && (location.hostname == this.hostname || !this.hostname)
    && this.hash.replace(/#/,'') ) {
      var $target = $(this.hash), target = this.hash;
      if (target) {
        var targetOffset = $target.offset().top;
        $(this).click(function(event) {
          event.preventDefault();
          $(scrollElem).animate({scrollTop: targetOffset}, 400, function() {
            location.hash = target;
          });
        });
      }
    }
  });

  // use the first element that is "scrollable"
  function scrollableElement(els) {
    for (var i = 0, argLength = arguments.length; i <argLength; i++) {
      var el = arguments[i],
          $scrollElement = $(el);
      if ($scrollElement.scrollTop()> 0) {
        return el;
      } else {
        $scrollElement.scrollTop(1);
        var isScrollable = $scrollElement.scrollTop()> 0;
        $scrollElement.scrollTop(0);
        if (isScrollable) {
          return el;
        }
      }
    }
    return [];
  }

});

// subnav

(function ($) {

	$(function(){

		// fix sub nav on scroll
		var $win = $(window),
				$body = $('body'),
				$nav = $('.subnav'),
				navHeight = $('.navbar').first().height(),
				subnavHeight = $('.subnav').first().height(),
				subnavTop = $('.subnav').length && $('.subnav').offset().top - navHeight,
				marginTop = parseInt($body.css('margin-top'), 10);
				isFixed = 0;

		processScroll();

		$win.on('scroll', processScroll);

		function processScroll() {
			var i, scrollTop = $win.scrollTop();

			if (scrollTop >= subnavTop && !isFixed) {
				isFixed = 1;
				$nav.addClass('subnav-fixed');
				$body.css('margin-top', marginTop + subnavHeight + 'px');
			} else if (scrollTop <= subnavTop && isFixed) {
				isFixed = 0;
				$nav.removeClass('subnav-fixed');
				$body.css('margin-top', marginTop + 'px');
			}
		}

	});

})(window.jQuery);<|endoftext|>


<commit_before>import { defineConfig } from "vite";
import { metablock } from "vite-plugin-userscript";
import manifest from "./package.json" assert { type: "json" };

const isDevBuild = process.env.NODE_ENV === "development";

function getDateString() {
  const date = new Date();
  const year = date.getFullYear();
  const month = `${date.getMonth() + 1}`.padStart(2, "0");
  const day = `${date.getDate()}`.padStart(2, "0");
  return `${year}${month}${day}`;
}

const filename = [
  "kitten-scientists",
  isDevBuild ? "-dev" : `-${manifest.version}`,
  process.env.NIGHTLY_BUILD ? `-${getDateString()}` : "",
  process.env.GITHUB_SHA ? `-${String(process.env.GITHUB_SHA).substring(0, 7)}` : "",
  ".user.js",
].join("");

export default defineConfig({
  plugins: [
    metablock({
      override: {
        version: manifest.version,
        description: manifest.description,
        homepage: manifest.homepage,
        supportURL: manifest.bugs.url,
      },
    }),
  ],
  build: {
    lib: {
      entry: "source/index.ts",
      name: "kitten-scientists",
    },
    minify: isDevBuild ? "esbuild" : false,
    outDir: "output",
    rollupOptions: {
      output: {
        extend: true,
        format: "umd",
        entryFileNames: filename,
      },
    },
  },
});
<commit_msg>fix: Minified dev builds<commit_after>import { defineConfig } from "vite";
import { metablock } from "vite-plugin-userscript";
import manifest from "./package.json" assert { type: "json" };

const isDevBuild = process.env.NODE_ENV === "development";

function getDateString() {
  const date = new Date();
  const year = date.getFullYear();
  const month = `${date.getMonth() + 1}`.padStart(2, "0");
  const day = `${date.getDate()}`.padStart(2, "0");
  return `${year}${month}${day}`;
}

const filename = [
  "kitten-scientists",
  isDevBuild ? "-dev" : `-${manifest.version}`,
  process.env.NIGHTLY_BUILD ? `-${getDateString()}` : "",
  process.env.GITHUB_SHA ? `-${String(process.env.GITHUB_SHA).substring(0, 7)}` : "",
  ".user.js",
].join("");

export default defineConfig({
  plugins: [
    metablock({
      override: {
        version: manifest.version,
        description: manifest.description,
        homepage: manifest.homepage,
        supportURL: manifest.bugs.url,
      },
    }),
  ],
  build: {
    lib: {
      entry: "source/index.ts",
      name: "kitten-scientists",
    },
    minify: isDevBuild ? false : "esbuild",
    outDir: "output",
    rollupOptions: {
      output: {
        extend: true,
        format: "umd",
        entryFileNames: filename,
      },
    },
  },
});
<|endoftext|>


<commit_before>module.exports = function (context, message) {
    var series = require('async/series');

    var google = require('googleapis');
    var googleAuth = require('google-auth-library');

    var calendar = google.calendar('v3');

    var client_email = process.env.client_email;
    var private_key = process.env.private_key;
    var user_address = 'igor@googleapps.wrdsb.ca';

    // *sigh* because Azure Functions application settings can't handle newlines, let's add them ourselves:
    private_key = private_key.split('\\n').join("\n");

    var calendar_list_entry_params = message.params;
    var calendar_user = message.user;
    context.log(calendar_list_entry_params);

    // stores our calendar list entry in the end
    var calendar_list_entry_created = {};

    // prep our credentials for G Suite APIs
    var jwtClient = new google.auth.JWT(
        client_email,
        null,
        private_key,
        ['https://www.googleapis.com/auth/calendar'], // an array of auth scopes
        calendar_user
    );

    var params = {
        auth: jwtClient,

        // specify we want JSON back from the API.
        // Group Settings API defaults to XML (or Atom), despite the docs
        alt: "json",

        // the Calendar List Entry to create
        resource: calendar_list_entry_params.resource,
        colorRgbFormat: calendar_list_entry_params.colorRgbFormat
    };

    jwtClient.authorize(function(err, tokens) {
        if (err) {
            context.log(err);
            return;
        }
        series([
            function createCalendarListEntry(createCalendarListEntryCallback) {
                calendar.calendarList.insert(params, function (err, result) {
                    if (err) {
                        createCalendarListEntryCallback(new Error(err));
                        return;
                    }
                    context.log(result);
                    createCalendarListEntryCallback(null, result);
                });
            }
        ],
        function (err, results) {
            if (err) {
                context.done(err);
            } else {
                calendar_list_entry_created = results[0];
                context.log(calendar_list_entry_created);
                context.done();
            }
        });
    });
};
<commit_msg>calendar_list_entry_create working<commit_after>module.exports = function (context, message) {
    var series = require('async/series');

    var google = require('googleapis');
    var googleAuth = require('google-auth-library');

    var calendar = google.calendar('v3');

    var client_email = process.env.client_email;
    var private_key = process.env.private_key;
    var user_address = 'igor@googleapps.wrdsb.ca';

    // *sigh* because Azure Functions application settings can't handle newlines, let's add them ourselves:
    private_key = private_key.split('\\n').join("\n");

    var calendar_list_entry_params = message.params;
    var calendar_user = message.user;
    context.log('For user ' + calendar_user + ' create list entry: ');
    context.log(calendar_list_entry_params);

    // stores our calendar list entry in the end
    var calendar_list_entry_created = {};

    // prep our credentials for G Suite APIs
    var jwtClient = new google.auth.JWT(
        client_email,
        null,
        private_key,
        ['https://www.googleapis.com/auth/calendar'], // an array of auth scopes
        calendar_user
    );

    var params = {
        auth: jwtClient,

        // specify we want JSON back from the API.
        // Group Settings API defaults to XML (or Atom), despite the docs
        alt: "json",

        // the Calendar List Entry to create
        resource: calendar_list_entry_params.resource,
        colorRgbFormat: calendar_list_entry_params.colorRgbFormat
    };

    jwtClient.authorize(function(err, tokens) {
        if (err) {
            context.log(err);
            return;
        }
        series([
            function createCalendarListEntry(createCalendarListEntryCallback) {
                calendar.calendarList.insert(params, function (err, result) {
                    if (err) {
                        createCalendarListEntryCallback(new Error(err));
                        return;
                    }
                    context.log(result);
                    createCalendarListEntryCallback(null, result);
                });
            }
        ],
        function (err, results) {
            if (err) {
                context.done(err);
            } else {
                calendar_list_entry_created = results[0];
                context.log(calendar_list_entry_created);
                context.done();
            }
        });
    });
};
<|endoftext|>


<commit_before>import asyncIteratorToStream from 'async-iterator-to-stream'
import { dirname, resolve } from 'path'

import Vhd from './vhd'
import {
  BLOCK_UNUSED,
  DISK_TYPE_DYNAMIC,
  FOOTER_SIZE,
  HEADER_SIZE,
  SECTOR_SIZE,
} from './_constants'
import { fuFooter, fuHeader, checksumStruct } from './_structs'
import { test as mapTestBit } from './_bitmap'

const resolveRelativeFromFile = (file, path) =>
  resolve('/', dirname(file), path).slice(1)

export default async function createSyntheticStream (handler, path) {
  const fds = []
  const cleanup = () => {
    for (let i = 0, n = fds.length; i < n; ++i) {
      handler.closeFile(fds[i]).catch(error => {
        console.warn('createReadStream, closeFd', i, error)
      })
    }
  }
  try {
    const vhds = []
    while (true) {
      const fd = await handler.openFile(path, 'r')
      fds.push(fd)
      const vhd = new Vhd(handler, fd)
      vhds.push(vhd)
      await vhd.readHeaderAndFooter()
      await vhd.readBlockAllocationTable()

      if (vhd.footer.diskType === DISK_TYPE_DYNAMIC) {
        break
      }

      path = resolveRelativeFromFile(path, vhd.header.parentUnicodeName)
    }
    const nVhds = vhds.length

    // this the VHD we want to synthetize
    const vhd = vhds[0]

    // this is the root VHD
    const rootVhd = vhds[nVhds - 1]

    // data of our synthetic VHD
    // TODO: set parentLocatorEntry-s in header
    let header = {
      ...vhd.header,
      tableOffset: FOOTER_SIZE + HEADER_SIZE,
      parentTimestamp: rootVhd.header.parentTimestamp,
      parentUnicodeName: rootVhd.header.parentUnicodeName,
      parentUuid: rootVhd.header.parentUuid,
    }

    const bat = Buffer.allocUnsafe(vhd.batSize)
    let footer = {
      ...vhd.footer,
      dataOffset: FOOTER_SIZE,
      diskType: rootVhd.footer.diskType,
    }
    const sectorsPerBlockData = vhd.sectorsPerBlock
    const sectorsPerBlock = sectorsPerBlockData + vhd.bitmapSize / SECTOR_SIZE

    const nBlocks = Math.ceil(footer.currentSize / header.blockSize)

    const blocksOwner = new Array(nBlocks)
    let blockOffset = Math.ceil((header.tableOffset + bat.length) / SECTOR_SIZE)
    for (let iBlock = 0; iBlock < nBlocks; ++iBlock) {
      let blockSector = BLOCK_UNUSED
      for (let i = 0; i < nVhds; ++i) {
        if (vhds[i].containsBlock(iBlock)) {
          blocksOwner[iBlock] = i
          blockSector = blockOffset
          blockOffset += sectorsPerBlock
          break
        }
      }
      bat.writeUInt32BE(blockSector, iBlock * 4)
    }
    const fileSize = (blockOffset + Math.ceil(FOOTER_SIZE / SECTOR_SIZE)) * SECTOR_SIZE

    const iterator = function * () {
      try {
        footer = fuFooter.pack(footer)
        checksumStruct(footer, fuFooter)
        yield footer

        header = fuHeader.pack(header)
        checksumStruct(header, fuHeader)
        yield header

        yield bat

        // TODO: for generic usage the bitmap needs to be properly computed for each block
        const bitmap = Buffer.alloc(vhd.bitmapSize, 0xff)
        for (let iBlock = 0; iBlock < nBlocks; ++iBlock) {
          const owner = blocksOwner[iBlock]
          if (owner === undefined) {
            continue
          }

          yield bitmap

          const blocksByVhd = new Map()
          const emitBlockSectors = function * (iVhd, i, n) {
            const vhd = vhds[iVhd]
            const isRootVhd = vhd === rootVhd
            if (!vhd.containsBlock(iBlock)) {
              if (isRootVhd) {
                yield Buffer.alloc((n - i) * SECTOR_SIZE)
              } else {
                yield * emitBlockSectors(iVhd + 1, i, n)
              }
              return
            }
            let block = blocksByVhd.get(vhd)
            if (block === undefined) {
              block = yield vhd._readBlock(iBlock)
              blocksByVhd.set(vhd, block)
            }
            const { bitmap, data } = block
            if (isRootVhd) {
              yield data.slice(i * SECTOR_SIZE, n * SECTOR_SIZE)
              return
            }
            while (i < n) {
              const hasData = mapTestBit(bitmap, i)
              const start = i
              do {
                ++i
              } while (i < n && mapTestBit(bitmap, i) === hasData)
              if (hasData) {
                yield data.slice(start * SECTOR_SIZE, i * SECTOR_SIZE)
              } else {
                yield * emitBlockSectors(iVhd + 1, start, i)
              }
            }
          }
          yield * emitBlockSectors(owner, 0, sectorsPerBlockData)
        }
        yield footer
      } finally {
        cleanup()
      }
    }

    const stream = asyncIteratorToStream(iterator())
    stream.length = fileSize
    return stream
  } catch (e) {
    cleanup()
    throw e
  }
}
<commit_msg>VHD: remove unnecessary rounding<commit_after>import asyncIteratorToStream from 'async-iterator-to-stream'
import { dirname, resolve } from 'path'

import Vhd from './vhd'
import {
  BLOCK_UNUSED,
  DISK_TYPE_DYNAMIC,
  FOOTER_SIZE,
  HEADER_SIZE,
  SECTOR_SIZE,
} from './_constants'
import { fuFooter, fuHeader, checksumStruct } from './_structs'
import { test as mapTestBit } from './_bitmap'

const resolveRelativeFromFile = (file, path) =>
  resolve('/', dirname(file), path).slice(1)

export default async function createSyntheticStream (handler, path) {
  const fds = []
  const cleanup = () => {
    for (let i = 0, n = fds.length; i < n; ++i) {
      handler.closeFile(fds[i]).catch(error => {
        console.warn('createReadStream, closeFd', i, error)
      })
    }
  }
  try {
    const vhds = []
    while (true) {
      const fd = await handler.openFile(path, 'r')
      fds.push(fd)
      const vhd = new Vhd(handler, fd)
      vhds.push(vhd)
      await vhd.readHeaderAndFooter()
      await vhd.readBlockAllocationTable()

      if (vhd.footer.diskType === DISK_TYPE_DYNAMIC) {
        break
      }

      path = resolveRelativeFromFile(path, vhd.header.parentUnicodeName)
    }
    const nVhds = vhds.length

    // this the VHD we want to synthetize
    const vhd = vhds[0]

    // this is the root VHD
    const rootVhd = vhds[nVhds - 1]

    // data of our synthetic VHD
    // TODO: set parentLocatorEntry-s in header
    let header = {
      ...vhd.header,
      tableOffset: FOOTER_SIZE + HEADER_SIZE,
      parentTimestamp: rootVhd.header.parentTimestamp,
      parentUnicodeName: rootVhd.header.parentUnicodeName,
      parentUuid: rootVhd.header.parentUuid,
    }

    const bat = Buffer.allocUnsafe(vhd.batSize)
    let footer = {
      ...vhd.footer,
      dataOffset: FOOTER_SIZE,
      diskType: rootVhd.footer.diskType,
    }
    const sectorsPerBlockData = vhd.sectorsPerBlock
    const sectorsPerBlock = sectorsPerBlockData + vhd.bitmapSize / SECTOR_SIZE

    const nBlocks = Math.ceil(footer.currentSize / header.blockSize)

    const blocksOwner = new Array(nBlocks)
    let blockOffset = Math.ceil((header.tableOffset + bat.length) / SECTOR_SIZE)
    for (let iBlock = 0; iBlock < nBlocks; ++iBlock) {
      let blockSector = BLOCK_UNUSED
      for (let i = 0; i < nVhds; ++i) {
        if (vhds[i].containsBlock(iBlock)) {
          blocksOwner[iBlock] = i
          blockSector = blockOffset
          blockOffset += sectorsPerBlock
          break
        }
      }
      bat.writeUInt32BE(blockSector, iBlock * 4)
    }
    const fileSize = blockOffset * SECTOR_SIZE + FOOTER_SIZE

    const iterator = function * () {
      try {
        footer = fuFooter.pack(footer)
        checksumStruct(footer, fuFooter)
        yield footer

        header = fuHeader.pack(header)
        checksumStruct(header, fuHeader)
        yield header

        yield bat

        // TODO: for generic usage the bitmap needs to be properly computed for each block
        const bitmap = Buffer.alloc(vhd.bitmapSize, 0xff)
        for (let iBlock = 0; iBlock < nBlocks; ++iBlock) {
          const owner = blocksOwner[iBlock]
          if (owner === undefined) {
            continue
          }

          yield bitmap

          const blocksByVhd = new Map()
          const emitBlockSectors = function * (iVhd, i, n) {
            const vhd = vhds[iVhd]
            const isRootVhd = vhd === rootVhd
            if (!vhd.containsBlock(iBlock)) {
              if (isRootVhd) {
                yield Buffer.alloc((n - i) * SECTOR_SIZE)
              } else {
                yield * emitBlockSectors(iVhd + 1, i, n)
              }
              return
            }
            let block = blocksByVhd.get(vhd)
            if (block === undefined) {
              block = yield vhd._readBlock(iBlock)
              blocksByVhd.set(vhd, block)
            }
            const { bitmap, data } = block
            if (isRootVhd) {
              yield data.slice(i * SECTOR_SIZE, n * SECTOR_SIZE)
              return
            }
            while (i < n) {
              const hasData = mapTestBit(bitmap, i)
              const start = i
              do {
                ++i
              } while (i < n && mapTestBit(bitmap, i) === hasData)
              if (hasData) {
                yield data.slice(start * SECTOR_SIZE, i * SECTOR_SIZE)
              } else {
                yield * emitBlockSectors(iVhd + 1, start, i)
              }
            }
          }
          yield * emitBlockSectors(owner, 0, sectorsPerBlockData)
        }
        yield footer
      } finally {
        cleanup()
      }
    }

    const stream = asyncIteratorToStream(iterator())
    stream.length = fileSize
    return stream
  } catch (e) {
    cleanup()
    throw e
  }
}
<|endoftext|>


<commit_before>'use strict';
import React, { Component } from 'react';
import {
  Text,
  Image,
  TouchableHighlight,
  View
} from 'react-native';
import Camera from 'react-native-camera';
import helpers from '../helpers/helpers.js';
var axios = require('axios');
import styles from '../styles.ios.js';
import GoogleResults from './GoogleResults.ios.js';
import AddIngredientGoogleResults from './AddIngredientGoogleResults.ios.js'

export default class camera extends Component {

  constructor(props) {
    super(props);
  }

  changeNavigation(results) {
    this.props.navigator.push({
      component: AddIngredientGoogleResults,
      passProps: {
        results: results,
        currentIngredients: this.props.currentIngredients,
        store: this.props.store
      }
    })
  }

  border(color) {
    return {
      borderColor: color,
      borderWidth: 5,
    }
  }

  goBack() {
    this.props.navigator.pop();
  }

  render() {
    return (
      <View style={styles.container}>
        <Camera
          ref={(cam) => {
            this.camera = cam;
          }}
          style={styles.preview}
          aspect={Camera.constants.Aspect.fill}
          captureTarget={Camera.constants.CaptureTarget.memory}>
          <View style={styles.navigationResults}>
            <TouchableHighlight style={[styles.backButtonCamera, this.border('white')]} onPress={this.goBack.bind(this)}>
              <Image style={styles.backButtonImage} source={{uri: 'https://cdn0.iconfinder.com/data/icons/vector-basic-tab-bar-icons/48/back_button-128.png'}} />
            </TouchableHighlight>
            <TouchableHighlight style={styles.takePicture} onPress={this.takePicture.bind(this)}>
              <Image style={styles.takePicture} source={{uri: 'https://s3.amazonaws.com/features.ifttt.com/newsletter_images/2015_February/camera512x512+(1).png'}}/>
            </TouchableHighlight>
          </View>
        </Camera>
      </View>
    );
  }

  takePicture() {
    this.camera.capture()
      .then((data) => {
        this.readPicture(data.data);
      })
      .catch(err => console.error(err));
  }

  readPicture(data) {
    helpers.camera.imageRecognition(data)
      .then(resp => {
        let descriptions = [];
        for (let obj of resp.data.responses[0].labelAnnotations) {
          descriptions.push(obj.description);
        }
        this.changeNavigation(descriptions);
      })
      .catch(err => {
        console.log('Error: ', err)
      })
  }
}<commit_msg>(code refactor) minor code cleanup<commit_after>'use strict';
import React, { Component } from 'react';
import { Text, Image, TouchableHighlight, View } from 'react-native';
import Camera from 'react-native-camera';
import helpers from '../helpers/helpers.js';
var axios = require('axios');
import styles from '../styles.ios.js';
import GoogleResults from './GoogleResults.ios.js';
import AddIngredientGoogleResults from './AddIngredientGoogleResults.ios.js'

export default class camera extends Component {

  constructor(props) {
    super(props);
  }

  changeNavigation(results) {
    this.props.navigator.push({
      component: AddIngredientGoogleResults,
      passProps: {
        results: results,
        currentIngredients: this.props.currentIngredients,
        store: this.props.store
      }
    })
  }

  border(color) {
    return {
      borderColor: color,
      borderWidth: 5,
    }
  }

  goBack() {
    this.props.navigator.pop();
  }

  render() {
    return (
      <View style={styles.container}>
        <Camera
          ref={(cam) => {
            this.camera = cam;
          }}
          style={styles.preview}
          aspect={Camera.constants.Aspect.fill}
          captureTarget={Camera.constants.CaptureTarget.memory}>
          <View style={styles.navigationResults}>
            <TouchableHighlight style={[styles.backButtonCamera, this.border('white')]} onPress={this.goBack.bind(this)}>
              <Image style={styles.backButtonImage} source={{uri: 'https://cdn0.iconfinder.com/data/icons/vector-basic-tab-bar-icons/48/back_button-128.png'}} />
            </TouchableHighlight>
            <TouchableHighlight style={styles.takePicture} onPress={this.takePicture.bind(this)}>
              <Image style={styles.takePicture} source={{uri: 'https://s3.amazonaws.com/features.ifttt.com/newsletter_images/2015_February/camera512x512+(1).png'}}/>
            </TouchableHighlight>
          </View>
        </Camera>
      </View>
    );
  }

  takePicture() {
    this.camera.capture()
      .then((data) => {
        this.readPicture(data.data);
      })
      .catch(err => console.error(err));
  }

  readPicture(data) {
    helpers.camera.imageRecognition(data)
      .then(resp => {
        let descriptions = [];
        for (let obj of resp.data.responses[0].labelAnnotations) {
          descriptions.push(obj.description);
        }
        this.changeNavigation(descriptions);
      })
      .catch(err => {
        console.log('Error: ', err)
      })
  }
}<|endoftext|>


<commit_before><commit_msg>removing unneeded function<commit_after><|endoftext|>


<commit_before>
this.CHAOTIC_TRAVERSION_ORDER = true;

//library loading helper function
var loadlib = function(lib) {
    //print('#loading: '+lib);
    load(lib);
};

var root = '../../';
var path = root+'lib/';
loadlib(path+'Joose.js');

//now to load the components
var comps = Joose.prototype.components();
for ( x in comps ) {
    var file = comps[x].replace(/\./g, '/')+'.js';
    loadlib(path+file);
}

var extpath = root+'ext/';
loadlib(extpath+'Test/TAP.js');
loadlib(extpath+'Test/TAP/Runner.js');
loadlib(extpath+'Test/TAP/Class.js');
<commit_msg>setting special option for rhino is no longer neccessary<commit_after>
//library loading helper function
var loadlib = function(lib) {
    //print('#loading: '+lib);
    load(lib);
};

var root = '../../';
var path = root+'lib/';
loadlib(path+'Joose.js');

//now to load the components
var comps = Joose.prototype.components();
for ( x in comps ) {
    var file = comps[x].replace(/\./g, '/')+'.js';
    loadlib(path+file);
}

var extpath = root+'ext/';
loadlib(extpath+'Test/TAP.js');
loadlib(extpath+'Test/TAP/Runner.js');
loadlib(extpath+'Test/TAP/Class.js');
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
 */

define([
    'underscore',
    'knockback',
    'contrail-view',
    'contrail-list-model',
    'monitor/infrastructure/controlnode/ui/js/models/ControlNodeRoutesModel'
    //Remove all query references once it is moved to core
], function (_, Knockback, ContrailView, ContrailListModel, ControlNodeRoutesModel) {
    var routingInstancesDropdownList = [{text:'All',value:'All'}],
    backwardRouteStack = [], forwardRouteStack = [], filteredPrefix = '',
    routInstance = '', showRouteStack;
    var ControlNodeRoutesFormView = ContrailView.extend({
        render: function (options) {
            var self = this, viewConfig = self.attributes.viewConfig,
                hostname = viewConfig['hostname'],
                prefix = 'controlroutes',
                routesTmpl = contrail.getTemplate4Id(
                            ctwc.TMPL_FORM_RESULT),
                controlNodeRoutesModel = new ControlNodeRoutesModel(),
                widgetConfig = contrail.checkIfExist(viewConfig.widgetConfig) ?
                        viewConfig.widgetConfig : null,
                routesFormId = "#" + prefix + "-form";
            monitorInfraUtils.appendHostNameInWidgetTitleForUnderlayPage(viewConfig);
            self.model = controlNodeRoutesModel;
            self.$el.append(routesTmpl({prefix: prefix}));

            var remoteAjaxConfig = {
                    remote: {
                        ajaxConfig: {
                            url: contrail.format(monitorInfraConstants.
                                    monitorInfraUrls['CONTROLNODE_ROUTE_INST_LIST'],
                                    hostname),
                            type: "GET",
                        },
                        dataParser: parseRoutingInstanceResp
                    },
                    cacheConfig: {
                    }
            };
            var routingInstanceListModel = new ContrailListModel(remoteAjaxConfig);
            routingInstanceListModel.onDataUpdate.subscribe(function(){
                self.model.routingInstanceOptionList(routingInstanceListModel.getItems());
            })

            self.renderView4Config($(self.$el).find(routesFormId),
                    this.model,
                    self.getViewConfig(options,viewConfig,routingInstanceListModel),
                    null,
                    null,
                    null,
                    function () {
                        self.model.showErrorAttr(prefix + '-container',
                                false);
                        Knockback.applyBindings(self.model,
                                document.getElementById(prefix + '-container'));
                        kbValidation.bind(self);
                        self.renderQueryResult(viewConfig);
                        $("#run_query").on('click', function() {
                            self.renderQueryResult(viewConfig);
                        });
                    }
            );
            if (widgetConfig !== null) {
                self.renderView4Config($(self.$el).find(routesFormId),
                        self.model, widgetConfig, null, null, null);
            }
        },

        renderQueryResult: function(viewConfig) {
            var self = this,
                prefix = 'controlroutes',
                hostname = viewConfig['hostname'],
                queryResultId = "#" + prefix + "-results",
                responseViewConfig = {
                    elementId: ctwl.CONTROLNODE_ROUTES_RESULT_VIEW,
                    view: "ControlRoutesResultView",
                    viewPathPrefix: ctwl.CONTROLNODE_VIEWPATH_PREFIX,
                    app: cowc.APP_CONTRAIL_CONTROLLER,
                    viewConfig: viewConfig
                };

            //Making the Routes call here as the result also needs to be update
            //prefix value in this form
            var routesQueryString = self.model.getControlRoutesQueryString();
            if(routesQueryString.prefix !== undefined){
                filteredPrefix = routesQueryString.prefix;
            }else{
                filteredPrefix = '';
            }
            if(routesQueryString.routingInst !== undefined){
                routInstance = routesQueryString.routingInst;
            }else{
                routInstance = '';
            }
            var routesRemoteConfig = {
                    url: monitorInfraConstants.
                        monitorInfraUrls['CONTROLNODE_ROUTES'] +
                        '?ip=' + hostname +
                        '&' + $.param(routesQueryString),
                    type: 'GET'
                };
            var listModelConfig = {
                    remote : {
                        ajaxConfig : routesRemoteConfig,
                        dataParser : function (response) {
                            var selValues = {};
                            showRouteStack = undefined;
                            backwardRouteStack = []; forwardRouteStack = [];
                            var parsedData = monitorInfraParsers.
                                        parseRoutes(response,routesQueryString);
                            if(getValueByJsonPath(response[0],'ShowRouteResp;tables;list','') !== ''){
                                backwardRoutes(response);
                                forwardRoutes(response);
                            }
                            var prefixList = [];
                            $.each(parsedData,function(i,d){
                                prefixList.push({text:d.dispPrefix,value:d.dispPrefix});
                            });
                            self.model.prefixOptionList(prefixList);
                            return parsedData;
                        }
                    },
                    cacheConfig : {
                       // ucid: ctwc.CACHE_CONFIGNODE
                    }
                };
            var backwardRoutes = function(model){
                var routingTable, showRoute, routingInstance, prefix;
                var showRouteTable = getValueByJsonPath(model[0],'ShowRouteResp;tables;list;ShowRouteTable',{});
                if(showRouteTable.constructor().length === undefined){
                    routingTable = showRouteTable.routing_table_name;
                    routingInstance =  showRouteTable.routing_instance;
                    showRoute = showRouteTable.routes.list.ShowRoute;
                }else{
                    routingTable = showRouteTable[0].routing_table_name;
                    routingInstance =  showRouteTable[0].routing_instance;
                    showRoute = showRouteTable[0].routes.list.ShowRoute
                }
                if(showRoute.constructor().length === undefined){
                    prefix = showRoute.prefix;
                }else{
                    prefix = showRoute[0].prefix;
                }
                if(showRouteStack === undefined){
                    showRouteStack = showRouteTable;
                    backwardRouteStack.push({
                        limit: routesQueryString.limit,
                        startRoutingTable: routingTable,
                        startRoutingInstance: routingInstance,
                        startPrefix: prefix,
                        prefix: filteredPrefix,
                        routingInst: routInstance
                    });
                }else{
                    if(!_.isEqual(showRouteStack, showRouteTable)){
                        showRouteStack = showRouteTable;
                        backwardRouteStack.push({
                            limit: routesQueryString.limit,
                            startRoutingTable: routingTable,
                            startRoutingInstance: routingInstance,
                            startPrefix: prefix,
                            prefix: filteredPrefix,
                            routingInst: routInstance
                        });
                    }
                }
            };
            var forwardRoutes = function(model){
                var routingTable, showRoute, routingInstance, prefix;
                var showRouteTable = getValueByJsonPath(model[0],'ShowRouteResp;tables;list;ShowRouteTable',{});
                if(showRouteTable.constructor().length === undefined){
                    routingTable = showRouteTable.routing_table_name;
                    routingInstance =  showRouteTable.routing_instance;
                    showRoute = showRouteTable.routes.list.ShowRoute;
                }else{
                    routingTable = showRouteTable[showRouteTable.length - 1].routing_table_name;
                    routingInstance =  showRouteTable[showRouteTable.length - 1].routing_instance;
                    showRoute = showRouteTable[showRouteTable.length - 1].routes.list.ShowRoute;
                }
                if(showRoute.constructor().length === undefined){
                    prefix = showRoute.prefix;
                }else{
                    prefix = showRoute[showRoute.length - 1].prefix;
                }
                forwardRouteStack.push({
                    limit: routesQueryString.limit,
                    startRoutingTable: routingTable,
                    startRoutingInstance: routingInstance,
                    startPrefix: prefix,
                    prefix: filteredPrefix,
                    routingInst:routInstance
                });
            };
            var model = new ContrailListModel(listModelConfig);
            self.renderView4Config($(self.$el).find(queryResultId),
                    model, responseViewConfig,null,null,null,function() {
                        monitorInfraUtils.bindPaginationListeners({
                            gridSel: $('#' + ctwl.CONTROLNODE_ROUTES_RESULTS),
                            model: self.model,
                            obj:viewConfig,
                            parseFn: function(response) {
                                backwardRoutes(response);
                                forwardRoutes(response);
                                var parsedData = monitorInfraParsers.
                                parseRoutes(response, routesQueryString);
                                return parsedData;
                            },
                            getUrlFn: function(step) {
                                var urlparm;
                                if(step === 'forward' && forwardRouteStack.length !== 0){
                                    urlParm = forwardRouteStack.pop();
                                    return monitorInfraConstants.
                                           monitorInfraUrls['CONTROLNODE_ROUTES'] +
                                           '?ip=' + hostname +
                                           '&' + $.param(urlParm);
                                }
                                if(step === 'backward' && backwardRouteStack.length !== 1){
                                    backwardRouteStack.splice(backwardRouteStack.length - 1, 1);
                                    urlParm = backwardRouteStack.pop();
                                    forwardRouteStack.pop();
                                    if(urlParm !== undefined){
                                        return monitorInfraConstants.
                                        monitorInfraUrls['CONTROLNODE_ROUTES'] +
                                        '?ip=' + hostname +
                                        '&' + $.param(urlParm);
                                    }
                                 }
                             }
                        });
                    });
        },

        getViewConfig: function (options,viewConfig,routingInstanceListModel) {
            var self = this;
            var hostname = viewConfig['hostname'];
            var addressFamilyList = ["All","enet","ermvpn","evpn",
                                     "inet","inetvpn","inet6","l3vpn","rtarget"];
            var routeLimits = [10, 50, 100, 200];
            $.each(routeLimits,function(idx,obj){
                routeLimits[idx] = {'value':obj,'text':obj+' Routes'};
             });
            routeLimits = [{'text':'All','value':'All'}].concat(routeLimits);
            var protocols = ['All','XMPP','BGP','ServiceChain','Static'];
            return {
                view: "SectionView",
                viewConfig: {
                    rows: [
                        {
                            columns: [
                                {
                                    elementId: 'routing_instance',
                                    view: "FormDropdownView",
                                    viewConfig: {
                                        path: 'routing_instance',
                                        dataBindValue: 'routing_instance',
                                        class: "col-xs-6",
                                        dataBindOptionList: 'routingInstanceOptionList',
                                        elementConfig: {
                                            defaultValueId: 0,
                                            dropdownAutoWidth : false,
                                            dataTextField:'text',
                                            dataValueField:'value'
                                        }
                                    }
                                },
                                {
                                    elementId: 'prefix',
                                    view: "FormComboboxView",
                                    viewConfig: {
                                        label:'Prefix',
                                        path: 'prefix',
                                        class: "col-xs-2",
                                        dataBindValue: 'prefix',
                                        dataBindOptionList: 'prefixOptionList',
                                        elementConfig: {
                                            dataTextField: "text",
                                            dataValueField: "value",
                                            placeholder: 'Prefix'
                                         }
                                    }
                                },
                                {
                                    elementId: 'routes_limit',
                                    view: "FormDropdownView",
                                    viewConfig: {
                                        path: 'routes_limit',
                                        label: 'Limit',
                                        dataBindValue: 'routes_limit',
                                        class: "col-xs-2",
                                        elementConfig: {
                                            dataTextField: "text",
                                            dataValueField: "value",
                                            data: routeLimits
                                        }
                                    }
                                }
                            ]
                        },
                        /*{
                            columns: [
                                {
                                    elementId: 'peer_source',
                                    view: "FormDropdownView",
                                    viewConfig: {
                                        path: 'peer_source',
                                        dataBindValue: 'peer_source',
                                        class: "col-xs-2",
                                        elementConfig: {
                                            dataSource: {
                                                type: 'remote',
                                                 url: contrail.format(
                                                         monitorInfraConstants.
                                                          monitorInfraUrls['CONTROLNODE_PEER_LIST'],
                                                         hostname),
                                                 parse:function(response){
                                                   var ret = ['All']
                                                   if(!(response instanceof Array)){
                                                     response = [response];
                                                   }
                                                   ret = ['All'].concat(response);
                                                   return ret;
                                                 }
                                             }
                                        }
                                    }
                                },
                                {
                                    elementId: 'address_family',
                                    view: "FormDropdownView",
                                    viewConfig: {
                                        path: 'address_family',
                                        dataBindValue: 'address_family',
                                        class: "col-xs-2",
                                        elementConfig: {
                                            data: addressFamilyList
                                        }
                                    }
                                },
                                {
                                    elementId: 'protocol',
                                    view: "FormDropdownView",
                                    viewConfig: {
                                        path: 'protocol',
                                        dataBindValue: 'protocol',
                                        class: "col-xs-2",
                                        elementConfig: {
                                            data: protocols
                                        }
                                    }
                                }
                            ]
                        },*/
                        {
                            columns: [
                                {
                                    elementId: 'run_query',
                                    view: "FormButtonView",
                                    viewConfig: {
                                        label: "Search",
                                        class: 'display-inline-block margin-0-10-0-0',
                                        elementConfig: {
                                            btnClass: 'btn-primary'
                                        }
                                    }
                                },
                                {
                                    elementId: 'reset_query',
                                    view: "FormButtonView",
                                    viewConfig: {
                                        label: "Reset",
                                        class: 'display-inline-block margin-0-10-0-0',
                                        elementConfig: {
                                            onClick: "reset"
                                        }
                                    }
                                }
                            ]
                        }
                    ]
                }
            };
        }
    });
    function parseRoutingInstanceResp (response){
        var ret = [];
        if(response != null && response['ShowRoutingInstanceSummaryResp'] != null &&
                response['ShowRoutingInstanceSummaryResp']['instances'] != null &&
                response['ShowRoutingInstanceSummaryResp']['instances']['list'] != null &&
                response['ShowRoutingInstanceSummaryResp']['instances']['list']['ShowRoutingInstance'] != null){
            var routingInstances = response['ShowRoutingInstanceSummaryResp']['instances']['list']['ShowRoutingInstance'];
            var routingInstancesLength = routingInstances.length;
            for(var i = 0; i < routingInstancesLength; i++) {
                routingInstancesDropdownList.push({text:routingInstances[i]['name'],value:routingInstances[i]['name']});
            }

        }
        return routingInstancesDropdownList;

    }
    return ControlNodeRoutesFormView;
});
<commit_msg>Fixed the duplicate Routing instances appearing in the drop under ControlNodes-Routes<commit_after>/*
 * Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
 */

define([
    'underscore',
    'knockback',
    'contrail-view',
    'contrail-list-model',
    'monitor/infrastructure/controlnode/ui/js/models/ControlNodeRoutesModel'
    //Remove all query references once it is moved to core
], function (_, Knockback, ContrailView, ContrailListModel, ControlNodeRoutesModel) {
    var routingInstancesDropdownList = [{text:'All',value:'All'}],
    backwardRouteStack = [], forwardRouteStack = [], filteredPrefix = '',
    routInstance = '', showRouteStack;
    var ControlNodeRoutesFormView = ContrailView.extend({
        render: function (options) {
            var self = this, viewConfig = self.attributes.viewConfig,
                hostname = viewConfig['hostname'],
                prefix = 'controlroutes',
                routesTmpl = contrail.getTemplate4Id(
                            ctwc.TMPL_FORM_RESULT),
                controlNodeRoutesModel = new ControlNodeRoutesModel(),
                widgetConfig = contrail.checkIfExist(viewConfig.widgetConfig) ?
                        viewConfig.widgetConfig : null,
                routesFormId = "#" + prefix + "-form";
            monitorInfraUtils.appendHostNameInWidgetTitleForUnderlayPage(viewConfig);
            self.model = controlNodeRoutesModel;
            self.$el.append(routesTmpl({prefix: prefix}));

            var remoteAjaxConfig = {
                    remote: {
                        ajaxConfig: {
                            url: contrail.format(monitorInfraConstants.
                                    monitorInfraUrls['CONTROLNODE_ROUTE_INST_LIST'],
                                    hostname),
                            type: "GET",
                        },
                        dataParser: parseRoutingInstanceResp
                    },
                    cacheConfig: {
                    }
            };
            var routingInstanceListModel = new ContrailListModel(remoteAjaxConfig);
            routingInstanceListModel.onDataUpdate.subscribe(function(){
                self.model.routingInstanceOptionList(routingInstanceListModel.getItems());
            })

            self.renderView4Config($(self.$el).find(routesFormId),
                    this.model,
                    self.getViewConfig(options,viewConfig,routingInstanceListModel),
                    null,
                    null,
                    null,
                    function () {
                        self.model.showErrorAttr(prefix + '-container',
                                false);
                        Knockback.applyBindings(self.model,
                                document.getElementById(prefix + '-container'));
                        kbValidation.bind(self);
                        self.renderQueryResult(viewConfig);
                        $("#run_query").on('click', function() {
                            self.renderQueryResult(viewConfig);
                        });
                    }
            );
            if (widgetConfig !== null) {
                self.renderView4Config($(self.$el).find(routesFormId),
                        self.model, widgetConfig, null, null, null);
            }
        },

        renderQueryResult: function(viewConfig) {
            var self = this,
                prefix = 'controlroutes',
                hostname = viewConfig['hostname'],
                queryResultId = "#" + prefix + "-results",
                responseViewConfig = {
                    elementId: ctwl.CONTROLNODE_ROUTES_RESULT_VIEW,
                    view: "ControlRoutesResultView",
                    viewPathPrefix: ctwl.CONTROLNODE_VIEWPATH_PREFIX,
                    app: cowc.APP_CONTRAIL_CONTROLLER,
                    viewConfig: viewConfig
                };

            //Making the Routes call here as the result also needs to be update
            //prefix value in this form
            var routesQueryString = self.model.getControlRoutesQueryString();
            if(routesQueryString.prefix !== undefined){
                filteredPrefix = routesQueryString.prefix;
            }else{
                filteredPrefix = '';
            }
            if(routesQueryString.routingInst !== undefined){
                routInstance = routesQueryString.routingInst;
            }else{
                routInstance = '';
            }
            var routesRemoteConfig = {
                    url: monitorInfraConstants.
                        monitorInfraUrls['CONTROLNODE_ROUTES'] +
                        '?ip=' + hostname +
                        '&' + $.param(routesQueryString),
                    type: 'GET'
                };
            var listModelConfig = {
                    remote : {
                        ajaxConfig : routesRemoteConfig,
                        dataParser : function (response) {
                            var selValues = {};
                            showRouteStack = undefined;
                            backwardRouteStack = []; forwardRouteStack = [];
                            var parsedData = monitorInfraParsers.
                                        parseRoutes(response,routesQueryString);
                            if(getValueByJsonPath(response[0],'ShowRouteResp;tables;list','') !== ''){
                                backwardRoutes(response);
                                forwardRoutes(response);
                            }
                            var prefixList = [];
                            $.each(parsedData,function(i,d){
                                prefixList.push({text:d.dispPrefix,value:d.dispPrefix});
                            });
                            self.model.prefixOptionList(prefixList);
                            return parsedData;
                        }
                    },
                    cacheConfig : {
                       // ucid: ctwc.CACHE_CONFIGNODE
                    }
                };
            var backwardRoutes = function(model){
                var routingTable, showRoute, routingInstance, prefix;
                var showRouteTable = getValueByJsonPath(model[0],'ShowRouteResp;tables;list;ShowRouteTable',{});
                if(showRouteTable.constructor().length === undefined){
                    routingTable = showRouteTable.routing_table_name;
                    routingInstance =  showRouteTable.routing_instance;
                    showRoute = showRouteTable.routes.list.ShowRoute;
                }else{
                    routingTable = showRouteTable[0].routing_table_name;
                    routingInstance =  showRouteTable[0].routing_instance;
                    showRoute = showRouteTable[0].routes.list.ShowRoute
                }
                if(showRoute.constructor().length === undefined){
                    prefix = showRoute.prefix;
                }else{
                    prefix = showRoute[0].prefix;
                }
                if(showRouteStack === undefined){
                    showRouteStack = showRouteTable;
                    backwardRouteStack.push({
                        limit: routesQueryString.limit,
                        startRoutingTable: routingTable,
                        startRoutingInstance: routingInstance,
                        startPrefix: prefix,
                        prefix: filteredPrefix,
                        routingInst: routInstance
                    });
                }else{
                    if(!_.isEqual(showRouteStack, showRouteTable)){
                        showRouteStack = showRouteTable;
                        backwardRouteStack.push({
                            limit: routesQueryString.limit,
                            startRoutingTable: routingTable,
                            startRoutingInstance: routingInstance,
                            startPrefix: prefix,
                            prefix: filteredPrefix,
                            routingInst: routInstance
                        });
                    }
                }
            };
            var forwardRoutes = function(model){
                var routingTable, showRoute, routingInstance, prefix;
                var showRouteTable = getValueByJsonPath(model[0],'ShowRouteResp;tables;list;ShowRouteTable',{});
                if(showRouteTable.constructor().length === undefined){
                    routingTable = showRouteTable.routing_table_name;
                    routingInstance =  showRouteTable.routing_instance;
                    showRoute = showRouteTable.routes.list.ShowRoute;
                }else{
                    routingTable = showRouteTable[showRouteTable.length - 1].routing_table_name;
                    routingInstance =  showRouteTable[showRouteTable.length - 1].routing_instance;
                    showRoute = showRouteTable[showRouteTable.length - 1].routes.list.ShowRoute;
                }
                if(showRoute.constructor().length === undefined){
                    prefix = showRoute.prefix;
                }else{
                    prefix = showRoute[showRoute.length - 1].prefix;
                }
                forwardRouteStack.push({
                    limit: routesQueryString.limit,
                    startRoutingTable: routingTable,
                    startRoutingInstance: routingInstance,
                    startPrefix: prefix,
                    prefix: filteredPrefix,
                    routingInst:routInstance
                });
            };
            var model = new ContrailListModel(listModelConfig);
            self.renderView4Config($(self.$el).find(queryResultId),
                    model, responseViewConfig,null,null,null,function() {
                        monitorInfraUtils.bindPaginationListeners({
                            gridSel: $('#' + ctwl.CONTROLNODE_ROUTES_RESULTS),
                            model: self.model,
                            obj:viewConfig,
                            parseFn: function(response) {
                                backwardRoutes(response);
                                forwardRoutes(response);
                                var parsedData = monitorInfraParsers.
                                parseRoutes(response, routesQueryString);
                                return parsedData;
                            },
                            getUrlFn: function(step) {
                                var urlparm;
                                if(step === 'forward' && forwardRouteStack.length !== 0){
                                    urlParm = forwardRouteStack.pop();
                                    return monitorInfraConstants.
                                           monitorInfraUrls['CONTROLNODE_ROUTES'] +
                                           '?ip=' + hostname +
                                           '&' + $.param(urlParm);
                                }
                                if(step === 'backward' && backwardRouteStack.length !== 1){
                                    backwardRouteStack.splice(backwardRouteStack.length - 1, 1);
                                    urlParm = backwardRouteStack.pop();
                                    forwardRouteStack.pop();
                                    if(urlParm !== undefined){
                                        return monitorInfraConstants.
                                        monitorInfraUrls['CONTROLNODE_ROUTES'] +
                                        '?ip=' + hostname +
                                        '&' + $.param(urlParm);
                                    }
                                 }
                             }
                        });
                    });
        },

        getViewConfig: function (options,viewConfig,routingInstanceListModel) {
            var self = this;
            var hostname = viewConfig['hostname'];
            var addressFamilyList = ["All","enet","ermvpn","evpn",
                                     "inet","inetvpn","inet6","l3vpn","rtarget"];
            var routeLimits = [10, 50, 100, 200];
            $.each(routeLimits,function(idx,obj){
                routeLimits[idx] = {'value':obj,'text':obj+' Routes'};
             });
            routeLimits = [{'text':'All','value':'All'}].concat(routeLimits);
            var protocols = ['All','XMPP','BGP','ServiceChain','Static'];
            return {
                view: "SectionView",
                viewConfig: {
                    rows: [
                        {
                            columns: [
                                {
                                    elementId: 'routing_instance',
                                    view: "FormDropdownView",
                                    viewConfig: {
                                        path: 'routing_instance',
                                        dataBindValue: 'routing_instance',
                                        class: "col-xs-6",
                                        dataBindOptionList: 'routingInstanceOptionList',
                                        elementConfig: {
                                            defaultValueId: 0,
                                            dropdownAutoWidth : false,
                                            dataTextField:'text',
                                            dataValueField:'value'
                                        }
                                    }
                                },
                                {
                                    elementId: 'prefix',
                                    view: "FormComboboxView",
                                    viewConfig: {
                                        label:'Prefix',
                                        path: 'prefix',
                                        class: "col-xs-2",
                                        dataBindValue: 'prefix',
                                        dataBindOptionList: 'prefixOptionList',
                                        elementConfig: {
                                            dataTextField: "text",
                                            dataValueField: "value",
                                            placeholder: 'Prefix'
                                         }
                                    }
                                },
                                {
                                    elementId: 'routes_limit',
                                    view: "FormDropdownView",
                                    viewConfig: {
                                        path: 'routes_limit',
                                        label: 'Limit',
                                        dataBindValue: 'routes_limit',
                                        class: "col-xs-2",
                                        elementConfig: {
                                            dataTextField: "text",
                                            dataValueField: "value",
                                            data: routeLimits
                                        }
                                    }
                                }
                            ]
                        },
                        /*{
                            columns: [
                                {
                                    elementId: 'peer_source',
                                    view: "FormDropdownView",
                                    viewConfig: {
                                        path: 'peer_source',
                                        dataBindValue: 'peer_source',
                                        class: "col-xs-2",
                                        elementConfig: {
                                            dataSource: {
                                                type: 'remote',
                                                 url: contrail.format(
                                                         monitorInfraConstants.
                                                          monitorInfraUrls['CONTROLNODE_PEER_LIST'],
                                                         hostname),
                                                 parse:function(response){
                                                   var ret = ['All']
                                                   if(!(response instanceof Array)){
                                                     response = [response];
                                                   }
                                                   ret = ['All'].concat(response);
                                                   return ret;
                                                 }
                                             }
                                        }
                                    }
                                },
                                {
                                    elementId: 'address_family',
                                    view: "FormDropdownView",
                                    viewConfig: {
                                        path: 'address_family',
                                        dataBindValue: 'address_family',
                                        class: "col-xs-2",
                                        elementConfig: {
                                            data: addressFamilyList
                                        }
                                    }
                                },
                                {
                                    elementId: 'protocol',
                                    view: "FormDropdownView",
                                    viewConfig: {
                                        path: 'protocol',
                                        dataBindValue: 'protocol',
                                        class: "col-xs-2",
                                        elementConfig: {
                                            data: protocols
                                        }
                                    }
                                }
                            ]
                        },*/
                        {
                            columns: [
                                {
                                    elementId: 'run_query',
                                    view: "FormButtonView",
                                    viewConfig: {
                                        label: "Search",
                                        class: 'display-inline-block margin-0-10-0-0',
                                        elementConfig: {
                                            btnClass: 'btn-primary'
                                        }
                                    }
                                },
                                {
                                    elementId: 'reset_query',
                                    view: "FormButtonView",
                                    viewConfig: {
                                        label: "Reset",
                                        class: 'display-inline-block margin-0-10-0-0',
                                        elementConfig: {
                                            onClick: "reset"
                                        }
                                    }
                                }
                            ]
                        }
                    ]
                }
            };
        }
    });
    function parseRoutingInstanceResp (response){
        routingInstancesDropdownList = [{text:'All',value:'All'}]
        if(response != null && response['ShowRoutingInstanceSummaryResp'] != null &&
                response['ShowRoutingInstanceSummaryResp']['instances'] != null &&
                response['ShowRoutingInstanceSummaryResp']['instances']['list'] != null &&
                response['ShowRoutingInstanceSummaryResp']['instances']['list']['ShowRoutingInstance'] != null){
            var routingInstances = response['ShowRoutingInstanceSummaryResp']['instances']['list']['ShowRoutingInstance'];
            var routingInstancesLength = routingInstances.length;
            for(var i = 0; i < routingInstancesLength; i++) {
                routingInstancesDropdownList.push({text:routingInstances[i]['name'],value:routingInstances[i]['name']});
            }

        }
        return routingInstancesDropdownList;

    }
    return ControlNodeRoutesFormView;
});
<|endoftext|>


<commit_before>angular.module('app.services', [])

.factory('Tasks', function($http) {

  return {

  };
})
..factory('Auth', function ($http, $location, $window) {
  // Don't touch this Auth service!!!
  // it is responsible for authenticating our user
  // by exchanging the user's username and password
  // for a JWT from the server
  // that JWT is then stored in localStorage as 'auth-token'
  // after you signin/signup open devtools, click resources,
  // then localStorage and you'll see your token from the server
  var signin = function (user) {
    return $http({
      method: 'POST',
      url: '/api/signin',
      data: user
    })
    .then(function (resp) {
      return resp.data.token;
    });
  };

  var signup = function (user) {
    return $http({
      method: 'POST',
      url: '/api/signup',
      data: user
    })
    .then(function (resp) {
      return resp.data.token;
    });
  };

  var isAuth = function () {
    return !!$window.localStorage.getItem('com.shortly');
  };

  var signout = function () {
    $window.localStorage.removeItem('com.shortly');
    $location.path('/signin');
  };

  return {
    signin: signin,
    signup: signup,
    isAuth: isAuth,
    signout: signout
  };
});
<commit_msg>update<commit_after>angular.module('app.services', [])

.factory('Tasks', function($http) {

  return {

  };
})
.factory('Auth', function ($http, $location, $window) {
  // Don't touch this Auth service!!!
  // it is responsible for authenticating our user
  // by exchanging the user's username and password
  // for a JWT from the server
  // that JWT is then stored in localStorage as 'auth-token'
  // after you signin/signup open devtools, click resources,
  // then localStorage and you'll see your token from the server
  var signin = function (user) {
    return $http({
      method: 'POST',
      url: '/api/signin',
      data: user
    })
    .then(function (resp) {
      return resp.data.token;
    });
  };

  var signup = function (user) {
    return $http({
      method: 'POST',
      url: '/api/signup',
      data: user
    })
    .then(function (resp) {
      return resp.data.token;
    });
  };

  var isAuth = function () {
    return !!$window.localStorage.getItem('com.shortly');
  };

  var signout = function () {
    $window.localStorage.removeItem('com.shortly');
    $location.path('/signin');
  };

  return {
    signin: signin,
    signup: signup,
    isAuth: isAuth,
    signout: signout
  };
});
<|endoftext|>


<commit_before>function desktopNotification(title,text,icon) {
    try {
        var notification = new Notification(title, {
            body: text,
            icon: icon
        });
        notification.onclick = function() {
            try {
                window.blur();
                setTimeout(window.focus, 0);
                notification.close();
            } catch(e) {}
        };
        setTimeout(function(){
            try {
                notification.close();
            } catch(e) {}
        },5000);
        window.onbeforeunload = function(){
            try {
                notification.close();
            } catch(e) {}
        };
        window.addEventListener("focus", function(event) {
            try {
                notification.close();
            } catch(e) {}
        }, false);
    } catch(e) {
    }
}<commit_msg>desktop notifications: googlehatesyou edition<commit_after>function desktopNotification(title,text,icon) {
    try {
        var notification = new Notification(title, {
            body: text,
            icon: icon
        });
        notification.onclick = function() {
            try {
                window.blur();
                setTimeout(window.focus, 0);
                notification.close();
            } catch(e) {}
        };
        setTimeout(function(){
            try {
                notification.close();
            } catch(e) {}
        },5000);
        window.onbeforeunload = function(){
            try {
                notification.close();
            } catch(e) {}
        };
        window.addEventListener("focus", function(event) {
            try {
                notification.close();
            } catch(e) {}
        }, false);
    } catch(e) {
    }
}

<|endoftext|>


<commit_before>import React from 'react';
import _ from 'lodash';
import classNames  from 'classnames';

class CodePreview extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      activeTab: 0
    };
  };

  static childContextTypes = {
    codePreview: React.PropTypes.object
  };

  getChildContext = () => {
    return {
      codePreview: {
        activeTab: this.state.activeTab
      }
    };
  };

  showTab = (index) => {
    this.setState({ activeTab: index });
  };

  renderNavItem = (child, index) => {
    const { title } = child.props;
    const { activeTab } = this.state;

    return (

 this.showTab(index)}
        className={activeTab == index ? 'is-active' : ''}
      >
        {title}

    );
  };

  renderContentItem = (child, index) => {
    const { title } = child.props;
    const { activeTab } = this.state;

    return (

        {React.cloneElement(child, { isActive: (activeTab == index) })}

    );
  };

  render() {
    const { variant, children } = this.props;

    const codePreviewClassName = classNames({
      'code-preview': true,
      'code-preview--no-bottom-radius': (variant == 'no-bottom-radius')
    });

    return (

              {children.map(this.renderNavItem)}

            {children.map(this.renderContentItem)}

    );
  };
};

export default CodePreview;
<commit_msg>[WEB-297] Removing context<commit_after>import React from 'react';
import _ from 'lodash';
import classNames  from 'classnames';

export default class CodePreview extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      activeTab: 0
    };
  };

  showTab = (index) => {
    this.setState({ activeTab: index });
  };

  renderNavItem = (child, index) => {
    const { title } = child.props;
    const { activeTab } = this.state;

    return (

 this.showTab(index)}
        className={activeTab == index ? 'is-active' : ''}
      >
        {title}

    );
  };

  renderContentItem = (child, index) => {
    const { title } = child.props;
    const { activeTab } = this.state;

    return (

        {React.cloneElement(child, { isActive: (activeTab == index) })}

    );
  };

  render() {
    const { variant, children } = this.props;

    const codePreviewClassName = classNames({
      'code-preview': true,
      'code-preview--no-bottom-radius': (variant == 'no-bottom-radius')
    });

    return (

              {children.map(this.renderNavItem)}

            {children.map(this.renderContentItem)}

    );
  };
};
<|endoftext|>


<commit_before><commit_msg>test/libs/router.spec.js: add description for Router.prototype._convertRouteToXRegexExp<commit_after><|endoftext|>


<commit_before><commit_msg>Delete Annotation.js<commit_after><|endoftext|>