<commit_before>const fs = require("fs");
const options = {};

// options.ip = '127.0.0.1';
// options.port = parseInt(process.argv[2]);
// options.config = { name: 'total.js' };
// options.https = { key: fs.readFileSync('keys/agent2-key.pem'), cert: fs.readFileSync('keys/agent2-cert.pem')};
// options.sleep = 3000;
// options.debugger = 40894;

function debug(){require("total.js");var port=parseInt(process.argv[process.argv.length-1]);return isNaN(port)||(options||(options={}),options.port=port),port>0&&!options.port&&(options.port=port||8e3),options.https?F.https("debug",options):(F.http("debug",options),void(first?F.emit("debug-start"):F.emit("debug-restart")))}function app(){function onFilter(path,isDirectory){return!isDirectory&&REG_THEMES.test(path)?REG_THEMES_INDEX.test(path):isDirectory?!0:REG_EXTENSION.test(path)}function onIncrease(clear){clear&&(clearTimeout(pidIncrease),speed=TIME),pidIncrease=setTimeout(function(){speed+=TIME,speed>4e3&&(speed=4e3),onIncrease()},12e4)}function onComplete(f){fs.readdir(directory,function(err,arr){for(var length=arr.length,i=0;length>i;i++){var name=arr[i];"debug.js"!==name&&REG_FILES.test(name)&&f.push(name)}length=f.length;for(var i=0;length>i;i++){var name=f[i];files[name]||(files[name]=isLoaded?0:null)}refresh()})}function refresh(){for(var filenames=Object.keys(files),length=filenames.length,i=0;length>i;i++){var filename=filenames[i];!function(filename){async.await(function(next){fs.stat(filename,function(err,stat){if(err)delete files[filename],changes.push(prefix+filename.replace(directory,"")+" (removed)"),force=!0;else{var ticks=stat.mtime.getTime();files[filename]&&files[filename]!==ticks&&(changes.push(prefix+filename.replace(directory,"")+(0===files[filename]?" (added)":" (modified)")),force=!0),files[filename]=ticks}next()})})}(filename)}async.complete(function(){if(isLoaded=!0,setTimeout(refresh_directory,speed),onIncrease(),1===status&&force){onIncrease(!0),restart();for(var length=changes.length,i=0;length>i;i++)console.log(changes[i]);changes=[],force=!1}})}function refresh_directory(){utils.ls(directories,onComplete,onFilter)}function restart(){if(null!==app){try{isSkip=!0,process.kill(app.pid)}catch(err){}app=null}var arr=process.argv,port=arr.pop();if(-1!==process.execArgv.indexOf("--debug")){var key="--debug="+(options["debugger"]||40894);-1===process.execArgv.indexOf(key)&&process.execArgv.push(key)}first?first=!1:arr.push("restart"),arr.push("debugging"),arr.push(port),app=fork(path.join(directory,"debug.js"),arr),app.on("message",function(msg){"eaddrinuse"===msg&&process.exit(1)}),app.on("exit",function(){return isSkip===!1?(app=null,void process.exit()):(isSkip=!1,void(255===status&&(app=null)))}),0===status&&app.send("debugging"),status=1}function end(){if(!arguments.callee.isEnd){if(arguments.callee.isEnd=!0,fs.unlink(pid,noop),null===app)return void process.exit(0);isSkip=!0,process.kill(app.pid),app=null,process.exit(0)}}function noop(){}const fork=require("child_process").fork,utils=require("total.js/utils"),directories=[directory+"/controllers",directory+"/definitions",directory+"/isomorphic",directory+"/modules",directory+"/resources",directory+"/models",directory+"/source",directory+"/workers",directory+"/packages",directory+"/themes"],async=new utils.Async,prefix="----------------------------------------------------> ";var pidIncrease,files={},force=!1,changes=[],app=null,status=0,pid="",pidInterval=null,isLoaded=!1,isSkip=!1,speed=TIME;process.on("SIGTERM",end),process.on("SIGINT",end),process.on("exit",end),process.pid>0&&(console.log(prefix+"PID: "+process.pid+" (v"+VERSION+")"),pid=path.join(directory,"debug.pid"),fs.writeFileSync(pid,process.pid),pidInterval=setInterval(function(){fs.exists(pid,function(e){e||(fs.unlink(pid,noop),null!==app&&(isSkip=!0,process.kill(app.pid)),process.exit(0))})},2e3)),restart(),refresh_directory()}function run(){if(isDebugging)return void debug();var filename=path.join(directory,"debug.pid");return fs.existsSync(filename)?(fs.unlinkSync(filename),void setTimeout(function(){app()},3e3)):void app()}const isDebugging=-1!==process.argv.indexOf("debugging"),directory=process.cwd(),path=require("path"),VERSION="5.0",TIME=2e3,REG_FILES=/config\-debug|config\-release|config|versions|sitemap|dependencies|\.js|\.resource/i,REG_THEMES=/\/themes\//i,REG_THEMES_INDEX=/themes(\/|\\)?[a-z0-9_.-]+(\/|\\)?index\.js/i,REG_EXTENSION=/\.(js|resource|package)/i;var first=-1===process.argv.indexOf("restart");process.on("uncaughtException",function(e){-1==e.toString().indexOf("ESRCH")&&console.log(e)}),run();<commit_msg>Update `debug.js` version.<commit_after>const fs = require("fs");
const options = {};

// options.ip = '127.0.0.1';
// options.port = parseInt(process.argv[2]);
// options.config = { name: 'total.js' };
// options.https = { key: fs.readFileSync('keys/agent2-key.pem'), cert: fs.readFileSync('keys/agent2-cert.pem')};
// options.sleep = 3000;
// options.debugger = 40894;

function debug(){require("total.js");var port=parseInt(process.argv[process.argv.length-1]);return isNaN(port)||(options||(options={}),options.port=port),port>0&&!options.port&&(options.port=port||8e3),options.https?F.https("debug",options):(F.http("debug",options),void(first?F.emit("debug-start"):F.emit("debug-restart")))}function app(){function onFilter(path,isDirectory){return!isDirectory&&REG_THEMES.test(path)?REG_THEMES_INDEX.test(path):isDirectory?!0:REG_EXTENSION.test(path)}function onIncrease(clear){clear&&(clearTimeout(pidIncrease),speed=TIME),pidIncrease=setTimeout(function(){speed+=TIME,speed>4e3&&(speed=4e3),onIncrease()},12e4)}function onComplete(f){fs.readdir(directory,function(err,arr){for(var length=arr.length,i=0;length>i;i++){var name=arr[i];"debug.js"!==name&&REG_FILES.test(name)&&f.push(name)}length=f.length;for(var i=0;length>i;i++){var name=f[i];files[name]||(files[name]=isLoaded?0:null)}refresh()})}function refresh(){for(var filenames=Object.keys(files),length=filenames.length,i=0;length>i;i++){var filename=filenames[i];!function(filename){async.await(function(next){fs.stat(filename,function(err,stat){var stamp="--- "+(new Date).format("yyyy-MM-dd-HH:mm:ss")+" ";if(err)delete files[filename],changes.push(stamp+prefix+filename.replace(directory,"")+" (removed)"),force=!0;else{var ticks=stat.mtime.getTime();files[filename]&&files[filename]!==ticks&&(changes.push(stamp+prefix+filename.replace(directory,"")+(0===files[filename]?" (added)":" (modified)")),force=!0),files[filename]=ticks}next()})})}(filename)}async.complete(function(){if(isLoaded=!0,setTimeout(refresh_directory,speed),onIncrease(),1===status&&force){onIncrease(!0),restart();for(var length=changes.length,i=0;length>i;i++)console.log(changes[i]);changes=[],force=!1}})}function refresh_directory(){utils.ls(directories,onComplete,onFilter)}function restart(){if(null!==app){try{isSkip=!0,process.kill(app.pid)}catch(err){}app=null}var arr=process.argv,port=arr.pop();if(-1!==process.execArgv.indexOf("--debug")){var key="--debug="+(options["debugger"]||40894);-1===process.execArgv.indexOf(key)&&process.execArgv.push(key)}first?first=!1:arr.push("restart"),arr.push("debugging"),arr.push(port),app=fork(path.join(directory,"debug.js"),arr),app.on("message",function(msg){"eaddrinuse"===msg&&process.exit(1)}),app.on("exit",function(){return isSkip===!1?(app=null,void process.exit()):(isSkip=!1,void(255===status&&(app=null)))}),0===status&&app.send("debugging"),status=1}function end(){if(!arguments.callee.isEnd){if(arguments.callee.isEnd=!0,fs.unlink(pid,noop),null===app)return void process.exit(0);isSkip=!0,process.kill(app.pid),app=null,process.exit(0)}}function noop(){}const fork=require("child_process").fork,utils=require("total.js/utils"),directories=[directory+"/controllers",directory+"/definitions",directory+"/isomorphic",directory+"/modules",directory+"/resources",directory+"/models",directory+"/source",directory+"/workers",directory+"/packages",directory+"/themes"],async=new utils.Async,prefix="---------------------------------> ";var pidIncrease,files={},force=!1,changes=[],app=null,status=0,pid="",pidInterval=null,isLoaded=!1,isSkip=!1,speed=TIME;process.on("SIGTERM",end),process.on("SIGINT",end),process.on("exit",end),process.pid>0&&(console.log(prefix+"PID: "+process.pid+" (v"+VERSION+")"),pid=path.join(directory,"debug.pid"),fs.writeFileSync(pid,process.pid),pidInterval=setInterval(function(){fs.exists(pid,function(e){e||(fs.unlink(pid,noop),null!==app&&(isSkip=!0,process.kill(app.pid)),process.exit(0))})},2e3)),restart(),refresh_directory()}function run(){if(isDebugging)return void debug();var filename=path.join(directory,"debug.pid");return fs.existsSync(filename)?(fs.unlinkSync(filename),void setTimeout(function(){app()},3e3)):void app()}const isDebugging=-1!==process.argv.indexOf("debugging"),directory=process.cwd(),path=require("path"),VERSION="6.0",TIME=2e3,REG_FILES=/config\-debug|config\-release|config|versions|sitemap|dependencies|\.js|\.resource/i,REG_THEMES=/\/themes\//i,REG_THEMES_INDEX=/themes(\/|\\)?[a-z0-9_.-]+(\/|\\)?index\.js/i,REG_EXTENSION=/\.(js|resource|package)/i;var first=-1===process.argv.indexOf("restart");process.on("uncaughtException",function(e){-1==e.toString().indexOf("ESRCH")&&console.log(e)}),run();<|endoftext|>


<commit_before>var constants = require('./constants');

/*
 * Logging method
 * */
module.exports = {
    log: function(logLevel, text) {
        var logDate = new Date().toString().replace(/G.*/,'').replace(/[a-zA-Z]*\ /,'');
        var logMessage = logDate+'- '+text;

        switch(logLevel) {
            case constants.log.INFO :
                console.info(logMessage);
                break;
            case constants.log.WARNING :
                console.warn(logMessage);
                break;
            case constants.log.ERROR :
                console.error(logMessage);
                break;
            default :
                console.log(logMessage);
        }
    },

    throwError: function(text) {
        throw new Error(text);
    },

    escapeString: function(str) {
        return str.replace(/[\0\x08\x09\x1a\n\r"'\\\%]/g, function (char) {
            switch (char) {
                case "\0":
                    return "\\0";
                case "\x08":
                    return "\\b";
                case "\x09":
                    return "\\t";
                case "\x1a":
                    return "\\z";
                case "\n":
                    return "\\n";
                case "\r":
                    return "\\r";
                case "\"":
                case "'":
                case "\\":
                case "%":
                    return "\\"+char; // prepends a backslash to backslash, percent,
                // and double/single quotes
            }
        });
    }
};
<commit_msg>display log level<commit_after>var constants = require('./constants');

/*
 * Logging method
 * */
module.exports = {
    log: function(logLevel, text) {
        var logDate = new Date().toString().replace(/G.*/,'').replace(/[a-zA-Z]*\ /,'');
        var logMessage = logLevel + ': ' + logDate+'- '+text;

        switch(logLevel) {
            case constants.log.INFO :
                console.info(logMessage);
                break;
            case constants.log.WARNING :
                console.warn(logMessage);
                break;
            case constants.log.ERROR :
                console.error(logMessage);
                break;
            default :
                console.log(logMessage);
        }
    },

    throwError: function(text) {
        throw new Error(text);
    },

    escapeString: function(str) {
        return str.replace(/[\0\x08\x09\x1a\n\r"'\\\%]/g, function (char) {
            switch (char) {
                case "\0":
                    return "\\0";
                case "\x08":
                    return "\\b";
                case "\x09":
                    return "\\t";
                case "\x1a":
                    return "\\z";
                case "\n":
                    return "\\n";
                case "\r":
                    return "\\r";
                case "\"":
                case "'":
                case "\\":
                case "%":
                    return "\\"+char; // prepends a backslash to backslash, percent,
                // and double/single quotes
            }
        });
    }
};
<|endoftext|>


<commit_before>import deferrable from 'golike-defer'
import find from 'lodash/find'
import gte from 'lodash/gte'
import isEmpty from 'lodash/isEmpty'
import lte from 'lodash/lte'

import {
  forEach,
  mapToArray,
  noop,
  parseSize,
  pCatch
} from '../../utils'

import {
  isVmHvm,
  isVmRunning,
  makeEditObject
} from '../utils'

export default {
  // TODO: clean up on error.
  @deferrable.onFailure
  async createVm ($onFailure, templateId, {
    name_label, // deprecated
    nameLabel = name_label, // eslint-disable-line camelcase

    clone = true,
    installRepository = undefined,
    vdis = undefined,
    vifs = undefined,
    existingVdis = undefined,

    coreOs = false,
    cloudConfig = undefined,

    ...props
  } = {}, checkLimits) {
    const installMethod = (() => {
      if (installRepository == null) {
        return 'none'
      }

      try {
        installRepository = this.getObject(installRepository)
        return 'cd'
      } catch (_) {
        return 'network'
      }
    })()
    const template = this.getObject(templateId)

    // Clones the template.
    const vmRef = await this[clone ? '_cloneVm' : '_copyVm'](template, nameLabel)
    $onFailure(() => this.deleteVm(vmRef, true)::pCatch(noop))

    // TODO: copy BIOS strings?

    // Removes disks from the provision XML, we will create them by
    // ourselves.
    await this.call('VM.remove_from_other_config', vmRef, 'disks')::pCatch(noop)

    // Creates the VDIs and executes the initial steps of the
    // installation.
    await this.call('VM.provision', vmRef)

    let vm = await this._getOrWaitObject(vmRef)

    // Set VMs params.
    await this._editVm(vm, props, checkLimits)

    // Sets boot parameters.
    {
      const isHvm = isVmHvm(vm)

      if (isHvm) {
        if (!vdis.length || installMethod === 'network') {
          const { HVM_boot_params: bootParams } = vm
          let order = bootParams.order
          if (order) {
            order = 'n' + order.replace('n', '')
          } else {
            order = 'ncd'
          }

          this._setObjectProperties(vm, {
            HVM_boot_params: { ...bootParams, order }
          })
        }
      } else { // PV
        if (vm.PV_bootloader === 'eliloader') {
          if (installMethod === 'network') {
            // TODO: normalize RHEL URL?

            await this._updateObjectMapProperty(vm, 'other_config', {
              'install-repository': installRepository
            })
          } else if (installMethod === 'cd') {
            await this._updateObjectMapProperty(vm, 'other_config', {
              'install-repository': 'cdrom'
            })
          }
        }
      }
    }

    // Inserts the CD if necessary.
    if (installMethod === 'cd') {
      // When the VM is started, if PV, the CD drive will become not
      // bootable and the first disk bootable.
      await this._insertCdIntoVm(installRepository, vm, {
        bootable: true
      })
    }

    let nDisks = 0

    // Modify existing (previous template) disks if necessary
    existingVdis && await Promise.all(mapToArray(existingVdis, async ({ size, $SR: srId, ...properties }, userdevice) => {
      ++nDisks

      const vbd = find(vm.$VBDs, { userdevice })
      if (!vbd) {
        return
      }
      const vdi = vbd.$VDI
      await this._setObjectProperties(vdi, properties)

      // if the disk is bigger
      if (
        size != null &&
        size > vdi.virtual_size
      ) {
        await this.resizeVdi(vdi.$id, size)
      }
      // if another SR is set, move it there
      if (srId) {
        await this.moveVdi(vdi.$id, srId)
      }
    }))

    // Creates the user defined VDIs.
    //
    // TODO: set vm.suspend_SR
    if (vdis) {
      const devices = await this.call('VM.get_allowed_VBD_devices', vm.$ref)
      await Promise.all(mapToArray(vdis, (vdiDescription, i) => {
        ++nDisks

        return this._createVdi(
          vdiDescription.size, // FIXME: Should not be done in Xapi.
          {
            name_label: vdiDescription.name_label,
            name_description: vdiDescription.name_description,
            sr: vdiDescription.sr || vdiDescription.SR
          }
        )
          .then(ref => this._getOrWaitObject(ref))
          .then(vdi => this._createVbd(vm, vdi, {
            // Only the first VBD if installMethod is not cd is bootable.
            bootable: installMethod !== 'cd' && !i,

            userdevice: devices[i]
          }))
      }))
    }

    // Destroys the VIFs cloned from the template.
    await Promise.all(mapToArray(vm.$VIFs, vif => this._deleteVif(vif)))

    // Creates the VIFs specified by the user.
    if (vifs) {
      const devices = await this.call('VM.get_allowed_VIF_devices', vm.$ref)
      await Promise.all(mapToArray(vifs, (vif, index) => this._createVif(
        vm,
        this.getObject(vif.network),
        {
          ipv4_allowed: vif.ipv4_allowed,
          ipv6_allowed: vif.ipv6_allowed,
          device: devices[index],
          locking_mode: isEmpty(vif.ipv4_allowed) && isEmpty(vif.ipv6_allowed) ? 'network_default' : 'locked',
          mac: vif.mac,
          mtu: vif.mtu
        }
      )))
    }

    // TODO: Assign VGPUs.

    if (cloudConfig != null) {
      // Refresh the record.
      vm = await this._waitObject(vm.$id, vm => vm.VBDs.length === nDisks)

      // Find the SR of the first VDI.
      let srRef
      forEach(vm.$VBDs, vbd => {
        let vdi
        if (
          vbd.type === 'Disk' &&
          (vdi = vbd.$VDI)
        ) {
          srRef = vdi.SR
          return false
        }
      })

      const method = coreOs
        ? 'createCoreOsCloudInitConfigDrive'
        : 'createCloudInitConfigDrive'
      await this[method](vm.$id, srRef, cloudConfig)
    }

    return this._waitObject(vm.$id)
  },

  // High level method to edit a VM.
  //
  // Params do not correspond directly to XAPI props.
  _editVm: makeEditObject({
    autoPoweron: {
      set (value, vm) {
        return Promise.all([
          this._updateObjectMapProperty(vm, 'other_config', {
            autoPoweron: value ? 'true' : null
          }),
          value && this.setPoolProperties({
            autoPoweron: true
          })
        ])
      }
    },

    CPUs: 'cpus',
    cpus: {
      addToLimits: true,

      // Current value may have constraints with other values.
      //
      // If the other value is not set and the constraint is not
      // respected, the other value is changed first.
      constraints: {
        cpusStaticMax: gte
      },

      get: vm => +vm.VCPUs_at_startup,
      set: [
        'VCPUs_at_startup',
        function (value, vm) {
          return isVmRunning(vm) && this._set('VCPUs_number_live', value)
        }
      ]
    },

    cpuCap: {
      get: vm => vm.VCPUs_params.cap && +vm.VCPUs_params.cap,
      set (cap, vm) {
        return this._updateObjectMapProperty(vm, 'VCPUs_params', { cap })
      }
    },

    cpusMax: 'cpusStaticMax',
    cpusStaticMax: {
      constraints: {
        cpus: lte
      },
      get: vm => +vm.VCPUs_max,
      set: 'VCPUs_max'
    },

    cpuWeight: {
      get: vm => vm.VCPUs_params.weight && +vm.VCPUs_params.weight,
      set (weight, vm) {
        return this._updateObjectMapProperty(vm, 'VCPUs_params', { weight })
      }
    },

    highAvailability: {
      set (ha, vm) {
        return this.call('VM.set_ha_restart_priority', vm.$ref, ha ? 'restart' : '')
      }
    },

    memoryMin: {
      constraints: {
        memoryMax: gte
      },
      get: vm => +vm.memory_dynamic_min,
      preprocess: parseSize,
      set: 'memory_dynamic_min'
    },

    memory: 'memoryMax',
    memoryMax: {
      addToLimits: true,
      limitName: 'memory',
      constraints: {
        memoryMin: lte,
        memoryStaticMax: gte
      },
      get: vm => +vm.memory_dynamic_max,
      preprocess: parseSize,
      set: 'memory_dynamic_max'
    },

    memoryStaticMax: {
      constraints: {
        memoryMax: lte
      },
      get: vm => +vm.memory_static_max,
      preprocess: parseSize,
      set: 'memory_static_max'
    },

    nameDescription: true,

    nameLabel: true,

    PV_args: true,

    tags: true
  }),

  async editVm (id, props, checkLimits) {
    return /* await */ this._editVm(this.getObject(id), props, checkLimits)
  },

  async revertVm (snapshotId, snapshotBefore = true) {
    const snapshot = this.getObject(snapshotId)
    if (snapshotBefore) {
      await this._snapshotVm(snapshot.$snapshot_of)
    }
    return this.call('VM.revert', snapshot.$ref)
  }
}
<commit_msg>fix(vm.create): properly handle optional param `VDIs`<commit_after>import deferrable from 'golike-defer'
import find from 'lodash/find'
import gte from 'lodash/gte'
import isEmpty from 'lodash/isEmpty'
import lte from 'lodash/lte'

import {
  forEach,
  mapToArray,
  noop,
  parseSize,
  pCatch
} from '../../utils'

import {
  isVmHvm,
  isVmRunning,
  makeEditObject
} from '../utils'

export default {
  // TODO: clean up on error.
  @deferrable.onFailure
  async createVm ($onFailure, templateId, {
    name_label, // deprecated
    nameLabel = name_label, // eslint-disable-line camelcase

    clone = true,
    installRepository = undefined,
    vdis = undefined,
    vifs = undefined,
    existingVdis = undefined,

    coreOs = false,
    cloudConfig = undefined,

    ...props
  } = {}, checkLimits) {
    const installMethod = (() => {
      if (installRepository == null) {
        return 'none'
      }

      try {
        installRepository = this.getObject(installRepository)
        return 'cd'
      } catch (_) {
        return 'network'
      }
    })()
    const template = this.getObject(templateId)

    // Clones the template.
    const vmRef = await this[clone ? '_cloneVm' : '_copyVm'](template, nameLabel)
    $onFailure(() => this.deleteVm(vmRef, true)::pCatch(noop))

    // TODO: copy BIOS strings?

    // Removes disks from the provision XML, we will create them by
    // ourselves.
    await this.call('VM.remove_from_other_config', vmRef, 'disks')::pCatch(noop)

    // Creates the VDIs and executes the initial steps of the
    // installation.
    await this.call('VM.provision', vmRef)

    let vm = await this._getOrWaitObject(vmRef)

    // Set VMs params.
    await this._editVm(vm, props, checkLimits)

    // Sets boot parameters.
    {
      const isHvm = isVmHvm(vm)

      if (isHvm) {
        if (!isEmpty(vdis) || installMethod === 'network') {
          const { HVM_boot_params: bootParams } = vm
          let order = bootParams.order
          if (order) {
            order = 'n' + order.replace('n', '')
          } else {
            order = 'ncd'
          }

          this._setObjectProperties(vm, {
            HVM_boot_params: { ...bootParams, order }
          })
        }
      } else { // PV
        if (vm.PV_bootloader === 'eliloader') {
          if (installMethod === 'network') {
            // TODO: normalize RHEL URL?

            await this._updateObjectMapProperty(vm, 'other_config', {
              'install-repository': installRepository
            })
          } else if (installMethod === 'cd') {
            await this._updateObjectMapProperty(vm, 'other_config', {
              'install-repository': 'cdrom'
            })
          }
        }
      }
    }

    // Inserts the CD if necessary.
    if (installMethod === 'cd') {
      // When the VM is started, if PV, the CD drive will become not
      // bootable and the first disk bootable.
      await this._insertCdIntoVm(installRepository, vm, {
        bootable: true
      })
    }

    let nDisks = 0

    // Modify existing (previous template) disks if necessary
    existingVdis && await Promise.all(mapToArray(existingVdis, async ({ size, $SR: srId, ...properties }, userdevice) => {
      ++nDisks

      const vbd = find(vm.$VBDs, { userdevice })
      if (!vbd) {
        return
      }
      const vdi = vbd.$VDI
      await this._setObjectProperties(vdi, properties)

      // if the disk is bigger
      if (
        size != null &&
        size > vdi.virtual_size
      ) {
        await this.resizeVdi(vdi.$id, size)
      }
      // if another SR is set, move it there
      if (srId) {
        await this.moveVdi(vdi.$id, srId)
      }
    }))

    // Creates the user defined VDIs.
    //
    // TODO: set vm.suspend_SR
    if (!isEmpty(vdis)) {
      const devices = await this.call('VM.get_allowed_VBD_devices', vm.$ref)
      await Promise.all(mapToArray(vdis, (vdiDescription, i) => {
        ++nDisks

        return this._createVdi(
          vdiDescription.size, // FIXME: Should not be done in Xapi.
          {
            name_label: vdiDescription.name_label,
            name_description: vdiDescription.name_description,
            sr: vdiDescription.sr || vdiDescription.SR
          }
        )
          .then(ref => this._getOrWaitObject(ref))
          .then(vdi => this._createVbd(vm, vdi, {
            // Only the first VBD if installMethod is not cd is bootable.
            bootable: installMethod !== 'cd' && !i,

            userdevice: devices[i]
          }))
      }))
    }

    // Destroys the VIFs cloned from the template.
    await Promise.all(mapToArray(vm.$VIFs, vif => this._deleteVif(vif)))

    // Creates the VIFs specified by the user.
    if (vifs) {
      const devices = await this.call('VM.get_allowed_VIF_devices', vm.$ref)
      await Promise.all(mapToArray(vifs, (vif, index) => this._createVif(
        vm,
        this.getObject(vif.network),
        {
          ipv4_allowed: vif.ipv4_allowed,
          ipv6_allowed: vif.ipv6_allowed,
          device: devices[index],
          locking_mode: isEmpty(vif.ipv4_allowed) && isEmpty(vif.ipv6_allowed) ? 'network_default' : 'locked',
          mac: vif.mac,
          mtu: vif.mtu
        }
      )))
    }

    // TODO: Assign VGPUs.

    if (cloudConfig != null) {
      // Refresh the record.
      vm = await this._waitObject(vm.$id, vm => vm.VBDs.length === nDisks)

      // Find the SR of the first VDI.
      let srRef
      forEach(vm.$VBDs, vbd => {
        let vdi
        if (
          vbd.type === 'Disk' &&
          (vdi = vbd.$VDI)
        ) {
          srRef = vdi.SR
          return false
        }
      })

      const method = coreOs
        ? 'createCoreOsCloudInitConfigDrive'
        : 'createCloudInitConfigDrive'
      await this[method](vm.$id, srRef, cloudConfig)
    }

    return this._waitObject(vm.$id)
  },

  // High level method to edit a VM.
  //
  // Params do not correspond directly to XAPI props.
  _editVm: makeEditObject({
    autoPoweron: {
      set (value, vm) {
        return Promise.all([
          this._updateObjectMapProperty(vm, 'other_config', {
            autoPoweron: value ? 'true' : null
          }),
          value && this.setPoolProperties({
            autoPoweron: true
          })
        ])
      }
    },

    CPUs: 'cpus',
    cpus: {
      addToLimits: true,

      // Current value may have constraints with other values.
      //
      // If the other value is not set and the constraint is not
      // respected, the other value is changed first.
      constraints: {
        cpusStaticMax: gte
      },

      get: vm => +vm.VCPUs_at_startup,
      set: [
        'VCPUs_at_startup',
        function (value, vm) {
          return isVmRunning(vm) && this._set('VCPUs_number_live', value)
        }
      ]
    },

    cpuCap: {
      get: vm => vm.VCPUs_params.cap && +vm.VCPUs_params.cap,
      set (cap, vm) {
        return this._updateObjectMapProperty(vm, 'VCPUs_params', { cap })
      }
    },

    cpusMax: 'cpusStaticMax',
    cpusStaticMax: {
      constraints: {
        cpus: lte
      },
      get: vm => +vm.VCPUs_max,
      set: 'VCPUs_max'
    },

    cpuWeight: {
      get: vm => vm.VCPUs_params.weight && +vm.VCPUs_params.weight,
      set (weight, vm) {
        return this._updateObjectMapProperty(vm, 'VCPUs_params', { weight })
      }
    },

    highAvailability: {
      set (ha, vm) {
        return this.call('VM.set_ha_restart_priority', vm.$ref, ha ? 'restart' : '')
      }
    },

    memoryMin: {
      constraints: {
        memoryMax: gte
      },
      get: vm => +vm.memory_dynamic_min,
      preprocess: parseSize,
      set: 'memory_dynamic_min'
    },

    memory: 'memoryMax',
    memoryMax: {
      addToLimits: true,
      limitName: 'memory',
      constraints: {
        memoryMin: lte,
        memoryStaticMax: gte
      },
      get: vm => +vm.memory_dynamic_max,
      preprocess: parseSize,
      set: 'memory_dynamic_max'
    },

    memoryStaticMax: {
      constraints: {
        memoryMax: lte
      },
      get: vm => +vm.memory_static_max,
      preprocess: parseSize,
      set: 'memory_static_max'
    },

    nameDescription: true,

    nameLabel: true,

    PV_args: true,

    tags: true
  }),

  async editVm (id, props, checkLimits) {
    return /* await */ this._editVm(this.getObject(id), props, checkLimits)
  },

  async revertVm (snapshotId, snapshotBefore = true) {
    const snapshot = this.getObject(snapshotId)
    if (snapshotBefore) {
      await this._snapshotVm(snapshot.$snapshot_of)
    }
    return this.call('VM.revert', snapshot.$ref)
  }
}
<|endoftext|>


<commit_before>(function() {
  angular.module('ngBootstrapizeMaven')
  .service('pageCache', function ($http, mvnLinker) {
    var memory = {};

    var pageCache = {
      get: function (path) {
        return memory[path];
      },

      trimPageContent: function (data) {
        if (data.indexOf('<frameset') >= 0) {
          // get only body content, as jquery cannot parse full page
          data = data.substring(data.indexOf('<frameset'), data.lastIndexOf('</frameset>'));
        } else {
          // get only body content, as jquery cannot parse full page
          data = data.substring(data.indexOf('<body'), data.lastIndexOf(''));
        }

        // very shitty - remove 'non-breaking space styling'
        data = data.replace(/( | )/g, '');

        return '
' + data.substr(data.indexOf('>') + 1) + '
';
      },

      load: function (path, successFn, failureFn, relativeTo) {
        path = path.replace(/\/\//g, '/').replace(/:\//g, '://');

        if (pageCache.get(path)) {
          successFn(pageCache.get(path));
        } else {
          $http.get(path).success(function (pageSrc, status, headers, config) {
            // FIXME: stopping images from loading - but images in content should be loaded!
            pageSrc = pageSrc.replace(/<img /g, '<i ').replace(/<\/img>/g, '');
            // rewrite links so they work in ang-boot-mav-site
            pageSrc = pageSrc.replace(/href=".*?"/g,
              mvnLinker.linkRelativeTo(path.substr('/maven'.length)));

            var pageData =  memory[path] = { src: pageSrc };
            pageData.status = status;
            pageData.loadTime = new Date().toString();
            pageData.trimmed = pageCache.trimPageContent(pageSrc);
            pageData.processed = $(pageData.trimmed);

            successFn(pageCache.get(path));
          }).error(function (data, status, headers, config) {
            memory[path] = { data: data, status: status };

            if (failureFn) {
              failureFn(memory[path]);
            }
          });
        }
      }
    };

    return pageCache;
  });
})();<commit_msg>Better link handling<commit_after>(function() {
  angular.module('ngBootstrapizeMaven')
  .service('pageCache', function ($http, mvnLinker) {
    var memory = {};

    var pageCache = {
      get: function (path) {
        return memory[path];
      },

      trimPageContent: function (data) {
        if (data.indexOf('<frameset') >= 0) {
          // get only body content, as jquery cannot parse full page
          data = data.substring(data.indexOf('<frameset'), data.lastIndexOf('</frameset>'));
        } else {
          // get only body content, as jquery cannot parse full page
          data = data.substring(data.indexOf('<body'), data.lastIndexOf(''));
        }

        // very shitty - remove 'non-breaking space styling'
        data = data.replace(/( | )/g, '');

        return '
' + data.substr(data.indexOf('>') + 1) + '
';
      },

      load: function (path, successFn, failureFn, relativeTo) {
        path = path.replace(/\/\//g, '/').replace(/:\//g, '://').replace(/^\/?#/, '/maven');

        if (pageCache.get(path)) {
          successFn(pageCache.get(path));
        } else {
          $http.get(path).success(function (pageSrc, status, headers, config) {
            // FIXME: stopping images from loading - but images in content should be loaded!
            pageSrc = pageSrc.replace(/<img /g, '<i ').replace(/<\/img>/g, '');
            // rewrite links so they work in ang-boot-mav-site
            pageSrc = pageSrc.replace(/href=".*?"/g,
              mvnLinker.linkRelativeTo(path.substr(path.indexOf('maven/') + 5)));

            var pageData =  memory[path] = { src: pageSrc };
            pageData.status = status;
            pageData.loadTime = new Date().toString();
            pageData.trimmed = pageCache.trimPageContent(pageSrc);
            pageData.processed = $(pageData.trimmed);

            successFn(pageCache.get(path));
          }).error(function (data, status, headers, config) {
            memory[path] = { data: data, status: status };

            if (failureFn) {
              failureFn(memory[path]);
            }
          });
        }
      }
    };

    return pageCache;
  });
})();<|endoftext|>


<commit_before>// robot.js -- OMG ROBOTS

var
  sys         = require('sys'),
  assert      = require('assert'),
  fieldobject = require('./fieldobject'),
  vec         = require('./vector'),
  NORTH       = new vec.Vector(0, 1);

function Robot(name, location, field) {
  this.name = name;
  this.field = field;
  this.location = new vec.Vector(location[0], location[1]);
  this.rotation = vec.normalizeAngle(Math.random() * 2 * Math.PI);
  this.wantedRotation = this.rotation;

  this.engine = 1;
  this.turretRot = 0;
  this.scanMode = "";
  this.scanWidth = Math.PI / 6;
  this.scanRange = 500;
  this.speed = 0;
  this.throttle = 0;
  this.armor = 100;
}
sys.inherits(Robot, fieldobject.FieldObject);

// Return enough information for a client to draw us on the screen.
Robot.prototype.renderInfo = function() {
  return {
    type: 'robot',
    name: this.name,
    location: [this.location.x, this.location.y],
    rotation: this.rotation,
    turret_rot: this.turretRot,
    scan_mode: this.scanMode,
    scan_width: this.scanWidth,
    scanrange: this.scanRange,
    speed: this.speed
  };
};

Robot.prototype.toJSON = function() {
  return {
    name: this.name,
    armor: this.armor
  };
};

Robot.prototype.pump = function() {
  // Calculate our physics: turn, move, or whatever.
  // First, we'll turn.
  var angleDiff = vec.normalizeAngle(this.wantedRotation - this.rotation),
      rotAccel = this.engine/5;
  if (Math.abs(angleDiff) < rotAccel) {
    this.rotation = this.wantedRotation;
  } else {
    this.rotation += angleDiff>0? rotAccel : -rotAccel;
  }
  this.rotation = vec.normalizeAngle(this.rotation);

  // Now, do throttle!
  var speedDiff = this.throttle - this.speed,
      accel = this.engine * 3;
  if (Math.abs(speedDiff) < accel) {
    this.speed += speedDiff;
  } else {
    this.speed += speedDiff>0? accel : -accel;
  }

  // Now, change our location!
  this.field.move(this,
    new vec.Vector(
      Math.sin(this.rotation),
      Math.cos(this.rotation)
    ).multiply(this.speed));
};

Robot.prototype.turn = function(amount) {
  this.wantedRotation = this.rotation + amount;
  return amount;
};

Robot.prototype.bearingTo = function(location) {
    // Return the direction (in radians) from our nose to the given vector
    // |
    // |
    // |-.  this angle
    // |  \
    // us-.:___      -   -   - the angle our vector library expects
    //         ''---..__
    //                  ''--location
    var angle = location.sub(this.location).angleTo(NORTH);
    angle = location.sub(this.location).x>0? angle : -angle;
    return vec.normalizeAngle(
      // Negative because the vector library is counting CCW and we want CW
      angle - this.rotation
    );
};

Robot.prototype.turretBearingTo = function(location) {
    // Return the direction (in radians) from our nose to the given vector
    // |   /turret angle
    // |  /
    // | /. return this angle
    // |/  \
    // us-.:___      -   -   - the angle our vector library expects
    //         ''---..__
    //                  ''--location
    return vec.normalizeAngle(
      // Negative because the vector library is counting CCW and we want CW
      location.sub(this.location).angleTo(NORTH) - this.rotation
    );
};

Robot.prototype.getTurretRot = function() {
  return this.turretRot;
};

Robot.prototype.setTurretRot = function(newRot) {
  this.turretRot = vec.normalizeAngle(newRot);
  return newRot;
};

Robot.prototype.getLocation = function() {
  return [this.location.x, this.location.y];
};

Robot.prototype.setThrottle = function(throttle) {
  // Set throttle. The minimum we can have is -self.engine*5 and the max we
  // can have is self.engine*10.
  // This expects a number between -50 and 100.
  var amount = Math.max(-50, Math.min(throttle, 100));
  this.throttle = 10 * this.engine * amount/100;
  return this.throttle;
};

Robot.prototype.getThrottle = function() {
  return this.throttle;
};

Robot.prototype.scanRobots = function(scanWidth) {
    // Scan for robots! Returns a function that, when called, will scan for
    // other robots.
    assert.ok(scanWidth <= Math.PI/2, "You can only scan 90° to one side.");
    this.scanWidth = scanWidth;
    this.scanMode = "robots";
    var self = this; // for closure
    return function() {
      self.scanMode = "";
      return self.field.allObjectsWithin(self.location, self.scanRange).filter(
        function(obj) {
          return (obj instanceof Robot) &&
                 (obj !== self);
        });
    };
};

process.mixin(exports,
  {
    Robot: Robot
  }
);
<commit_msg>Fixed turretBearingto bugs<commit_after>// robot.js -- OMG ROBOTS

var
  sys         = require('sys'),
  assert      = require('assert'),
  fieldobject = require('./fieldobject'),
  vec         = require('./vector'),
  NORTH       = new vec.Vector(0, 1);

function Robot(name, location, field) {
  this.name = name;
  this.field = field;
  this.location = new vec.Vector(location[0], location[1]);
  this.rotation = vec.normalizeAngle(Math.random() * 2 * Math.PI);
  this.wantedRotation = this.rotation;

  this.engine = 1;
  this.turretRot = 0;
  this.scanMode = "";
  this.scanWidth = Math.PI / 6;
  this.scanRange = 500;
  this.speed = 0;
  this.throttle = 0;
  this.armor = 100;
}
sys.inherits(Robot, fieldobject.FieldObject);

// Return enough information for a client to draw us on the screen.
Robot.prototype.renderInfo = function() {
  return {
    type: 'robot',
    name: this.name,
    location: [this.location.x, this.location.y],
    rotation: this.rotation,
    turret_rot: this.turretRot,
    scan_mode: this.scanMode,
    scan_width: this.scanWidth,
    scanrange: this.scanRange,
    speed: this.speed
  };
};

Robot.prototype.toJSON = function() {
  return {
    name: this.name,
    armor: this.armor
  };
};

Robot.prototype.pump = function() {
  // Calculate our physics: turn, move, or whatever.
  // First, we'll turn.
  var angleDiff = vec.normalizeAngle(this.wantedRotation - this.rotation),
      rotAccel = this.engine/5;
  if (Math.abs(angleDiff) < rotAccel) {
    this.rotation = this.wantedRotation;
  } else {
    this.rotation += angleDiff>0? rotAccel : -rotAccel;
  }
  this.rotation = vec.normalizeAngle(this.rotation);

  // Now, do throttle!
  var speedDiff = this.throttle - this.speed,
      accel = this.engine * 3;
  if (Math.abs(speedDiff) < accel) {
    this.speed += speedDiff;
  } else {
    this.speed += speedDiff>0? accel : -accel;
  }

  // Now, change our location!
  this.field.move(this,
    new vec.Vector(
      Math.sin(this.rotation),
      Math.cos(this.rotation)
    ).multiply(this.speed));
};

Robot.prototype.turn = function(amount) {
  this.wantedRotation = this.rotation + amount;
  return amount;
};

Robot.prototype.bearingTo = function(location) {
    // Return the direction (in radians) from our nose to the given vector
    // |
    // |
    // |-.  this angle
    // |  \
    // us-.:___      -   -   - the angle our vector library expects
    //         ''---..__
    //                  ''--location
    var angle = location.sub(this.location).angleTo(NORTH);
    angle = location.sub(this.location).x>0? angle : -angle;
    return vec.normalizeAngle(
      // Negative because the vector library is counting CCW and we want CW
      angle - this.rotation
    );
};

Robot.prototype.turretBearingTo = function(location) {
    // Return the direction (in radians) from our nose to the given vector
    // |   /turret angle
    // |  /
    // | /. return this angle
    // |/  \
    // us-.:___      -   -   - the angle our vector library expects
    //         ''---..__
    //                  ''--location
    var angle = location.sub(this.location).angleTo(NORTH);
    angle = location.sub(this.location).x>0? angle : -angle;
    return vec.normalizeAngle(
      // Negative because the vector library is counting CCW and we want CW
      angle - (this.rotation + this.turretRot)
    );
};

Robot.prototype.distanceTo = function(location) {
    return this.location.sub(location).dist();
};

Robot.prototype.getTurretRot = function() {
  return this.turretRot;
};

Robot.prototype.setTurretRot = function(newRot) {
  this.turretRot = vec.normalizeAngle(newRot);
  return newRot;
};

Robot.prototype.getLocation = function() {
  return [this.location.x, this.location.y];
};

Robot.prototype.setThrottle = function(throttle) {
  // Set throttle. The minimum we can have is -self.engine*5 and the max we
  // can have is self.engine*10.
  // This expects a number between -50 and 100.
  var amount = Math.max(-50, Math.min(throttle, 100));
  this.throttle = 10 * this.engine * amount/100;
  return this.throttle;
};

Robot.prototype.getThrottle = function() {
  return this.throttle;
};

Robot.prototype.scanRobots = function(scanWidth) {
    // Scan for robots! Returns a function that, when called, will scan for
    // other robots.
    assert.ok(scanWidth <= Math.PI/2, "You can only scan 90° to one side.");
    this.scanWidth = scanWidth;
    this.scanMode = "robots";
    var self = this; // for closure
    return function() {
      self.scanMode = "";
      return self.field.allObjectsWithin(self.location, self.scanRange).filter(
        function(obj) {
          return (obj instanceof Robot) &&
                 (obj !== self);
        });
    };
};

process.mixin(exports,
  {
    Robot: Robot
  }
);
<|endoftext|>


<commit_before>'use strict';

let isCI = !!process.env.CI;

let config = {
  "framework": "qunit",
  "test_page": "tests/index.html?hidepassed",
  "disable_watching": true,
  "launchers": {
    "Node": {
      "exe": "node", args: ["./bin/run-node-tests.js"],
      "protocol": "tap"
     }
  },
  "browser_args": {
    "Chrome": {
      "mode": "ci",
      "args": [
        '--disable-gpu',
        '--headless',
        '--remote-debugging-port=9222'
      ]
    }
  },
  "launch_in_dev": [
    "Chrome",
    "Node"
  ],
  "launch_in_ci": [
    "Chrome",
    "Node"
  ]
};

if (isCI) {
  config.tap_quiet_logs = true;
}

module.exports = config;
<commit_msg>testem: Adjust Chrome command line flags<commit_after>'use strict';

let isCI = !!process.env.CI;

let config = {
  "framework": "qunit",
  "test_page": "tests/index.html?hidepassed",
  "disable_watching": true,
  "launchers": {
    "Node": {
      "exe": "node", args: ["./bin/run-node-tests.js"],
      "protocol": "tap"
     }
  },
  "browser_args": {
    "Chrome": {
      "mode": "ci",
      "args": [
        // --no-sandbox is needed when running Chrome inside a container
        process.env.CI ? '--no-sandbox' : null,
        '--headless',
        '--disable-gpu',
        '--disable-dev-shm-usage',
        '--disable-software-rasterizer',
        '--mute-audio',
        '--remote-debugging-port=0',
        '--window-size=1440,900'
      ]
    }
  },
  "launch_in_dev": [
    "Chrome",
    "Node"
  ],
  "launch_in_ci": [
    "Chrome",
    "Node"
  ]
};

if (isCI) {
  config.tap_quiet_logs = true;
}

module.exports = config;
<|endoftext|>


<commit_before>/* eslint-env node */
module.e€~€|%%%|%€€|$~$¥{!{!!~$$~*€|>]!]$$~xports = {
  "test_page": "tests/index.html?hidepassed",
  "disable_watching": true,
  "launchers": {
    "AltPhantom": {
      "exe": "phantomjs",
      "args": ["tests/phantom-runer.js"],
      "protocol": "browser"
    }
  },
  "launch_in_ci": [
    "AltPhantom"
  ],
  "launch_in_dev": [
    "AltPhantom",
    "Chrome"
  ]
};
<commit_msg>Revert "Break stuff more"<commit_after>/* eslint-env node */
module.exports = {
  "test_page": "tests/index.html?hidepassed",
  "disable_watching": true,
  "launchers": {
    "AltPhantom": {
      "exe": "phantomjs",
      "args": ["tests/phantom-runer.js"],
      "protocol": "browser"
    }
  },
  "launch_in_ci": [
    "AltPhantom"
  ],
  "launch_in_dev": [
    "AltPhantom",
    "Chrome"
  ]
};
<|endoftext|>


<commit_before>// Can't tell which thread we're in so let's try both
import electron from 'electron'

const Menu = electron.Menu || electron.remote.Menu
const app = electron.app || electron.remote.app
const shell = electron.shell || electron.remote.shell

export default function makeMenu (window) {
  if (process.platform === 'darwin') {
    const template = [{
      label: 'Keybase',
      submenu: [
        {label: 'About Keybase', role: 'about'},
        {type: 'separator'},
        {label: 'Hide Keybase', accelerator: 'CmdOrCtrl+H', role: 'hide'},
        {label: 'Hide Others', accelerator: 'CmdOrCtrl+Shift+H', role: 'hideothers'},
        {label: 'Show All', role: 'unhide'},
        {type: 'separator'},
        {label: 'Quit', accelerator: 'CmdOrCtrl+Q', click () { app.emit('close-windows') }}
      ]
    }, {
      label: 'Edit',
      submenu: [
        {label: 'Undo', accelerator: 'CmdOrCtrl+Z', role: 'undo'},
        {label: 'Redo', accelerator: 'Shift+CmdOrCtrl+Z', role: 'redo'},
        {type: 'separator'},
        {label: 'Cut', accelerator: 'CmdOrCtrl+X', role: 'cut'},
        {label: 'Copy', accelerator: 'CmdOrCtrl+C', role: 'copy'},
        {label: 'Paste', accelerator: 'CmdOrCtrl+V', role: 'paste'},
        {label: 'Select All', accelerator: 'CmdOrCtrl+A', role: 'selectall'}
      ]
    }, {
      label: 'Window',
      submenu: [
        {label: 'Minimize', accelerator: 'CmdOrCtrl+M', role: 'minimize'},
        {label: 'Close', accelerator: 'CmdOrCtrl+W', role: 'close'},
        {type: 'separator'},
        {label: 'Bring All to Front', role: 'front'},
        {label: 'Reload',
          accelerator: 'CmdOrCtrl+R',
          click: (item, focusedWindow) => focusedWindow && focusedWindow.reload()
        }
      ].concat(__DEV__ ? ([ // eslint-disable-line no-undef
        {label: 'Toggle Developer Tools',
          accelerator: (() => (process.platform === 'darwin') ? 'Alt+Command+I' : 'Ctrl+Shift+I')(),
          click: (item, focusedWindow) => focusedWindow && focusedWindow.toggleDevTools()
        }
      ]) : [])
    }, {
      label: 'Help',
      submenu: [
        {label: 'Learn More', click () { shell.openExternal('https://keybase.io') }}
      ]
    }]
    const menu = Menu.buildFromTemplate(template)
    Menu.setApplicationMenu(menu)
  } else {
    const template = [{
      label: '&File',
      submenu: [
        {label: '&Close', accelerator: 'CmdOrCtrl+W', click () { this.remoteWindow.close() }}
      ]
    }, {
      label: 'Help',
      submenu: [{label: 'Learn More', click () { shell.openExternal('https://keybase.io') }}]
    }]
    const menu = Menu.buildFromTemplate(template)
    window.setMenu(menu)
  }
}

export function setupContextMenu(window) {
  console.log('setting up context menu:', window)

  const InputMenu = Menu.buildFromTemplate([
    {label: 'Undo', role: 'undo'},
    {label: 'Redo', role: 'redo'},
    {type: 'separator'},
    {label: 'Cut', role: 'cut'},
    {label: 'Copy', role: 'copy'},
    {label: 'Paste', role: 'paste'},
    {type: 'separator'},
    {label: 'Select all', role: 'selectall'}
  ])

  console.log(document, document.body)

  document.body.addEventListener('contextmenu', e => {
    console.log('got context request', e)
    e.preventDefault();
    e.stopPropagation();

    let node = e.target

    while (node) {
      if (node.nodeName.match(/^(input|textarea)$/i) || node.isContentEditable) {
        InputMenu.popup(window)
        break
      }
      node = node.parentNode
    }
  })
}
<commit_msg>cleanup<commit_after>// Can't tell which thread we're in so let's try both
import electron from 'electron'

const Menu = electron.Menu || electron.remote.Menu
const app = electron.app || electron.remote.app
const shell = electron.shell || electron.remote.shell

export default function makeMenu (window) {
  if (process.platform === 'darwin') {
    const template = [{
      label: 'Keybase',
      submenu: [
        {label: 'About Keybase', role: 'about'},
        {type: 'separator'},
        {label: 'Hide Keybase', accelerator: 'CmdOrCtrl+H', role: 'hide'},
        {label: 'Hide Others', accelerator: 'CmdOrCtrl+Shift+H', role: 'hideothers'},
        {label: 'Show All', role: 'unhide'},
        {type: 'separator'},
        {label: 'Quit', accelerator: 'CmdOrCtrl+Q', click () { app.emit('close-windows') }}
      ]
    }, {
      label: 'Edit',
      submenu: [
        {label: 'Undo', accelerator: 'CmdOrCtrl+Z', role: 'undo'},
        {label: 'Redo', accelerator: 'Shift+CmdOrCtrl+Z', role: 'redo'},
        {type: 'separator'},
        {label: 'Cut', accelerator: 'CmdOrCtrl+X', role: 'cut'},
        {label: 'Copy', accelerator: 'CmdOrCtrl+C', role: 'copy'},
        {label: 'Paste', accelerator: 'CmdOrCtrl+V', role: 'paste'},
        {label: 'Select All', accelerator: 'CmdOrCtrl+A', role: 'selectall'}
      ]
    }, {
      label: 'Window',
      submenu: [
        {label: 'Minimize', accelerator: 'CmdOrCtrl+M', role: 'minimize'},
        {label: 'Close', accelerator: 'CmdOrCtrl+W', role: 'close'},
        {type: 'separator'},
        {label: 'Bring All to Front', role: 'front'},
        {label: 'Reload',
          accelerator: 'CmdOrCtrl+R',
          click: (item, focusedWindow) => focusedWindow && focusedWindow.reload()
        }
      ].concat(__DEV__ ? ([ // eslint-disable-line no-undef
        {label: 'Toggle Developer Tools',
          accelerator: (() => (process.platform === 'darwin') ? 'Alt+Command+I' : 'Ctrl+Shift+I')(),
          click: (item, focusedWindow) => focusedWindow && focusedWindow.toggleDevTools()
        }
      ]) : [])
    }, {
      label: 'Help',
      submenu: [
        {label: 'Learn More', click () { shell.openExternal('https://keybase.io') }}
      ]
    }]
    const menu = Menu.buildFromTemplate(template)
    Menu.setApplicationMenu(menu)
  } else {
    const template = [{
      label: '&File',
      submenu: [
        {label: '&Close', accelerator: 'CmdOrCtrl+W', click () { this.remoteWindow.close() }}
      ]
    }, {
      label: 'Help',
      submenu: [{label: 'Learn More', click () { shell.openExternal('https://keybase.io') }}]
    }]
    const menu = Menu.buildFromTemplate(template)
    window.setMenu(menu)
  }
}

export function setupContextMenu(window) {
  const InputMenu = Menu.buildFromTemplate([
    {label: 'Undo', role: 'undo'},
    {label: 'Redo', role: 'redo'},
    {type: 'separator'},
    {label: 'Cut', role: 'cut'},
    {label: 'Copy', role: 'copy'},
    {label: 'Paste', role: 'paste'},
    {type: 'separator'},
    {label: 'Select all', role: 'selectall'}
  ])

  document.body.addEventListener('contextmenu', e => {
    e.preventDefault();
    e.stopPropagation();

    let node = e.target

    while (node) {
      if (node.nodeName.match(/^(input|textarea)$/i) || node.isContentEditable) {
        InputMenu.popup(window)
        break
      }
      node = node.parentNode
    }
  })
}
<|endoftext|>


<commit_before>var sessions = {};
var channels = {};

var online = [];

var express = require('express');
var router = express.Router();

var mumble = require("../modules/mumble");

module.exports = function(io) {
  mumble(function(error, connection) {
    if( error ) { throw new Error( error ); }

    //if(process.env.NODE_ENV == 'production')
      connection.authenticate( 'ontrac-bot2', 'regis' );

    connection.on( 'userState', function (state) {
      sessions[state.session] = state;
      online = [];
      for (var key in sessions) {
        if (sessions.hasOwnProperty(key)) {
          if(sessions[key].name.indexOf("ontrac") == -1)
            online.push( sessions[key].name );
        }
      }
    });

    router.get('/online', function(req, res) {
      res.json(online);
    });

  });
  return {router: router, models: []}
};
<commit_msg>NEW MUMBLE<commit_after>var sessions = {};
var channels = {};

var online = [];

var express = require('express');
var router = express.Router();

var mumble = require("../modules/mumble");

module.exports = function(io) {
  mumble(function(error, connection) {
    if( error ) { throw new Error( error ); }

    if(process.env.NODE_ENV == 'production')
      connection.authenticate( 'ontrac-bot2', 'regis' );

    connection.on( 'userState', function (state) {
      sessions[state.session] = state;
      online = [];
      for (var key in sessions) {
        if (sessions.hasOwnProperty(key)) {
          if(sessions[key].name.indexOf("ontrac") == -1)
            online.push( sessions[key].name );
        }
      }
    });

    router.get('/online', function(req, res) {
      res.json(online);
    });

  });
  return {router: router, models: []}
};
<|endoftext|>


<commit_before>var botao = document.querySelector('#mudaLayout');
var mural = document.querySelector('.mural');
var botoesRemove = document.querySelectorAll('.opcoesDoCartao-remove');
var formulario = document.querySelector('.novoCartao');

botao.addEventListener('click', mudaLayout);
botao.addEventListener('click', mudaLabelBotao);

function mudaLabelBotao(){
    if(mural.classList.contains('mural--linhas')){
        botao.textContent = 'Blocos';
    }else{
        botao.textContent = 'Linhas';
    }
}

function mudaLayout(){
    mural.classList.toggle('mural--linhas');
};

for(var i=0; i<botoesRemove.length;i++){
    var botaoRemove = botoesRemove[i];
    botaoRemove.addEventListener('click', function(){
        //this.parentNode.parentNode.remove();
        var botao = this;
        var idCartao = 'cartao_' + botao.dataset.cartao;

        var cartao = document.querySelector('#'+idCartao);
        cartao.classList.add('cartao--sumindo');
        setTimeout(function(){
            cartao.remove();
        },400);
    });
}

formulario.addEventListener('submit', salvaNovoCarta);

function salvaNovoCarta(evento){
    evento.preventDefault();
    var campoConteudo = document.querySelector('.novoCartao-conteudo');
    var digitado = campoConteudo.value;
    if(digitado.length>0){

        var mural = document.querySelector('.mural');
        //var campoConteudo = document.querySelector('[name=novoCartao-conteudo]');

        var conteudoNovoCartao= document.createElement('p');
        conteudoNovoCartao.textContent  = digitado;
        conteudoNovoCartao.classList.add('cartao-conteudo');

        var novoCartao = document.createElement('div');
        novoCartao.classList.add('cartao');

        novoCartao.appendChild(conteudoNovoCartao);
        mural.insertBefore(novoCartao, mural.firstElementChild);
        campoConteudo.value = '';
        campoConteudo.focus();
    }
}<commit_msg>acrescentou o botao excluir no cartão criado<commit_after>var botao = document.querySelector('#mudaLayout');
var mural = document.querySelector('.mural');
var botoesRemove = document.querySelectorAll('.opcoesDoCartao-remove');
var formulario = document.querySelector('.novoCartao');

botao.addEventListener('click', mudaLayout);
botao.addEventListener('click', mudaLabelBotao);

function mudaLabelBotao(){
    if(mural.classList.contains('mural--linhas')){
        botao.textContent = 'Blocos';
    }else{
        botao.textContent = 'Linhas';
    }
}

function mudaLayout(){
    mural.classList.toggle('mural--linhas');
};

$('.opcoesDoCartao-remove').click(removeCartao);

function removeCartao(){
        //this.parentNode.parentNode.remove();
        var botao = $(this);
        var idCartao = 'cartao_' + botao.data('cartao');

        var cartao = $('#'+idCartao).addClass('cartao--sumindo');
        setTimeout(function(){
            cartao.remove();
        },400);
    }

$('.novoCartao').submit(salvaNovoCarta);

 var numeroDeCartoes = $('.cartao').length;

function salvaNovoCarta(evento){
    evento.preventDefault();

    var campoConteudo = $('.novoCartao-conteudo');
    var digitado = campoConteudo.val();
    if(digitado){
     numeroDeCartoes++;
        var novoCartao = $('<div>').addClass('cartao').attr('id', 'cartao_'+(numeroDeCartoes+1)) ;

        var opcoesDoCartao = $('<div>').addClass('opcoesDoCartao').appendTo(novoCartao);

        $('<button>').addClass('opcoesDoCartao-opcao opcoesDoCartao-remove').text('Remove').appendTo(opcoesDoCartao).data('cartao',numeroDeCartoes+1).click(removeCartao);

        $('<p>').text(digitado).addClass('cartao-conteudo').appendTo(novoCartao);
        novoCartao.prependTo('.mural');
        campoConteudo.val('').focus();
    }
}<|endoftext|>


<commit_before>'use strict';

var path = process.cwd();
var ctrlPath = path + '/server/ctrl';

const UserController = require(ctrlPath + '/user-ctrl.server.js');
const BookController = require(ctrlPath + '/book-ctrl.server.js');
const TradeController = require(ctrlPath + '/trade-ctrl.server.js');
const debug = require('debug')('book-routes');

var _log = function(msg) {
    console.log('[LOG@SERVER]: ' + msg);
};

/* Function for debug logging requests.*/
var reqDebug = function(req) {
	_log('\t\tHeaders: ' + JSON.stringify(req.headers));
	_log('\t\tBody: ' + JSON.stringify(req.body));
	_log('\t\tParams: ' + JSON.stringify(req.params));
	_log('\t\tUrl:' + JSON.stringify(req.url));
	_log('\t\tText:' + JSON.stringify(req.text));
	_log('\t\tContent:' + JSON.stringify(req.content));
	_log('\t\tQuery:' + JSON.stringify(req.query));
};

var notAuthorized = {msg: 'Operation not authorized. Log in first.'};
var errorInternal = {msg: 'Server internal error.'};
var errorForbidden = {msg: 'Requested action forbidden.'};
var requestOk = {msg: 'Request was completed OK.'};

module.exports = function(app, passport) {

    /* Renders a pug template.*/
    var renderPug = function(req, res, pugFile) {
        var isAuth = req.isAuthenticated();
        res.render(path + '/pug/' + pugFile, {isAuth: isAuth});
    };

    /* loggedIn func from clementine.js. */
	var isLoggedIn = function(req, res, next) {
		if (req.isAuthenticated()) {
			return next();
		}
        else {
			return res.redirect('/login');
		}
	};

    /* Returns the username from the request. Logs an error if username is not
     * present. */
    var getUserName = function(req, route) {
        if (req.user) {
            if (req.user.username) {
                return req.user.username;
            }
            else {
                logError(route, 'getUserName: No req.user.username exists.',
                    req);
            }
        }
        else {
            logError(route, 'getUserName: No req.user exists.', req);
        }
        return null;
    };

    var logErrorReq = function(req) {
        console.error('Error REQ headers: ');
        reqDebug(req);
    };

    /* Logs an error with route and request information included.*/
    var logError = function(route, err, req) {
        var date = new Date();
        console.error(date + ' [ERROR@SERVER] route ' + route + ' | ' + err);
        if (req) {
            logErrorReq(req);
        }
    };

    // CONTROLLERS
    var userController = new UserController(path);
    var bookController = new BookController(path);
    var tradeController = new TradeController(path);

    //----------------------------------------------------------------------
    // ROUTES
    //----------------------------------------------------------------------

	app.route('/')
		.get((req, res) => {
            renderPug(req, res, 'index.pug');
		});

	app.route('/about')
		.get((req, res) => {
            renderPug(req, res, 'about.pug');
		});

	app.route('/allbooks')
		.get((req, res) => {
            renderPug(req, res, 'books.pug');
		});

	app.route('/signup')
		.get((req, res) => {
            renderPug(req, res, 'signup.pug');
		});

	app.route('/login')
		.get((req, res) => {
            renderPug(req, res, 'login.pug');
		});

	app.route('/loginFailed')
		.get((req, res) => {
            res.render(path + '/pug/login.pug',
                {isAuth: false, loginFailed: true});
        });

    // If a user logs out, return to main page
	app.route('/logout')
		.get((req, res) => {
			req.logout();
			res.redirect('/');
		});

	app.route('/profile')
		.get(isLoggedIn, (req, res) => {
            renderPug(req, res, 'profile.pug');
		});

    // Handle registration of user
    app.route('/forms/signup')
        .post((req, res) => {
            debug('Got a signup form GET request..');
            // reqDebug(req);
            userController.addLocalUser(req, res);
        });

    // Called by client to check their authentication status
	app.route('/amiauth')
		.get((req, res) => {
            var data = {isAuth: false};
            if (req.isAuthenticated()) {
                data.isAuth = true;
                data.username = req.user.username;
                userController.getUserID(data.username, (err, userID) => {
                    if (err) {
                        logError('/amiauth', err, req);
                        res.json({error: 'Failed to authenticate'});
                    }
                    else {
                        data.userID = userID;
                        res.json(data);
                    }
                });
            }
            else {
                res.json(data);
            }
		});

    //----------------------------------
    // Routes for manipulating user data
    //----------------------------------

    app.route('/user/:name')
        .get(isLoggedIn, (req, res) => {
            var username = req.params.name;
            if (username === req.user.username) {
                userController.getUserByName(username, (err, data) => {
                    if (err) {
                        logError('/user/' + username, err, req);
                        res.status(500).json(errorInternal);
                    }
                    else {
                        delete data.local.password;
                        res.json(data);
                    }
                });
            }
            else {
                // Forbidden
                logError('/user/' + username,
                    'Forbidden action attempted.', req);
                res.status(403).json(errorForbidden);
            }
        });

    //--------------------------------------
    // Routes for the book data
    //--------------------------------------
    app.route('/book')
        .get(isLoggedIn, (req, res) => {
            var username = req.user.username;
            bookController.getBooks(username, (err, data) => {
                if (err) {
                    logError('GET /book/', err, req);
                    res.status(500).json(errorInternal);
                }
                else {
                    res.status(200).json(data);
                }
            });
        })
        .post(isLoggedIn, (req, res) => {
            var username = req.body.username;
            var bookTitle = req.body.title;
            _log('Server got POST-req to /book. User: ' + username);
            if (username === req.user.username) {
                var bookData = {username: username, title: bookTitle};
                bookController.addBook(bookData, (err, bookData) => {
                    if (err) {
                        logError('POST /book/' + bookTitle, err, req);
                        res.status(500).json(errorInternal);
                    }
                    else {
                        console.log('bookData is ' + JSON.stringify(bookData));
                        res.status(200).json(bookData);
                    }
                });
            }
            else {
                res.status(403).json(notAuthorized);
            }
        })
        .delete(isLoggedIn, (req, res) => {
            if (req.body) {
                var bookData = req.body;
                var updateObj = {
                    username: req.user.username,
                    book: bookData
                };
                debug('Server got DELETE-req to /book. Data: '
                    + JSON.stringify(bookData));
                bookController.deleteBook(updateObj, (err) => {
                    if (err) {
                        logError('DELETE /book/' + bookData, err, req);
                        res.status(500).json(errorInternal);
                    }
                    else {
                        res.status(200).json({msg: 'OK'});
                    }
                });
            }
            else {
                res.status(400).json({msg: 'No proper body in DELETE'});
            }

        });

    //----------------------------------
    // Routes for Trade Requests
    //----------------------------------

    app.route('/tradereq/accept')
        .post(isLoggedIn, (req, res) => {
            var username = getUserName(req, '/tradereq/accept');
            console.log('accept user ' + username);
            res.status(500).json(errorInternal);

        });

    app.route('/tradereq/reject')
        .post(isLoggedIn, (req, res) => {
            var username = getUserName(req, 'tradereq/reject');
            console.log('reject user ' + username);
            res.status(500).json(errorInternal);

        });

    app.route('/tradereq')
        .post(isLoggedIn, (req, res) => {
            var username = getUserName(req, '/tradereq');
            tradeController.addTradeReq(username, req.body, err => {
                if (err) {
                    logError('POST /tradereq', err, req);
                    res.status(500).json(errorInternal);
                }
                else {
                    res.status(200).json(requestOk);
                }
            });
        })
        .delete(isLoggedIn, (req, res) => {
            var username = getUserName(req, '/tradereq');
            console.log('delete user ' + username);
            res.status(500).json(errorInternal);
        });

    //--------------------------------------
    // User registration and authentication
    //--------------------------------------

	app.route('/api/:id')
		.get((req, res) => {
            userController.getUser(req, res);
		});

    // Logs user in via form (after successful authentication
	app.route('/auth/userlogin')
        .post(passport.authenticate('local',
            { failureRedirect: '/loginFailed' }),
		(req, res) => {
			res.redirect('/');
		});

};
<commit_msg>Finalized delete-route for removing tradeReqs.<commit_after>'use strict';

var path = process.cwd();
var ctrlPath = path + '/server/ctrl';

const UserController = require(ctrlPath + '/user-ctrl.server.js');
const BookController = require(ctrlPath + '/book-ctrl.server.js');
const TradeController = require(ctrlPath + '/trade-ctrl.server.js');
const debug = require('debug')('book-routes');

var _log = function(msg) {
    console.log('[LOG@SERVER]: ' + msg);
};

/* Function for debug logging requests.*/
var reqDebug = function(req) {
	_log('\t\tHeaders: ' + JSON.stringify(req.headers));
	_log('\t\tBody: ' + JSON.stringify(req.body));
	_log('\t\tParams: ' + JSON.stringify(req.params));
	_log('\t\tUrl:' + JSON.stringify(req.url));
	_log('\t\tText:' + JSON.stringify(req.text));
	_log('\t\tContent:' + JSON.stringify(req.content));
	_log('\t\tQuery:' + JSON.stringify(req.query));
};

var notAuthorized = {msg: 'Operation not authorized. Log in first.'};
var errorInternal = {msg: 'Server internal error.'};
var errorForbidden = {msg: 'Requested action forbidden.'};
var requestOk = {msg: 'Request was completed OK.'};

module.exports = function(app, passport) {

    /* Renders a pug template.*/
    var renderPug = function(req, res, pugFile) {
        var isAuth = req.isAuthenticated();
        res.render(path + '/pug/' + pugFile, {isAuth: isAuth});
    };

    /* loggedIn func from clementine.js. */
	var isLoggedIn = function(req, res, next) {
		if (req.isAuthenticated()) {
			return next();
		}
        else {
			return res.redirect('/login');
		}
	};

    /* Returns the username from the request. Logs an error if username is not
     * present. */
    var getUserName = function(req, route) {
        if (req.user) {
            if (req.user.username) {
                return req.user.username;
            }
            else {
                logError(route, 'getUserName: No req.user.username exists.',
                    req);
            }
        }
        else {
            logError(route, 'getUserName: No req.user exists.', req);
        }
        return null;
    };

    var logErrorReq = function(req) {
        console.error('Error REQ headers: ');
        reqDebug(req);
    };

    /* Logs an error with route and request information included.*/
    var logError = function(route, err, req) {
        var date = new Date();
        console.error(date + ' [ERROR@SERVER] route ' + route + ' | ' + err);
        if (req) {
            logErrorReq(req);
        }
    };

    // CONTROLLERS
    var userController = new UserController(path);
    var bookController = new BookController(path);
    var tradeController = new TradeController(path);

    //----------------------------------------------------------------------
    // ROUTES
    //----------------------------------------------------------------------

	app.route('/')
		.get((req, res) => {
            renderPug(req, res, 'index.pug');
		});

	app.route('/about')
		.get((req, res) => {
            renderPug(req, res, 'about.pug');
		});

	app.route('/allbooks')
		.get((req, res) => {
            renderPug(req, res, 'books.pug');
		});

	app.route('/signup')
		.get((req, res) => {
            renderPug(req, res, 'signup.pug');
		});

	app.route('/login')
		.get((req, res) => {
            renderPug(req, res, 'login.pug');
		});

	app.route('/loginFailed')
		.get((req, res) => {
            res.render(path + '/pug/login.pug',
                {isAuth: false, loginFailed: true});
        });

    // If a user logs out, return to main page
	app.route('/logout')
		.get((req, res) => {
			req.logout();
			res.redirect('/');
		});

	app.route('/profile')
		.get(isLoggedIn, (req, res) => {
            renderPug(req, res, 'profile.pug');
		});

    // Handle registration of user
    app.route('/forms/signup')
        .post((req, res) => {
            debug('Got a signup form GET request..');
            // reqDebug(req);
            userController.addLocalUser(req, res);
        });

    // Called by client to check their authentication status
	app.route('/amiauth')
		.get((req, res) => {
            var data = {isAuth: false};
            if (req.isAuthenticated()) {
                data.isAuth = true;
                data.username = req.user.username;
                userController.getUserID(data.username, (err, userID) => {
                    if (err) {
                        logError('/amiauth', err, req);
                        res.json({error: 'Failed to authenticate'});
                    }
                    else {
                        data.userID = userID;
                        res.json(data);
                    }
                });
            }
            else {
                res.json(data);
            }
		});

    //----------------------------------
    // Routes for manipulating user data
    //----------------------------------

    app.route('/user/:name')
        .get(isLoggedIn, (req, res) => {
            var username = req.params.name;
            if (username === req.user.username) {
                userController.getUserByName(username, (err, data) => {
                    if (err) {
                        logError('/user/' + username, err, req);
                        res.status(500).json(errorInternal);
                    }
                    else {
                        delete data.local.password;
                        res.json(data);
                    }
                });
            }
            else {
                // Forbidden
                logError('/user/' + username,
                    'Forbidden action attempted.', req);
                res.status(403).json(errorForbidden);
            }
        });

    //--------------------------------------
    // Routes for the book data
    //--------------------------------------
    app.route('/book')
        .get(isLoggedIn, (req, res) => {
            var username = req.user.username;
            bookController.getBooks(username, (err, data) => {
                if (err) {
                    logError('GET /book/', err, req);
                    res.status(500).json(errorInternal);
                }
                else {
                    res.status(200).json(data);
                }
            });
        })
        .post(isLoggedIn, (req, res) => {
            var username = req.body.username;
            var bookTitle = req.body.title;
            _log('Server got POST-req to /book. User: ' + username);
            if (username === req.user.username) {
                var bookData = {username: username, title: bookTitle};
                bookController.addBook(bookData, (err, bookData) => {
                    if (err) {
                        logError('POST /book/' + bookTitle, err, req);
                        res.status(500).json(errorInternal);
                    }
                    else {
                        console.log('bookData is ' + JSON.stringify(bookData));
                        res.status(200).json(bookData);
                    }
                });
            }
            else {
                res.status(403).json(notAuthorized);
            }
        })
        .delete(isLoggedIn, (req, res) => {
            if (req.body) {
                var bookData = req.body;
                var updateObj = {
                    username: req.user.username,
                    book: bookData
                };
                debug('Server got DELETE-req to /book. Data: '
                    + JSON.stringify(bookData));
                bookController.deleteBook(updateObj, (err) => {
                    if (err) {
                        logError('DELETE /book/' + bookData, err, req);
                        res.status(500).json(errorInternal);
                    }
                    else {
                        res.status(200).json({msg: 'OK'});
                    }
                });
            }
            else {
                res.status(400).json({msg: 'No proper body in DELETE'});
            }

        });

    //----------------------------------
    // Routes for Trade Requests
    //----------------------------------

    app.route('/tradereq/accept')
        .post(isLoggedIn, (req, res) => {
            var username = getUserName(req, '/tradereq/accept');
            console.log('accept user ' + username);
            res.status(500).json(errorInternal);

        });

    app.route('/tradereq/reject')
        .post(isLoggedIn, (req, res) => {
            var username = getUserName(req, 'tradereq/reject');
            console.log('reject user ' + username);
            res.status(500).json(errorInternal);

        });

    app.route('/tradereq')
        .post(isLoggedIn, (req, res) => {
            var username = getUserName(req, '/tradereq');
            tradeController.addTradeReq(username, req.body, err => {
                if (err) {
                    logError('POST /tradereq', err, req);
                    res.status(500).json(errorInternal);
                }
                else {
                    res.status(200).json(requestOk);
                }
            });
        })
        .delete(isLoggedIn, (req, res) => {
            var username = getUserName(req, '/tradereq');
            console.log('delete user ' + username);
            tradeController.removeTradeReq(username, req.body, err => {
                if (err) {
                    logError('DELETE /tradereq', err, req);
                    res.status(500).json(errorInternal);
                }
                else {
                    res.status(200).json(requestOk);
                }
            });
        });

    //--------------------------------------
    // User registration and authentication
    //--------------------------------------

	app.route('/api/:id')
		.get((req, res) => {
            userController.getUser(req, res);
		});

    // Logs user in via form (after successful authentication
	app.route('/auth/userlogin')
        .post(passport.authenticate('local',
            { failureRedirect: '/loginFailed' }),
		(req, res) => {
			res.redirect('/');
		});

};
<|endoftext|>


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

  define([], function() {

    // promise() -> promise
    // constructs a representation of a value.
    // The value must be provided at later point in time.
    function makePromise() {
      var _resolved = false;
      var _value = undefined;

      return {
        value: value
        // put stuff here
      };

      function value(val) {
        if (!_resolved) {
          _value = val;
          _resolved = true;
          return;
        }
        throw new Error('already resolved');
      }
    }

    // fulfill(promise, value) -> ()
    // puts a value in the promise, allowing the
    // expressions that depend on the value
    // to be computed
    function fulfill(promise, value) {
      promise.value(value);
    }

    // depend(expression, promise) -> promise
    // defines a dependency between the expression
    // and the value of the promise.
    // It returns a new promise for the result
    // of the expression, so new expressions
    // can depend on that value.
    function depend(expression, promise) {

    }

    return {
      promise: makePromise,
      fulfill: fulfill,
      depend: depend
    };
  });

})();<commit_msg>just for the heck of it....<commit_after>(function() {
  'use strict';

  define([], function() {

    // promise() -> promise
    // constructs a representation of a value.
    // The value must be provided at later point in time.
    function makePromise() {
      var _resolved = false;
      var _value = undefined;

      return {
        value: value
        // put stuff here
      };

      function value(val) {
        if (!_resolved) {
          _value = val;
          _resolved = true;
          return;
        }
        throw new Error('already resolved');
      }
    }

    // fulfill(promise, value) -> ()
    // puts a value in the promise, allowing the
    // expressions that depend on the value
    // to be computed.
    function fulfill(promise, value) {
      promise.value(value);
    }

    // depend(expression, promise) -> promise
    // defines a dependency between the expression
    // and the value of the promise.
    // It returns a new promise for the result
    // of the expression, so new expressions
    // can depend on that value.
    function depend(expression, promise) {

    }

    return {
      promise: makePromise,
      fulfill: fulfill,
      depend: depend
    };
  });

})();<|endoftext|>


<commit_before>(function(mod) {
  if (typeof exports == "object" && typeof module == "object") // CommonJS
    mod(require("../../lib/codemirror"));
  else if (typeof define == "function" && define.amd) // AMD
    define(["../../lib/codemirror"], mod);
  else // Plain browser env
    mod(CodeMirror);
})(function(CodeMirror) {
  "use strict";

  CodeMirror.defineMode('coq', function(_config, parserConfig) {

    var vernacular = [
      'Add', 'All', 'Arguments', 'Axiom',
      'Bind',
      'Canonical', 'Check', 'Class', 'Close', 'Coercion', 'CoFixpoint',
      'CoInductive', 'Context', 'Contextual', 'Corollary',
      'Defined', 'Definition', 'Delimit',
      'Eval',
      'End', 'Example', 'Export',
      'Fact', 'Fixpoint', 'From',
      'Global', 'Goal', 'Graph',
      'Hint', 'Hypotheses', 'Hypothesis',
      'Implicit', 'Implicits', 'Import', 'Inductive', 'Infix', 'Instance',
      'Lemma', 'Let', 'Local', 'Ltac',
      'Module', 'Morphism',
      'Notation',
      'Open',
      'Parameter', 'Parameters', 'Prenex', 'Print', 'Printing', 'Program',
      'Projections', 'Proof',
      'Proposition',
      'Qed',
      'Record', 'Relation', 'Remark', 'Require', 'Reserved', 'Resolve', 'Rewrite',
      'Save', 'Scope', 'Search', 'Section', 'Set', 'Show', 'Strict', 'Structure',
      'Tactic', 'Theorem', 'Types',
      'Unset',
      'Variable', 'Variables', 'View'
    ];

    var gallina = [
      'as',
      'at',
      'cofix',
      'else', 'end',
      'False', 'fix', 'for', 'forall', 'fun',
      'if', 'in', 'is',
      'let',
      'match',
      'of',
      'Prop',
      'return',
      'struct',
      'then', 'True', 'Type',
      'when', 'with'
    ];

    var tactics = [
      'after', 'apply', 'assert', 'auto', 'autorewrite',
      'case', 'change', 'clear', 'compute', 'congruence', 'constructor',
      'cut', 'cutrewrite',
      'dependent', 'destruct',
      'eapply', 'eassumption', 'eauto', 'econstructor', 'elim', 'exists',
      'field', 'firstorder', 'fold', 'fourier',
      'generalize',
      'have', 'hnf',
      'induction', 'injection', 'intro', 'intros', 'inversion',
      'left',
      'move',
      'pattern', 'pose',
      'refine', 'remember', 'rename', 'replace', 'revert', 'rewrite',
      'right', 'ring',
      'set', 'simpl', 'specialize', 'split', 'subst', 'symmetry',
      'transitivity', 'trivial',
      'unfold', 'unlock', 'using'
    ];

    var terminators = [
      'assumption',
      'by',
      'contradiction',
      'discriminate',
      'exact',
      'now',
      'omega',
      'reflexivity',
      'tauto'
    ];

    var admitters = [
      'admit',
      'Admitted'
    ];

    var words = {};
    vernacular.map(function(word){words[word] = 'builtin';});
    gallina.map(function(word){words[word] = 'keyword';});
    tactics.map(function(word){words[word] = 'tactic';});
    terminators.map(function(word){words[word] = 'terminator';});
    admitters.map(function(word){words[word] = 'keyword';});

//        'let': 'keyword',
//        'print_endline': 'builtin',
//        'true': 'atom',

    function tokenBase(stream, state) {
      if(stream.sol()) {
        state.logicalsol = true; // logicalsol: only \s caracters seen from sol
      }
      if(stream.eol())
        state.logicalsol = false;

      if(stream.eatSpace())
        return null;

      var ch = stream.next();

      if(state.logicalsol) {
        if(/[\*\-\+]/.test(ch)) {
          state.logicalsol = false;
          return 'bullet';
        }
        if(/[\{\}]/.test(ch)) {
          state.logicalsol = false;
          return 'brace';
        }
        if(!(/\s/.test(ch)))
          state.logicalsol = false;
      }

      if(ch === '.') {
        state.tokenize = tokenStatementEnd;
        return state.tokenize(stream, state);
      }

      if (ch === '"') {
        state.tokenize = tokenString;
        return state.tokenize(stream, state);
      }

      if (ch === '(') {
        if (stream.eat('*')) {
          state.commentLevel++;
          state.tokenize = tokenComment;
          return state.tokenize(stream, state);
        }
      }

      if (ch === '~') {
        stream.eatWhile(/\w/);
        return 'variable-2';
      }

      if (ch === '`') {
        stream.eatWhile(/\w/);
        return 'quote';
      }

      if (/\d/.test(ch)) {
        stream.eatWhile(/[\d]/);
        /*
        if (stream.eat('.')) {
          stream.eatWhile(/[\d]/);
        }
        */
        return 'number';
      }

      if ( /[+\-*&%=<>!?|]/.test(ch)) {
        return 'operator';
      }

      if(/[\[\]]/.test(ch)) {
        return 'bracket';
      }

      stream.eatWhile(/\w/);
      var cur = stream.current();
      return words.hasOwnProperty(cur) ? words[cur] : 'variable';
    }

    function tokenString(stream, state) {
      var next, end = false, escaped = false;
      while ((next = stream.next()) !== null) {
        if (next === '"' && !escaped) {
          end = true;
          break;
        }
        escaped = !escaped && next === '\\';
      }
      if (end && !escaped) {
        state.tokenize = tokenBase;
      }
      return 'string';
    }

    function tokenComment(stream, state) {
      var prev, next;
      while(state.commentLevel > 0 && (next = stream.next()) !== null) {
        if (prev === '(' && next === '*') state.commentLevel++;
        if (prev === '*' && next === ')') state.commentLevel--;
        prev = next;
      }
      if (state.commentLevel <= 0) {
        state.tokenize = tokenBase;
      }
      return 'comment';
    }

    function tokenStatementEnd(stream, state) {
      state.tokenize = tokenBase;
      if(stream.eol() || stream.match(/\s/, false))
        return 'statementend';

    }

    return {
      startState: function() {
        return {tokenize: tokenBase, commentLevel: 0};
      },
      token: function(stream, state) {
        return state.tokenize(stream, state);
      },
      blockCommentStart: "(*",
      blockCommentEnd: "*)",
      lineComment: null
    };
  });

  CodeMirror.defineMIME('text/x-coq', {
    name: 'coq'
  });

});
<commit_msg>bugfix tokenComment<commit_after>(function(mod) {
  if (typeof exports == "object" && typeof module == "object") // CommonJS
    mod(require("../../lib/codemirror"));
  else if (typeof define == "function" && define.amd) // AMD
    define(["../../lib/codemirror"], mod);
  else // Plain browser env
    mod(CodeMirror);
})(function(CodeMirror) {
  "use strict";

  CodeMirror.defineMode('coq', function(_config, parserConfig) {

    var vernacular = [
      'Add', 'All', 'Arguments', 'Axiom',
      'Bind',
      'Canonical', 'Check', 'Class', 'Close', 'Coercion', 'CoFixpoint',
      'CoInductive', 'Context', 'Contextual', 'Corollary',
      'Defined', 'Definition', 'Delimit',
      'Eval',
      'End', 'Example', 'Export',
      'Fact', 'Fixpoint', 'From',
      'Global', 'Goal', 'Graph',
      'Hint', 'Hypotheses', 'Hypothesis',
      'Implicit', 'Implicits', 'Import', 'Inductive', 'Infix', 'Instance',
      'Lemma', 'Let', 'Local', 'Ltac',
      'Module', 'Morphism',
      'Notation',
      'Open',
      'Parameter', 'Parameters', 'Prenex', 'Print', 'Printing', 'Program',
      'Projections', 'Proof',
      'Proposition',
      'Qed',
      'Record', 'Relation', 'Remark', 'Require', 'Reserved', 'Resolve', 'Rewrite',
      'Save', 'Scope', 'Search', 'Section', 'Set', 'Show', 'Strict', 'Structure',
      'Tactic', 'Theorem', 'Types',
      'Unset',
      'Variable', 'Variables', 'View'
    ];

    var gallina = [
      'as',
      'at',
      'cofix',
      'else', 'end',
      'False', 'fix', 'for', 'forall', 'fun',
      'if', 'in', 'is',
      'let',
      'match',
      'of',
      'Prop',
      'return',
      'struct',
      'then', 'True', 'Type',
      'when', 'with'
    ];

    var tactics = [
      'after', 'apply', 'assert', 'auto', 'autorewrite',
      'case', 'change', 'clear', 'compute', 'congruence', 'constructor',
      'cut', 'cutrewrite',
      'dependent', 'destruct',
      'eapply', 'eassumption', 'eauto', 'econstructor', 'elim', 'exists',
      'field', 'firstorder', 'fold', 'fourier',
      'generalize',
      'have', 'hnf',
      'induction', 'injection', 'intro', 'intros', 'inversion',
      'left',
      'move',
      'pattern', 'pose',
      'refine', 'remember', 'rename', 'replace', 'revert', 'rewrite',
      'right', 'ring',
      'set', 'simpl', 'specialize', 'split', 'subst', 'symmetry',
      'transitivity', 'trivial',
      'unfold', 'unlock', 'using'
    ];

    var terminators = [
      'assumption',
      'by',
      'contradiction',
      'discriminate',
      'exact',
      'now',
      'omega',
      'reflexivity',
      'tauto'
    ];

    var admitters = [
      'admit',
      'Admitted'
    ];

    var words = {};
    vernacular.map(function(word){words[word] = 'builtin';});
    gallina.map(function(word){words[word] = 'keyword';});
    tactics.map(function(word){words[word] = 'tactic';});
    terminators.map(function(word){words[word] = 'terminator';});
    admitters.map(function(word){words[word] = 'keyword';});

//        'let': 'keyword',
//        'print_endline': 'builtin',
//        'true': 'atom',

    function tokenBase(stream, state) {
      if(stream.sol()) {
        state.logicalsol = true; // logicalsol: only \s caracters seen from sol
      }
      if(stream.eol())
        state.logicalsol = false;

      if(stream.eatSpace())
        return null;

      var ch = stream.next();

      if(state.logicalsol) {
        if(/[\*\-\+]/.test(ch)) {
          state.logicalsol = false;
          return 'bullet';
        }
        if(/[\{\}]/.test(ch)) {
          state.logicalsol = false;
          return 'brace';
        }
        if(!(/\s/.test(ch)))
          state.logicalsol = false;
      }

      if(ch === '.') {
        state.tokenize = tokenStatementEnd;
        return state.tokenize(stream, state);
      }

      if (ch === '"') {
        state.tokenize = tokenString;
        return state.tokenize(stream, state);
      }

      if (ch === '(') {
        if (stream.peek() === '*') {
          stream.next();
          state.commentLevel++;
          state.tokenize = tokenComment;
          return state.tokenize(stream, state);
        }
      }

      if (ch === '~') {
        stream.eatWhile(/\w/);
        return 'variable-2';
      }

      if (ch === '`') {
        stream.eatWhile(/\w/);
        return 'quote';
      }

      if (/\d/.test(ch)) {
        stream.eatWhile(/[\d]/);
        /*
        if (stream.eat('.')) {
          stream.eatWhile(/[\d]/);
        }
        */
        return 'number';
      }

      if ( /[+\-*&%=<>!?|]/.test(ch)) {
        return 'operator';
      }

      if(/[\[\]]/.test(ch)) {
        return 'bracket';
      }

      stream.eatWhile(/\w/);
      var cur = stream.current();
      return words.hasOwnProperty(cur) ? words[cur] : 'variable';
    }

    function tokenString(stream, state) {
      var next, end = false, escaped = false;
      while ((next = stream.next()) != null) {
        if (next === '"' && !escaped) {
          end = true;
          break;
        }
        escaped = !escaped && next === '\\';
      }
      if (end && !escaped) {
        state.tokenize = tokenBase;
      }
      return 'string';
    }

    function tokenComment(stream, state) {
      var ch;
      while(state.commentLevel && (ch = stream.next())) {
        if(ch === '(' && stream.peek() === '*') {
          stream.next();
          state.commentLevel++;
        }

        if(ch === '*' && stream.peek() === ')') {
          stream.next();
          state.commentLevel--;
        }
      }

      if(!state.commentLevel)
        state.tokenize = tokenBase;

      return 'comment';
    }

    function tokenStatementEnd(stream, state) {
      state.tokenize = tokenBase;
      if(stream.eol() || stream.match(/\s/, false))
        return 'statementend';
    }

    return {
      startState: function() {
        return {tokenize: tokenBase, commentLevel: 0};
      },
      token: function(stream, state) {
        return state.tokenize(stream, state);
      },
      blockCommentStart: "(*",
      blockCommentEnd: "*)",
      lineComment: null
    };
  });

  CodeMirror.defineMIME('text/x-coq', {
    name: 'coq'
  });

});
<|endoftext|>


<commit_before>// function showRecaptcha(element) {
//   Recaptcha.create('6LeObAUTAAAAAMtfwY22umX9YCTNoklUHp1wBj2I', element, {
//     theme: 'custom', // maybe pick another at https://developers.google.com/recaptcha/docs/customization
//     custom_theme_widget: 'recaptcha_widget'
//   });
// }

// function setupRecaptcha() {

$(document).ready(function(){
  var contactFormHost = 'http://localhost:5000/',
      $form = $('#contact-form'),
      notice = $form.find('#notice'),
      form_info = $form.serialize();

    $form.on('submit', function(event){
      event.preventDefault();

      $target = event.target

      console.log(form_info)
      console.log($target.serialize)

      $.ajax({
        type: 'POST',
        url: contactFormHost + 'send_email',
        data: $form.serialize(),
        dataType: 'json',
        success: function(response) {
          switch (response.message) {
            case 'success':
              $form.fadeOut(function() {
                $form.html('
' + $form.data('success') + '
').fadeIn();
              });
              break;

            case 'failure_captcha':
              showRecaptcha('recaptcha_widget');
              notice.text(notice.data('captcha-failed')).fadeIn();
              break;

            case 'failure_email':
              notice.text(notice.data('error')).fadeIn();
          }
        },
        error: function(xhr, ajaxOptions, thrownError) {
          notice.text(notice.data('error')).fadeIn();
        }
      });
    });
  })<commit_msg>Working on recaptcha<commit_after>function showRecaptcha(element) {
  Recaptcha.create('6LeObAUTAAAAAMtfwY22umX9YCTNoklUHp1wBj2I', element, {
    theme: 'custom', // maybe pick another at https://developers.google.com/recaptcha/docs/customization
    custom_theme_widget: 'recaptcha_widget'
  });
}

// function setupRecaptcha() {

$(document).ready(function(){
  var contactFormHost = 'http://localhost:5000/',
      $form = $('#contact-form'),
      notice = $form.find('#notice'),
      form_info = $form.serialize();

    $form.on('submit', function(event){
      event.preventDefault();

      $target = event.target

      console.log(form_info)
      console.log($target.serialize)

      $.ajax({
        type: 'POST',
        url: contactFormHost + 'send_email',
        data: $form.serialize(),
        dataType: 'json',
        success: function(response) {
          switch (response.message) {
            case 'success':
              $form.fadeOut(function() {
                $form.html('
' + $form.data('success') + '
').fadeIn();
              });
              break;

            case 'failure_captcha':
              showRecaptcha('recaptcha_widget');
              notice.text(notice.data('captcha-failed')).fadeIn();
              break;

            case 'failure_email':
              notice.text(notice.data('error')).fadeIn();
          }
        },
        error: function(xhr, ajaxOptions, thrownError) {
          notice.text(notice.data('error')).fadeIn();
        }
      });
    });
  })<|endoftext|>