<commit_before>'use strict';

const _ = require('lodash');
const colors = require('colors/safe');

const AppConfig = require('../models/app_configuration.js');
const Logger = require('../logger.js');

const { get: getApplication, getAllInstances } = require('@clevercloud/client/cjs/api/application.js');
const { sendToApi } = require('../models/send-to-api.js');

function displayGroupInfo (instances, commit) {
  return `(${displayFlavors(instances)},  Commit: ${commit || 'N/A'})`;
}

function displayFlavors (instances) {
  return _(instances)
    .groupBy((i) => i.flavor.name)
    .map((instances, flavorName) => `${instances.length}*${flavorName}`)
    .value()
    .join(', ');
}

function computeStatus (instances, app) {
  const upInstances = _.filter(instances, ({ state }) => state === 'UP');
  const isUp = !_.isEmpty(upInstances);
  const upCommit = _(upInstances).map('commit').head();

  const deployingInstances = _.filter(instances, ({ state }) => state === 'DEPLOYING');
  const isDeploying = !_.isEmpty(deployingInstances);
  const deployingCommit = _(deployingInstances).map('commit').head();

  const statusMessage = isUp
    ? `${colors.bold.green('running')} ${displayGroupInfo(upInstances, upCommit)}`
    : colors.bold.red('stopped');

  const statusLine = `${app.name}: ${statusMessage}`;
  const deploymentLine = isDeploying
    ? `Deployment in progress ${displayGroupInfo(deployingInstances, deployingCommit)}`
    : '';

  return [statusLine, deploymentLine].join('\n');
}

function displayScalability (app) {

  const { minFlavor, maxFlavor, minInstances, maxInstances } = app.instance;

  const vertical = (minFlavor.name === maxFlavor.name)
    ? minFlavor.name
    : `${minFlavor.name} to ${maxFlavor.name}`;

  const horizontal = (minInstances === maxInstances)
    ? minInstances
    : `${minInstances} to ${maxInstances}`;

  const enabled = (minFlavor.name !== maxFlavor.name)
    || (minInstances !== maxInstances);

  return `Scalability:
  Auto scalability: ${enabled ? colors.green('enabled') : colors.red('disabled')}
  Scalers: ${colors.bold(horizontal)}
  Sizes: ${colors.bold(vertical)}
  Decicated build: ${app.separateBuild ? colors.bold(app.buildFlavor.name) : colors.red('disabled')}`;
}

async function status (params) {
  const { alias } = params.options;
  const { ownerId, appId } = await AppConfig.getAppDetails({ alias });

  const instances = await getAllInstances({ id: ownerId, appId }).then(sendToApi);
  const app = await getApplication({ id: ownerId, appId }).then(sendToApi);

  Logger.println(computeStatus(instances, app));
  Logger.println(displayScalability(app));
}

module.exports = { status };
<commit_msg>Fix typo in `clever status` output<commit_after>'use strict';

const _ = require('lodash');
const colors = require('colors/safe');

const AppConfig = require('../models/app_configuration.js');
const Logger = require('../logger.js');

const { get: getApplication, getAllInstances } = require('@clevercloud/client/cjs/api/application.js');
const { sendToApi } = require('../models/send-to-api.js');

function displayGroupInfo (instances, commit) {
  return `(${displayFlavors(instances)},  Commit: ${commit || 'N/A'})`;
}

function displayFlavors (instances) {
  return _(instances)
    .groupBy((i) => i.flavor.name)
    .map((instances, flavorName) => `${instances.length}*${flavorName}`)
    .value()
    .join(', ');
}

function computeStatus (instances, app) {
  const upInstances = _.filter(instances, ({ state }) => state === 'UP');
  const isUp = !_.isEmpty(upInstances);
  const upCommit = _(upInstances).map('commit').head();

  const deployingInstances = _.filter(instances, ({ state }) => state === 'DEPLOYING');
  const isDeploying = !_.isEmpty(deployingInstances);
  const deployingCommit = _(deployingInstances).map('commit').head();

  const statusMessage = isUp
    ? `${colors.bold.green('running')} ${displayGroupInfo(upInstances, upCommit)}`
    : colors.bold.red('stopped');

  const statusLine = `${app.name}: ${statusMessage}`;
  const deploymentLine = isDeploying
    ? `Deployment in progress ${displayGroupInfo(deployingInstances, deployingCommit)}`
    : '';

  return [statusLine, deploymentLine].join('\n');
}

function displayScalability (app) {

  const { minFlavor, maxFlavor, minInstances, maxInstances } = app.instance;

  const vertical = (minFlavor.name === maxFlavor.name)
    ? minFlavor.name
    : `${minFlavor.name} to ${maxFlavor.name}`;

  const horizontal = (minInstances === maxInstances)
    ? minInstances
    : `${minInstances} to ${maxInstances}`;

  const enabled = (minFlavor.name !== maxFlavor.name)
    || (minInstances !== maxInstances);

  return `Scalability:
  Auto scalability: ${enabled ? colors.green('enabled') : colors.red('disabled')}
  Scalers: ${colors.bold(horizontal)}
  Sizes: ${colors.bold(vertical)}
  Dedicated build: ${app.separateBuild ? colors.bold(app.buildFlavor.name) : colors.red('disabled')}`;
}

async function status (params) {
  const { alias } = params.options;
  const { ownerId, appId } = await AppConfig.getAppDetails({ alias });

  const instances = await getAllInstances({ id: ownerId, appId }).then(sendToApi);
  const app = await getApplication({ id: ownerId, appId }).then(sendToApi);

  Logger.println(computeStatus(instances, app));
  Logger.println(displayScalability(app));
}

module.exports = { status };
<|endoftext|>


<commit_before>export const ADD_TODO = 'ADD_TODO';
export const TOGGLE_TODO = 'TOGGLE_TODO';

let nextId = 4;
export function addTodo(text) {
  console.log(text);
  return {
    type: ADD_TODO,
    id: nextId++,
    text: text
  }
}

export function toggleTodo(id) {
  return {
    type: TOGGLE_TODO,
    id: id
  }
}
<commit_msg>clean up<commit_after>export const ADD_TODO = 'ADD_TODO';
export const TOGGLE_TODO = 'TOGGLE_TODO';

let nextId = 4;
export function addTodo(text) {
  return {
    type: ADD_TODO,
    id: nextId++,
    text: text
  }
}

export function toggleTodo(id) {
  return {
    type: TOGGLE_TODO,
    id: id
  }
}
<|endoftext|>


<commit_before>import http from 'http';
import path from 'path';
import express from 'express';
import morgan from 'morgan';
import explore from './explore';
import home from './home';
import api from './api';
import compression from 'compression';
import kue from 'kue';
import { parse } from 'url';
import arenaPassport from  'arena-passport';
import bodyParser from 'body-parser';
import cookieParser from 'cookie-parser';
import session from 'cookie-session';
import CurrentUser from '../common/lib/current_user'

import config from '../config.js';

const { PORT, NODE_ENV, APP_URL, SECURE_ARENA_URL } = process.env;

const app = express();

import webpack from 'webpack';
import webpackHotMiddleware from 'webpack-hot-middleware';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackDevelopmentConfig from '../webpack.development.config';

const compiler = webpack(webpackDevelopmentConfig);

kue.Job.rangeByState( 'complete', 0, 10000, 'asc', function( err, jobs ) {
  jobs.forEach( function( job ) {
    job.remove( function(){
      console.log( 'removed job #', job.id );
    });
  });
});

if (NODE_ENV !== 'production') {
  app
    .use(webpackDevMiddleware(compiler, {
      noInfo: true,
      publicPath: webpackDevelopmentConfig.output.publicPath,
    }))
    .use(webpackHotMiddleware(compiler));
}

app
  // Other various middleware
  .use(bodyParser.urlencoded({ extended: true }))
  .use(bodyParser.json())
  .use(morgan('combined'))

app.keys = ['foo']

app
  // Auth
  .use(cookieParser())
  .use(session({
    secret: config.SESSION_SECRET,
    domain: config.COOKIE_DOMAIN,
    key: config.SESSION_COOKIE_KEY,
    maxage: config.SESSION_COOKIE_MAX_AGE,
  }))
  .use(arenaPassport({
    SECURE_ARENA_URL: SECURE_ARENA_URL || config.SECURE_ARENA_URL,
    APP_URL: APP_URL,
    CurrentUser: CurrentUser
  }))

  // Favicon
  .get('/favicon.ico', (req, res) => {
    res
      .status(200)
      .set({ 'Content-Type': 'image/x-icon' })
      .end();
  })

  // Ensure SSL
  .use((req, res, next) => {
    const protocol = req.get('X-Forwarded-Proto') || req.protocol;
    if(protocol !== 'https' && parse(APP_URL).protocol == 'https:'){
      url =
      res.redirect(301, APP_URL + req.url.replace("//", "/"))
    }else{
      next();
    }
  })

  // Apps
  .use(compression())
  .use(express.static(path.resolve(__dirname, '../public')))
  .use(explore)
  .use(home)
  .use(api);

const server = http.createServer(app);

server.listen(PORT, () => {
  console.log(`listening on ${PORT}`);
});
<commit_msg>Remove middleware<commit_after>import http from 'http';
import path from 'path';
import express from 'express';
import morgan from 'morgan';
import explore from './explore';
import home from './home';
import api from './api';
import compression from 'compression';
import kue from 'kue';
import { parse } from 'url';
import arenaPassport from  'arena-passport';
import bodyParser from 'body-parser';
import cookieParser from 'cookie-parser';
import session from 'cookie-session';
import CurrentUser from '../common/lib/current_user'

import config from '../config.js';

const { PORT, NODE_ENV, APP_URL, SECURE_ARENA_URL } = process.env;

const app = express();

import webpack from 'webpack';
import webpackHotMiddleware from 'webpack-hot-middleware';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackDevelopmentConfig from '../webpack.development.config';

const compiler = webpack(webpackDevelopmentConfig);

kue.Job.rangeByState( 'complete', 0, 10000, 'asc', function( err, jobs ) {
  jobs.forEach( function( job ) {
    job.remove( function(){
      console.log( 'removed job #', job.id );
    });
  });
});

if (NODE_ENV !== 'production') {
  app
    .use(webpackDevMiddleware(compiler, {
      noInfo: true,
      publicPath: webpackDevelopmentConfig.output.publicPath,
    }))
    .use(webpackHotMiddleware(compiler));
}

app
  // Other various middleware
  .use(bodyParser.urlencoded({ extended: true }))
  .use(bodyParser.json())
  .use(morgan('combined'))

app.keys = ['foo']

app
  // Auth
  .use(cookieParser())
  .use(session({
    secret: config.SESSION_SECRET,
    domain: config.COOKIE_DOMAIN,
    key: config.SESSION_COOKIE_KEY,
    maxage: config.SESSION_COOKIE_MAX_AGE,
  }))
  .use(arenaPassport({
    SECURE_ARENA_URL: SECURE_ARENA_URL || config.SECURE_ARENA_URL,
    APP_URL: APP_URL,
    CurrentUser: CurrentUser
  }))

  // Favicon
  .get('/favicon.ico', (req, res) => {
    res
      .status(200)
      .set({ 'Content-Type': 'image/x-icon' })
      .end();
  })

  // Apps
  .use(compression())
  .use(express.static(path.resolve(__dirname, '../public')))
  .use(explore)
  .use(home)
  .use(api);

const server = http.createServer(app);

server.listen(PORT, () => {
  console.log(`listening on ${PORT}`);
});
<|endoftext|>


<commit_before>const ps = require('geo-pixel-stream')
      fs = require('fs')
      program = require('commander')

function readGeoTiff(filePath) {
  return new Promise(function(resolve, reject) {
    let readers = ps.createReadStreams(filePath)
    let blocks = []

    console.log('File metadata :')
    console.log(readers[0].metadata)

    readers[0].on('data', function(data) {
      var blockPoints = [],
          blockLen = data.blockSize.x * data.blockSize.y

      for (let i=0; i<blockLen; i++)
        blockPoints.push(data.buffer[i])
      blocks.push(blockPoints)
    })

    readers[0].on('end', function() {
      resolve({ blocks: blocks, metadata: readers[0].metadata })
    })
  })
}

function linearize(blocks, block_width, blocks_per_row) {
  let points = []
  console.log('Found ' + blocks.length + ' blocks of ' + blocks[0].length + ' points')
  console.log('linearize...')

  for (let i=0; i<blocks.length * blocks[0].length; i++) {
    let col = i % (block_width * blocks_per_row), row = Math.floor(i / (block_width * blocks_per_row))
    let block = Math.floor(col / block_width) + Math.floor(row / block_width) * blocks_per_row

    let colInBlock = col % block_width
    let rowInBlock = row % block_width

    //console.log(row, col, block, colInBlock, rowInBlock)

    points[i] = blocks[block][colInBlock + rowInBlock * block_width]
  }

  console.log(points.length + ' points found.')
  return points
}

var gtiff2json = function(filePath) {
  return new Promise(function(resolve, reject) {
    readGeoTiff(filePath).then(function(data) {
      return linearize(data.blocks, data.metadata.blockSize.x, data.blocks.length / data.metadata.blockSize.x)
    })
    .then(function(points) {
      resolve(points)
    })
    .catch(function(err) {
      reject(err)
    })
  })
}

module.exports = gtiff2json

program
  .version(require('./package.json').version)
  .usage('<file> [options]')
  .option('-o, --output <file>', 'Output in a file instead of stdout')
  .parse(process.argv)

var inputFile = program.args[0]

gtiff2json(inputFile).then(function(points) {
  if (program.output) {
    fs.writeFile(program.output, JSON.stringify(points), function(err) {
      if (err) {
        console.error('Writing output file failed : ', err)
        return
      }
      console.log('Wrote ' + points.length + ' points into file.')
    })
  } else {
    console.log(points)
  }
})
.catch(function(err) {
  console.log(err)
})
<commit_msg>Added verbose mode and RLE compression<commit_after>const ps = require('geo-pixel-stream')
      fs = require('fs')
      program = require('commander')

function readGeoTiff(filePath) {
  return new Promise(function(resolve, reject) {
    let readers = ps.createReadStreams(filePath)
    let blocks = []

    if (program.verbose) {
      console.log('File metadata :')
      console.log(readers[0].metadata)
    }

    readers[0].on('data', function(data) {
      var blockPoints = [],
          blockLen = data.blockSize.x * data.blockSize.y

      for (let i=0; i<blockLen; i++)
        blockPoints.push(data.buffer[i])
      blocks.push(blockPoints)
    })

    readers[0].on('end', function() {
      resolve({ blocks: blocks, metadata: readers[0].metadata })
    })
  })
}

function linearize(blocks, block_width, blocks_per_row) {
  let points = []
  if (program.verbose) {
    console.log('Found ' + blocks.length + ' blocks of ' + blocks[0].length + ' points')
  }

  for (let i=0; i<blocks.length * blocks[0].length; i++) {
    let col = i % (block_width * blocks_per_row), row = Math.floor(i / (block_width * blocks_per_row))
    let block = Math.floor(col / block_width) + Math.floor(row / block_width) * blocks_per_row

    let colInBlock = col % block_width
    let rowInBlock = row % block_width

    //console.log(row, col, block, colInBlock, rowInBlock)

    points[i] = blocks[block][colInBlock + rowInBlock * block_width]
  }

  if (program.verbose) {
    console.log('Linearized ' + points.length + ' points.')
  }
  return points
}

function compress(points) {
  let output = []
  let currentValue = points[0], currentLen = 1

  for (let i=1, len = points.length; i<len; i++) {
    if (points[i] == currentValue) currentLen++
    else {
      output.push(currentValue)
      output.push(currentLen)

      currentValue = points[i]
      currentLen = 1
    }
  }

  if (program.verbose) {
    console.log('Compressed to ' + output.length + ' points.')
  }
  return output
}

var gtiff2json = function(filePath) {
  return new Promise(function(resolve, reject) {
    readGeoTiff(filePath).then(function(data) {
      return linearize(data.blocks, data.metadata.blockSize.x, Math.max(1, data.metadata.width / data.metadata.blockSize.x))
    })
    .then(function(points) {
      if (!program.compress) {
        resolve(points)
      } else {
        resolve(compress(points))
      }
    })
    .catch(function(err) {
      reject(err)
    })
  })
}

module.exports = gtiff2json

program
  .version(require('./package.json').version)
  .usage('<file> [options]')
  .option('-c, --compress', 'Output RLE compressed JSON')
  .option('-o, --output <file>', 'Output in a file instead of stdout')
  .option('-v, --verbose', 'Verbose mode for debug purpose')
  .parse(process.argv)

var inputFile = program.args[0]

gtiff2json(inputFile).then(function(points) {
  if (program.output) {
    fs.writeFile(program.output, JSON.stringify(points), function(err) {
      if (err) {
        console.error('Writing output file failed : ', err)
        return
      }
      if (program.verbose) {
        console.log('Wrote ' + points.length + ' points into file.')
      }
    })
  } else {
    console.log(points)
  }
})
.catch(function(err) {
  console.log(err)
})
<|endoftext|>


<commit_before>import { Vertex, distance } from './Geometry'
import { enforceRectLimits, enforcePolarLimits } from './LimitEnforcer'
import { getShape } from '../features/shapes/selectors'
import Victor from 'victor'

// Transform functions
function rotate(vertex, angleDeg) {
  var angle = Math.PI / 180.0 * angleDeg
  return Vertex(
           vertex.x * Math.cos(angle) - vertex.y * Math.sin(angle),
           vertex.x * Math.sin(angle) + vertex.y * Math.cos(angle),
           vertex.f)
}

function scale(vertex, scale_perc) {
  var scale = scale_perc / 100.0
  return {
    x: vertex.x * scale,
    y: vertex.y * scale,
    f: vertex.f,
  }
}

function offset(vertex, offsetX, offsetY) {
  return {
    x: vertex.x + offsetX,
    y: vertex.y + offsetY,
    f: vertex.f,
  }
}

function track(vertex, data, loop_index) {
  let angle = data.trackLength * loop_index / 16 * 2.0 * Math.PI
  let radius = 1.0
  if (data.trackGrowEnabled) {
    radius = 1.0 + loop_index / 10.0 * data.trackGrow / 100.0
  }
  return {
    x: vertex.x + radius * data.trackValue * Math.cos(angle),
    y: vertex.y + radius * data.trackValue * Math.sin(angle),
    f: vertex.f, // Why do I still have f in here?
  }
}

export const transform = (data, vertex, amount, trackIndex=0, numLoops) => {
  numLoops = numLoops || data.numLoops
  let transformedVertex = vertex

  if (data.repeatEnabled && data.growEnabled) {
    transformedVertex = scale(transformedVertex, 100.0 + (data.growValue * amount))
  }

  transformedVertex = offset(transformedVertex, data.offsetX || 0, data.offsetY || 0)

  if (data.repeatEnabled && data.spinEnabled) {
    const loopPeriod = numLoops / (parseInt(data.spinSwitchbacks) + 1)
    const stage = amount/loopPeriod
    const direction = (stage % 2 < 1 ? 1.0 : -1.0)
    var spinAmount = direction * (amount % loopPeriod) * data.spinValue

    // Add in the amount it goes positive to the negatives, so they start at the same place.
    if (direction < 0.0) {
      spinAmount += loopPeriod * data.spinValue
    }
    transformedVertex = rotate(transformedVertex, spinAmount)
  }

  if (data.repeatEnabled && data.trackEnabled) {
    transformedVertex = track(transformedVertex, data, trackIndex)
  }

  return transformedVertex
}

// Vertex functions
const getShapeVertices = (state) => {
  const shape = getShape(state.shape)
  return shape.getVertices(state).map(vertex => {
    return scale(vertex, 100.0 * state.shape.startingSize)
  })
}

function addRectEndpoints(machine, vertices) {
  // OK, let's assign corners indices:
  //
  // [1]   [2]
  //
  //
  // [0]   [3]
  const dx = (machine.maxX - machine.minX) / 2.0
  const dy = (machine.maxY - machine.minY) / 2.0
  const corners = [
    {x: -dx, y: -dy},
    {x: -dx, y:  dy},
    {x:  dx, y:  dy},
    {x:  dx, y: -dy}
  ]

  let first = vertices[0]
  let last = vertices[vertices.length-1]
  let maxRadius = Math.sqrt(Math.pow(2.0*dx,2.0) + Math.pow(2.0*dy, 2.0)) / 2.0
  let vFirst = Victor.fromObject(first)
  let vLast = Victor.fromObject(last)
  let outPoint
  let newVertices = []

  if (vFirst.magnitude() <= vLast.magnitude()) {
    // It's going outward
    let scale = maxRadius / vLast.magnitude()
    outPoint = vLast.multiply(Victor(scale,scale))
    newVertices.push({ ...last, x: outPoint.x, y: outPoint.y})
  } else {
    let scale = maxRadius / vFirst.magnitude()
    outPoint = vFirst.multiply(Victor(scale,scale))
    newVertices.push({ ...first, x: outPoint.x, y: outPoint.y})
  }

  let nextCorner = 1
  if (outPoint.x >= dx) {
    // right
    nextCorner = 2
  } else if (outPoint.x <= -dx) {
    // left
    nextCorner = 0
  } else if (outPoint.y >= dy) {
    // up
    nextCorner = 1
  } else if (outPoint.y <= -dy) {
    // down
    nextCorner = 3
  } else {
    console.log("Darn!")
    nextCorner = 3
  }

  while (nextCorner !== machine.rectOrigin[0]) {
    newVertices.push({ ...first, x: corners[nextCorner].x, y: corners[nextCorner].y})
    nextCorner -= 1
    if (nextCorner < 0) {
      nextCorner = 3
    }
  }

  newVertices.push({ ...first, x: corners[nextCorner].x, y: corners[nextCorner].y})

  if (vFirst.magnitude() <= vLast.magnitude()) {
    // outward
    vertices = vertices.concat(newVertices)
  } else {
    vertices = newVertices.reverse().concat(vertices)
  }

  return vertices
}

function addPolarEndpoints(machine, vertices) {
  const maxRadius = machine.maxRadius

  if (machine.polarStartPoint !== 'none') {
    if (machine.polarStartPoint === 'center') {
      vertices.unshift(Vertex(0.0, 0.0))
    } else {
      const first = Victor.fromObject(vertices[0])
      const scale = maxRadius / first.magnitude()
      const startPoint = first.multiply(Victor(scale, scale))
      vertices.unshift(Vertex(startPoint.x, startPoint.y))
    }
  }

  if (machine.polarEndPoint !== 'none') {
    if (machine.polarEndPoint === 'center') {
      vertices.push(Vertex(0.0, 0.0))
    } else {
      const last = Victor.fromObject(vertices[vertices.length-1])
      const scale = maxRadius / last.magnitude()
      const endPoint = last.multiply(Victor(scale, scale))
      vertices.push(Vertex(endPoint.x, endPoint.y))
    }
  }

  return vertices
}

function buildTrackLoop(state, i, t) {
  const input = getShapeVertices(state)
  const numTrackLoops = state.transform.repeatEnabled ? state.transform.trackNumLoops : 1
  const nextTrackVertex = transform(state.transform, input[0], 0, i + 1, numTrackLoops)
  const backtrack = numTrackLoops > 1 && t === numTrackLoops - 1
  let numVertices = input.length
  let trackVertices = []
  let trackDistances = []

  for (var j=0; j<numVertices; j++) {
    const amount = state.transform.transformFrequency === 'point' ? i + t + j/input.length : i + t
    const trackVertex = transform(state.transform, input[j], amount, i, numTrackLoops)
    trackVertices.push(trackVertex)

    if (backtrack) {
      trackDistances.push(distance(nextTrackVertex, trackVertex))
    }
  }

  // backtrack to the vertex with the shortest distance to the first vertex in
  // the next track loop; this minimizes the amount our shape draws over the
  // previous shape, which is not visually appealing.
  if (backtrack) {
    let minIdx = 0
    let minD = Number.MAX_SAFE_INTEGER

    trackDistances.forEach((d, idx) => {
      if (d <= minD) {
        minD = d
        minIdx = idx
      }
    })

    if (minIdx !== 0) {
      trackVertices = trackVertices.concat(trackVertices.slice(minIdx, trackVertices.length-1).reverse())
    }
  }

  return trackVertices
}

// ensure vertices do not exceed machine boundary limits, and endpoints as needed
export const polishVertices = (state, vertices) => {
  const machine = state.machine

  if (vertices.length > 0) {
    if (machine.rectangular) {
      if (machine.rectOrigin.length === 1) {
        vertices = addRectEndpoints(machine, vertices)
      }

      const sizeX = (machine.maxX - machine.minX)/2.0
      const sizeY = (machine.maxY - machine.minY)/2.0
      vertices = enforceRectLimits(vertices, sizeX, sizeY)
    } else {
      vertices = addPolarEndpoints(machine, vertices)
      vertices = enforcePolarLimits(vertices, machine.maxRadius)
    }
  }

  if (state.gcode.reverse) {
    vertices.reverse()
  }

  return vertices
}

export const thetaRho = (state) => {
  let machine = state.machine
  var x_scale = (machine.maxX - machine.minX)/2.0 * 0.01 * state.file.zoom
  var y_scale = (machine.maxY - machine.minY)/2.0 * 0.01 * state.file.zoom
  if (!machine.rectangular) {
    x_scale = y_scale = machine.maxRadius
  }
  x_scale *= 0.01 * state.file.zoom
  y_scale *= 0.01 * state.file.zoom
  if (state.file.aspectRatio) {
    x_scale = y_scale = Math.min(x_scale,y_scale)
  }

  const newVertices = state.file.vertices.map( (vertex) => {
    return {...vertex,
      x: vertex.x * x_scale,
      y: vertex.y * y_scale,
    }
  })
  return polishVertices(state, newVertices)
}

export const transformShapes = (state) => {
  const input = getShapeVertices(state)
  const numLoops = state.transform.repeatEnabled ? state.transform.numLoops : 1
  const numTrackLoops = state.transform.repeatEnabled ? state.transform.trackNumLoops : 1
  let outputVertices = []

  for (var i=0; i<numLoops; i++) {
    if (numTrackLoops > 1) {
      for (var t=0; t<numTrackLoops; t++) {
        outputVertices = outputVertices.concat(buildTrackLoop(state, i, t))
      }
    } else {
      for (i=0; i<numLoops; i++) {
        for (var j=0; j<input.length; j++) {
          let amount = state.transform.transformFrequency === 'point' ? i + j/input.length : i
          outputVertices.push(transform(state.transform, input[j], amount, amount))
        }
      }
    }
  }

  return polishVertices(state, outputVertices)
}
<commit_msg>don't draw track loop unless track is enabled<commit_after>import { Vertex, distance } from './Geometry'
import { enforceRectLimits, enforcePolarLimits } from './LimitEnforcer'
import { getShape } from '../features/shapes/selectors'
import Victor from 'victor'

// Transform functions
function rotate(vertex, angleDeg) {
  var angle = Math.PI / 180.0 * angleDeg
  return Vertex(
           vertex.x * Math.cos(angle) - vertex.y * Math.sin(angle),
           vertex.x * Math.sin(angle) + vertex.y * Math.cos(angle),
           vertex.f)
}

function scale(vertex, scale_perc) {
  var scale = scale_perc / 100.0
  return {
    x: vertex.x * scale,
    y: vertex.y * scale,
    f: vertex.f,
  }
}

function offset(vertex, offsetX, offsetY) {
  return {
    x: vertex.x + offsetX,
    y: vertex.y + offsetY,
    f: vertex.f,
  }
}

function track(vertex, data, loop_index) {
  let angle = data.trackLength * loop_index / 16 * 2.0 * Math.PI
  let radius = 1.0
  if (data.trackGrowEnabled) {
    radius = 1.0 + loop_index / 10.0 * data.trackGrow / 100.0
  }
  return {
    x: vertex.x + radius * data.trackValue * Math.cos(angle),
    y: vertex.y + radius * data.trackValue * Math.sin(angle),
    f: vertex.f, // Why do I still have f in here?
  }
}

export const transform = (data, vertex, amount, trackIndex=0, numLoops) => {
  numLoops = numLoops || data.numLoops
  let transformedVertex = vertex

  if (data.repeatEnabled && data.growEnabled) {
    transformedVertex = scale(transformedVertex, 100.0 + (data.growValue * amount))
  }

  transformedVertex = offset(transformedVertex, data.offsetX || 0, data.offsetY || 0)

  if (data.repeatEnabled && data.spinEnabled) {
    const loopPeriod = numLoops / (parseInt(data.spinSwitchbacks) + 1)
    const stage = amount/loopPeriod
    const direction = (stage % 2 < 1 ? 1.0 : -1.0)
    var spinAmount = direction * (amount % loopPeriod) * data.spinValue

    // Add in the amount it goes positive to the negatives, so they start at the same place.
    if (direction < 0.0) {
      spinAmount += loopPeriod * data.spinValue
    }
    transformedVertex = rotate(transformedVertex, spinAmount)
  }

  if (data.repeatEnabled && data.trackEnabled) {
    transformedVertex = track(transformedVertex, data, trackIndex)
  }

  return transformedVertex
}

// Vertex functions
const getShapeVertices = (state) => {
  const shape = getShape(state.shape)
  return shape.getVertices(state).map(vertex => {
    return scale(vertex, 100.0 * state.shape.startingSize)
  })
}

function addRectEndpoints(machine, vertices) {
  // OK, let's assign corners indices:
  //
  // [1]   [2]
  //
  //
  // [0]   [3]
  const dx = (machine.maxX - machine.minX) / 2.0
  const dy = (machine.maxY - machine.minY) / 2.0
  const corners = [
    {x: -dx, y: -dy},
    {x: -dx, y:  dy},
    {x:  dx, y:  dy},
    {x:  dx, y: -dy}
  ]

  let first = vertices[0]
  let last = vertices[vertices.length-1]
  let maxRadius = Math.sqrt(Math.pow(2.0*dx,2.0) + Math.pow(2.0*dy, 2.0)) / 2.0
  let vFirst = Victor.fromObject(first)
  let vLast = Victor.fromObject(last)
  let outPoint
  let newVertices = []

  if (vFirst.magnitude() <= vLast.magnitude()) {
    // It's going outward
    let scale = maxRadius / vLast.magnitude()
    outPoint = vLast.multiply(Victor(scale,scale))
    newVertices.push({ ...last, x: outPoint.x, y: outPoint.y})
  } else {
    let scale = maxRadius / vFirst.magnitude()
    outPoint = vFirst.multiply(Victor(scale,scale))
    newVertices.push({ ...first, x: outPoint.x, y: outPoint.y})
  }

  let nextCorner = 1
  if (outPoint.x >= dx) {
    // right
    nextCorner = 2
  } else if (outPoint.x <= -dx) {
    // left
    nextCorner = 0
  } else if (outPoint.y >= dy) {
    // up
    nextCorner = 1
  } else if (outPoint.y <= -dy) {
    // down
    nextCorner = 3
  } else {
    console.log("Darn!")
    nextCorner = 3
  }

  while (nextCorner !== machine.rectOrigin[0]) {
    newVertices.push({ ...first, x: corners[nextCorner].x, y: corners[nextCorner].y})
    nextCorner -= 1
    if (nextCorner < 0) {
      nextCorner = 3
    }
  }

  newVertices.push({ ...first, x: corners[nextCorner].x, y: corners[nextCorner].y})

  if (vFirst.magnitude() <= vLast.magnitude()) {
    // outward
    vertices = vertices.concat(newVertices)
  } else {
    vertices = newVertices.reverse().concat(vertices)
  }

  return vertices
}

function addPolarEndpoints(machine, vertices) {
  const maxRadius = machine.maxRadius

  if (machine.polarStartPoint !== 'none') {
    if (machine.polarStartPoint === 'center') {
      vertices.unshift(Vertex(0.0, 0.0))
    } else {
      const first = Victor.fromObject(vertices[0])
      const scale = maxRadius / first.magnitude()
      const startPoint = first.multiply(Victor(scale, scale))
      vertices.unshift(Vertex(startPoint.x, startPoint.y))
    }
  }

  if (machine.polarEndPoint !== 'none') {
    if (machine.polarEndPoint === 'center') {
      vertices.push(Vertex(0.0, 0.0))
    } else {
      const last = Victor.fromObject(vertices[vertices.length-1])
      const scale = maxRadius / last.magnitude()
      const endPoint = last.multiply(Victor(scale, scale))
      vertices.push(Vertex(endPoint.x, endPoint.y))
    }
  }

  return vertices
}

function buildTrackLoop(state, i, t) {
  const input = getShapeVertices(state)
  const numTrackLoops = state.transform.repeatEnabled ? state.transform.trackNumLoops : 1
  const nextTrackVertex = transform(state.transform, input[0], 0, i + 1, numTrackLoops)
  const backtrack = numTrackLoops > 1 && t === numTrackLoops - 1
  let numVertices = input.length
  let trackVertices = []
  let trackDistances = []

  for (var j=0; j<numVertices; j++) {
    const amount = state.transform.transformFrequency === 'point' ? i + t + j/input.length : i + t
    const trackVertex = transform(state.transform, input[j], amount, i, numTrackLoops)
    trackVertices.push(trackVertex)

    if (backtrack) {
      trackDistances.push(distance(nextTrackVertex, trackVertex))
    }
  }

  // backtrack to the vertex with the shortest distance to the first vertex in
  // the next track loop; this minimizes the amount our shape draws over the
  // previous shape, which is not visually appealing.
  if (backtrack) {
    let minIdx = 0
    let minD = Number.MAX_SAFE_INTEGER

    trackDistances.forEach((d, idx) => {
      if (d <= minD) {
        minD = d
        minIdx = idx
      }
    })

    if (minIdx !== 0) {
      trackVertices = trackVertices.concat(trackVertices.slice(minIdx, trackVertices.length-1).reverse())
    }
  }

  return trackVertices
}

// ensure vertices do not exceed machine boundary limits, and endpoints as needed
export const polishVertices = (state, vertices) => {
  const machine = state.machine

  if (vertices.length > 0) {
    if (machine.rectangular) {
      if (machine.rectOrigin.length === 1) {
        vertices = addRectEndpoints(machine, vertices)
      }

      const sizeX = (machine.maxX - machine.minX)/2.0
      const sizeY = (machine.maxY - machine.minY)/2.0
      vertices = enforceRectLimits(vertices, sizeX, sizeY)
    } else {
      vertices = addPolarEndpoints(machine, vertices)
      vertices = enforcePolarLimits(vertices, machine.maxRadius)
    }
  }

  if (state.gcode.reverse) {
    vertices.reverse()
  }

  return vertices
}

export const thetaRho = (state) => {
  let machine = state.machine
  var x_scale = (machine.maxX - machine.minX)/2.0 * 0.01 * state.file.zoom
  var y_scale = (machine.maxY - machine.minY)/2.0 * 0.01 * state.file.zoom
  if (!machine.rectangular) {
    x_scale = y_scale = machine.maxRadius
  }
  x_scale *= 0.01 * state.file.zoom
  y_scale *= 0.01 * state.file.zoom
  if (state.file.aspectRatio) {
    x_scale = y_scale = Math.min(x_scale,y_scale)
  }

  const newVertices = state.file.vertices.map( (vertex) => {
    return {...vertex,
      x: vertex.x * x_scale,
      y: vertex.y * y_scale,
    }
  })
  return polishVertices(state, newVertices)
}

export const transformShapes = (state) => {
  const input = getShapeVertices(state)
  const numLoops = state.transform.repeatEnabled ? state.transform.numLoops : 1
  const numTrackLoops = state.transform.repeatEnabled ? state.transform.trackNumLoops : 1
  let outputVertices = []

  for (var i=0; i<numLoops; i++) {
    if (state.transform.trackEnabled && numTrackLoops > 1) {
      for (var t=0; t<numTrackLoops; t++) {
        outputVertices = outputVertices.concat(buildTrackLoop(state, i, t))
      }
    } else {
      for (i=0; i<numLoops; i++) {
        for (var j=0; j<input.length; j++) {
          let amount = state.transform.transformFrequency === 'point' ? i + j/input.length : i
          outputVertices.push(transform(state.transform, input[j], amount, amount))
        }
      }
    }
  }

  return polishVertices(state, outputVertices)
}
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015-present, Joshua Hollenbeck
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree.
 */
const RefraxSchema = require('RefraxSchema');
const RefraxConfig = require('RefraxConfig');
const RefraxTools = require('RefraxTools');
const RefraxResource = require('RefraxResource');
const RefraxMutableResource = require('RefraxMutableResource');
const createAction = require('createAction');
const createSchemaCollection = require('createSchemaCollection');
const createSchemaResource = require('createSchemaResource');
const createSchemaNamespace = require('createSchemaNamespace');
const processResponse = require('processResponse');
const RefraxStore = require('RefraxStore');

export default {
  Config: RefraxConfig,
  MutableResource: RefraxMutableResource,
  Resource: RefraxResource,
  Schema: RefraxSchema,
  Store: RefraxStore,
  Tools: RefraxTools,
  createAction,
  createSchemaCollection,
  createSchemaNamespace,
  createSchemaResource,
  processResponse
};
<commit_msg>Expose Parameters/Options classes<commit_after>/**
 * Copyright (c) 2015-present, Joshua Hollenbeck
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree.
 */
const RefraxSchema = require('RefraxSchema');
const RefraxConfig = require('RefraxConfig');
const RefraxTools = require('RefraxTools');
const RefraxResource = require('RefraxResource');
const RefraxMutableResource = require('RefraxMutableResource');
const RefraxParameters = require('RefraxParameters');
const RefraxOptions = require('RefraxOptions');
const createAction = require('createAction');
const createSchemaCollection = require('createSchemaCollection');
const createSchemaResource = require('createSchemaResource');
const createSchemaNamespace = require('createSchemaNamespace');
const processResponse = require('processResponse');
const RefraxStore = require('RefraxStore');

export default {
  Config: RefraxConfig,
  MutableResource: RefraxMutableResource,
  Resource: RefraxResource,
  Schema: RefraxSchema,
  Store: RefraxStore,
  Tools: RefraxTools,
  Parameters: RefraxParameters,
  Options: RefraxOptions,
  createAction,
  createSchemaCollection,
  createSchemaNamespace,
  createSchemaResource,
  processResponse
};
<|endoftext|>


<commit_before>var app = require('express')();
var server = require('http').Server(app);
var fetch = require('node-fetch');
var io = require('socket.io')(server, { path: '/sockets'});
var dbip = process.env.DBIP || 'localhost';
var dbport = process.env.DBPORT || 5000;
var url = 'http://' + dbip + ':' + dbport + '/';

var fetchOptions = require('./helpers').fetchOptions;

app.get('/', (req, res) => {res.end()});

function handleErrors(response) {
    console.log('handleErrors', response);
    if (!response.ok) {
        console.log('status', response.statusText);
        throw Error(response.statusText);
    }
    return response;
}

var nsp = io.of('/ngage');
nsp.on('connection', function (socket) {
  socket.on('subscribe', data => {
    socket.join(data.room);
    var options = fetchOptions('POST', data);
    fetch(url + 'pa', options)
      .then(res => {nsp.in(data.room).emit('addparticipant')})
      .catch(e => { socket.emit('participantSubmit', 'Server is unavailable'); });
    // socket.emit('join');
  });

  socket.on('unsubscribe', function(data) { socket.leave(data.room); })

  socket.on('start', function (data) {
    nsp.in(data.room).emit('start', '');

    fetch(url + 'qByS/' + data.room)
      .then(res => res.json())
      .then(questions => { nsp.in(data.room).emit('questions', questions); })
      .catch (e => { socket.emit('questions', 'Server is unavailable'); });
  });

  socket.on('askQ', function (data) {
    fetch(url + 'aByQ/' + data.question.questionID)
      .then(handleErrors)
      .then(res => res.json())
      .then(answers => { nsp.in(data.room).emit('answers', {answers: answers, question: data.question}); })
      .catch(e => { socket.emit('answers', 'Server is unavailable'); })
  });

  socket.on('showA', function(data) {
    fetch(url + 'aByCorrect/' + data.questionID)
    .then(handleErrors)
    .then(res => res.json())
    .then(correct => {nsp.in(data.room).emit('correct', {
      correct: correct
    })})
    .catch(e => {socket.emit('correct', 'Server is unavailable to get correct answer')})
  });

  socket.on('submitResponse', data => {
    nsp.in(data.room).emit('resp', data);
    var options = fetchOptions('POST', data);

    fetch(url + 'r', options)
      .catch(e => { socket.emit('responseSubmit', 'Server is unavailable'); });
  });

  socket.on('submitAudQuestion', data => {

    var options = fetchOptions('POST', data);
    fetch(url + 'aqByS/', options)
      .then(handleErrors)
      .then(res => res.json())
      .then(audQuestion => { nsp.in(data.room).emit('audquestions', audQuestion); })
      .catch(err => { socket.emit('audQuestionSubmit', 'Server is unavailable'); });
  });

  socket.on('upvoteAudQuestion', data => {
    nsp.in(data.room).emit('upvote', data.audQuestionID);
    var options = fetchOptions('PUT', data);

    fetch(url + 'aq/' + data.audQuestionID, options)
      .catch(err => { socket.emit('audQuestionUpvote', 'Server is unavailable'); });
  });

  socket.on('enableAsk', data => {
    // for the actual rooms
    nsp.in(data.room).emit('askenabled', data.askEnabled);

    // TODO: need to add fetch put request here
    // for the tests --> (can probably change since we
    // are now going to use a database call
    if (!data.room) {
      socket.emit('askenabled', data.askEnabled);
    }

  });

  socket.on('enableAudQ', data => {
    // for the actual rooms
    nsp.in(data.room).emit('audqenabled', data.audQEnabled);

    // TODO: need to add fetch put request here
    // for the tests --> (can probably change since we
    // are now going to use a database call
    if (!data.room) {
      socket.emit('audqenabled', data.audQEnabled);
    }

  });

});

module.exports = server;
<commit_msg>(feat) Add db requests for audience participation<commit_after>var app = require('express')();
var server = require('http').Server(app);
var fetch = require('node-fetch');
var io = require('socket.io')(server, { path: '/sockets'});
var dbip = process.env.DBIP || 'localhost';
var dbport = process.env.DBPORT || 5000;
var url = 'http://' + dbip + ':' + dbport + '/';

var fetchOptions = require('./helpers').fetchOptions;

app.get('/', (req, res) => {res.end()});

function handleErrors(response) {
    console.log('handleErrors', response);
    if (!response.ok) {
        console.log('status', response.statusText);
        throw Error(response.statusText);
    }
    return response;
}

var nsp = io.of('/ngage');
nsp.on('connection', function (socket) {
  socket.on('subscribe', data => {
    socket.join(data.room);
    var options = fetchOptions('POST', data);
    fetch(url + 'pa', options)
      .then(res => {nsp.in(data.room).emit('addparticipant')})
      .catch(e => { socket.emit('participantSubmit', 'Server is unavailable'); });
    // socket.emit('join');
  });

  socket.on('unsubscribe', function(data) { socket.leave(data.room); })

  socket.on('start', function (data) {
    nsp.in(data.room).emit('start', '');

    fetch(url + 'qByS/' + data.room)
      .then(res => res.json())
      .then(questions => { nsp.in(data.room).emit('questions', questions); })
      .catch (e => { socket.emit('questions', 'Server is unavailable'); });
  });

  socket.on('askQ', function (data) {
    fetch(url + 'aByQ/' + data.question.questionID)
      .then(handleErrors)
      .then(res => res.json())
      .then(answers => { nsp.in(data.room).emit('answers', {answers: answers, question: data.question}); })
      .catch(e => { socket.emit('answers', 'Server is unavailable'); })
  });

  socket.on('showA', function(data) {
    fetch(url + 'aByCorrect/' + data.questionID)
    .then(handleErrors)
    .then(res => res.json())
    .then(correct => {nsp.in(data.room).emit('correct', {
      correct: correct
    })})
    .catch(e => {socket.emit('correct', 'Server is unavailable to get correct answer')})
  });

  socket.on('submitResponse', data => {
    nsp.in(data.room).emit('resp', data);
    var options = fetchOptions('POST', data);

    fetch(url + 'r', options)
      .catch(e => { socket.emit('responseSubmit', 'Server is unavailable'); });
  });

  socket.on('submitAudQuestion', data => {

    var options = fetchOptions('POST', data);
    fetch(url + 'aqByS/', options)
      .then(handleErrors)
      .then(res => res.json())
      .then(audQuestion => { nsp.in(data.room).emit('audquestions', audQuestion); })
      .catch(err => { socket.emit('audQuestionSubmit', 'Server is unavailable'); });
  });

  socket.on('upvoteAudQuestion', data => {
    nsp.in(data.room).emit('upvote', data.audQuestionID);
    var options = fetchOptions('PUT', data);

    fetch(url + 'aq/' + data.audQuestionID, options)
      .catch(err => { socket.emit('audQuestionUpvote', 'Server is unavailable'); });
  });

  socket.on('enableAsk', data => {
    // for the actual rooms
    nsp.in(data.room).emit('askenabled', data.askEnabled);

    var options = fetchOptions('PUT', {flag: data.askEnabled});
    fetch(url + 'sAsk/' + data.sessionID, options)
      .catch(err => { socket.emit('askenabled', 'Server is unavailable') })

  });

  socket.on('enableAudQ', data => {
    // for the actual rooms
    nsp.in(data.room).emit('audqenabled', data.audQEnabled);

    var options = fetchOptions('PUT', {flag: data.audQEnabled});
    fetch(url + 'sAudQ/' + data.sessionID, options)
      .catch(err => { socket.emit('audqenabled', 'Server is unavailable') })

  });

});

module.exports = server;
<|endoftext|>


<commit_before>var assert = require('chai').assert;
var ss = require('../../sidekick-security');
var path = require('path');
var Promise = require('bluebird');

describe('security analyser', function() {

  describe('scans files', function () {

    before(function () {
    });

    it('finds known violation: extension match', function (done) {
      ss._testRun(path.join(__dirname, '/fixtures/dir_with_issues/extension/extension_match.pem'))
        .then(function (annotation) {
          console.log(annotation);
          done();
        });
    });

    it('finds known violation: extension regex', function (done) {
      ss._testRun(path.join(__dirname, '/fixtures/dir_with_issues/extension/extension_regex.id_rsa'))
        .then(function (annotation) {
          console.log(annotation);
          done();
        });
    });

  });

  describe('finds know issues in filenames', function(){

    function runTest (testData, done){
      var issues = [];
      var promises = [];

      testData.forEach(function(filePath){
        var promise = ss._testRun(path.join(__dirname, '/', filePath));
        promises.push(promise);
        promise.then(function (annotation) {
          assert.isDefined(annotation, 'failed to find issue with: ' + filePath);
          console.log(annotation);
          issues.push(annotation);
        }, function(err){
          assert.equal(true, false);
        });
      });

      return Promise.all(promises).then(function(){
        try{
          assert.equal(issues.length, testData.length, 'Did not find all issues');
        } catch(e){
          Promise.reject();
        }
        done();
      });
    }

    it('detects private keys', function(done) {
      var testData = [
        'id_rsa',
        'production_rsa',
        '.ssh/id_rsa',
        'ssh/id_rsa',
        'privatekeys/id_rsa',
        'id_dsa',
        'key_dsa',
        '.ssh/id_dsa',
        'privatekeys/id_dsa',
        'id_ed25519',
        'user_ed25519',
        '.ssh/id_ed25519',
        'privatekeys/id_ed25519',
        '.ssh/id_ecdsa',
        'id_ecdsa',
        'jenkins_ecdsa',
        'ssh/id_ecdsa',
        'privatekeys/id_ecdsa'
      ];
      return runTest(testData, done);
    });

    it('detects files with .pem extension', function(done) {
      var testData = [
        'privatekey.pem',
        'keys/privatekey.pem',
        '.secret.pem'
      ];
      return runTest(testData, done);
    });

    it('detects files with .key(pair) extension', function(done) {
      var testData = [
        'privatekey.key',
        'keys/privatekey.key',
        '.secret.key',
        'production.keypair',
        'keys/privatekey.keypair'
      ];
      return runTest(testData, done);
    });

    it('detects files with .pkcs12 extension', function(done) {
      var testData = [
        'privatekey.pkcs12',
        'keys/privatekey.pkcs12',
        '.secret.pkcs12',
      ];
      return runTest(testData, done);
    });

    it('detects files with .pfx extension', function(done) {
      var testData = [
        'privatekey.pfx',
        'keys/privatekey.pfx',
        '.secret.pfx',
      ];
      return runTest(testData, done);
    });

    it('detects files with .p12 extension', function(done) {
      var testData = [
        'privatekey.p12',
        'keys/privatekey.p12',
        '.secret.p12',
      ];
      return runTest(testData, done);
    });

    it('detects files with .asc extension', function(done) {
      var testData = [
        'privatekey.asc',
        'keys/privatekey.asc',
        '.secret.asc',
      ];
      return runTest(testData, done);
    });

    it('detects Pidgin private OTR keys', function(done) {
      var testData = [
        'otr.private_key',
        '.purple/otr.private_key',
        'pidgin/otr.private_key',
      ];
      return runTest(testData, done);
    });

    it('detects shell command history files', function(done) {
      var testData = [
        '.bash_history',
        'bash_history',
        'bash/bash_history',
        '.zsh_history',
        'zsh_history',
        'zsh/zsh_history',
        '.zhistory',
        'zhistory',
        'zsh/zhistory',
        '.history',
        'history',
        'shell/history'
      ];
      return runTest(testData, done);
    });

    it('detects MySQL client command history files', function(done) {
      var testData = [
        '.mysql_history',
        'mysql_history',
        'history/.mysql_history',
      ];
      return runTest(testData, done);
    });

    it('detects PostgreSQL client command history files', function(done) {
      var testData = [
        '.psql_history',
        'psql_history',
        'history/.psql_history',
      ];
      return runTest(testData, done);
    });

    it('detects IRB console history files', function(done) {
      var testData = [
        '.irb_history',
        'irb_history',
        'history/.irb_history',
      ];
      return runTest(testData, done);
    });

    it('detects Pidgin chat client account configuration files', function(done) {
      var testData = [
        '.purple/accounts.xml',
        'purple/accounts.xml',
        'config/purple/accounts.xml',
      ];
      return runTest(testData, done);
    });

    it('detects XChat client server list configuration files', function(done) {
      var testData = [
        '.xchat2/servlist_.conf',
        '.xchat2/servlist.conf',
        'xchat2/servlist_.conf',
        'xchat2/servlist.conf',
        'xchat/servlist_.conf',
        'xchat/servlist.conf',
        '.xchat/servlist_.conf',
        '.xchat/servlist.conf',
        'config/.xchat/servlist.conf'
      ];
      return runTest(testData, done);
    });

    it('detects Hexchat client server list configuration files', function(done) {
      var testData = [
        '.hexchat/servlist.conf',
        'hexchat/servlist.conf',
        'config/.hexchat/servlist.conf'
      ];
      return runTest(testData, done);
    });

    it('detects irrsi IRC client configuration files', function(done) {
      var testData = [
        '.irssi/config',
        'irssi/config',
        'config/.irssi/config'
      ];
      return runTest(testData, done);
    });

    it('detects Recon-ng API key databases', function(done) {
      var testData = [
        '.recon-ng/keys.db',
        'recon-ng/keys.db',
        'config/.recon-ng/keys.db'
      ];
      return runTest(testData, done);
    });

    it('detects DBeaver configuration files', function(done) {
      var testData = [
        '.dbeaver-data-sources.xml',
        'dbeaver-data-sources.xml',
        'config/.dbeaver-data-sources.xml'
      ];
      return runTest(testData, done);
    });

    it('detects Mutt configuration files', function(done) {
      var testData = [
        '.muttrc',
        'muttrc',
        'config/.muttrc'
      ];
      return runTest(testData, done);
    });

    it('detects S3cmd configuration files', function(done) {
      var testData = [
        '.s3cfg',
        's3cfg',
        'config/.s3cfg'
      ];
      return runTest(testData, done);
    });

    it('detects T Twitter client configuration files', function(done) {
      var testData = [
        '.trc',
        'trc',
        'config/.trc'
      ];
      return runTest(testData, done);
    });

    it('detects OpenVPN configuration files', function(done) {
      var testData = [
        'vpn.ovpn',
        '.cryptostorm.ovpn',
        'config/work.ovpn'
      ];
      return runTest(testData, done);
    });

    it('detects Gitrob configuration files', function(done) {
      var testData = [
        '.gitrobrc',
        'gitrobrc',
        'config/.gitrobrc'
      ];
      return runTest(testData, done);
    });

    it('detects shell configuration files', function(done) {
      var testData = [
        '.bashrc',
        'bashrc',
        'bash/.bashrc',
        '.zshrc',
        'zshrc',
        'zsh/.zshrc'
      ];
      return runTest(testData, done);
    });

    it('detects shell profile files', function(done) {
      var testData = [
        '.bash_profile',
        'bash_profile',
        'bash/.bash_profile',
        '.zsh_profile',
        'zsh_profile',
        'zsh/.zsh_profile',
        '.profile',
        'profile',
        'sh/.profile'
      ];
      return runTest(testData, done);
    });

    it('detects shell alias files', function(done) {
      var testData = [
        '.bash_aliases',
        'bash_aliases',
        'bash/.bash_aliases',
        '.zsh_aliases',
        'zsh_aliases',
        'zsh/.zsh_aliases',
        '.aliases',
        'aliases',
        'sh/.aliases'
      ];
      return runTest(testData, done);
    });

    it('detects Rails secret token configuration files', function(done) {
      var testData = [
        'secret_token.rb',
        'config/initializers/secret_token.rb'
      ];
      return runTest(testData, done);
    });

    it('detects Omniauth configuration files', function(done) {
      var testData = [
        'omniauth.rb',
        'config/initializers/omniauth.rb'
      ];
      return runTest(testData, done);
    });

    it('detects Carrierwave configuration files', function(done) {
      var testData = [
        'carrierwave.rb',
        'config/initializers/carrierwave.rb'
      ];
      return runTest(testData, done);
    });

    it('detects Rails schema files', function(done) {
      var testData = [
        'schema.rb',
        'db/schema.rb'
      ];
      return runTest(testData, done);
    });

    it('detects Rails database configuration files', function(done) {
      var testData = [
        'database.yml',
        'config/database.yml'
      ];
      return runTest(testData, done);
    });

    it('detects Django settings files', function(done) {
      var testData = [
        'settings.py',
      ];
      return runTest(testData, done);
    });

    it('detects PHP configuration files', function(done) {
      var testData = [
        'config.php',
        'config/config.inc.php',
        'db_config.php',
        'secret_config.inc.php'
      ];
      return runTest(testData, done);
    });

    it('detects KeePass database files', function(done) {
      var testData = [
        'keepass.kdb',
        'secret/pwd.kdb'
      ];
      return runTest(testData, done);
    });

    it('detects 1Password database files', function(done) {
      var testData = [
        'passwords.agilekeychain',
        'secret/pwd.agilekeychain'
      ];
      return runTest(testData, done);
    });

    it('detects Apple keychain database files', function(done) {
      var testData = [
        'passwords.keychain',
        'secret/pwd.keychain'
      ];
      return runTest(testData, done);
    });

    it('detects GNOME keyring database files', function(done) {
      var testData = [
        'passwords.keystore',
        'passwords.keyring',
        'secret/pwd.keystore',
        'secret/pwd.keyring'
      ];
      return runTest(testData, done);
    });

    it('detects log files', function(done) {
      var testData = [
        'log.log',
        'logs/production.log',
        '.secret.log'
      ];
      return runTest(testData, done);
    });

    it('detects PCAP files', function(done) {
      var testData = [
        'capture.pcap',
        'debug/production.pcap'
      ];
      return runTest(testData, done);
    });

    it('detects SQL files', function(done) {
      var testData = [
        'db.sql',
        'db.sqldump',
        'setup/database.sql',
        'backup/production.sqldump'
      ];
      return runTest(testData, done);
    });

    it('detects GnuCash database files', function(done) {
      var testData = [
        'budget.gnucash',
        '.budget.gnucash',
        'finance/budget.gnucash'
      ];
      return runTest(testData, done);
    });

    it('detects files containing word: backup', function(done) {
      var testData = [
        'backup.tar.gz',
        'backups/dbbackup.zip'
      ];
      return runTest(testData, done);
    });

    it('detects files containing word: dump', function(done) {
      var testData = [
        'dump.bin',
        'debug/memdump.txt'
      ];
      return runTest(testData, done);
    });

    it('detects files containing word: password', function(done) {
      var testData = [
        'passwords.xls',
        'private/password-reminders.txt'
      ];
      return runTest(testData, done);
    });

    it('detects files containing wordis: private, key', function(done) {
      var testData = [
        'privatekey.asc',
        'super_private_key.asc',
        'private/private_keys.tar.gz'
      ];
      return runTest(testData, done);
    });

    it('detects Jenkins publish over ssh plugin configuration files', function(done) {
      var testData = [
        'jenkins.plugins.publish_over_ssh.BapSshPublisherPlugin.xml',
        'jenkins/jenkins.plugins.publish_over_ssh.BapSshPublisherPlugin.xml'
      ];
      return runTest(testData, done);
    });

    it('detects Jenkins credentials files', function(done) {
      var testData = [
        'credentials.xml',
        'jenkins/credentials.xml'
      ];
      return runTest(testData, done);
    });

    it('detects Apache htpasswd files', function(done) {
      var testData = [
        '.htpasswd',
        'htpasswd',
        'public/htpasswd',
        'admin/.htpasswd'
      ];
      return runTest(testData, done);
    });

    it('detects netrc files', function(done) {
      var testData = [
        '.netrc',
        'netrc',
        'dotfiles/.netrc',
        'homefolder/netrc'
      ];
      return runTest(testData, done);
    });

    it('detects KDE Wallet Manager files', function(done) {
      var testData = [
        'wallet.kwallet',
        '.wallet.kwallet',
        'dotfiles/secret.kwallet',
        'homefolder/creds.kwallet'
      ];
      return runTest(testData, done);
    });

    it('detects MediaWiki configuration files', function(done) {
      var testData = [
        'LocalSettings.php',
        'mediawiki/LocalSettings.php',
        'configs/LocalSettings.php'
      ];
      return runTest(testData, done);
    });

    it('detects Tunnelblick VPN configuration files', function(done) {
      var testData = [
        'vpn.tblk',
        'secret/tunnel.tblk',
        'configs/.tunnelblick.tblk'
      ];
      return runTest(testData, done);
    });

    it('detects Rubygems credentials files', function(done) {
      var testData = [
        '.gem/credentials',
        'gem/credentials',
      ];
      return runTest(testData, done);
    });
  })
});
<commit_msg>fix: Fixed broken test.<commit_after>var assert = require('chai').assert;
var expect = require('chai').expect;
var ss = require('../../sidekick-security');
var path = require('path');
var Promise = require('bluebird');

describe('security analyser', function() {

  describe('scans files', function () {

    before(function () {
    });

    it('finds known violation: extension match', function (done) {
      ss._testRun(path.join(__dirname, '/fixtures/dir_with_issues/extension/extension_match.pem'))
        .then(function (annotation) {
          console.log(annotation);
          done();
        });
    });

    it('finds known violation: extension regex', function (done) {
      ss._testRun(path.join(__dirname, '/fixtures/dir_with_issues/extension/extension_regex.id_rsa'))
        .then(function (annotation) {
          console.log(annotation);
          done();
        });
    });

  });

  describe('finds know issues in filenames', function(){

    function runTest (testData, done){
      var issues = [];
      var promises = [];

      testData.forEach(function(filePath){
        var promise = ss._testRun(path.join(__dirname, '/', filePath));
        promises.push(promise);
        promise.then(function (annotation) {
          expect(annotation).to.exist;
          console.log(annotation);
          issues.push(annotation);
        }, function(err){
          expect(true).to.equal(false);
        });
      });

      return Promise.all(promises).then(function(){
        try{
          expect(issues.length).to.equal(testData.length);
        } catch(e){
          Promise.reject();
        }
        done();
      });
    }

    it('detects private keys', function(done) {
      var testData = [
        'id_rsa',
        'production_rsa',
        '.ssh/id_rsa',
        'ssh/id_rsa',
        'privatekeys/id_rsa',
        'id_dsa',
        'key_dsa',
        '.ssh/id_dsa',
        'privatekeys/id_dsa',
        'id_ed25519',
        'user_ed25519',
        '.ssh/id_ed25519',
        'privatekeys/id_ed25519',
        '.ssh/id_ecdsa',
        'id_ecdsa',
        'jenkins_ecdsa',
        'ssh/id_ecdsa',
        'privatekeys/id_ecdsa'
      ];
      return runTest(testData, done);
    });

    it('detects files with .pem extension', function(done) {
      var testData = [
        'privatekey.pem',
        'keys/privatekey.pem',
        '.secret.pem'
      ];
      return runTest(testData, done);
    });

    it('detects files with .key(pair) extension', function(done) {
      var testData = [
        'privatekey.key',
        'keys/privatekey.key',
        '.secret.key',
        'production.keypair',
        'keys/privatekey.keypair'
      ];
      return runTest(testData, done);
    });

    it('detects files with .pkcs12 extension', function(done) {
      var testData = [
        'privatekey.pkcs12',
        'keys/privatekey.pkcs12',
        '.secret.pkcs12',
      ];
      return runTest(testData, done);
    });

    it('detects files with .pfx extension', function(done) {
      var testData = [
        'privatekey.pfx',
        'keys/privatekey.pfx',
        '.secret.pfx',
      ];
      return runTest(testData, done);
    });

    it('detects files with .p12 extension', function(done) {
      var testData = [
        'privatekey.p12',
        'keys/privatekey.p12',
        '.secret.p12',
      ];
      return runTest(testData, done);
    });

    it('detects files with .asc extension', function(done) {
      var testData = [
        'privatekey.asc',
        'keys/privatekey.asc',
        '.secret.asc',
      ];
      return runTest(testData, done);
    });

    it('detects Pidgin private OTR keys', function(done) {
      var testData = [
        'otr.private_key',
        '.purple/otr.private_key',
        'pidgin/otr.private_key',
      ];
      return runTest(testData, done);
    });

    it('detects shell command history files', function(done) {
      var testData = [
        '.bash_history',
        'bash_history',
        'bash/bash_history',
        '.zsh_history',
        'zsh_history',
        'zsh/zsh_history',
        '.zhistory',
        'zhistory',
        'zsh/zhistory',
        '.history',
        'history',
        'shell/history'
      ];
      return runTest(testData, done);
    });

    it('detects MySQL client command history files', function(done) {
      var testData = [
        '.mysql_history',
        'mysql_history',
        'history/.mysql_history',
      ];
      return runTest(testData, done);
    });

    it('detects PostgreSQL client command history files', function(done) {
      var testData = [
        '.psql_history',
        'psql_history',
        'history/.psql_history',
      ];
      return runTest(testData, done);
    });

    it('detects IRB console history files', function(done) {
      var testData = [
        '.irb_history',
        'irb_history',
        'history/.irb_history',
      ];
      return runTest(testData, done);
    });

    it('detects Pidgin chat client account configuration files', function(done) {
      var testData = [
        '.purple/accounts.xml',
        'purple/accounts.xml',
        'config/purple/accounts.xml',
      ];
      return runTest(testData, done);
    });

    it('detects XChat client server list configuration files', function(done) {
      var testData = [
        '.xchat2/servlist_.conf',
        '.xchat2/servlist.conf',
        'xchat2/servlist_.conf',
        'xchat2/servlist.conf',
        'xchat/servlist_.conf',
        'xchat/servlist.conf',
        '.xchat/servlist_.conf',
        '.xchat/servlist.conf',
        'config/.xchat/servlist.conf'
      ];
      return runTest(testData, done);
    });

    it('detects Hexchat client server list configuration files', function(done) {
      var testData = [
        '.hexchat/servlist.conf',
        'hexchat/servlist.conf',
        'config/.hexchat/servlist.conf'
      ];
      return runTest(testData, done);
    });

    it('detects irrsi IRC client configuration files', function(done) {
      var testData = [
        '.irssi/config',
        'irssi/config',
        'config/.irssi/config'
      ];
      return runTest(testData, done);
    });

    it('detects Recon-ng API key databases', function(done) {
      var testData = [
        '.recon-ng/keys.db',
        'recon-ng/keys.db',
        'config/.recon-ng/keys.db'
      ];
      return runTest(testData, done);
    });

    it('detects DBeaver configuration files', function(done) {
      var testData = [
        '.dbeaver-data-sources.xml',
        'dbeaver-data-sources.xml',
        'config/.dbeaver-data-sources.xml'
      ];
      return runTest(testData, done);
    });

    it('detects Mutt configuration files', function(done) {
      var testData = [
        '.muttrc',
        'muttrc',
        'config/.muttrc'
      ];
      return runTest(testData, done);
    });

    it('detects S3cmd configuration files', function(done) {
      var testData = [
        '.s3cfg',
        's3cfg',
        'config/.s3cfg'
      ];
      return runTest(testData, done);
    });

    it('detects T Twitter client configuration files', function(done) {
      var testData = [
        '.trc',
        'trc',
        'config/.trc'
      ];
      return runTest(testData, done);
    });

    it('detects OpenVPN configuration files', function(done) {
      var testData = [
        'vpn.ovpn',
        '.cryptostorm.ovpn',
        'config/work.ovpn'
      ];
      return runTest(testData, done);
    });

    it('detects Gitrob configuration files', function(done) {
      var testData = [
        '.gitrobrc',
        'gitrobrc',
        'config/.gitrobrc'
      ];
      return runTest(testData, done);
    });

    it('detects shell configuration files', function(done) {
      var testData = [
        '.bashrc',
        'bashrc',
        'bash/.bashrc',
        '.zshrc',
        'zshrc',
        'zsh/.zshrc'
      ];
      return runTest(testData, done);
    });

    it('detects shell profile files', function(done) {
      var testData = [
        '.bash_profile',
        'bash_profile',
        'bash/.bash_profile',
        '.zsh_profile',
        'zsh_profile',
        'zsh/.zsh_profile',
        '.profile',
        'profile',
        'sh/.profile'
      ];
      return runTest(testData, done);
    });

    it('detects shell alias files', function(done) {
      var testData = [
        '.bash_aliases',
        'bash_aliases',
        'bash/.bash_aliases',
        '.zsh_aliases',
        'zsh_aliases',
        'zsh/.zsh_aliases',
        '.aliases',
        'aliases',
        'sh/.aliases'
      ];
      return runTest(testData, done);
    });

    it('detects Rails secret token configuration files', function(done) {
      var testData = [
        'secret_token.rb',
        'config/initializers/secret_token.rb'
      ];
      return runTest(testData, done);
    });

    it('detects Omniauth configuration files', function(done) {
      var testData = [
        'omniauth.rb',
        'config/initializers/omniauth.rb'
      ];
      return runTest(testData, done);
    });

    it('detects Carrierwave configuration files', function(done) {
      var testData = [
        'carrierwave.rb',
        'config/initializers/carrierwave.rb'
      ];
      return runTest(testData, done);
    });

    it('detects Rails schema files', function(done) {
      var testData = [
        'schema.rb',
        'db/schema.rb'
      ];
      return runTest(testData, done);
    });

    it('detects Rails database configuration files', function(done) {
      var testData = [
        'database.yml',
        'config/database.yml'
      ];
      return runTest(testData, done);
    });

    it('detects Django settings files', function(done) {
      var testData = [
        'settings.py',
      ];
      return runTest(testData, done);
    });

    it('detects PHP configuration files', function(done) {
      var testData = [
        'config.php',
        'config/config.inc.php',
        'db_config.php',
        'secret_config.inc.php'
      ];
      return runTest(testData, done);
    });

    it('detects KeePass database files', function(done) {
      var testData = [
        'keepass.kdb',
        'secret/pwd.kdb'
      ];
      return runTest(testData, done);
    });

    it('detects 1Password database files', function(done) {
      var testData = [
        'passwords.agilekeychain',
        'secret/pwd.agilekeychain'
      ];
      return runTest(testData, done);
    });

    it('detects Apple keychain database files', function(done) {
      var testData = [
        'passwords.keychain',
        'secret/pwd.keychain'
      ];
      return runTest(testData, done);
    });

    it('detects GNOME keyring database files', function(done) {
      var testData = [
        'passwords.keystore',
        'passwords.keyring',
        'secret/pwd.keystore',
        'secret/pwd.keyring'
      ];
      return runTest(testData, done);
    });

    it('detects log files', function(done) {
      var testData = [
        'log.log',
        'logs/production.log',
        '.secret.log'
      ];
      return runTest(testData, done);
    });

    it('detects PCAP files', function(done) {
      var testData = [
        'capture.pcap',
        'debug/production.pcap'
      ];
      return runTest(testData, done);
    });

    it('detects SQL files', function(done) {
      var testData = [
        'db.sql',
        'db.sqldump',
        'setup/database.sql',
        'backup/production.sqldump'
      ];
      return runTest(testData, done);
    });

    it('detects GnuCash database files', function(done) {
      var testData = [
        'budget.gnucash',
        '.budget.gnucash',
        'finance/budget.gnucash'
      ];
      return runTest(testData, done);
    });

    it('detects files containing word: backup', function(done) {
      var testData = [
        'backup.tar.gz',
        'backups/dbbackup.zip'
      ];
      return runTest(testData, done);
    });

    it('detects files containing word: dump', function(done) {
      var testData = [
        'dump.bin',
        'debug/memdump.txt'
      ];
      return runTest(testData, done);
    });

    it('detects files containing word: password', function(done) {
      var testData = [
        'passwords.xls',
        'private/password-reminders.txt'
      ];
      return runTest(testData, done);
    });

    it('detects files containing wordis: private, key', function(done) {
      var testData = [
        'privatekey.asc',
        'super_private_key.asc',
        'private/private_keys.tar.gz'
      ];
      return runTest(testData, done);
    });

    it('detects Jenkins publish over ssh plugin configuration files', function(done) {
      var testData = [
        'jenkins.plugins.publish_over_ssh.BapSshPublisherPlugin.xml',
        'jenkins/jenkins.plugins.publish_over_ssh.BapSshPublisherPlugin.xml'
      ];
      return runTest(testData, done);
    });

    it('detects Jenkins credentials files', function(done) {
      var testData = [
        'credentials.xml',
        'jenkins/credentials.xml'
      ];
      return runTest(testData, done);
    });

    it('detects Apache htpasswd files', function(done) {
      var testData = [
        '.htpasswd',
        'htpasswd',
        'public/htpasswd',
        'admin/.htpasswd'
      ];
      return runTest(testData, done);
    });

    it('detects netrc files', function(done) {
      var testData = [
        '.netrc',
        'netrc',
        'dotfiles/.netrc',
        'homefolder/netrc'
      ];
      return runTest(testData, done);
    });

    it('detects KDE Wallet Manager files', function(done) {
      var testData = [
        'wallet.kwallet',
        '.wallet.kwallet',
        'dotfiles/secret.kwallet',
        'homefolder/creds.kwallet'
      ];
      return runTest(testData, done);
    });

    it('detects MediaWiki configuration files', function(done) {
      var testData = [
        'LocalSettings.php',
        'mediawiki/LocalSettings.php',
        'configs/LocalSettings.php'
      ];
      return runTest(testData, done);
    });

    it('detects Tunnelblick VPN configuration files', function(done) {
      var testData = [
        'vpn.tblk',
        'secret/tunnel.tblk',
        'configs/.tunnelblick.tblk'
      ];
      return runTest(testData, done);
    });

    it('detects Rubygems credentials files', function(done) {
      var testData = [
        '.gem/credentials',
        'gem/credentials',
      ];
      return runTest(testData, done);
    });
  })
});
<|endoftext|>


<commit_before>(function() {
  SAMPLE_SIZE = 2048;

  var adapter = function ( dance ) {
    this.dance = dance;
    this.context = window.audioContext ?
      new window.AudioContext() :
      new window.webkitAudioContext();
  };

  adapter.prototype = {
    load : function ( path, callback ) {
      var
        req = new XMLHttpRequest(),
        _this = this;

      this.source = this.context.createBufferSource();
      this.loaded = false;

      req.open( 'GET', path, true );
      req.responseType = 'arraybuffer';

      req.onload = function () {
        if ( _this.context.decodeAudioData ) {
          _this.context.decodeAudioData( req.response, function( buffer ) {
            _this.source.buffer = buffer;
          }, function( e ) {
            console.log( e );
          });
        } else {
          _this.source.buffer = _this.context.createBuffer( req.response, false );
        }
        _this.source.connect( _this.context.destination );
        _this.source.connect( _this.fft );
        _this.fft.connect( _this.proc );
        _this.proc.connect( _this.context.destination );
        _this.loaded = true;
        _this.dance.trigger( 'loaded' );
      };
      req.send();

      this.proc = this.context.createJavaScriptNode( SAMPLE_SIZE / 2, 1, 1 );
      this.proc.onaudioprocess = function() { _this.update.call( _this ); };
      this.source.connect( this.context.destination );

      this.fft    = this.context.createAnalyser();
      this.data   = new Uint8Array( this.fft.frequencyBinCount );
    },
    play : function () {
      var _this = this;
      (function play() {
        setTimeout(function() {
          _this.loaded ? _this.source.noteOn( 0.0 ) : play();
        }, 10);
      })();
    },
    stop : function () { this.source.noteOff(0); },
    getSpectrum : function () { return this.data; },
    getTime : function () { return this.context.currentTime; },
    update : function ( e ) {
      this.fft.getByteFrequencyData( this.data );
      this.dance.trigger( 'update' );
    }
  };

  Dance.adapters.webkit = adapter;

})();
<commit_msg>Might as well save commented out Uint8Array test for later<commit_after>(function() {
  SAMPLE_SIZE = 2048;

  var adapter = function ( dance ) {
    this.dance = dance;
    this.context = window.audioContext ?
      new window.AudioContext() :
      new window.webkitAudioContext();
  };

  adapter.prototype = {
    load : function ( path, callback ) {
      var
        req = new XMLHttpRequest(),
        _this = this;

      this.source = this.context.createBufferSource();
      this.loaded = false;

      req.open( 'GET', path, true );
      req.responseType = 'arraybuffer';

      req.onload = function () {
        if ( _this.context.decodeAudioData ) {
          _this.context.decodeAudioData( req.response, function( buffer ) {
            _this.source.buffer = buffer;
          }, function( e ) {
            console.log( e );
          });
        } else {
          _this.source.buffer = _this.context.createBuffer( req.response, false );
        }
        _this.source.connect( _this.context.destination );
        _this.source.connect( _this.fft );
        _this.fft.connect( _this.proc );
        _this.proc.connect( _this.context.destination );
        _this.loaded = true;
        _this.dance.trigger( 'loaded' );
      };
      req.send();

      this.proc = this.context.createJavaScriptNode( SAMPLE_SIZE / 2, 1, 1 );
      this.proc.onaudioprocess = function() { _this.update.call( _this ); };
      this.source.connect( this.context.destination );

      this.fft    = this.context.createAnalyser();
//      this.data   = new Float32Array( this.fft.frequencyBinCount );
      this.data   = new Uint8Array( this.fft.frequencyBinCount );
    },
    play : function () {
      var _this = this;
      (function play() {
        setTimeout(function() {
          _this.loaded ? _this.source.noteOn( 0.0 ) : play();
        }, 10);
      })();
    },
    stop : function () { this.source.noteOff(0); },
    getSpectrum : function () { return this.data; },
    getTime : function () { return this.context.currentTime; },
    update : function ( e ) {
      this.fft.getByteFrequencyData( this.data );
//      this.fft.getFloatFrequencyData( this.data );
      this.dance.trigger( 'update' );
    }
  };

  Dance.adapters.webkit = adapter;

})();
<|endoftext|>


<commit_before>// Copyright 2014 Volker Sorge
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Debug facility for the speech rule engine.
 *
 * @author volker.sorge@gmail.com (Volker Sorge)
 */

goog.provide('sre.Debugger');

goog.require('sre.SystemExternal');

/**
 * @constructor
 */
sre.Debugger = function() {
  /**
   * Whether the debugger is active.
   * @type {boolean}
   * @private
   */
  this.isActive_ = false;
  /**
   * @type {function(string)} Output function.
   * @private
   */
  this.outputFunction_ = console.log;
  /**
   * @type {?stream} Output stream of the debug file.
   * @private
   */
  this.stream_ = null;
};
goog.addSingletonGetter(sre.Debugger);

/**
 * Flag for the debug mode of the speech rule engine.
 * @param {string=} opt_file A filename to log the debug information.
 */
sre.Debugger.prototype.init = function(opt_file) {
  if (opt_file) {
    this.startDebugFile_(opt_file);
  }
  this.isActive_ = true;
};

/**
 * Initialises the debug file.
 * This is handled asynchronously.
 * @param {!string} filename The filename to route debug output to.
 * @private
 */
sre.Debugger.prototype.startDebugFile_ = function(filename) {
  this.stream_ = sre.SystemExternal.fs.createWriteStream(filename);
  this.outputFunction_ = goog.bind(
      function(var_args) {
        var outputList = Array.prototype.slice.call(arguments, 0);
        this.stream_.write(outputList.join(' '));
        this.stream_.write('\n');},
      this);
  this.stream_.on('error', goog.bind(
      function(error) {
        console.log('Invalid log file. Debug information sent to console.');
        this.outputFunction_ = console.log;
      },
      this));
  this.stream_.on('finish', function() {
    console.log('Finalizing debug file.');
  });
};

/**
 * Writes the debug output to the debuggers current stream.
 * @param {Array.<string>} outputList List of output strings.
 * @private
 */
sre.Debugger.prototype.output_ = function(outputList) {
  this.outputFunction_.apply(
      console.log === this.outputFunction_ ? console : this.outputFunction_,
      ['Speech Rule Engine Debugger:'].concat(outputList));
};

/**
 * Give debug output.
 * @param {...*} var_args Rest elements of debug output.
 */
sre.Debugger.prototype.output = function(var_args) {
  if (this.isActive_) {
    this.output_(Array.prototype.slice.call(arguments, 0));
  }
};

/**
 * Give debug output by compiling executing a function. The main idea is that
 * costly output is only generated when the debug mode is indeed active.
 * @param {function(): Array.<string>} func The function that generates the
 *      debug output.
 */
sre.Debugger.prototype.generateOutput = function(func) {
  if (this.isActive_) {
    this.output_(func.apply(func, []));
  }
};

/**
 * Gracefully exits the debugger.
 * @param {function()=} opt_callback Function to be executed after exiting the
 *     debugger.
 */
sre.Debugger.prototype.exit = function(opt_callback) {
  var callback = opt_callback || function() {};
  if (this.isActive_ && this.stream_) {
    this.stream_.end('', '', callback);
  }
  this.isActive_ = false;
};
<commit_msg>Sets debugger to always active. That's temporary!<commit_after>// Copyright 2014 Volker Sorge
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Debug facility for the speech rule engine.
 *
 * @author volker.sorge@gmail.com (Volker Sorge)
 */

goog.provide('sre.Debugger');

goog.require('sre.SystemExternal');

/**
 * @constructor
 */
sre.Debugger = function() {
  /**
   * Whether the debugger is active.
   * @type {boolean}
   * @private
   */
  this.isActive_ = true;
  /**
   * @type {function(string)} Output function.
   * @private
   */
  this.outputFunction_ = console.log;
  /**
   * @type {?stream} Output stream of the debug file.
   * @private
   */
  this.stream_ = null;
};
goog.addSingletonGetter(sre.Debugger);

/**
 * Flag for the debug mode of the speech rule engine.
 * @param {string=} opt_file A filename to log the debug information.
 */
sre.Debugger.prototype.init = function(opt_file) {
  if (opt_file) {
    this.startDebugFile_(opt_file);
  }
  this.isActive_ = true;
};

/**
 * Initialises the debug file.
 * This is handled asynchronously.
 * @param {!string} filename The filename to route debug output to.
 * @private
 */
sre.Debugger.prototype.startDebugFile_ = function(filename) {
  this.stream_ = sre.SystemExternal.fs.createWriteStream(filename);
  this.outputFunction_ = goog.bind(
      function(var_args) {
        var outputList = Array.prototype.slice.call(arguments, 0);
        this.stream_.write(outputList.join(' '));
        this.stream_.write('\n');},
      this);
  this.stream_.on('error', goog.bind(
      function(error) {
        console.log('Invalid log file. Debug information sent to console.');
        this.outputFunction_ = console.log;
      },
      this));
  this.stream_.on('finish', function() {
    console.log('Finalizing debug file.');
  });
};

/**
 * Writes the debug output to the debuggers current stream.
 * @param {Array.<string>} outputList List of output strings.
 * @private
 */
sre.Debugger.prototype.output_ = function(outputList) {
  this.outputFunction_.apply(
      console.log === this.outputFunction_ ? console : this.outputFunction_,
      ['Speech Rule Engine Debugger:'].concat(outputList));
};

/**
 * Give debug output.
 * @param {...*} var_args Rest elements of debug output.
 */
sre.Debugger.prototype.output = function(var_args) {
  if (this.isActive_) {
    this.output_(Array.prototype.slice.call(arguments, 0));
  }
};

/**
 * Give debug output by compiling executing a function. The main idea is that
 * costly output is only generated when the debug mode is indeed active.
 * @param {function(): Array.<string>} func The function that generates the
 *      debug output.
 */
sre.Debugger.prototype.generateOutput = function(func) {
  if (this.isActive_) {
    this.output_(func.apply(func, []));
  }
};

/**
 * Gracefully exits the debugger.
 * @param {function()=} opt_callback Function to be executed after exiting the
 *     debugger.
 */
sre.Debugger.prototype.exit = function(opt_callback) {
  var callback = opt_callback || function() {};
  if (this.isActive_ && this.stream_) {
    this.stream_.end('', '', callback);
  }
  this.isActive_ = false;
};
<|endoftext|>