<commit_before>/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Stefan Goessner - 2016-20. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
'use strict';

const vscode = require('vscode');

// this method is called when extension is activated ..
exports.activate = function activate(context) {
    let   mdit = null;   // markdown-it object ...

    const path = require('path'),
          fs = require('fs'),
          cfg = (key) => vscode.workspace.getConfiguration('mdmath')[key],
          infoMsg = (msg) => {
                vscode.window.showInformationMessage(`Markdown + Math: ${msg}`);
          },
          errMsg = (msg) => {
                vscode.window.showErrorMessage(`Markdown + Math: ${msg}`);
          },
          asHTML = (doc) => {
                const usrcss = cfg('style');
                return htmlTmpl(mdit.render(doc.getText()), usrcss.length ? usrcss : false);
          },
          clip = () => {
                const doc = vscode.window.activeTextEditor
                         && vscode.window.activeTextEditor.document;

              vscode.env.clipboard.writeText(asHTML(doc))
                    .then(()=>infoMsg('Html copied to clipboard!'),
                          (err)=>errMsg('Html copying to clipboard failed: ' + err.message));
          },
          save = (arg) => {
                try {
                    const doc = arg && arg.uri ? arg : vscode.window.activeTextEditor && vscode.window.activeTextEditor.document;
                    const uri = vscode.window.activeTextEditor.document.uri;
                    if (!doc)
                        errMsg('Saving html failed: invalid editor document!');
                    else if (doc.languageId !== 'markdown')
                        errMsg('Saving html failed: Active document is no markdown source document!');
                    else if (doc.isUntitled)
                        errMsg('Saving html failed: current untitled markdown document needs to be saved once first!');
                    else {
                        fs.writeFileSync(outputLocationOf(uri.fsPath), asHTML(doc), 'utf8');
                        infoMsg(`Html saved to ${outputLocationOf(uri.fsPath)} !`);
                    }
                } catch (err) {
                    errMsg('Saving html failed: ' + err.message);
                }
          },
          outputLocationOf = (fsPath) => {
                const root = vscode.workspace.getWorkspaceFolder(fsPath),
                      parsed = path.parse(fsPath),
                      savePath = cfg('savePath')  // use https://code.visualstudio.com/updates/v1_31#_global-storage-path instead in future !
                                    .replace('${file.name}', parsed.name)
                                    .replace('${file.ext}', parsed.ext),
                      out = savePath.startsWith('/') ? path.resolve(root, `.${savePath}`) : path.resolve(parsed.dir, savePath);

                return path.isAbsolute(out) ? out : path.resolve(parsed.dir, `./${parsed.name}.html`);
          },
          loadMacros = () => {
                try {
                    const macroUrl = cfg('macroFile'),
                          macros = macroUrl.length ? fs.readFileSync(path.resolve(macroUrl),'utf8')
                                                   : JSON.stringify(cfg('macros'))
                    return JSON.parse(macros);
                } catch (err) {
                    errMsg('Loading macros failed: ' + err.message);
                }
          },
          delimiters = JSON.parse(JSON.stringify(cfg('delimiters'))) || 'dollars', // wondering why this ...
          macros = loadMacros();  // ... JSON stuff is necessary ...

    context.subscriptions.push(vscode.commands.registerCommand('extension.clipToHtml', clip));
    context.subscriptions.push(vscode.commands.registerCommand('extension.saveToHtml', save));

    if (cfg('autosave')) {  // Initialize autosave functionality ... if user defined !
        let watching = false;
        const initWatching = () => {
            if (!watching && vscode.window.activeTextEditor) {
                const pattern = new vscode.RelativePattern(path.dirname(vscode.window.activeTextEditor.document.uri.fsPath), '**/*.md'),
                      watcher = vscode.workspace.createFileSystemWatcher(pattern,false,false,true);
                watcher.onDidChange(save);
                watcher.onDidCreate(save);
                watching = true;
            }
        };
        context.subscriptions.push(vscode.window.onDidChangeActiveTextEditor(initWatching));
    }

    return {
        extendMarkdownIt: function(md) {
            const options =  { engine: require('katex'),
                               delimiters };

            if (macros) options.macros = macros;

            return (mdit = md).use(require('markdown-it-texmath'), options);
        }
    }
}
// this method is called when extension is deactivated ..
exports.deactivate = function deactivate() {};

const htmlTmpl = (html,usrcss) => `<!doctype html>

<meta charset="utf-8">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/github-markdown-css/3.0.1/github-markdown.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@9.18.1/lib/index.min.js">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/katex.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/markdown-it-texmath@0.6.5/css/texmath.css">
<link rel="stylesheet" href="https://gitcdn.xyz/repo/goessner/mdmath/master/css/vscode-texmath.css">
${usrcss ? `<link rel="stylesheet" href="${usrcss}">` : ''}

${html}
`.replace(/<img src="vscode-resource:/g,'<img src="');

<commit_msg>Version 2.5<commit_after>/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Stefan Goessner - 2016-20. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
'use strict';

const vscode = require('vscode');

// this method is called when extension is activated ..
exports.activate = function activate(context) {
    let   mdit = null;   // markdown-it object ...

    const path = require('path'),
          fs = require('fs'),
          cfg = (key) => vscode.workspace.getConfiguration('mdmath')[key],
          infoMsg = (msg) => {
                vscode.window.showInformationMessage(`Markdown+Math: ${msg}`);
          },
          errMsg = (msg) => {
                vscode.window.showErrorMessage(`Markdown+Math: ${msg}`);
          },
          asHTML = (doc) => {
                const usrcss = cfg('style');
                return htmlTmpl(mdit.render(doc.getText()), usrcss.length ? usrcss : false);
          },
          clip = () => {
                const doc = vscode.window.activeTextEditor
                         && vscode.window.activeTextEditor.document;

              vscode.env.clipboard.writeText(asHTML(doc))
                    .then(()=>infoMsg('Html copied to clipboard!'),
                          (err)=>errMsg('Html copying to clipboard failed: ' + err.message));
          },
          save = (arg) => {
                try {
                    const doc = arg && arg.uri ? arg : vscode.window.activeTextEditor && vscode.window.activeTextEditor.document;
                    const uri = vscode.window.activeTextEditor.document.uri;
                    if (!doc)
                        errMsg('Saving html failed: invalid editor document!');
                    else if (doc.languageId !== 'markdown')
                        errMsg('Saving html failed: Active document is no markdown source document!');
                    else if (doc.isUntitled)
                        errMsg('Saving html failed: current untitled markdown document needs to be saved once first!');
                    else {
                        fs.writeFileSync(outputLocationOf(uri.fsPath), asHTML(doc), 'utf8');
                        infoMsg(`Html saved to ${outputLocationOf(uri.fsPath)} !`);
                    }
                } catch (err) {
                    errMsg('Saving html failed: ' + err.message);
                }
          },
          outputLocationOf = (fsPath) => {
                const root = vscode.workspace.getWorkspaceFolder(fsPath),
                      parsed = path.parse(fsPath),
                      savePath = cfg('savePath')  // use https://code.visualstudio.com/updates/v1_31#_global-storage-path instead in future !
                                    .replace('${file.name}', parsed.name)
                                    .replace('${file.ext}', parsed.ext),
                      out = savePath.startsWith('/') ? path.resolve(root, `.${savePath}`) : path.resolve(parsed.dir, savePath);

                return path.isAbsolute(out) ? out : path.resolve(parsed.dir, `./${parsed.name}.html`);
          },
          loadMacros = () => {
                try {
                    const macroUrl = cfg('macroFile'),
                          macros = macroUrl.length ? fs.readFileSync(path.resolve(macroUrl),'utf8')
                                                   : JSON.stringify(cfg('macros'))
                    return JSON.parse(macros);
                } catch (err) {
                    errMsg('Loading macros failed: ' + err.message);
                }
          },
          delimiters = JSON.parse(JSON.stringify(cfg('delimiters'))) || 'dollars', // wondering why this ...
          macros = loadMacros();  // ... JSON stuff is necessary ...

    context.subscriptions.push(vscode.commands.registerCommand('extension.clipToHtml', clip));
    context.subscriptions.push(vscode.commands.registerCommand('extension.saveToHtml', save));

    if (cfg('autosave')) {  // Initialize autosave functionality ... if user defined !
        let watching = false;
        const initWatching = () => {
            if (!watching && vscode.window.activeTextEditor) {
                const pattern = new vscode.RelativePattern(path.dirname(vscode.window.activeTextEditor.document.uri.fsPath), '**/*.md'),
                      watcher = vscode.workspace.createFileSystemWatcher(pattern,false,false,true);
                watcher.onDidChange(save);
                watcher.onDidCreate(save);
                watching = true;
            }
        };
        context.subscriptions.push(vscode.window.onDidChangeActiveTextEditor(initWatching));
    }

    return {
        extendMarkdownIt: function(md) {
            const options =  { engine: require('katex'),
                               delimiters };

            if (macros) options.macros = macros;

            return (mdit = md).use(require('markdown-it-texmath'), options);
        }
    }
}
// this method is called when extension is deactivated ..
exports.deactivate = function deactivate() {};

const htmlTmpl = (html,usrcss) => `<!doctype html>

<meta charset="utf-8">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/github-markdown-css/3.0.1/github-markdown.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@9.18.1/lib/index.min.js">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/katex.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/markdown-it-texmath@0.6.5/css/texmath.css">
<link rel="stylesheet" href="https://gitcdn.xyz/repo/goessner/mdmath/master/css/vscode-texmath.css">
${usrcss ? `<link rel="stylesheet" href="${usrcss}">` : ''}

${html}
`.replace(/<img src="vscode-resource:/g,'<img src="');

<|endoftext|>


<commit_before>'use strict';
var path     = require('path'),
    root     = path.resolve(path.join(__dirname, '../../')),
    jade     = require('jade'),
    coffee   = require(root + '/public/js/vendor/coffee-script').CoffeeScript,
    jsx      = require(root + '/public/js/vendor/JSXTransformer'),
    markdown = require(root + '/public/js/vendor/markdown'),
    less     = require('less'),
    stylus   = require('stylus'),
    RSVP     = require('rsvp'),
    exec     = require('child_process').exec;

var processors = module.exports = {
  mime: {
    'js': 'application/javascript',
    'css': 'text/css',
    'html': 'text/html',
    'md': 'text/x-markdown',
    'mdown': 'text/x-markdown',
    'markdown': 'text/x-markdown',
    'coffee': 'application/javascript',
    'coffeescript': 'application/javascript',
    'jsx': 'application/javascript',
    'json': 'application/json',
    'ts': 'application/javascript',
    'styl': 'text/css',
    'less': 'text/css',
    'sass': 'text/css',
    'scss': 'text/css',
    '_default': 'text/plain'
  },

  aliases: {
    'md': 'markdown',
    'mdown': 'markdown',
    'coffee': 'coffeescript',
    'pde': 'processing',
    'ts': 'typescript',
    'styl': 'stylus',
  },

  lookup: {
    'markdown': 'html',
    'jade': 'html',
    'coffeescript': 'javascript',
    'jsx': 'javascript',
    'pde': 'javascript',
    'ts': 'javascript',
    'stylus': 'css',
    'less': 'css',
    'sass': 'css',
    'scss': 'css',
  },

  run: function (language, source) {
    return new RSVP.Promise(function (resolve, reject) {
      console.log('node ' + __dirname);
      var child = exec('node', [__dirname], {
        // timeout: 2000
      });
      var output = '';

      child.stderr.on('data', function (data) {
        console.error(language + ' processor errors');
        console.error(data);
      });

      child.stdout.on('data', function (message) {
        console.log('output', message);
        output += message;
      });

      child.on('exit', function () {
        console.log('exit');
        resolve(output);
      });

      child.stdin.write(JSON.stringify({ language: language, source: source }) + '\n');
    });
  },

  coffeescript: function (source) {
    return new RSVP.Promise(function (resolve, reject) {
      try {
        resolve(coffee.compile(source, {
          bare: true
        }));
      } catch (e) {
        console.error(e.message);
        reject(e);
      }
    });
  },
  jsx: function(source) {
    return new RSVP.Promise(function (resolve, reject) {
      try {
        resolve(jsx.transform(source).code);
      } catch (e) {
        console.error(e.message);
        reject(e);
      }
    });
  },
  jade: function (source) {
    return new RSVP.Promise(function (resolve, reject) {
      try {
        resolve(jade.compile(source, { pretty: true })());
      } catch (e) {
        reject(e);
      }
    });
  },
  markdown: function (source) {
    return new RSVP.Promise(function (resolve, reject) {
      try {
        resolve(markdown.toHTML(source));
      } catch (e) {
        reject(e);
      }
    });
  },
  less: function (source) {
    return new RSVP.Promise(function (resolve, reject) {
      try {
        less.Parser().parse(source, function (err, result) {
          if (err) {
            console.error(err);
            return reject(err);
          }
          resolve(result.toCSS().trim());
        });
      } catch (e) {
        reject(e);
      }
    });
  },
  stylus: function (source) {
    return new RSVP.Promise(function (resolve, reject) {
      try {
        stylus(source).render(function (err, result) {
          if (err) {
            console.error(err);
            return reject(err);
          }
          resolve(result.trim());
        });
      } catch (e) {
        reject(e);
      }
    });
  }
};

if (!module.parent) {
  console.log('running');
  process.stdin.setEncoding('utf8');

  console.log('running child');
  var message = '';
  process.stdin.on('readable', function(event) {
    var chunk = process.stdin.read();
    if (chunk !== null) {
      message += chunk;
    }
  }).on('end', function () {
    console.log('got ', message);
  });

    // console.log('got message', event);
    // if (event.language && typeof processors[event.language] === 'function') {
      // processors[event.language](event.source).then(function (output) {
      //   process.send(output);
      // }, function (error) {
      //   console.error(error);
      // }).then(function () {
      //   process.exit(0);
      // });
    // }
  // });
}
<commit_msg>Working terminate and fork<commit_after>'use strict';
var path     = require('path'),
    root     = path.resolve(path.join(__dirname, '../../')),
    jade     = require('jade'),
    coffee   = require(root + '/public/js/vendor/coffee-script').CoffeeScript,
    jsx      = require(root + '/public/js/vendor/JSXTransformer'),
    markdown = require(root + '/public/js/vendor/markdown'),
    less     = require('less'),
    stylus   = require('stylus'),
    RSVP     = require('rsvp'),
    fork     = require('child_process').fork;

var processors = module.exports = {
  mime: {
    'js': 'application/javascript',
    'css': 'text/css',
    'html': 'text/html',
    'md': 'text/x-markdown',
    'mdown': 'text/x-markdown',
    'markdown': 'text/x-markdown',
    'coffee': 'application/javascript',
    'coffeescript': 'application/javascript',
    'jsx': 'application/javascript',
    'json': 'application/json',
    'ts': 'application/javascript',
    'styl': 'text/css',
    'less': 'text/css',
    'sass': 'text/css',
    'scss': 'text/css',
    '_default': 'text/plain'
  },

  aliases: {
    'md': 'markdown',
    'mdown': 'markdown',
    'coffee': 'coffeescript',
    'pde': 'processing',
    'ts': 'typescript',
    'styl': 'stylus',
  },

  lookup: {
    'markdown': 'html',
    'jade': 'html',
    'coffeescript': 'javascript',
    'jsx': 'javascript',
    'pde': 'javascript',
    'ts': 'javascript',
    'stylus': 'css',
    'less': 'css',
    'sass': 'css',
    'scss': 'css',
  },

  run: function (language, source) {
    return new RSVP.Promise(function (resolve, reject) {
      var child = fork(__dirname);
      var output = '';

      var timeout = setTimeout(function () {
        console.error(language + ' processor timeout');
        child.kill();
      }, 1000);

      child.on('stderr', function (data) {
        console.error(language + ' processor errors');
        console.error(data);
      });

      child.on('message', function (message) {
        output += message;
      });

      child.on('exit', function () {
        clearTimeout(timeout);
        resolve(output);
      });

      child.send({ language: language, source: source });
    });
  },

  coffeescript: function (source) {
    return new RSVP.Promise(function (resolve, reject) {
      try {
        resolve(coffee.compile(source, {
          bare: true
        }));
      } catch (e) {
        console.error(e.message);
        reject(e);
      }
    });
  },
  jsx: function(source) {
    return new RSVP.Promise(function (resolve, reject) {
      try {
        resolve(jsx.transform(source).code);
      } catch (e) {
        console.error(e.message);
        reject(e);
      }
    });
  },
  jade: function (source) {
    return new RSVP.Promise(function (resolve, reject) {
      try {
        resolve(jade.compile(source, { pretty: true })());
      } catch (e) {
        reject(e);
      }
    });
  },
  markdown: function (source) {
    return new RSVP.Promise(function (resolve, reject) {
      try {
        resolve(markdown.toHTML(source));
      } catch (e) {
        reject(e);
      }
    });
  },
  less: function (source) {
    return new RSVP.Promise(function (resolve, reject) {
      try {
        less.Parser().parse(source, function (err, result) {
          if (err) {
            console.error(err);
            return reject(err);
          }
          resolve(result.toCSS().trim());
        });
      } catch (e) {
        reject(e);
      }
    });
  },
  stylus: function (source) {
    return new RSVP.Promise(function (resolve, reject) {
      try {
        stylus(source).render(function (err, result) {
          if (err) {
            console.error(err);
            return reject(err);
          }
          resolve(result.trim());
        });
      } catch (e) {
        reject(e);
      }
    });
  }
};

if (!module.parent) {
  process.stdin.setEncoding('utf8');
  process.on('message', function (event) {
    if (event.language && typeof processors[event.language] === 'function') {
      processors[event.language](event.source).then(function (output) {
        process.send(output);
      }, function (error) {
        console.error(error);
      }).then(function () {
        process.exit(0);
      });
    }
  });
}
<|endoftext|>


<commit_before>module.exports = function(gameServer, split) {
  var c = split[1];
if (c == 'power') {
 if (gameServer.auon == 1) {
   gameServer.auon = 0;
   console.log("[Console] Turned off plugin");

 } else {
   gameServer.auon = 1;
   console.log("[Console] Turned on plugin");
 }

}
if (gameServer.auon != 1) {
  console.log("[Console] Turn on the plugin first")
  return;
}
if (c == 'record') {
  fs.writeFileSync('accounts.json',JSON.stringify(gameServer.account, null, 2));
  console.log("[Console] Recorded accounts");
}

}
<commit_msg>Update command.js<commit_after>module.exports = function(gameServer, split) {
  var c = split[1];
if (c == 'power') {
 if (gameServer.auon == 1) {
   gameServer.auon = 0;
   console.log("[Console] Turned off plugin");

 } else {
   gameServer.auon = 1;
   console.log("[Console] Turned on plugin");
 }

}
if (gameServer.auon != 1) {
  console.log("[Console] Turn on the plugin first")
  return;
}
if (c == 'record') {
  fs.writeFileSync('accounts.json',JSON.stringify(gameServer.account, null, 2));
  console.log("[Console] Recorded accounts");
} else if (c == 'register') {
  if (!split[2]) {

    console.log("[Console] Please specify a username")
    return;
  }
  if (!split[2]) {
     console.log("[Console] Please specify a password")
     return;
  }
  var p = {
    username: split[1],
    pass: split[2],

  }
  gameServer.account.push(p);
  console.log("[Console] Registered account");

} else if (c == 'remove') {
  if (!split[2]) {

    console.log("[Console] Please specify a username")
    return;
  }
  var acc = 0;
  for (var i in gameServer.account) {
    var account = gameServer.account[i];
    if (account.username == split[2]) {
      acc = acount;
      break;
    }
  }
  var index = gameServer.account.indexOf(acc);
    if (index != -1) {
      gameServer.account.splice(index, 1);
      console.log("[Console] Removed " + acc.username);
    } else {
      // todo do we really care?
      console.log("[Console] No such account exsists!");
    }
} else if (c == 'edit') {
  if (!split[2]) {

    console.log("[Console] Please specify a username")
    return;
  }
  if (!split[3]) {

    console.log("[Console] Please specify a parameter")
    return;
  }
  if (!split[4]) {

    console.log("[Console] Please specify the change")
    return;
  }
   for (var i in gameServer.account) {
    if (gameServer.account[i].username == split[2]) {
      var account = gameServer.account[i]
      account[split[3]] = split[4];
      console.log("[Console] Set the " + split[3] + " par to " + split[4]);
      break;
    }

   }

} else {

  console.log("[Console] Please specify a valid command!, register, remove, edit, power");
}

};
<|endoftext|>


<commit_before>import React from 'react';

import './styles.css';

export default class About extends React.Component {
  render() {
    return (

Um verkefnið

Um vefinn

Á þessum vef finnur þú upplýsingar og tölfræði um þingmenn og þingflokka fyrir kjörtímabilið 2013-2016.

Markmið vefsins er að sækja gögn sem finna má á vef Alþingis, vinna úr þeim og setja fram á skemmtilegan, fræðandi og helst af öllu hlutlausan máta.

Hvaðan koma gögnin?

Öll gögn eru sótt af vef Alþingis og skiptast þau niður í tvo meginflokka: atkvæðaskrá og ræður eftir þingum.

Gögnin eru sótt sjálfkrafa, hver einasta undirsíða fyrir alla þingmenn er skoðuð og gögnum breytt yfir á form sem þægilegt er fyrir tölvu að vinna úr þeim.

Því næst er byrjað að vinna úr gögnunum, þau flokkuð og skoðuð fyrir hvern þingmann. Eftir að hafa unnið úr þeim fyrir hvern þingmann eru upplýsingum safnað saman til þess að fá gögn fyrir þingflokkana.

Verkefnið

Þetta er verkefni eftir Bæring Gunnar Steinþórsson.

Sérstakar þakkir fá samstarfsfélagar mínir hjá Aranja;
 Davíð Bachmann Jóhannesson, Sebastian Helms og Ægir Giraldo Þorsteinsson fyrir hjálp við útfærslu og hönnun á vefnum.

Ábendingar og hugmyndir eru vel þegnar á thingmenn@aranja.com.

    );
  }
}
<commit_msg>Frontend: link to all mps from althingi.is in about<commit_after>import React from 'react';

import './styles.css';

export default class About extends React.Component {
  render() {
    return (

Um verkefnið

Um vefinn

Á þessum vef finnur þú upplýsingar og tölfræði um þingmenn og þingflokka fyrir kjörtímabilið 2013-2016.

Markmið vefsins er að sækja gögn sem finna má á vef Alþingis, vinna úr þeim og setja fram á skemmtilegan, fræðandi og helst af öllu hlutlausan máta.

Hvaðan koma gögnin?

Öll gögn eru sótt af vef Alþingis og skiptast þau niður í tvo meginflokka: atkvæðaskrá og ræður eftir þingum.

Gögnin eru sótt sjálfkrafa, hver einasta undirsíða fyrir alla þingmenn er skoðuð og gögnum breytt yfir á form sem þægilegt er fyrir tölvu að vinna úr þeim.

Því næst er byrjað að vinna úr gögnunum, þau flokkuð og skoðuð fyrir hvern þingmann. Eftir að hafa unnið úr þeim fyrir hvern þingmann eru upplýsingum safnað saman til þess að fá gögn fyrir þingflokkana.

Verkefnið

Þetta er verkefni eftir Bæring Gunnar Steinþórsson.

Sérstakar þakkir fá samstarfsfélagar mínir hjá Aranja;
 Davíð Bachmann Jóhannesson, Sebastian Helms og Ægir Giraldo Þorsteinsson fyrir hjálp við útfærslu og hönnun á vefnum.

Ábendingar og hugmyndir eru vel þegnar á thingmenn@aranja.com.

    );
  }
}
<|endoftext|>


<commit_before>"use strict";

function Grafici(config) {
	this.config = config;
	this.targetTables = [];
	this.graphs = [];

	this.init = function(config) {
		this.targetTables = document.querySelectorAll('.' + config.tableClass);

		this.buildGraphs(this.targetTables);
	};

	this.buildGraphs = function(targetTables) {
		var results;

		for (var i = 0; i < targetTables.length; i++) {
			var rows = targetTables[i].getElementsByTagName('tr');
			var header = rows[0];

			var dataSet = {
				id: i,
				title: targetTables[i].getElementsByTagName('caption')[0].textContent,
				xAxisLabel: header.cells[0].textContent,
				yAxisLabel: header.cells[1].textContent,
				xAxis: [],
				yAxis: [],
				graphType: this.getGraphType(targetTables[i])
			};

			//Get X axis data
			for (var xIndex = 1; xIndex < rows.length; xIndex++) {
				dataSet.xAxis.push(rows[xIndex].cells[0].textContent);
			}

			//Get Y axis data
			for (var yIndex = 1; yIndex < rows.length; yIndex++) {
				dataSet.yAxis.push(rows[yIndex].cells[1].textContent);
			}

			//Get number of rows and columns.
			//TODO: allow for a custom number of rows/columns based on
			//user specification.
			dataSet.numRows = dataSet.xAxis.length;
			dataSet.numColumns = dataSet.yAxis.length;

			dataSet.max = this.getMaxOfArray(dataSet.yAxis);
			dataSet.min = this.getMinOfArray(dataSet.yAxis);

			this.graphs.push(dataSet)
		}

		this.drawGraphs(this.graphs);
	};

	this.getGraphType = function(graphElem) {
		var classNames = graphElem.getAttribute('class');
		var graphType = {};

		if (classNames.indexOf('grafici-bar-graph') != -1) {
			graphType.barGraph = true;
		}

		if (classNames.indexOf('grafici-line-graph') != -1) {
			graphType.lineGraph = true;
		}

		if (graphType == {}) {
			graphType.lineGraph = true;
		}

		return graphType;
	};

	this.drawGraphs = function(graphs) {

		for (var graphIndex in graphs) {
			var currentGraph = graphs[graphIndex];

			//Fit graph within alotted space. Pads top and bottom by 5%.
			var paddingFactor = (((currentGraph.numRows + 1) / currentGraph.numRows) + 1) / 2;
			paddingFactor = ((paddingFactor - 1) / 2) + 1;

			//Get the top and bottom of the chart with padding space added in
			var graphTop = Math.floor(this.config.graphSize.height-(this.config.graphSize.height*paddingFactor));
			var graphBottom = Math.floor(this.config.graphSize.height * (paddingFactor * paddingFactor));

			//Hide taret tables, leaving them visible for a screenreader
			this.targetTables[graphIndex].style.cssText = "opacity:0;position:absolute !important;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);";

			//Create primary graph svg string
			var figureOutput = '
';
			var graphOutput = '<svg class="grafici-graph__svg" viewBox = "0 ' + graphTop + ' ' + this.config.graphSize.width + ' ' + graphBottom + '" version = "1.1">';

			//Create x axis labels svg string
			var outputXAxis = '<svg class="grafici-graph__xAxis" viewBox = "0 0 ' + this.config.graphSize.width + ' ' + this.config.graphSize.xAxisHeight + '" version = "1.1">';

			if (this.config.gridLines) {
				//draw baseline grid's rows
				for (var i = graphTop; i < graphBottom / this.config.gridLines.size; i++) {
					graphOutput += this.drawLine(0, i * this.config.gridLines.size, this.config.graphSize.width, i * this.config.gridLines.size, this.config.gridLines.stroke, this.config.gridLines.strokeWidth);
				}

				//draw baseline grid's columns
				for (var i = 0; i < this.config.graphSize.width / this.config.gridLines.size; i++) {
					graphOutput += this.drawLine(i * this.config.gridLines.size, graphTop, i * this.config.gridLines.size, graphBottom, this.config.gridLines.stroke, this.config.gridLines.strokeWidth);
				}
			}

			//draw data labels and points
			for (var j = 0; j < currentGraph.numRows; j++) {
				var columnLeft = ((j+1) / (currentGraph.numColumns + 1)) * this.config.graphSize.width;
				var dataHeight = this.config.graphSize.height + (((currentGraph.yAxis[j] - currentGraph.min) / (currentGraph.max - currentGraph.min)) * -this.config.graphSize.height);
				var nextColumnLeft = ((j+2) / (currentGraph.numColumns + 1)) * this.config.graphSize.width || false;
				var nextDataHeight = parseInt(this.config.graphSize.height) + (((currentGraph.yAxis[j+1] - currentGraph.min) / (currentGraph.max - currentGraph.min)) * -this.config.graphSize.height);

				if (currentGraph.graphType.lineGraph) {
					//lines between datapoints
					if (j + 1 < currentGraph.numRows) {
						graphOutput += this.drawLine(columnLeft, dataHeight, nextColumnLeft, nextDataHeight, this.config.graphLines.stroke, this.config.graphLines.strokeWidth);
					}
					//datapoints
					graphOutput += this.drawCircle(columnLeft, dataHeight, this.config.graphPoints.radius);
				}

				if (currentGraph.graphType.barGraph) {
					//datapoints
					graphOutput += this.drawLine(columnLeft, graphBottom, columnLeft, dataHeight, this.config.barGraphLines.stroke, this.config.barGraphLines.strokeWidth);
				}

				//datalabels
				graphOutput += this.drawText(columnLeft, dataHeight, 3, 1, 'start', 'black', 4, currentGraph.yAxis[j], 'grafici-data-label');

				//X axis datalabels
				outputXAxis += this.drawText(columnLeft, this.config.graphSize.xAxisHeight, 0, this.config.graphSize.xAxisHeight/-2, 'middle', 'black', 3, currentGraph.xAxis[j], 'grafici-x-label');
			}

			console.log(this.config.gridLines.size * this.config.graphSize.yAxisLabelFrequency);
			//output Y axis datalabels
			for (var k = 0; k < (graphBottom / (this.config.gridLines.size * this.config.graphSize.yAxisLabelFrequency)); k++) {
				//Y axis datalabels
				var labelHeight = k * 3 * this.config.graphSize.yAxisLabelFrequency;

				var labelText = (((currentGraph.max - currentGraph.min) / ((-graphBottom-graphTop) / labelHeight)) + currentGraph.min) + (currentGraph.max-currentGraph.min-graphTop) + graphTop;

				labelText = Math.round(labelText * 100) / 100;

				graphOutput += this.drawText(0, labelHeight, 0.5, 1, 'start', 'black', 3, labelText, 'grafici-y-label');
			}

			outputXAxis += '</svg>';
			graphOutput += '</svg>';

			figureOutput += graphOutput + outputXAxis + '
' + currentGraph.title + '

';

			this.targetTables[graphIndex].insertAdjacentHTML('afterend', figureOutput);

			document.getElementById(this.config.outputID + '-' + currentGraph.id).querySelector('.grafici-graph__svg').style.cssText = "border:" + this.config.graphBorder.width + " solid " + this.config.graphBorder.color + ";";
		};

	};

	this.drawLine = function(x1, y1, x2, y2, strokeColor, strokeWidth) {
		var line = '<line x1="' + x1 + '" y1="' + y1 + '" x2="' + x2 + '" y2="' + y2 + '" stroke="' + strokeColor + '" stroke-width = "' + strokeWidth + '"/>';

		return line;
	};

	this.drawText = function(x, y, dx, dy, textAnchor, textColor, fontSize, textString, className) {
		var text = '<text class="' + className + '" x="' + x + '" y="' + y + '" dx="' + dx + '" dy="' + dy + '" text-anchor="' + textAnchor + '" fill="' + textColor + '" font-size="' + fontSize + '">';

		text += textString.toString() + '</text>';

		return text;
	};

	this.drawCircle = function(cx, cy, r) {
		var circle = '<circle cx="' + cx + '" cy="' + cy + '" r="' + r + '" fill="' + this.config.graphPoints.color + '" stroke="' + this.config.graphPoints.stroke + '" stroke-width="' + this.config.graphPoints.strokeWidth + '" />';

		return circle;
	};

	//Utility functions
	this.getMaxOfArray = function(numArray) {
  	return Math.max.apply(null, numArray);
	};

	this.getMinOfArray = function(numArray) {
  	return Math.min.apply(null, numArray);
	};

	this.init(this.config);
}<commit_msg>Removing unneeded console.logs<commit_after>"use strict";

function Grafici(config) {
  this.config = config;
  this.targetTables = [];
  this.graphs = [];

  this.init = function(config) {
    this.targetTables = document.querySelectorAll('.' + config.tableClass);

    this.buildGraphs(this.targetTables);
  };

  this.buildGraphs = function(targetTables) {
    var results;

    for (var i = 0; i < targetTables.length; i++) {
      var rows = targetTables[i].getElementsByTagName('tr');
      var header = rows[0];

      var dataSet = {
        id: i,
        title: targetTables[i].getElementsByTagName('caption')[0].textContent,
        xAxisLabel: header.cells[0].textContent,
        yAxisLabel: header.cells[1].textContent,
        xAxis: [],
        yAxis: [],
        graphType: this.getGraphType(targetTables[i])
      };

      //Get X axis data
      for (var xIndex = 1; xIndex < rows.length; xIndex++) {
        dataSet.xAxis.push(rows[xIndex].cells[0].textContent);
      }

      //Get Y axis data
      for (var yIndex = 1; yIndex < rows.length; yIndex++) {
        dataSet.yAxis.push(rows[yIndex].cells[1].textContent);
      }

      //Get number of rows and columns.
      //TODO: allow for a custom number of rows/columns based on
      //user specification.
      dataSet.numRows = dataSet.xAxis.length;
      dataSet.numColumns = dataSet.yAxis.length;

      dataSet.max = this.getMaxOfArray(dataSet.yAxis);
      dataSet.min = this.getMinOfArray(dataSet.yAxis);

      this.graphs.push(dataSet)
    }

    this.drawGraphs(this.graphs);
  };

  this.getGraphType = function(graphElem) {
    var classNames = graphElem.getAttribute('class');
    var graphType = {};

    if (classNames.indexOf('grafici-bar-graph') != -1) {
      graphType.barGraph = true;
    }

    if (classNames.indexOf('grafici-line-graph') != -1) {
      graphType.lineGraph = true;
    }

    if (graphType == {}) {
      graphType.lineGraph = true;
    }

    return graphType;
  };

  this.drawGraphs = function(graphs) {

    for (var graphIndex in graphs) {
      var currentGraph = graphs[graphIndex];

      //Fit graph within alotted space. Pads top and bottom by 5%.
      var paddingFactor = (((currentGraph.numRows + 1) / currentGraph.numRows) + 1) / 2;
      paddingFactor = ((paddingFactor - 1) / 2) + 1;

      //Get the top and bottom of the chart with padding space added in
      var graphTop = Math.floor(this.config.graphSize.height-(this.config.graphSize.height*paddingFactor));
      var graphBottom = Math.floor(this.config.graphSize.height * (paddingFactor * paddingFactor));

      //Hide taret tables, leaving them visible for a screenreader
      this.targetTables[graphIndex].style.cssText = "opacity:0;position:absolute !important;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);";

      //Create primary graph svg string
      var figureOutput = '
';
      var graphOutput = '<svg class="grafici-graph__svg" viewBox = "0 ' + graphTop + ' ' + this.config.graphSize.width + ' ' + graphBottom + '" version = "1.1">';

      //Create x axis labels svg string
      var outputXAxis = '<svg class="grafici-graph__xAxis" viewBox = "0 0 ' + this.config.graphSize.width + ' ' + this.config.graphSize.xAxisHeight + '" version = "1.1">';

      if (this.config.gridLines) {
        //draw baseline grid's rows
        for (var i = graphTop; i < graphBottom / this.config.gridLines.size; i++) {
          graphOutput += this.drawLine(0, i * this.config.gridLines.size, this.config.graphSize.width, i * this.config.gridLines.size, this.config.gridLines.stroke, this.config.gridLines.strokeWidth);
        }

        //draw baseline grid's columns
        for (var i = 0; i < this.config.graphSize.width / this.config.gridLines.size; i++) {
          graphOutput += this.drawLine(i * this.config.gridLines.size, graphTop, i * this.config.gridLines.size, graphBottom, this.config.gridLines.stroke, this.config.gridLines.strokeWidth);
        }
      }

      //draw data labels and points
      for (var j = 0; j < currentGraph.numRows; j++) {
        var columnLeft = ((j+1) / (currentGraph.numColumns + 1)) * this.config.graphSize.width;
        var dataHeight = this.config.graphSize.height + (((currentGraph.yAxis[j] - currentGraph.min) / (currentGraph.max - currentGraph.min)) * -this.config.graphSize.height);
        var nextColumnLeft = ((j+2) / (currentGraph.numColumns + 1)) * this.config.graphSize.width || false;
        var nextDataHeight = parseInt(this.config.graphSize.height) + (((currentGraph.yAxis[j+1] - currentGraph.min) / (currentGraph.max - currentGraph.min)) * -this.config.graphSize.height);

        if (currentGraph.graphType.lineGraph) {
          //lines between datapoints
          if (j + 1 < currentGraph.numRows) {
            graphOutput += this.drawLine(columnLeft, dataHeight, nextColumnLeft, nextDataHeight, this.config.graphLines.stroke, this.config.graphLines.strokeWidth);
          }
          //datapoints
          graphOutput += this.drawCircle(columnLeft, dataHeight, this.config.graphPoints.radius);
        }

        if (currentGraph.graphType.barGraph) {
          //datapoints
          graphOutput += this.drawLine(columnLeft, graphBottom, columnLeft, dataHeight, this.config.barGraphLines.stroke, this.config.barGraphLines.strokeWidth);
        }

        //datalabels
        graphOutput += this.drawText(columnLeft, dataHeight, 3, 1, 'start', 'black', 4, currentGraph.yAxis[j], 'grafici-data-label');

        //X axis datalabels
        outputXAxis += this.drawText(columnLeft, this.config.graphSize.xAxisHeight, 0, this.config.graphSize.xAxisHeight/-2, 'middle', 'black', 3, currentGraph.xAxis[j], 'grafici-x-label');
      }

      //output Y axis datalabels
      for (var k = 0; k < (graphBottom / (this.config.gridLines.size * this.config.graphSize.yAxisLabelFrequency)); k++) {
        //Y axis datalabels
        var labelHeight = k * 3 * this.config.graphSize.yAxisLabelFrequency;

        var labelText = (((currentGraph.max - currentGraph.min) / ((-graphBottom-graphTop) / labelHeight)) + currentGraph.min) + (currentGraph.max-currentGraph.min-graphTop) + graphTop;

        labelText = Math.round(labelText * 100) / 100;

        graphOutput += this.drawText(0, labelHeight, 0.5, 1, 'start', 'black', 3, labelText, 'grafici-y-label');
      }

      outputXAxis += '</svg>';
      graphOutput += '</svg>';

      figureOutput += graphOutput + outputXAxis + '
' + currentGraph.title + '

';

      this.targetTables[graphIndex].insertAdjacentHTML('afterend', figureOutput);

      document.getElementById(this.config.outputID + '-' + currentGraph.id).querySelector('.grafici-graph__svg').style.cssText = "border:" + this.config.graphBorder.width + " solid " + this.config.graphBorder.color + ";";
    };

  };

  this.drawLine = function(x1, y1, x2, y2, strokeColor, strokeWidth) {
    var line = '<line x1="' + x1 + '" y1="' + y1 + '" x2="' + x2 + '" y2="' + y2 + '" stroke="' + strokeColor + '" stroke-width = "' + strokeWidth + '"/>';

    return line;
  };

  this.drawText = function(x, y, dx, dy, textAnchor, textColor, fontSize, textString, className) {
    var text = '<text class="' + className + '" x="' + x + '" y="' + y + '" dx="' + dx + '" dy="' + dy + '" text-anchor="' + textAnchor + '" fill="' + textColor + '" font-size="' + fontSize + '">';

    text += textString.toString() + '</text>';

    return text;
  };

  this.drawCircle = function(cx, cy, r) {
    var circle = '<circle cx="' + cx + '" cy="' + cy + '" r="' + r + '" fill="' + this.config.graphPoints.color + '" stroke="' + this.config.graphPoints.stroke + '" stroke-width="' + this.config.graphPoints.strokeWidth + '" />';

    return circle;
  };

  //Utility functions
  this.getMaxOfArray = function(numArray) {
    return Math.max.apply(null, numArray);
  };

  this.getMinOfArray = function(numArray) {
    return Math.min.apply(null, numArray);
  };

  this.init(this.config);
}<|endoftext|>