<commit_before>/*
JS Conversion of the python one I wrote

Clyde's Simple Shuffler Encryption

@Desc
This encryption algorthym is design for users to use their own keys to build
a unique encrypted output. It called shuffler as it uses the inputed key
to shuffle each character in the message, thus making it harder to crack.

I highly advise you to not use this for passwords. Paswords are secured by
hashing and not through encryption. Hashed values can't be decrypted where as
encryption can. Feel free to encrypt stuff for fun and use this as a learning
tool.

If you use this to encrypt something sensitive, use at your own discretion. I am
not responsible for messages you've created that's gotten cracked.

@author
Clyde Smets <clyde.smets@gmail.com>

@license
MIT

*/

const fs = require('fs')

const getKey = () => {
    const enc = fs.readSync('key/encoding.txt', 'utf8')
    return enc
}

const encode = (message, options) => {
    const charList = message.split("")
    const binary = charList.map((char) => {
        const bin = char.charCodeAt(0).toString(2)
        return bin
    })
    const eightBitBin = binary.map((bits) => {
        const eightBit = recPrepend(8, bits, '0')
        return eightBit
    })
    const longBin = eightBitBin.join('')
    const blocks = longBin.match(/.{1,24}/g)
    const padNum = padCount(blocks[blocks.length - 1], 24)
    const fillBlock = fill(blocks[blocks.length - 1], 24)
    blocks[blocks.length - 1] = fillBlock
    const longPaddedBin = blocks.join('')
    const createGroups = ".{1," + options.size + "}"
    const re = new RegExp(createGroups, "g")
    const grouped = longPaddedBin.match(re)
    const fillGrp = fill(grouped[grouped.length - 1], options.size)
    grouped[grouped.length - 1] = fillGrp

    const numInGroup = (24 / options.size) >> 0

    const encoded = recEncodeGrp(
        grouped,
        numInGroup - 1,
        padNum,
        0,
        options
    )

    return encoded
}

const decode = (message, options) => {
    const chars = message.split("")
    const encDeci = chars.map((char) => {
        if (char === options.pad) {
            return char
        } else {
            return options.encoding.indexOf(char)
        }
    })
    const binary = encDeci.map((deci) => {
        if (deci === options.pad) {
            return options.pad
        } else {
            const bin = (deci >>> 0).toString(2)
            const completeBin = recPrepend(options.size, bin, '0')
            return completeBin
        }
    })
    const removePad = binary.filter((bin) => {
        return bin !== options.pad
    })
    const longBinary = removePad.join('')
    const decodedBinary = longBinary.match(/.{1,8}/g)
    const fillDecodedBinary = decodedBinary.map((bin) => {
        return recPrepend(8,bin,'0')
    })
    const removeNull = fillDecodedBinary.filter((bin) => {
        return bin !== '00000000'
    })
    const decodedDeci = removeNull.map((bin) => {
        return parseInt(bin, 2)
    })
    const decodedChar = decodedDeci.map((deci) => {
        return String.fromCharCode(deci)
    })
    const decoded = decodedChar.join('')
    return decoded
}

const recEncodeGrp = (grp, padGrp, padNum, index, opts) => {
    const padCutOff = grp.length - padGrp
    if (index < padCutOff) {
        grp[index] = encodeBits(grp[index], opts.encoding)
        return recEncodeGrp(grp, padGrp, padNum, index + 1, opts)
    } else if (index < grp.length){
        if (index >= (grp.length - padNum) && index < grp.length) {
            grp[index] = opts.pad
        } else {
            grp[index] = encodeBits(grp[index], opts.encoding)
        }
        return recEncodeGrp(grp, padGrp, padNum, index + 1, opts)
    } else {
        return grp.join('')
    }
}

const encodeBits = (bits, encoding) => {
    const index = parseInt(bits, 2)
    return encoding[index]
}

const fill = (bits, size) => {
    const filled = recAppend(size, bits, '0')
    return filled
}

const recAppend = (num, str, char) => {
    if (str.length < num) {
        const append = str + char
        return recAppend(num, append, char)
    } else {
        return str
    }
}

const recPrepend = (num, str, char) => {
    if (str.length < num) {
        const prepend = char + str
        return recPrepend(num, prepend, char)
    } else {
        return str
    }
}

const padCount = (bits, blockSize) => {
    if (bits.length < blockSize) {
        const count = blockSize / bits.length
        const blockBitSize = blockSize / 8
        const numOfPads = blockBitSize - Math.ceil(count)
        return numOfPads
    } else {
        return 0
    }
}

const makeLength = (str, len) => {
    if (str.length < len) {
        return makeLength(str + str, len)
    } else {
        return str.substring(0,len)
    }
}

const resizeKey = (key, len) => {
    if (key.length > len) {
        return key.substring(0, len)
    } else {
        return makeLength(key, len)
    }
}

const shiftValue = (list, pos, num) => {
    const shift = pos + num
    if (shift < list.length) {
        return list[shift]
    } else {
        const remainder = list.length - (pos + 1)
        const wrappedShift = (num - remainder) - 1
        return list[wrappedShift]
    }
}

const getPadNum = (chars, pad) => {
    const pads = chars.filter((char) => {
        return char === pad
    })

    return pads.length
}

const encrypt = (message, options) => {
    const encoded = encode(message, options)
    const encodedChar = encoded.split('')

    const padNum = getPadNum(encodedChar, options.pad)

    encodedChar.splice(encodedChar.length - padNum, padNum)

    const key = resizeKey(options.key, encodedChar.length)

    const encodingList = options.encoding.split('')

    const shiftChars = (index, res) => {
        if (res.length > key.length - 1) {
            return res
        } else {
            const pos = options.encoding.indexOf(encodedChar[index])
            const shifted = shiftValue(encodingList, pos, parseInt(key[index]))
            return shiftChars(index + 1, res + shifted)
        }
    }
    const encrypted = shiftChars(0, '')

    const missingPads = encoded.slice(-padNum)

    return encrypted + missingPads
}

const unShiftValue = (list, pos, shift) => {
    index = pos - shift
    if (index < 0) {
        // Negative number
        return list.length - Math.abs(index)
    } else {
        return index
    }
}

const decrypt = (crypted, options) => {

    const cryptedChar = crypted.split('')
    const padNum = getPadNum(cryptedChar, options.pad)
    cryptedChar.splice(cryptedChar.length - padNum, padNum)

    // Resize the key
    const key = resizeKey(options.key, cryptedChar.length)
    const unshift = (index, res) => {
        if (res.length > key.length - 1) {
            return res
        } else {
            const pos = options.encoding.indexOf(cryptedChar[index])
            const unShiftIndex = unShiftValue(options.encoding, pos,
                parseInt(key[index]))
            const unshifted = options.encoding[unShiftIndex]
            return unshift(index + 1, res + unshifted)
        }
    }

    const unshifted = unshift(0,'')
    const missingPads = crypted.slice(-padNum)
    const encoded = unshifted + missingPads
    const decrypted = decode(encoded, options)
    return decrypted
}

const o = {
    pad: "=",
    encoding: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
    size: 6,
    key: '3924834902384'
}
const e = encrypt("Hello!! I'm a robot. Yahoo! wee poop.s", o)
console.log(e)
const d = decrypt(e, o)
console.log(d)
<commit_msg>Added comments<commit_after>/*
JS Conversion of the python one I wrote
https://github.com/csmets/CSSCrypt

Clyde's Simple Shuffler Encryption

@Desc
This encryption algorthym is design for users to use their own keys to build
a unique encrypted output. It called shuffler as it uses the inputed key
to shuffle each character in the message, thus making it harder to crack.

I highly advise you to not use this for passwords. Paswords are secured by
hashing and not through encryption. Hashed values can't be decrypted where as
encryption can. Feel free to encrypt stuff for fun and use this as a learning
tool.

If you use this to encrypt something sensitive, use at your own discretion. I am
not responsible for messages you've created that's gotten cracked.

@author
Clyde Smets <clyde.smets@gmail.com>

@license
MIT

*/

const encode = (message, options) => {

    // Split message to individual characters for map binary conversion
    const charList = message.split("")

    // Convert characters to binary
    const binary = charList.map((char) => {
        const bin = char.charCodeAt(0).toString(2)
        return bin
    })

    // Make binary 8bit - sometimes a converted character spits only '0101' and
    // not the full 8bits.
    const eightBitBin = binary.map((bits) => {
        const eightBit = recPrepend(8, bits, '0')
        return eightBit
    })

    // Join the binary to one long string
    const longBin = eightBitBin.join('')

    // Split the long binary string into block of 24 used in encoding
    const blocks = longBin.match(/.{1,24}/g)

    // Get the number of pad characters it will need to add. AKA the '='
    // you famously see in base64
    const padNum = padCount(blocks[blocks.length - 1], 24)

    // Make last block size up to 24 bits
    const fillBlock = fill(blocks[blocks.length - 1], 24)
    blocks[blocks.length - 1] = fillBlock

    const longPaddedBin = blocks.join('')

    // Make new blocks of bits using specified encoding size
    const encBlockRegex = ".{1," + options.size + "}"
    const re = new RegExp(encBlockRegex, "g")
    const encBlocks = longPaddedBin.match(re)
    const fillBlock = fill(encBlocks[encBlocks.length - 1], options.size)
    encBlocks[encBlocks.length - 1] = fillBlock

    const numInGroup = (24 / options.size) >> 0

    const encoded = recEncodeGrp(
        grouped,
        numInGroup - 1,
        padNum,
        0,
        options
    )

    return encoded
}

const recEncodeGrp = (grp, padGrp, padNum, index, opts) => {
    const padCutOff = grp.length - padGrp
    if (index < padCutOff) {
        grp[index] = encodeBits(grp[index], opts.encoding)
        return recEncodeGrp(grp, padGrp, padNum, index + 1, opts)
    } else if (index < grp.length){
        if (index >= (grp.length - padNum) && index < grp.length) {
            grp[index] = opts.pad
        } else {
            grp[index] = encodeBits(grp[index], opts.encoding)
        }
        return recEncodeGrp(grp, padGrp, padNum, index + 1, opts)
    } else {
        return grp.join('')
    }
}

const encodeBits = (bits, encoding) => {
    const index = parseInt(bits, 2)
    return encoding[index]
}

const decode = (message, options) => {
    const chars = message.split("")
    const encDeci = chars.map((char) => {
        if (char === options.pad) {
            return char
        } else {
            return options.encoding.indexOf(char)
        }
    })
    const binary = encDeci.map((deci) => {
        if (deci === options.pad) {
            return options.pad
        } else {
            const bin = (deci >>> 0).toString(2)
            const completeBin = recPrepend(options.size, bin, '0')
            return completeBin
        }
    })
    const removePad = binary.filter((bin) => {
        return bin !== options.pad
    })
    const longBinary = removePad.join('')
    const decodedBinary = longBinary.match(/.{1,8}/g)
    const fillDecodedBinary = decodedBinary.map((bin) => {
        return recPrepend(8,bin,'0')
    })
    const removeNull = fillDecodedBinary.filter((bin) => {
        return bin !== '00000000'
    })
    const decodedDeci = removeNull.map((bin) => {
        return parseInt(bin, 2)
    })
    const decodedChar = decodedDeci.map((deci) => {
        return String.fromCharCode(deci)
    })
    const decoded = decodedChar.join('')
    return decoded
}

const fill = (bits, size) => {
    const filled = recAppend(size, bits, '0')
    return filled
}

const recAppend = (num, str, char) => {
    if (str.length < num) {
        const append = str + char
        return recAppend(num, append, char)
    } else {
        return str
    }
}

const recPrepend = (num, str, char) => {
    if (str.length < num) {
        const prepend = char + str
        return recPrepend(num, prepend, char)
    } else {
        return str
    }
}

const padCount = (bits, blockSize) => {
    if (bits.length < blockSize) {
        const count = blockSize / bits.length
        const blockBitSize = blockSize / 8
        const numOfPads = blockBitSize - Math.ceil(count)
        return numOfPads
    } else {
        return 0
    }
}

const makeLength = (str, len) => {
    if (str.length < len) {
        return makeLength(str + str, len)
    } else {
        return str.substring(0,len)
    }
}

const resizeKey = (key, len) => {
    if (key.length > len) {
        return key.substring(0, len)
    } else {
        return makeLength(key, len)
    }
}

const shiftValue = (list, pos, num) => {
    const shift = pos + num
    if (shift < list.length) {
        return list[shift]
    } else {
        const remainder = list.length - (pos + 1)
        const wrappedShift = (num - remainder) - 1
        return list[wrappedShift]
    }
}

const getPadNum = (chars, pad) => {
    const pads = chars.filter((char) => {
        return char === pad
    })

    return pads.length
}

const encrypt = (message, options) => {
    const encoded = encode(message, options)
    const encodedChar = encoded.split('')

    const padNum = getPadNum(encodedChar, options.pad)

    encodedChar.splice(encodedChar.length - padNum, padNum)

    const key = resizeKey(options.key, encodedChar.length)

    const encodingList = options.encoding.split('')

    const shiftChars = (index, res) => {
        if (res.length > key.length - 1) {
            return res
        } else {
            const pos = options.encoding.indexOf(encodedChar[index])
            const shifted = shiftValue(encodingList, pos, parseInt(key[index]))
            return shiftChars(index + 1, res + shifted)
        }
    }
    const encrypted = shiftChars(0, '')

    const missingPads = encoded.slice(-padNum)

    return encrypted + missingPads
}

const unShiftValue = (list, pos, shift) => {
    index = pos - shift
    if (index < 0) {
        // Negative number
        return list.length - Math.abs(index)
    } else {
        return index
    }
}

const decrypt = (crypted, options) => {

    const cryptedChar = crypted.split('')
    const padNum = getPadNum(cryptedChar, options.pad)
    cryptedChar.splice(cryptedChar.length - padNum, padNum)

    // Resize the key
    const key = resizeKey(options.key, cryptedChar.length)
    const unshift = (index, res) => {
        if (res.length > key.length - 1) {
            return res
        } else {
            const pos = options.encoding.indexOf(cryptedChar[index])
            const unShiftIndex = unShiftValue(options.encoding, pos,
                parseInt(key[index]))
            const unshifted = options.encoding[unShiftIndex]
            return unshift(index + 1, res + unshifted)
        }
    }

    const unshifted = unshift(0,'')
    const missingPads = crypted.slice(-padNum)
    const encoded = unshifted + missingPads
    const decrypted = decode(encoded, options)
    return decrypted
}

const o = {
    pad: "=",
    encoding: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
    size: 6,
    key: '3924834902384'
}
const e = encrypt("Hello!! I'm a robot. Yahoo! wee poop.s", o)
console.log(e)
const d = decrypt(e, o)
console.log(d)
<|endoftext|>


<commit_before>var Slack = require('slack-client');
// FIXME: Find a portable way to add our project files to NODE_PATH
var creds = require('./credentials/testbot.js');

var slackToken = creds.api_token;
var autoReconnect = true; // Automatically reconnect after an error response from Slack.
var autoMark = true; // Automatically mark each message as read after it is processed.

var slack = new Slack(slackToken, autoReconnect, autoMark)

slack.on('open', function(){
    console.log("Connected to %s %s", slack.team.name, slack.self.name);
});

slack.on('message', function(message){
    console.log("%s: %s", new Date().toISOString(), message);
});

slack.on('error', function(err){
    console.error("%s: error: %s", new Date().toISOString(), err);
});

slack.login();
<commit_msg>Ensure text in main.js does not pass line 80.<commit_after>var Slack = require('slack-client');
// FIXME: Find a portable way to add our project files to NODE_PATH
var creds = require('./credentials/testbot.js');

var slackToken = creds.api_token;
var autoReconnect = true; // automatically reconnect on error
var autoMark = true; // automatically mark messages as read

var slack = new Slack(slackToken, autoReconnect, autoMark)

slack.on('open', function(){
    console.log("Connected to %s %s", slack.team.name, slack.self.name);
});

slack.on('message', function(message){
    console.log("%s: %s", new Date().toISOString(), message);
});

slack.on('error', function(err){
    console.error("%s: error: %s", new Date().toISOString(), err);
});

slack.login();
<|endoftext|>


<commit_before>/******** Project - Final *********************************
Authors: Eric Wooley, Tandra Felly, Lauryn Loudermilk
Description: Javascript automata engine.
**********************************************************/
// Start Automiton engine
var aut = new DFA();
// TODO: Hookup DFA STFF HERE
// Adds an html5 canvas to container
var stage = new Kinetic.Stage({
  container: 'canvas_container',
  width:$("#canvas_container").width(),
  height: $("#canvas_container").height()
});
// index, with the keys formatted as stateFromId-stateToId
// ex: if a state goes from state with id 1, to a state with id 3
// the index would be savedTransitions["1-3"]
var savedTransitions = {};

// Layer to preview gestuers on.
var gesture_preview = new Kinetic.Layer();

// Layer to have touch events on.
var touch_layer = new Kinetic.Layer();

// Layer to draw our shapes
var dfa_layer = new Kinetic.Layer();
stage.add(dfa_layer);

var tooltip_layer = new Kinetic.Layer();
stage.add(tooltip_layer);
// an empty stage does not emit mouse-events
// so fill the stage with a background rectangle
// that can emit mouse-events
var whiteboard = new Kinetic.Rect({
  x: 0,
  y: 0,
  width: stage.getWidth(),
  height: stage.getHeight(),
    stroke: 'black',
    strokeWidth: 1,
  });

// an array of all the states.
var states = [];
// these are the gesture events. when we get a circle call this event, etc...
var events = {
  circle: function(e){
    var circle = new Kinetic.Circle({
      x: e.center.x,
      y: e.center.y,
      radius: e.radius,
      fill: 'red',
      stroke: 'black',
      strokeWidth: 4,
      draggable: true
    });
    circle.on('click', function(){
      console.log("you clicked the circle!");
      if (document.getElementById("move").checked){
        console.log('move is active')
        move();
      }
      else{
        remove();
      }
    });
    circle.on('dragstart', function() {
        console.log('dragstart');
        this.setFill("grey");
        dfa_layer.draw();
      });
      circle.on('dragend', function() {
        console.log('dragend');
        this.setFill("red");
        dfa_layer.draw();
    })
    // This adds a node to circle for the engine to work with.
    console.log()
    var state = {
      geo: circle,
      node: aut.add_node({
        deleteTransition: function(l, node1, node2){
          var t = savedTransitions[node1.getId()+"-"+node2.getId()];
          if(t){
            var new_label = node1.getTransitionAsString(node2).replace(l, '');
            if(new_label && new_label.length > 0){
              t.text.setText(new_label);
              tooltip_layer.draw();
            } else {
              t.removeSelf();
              delete savedTransitions[node1.getId()+"-"+node2.getId()];
            }
          }
        }
      })
    };
    dfa_layer.add(circle);
    dfa_layer.draw(); //called to draw the layer after changes
    states.push(state);

  },

  // This function is fired when there is a line drawn between two circles.
  // This funciton can be found in lib/transition.js
  line: function(e){
    transition(e);
  }
};

// Call the canvas gestures library.
gesturesController = canvas_gestures({
  whiteboard: whiteboard,
  stage: stage,
  preview: gesture_preview,
  events: events,
  onClick:function(loc){
    console.log(JSON.stringify(loc))
    $.each(states, function(index, state){
      if(state.geo.intersects(loc)){
        return state.geo.fire("click");
      }
    });
  }
});
gesturesController.enableGestures();
// to disable gestures controller:
// gesturesController.disableGestures();
touch_layer.add(whiteboard);
touch_layer.draw();

stage.add(touch_layer);
stage.add(gesture_preview);<commit_msg>made drags redraw transitions<commit_after>/******** Project - Final *********************************
Authors: Eric Wooley, Tandra Felly, Lauryn Loudermilk
Description: Javascript automata engine.
**********************************************************/
// Start Automiton engine
var aut = new DFA();
// TODO: Hookup DFA STFF HERE
// Adds an html5 canvas to container
var stage = new Kinetic.Stage({
  container: 'canvas_container',
  width:$("#canvas_container").width(),
  height: $("#canvas_container").height()
});
// index, with the keys formatted as stateFromId-stateToId
// ex: if a state goes from state with id 1, to a state with id 3
// the index would be savedTransitions["1-3"]
var savedTransitions = {};

// Layer to preview gestuers on.
var gesture_preview = new Kinetic.Layer();

// Layer to have touch events on.
var touch_layer = new Kinetic.Layer();

// Layer to draw our shapes
var dfa_layer = new Kinetic.Layer();
stage.add(dfa_layer);

// layer for arcs
var transition_layer = new Kinetic.Layer();
stage.add(transition_layer);

var tooltip_layer = new Kinetic.Layer();
stage.add(tooltip_layer);
// an empty stage does not emit mouse-events
// so fill the stage with a background rectangle
// that can emit mouse-events
var whiteboard = new Kinetic.Rect({
  x: 0,
  y: 0,
  width: stage.getWidth(),
  height: stage.getHeight(),
    stroke: 'black',
    strokeWidth: 1,
  });

// an array of all the states.
var states = [];
// these are the gesture events. when we get a circle call this event, etc...
var events = {
  circle: function(e){
    var circle = new Kinetic.Circle({
      x: e.center.x,
      y: e.center.y,
      radius: e.radius,
      fill: 'red',
      stroke: 'black',
      strokeWidth: 4,
      draggable: true
    });
    circle.on('click', function(){
      console.log("you clicked the circle!");
      if (document.getElementById("move").checked){
        console.log('move is active')
        move();
      }
      else{
        remove();
      }
    });

    // This adds a node to circle for the engine to work with.
    console.log()
    var state = {
      geo: circle,
      node: aut.add_node({
        deleteTransition: function(l, node1, node2){
          var t = savedTransitions[node1.getId()+"-"+node2.getId()];
          if(t){
            var new_label = node1.getTransitionAsString(node2).replace(l, '');
            if(new_label && new_label.length > 0){
              t.text.setText(new_label);
              tooltip_layer.draw();
            } else {
              t.clear();
              delete savedTransitions[node1.getId()+"-"+node2.getId()];
            }
          }
        }
      }),
      outgoingTransitions:{},
      incomingTransitions:{}
    };
    circle.on('dragstart', function() {
        console.log('dragstart');
        this.setFill("grey");
        dfa_layer.draw();
      });
      circle.on('dragend', function() {
        console.log('dragend');
        this.setFill("red");
        $.each(state.outgoingTransitions, function(index, val){
          val.draw();
        });
        $.each(state.incomingTransitions, function(index, val){
          val.draw();
        });
        dfa_layer.draw();
    });
    dfa_layer.add(circle);
    dfa_layer.draw(); //called to draw the layer after changes
    states.push(state);

  },

  // This function is fired when there is a line drawn between two circles.
  // This funciton can be found in lib/transition.js
  line: function(e){
    transition(e);
  }
};

// Call the canvas gestures library.
gesturesController = canvas_gestures({
  whiteboard: whiteboard,
  stage: stage,
  preview: gesture_preview,
  events: events,
  onClick:function(loc){
    console.log(JSON.stringify(loc))
    $.each(states, function(index, state){
      if(state.geo.intersects(loc)){
        return state.geo.fire("click");
      }
    });
  }
});
gesturesController.enableGestures();
// to disable gestures controller:
// gesturesController.disableGestures();
touch_layer.add(whiteboard);
touch_layer.draw();

stage.add(touch_layer);
stage.add(gesture_preview);<|endoftext|>


<commit_before>//Example usages
// const vttToJson = require('vtt-json');
// const fs = require('fs');
// const {splitWavParallel, splitWavSequential} = require('./split_wav_by_json');

// (async() => {
//   var vtt = fs.readFileSync('sample.vtt').toString();
//   var json = await vttToJson(vtt);
//   // console.log(json);
//   var ret = await splitWavParallel('sample.wav', json);
//   console.log(ret);
// })();

const {spawn} = require('child-process-promise');
const fs = require('fs');

function deleteDirectoryRecursive(path) {
  if (fs.existsSync(path)) {
    fs.readdirSync(path).forEach(function(file, index){
      var curPath = path + "/" + file;
      if (fs.lstatSync(curPath).isDirectory()) { // recurse
        deleteDirectoryRecursive(curPath);
      } else { // delete file
        fs.unlinkSync(curPath);
      }
    });
    fs.rmdirSync(path);
  }
};

function createTempDir(prefix, noThrow, noLog) {
  let tempDirName = `${prefix}-tmp`
  if (!fs.existsSync(tempDirName)) {
    try {
      fs.mkdirSync(`${prefix}-tmp`);
    } catch (err) {
      if (!noThrow) {
        throw err;
      }
      if (!noLog) {
        console.error(err);
      }
      return null;
    }
  }
  return tempDirName;
}
//
// function onExit(childProcess, idx, noThrow, noLog) {
//   return new Promise((resolve, reject) => {
//     childProcess.once('exit', (code, signal) => {
//       if (code === 0) {
//         resolve(0);
//       } else {
//         if (!noThrow) {
//           reject(new Error(`Exit code nonzero when trying to produce ${idx + 1}.wav: ${code}, abort.`));
//         }
//         if (!noLog) {
//           console.error(`Exit code nonzero when trying to produce ${idx + 1}.wav: ${code}, abort.`);
//         }
//         resolve(1);
//       }
//     });
//     childProcess.once('error', (err) => {
//       if (!noThrow) {
//         reject(err);
//       }
//       if (!noLog) {
//         console.error(err);
//       }
//       resolve(1);
//     });
//   });
// }

/**
*
* Split a wav file according to an array of instructions in json format, of which
* an instruction item must contain a 'start' and an 'end' field that indicates
* the number of milliseconds into and out of the .wav file to be copied into a
* separate .wav file. Starting from the first instruction, This method only
* executes the command of doing so if the proceeding instruction succeeds.
* By its sequential nature, it runs slower than splitWavParallel but will abort
* earlier if an error occurs early.
*
* @method splitWavSequential
* @param {String} wavFile the path to the wavFile that is going to be splitted.
* @param {String} wavFile all instructions in json format, typically converted
*                 from a .vtt file
* @param {Boolean} noThrow whether the function should throw upon error.
* @param {Boolean} noLog whether the function should console.log upon error.
* @param {Boolean} deleteTmpDirOnFailure whether the function should delete
*                  the temporary directory created to hold the splitted .wav
*                   files upon failure for whatever reason.
* @return {Integer} Returns 0 on success and 1 on failure.
*/
async function splitWavSequential(wavFile, splitInstsInJson, noThrow=true, noLog=true, deleteTmpDirOnFailure=true) {
  let tempDirName = createTempDir(wavFile, noThrow, noLog);
  if (!tempDirName) {
    return 1; //On failure
  }

  for (let i = 0; i < splitInstsInJson.length; i++) {
    let currInst = splitInstsInJson[i];
    const ffmpeg = spawn('ffmpeg', ['-y', '-i', wavFile, '-ss', String(currInst.start / 1000), '-to', String(currInst.end / 1000), '-c', 'copy', `${tempDirName}/${i + 1}.wav`]);
    try {
      await ffmpeg;
    } catch (err) {
      if (deleteTmpDirOnFailure) {
        deleteDirectoryRecursive(tempDirName);
      }
      console.error(`Error encountered trying to produce ${i + 1}.wav, abort.`);
      if (!noThrow) {
        throw err;
      }
      if (!noLog) {
        console.error(err);
      }
      return 1;
    }
  }

  return 0; //On success
}

/**
*
* Split a wav file according to an array of instructions in json format, of which
* an instruction item must contain a 'start' and an 'end' field that indicates
* the number of milliseconds into and out of the .wav file to be copied into a
* separate .wav file. Starting from the first instruction, This method executes
* all the commands of doing so in parallel.
* Not going to abort until all commands finished running even if an error occurs.
*
* @method splitWavSequential
* @param {String} wavFile the path to the wavFile that is going to be splitted.
* @param {String} wavFile all instructions in json format, typically converted
*                 from a .vtt file
* @param {Boolean} noThrow whether the function should throw upon error.
* @param {Boolean} noLog whether the function should console.log upon error.
* @param {Boolean} deleteTmpDirOnFailure whether the function should delete
*                  the temporary directory created to hold the splitted .wav
*                   files upon failure for whatever reason.
* @return {Integer} Returns 0 on success and 1 on failure.
*/
async function splitWavParallel(wavFile, splitInstsInJson, noThrow=true, noLog=true, deleteTmpDirOnFailure=true) {
  let tempDirName = createTempDir(wavFile, noThrow, noLog);
  if (!tempDirName) {
    return 1; //On failure
  }

  let retval = 0;
  const promises = splitInstsInJson.map(async (currInst, idx) => {
    const ffmpeg = spawn('ffmpeg', ['-y', '-i', wavFile, '-ss', String(currInst.start / 1000), '-to', String(currInst.end / 1000), '-c', 'copy', `${tempDirName}/${idx + 1}.wav`]);
    try {
      await ffmpeg;
    } catch (err) {
      console.error(`Error encountered trying to produce ${idx + 1}.wav, abort.`);
      if (!noThrow) {
        throw err;
      }
      if (!noLog) {
        console.error(err);
      }
      retval = 1;
    }
  });

  try {
    await Promise.all(promises);
  } catch(err) {
    if (deleteTmpDirOnFailure) {
      deleteDirectoryRecursive(tempDirName);
    }
    throw err;
  }

  if (retval && deleteTmpDirOnFailure) {
    deleteDirectoryRecursive(tempDirName);
  }

  return retval;
}

module.exports = {
  splitWavParallel: splitWavParallel,
  splitWavSequential: splitWavSequential
}
<commit_msg>Delete split_wav_by_json.js<commit_after><|endoftext|>


<commit_before>var view = null
var $modal = null

// The public API.
Modal = {

	show: function(templateName, data){

		// Only show the modal if no modal is shown at the moment.
		// See issue #2.
		if($modal == null){

			var template = Template.peppelg_modal
			var data = {
				templateName: templateName,
				data: data
			}
			var parentNode = document.body

			view = Blaze.renderWithData(template, data, parentNode)

		}

	},

	hide: function(){
		$modal.modal('hide')
	}

}

// The modal template.
var templateName = 'peppelg_modal'

Template[templateName].rendered = function(){

	$modal = $('.modal')

	$modal.modal()

	$modal.on('hidden.bs.modal', function(event){
		Blaze.remove(view)
		$modal = null
		view = null
	})

}<commit_msg>Fixed #4 (autofocus).<commit_after>var view = null
var $modal = null

// The public API.
Modal = {

	show: function(templateName, data){

		// Only show the modal if no modal is shown at the moment.
		// See issue #2.
		if($modal == null){

			var template = Template.peppelg_modal
			var data = {
				templateName: templateName,
				data: data
			}
			var parentNode = document.body

			view = Blaze.renderWithData(template, data, parentNode)

		}

	},

	hide: function(){
		$modal.modal('hide')
	}

}

// The modal template.
var templateName = 'peppelg_modal'

Template[templateName].rendered = function(){

	var template = this

	$modal = $('.modal')

	$modal.modal()

	$modal.on('shown.bs.modal', function(event){
		template.$('[autofocus]').focus()
	})

	$modal.on('hidden.bs.modal', function(event){
		Blaze.remove(view)
		$modal = null
		view = null
	})

}<|endoftext|>


<commit_before>/* global __dirname */
/* global Editor */

var Util = require( 'util' );
var Path = require( 'path' );
var Firedoc = require( 'firedoc' ).Firedoc;
var enginePath = Editor.url( 'app://utils/api/engine-framework' );
var editorPath = Editor.url( 'app://utils/api/editor-framework' );
var runtimePath = Editor.runtimePath;
var doc;

module.exports = {
    load: function () {
        doc = new Firedoc( {
            cwd: enginePath,
            paths: [
                enginePath,
                editorPath,
                Editor.projectPath
            ],
            parseOnly: true
        } );
        console.log(Editor.appPath);
    },

    unload: function () {
        Editor.Panel.close('code-editor.panel');
    },

    'code-editor:open-by-uuid': function( uuid ) {
        // if ( !win || !win.focus ) {
        //     win = new Editor.Window( 'code-editor', {
        //         'title': 'Fireball - Code Editor',
        //         'width': 960,
        //         'height': 720,
        //         'min-width': 300,
        //         'min-height': 300,
        //         'show': true,
        //         'resizable': true,
        //     } );
        //     Editor.MainMenu.add( 'File/Save', {
        //         'message': 'code-editor:save'
        //     } );
        //     win.nativeWin.on( 'closed', function() {
        //         Editor.MainMenu.remove('File/Save');
        //         win = null;
        //     } );
        //     win.nativeWin.webContents.on( 'did-finish-load', function() {
        //         doc.build( function ( err, ast, opt ) {
        //             win.nativeWin.webContents.send( 'code-editor:ast', ast );
        //         } );
        //     } );
        // } else {
        //     win.focus();
        // }
        // win.load( 'packages://code-editor/panel/index.html', {
        //     url: Editor.assetdb.uuidToUrl( uuid ),
        //     path: Editor.assetdb.uuidToFspath( uuid ),
        // } );

        Editor.Panel.open('code-editor.panel', {
            url: Editor.assetdb.uuidToUrl( uuid ),
            path: Editor.assetdb.uuidToFspath( uuid ),
        });
    },

    'code-editor:save': function() {
        // win.nativeWin.webContents.send( 'code-editor:save-from-page' );
        Editor.Panel.sendToPanel( 'code-editor.panel', 'code-editor:save-from-page' );
    },

    // 'code-editor:open-by-path': function( path ) {
    //     var win = new Editor.Window( 'code-editor', {
    //         'title': 'Fireball - Canvas Studio',
    //         'width': 1280,
    //         'height': 720,
    //         'min-width': 100,
    //         'min-height': 100,
    //         'show': false,
    //         'resizable': true,
    //     } );
    //     win.load( 'packages://code-editor/panel/index.html', {
    //         path: path
    //     } );
    // },
};
<commit_msg>init ast when first time open the code editor window<commit_after>/* global __dirname */
/* global Editor */

var Util = require( 'util' );
var Path = require( 'path' );
var Firedoc = require( 'firedoc' ).Firedoc;
var enginePath = Editor.url( 'app://utils/api/engine-framework' );
var editorPath = Editor.url( 'app://utils/api/editor-framework' );
var runtimePath = Editor.runtimePath;
var doc;

module.exports = {
    load: function () {
        doc = new Firedoc( {
            cwd: enginePath,
            paths: [
                enginePath,
                editorPath,
                Editor.projectPath
            ],
            parseOnly: true
        } );
        console.log(Editor.appPath);
    },

    unload: function () {
        Editor.Panel.close('code-editor.panel');
    },

    'code-editor:open-by-uuid': function( uuid ) {
        // if ( !win || !win.focus ) {
        //     win = new Editor.Window( 'code-editor', {
        //         'title': 'Fireball - Code Editor',
        //         'width': 960,
        //         'height': 720,
        //         'min-width': 300,
        //         'min-height': 300,
        //         'show': true,
        //         'resizable': true,
        //     } );
        //     Editor.MainMenu.add( 'File/Save', {
        //         'message': 'code-editor:save'
        //     } );
        //     win.nativeWin.on( 'closed', function() {
        //         Editor.MainMenu.remove('File/Save');
        //         win = null;
        //     } );
        //     win.nativeWin.webContents.on( 'did-finish-load', function() {
        //         doc.build( function ( err, ast, opt ) {
        //             win.nativeWin.webContents.send( 'code-editor:ast', ast );
        //         } );
        //     } );
        // } else {
        //     win.focus();
        // }
        // win.load( 'packages://code-editor/panel/index.html', {
        //     url: Editor.assetdb.uuidToUrl( uuid ),
        //     path: Editor.assetdb.uuidToFspath( uuid ),
        // } );

        Editor.Panel.open('code-editor.panel', {
            url: Editor.assetdb.uuidToUrl( uuid ),
            path: Editor.assetdb.uuidToFspath( uuid ),
        });

        var editorWin = Editor.Panel.findWindow('code-editor.panel');
        editorWin.nativeWin.webContents.on( 'did-finish-load', function() {
            doc.build( function ( err, ast, opt ) {
                editorWin.sendToPage( 'code-editor:ast', ast );
            });
        });
    },

    'code-editor:save': function() {
        // win.nativeWin.webContents.send( 'code-editor:save-from-page' );
        Editor.Panel.sendToPanel( 'code-editor.panel', 'code-editor:save-from-page' );
    },

    // 'code-editor:open-by-path': function( path ) {
    //     var win = new Editor.Window( 'code-editor', {
    //         'title': 'Fireball - Canvas Studio',
    //         'width': 1280,
    //         'height': 720,
    //         'min-width': 100,
    //         'min-height': 100,
    //         'show': false,
    //         'resizable': true,
    //     } );
    //     win.load( 'packages://code-editor/panel/index.html', {
    //         path: path
    //     } );
    // },
};
<|endoftext|>


<commit_before>/*!
 * VisualEditor UserInterface Frame class.
 *
 * @copyright 2011-2013 VisualEditor Team and others; see AUTHORS.txt
 * @license The MIT License (MIT); see LICENSE.txt
 */

/**
 * UserInterface iframe abstraction.
 *
 * @class
 * @extends ve.EventEmitter
 *
 * @constructor
 * @param {Object} [config] Config options
 * @cfg {string[]} [stylesheets] List of stylesheet file names, each relative to ve/ui/styles
 */
ve.ui.Frame = function VeUiFrame( config ) {
	// Inheritance
	ve.EventEmitter.call( this );

	// Properties
	this.initialized = false;
	this.config = config;
	this.$ = $( '' );

	// Events
	this.$.load( ve.bind( this.onLoad, this ) );

	// Initialize
	this.$
		.addClass( 've-ui-frame' )
		.attr( { 'frameborder': 0, 'scrolling': 'no' } );
};

/* Inheritance */

ve.inheritClass( ve.ui.Frame, ve.EventEmitter );

/* Events */

/**
 * @event initialize
 */

/* Methods */

/**
 * Handle frame load events.
 *
 * Once the iframe's stylesheets are loaded, the `initialize` event will be emitted.
 *
 * Sounds simple right? Read on...
 *
 * When you create a dynamic iframe using open/write/close, the window.load event for the
 * iframe is triggered when you call close, and there's no further load event to indicate that
 * everything is actually loaded.
 *
 * By dynamically adding stylesheet links, we can detect when each link is loaded by testing if we
 * have access to each of their `sheet.cssRules` properties. Every 10ms we poll to see if we have
 * access to the style's `sheet.cssRules` property yet.
 *
 * However, because of security issues, we never have such access if the stylesheet came from a
 * different site. Thus, we are left with linking to the stylesheets through a style element with
 * multiple `@import` statements - which ends up being simpler anyway. Since we created that style,
 * we always have access, and its contents are only available when everything is done loading.
 *
 * @emits initialize
 */
ve.ui.Frame.prototype.onLoad = function () {
	var interval, rules,
		win = this.$.prop( 'contentWindow' ),
		doc = win.document,
		style = doc.createElement( 'style' ),
		initialize = ve.bind( function () {
			this.initialized = true;
			this.emit( 'initialize' );
		}, this );

	// Initialize contents
	doc.open();
	doc.write(
		'' +
			'

' +
		''
	);
	doc.close();

	// Import all stylesheets
	style.textContent = '@import "' + this.config.stylesheets.join( '";\n@import "' ) + '";';
	doc.body.appendChild( style );

	// Poll for access to stylesheet content
	interval = setInterval( ve.bind( function () {
		try {
			// MAGIC: only accessible when the stylesheet is loaded
			rules = style.sheet.cssRules;
			// If that didn't throw an exception, we're done loading
			clearInterval( interval );
			// Protect against IE running interval one extra time after clearing
			if ( !this.initialized ) {
				initialize();
			}
		} catch ( e ) { }
	}, this ), 10 );

	// Properties
	this.$$ = ve.ui.get$$( doc, this );
	this.$content = this.$$( '.ve-ui-frame-content' );
};

/**
 * @param {Function} callback
 */
ve.ui.Frame.prototype.run = function ( callback ) {
	if ( this.initialized ) {
		callback();
	} else {
		this.once( 'initialize', callback );
	}
};

/**
 * Sets the size of the frame.
 *
 * @method
 * @param {number} width Frame width in pixels
 * @param {number} height Frame height in pixels
 * @chainable
 */
ve.ui.Frame.prototype.setSize = function ( width, height ) {
	this.$.css( { 'width': width, 'height': height } );
	return this;
};
<commit_msg>Initialize iframe for dialog with correct doctype<commit_after>/*!
 * VisualEditor UserInterface Frame class.
 *
 * @copyright 2011-2013 VisualEditor Team and others; see AUTHORS.txt
 * @license The MIT License (MIT); see LICENSE.txt
 */

/**
 * UserInterface iframe abstraction.
 *
 * @class
 * @extends ve.EventEmitter
 *
 * @constructor
 * @param {Object} [config] Config options
 * @cfg {string[]} [stylesheets] List of stylesheet file names, each relative to ve/ui/styles
 */
ve.ui.Frame = function VeUiFrame( config ) {
	// Inheritance
	ve.EventEmitter.call( this );

	// Properties
	this.initialized = false;
	this.config = config;
	this.$ = $( '' );

	// Events
	this.$.load( ve.bind( this.onLoad, this ) );

	// Initialize
	this.$
		.addClass( 've-ui-frame' )
		.attr( { 'frameborder': 0, 'scrolling': 'no' } );
};

/* Inheritance */

ve.inheritClass( ve.ui.Frame, ve.EventEmitter );

/* Events */

/**
 * @event initialize
 */

/* Methods */

/**
 * Handle frame load events.
 *
 * Once the iframe's stylesheets are loaded, the `initialize` event will be emitted.
 *
 * Sounds simple right? Read on...
 *
 * When you create a dynamic iframe using open/write/close, the window.load event for the
 * iframe is triggered when you call close, and there's no further load event to indicate that
 * everything is actually loaded.
 *
 * By dynamically adding stylesheet links, we can detect when each link is loaded by testing if we
 * have access to each of their `sheet.cssRules` properties. Every 10ms we poll to see if we have
 * access to the style's `sheet.cssRules` property yet.
 *
 * However, because of security issues, we never have such access if the stylesheet came from a
 * different site. Thus, we are left with linking to the stylesheets through a style element with
 * multiple `@import` statements - which ends up being simpler anyway. Since we created that style,
 * we always have access, and its contents are only available when everything is done loading.
 *
 * @emits initialize
 */
ve.ui.Frame.prototype.onLoad = function () {
	var interval, rules,
		win = this.$.prop( 'contentWindow' ),
		doc = win.document,
		style = doc.createElement( 'style' ),
		initialize = ve.bind( function () {
			this.initialized = true;
			this.emit( 'initialize' );
		}, this );

	// Initialize contents
	doc.open();
	doc.write(
		'<!doctype html>' +
		'' +
			'' +
				'

' +
			'' +
		''
	);
	doc.close();

	// Import all stylesheets
	style.textContent = '@import "' + this.config.stylesheets.join( '";\n@import "' ) + '";';
	doc.body.appendChild( style );

	// Poll for access to stylesheet content
	interval = setInterval( ve.bind( function () {
		try {
			// MAGIC: only accessible when the stylesheet is loaded
			rules = style.sheet.cssRules;
			// If that didn't throw an exception, we're done loading
			clearInterval( interval );
			// Protect against IE running interval one extra time after clearing
			if ( !this.initialized ) {
				initialize();
			}
		} catch ( e ) { }
	}, this ), 10 );

	// Properties
	this.$$ = ve.ui.get$$( doc, this );
	this.$content = this.$$( '.ve-ui-frame-content' );
};

/**
 * @param {Function} callback
 */
ve.ui.Frame.prototype.run = function ( callback ) {
	if ( this.initialized ) {
		callback();
	} else {
		this.once( 'initialize', callback );
	}
};

/**
 * Sets the size of the frame.
 *
 * @method
 * @param {number} width Frame width in pixels
 * @param {number} height Frame height in pixels
 * @chainable
 */
ve.ui.Frame.prototype.setSize = function ( width, height ) {
	this.$.css( { 'width': width, 'height': height } );
	return this;
};
<|endoftext|>


<commit_before>function init() { // Main function
	// ========== VARIABLE INITIATION v ==========
	var c = document.getElementById("retrovirus"), // Access the canvas
		vImg = document.getElementById("vImg"), // Virus's image
        abImg1 = document.getElementById("abImg1"),
        abImg2 = document.getElementById("abImg2"),
        abImg3 = document.getElementById("abImg3"), // Antibodys are a little redundant, but i can't get around it
        abImg4 = document.getElementById("abImg4"),
        abImg5 = document.getElementById("abImg5"),
		ctx = c.getContext("2d"), // 2D Canvas context
		height = window.innerHeight, // Shortcut to window.innerHeight
		width = window.innerWidth, // Shortcut to window.innerWidth
		centerH, // Center of the canvas's height
		centerW, // Center of the canvas's width
		cW, // Shortcut to the canvas's width
		cH, // Shortcut to the canvas's height
		gridH, // For accessing movement distance/grid height
		gridW // For accessing movement distance/grid width

	// ========== VARIABLE INITIATION ^ ==========

	// ========== GLOBAL FUNCTIONS v =============

	function writeText(text) { // Text writing function
		ctx.textAlign = "center"
		ctx.font = "12pt ABeeZee"
		ctx.fillText(text, centerW, centerH)
	}

	// ========== GLOBAL FUNCTIONS ^ ==========

 	// =============== CLASSES v ==============

	var RetroVirus = function(x, y) { // Virus constructor
		this.x = x
		this.y = y
	}

	RetroVirus.prototype = { // Virus prototype functions
		move : function(newX, newY) {
			ctx.clearRect(0, 0, cW, cH)
			ctx.rect(0, 0, cW, cH) // Set the canvas background to black
			ctx.fillStyle = "black"
            ctx.fill()
			ctx.drawImage(vImg, newX, newY)
            antibody1.render()
            antibody2.render()
            antibody3.render()
            antibody4.render()
            antibody5.render()
			return this.x * this.y
		}
	}

    var Antibody = function(x, y) {
        this.x = x
        this.y = y
    }

	var virus = new RetroVirus() // Create new virus with constructor
    var antibody1 = new Antibody()
    var antibody2 = new Antibody()
    var antibody3 = new Antibody()
    var antibody4 = new Antibody()
    var antibody5 = new Antibody()

	// ========== CLASSES ^ ==========

   	if (width > height) { // If in landscape mode

   		// ========== SECOND VARIABLE INITIATION v ==========

		c.width = width - 18
		c.height = height - 22
		cW = c.width
		cH = c.height
		centerW = cW / 2
		centerH = cH / 2

		// ========== SECOND VARIABLE INITIATION ^ ==========

		// ========== SPECIAL FUNCTIONS v ==========

		function grid(countX) { // Sections where the virus will be
			var pos; // Position to start/end the line
			for (var i = countX - 1; i > 0; i--) {
				gridW = cW / countX
				pos = gridW * i
				ctx.moveTo(pos, 0)
				ctx.lineTo(pos, cH)
                // ctx.strokeStyle = "white"
				ctx.stroke()
			}

			for (var i = countX - 1; i > 0; i--) {
				gridH = gridW // Ensure a square
				pos = gridH * i
				ctx.moveTo(0, pos)
				ctx.lineTo(cW, pos)
				// ctx.strokeStyle = "white"
                ctx.stroke()
			}
		}

		// ========== SPECIAL FUNCTIONS ^ ==========

		grid(20) // 20 squares across

		virus.x = centerW // Set the virus's starting position
		virus.y = centerH // - gridH / 2 // To offset image for collision

        antibody1.x = gridW * 3
        antibody1.y = gridW * 6

        antibody2.x = gridW * 15
        antibody2.y = gridW * 4

        antibody3.x = gridW * 7
        antibody3.y = gridW * 5

        antibody4.x = gridW * 9
        antibody4.y = gridW * 2

        antibody5.x = gridW * 8
        antibody5.y = gridW * 9

        antibody1.move = function(newX, newY) {
            ctx.clearRect(0, 0, cW, cH)
            ctx.rect(0, 0, cW, cH) // Set the canvas background to black
            ctx.fillStyle = "black"
            ctx.fill()
            ctx.drawImage(abImg1, newX, newY)
            virus.render()
            antibody2.render()
            antibody3.render()
            antibody4.render()
            antibody5.render()
            return this.x * this.y
        }

        antibody2.move = function(newX, newY) {
            ctx.clearRect(0, 0, cW, cH)
            ctx.rect(0, 0, cW, cH) // Set the canvas background to black
            ctx.fillStyle = "black"
            ctx.fill()
            ctx.drawImage(abImg2, newX, newY)
            virus.render()
            antibody1.render()
            antibody3.render()
            antibody4.render()
            antibody5.render()
            return this.x * this.y
        }

        antibody3.move = function(newX, newY) {
            ctx.clearRect(0, 0, cW, cH)
            ctx.rect(0, 0, cW, cH) // Set the canvas background to black
            ctx.fillStyle = "black"
            ctx.fill()
            ctx.drawImage(abImg3, newX, newY)
            virus.render()
            antibody1.render()
            antibody2.render()
            antibody4.render()
            antibody5.render()
            return this.x * this.y
        }

        antibody4.move = function(newX, newY) {
            ctx.clearRect(0, 0, cW, cH)
            ctx.rect(0, 0, cW, cH) // Set the canvas background to black
            ctx.fillStyle = "black"
            ctx.fill()
            ctx.drawImage(abImg4, newX, newY)
            virus.render()
            antibody1.render()
            antibody2.render()
            antibody3.render()
            antibody5.render()
            return this.x * this.y
        }

        antibody5.move = function(newX, newY) {
            ctx.clearRect(0, 0, cW, cH)
            ctx.rect(0, 0, cW, cH) // Set the canvas background to black
            ctx.fillStyle = "black"
            ctx.fill()
            ctx.drawImage(abImg5, newX, newY)
            virus.render()
            antibody1.render()
            antibody2.render()
            antibody3.render()
            antibody4.render()
            return this.x * this.y
        }

        antibody1.render = function() {
            ctx.drawImage(abImg1, antibody1.x, antibody1.y)
            return abImg1
        }

        antibody2.render = function() {
            ctx.drawImage(abImg2, antibody2.x, antibody2.y)
            return abImg2
        }

        antibody3.render = function() {
            ctx.drawImage(abImg3, antibody3.x, antibody3.y)
            return abImg3
        }

        antibody4.render = function() {
            ctx.drawImage(abImg4, antibody4.x, antibody4.y)
            return abImg4
        }

        antibody5.render = function() {
            ctx.drawImage(abImg5, antibody5.x, antibody5.y)
            return abImg5
        }

		virus.render = function() {
			ctx.drawImage(vImg, virus.x, virus.y)
			return vImg
		}

		ctx.rect(0, 0, cW, cH) // Set the canvas background to black
		ctx.fillStyle = "black"
		ctx.fill()

	} else { // If in portrait mode
		ctx.textAlign = "center"
		ctx.font = "12pt ABeeZee"
		ctx.fillText("Please use landscape mode.", centerW, centerH)
	}

	// ========== CRUCIAL FUNDEMENTALS v ==========

    setInterval(function() {
            if (antibody1.x - virus.x > 0 && antibody1.x - virus.x > antibody1.y - virus.y)  {
                antibody1.move(antibody1.x -= gridW, antibody1.y)
            }

            else if (antibody1.y - virus.y < 0 && antibody1.y - virus.y < antibody1.x - virus.x) {
                antibody1.move(antibody1.x, antibody1.y += gridW)
            }

            else if (antibody1.x - virus.x < 0 && antibody1.x - virus.x < antibody1.y - virus.y) {
                antibody1.move(antibody1.x += gridW, antibody1.y)
            }

            else if (antibody1.y - virus.y > 0 && antibody1.y - virus.y > antibody1.x - virus.x) {
                antibody1.move(antibody1.x, antibody1.y -= gridW)
            }

    }, 500)

    setInterval(function() {
            if (antibody2.x - virus.x > 0 && antibody2.x - virus.x > antibody2.y - virus.y) {
                antibody2.move(antibody2.x -= gridW, antibody2.y)
            }

            else if (antibody2.y - virus.y < 0 && antibody2.y - virus.y < antibody2.x - virus.x) {
                antibody2.move(antibody2.x, antibody2.y += gridW)
            }

            else if (antibody2.x - virus.x < 0 && antibody2.x - virus.x < antibody2.y - virus.y) {
                antibody2.move(antibody2.x += gridW, antibody2.y)
            }

            else if (antibody2.y - virus.y > 0 && antibody2.y - virus.y > antibody2.x - virus.x) {
                antibody2.move(antibody2.x, antibody2.y -= gridW)
            }

    }, 500)

    setInterval(function() {
            if (antibody3.x - virus.x > 0 && antibody3.x - virus.x > antibody3.y - virus.y) {
                antibody3.move(antibody3.x -= gridW, antibody3.y)
            }

            else if (antibody3.y - virus.y < 0 && antibody3.y - virus.y < antibody3.x - virus.x) {
                antibody3.move(antibody3.x, antibody3.y += gridW)
            }

            else if (antibody3.x - virus.x < 0 && antibody3.x - virus.x < antibody3.y - virus.y) {
                antibody3.move(antibody3.x += gridW, antibody3.y)
            }

            else if (antibody3.y - virus.y > 0 && antibody3.y - virus.y > antibody3.x - virus.x) {
                antibody3.move(antibody3.x, antibody3.y -= gridW)
            }

    }, 500)

    setInterval(function() {
            if (antibody4.x - virus.x > 0 && antibody4.x - virus.x > antibody4.y - virus.y) {
                antibody4.move(antibody4.x -= gridW, antibody4.y)
            }

            else if (antibody4.y - virus.y < 0 && antibody4.y - virus.y < antibody4.x - virus.x) {
                antibody4.move(antibody4.x, antibody4.y += gridW)
            }

            else if (antibody4.x - virus.x < 0 && antibody4.x - virus.x < antibody4.y - virus.y) {
                antibody4.move(antibody4.x += gridW, antibody4.y)
            }

            else if (antibody4.y - virus.y > 0 && antibody4.y - virus.y > antibody4.x - virus.x) {
                antibody4.move(antibody4.x, antibody4.y -= gridW)
            }

    }, 500)

    setInterval(function() {
            if (antibody5.x - virus.x > 0 && antibody5.x - virus.x > antibody5.y - virus.y) {
                antibody5.move(antibody5.x -= gridW, antibody5.y)
            }

            else if (antibody5.y - virus.y < 0 && antibody5.y - virus.y < antibody5.x - virus.x) {
                antibody5.move(antibody5.x, antibody5.y += gridW)
            }

            else if (antibody5.x - virus.x < 0 && antibody5.x - virus.x < antibody5.y - virus.y) {
                antibody5.move(antibody5.x += gridW, antibody5.y)
            }

            else if (antibody5.y - virus.y > 0 && antibody5.y - virus.y > antibody5.x - virus.x) {
                antibody5.move(antibody5.x, antibody5.y -= gridW)
            }

    }, 500)

	window.addEventListener("keydown", function(event) { // Key listener
		switch (event.keyCode) {
			case 37: // Left
				if(virus.x < 0) {} // For edge collision
				else { // Print image at new position
					virus.move(virus.x - gridW, virus.y)
					virus.x -= gridW
				}
				break

			case 38: // Up
				if(virus.y - gridH  < 0) {}
				else {
					virus.move(virus.x, virus.y - gridH)
					virus.y -= gridH
				}
				break

			case 39: // Right
				if(virus.x + gridW * 2 > cW) {}
				else {
					virus.move(virus.x + gridW, virus.y)
					virus.x += gridW
				}
				break

			case 40: // Down
				if(virus.y + gridH * 2 > cH) {}
				else {
					virus.move(virus.x, virus.y + gridH)
					virus.y += gridH
				}
				break
			}
	}, false)

    window.addEventListener("load", function () {
        virus.render()
        antibody1.render()
        antibody2.render()
        antibody3.render()
        antibody4.render()
        antibody5.render()
    }, false)

	// ========== CRUCIAL FUNDEMENTALS ^ ==========
}

document.addEventListener("DOMContentLoaded", init, false) // Run when the DOM has loaded
<commit_msg>Big fix for antibodies<commit_after>function init() { // Main function
	// ========== VARIABLE INITIATION v ==========
	var c = document.getElementById("retrovirus"), // Access the canvas
		vImg = document.getElementById("vImg"), // Virus's image
        	abImg1 = document.getElementById("abImg1"),
        	abImg2 = document.getElementById("abImg2"),
        	abImg3 = document.getElementById("abImg3"), // Antibodys are a little redundant, but i can't get around it
        	abImg4 = document.getElementById("abImg4"),
        	abImg5 = document.getElementById("abImg5"),
        	abCount = 5;
        	numbers[], // Possible array fix
        	abImg[], // Possible array fix
		ctx = c.getContext("2d"), // 2D Canvas context
		height = window.innerHeight, // Shortcut to window.innerHeight
		width = window.innerWidth, // Shortcut to window.innerWidth
		centerH, // Center of the canvas's height
		centerW, // Center of the canvas's width
		cW, // Shortcut to the canvas's width
		cH, // Shortcut to the canvas's height
		gridH, // For accessing movement distance/grid height
		gridW // For accessing movement distance/grid width

		for (i = 0; i < abCount, i++) {
			var j = i + 1
			numbers.push[j.toString()]
			abImg[i + 1] = document.getElemenById("abImg" + numbers[i])
		}

	// ========== VARIABLE INITIATION ^ ==========

	// ========== GLOBAL FUNCTIONS v =============

	function writeText(text) { // Text writing function
		ctx.textAlign = "center"
		ctx.font = "12pt ABeeZee"
		ctx.fillText(text, centerW, centerH)
	}

	// ========== GLOBAL FUNCTIONS ^ ==========

 	// =============== CLASSES v ==============

	var RetroVirus = function(x, y) { // Virus constructor
		this.x = x
		this.y = y
	}

	RetroVirus.prototype = { // Virus prototype functions
		move : function(newX, newY) {
			ctx.clearRect(0, 0, cW, cH)
			ctx.rect(0, 0, cW, cH) // Set the canvas background to black
			ctx.fillStyle = "black"
			ctx.fill()
			ctx.drawImage(vImg, newX, newY)
			for (i = 0; i < abCount; i++) {
				antibody[i + 1].render(i + 1)
			}
			return this.x * this.y
		}
	}

    var Antibody = function(x, y) {
        this.x = x
        this.y = y
    }

	var virus = new RetroVirus() // Create new virus with constructor
	var antibody[]
	for (i = 0; i < abCount; i++)
		antibody[i + 1] = new Antibody()
	}

	// ========== CLASSES ^ ==========

   	if (width > height) { // If in landscape mode

   		// ========== SECOND VARIABLE INITIATION v ==========

		c.width = width - 18
		c.height = height - 22
		cW = c.width
		cH = c.height
		centerW = cW / 2
		centerH = cH / 2

		// ========== SECOND VARIABLE INITIATION ^ ==========

		// ========== SPECIAL FUNCTIONS v ==========

		function grid(countX) { // Sections where the virus will be
			var pos; // Position to start/end the line
			for (var i = countX - 1; i > 0; i--) {
				gridW = cW / countX
				pos = gridW * i
				ctx.moveTo(pos, 0)
				ctx.lineTo(pos, cH)
				// ctx.strokeStyle = "white"
				ctx.stroke()
			}

			for (var i = countX - 1; i > 0; i--) {
				gridH = gridW // Ensure a square
				pos = gridH * i
				ctx.moveTo(0, pos)
				ctx.lineTo(cW, pos)
				// ctx.strokeStyle = "white"
				ctx.stroke()
			}
		}

		// ========== SPECIAL FUNCTIONS ^ ==========

		grid(20) // 20 squares across

		virus.x = centerW // Set the virus's starting position
		virus.y = centerH // - gridH / 2 // To offset image for collision

		// We'll let this fly for now

		antibody[1].x = gridW * 3
		antibody[1].y = gridW * 6

		antibody[2].x = gridW * 15
		antibody[2].y = gridW * 4

		antibody[3].x = gridW * 7
		antibody[3].y = gridW * 5

		antibody[4].x = gridW * 9
		antibody[4].y = gridW * 2

		antibody[5].x = gridW * 8
		antibody[5].y = gridW * 9

		antibody.move = function(newX, newY) {
			ctx.clearRect(0, 0, cW, cH)
			ctx.rect(0, 0, cW, cH) // Set the canvas background to black
			ctx.fillStyle = "black"
			ctx.fill()
			for(i = 0; i < abCount; i++) {
				ctx.drawImage(abImg[i + 1], newX, newY)
			}
			virus.render()
			return this.x * this.y
		}

        // antibody2.move = function(newX, newY) {
        //     ctx.clearRect(0, 0, cW, cH)
        //     ctx.rect(0, 0, cW, cH) // Set the canvas background to black
        //     ctx.fillStyle = "black"
        //     ctx.fill()
        //     ctx.drawImage(abImg2, newX, newY)
        //     virus.render()
        //     antibody1.render()
        //     antibody3.render()
        //     antibody4.render()
        //     antibody5.render()
        //     return this.x * this.y
        // }

        // antibody3.move = function(newX, newY) {
        //     ctx.clearRect(0, 0, cW, cH)
        //     ctx.rect(0, 0, cW, cH) // Set the canvas background to black
        //     ctx.fillStyle = "black"
        //     ctx.fill()
        //     ctx.drawImage(abImg3, newX, newY)
        //     virus.render()
        //     antibody1.render()
        //     antibody2.render()
        //     antibody4.render()
        //     antibody5.render()
        //     return this.x * this.y
        // }

        // antibody4.move = function(newX, newY) {
        //     ctx.clearRect(0, 0, cW, cH)
        //     ctx.rect(0, 0, cW, cH) // Set the canvas background to black
        //     ctx.fillStyle = "black"
        //     ctx.fill()
        //     ctx.drawImage(abImg4, newX, newY)
        //     virus.render()
        //     antibody1.render()
        //     antibody2.render()
        //     antibody3.render()
        //     antibody5.render()
        //     return this.x * this.y
        // }

        // antibody5.move = function(newX, newY) {
        //     ctx.clearRect(0, 0, cW, cH)
        //     ctx.rect(0, 0, cW, cH) // Set the canvas background to black
        //     ctx.fillStyle = "black"
        //     ctx.fill()
        //     ctx.drawImage(abImg5, newX, newY)
        //     virus.render()
        //     antibody1.render()
        //     antibody2.render()
        //     antibody3.render()
        //     antibody4.render()
        //     return this.x * this.y
        // }

		antibody.render = function(toRender) {
			ctx.drawImage(abImg[toRender], antibody[toRender].x, antibody[toRender].y)
			return abImg[toRender]
		}

		virus.render = function() {
			ctx.drawImage(vImg, virus.x, virus.y)
			return vImg
		}

		ctx.rect(0, 0, cW, cH) // Set the canvas background to black
		ctx.fillStyle = "black"
		ctx.fill()

	} else { // If in portrait mode
		ctx.textAlign = "center"
		ctx.font = "12pt ABeeZee"
		ctx.fillText("Please use landscape mode.", centerW, centerH)
	}

	// ========== CRUCIAL FUNDEMENTALS v ==========

	setInterval(function() {
		for(i = 0; i < abCount; i++) {
			if (antibody[i + 1].x - virus.x > 0 && antibody[i + 1].x - virus.x > antibody[i + 1].y - virus.y)  {
				antibody[i + 1].move(antibody[i + 1].x -= gridW, antibody[i + 1].y)
			}

			else if (antibody[i + 1].y - virus.y < 0 && antibody[i + 1].y - virus.y < antibody[i + 1].x - virus.x) {
				antibody[i + 1].move(antibody[i + 1].x, antibody[i + 1].y += gridW)
			}

			else if (antibody[i + 1].x - virus.x < 0 && antibody[i + 1].x - virus.x < antibody[i + 1].y - virus.y) {
				antibody[i + 1].move(antibody[i + 1].x += gridW, antibody[i + 1].y)
			}

			else if (antibody[i + 1].y - virus.y > 0 && antibody[i + 1].y - virus.y > antibody[i + 1].x - virus.x) {
				antibody[i + 1].move(antibody[I + 1].x, antibody[i + 1].y -= gridW)
			}
		}
    }, 500)

	window.addEventListener("keydown", function(event) { // Key listener
		switch (event.keyCode) {
			case 37: // Left
				if(virus.x < 0) {} // For edge collision
				else { // Print image at new position
					virus.move(virus.x - gridW, virus.y)
					virus.x -= gridW
				}
				break

			case 38: // Up
				if(virus.y - gridH  < 0) {}
				else {
					virus.move(virus.x, virus.y - gridH)
					virus.y -= gridH
				}
				break

			case 39: // Right
				if(virus.x + gridW * 2 > cW) {}
				else {
					virus.move(virus.x + gridW, virus.y)
					virus.x += gridW
				}
				break

			case 40: // Down
				if(virus.y + gridH * 2 > cH) {}
				else {
					virus.move(virus.x, virus.y + gridH)
					virus.y += gridH
				}
				break
			}
	}, false)

	window.addEventListener("load", function () {
		virus.render()
		for(i = 0; i < abCount; i++) {
			antibody[i + 1].render()
		}
    }, false)

	// ========== CRUCIAL FUNDEMENTALS ^ ==========
}

document.addEventListener("DOMContentLoaded", init, false) // Run when the DOM has loaded
<|endoftext|>


<commit_before>// @flow

import React, { Component } from 'react';
import classNames from 'classnames';
import { SHAPES, COLORS } from '../constants/tetromino';
import { attachPointerDownEvent } from '../utils/events';
import { getPlayer } from '../reducers/game';
import Tetromino from './Tetromino';
import Button from './Button';

import type { User, Game } from '../types/state';

export type Props = {
  curUser: User,
  game: Game,
  onMenu: Function
};

export default class GamePanel extends Component<Props> {
  /**
   * The game panel contains:
   * - The next Tetromino to be inserted
   * - The score and lines cleared
   * - Start or pause/resume controls
   */
  renderGameButton() {
    const { curUser, game, onMenu } = this.props;
    const player = getPlayer(game, curUser.id);

    if (player.status !== 'PENDING') {
      return;
    }

    return <Button {...attachPointerDownEvent(onMenu)}>READY</Button>;
  }

  render() {
    const { curUser, game } = this.props;
    const player = getPlayer(game, curUser.id);
    const { score, lines, nextTetromino } = player;

    return (

            World Tetris

Score

{score}

Lines

{lines}

Next

          <Tetromino
            key={nextTetromino}
            color={COLORS[nextTetromino]}
            grid={SHAPES[nextTetromino]}
          />

Players

          {game.players.map(player => {
            const { user } = player;
            const classes = classNames('user', {
              // 'user-ready': user.status === 'READY',
            });

            return (

                {user.name}

            );
          })}

{this.renderGameButton()}

    );
  }

  getNextTetrominoClass() {
    const { curUser, game } = this.props;
    const player = getPlayer(game, curUser.id);
    const { nextTetromino } = player;

    // We use this extra class to position tetrominoes differently from CSS
    // based on their type
    return `next-tetromino next-tetromino-${nextTetromino}`;
  }
}
<commit_msg>Highlight current user in GamePanel<commit_after>// @flow

import React, { Component } from 'react';
import classNames from 'classnames';
import { SHAPES, COLORS } from '../constants/tetromino';
import { attachPointerDownEvent } from '../utils/events';
import { getPlayer } from '../reducers/game';
import Tetromino from './Tetromino';
import Button from './Button';

import type { User, Game } from '../types/state';

export type Props = {
  curUser: User,
  game: Game,
  onMenu: Function
};

export default class GamePanel extends Component<Props> {
  /**
   * The game panel contains:
   * - The next Tetromino to be inserted
   * - The score and lines cleared
   * - Start or pause/resume controls
   */
  renderGameButton() {
    const { curUser, game, onMenu } = this.props;
    const player = getPlayer(game, curUser.id);

    if (player.status !== 'PENDING') {
      return;
    }

    return <Button {...attachPointerDownEvent(onMenu)}>READY</Button>;
  }

  render() {
    const { curUser, game } = this.props;
    const player = getPlayer(game, curUser.id);
    const { score, lines, nextTetromino } = player;

    return (

            World Tetris

Score

{score}

Lines

{lines}

Next

          <Tetromino
            key={nextTetromino}
            color={COLORS[nextTetromino]}
            grid={SHAPES[nextTetromino]}
          />

Players

          {game.players.map(player => {
            const { user } = player;
            const isMe = user.id === curUser.id;
            const classes = classNames('user', {
              // 'user-ready': user.status === 'READY',
            });

            return (

                {isMe ? {user.name} : user.name}

            );
          })}

{this.renderGameButton()}

    );
  }

  getNextTetrominoClass() {
    const { curUser, game } = this.props;
    const player = getPlayer(game, curUser.id);
    const { nextTetromino } = player;

    // We use this extra class to position tetrominoes differently from CSS
    // based on their type
    return `next-tetromino next-tetromino-${nextTetromino}`;
  }
}
<|endoftext|>


<commit_before>
/*
The MIT License (MIT)

Copyright (c) 2014 Rob Christian

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.
*/

/*

Semi-colons are just FUD. If your minifier can't handle this code, switch to one that is JS-compliant.

*/

;(function(){

  /*  Private Class Data  */

  var DEFINE = Object.defineProperty
  var OVERRIDE = function(object, method_name, method){
    DEFINE(object, method_name, { enumerable:false, configurable:false, value:method })
  }
  var _property_manipulator_ = null
  var PROPERTY_MANIPULATOR = function(obj){
    if (! obj) return _property_manipulator_
    else _property_manipulator_ = obj
    return PROPERTY_MANIPULATOR
  }

  var _bindables = []
  var _events = new MicroEvent()

  /*  Bindable Classes  */

  function Bindable(data){
    if (typeOf(data) === 'Array')
      return new BindableArray(data)
    else if (familyOf(data) === 'complex')
      return new BindableObject(data)
  }

  function bind(){ console.log('BIND', arguments)

    opts = Array.prototype.slice.call(arguments)

    if (opts.length === 3) {
      var parent = opts[0]
      var property = opts[1]
      var setter_cb = opts[2]

      parent[property] = PROPERTY_MANIPULATOR({
        send:function(id){ _events.bind(id,setter_cb) }
      })
    }

    else {
      var setter_cb = opts[1]
      opts[0]._array_events_ = PROPERTY_MANIPULATOR({
        send:function(id){ _events.bind(id,setter_cb) }
      })
    }

  }

  function unbind(setter_cb){
    _events.unbind(setter_cb)
  }

  function recompute(data){
    if (familyOf(data) === 'complex')
      this.constructor.apply(this,data)
    return this
  }

  function BindableObject(data){
    Object.keys(data).map(function(prop){
      this._new_property_ = [prop, data[prop]]
    }.bind(this))
  }
  DEFINE(BindableObject.prototype, 'bind', { enumerable:false, configurable:false, value:bind })
  DEFINE(BindableObject.prototype, 'unbind', { enumerable:false, configurable:false, value:unbind })
  DEFINE(BindableObject.prototype, 'recompute', { enumerable:false, configurable:false, value:recompute })
  DEFINE(BindableObject.prototype, '_new_property_', { enumerable:false, configurable:false,
    set:function(){ addProperty.apply(this, arguments) }
  })

  function BindableArray(array){
    var self = []

    DEFINE(self, '_id', { enumerable:false, configurable:false, value:Math.random().toString().split('.')[1] })
    DEFINE(self, 'bind', { enumerable:false, configurable:false, value:bind })
    DEFINE(self, 'unbind', { enumerable:false, configurable:false, value:unbind })
    DEFINE(self, 'recompute', { enumerable:false, configurable:false, value:recompute })
    DEFINE(self, '_new_property_', { enumerable:false, configurable:false,
      set:function(){ addProperty.apply(self, arguments) }
    })
    DEFINE(self, '_array_events_', { enumerable:false, configurable:false,
      set:function(manipulator){
        if (manipulator === PROPERTY_MANIPULATOR && PROPERTY_MANIPULATOR().send)
          PROPERTY_MANIPULATOR().send(this._id)
      }
    })
    OVERRIDE(self, 'push', function(v){
      self._new_property_ = [self.length, v]
      _events.trigger(this._id, ['push', self.length-1, self[self.length-1]])
    })
    OVERRIDE(self, 'pop', function(){
      var r = self[self.length-1]
      self.length = self.length-1
      return r
    })
    OVERRIDE(self, 'shift', function(){
      var r = self[0]
      Object.keys(self).map(function(idx){
        self[+idx-1] = self[+idx]
      })
      self.length = self.length-1
      return r
    })
    OVERRIDE(self, 'unshift', function(obj){

      Object.keys(self).map(function(idx){
        console.log(+idx+1, +idx)
        self._new_property_ = [+idx+1, self[+idx]]
        self[+idx] = PROPERTY_MANIPULATOR({
          send:function(id){ self[+idx+1] = PROPERTY_MANIPULATOR({id:id}) }
        })
      })

      self._new_property_ = [0, obj]
    })
    OVERRIDE(self, 'splice', function(idx1, idx2){
      //
    })
    OVERRIDE(self, 'slice', function(idx1, idx2){
      //
    })
    OVERRIDE(self, 'reverse', function(idx1, idx2){
      //
    })
    OVERRIDE(self, 'concat', function(arr){
      if (arr && arr.length) {
        Object.keys(arr).map(function(key){
          self._new_property_ = [self.length, arr[key]]
        })
      }
    })
    Object.keys(array).map(function(idx){
      self._new_property_ = [+idx, array[+idx]]
    })

    return self
  }

  function addProperty(args){
    var _val = undefined
    var _id = Math.random().toString().split('.')[1]

    if (typeOf(args) === 'Array') {
      var key = args[0]
      var val = args[1]
    } else {
      console.log('Abort! Bad property assignment:',args)
      return
    }
    // console.log('addProperty', key, val)

    DEFINE(this, key, {
      enumerable: true
    , configurable: true
    , get: function(){ return _val }
    , set: function(value){
        if (value === PROPERTY_MANIPULATOR && PROPERTY_MANIPULATOR().send) {
          PROPERTY_MANIPULATOR().send(_id)
        }
        else if (value === PROPERTY_MANIPULATOR && PROPERTY_MANIPULATOR().id) {
          _id = PROPERTY_MANIPULATOR().id
        }
        else if (familyOf(value) === 'complex') {
          _val = new Bindable(value)
          _events.trigger(_id, _val)
        }
        else {
          _val = value
          _events.trigger(_id, _val)
        }
      }
    })
    this[key] = val
  }

  /* Takes a form DOM object and a Binding object, and does the rest for you. */

  function bindForm(form, bindable){

    ;[].forEach.call(form.querySelectorAll('input'), function(field){

      if (field.name in bindable) {
        fieldManager(function(input_handler, output_handler){

          field.addEventListener('input', function(ev){
            var do_it = function(){ bindable[field.name] = ev.target.value }
            input_handler( do_it )
          })

          bindable.bind(bindable, field.name, function(val){
            var do_it = function(){ field.value = val }
            output_handler( do_it )
          })

        })

        field.value = bindable[field.name]
      }

    })
  }

  /* Inverts control: Prevents inputs from receiving updates while they are the sender. */

  function fieldManager(receive_handlers){
    var _sent_by_me = false

    function input_handler(do_it){
      _sent_by_me = true
      do_it()
    }
    function output_handler(do_it){
      _sent_by_me ? _sent_by_me = false : do_it()
    }
    receive_handlers( input_handler, output_handler )
  }

  /* Our entry point for creating bindable objects, keeps a reference to the object created. */

  function NewBindable(data){
    var bindable = new Bindable(data)
    _bindables.push(bindable)
    return bindable
  }

  /*  HELPERS  */

  function familyOf(thing){
    if (typeOf(thing)) {
      return {
        Date: 'simple'
      , String: 'simple'
      , Number: 'simple'
      , Boolean: 'simple'
      , Function: 'simple'
      , Array: 'complex'
      , Object: 'complex'
      , 'undefined': 'falsey'
      , 'null': 'falsey'
      }[typeOf(thing)] || 'complex'
    } else {
      return false
    }
  }

  function typeOf(thing){
    return (thing != null && !Number.isNaN(thing) && thing.constructor) ? thing.constructor.name : '' + thing
  }

  NewBindable.fieldManager = fieldManager
  NewBindable.bindForm = bindForm

  DEFINE(NewBindable, 'bindables', {get:function(){return _bindables}, enumerable:true})
  DEFINE(NewBindable, 'PROPERTY_MANIPULATOR', {value:PROPERTY_MANIPULATOR, writeable:false})

  if (typeof module !== 'undefined' && module.hasOwnProperty('exports')) {
    module.exports = NewBindable
  } else {
    window.Connected  = NewBindable
    window.familyOf   = familyOf
    window.typeOf     = typeOf
    window.Bindable   = Bindable
  }

})()
<commit_msg>Add missing 'var'.<commit_after>
/*
The MIT License (MIT)

Copyright (c) 2014 Rob Christian

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.
*/

/*

Semi-colons are just FUD. If your minifier can't handle this code, switch to one that is JS-compliant.

*/

;(function(){

  /*  Private Class Data  */

  var DEFINE = Object.defineProperty
  var OVERRIDE = function(object, method_name, method){
    DEFINE(object, method_name, { enumerable:false, configurable:false, value:method })
  }
  var _property_manipulator_ = null
  var PROPERTY_MANIPULATOR = function(obj){
    if (! obj) return _property_manipulator_
    else _property_manipulator_ = obj
    return PROPERTY_MANIPULATOR
  }

  var _bindables = []
  var _events = new MicroEvent()

  /*  Bindable Classes  */

  function Bindable(data){
    if (typeOf(data) === 'Array')
      return new BindableArray(data)
    else if (familyOf(data) === 'complex')
      return new BindableObject(data)
  }

  function bind(){ console.log('BIND', arguments)

    var opts = Array.prototype.slice.call(arguments)

    if (opts.length === 3) {
      var parent = opts[0]
      var property = opts[1]
      var setter_cb = opts[2]

      parent[property] = PROPERTY_MANIPULATOR({
        send:function(id){ _events.bind(id,setter_cb) }
      })
    }

    else {
      var setter_cb = opts[1]
      opts[0]._array_events_ = PROPERTY_MANIPULATOR({
        send:function(id){ _events.bind(id,setter_cb) }
      })
    }

  }

  function unbind(setter_cb){
    _events.unbind(setter_cb)
  }

  function recompute(data){
    if (familyOf(data) === 'complex')
      this.constructor.apply(this,data)
    return this
  }

  function BindableObject(data){
    Object.keys(data).map(function(prop){
      this._new_property_ = [prop, data[prop]]
    }.bind(this))
  }
  DEFINE(BindableObject.prototype, 'bind', { enumerable:false, configurable:false, value:bind })
  DEFINE(BindableObject.prototype, 'unbind', { enumerable:false, configurable:false, value:unbind })
  DEFINE(BindableObject.prototype, 'recompute', { enumerable:false, configurable:false, value:recompute })
  DEFINE(BindableObject.prototype, '_new_property_', { enumerable:false, configurable:false,
    set:function(){ addProperty.apply(this, arguments) }
  })

  function BindableArray(array){
    var self = []

    DEFINE(self, '_id', { enumerable:false, configurable:false, value:Math.random().toString().split('.')[1] })
    DEFINE(self, 'bind', { enumerable:false, configurable:false, value:bind })
    DEFINE(self, 'unbind', { enumerable:false, configurable:false, value:unbind })
    DEFINE(self, 'recompute', { enumerable:false, configurable:false, value:recompute })
    DEFINE(self, '_new_property_', { enumerable:false, configurable:false,
      set:function(){ addProperty.apply(self, arguments) }
    })
    DEFINE(self, '_array_events_', { enumerable:false, configurable:false,
      set:function(manipulator){
        if (manipulator === PROPERTY_MANIPULATOR && PROPERTY_MANIPULATOR().send)
          PROPERTY_MANIPULATOR().send(this._id)
      }
    })
    OVERRIDE(self, 'push', function(v){
      self._new_property_ = [self.length, v]
      _events.trigger(this._id, ['push', self.length-1, self[self.length-1]])
    })
    OVERRIDE(self, 'pop', function(){
      var r = self[self.length-1]
      self.length = self.length-1
      return r
    })
    OVERRIDE(self, 'shift', function(){
      var r = self[0]
      Object.keys(self).map(function(idx){
        self[+idx-1] = self[+idx]
      })
      self.length = self.length-1
      return r
    })
    OVERRIDE(self, 'unshift', function(obj){

      Object.keys(self).map(function(idx){
        console.log(+idx+1, +idx)
        self._new_property_ = [+idx+1, self[+idx]]
        self[+idx] = PROPERTY_MANIPULATOR({
          send:function(id){ self[+idx+1] = PROPERTY_MANIPULATOR({id:id}) }
        })
      })

      self._new_property_ = [0, obj]
    })
    OVERRIDE(self, 'splice', function(idx1, idx2){
      //
    })
    OVERRIDE(self, 'slice', function(idx1, idx2){
      //
    })
    OVERRIDE(self, 'reverse', function(idx1, idx2){
      //
    })
    OVERRIDE(self, 'concat', function(arr){
      if (arr && arr.length) {
        Object.keys(arr).map(function(key){
          self._new_property_ = [self.length, arr[key]]
        })
      }
    })
    Object.keys(array).map(function(idx){
      self._new_property_ = [+idx, array[+idx]]
    })

    return self
  }

  function addProperty(args){
    var _val = undefined
    var _id = Math.random().toString().split('.')[1]

    if (typeOf(args) === 'Array') {
      var key = args[0]
      var val = args[1]
    } else {
      console.log('Abort! Bad property assignment:',args)
      return
    }
    // console.log('addProperty', key, val)

    DEFINE(this, key, {
      enumerable: true
    , configurable: true
    , get: function(){ return _val }
    , set: function(value){
        if (value === PROPERTY_MANIPULATOR && PROPERTY_MANIPULATOR().send) {
          PROPERTY_MANIPULATOR().send(_id)
        }
        else if (value === PROPERTY_MANIPULATOR && PROPERTY_MANIPULATOR().id) {
          _id = PROPERTY_MANIPULATOR().id
        }
        else if (familyOf(value) === 'complex') {
          _val = new Bindable(value)
          _events.trigger(_id, _val)
        }
        else {
          _val = value
          _events.trigger(_id, _val)
        }
      }
    })
    this[key] = val
  }

  /* Takes a form DOM object and a Binding object, and does the rest for you. */

  function bindForm(form, bindable){

    ;[].forEach.call(form.querySelectorAll('input'), function(field){

      if (field.name in bindable) {
        fieldManager(function(input_handler, output_handler){

          field.addEventListener('input', function(ev){
            var do_it = function(){ bindable[field.name] = ev.target.value }
            input_handler( do_it )
          })

          bindable.bind(bindable, field.name, function(val){
            var do_it = function(){ field.value = val }
            output_handler( do_it )
          })

        })

        field.value = bindable[field.name]
      }

    })
  }

  /* Inverts control: Prevents inputs from receiving updates while they are the sender. */

  function fieldManager(receive_handlers){
    var _sent_by_me = false

    function input_handler(do_it){
      _sent_by_me = true
      do_it()
    }
    function output_handler(do_it){
      _sent_by_me ? _sent_by_me = false : do_it()
    }
    receive_handlers( input_handler, output_handler )
  }

  /* Our entry point for creating bindable objects, keeps a reference to the object created. */

  function NewBindable(data){
    var bindable = new Bindable(data)
    _bindables.push(bindable)
    return bindable
  }

  /*  HELPERS  */

  function familyOf(thing){
    if (typeOf(thing)) {
      return {
        Date: 'simple'
      , String: 'simple'
      , Number: 'simple'
      , Boolean: 'simple'
      , Function: 'simple'
      , Array: 'complex'
      , Object: 'complex'
      , 'undefined': 'falsey'
      , 'null': 'falsey'
      }[typeOf(thing)] || 'complex'
    } else {
      return false
    }
  }

  function typeOf(thing){
    return (thing != null && !Number.isNaN(thing) && thing.constructor) ? thing.constructor.name : '' + thing
  }

  NewBindable.fieldManager = fieldManager
  NewBindable.bindForm = bindForm

  DEFINE(NewBindable, 'bindables', {get:function(){return _bindables}, enumerable:true})
  DEFINE(NewBindable, 'PROPERTY_MANIPULATOR', {value:PROPERTY_MANIPULATOR, writeable:false})

  if (typeof module !== 'undefined' && module.hasOwnProperty('exports')) {
    module.exports = NewBindable
  } else {
    window.Connected  = NewBindable
    window.familyOf   = familyOf
    window.typeOf     = typeOf
    window.Bindable   = Bindable
  }

})()
<|endoftext|>


<commit_before>var fs = require('fs');
var vm = require('vm');
var net = require('net');
var child_process = require('child_process');
var Bacon = require('baconjs');
var SSE = require('express-sse');
var request = require('request');

var opt = require('node-getopt').create([
  ['h', 'help', 'display this help'],
  ['v', 'version', 'show version'],
  ['p', 'port=PORT', 'listen port']
])
.bindHelp()
.parseSystem();

if (opt.options.version) {
    console.log('nwatchlive 0.0.1');
    process.exit();
}

var port = opt.options.port || 3050;

if (opt.argv.length == 0) {
    console.log('no services specified.');
    process.exit(1);
}

var watchers = {};

var watchHTTP = function(url) {
    return function(ack, err) {
        request(url, function(e, response, body) {
            if (e) {
                err(e.message);
            } else if (response.statusCode != 200) {
                err("status " + response.statusCode);
            } else {
                ack();
            }
        });
    };
};

var watchTCP = function(host, port) {
    return function(ack, err) {
        var cte = false;
        var conn = net.createConnection({'host': host,
                                         'port': port},
                                        function() {
            ack();
            cte = true;
            conn.end();
        });
        conn.on('end', function() {
            if (!cte) {
                err('premature FIN');
            }
        });
        conn.on('timeout', function() {
            err('timeout');
        });
        conn.on('error', function(e) {
            err(e.message);
        });
    };
};

var watchChild = function(child, args) {
    return function(ack, err) {
        var chld = child_process.spawn(child, args);
        chld.on('error', function(e) {
            err(e.message);
        });
        chld.on('exit', function(code, signal) {
            if (signal !== null) {
                err(signal);
            } else if (code != 0) {
                err('Exited with code ' + code);
            } else {
                ack();
            }
        });
    };
};

var watchPing = function(target) {
    return watchChild('ping', ['-c', '1', '-W', '3', target]);
};

var watchPing6 = function(target) {
    return watchChild('ping6', ['-c', '1', '-W', '3', target]);
};

var context = vm.createContext({
    'addWatcher': function(name, watcher) {
        watchers[name] = watcher;
    },
    'watchHTTP': watchHTTP,
    'watchChild': watchChild,
    'watchTCP': watchTCP,
    'watchPing': watchPing,
    'watchPing6': watchPing6,
    'require': require
});
opt.argv.forEach(function(sfile) {
    var services = fs.readFileSync(sfile);

    vm.runInContext(services, context, sfile);
});
console.log(watchers);

var services = [];
for (var watcher in watchers) {
    if (watchers.hasOwnProperty(watcher)) {
        services.push(watcher);
    }
}
var statuses = {};
services.forEach(function(service) {
    statuses[service] = '...';
});
var statBus = new Bacon.Bus();
var Stat = statBus.toProperty(statuses);

var setStatus = function(service, stat) {
    var oldStatus = statuses[service];
    if (oldStatus === stat) {
        return;
    }
    statuses[service] = stat;
    statBus.push(statuses);
};

var propertiesInflight = [];
var currentQueryGeneration = 0;

var runQueries = function() {
    currentQueryGeneration += 1;
    var currentQuery = currentQueryGeneration;
    propertiesInflight.forEach(function(inflight) {
        setStatus(inflight, 'query timed out');
    });
    services.forEach(function(service) {
        propertiesInflight.push(service);
        var watcher = watchers[service];
        var recv = function(stat) {
            if (currentQuery !== currentQueryGeneration)
                return;
            var ix = propertiesInflight.indexOf(service);
            if (ix > -1) {
                propertiesInflight.splice(ix, 1);
                setStatus(service, stat);
            }
        };
        var ack = function() {
            recv(null);
        };
        var err = function(e) {
            recv(e || 'error');
        };
        setImmediate(function() {
            watcher(ack, err);
        });
    });
};

runQueries();

var INTERVAL = 6;
setInterval(runQueries, INTERVAL*1000);

Stat.onValue(function(val) {
    console.log(val);
});

var express = require('express');
var app = express();
var root = fs.readFileSync(__dirname + '/index.html', {'encoding': 'utf-8'});
root = root.replace('$ROOT$', '');

app.get('/', function(req, res) {
    res.header('Content-Type', 'text/html; charset=utf-8');
    res.end(root);
});

app.get('/status', function(req, res) {
    res.header('Content-Type', 'application/json');
    res.end(JSON.stringify(statuses));
});

var sse = new SSE([]);

app.get('/stream', sse.init);

Stat.debounce(250).onValue(function(x) {
    sse.send(x);
    sse.updateInit([x]);
});

app.use('/static', express.static(__dirname + '/static'));

var server = app.listen(port, '::', function() {
    var ad = server.address();
    var hs = ad.address;
    var pt = ad.port;
    console.log("Listening on http://%s:%s", hs, pt);
});

<commit_msg>Pass in console to services files<commit_after>var fs = require('fs');
var vm = require('vm');
var net = require('net');
var child_process = require('child_process');
var Bacon = require('baconjs');
var SSE = require('express-sse');
var request = require('request');

var opt = require('node-getopt').create([
  ['h', 'help', 'display this help'],
  ['v', 'version', 'show version'],
  ['p', 'port=PORT', 'listen port']
])
.bindHelp()
.parseSystem();

if (opt.options.version) {
    console.log('nwatchlive 0.0.1');
    process.exit();
}

var port = opt.options.port || 3050;

if (opt.argv.length == 0) {
    console.log('no services specified.');
    process.exit(1);
}

var watchers = {};

var watchHTTP = function(url) {
    return function(ack, err) {
        request(url, function(e, response, body) {
            if (e) {
                err(e.message);
            } else if (response.statusCode != 200) {
                err("status " + response.statusCode);
            } else {
                ack();
            }
        });
    };
};

var watchTCP = function(host, port) {
    return function(ack, err) {
        var cte = false;
        var conn = net.createConnection({'host': host,
                                         'port': port},
                                        function() {
            ack();
            cte = true;
            conn.end();
        });
        conn.on('end', function() {
            if (!cte) {
                err('premature FIN');
            }
        });
        conn.on('timeout', function() {
            err('timeout');
        });
        conn.on('error', function(e) {
            err(e.message);
        });
    };
};

var watchChild = function(child, args) {
    return function(ack, err) {
        var chld = child_process.spawn(child, args);
        chld.on('error', function(e) {
            err(e.message);
        });
        chld.on('exit', function(code, signal) {
            if (signal !== null) {
                err(signal);
            } else if (code != 0) {
                err('Exited with code ' + code);
            } else {
                ack();
            }
        });
    };
};

var watchPing = function(target) {
    return watchChild('ping', ['-c', '1', '-W', '3', target]);
};

var watchPing6 = function(target) {
    return watchChild('ping6', ['-c', '1', '-W', '3', target]);
};

var context = vm.createContext({
    'addWatcher': function(name, watcher) {
        watchers[name] = watcher;
    },
    'watchHTTP': watchHTTP,
    'watchChild': watchChild,
    'watchTCP': watchTCP,
    'watchPing': watchPing,
    'watchPing6': watchPing6,
    'require': require,
    'console': console
});
opt.argv.forEach(function(sfile) {
    var services = fs.readFileSync(sfile);

    vm.runInContext(services, context, sfile);
});
console.log(watchers);

var services = [];
for (var watcher in watchers) {
    if (watchers.hasOwnProperty(watcher)) {
        services.push(watcher);
    }
}
var statuses = {};
services.forEach(function(service) {
    statuses[service] = '...';
});
var statBus = new Bacon.Bus();
var Stat = statBus.toProperty(statuses);

var setStatus = function(service, stat) {
    var oldStatus = statuses[service];
    if (oldStatus === stat) {
        return;
    }
    statuses[service] = stat;
    statBus.push(statuses);
};

var propertiesInflight = [];
var currentQueryGeneration = 0;

var runQueries = function() {
    currentQueryGeneration += 1;
    var currentQuery = currentQueryGeneration;
    propertiesInflight.forEach(function(inflight) {
        setStatus(inflight, 'query timed out');
    });
    services.forEach(function(service) {
        propertiesInflight.push(service);
        var watcher = watchers[service];
        var recv = function(stat) {
            if (currentQuery !== currentQueryGeneration)
                return;
            var ix = propertiesInflight.indexOf(service);
            if (ix > -1) {
                propertiesInflight.splice(ix, 1);
                setStatus(service, stat);
            }
        };
        var ack = function() {
            recv(null);
        };
        var err = function(e) {
            recv(e || 'error');
        };
        setImmediate(function() {
            watcher(ack, err);
        });
    });
};

runQueries();

var INTERVAL = 6;
setInterval(runQueries, INTERVAL*1000);

Stat.onValue(function(val) {
    console.log(val);
});

var express = require('express');
var app = express();
var root = fs.readFileSync(__dirname + '/index.html', {'encoding': 'utf-8'});
root = root.replace('$ROOT$', '');

app.get('/', function(req, res) {
    res.header('Content-Type', 'text/html; charset=utf-8');
    res.end(root);
});

app.get('/status', function(req, res) {
    res.header('Content-Type', 'application/json');
    res.end(JSON.stringify(statuses));
});

var sse = new SSE([]);

app.get('/stream', sse.init);

Stat.debounce(250).onValue(function(x) {
    sse.send(x);
    sse.updateInit([x]);
});

app.use('/static', express.static(__dirname + '/static'));

var server = app.listen(port, '::', function() {
    var ad = server.address();
    var hs = ad.address;
    var pt = ad.port;
    console.log("Listening on http://%s:%s", hs, pt);
});

<|endoftext|>


<commit_before>Ext.define("Component",{
    extend: "Ext.data.Model",
    idProperty: 'id',
    events: [],
	config: {
        name: "naam",
        div: "left_menu",
        //mapViewert: new Object(),
        options: "opt1"
    },
    constructor: function(config){
        this.viewerController = viewerController;
        this.initConfig(config);
        return this;
    },
    velden: [
        {name: 'id', type: 'string'},
        {name: 'name', type: 'string'},
        {name: 'shortName', type: 'string'},
        {name: 'restrictions', type: 'array'},
        {name: 'addOnce', type: 'boolean'},
        {name: 'linkedComponents', type: 'array'},
        {name: 'addedToRegions', type: 'array'}
    ],
    bind : function(event,handler){
        this.addListener(event,handler);
    },
    isAddedToRegion: function(regionid) {
        var isAdded = false;
        Ext.Array.each(this.get('addedToRegions'), function(region, index) {
            if(region == regionid) {
                isAdded = true;
            }
        });
        return isAdded;
    }
});<commit_msg>removed class which was only for design-time (viewer-admin)<commit_after><|endoftext|>