<commit_before>/**
* @Author: gyanl, ananayarora
* @Date:   2016-09-29T09:56:56+05:30
* @Last modified by:   ananayarora
* @Last modified time: 2016-09-29T10:00:14+05:30
*/

var newColour = [];
var format = 'hex';
//The index of the currently selected color
var currentColour = 0;
var numColours = 0;

function changeColorFormat() {
    format = document.querySelector('input[type="radio"]:checked').value;
}

function genColor() {
    var a = "";
    for (var i = 0; i < 3; i++)
        a = a.concat(Math.floor(Math.random() * 255).toString(16));

    if (a.length < 6) {
        for (var i = 0; i < (6 - a.length); i++)
            a = "0" + a;
    }
    return "#" + a;
}

function changeColour(num) {
    if (num != -1) {
        currentColour = num;
        new_color = newColour[currentColour];
        document.getElementById('c'+currentColour).focus();
        //outline();  either use the fn or just write the code here.
    } else {
        currentColour = 0;
        new_color = genColor();
        newColour.unshift(new_color);
        if (numColours<6){
            numColours++;
        }
        for (var i = 0; i < 6; i++) {
            var div_id = "c" + (i);
            document.getElementById(div_id).style.background = newColour[i];
            document.getElementById('c0').focus();
        }
    }
    document.body.style.backgroundColor = new_color;
    document.getElementById('clipboard').style.background = new_color;
    document.getElementById('generate').style.background = new_color;
    document.getElementById('copyall').style.background = new_color;
    document.getElementById('clipboard').setAttribute("data-clipboard-text", formatColor(new_color));
}

function formatColor(color) {
    color = convertColor(color, format);
    return color;
}

function toast(yo) {
    yo.setAttribute("data-clipboard-text", formatColor(newColour[currentColour]));
    document.getElementById("toast").innerHTML = yo.getAttribute("data-clipboard-text") + " copied to clipboard.";
}

function copyAll(yo) {
    var colors = formatColor(newColour[0]);
    for (var i = 1; i < 6; i++) {
        if (newColour[i]) {
            colors = colors + ", " + formatColor(newColour[i]);
        }
    }
    document.getElementById('copyall').setAttribute("data-clipboard-text", colors);
    document.getElementById("toast").innerHTML = yo.getAttribute("data-clipboard-text") + " copied to clipboard.";
}

function start() {
    var clipboard = new Clipboard('.btn');
    changeColour(-1);
}

document.onkeydown = function(e) {
    switch (e.keyCode) {
        case 82:
        changeColour(-1);
        break;

        case 67:
        var color = document.getElementById('clipboard');
        toast(color);
        break;

        case 65:
        var color = document.getElementById('copyall');
        copyAll(color);
        break;

        case 37:
        if(currentColour>0){
            changeColour(currentColour-1);
        }
        else{
            changeColour(numColours-1);
        }
        break;

        case 39:
        if(currentColour<numColours-1){
            changeColour(currentColour+1);
        }
        else{
            changeColour(0);
        }
    }
};
<commit_msg>added fix for copy<commit_after>/**
* @Author: gyanl, ananayarora
* @Date:   2016-09-29T09:56:56+05:30
* @Last modified by:   ananayarora
* @Last modified time: 2016-09-29T10:00:14+05:30
*/

var newColour = [];
var format = 'hex';
//The index of the currently selected color
var currentColour = 0;
var numColours = 0;

function changeColorFormat() {
    format = document.querySelector('input[type="radio"]:checked').value;
}

function genColor() {
    var a = "";
    for (var i = 0; i < 3; i++)
        a = a.concat(Math.floor(Math.random() * 255).toString(16));

    if (a.length < 6) {
        for (var i = 0; i < (6 - a.length); i++)
            a = "0" + a;
    }
    return "#" + a;
}

function changeColour(num) {
    if (num != -1) {
        currentColour = num;
        new_color = newColour[currentColour];
        document.getElementById('c'+currentColour).focus();
        //outline();  either use the fn or just write the code here.
    } else {
        currentColour = 0;
        new_color = genColor();
        newColour.unshift(new_color);
        if (numColours<6){
            numColours++;
        }
        for (var i = 0; i < 6; i++) {
            var div_id = "c" + (i);
            document.getElementById(div_id).style.background = newColour[i];
            document.getElementById('c0').focus();
        }
    }
    document.body.style.backgroundColor = new_color;
    document.getElementById('clipboard').style.background = new_color;
    document.getElementById('generate').style.background = new_color;
    document.getElementById('copyall').style.background = new_color;
    document.getElementById('clipboard').setAttribute("data-clipboard-text", formatColor(new_color));
}

function formatColor(color) {
    color = convertColor(color, format);
    return color;
}

function toast(yo) {
    yo.setAttribute("data-clipboard-text", formatColor(newColour[currentColour]));
    document.getElementById("toast").innerHTML = yo.getAttribute("data-clipboard-text") + " copied to clipboard.";
}

function copyAll(yo) {
    var colors = formatColor(newColour[0]);
    for (var i = 1; i < 6; i++) {
        if (newColour[i]) {
            colors = colors + ", " + formatColor(newColour[i]);
        }
    }
    document.getElementById('copyall').setAttribute("data-clipboard-text", colors);
    document.getElementById("toast").innerHTML = yo.getAttribute("data-clipboard-text") + " copied to clipboard.";
}

function start() {
    var clipboard = new Clipboard('.btn');
    changeColour(-1);
}

document.onkeydown = function(e) {
    switch (e.keyCode) {
        case 82:
        changeColour(-1);
        break;

        case 67:
        var color = document.getElementById('clipboard');
        color.click();
        break;

        case 65:
        var color = document.getElementById('copyall');
        color.click();
        break;

        case 37:
        if(currentColour>0){
            changeColour(currentColour-1);
        }
        else{
            changeColour(numColours-1);
        }
        break;

        case 39:
        if(currentColour<numColours-1){
            changeColour(currentColour+1);
        }
        else{
            changeColour(0);
        }
    }
};
<|endoftext|>


<commit_before>'use strict';

/* eslint-disable import/no-extraneous-dependencies, global-require */

const minimatch = require('minimatch');
const resolve = require('rollup-plugin-node-resolve');
const commonjs = require('rollup-plugin-commonjs');
const babel = require('rollup-plugin-babel');
const string = require('rollup-plugin-string');

function ensureArray(as) {
  return !as || Array.isArray(as) ? as : [as];
}

function flatten(a) {
  return a.reduce((result, item) => {
    if (Array.isArray(item)) {
      result.push.apply(result, flatten(item)); // eslint-disable-line prefer-spread
    } else {
      result.push(item);
    }
    return result;
  }, []);
}

const cloptions = require('minimist')(process.argv.slice(2), {
  alias: {
    b: 'browsers',
    f: 'files',
    d: 'debug',
    s: 'sauce',
    v: 'verbose',
  },
  boolean: ['debug', 'verbose'],
});

const customLaunchers = {
  sl_chrome_sierra: {
    base: 'SauceLabs',
    platform: 'OS X 10.12',
    browserName: 'chrome',
  },
  sl_chrome_linux: {
    base: 'SauceLabs',
    platform: 'Linux',
    browserName: 'chrome',
  },
  sl_chrome_win7: {
    base: 'SauceLabs',
    platform: 'Windows 7',
    browserName: 'chrome',
  },
  sl_chrome_android: {
    base: 'SauceLabs',
    platform: 'Android',
    browserName: 'chrome',
  },
  sl_firefox_sierra: {
    base: 'SauceLabs',
    platform: 'OS X 10.12',
    browserName: 'firefox',
    version: '45',
  },
  sl_firefox_linux: {
    base: 'SauceLabs',
    platform: 'Linux',
    browserName: 'firefox',
    version: '45',
  },
  sl_firefox_win7: {
    base: 'SauceLabs',
    platform: 'Windows 7',
    browserName: 'firefox',
    version: '45',
  },
  sl_safari_sierra: {
    base: 'SauceLabs',
    platform: 'OS X 10.12',
    browserName: 'safari',
    version: '10',
  },
  sl_safari_elcapitan: {
    base: 'SauceLabs',
    platform: 'OS X 10.11',
    browserName: 'safari',
    version: '10',
  },
  sl_microsoftedge_win10: {
    base: 'SauceLabs',
    version: 14,
    platform: 'Windows 10',
    browserName: 'microsoftedge',
  },
  sl_ie_win10: {
    base: 'SauceLabs',
    version: 11,
    platform: 'Windows 10',
    browserName: 'internet explorer',
  },
  sl_ie_win7: {
    base: 'SauceLabs',
    version: 11,
    platform: 'Windows 7',
    browserName: 'internet explorer',
  },
  Chrome_Travis: {
    base: 'Chrome',
    flags: ['--no-sandbox'],
  },
};

const sauceLaunchers = {
  chrome: ['sl_chrome_sierra', 'sl_chrome_linux', 'sl_chrome_win7', 'sl_chrome_android'],
  firefox: ['sl_firefox_sierra', 'sl_firefox_linux', 'sl_firefox_win7'],
  safari: ['sl_safari_sierra', 'sl_safari_elcapitan'],
  microsoftedge: ['sl_microsoftedge_win10'],
  ie: ['sl_ie_win10', 'sl_ie_win7'],
};

const travisLaunchers = {
  chrome: 'Chrome_Travis',
};

module.exports = function (config) {
  if (cloptions.sauce) {
    if (!process.env.TRAVIS) {
      throw new Error([
        'You need extra caution when you run Sauce testing locally.',
        'You can comment out lines here if you know what you are doing.',
      ].join(' '));
    }
    if (!process.env.SAUCE_USERNAME || !process.env.SAUCE_ACCESS_KEY) {
      throw new Error('Missing SAUCE_USERNAME or SAUCE_ACCESS_KEY environment variables.');
    }
  }

  config.set({
    basePath: '..',

    frameworks: ['mocha', 'sinon-chai'],

    files: (() => {
      const list = ensureArray(cloptions.files || [
        'node_modules/core-js/modules/es6.weak-map.js', // For generatoring coverage report for untested files
        'src/{components,globals}/**/*.js', // For generatoring coverage report for untested files
        'tests/spec/**/*.js',
      ]);
      const htmlFiles = list.filter(file => minimatch(file, 'src/components/**/*.html'));
      if (htmlFiles.length > 0) {
        const explanationArgs = htmlFiles.map(file => `-f ${file}`).join(' ');
        // eslint-disable-next-line no-console
        console.warn('WARNING: The given files contain component sample HTML.');
        // eslint-disable-next-line no-console
        console.warn(`You may have wanted:\n\tgulp test:a11y ${explanationArgs}`);
      }
      list.unshift('demo/polyfills/index.js');
      return list;
    })(),

    exclude: [],

    preprocessors: {
      '**/core-js/**/*.js': ['rollup', 'sourcemap'], // For generatoring coverage report for untested files
      'src/**/*.js': ['rollup', 'sourcemap'], // For generatoring coverage report for untested files
      'tests/spec/**/*.js': ['rollup', 'sourcemap'],
      'demo/polyfills/**/*.js': ['rollup', 'sourcemap'],
    },

    rollupPreprocessor: {
      plugins: [
        resolve({
          jsnext: true,
          main: true,
        }),
        string({
          include: '**/*.html',
        }),
        commonjs({
          include: ['node_modules/**'],
          namedExports: {
            'node_modules/bluebird/js/release/bluebird.js': ['promisify'],
          },
        }),
        babel({
          exclude: 'node_modules/**',
          runtimeHelpers: true,
          presets: [
            [
              'env',
              {
                modules: false,
                targets: {
                  browsers: ['last 1 version', 'ie >= 11'],
                },
              },
            ],
          ],
          plugins: [
            'transform-class-properties',
            ['transform-runtime', { polyfill: false }],
          ].concat(cloptions.debug ? [] : [
            [
              'istanbul',
              {
                include: [
                  'src/components/**/*.js',
                ],
              },
            ],
          ]),
        }),
      ],
      format: 'iife',
      moduleName: 'test',
      sourceMap: 'inline',
    },

    customLaunchers,

    sauceLabs: {
      testName: `carbon-components #${process.env.TRAVIS_BUILD_NUMBER} (${process.env.TRAVIS_BUILD_ID})`,
      buildLabel: `TRAVIS #${process.env.TRAVIS_BUILD_NUMBER} (${process.env.TRAVIS_BUILD_ID})`,
      recordScreenshots: true,
      tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER,
    },

    plugins: [
      require('karma-mocha'),
      require('karma-sinon-chai'),
      require('karma-sourcemap-loader'),
      require('karma-mocha-reporter'),
      require('karma-coverage'),
      require('karma-rollup-plugin'),
      require('karma-phantomjs-launcher'),
      require('karma-chrome-launcher'),
      require('karma-firefox-launcher'),
      require('karma-safari-launcher'),
      require('karma-ie-launcher'),
    ].concat(cloptions.sauce ? [require('karma-sauce-launcher')] : []),

    reporters: (() => {
      const reporters = ['mocha'];
      if (!cloptions.debug) {
        reporters.push('coverage');
      }
      return reporters;
    })(),

    coverageReporter: Object.assign({
      dir: 'tests/coverage',
      reporters: [
        { type: 'html' },
        { type: 'text' },
      ],
    }, cloptions.files ? {} : {
      check: {
        each: {
          statements: 40,
          branches: 40,
          functions: 40,
          lines: 40,
          excludes: [
            // Files in this exclude list are of either:
            // - Not meeting the code coverage standard set here, which shouldn't have happened
            // - Very browser dependent code that wouldn't get code coverage unless we run the suite with Sauce Labs
            // That said, new files should never be added, except for misc code that is very broser-specific
            'src/components/accordion/accordion.js',
            'src/components/copy-button/copy-button.js',
            'src/components/detail-page-header/detail-page-header.js',
            'src/components/interior-left-nav/interior-left-nav.js',
            'src/components/pagination/pagination.js',
            'src/components/search/search-with-options.js',
            'src/components/tooltip/tooltip.js',
            'src/components/unified-header/left-nav.js',
            'src/components/unified-header/profile-switcher.js',
            'src/globals/js/misc/resize.js',
          ],
        },
      },
    }),

    port: 9876,

    colors: true,

    logLevel: config.LOG_INFO,

    browserNoActivityTimeout: 60000,

    autoWatch: true,
    autoWatchBatchDelay: 400,

    browsers: flatten(ensureArray(cloptions.browsers || 'PhantomJS')
      .map((browser) => {
        const browserLower = browser.toLowerCase();
        return (cloptions.sauce && sauceLaunchers[browserLower])
          || (process.env.TRAVIS && travisLaunchers[browserLower])
          || browser;
      })),

    singleRun: false,

    concurrency: Infinity,
  });
};

<commit_msg>fix(test): avoid default-not-exported warning from Rollup in test (#176)<commit_after>'use strict';

/* eslint-disable import/no-extraneous-dependencies, global-require */

const minimatch = require('minimatch');
const resolve = require('rollup-plugin-node-resolve');
const commonjs = require('rollup-plugin-commonjs');
const babel = require('rollup-plugin-babel');
const string = require('rollup-plugin-string');

function ensureArray(as) {
  return !as || Array.isArray(as) ? as : [as];
}

function flatten(a) {
  return a.reduce((result, item) => {
    if (Array.isArray(item)) {
      result.push.apply(result, flatten(item)); // eslint-disable-line prefer-spread
    } else {
      result.push(item);
    }
    return result;
  }, []);
}

const cloptions = require('minimist')(process.argv.slice(2), {
  alias: {
    b: 'browsers',
    f: 'files',
    d: 'debug',
    s: 'sauce',
    v: 'verbose',
  },
  boolean: ['debug', 'verbose'],
});

const customLaunchers = {
  sl_chrome_sierra: {
    base: 'SauceLabs',
    platform: 'OS X 10.12',
    browserName: 'chrome',
  },
  sl_chrome_linux: {
    base: 'SauceLabs',
    platform: 'Linux',
    browserName: 'chrome',
  },
  sl_chrome_win7: {
    base: 'SauceLabs',
    platform: 'Windows 7',
    browserName: 'chrome',
  },
  sl_chrome_android: {
    base: 'SauceLabs',
    platform: 'Android',
    browserName: 'chrome',
  },
  sl_firefox_sierra: {
    base: 'SauceLabs',
    platform: 'OS X 10.12',
    browserName: 'firefox',
    version: '45',
  },
  sl_firefox_linux: {
    base: 'SauceLabs',
    platform: 'Linux',
    browserName: 'firefox',
    version: '45',
  },
  sl_firefox_win7: {
    base: 'SauceLabs',
    platform: 'Windows 7',
    browserName: 'firefox',
    version: '45',
  },
  sl_safari_sierra: {
    base: 'SauceLabs',
    platform: 'OS X 10.12',
    browserName: 'safari',
    version: '10',
  },
  sl_safari_elcapitan: {
    base: 'SauceLabs',
    platform: 'OS X 10.11',
    browserName: 'safari',
    version: '10',
  },
  sl_microsoftedge_win10: {
    base: 'SauceLabs',
    version: 14,
    platform: 'Windows 10',
    browserName: 'microsoftedge',
  },
  sl_ie_win10: {
    base: 'SauceLabs',
    version: 11,
    platform: 'Windows 10',
    browserName: 'internet explorer',
  },
  sl_ie_win7: {
    base: 'SauceLabs',
    version: 11,
    platform: 'Windows 7',
    browserName: 'internet explorer',
  },
  Chrome_Travis: {
    base: 'Chrome',
    flags: ['--no-sandbox'],
  },
};

const sauceLaunchers = {
  chrome: ['sl_chrome_sierra', 'sl_chrome_linux', 'sl_chrome_win7', 'sl_chrome_android'],
  firefox: ['sl_firefox_sierra', 'sl_firefox_linux', 'sl_firefox_win7'],
  safari: ['sl_safari_sierra', 'sl_safari_elcapitan'],
  microsoftedge: ['sl_microsoftedge_win10'],
  ie: ['sl_ie_win10', 'sl_ie_win7'],
};

const travisLaunchers = {
  chrome: 'Chrome_Travis',
};

module.exports = function (config) {
  const objectToStringPolyfillPath = require.resolve('core-js/library/modules/es6.object.to-string.js');

  if (cloptions.sauce) {
    if (!process.env.TRAVIS) {
      throw new Error([
        'You need extra caution when you run Sauce testing locally.',
        'You can comment out lines here if you know what you are doing.',
      ].join(' '));
    }
    if (!process.env.SAUCE_USERNAME || !process.env.SAUCE_ACCESS_KEY) {
      throw new Error('Missing SAUCE_USERNAME or SAUCE_ACCESS_KEY environment variables.');
    }
  }

  config.set({
    basePath: '..',

    frameworks: ['mocha', 'sinon-chai'],

    files: (() => {
      const list = ensureArray(cloptions.files || [
        'node_modules/core-js/modules/es6.weak-map.js', // For generatoring coverage report for untested files
        'src/{components,globals}/**/*.js', // For generatoring coverage report for untested files
        'tests/spec/**/*.js',
      ]);
      const htmlFiles = list.filter(file => minimatch(file, 'src/components/**/*.html'));
      if (htmlFiles.length > 0) {
        const explanationArgs = htmlFiles.map(file => `-f ${file}`).join(' ');
        // eslint-disable-next-line no-console
        console.warn('WARNING: The given files contain component sample HTML.');
        // eslint-disable-next-line no-console
        console.warn(`You may have wanted:\n\tgulp test:a11y ${explanationArgs}`);
      }
      list.unshift('demo/polyfills/index.js');
      return list;
    })(),

    exclude: [],

    preprocessors: {
      '**/core-js/**/*.js': ['rollup', 'sourcemap'], // For generatoring coverage report for untested files
      'src/**/*.js': ['rollup', 'sourcemap'], // For generatoring coverage report for untested files
      'tests/spec/**/*.js': ['rollup', 'sourcemap'],
      'demo/polyfills/**/*.js': ['rollup', 'sourcemap'],
    },

    rollupPreprocessor: {
      plugins: [
        {
          // eslint-disable-next-line consistent-return
          load(id) {
            // core-js/library/modules/es6.object.to-string.js is a zero-length file
            if (id === objectToStringPolyfillPath) {
              return 'export default undefined';
            }
          },
        },
        resolve({
          jsnext: true,
          main: true,
        }),
        string({
          include: '**/*.html',
        }),
        commonjs({
          include: ['node_modules/**'],
          namedExports: {
            'node_modules/bluebird/js/release/bluebird.js': ['promisify'],
          },
        }),
        babel({
          exclude: 'node_modules/**',
          runtimeHelpers: true,
          presets: [
            [
              'env',
              {
                modules: false,
                targets: {
                  browsers: ['last 1 version', 'ie >= 11'],
                },
              },
            ],
          ],
          plugins: [
            'transform-class-properties',
            ['transform-runtime', { polyfill: false }],
          ].concat(cloptions.debug ? [] : [
            [
              'istanbul',
              {
                include: [
                  'src/components/**/*.js',
                ],
              },
            ],
          ]),
        }),
      ],
      format: 'iife',
      moduleName: 'test',
      sourceMap: 'inline',
    },

    customLaunchers,

    sauceLabs: {
      testName: `carbon-components #${process.env.TRAVIS_BUILD_NUMBER} (${process.env.TRAVIS_BUILD_ID})`,
      buildLabel: `TRAVIS #${process.env.TRAVIS_BUILD_NUMBER} (${process.env.TRAVIS_BUILD_ID})`,
      recordScreenshots: true,
      tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER,
    },

    plugins: [
      require('karma-mocha'),
      require('karma-sinon-chai'),
      require('karma-sourcemap-loader'),
      require('karma-mocha-reporter'),
      require('karma-coverage'),
      require('karma-rollup-plugin'),
      require('karma-phantomjs-launcher'),
      require('karma-chrome-launcher'),
      require('karma-firefox-launcher'),
      require('karma-safari-launcher'),
      require('karma-ie-launcher'),
    ].concat(cloptions.sauce ? [require('karma-sauce-launcher')] : []),

    reporters: (() => {
      const reporters = ['mocha'];
      if (!cloptions.debug) {
        reporters.push('coverage');
      }
      return reporters;
    })(),

    coverageReporter: Object.assign({
      dir: 'tests/coverage',
      reporters: [
        { type: 'html' },
        { type: 'text' },
      ],
    }, cloptions.files ? {} : {
      check: {
        each: {
          statements: 40,
          branches: 40,
          functions: 40,
          lines: 40,
          excludes: [
            // Files in this exclude list are of either:
            // - Not meeting the code coverage standard set here, which shouldn't have happened
            // - Very browser dependent code that wouldn't get code coverage unless we run the suite with Sauce Labs
            // That said, new files should never be added, except for misc code that is very broser-specific
            'src/components/accordion/accordion.js',
            'src/components/copy-button/copy-button.js',
            'src/components/detail-page-header/detail-page-header.js',
            'src/components/interior-left-nav/interior-left-nav.js',
            'src/components/pagination/pagination.js',
            'src/components/search/search-with-options.js',
            'src/components/tooltip/tooltip.js',
            'src/components/unified-header/left-nav.js',
            'src/components/unified-header/profile-switcher.js',
            'src/globals/js/misc/resize.js',
          ],
        },
      },
    }),

    port: 9876,

    colors: true,

    logLevel: config.LOG_INFO,

    browserNoActivityTimeout: 60000,

    autoWatch: true,
    autoWatchBatchDelay: 400,

    browsers: flatten(ensureArray(cloptions.browsers || 'PhantomJS')
      .map((browser) => {
        const browserLower = browser.toLowerCase();
        return (cloptions.sauce && sauceLaunchers[browserLower])
          || (process.env.TRAVIS && travisLaunchers[browserLower])
          || browser;
      })),

    singleRun: false,

    concurrency: Infinity,
  });
};

<|endoftext|>


<commit_before>// Basic Operations

function run ()
{
	var compute = ((13+2)*34-2);
	console.log(compute);

	var string = "IlovemyMacbookPro".length;
	console.log(string);

	var string1 = "Hello";
	var string2 = "World";
	console.log(string1+" "+string2+"!");

	var num = 10;
	console.log(num+=10);
	console.log(num-=10);
	console.log(num*=10);
	console.log(num/=10);

	var str1 = "asdasdasdsadasdasdsad";
	var str2 = "Adasdasdasdasd";

	console.log(str1==str2);

	console.log(str2[0]);
}

run();

<commit_msg>Implemented JS charAt property<commit_after>// Basic Operations

function run ()
{
	var compute = ((13+2)*34-2);
	console.log(compute);

	var string = "IlovemyMacbookPro".length;
	console.log(string);

	var string1 = "Hello";
	var string2 = "World";
	console.log(string1+" "+string2+"!");

	var num = 10;
	console.log(num+=10);
	console.log(num-=10);
	console.log(num*=10);
	console.log(num/=10);

	var str1 = "asdas dasdsadasdasdsad";
	var str2 = "Adasdasdasdasd";

	console.log(str1==str2);

	console.log(str2[0]);

	console.log(str1.charAt(5));
}

run();

<|endoftext|>


<commit_before>module.exports = config => {
  config.set({
    frameworks: ['jasmine'],

    files: ['*.js'],

    preprocessors: {
      '*.js': ['webpack'],
    },

    browsers: [process.env.BROWSER || 'chrome'],

    plugins: [
      'karma-chrome-launcher',
      'karma-webpack',
      'karma-jasmine',
    ],

    webpack: {
      devtool: 'inline-source-map',
    },

    customLaunchers: {
      chrome: {
        base: 'Chrome',
        flags: ['--use-fake-device-for-media-stream',
                '--use-fake-ui-for-media-stream', '--disable-popup-blocking'],
      },
      firefox: {
        base: 'Firefox',
        prefs: {
          'media.navigator.permission.disabled': true,
          'media.navigator.streams.fake': true,
        },
      },
    },

    webpackMiddleware: {
      noInfo: true,
    },
  });
};
<commit_msg>Forgot to include the plugin<commit_after>module.exports = config => {
  config.set({
    frameworks: ['jasmine'],

    files: ['*.js'],

    preprocessors: {
      '*.js': ['webpack'],
    },

    browsers: [process.env.BROWSER || 'chrome'],

    plugins: [
      'karma-chrome-launcher',
      'karma-firefox-launcher',
      'karma-webpack',
      'karma-jasmine',
    ],

    webpack: {
      devtool: 'inline-source-map',
    },

    customLaunchers: {
      chrome: {
        base: 'Chrome',
        flags: ['--use-fake-device-for-media-stream',
                '--use-fake-ui-for-media-stream', '--disable-popup-blocking'],
      },
      firefox: {
        base: 'Firefox',
        prefs: {
          'media.navigator.permission.disabled': true,
          'media.navigator.streams.fake': true,
        },
      },
    },

    webpackMiddleware: {
      noInfo: true,
    },
  });
};
<|endoftext|>


<commit_before>(function(window, document, undefined) {
    window.onload = init;
    function init() {
        //get the canvas
        var canvas = document.getElementById("mapcanvas");
        var c = canvas.getContext("2d");
        var cwidth = 960;
        var cheight = 540;
        var moves = {
            u: [0,-1],
            d: [0,1],
            l: [-1,0],
            r: [1,0]
        };
        document.getElementById("paintbtn").onclick = paint;

        function shuffle(array) {
          var currentIndex = array.length, temporaryValue, randomIndex ;

          // While there remain elements to shuffle...
          while (0 !== currentIndex) {

            // Pick a remaining element...
            randomIndex = Math.floor(Math.random() * currentIndex);
            currentIndex -= 1;

            // And swap it with the current element.
            temporaryValue = array[currentIndex];
            array[currentIndex] = array[randomIndex];
            array[randomIndex] = temporaryValue;
          }

          return array;
        }

        function reset(){
            c.clearRect ( 0 , 0 , canvas.width, canvas.height );
            c.beginPath();
        }

        function walk(start, stop, steps){
            var distX = stop.x - start.x;
            var distY = stop.y - start.y;

            var walkSteps = [];
            for(var i = 0; i< Math.abs(distX); i++){
                if(distX < 0){
                    walkSteps.push(moves.l);
                } else {
                    walkSteps.push(moves.r);
                }
            }
            for(var i = 0; i< Math.abs(distY); i++){
                if(distY < 0){
                    walkSteps.push(moves.u);
                } else {
                    walkSteps.push(moves.d);
                }
            }

            //add a number of random pairs based on how big our grid is
            for(var i = 0; i< steps; i++){
                var rand = Math.floor(Math.random() * 2);
                if(rand < 1){
                    walkSteps.push(moves.u);
                    walkSteps.push(moves.d);
                } else{
                    walkSteps.push(moves.l);
                    walkSteps.push(moves.r);
                }
            }

            return shuffle(walkSteps);
        }

        function createRoom(x, y, pw, ph){
            var randw = Math.floor((Math.random() * ((pw/2) - 1 + 1) + 1) );
            var randh = Math.floor((Math.random() * ((ph/2) - 1 + 1) + 1) );
            //alert(randw + ", " + randh);

            return [randw, randh];
        }

        function paint(){
            reset();

            var widthSelect = document.getElementById("width");
            var pathWidth = widthSelect.options[widthSelect.selectedIndex].value;

            var heightSelect = document.getElementById("height");
            var pathHeight = heightSelect.options[heightSelect.selectedIndex].value;
            //alert(pathWidth + ", " + pathHeight);

            //create a start and endpoint based on the grid size
            var startpoint = {
               x: -1,
               y: -1
            }
           var endpoint = {
               x: -1,
               y: -1
            }
            startpoint.x = 0;
            startpoint.y = pathHeight - 1;

            endpoint.x = pathWidth - 1;
            endpoint.y = 0;

            //paint the base grid
            for(var i = 0; i< pathWidth; i++){
                for(var j = 0; j< pathHeight; j++){

                    c.beginPath();
                    //c.lineWidth = 1;
                    c.fillStyle = "#000000";
                    c.fillRect(i*30, j*30, 30, 30);
                    c.stroke();
               }
           }

           var randsteps = 2* Math.floor((pathWidth/2) * (pathHeight/2));

           //create a random path that we will walk
           var walkArray = walk(startpoint, endpoint, randsteps);

           //create two moving points representing where we are and where we were
           var movingpoint = {
               x: -1,
               y: -1
           };
           var movingpointold = {
               x: -1,
               y: -1
           };
           movingpoint.x = startpoint.x;
           movingpoint.y = startpoint.y;
           movingpointold.x = startpoint.x;
           movingpointold.y = startpoint.y;

           //follow the path and paint along the way
           for (var i = 0; i< walkArray.length; i++){
               movingpoint.x = movingpoint.x + walkArray[i][0];
               movingpoint.y = movingpoint.y + walkArray[i][1];
               var oppcurrMoveX = -1 * walkArray[i][0];
               var oppcurrMoveY = -1 * walkArray[i][1];
               var index = -1;
               for(var j = i; j< walkArray.length; j++){
                   if(walkArray[j][0] == oppcurrMoveX && walkArray[j][1] == oppcurrMoveY){
                       index = j;
                       break;
                   }
               }
               if(movingpoint.x > pathWidth -1){
                   movingpoint.x = movingpoint.x - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }
               if(movingpoint.x < 0){
                   movingpoint.x = movingpoint.x + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }
               if(movingpoint.y > pathHeight -1){
                   movingpoint.y = movingpoint.y - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }
               if( movingpoint.y < 0){
                   movingpoint.y = movingpoint.y + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }

               var movedirX = movingpoint.x - movingpointold.x;
               var movedirY = movingpoint.y - movingpointold.y;

               for(var l = 0; l< 30; l++){
                   c.fillStyle = "#FFFFFF";
                   c.fillRect(movingpointold.x*30 + l*movedirX + 9, movingpointold.y*30 + l*movedirY + 9, 6, 6);
               }

               c.fillStyle = "#FFFFFF";
               c.fillRect(movingpoint.x*30, movingpoint.y*30, 24, 24);

               movingpointold.x = movingpoint.x;
               movingpointold.y = movingpoint.y;
           }

            for(var i = 0; i< Math.floor(pathWidth/2)+1; i++){
                for(var j = 0; j< Math.floor(pathHeight/2)+1; j++){
                    var randRoom = Math.floor((Math.random() * 9));
                    if(randRoom < 1){
                        roomDim = createRoom(i,j,pathWidth,pathHeight);
                        c.beginPath();
                        c.lineWidth = 3;
                        c.fillStyle = "#FFFFFF";
                        c.fillRect(i*30 , j*30, roomDim[0]*24, roomDim[1]*24);
                        c.stroke();
                    }
                }
            }

            //paint the start and end points.
            c.fillStyle = "#33CC33";
            c.fillRect(startpoint.x*30, startpoint.y*30, 24, 24);
            c.fillStyle = "#CC0000";
            c.fillRect(endpoint.x*30, endpoint.y*30, 24 ,24);
        }
    }
})(window, document, undefined);
<commit_msg>Update script.js<commit_after>(function(window, document, undefined) {
    window.onload = init;
    function init() {
        //get the canvas
        var canvas = document.getElementById("mapcanvas");
        var c = canvas.getContext("2d");
        var cwidth = 960;
        var cheight = 540;
        var moves = {
            u: [0,-1],
            d: [0,1],
            l: [-1,0],
            r: [1,0]
        };
        document.getElementById("paintbtn").onclick = paint;

        function shuffle(array) {
          var currentIndex = array.length, temporaryValue, randomIndex ;

          // While there remain elements to shuffle...
          while (0 !== currentIndex) {

            // Pick a remaining element...
            randomIndex = Math.floor(Math.random() * currentIndex);
            currentIndex -= 1;

            // And swap it with the current element.
            temporaryValue = array[currentIndex];
            array[currentIndex] = array[randomIndex];
            array[randomIndex] = temporaryValue;
          }

          return array;
        }

        function reset(){
            c.clearRect ( 0 , 0 , canvas.width, canvas.height );
            c.beginPath();
        }

        function walk(start, stop, steps){
            var distX = stop.x - start.x;
            var distY = stop.y - start.y;

            var walkSteps = [];
            for(var i = 0; i< Math.abs(distX); i++){
                if(distX < 0){
                    walkSteps.push(moves.l);
                } else {
                    walkSteps.push(moves.r);
                }
            }
            for(var i = 0; i< Math.abs(distY); i++){
                if(distY < 0){
                    walkSteps.push(moves.u);
                } else {
                    walkSteps.push(moves.d);
                }
            }

            //add a number of random pairs based on how big our grid is
            for(var i = 0; i< steps; i++){
                var rand = Math.floor(Math.random() * 2);
                if(rand < 1){
                    walkSteps.push(moves.u);
                    walkSteps.push(moves.d);
                } else{
                    walkSteps.push(moves.l);
                    walkSteps.push(moves.r);
                }
            }

            return shuffle(walkSteps);
        }

        function createRoom(x, y, pw, ph){
            var randw = Math.floor((Math.random() * ((pw/2) - 1 + 1) + 1) );
            var randh = Math.floor((Math.random() * ((ph/2) - 1 + 1) + 1) );
            //alert(randw + ", " + randh);

            return [randw, randh];
        }

        function paint(){
            reset();

            var widthSelect = document.getElementById("width");
            var pathWidth = widthSelect.options[widthSelect.selectedIndex].value;

            var heightSelect = document.getElementById("height");
            var pathHeight = heightSelect.options[heightSelect.selectedIndex].value;
            //alert(pathWidth + ", " + pathHeight);

            //create a start and endpoint based on the grid size
            var startpoint = {
               x: -1,
               y: -1
            }
           var endpoint = {
               x: -1,
               y: -1
            }
            startpoint.x = 0;
            startpoint.y = pathHeight - 1;

            endpoint.x = pathWidth - 1;
            endpoint.y = 0;

            //paint the base grid
            for(var i = 0; i< pathWidth; i++){
                for(var j = 0; j< pathHeight; j++){

                    c.beginPath();
                    //c.lineWidth = 1;
                    c.fillStyle = "#000000";
                    c.fillRect(i*30, j*30, 30, 30);
                    c.stroke();
               }
           }

           var randsteps = 2* Math.floor((pathWidth/2) * (pathHeight/2));

           //create a random path that we will walk
           var walkArray = walk(startpoint, endpoint, randsteps);

           //create two moving points representing where we are and where we were
           var movingpoint = {
               x: -1,
               y: -1
           };
           var movingpointold = {
               x: -1,
               y: -1
           };
           movingpoint.x = startpoint.x;
           movingpoint.y = startpoint.y;
           movingpointold.x = startpoint.x;
           movingpointold.y = startpoint.y;

           //follow the path and paint along the way
           for (var i = 0; i< walkArray.length; i++){
               movingpoint.x = movingpoint.x + walkArray[i][0];
               movingpoint.y = movingpoint.y + walkArray[i][1];
               var oppcurrMoveX = -1 * walkArray[i][0];
               var oppcurrMoveY = -1 * walkArray[i][1];
               var index = -1;
               for(var j = i; j< walkArray.length; j++){
                   if(walkArray[j][0] == oppcurrMoveX && walkArray[j][1] == oppcurrMoveY){
                       index = j;
                       break;
                   }
               }
               if(movingpoint.x > pathWidth -1){
                   movingpoint.x = movingpoint.x - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }
               if(movingpoint.x < 0){
                   movingpoint.x = movingpoint.x + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }
               if(movingpoint.y > pathHeight -1){
                   movingpoint.y = movingpoint.y - 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }
               if( movingpoint.y < 0){
                   movingpoint.y = movingpoint.y + 1;
                   if (index > -1) {
                       walkArray.splice(index, 1);
                   }

               }

               var movedirX = movingpoint.x - movingpointold.x;
               var movedirY = movingpoint.y - movingpointold.y;

               for(var l = 0; l< 30; l++){
                   c.fillStyle = "#FFFFFF";
                   c.fillRect(movingpointold.x*30 + l*movedirX + 9, movingpointold.y*30 + l*movedirY + 9, 6, 6);
               }

               c.fillStyle = "#FFFFFF";
               c.fillRect(movingpoint.x*30, movingpoint.y*30, 24, 24);

               movingpointold.x = movingpoint.x;
               movingpointold.y = movingpoint.y;
           }

            for(var i = 0; i< Math.floor(pathWidth/2)+1; i++){
                for(var j = 0; j< Math.floor(pathHeight/2)+1; j++){
                    var randRoom = Math.floor((Math.random() * 9));
                    if(randRoom < 1){
                        roomDim = createRoom(i,j,pathWidth,pathHeight);
                        c.beginPath();
                        //c.lineWidth = 3;
                        c.fillStyle = "#FFFFFF";
                        c.fillRect(i*30 , j*30, roomDim[0]*30 - roomDim[0]*6, roomDim[1]*30 - roomDim[1]*6);
                        c.stroke();
                    }
                }
            }

            //paint the start and end points.
            c.fillStyle = "#33CC33";
            c.fillRect(startpoint.x*30, startpoint.y*30, 24, 24);
            c.fillStyle = "#CC0000";
            c.fillRect(endpoint.x*30, endpoint.y*30, 24 ,24);
        }
    }
})(window, document, undefined);
<|endoftext|>


<commit_before>// Modal Image Gallery
function onClick(element) {
    document.getElementById("img01").src = element.src;
    document.getElementById("modal01").style.display = "block";
    var captionText = document.getElementById("caption");
    captionText.innerHTML = element.alt;
}

// Change style of navbar on scroll
window.onscroll = function() {myFunction()};
function myFunction() {
    var navbar = document.getElementById("myNavbar");
    if (document.body.scrollTop > 100 || document.documentElement.scrollTop > 100) {
        navbar.className = "w3-bar" + " w3-card-2" + " w3-animate-top" + " w3-white";
    } else {
        navbar.className = navbar.className.replace(" w3-card-2 w3-animate-top w3-white", "");
    }
}

// Used to toggle the menu on small screens when clicking on the menu button
function toggleFunction() {
    var x = document.getElementById("navDemo");
    if (x.className.indexOf("w3-show") == -1) {
        x.className += " w3-show";
    } else {
        x.className = x.className.replace(" w3-show", "");
    }
}

//connecting scroll to a div class

    var $win = $(window);
    $win.on('scroll', function(s){

    var top = $win.scrollTop();

    top = top - 4300;

    if(top<0)
    $('.contactInfo').css('margin-left',top + 'px');
});

//image scroll
var $win = $(window);
$win.on('scroll', function(s){
  var top = $win.scrollTop();
  top = top/8;
$('.aliMain').css('margin-right',top + 'px');
});

// bounce animation for new link
setInterval(function(){
    $('#laramedia').toggleClass('animated swing');
},1500);
//animating the email
setInterval(function(){
    $('#email').toggleClass('animated swing');
},2000);
//aniamting CV
setInterval(function(){
    $('#cv').toggleClass('animated flash');
},2000);

  var typed = new Typed('#myName', {
    strings: ["Ali Kiyan"],
    typeSpeed: 300
  });
  var typed = new Typed('#bio', {
    strings: ["My name is Ali and I am studying my masters ( Databases and Web-Based Systems as an international student. I am a 22 year old tech fanatic looking for an oppotunity to work and master my skill. Having studied in software engineering in my Bachelor, I can say I have a proper understanding of computer science and software development. I have experience in web development and designed full web sites (front-end and backend with database design). I would like to develop applications and web applications as well."],
    typeSpeed: 30
  });
  var typed = new Typed('#cvT', {
    strings: ["Ali Kiyan CV"],
    typeSpeed: 100
  });

document.querySelectorAll(".typed-cursor")[0].style.display = "none";
document.querySelectorAll(".typed-cursor")[1].style.display = "none";
document.querySelectorAll(".typed-cursor")[2].style.display = "none";
<commit_msg>minor<commit_after>// Modal Image Gallery
function onClick(element) {
    document.getElementById("img01").src = element.src;
    document.getElementById("modal01").style.display = "block";
    var captionText = document.getElementById("caption");
    captionText.innerHTML = element.alt;
}

// Change style of navbar on scroll
window.onscroll = function() {myFunction()};
function myFunction() {
    var navbar = document.getElementById("myNavbar");
    if (document.body.scrollTop > 100 || document.documentElement.scrollTop > 100) {
        navbar.className = "w3-bar" + " w3-card-2" + " w3-animate-top" + " w3-white";
    } else {
        navbar.className = navbar.className.replace(" w3-card-2 w3-animate-top w3-white", "");
    }
}

// Used to toggle the menu on small screens when clicking on the menu button
function toggleFunction() {
    var x = document.getElementById("navDemo");
    if (x.className.indexOf("w3-show") == -1) {
        x.className += " w3-show";
    } else {
        x.className = x.className.replace(" w3-show", "");
    }
}

//connecting scroll to a div class

    var $win = $(window);
    $win.on('scroll', function(s){

    var top = $win.scrollTop();

    top = top - 4300;

    if(top<0)
    $('.contactInfo').css('margin-left',top + 'px');
});

//image scroll
var $win = $(window);
$win.on('scroll', function(s){
  var top = $win.scrollTop();
  top = top/8;
$('.aliMain').css('margin-right',top + 'px');
});

// bounce animation for new link
setInterval(function(){
    $('#laramedia').toggleClass('animated swing');
},1500);
//animating the email
setInterval(function(){
    $('#email').toggleClass('animated swing');
},2000);
//aniamting CV
setInterval(function(){
    $('#cv').toggleClass('animated flash');
},2000);

  var typed = new Typed('#myName', {
    strings: ["Ali Kiyan"],
    typeSpeed: 300
  });
  var typed = new Typed('#bio', {
    strings: ["My name is Ali and I am studying my masters ( Databases and Web-Based Systems) as an international student. I am a 22 year old tech fanatic looking for an oppotunity to work and master my skill. Having studied in software engineering in my Bachelor, I can say I have a proper understanding of computer science and software development. I have experience in web development and designed full web sites (front-end and backend with database design). I would like to develop applications and web applications as well."],
    typeSpeed: 30
  });
  var typed = new Typed('#cvT', {
    strings: ["Ali Kiyan CV"],
    typeSpeed: 100
  });

document.querySelectorAll(".typed-cursor")[0].style.display = "none";
document.querySelectorAll(".typed-cursor")[1].style.display = "none";
document.querySelectorAll(".typed-cursor")[2].style.display = "none";
<|endoftext|>


<commit_before>(function () {
    'use strict';

    var VERBOSE = true;
    var argv = require('nw.gui').App.argv;
    var FileManager = require('./js/file-manager');

    var keys = {
        escape: 27
    };
    var WORKING_FILE_NAME = 'working-file';

    var editor = new EpicEditor({
        basePath: 'lib/EpicEditor-v0.2.2/',
        focusOnLoad: true,
        button: false,
        autogrow: true,
        file: {
            name: WORKING_FILE_NAME,
            autoSave: 3000,
        }
    });

    var file_manager = new FileManager(editor);
    if (VERBOSE) {
        file_manager.on('event', function (event) {
            if (event.type !== 'error') {
                console.log(event.type, event);
            }
        });
    }

    editor.load(function () {
        jQuery(function () {
            $('input[type=file][name=file-to-open]').on('change', handleFile(function (file_path) {
                file_manager.openFile(file_path);
            }));

            $('input[type=file][name=file-to-save]').on('change', handleFile(function (file_path) {
                file_manager.saveFile(file_path);
            }));

            $('input[type=file][name=file-to-export]').on('change', handleFile(function (file_path) {
                file_manager.exportFile(file_path, 'html');
            }));

            function handleFile(processor) {
                return function (event) {
                    var $input_file = $(event.currentTarget);
                    var file_path = $input_file.val();

                    if (!file_path) {
                        return;
                    }
                    $input_file.val('');
                    processor(file_path);
                };
            }

            $('button#fullscreen').on('click', function () {
                editor.enterFullscreen();
            });

            $(window).on('keyup', function (event) {
                if (editor.is('fullscreen') && event.keyCode === keys.escape) {
                    editor.exitFullscreen();
                }
            });

            $('input[type=radio][name=mode-choice]').on('change', function (event) {
                var $selected = event.currentTarget;
                try {
                    editor[$selected.value]();
                } catch (error) {
                    throw new Error('unknown mode `' + $selected.value + '`');
                }
            });
        });
    });
}());
<commit_msg>Add: program args handling feature<commit_after>(function () {
    'use strict';

    var VERBOSE = true;
    var argv = require('nw.gui').App.argv;
    var FileManager = require('./js/file-manager');

    var keys = {
        escape: 27
    };
    var WORKING_FILE_NAME = 'working-file';

    var editor = new EpicEditor({
        basePath: 'lib/EpicEditor-v0.2.2/',
        focusOnLoad: true,
        button: false,
        autogrow: true,
        file: {
            name: WORKING_FILE_NAME,
            autoSave: 3000,
        }
    });

    var file_manager = new FileManager(editor);
    if (VERBOSE) {
        file_manager.on('event', function (event) {
            if (event.type !== 'error') {
                console.log(event.type, event);
            }
        });
    }

    editor.load(function () {
        if (argv.length) {
            file_manager.openFile(argv.join(' '));
        }

        jQuery(function () {
            $('input[type=file][name=file-to-open]').on('change', handleFile(function (file_path) {
                file_manager.openFile(file_path);
            }));

            $('input[type=file][name=file-to-save]').on('change', handleFile(function (file_path) {
                file_manager.saveFile(file_path);
            }));

            $('input[type=file][name=file-to-export]').on('change', handleFile(function (file_path) {
                file_manager.exportFile(file_path, 'html');
            }));

            function handleFile(processor) {
                return function (event) {
                    var $input_file = $(event.currentTarget);
                    var file_path = $input_file.val();

                    if (!file_path) {
                        return;
                    }
                    $input_file.val('');
                    processor(file_path);
                };
            }

            $('button#fullscreen').on('click', function () {
                editor.enterFullscreen();
            });

            $(window).on('keyup', function (event) {
                if (editor.is('fullscreen') && event.keyCode === keys.escape) {
                    editor.exitFullscreen();
                }
            });

            $('input[type=radio][name=mode-choice]').on('change', function (event) {
                var $selected = event.currentTarget;
                try {
                    editor[$selected.value]();
                } catch (error) {
                    throw new Error('unknown mode `' + $selected.value + '`');
                }
            });
        });
    });
}());
<|endoftext|>


<commit_before>function calculateLabel ($obj, possibilities){
	var possibilities = (typeof possibilities == 'object') ? possibilities : ["te_name", "name", "title", "id"];
	var eventLabel = null;
	for (var i = 0; i <= (possibilities.length - 1); i++) {
		var possibility = $obj.attr(possibilities[i]);
		if(possibility && possibility.length){
			eventLabel = possibility;
			break;
		}
	}
	return eventLabel;
}
function pushEvent ( eventInfo ) {
	if(window.trackeverything.settings.debug){ console.log(eventInfo); }
	_gaq.push(eventInfo);
}
jQuery(function ($){
	$.expr[':'].external = function(obj){
		return !obj.href.match(/^mailto:/) && !obj.href.match(/^#:/) && (obj.hostname.replace(/^www\./i, '') != document.location.hostname.replace(/^www\./i, ''));
	};

	for (var i = window.trackeverything.dictionary.length - 1; i >= 0; i--) {
		$(window.trackeverything.dictionary[i].selector).attr("te_name", window.trackeverything.dictionary[i].name);
	}
	if(window.trackeverything.settings.forms){
		$("form").on("submit.jqte.jqtedefault", function (e) {
			var formLabel = calculateLabel($(this));

			var eventInfo = ['_trackEvent', 'Form', 'Submission'];
			if(formLabel != null){
				eventInfo.push(formLabel);
			}
			if(!(window.trackeverything.settings.search == false && $(this).attr("method") && $(this).attr("method").toLowerCase() == "get" && $(this).children("input[name=s]").length)){
				pushEvent(eventInfo);
			}
		});
		if(window.trackeverything.settings.debug){
			$("form").addClass("track-everything track-everything-default track-everything-form");
		}
	}
	if(window.trackeverything.settings.outbound){
		$("a:external").on("click.jqte.jqtedefault keypress.jqte.jqtedefault", function (e) {
			var eventLabel = calculateLabel($(this), ["te_name", "href"]);

			var eventInfo = ['_trackEvent', 'Link', 'Outbound', eventLabel, null, true];
			pushEvent(eventInfo);
		});
		if(window.trackeverything.settings.debug){
			$("a:external").addClass("track-everything track-everything-default track-everything-outbound");
		}
	}
	if(window.trackeverything.settings.email){
		$('a[href^="mailto:"]').on("click.jqte.jqtedefault keypress.jqte.jqtedefault", function (e) {
			var eventLabel = $(this).attr("href").substring(7);

			var eventInfo = ['_trackEvent', 'Link', 'Email', eventLabel, null, true];
			pushEvent(eventInfo);
		});
		if(window.trackeverything.settings.debug){
			$('a[href^="mailto:"]').addClass("track-everything track-everything-default track-everything-outbound");
		}
	}
	for (var i = window.trackeverything.special.length - 1; i >= 0; i--) {
		var $special = window.trackeverything.special[i];
		$($special.selector).off(".jqtedefault");
		if(window.trackeverything.settings.debug){
			$($special.selector).addClass("track-everything track-everything-special").removeClass("track-everything-default");
		}
		var events = [];
		for (var j = $special.events.length - 1; j >= 0; j--) {
			events = $special.events[j] + ".jqte.jqtespecial";
		}
		$($special.selector).on(events.join(" "), function () {
			if($special.name.length){
				$(this).attr("te_oname", $special.name);
			}
			var eventLabel = calculateLabel($(this), ["te_oname", "te_name", "name", "title", "id", "href"]);
			var eventInfo = ['_trackEvent', $special.category, $special.action, eventLabel];

			pushEvent(eventInfo);
		});
	};
});<commit_msg>Fixed Email Tracking<commit_after>function calculateLabel ($obj, possibilities){
	var possibilities = (typeof possibilities == 'object') ? possibilities : ["te_name", "name", "title", "id"];
	var eventLabel = null;
	for (var i = 0; i <= (possibilities.length - 1); i++) {
		var possibility = $obj.attr(possibilities[i]);
		if(possibility && possibility.length){
			eventLabel = possibility;
			break;
		}
	}
	return eventLabel;
}
function pushEvent ( eventInfo ) {
	if(window.trackeverything.settings.debug){ console.log(eventInfo); }
	_gaq.push(eventInfo);
}
jQuery(function ($){
	$.expr[':'].external = function(obj){
		return !obj.href.match(/^mailto:/) && !obj.href.match(/^#:/) && (obj.hostname.replace(/^www\./i, '') != document.location.hostname.replace(/^www\./i, ''));
	};

	for (var i = window.trackeverything.dictionary.length - 1; i >= 0; i--) {
		$(window.trackeverything.dictionary[i].selector).attr("te_name", window.trackeverything.dictionary[i].name);
	}
	if(window.trackeverything.settings.forms){
		$("form").on("submit.jqte.jqtedefault", function (e) {
			var formLabel = calculateLabel($(this));

			var eventInfo = ['_trackEvent', 'Form', 'Submission'];
			if(formLabel != null){
				eventInfo.push(formLabel);
			}
			if(!(window.trackeverything.settings.search == false && $(this).attr("method") && $(this).attr("method").toLowerCase() == "get" && $(this).children("input[name=s]").length)){
				pushEvent(eventInfo);
			}
		});
		if(window.trackeverything.settings.debug){
			$("form").addClass("track-everything track-everything-default track-everything-form");
		}
	}
	if(window.trackeverything.settings.outbound){
		$("a:external").on("click.jqte.jqtedefault keypress.jqte.jqtedefault", function (e) {
			var eventLabel = calculateLabel($(this), ["te_name", "href"]);

			var eventInfo = ['_trackEvent', 'Link', 'Outbound', eventLabel, null, true];
			pushEvent(eventInfo);
		});
		if(window.trackeverything.settings.debug){
			$("a:external").addClass("track-everything track-everything-default track-everything-outbound");
		}
	}
	if(window.trackeverything.settings.email){
		$('a[href^="mailto:"]').on("click.jqte.jqtedefault keypress.jqte.jqtedefault", function (e) {
			var eventLabel = $(this).attr("href").substring(7);

			var eventInfo = ['_trackEvent', 'Link', 'Email', eventLabel];
			pushEvent(eventInfo);
		});
		if(window.trackeverything.settings.debug){
			$('a[href^="mailto:"]').addClass("track-everything track-everything-default track-everything-email");
		}
	}
	for (var i = window.trackeverything.special.length - 1; i >= 0; i--) {
		var $special = window.trackeverything.special[i];
		$($special.selector).off(".jqtedefault");
		if(window.trackeverything.settings.debug){
			$($special.selector).addClass("track-everything track-everything-special").removeClass("track-everything-default");
		}
		var events = [];
		for (var j = $special.events.length - 1; j >= 0; j--) {
			events = $special.events[j] + ".jqte.jqtespecial";
		}
		$($special.selector).on(events.join(" "), function () {
			if($special.name.length){
				$(this).attr("te_oname", $special.name);
			}
			var eventLabel = calculateLabel($(this), ["te_oname", "te_name", "name", "title", "id", "href"]);
			var eventInfo = ['_trackEvent', $special.category, $special.action, eventLabel];

			pushEvent(eventInfo);
		});
	};
});<|endoftext|>


<commit_before>(function (OC, window, $, undefined) {
    'use strict';

$(document).ready(function () {

    // this notes object holds all our notes
    var Papers = function (baseUrl) {
        this._baseUrl = baseUrl;
        this._papers = [];
        this._activePaper = undefined;
    };

    Papers.prototype = {
        load: function (id) {
            var self = this;
            this._papers.forEach(function (paper) {
                if (paper.id === id) {
                    paper.active = true;
                    self._activeNote = paper;
                } else {
                    paper.active = false;
                }
            });
        },
        getActive: function () {
            return this._activePaper;
        },
        getAll: function () {
            return this._papers;
        },
        loadAll: function () {
            var deferred = $.Deferred();
            var self = this;
            $.get(this._baseUrl).done(function (papers) {
                self._activePaper = undefined;
                self._papers = papers;
                deferred.resolve();
            }).fail(function () {
                deferred.reject();
            });
            return deferred.promise();
        },
        create: function (paper) {
            var deferred = $.Deferred();
            var self = this;
            $.ajax({
                url: this._baseUrl,
                method: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(paper)
            }).done(function (paper) {
                self._papers.push(paper);
                self._activeNote = paper;
                self.load(paper.id);
                deferred.resolve();
            }).fail(function () {
                deferred.reject();
            });
            return deferred.promise();
        }
    };

    // this will be the view that is used to update the html
    var View = function (papers) {
        this._papers = papers;
    };

    View.prototype = {
        renderContent: function () {
        },
        renderList: function () {
            var tmpl = $.templates("#list-template");
            var papers = {papers: this._papers.getAll()};
            var html = tmpl.render(papers);
            $("#paper-list").find("ul").html(html);
        },
        renderNavigation: function () {
            var self = this;
            $('#add_button').click(function () {
                var paper = {
                    url: $('#add_url').val()
                };

                self._papers.create(paper).done(function() {
                    self.render();
                }).fail(function () {
                    alert('Could not add new paper');
                });
            });
        },
        render: function () {
            this.renderContent();
            this.renderList();
            this.renderNavigation();
        }
    };

    var papers = new Papers(OC.generateUrl('/apps/paper/papers'));
    var view = new View(papers);
    papers.loadAll().done(function () {
        view.render();
    }).fail(function () {
        alert('Could not load papers');
    });
});

})(OC, window, jQuery);<commit_msg>Clear input on creation<commit_after>(function (OC, window, $, undefined) {
    'use strict';

$(document).ready(function () {

    // this notes object holds all our notes
    var Papers = function (baseUrl) {
        this._baseUrl = baseUrl;
        this._papers = [];
        this._activePaper = undefined;
    };

    Papers.prototype = {
        load: function (id) {
            var self = this;
            this._papers.forEach(function (paper) {
                if (paper.id === id) {
                    paper.active = true;
                    self._activeNote = paper;
                } else {
                    paper.active = false;
                }
            });
        },
        getActive: function () {
            return this._activePaper;
        },
        getAll: function () {
            return this._papers;
        },
        loadAll: function () {
            var deferred = $.Deferred();
            var self = this;
            $.get(this._baseUrl).done(function (papers) {
                self._activePaper = undefined;
                self._papers = papers;
                deferred.resolve();
            }).fail(function () {
                deferred.reject();
            });
            return deferred.promise();
        },
        create: function (paper) {
            var deferred = $.Deferred();
            var self = this;
            $.ajax({
                url: this._baseUrl,
                method: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(paper)
            }).done(function (paper) {
                self._papers.push(paper);
                self._activeNote = paper;
                self.load(paper.id);
                deferred.resolve();
            }).fail(function () {
                deferred.reject();
            });
            return deferred.promise();
        }
    };

    // this will be the view that is used to update the html
    var View = function (papers) {
        this._papers = papers;
    };

    View.prototype = {
        renderContent: function () {
        },
        renderList: function () {
            var tmpl = $.templates("#list-template");
            var papers = {papers: this._papers.getAll()};
            var html = tmpl.render(papers);
            $("#paper-list").find("ul").html(html);
        },
        renderNavigation: function () {
            var self = this;
            $('#add_button').click(function () {
                var paper = {
                    url: $('#add_url').val()
                };

                self._papers.create(paper).done(function() {
                    self.render();
                    $('#add_url').val('');
                }).fail(function () {
                    alert('Could not add new paper');
                });
            });
        },
        render: function () {
            this.renderContent();
            this.renderList();
            this.renderNavigation();
        }
    };

    var papers = new Papers(OC.generateUrl('/apps/paper/papers'));
    var view = new View(papers);
    papers.loadAll().done(function () {
        view.render();
    }).fail(function () {
        alert('Could not load papers');
    });
});

})(OC, window, jQuery);<|endoftext|>


<commit_before>/**
 * main script to make ajax requests, handle responses and create graphs.
 */

/**
 * Draw chart.
 * @param data
 */
function drawChart(data) {
    var _data = [];
    var keysArr = Object.keys(data);
    for (var i = 0; i < keysArr.length; i++) {
        if (i > 10) {
            continue;
        }
        var obj = data[keysArr[i]];
        var name = obj.name;
        var x = [];
        var y = [];
        obj.data.forEach(function (val, index) {
            y.push(val.duration);
            x.push(dateFormat(val.startTime));
        });
        _data.push({
            x: x,
            y: y,
            mode: 'lines',
            type: 'scatter',
            name: name
        });
    }

    function dateFormat(ts) {
        var dateStr = "";
        var d = new Date(ts);
        dateStr = d.getFullYear() + "-";
        dateStr = dateStr + (d.getMonth() + 1) + "-";
        dateStr = dateStr + (d.getDate()) + " ";
        dateStr = dateStr + (d.getHours()) + ":";
        dateStr = dateStr + (d.getMinutes()) + ":";
        dateStr = dateStr + (d.getSeconds()) + "";
        return dateStr;
    }

    var layout = {
        title: 'My Stats',
        showlegend: true,
        xaxis: {
            type: 'date'
        },
        yaxis: {
            title: 'Time',
            type: 'linear'
        }
    };
    Plotly.newPlot('my-chart', _data, layout, {showLink: false});
}
/**
 * Process array of items and group single website data.
 * @example
 * {"<website_name>"{
 * data:[]
 * name:<website name>
 * }}
 * @param items {Array} of items
 */
function processItems(items) {
    var data = {};
    items.forEach(function (val, index) {
        if (typeof data[val.domain] === "undefined") {
            data[val.domain] = {
                data: [],
                name: val.domain
            }
        }
        data[val.domain].data.push(val);
    });
    return data;
}

function init() {
    gapi.client.load('greeting', 'v1', function () {
        gapi.client.greeting.website_data.get().execute(function (resp) {
            console.log(resp.items);
            drawChart(processItems(resp.items));
        });
    }, "https://my-stats-ext.appspot.com/_ah/api");
}<commit_msg>Display only top 10 sites in sorted order.<commit_after>/**
 * main script to make ajax requests, handle responses and create graphs.
 */

/**
 * Draw chart.
 * @param data
 */
function drawChart(websiteData) {
    var data = websiteData[0];
    var sortObj = websiteData[1];
    var _data = [];
    var keysArr = Object.keys(sortObj);
    for (var i = 0; i < keysArr.length; i++) {
        var obj = data[keysArr[i]];
        var name = obj.name;
        var x = [];
        var y = [];
        obj.data.forEach(function (val, index) {
            y.push(secToHours(val.duration));
            x.push(dateFormat(val.startTime));
        });
        _data.push({
            x: x,
            y: y,
            mode: 'lines',
            type: 'scatter',
            name: name
        });
    }

    function dateFormat(ts) {
        var dateStr = "";
        var d = new Date(ts);
        dateStr = d.getFullYear() + "-";
        dateStr = dateStr + (d.getMonth() + 1) + "-";
        dateStr = dateStr + (d.getDate()) + " ";
        dateStr = dateStr + (d.getHours()) + ":";
        dateStr = dateStr + (d.getMinutes()) + ":";
        dateStr = dateStr + (d.getSeconds()) + "";
        return dateStr;
    }

    function secToHours(sec) {
        return (sec / (60 * 60));
    }

    var layout = {
        title: 'My Stats',
        showlegend: true,
        xaxis: {
            type: 'date'
        },
        yaxis: {
            title: 'Time(Hours)',
            type: 'linear'
        }
    };
    Plotly.newPlot('my-chart', _data, layout, {showLink: false});
}
/**
 * Process array of items and group single website data.
 * @example
 * {"<website_name>"{
 * data:[]
 * name:<website name>
 * }}
 * @param items {Array} of items
 */
function processItems(items) {
    var data = {};
    var durObj = {};
    var sortArr;
    items.forEach(function (val, index) {
        if (typeof data[val.domain] === "undefined") {
            data[val.domain] = {
                data: [],
                name: val.domain
            }
            durObj[val.domain] = {
                duration: 0
            }
        }
        durObj[val.domain]['duration'] += val.duration;
        data[val.domain].data.push(val);
    });
    console.log(durObj);
    sortArr = sortByDur(durObj);
    return [data, sortArr];
}

function sortByDur(obj) {
    var keyArr = Object.keys(obj);
    var sortableArr = [];
    var sortObj = {};
    keyArr.forEach(function (val) {
        sortableArr.push([val, obj[val]['duration']]);
    });
    var sortArr = sortableArr.sort(function (a, b) {
        return a[1] - b[1];
    });
    /* Convert to object first 10 sites.*/
    console.log(sortArr);
    for (var i = sortArr.length - 1; i > sortArr.length - 11; i--) {
        sortObj[sortArr[i][0]] = sortArr[i][1];
    }
    console.log(sortObj);
    return sortObj;
}
function init() {
    gapi.client.load('greeting', 'v1', function () {
        gapi.client.greeting.website_data.get().execute(function (resp) {
            console.log(resp.items);
            drawChart(processItems(resp.items));
        });
    }, "https://my-stats-ext.appspot.com/_ah/api");
}<|endoftext|>


<commit_before>/**
 * Author: Olaolu Olawuyi

 * Date Created: 20/08/2015

 * Last Modified: 24/04/2016

 * Twitter: @whizkydee, @webtwic

 * Github: https://github.com/webtwic/webtwic-site

*/

var Webtwic = Webtwic || {};

browser_name = bowser.name.toLowerCase();

var test_canvas = document.createElement( 'canvas' );
var canvascheck = ( test_canvas.getContext ) ? true : false;

Webtwic = {
	// Basic Information about Webtwic
	name: 'Webtwic',
	description: 'A community focused on code tweaks, articles and tutorials for newbie and professional developers.',
	repo: 'https://github.com/webtwic/webtwic-site',
	author: 'Olaolu Olawuyi',
	version: '1.0.0',

	// Start main functions for the object

	// Function to add browser name and version to body class
	showBrowser: function( b ) {
		b = (typeof b == 'undefined') ? browser_name : b.toLowerCase();
		if ( ! ( bowser.webkit ) )
			$( 'body' ).addClass( b + ' ' + b + parseInt( bowser.version ) );
		else
			$( 'body' ).addClass( 'webkit' + ' ' + b + ' ' + b + parseInt( bowser.version ) );
	},

	// Function to set attributes and values to elements
	setAttr: function( elem, name, val ) {
		$( elem, this ).attr( name, val );
	},

	// Function to push down .site-content
	adjustSiteContent: function() {
		if ( $( 'body' ).hasClass( 'default-body' ) ) {
			$( '.top-stripe' ).addClass( 'adjustedMargin' );
			$( '#header .logo' ).addClass( 'adjustedTop' );
			$( '.main-menu' ).addClass( 'adjustedMargin' );
			$( '#header' ).addClass( 'adjustSiteContent' );
		} else if ( $( 'body' ).hasClass( 'secondary-body' ) ) {
			$( '.site-content' ).addClass( 'adjustSiteContent' );
			$( '.secondary-header' ).addClass( 'adjustedMargin' );
		}
	},

	// Function to push up .site-content to default state
	undoSiteAdjust: function() {
		if ( $( 'body' ).hasClass( 'default-body' ) ) {
			$( '.top-stripe' ).removeClass( 'adjustedMargin' );
			$( '#header .logo' ).removeClass( 'adjustedTop' );
			$( '.main-menu' ).removeClass( 'adjustedMargin' );
			$( '#header' ).removeClass( 'adjustSiteContent' );
		} else if ( $( 'body' ).hasClass( 'secondary-body' ) ) {
			$( '.secondary-header' ).removeClass( 'adjustedMargin' );
		}
	},

	// Function to show Notifications before header
	showNotif: function( text ) {
		text = ( typeof text == 'undefined' ) ? notif_text : text;
		Webtwic.adjustSiteContent();
		$( 'body' ).prepend(
			'
'+text+''+close_button+'
'
		);

		$( '.close-button' ).on( 'click', function( e ) {
			e.preventDefault();
			Webtwic.undoReset();
		});
	},

	// Function to hide Notifications
	hideNotif: function() {
		$( '#notifBanner' ).removeClass( 'notif_vis' );
	},

	resetSite: function() {
		Webtwic.showNotif();
		Webtwic.adjustSiteContent();
	},

	undoReset: function() {
		Webtwic.hideNotif();
		Webtwic.undoSiteAdjust();
	},
};

var WBT = Webtwic,

	 $$ = Webtwic,

	 close_button = '',

	 browser_link = ' ' + 'bowser.' + ' ',

	 notif_text = 'Whoa. Your browser currently dosen\'t support some necessary features. Please try refreshing this page or get a better' +browser_link;

// Detect when the DOM is ready

jQuery( document ).ready( function() {
	// Test for HTML5 support
	if ( window.Modernizr )
		if ( !Modernizr.canvas )
			Webtwic.showNotif ( "Oops. Looks like your browser doesn't support HTML5. Please get a better" +browser_link+ "for an awesome experience." );
		 else /* do nothing */ ;
	 else if ( !window.Modernizr )
		if ( canvascheck === false )
			Webtwic.showNotif ( "Oops. Looks like your browser doesn't support HTML5. Please get a better" +browser_link+ "for an awesome experience." );
		 else /* do nothing */ ;
	 else /* do nothing */ ;

	// Define Variables
	var $scroll_top = $( 'a.scroll_top' ),
	is_toggle_active = $( '.hamburger' ).hasClass( 'is_active' ),
	height = 200;

	// Performance Fixes

	// Start browser detection
	switch ( browser_name ) {
	   case 'microsoft edge':
	      Webtwic.showBrowser( 'msedge' );
	      break;
		default:
			Webtwic.showBrowser();
	}

	/*
		TODO: Rebuild Performance fixes for attributes
		See history of Performance fixes.
		Also, check StackOverflow.
		See Issue #12
	*/
	var M = Modernizr;

	var required_features = M.flexbox || M.inlinesvg || M.svg || M.svgclippaths || M.fontface || M.boxshadow || M.borderradius || M.csstransforms;

	if ( window.Modernizr )
		if ( !( required_features ) )
			Webtwic.showNotif();
		else /* do nothing */ ;
	 else /* do nothing */ ;

	// Start Main Page

	$( 'nav li ul.drop-nav' )
	.hide()
	.removeClass( 'dropNavFallback' );

	if ( $( window ).width() > 768 ) {
		$( 'nav li.dropdown' ).hover(function() {
			$( 'ul.drop-nav', this )
			.stop()
			.slideDown( 'fast' );
		}, function() {
			$( 'ul.drop-nav', this )
			.stop()
			.slideUp( 'fast' );
		});
	}

	$( '.active-item' ).append(
		'<svg viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><path d="M 16.682,19.674c 0.010-0.012, 0.014-0.028, 0.024-0.040l 6.982-7.714c 0.39-0.434, 0.39-1.138,0-1.572 c-0.004-0.004-0.008-0.006-0.012-0.008C 23.496,10.13, 23.244,10, 22.964,10L 8.998,10 c-0.286,0-0.54,0.138-0.722,0.352L 8.272,10.348 c-0.39,0.434-0.39,1.138,0,1.572l 6.998,7.754C 15.66,20.108, 16.292,20.108, 16.682,19.674z"></path></svg>'
	);

	$( 'a.hamburger' ).on('click', function( e ) {
		$( this ).toggleClass( 'is_active' );

		e.preventDefault();
	});
	$( '.mobile-header .mobile-nav' ).hide();

	$( window ).scroll(function() {
		( $( this ).scrollTop() > height ) ? $scroll_top.addClass( 'topVisible' ): $scroll_top.removeClass( 'topVisible' );
	});

	// Styles for homepage article-social

	$( '.article .article-social a' ).hover(function() {
		$( 'span', this )
		.eq(1)
		.fadeIn(400);
	}, function() {
		$( 'span', this )
		.eq(1)
		.fadeOut(250);
	});

	// Functions for search-icon and ui-overlay-search

	$( '.header-follow-search .search-wrap' ).on( 'click', function() {
		openUiOverlay();
	});

	$( '.header-follow-search .close-icon' ).on( 'click', function( e ) {
		e.preventDefault();
		closeUiOverlay();
	});

	$( '.header-follow-search .close-icon' ).hover(
		function() {
			$( this ).addClass( 'spin' );
		}, function() {
			$( this ).removeClass( 'spin' );
	});

	function openUiOverlay() {
		$( '.ui-overlay-search' )
		.fadeIn(400)
		.addClass( 'is_open' );
	}

	function closeUiOverlay() {
		$( '.ui-overlay-search' )
		.fadeOut(400)
		.removeClass( 'is_open' );
	}

	$( '.ui-overlay-search .search-input input' ).on('focus', function() {
		$( '.search-input' ).attr( 'data-focused', 'true' );
		$( '.search-input input' ).addClass( '_is-focused' );
		$( '#__expand' ).addClass( 'visible' );
	});

	$( '.ui-overlay-search .search-input input' ).on('blur', function() {
		$( '.search-input' ).attr( 'data-focused', 'false' );
		$( '.search-input input' ).removeClass( '_is-focused' );
		$( '#__expand' ).removeClass( 'visible' );
	});

	$( '.post-meta .post-meta-inner .cta-btns a.is_inactive' ).on( 'click', function( e ) {
		e.preventDefault();
	});

	$( document ).keydown(function( e ) {
		if ( e.keyCode == 27 )
			closeUiOverlay();
		else /* do nothing */ ;
 	});

	$( '.mobile-nav' ).hide();

	// Functions for more-posts button click

	var loadMoreBtn = '.secondary-category-section .category-posts-column [data-clicked="false"]';

	function addLoader() {
		$( loadMoreBtn )
		.attr( 'data-clicked', 'true' )
		.append( '' );
	}

	$( loadMoreBtn ).on( 'click', function( e ) {
		$( this ).css({
			'background': '#50ABF1',
			'color': '#fff'
		});
		addLoader();
		e.preventDefault();
	});

	$scroll_top.on( 'click', function( e ) {
		$( 'body, html' ).animate({
			scrollTop: 0
		}, 1000);

		e.preventDefault();
	});

});
<commit_msg>Update script.js<commit_after>/**
 * Author: Olaolu Olawuyi

 * Date Created: 20/08/2015

 * Last Modified: 24/04/2016

 * Twitter: @whizkydee, @webtwic

 * Github: https://github.com/webtwic/webtwic-site

*/

var Webtwic = Webtwic || {};

browser_name = bowser.name.toLowerCase();

var test_canvas = document.createElement( 'canvas' );
var canvascheck = ( test_canvas.getContext ) ? true : false;

Webtwic = {
	// Basic Information about Webtwic
	name: 'Webtwic',
	description: 'A community focused on code tweaks, articles and tutorials for newbie and professional developers.',
	repo: 'https://github.com/webtwic/webtwic-site',
	author: 'Olaolu Olawuyi',
	version: '1.0.0',

	// Start main functions for the object

	// Function to add browser name and version to body class
	showBrowser: function( b ) {
		b = (typeof b == 'undefined') ? browser_name : b.toLowerCase();
		if ( ! ( bowser.webkit ) )
			$( 'body' ).addClass( b + ' ' + b + parseInt( bowser.version ) );
		else
			$( 'body' ).addClass( 'webkit' + ' ' + b + ' ' + b + parseInt( bowser.version ) );
	},

	// Function to set attributes and values to elements
	setAttr: function( elem, name, val ) {
		$( elem, this ).attr( name, val );
	},

	// Function to push down .site-content
	adjustSiteContent: function() {
		if ( $( 'body' ).hasClass( 'default-body' ) ) {
			$( '.top-stripe' ).addClass( 'adjustedMargin' );
			$( '#header .logo' ).addClass( 'adjustedTop' );
			$( '.main-menu' ).addClass( 'adjustedMargin' );
			$( '#header' ).addClass( 'adjustSiteContent' );
		} else if ( $( 'body' ).hasClass( 'secondary-body' ) ) {
			$( '.site-content' ).addClass( 'adjustSiteContent' );
			$( '.secondary-header' ).addClass( 'adjustedMargin' );
		}
	},

	// Function to push up .site-content to default state
	undoSiteAdjust: function() {
		if ( $( 'body' ).hasClass( 'default-body' ) ) {
			$( '.top-stripe' ).removeClass( 'adjustedMargin' );
			$( '#header .logo' ).removeClass( 'adjustedTop' );
			$( '.main-menu' ).removeClass( 'adjustedMargin' );
			$( '#header' ).removeClass( 'adjustSiteContent' );
		} else if ( $( 'body' ).hasClass( 'secondary-body' ) ) {
			$( '.secondary-header' ).removeClass( 'adjustedMargin' );
		}
	},

	// Function to show Notifications before header
	showNotif: function( text ) {
		text = ( typeof text == 'undefined' ) ? notif_text : text;
		Webtwic.adjustSiteContent();
		$( 'body' ).prepend(
			'
'+text+''+close_button+'
'
		);

		$( '.close-button' ).on( 'click', function( e ) {
			e.preventDefault();
			Webtwic.undoReset();
		});
	},

	// Function to hide Notifications
	hideNotif: function() {
		$( '#notifBanner' ).removeClass( 'notif_vis' );
	},

	resetSite: function() {
		Webtwic.showNotif();
		Webtwic.adjustSiteContent();
	},

	undoReset: function() {
		Webtwic.hideNotif();
		Webtwic.undoSiteAdjust();
	},
};

var WBT = Webtwic,
	 $$ = Webtwic,
	 close_button = '',
	 browser_link = ' ' + 'bowser.' + ' ',
	 notif_text = 'Whoa. Your browser currently dosen\'t support some important features. Please try refreshing this page or get a better' +browser_link;

// Detect when the DOM is ready

jQuery( document ).ready( function() {
	// Test for HTML5 support
	if ( window.Modernizr )
		if ( !Modernizr.canvas )
			Webtwic.showNotif ( "Oops. Looks like your browser doesn't support HTML5. Please get a better" +browser_link+ "for an awesome experience." );
		 else /* do nothing */ ;
	 else if ( !window.Modernizr )
		if ( canvascheck === false )
			Webtwic.showNotif ( "Oops. Looks like your browser doesn't support HTML5. Please get a better" +browser_link+ "for an awesome experience." );
		 else /* do nothing */ ;
	 else /* do nothing */ ;

	// Define Variables
	var $scroll_top = $( 'a.scroll_top' ),
	is_toggle_active = $( '.hamburger' ).hasClass( 'is_active' ),
	height = 200;

	// Performance Fixes

	// Start browser detection
	switch ( browser_name ) {
	   case 'microsoft edge':
	      Webtwic.showBrowser( 'msedge' );
	      break;
		default:
			Webtwic.showBrowser();
	}

	/*
		TODO: Rebuild Performance fixes for attributes
		See history of Performance fixes.
		Also, check StackOverflow.
		See Issue #12
	*/
	var M = Modernizr;

	var required_features = M.flexbox || M.inlinesvg || M.svg || M.svgclippaths || M.fontface || M.boxshadow || M.borderradius || M.csstransforms;

	if ( window.Modernizr )
		if ( !( required_features ) )
			Webtwic.showNotif();
		else /* do nothing */ ;
	 else /* do nothing */ ;

	// Start Main Page

	$( 'nav li ul.drop-nav' )
	.hide()
	.removeClass( 'dropNavFallback' );

	if ( $( window ).width() > 768 ) {
		$( 'nav li.dropdown' ).hover(function() {
			$( 'ul.drop-nav', this )
			.stop()
			.slideDown( 'fast' );
		}, function() {
			$( 'ul.drop-nav', this )
			.stop()
			.slideUp( 'fast' );
		});
	}

	$( '.active-item' ).append(
		'<svg viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><path d="M 16.682,19.674c 0.010-0.012, 0.014-0.028, 0.024-0.040l 6.982-7.714c 0.39-0.434, 0.39-1.138,0-1.572 c-0.004-0.004-0.008-0.006-0.012-0.008C 23.496,10.13, 23.244,10, 22.964,10L 8.998,10 c-0.286,0-0.54,0.138-0.722,0.352L 8.272,10.348 c-0.39,0.434-0.39,1.138,0,1.572l 6.998,7.754C 15.66,20.108, 16.292,20.108, 16.682,19.674z"></path></svg>'
	);

	$( 'a.hamburger' ).on('click', function( e ) {
		$( this ).toggleClass( 'is_active' );

		e.preventDefault();
	});
	$( '.mobile-header .mobile-nav' ).hide();

	$( window ).scroll(function() {
		( $( this ).scrollTop() > height ) ? $scroll_top.addClass( 'topVisible' ): $scroll_top.removeClass( 'topVisible' );
	});

	// Styles for homepage article-social

	$( '.article .article-social a' ).hover(function() {
		$( 'span', this )
		.eq(1)
		.fadeIn(400);
	}, function() {
		$( 'span', this )
		.eq(1)
		.fadeOut(250);
	});

	// Functions for search-icon and ui-overlay-search

	$( '.header-follow-search .search-wrap' ).on( 'click', function() {
		openUiOverlay();
	});

	$( '.header-follow-search .close-icon' ).on( 'click', function( e ) {
		e.preventDefault();
		closeUiOverlay();
	});

	$( '.header-follow-search .close-icon' ).hover(
		function() {
			$( this ).addClass( 'spin' );
		}, function() {
			$( this ).removeClass( 'spin' );
	});

	function openUiOverlay() {
		$( '.ui-overlay-search' )
		.fadeIn(400)
		.addClass( 'is_open' );
	}

	function closeUiOverlay() {
		$( '.ui-overlay-search' )
		.fadeOut(400)
		.removeClass( 'is_open' );
	}

	$( '.ui-overlay-search .search-input input' ).on('focus', function() {
		$( '.search-input' ).attr( 'data-focused', 'true' );
		$( '.search-input input' ).addClass( '_is-focused' );
		$( '#__expand' ).addClass( 'visible' );
	});

	$( '.ui-overlay-search .search-input input' ).on('blur', function() {
		$( '.search-input' ).attr( 'data-focused', 'false' );
		$( '.search-input input' ).removeClass( '_is-focused' );
		$( '#__expand' ).removeClass( 'visible' );
	});

	$( '.post-meta .post-meta-inner .cta-btns a.is_inactive' ).on( 'click', function( e ) {
		e.preventDefault();
	});

	$( document ).keydown(function( e ) {
		if ( e.keyCode == 27 )
			closeUiOverlay();
		else /* do nothing */ ;
 	});

	$( '.mobile-nav' ).hide();

	// Functions for more-posts button click

	var loadMoreBtn = '.secondary-category-section .category-posts-column [data-clicked="false"]';

	function addLoader() {
		$( loadMoreBtn )
		.attr( 'data-clicked', 'true' )
		.append( '' );
	}

	$( loadMoreBtn ).on( 'click', function( e ) {
		$( this ).css({
			'background': '#50ABF1',
			'color': '#fff'
		});
		addLoader();
		e.preventDefault();
	});

	$scroll_top.on( 'click', function( e ) {
		$( 'body, html' ).animate({
			scrollTop: 0
		}, 1000);

		e.preventDefault();
	});

});
<|endoftext|>


<commit_before>var parser = {};
// Return the node containing the DOM path leading to the html object containing
// offending pattern e.g. Taiwan, Province of China.
parser.getOffendingNode = function() {
  var taiwanNodePath = parser.getTaiwanNode_();
  if (taiwanNodePath.length == 0) {
    return null;
  }
  var taiwanNode = taiwanNodePath[taiwanNodePath.length - 1];
  if (parser.matchOffending_(taiwanNode.innerHTML)) {
    return taiwanNode;
  }
  return null;
};

function scrollIntoView (element, alignTop) {

    var document = element.ownerDocument;
    var origin = element, originRect = origin.getBoundingClientRect();
    var hasScroll = false;
    var documentScroll = document.scrollingElement;

    while (element) {

        if (element == document.body) {
            element = documentScroll;
        } else {
            element = element.parentNode;
        }

        if (element) {
            var hasScrollbar = (!element.clientHeight) ? false : element.scrollHeight > element.clientHeight;

            if (!hasScrollbar) {
                if (element == documentScroll) {
                    element = null;
                }
                continue;
            }

            var rects;
            if (element == documentScroll) {
                rects = {
                    left : 0,
                    top : 0
                };
            } else {
                rects = element.getBoundingClientRect();
            }

            // check that elementRect is in rects
            var deltaLeft = originRect.left - (rects.left + (parseInt(element.style.borderLeftWidth, 10) | 0));
            var deltaRight = originRect.right
                            - (rects.left + element.clientWidth + (parseInt(element.style.borderLeftWidth, 10) | 0));
            var deltaTop = originRect.top - (rects.top + (parseInt(element.style.borderTopWidth, 10) | 0));
            var deltaBottom = originRect.bottom
                            - (rects.top + element.clientHeight + (parseInt(element.style.borderTopWidth, 10) | 0));

            // adjust display depending on deltas
            if (deltaLeft < 0) {
                element.scrollLeft += deltaLeft;
            } else if (deltaRight > 0) {
                element.scrollLeft += deltaRight;
            }

            if (alignTop === true && !hasScroll) {
                element.scrollTop += deltaTop;
            } else if (alignTop === false && !hasScroll) {
                element.scrollTop += deltaBottom;
            } else {
                if (deltaTop < 0) {
                    element.scrollTop += deltaTop;
                } else if (deltaBottom > 0) {
                    element.scrollTop += deltaBottom;
                }
            }

            if (element == documentScroll) {
                element = null;
            } else {
                // readjust element position after scrolls, and check if vertical scroll has changed.
                // this is required to perform only one alignment
                var nextRect = origin.getBoundingClientRect();
                if (nextRect.top != originRect.top) {
                    hasScroll = true;
                }
                originRect = nextRect;
            }
        }
    }

    // put the element into middle of the view
    document.body.scrollTop -= screen.height/2;

}

// Private methods.
parser.getTaiwanNode_ = function() {
  var node = $('*:contains("Taiwan")');
  if (node) {
    return node;
  }
  return $('*:contains("taiwan")');
};
parser.getText_ = function(node) {
  var lastNode = node.last();
  return lastNode[0].innerHTML;
};

parser.patterns_ = [
  new RegExp('taiwan\\s*,?\\s*province\\s*of\\s*china', 'i'),
  new RegExp('taiwan\\s*,?\\s*prc', 'i'),
  new RegExp('taiwan\\s*,?\\s*china', 'i'),
  new RegExp('china\\s*,?\\s*taiwan', 'i')
];

parser.matchOffending_ = function(text) {
  for (var x = 0; x < parser.patterns_.length; ++x) {
    var re = parser.patterns_[x];
    if (text.match(re)) {
      return text;
    }
  }
  return false;
};

var highlightText = function() {

  // add style to element
  this.style.textDecoration = "line-through";

  // check if the found pattern is in a long paragraph
  var parent_text = $(this.parentNode).text();
  var parent;
  if (parent_text.length > 100){
    this.parentNode.innerHTML = this.parentNode.innerHTML.replace( this.outerHTML,
      "" + this.outerHTML + "" );
    parent = document.getElementsByClassName("offending-text")[0];
  }else{
    parent = this.parentNode;
  }

  // add style to parent element
  parent.style.cssText = 'border: 3;border-style: solid; border-color: #d11212; text-decoration: line-through;';

  // scroll element into view
  // var _ele = this;

  $(document).ready(function(){
    scrollIntoView(parent, true);
  });

  // fade in fade out calling each other for ever
  var fadeOut = function(el) {
    el.style.opacity = 1;

    (function fade() {
      if ((el.style.opacity -= .04) < 0) {
        fadeIn(el);
      } else {
        requestAnimationFrame(fade);
      }
    })();
  };

  var fadeIn = function(el) {
    el.style.opacity = 0;

    (function fade() {
      var val = parseFloat(el.style.opacity);
      if (!((val += .04) > 1)) {
        el.style.opacity = val;
        requestAnimationFrame(fade);
      } else {
        fadeOut(el);
      }
    })();
  };

  // start animation of fade in and fade out
  fadeOut(parent);
};

$(function() {
  var baseUrl = getBaseUrl(location.href);
  const cp = new ContactParser(baseUrl, $(document));
  var offendingNode = parser.getOffendingNode();
  if (offendingNode) {
    highlightText.call(offendingNode);
  }
  if (offendingNode !== null) {
    cp.findMailAddresses(function(mailAddresses) {
      for (var i = 0; i < mailAddresses.length; ++i) {
        console.log(mailAddresses[i]);
      }
    });
  }
});

function getBaseUrl(origUrl) {
  var pathArray = origUrl.split('/');
  var protocol = pathArray[0];
  var host = pathArray[2];
  return protocol + '//' + host;
}
<commit_msg>[FIX] twinkle only offending ele<commit_after>function scrollIntoView (element, alignTop) {

  console.log("Scroll into view");

  var document = element.ownerDocument;
  var origin = element, originRect = origin.getBoundingClientRect();
  var hasScroll = false;
  var documentScroll = document.scrollingElement;

  while (element) {
    if (element == document.body) {
      element = documentScroll;
    } else {
      element = element.parentNode;
    }

    if (element) {
      var hasScrollbar = (!element.clientHeight)?
          false : element.scrollHeight > element.clientHeight;
      if (!hasScrollbar) {
        if (element == documentScroll) {
          element = null;
        }
        continue;
      }
      var rects;
      if (element == documentScroll) {
        rects = {
          left: 0,
          top: 0
        };
      } else {
        rects = element.getBoundingClientRect();
      }

      // check that elementRect is in rects
      var deltaLeft =
          originRect.left -
          (rects.left + (parseInt(element.style.borderLeftWidth, 10) | 0));
      var deltaRight =
          originRect.right -
          (rects.left + element.clientWidth +
           (parseInt(element.style.borderLeftWidth, 10) | 0));
      var deltaTop =
          originRect.top -
          (rects.top + (parseInt(element.style.borderTopWidth, 10) | 0));
      var deltaBottom =
        originRect.bottom -
        (rects.top + element.clientHeight +
         (parseInt(element.style.borderTopWidth, 10) | 0));

      // adjust display depending on deltas
      if (deltaLeft < 0) {
        element.scrollLeft += deltaLeft;
      } else if (deltaRight > 0) {
        element.scrollLeft += deltaRight;
      }

      if (alignTop === true && !hasScroll) {
        element.scrollTop += deltaTop;
      } else if (alignTop === false && !hasScroll) {
        element.scrollTop += deltaBottom;
      } else {
        if (deltaTop < 0) {
          element.scrollTop += deltaTop;
        } else if (deltaBottom > 0) {
          element.scrollTop += deltaBottom;
        }
      }

      if (element == documentScroll) {
        element = null;
      } else {
        // readjust element position after scrolls, and check if vertical scroll
        // has changed. This is required to perform only one alignment
        var nextRect = origin.getBoundingClientRect();
        if (nextRect.top != originRect.top) {
          hasScroll = true;
        }
        originRect = nextRect;
      }
    }
  }

    // put the element into middle of the view
    console.log("QQ");
    document.body.scrollTop -= screen.height/2;

}

var parser = {};
// Return the node containing the DOM path leading to the html object containing
// offending pattern e.g. Taiwan, Province of China.
parser.getOffendingNode = function() {
  return parser.traverse_(document);
};
parser.getOffendingText = function(node) {
  return parser.matchOffending_(parser.getText_(node));
};
// Private methods.
parser.traverse_ = function(node) {
  for (var x = 0; x < node.children.length; ++x) {
    var child = parser.traverse_(node.children[x]);
    if (child) {
      return child;
    }
  }

  if (node.tagName == 'SCRIPT' ||
      node.tagName == 'TITLE') {
    return null;
  }
  var text = parser.getText_(node);
  if (text) {
    var offendingText = parser.matchOffending_(text);
    if (offendingText) {
      console.log('Offending text: ' + offendingText);
      return node;
    }
  }
  return null;
};
parser.getText_ = function(node) {
  var text = node.text;
  if (node.tagName == 'H2') {
    text = node.textContent;
  } else if (node.tagName == 'A') {
    text = node.innerText;
  }
  return text;
};

parser.patterns_ = [
  new RegExp('taiwan\\s*,?\\s*province\\s*of\\s*china', 'i'),
  new RegExp('taiwan\\s*,?\\s*prc', 'i'),
  new RegExp('chinese\\s*,?\\s*taipei', 'i'),
  new RegExp('taiwan\\s*,?\\s*china', 'i'),
  new RegExp('china\\s*,?\\s*taiwan', 'i')
];

parser.matchOffending_ = function(text) {
  for (var x = 0; x < parser.patterns_.length; ++x) {
    var re = parser.patterns_[x];
    if (text.match(re)) {
      return text;
    }
  }
  return false;
};

var highlightText = function(highlightText) {

  // add style to element
  this.style.textDecoration = "line-through";

  // check if the found pattern is in a long paragraph
  var parent_text = $(this.parentNode).text();
  var _ele = this;
  var parent;
  if (parent_text.length > 100){
    this.parentNode.innerHTML = this.parentNode.innerHTML.replace( this.outerHTML,
      "
" + this.outerHTML + "
" );
    parent = document.getElementsByClassName("offending-text")[0];
  }else{
    console.log(this.parentNode);
    parent = this.parentNode;
  }

  // add style to parent element
  parent.style.cssText = 'border: 3;border-style: solid; border-color: #d11212; text-decoration: line-through; display: inline-block;';

  // scroll element into view
  $(document).ready(function(){
    scrollIntoView(parent, true);
  });

  // fade in fade out calling each other for ever
  var fadeOut = function(el) {
    el.style.opacity = 1;

    (function fade() {
      if ((el.style.opacity -= .04) < 0) {
        fadeIn(el);
      } else {
        requestAnimationFrame(fade);
      }
    })();
  };

  var fadeIn = function(el) {
    el.style.opacity = 0;

    (function fade() {
      var val = parseFloat(el.style.opacity);
      if (!((val += .04) > 1)) {
        el.style.opacity = val;
        requestAnimationFrame(fade);
      } else {
        fadeOut(el);
      }
    })();
  };

  // start animation of fade in and fade out
  fadeOut(parent);
};

$(function() {
  var baseUrl = getBaseUrl(location.href);
  var offendingNode = parser.getOffendingNode();
  var offendingText = parser.getOffendingText(offendingNode);
  if (offendingNode) {
    highlightText.call(offendingNode, offendingText);
  }
  if (offendingNode !== null) {
    const cp = new ContactParser(baseUrl, $(document));
    cp.findMailAddresses(function(mailAddresses) {
      for (var i = 0; i < mailAddresses.length; ++i) {
        console.log(mailAddresses[i]);
      }
    });
  }
});

function getBaseUrl(origUrl) {
  var pathArray = origUrl.split('/');
  var protocol = pathArray[0];
  var host = pathArray[2];
  return protocol + '//' + host;
}
<|endoftext|>