<commit_before>'use strict'

var isNode = (typeof window === 'undefined');

var path, slash, child_process;

var requireHack = require;

if (isNode) {
  path = requireHack("path");
  slash = requireHack("slash");
  child_process = requireHack("child_process");
}

function send(receiver, message) {
  if (isNode) {
    receiver.send(message);
  } else {
    receiver.postMessage(message);
  }
}

function createProcess(script, cwd) {
  if (isNode) {
    let p = child_process.fork(path.join(process.cwd(), script), {
      cwd: toAbsPath(cwd),
      // pipe stdout/stderr into this process
      silent: true
    });

    // handle stdout of child
    p.stdout.on("data", (data) => {
      process.stdout.write(`[Indexing] (${cwd}) ${data}`);
    });

    // handle stderr of child
    p.stderr.on("data", (data) => {
      process.stderr.write(`[Indexing] (${cwd}) ${data}`);
    });

    return p;
  }

  // in Browser:
  return new Worker(script);
}

// Object that holds workers for server subdirectories,
// e.g. '/lively4-core'
var workers = {};
var indexStatus = {};

var promiseCallbacks = {};
var workerReadyPromise;
// rootFolder is an absolute directory to where the server serves,
// e.g. where the lively4-core folder is found
var rootFolder = null;
var idxFileName = "index.l4idx";

var curMsgId = 0;

// *** Exported methods ***

export function setRootFolder(filepath) {
  // becomes e.g. "C:/felix/bla" on Windows
  if (isNode) {
    rootFolder = slash(path.resolve(filepath));
  } else {
    rootFolder = filepath;
  }
}

export function startWorker(subdir) {
  return new Promise((resolve, reject) => {
    if (!rootFolder) {
      throw new Error("startWorker: no root folder set");
    }

    if (workers[subdir]) {
      console.log("[Indexing] Worker already exists");
      resolve();
      return;
    }

    console.log("[Indexing] Starting new worker for " + subdir);
    try {
      let script = isNode ? "./lively4-search/server/lunr-node-search-worker.js" : "./src/external/lively4-search/client/lunr-es6-search-worker-wrapper.js";
      workers[subdir] = createProcess(script, subdir);
    } catch (err) {
      console.log("[Indexing] Error starting new worker for " + subdir + ": " + err);
      reject(err);
      return;
    }

    let messageHandler = function(m) {
      // web workers hide the sent message behind the data key
      if (!isNode) {
        m = m.data;
      }
      switch (m.type) {
        case "worker-ready":
          resolve();
          break;
        case "search-response":
          handleSearchResponse(m.msgId, m.message);
          break;
        case "init-response":
          handleInitResponse(m.msgId, m.message, subdir);
          break;
        case "index-status-response":
          handleIndexStatusResponse(m.msgId, m.message, subdir);
          break;
        case "error":
          console.log("[Indexing] Error (" + subdir + "): " + m.message);
          break;
        default:
          console.log("[Indexing] Unknown message:", m);
      }
    }

    if (isNode) {
      workers[subdir].on("message", messageHandler);
    } else {
      workers[subdir].onmessage = messageHandler;
    }
  });
}

function stopWorker(subdir) {
  console.log("stop", subdir);
  send(workers[subdir], {
    type: "stop"
  });

  delete workers[subdir];
  delete indexStatus[subdir];
}

export function createIndex(subdir, options) {
  return startWorker(subdir).then(() => {
    return new Promise((resolve, reject) => {
      if (!rootFolder) {
        console.log("[Indexing] Cannot create index, no root folder set");
        reject("Error: no root folder set");
        return;
      }

      if (indexStatus[subdir] === "ready") {
        console.log("[Indexing] Index already exists");
        resolve();
        return;
      }

      if (indexStatus[subdir] === "indexing") {
        reject();
        return;
      }

      var msgId = getNextMsgId();
      promiseCallbacks[msgId] = {
        resolve: resolve,
        reject: reject
      };

      send(workers[subdir], {
        type: "init",
        msgId: msgId,
        options: options
      });

      indexStatus[subdir] = "indexing";
    });
  });
}

export function removeIndex(subdir, options) {
  return startWorker(subdir).then(() => {
    new Promise((resolve, reject) => {
      if (!rootFolder) {
        console.log("[Indexing] Cannot remove index, no root folder set");
        reject("Error: no root folder set");
        return;
      }

      send(workers[subdir], {
        type: "removeIndex"
      });

      // stopWorker(subdir);

      delete indexStatus[subdir];
    });
  });
}

export function setup(options) {
  return new Promise((resolve, reject) => {

    let fetchStatus =  () => {
      createIndex(options.path, options).then( () => {
        resolve();
        clearInterval(interval);
      }, () => {
        console.log("[Indexing] Waiting for index: " + options.name)
      });
    };

    fetchStatus();
    let interval = setInterval(fetchStatus, 5000);
  });
}

export function search(subdir, query) {
  if (!workers[subdir]) {
    console.log("[Indexing] Cannot search, no index created for " + subdir);
    return Promise.reject();
  }

  var msgId = getNextMsgId();
  promiseCallbacks[msgId] = {};

  var p = new Promise((resolve, reject) => {
    promiseCallbacks[msgId].resolve = resolve;
    promiseCallbacks[msgId].reject = reject;
  });

  send(workers[subdir], {
    type: "search",
    msgId: msgId,
    query: query
  });

  return p;
}

export function getStatus(subdir, options) {
  return startWorker(subdir).then(() => {
    if (indexStatus[subdir]) {
      return Promise.resolve(indexStatus[subdir]);
    }
    var msgId = getNextMsgId();
    promiseCallbacks[msgId] = {};

    var p = new Promise((resolve, reject) => {
      promiseCallbacks[msgId].resolve = resolve;
      promiseCallbacks[msgId].reject = reject;
    });

    send(workers[subdir], {
      type: "checkIndexFile",
      msgId: msgId,
      options: options
    });

    return p;
  });
}

export function find(pattern) {
  return search(this.path, pattern).then( (result) => {
    return result.map( (res) => {
      res.path = join(this.path, res.ref);
      res.type = "dropbox";
      return res;
    });
  });
}

function handleSearchResponse(msgId, result) {
  if (!promiseCallbacks[msgId]) {
    console.log(`[Indexing] No promise registered for ${msgId}`);
    return;
  }

  var resolve = promiseCallbacks[msgId].resolve;
  delete promiseCallbacks[msgId];

  resolve(result);
}

function handleInitResponse(msgId, result, subdir) {
  // Worker does not send a msgId, when it had to create the
  // requested index, because the msgId was already used to
  // signal that the index did not exist.
  if (!msgId) {
    // index has been created now,
    // so next call to createIndex will resolve immediately
    indexStatus[subdir] = "ready";
    return;
  }

  if (!promiseCallbacks[msgId]) {
    // this should never happen!
    console.log(`[Indexing] No promise registered for ${msgId}`);
    return;
  }

  var resolve = promiseCallbacks[msgId].resolve;
  var reject = promiseCallbacks[msgId].reject;
  delete promiseCallbacks[msgId];

  if (result === "ready") {
    // index was requested and just had to be loaded from disk
    indexStatus[subdir] = "ready";
    resolve();
  } else {
    // index was requested, does not exist and is being built now
    indexStatus[subdir] = "indexing";
    reject();
  }
}

function handleIndexStatusResponse(msgId, result, subdir) {
  if (!promiseCallbacks[msgId]) {
    // this should never happen!
    console.log(`[Indexing] No promise registered for ${msgId}`);
    return;
  }

  var resolve = promiseCallbacks[msgId].resolve;
  delete promiseCallbacks[msgId];

  resolve(result);

  if (result === "unavailable") {
    stopWorker(subdir);
  }
}

export function addFile(serverRelPath) {
  // e.g. serverRelPath == "/lively4-core/src/client/foo.js"
  serverRelPath = slash(serverRelPath);
  // find corresponding index
  var subdir = getIndexSubdir(serverRelPath);

  if (!subdir || !workers[subdir]) {
    console.log("[Indexing] Cannot add file, no index created for " + serverRelPath);
    return;
  }

  var absPath = toAbsPath(serverRelPath);
  send(workers[subdir], {
    type: "addFile",
    idxRelPath: toIdxRelPath(subdir, absPath)
  });
}

export function removeFile(serverRelPath) {
  // e.g. serverRelPath == "/lively4-core/src/client/foo.js"
  serverRelPath = slash(serverRelPath);
  // find corresponding index
  var subdir = getIndexSubdir(serverRelPath);
  if (!subdir) {
    // no index found for the serverRelPath, so dont remove it
    return;
  }
  if (!workers[subdir]) {
    console.log("[Indexing] Cannot remove file, no index created for " + subdir);
    return;
  }

  var absPath = toAbsPath(serverRelPath);
  send(workers[subdir], {
    type: "removeFile",
    idxRelPath: toIdxRelPath(subdir, absPath)
  });
}

// *** Helper methods ***

function getIndexSubdir(filepath) {
  return Object.keys(workers).find(function(subidx) {
    return filepath.indexOf(subidx + "/") == 0;
  });
}

function toAbsPath(serverRelPath) {
  return slash(path.join(rootFolder, serverRelPath));
}

function toIdxRelPath(subdir, absPath) {
  if (!rootFolder) {
    return;
  }

  // remove e.g. <rootFolder>/lively4-core/ (including the last slash, therefore + 1)
  return slash(absPath.slice(rootFolder.length + subdir.length + 1));
}

function getNextMsgId() {
  curMsgId++;
  return curMsgId;
}

function join(path1, path2) {
  if (path1[path1.length-1] != "/") {
    path1 += "/";
  }
  if (path2[0] == "/") {
    path2 = path2.slice(1, path2.length);
  }
  return path1 + path2;
}
<commit_msg>fix concurrent requests that caused double stop for workers<commit_after>'use strict'

var isNode = (typeof window === 'undefined');

var path, slash, child_process;

var requireHack = require;

if (isNode) {
  path = requireHack("path");
  slash = requireHack("slash");
  child_process = requireHack("child_process");
}

function send(receiver, message) {
  if (!receiver) return;

  if (isNode) {
    receiver.send(message);
  } else {
    receiver.postMessage(message);
  }
}

function createProcess(script, cwd) {
  if (isNode) {
    let p = child_process.fork(path.join(process.cwd(), script), {
      cwd: toAbsPath(cwd),
      // pipe stdout/stderr into this process
      silent: true
    });

    // handle stdout of child
    p.stdout.on("data", (data) => {
      process.stdout.write(`[Indexing] (${cwd}) ${data}`);
    });

    // handle stderr of child
    p.stderr.on("data", (data) => {
      process.stderr.write(`[Indexing] (${cwd}) ${data}`);
    });

    return p;
  }

  // in Browser:
  return new Worker(script);
}

// Object that holds workers for server subdirectories,
// e.g. '/lively4-core'
var workers = {};
var indexStatus = {};

var promiseCallbacks = {};
var workerReadyPromise;
// rootFolder is an absolute directory to where the server serves,
// e.g. where the lively4-core folder is found
var rootFolder = null;
var idxFileName = "index.l4idx";

var curMsgId = 0;

// *** Exported methods ***

export function setRootFolder(filepath) {
  // becomes e.g. "C:/felix/bla" on Windows
  if (isNode) {
    rootFolder = slash(path.resolve(filepath));
  } else {
    rootFolder = filepath;
  }
}

export function startWorker(subdir) {
  return new Promise((resolve, reject) => {
    if (!rootFolder) {
      throw new Error("startWorker: no root folder set");
    }

    if (workers[subdir]) {
      console.log("[Indexing] Worker already exists");
      resolve();
      return;
    }

    console.log("[Indexing] Starting new worker for " + subdir);
    try {
      let script = isNode ? "./lively4-search/server/lunr-node-search-worker.js" : "./src/external/lively4-search/client/lunr-es6-search-worker-wrapper.js";
      workers[subdir] = createProcess(script, subdir);
    } catch (err) {
      console.log("[Indexing] Error starting new worker for " + subdir + ": " + err);
      reject(err);
      return;
    }

    let messageHandler = function(m) {
      // web workers hide the sent message behind the data key
      if (!isNode) {
        m = m.data;
      }
      switch (m.type) {
        case "worker-ready":
          resolve();
          break;
        case "search-response":
          handleSearchResponse(m.msgId, m.message);
          break;
        case "init-response":
          handleInitResponse(m.msgId, m.message, subdir);
          break;
        case "index-status-response":
          handleIndexStatusResponse(m.msgId, m.message, subdir);
          break;
        case "error":
          console.log("[Indexing] Error (" + subdir + "): " + m.message);
          break;
        default:
          console.log("[Indexing] Unknown message:", m);
      }
    }

    if (isNode) {
      workers[subdir].on("message", messageHandler);
    } else {
      workers[subdir].onmessage = messageHandler;
    }
  });
}

function stopWorker(subdir) {
  console.log("stop", subdir);
  send(workers[subdir], {
    type: "stop"
  });

  delete workers[subdir];
  delete indexStatus[subdir];
}

export function createIndex(subdir, options) {
  return startWorker(subdir).then(() => {
    return new Promise((resolve, reject) => {
      if (!rootFolder) {
        console.log("[Indexing] Cannot create index, no root folder set");
        reject("Error: no root folder set");
        return;
      }

      if (indexStatus[subdir] === "ready") {
        console.log("[Indexing] Index already exists");
        resolve();
        return;
      }

      if (indexStatus[subdir] === "indexing") {
        reject();
        return;
      }

      var msgId = getNextMsgId();
      promiseCallbacks[msgId] = {
        resolve: resolve,
        reject: reject
      };

      send(workers[subdir], {
        type: "init",
        msgId: msgId,
        options: options
      });

      indexStatus[subdir] = "indexing";
    });
  });
}

export function removeIndex(subdir, options) {
  return startWorker(subdir).then(() => {
    send(workers[subdir], {
      type: "removeIndex"
    });

    stopWorker(subdir);

    delete indexStatus[subdir];
  });
}

export function setup(options) {
  return new Promise((resolve, reject) => {

    let fetchStatus =  () => {
      createIndex(options.path, options).then( () => {
        resolve();
        clearInterval(interval);
      }, () => {
        console.log("[Indexing] Waiting for index: " + options.name)
      });
    };

    fetchStatus();
    let interval = setInterval(fetchStatus, 5000);
  });
}

export function search(subdir, query) {
  if (!workers[subdir]) {
    console.log("[Indexing] Cannot search, no index created for " + subdir);
    return Promise.reject();
  }

  var msgId = getNextMsgId();
  promiseCallbacks[msgId] = {};

  var p = new Promise((resolve, reject) => {
    promiseCallbacks[msgId].resolve = resolve;
    promiseCallbacks[msgId].reject = reject;
  });

  send(workers[subdir], {
    type: "search",
    msgId: msgId,
    query: query
  });

  return p;
}

export function getStatus(subdir, options) {
  return startWorker(subdir).then(() => {
    if (indexStatus[subdir]) {
      return Promise.resolve(indexStatus[subdir]);
    }
    var msgId = getNextMsgId();
    promiseCallbacks[msgId] = {};

    var p = new Promise((resolve, reject) => {
      promiseCallbacks[msgId].resolve = resolve;
      promiseCallbacks[msgId].reject = reject;
    });

    send(workers[subdir], {
      type: "checkIndexFile",
      msgId: msgId,
      options: options
    });

    return p;
  });
}

export function find(pattern) {
  return search(this.path, pattern).then( (result) => {
    return result.map( (res) => {
      res.path = join(this.path, res.ref);
      res.type = "dropbox";
      return res;
    });
  });
}

function handleSearchResponse(msgId, result) {
  if (!promiseCallbacks[msgId]) {
    console.log(`[Indexing] No promise registered for ${msgId}`);
    return;
  }

  var resolve = promiseCallbacks[msgId].resolve;
  delete promiseCallbacks[msgId];

  resolve(result);
}

function handleInitResponse(msgId, result, subdir) {
  // Worker does not send a msgId, when it had to create the
  // requested index, because the msgId was already used to
  // signal that the index did not exist.
  if (!msgId) {
    // index has been created now,
    // so next call to createIndex will resolve immediately
    indexStatus[subdir] = "ready";
    return;
  }

  if (!promiseCallbacks[msgId]) {
    // this should never happen!
    console.log(`[Indexing] No promise registered for ${msgId}`);
    return;
  }

  var resolve = promiseCallbacks[msgId].resolve;
  var reject = promiseCallbacks[msgId].reject;
  delete promiseCallbacks[msgId];

  if (result === "ready") {
    // index was requested and just had to be loaded from disk
    indexStatus[subdir] = "ready";
    resolve();
  } else {
    // index was requested, does not exist and is being built now
    indexStatus[subdir] = "indexing";
    reject();
  }
}

function handleIndexStatusResponse(msgId, result, subdir) {
  if (!promiseCallbacks[msgId]) {
    // this should never happen!
    console.log(`[Indexing] No promise registered for ${msgId}`);
    return;
  }

  var resolve = promiseCallbacks[msgId].resolve;
  delete promiseCallbacks[msgId];

  resolve(result);

  if (result === "unavailable") {
    stopWorker(subdir);
  }
}

export function addFile(serverRelPath) {
  // e.g. serverRelPath == "/lively4-core/src/client/foo.js"
  serverRelPath = slash(serverRelPath);
  // find corresponding index
  var subdir = getIndexSubdir(serverRelPath);

  if (!subdir || !workers[subdir]) {
    console.log("[Indexing] Cannot add file, no index created for " + serverRelPath);
    return;
  }

  var absPath = toAbsPath(serverRelPath);
  send(workers[subdir], {
    type: "addFile",
    idxRelPath: toIdxRelPath(subdir, absPath)
  });
}

export function removeFile(serverRelPath) {
  // e.g. serverRelPath == "/lively4-core/src/client/foo.js"
  serverRelPath = slash(serverRelPath);
  // find corresponding index
  var subdir = getIndexSubdir(serverRelPath);
  if (!subdir) {
    // no index found for the serverRelPath, so dont remove it
    return;
  }
  if (!workers[subdir]) {
    console.log("[Indexing] Cannot remove file, no index created for " + subdir);
    return;
  }

  var absPath = toAbsPath(serverRelPath);
  send(workers[subdir], {
    type: "removeFile",
    idxRelPath: toIdxRelPath(subdir, absPath)
  });
}

// *** Helper methods ***

function getIndexSubdir(filepath) {
  return Object.keys(workers).find(function(subidx) {
    return filepath.indexOf(subidx + "/") == 0;
  });
}

function toAbsPath(serverRelPath) {
  return slash(path.join(rootFolder, serverRelPath));
}

function toIdxRelPath(subdir, absPath) {
  if (!rootFolder) {
    return;
  }

  // remove e.g. <rootFolder>/lively4-core/ (including the last slash, therefore + 1)
  return slash(absPath.slice(rootFolder.length + subdir.length + 1));
}

function getNextMsgId() {
  curMsgId++;
  return curMsgId;
}

function join(path1, path2) {
  if (path1[path1.length-1] != "/") {
    path1 += "/";
  }
  if (path2[0] == "/") {
    path2 = path2.slice(1, path2.length);
  }
  return path1 + path2;
}
<|endoftext|>


<commit_before>parseChange = function (changeType, severity, oldValStr, newValStr, oldValObj, newValObj, ctx) {
  let newVal = newValStr || newValObj || null;
  let oldVal = oldValStr || oldValObj || null;

  let colorMarkerStr = insertColorMarker(severity);

  let charName;
  if (ctx) charName = ctx.charName;
  else if (newVal) charName = newVal.characterName;
  else if (oldVal) charName = oldVal.characterName;

  let charStr = 'The character "' + charName + '" ';

  let oldName = ctx ? ctx.oldName : null;
  let newName = ctx ? ctx.newName : null;

  let changeTypeStr = '' + changeType + ' '

  let contentStr;
  switch (changeType) {
    case 'INVALIDKEY':
      contentStr = 'This key has expired or been deleted.'
      break;
    case 'SINGLECHAR':
      contentStr = 'This key only provides info about a single character.';
      break;
    case 'BADMASK':
      contentStr = 'The access rights no longer satisfy the Corporation conditions.';
      break;
    case 'EXPIRES':
      contentStr = 'This key has been set to expire.';
      break;
    case 'leaveCorp':
      contentStr = charStr + 'left "' + oldName + '" and is now part of an NPC corporation.';
      break;
    case 'leaveAlliance':
      contentStr = charStr + 'and its corporation are no longer allied with "' + oldName + '".';
      break;
    case 'joinCorp':
      contentStr = charStr + 'joined the "' + oldName + '" corporation.';
      break;
    case 'joinAlliance':
      contentStr = charStr + 'and its corporation formed an alliance with "' + oldName + '".';
      break;
    case 'switchCorp':
      contentStr = charStr + 'left "' + oldName + '" to join "' + newName + '".';
      break;
    case 'switchAlliance':
      contentStr = charStr + 'and its corporation broke their alliance with "' + oldName + '" to form a new alliance with "' + newName + '".';
      break;
    case 'addCharacter':
      contentStr = charStr + 'has been created.';
      break;
    case 'removeCharacter':
      contentStr = charStr + 'has been deleted.';
      break;
    default:
  }

  dispStr = '
' + colorMarkerStr + changeTypeStr + contentStr + '
';

  return dispStr;
}
<commit_msg>Fix bug where alliance being joined wasn't displaying<commit_after>parseChange = function (changeType, severity, oldValStr, newValStr, oldValObj, newValObj, ctx) {
  let newVal = newValStr || newValObj || null;
  let oldVal = oldValStr || oldValObj || null;

  let colorMarkerStr = insertColorMarker(severity);

  let charName;
  if (ctx) charName = ctx.charName;
  else if (newVal) charName = newVal.characterName;
  else if (oldVal) charName = oldVal.characterName;

  let charStr = 'The character "' + charName + '" ';

  let oldName = ctx ? ctx.oldName : null;
  let newName = ctx ? ctx.newName : null;

  let changeTypeStr = '' + changeType + ' '

  let contentStr;
  switch (changeType) {
    case 'INVALIDKEY':
      contentStr = 'This key has expired or been deleted.'
      break;
    case 'SINGLECHAR':
      contentStr = 'This key only provides info about a single character.';
      break;
    case 'BADMASK':
      contentStr = 'The access rights no longer satisfy the Corporation conditions.';
      break;
    case 'EXPIRES':
      contentStr = 'This key has been set to expire.';
      break;
    case 'leaveCorp':
      contentStr = charStr + 'left "' + oldName + '" and is now part of an NPC corporation.';
      break;
    case 'leaveAlliance':
      contentStr = charStr + 'and its corporation are no longer allied with "' + oldName + '".';
      break;
    case 'joinCorp':
      contentStr = charStr + 'joined the "' + oldName + '" corporation.';
      break;
    case 'joinAlliance':
      contentStr = charStr + 'and its corporation formed an alliance with "' + newName + '".';
      break;
    case 'switchCorp':
      contentStr = charStr + 'left "' + oldName + '" to join "' + newName + '".';
      break;
    case 'switchAlliance':
      contentStr = charStr + 'and its corporation broke their alliance with "' + oldName + '" to form a new alliance with "' + newName + '".';
      break;
    case 'addCharacter':
      contentStr = charStr + 'has been created.';
      break;
    case 'removeCharacter':
      contentStr = charStr + 'has been deleted.';
      break;
    default:
  }

  dispStr = '
' + colorMarkerStr + changeTypeStr + contentStr + '
';

  return dispStr;
}
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import {
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  Switch,
  Picker,
  StatusBar,
  ScrollView,
  Platform,
} from 'react-native'
import Camera, {
  Aspect,
  CaptureQuality,
  TorchMode,
  RotateMode,
} from 'react-native-openalpr'
import { check, request, PERMISSIONS, RESULTS } from 'react-native-permissions'

const cameraPermission = Platform.select({
  ios: PERMISSIONS.IOS.CAMERA,
  android: PERMISSIONS.ANDROID.CAMERA,
})

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  camera: {
    flex: 1,
  },
  options: {
    position: 'absolute',
    top: 100,
    left: 20,
    right: 20,
    bottom: 20,
    borderRadius: 10,
    backgroundColor: 'white',
  },
  button: {
    position: 'absolute',
    right: 0,
    top: 20,
    color: 'white',
    width: 80,
    height: 80,
    alignItems: 'center',
  },
  buttonText: {
    fontSize: 50,
    alignSelf: 'center',
    color: '#2ab7ca',
  },
  plateText: {
    position: 'absolute',
    top: 20,
    left: 20,
    fontSize: 30,
    color: '#fe4a49',
  },
  confidenceText: {
    position: 'absolute',
    top: 20,
    left: 200,
    fontSize: 30,
    color: '#fe4a49',
  },
  switchGroup: {
    flex: 1,
    flexDirection: 'row',
    margin: 20,
    marginBottom: 0,
  },
  switchText: {
    flex: 1,
    fontSize: 25,
  },
  switch: {
    padding: 10,
  },
  pickerGroup: {},
  pickerText: {
    fontSize: 25,
    paddingTop: 20,
    textAlign: 'center',
  },
  picker: {
    backgroundColor: '#eee',
  },
})

const MySwitch = ({ title, value, onValueChange }) => (
  <View style={styles.switchGroup}>
    <Text style={styles.switchText}>{title}</Text>
    <Switch onValueChange={onValueChange} value={value} style={styles.switch} />
  </View>
)

const MyPicker = ({ title, selectedValue, values, onValueChange }) => (
  <View style={styles.pickerGroup}>
    <Text style={styles.pickerText}>{title}</Text>
    <Picker
      selectedValue={selectedValue}
      onValueChange={onValueChange}
      style={styles.picker}>
      {values.map(({ label, value }) => (
        <Picker.Item key={value} label={label} value={value} />
      ))}
    </Picker>
  </View>
)

const colorOptions = [
  { label: 'Red', value: '#ff0000' },
  { label: 'Green', value: '#00ff00' },
  { label: 'Blue', value: '#0000ff' },
]

const aspectOptions = [
  { label: 'Fill', value: Aspect.fill },
  { label: 'Fit', value: Aspect.fit },
  { label: 'Stretch', value: Aspect.stretch },
]

const qualityOptions = [
  { label: 'Low', value: CaptureQuality.low },
  { label: 'Medium', value: CaptureQuality.medium },
  { label: 'High', value: CaptureQuality.high },
]

const countryOptions = [
  { label: 'eu', value: 'eu' },
  { label: 'us', value: 'us' },
]

export default class App extends Component {
  state = {
    showOptions: false,
    plate: 'Point at a plate',
    confidence: '',
    error: null,
    showCamera: false,
    // Camera options
    camera: {
      aspect: Aspect.fill,
    },
    captureQuality: CaptureQuality.medium,
    aspect: CaptureQuality.stretch,
    rotateMode: false,
    torchMode: false,
    showPlateOutline: true,
    plateOutlineColor: '#ff0000',
    country: 'eu',
    touchToFocus: true,
  }

  async componentDidMount() {
    this.checkPermission()
  }

  async checkPermission() {
    switch (await check(cameraPermission)) {
      case RESULTS.UNAVAILABLE:
        this.setState({
          error:
            'This feature is not available (on this device / in this context)',
        })
        break
      case RESULTS.DENIED:
        this.requestPermission()
        break
      case RESULTS.GRANTED:
        this.setState({
          showCamera: true,
        })
        break
      case RESULTS.BLOCKED:
        this.setState({
          error: 'The permission is denied and not requestable anymore',
        })
        break
    }
  }

  async requestPermission() {
    switch (await request(cameraPermission)) {
      case RESULTS.UNAVAILABLE:
        this.setState({
          error:
            'This feature is not available (on this device / in this context)',
        })
        break
      case RESULTS.DENIED:
        this.setState({
          error: 'The permission has been denied',
        })
        break
      case RESULTS.GRANTED:
        this.setState({
          showCamera: true,
        })
        break
      case RESULTS.BLOCKED:
        this.setState({
          error: 'The permission is denied and not requestable anymore',
        })
        break
    }
  }

  onPlateRecognized = ({ plate, confidence }) => {
    this.setState({
      plate,
      confidence: confidence.toFixed(1),
    })
  }

  toggleOptions = () => this.setState({ showOptions: !this.state.showOptions })

  render() {
    const {
      showCamera,
      error,
      showOptions,
      plate,
      plateOutlineColor,
      showPlateOutline,
      captureQuality,
      aspect,
      rotateMode,
      torchMode,
      country,
      confidence,
      touchToFocus,
    } = this.state
    return (
      <View style={styles.container}>
        {/* <StatusBar  /> */}
        {showCamera && (
          <Camera
            style={styles.camera}
            aspect={aspect}
            captureQuality={captureQuality}
            country={country}
            onPlateRecognized={this.onPlateRecognized}
            plateOutlineColor={plateOutlineColor}
            showPlateOutline={showPlateOutline}
            torchMode={this.state.torchMode ? TorchMode.on : TorchMode.off}
            // rotateMode={this.state.rotateMode ? RotateMode.on : RotateMode.off}
            touchToFocus={touchToFocus}
          />
        )}
        {error && <Text>{error}</Text>}
        <TouchableOpacity style={styles.button} onPress={this.toggleOptions}>
          <Text style={styles.buttonText}>{showOptions ? '✕' : '☰'}</Text>
        </TouchableOpacity>
        <Text style={styles.plateText}>{plate}</Text>
        <Text style={styles.confidenceText}>
          {confidence ? confidence + '%' : ''}
        </Text>
        {showOptions && (
          <ScrollView style={styles.options}>
            <MySwitch
              title="Orientation"
              value={rotateMode}
              onValueChange={value => this.setState({ rotateMode: value })}
            />
            <MySwitch
              title="Torch"
              value={torchMode}
              onValueChange={value => this.setState({ torchMode: value })}
            />
            <MySwitch
              title="Show plate outline"
              value={showPlateOutline}
              onValueChange={value =>
                this.setState({ showPlateOutline: value })
              }
            />
            <MySwitch
              title="Touch to focus"
              value={touchToFocus}
              onValueChange={value => this.setState({ touchToFocus: value })}
            />
            <MyPicker
              title="Color"
              selectedValue={plateOutlineColor}
              onValueChange={value =>
                this.setState({ plateOutlineColor: value })
              }
              values={colorOptions}
            />
            <MyPicker
              title="Quality"
              selectedValue={captureQuality}
              onValueChange={value => this.setState({ captureQuality: value })}
              values={qualityOptions}
            />
            <MyPicker
              title="Aspect"
              selectedValue={aspect}
              onValueChange={value => this.setState({ aspect: value })}
              values={aspectOptions}
            />
            <MyPicker
              title="Country"
              selectedValue={country}
              onValueChange={value => this.setState({ country: value })}
              values={countryOptions}
            />
          </ScrollView>
        )}
      </View>
    )
  }
}
<commit_msg>Example how to take picture<commit_after>import React, { Component } from 'react'
import {
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  Switch,
  Picker,
  StatusBar,
  ScrollView,
  Platform,
  Image,
  Dimensions,
} from 'react-native'
import Camera, {
  Aspect,
  CaptureQuality,
  TorchMode,
  RotateMode,
  takePicture,
} from 'react-native-openalpr'
import { check, request, PERMISSIONS, RESULTS } from 'react-native-permissions'

const cameraPermission = Platform.select({
  ios: PERMISSIONS.IOS.CAMERA,
  android: PERMISSIONS.ANDROID.CAMERA,
})

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  camera: {
    flex: 1,
  },
  options: {
    position: 'absolute',
    top: 100,
    left: 20,
    right: 20,
    bottom: 20,
    borderRadius: 10,
    backgroundColor: 'white',
  },
  button: {
    position: 'absolute',
    right: 0,
    top: 20,
    color: 'white',
    width: 80,
    height: 80,
    alignItems: 'center',
  },
  buttonText: {
    fontSize: 50,
    alignSelf: 'center',
    color: '#2ab7ca',
  },
  plateText: {
    position: 'absolute',
    top: 20,
    left: 20,
    fontSize: 30,
    color: '#fe4a49',
  },
  confidenceText: {
    position: 'absolute',
    top: 20,
    left: 200,
    fontSize: 30,
    color: '#fe4a49',
  },
  switchGroup: {
    flex: 1,
    flexDirection: 'row',
    margin: 20,
    marginBottom: 0,
  },
  switchText: {
    flex: 1,
    fontSize: 25,
  },
  switch: {
    padding: 10,
  },
  pickerGroup: {},
  pickerText: {
    fontSize: 25,
    paddingTop: 20,
    textAlign: 'center',
  },
  picker: {
    backgroundColor: '#eee',
  },
  takePicture: {
    position: 'absolute',
    bottom: 50,
    right: 50,
    borderRadius: 10,
    backgroundColor: '#fe4a49',
  },
  takePictureText: {
    color: 'white',
    padding: 10,
    fontSize: 20,
  },
  pictureWrapper: {
    position: 'absolute',
    top: 20,
    left: 20,
    right: 20,
    bottom: 20,
    backgroundColor: 'gray',
    borderColor: 'white',
    borderWidth: 1,
  },
  picture: {
    transform: [{ rotate: '90deg' }],
    width: Dimensions.get('screen').width - 42,
    height: Dimensions.get('screen').height - 42,
    resizeMode: 'contain',
  },
})

const MySwitch = ({ title, value, onValueChange }) => (
  <View style={styles.switchGroup}>
    <Text style={styles.switchText}>{title}</Text>
    <Switch onValueChange={onValueChange} value={value} style={styles.switch} />
  </View>
)

const MyPicker = ({ title, selectedValue, values, onValueChange }) => (
  <View style={styles.pickerGroup}>
    <Text style={styles.pickerText}>{title}</Text>
    <Picker
      selectedValue={selectedValue}
      onValueChange={onValueChange}
      style={styles.picker}>
      {values.map(({ label, value }) => (
        <Picker.Item key={value} label={label} value={value} />
      ))}
    </Picker>
  </View>
)

const colorOptions = [
  { label: 'Red', value: '#ff0000' },
  { label: 'Green', value: '#00ff00' },
  { label: 'Blue', value: '#0000ff' },
]

const aspectOptions = [
  { label: 'Fill', value: Aspect.fill },
  { label: 'Fit', value: Aspect.fit },
  { label: 'Stretch', value: Aspect.stretch },
]

const qualityOptions = [
  { label: 'Low', value: CaptureQuality.low },
  { label: 'Medium', value: CaptureQuality.medium },
  { label: 'High', value: CaptureQuality.high },
]

const countryOptions = [
  { label: 'eu', value: 'eu' },
  { label: 'us', value: 'us' },
]

export default class App extends Component {
  state = {
    showOptions: false,
    plate: 'Point at a plate',
    confidence: '',
    error: null,
    showCamera: false,
    // Camera options
    camera: {
      aspect: Aspect.fill,
    },
    captureQuality: CaptureQuality.medium,
    aspect: CaptureQuality.stretch,
    rotateMode: false,
    torchMode: false,
    showPlateOutline: true,
    plateOutlineColor: '#ff0000',
    country: 'eu',
    touchToFocus: true,
  }

  async componentDidMount() {
    this.checkPermission()
  }

  async checkPermission() {
    switch (await check(cameraPermission)) {
      case RESULTS.UNAVAILABLE:
        this.setState({
          error:
            'This feature is not available (on this device / in this context)',
        })
        break
      case RESULTS.DENIED:
        this.requestPermission()
        break
      case RESULTS.GRANTED:
        this.setState({
          showCamera: true,
        })
        break
      case RESULTS.BLOCKED:
        this.setState({
          error: 'The permission is denied and not requestable anymore',
        })
        break
    }
  }

  async requestPermission() {
    switch (await request(cameraPermission)) {
      case RESULTS.UNAVAILABLE:
        this.setState({
          error:
            'This feature is not available (on this device / in this context)',
        })
        break
      case RESULTS.DENIED:
        this.setState({
          error: 'The permission has been denied',
        })
        break
      case RESULTS.GRANTED:
        this.setState({
          showCamera: true,
        })
        break
      case RESULTS.BLOCKED:
        this.setState({
          error: 'The permission is denied and not requestable anymore',
        })
        break
    }
  }

  onPlateRecognized = ({ plate, confidence }) => {
    this.setState({
      plate,
      confidence: confidence.toFixed(1),
    })
  }

  toggleOptions = () => this.setState({ showOptions: !this.state.showOptions })

  onTakePicturePress = async () => {
    const picture = await takePicture({
      width: 4032,
      height: 3024,
      quality: 0.8,
    })
    this.setState({
      picture,
    })
  }

  onClosePicturePress = () =>
    this.setState({
      picture: null,
    })

  render() {
    const {
      showCamera,
      error,
      showOptions,
      plate,
      plateOutlineColor,
      showPlateOutline,
      captureQuality,
      aspect,
      rotateMode,
      torchMode,
      country,
      confidence,
      touchToFocus,
      picture,
    } = this.state
    return (
      <View style={styles.container}>
        {/* <StatusBar  /> */}
        {showCamera && (
          <Camera
            style={styles.camera}
            aspect={aspect}
            captureQuality={captureQuality}
            country={country}
            onPlateRecognized={this.onPlateRecognized}
            plateOutlineColor={plateOutlineColor}
            showPlateOutline={showPlateOutline}
            torchMode={this.state.torchMode ? TorchMode.on : TorchMode.off}
            // rotateMode={this.state.rotateMode ? RotateMode.on : RotateMode.off}
            touchToFocus={touchToFocus}
          />
        )}
        {error && <Text>{error}</Text>}
        <TouchableOpacity style={styles.button} onPress={this.toggleOptions}>
          <Text style={styles.buttonText}>{showOptions ? '✕' : '☰'}</Text>
        </TouchableOpacity>
        <Text style={styles.plateText}>{plate}</Text>
        <Text style={styles.confidenceText}>
          {confidence ? confidence + '%' : ''}
        </Text>
        <TouchableOpacity
          style={styles.takePicture}
          onPress={this.onTakePicturePress}>
          <Text style={styles.takePictureText}>Take picure</Text>
        </TouchableOpacity>
        {picture && (
          <TouchableOpacity
            style={styles.pictureWrapper}
            onPress={this.onClosePicturePress}>
            <Image style={styles.picture} source={{ uri: picture }} />
          </TouchableOpacity>
        )}
        {showOptions && (
          <ScrollView style={styles.options}>
            <MySwitch
              title="Orientation"
              value={rotateMode}
              onValueChange={value => this.setState({ rotateMode: value })}
            />
            <MySwitch
              title="Torch"
              value={torchMode}
              onValueChange={value => this.setState({ torchMode: value })}
            />
            <MySwitch
              title="Show plate outline"
              value={showPlateOutline}
              onValueChange={value =>
                this.setState({ showPlateOutline: value })
              }
            />
            <MySwitch
              title="Touch to focus"
              value={touchToFocus}
              onValueChange={value => this.setState({ touchToFocus: value })}
            />
            <MyPicker
              title="Color"
              selectedValue={plateOutlineColor}
              onValueChange={value =>
                this.setState({ plateOutlineColor: value })
              }
              values={colorOptions}
            />
            <MyPicker
              title="Quality"
              selectedValue={captureQuality}
              onValueChange={value => this.setState({ captureQuality: value })}
              values={qualityOptions}
            />
            <MyPicker
              title="Aspect"
              selectedValue={aspect}
              onValueChange={value => this.setState({ aspect: value })}
              values={aspectOptions}
            />
            <MyPicker
              title="Country"
              selectedValue={country}
              onValueChange={value => this.setState({ country: value })}
              values={countryOptions}
            />
          </ScrollView>
        )}
      </View>
    )
  }
}
<|endoftext|>


<commit_before>function CODE39(string){
	string = string.toUpperCase();

	var encodings = {
		"0": 20957, "1": 29783, "2": 23639, "3": 30485,
		"4": 20951, "5": 29813, "6": 23669, "7": 20855,
		"8": 29789, "9": 23645, "A": 29975, "B": 23831,
		"C": 30533, "D": 22295, "E": 30149, "F": 24005,
		"G": 21623, "H": 29981, "I": 23837, "J": 22301,
		"K": 30023, "L": 23879, "M": 30545, "N": 22343,
		"O": 30161, "P": 24017, "Q": 21959, "R": 30065,
		"S": 23921, "T": 22385, "U": 29015, "V": 18263,
		"W": 29141, "X": 17879, "Y": 29045, "Z": 18293,
		"-": 17783, ".": 29021, " ": 18269, "$": 17477,
		"/": 17489, "+": 17681, "%": 20753, "*": 35770
	};

	this.encode = function(){
		var result = "";
		result += encodings["*"].toString(2);
		for(var i=0; i<string.length; i++){
			result += encodings[string[i]].toString(2) + "0";
		}
		result += encodings["*"].toString(2);

		return {data: result, text: string};
	};

	//Use the regexp variable for validation
	this.valid = function(){
		return string.search(/^[0-9A-Z\-\.\ \$\/\+\%]+$/) !== -1;
	};
}

//Required to register for both browser and nodejs
function register(core){
	core.register(CODE39, /^CODE.?39$/i, 3);
}
export default register;
<commit_msg>Made CODE39 into ES6<commit_after>class CODE39 {
	constructor(string){
		this.string = string.toUpperCase();

		this.encodings = {
			"0": 20957, "1": 29783, "2": 23639, "3": 30485,
			"4": 20951, "5": 29813, "6": 23669, "7": 20855,
			"8": 29789, "9": 23645, "A": 29975, "B": 23831,
			"C": 30533, "D": 22295, "E": 30149, "F": 24005,
			"G": 21623, "H": 29981, "I": 23837, "J": 22301,
			"K": 30023, "L": 23879, "M": 30545, "N": 22343,
			"O": 30161, "P": 24017, "Q": 21959, "R": 30065,
			"S": 23921, "T": 22385, "U": 29015, "V": 18263,
			"W": 29141, "X": 17879, "Y": 29045, "Z": 18293,
			"-": 17783, ".": 29021, " ": 18269, "$": 17477,
			"/": 17489, "+": 17681, "%": 20753, "*": 35770
		};
	};

	encode(){
		var result = "";
		result += this.encodings["*"].toString(2);
		for(var i=0; i<this.string.length; i++){
			result += this.encodings[this.string[i]].toString(2) + "0";
		}
		result += this.encodings["*"].toString(2);

		return {data: result, text: this.string};
	};

	//Use the regexp variable for validation
	valid(){
		return this.string.search(/^[0-9A-Z\-\.\ \$\/\+\%]+$/) !== -1;
	};
}

//Required to register for both browser and nodejs
function register(core){
	core.register(CODE39, /^CODE.?39$/i, 3);
}
export default register;
<|endoftext|>


<commit_before>import React from 'react'
import ReactDOM from 'react-dom';
import ShQuill from '../bin/sh-quill'

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            reason: '
beginning text
'
        };

        this.handleChange = this.handleChange.bind(this);
    }

    handleChange() {
        this.setState({
            reason: `

one

two

three

four

`
        })
    }

    render() {
        return (

                    <ShQuill className="sm" value={this.state.reason}/>

                <button onClick={this.handleChange}>test</button>

        )
    }
}

ReactDOM.render(<App/>, document.getElementById('app'));<commit_msg>updated the example app so that it would work<commit_after>import React from 'react'
import ReactDOM from 'react-dom';
import ShQuill from '../src/index'

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            reason: '
beginning text
'
        };

        this.handleChange = this.handleChange.bind(this);
    }

    handleChange() {
        this.setState({
            reason: `

one

two

three

four

`
        })
    }

    render() {
        return (

                    <ShQuill className="sm" value={this.state.reason}/>

                <button onClick={this.handleChange}>test</button>

        )
    }
}

ReactDOM.render(<App/>, document.getElementById('app'));<|endoftext|>


<commit_before>var Q = require('q'),
    info = JSON.parse(require('fs').readFileSync(__dirname + '/../package.json'));

var coa = module.exports = require('coa').Cmd()
    .helpful()
    .name(info.name)
    .title(info.description)
    .opt()
        .name('version').title('Version')
        .short('v').long('version')
        .only()
        .flag()
        .act(function(opts) {
            return info.version;
        })
        .end()
    .opt()
        .name('config').title('Local config')
        .short('c').long('config')
        .end()
    .opt()
        .name('disable').title('Disable plugin')
        .short('d').long('disable')
        .arr()
        .end()
    .opt()
        .name('enable').title('Enable plugin')
        .short('e').long('enable')
        .arr()
        .end()
    .opt()
        .name('input').title('Input file (default: stdin)')
        .short('i').long('input')
        .input()
        .end()
    .opt()
        .name('output').title('Output file (default: stdout)')
        .short('o').long('output')
        .output()
        .end()
    .act(function(options) {

        var input = [],
            deferred = Q.defer(),
            SVGO = require('./svgo');

        options.input
            .on('data', function(chunk) {
                input.push(chunk);
            })
            .once('end', function() {
                deferred.resolve(input.join());
            })
            .resume();

        return deferred.promise
            .then(function(svg) {
                return SVGO(svg, { coa: options });
            })
            .then(function(svgmin) {
                var output = options.output;

                output.write(svgmin);

                output === process.stdout ?
                    output.write('\n') :
                    output.end();
            });

    });
<commit_msg>add an empty values rejecting to coa.js<commit_after>var Q = require('q'),
    info = JSON.parse(require('fs').readFileSync(__dirname + '/../package.json'));

var coa = module.exports = require('coa').Cmd()
    .helpful()
    .name(info.name)
    .title(info.description)
    .opt()
        .name('version').title('Version')
        .short('v').long('version')
        .only()
        .flag()
        .act(function(opts) {
            return info.version;
        })
        .end()
    .opt()
        .name('config').title('Local config')
        .short('c').long('config')
        .val(function(val) {
            return val || coa.reject('Option --config must have a value.');
        })
        .end()
    .opt()
        .name('disable').title('Disable plugin')
        .short('d').long('disable')
        .arr()
        .val(function(val) {
            return val || coa.reject('Option --disable must have a value.');
        })
        .end()
    .opt()
        .name('enable').title('Enable plugin')
        .short('e').long('enable')
        .arr()
        .val(function(val) {
            return val || coa.reject('Option --enable must have a value.');
        })
        .end()
    .opt()
        .name('input').title('Input file (default: stdin)')
        .short('i').long('input')
        .input()
        .end()
    .opt()
        .name('output').title('Output file (default: stdout)')
        .short('o').long('output')
        .output()
        .end()
    .act(function(options) {

        var input = [],
            deferred = Q.defer(),
            SVGO = require('./svgo');

        options.input
            .on('data', function(chunk) {
                input.push(chunk);
            })
            .once('end', function() {
                deferred.resolve(input.join());
            })
            .resume();

        return deferred.promise
            .then(function(svg) {
                return SVGO(svg, { coa: options });
            })
            .then(function(svgmin) {
                var output = options.output;

                output.write(svgmin);

                output === process.stdout ?
                    output.write('\n') :
                    output.end();
            });

    });
<|endoftext|>


<commit_before>/**
 * Cross-Origin requests for IE 8—9
 * Uses iframe and Cross Document Messaging
 */
define(function() {

    var processing = {};

    function guid() {
        return +new Date() + '' + Math.ceil(Math.random() * 10000);
    }

    function getCORURI(request, options) {
        // TODO: always ssl
        var uri = request.uri,
            host,
            scheme = '',
            cor = '',
            _;

        _ = uri.split('//');

        if (_.length > 1) {
            if (_[0].substr(_[0].length - 1)  === ':') {
                scheme = _[0];
            }

            _ = _[1].split('/');
            host = _[0];
        }

        if (host) {
            cor = scheme + '//' + host
        }

        cor += options.cor;

        return cor;
    }

    function getProxy(uri, callback) {
        if (!getProxy.mems) {
            getProxy.mems = {};
        }

        if (getProxy.mems[uri]) {
            callback(getProxy.mems[uri]);
            return;
        }

        var div = document.createElement('div'),
            id = 'i' + guid(),
            onload = 'f' + guid();

        div.style.width = div.style.height = '0px';
        div.style.visibility = div.style.overflow = 'hidden';
		div.innerHTML = '<iframe id="' + id + '" src="' + uri + '" style="" onload="' + onload + '()" />';

        window[onload] = function() {
            getProxy.mems[uri] = document.getElementById(id).contentWindow;
            callback(getProxy.mems[uri]);
        };

        document.body.appendChild(div);
    }

    function handle(e) {
        e = e || event;

        var message,
            xhr;

        try {
            message = JSON.parse(e.data);
        } catch (e) {
            return;
        }

        if (message.type !== 'cor'
            || !processing[message.id]) {

            return;
        }

        xhr = processing[message.id];
        processing[message.id] = undefined;
        delete processing[message.id];

        xhr.status = message.status;
        xhr.responseText = message.response;
        xhr.headers = message.headers;

        message.status
            ? xhr.onload()
            : xhr.onerror({});
    }

    function send(request, options, xhr) {
        var uri = getCORURI(request, options),
            id = guid();

        processing[id] = xhr;

        getProxy(uri, function(proxy) {
            proxy.postMessage(JSON.stringify({
                id: id,
                req: request
            }), '*');
        });
    }

    window.onmessage = handle;

    return function(options) {

        var request = { headers: {} };

        this.headers = {};
        this.onload = null;
        this.onerror = null;
        this.withCredentials = false;

        this.open = function(method, uri) {
            request.method = method;
            request.uri = uri;
        };

        this.setRequestHeader = function(name, value) {
            request.headers[name] = value;
        };

        this.getResponseHeader = function(name) {
            return this.headers[name.toLowerCase()];
        };

        this.send = function(body) {
            request.body = body;

            send(request, options, this);
        };

    }

});<commit_msg>Исправлена перезапись обработчика onmessage при повторной инициализации в ie<commit_after>/**
 * Cross-Origin requests for IE 8—9
 * Uses iframe and Cross Document Messaging
 */
define(function() {

    var processing = {};

    function guid() {
        return +new Date() + '' + Math.ceil(Math.random() * 10000);
    }

    function getCORURI(request, options) {
        // TODO: always ssl
        var uri = request.uri,
            host,
            scheme = '',
            cor = '',
            _;

        _ = uri.split('//');

        if (_.length > 1) {
            if (_[0].substr(_[0].length - 1)  === ':') {
                scheme = _[0];
            }

            _ = _[1].split('/');
            host = _[0];
        }

        if (host) {
            cor = scheme + '//' + host
        }

        cor += options.cor;

        return cor;
    }

    function getProxy(uri, callback) {
        if (!getProxy.mems) {
            getProxy.mems = {};
        }

        if (getProxy.mems[uri]) {
            callback(getProxy.mems[uri]);
            return;
        }

        var div = document.createElement('div'),
            id = 'i' + guid(),
            onload = 'f' + guid();

        div.style.width = div.style.height = '0px';
        div.style.visibility = div.style.overflow = 'hidden';
		div.innerHTML = '<iframe id="' + id + '" src="' + uri + '" style="" onload="' + onload + '()" />';

        window[onload] = function() {
            getProxy.mems[uri] = document.getElementById(id).contentWindow;
            callback(getProxy.mems[uri]);
        };

        document.body.appendChild(div);
    }

    function handle(e) {
        e = e || event;

        var message,
            xhr;

        try {
            message = JSON.parse(e.data);
        } catch (e) {
            return;
        }

        if (message.type !== 'cor'
            || !processing[message.id]) {

            return;
        }

        xhr = processing[message.id];
        processing[message.id] = undefined;
        delete processing[message.id];

        xhr.status = message.status;
        xhr.responseText = message.response;
        xhr.headers = message.headers;

        message.status
            ? xhr.onload()
            : xhr.onerror({});
    }

    function send(request, options, xhr) {
        var uri = getCORURI(request, options),
            id = guid();

        processing[id] = xhr;

        getProxy(uri, function(proxy) {
            proxy.postMessage(JSON.stringify({
                id: id,
                req: request
            }), '*');
        });
    }

    window.onmessage = window.onmessage || handle;

    return function(options) {

        var request = { headers: {} };

        this.headers = {};
        this.onload = null;
        this.onerror = null;
        this.withCredentials = false;

        this.open = function(method, uri) {
            request.method = method;
            request.uri = uri;
        };

        this.setRequestHeader = function(name, value) {
            request.headers[name] = value;
        };

        this.getResponseHeader = function(name) {
            return this.headers[name.toLowerCase()];
        };

        this.send = function(body) {
            request.body = body;

            send(request, options, this);
        };

    }

});<|endoftext|>


<commit_before>"use strict";

const IGNORELIST = [
  '00000000000',
  '11111111111',
  '22222222222',
  '33333333333',
  '44444444444',
  '55555555555',
  '66666666666',
  '77777777777',
  '88888888888',
  '99999999999',
  '12345678909'
];

let checkDigit = (numbers) => {
  numbers = numbers.split("").map((number) => parseInt(number, 10));

  let modulus = numbers.length + 1;

  let multiply = numbers.map((number, index) => number * (modulus - index));

  let mod = multiply.reduce((buffer, number) => buffer + number) % 11;

  return (mod < 2 ? 0 : 11 - mod);
};

let CPF = {};

CPF.strip = (number) => (number || "").toString().replace(/[^\d]/g, "");

CPF.format = (number) => CPF.strip(number).replace(
  /^(\d{3})(\d{3})(\d{3})(\d{2})$/, "$1.$2.$3-$4");

CPF.isValid = (number) => {
  let stripped = CPF.strip(number);

  if (!stripped) return false;

  if (stripped.length !== 11) return false;

  if (IGNORELIST.indexOf(stripped) >= 0) return false;

  let numbers = stripped.substr(0, 9);
  numbers += checkDigit(numbers);
  numbers += checkDigit(numbers);

  return numbers.substr(-2) === stripped.substr(-2);
};

CPF.generate = (formatted) => {
  let numbers = "",
    i = 0;

  while (i < 9) {
    numbers += Math.floor(Math.random() * 9);
    i++;
  }

  numbers += checkDigit(numbers);
  numbers += checkDigit(numbers);

  return (formatted ? CPF.format(numbers) : numbers);
};

module.exports = CPF;
<commit_msg>Commit<commit_after>/**
 * @fileoverview Responsible for generating file, validate, format Register of
 * Brazilian Individuals (CPF)
 *
 * @license The MIT License (MIT)
 * Copyright (c) 2016 Rodrigo Oler
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
 * OR OTHER DEALINGS IN THE SOFTWARE.
 * @author https://github.com/RodrigoOler/ (Rodrigo Oler)
 * @version 1.0.0
 */

"use strict";

/**
 * List of CPF Ignored
 * @type {Array}
 * @author https://github.com/RodrigoOler/ (Rodrigo Oler)
 */
const IGNORELIST = [
  '00000000000',
  '11111111111',
  '22222222222',
  '33333333333',
  '44444444444',
  '55555555555',
  '66666666666',
  '77777777777',
  '88888888888',
  '99999999999',
  '12345678909'
];

let checkDigit = (numbers) => {
  numbers = numbers.split("").map((number) => parseInt(number, 10));

  let modulus = numbers.length + 1;

  let multiply = numbers.map((number, index) => number * (modulus - index));

  let mod = multiply.reduce((buffer, number) => buffer + number) % 11;

  return (mod < 2 ? 0 : 11 - mod);
};

let CPF = {};

CPF.strip = (number) => (number || "").toString().replace(/[^\d]/g, "");

CPF.format = (number) => CPF.strip(number).replace(
  /^(\d{3})(\d{3})(\d{3})(\d{2})$/, "$1.$2.$3-$4");

CPF.isValid = (number) => {
  let stripped = CPF.strip(number);

  if (!stripped) return false;

  if (stripped.length !== 11) return false;

  if (IGNORELIST.indexOf(stripped) >= 0) return false;

  let numbers = stripped.substr(0, 9);
  numbers += checkDigit(numbers);
  numbers += checkDigit(numbers);

  return numbers.substr(-2) === stripped.substr(-2);
};

CPF.generate = (formatted) => {
  let numbers = "",
    i = 0;

  while (i < 9) {
    numbers += Math.floor(Math.random() * 9);
    i++;
  }

  numbers += checkDigit(numbers);
  numbers += checkDigit(numbers);

  return (formatted ? CPF.format(numbers) : numbers);
};

module.exports = CPF;
<|endoftext|>


<commit_before>"use strict";

var crx = require('crx');
var exec = require('child_process').exec;
var path = require('path');

var required_properties = ['manifest_version', 'name', 'version'];
var homeDir = process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE;
var filename_template = "<%= pkg.name %>-<%= manifest.version %>.crx";

/**
 * Resolve the home directory of a supposed-path value
 *
 * @param {String} value
 * @returns {String}
 */
function resolveHomeDirectory(value){
  if (homeDir && typeof value === 'string' && value[0] === '~'){
    value = value.replace(/^~/, homeDir);
  }

  return value;
}

/**
 * Initializes the grunt helper
 *
 * @param {grunt} grunt
 * @returns {{build: Function, expandConfiguration: Function, getTaskConfiguration: Function, resolveHomeDirectory: Function}}
 */
exports.init = function(grunt){
  /**
   * Builds a pre-configured chrome extension in 3 steps
   *
   * @api
   * @param {crx} ChromeExtension
   * @param {Function} callback
   * @return null
   */
  function build(ChromeExtension, callback) {
    grunt.file.mkdir(path.dirname(ChromeExtension.dest));

    grunt.util.async.series([
      function(done){
        ChromeExtension.load(done);
      },
      function(done){
        if (!Array.isArray(ChromeExtension.exclude) || !ChromeExtension.exclude.length){
          return done();
        }

        var files = grunt.file.expand(ChromeExtension.exclude.map(function(pattern){
          return path.join(ChromeExtension.path, '/', pattern);
        }));

        exec('rm -rf '+ files.join(' '), done);
      },
      function(done){
        ChromeExtension.pack(function(err, data){
          if (err){
            throw new grunt.task.taskError(err);
          }

          grunt.file.write(this.dest, data);

          done();
        });
      }
    ], callback);
  }

  function createObject(taskConfig, defaults){
    taskConfig = expandConfiguration(taskConfig, defaults);

    return new crx(taskConfig);
  }

  /**
   * Refines a task configuration (expand settings etc.)
   *
   * @param {Object} taskConfig
   * @param {Object=} defaults
   * @return {Object}
   */
  function expandConfiguration(taskConfig, defaults){
    defaults = defaults || getTaskConfiguration();
    grunt.util._.defaults(taskConfig, defaults, taskConfig);

    ['dest', 'src'].forEach(function(key){
      if ((Array.isArray(taskConfig[key]) && taskConfig[key].length === 0) || !taskConfig[key]){
        grunt.fail.fatal("You can't specify an empty '"+key+"' configuration value.");
      }
    });

    // XXX (alexeykuzmin): Is there a better way to get source folder path?
    var sourceDir = Array.isArray(taskConfig.src) ? taskConfig.src[0] : taskConfig.src;

    // Eventually expanding `~` in config paths
    ['privateKey', 'src', 'dest'].forEach(function(key){
      taskConfig[key] = resolveHomeDirectory(taskConfig[key]);
    });

    // Checking availability
    if (!grunt.file.exists(sourceDir)){
      grunt.fail.fatal('Unable to locate source directory.');
    }

    if (!grunt.file.exists(taskConfig.privateKey)){
      grunt.fail.fatal('Unable to locate your private key.');
    }
    else{
      taskConfig.privateKey = grunt.file.read(taskConfig.privateKey);
    }

    // Check extension manifest
    taskConfig.manifest = grunt.file.readJSON(path.join(sourceDir, 'manifest.json'));
    required_properties.forEach(function(prop) {
      if ('undefined' === typeof taskConfig.manifest[prop]) {
        grunt.fail.fatal('Invalid manifest: property "' + prop + '" is missing.');
      }
    });

    // Expanding destination
    if (grunt.file.isDir(taskConfig.dest)){
      var filename = taskConfig.filename || filename_template;

      taskConfig.dest = path.join(taskConfig.dest, filename);
    }

    ['dest'].forEach(function(key){
      taskConfig[key] = grunt.template.process(taskConfig[key], {
        "data": {
          "manifest": taskConfig.manifest,
          "pkg": grunt.file.readJSON('package.json')
        }
      });
    });

    // Codebase generation (@todo cleanup that with clean separation of grunt and chrome extension config)
    taskConfig.codebase = taskConfig.baseURL || taskConfig.codebase || null;

    if (taskConfig.codebase && !/.crx$/.test(taskConfig.codebase)){
      taskConfig.codebase = taskConfig.codebase.replace(/\/$/, '');
      taskConfig.codebase += '/' + path.basename(taskConfig.dest);
    }

    // @todo remove that to better separate grunt config and Chrome Extension config
    taskConfig.rootDirectory = taskConfig.src;
    taskConfig.maxBuffer = taskConfig.options.maxBuffer || taskConfig.maxBuffer || undefined;

    return taskConfig;
  }

  /**
   * Returns a task configuration profile
   *
   * @param {String=} profile
   * @return {Object}
   */
  function getTaskConfiguration(profile){
    var config;

    profile = profile || 'default';

    config = grunt.file.readJSON('data/config-'+ profile +'.json');

    return config;
  }

  /*
   * Blending
   */
  return {
    "build": build,
    "createObject": createObject,
    "expandConfiguration": expandConfiguration,
    "filename": filename_template,
    "getTaskConfiguration": getTaskConfiguration,
    "resolveHomeDirectory": resolveHomeDirectory
  };
};<commit_msg>Fixing file location<commit_after>"use strict";

var crx = require('crx');
var exec = require('child_process').exec;
var path = require('path');

var required_properties = ['manifest_version', 'name', 'version'];
var homeDir = process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE;
var filename_template = "<%= pkg.name %>-<%= manifest.version %>.crx";

/**
 * Resolve the home directory of a supposed-path value
 *
 * @param {String} value
 * @returns {String}
 */
function resolveHomeDirectory(value){
  if (homeDir && typeof value === 'string' && value[0] === '~'){
    value = value.replace(/^~/, homeDir);
  }

  return value;
}

/**
 * Initializes the grunt helper
 *
 * @param {grunt} grunt
 * @returns {{build: Function, expandConfiguration: Function, getTaskConfiguration: Function, resolveHomeDirectory: Function}}
 */
exports.init = function(grunt){
  /**
   * Builds a pre-configured chrome extension in 3 steps
   *
   * @api
   * @param {crx} ChromeExtension
   * @param {Function} callback
   * @return null
   */
  function build(ChromeExtension, callback) {
    grunt.file.mkdir(path.dirname(ChromeExtension.dest));

    grunt.util.async.series([
      function(done){
        ChromeExtension.load(done);
      },
      function(done){
        if (!Array.isArray(ChromeExtension.exclude) || !ChromeExtension.exclude.length){
          return done();
        }

        var files = grunt.file.expand(ChromeExtension.exclude.map(function(pattern){
          return path.join(ChromeExtension.path, '/', pattern);
        }));

        exec('rm -rf '+ files.join(' '), done);
      },
      function(done){
        ChromeExtension.pack(function(err, data){
          if (err){
            throw new grunt.task.taskError(err);
          }

          grunt.file.write(this.dest, data);

          done();
        });
      }
    ], callback);
  }

  function createObject(taskConfig, defaults){
    taskConfig = expandConfiguration(taskConfig, defaults);

    return new crx(taskConfig);
  }

  /**
   * Refines a task configuration (expand settings etc.)
   *
   * @param {Object} taskConfig
   * @param {Object=} defaults
   * @return {Object}
   */
  function expandConfiguration(taskConfig, defaults){
    defaults = defaults || getTaskConfiguration();
    grunt.util._.defaults(taskConfig, defaults, taskConfig);

    ['dest', 'src'].forEach(function(key){
      if ((Array.isArray(taskConfig[key]) && taskConfig[key].length === 0) || !taskConfig[key]){
        grunt.fail.fatal("You can't specify an empty '"+key+"' configuration value.");
      }
    });

    // XXX (alexeykuzmin): Is there a better way to get source folder path?
    var sourceDir = Array.isArray(taskConfig.src) ? taskConfig.src[0] : taskConfig.src;

    // Eventually expanding `~` in config paths
    ['privateKey', 'src', 'dest'].forEach(function(key){
      taskConfig[key] = resolveHomeDirectory(taskConfig[key]);
    });

    // Checking availability
    if (!grunt.file.exists(sourceDir)){
      grunt.fail.fatal('Unable to locate source directory.');
    }

    if (!grunt.file.exists(taskConfig.privateKey)){
      grunt.fail.fatal('Unable to locate your private key.');
    }
    else{
      taskConfig.privateKey = grunt.file.read(taskConfig.privateKey);
    }

    // Check extension manifest
    taskConfig.manifest = grunt.file.readJSON(path.join(sourceDir, 'manifest.json'));
    required_properties.forEach(function(prop) {
      if ('undefined' === typeof taskConfig.manifest[prop]) {
        grunt.fail.fatal('Invalid manifest: property "' + prop + '" is missing.');
      }
    });

    // Expanding destination
    if (grunt.file.isDir(taskConfig.dest)){
      var filename = taskConfig.filename || filename_template;

      taskConfig.dest = path.join(taskConfig.dest, filename);
    }

    ['dest'].forEach(function(key){
      taskConfig[key] = grunt.template.process(taskConfig[key], {
        "data": {
          "manifest": taskConfig.manifest,
          "pkg": grunt.file.readJSON('package.json')
        }
      });
    });

    // Codebase generation (@todo cleanup that with clean separation of grunt and chrome extension config)
    taskConfig.codebase = taskConfig.baseURL || taskConfig.codebase || null;

    if (taskConfig.codebase && !/.crx$/.test(taskConfig.codebase)){
      taskConfig.codebase = taskConfig.codebase.replace(/\/$/, '');
      taskConfig.codebase += '/' + path.basename(taskConfig.dest);
    }

    // @todo remove that to better separate grunt config and Chrome Extension config
    taskConfig.rootDirectory = taskConfig.src;
    taskConfig.maxBuffer = taskConfig.options.maxBuffer || taskConfig.maxBuffer || undefined;

    return taskConfig;
  }

  /**
   * Returns a task configuration profile
   *
   * @param {String=} profile
   * @return {Object}
   */
  function getTaskConfiguration(profile){
    var config;

    profile = profile || 'default';

    config = grunt.file.readJSON(__dirname + '/../data/config-'+ profile +'.json');

    return config;
  }

  /*
   * Blending
   */
  return {
    "build": build,
    "createObject": createObject,
    "expandConfiguration": expandConfiguration,
    "filename": filename_template,
    "getTaskConfiguration": getTaskConfiguration,
    "resolveHomeDirectory": resolveHomeDirectory
  };
};<|endoftext|>


<commit_before>/**
 * 为常用的 button 组件添加点击效果，同时全局增加 tap 事件
 *
 * @author      mufeng  <smufeng@gmail.com>
 * @version     0.1     <2015-06-02>
 */

$.ready(function() {
    var $document = $(document), tap = {}, inputs, delay = 300;

    function checkClass(item, test) {
        var find, cls = item.attr ? item.attr("class") :
                  item.getAttribute || item.getAttribute("class");

        /* 转换为数组，便于后面操作 */
        cls  = cls.split(" ");
        find = (test || "button item tab-item").split(" ");

        for (var i=0; i<find.length; i++) {
            if (cls.indexOf(find[i]) >= 0) return true;
        }

        return false;
    }

    // 清除激活类
    function clearActive($target) {
        if (checkClass($target)) {

            clearTimeout($target.data("_active_handle"));
            $target.removeClass("active");
        }
    }

    /* TODO: fastclick 功能完成 */
    $document.on("touchstart", function(e) {
        /* 忽略多指手势操作 */
        console.log(e)
        var touchs = e.changedTouches;
        if (touchs && touchs.length > 1) return true;

        var $target = $(e.target), handle, tagName, path = e.path;

        /* 记录此次点击事件的相关信息，用于方法判断 */
        if (touchs && touchs[0]) {
            tap.startX = touchs[0].pageX;
            tap.startY = touchs[0].pageY;
        } else {
            tap.startX = e.pageX;
            tap.startY = e.pageY;
        }
        tap.startT = $.getTime();

        /* 修复移动端input点击焦点不更新的问题 */
        tagName = e.target.tagName;
        if ("INPUT TEXTAREA".search(tagName) >= 0) {
            inputs = e.target;
        } else {
            inputs && inputs.blur();    // 刷新焦点
        }

        /* 给按钮类的组件添加点击样式 */
        for (var i = 0; i<path.length; i++) {
            if (checkClass($target)) {
                handle = setTimeout((function($actobj) {
                    return function() {
                        $actobj.addClass("active");
                    }
                })($target), 24);
                $target.data("_active_handle", handle);
            }
        }
    });

    $document.on("touchmove", $.delayCall($.onceCall(function(e) {
        e.preventDefault(); // 修复微信下拉显示网页地址

        for(var i = 0; i<e.path.length; i++) {
            clearActive($(e.target));
        }
    }), 16));

    $document.on("touchend", function(e) {
        var cx, cy, ct, $target = $(e.target),
            touch = e.changedTouches ? e.changedTouches[0] : e;

        cx = Math.abs(touch.pageX - tap.startX);
        cy = Math.abs(touch.pageY - tap.startY);
        ct = $.getTime() - tap.startT;

        if (cx<5 && cy < 5 && ct < delay) {
            $target.trigger("tap");
        }

        /* 如果点击时间太短，手动延迟动画移除时间 */
        setTimeout(function() {
            clearActive($target);   // 清除激活类
        }, 220-ct >= 0 ? 220-ct : 0);
    });
});<commit_msg>tap事件bug修复<commit_after>/**
 * 为常用的 button 组件添加点击效果，同时全局增加 tap 事件
 *
 * @author      mufeng  <smufeng@gmail.com>
 * @version     0.1     <2015-06-02>
 */

$.ready(function() {
    var $document = $(document), tap = {}, inputs, delay = 300;

    function checkClass(item, test) {
        var find, cls = item.attr ? item.attr("class") :
                  item.getAttribute || item.getAttribute("class");

        /* 转换为数组，便于后面操作 */
        cls  = (cls || "").split(" ");
        find = (test || "button item tab-item").split(" ");

        for (var i=0; i<find.length; i++) {
            if (cls.indexOf(find[i]) >= 0) return true;
        }

        return false;
    }

    // 清除激活类
    function clearActive($target) {
        if (checkClass($target)) {

            clearTimeout($target.data("_active_handle"));
            $target.removeClass("active");
        }
    }

    /* TODO: fastclick 功能完成 */
    $document.on("touchstart", function(e) {
        /* 忽略多指手势操作 */
        console.log(e)
        var touchs = e.changedTouches;
        if (touchs && touchs.length > 1) return true;

        var $target = $(e.target), handle, tagName, path = e.path;

        /* 记录此次点击事件的相关信息，用于方法判断 */
        if (touchs && touchs[0]) {
            tap.startX = touchs[0].pageX;
            tap.startY = touchs[0].pageY;
        } else {
            tap.startX = e.pageX;
            tap.startY = e.pageY;
        }
        tap.startT = $.getTime();

        /* 修复移动端input点击焦点不更新的问题 */
        tagName = e.target.tagName;
        if ("INPUT TEXTAREA".search(tagName) >= 0) {
            inputs = e.target;
        } else {
            inputs && inputs.blur();    // 刷新焦点
        }

        /* 给按钮类的组件添加点击样式 */
        for (var i = 0; i<path.length; i++) {
            if (checkClass($target)) {
                handle = setTimeout((function($actobj) {
                    return function() {
                        $actobj.addClass("active");
                    }
                })($target), 24);
                $target.data("_active_handle", handle);
            }
        }
    });

    $document.on("touchmove", $.delayCall($.onceCall(function(e) {
        e.preventDefault(); // 修复微信下拉显示网页地址

        for(var i = 0; i<e.path.length; i++) {
            clearActive($(e.target));
        }
    }), 16));

    $document.on("touchend", function(e) {
        var cx, cy, ct, $target = $(e.target),
            touch = e.changedTouches ? e.changedTouches[0] : e;

        cx = Math.abs(touch.pageX - tap.startX);
        cy = Math.abs(touch.pageY - tap.startY);
        ct = $.getTime() - tap.startT;

        if (cx<5 && cy < 5 && ct < delay) {
            $target.trigger("tap");
        }

        /* 如果点击时间太短，手动延迟动画移除时间 */
        setTimeout(function() {
            clearActive($target);   // 清除激活类
        }, 220-ct >= 0 ? 220-ct : 0);
    });
});<|endoftext|>


<commit_before>/* global $ _ requests sidebar */
'use strict';
// ==UserScript==
// @name         MusicBrainz: Shortcuts
// @namespace    mbz-joseffriedrich
// @author       Josef Friedrich
// @version      10
// @downloadURL  https://raw.githubusercontent.com/Josef-Friedrich/greasemonkey-user-scripts/master/mbz-shortcuts.user.js
// @updateURL    https://raw.githubusercontent.com/Josef-Friedrich/greasemonkey-user-scripts/master/mbz-shortcuts.user.js
// @supportURL   https://github.com/Josef-Friedrich/greasemonkey-user-scripts
// @icon         https://raw.githubusercontent.com/Josef-Friedrich/greasemonkey-user-scripts/master/icon.png
// @description  musicbrainz.org: Add some shortcuts
// @compatible   firefox+greasemonkey
// @licence      MIT (https://opensource.org/licenses/MIT)
// @include      http*://musicbrainz.org/release/*/edit-relationships
// @require      https://craig.global.ssl.fastly.net/js/mousetrap/mousetrap.min.js
// @grant        none
// @run-at       document-end
// ==/UserScript==

function AddShortCuts(id, key) {
    var link = $("#" + id);
    link.attr({
        title: "Shortcut: " + key,
        accesskey: key
    });
    var text = link.html();
    link.html(text + " (" + key + ")");
}

AddShortCuts("batch-recording", "r");
AddShortCuts("batch-create-works", "n");
AddShortCuts("batch-work", "w");
<commit_msg>hotkey version<commit_after>/* global $ _ requests sidebar */
'use strict';
// ==UserScript==
// @name         MusicBrainz: Shortcuts
// @namespace    mbz-joseffriedrich
// @author       Josef Friedrich
// @version      10
// @downloadURL  https://raw.githubusercontent.com/Josef-Friedrich/greasemonkey-user-scripts/master/mbz-shortcuts.user.js
// @updateURL    https://raw.githubusercontent.com/Josef-Friedrich/greasemonkey-user-scripts/master/mbz-shortcuts.user.js
// @supportURL   https://github.com/Josef-Friedrich/greasemonkey-user-scripts
// @icon         https://raw.githubusercontent.com/Josef-Friedrich/greasemonkey-user-scripts/master/icon.png
// @description  musicbrainz.org: Add some shortcuts
// @compatible   firefox+greasemonkey
// @licence      MIT (https://opensource.org/licenses/MIT)
// @include      http*://musicbrainz.org/release/*/edit-relationships
// @require      https://raw.githubusercontent.com/jeresig/jquery.hotkeys/master/jquery.hotkeys.js
// @grant        none
// @run-at       document-end
// ==/UserScript==

function AddShortCuts(id, key) {
  var link = $('#' + id);
  link.bind('keydown', key, function() { this.click();
  });
  link.attr({
    title: 'Shortcut: ' + key
  });
  var text = link.html();
  link.html(text + ' (' + key + ')');
}
AddShortCuts('batch-recording', 'r');
AddShortCuts('batch-create-works', 'n');
AddShortCuts('batch-work', 'w');
<|endoftext|>


<commit_before>/*!
 * angular-masonry <%= pkg.version %>
 * Pascal Hartig, weluse GmbH, http://weluse.de/
 * License: MIT
 */
(function () {
  'use strict';

  angular.module('wu.masonry', [])
    .controller('MasonryCtrl', function controller($scope, $element, $timeout) {
      var bricks = {};
      var reloadScheduled = false;
      var self = this;

      // Make sure it's only executed once within a reasonable time-frame in
      // case multiple elements are removed or added at once.
      function scheduleReload() {
        if (!reloadScheduled) {
          reloadScheduled = true;

          $timeout(function relayout() {
            reloadScheduled = false;
            $element.masonry('layout');
          }, 0);
        }
      }

      function defaultLoaded($element) {
        $element.addClass('loaded');
      }

      this.appendBrick = function appendBrick(element, id) {
        function _append() {
          if (Object.keys(bricks).length === 0) {
            // Call masonry asynchronously on initialization.
            $timeout(function () {
              $element.masonry('resize');
            });
          }

          if (bricks[id] === undefined) {
            // I wanted to make this dynamic but ran into huuuge memory leaks
            // that I couldn't fix. If you know how to dynamically add a
            // callback so one could say <masonry loaded="callback($element)">
            // please submit a pull request!
            defaultLoaded(element);

            // Keep track of added elements.
            bricks[id] = true;
            $element.masonry('appended', element, true);
            scheduleReload();
          }
        }

        element.imagesLoaded(_append);
      };

      this.removeBrick = function removeBrick(id, element) {
        delete bricks[id];
        $element.masonry('remove', element);

        scheduleReload();
      };
    }).directive('masonry', function () {
      return {
        restrict: 'AE',
        controller: 'MasonryCtrl',
        link: function postLink(scope, element, attrs) {
          var attrOptions = scope.$eval(attrs.options);
          var options = angular.extend(attrOptions || {}, {
            itemSelector: attrs.itemSelector || '.masonry-brick',
            columnWidth: attrs.columnWidth
          });
          element.masonry(options);
        }
      };
    }).directive('masonryBrick', function () {
      return {
        restrict: 'AC',
        require: '^masonry',
        link: function postLink(scope, element, attrs, ctrl) {
          var id = scope.$id;

          ctrl.appendBrick(element, id);
          scope.$on('$destroy', function () {
            ctrl.removeBrick(id, element);
          });
        }
      };
    });
}());
<commit_msg>chore(app): remove unused self<commit_after>/*!
 * angular-masonry <%= pkg.version %>
 * Pascal Hartig, weluse GmbH, http://weluse.de/
 * License: MIT
 */
(function () {
  'use strict';

  angular.module('wu.masonry', [])
    .controller('MasonryCtrl', function controller($scope, $element, $timeout) {
      var bricks = {};
      var reloadScheduled = false;

      // Make sure it's only executed once within a reasonable time-frame in
      // case multiple elements are removed or added at once.
      function scheduleReload() {
        if (!reloadScheduled) {
          reloadScheduled = true;

          $timeout(function relayout() {
            reloadScheduled = false;
            $element.masonry('layout');
          }, 0);
        }
      }

      function defaultLoaded($element) {
        $element.addClass('loaded');
      }

      this.appendBrick = function appendBrick(element, id) {
        function _append() {
          if (Object.keys(bricks).length === 0) {
            // Call masonry asynchronously on initialization.
            $timeout(function () {
              $element.masonry('resize');
            });
          }

          if (bricks[id] === undefined) {
            // I wanted to make this dynamic but ran into huuuge memory leaks
            // that I couldn't fix. If you know how to dynamically add a
            // callback so one could say <masonry loaded="callback($element)">
            // please submit a pull request!
            defaultLoaded(element);

            // Keep track of added elements.
            bricks[id] = true;
            $element.masonry('appended', element, true);
            scheduleReload();
          }
        }

        element.imagesLoaded(_append);
      };

      this.removeBrick = function removeBrick(id, element) {
        delete bricks[id];
        $element.masonry('remove', element);

        scheduleReload();
      };
    }).directive('masonry', function () {
      return {
        restrict: 'AE',
        controller: 'MasonryCtrl',
        link: function postLink(scope, element, attrs) {
          var attrOptions = scope.$eval(attrs.options);
          var options = angular.extend(attrOptions || {}, {
            itemSelector: attrs.itemSelector || '.masonry-brick',
            columnWidth: attrs.columnWidth
          });
          element.masonry(options);
        }
      };
    }).directive('masonryBrick', function () {
      return {
        restrict: 'AC',
        require: '^masonry',
        link: function postLink(scope, element, attrs, ctrl) {
          var id = scope.$id;

          ctrl.appendBrick(element, id);
          scope.$on('$destroy', function () {
            ctrl.removeBrick(id, element);
          });
        }
      };
    });
}());
<|endoftext|>


<commit_before>
/* medea - an Open Source, WebGL-based 3d engine for next-generation browser games.
 * (or alternatively, for clumsy and mostly useless tech demos written solely for fun)
 *
 * medea is (c) 2011, Alexander C. Gessler
 * licensed under the terms and conditions of a 3 clause BSD license.
 */

medea._addMod('shader',['filesystem'],function(undefined) {
	"use strict";
	var medea = this, gl = medea.gl;

	medea.SHADER_TYPE_PIXEL = gl.FRAGMENT_SHADER;
	medea.SHADER_TYPE_VERTEX = gl.VERTEX_SHADER;

	medea._initMod('filesystem');

	// cache for compiled shader objects.
	var sh_cache = {
	};

	medea.Shader = medea.Resource.extend( {

		init : function(src, defines, callback) {

			this.type = src.split('.').pop() == 'ps' ? medea.SHADER_TYPE_PIXEL : medea.SHADER_TYPE_VERTEX;
			this.shader = 0;
			this.defines = defines ? medea.Merge(defines,{}) : {};

			// trigger deferred loading
			this._super(src, callback);
		},

		OnDelayedInit : function(data) {

// #ifdef DEBUG
			medea.DebugAssert(typeof data === "string","got unexpected argument, perhaps the source for the shader was not a single resource?");
// #endif
			this.source = data;

			var c = this._GetCacheName();
			var s = sh_cache[c];
			if(s !== undefined) {
				this.gen_source = s.gen_source;
				this.shader = s.shader;
				this._super();
				return;
			}

			s = this.shader = gl.createShader(this.type);
			this.gen_source = this._PrependDefines(data);

			// XXX run preprocessor manually so we have access to the
			// final, preprocessed shader.

			// create a new cache entry for this shader
			sh_cache[c] = {
				shader : this.shader,
				source : this.source,
				gen_source : this.gen_source
			};

			// compile the preprocessed shader
			gl.shaderSource(s,this.gen_source);
			gl.compileShader(s);

			if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) {
				medea.NotifyFatal("failure compiling shader " +  this.src + ", error log: " + gl.getShaderInfoLog(s));
				return;
			}

			// mark this resource as complete
			this._super();

			medea.LogDebug("successfully compiled shader " + this.src);
		},

		GetSourceCode : function() {
			return this.source;
		},

		GetPreProcessedSourceCode : function() {
		// XXX this is not the preprocessed source code ..
			return this.gen_source;
		},

		GetGlShader : function(gl) {
			return this.shader;
		},

		_PrependDefines : function(data) {
			var d = this.defines;

			var o = '';
			for(var k in d) {
				o += '#define ' + k + ' ' + (d[k] || '') + '\n';
			}
			if (o === '') {
				return data;
			}
			return	'/* !begin medea-generated head! */\n' + o +
					'/* !end medea-generated head! */\n' + data;
		},

		_GetCacheName : function() {
			var o = this.src;

			if (this.defines) {
				var d = this.defines;
				o += '#';
				for(var k in d) {
					o += k+'='+(d[k] || '');
				}
			}

			return o;
		},
	});

	medea.CreateShader = function(res, defines, callback) {
		return new medea.Shader(res, defines, callback);
	}
});
<commit_msg>- use cpp.js to preprocess GLSL shaders.<commit_after>
/* medea - an Open Source, WebGL-based 3d engine for next-generation browser games.
 * (or alternatively, for clumsy and mostly useless tech demos written solely for fun)
 *
 * medea is (c) 2011, Alexander C. Gessler
 * licensed under the terms and conditions of a 3 clause BSD license.
 */

medea._addMod('shader',['filesystem','cpp/cpp.js'],function(undefined) {
	"use strict";
	var medea = this, gl = medea.gl;

	medea.SHADER_TYPE_PIXEL = gl.FRAGMENT_SHADER;
	medea.SHADER_TYPE_VERTEX = gl.VERTEX_SHADER;

	medea._initMod('filesystem');

	// cache for compiled shader objects.
	var sh_cache = {
	};

	var default_defines = {
		'GL_ES' : ''
	};

	medea.Shader = medea.Resource.extend( {

		init : function(src, defines, callback) {

			this.type = src.split('.').pop() == 'ps' ? medea.SHADER_TYPE_PIXEL : medea.SHADER_TYPE_VERTEX;
			this.shader = 0;
			this.defines = medea.Merge(defines || {},default_defines);

			// trigger deferred loading
			this._super(src, callback);
		},

		OnDelayedInit : function(data) {

// #ifdef DEBUG
			medea.DebugAssert(typeof data === "string","got unexpected argument, perhaps the source for the shader was not a single resource?");
// #endif
			this.source = data;

			var c = this._GetCacheName();
			var s = sh_cache[c];
			if(s !== undefined) {
				this.gen_source = s.gen_source;
				this.shader = s.shader;
				this._super();
				return;
			}

			s = this.shader = gl.createShader(this.type);

			var cpp = cpp_js();
			cpp.define_multiple(this.defines);
			this.gen_source = cpp.run(data, this.src);

			// create a new cache entry for this shader
			sh_cache[c] = {
				shader : this.shader,
				source : this.source,
				gen_source : this.gen_source
			};

			// compile the preprocessed shader
			gl.shaderSource(s,this.gen_source);
			gl.compileShader(s);

			if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) {
				medea.NotifyFatal("failure compiling shader " +  this.src + ", error log: " + gl.getShaderInfoLog(s));
				return;
			}

			// mark this resource as complete
			this._super();

			medea.LogDebug("successfully compiled shader " + this.src);
		},

		GetSourceCode : function() {
			return this.source;
		},

		GetPreProcessedSourceCode : function() {
			return this.gen_source;
		},

		GetGlShader : function(gl) {
			return this.shader;
		},

		_PrependDefines : function(data) {
			var d = this.defines;

			var o = '';
			for(var k in d) {
				o += '#define ' + k + ' ' + (d[k] || '') + '\n';
			}
			if (o === '') {
				return data;
			}
			return	'/* !begin medea-generated head! */\n' + o +
					'/* !end medea-generated head! */\n' + data;
		},

		_GetCacheName : function() {
			var o = this.src;

			if (this.defines) {
				var d = this.defines;
				o += '#';
				for(var k in d) {
					o += k+'='+(d[k] || '');
				}
			}

			return o;
		},
	});

	medea.CreateShader = function(res, defines, callback) {
		return new medea.Shader(res, defines, callback);
	}
});
<|endoftext|>


<commit_before>import gitHub from 'github-basic';
import Promise from 'promise';
import throat from 'throat';
import chalk from 'chalk';

const client = gitHub({version: 3, auth: process.env.GITHUB_TOKEN});
const betaClient = gitHub({version: 3, auth: process.env.GITHUB_TOKEN});
betaClient._version = 'application/vnd.github.polaris-preview+json';
const logins = [
  'ForbesLindesay-Bot',
  'greenkeeperio-bot',
];

function isMergable(issue) {
  if (!issue.pull_request) return false;
  if (logins.indexOf(issue.user.login) !== -1) {
    // at least one hour old
    return issue.updated_at < (new Date(Date.now() - 1000 * 60 * 60)).toISOString();
  }
  return false;
}
function mergePullRequest(pr) {
  return client.get(pr.commits_url).then(commits => {
    if (commits.length === 1) {
      return betaClient.put('/repos/:owner/:repo/pulls/:number/merge', {
        owner: pr.base.repo.owner.login,
        repo: pr.base.repo.name,
        number: pr.number,
        commit_title: commits[0].commit.message.split('\n\n')[0] + ' (#' + pr.number + ')',
        commit_message: commits[0].commit.message.split('\n\n').slice(1).join('\n\n'),
        sha: pr.head.sha,
        squash: true,
      }).then(res => {
        if (res.merged) console.log('merged');
        if (res.merged && pr.head.repo.id === pr.base.repo.id) {
          return client.delete('/repos/:owner/:repo/git/refs/:ref',
            {
              owner: pr.head.repo.owner.login,
              repo: pr.head.repo.name,
              ref: 'heads/' + pr.head.ref,
            }
          );
        }
      });
    }
  });
}
function handlePullRequest(pr) {
  if (!pr.mergeable) return null;
  return client.get(pr.statuses_url).then(
    statuses => {
      const statusesMap = {};
      statuses.forEach(status => {
        if (!statusesMap[status.context] || status.created_at > statusesMap[status.context]) {
          statusesMap[status.context] = status.created_at;
        }
      });
      statuses = statuses.filter(
        status => status.created_at === statusesMap[status.context]
      );
      if (statuses.length && statuses.every(status => status.state === 'success')) {
        console.log(chalk.green('merging:'));
        console.log(pr.title);
        console.dir(pr.html_url);
        return mergePullRequest(pr);
      } else {
        console.log(chalk.red('not merging:'));
        console.log(pr.title);
        console.dir(pr.html_url);
      }
    }
  );
}

function run(getIssues) {
  let getNext = null;
  return getIssues().then(issues => {
    getNext = issues.getNext;
    return Promise.all(
      issues.filter(isMergable).map(
        throat(1, issue => client.get(issue.pull_request.url).then(pr => handlePullRequest(pr)))
      )
    );
  }).then(() => {
    if (getNext) return run(getNext);
  });
}
export default function (data) {
  return run(() => client.get('/issues', {filter: 'all', state: 'open'}));
}
<commit_msg>Speed up auto-merge<commit_after>import gitHub from 'github-basic';
import Promise from 'promise';
import throat from 'throat';
import chalk from 'chalk';

const client = gitHub({version: 3, auth: process.env.GITHUB_TOKEN});
const betaClient = gitHub({version: 3, auth: process.env.GITHUB_TOKEN});
betaClient._version = 'application/vnd.github.polaris-preview+json';
const logins = [
  'ForbesLindesay-Bot',
  'greenkeeperio-bot',
];

function isMergable(issue) {
  if (!issue.pull_request) return false;
  if (logins.indexOf(issue.user.login) !== -1) {
    // at least 5 minutes
    return issue.updated_at < (new Date(Date.now() - 1000 * 60 * 5)).toISOString();
  }
  return false;
}
function mergePullRequest(pr) {
  return client.get(pr.commits_url).then(commits => {
    if (commits.length === 1) {
      return betaClient.put('/repos/:owner/:repo/pulls/:number/merge', {
        owner: pr.base.repo.owner.login,
        repo: pr.base.repo.name,
        number: pr.number,
        commit_title: commits[0].commit.message.split('\n\n')[0] + ' (#' + pr.number + ')',
        commit_message: commits[0].commit.message.split('\n\n').slice(1).join('\n\n'),
        sha: pr.head.sha,
        squash: true,
      }).then(res => {
        if (res.merged) console.log('merged');
        if (res.merged && pr.head.repo.id === pr.base.repo.id) {
          return client.delete('/repos/:owner/:repo/git/refs/:ref',
            {
              owner: pr.head.repo.owner.login,
              repo: pr.head.repo.name,
              ref: 'heads/' + pr.head.ref,
            }
          );
        }
      });
    }
  });
}
function handlePullRequest(pr) {
  if (!pr.mergeable) return null;
  return client.get(pr.statuses_url).then(
    statuses => {
      const statusesMap = {};
      statuses.forEach(status => {
        if (!statusesMap[status.context] || status.created_at > statusesMap[status.context]) {
          statusesMap[status.context] = status.created_at;
        }
      });
      statuses = statuses.filter(
        status => status.created_at === statusesMap[status.context]
      );
      if (statuses.length && statuses.every(status => status.state === 'success')) {
        console.log(chalk.green('merging:'));
        console.log(pr.title);
        console.dir(pr.html_url);
        return mergePullRequest(pr);
      } else {
        console.log(chalk.red('not merging:'));
        console.log(pr.title);
        console.dir(pr.html_url);
      }
    }
  );
}

function run(getIssues) {
  let getNext = null;
  return getIssues().then(issues => {
    getNext = issues.getNext;
    return Promise.all(
      issues.filter(isMergable).map(
        throat(1, issue => client.get(issue.pull_request.url).then(pr => handlePullRequest(pr)))
      )
    );
  }).then(() => {
    if (getNext) return run(getNext);
  });
}
export default function (data) {
  return run(() => client.get('/issues', {filter: 'all', state: 'open'}));
}
<|endoftext|>