<commit_before>import syllable from 'syllable';
import _ from 'lodash';
import wordnet from 'wordnet';
var $ = require('jquery-deferred');
import stopwords from './data/stopwords.js';
import descriptors from './data/descriptors.js';
import cusseth from './data/cusseth.js';
import nouns from './data/nouns.js';
import thesaurus from './data/thesaurus.js';

let adjectives = descriptors.map(word => [word, syllable(word)]);
let curses = cusseth.map(word => [word, syllable(word)]);

const HAIKU_LENGTH = 17;
const separator = '//';
const FOUL = false;

// Chrys' Domain
function addModifier(phrase, length, mod) {
  let tokens = phrase.split(/\W/);
  let nounList = tokens.map(word => _.contains(nouns, word));
  for (var i in nounList) {
    if (nounList[i]) {
      tokens.splice(i, 0, mod);
      return tokens.join(' ');
    }
  }

  return mod + ' ' + phrase;
}

export function addExpletive(phrase, length) {
  var curse = _.sample(curses.filter(tuple => tuple[1] === length));
  if (!curse) {
    return addExpletive(addExpletive(phrase, length - 1), 1);
  }

  return addModifier(phrase, length, curse[0]);
}

export function addAdjective(phrase, length) {
  var adj = _.sample(adjectives.filter(tuple => tuple[1] === length));
  if (!adj) {
    return addAdjective(addAdjective(phrase, length - 1), 1);
  }

  return addModifier(phrase, length, adj[0]);
}

export function removeWords(phrase, length) {
  console.log(phrase, length);
  let tokens = phrase.split(/\W/);
  let newTokens = [];
  tokens.forEach(function(token) {
    if (length && _.contains(stopwords, token)) {
      length -= syllable(token);
    } else {
      newTokens.push(token);
    }
  });

  return newTokens.join(' ');
}

function addWords(phrase, length) {
  if (FOUL) {
    return addExpletive(phrase, length);
  } else {
    return addAdjective(phrase, length);
  }
}

// Nicole WUZ HERE
export function shortenWord(word, adjustment) {
  let possibleNewWord = [];
  let theNewWord;
  let newWordSyllables;
  let adjustedList;
  let otheradjustednotasgoodList;
  let currentWordSyllables = syllable(word);

  adjustment = -adjustment;

  let list = []

  var response = possibleSynonymArray(word);

  if (!_.isEmpty(response)) {
    for (let x=0; x<response.length; x++) {
      list[x] = [response[x], syllable(response[x])]
    }

    adjustedList = list.filter(synonym => synonym[1] - currentWordSyllables === adjustment);

    if (!_.isEmpty(adjustedList)) {
      return adjustedList[0][0];
    }

    else {
      otheradjustednotasgoodList = list.filter(synonym => (synonym[1] - currentWordSyllables > adjustment) && (synonym[1] < currentWordSyllables)).sort(function(a, b) {return a[1]-b[1]});
    }

    if (!_.isEmpty(otheradjustednotasgoodList)) {
      return otheradjustednotasgoodList[0][0]
    } else {
      return word;
    }
  } else {
    return word;
  }

}

function possibleSynonymArray(word) {
  if (thesaurus[word]) {
    return thesaurus[word];
  }
}

function possibleSynonymArrayAsync(word) {
  var promise = $.Deferred();

  var possibleNewWords = [];
  wordnet.lookup(word, function(err, definitions) {
    if (definitions) {
      definitions.forEach(function(definition) {
        var words = definition.meta.words;
        words.forEach(function(word) {
          if (!_.includes(possibleNewWords, word.word)) {
            possibleNewWords.push(word.word);
          }
        });
      });
    }
    promise.resolve(possibleNewWords);
  });
  return promise;
}

export function expandWord(word, adjustment) {
  let possibleNewWord = [];
  let theNewWord;
  let newWordSyllables;
  let adjustedList;
  let otheradjustednotasgoodList;
  let currentWordSyllables = syllable(word);
  let list = []

  var response = possibleSynonymArray(word);

  if (!_.isEmpty(response)){
    for (let x=0; x<response.length; x++) {
      list[x] = [response[x], syllable(response[x])]
    }

    adjustedList = list.filter(synonym => synonym[1] - currentWordSyllables === adjustment);
    if (!_.isEmpty(adjustedList)) {
      return adjustedList[0][0];
    } else {
      otheradjustednotasgoodList = list.filter(synonym => (synonym[1] - currentWordSyllables < adjustment) && (synonym[1] > currentWordSyllables)).sort(function(a, b) {return b[1]-a[1]});
    }

    if (!_.isEmpty(otheradjustednotasgoodList)) {
      return otheradjustednotasgoodList[0][0]
    } else {
      return word;
    }
  } else {
    return word;
  }
}

let countSyllables = function(phrase) {
  let tokens = phrase.split(/\W/);
  return _.sum(tokens.map(syllable));
};

function adjustWord(word, adjustment) {
  if (adjustment > 0) {
    return expandWord(word, adjustment);
  } else if (adjustment < 0) {
    return shortenWord(word, adjustment);
  } else {
    return word;
  }
}

export function adjustPhrase(phrase, adjustment) {
  console.log(phrase, adjustment);
  if (adjustment > 0) {
    return addWords(phrase, adjustment);
  } else if (adjustment < 0) {
    return removeWords(phrase, adjustment);
  } else {
    return phrase;
  }
}

function adjustSyllables(lines, adjustment) {
  let line = 0;
  let idx = 0;
  let token = lines[line][idx];

  // First loop to make small adjustments to existing words' lengths.
  while (adjustment !== 0 && line < 3) {
    let newWord = adjustWord(token, adjustment);

    if (newWord) {
      lines[line][idx] = newWord;
      adjustment -= (syllable(newWord) - syllable(token));
    }

    idx++;
    token = lines[line][idx];
    if (!token) {
      line++;
      idx = 0;
      if (line > 2) {
        break;
      }
      token = lines[line][idx];

    }
  }

  var joined = lines.map(line => line.join(' '));
  line = 0;

  // Second while loop to add / remove extraneous words
  while (adjustment !== 0 && line < 3) {
    let oldPhrase = joined[line];
    let lineCount = countSyllables(oldPhrase);

    if ((line === 1 && lineCount === 7) || lineCount === 5) {
      line++;
    } else {
      var newPhrase;
      var maxLineAdjustment = (line === 1) ? 7 : 5;
      var lineAdjustment;

      if (adjustment < 0) {
        if ((adjustment * -1) > lineCount) {
          lineAdjustment = lineCount * -1;
        } else {
          lineAdjustment = adjustment;
        }
      } else if (adjustment > 0) {

        let maxPossibleAdjustment = (maxLineAdjustment - lineCount);
        lineAdjustment = adjustment > maxPossibleAdjustment ? maxPossibleAdjustment : adjustment;

      }

      newPhrase = adjustPhrase(oldPhrase, lineAdjustment);

      joined[line] = newPhrase;
      adjustment -= (countSyllables(newPhrase) - countSyllables(oldPhrase));
      line++;
    }

  }

  return joined.join(' ' + separator + ' ');
}

export function isHaiku(msg) {
  return countSyllables(msg, separator) === HAIKU_LENGTH;
}

export function breakIntoHaiku(msg) {
  var tokens = msg.trim().split(/\W/);
  var rows = [[], [], []];
  var rowSyllables = 0;
  var line = 0;
  while (tokens.length) {
    let token = tokens.shift();
    let tokenLength = syllable(token);

    if (line === 0) {
      var diff = (rowSyllables + tokenLength) - 5;
      if (diff > 0) {
        line += 1;
        rowSyllables = 0;
      }

    } else if (line === 1) {

      var diff = (rowSyllables + tokenLength) - 7;
      if (diff > 0) {
        line += 1;
        rowSyllables = 0;
      }

    }

    rowSyllables += tokenLength;
    rows[line].push(token);

  }

  return rows;
}

/**
 * steps to check if it is a haiku
 * 1. check syllable length of commit
 * 2. if longer - > check for haikus in commit..
 *  a) if haiku -> print done !
 *  b) if not -> get most of haiku and continue? choose key words and continue?
 * 3. if shorter -> check syllable counts?
 * for what is missing -> fill in rhyme etc. to make up length ?? nonsensical ??
 */
 export function makeHaiku(msg) {
  let syllables = countSyllables(msg);
  let difference = HAIKU_LENGTH - syllables;

  msg = breakIntoHaiku(msg);
  return adjustSyllables(msg, difference);
}<commit_msg>this commit message // is already a haiku // refrigerator<commit_after>import syllable from 'syllable';
import _ from 'lodash';
import wordnet from 'wordnet';
var $ = require('jquery-deferred');
import stopwords from './data/stopwords.js';
import descriptors from './data/descriptors.js';
import cusseth from './data/cusseth.js';
import nouns from './data/nouns.js';
import thesaurus from './data/thesaurus.js';

let adjectives = descriptors.map(word => [word, syllable(word)]);
let curses = cusseth.map(word => [word, syllable(word)]);

const HAIKU_LENGTH = 17;
const separator = '//';
const FOUL = false;

// Chrys' Domain
function addModifier(phrase, length, mod) {
  let tokens = phrase.split(/\W/);
  let nounList = tokens.map(word => _.contains(nouns, word));
  for (var i in nounList) {
    if (nounList[i]) {
      tokens.splice(i, 0, mod);
      return tokens.join(' ');
    }
  }

  return mod + ' ' + phrase;
}

export function addExpletive(phrase, length) {
  var curse = _.sample(curses.filter(tuple => tuple[1] === length));
  if (!curse) {
    return addExpletive(addExpletive(phrase, length - 1), 1);
  }

  return addModifier(phrase, length, curse[0]);
}

export function addAdjective(phrase, length) {
  var adj = _.sample(adjectives.filter(tuple => tuple[1] === length));
  if (!adj) {
    return addAdjective(addAdjective(phrase, length - 1), 1);
  }

  return addModifier(phrase, length, adj[0]);
}

export function removeWords(phrase, length) {
  console.log(phrase, length);
  let tokens = phrase.split(/\W/);
  let newTokens = [];
  tokens.forEach(function(token) {
    if (length && _.contains(stopwords, token)) {
      length -= syllable(token);
    } else {
      newTokens.push(token);
    }
  });

  return newTokens.join(' ');
}

function addWords(phrase, length) {
  if (FOUL) {
    return addExpletive(phrase, length);
  } else {
    return addAdjective(phrase, length);
  }
}

// Nicole WUZ HERE
export function shortenWord(word, adjustment) {
  let possibleNewWord = [];
  let theNewWord;
  let newWordSyllables;
  let adjustedList;
  let otheradjustednotasgoodList;
  let currentWordSyllables = syllable(word);

  adjustment = -adjustment;

  let list = []

  var response = possibleSynonymArray(word);

  if (!_.isEmpty(response)) {
    for (let x=0; x<response.length; x++) {
      list[x] = [response[x], syllable(response[x])]
    }

    adjustedList = list.filter(synonym => synonym[1] - currentWordSyllables === adjustment);

    if (!_.isEmpty(adjustedList)) {
      return adjustedList[0][0];
    }

    else {
      otheradjustednotasgoodList = list.filter(synonym => (synonym[1] - currentWordSyllables > adjustment) && (synonym[1] < currentWordSyllables)).sort(function(a, b) {return a[1]-b[1]});
    }

    if (!_.isEmpty(otheradjustednotasgoodList)) {
      return otheradjustednotasgoodList[0][0]
    } else {
      return word;
    }
  } else {
    return word;
  }

}

function possibleSynonymArray(word) {
  if (thesaurus[word]) {
    return thesaurus[word];
  }
}

function possibleSynonymArrayAsync(word) {
  var promise = $.Deferred();

  var possibleNewWords = [];
  wordnet.lookup(word, function(err, definitions) {
    if (definitions) {
      definitions.forEach(function(definition) {
        var words = definition.meta.words;
        words.forEach(function(word) {
          if (!_.includes(possibleNewWords, word.word)) {
            possibleNewWords.push(word.word);
          }
        });
      });
    }
    promise.resolve(possibleNewWords);
  });
  return promise;
}

export function expandWord(word, adjustment) {
  let possibleNewWord = [];
  let theNewWord;
  let newWordSyllables;
  let adjustedList;
  let otheradjustednotasgoodList;
  let currentWordSyllables = syllable(word);
  let list = []

  var response = possibleSynonymArray(word);

  if (!_.isEmpty(response)){
    for (let x=0; x<response.length; x++) {
      list[x] = [response[x], syllable(response[x])]
    }

    adjustedList = list.filter(synonym => synonym[1] - currentWordSyllables === adjustment);
    if (!_.isEmpty(adjustedList)) {
      return adjustedList[0][0];
    } else {
      otheradjustednotasgoodList = list.filter(synonym => (synonym[1] - currentWordSyllables < adjustment) && (synonym[1] > currentWordSyllables)).sort(function(a, b) {return b[1]-a[1]});
    }

    if (!_.isEmpty(otheradjustednotasgoodList)) {
      return otheradjustednotasgoodList[0][0]
    } else {
      return word;
    }
  } else {
    return word;
  }
}

let countSyllables = function(phrase) {
  let tokens = phrase.split(/\W/);
  return _.sum(tokens.map(syllable));
};

function adjustWord(word, adjustment) {
  if (adjustment > 0) {
    return expandWord(word, adjustment);
  } else if (adjustment < 0) {
    return shortenWord(word, adjustment);
  } else {
    return word;
  }
}

export function adjustPhrase(phrase, adjustment) {
  console.log(phrase, adjustment);
  if (adjustment > 0) {
    return addWords(phrase, adjustment);
  } else if (adjustment < 0) {
    return removeWords(phrase, adjustment);
  } else {
    return phrase;
  }
}

function adjustSyllables(lines, adjustment) {
  let line = 0;
  let idx = 0;
  let token = lines[line][idx];

  // First loop to make small adjustments to existing words' lengths.
  while (adjustment !== 0 && line < 3) {
    let newWord = adjustWord(token, adjustment);

    if (newWord) {
      lines[line][idx] = newWord;
      adjustment -= (syllable(newWord) - syllable(token));
    }

    idx++;
    token = lines[line][idx];
    if (!token) {
      line++;
      idx = 0;
      if (line > 2) {
        break;
      }
      token = lines[line][idx];

    }
  }

  var joined = lines.map(line => line.join(' '));
  line = 0;

  // Second while loop to add / remove extraneous words
  while (adjustment !== 0 && line < 3) {
    let oldPhrase = joined[line];
    let lineCount = countSyllables(oldPhrase);

    if ((line === 1 && lineCount === 7) || lineCount === 5) {
      line++;
    } else {
      var newPhrase;
      var maxLineAdjustment = (line === 1) ? 7 : 5;
      var lineAdjustment;

      if (adjustment < 0) {
        if ((adjustment * -1) > lineCount) {
          lineAdjustment = lineCount * -1;
        } else {
          lineAdjustment = adjustment;
        }
      } else if (adjustment > 0) {

        let maxPossibleAdjustment = (maxLineAdjustment - lineCount);
        lineAdjustment = adjustment > maxPossibleAdjustment ? maxPossibleAdjustment : adjustment;

      }

      newPhrase = adjustPhrase(oldPhrase, lineAdjustment);

      joined[line] = newPhrase;
      adjustment -= (countSyllables(newPhrase) - countSyllables(oldPhrase));
      line++;
    }

  }

  return joined.join(' ' + separator + ' ');
}

export function isHaiku(msg) {
  return countSyllables(msg, separator) === HAIKU_LENGTH;
}

export function breakIntoHaiku(msg) {
  var tokens = msg.trim().split(/\W/);
  var rows = [[], [], []];
  var rowSyllables = 0;
  var line = 0;
  while (tokens.length) {
    let token = tokens.shift();
    let tokenLength = syllable(token);

    if (line === 0) {
      var diff = (rowSyllables + tokenLength) - 5;
      if (diff > 0) {
        line += 1;
        rowSyllables = 0;
      }

    } else if (line === 1) {

      var diff = (rowSyllables + tokenLength) - 7;
      if (diff > 0) {
        line += 1;
        rowSyllables = 0;
      }

    }

    rowSyllables += tokenLength;
    rows[line].push(token);

  }

  return rows;
}

/**
 * steps to check if it is a haiku
 * 1. check syllable length of commit
 * 2. if longer - > check for haikus in commit..
 *  a) if haiku -> print done !
 *  b) if not -> get most of haiku and continue? choose key words and continue?
 * 3. if shorter -> check syllable counts?
 * for what is missing -> fill in rhyme etc. to make up length ?? nonsensical ??
 */
 export function makeHaiku(msg) {
  let syllables = countSyllables(msg);
  let difference = HAIKU_LENGTH - syllables;

  msg = breakIntoHaiku(msg);
  return adjustSyllables(msg, difference);
}<|endoftext|>


<commit_before>import Vue from 'vue'
import Resource from 'vue-resource'
import { sync } from 'vuex-router-sync'
import store from './store'
import router from './router'
import App from './components/App.vue'

// Google charts
window.google.charts.load('current', {
  'packages': ['corechart', 'line']
})

// install resource, for http requests
Vue.use(Resource)

const app = new Vue({
  router: router,
  store: store,
  el: "#app",
  template: "<App/>",
  components: { App }
})

window.google.charts.setOnLoadCallback(() => {
  app.$store.commit('SET_CHARTSLOADED')
})

function update_10s () {
  app.$store.dispatch('FETCH_WORLDS')
  app.$store.dispatch('FETCH_MATCHES')
}

function update_1m () {
  app.$store.dispatch('FETCH_GLICKO') // does this really need to be here? could be done once maybe.
  app.$store.dispatch('FETCH_PREDICTEDGLICKO')
  app.$store.dispatch('FETCH_LEADERBOARD')
}

update_10s()
update_1m()
app.$store.dispatch('FETCH_OBJECTIVES')
setInterval(update_10s, 10000)
setInterval(update_1m, 60000)

export { app, router, store }
<commit_msg>Remove unused dependency<commit_after>import Vue from 'vue'
import Resource from 'vue-resource'
import store from './store'
import router from './router'
import App from './components/App.vue'

// Google charts
window.google.charts.load('current', {
  'packages': ['corechart', 'line']
})

// install resource, for http requests
Vue.use(Resource)

const app = new Vue({
  router: router,
  store: store,
  el: "#app",
  template: "<App/>",
  components: { App }
})

window.google.charts.setOnLoadCallback(() => {
  app.$store.commit('SET_CHARTSLOADED')
})

function update_10s () {
  app.$store.dispatch('FETCH_WORLDS')
  app.$store.dispatch('FETCH_MATCHES')
}

function update_1m () {
  app.$store.dispatch('FETCH_GLICKO') // does this really need to be here? could be done once maybe.
  app.$store.dispatch('FETCH_PREDICTEDGLICKO')
  app.$store.dispatch('FETCH_LEADERBOARD')
}

update_10s()
update_1m()
app.$store.dispatch('FETCH_OBJECTIVES')
setInterval(update_10s, 10000)
setInterval(update_1m, 60000)

export { app, router, store }
<|endoftext|>


<commit_before>/*
 * BouyomiCraft v1.0.0
 *  Minecraftのチャットを棒読みちゃんで読み上げるソフト
 *  Author: prince(MinecraftID: prince_0203)
 *  制作開始: 2016/01/29
 */

/*jshint esnext: true*/

const electron = require('electron');

const app = electron.app;

const BrowserWindow = electron.BrowserWindow;

const path = require('path');

var mainWindow = null;

app.on('window-all-closed', function() {
  if (process.platform !== 'darwin')
    app.quit();
});

app.on('ready', function() {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    show: false
  });

  mainWindow.loadURL(path.join('file://', __dirname, '/index.html'));

  mainWindow.webContents.on('dom-ready', function() {
    mainWindow.show();
  });

  mainWindow.on('closed', function() {
    mainWindow = null;
  });
});
<commit_msg>バージョン表記を更新<commit_after>/*
 * BouyomiCraft v1.0.1
 *  Minecraftのチャットを棒読みちゃんで読み上げるソフト
 *  Author: prince(MinecraftID: prince_0203)
 *  制作開始: 2016/01/29
 */

/*jshint esnext: true*/

const electron = require('electron');

const app = electron.app;

const BrowserWindow = electron.BrowserWindow;

const path = require('path');

var mainWindow = null;

app.on('window-all-closed', function() {
  if (process.platform !== 'darwin')
    app.quit();
});

app.on('ready', function() {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    show: false
  });

  mainWindow.loadURL(path.join('file://', __dirname, '/index.html'));

  mainWindow.webContents.on('dom-ready', function() {
    mainWindow.show();
  });

  mainWindow.on('closed', function() {
    mainWindow = null;
  });
});
<|endoftext|>


<commit_before>'use babel'

/* @flow */

import Path from 'path'
import FS from 'fs'
import Chokidar from 'chokidar'
import {Disposable} from 'sb-event-kit'
import {read} from './helpers/common'
import {findRoot} from './helpers/find-root'
import {scanFiles} from './helpers/scan-files'
import {getConfig} from './helpers/get-config'
import {getPlugins} from './helpers/get-plugins'
import {execute} from './helpers/execute'
import {fromObject} from './helpers/source-map'
import {saveFile} from './helpers/save-file'
import type {Ucompiler$Compile$Results, Ucompiler$Compile$Result, Ucompiler$Config$Rule} from './types'

export async function compile(
  directory: string,
  ruleName:?string = null,
  errorCallback: ((error: Error) => void) = function(e) { throw e },
  saveContents: boolean = true
): Promise<Ucompiler$Compile$Results> {
  const rootDirectory = await findRoot(directory)
  const {rule: config} = await getConfig(rootDirectory, ruleName)
  const files = await scanFiles(rootDirectory, config)
  let promises = []

  const toReturn = {
    status: true,
    contents: [],
    sourceMaps: [],
    state: []
  }

  promises = files.map(filePath => {
    return compileFile(rootDirectory, filePath, config).then(function(result) {
      toReturn.contents.push({path: filePath, contents: result.contents})
      toReturn.sourceMaps.push({path: filePath, contents: result.sourceMap})
      toReturn.state.push({path: filePath, state: result.state})
    }, function(e) {
      toReturn.status = false
      errorCallback(e)
    })
  })

  await Promise.all(promises)

  return toReturn
}

export async function compileFile(
  rootDirectory: string,
  filePath: string,
  config: Ucompiler$Config$Rule
): Promise<Ucompiler$Compile$Result> {
  const fileContents = await read(filePath)
  const state = {imports: []}

  const plugins = await getPlugins(rootDirectory, config)
  const result = await execute(plugins, fileContents, {
    rootDirectory: rootDirectory,
    filePath: filePath,
    state: state,
    config: config
  })

  return {
    filePath: filePath,
    contents: result.contents,
    sourceMap: result.sourceMap ? fromObject(rootDirectory, filePath, result.sourceMap) : null,
    state: state
  }
}

export async function watch(
  directory: string,
  ruleName: string,
  errorCallback: ((error: Error) => void) = function(e) { console.error(e.stack) }
): Promise {
  const rootDirectory = await findRoot(directory)
  const {rule: config} = await getConfig(rootDirectory, ruleName)
  const targetDirectories = config.include.map(function(entry) {
    return Path.join(rootDirectory, entry.directory)
  })

  function onChange(filePath) {
    compileFile(rootDirectory, filePath, config, { imports: [] }).then(function(result) {
      saveFile(rootDirectory, result, config)
    }).catch(errorCallback)
  }

  const watcher = Chokidar.watch(targetDirectories)
  watcher.on('change', onChange)
  watcher.on('add', onChange)

  return new Disposable(function() {
    watcher.close()
  })
}
<commit_msg>:new: Add saveIncludedFiles parameter to main<commit_after>'use babel'

/* @flow */

import Path from 'path'
import FS from 'fs'
import Chokidar from 'chokidar'
import {Disposable} from 'sb-event-kit'
import {read} from './helpers/common'
import {findRoot} from './helpers/find-root'
import {scanFiles} from './helpers/scan-files'
import {getConfig} from './helpers/get-config'
import {getPlugins} from './helpers/get-plugins'
import {execute} from './helpers/execute'
import {fromObject} from './helpers/source-map'
import {saveFile} from './helpers/save-file'
import {getParents} from './helpers/get-parents'
import type {Ucompiler$Compile$Results, Ucompiler$Compile$Result, Ucompiler$Config$Rule} from './types'

export async function compile(
  directory: string,
  ruleName:?string = null,
  errorCallback: ((error: Error) => void) = function(e) { throw e },
  saveContents: boolean = true,
  saveIncludedFiles: boolean = false
): Promise<Ucompiler$Compile$Results> {
  const rootDirectory = await findRoot(directory)
  const {rule: config} = await getConfig(rootDirectory, ruleName)
  const files = await scanFiles(rootDirectory, config)
  let promises

  const toReturn = {
    status: true,
    contents: [],
    sourceMaps: [],
    state: []
  }
  const imports = new Map()
  const results = new Map()

  promises = files.map(function(filePath) {
    return compileFile(rootDirectory, filePath, config).then(function(result) {
      toReturn.contents.push({path: filePath, contents: result.contents})
      toReturn.sourceMaps.push({path: filePath, contents: result.sourceMap})
      toReturn.state.push({path: filePath, state: result.state})
      imports.set(filePath, result.state.imports)
      results.set(filePath, result)
    }, function(e) {
      toReturn.status = false
      errorCallback(e)
    })
  })

  await Promise.all(promises)

  if (saveContents) {
    const parentsMap = getParents(imports)
    promises = files.map(function(filePath) {
      const imports = parentsMap.get(filePath) || []
      const result = results.get(filePath)
      if (result && (!imports.length || saveIncludedFiles)) {
        return saveFile(rootDirectory, result, config)
      }
    })

    await Promise.all(promises)
  }

  results.clear()
  imports.clear()

  return toReturn
}

export async function compileFile(
  rootDirectory: string,
  filePath: string,
  config: Ucompiler$Config$Rule
): Promise<Ucompiler$Compile$Result> {
  const fileContents = await read(filePath)
  const state = {imports: []}

  const plugins = await getPlugins(rootDirectory, config)
  const result = await execute(plugins, fileContents, {
    rootDirectory: rootDirectory,
    filePath: filePath,
    state: state,
    config: config
  })

  return {
    filePath: filePath,
    contents: result.contents,
    sourceMap: result.sourceMap ? fromObject(rootDirectory, filePath, result.sourceMap) : null,
    state: state
  }
}

export async function watch(
  directory: string,
  ruleName: string,
  errorCallback: ((error: Error) => void) = function(e) { console.error(e.stack) }
): Promise {
  const rootDirectory = await findRoot(directory)
  const {rule: config} = await getConfig(rootDirectory, ruleName)
  const targetDirectories = config.include.map(function(entry) {
    return Path.join(rootDirectory, entry.directory)
  })

  function onChange(filePath) {
    compileFile(rootDirectory, filePath, config).then(function(result) {
      saveFile(rootDirectory, result, config)
    }).catch(errorCallback)
  }

  const watcher = Chokidar.watch(targetDirectories)
  watcher.on('change', onChange)
  watcher.on('add', onChange)

  return new Disposable(function() {
    watcher.close()
  })
}
<|endoftext|>


<commit_before>// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import Vuetify from 'vuetify'
import 'vuetify/dist/vuetify.min.css'
import Vuex from 'vuex'
import axios from 'axios'
import moment from 'moment'

import App from './App'

Vue.config.productionTip = false
Vue.use(Vuetify)
Vue.use(Vuex)

/* eslint-disable no-new */
const store = new Vuex.Store({
  state: {
    server: 0,
    servers: [],
    total: 0,
    search: '',
    nodes: [],
    events: [],
    event: {}
  },
  mutations: {
    updateEvents(state, payload) {
      state.events = payload.events
    },
    updateNodes(state, payload) {
      state.nodes = payload.nodes
    },
    addEvent(state, payload) {
      const event = payload.event
      state.nodes = state.nodes.filter((node) => node.node !== event.node)
      if (event.event !== 'disconnect')
        state.nodes.push({
          node: event.node,
          pub: event.pub,
          flag: false,
          country_name: '',
          timestamp: event.timestamp,
          vpn: event.vpn
        })
      if (event.node.includes(state.search)) {
        state.events = state.events.filter((itm) => itm.id !== event.id)
        state.events.unshift(event)
        state.events.pop()
        state.event = event
      }
    },
    changeServer(state, payload) {
      state.server = payload.server
    },
    changeSearch(state, payload) {
      state.search = payload.text
    }
  },
  actions: {
    changeServer(context, payload) {
      context.commit('changeServer', {
        server: payload.server
      })
      context.dispatch('refresh')
    },
    changePage(context, opt) {
      axios.get(`/log/${store.state.server}/${opt.page}/${opt.size}/${store.state.search}`)
      .then((response) => {
        context.commit({
          type: 'updateEvents',
          events: response.data
        })
      })
      axios.get(`/log/${store.state.server}/size/${store.state.search}`)
        .then((response) => store.state.total = response.data.value)
    },
    refresh(context) {
      axios.get(`/entries/${store.state.server}`)
        .then((response) => {
          const nodes = response.data.map((node) => {
            node.flag = false
            node.country_name = ''
            return node
          })
          context.commit({
            type: 'updateNodes',
            nodes: nodes
          })
        })
    }
  }
})

new Vue({
  el: '#app',
  template: '<App/>',
  components: { App },
  store,
  computed: {
    server () {
      return this.$store.state.server
    }
  },
  watch: {
    'server': (val) => {
      axios.get(`/log/${val}/size/${store.state.search}`)
        .then((response) => store.state.total = response.data.value)
    }
  },
  beforeMount () {
    axios.get('/servers')
      .then((response) => {
        store.state.servers = response.data
        store.commit('changeServer', {
          server: response.data[0].id
        })
        axios.get(`/log/${store.state.server}/size/${store.state.search}`)
          .then((response) => store.state.total = response.data.value)
      })
    const socket = new ReconnectingWebSocket(`${window.location.origin.replace('http','ws')}/live/log`)
    socket.onmessage = (event) => {
      event = JSON.parse(event.data)
      if (event.server === store.state.server)
        store.commit({
          type: 'addEvent',
          event: event
        })
    }
  }
})
<commit_msg>Minor improvements<commit_after>// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import Vuetify from 'vuetify'
import 'vuetify/dist/vuetify.min.css'
import Vuex from 'vuex'
import axios from 'axios'
import moment from 'moment'

import App from './App'

Vue.config.productionTip = false
Vue.use(Vuetify)
Vue.use(Vuex)

/* eslint-disable no-new */
const store = new Vuex.Store({
  state: {
    server: 0,
    servers: [],
    total: 0,
    search: '',
    nodes: [],
    events: [],
    event: {}
  },
  mutations: {
    updateEvents(state, payload) {
      state.events = payload.events
    },
    updateNodes(state, payload) {
      state.nodes = payload.nodes
    },
    addEvent(state, payload) {
      const event = payload.event
      state.nodes = state.nodes.filter((node) => node.node !== event.node)
      if (event.event !== 'disconnect')
        state.nodes.push({
          node: event.node,
          pub: event.pub,
          flag: false,
          country_name: '',
          timestamp: event.timestamp,
          vpn: event.vpn
        })
      if (event.node.includes(state.search)) {
        state.events = state.events.filter((itm) => itm.id !== event.id)
        state.events.unshift(event)
        state.events.pop()
      }
      state.event = event
    },
    changeServer(state, payload) {
      state.server = payload.server
    },
    changeSearch(state, payload) {
      state.search = payload.text
    }
  },
  actions: {
    changeServer(context, payload) {
      context.commit('changeServer', {
        server: payload.server
      })
      context.dispatch('refresh')
    },
    changePage(context, opt) {
      axios.get(`/log/${store.state.server}/${opt.page}/${opt.size}/${store.state.search}`)
      .then((response) => {
        context.commit({
          type: 'updateEvents',
          events: response.data
        })
      })
      axios.get(`/log/${store.state.server}/size/${store.state.search}`)
        .then((response) => store.state.total = response.data.value)
    },
    refresh(context) {
      axios.get(`/entries/${store.state.server}`)
        .then((response) => {
          const nodes = response.data.map((node) => {
            node.flag = false
            node.country_name = ''
            return node
          })
          context.commit({
            type: 'updateNodes',
            nodes: nodes
          })
        })
    }
  }
})

new Vue({
  el: '#app',
  template: '<App/>',
  components: { App },
  store,
  computed: {
    server () {
      return this.$store.state.server
    }
  },
  watch: {
    'server': (val) => {
      axios.get(`/log/${val}/size/${store.state.search}`)
        .then((response) => store.state.total = response.data.value)
    }
  },
  beforeMount () {
    axios.get('/servers')
      .then((response) => {
        store.state.servers = response.data
        store.commit('changeServer', {
          server: response.data[0].id
        })
        axios.get(`/log/${store.state.server}/size/${store.state.search}`)
          .then((response) => store.state.total = response.data.value)
      })
    const socket = new ReconnectingWebSocket(`${window.location.origin.replace('http','ws')}/live/log`)
    socket.onmessage = (event) => {
      event = JSON.parse(event.data)
      if (event.server === store.state.server)
        store.commit({
          type: 'addEvent',
          event: event
        })
    }
  }
})
<|endoftext|>


<commit_before>import Vue from 'vue';
import VueI18n from 'vue-i18n';
import VueRouter from 'vue-router';
import App from './App.vue';
import Index from './pages/Home/index.vue';

import HiraganaStore from './stores/HiraganaStore.js';
import HiraganaList from './pages/Hiragana/list.vue';
import HiraganaQuizz from './pages/Hiragana/quizz.vue';
import HiraganaIndex from './pages/Hiragana/index.vue';

import locales from './locales.js';

Vue.use(VueI18n, {
  lang: navigator.language,
  locales,
});

Vue.use(VueRouter);

document.title = Vue.t('document.title');

var router = new VueRouter();

router.map({
  '/': {
    component: Index,
  },
  '/hiragana': {
    component: HiraganaIndex,

    subRoutes: {
      '/list': {
        component: HiraganaList,
      },
      '/quizz': {
        component: HiraganaQuizz,
      }
    }
  }
});

router.beforeEach(transition => {

  if (transition.to.path === '/hiragana/quizz') {
    HiraganaStore.resetQuizz();
  }

  transition.next();
});

router.start(App, '#app');<commit_msg>Add katakana routes<commit_after>import Vue from 'vue';
import VueI18n from 'vue-i18n';
import VueRouter from 'vue-router';
import App from './App.vue';
import Index from './pages/Home/index.vue';

import HiraganaStore from './stores/HiraganaStore.js';
import HiraganaList from './pages/Hiragana/list.vue';
import HiraganaQuizz from './pages/Hiragana/quizz.vue';
import HiraganaIndex from './pages/Hiragana/index.vue';

import KatakanaList from './pages/Katakana/list.vue';
import KatakanaQuizz from './pages/Katakana/quizz.vue';
import KatakanaIndex from './pages/Katakana/index.vue';

import locales from './locales.js';

Vue.use(VueI18n, {
  lang: navigator.language,
  locales,
});

Vue.use(VueRouter);

document.title = Vue.t('document.title');

var router = new VueRouter();

router.map({
  '/': {
    component: Index,
  },
  '/hiragana': {
    component: HiraganaIndex,

    subRoutes: {
      '/list': {
        component: HiraganaList,
      },
      '/quizz': {
        component: HiraganaQuizz,
      }
    }
  },
  '/katakana': {
    component: KatakanaIndex,

    subRoutes: {
      '/list': {
        component: KatakanaList,
      },
      '/quizz': {
        component: KatakanaQuizz,
      }
    }
  }
});

router.beforeEach(transition => {

  if (transition.to.path === '/hiragana/quizz') {
    HiraganaStore.resetQuizz();
  }

  transition.next();
});

router.start(App, '#app');<|endoftext|>


<commit_before>import { around } from 'meld'
import { isArray, extend } from 'underscore'
import Plugin from 'extplug/Plugin'
import SuggestionView from 'plug/views/rooms/chat/ChatSuggestionView'
import ChatView from 'plug/views/rooms/chat/ChatView'

import * as presets from './presets'
import style from './style.css'

const templateItem = window.requirejs('hbs!templates/room/chat/ChatSuggestionItem')

// kinda random, height of a single suggestion item according to plug.dj
const ITEM_HEIGHT = 38

export default Plugin.extend({
  name: 'Advanced Autocomplete',
  description: 'Autocompletes things in chat according to the current room ' +
                'settings. Room owners might use this for bot commands or ' +
                'silly memes.',

  style,

  enable() {
    const plugin = this

    this.onUpdate()
    this.listenTo(this.ext.roomSettings, 'change:autocomplete', this.onUpdate)

    // builds a suggestions array for the current input text
    this._checkAdvice = around(SuggestionView.prototype, 'check', function (joinpoint) {
      let res = joinpoint.proceed()

      // clear the suggestion objects by default (used by our patched
      // updateSuggestions to determine if we matched custom suggestions)
      this.suggestionObjects = []

      // original check() resulted in suggestions
      if (this.suggestions.length) {
        return res
      }

      let [ message, caret ] = joinpoint.args
      plugin.completions.forEach(o => {
        let start = message.lastIndexOf(` ${o.trigger}`, caret)
        if (start === -1) {
          start = message.indexOf(o.trigger) === 0 ? 0 : -1
        }
        else {
          start = start + 1
        }

        if (start !== -1) {
          this.type = o.trigger
          let typed = message.substr(start + o.trigger.length)
          if (typed.length >= 1) {
            this.suggestionObjects = o.suggestions
              .filter(suggestion => (suggestion.string || '').indexOf(typed) === 0)
              .slice(0, 10)
              .sort((a, b) => a.string > b.string ? 1
                            : a.string < b.string ? -1
                            : 0)
            this.suggestions = this.suggestionObjects.map(sug => sug.string)
          }
          else {
            this.suggestions = []
          }
        }
      })

      return res
    })

    // displays the suggestions list
    this._updateAdvice = around(SuggestionView.prototype, 'updateSuggestions', function (joinpoint) {
      if (this.type !== '@' && this.type !== ':' &&
          this.suggestions.length > 0 &&
          this.suggestionObjects && this.suggestionObjects.length > 0) {
        // not users, nor emoji: this is a custom suggestion list
        let items = this.suggestionObjects.map((suggestion, i) => {
          let el = $(templateItem({
            value: this.type + suggestion.string,
            index: i,
            image: plugin.getImage(suggestion)
          })).mousedown(this.pressBind).mouseenter(this.overBind)
          if (suggestion.description) {
            el.find('.value').append(
              ' ',
              $('<span />').addClass('extplug-ac-descr')
                            .text(suggestion.description)
            )
          }
          return el
        })
        this.$itemContainer
          .empty()
          .append(items)
        // random copy-paste bits from plug.dj's SuggestionView#updateSuggestion
        if (this.index === -1 || this.index >= this.suggestions.length) {
          this.index = 0
        }
        this.updateSelectedSuggestion()
        this.$el.height(this.suggestions.length * ITEM_HEIGHT)
        _.delay(this.showBind, 10)
        _.delay(this.showBind, 15)
        this.$document.on('mousedown', this.documentClickBind)
      }
      else {
        return joinpoint.proceed()
      }
    })

    // computes the correct selection range for custom suggestions
    // plug.dj uses "getMentionsRange" if the suggestion type == "@", or
    // "getEmojiRange" otherwise, so we'll hijack getEmojiRange for everything
    // else as well! :D
    this._rangeAdvice = around(ChatView.prototype, 'getEmojiRange', function (joinpoint) {
      let suggestionView = this.suggestionView
      let trigger = suggestionView.type

      // it really is an emoji thing
      if (trigger === ':') {
        return joinpoint.proceed()
      }

      let caret = this.getCaratPosition()
      if (caret > 0) {
        let message = this.chatInput.value.substr(0, caret),
          start = message.lastIndexOf(` ${trigger}`)
        if (start === -1) {
          start = message.indexOf(trigger) === 0 ? 0 : -1
        }
        else {
          start = start + 1
        }
        return [ start + trigger.length, caret ]
      }
    })
  },

  disable() {
    this._checkAdvice.remove()
    this._updateAdvice.remove()
    this._rangeAdvice.remove()
  },

  // builds image HTML for a given suggestion
  getImage(suggestion) {
    if (suggestion.icon) {
      return $('<div />').addClass('extplug-ac-centering').append(
        $('<i />').addClass(`icon ${suggestion.icon}`)
      )[0].outerHTML
    }
    return ''
  },

  // builds the appropriate set of possible autocomplete suggestions
  // (without things that are irrelevant to the user etc)
  onUpdate() {
    let completions = this.ext.roomSettings.get('autocomplete') || []
    // clean up autocomplete settings
    this.completions = completions
      // remove invalid entries
      .filter(comp => comp && (!!comp.preset ||
                                !!comp.trigger && isArray(comp.suggestions)))
      // resolve presets
      .map(comp => comp.preset && comp.preset in presets
                  ? extend({}, presets[comp.preset] || {}, comp)
                  : comp)
      .map(o => {
        // clean up suggestions lists
        o.suggestions = o.suggestions
          // convert shorthand strings to suggestion objects
          .map(sug => typeof sug === 'string' ? { string: sug } : sug)
          // remove invalid entries
          .filter(sug => typeof sug.string === 'string')
          // remove suggestions that cannot be selected by the user
          // (mostly intended for bot commands)
          .filter(sug => (sug.role || 0) <= API.getUser().role)
          // strip command prefix from suggestion strings
          .map(sug => {
            if (sug.string.indexOf(o.trigger) === 0) {
              sug.string = sug.string.slice(o.trigger.length)
            }
            return sug
          })
        return o
      })
      // sort by trigger length, so longer triggers get checked for
      // completions _after_ shorter triggers.
      // this way longer triggers will overwrite shorter triggers.
      // this is useful for a kind of multiple-autocomplete, for example for a
      // room bot with a "!ban" command:
      // ! triggers "!mute" and "!ban",
      // !ban triggers "!ban perma", "!ban day" and "!ban hour"
      // now if the user completes "!ban", autocomplete will switch to using
      // the !ban trigger, and offer suggestions for "perma", "hour" and "day"
      .sort((a, b) => a.trigger.length - b.trigger.length)
  }

})
<commit_msg>Prevent crash on room settings with RCS-style autocomplete setting<commit_after>import { around } from 'meld'
import { isArray, extend } from 'underscore'
import Plugin from 'extplug/Plugin'
import SuggestionView from 'plug/views/rooms/chat/ChatSuggestionView'
import ChatView from 'plug/views/rooms/chat/ChatView'

import * as presets from './presets'
import style from './style.css'

const templateItem = window.requirejs('hbs!templates/room/chat/ChatSuggestionItem')

// kinda random, height of a single suggestion item according to plug.dj
const ITEM_HEIGHT = 38

export default Plugin.extend({
  name: 'Advanced Autocomplete',
  description: 'Autocompletes things in chat according to the current room ' +
                'settings. Room owners might use this for bot commands or ' +
                'silly memes.',

  style,

  enable() {
    const plugin = this

    this.onUpdate()
    this.listenTo(this.ext.roomSettings, 'change:autocomplete', this.onUpdate)

    // builds a suggestions array for the current input text
    this._checkAdvice = around(SuggestionView.prototype, 'check', function (joinpoint) {
      let res = joinpoint.proceed()

      // clear the suggestion objects by default (used by our patched
      // updateSuggestions to determine if we matched custom suggestions)
      this.suggestionObjects = []

      // original check() resulted in suggestions
      if (this.suggestions.length) {
        return res
      }

      let [ message, caret ] = joinpoint.args
      plugin.completions.forEach(o => {
        let start = message.lastIndexOf(` ${o.trigger}`, caret)
        if (start === -1) {
          start = message.indexOf(o.trigger) === 0 ? 0 : -1
        }
        else {
          start = start + 1
        }

        if (start !== -1) {
          this.type = o.trigger
          let typed = message.substr(start + o.trigger.length)
          if (typed.length >= 1) {
            this.suggestionObjects = o.suggestions
              .filter(suggestion => (suggestion.string || '').indexOf(typed) === 0)
              .slice(0, 10)
              .sort((a, b) => a.string > b.string ? 1
                            : a.string < b.string ? -1
                            : 0)
            this.suggestions = this.suggestionObjects.map(sug => sug.string)
          }
          else {
            this.suggestions = []
          }
        }
      })

      return res
    })

    // displays the suggestions list
    this._updateAdvice = around(SuggestionView.prototype, 'updateSuggestions', function (joinpoint) {
      if (this.type !== '@' && this.type !== ':' &&
          this.suggestions.length > 0 &&
          this.suggestionObjects && this.suggestionObjects.length > 0) {
        // not users, nor emoji: this is a custom suggestion list
        let items = this.suggestionObjects.map((suggestion, i) => {
          let el = $(templateItem({
            value: this.type + suggestion.string,
            index: i,
            image: plugin.getImage(suggestion)
          })).mousedown(this.pressBind).mouseenter(this.overBind)
          if (suggestion.description) {
            el.find('.value').append(
              ' ',
              $('<span />').addClass('extplug-ac-descr')
                            .text(suggestion.description)
            )
          }
          return el
        })
        this.$itemContainer
          .empty()
          .append(items)
        // random copy-paste bits from plug.dj's SuggestionView#updateSuggestion
        if (this.index === -1 || this.index >= this.suggestions.length) {
          this.index = 0
        }
        this.updateSelectedSuggestion()
        this.$el.height(this.suggestions.length * ITEM_HEIGHT)
        _.delay(this.showBind, 10)
        _.delay(this.showBind, 15)
        this.$document.on('mousedown', this.documentClickBind)
      }
      else {
        return joinpoint.proceed()
      }
    })

    // computes the correct selection range for custom suggestions
    // plug.dj uses "getMentionsRange" if the suggestion type == "@", or
    // "getEmojiRange" otherwise, so we'll hijack getEmojiRange for everything
    // else as well! :D
    this._rangeAdvice = around(ChatView.prototype, 'getEmojiRange', function (joinpoint) {
      let suggestionView = this.suggestionView
      let trigger = suggestionView.type

      // it really is an emoji thing
      if (trigger === ':') {
        return joinpoint.proceed()
      }

      let caret = this.getCaratPosition()
      if (caret > 0) {
        let message = this.chatInput.value.substr(0, caret),
          start = message.lastIndexOf(` ${trigger}`)
        if (start === -1) {
          start = message.indexOf(trigger) === 0 ? 0 : -1
        }
        else {
          start = start + 1
        }
        return [ start + trigger.length, caret ]
      }
    })
  },

  disable() {
    this._checkAdvice.remove()
    this._updateAdvice.remove()
    this._rangeAdvice.remove()
  },

  // builds image HTML for a given suggestion
  getImage(suggestion) {
    if (suggestion.icon) {
      return $('<div />').addClass('extplug-ac-centering').append(
        $('<i />').addClass(`icon ${suggestion.icon}`)
      )[0].outerHTML
    }
    return ''
  },

  // builds the appropriate set of possible autocomplete suggestions
  // (without things that are irrelevant to the user etc)
  onUpdate() {
    let completions = this.ext.roomSettings.get('autocomplete') || []
    if (!Array.isArray(completions)) {
      // TODO support RCS-style autocomplete, too
      return
    }

    // clean up autocomplete settings
    this.completions = completions
      // remove invalid entries
      .filter(comp => comp && (!!comp.preset ||
                                !!comp.trigger && isArray(comp.suggestions)))
      // resolve presets
      .map(comp => comp.preset && comp.preset in presets
                  ? extend({}, presets[comp.preset] || {}, comp)
                  : comp)
      .map(o => {
        // clean up suggestions lists
        o.suggestions = o.suggestions
          // convert shorthand strings to suggestion objects
          .map(sug => typeof sug === 'string' ? { string: sug } : sug)
          // remove invalid entries
          .filter(sug => typeof sug.string === 'string')
          // remove suggestions that cannot be selected by the user
          // (mostly intended for bot commands)
          .filter(sug => (sug.role || 0) <= API.getUser().role)
          // strip command prefix from suggestion strings
          .map(sug => {
            if (sug.string.indexOf(o.trigger) === 0) {
              sug.string = sug.string.slice(o.trigger.length)
            }
            return sug
          })
        return o
      })
      // sort by trigger length, so longer triggers get checked for
      // completions _after_ shorter triggers.
      // this way longer triggers will overwrite shorter triggers.
      // this is useful for a kind of multiple-autocomplete, for example for a
      // room bot with a "!ban" command:
      // ! triggers "!mute" and "!ban",
      // !ban triggers "!ban perma", "!ban day" and "!ban hour"
      // now if the user completes "!ban", autocomplete will switch to using
      // the !ban trigger, and offer suggestions for "perma", "hour" and "day"
      .sort((a, b) => a.trigger.length - b.trigger.length)
  }

})
<|endoftext|>


<commit_before>'use strict'

/**
 * plugin.js
 *
 * Released under LGPL License.
 * Copyright (c) 2016 SIRAP Group All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

/**
 * plugin.js Tinymce plugin headersfooters
 * @file plugin.js
 * @module
 * @name tinycmce-plugin-headersfooters
 * @description A plugin for tinymce WYSIWYG HTML editor that allow to insert headers and footers - requires tinymce-plugin-paginate.
 * @link https://github.com/sirap-group/tinymce-plugin-headersfooters
 * @author Rémi Becheras
 * @author Groupe SIRAP
 * @license GNU GPL-v2 http://www.tinymce.com/license
 * @version 1.0.0
 */

/**
 * Tinymce library - injected by the plugin loader.
 * @external tinymce
 * @see {@link https://www.tinymce.com/docs/api/class/tinymce/|Tinymce API Reference}
 */
var tinymce = window.tinymce

/**
 * The jQuery plugin namespace - plugin dependency.
 * @external "jQuery.fn"
 * @see {@link http://learn.jquery.com/plugins/|jQuery Plugins}
 */
var $ = window.jQuery

var HeaderFooterFactory = require('./classes/HeaderFooterFactory')
var ui = require('./utils/ui')

// Add the plugin to the tinymce PluginManager
tinymce.PluginManager.add('headersfooters', tinymcePluginHeadersFooters)

/**
 * Tinymce plugin headers/footers
 * @function
 * @global
 * @param {tinymce.Editor} editor - The injected tinymce editor.
 * @returns void
 */
function tinymcePluginHeadersFooters (editor, url) {
  var headerFooterFactory

  // add menu items
  editor.addMenuItem('insertHeader', ui.menuItems.insertHeader)
  editor.addMenuItem('removeHeader', ui.menuItems.removeHeader)
  editor.addMenuItem('insertFooter', ui.menuItems.insertFooter)
  editor.addMenuItem('removeFooter', ui.menuItems.removeFooter)

  editor.on('init', onInitHandler)
  editor.on('SetContent', onSetContent)

  /**
   * On init event handler. Instanciate the factory and initialize menu items states
   * @function
   * @inner
   * @returns void
   */
  function onInitHandler () {
    headerFooterFactory = new HeaderFooterFactory(editor)
    initMenuItems(headerFooterFactory, ui.menuItems)
  }

  /**
   * On SetContent event handler. Load or reload headers and footers from existing elements if it should do.
   * @function
   * @inner
   * @returns void
   */
  function onSetContent (evt) {
    // var $bodyElmt = $('body', editor.getDoc())
    var content = $(editor.getBody()).html()
    var emptyContent = '

'
    if (content && content !== emptyContent) {
      if (headerFooterFactory) {
        reloadHeadFoots()
      } else {
        setTimeout(reloadHeadFoots, 100)
      }
    }
  }

  /**
   * Helper function. Do the reload of headers and footers
   * @function
   * @inner
   * @returns void
   */
  function reloadHeadFoots () {
    var $headFootElmts = $('*[data-headfoot]', editor.getDoc())
    $headFootElmts.each(function (i, el) {
      headerFooterFactory.loadElement(el)
    })
  }
}

/**
 * Initialize menu items states (show, hide, ...) and implements onclick handlers
 * @function
 * @inner
 * @param {HeaderFooterFactory} factory The header and footer factory
 * @param {object} menuItems The set of plugin's menu items
 * @returns undefined
 */
function initMenuItems (factory, menuItems) {
  // on startup, hide remove buttons
  menuItems.removeHeader.hide()
  menuItems.removeFooter.hide()

  // override insertHeader, insertFooter, removeHeader and removeFooter onclick handlers
  menuItems.insertHeader.onclick = function () {
    factory.insertHeader()
    menuItems.insertHeader.hide()
    menuItems.removeHeader.show()
  }
  menuItems.insertFooter.onclick = function () {
    factory.insertFooter()
    menuItems.insertFooter.hide()
    menuItems.removeFooter.show()
  }
  menuItems.removeHeader.onclick = function () {
    factory.removeHeader()
    menuItems.insertHeader.show()
    menuItems.removeHeader.hide()
  }
  menuItems.removeFooter.onclick = function () {
    factory.removeFooter()
    menuItems.insertFooter.show()
    menuItems.removeFooter.hide()
  }
}
<commit_msg>reset and reinit menu items states in headers/footers are loaded fro mexisting elements<commit_after>'use strict'

/**
 * plugin.js
 *
 * Released under LGPL License.
 * Copyright (c) 2016 SIRAP Group All rights reserved
 *
 * License: http://www.tinymce.com/license
 * Contributing: http://www.tinymce.com/contributing
 */

/**
 * plugin.js Tinymce plugin headersfooters
 * @file plugin.js
 * @module
 * @name tinycmce-plugin-headersfooters
 * @description A plugin for tinymce WYSIWYG HTML editor that allow to insert headers and footers - requires tinymce-plugin-paginate.
 * @link https://github.com/sirap-group/tinymce-plugin-headersfooters
 * @author Rémi Becheras
 * @author Groupe SIRAP
 * @license GNU GPL-v2 http://www.tinymce.com/license
 * @version 1.0.0
 */

/**
 * Tinymce library - injected by the plugin loader.
 * @external tinymce
 * @see {@link https://www.tinymce.com/docs/api/class/tinymce/|Tinymce API Reference}
 */
var tinymce = window.tinymce

/**
 * The jQuery plugin namespace - plugin dependency.
 * @external "jQuery.fn"
 * @see {@link http://learn.jquery.com/plugins/|jQuery Plugins}
 */
var $ = window.jQuery

var HeaderFooterFactory = require('./classes/HeaderFooterFactory')
var ui = require('./utils/ui')

// Add the plugin to the tinymce PluginManager
tinymce.PluginManager.add('headersfooters', tinymcePluginHeadersFooters)

/**
 * Tinymce plugin headers/footers
 * @function
 * @global
 * @param {tinymce.Editor} editor - The injected tinymce editor.
 * @returns void
 */
function tinymcePluginHeadersFooters (editor, url) {
  var headerFooterFactory

  // add menu items
  editor.addMenuItem('insertHeader', ui.menuItems.insertHeader)
  editor.addMenuItem('removeHeader', ui.menuItems.removeHeader)
  editor.addMenuItem('insertFooter', ui.menuItems.insertFooter)
  editor.addMenuItem('removeFooter', ui.menuItems.removeFooter)

  editor.on('init', onInitHandler)
  editor.on('SetContent', onSetContent)

  /**
   * On init event handler. Instanciate the factory and initialize menu items states
   * @function
   * @inner
   * @returns void
   */
  function onInitHandler () {
    headerFooterFactory = new HeaderFooterFactory(editor)
    initMenuItems(headerFooterFactory, ui.menuItems)
  }

  /**
   * On SetContent event handler. Load or reload headers and footers from existing elements if it should do.
   * @function
   * @inner
   * @returns void
   */
  function onSetContent (evt) {
    // var $bodyElmt = $('body', editor.getDoc())
    var content = $(editor.getBody()).html()
    var emptyContent = '

'
    if (content && content !== emptyContent) {
      if (headerFooterFactory) {
        reloadHeadFoots()
      } else {
        setTimeout(reloadHeadFoots, 100)
      }
    }
  }

  /**
   * Helper function. Do the reload of headers and footers
   * @function
   * @inner
   * @returns void
   */
  function reloadHeadFoots () {
    var $headFootElmts = $('*[data-headfoot]', editor.getDoc())

    // init starting states
    ui.menuItems.insertHeader.show()
    ui.menuItems.insertFooter.show()
    ui.menuItems.removeHeader.hide()
    ui.menuItems.removeFooter.hide()

    // set another state and load elements if a header or a footer exists
    $headFootElmts.each(function (i, el) {
      var $el = $(el)
      if ($el.attr('data-headfoot-header')) {
        ui.menuItems.insertHeader.hide()
        ui.menuItems.removeHeader.show()
      } else if ($el.attr('data-headfoot-footer')) {
        ui.menuItems.insertFooter.hide()
        ui.menuItems.removeFooter.show()
      }
      headerFooterFactory.loadElement(el)
    })
  }
}

/**
 * Initialize menu items states (show, hide, ...) and implements onclick handlers
 * @function
 * @inner
 * @param {HeaderFooterFactory} factory The header and footer factory
 * @param {object} menuItems The set of plugin's menu items
 * @returns undefined
 */
function initMenuItems (factory, menuItems) {
  // on startup, hide remove buttons
  menuItems.removeHeader.hide()
  menuItems.removeFooter.hide()

  // override insertHeader, insertFooter, removeHeader and removeFooter onclick handlers
  menuItems.insertHeader.onclick = function () {
    factory.insertHeader()
    menuItems.insertHeader.hide()
    menuItems.removeHeader.show()
  }
  menuItems.insertFooter.onclick = function () {
    factory.insertFooter()
    menuItems.insertFooter.hide()
    menuItems.removeFooter.show()
  }
  menuItems.removeHeader.onclick = function () {
    factory.removeHeader()
    menuItems.insertHeader.show()
    menuItems.removeHeader.hide()
  }
  menuItems.removeFooter.onclick = function () {
    factory.removeFooter()
    menuItems.insertFooter.show()
    menuItems.removeFooter.hide()
  }
}
<|endoftext|>


<commit_before>var express = require("express")
var app = express();
var models = require("./models")
var bodyParser = require("body-parser")
app.use(bodyParser.urlencoded({extended:true}))
app.use(bodyParser.json())
app.use(function(req,res,next){
    res.append("Access-Control-Allow-Origin","*")
    res.append("Access-Control-Allow-Method","GET, POST, OPTIONS");
    res.append("Access-Control-Allow-Headers","X-Kyoppie-Access-Token");
    res.append("Access-Control-Max-Age","86400")
    next();
})

var routes = require("./routes")
routes.forEach(function(route){
    var login = true;
    if(route.login !== undefined) login = route.login;
    var method = route.method;
    var path = route.name;
    app[method](path,function(req,res,next){
        if(req.headers["x-kyoppie-access-token"]){
            models.access_tokens.findOne({
                secret:req.headers["x-kyoppie-access-token"]
            }).populate("app user").then(function(token){
                if(token){
                    req.token=token;
                }
                next();
            },function(){
                res.status(500).send({response:false,error:"server-side-auth-error"})
            })
        } else {
            next();
        }
    },require("./handlers/web"+path));
})
app.all("*",function(req,res){
    // not found
    res.status(404).send({result:false,error:"not-found-api"})
})
app.listen(4005,function(){
    console.log("listen for 4005 port");
})<commit_msg>login check<commit_after>var express = require("express")
var app = express();
var models = require("./models")
var bodyParser = require("body-parser")
app.use(bodyParser.urlencoded({extended:true}))
app.use(bodyParser.json())
app.use(function(req,res,next){
    res.append("Access-Control-Allow-Origin","*")
    res.append("Access-Control-Allow-Method","GET, POST, OPTIONS");
    res.append("Access-Control-Allow-Headers","X-Kyoppie-Access-Token");
    res.append("Access-Control-Max-Age","86400")
    next();
})

var routes = require("./routes")
routes.forEach(function(route){
    var login = true;
    if(route.login !== undefined) login = route.login;
    var method = route.method;
    var path = route.name;
    app[method](path,function(req,res,next){
        if(req.headers["x-kyoppie-access-token"]){
            models.access_tokens.findOne({
                secret:req.headers["x-kyoppie-access-token"]
            }).populate("app user").then(function(token){
                if(token){
                    req.token=token;
                }
                next();
            },function(){
                res.status(500).send({response:false,error:"server-side-auth-error"})
            })
        } else {
            next();
        }
    },function(req,res,next){
        if(login && !req.token){
            res.status(403).send({response:false,error:"please-login"})
        } else {
            next();
        }
    },require("./handlers/web"+path));
})
app.all("*",function(req,res){
    // not found
    res.status(404).send({result:false,error:"not-found-api"})
})
app.listen(4005,function(){
    console.log("listen for 4005 port");
})<|endoftext|>


<commit_before>const path = require('path')
const cp = require('child_process')
const uuid = require('uuid')
const assert = require('assert')
const debug = require('debug')('main')

const Writable = require('stream').Writable
const pyPath = path.join(__dirname, '..', 'etc', 'run.py')

function createWritable(data) {
    const writable = new Writable()
    writable._write = (chunk, encoding, callback) => {
        data.push(String(chunk))
        callback(null)
    }
    return writable
}

function spawnPython(resolve, reject, logStreams) {
    assert(Array.isArray(logStreams), 'Log streams should be an array')

    const python = cp.spawn('python', [pyPath])
    const data = []
    const errData = []

    if (Array.isArray(logStreams)) {
        debug(logStreams.map(ws =>
            ((typeof ws === 'object' && 'path' in ws) ? ws.path : ws)
        ))
        if (logStreams.length && logStreams[0] instanceof Writable) python.stdout.pipe(logStreams[0])
        if (logStreams.length > 1 && logStreams[2] instanceof Writable)python.stderr.pipe(logStreams[1])
    }

    const stdoutDrain = createWritable(data)
    const stderrDrain = createWritable(errData)

    python.stdout
        .pipe(stdoutDrain)

    python.stderr
        .pipe(stderrDrain)

    python.on('exit', (code) => {
        if (code !== 0) {
            return reject(getPythonExitError(errData, code))
        }
        return resolve(data.join().trim())
    })
}

function getPythonExitError(errData, code) {
    const title = `Process exited with code ${code}`
    const message = errData.join().trim()
    const error = new Error()
    error.title = title
    error.message = message
    return error
}

function getWindowsWithPython(logStreams) {
    return new Promise((resolve, reject) =>
        spawnPython(resolve, reject, logStreams)
    )
        .then(JSON.parse)
}

function screencapture(windowId, dir, format, index, cursor, noShadow) {
    assert(windowId)
    assert(dir)
    const extension = typeof format === 'string' ? format : 'png'
    const allowedFormats = ['jpg', 'png']
    try {
        assert(allowedFormats.indexOf(extension) !== -1)
    } catch (err) {
        const error = new Error()
        error.message = `Format ${format} not allowed. Allowed formats are: ${
            allowedFormats.join(', ')
        }`
        return Promise.reject(error)
    }

    const filename = path.join(dir, (index ? String(index) : uuid.v4()))
    const fullFilename = `${filename}.${extension}`
    debug(fullFilename)

    const customArgs = []
    if (format) {
        customArgs.push('-t')
        customArgs.push(extension)
    }
    if (cursor) {
        customArgs.push('-C')
    }
    if (noShadow) {
        customArgs.push('-o')
    }
    const args = [`-l${windowId}`, fullFilename]
    const allArgs = [].concat(customArgs, args)
    debug(allArgs)

    return new Promise((resolve, reject) => {
        // add code here to run exec
        const screencapture = cp.spawn('screencapture', allArgs)
        const data = []
        screencapture.stdout.on('data', (chunk) => {
            data.push(String(chunk))
        })
        screencapture.stdout.pipe(process.stdout)
        screencapture.stderr.pipe(process.stderr)
        screencapture.on('exit', () => resolve(fullFilename))
    })
}

// data from python script comes in a form of JSON array, like
// add example here
function parseArray(arr) {
    return {
        winid: arr[0],
        app: arr[1],
        title: arr[2],
        pid: arr[3],
    }
}

function getWindows(app, title, logStreams) {
    return getWindowsWithPython(logStreams)
        .then(windows => windows.map(parseArray))
        .then(windowsAsObjects => windowsAsObjects
            .filter((win) => {
                if (typeof app !== 'string') return true
                return win.app.toLowerCase().indexOf(app.toLowerCase()) !== -1
            })
            .filter((win) => {
                if (typeof title !== 'string') return true
                return win.title.toLowerCase().indexOf(title.toLowerCase()) !== -1
            })
        )
}

function main(dir, winName, title, format) {
    assert(dir)
    const screenshots = []
    return getWindows(winName, title)
        .then((res) => {
            assert(res.length, 'No windows found')
            debug('Found windows:', res)
            return Promise.all(res.map(win =>
                screencapture(win.winid, dir, format)
            ))
        })
}

module.exports = main

// run2 interface
main.getWindows = (app, title, logStreams) => getWindows(app, title, logStreams)
main.screenshotById = (winId, dir, index, cursor, format, noShadow) => screencapture(winId, dir, format, index, cursor, noShadow)

<commit_msg>make logStderr work<commit_after>const path = require('path')
const cp = require('child_process')
const uuid = require('uuid')
const assert = require('assert')
const debug = require('debug')('main')

const Writable = require('stream').Writable
const pyPath = path.join(__dirname, '..', 'etc', 'run.py')

function createWritable(data) {
    const writable = new Writable()
    writable._write = (chunk, encoding, callback) => {
        data.push(String(chunk))
        callback(null)
    }
    return writable
}

function spawnPython(resolve, reject, logStreams) {
    assert(Array.isArray(logStreams), 'Log streams should be an array')

    const python = cp.spawn('python', [pyPath])
    const data = []
    const errData = []

    if (Array.isArray(logStreams)) {
        if (logStreams.length && logStreams[0] instanceof Writable) python.stdout.pipe(logStreams[0])
        if (logStreams.length > 1 && logStreams[1] instanceof Writable)python.stderr.pipe(logStreams[1])
    }

    const stdoutDrain = createWritable(data)
    const stderrDrain = createWritable(errData)

    python.stdout
        .pipe(stdoutDrain)

    python.stderr
        .pipe(stderrDrain)

    python.on('exit', (code) => {
        if (code !== 0) {
            return reject(getPythonExitError(errData, code))
        }
        return resolve(data.join().trim())
    })
}

function getPythonExitError(errData, code) {
    const title = `Process exited with code ${code}`
    const message = errData.join().trim()
    const error = new Error()
    error.title = title
    error.message = message
    return error
}

function getWindowsWithPython(logStreams) {
    return new Promise((resolve, reject) =>
        spawnPython(resolve, reject, logStreams)
    )
        .then(JSON.parse)
}

function screencapture(windowId, dir, format, index, cursor, noShadow) {
    assert(windowId)
    assert(dir)
    const extension = typeof format === 'string' ? format : 'png'
    const allowedFormats = ['jpg', 'png']
    try {
        assert(allowedFormats.indexOf(extension) !== -1)
    } catch (err) {
        const error = new Error()
        error.message = `Format ${format} not allowed. Allowed formats are: ${
            allowedFormats.join(', ')
        }`
        return Promise.reject(error)
    }

    const filename = path.join(dir, (index ? String(index) : uuid.v4()))
    const fullFilename = `${filename}.${extension}`
    debug(fullFilename)

    const customArgs = []
    if (format) {
        customArgs.push('-t')
        customArgs.push(extension)
    }
    if (cursor) {
        customArgs.push('-C')
    }
    if (noShadow) {
        customArgs.push('-o')
    }
    const args = [`-l${windowId}`, fullFilename]
    const allArgs = [].concat(customArgs, args)
    debug(allArgs)

    return new Promise((resolve, reject) => {
        // add code here to run exec
        const screencapture = cp.spawn('screencapture', allArgs)
        const data = []
        screencapture.stdout.on('data', (chunk) => {
            data.push(String(chunk))
        })
        screencapture.stdout.pipe(process.stdout)
        screencapture.stderr.pipe(process.stderr)
        screencapture.on('exit', () => resolve(fullFilename))
    })
}

// data from python script comes in a form of JSON array, like
// add example here
function parseArray(arr) {
    return {
        winid: arr[0],
        app: arr[1],
        title: arr[2],
        pid: arr[3],
    }
}

function getWindows(app, title, logStreams) {
    return getWindowsWithPython(logStreams)
        .then(windows => windows.map(parseArray))
        .then(windowsAsObjects => windowsAsObjects
            .filter((win) => {
                if (typeof app !== 'string') return true
                return win.app.toLowerCase().indexOf(app.toLowerCase()) !== -1
            })
            .filter((win) => {
                if (typeof title !== 'string') return true
                return win.title.toLowerCase().indexOf(title.toLowerCase()) !== -1
            })
        )
}

function main(dir, winName, title, format) {
    assert(dir)
    const screenshots = []
    return getWindows(winName, title)
        .then((res) => {
            assert(res.length, 'No windows found')
            debug('Found windows:', res)
            return Promise.all(res.map(win =>
                screencapture(win.winid, dir, format)
            ))
        })
}

module.exports = main

// run2 interface
main.getWindows = (app, title, logStreams) => getWindows(app, title, logStreams)
main.screenshotById = (winId, dir, index, cursor, format, noShadow) => screencapture(winId, dir, format, index, cursor, noShadow)

<|endoftext|>


<commit_before>import craftai from 'craft-ai-client-js';
import loadCfg from './loadCfg';

loadCfg()
  .then(config => craftai(config))
  .then(instance => {
    console.log(`'${instance.id}' successfully created!`);
    return instance.createAgent('bts/hello_world.bt', {name: 'juliette'})
      .then(agent => console.log(`agent #${agent.id} created.`))
      .then(() => instance.createAgent('bts/hello_world.bt', {name: 'romeo'}))
      .then(agent => console.log(`agent #${agent.id} created.`))
      .then(() => instance.registerAction(
        'HelloWorld',
        (requestId, agentId, input, success, failure) => {
          console.log(`#${agentId}: "Hello World!"`);
          success();
        }))
      .then(() => instance.registerAction(
        'SayMyName',
        (requestId, agentId, input, success, failure) => {
          console.log(`#${agentId}: "My name is ${input.name}."`);
          success();
        }))
      .then(() => instance.update(500))
      .catch((err) => {
        console.log(`Error during the instance lifetime, check 'https://workbench.craft.ai/instances/${instance.cfg.owner}/${instance.cfg.name}/${instance.cfg.version}/${instance.id}/monitor' for further information.`);
        console.log(err);
      });
  })
  .catch((err) => {
    console.log(`Error during instance creation.`);
    console.log(err);
  });
<commit_msg>Correcting the import of craft-ai<commit_after>import craftai from 'craft-ai';
import loadCfg from './loadCfg';

loadCfg()
  .then(config => craftai(config))
  .then(instance => {
    console.log(`'${instance.id}' successfully created!`);
    return instance.createAgent('bts/hello_world.bt', {name: 'juliette'})
      .then(agent => console.log(`agent #${agent.id} created.`))
      .then(() => instance.createAgent('bts/hello_world.bt', {name: 'romeo'}))
      .then(agent => console.log(`agent #${agent.id} created.`))
      .then(() => instance.registerAction(
        'HelloWorld',
        (requestId, agentId, input, success, failure) => {
          console.log(`#${agentId}: "Hello World!"`);
          success();
        }))
      .then(() => instance.registerAction(
        'SayMyName',
        (requestId, agentId, input, success, failure) => {
          console.log(`#${agentId}: "My name is ${input.name}."`);
          success();
        }))
      .then(() => instance.update(500))
      .catch((err) => {
        console.log(`Error during the instance lifetime, check 'https://workbench.craft.ai/instances/${instance.cfg.owner}/${instance.cfg.name}/${instance.cfg.version}/${instance.id}/monitor' for further information.`);
        console.log(err);
      });
  })
  .catch((err) => {
    console.log(`Error during instance creation.`);
    console.log(err);
  });
<|endoftext|>


<commit_before>var idCounter=0;
function generateId() {
	return 'statistics-classification-binary-id-'+(idCounter++);
}

$('.statistics-classification-binary').each(function(){
	var containerNode=$(this);
	var htmlOptions={
		heading: this.nodeName=='SECTION',
		lang: containerNode.closest('[lang]').attr('lang'),
		storage: containerNode.attr('data-storage'),
	};
	var codeOptions={};
	if (htmlOptions.storage && localStorage[htmlOptions.storage]) {
		codeOptions=JSON.parse(localStorage[htmlOptions.storage]);
	}
	var options=getOptions(htmlOptions,codeOptions);
	containerNode.html(generateHtml(options));

	function applyCodeOptions() {
		containerNode.find('table').replaceWith(generateCodeTable(options));
		if (options.html.storage) {
			localStorage[options.html.storage]=JSON.stringify(options.code);
		}
	}
	function showHideSuboptionInputs(optionName,optionValue) {
		containerNode.find(".code-options [data-option^='"+optionName+".']").show()
			.not("[data-option^='"+optionName+"."+optionValue+".']").hide();
	}
	function createOptionInput(optionName) {
		function openClose(inputTag) {
			return $(inputTag).on('input',function(){
				options.code[optionName]=this.value;
				applyCodeOptions();
			});
		}
		function select(){
			return $("<select>").append(options.code[optionName+'AvailableValues'].map(function(optionAvailableValue){
				return $("<option>").val(optionAvailableValue).html(options.i18n('options.code.'+optionName+'.'+optionAvailableValue));
			})).on('change',function(){
				options.code[optionName]=this.value;
				showHideSuboptionInputs(optionName,this.value);
				applyCodeOptions();
			});
		}
		if (optionName=='postprocess') {
			return openClose("<textarea spellcheck='false'>");
		} else if (optionName=='split') {
			return select();
		} else if (optionName=='splitRandomSeed') {
			return openClose("<input type='number'>");
		} else if (optionName=='splitRandomRatio' || optionName=='threshold') {
			return openClose("<input type='number' min='0' max='1' step='any'>");
		} else {
			return openClose("<input type='text'>");
		}
	}
	// all inputs with restored/default values
	containerNode.find('.code-options [data-option]').each(function(){
		// TODO why parsing out stuff when can just regenerate with inputs instead of generateHtml() with static html?
		var div=$(this);
		var id=generateId();
		var label=div.find('.label');
		var labelTitle=label.attr('title');
		var newLabel=$(""+label.html()+"");
		if (labelTitle) {
			newLabel.attr('title',labelTitle);
		}
		label.replaceWith(newLabel);
		var code=div.find('code');
		code.replaceWith(
			createOptionInput(div.attr('data-option')).attr('id',id).val(code.text())
		);
	});
	// hide inputs related to options that are not selected
	containerNode.find('.code-options [data-option]').each(function(){
		var div=$(this);
		var select=div.find('select');
		if (select.length) {
			showHideSuboptionInputs(div.attr('data-option'),select.val());
		}
	});
	containerNode.find('.code-options').append(
		$("
").append(
			$("<button type='button'>"+options.i18n('Reset options')+"</button>").click(function(){
				options.code.reset();
				containerNode.find('.code-options [data-option]').each(function(){
					var div=$(this);
					var optionName=div.attr('data-option');
					div.find('input').each(function(){
						this.value=options.code[optionName];
					});
				});
				applyCodeOptions();
			})
		)
	);
});
<commit_msg>restored type='number' on some inputs<commit_after>var idCounter=0;
function generateId() {
	return 'statistics-classification-binary-id-'+(idCounter++);
}

$('.statistics-classification-binary').each(function(){
	var containerNode=$(this);
	var htmlOptions={
		heading: this.nodeName=='SECTION',
		lang: containerNode.closest('[lang]').attr('lang'),
		storage: containerNode.attr('data-storage'),
	};
	var codeOptions={};
	if (htmlOptions.storage && localStorage[htmlOptions.storage]) {
		codeOptions=JSON.parse(localStorage[htmlOptions.storage]);
	}
	var options=getOptions(htmlOptions,codeOptions);
	containerNode.html(generateHtml(options));

	function applyCodeOptions() {
		containerNode.find('table').replaceWith(generateCodeTable(options));
		if (options.html.storage) {
			localStorage[options.html.storage]=JSON.stringify(options.code);
		}
	}
	function showHideSuboptionInputs(optionName,optionValue) {
		containerNode.find(".code-options [data-option^='"+optionName+".']").show()
			.not("[data-option^='"+optionName+"."+optionValue+".']").hide();
	}
	function createOptionInput(optionName) {
		function openClose(inputTag) {
			return $(inputTag).on('input',function(){
				options.code[optionName]=this.value;
				applyCodeOptions();
			});
		}
		function select(){
			return $("<select>").append(options.code[optionName+'AvailableValues'].map(function(optionAvailableValue){
				return $("<option>").val(optionAvailableValue).html(options.i18n('options.code.'+optionName+'.'+optionAvailableValue));
			})).on('change',function(){
				options.code[optionName]=this.value;
				showHideSuboptionInputs(optionName,this.value);
				applyCodeOptions();
			});
		}
		if (optionName=='postprocess') {
			return openClose("<textarea spellcheck='false'>");
		} else if (optionName=='split') {
			return select();
		} else if (optionName=='split.random.seed') {
			return openClose("<input type='number'>");
		} else if (optionName=='split.random.ratio' || optionName=='threshold') {
			return openClose("<input type='number' min='0' max='1' step='any'>");
		} else {
			return openClose("<input type='text'>");
		}
	}
	// all inputs with restored/default values
	containerNode.find('.code-options [data-option]').each(function(){
		// TODO why parsing out stuff when can just regenerate with inputs instead of generateHtml() with static html?
		var div=$(this);
		var id=generateId();
		var label=div.find('.label');
		var labelTitle=label.attr('title');
		var newLabel=$(""+label.html()+"");
		if (labelTitle) {
			newLabel.attr('title',labelTitle);
		}
		label.replaceWith(newLabel);
		var code=div.find('code');
		code.replaceWith(
			createOptionInput(div.attr('data-option')).attr('id',id).val(code.text())
		);
	});
	// hide inputs related to options that are not selected
	containerNode.find('.code-options [data-option]').each(function(){
		var div=$(this);
		var select=div.find('select');
		if (select.length) {
			showHideSuboptionInputs(div.attr('data-option'),select.val());
		}
	});
	containerNode.find('.code-options').append(
		$("
").append(
			$("<button type='button'>"+options.i18n('Reset options')+"</button>").click(function(){
				options.code.reset();
				containerNode.find('.code-options [data-option]').each(function(){
					var div=$(this);
					var optionName=div.attr('data-option');
					div.find('input').each(function(){
						this.value=options.code[optionName];
					});
				});
				applyCodeOptions();
			})
		)
	);
});
<|endoftext|>


<commit_before>$(document).ready(function(){
	MIDI.loadPlugin({
		soundfontUrl: "./soundfont/",
		instrument: "acoustic_grand_piano",
		callback: function() {

			// play the note
			MIDI.setVolume(0, 127);
			$('#button').click(function(e) {
							var delay = 0; // play one note every quarter second
					var note = 50; // the MIDI note
					var velocity = 127; // how hard the note hits

				console.log('hey');
				MIDI.noteOn(0, note, velocity, delay);
				MIDI.noteOn(0, note+4, velocity, delay);
				MIDI.noteOn(0, note+7, velocity, delay);
				MIDI.noteOn(0, note+12, velocity, delay);
				MIDI.noteOff(0, note, delay + 5);
				MIDI.noteOff(0, note+4, delay + 5);
				MIDI.noteOff(0, note+7, delay + 5);
				MIDI.noteOff(0, note+12, delay + 5);
			});

			MIDI.setReverbImpulseResponse('./ir/spatialized7.wav');

			function playNote(data) {
				var pitch = get_note_from_scale(data.note, 'pentatonic');
				console.log(pitch);
				MIDI.noteOn(0, pitch, data.velocity, 0);
				MIDI.noteOff(0, pitch, data.duration);
			}

			window.addEventListener("message", function(event) {
				playNote(event.data);
			});
		}
	});

});<commit_msg>src js changes idfk<commit_after>var synth;

$(document).ready(function(){
	MIDI.loadPlugin({
		soundfontUrl: "./soundfont/",
		instrument: "acoustic_grand_piano",
		callback: function() {

			MIDI.setReverbImpulseResponse('./ir/spatialized7.wav');

			function playNote(data) {
				var pitch = get_note_from_scale(data.note, 'pentatonic');
				MIDI.noteOn(0, pitch, data.velocity, 0);
				MIDI.noteOff(0, pitch, data.duration);
			}

			window.addEventListener("message", function(event) {
				playNote(event.data);
			});
		}
	});

  var audioContext = new webkitAudioContext();
  audioContext.sampleRate = 44100;

  synth = new MonoSynth(audioContext);

  synth.noteOn('C2', 0.05);

  setTimeout(changeBassNote, 12000);

});

var bassNotes = ['C2', 'D2', 'E2', 'G2', 'C3'];

function changeBassNote() {
	var note = bassNotes[Math.floor(Math.random()*bassNotes.length)];
	synth.noteSlide(note, 0.05);
	setTimeout(changeBassNote, 12000);
}<|endoftext|>


<commit_before>
var https = require('https');
var express = require("express");
var bodyParser = require("body-parser");
var macaroons = require('macaroons.js');
var macaroonVerifier = require('./macaroon-verifier.js');

// A request wrapper that inserts the container mangers root cert and
// arbiter api key into GET and POST requests
var request = require('./lib/databox-request/databox-request.js')();

const DATABOX_LOCAL_NAME = process.env.DATABOX_LOCAL_NAME || "databox-store-blob";

const DATABOX_ARBITER_ENDPOINT = process.env.DATABOX_ARBITER_ENDPOINT || "https://databox-arbiter:8080"

//HTTPS certs created by the container mangers for this components HTTPS server.
const HTTPS_CLIENT_CERT = process.env.HTTPS_CLIENT_CERT || '';
const HTTPS_CLIENT_PRIVATE_KEY = process.env.HTTPS_CLIENT_PRIVATE_KEY || '';
const credentials = {
	key:  HTTPS_CLIENT_PRIVATE_KEY,
	cert: HTTPS_CLIENT_CERT,
};

// TODO: Refactor token to key here and in CM to avoid confusion with bearer tokens
var ARBITER_KEY = process.env.ARBITER_TOKEN;
var NO_SECURITY = !!process.env.NO_SECURITY;

//ENDPOINTs
var timeseriesRouter = require('./timeseries.js');
var keyValueRouter = require('./keyvalue.js');
var actuateRouter = require('./actuate.js');
var hypercat = require('./lib/hypercat/hypercat.js');

var app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

/*
* DATABOX API Logging
* Logs all requests and responses to/from the API in bunyan format in nedb
*/
var logsDb = require('./lib/log/databox-log-db.js')('../database/datastoreLOG.db');
var databoxLoggerApi = require('./lib/log/databox-log-api.js');
var databoxLogger = require('./lib/log/databox-log-middelware.js')(logsDb);
app.use(databoxLogger);

var server = null;
if(credentials.cert === '' || credentials.key === '') {
    var http = require('http');
    console.log("WARNING NO HTTPS credentials supplied running in http mode!!!!");
    server = http.createServer(app);
} else {
    server = https.createServer(credentials,app);
}

app.get("/status", function(req, res) {
    res.send("active");

});

app.get("/api/status", function(req, res) {
    res.send("active");
});

app.use('/api/cat',hypercat(app));

app.use('/logs',databoxLoggerApi(app,logsDb));

app.use('/api/actuate',actuateRouter(app));

app.use('/:var(api/data|api/ts)?',timeseriesRouter(app));

app.use('/api/key',keyValueRouter(app));

//Register with arbiter and get secret
macaroonVerifier.getSecretFromArbiter(ARBITER_KEY)

	.then((secret) => {
		// TODO: Clean up

		if (!NO_SECURITY)
			app.use(macaroonVerifier.verifier(secret, DATABOX_LOCAL_NAME));

		//Websocket connection to live stream data
        var WebSocketServer = require('ws').Server;
        app.wss = new WebSocketServer({ server: server, verifyClient: macaroonVerifier.wsVerifier(secret, DATABOX_LOCAL_NAME) });
        app.broadcastDataOverWebSocket = require('./lib/websockets/broadcastDataOverWebSocket.js')(app);

		server.listen(8080, function () {
            console.log("listening on port 8080");
        });
	})

	.catch((err) => {
		console.log(err);
	});

module.exports = app;
<commit_msg>macaroonVerifier must be added befor endpoints<commit_after>
var https = require('https');
var express = require("express");
var bodyParser = require("body-parser");
var macaroons = require('macaroons.js');
var macaroonVerifier = require('./macaroon-verifier.js');

// A request wrapper that inserts the container mangers root cert and
// arbiter api key into GET and POST requests
var request = require('./lib/databox-request/databox-request.js')();

const DATABOX_LOCAL_NAME = process.env.DATABOX_LOCAL_NAME || "databox-store-blob";

const DATABOX_ARBITER_ENDPOINT = process.env.DATABOX_ARBITER_ENDPOINT || "https://databox-arbiter:8080"

//HTTPS certs created by the container mangers for this components HTTPS server.
const HTTPS_CLIENT_CERT = process.env.HTTPS_CLIENT_CERT || '';
const HTTPS_CLIENT_PRIVATE_KEY = process.env.HTTPS_CLIENT_PRIVATE_KEY || '';
const credentials = {
	key:  HTTPS_CLIENT_PRIVATE_KEY,
	cert: HTTPS_CLIENT_CERT,
};

// TODO: Refactor token to key here and in CM to avoid confusion with bearer tokens
var ARBITER_KEY = process.env.ARBITER_TOKEN;
var NO_SECURITY = !!process.env.NO_SECURITY;

//ENDPOINTs
var timeseriesRouter = require('./timeseries.js');
var keyValueRouter = require('./keyvalue.js');
var actuateRouter = require('./actuate.js');
var hypercat = require('./lib/hypercat/hypercat.js');

var app = express();

//Register with arbiter and get secret
macaroonVerifier.getSecretFromArbiter(ARBITER_KEY)

	.then((secret) => {
		// TODO: Clean up

		app.use(bodyParser.json());
		app.use(bodyParser.urlencoded({extended: true}));

		if (!NO_SECURITY)
			//everything after here will require a valid macaroon
			app.use(macaroonVerifier.verifier(secret, DATABOX_LOCAL_NAME));

		/*
		* DATABOX API Logging
		* Logs all requests and responses to/from the API in bunyan format in nedb
		*/
		var logsDb = require('./lib/log/databox-log-db.js')('../database/datastoreLOG.db');
		var databoxLoggerApi = require('./lib/log/databox-log-api.js');
		var databoxLogger = require('./lib/log/databox-log-middelware.js')(logsDb);
		app.use(databoxLogger);

		var server = null;
		if(credentials.cert === '' || credentials.key === '') {
			var http = require('http');
			console.log("WARNING NO HTTPS credentials supplied running in http mode!!!!");
			server = http.createServer(app);
		} else {
			server = https.createServer(credentials,app);
		}

		app.get("/status", function(req, res) {
			res.send("active");

		});

		app.get("/api/status", function(req, res) {
			res.send("active");
		});

		app.use('/api/cat',hypercat(app));

		app.use('/logs',databoxLoggerApi(app,logsDb));

		app.use('/api/actuate',actuateRouter(app));

		app.use('/:var(api/data|api/ts)?',timeseriesRouter(app));

		app.use('/api/key',keyValueRouter(app));

		//Websocket connection to live stream data
        var WebSocketServer = require('ws').Server;
        app.wss = new WebSocketServer({ server: server, verifyClient: macaroonVerifier.wsVerifier(secret, DATABOX_LOCAL_NAME) });
        app.broadcastDataOverWebSocket = require('./lib/websockets/broadcastDataOverWebSocket.js')(app);

		server.listen(8080, function () {
            console.log("listening on port 8080");
        });
	})

	.catch((err) => {
		console.log(err);
	});

module.exports = app;
<|endoftext|>


<commit_before>MG.init = function () {
    MG.fog.init();
    MG.banner.init();
    MG.game.init();
    MG.hud.init();

    document.addEventListener('mousemove', function(evt){
            MG.game.onMouseMove(evt.clientX, evt.clientY);
        }, false);

    window.addEventListener('mousedown', MG.game.onMouseClick, false);

    var lastTick = 0;

    var update = function (dt) {
        MG.fog.update(dt);
        MG.game.update(dt);
        MG.hud.update(dt);
        MG.banner.update(dt);

        MG.fog.updateDOM();
        MG.game.updateDOM();
        MG.hud.updateDOM();
        MG.banner.updateDOM();
    }

    var mainLoop = function(thisTick) {
        thisTick = thisTick || 0;
        var dt = (thisTick - lastTick)/1000;
        // pretend that the frame rate is actually higher if it drops below
        // 10fps in order to avoid wierdness
        if (dt > 1/10) {
            dt = 1/10;
        }

        lastTick = thisTick;

        update(dt);

        window.requestAnimationFrame(mainLoop);
    }

    mainLoop();
}

MG.init();
<commit_msg>workaround for old qt webkit `requestAnimationFrame`<commit_after>MG.init = function () {
    MG.fog.init();
    MG.banner.init();
    MG.game.init();
    MG.hud.init();

    document.addEventListener('mousemove', function(evt){
            MG.game.onMouseMove(evt.clientX, evt.clientY);
        }, false);

    window.addEventListener('mousedown', MG.game.onMouseClick, false);

    var update = function (dt) {
        MG.fog.update(dt);
        MG.game.update(dt);
        MG.hud.update(dt);
        MG.banner.update(dt);

        MG.fog.updateDOM();
        MG.game.updateDOM();
        MG.hud.updateDOM();
        MG.banner.updateDOM();
    }

    var lastTick = 0;
    var zeroCounter = 0;
    var useFallback = false;

    if (!window.requestAnimationFrame) {
        useFallback = true;
    }

    var mainLoop = function(thisTick) {
        var dt;

        // Some browsers don't pass in a time.  If `thisTick` isn't set for
        //  more than a few frames fall back to `setTimeout`
        if (!thisTick) {
            zeroCounter += 1;
        } else {
            zeroCounter = 0;
        }
        if (zeroCounter > 10) {
            useFallback = true;
        }

        thisTick = thisTick || 0;
        if (useFallback) {
            dt = 1/30;
        } else {
            var dt = (thisTick - lastTick)/1000;
        }
        // pretend that the frame rate is actually higher if it drops below
        // 10fps in order to avoid wierdness
        if (dt > 1/10) {
            dt = 1/10;
        }

        lastTick = thisTick;

        update(dt);

        if (useFallback) {
            window.setTimeout(mainLoop, 1000 / 30);
        } else {
            window.requestAnimationFrame(mainLoop);
        }
    }

    mainLoop();
}

MG.init();
<|endoftext|>


<commit_before>const electron = require('electron')
const fs = require('fs')
const path = require('path')
const shell = require('electron').shell

const MarkdownRenderer = require('./renderer').MarkdownRenderer

const app = electron.app
const BrowserWindow = electron.BrowserWindow

let mainWindow

const reloadWindow = url => {
  mainWindow.loadURL(url)
}

const renderer = new MarkdownRenderer(reloadWindow)

const createWindow = () => {
  mainWindow = new BrowserWindow({title: 'MD Reader', autoHideMenuBar: true})

  var cssPath = '../node_modules/github-markdown-css/github-markdown.css'

  fs.readFile(path.join(__dirname, cssPath), 'utf8', (err, css) => {
    if (err) throw err

    mainWindow.webContents.on('did-finish-load', () => {
      mainWindow.webContents.insertCSS(css)
    })
  })

  var markdownFileName = process.argv[2]
  if (markdownFileName) {
    renderer.loadFile(markdownFileName)
    fs.watch(markdownFileName, () => {
      renderer.loadFile(markdownFileName)
    })
  } else {
    renderer.load('# Welcome in Mauve!\n\nDrag files here to view them')
  }

  mainWindow.webContents.on('will-navigate', handleRedirect)
  mainWindow.on('closed', () => {
    mainWindow = null
  })
}

app.on('ready', createWindow)

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (mainWindow === null) {
    createWindow()
  }
})

const handleRedirect = (e, url) => {
  e.preventDefault()
  if (/^file:\/\//.test(url)) {
    url = url.replace(/^file:\/\//, '')
    renderer.loadFile(url)
  }
  else if(url != mainWindow.webContents.getURL()) {
    shell.openExternal(url)
  }
}
<commit_msg>Reorder functions<commit_after>const electron = require('electron')
const fs = require('fs')
const path = require('path')
const shell = require('electron').shell

const MarkdownRenderer = require('./renderer').MarkdownRenderer

const app = electron.app
const BrowserWindow = electron.BrowserWindow

let mainWindow

const reloadWindow = url => {
  mainWindow.loadURL(url)
}

const renderer = new MarkdownRenderer(reloadWindow)

const createWindow = () => {
  mainWindow = new BrowserWindow({title: 'MD Reader', autoHideMenuBar: true})

  var cssPath = '../node_modules/github-markdown-css/github-markdown.css'

  fs.readFile(path.join(__dirname, cssPath), 'utf8', (err, css) => {
    if (err) throw err

    mainWindow.webContents.on('did-finish-load', () => {
      mainWindow.webContents.insertCSS(css)
    })
  })

  var markdownFileName = process.argv[2]
  if (markdownFileName) {
    renderer.loadFile(markdownFileName)
    fs.watch(markdownFileName, () => {
      renderer.loadFile(markdownFileName)
    })
  } else {
    renderer.load('# Welcome in Mauve!\n\nDrag files here to view them')
  }

  mainWindow.webContents.on('will-navigate', handleRedirect)
  mainWindow.on('closed', () => {
    mainWindow = null
  })
}

const handleRedirect = (e, url) => {
  e.preventDefault()
  if (/^file:\/\//.test(url)) {
    url = url.replace(/^file:\/\//, '')
    renderer.loadFile(url)
  }
  else if(url != mainWindow.webContents.getURL()) {
    shell.openExternal(url)
  }
}

app.on('ready', createWindow)

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (mainWindow === null) {
    createWindow()
  }
})
<|endoftext|>