<commit_before>/*
hud.js
------
    This file contains the code for controlling the player
    health HUD. The technique used is "injection", which is
    an extension of the original code. The way it works is
    by creating a new instance of original code and supply it
    with a new name. Simply put, injection is a copy of the
    original but different in the sense of the extra code we
    add. While injecting, we modify the original code. In
    the case of this plugin, we overwrite the draw() function
    of our game. The this.parent() function will point to our
    old draw() function, so everything there is kept. All we
    check for in the new isntance is the presence of a player
    entity, and if true then a HUD is drawn.

    The health HUD consists of two parts: A number and Health bar.

    Number: A function which handles drawing a black, slightly transparent
    rectangle where the health will be visible. Uses the following
    canvas properties to draw the HUD to screen:
        | fillstyle: This property sets the color
        | font: This property sets the font
        | setAlpha(): This property sets the transparency.
            | setalpha = 1: Fully Solid
            | setAlpha = 0: Fully transparent
        | fillRect(): This property draws a rectangle to the screen
          given a given position with a given width + height
        | fillText(): This property draws text on screen at a given positon.

    Bar: A function which draws two rectangles on top of each other. Uses
    the same canvas properties above to draw.

*/

ig.module(
    'plugins.hud.hud'
)
.defines(function() {
    ig.hud = ig.Class.extend({
        // Get the canvas
        canvas  : document.getElementById('canvas'),
        // Check if the canvas is being viewed
        context : canvas.getContext('2d'),

        init: function() {
            ig.Game.inject({
                draw: function() {
                    this.parent();
                    // If there is a player. draw the HUD
                    if(ig.game.getEntitiesByType('EntityPlayer').length  != 0) {
                        if(this.hud && !ig.game.menuVisible) {
                            this.hud.number_health();
                            this.hud.bar_health();
                            this.hud.number_mana();
                            this.hud.bar_mana();
                            // this.hud.number_stamina();
                            // this.hud.bar_stamina();
                            // this.hud.number_level();
                            // this.hud.bar_exp();
                        }
                    }
                }
            })
        },

        // ----- Health Meter -----
        number_health: function() {
            if(!this.context) return null;
            // Get the player instance
            var player  = ig.game.getEntitiesByType('EntityPlayer')[0];

            if(player.attacking && !this.menuVisible){
                ig.game.attackingAnimation.draw(10, 185);
            }
            else if(!player.attacking && !this.menuVisible){
                ig.game.okayAnimation.draw(10, 185);
            }
            // Draw a transparent Black Rectangle
            var context  = this.canvas.getContext('2d');
            // Set visual properties of the HUD
            context.fillStyle = "rgb(0, 0, 0)";
            context.setAlpha = 0.7; //set transparency
            //context.fillRect (10, 10, 75, 13);
            //draw text on top of the rectangle
            context.fillStyle = "rgb(255, 255, 255)";
            context.font = "13px Arial";
            // (11, 21): x, y position to draw to screen
            context.fillText ('HP: ' + player.health + '/' + player.stats.maxHP, 120, 385); //font used is the default canvas font
            context.setAlpha = 1;
            return null;
        },

        bar_health: function() {
            if(!this.context) return null;
            // Get the player instance
            var player  = ig.game.getEntitiesByType('EntityPlayer')[0];

            // Draw a transparent Black Rectangle
            var h = 100 * Math.min(player.health / player.stats.maxHP, 100);
            var context  = this.canvas.getContext('2d');
            // Set visual properties of the HUD
            context.fillStyle = "rgb(0, 0, 0)";
            context.setAlpha = 0.7;
            //context.fillRect (90, 10, 100, 13);
            // Determine what color of health to draw, Bright red for full, dim red otherwise
            var color = h < 100 ? "rgb(175, 0, 0)" : "rgb(225, 0, 0)";
            //var color = "rgb(200, 0, 0)";
            context.fillStyle = color;
            context.setAlpha = 0.9;

            // (x, y, .., ..)
            context.fillRect (95, 390, h-2, 8);
            context.setAlpha = 1;
            return null;
        },

        // ----- Mana Meter -----
        number_mana: function() {
            if(!this.context) return null;
            // Get the player instance
            var player  = ig.game.getEntitiesByType('EntityPlayer')[0];
            // Draw a transparent Black Rectangle
            var context  = this.canvas.getContext('2d');
            // Set visual properties of the HUD
            context.fillStyle = "rgb(0, 0, 0)";
            context.setAlpha = 0.7; //set transparency
            //context.fillRect (10, 25, 75, 13);
            //draw text on top of the rectangle
            context.fillStyle = "rgb(255, 255, 255)";
            context.font = "13px Arial";
            context.fillText ('MP: ' + player.tp + '/' + player.stats.maxTP, 120, 425); //font used is the default canvas font
            context.setAlpha = 1;
            return null;
        },

        bar_mana: function() {
            if(!this.context) return null;
            // Get the player instance
            var player  = ig.game.getEntitiesByType('EntityPlayer')[0];

            // Draw a transparent Black Rectangle
            var h = 100 * Math.min(player.tp / player.stats.maxTP, 100);
            var context  = this.canvas.getContext('2d');
            // Set visual properties of the HUD
            context.fillStyle = "rgb(0, 0, 0)";
            context.setAlpha = 0.7;
            //context.fillRect (90, 25, 100, 13);
            // Determine what color of mana to draw, Bright blue for full, dim blue otherwise
            var color = h < 100 ? "rgb(0, 0, 175)" : "rgb(0, 0, 225)";
            //var color = "rgb(0, 0, 200)";
            context.fillStyle = color;
            context.setAlpha = 0.9;
            context.fillRect (95, 430, h-2, 8);
            context.setAlpha = 1;
            return null;
        },

        // ----- Stamina Meter -----
        number_stamina: function() {
            if(!this.context) return null;
            // Get the player instance
            var player  = ig.game.getEntitiesByType('EntityPlayer')[0];
            // Draw a transparent Black Rectangle
            var context  = this.canvas.getContext('2d');
            // Set visual properties of the HUD
            context.fillStyle = "rgb(0, 0, 0)";
            context.setAlpha = 0.7; //set transparency
            context.fillRect (10, 40, 75, 13);
            //draw text on top of the rectangle
            context.fillStyle = "rgb(255, 255, 255)";
            context.font = "13px Arial";
            context.fillText ('SP: ' + player.stamina + '/' + player.max_stamina, 11, 51); //font used is the default canvas font
            context.setAlpha = 1;
            return null;
        },

        bar_stamina: function() {
            if(!this.context) return null;
            // Get the player instance
            var player  = ig.game.getEntitiesByType('EntityPlayer')[0];
            // Draw a transparent Black Rectangle
            var h = 100 * Math.min(player.stamina / player.max_stamina, 100);
            var context  = this.canvas.getContext('2d');
            // Set visual properties of the HUD
            context.fillStyle = "rgb(0, 0, 0)";
            context.setAlpha = 0.7;
            context.fillRect (90, 40, 100, 13);
            // Determine what color of stamina to draw, Bright green for full, dim green otherwise
            var color = h < 100 ? "rgb(0, 175, 0)" : "rgb(0, 225, 0)";
            //var color = "rgb(0, 200, 0)";
            context.fillStyle = color;
            context.setAlpha = 0.9;
            context.fillRect (91, 41, h-2, 11);
            context.setAlpha = 1;
            return null;
        },

        // ----- Level/Experience Meter -----
        number_level: function() {
            if(!this.context) return null;
            // Get the player instance
            var player  = ig.game.getEntitiesByType('EntityPlayer')[0];
            // Draw a transparent Black Rectangle
            var context  = this.canvas.getContext('2d');
            // Set visual properties of the HUD
            context.fillStyle = "rgb(0, 0, 0)";
            context.setAlpha = 0.7; //set transparency
            context.fillRect (10, 55, 75, 13);
            //draw text on top of the rectangle
            context.fillStyle = "rgb(255, 255, 255)";
            context.font = "13px Arial";
            context.fillText ('Level: ' + ig.game.LEVEL, 11, 66); //font used is the default canvas font
            context.setAlpha = 1;
            return null;
        },

        bar_exp: function() {
            if(!this.context) return null;
            // Get the player instance
            var player  = ig.game.getEntitiesByType('EntityPlayer')[0];
            // Draw a transparent Black Rectangle
            var h = 100 * Math.min(ig.game.EXP.curr / ig.game.EXP.next, 100);
            var context  = this.canvas.getContext('2d');
            // Set visual properties of the HUD
            context.fillStyle = "rgb(0, 0, 0)";
            context.setAlpha = 0.7;
            context.fillRect (90, 55, 100, 13);
            var color = "rgb(200, 200, 0)";
            context.fillStyle = color;
            context.setAlpha = 0.9;
            context.fillRect (91, 56, h-2, 11);
            context.setAlpha = 1;
            return null;
        },
    });
})
<commit_msg>Repositioning hud elements<commit_after>/*
hud.js
------
    This file contains the code for controlling the player
    health HUD. The technique used is "injection", which is
    an extension of the original code. The way it works is
    by creating a new instance of original code and supply it
    with a new name. Simply put, injection is a copy of the
    original but different in the sense of the extra code we
    add. While injecting, we modify the original code. In
    the case of this plugin, we overwrite the draw() function
    of our game. The this.parent() function will point to our
    old draw() function, so everything there is kept. All we
    check for in the new isntance is the presence of a player
    entity, and if true then a HUD is drawn.

    The health HUD consists of two parts: A number and Health bar.

    Number: A function which handles drawing a black, slightly transparent
    rectangle where the health will be visible. Uses the following
    canvas properties to draw the HUD to screen:
        | fillstyle: This property sets the color
        | font: This property sets the font
        | setAlpha(): This property sets the transparency.
            | setalpha = 1: Fully Solid
            | setAlpha = 0: Fully transparent
        | fillRect(): This property draws a rectangle to the screen
          given a given position with a given width + height
        | fillText(): This property draws text on screen at a given positon.

    Bar: A function which draws two rectangles on top of each other. Uses
    the same canvas properties above to draw.

*/

ig.module(
    'plugins.hud.hud'
)
.defines(function() {
    ig.hud = ig.Class.extend({
        // Get the canvas
        canvas  : document.getElementById('canvas'),
        // Check if the canvas is being viewed
        context : canvas.getContext('2d'),

        init: function() {
            ig.Game.inject({
                draw: function() {
                    this.parent();
                    // If there is a player. draw the HUD
                    if(ig.game.getEntitiesByType('EntityPlayer').length  != 0) {
                        if(this.hud && !ig.game.menuVisible) {
                            ig.game.barHud.draw(0, 150);
                            this.hud.number_health();
                            this.hud.bar_health();
                            this.hud.number_mana();
                            this.hud.bar_mana();
                            // this.hud.number_stamina();
                            // this.hud.bar_stamina();
                            // this.hud.number_level();
                            // this.hud.bar_exp();
                        }
                    }
                }
            })
        },

        // ----- Health Meter -----
        number_health: function() {
            if(!this.context) return null;
            // Get the player instance
            var player  = ig.game.getEntitiesByType('EntityPlayer')[0];

            if(player.attacking && !this.menuVisible){
                ig.game.attackingAnimation.draw(20, 180);
            }
            else if(!player.attacking && !this.menuVisible){
                ig.game.okayAnimation.draw(20, 180);
            }
            // Draw a transparent Black Rectangle
            var context  = this.canvas.getContext('2d');
            // Set visual properties of the HUD
            context.fillStyle = "rgb(0, 0, 0)";
            context.setAlpha = 0.7; //set transparency
            //context.fillRect (10, 10, 75, 13);
            //draw text on top of the rectangle
            context.fillStyle = "rgb(255, 255, 255)";
            context.font = "13px Arial";
            // (11, 21): x, y position to draw to screen
            context.fillText ('HP: ' + player.health + '/' + player.stats.maxHP, 135, 385); //font used is the default canvas font
            context.setAlpha = 1;
            return null;
        },

        bar_health: function() {
            if(!this.context) return null;
            // Get the player instance
            var player  = ig.game.getEntitiesByType('EntityPlayer')[0];

            // Draw a transparent Black Rectangle
            var h = 100 * Math.min(player.health / player.stats.maxHP, 100);
            var context  = this.canvas.getContext('2d');
            // Set visual properties of the HUD
            context.fillStyle = "rgb(0, 0, 0)";
            context.setAlpha = 0.7;
            //context.fillRect (90, 10, 100, 13);
            // Determine what color of health to draw, Bright red for full, dim red otherwise
            var color = h < 100 ? "rgb(175, 0, 0)" : "rgb(225, 0, 0)";
            //var color = "rgb(200, 0, 0)";
            context.fillStyle = color;
            context.setAlpha = 0.9;

            // (x, y, .., ..)
            context.fillRect (115, 390, h-6, 8);
            context.setAlpha = 1;
            return null;
        },

        // ----- Mana Meter -----
        number_mana: function() {
            if(!this.context) return null;
            // Get the player instance
            var player  = ig.game.getEntitiesByType('EntityPlayer')[0];
            // Draw a transparent Black Rectangle
            var context  = this.canvas.getContext('2d');
            // Set visual properties of the HUD
            context.fillStyle = "rgb(0, 0, 0)";
            context.setAlpha = 0.7; //set transparency
            //context.fillRect (10, 25, 75, 13);
            //draw text on top of the rectangle
            context.fillStyle = "rgb(255, 255, 255)";
            context.font = "13px Arial";
            context.fillText ('MP: ' + player.tp + '/' + player.stats.maxTP, 135, 425); //font used is the default canvas font
            context.setAlpha = 1;
            return null;
        },

        bar_mana: function() {
            if(!this.context) return null;
            // Get the player instance
            var player  = ig.game.getEntitiesByType('EntityPlayer')[0];

            // Draw a transparent Black Rectangle
            var h = 100 * Math.min(player.tp / player.stats.maxTP, 100);
            var context  = this.canvas.getContext('2d');
            // Set visual properties of the HUD
            context.fillStyle = "rgb(0, 0, 0)";
            context.setAlpha = 0.7;
            //context.fillRect (90, 25, 100, 13);
            // Determine what color of mana to draw, Bright blue for full, dim blue otherwise
            var color = h < 100 ? "rgb(0, 0, 175)" : "rgb(0, 0, 225)";
            //var color = "rgb(0, 0, 200)";
            context.fillStyle = color;
            context.setAlpha = 0.9;
            context.fillRect (115, 430, h-6, 8);
            context.setAlpha = 1;
            return null;
        },

        // ----- Stamina Meter -----
        number_stamina: function() {
            if(!this.context) return null;
            // Get the player instance
            var player  = ig.game.getEntitiesByType('EntityPlayer')[0];
            // Draw a transparent Black Rectangle
            var context  = this.canvas.getContext('2d');
            // Set visual properties of the HUD
            context.fillStyle = "rgb(0, 0, 0)";
            context.setAlpha = 0.7; //set transparency
            context.fillRect (10, 40, 75, 13);
            //draw text on top of the rectangle
            context.fillStyle = "rgb(255, 255, 255)";
            context.font = "13px Arial";
            context.fillText ('SP: ' + player.stamina + '/' + player.max_stamina, 11, 51); //font used is the default canvas font
            context.setAlpha = 1;
            return null;
        },

        bar_stamina: function() {
            if(!this.context) return null;
            // Get the player instance
            var player  = ig.game.getEntitiesByType('EntityPlayer')[0];
            // Draw a transparent Black Rectangle
            var h = 100 * Math.min(player.stamina / player.max_stamina, 100);
            var context  = this.canvas.getContext('2d');
            // Set visual properties of the HUD
            context.fillStyle = "rgb(0, 0, 0)";
            context.setAlpha = 0.7;
            context.fillRect (90, 40, 100, 13);
            // Determine what color of stamina to draw, Bright green for full, dim green otherwise
            var color = h < 100 ? "rgb(0, 175, 0)" : "rgb(0, 225, 0)";
            //var color = "rgb(0, 200, 0)";
            context.fillStyle = color;
            context.setAlpha = 0.9;
            context.fillRect (91, 41, h-2, 11);
            context.setAlpha = 1;
            return null;
        },

        // ----- Level/Experience Meter -----
        number_level: function() {
            if(!this.context) return null;
            // Get the player instance
            var player  = ig.game.getEntitiesByType('EntityPlayer')[0];
            // Draw a transparent Black Rectangle
            var context  = this.canvas.getContext('2d');
            // Set visual properties of the HUD
            context.fillStyle = "rgb(0, 0, 0)";
            context.setAlpha = 0.7; //set transparency
            context.fillRect (10, 55, 75, 13);
            //draw text on top of the rectangle
            context.fillStyle = "rgb(255, 255, 255)";
            context.font = "13px Arial";
            context.fillText ('Level: ' + ig.game.LEVEL, 11, 66); //font used is the default canvas font
            context.setAlpha = 1;
            return null;
        },

        bar_exp: function() {
            if(!this.context) return null;
            // Get the player instance
            var player  = ig.game.getEntitiesByType('EntityPlayer')[0];
            // Draw a transparent Black Rectangle
            var h = 100 * Math.min(ig.game.EXP.curr / ig.game.EXP.next, 100);
            var context  = this.canvas.getContext('2d');
            // Set visual properties of the HUD
            context.fillStyle = "rgb(0, 0, 0)";
            context.setAlpha = 0.7;
            context.fillRect (90, 55, 100, 13);
            var color = "rgb(200, 200, 0)";
            context.fillStyle = color;
            context.setAlpha = 0.9;
            context.fillRect (91, 56, h-2, 11);
            context.setAlpha = 1;
            return null;
        },
    });
})
<|endoftext|>


<commit_before>#!/usr/bin/env node

var _ = require('lodash-node');
var child_process = require('child_process');
var Command = require('commander').Command;
var crayon = require('@ccheever/crayon');
var glob = require('glob');
var instapromise = require('instapromise');
var path = require('path');
var program = require('commander');

var log = require('./log');
var update = require('./update');
var urlOpts = require('./urlOpts');

Command.prototype.urlOpts = function () {
  urlOpts.addOptions(this);
  return this;
};

Command.prototype.asyncAction = function (asyncFn) {
  return this.action(async (...args) => {
    try {
      let result = await asyncFn(...args);
    } catch (err) {
     if (err._isCommandError) {
       if (false) {
         log.error(crayon.orange.bold(err.code) + ' ' + crayon.red(err.message));
       } else {
         log.error(err.message);
       }
     } else if (err._isApiError) {
       log.error(crayon.red(err.message));
     } else {
       log.error(err.message);
       crayon.gray.error(err.stack);
     }
   }
  });
}

Command.prototype.asyncActionProjectDir = function (asyncFn) {
  return this.asyncAction(async (projectDir, ...args) => {
    if (!projectDir) {
      projectDir = process.cwd();
    }

    return asyncFn(projectDir, ...args);
  });
}

async function runAsync() {
  try {
    program.name = 'exp';
    program.version(require('../package.json').version);
    glob.sync('commands/*.js', {
      cwd: __dirname,
    }).forEach(file => {
      require('./' + file)(program);
    });

    program.parse(process.argv);

    let subCommand = process.argv[2];
    if (subCommand) {
      let commands = _.map(program.commands, '_name');
      if (!_.includes(commands, subCommand)) {
        console.log(`"${subCommand}" is not an exp command. See "exp --help" for the full list of commands.`);
      }
    } else {
      program.help();
    }
  } catch (e) {
    console.error(e);
  }
}

async function checkForUpdateAsync() {
  let checkForUpdate = await update.checkForExpUpdateAsync();
  switch (checkForUpdate.state) {
    case 'up-to-date':
      break;
    case 'out-of-date':
      crayon.green.error(checkForUpdate.message);
      break;
    case 'ahead-of-published':
      crayon.cyan.error(checkForUpdate.message);
      break;
    case 'deprecated':
      crayon.yellow.bold.error(checkForUpdate.message);
      break;
    default:
      log.error("Confused about what version of exp you have?");
  }
}

if (require.main === module) {
  Promise.all([
    runAsync(),
    checkForUpdateAsync(),
  ]);
}
<commit_msg>Add option to change server url<commit_after>#!/usr/bin/env node

var _ = require('lodash-node');
var child_process = require('child_process');
var Command = require('commander').Command;
var crayon = require('@ccheever/crayon');
var glob = require('glob');
var instapromise = require('instapromise');
var path = require('path');
var program = require('commander');
var url = require('url');

import {
  Config,
} from 'xdl';

var log = require('./log');
var update = require('./update');
var urlOpts = require('./urlOpts');

Command.prototype.urlOpts = function () {
  urlOpts.addOptions(this);
  return this;
};

Command.prototype.asyncAction = function (asyncFn) {
  return this.action(async (...args) => {
    try {
      let result = await asyncFn(...args);
    } catch (err) {
     if (err._isCommandError) {
       if (false) {
         log.error(crayon.orange.bold(err.code) + ' ' + crayon.red(err.message));
       } else {
         log.error(err.message);
       }
     } else if (err._isApiError) {
       log.error(crayon.red(err.message));
     } else {
       log.error(err.message);
       crayon.gray.error(err.stack);
     }
   }
  });
}

Command.prototype.asyncActionProjectDir = function (asyncFn) {
  return this.asyncAction(async (projectDir, ...args) => {
    if (!projectDir) {
      projectDir = process.cwd();
    }

    return asyncFn(projectDir, ...args);
  });
}

async function runAsync() {
  try {
    if (process.env.SERVER_URL) {
      let serverUrl = process.env.SERVER_URL;
      if (!serverUrl.startsWith('http')) {
        serverUrl = 'http://' + serverUrl;
      }
      let parsedUrl = url.parse(serverUrl);
      Config.api.host = parsedUrl.hostname;
      Config.api.port = parsedUrl.port;
    }

    program.name = 'exp';
    program.version(require('../package.json').version);
    glob.sync('commands/*.js', {
      cwd: __dirname,
    }).forEach(file => {
      require('./' + file)(program);
    });

    program.parse(process.argv);

    let subCommand = process.argv[2];
    if (subCommand) {
      let commands = _.map(program.commands, '_name');
      if (!_.includes(commands, subCommand)) {
        console.log(`"${subCommand}" is not an exp command. See "exp --help" for the full list of commands.`);
      }
    } else {
      program.help();
    }
  } catch (e) {
    console.error(e);
  }
}

async function checkForUpdateAsync() {
  let checkForUpdate = await update.checkForExpUpdateAsync();
  switch (checkForUpdate.state) {
    case 'up-to-date':
      break;
    case 'out-of-date':
      crayon.green.error(checkForUpdate.message);
      break;
    case 'ahead-of-published':
      crayon.cyan.error(checkForUpdate.message);
      break;
    case 'deprecated':
      crayon.yellow.bold.error(checkForUpdate.message);
      break;
    default:
      log.error("Confused about what version of exp you have?");
  }
}

if (require.main === module) {
  Promise.all([
    runAsync(),
    checkForUpdateAsync(),
  ]);
}
<|endoftext|>


<commit_before>'use strict';

angular.module('ddsApp').controller('FoyerLogementCtrl', function($scope, $http, logementTypes, situation) {
    $scope.situation = situation;

    if (!situation.logement) {
        situation.logement = {};
    }
    if (!situation.logement.adresse) {
        situation.logement.adresse = {};
    }

    $scope.logementTypes = logementTypes;
    $scope.locationTypes = _.find(logementTypes, { id: 'locataire' }).locationTypes;

    $scope.locationTypeLabel = function() {
        return _.find($scope.locationTypes, { id: situation.logement.locationType }).label;
    };

    $scope.logementTypeLabel = function() {
        return _.find(logementTypes, { id: situation.logement.type }).label;
    };

    $scope.loyerLabel = function() {
        return 'proprietaire' === situation.logement.type ? 'mensualité d\'emprunt' : 'loyer';
    };

    $scope.primoAccedantTooltip = 'Un primo-accédant est une personne (ou un ménage) qui n’a pas été propriétaire de sa résidence principale dans les deux années qui viennent de s’écouler.';

    $scope.updateCities = function() {
        $scope.cities = [];
        var codePostal = situation.logement.adresse.codePostal;
        if (9999 < codePostal && 100000 > codePostal) {
            var baseApi = '//public.opendatasoft.com/api/records/1.0/search?dataset=correspondance-code-insee-code-postal&format=jsonp&callback=JSON_CALLBACK&q=';
            $http.jsonp(baseApi + situation.logement.adresse.codePostal).then(function(result) {
                $scope.cities = [];
                result.data.records.forEach(function(record) {
                    var field = 'nom_comm';
                    $scope.cities.push(record.fields[field]);
                });
                situation.logement.adresse.ville = $scope.cities[0];
            });
        } else {
            $scope.situation.logement.adresse.ville = null;
        }
    };

    $scope.submit = function() {
        situation.logement.formCompleted = true;
    };
});
<commit_msg>fix bug liste incomplète des villes sélectionnables pour l'adresse du logement<commit_after>'use strict';

angular.module('ddsApp').controller('FoyerLogementCtrl', function($scope, $http, logementTypes, situation) {
    $scope.situation = situation;

    if (!situation.logement) {
        situation.logement = {};
    }
    if (!situation.logement.adresse) {
        situation.logement.adresse = {};
    }

    $scope.logementTypes = logementTypes;
    $scope.locationTypes = _.find(logementTypes, { id: 'locataire' }).locationTypes;

    $scope.locationTypeLabel = function() {
        return _.find($scope.locationTypes, { id: situation.logement.locationType }).label;
    };

    $scope.logementTypeLabel = function() {
        return _.find(logementTypes, { id: situation.logement.type }).label;
    };

    $scope.loyerLabel = function() {
        return 'proprietaire' === situation.logement.type ? 'mensualité d\'emprunt' : 'loyer';
    };

    $scope.primoAccedantTooltip = 'Un primo-accédant est une personne (ou un ménage) qui n’a pas été propriétaire de sa résidence principale dans les deux années qui viennent de s’écouler.';

    $scope.updateCities = function() {
        $scope.cities = [];
        var codePostal = situation.logement.adresse.codePostal;
        if (9999 < codePostal && 100000 > codePostal) {
            var baseApi = '//public.opendatasoft.com/api/records/1.0/search?dataset=correspondance-code-insee-code-postal&format=jsonp&callback=JSON_CALLBACK&rows=1000&q=';
            $http.jsonp(baseApi + situation.logement.adresse.codePostal).then(function(result) {
                $scope.cities = [];
                result.data.records.forEach(function(record) {
                    var field = 'nom_comm';
                    $scope.cities.push(record.fields[field]);
                });
                situation.logement.adresse.ville = $scope.cities[0];
            });
        } else {
            $scope.situation.logement.adresse.ville = null;
        }
    };

    $scope.submit = function() {
        situation.logement.formCompleted = true;
    };
});
<|endoftext|>


<commit_before>/*global gyrocopter */
(function () {
'use strict';

/**
 * The main controller for the app.
 */
gyrocopter.controller('gyrocopterCtrl', function mainCtrl($scope, Browser) {

  $scope.platforms = Browser.getPlatforms();

  $scope.selected = $scope.platforms[0].browsers[0];
  $scope.selectBrowser = function(browser){
    $scope.selected = browser;
    $scope.updateAxes();
    $scope.saveData();
  };

  $scope.updateAxes = function(){
    var rotation = $scope.css.transform.match(/-?(\d+)/g);
    console.log(rotation);
  };

  $scope.setDefaultRotation = function(){
    $scope.rotateDevice();
  };

  /**
   * Compute methods
   */

  $scope.getRange = function(max, min){
    return Math.abs(max - min);
  };

  $scope.getAlphaRotation = function(){
    var alpha = $scope.alpha;
    return alpha;
  };

  $scope.getBetaRotation = function(){
    var beta = $scope.beta - 180;
    var range = $scope.getRange($scope.selected.rotation.beta.max, $scope.selected.rotation.beta.min);

    if (range === 180) {
      if (beta > 90) {
        return (90 - beta + 90);
      }
      if (beta < -90) {
        return -1 * (90 + beta + 90);
      }
    }

    return beta;
  };

  $scope.getGammaRotation = function(){
    var gamma = $scope.gamma - 180;

    var range = $scope.getRange($scope.selected.rotation.gamma.max, $scope.selected.rotation.gamma.min);

    if (range === 180) {
      if (gamma > 90) {
        return (gamma - 180);
      }
      if (gamma <= -90) {
        return (gamma + 180);
      }
    }

    if (gamma < -90 && $scope.selected.rotation.gamma.min > 180) {
      gamma = $scope.selected.rotation.gamma.min + gamma + 90;
    }

    return gamma;
  };

  /**
   * Rotation methods
   */

  var prettyRotate = function(val){
    if (val > 360) {
      return val - 360;
    }

    if (val < -360) {
      return val + 360;
    }

    return val;
  };

  $scope.rotateDevice = function(){
    var alpha = $scope.alpha;
    var beta = $scope.beta;
    var gamma = $scope.gamma;
    var alphaMult = $scope.selected.rotation.alpha.reverse ? -1 : 1;
    var betaMult = $scope.selected.rotation.beta.reverse ? -1 : 1;
    var gammaMult = $scope.selected.rotation.gamma.reverse ? -1 : 1;

    $scope.css = {};

    var a = - alpha * alphaMult;
    var b = betaMult > 0 ? (- beta + 90 - 180) * betaMult : (- beta + 90 - 180) * betaMult - 180;
    var c = gammaMult > 0 ? - (- gamma - 180) * gammaMult : - (- gamma - 180) * gammaMult;

    a = prettyRotate(a);
    b = prettyRotate(b);
    c = prettyRotate(c);

    $scope.css['transform'] = 'rotateX(' + b + 'deg)' + 'rotateY(' + c + 'deg)' + 'rotateZ(' + a + 'deg)';
    $scope.css['-webkit-transform'] = 'rotateX(' + b + 'deg)' + 'rotateY(' + c + 'deg)' + 'rotateZ(' + a + 'deg)';

    sendJS($scope.getAlphaRotation($scope.alpha), $scope.getBetaRotation($scope.beta), $scope.getGammaRotation($scope.gamma));
  }

  // $scope.rotate = function(alpha, beta, gamma){
  //   $scope.css = {};

  //   var a = 360 - alpha;
  //   var b = - beta + 90;
  //   var c = gamma;

  //   $scope.css['transform'] = 'rotateX(' + b + 'deg)' + 'rotateY(' + c + 'deg)' + 'rotateZ(' + a + 'deg)';
  //   $scope.css['-webkit-transform'] = 'rotateX(' + b + 'deg)' + 'rotateY(' + c + 'deg)' + 'rotateZ(' + a + 'deg)';
  // };

  $scope.saveData = function(){
    chrome.storage.local.set({'alpha': $scope.alpha, 'beta': $scope.beta, 'gamma': $scope.gamma, 'browser': JSON.stringify($scope.selected)}, function() {
      console.log('saved');
    });
  };

  chrome.storage.local.get(['alpha', 'beta', 'gamma', 'browser'], function(storage){
    console.log(storage);
    $scope.alpha = Number(storage.alpha) || 0;
    $scope.beta = Number(storage.beta) || 270;
    $scope.gamma = Number(storage.gamma) || 180;
    $scope.selected = JSON.parse(storage.browser || '{}');
    if (!$scope.selected.id) {
      $scope.selected = $scope.platforms[0].browsers[0];
    }
    $scope.rotateDevice();
    $scope.$apply();
  });

  /**
   * Dispatches a DeviceOrientation Event
   * @param  {double?} alpha    Rotate the device frame around its z axis by alpha degrees, with alpha in [0, 360).
   * @param  {double?} beta     Rotate the device frame around its x axis by beta degrees, with beta in [-180, 180).
   * @param  {double?} gamma    Rotate the device frame around its y axis by gamma degrees, with gamma in [-90, 90).
   * @param  {boolean} absolute Indicates absolute values for the three angles or relative to some arbitrary orientation.
   */

  var sendJS = function(alpha, beta, gamma, absolute){
    console.log(alpha, beta, gamma);

    var a = alpha;
    var b = beta;
    var c = gamma;
    absolute = true;
    // var event = document.createEvent("DeviceOrientationEvent");
    // event.initDeviceOrientationEvent("deviceorientation", false, false, alpha, beta, gamma, absolute);
    // window.dispatchEvent(event);

    var js = '';
    js += 'var event = document.createEvent("DeviceOrientationEvent");';
    js += 'event.initDeviceOrientationEvent("deviceorientation", false, false, ' + a + ', ' + b + ', ' + c + ', ' + absolute + ');';
    js += 'window.dispatchEvent(event);';

    chrome.tabs.executeScript({
      code: js
    });
  };

  $scope.reset = function(){
    $scope.alpha = 0;
    $scope.beta = 270;
    $scope.gamma = 180;
    $scope.rotateDevice();
    $scope.saveData();
  };

  var STEPPER = 0.5;

  $scope.compute = function(next, direction, min, max){
    if (direction === 'left') {
      next -= STEPPER;
    }
    else {
      next += STEPPER;
    }

    if (next < min) {
      next = max - STEPPER;
    }
    else if (next >= max) {
      next = min;
    }

    return next;
  };

  $scope.stepAlpha = function(direction){
    var next =  $scope.compute(Number($scope.alpha), direction, 0, 359.5);
    $scope.alpha = next;
    $scope.rotateDevice()
    $scope.saveData();
  };

  $scope.stepBeta = function(direction){
    var next =  $scope.compute(Number($scope.beta), direction, 0.5, 360);
    $scope.beta = next;
    $scope.rotateDevice()
    $scope.saveData();
  };

  $scope.stepGamma = function(direction){
    var next =  $scope.compute(Number($scope.gamma), direction, 0, 359.5);
    $scope.gamma = next;
    $scope.rotateDevice()
    $scope.saveData();
  };
});

})();
<commit_msg>get rotation values<commit_after>/*global gyrocopter */
(function () {
'use strict';

/**
 * The main controller for the app.
 */
gyrocopter.controller('gyrocopterCtrl', function mainCtrl($scope, Browser) {

  $scope.platforms = Browser.getPlatforms();

  $scope.selected = $scope.platforms[0].browsers[0];
  $scope.selectBrowser = function(browser){
    $scope.selected = browser;
    $scope.updateAxes();
    $scope.saveData();
  };

  $scope.updateAxes = function(){
    var rotation = $scope.css.transform.match(/-?(\d+)(\.(\d+))?/g);

    console.log($scope.css.transform);
    console.log(rotation);

    var b = Number(rotation[0]);
    var c = Number(rotation[1]);
    var a = Number(rotation[2]);

    var alphaMult = $scope.selected.rotation.alpha.reverse ? -1 : 1;
    var betaMult = $scope.selected.rotation.beta.reverse ? -1 : 1;
    var gammaMult = $scope.selected.rotation.gamma.reverse ? -1 : 1;

    console.log([$scope.alpha, $scope.beta, $scope.gamma]);
    $scope.alpha = - (a/alphaMult);
    $scope.beta = betaMult > 0 ? - (b/betaMult) + 90 - 180 : - ((b - 180)/betaMult) + 90 - 180;
    $scope.gamma = (c/gammaMult) - 180;
    console.log([$scope.alpha, $scope.beta, $scope.gamma]);
  };

  $scope.setDefaultRotation = function(){
    $scope.rotateDevice();
  };

  /**
   * Compute methods
   */

  $scope.getRange = function(max, min){
    return Math.abs(max - min);
  };

  $scope.getAlphaRotation = function(){
    var alpha = $scope.alpha;
    return alpha;
  };

  $scope.getBetaRotation = function(){
    var beta = $scope.beta - 180;
    var range = $scope.getRange($scope.selected.rotation.beta.max, $scope.selected.rotation.beta.min);

    if (range === 180) {
      if (beta > 90) {
        return (90 - beta + 90);
      }
      if (beta < -90) {
        return -1 * (90 + beta + 90);
      }
    }

    return beta;
  };

  $scope.getGammaRotation = function(){
    var gamma = $scope.gamma - 180;

    var range = $scope.getRange($scope.selected.rotation.gamma.max, $scope.selected.rotation.gamma.min);

    if (range === 180) {
      if (gamma > 90) {
        return (gamma - 180);
      }
      if (gamma <= -90) {
        return (gamma + 180);
      }
    }

    if (gamma < -90 && $scope.selected.rotation.gamma.min > 180) {
      gamma = $scope.selected.rotation.gamma.min + gamma + 90;
    }

    return gamma;
  };

  /**
   * Rotation methods
   */

  var prettyRotate = function(val){
    if (val > 360) {
      return val - 360;
    }

    if (val < -360) {
      return val + 360;
    }

    return val;
  };

  $scope.rotateDevice = function(){
    var alpha = $scope.alpha;
    var beta = $scope.beta;
    var gamma = $scope.gamma;
    var alphaMult = $scope.selected.rotation.alpha.reverse ? -1 : 1;
    var betaMult = $scope.selected.rotation.beta.reverse ? -1 : 1;
    var gammaMult = $scope.selected.rotation.gamma.reverse ? -1 : 1;

    $scope.css = {};

    var a = - alpha * alphaMult;
    var b = betaMult > 0 ? (- beta + 90 - 180) * betaMult : (- beta + 90 - 180) * betaMult - 180;
    var c = - (- gamma - 180) * gammaMult;

    a = prettyRotate(a);
    b = prettyRotate(b);
    c = prettyRotate(c);

    $scope.css['transform'] = 'rotateX(' + b + 'deg)' + 'rotateY(' + c + 'deg)' + 'rotateZ(' + a + 'deg)';
    $scope.css['-webkit-transform'] = 'rotateX(' + b + 'deg)' + 'rotateY(' + c + 'deg)' + 'rotateZ(' + a + 'deg)';

    sendJS($scope.getAlphaRotation($scope.alpha), $scope.getBetaRotation($scope.beta), $scope.getGammaRotation($scope.gamma));
  }

  $scope.saveData = function(){
    chrome.storage.local.set({'alpha': $scope.alpha, 'beta': $scope.beta, 'gamma': $scope.gamma, 'browser': JSON.stringify($scope.selected)}, function() {
      console.log('saved');
    });
  };

  chrome.storage.local.get(['alpha', 'beta', 'gamma', 'browser'], function(storage){
    console.log(storage);
    $scope.alpha = Number(storage.alpha) || 0;
    $scope.beta = Number(storage.beta) || 270;
    $scope.gamma = Number(storage.gamma) || 180;
    $scope.selected = JSON.parse(storage.browser || '{}');
    if (!$scope.selected.id) {
      $scope.selected = $scope.platforms[0].browsers[0];
    }
    $scope.rotateDevice();
    $scope.$apply();
  });

  /**
   * Dispatches a DeviceOrientation Event
   * @param  {double?} alpha    Rotate the device frame around its z axis by alpha degrees, with alpha in [0, 360).
   * @param  {double?} beta     Rotate the device frame around its x axis by beta degrees, with beta in [-180, 180).
   * @param  {double?} gamma    Rotate the device frame around its y axis by gamma degrees, with gamma in [-90, 90).
   * @param  {boolean} absolute Indicates absolute values for the three angles or relative to some arbitrary orientation.
   */

  var sendJS = function(alpha, beta, gamma, absolute){
    console.log(alpha, beta, gamma);

    var a = alpha;
    var b = beta;
    var c = gamma;
    absolute = true;
    // var event = document.createEvent("DeviceOrientationEvent");
    // event.initDeviceOrientationEvent("deviceorientation", false, false, alpha, beta, gamma, absolute);
    // window.dispatchEvent(event);

    var js = '';
    js += 'var event = document.createEvent("DeviceOrientationEvent");';
    js += 'event.initDeviceOrientationEvent("deviceorientation", false, false, ' + a + ', ' + b + ', ' + c + ', ' + absolute + ');';
    js += 'window.dispatchEvent(event);';

    chrome.tabs.executeScript({
      code: js
    });
  };

  $scope.reset = function(){
    $scope.alpha = 0;
    $scope.beta = 270;
    $scope.gamma = 180;
    $scope.rotateDevice();
    $scope.saveData();
  };

  var STEPPER = 0.5;

  $scope.compute = function(next, direction, min, max){
    if (direction === 'left') {
      next -= STEPPER;
    }
    else {
      next += STEPPER;
    }

    if (next < min) {
      next = max - STEPPER;
    }
    else if (next >= max) {
      next = min;
    }

    return next;
  };

  $scope.stepAlpha = function(direction){
    var next =  $scope.compute(Number($scope.alpha), direction, 0, 359.5);
    $scope.alpha = next;
    $scope.rotateDevice()
    $scope.saveData();
  };

  $scope.stepBeta = function(direction){
    var next =  $scope.compute(Number($scope.beta), direction, 0.5, 360);
    $scope.beta = next;
    $scope.rotateDevice()
    $scope.saveData();
  };

  $scope.stepGamma = function(direction){
    var next =  $scope.compute(Number($scope.gamma), direction, 0, 359.5);
    $scope.gamma = next;
    $scope.rotateDevice()
    $scope.saveData();
  };
});

})();
<|endoftext|>


<commit_before>'use strict';

angular.module('gisto.directive.editor', []).directive('editor', ['$timeout', 'appSettings', function ($timeout, appSettings) {
    return {
        restrict: 'E',
        template: '

' +
        '
{{file.content}}
' +
        '

',
        link: function ($scope, $element, $attrs) {
            $scope.showmd = false;
            if ($attrs.language === 'markdown') {
                $scope.showmd = true;
            }

            appSettings.loadSettings().then(function (appSettingsResult) {

                $timeout(function () {

                    var lang = $attrs.language,
                        font = parseInt(appSettingsResult.font_size),
                        indexed = $attrs.index,
                        editor = ace.edit($element.find('pre')[0]),
                        session = editor.getSession(),
                        theme = $attrs.theme,
                        inUpdateProcess = false;

                    // Emmet
                    if (lang === 'html' && appSettingsResult.editor_ext.emmet) {
                        console.log('Emmet should be loaded');
                        ace.require("ace/ext/emmet");
                        editor.setOptions({
                            enableEmmet: true
                        });
                    } else {
                        editor.setOptions({
                            enableEmmet: false
                        });
                    }

                    // Auto-completion
                    if (appSettingsResult.editor_ext.emmet) {
                        console.log('language tools should be loaded');
                        ace.require("ace/ext/language_tools");
                        editor.setOptions({
                            enableBasicAutocompletion: true,
                            enableSnippets: true
                        });
                    }
                    // Status bar
                    if (appSettingsResult.editor_ext.statusbar) {
                        var StatusBar = ace.require('ace/ext/statusbar').StatusBar;
                        var statusBar = new StatusBar(editor, document.getElementById('statusBar-' + $attrs.index));
                    }

                    // VIM mode
                    if(appSettingsResult.editor_vim_mode) {
                        editor.setKeyboardHandler("ace/keyboard/vim");
                    }

                    // word wrap
                    if(appSettingsResult.editor_word_wrap) {
                        editor.getSession().setUseWrapMode(true);
                    }

                    editor.setTheme("ace/theme/" + theme);
                    editor.getSession().setMode("ace/mode/" + lang);
                    editor.setFontSize(font);
                    editor.setShowPrintMargin(false);
                    editor.renderer.setShowGutter(true);
                    editor.setAutoScrollEditorIntoView(true);
                    var maxLinesSettings = appSettingsResult.max_lines.toString();
                    var minLinesSettings = (appSettingsResult.min_lines !== 0) ? appSettingsResult.min_lines.toString() : editor.session.getLength().toString();
                    editor.setOption("maxLines", maxLinesSettings);
                    editor.setOption("minLines", minLinesSettings);
                    editor.resize(true);

                    console.log('language:', lang);
                    console.log('Theme:', theme);
                    console.log('Font size:', font);
                    console.log('renderer.lineHeight', editor.renderer.lineHeight);
                    console.log('# of LINES', editor.session.getLength());
                    console.log('max_lines', appSettingsResult.max_lines);
                    console.log('min_lines', appSettingsResult.min_lines);

                    editor.on('paste', function(text) {
                        // delay the change event to the end of the call stack
                        // and fire a change event with an extra parameter indicating
                        // that this is a paste event and continue to update the reference
                        // to angular file model.
                        $timeout(function() {
                            editor._emit('change', {target: editor, pasteEvent: true});
                        },0);

                    });

                    editor.on('change', function (data) {

                        // change coming from manually changing the value using the api
                        // skip the update
                        if (inUpdateProcess) {
                            return;
                        }

                        // only react to user actions
                        if (data.pasteEvent || editor.curOp && editor.curOp.command.name) {
                            $scope.$apply(function () {
                                $scope.file.content = editor.getValue();
                                if (!$scope.edit) {
                                    $scope.enableEdit();
                                }
                            });
                        }
                    });

                    // listen to ngModel render and update the session
                    $scope.$on('ace-update', function (e, updatedFile) {
                        if ($scope.file.filename === updatedFile) {
                            inUpdateProcess = true;
                            session.setValue($scope.file.content);
                            inUpdateProcess = false;
                        }
                    });

                }, 0);
            });
        }

    };
}]);<commit_msg>FIX (editor): Add element matching by class rather than element to prevent mismatched elements<commit_after>'use strict';

angular.module('gisto.directive.editor', []).directive('editor', ['$timeout', 'appSettings', function ($timeout, appSettings) {
    return {
        restrict: 'E',
        template: '

' +
        '
{{file.content}}
' +
        '

',
        link: function ($scope, $element, $attrs) {
            $scope.showmd = false;
            if ($attrs.language === 'markdown') {
                $scope.showmd = true;
            }

            appSettings.loadSettings().then(function (appSettingsResult) {

                $timeout(function () {

                    var lang = $attrs.language,
                        font = parseInt(appSettingsResult.font_size),
                        indexed = $attrs.index,
                        editor = ace.edit($element.find('.editor')[0]),
                        session = editor.getSession(),
                        theme = $attrs.theme,
                        inUpdateProcess = false;

                    // Emmet
                    if (lang === 'html' && appSettingsResult.editor_ext.emmet) {
                        console.log('Emmet should be loaded');
                        ace.require("ace/ext/emmet");
                        editor.setOptions({
                            enableEmmet: true
                        });
                    } else {
                        editor.setOptions({
                            enableEmmet: false
                        });
                    }

                    // Auto-completion
                    if (appSettingsResult.editor_ext.emmet) {
                        console.log('language tools should be loaded');
                        ace.require("ace/ext/language_tools");
                        editor.setOptions({
                            enableBasicAutocompletion: true,
                            enableSnippets: true
                        });
                    }
                    // Status bar
                    if (appSettingsResult.editor_ext.statusbar) {
                        var StatusBar = ace.require('ace/ext/statusbar').StatusBar;
                        var statusBar = new StatusBar(editor, document.getElementById('statusBar-' + $attrs.index));
                    }

                    // VIM mode
                    if(appSettingsResult.editor_vim_mode) {
                        editor.setKeyboardHandler("ace/keyboard/vim");
                    }

                    // word wrap
                    if(appSettingsResult.editor_word_wrap) {
                        editor.getSession().setUseWrapMode(true);
                    }

                    editor.setTheme("ace/theme/" + theme);
                    editor.getSession().setMode("ace/mode/" + lang);
                    editor.setFontSize(font);
                    editor.setShowPrintMargin(false);
                    editor.renderer.setShowGutter(true);
                    editor.setAutoScrollEditorIntoView(true);
                    var maxLinesSettings = appSettingsResult.max_lines.toString();
                    var minLinesSettings = (appSettingsResult.min_lines !== 0) ? appSettingsResult.min_lines.toString() : editor.session.getLength().toString();
                    editor.setOption("maxLines", maxLinesSettings);
                    editor.setOption("minLines", minLinesSettings);
                    editor.resize(true);

                    console.log('language:', lang);
                    console.log('Theme:', theme);
                    console.log('Font size:', font);
                    console.log('renderer.lineHeight', editor.renderer.lineHeight);
                    console.log('# of LINES', editor.session.getLength());
                    console.log('max_lines', appSettingsResult.max_lines);
                    console.log('min_lines', appSettingsResult.min_lines);

                    editor.on('paste', function(text) {
                        // delay the change event to the end of the call stack
                        // and fire a change event with an extra parameter indicating
                        // that this is a paste event and continue to update the reference
                        // to angular file model.
                        $timeout(function() {
                            editor._emit('change', {target: editor, pasteEvent: true});
                        },0);

                    });

                    editor.on('change', function (data) {

                        // change coming from manually changing the value using the api
                        // skip the update
                        if (inUpdateProcess) {
                            return;
                        }

                        // only react to user actions
                        if (data.pasteEvent || editor.curOp && editor.curOp.command.name) {
                            $scope.$apply(function () {
                                $scope.file.content = editor.getValue();
                                if (!$scope.edit) {
                                    $scope.enableEdit();
                                }
                            });
                        }
                    });

                    // listen to ngModel render and update the session
                    $scope.$on('ace-update', function (e, updatedFile) {
                        if ($scope.file.filename === updatedFile) {
                            inUpdateProcess = true;
                            session.setValue($scope.file.content);
                            inUpdateProcess = false;
                        }
                    });

                }, 0);
            });
        }

    };
}]);<|endoftext|>


<commit_before>'use strict';

/* Query All Feeds From DB Service */

mftApp.factory('SingleFeed', ['$resource', function($resource) {
	//var getFeed = $resource('JSON/feeds.json', {id:'@id', status:'@status', interface:'@interface'},
	var getFeed = $resource('http://dev.bigcompass.com\:2222/rest/AaronL/SingleFeed/:id', {id:'@ID'},
	{ post: {method: 'POST'},
	get: {method: 'GET'},
	update: {method:'PUT', transformRequest: function(data, headersGetter)},
	query: {method:'GET', isArray:false}});
	return getFeed;
}]);<commit_msg>Feed Edit<commit_after>'use strict';

/* Query All Feeds From DB Service */

mftApp.factory('SingleFeed', ['$resource', function($resource) {
	//var getFeed = $resource('JSON/feeds.json', {id:'@id', status:'@status', interface:'@interface'},
	var getFeed = $resource('http://dev.bigcompass.com\:2222/rest/AaronL/SingleFeed/:id', {id:'@ID'},
	{ post: {method: 'POST'},
	get: {method: 'GET'},
	update: {method:'PUT', params:{active:'@IS_ACTIVE'}, transformRequest:function(data, headersGetter);},
	query: {method:'GET', isArray:false}});
	return getFeed;
}]);<|endoftext|>


<commit_before>var exec = require('child_process').exec;
var spawn = require('child_process').spawn;
var forever = require('forever');
var util = require('util');
var config = require(__dirname+'/../config/config.js');

function GatewayProcessManager() {

  this.processNames = [
    "deposits",
    "outgoing",
    "incoming",
    "withdrawals",
    "server"
  ];

  this.processes = {};

}

GatewayProcessManager.prototype.start = function(opts) {
  if (!opts) { opts = {}; };

  var manager = this;

  var processNames = opts.processes || manager.processNames;

  processNames.forEach(function(name) {
    exec('pm2 --cron "0 * * * *" start '+ __dirname+'/../processes/'+name+'.js --name '+name);
  });

  if (config.get('WITHDRAWALS_CALLBACK_URL')) {
    exec('pm2 --cron "0 * * * *" start '+ __dirname+'/../processes/withdrawal_callbacks.js --name callbacks');
  }

  if (config.get('RIPPLE_REST_PATH')) {
    var path = config.get('RIPPLE_REST_PATH');
    exec('pm2 --cron "0 * * * *" start '+path+'/server.js --name ripplerest');
  }

  util.puts('Starting gateway processes and running `pm2 list`...');
  setTimeout(function(){
    pm2 = spawn('pm2', ['list']);
    pm2.stdout.on('data', function (data) {
      util.puts(data.toString());
    });
  }, 3000);
}

GatewayProcessManager.prototype.stop = function(opts) {
  if (!opts) { opts = {}; };

  var manager = this;

  var processNames = opts.processes || manager.processNames;

  processNames.forEach(function(name) {

    exec('pm2 stop '+ __dirname+'/../../processes/'+name+'.js');

  });

  util.puts('Stopping gateway processes and running `pm2 list`...');
  setTimeout(function(){
    pm2 = spawn('pm2', ['list']);
    pm2.stdout.on('data', function (data) {
      util.puts(data.toString());
    });
  }, 3000);
}

GatewayProcessManager.prototype.restart = function(opts) {
  if (!opts) { opts = {}; };

  var manager = this;

  var processNames = opts.processes || manager.processNames;

  processNames.forEach(function(name) {

    exec('pm2 restart '+ __dirname+'/../../processes/'+name+'.js');

  });

  util.puts('Restarting gateway processes and running `pm2 list`...');
  setTimeout(function(){
    pm2 = spawn('pm2', ['list']);
    pm2.stdout.on('data', function (data) {
      util.puts(data.toString());
    });
  }, 3000);
}

GatewayProcessManager.prototype.listProcesses = function(opts, fn) {
  var command;
  if (typeof opts == 'function'){
    fn = opts;
    opts = { json: true }
  }

  if (opts.json){
    command = 'prettylist';
  } else {
    command = 'list';
  }

  var output = "";
  var pm2 = exec('pm2 '+command);

  pm2.stdout.on('data', function (data) {
    output += data;
  });

  pm2.on('close', function (code) {
    if (opts.json){
      fn(null, output);
    } else {
      fn(null, output);
    }
  });
};

module.exports = GatewayProcessManager;

<commit_msg>[CHORE] pass callback on process start<commit_after>var exec = require('child_process').exec;
var spawn = require('child_process').spawn;
var forever = require('forever');
var util = require('util');
var config = require(__dirname+'/../config/config.js');

function GatewayProcessManager() {

  this.processNames = [
    "deposits",
    "outgoing",
    "incoming",
    "withdrawals",
    "server"
  ];

  this.processes = {};

}

GatewayProcessManager.prototype.start = function(opts, fn) {
  if (!opts) { opts = {}; };

  var manager = this;

  var processNames = opts.processes || manager.processNames;

  processNames.forEach(function(name) {
    exec('pm2 --cron "0 * * * *" start '+ __dirname+'/../processes/'+name+'.js --name '+name);
  });

  if (config.get('WITHDRAWALS_CALLBACK_URL')) {
    exec('pm2 --cron "0 * * * *" start '+ __dirname+'/../processes/withdrawal_callbacks.js --name callbacks');
  }

  if (config.get('RIPPLE_REST_PATH')) {
    var path = config.get('RIPPLE_REST_PATH');
    exec('pm2 --cron "0 * * * *" start '+path+'/server.js --name ripplerest');
  }

  util.puts('Starting gateway processes and running `pm2 list`...');
  setTimeout(function(){
    pm2 = spawn('pm2', ['list']);
    pm2.stdout.on('data', function (data) {
      util.puts(data.toString());
    });
  }, 3000);

  fn(null, processNames);
}

GatewayProcessManager.prototype.stop = function(opts) {
  if (!opts) { opts = {}; };

  var manager = this;

  var processNames = opts.processes || manager.processNames;

  processNames.forEach(function(name) {

    exec('pm2 stop '+ __dirname+'/../../processes/'+name+'.js');

  });

  util.puts('Stopping gateway processes and running `pm2 list`...');
  setTimeout(function(){
    pm2 = spawn('pm2', ['list']);
    pm2.stdout.on('data', function (data) {
      util.puts(data.toString());
    });
  }, 3000);
}

GatewayProcessManager.prototype.restart = function(opts) {
  if (!opts) { opts = {}; };

  var manager = this;

  var processNames = opts.processes || manager.processNames;

  processNames.forEach(function(name) {

    exec('pm2 restart '+ __dirname+'/../../processes/'+name+'.js');

  });

  util.puts('Restarting gateway processes and running `pm2 list`...');
  setTimeout(function(){
    pm2 = spawn('pm2', ['list']);
    pm2.stdout.on('data', function (data) {
      util.puts(data.toString());
    });
  }, 3000);
}

GatewayProcessManager.prototype.listProcesses = function(opts, fn) {
  var command;
  if (typeof opts == 'function'){
    fn = opts;
    opts = { json: true }
  }

  if (opts.json){
    command = 'prettylist';
  } else {
    command = 'list';
  }

  var output = "";
  var pm2 = exec('pm2 '+command);

  pm2.stdout.on('data', function (data) {
    output += data;
  });

  pm2.on('close', function (code) {
    if (opts.json){
      fn(null, output);
    } else {
      fn(null, output);
    }
  });
};

module.exports = GatewayProcessManager;

<|endoftext|>


<commit_before>'use strict';

angular.module('app')
    .controller('rgiNewAssessmentDialogCtrl', function (
        $scope,
        $route,
        $rootScope,
        $location,
        rgiAnswerMethodSrvc,
        rgiAssessmentMethodSrvc,
        rgiAssessmentSrvc,
        rgiCountrySrvc,
        rgiHttpResponseProcessorSrvc,
        rgiIdentitySrvc,
        MINERAL_TAGS_SET,
        rgiNotifier,
        rgiQuestionMethodSrvc,
        rgiQuestionSrvc,
        rgiUtilsSrvc
    ) {
        $scope.countries = rgiCountrySrvc.query({country_use: true});
        $scope.disable_button = false;
        //TODO
        //rgiCountrySrvc.query({}, function (countries) {
        //    var country_values = {},
        //        country_selector = [];
        //
        //    countries.forEach(function (el) {
        //        var add_obj = {value: el.iso2, name: el.country};
        //        country_values[el.iso2] = el;
        //        country_values[el.iso2].index = country_selector.length;
        //        country_selector.push(add_obj);
        //    });
        //    $scope.country_values = country_values;
        //    $scope.country_selector = country_selector;
        //});

        $scope.new_assessment = {
            year: $scope.year ? parseInt($scope.year) : '',
            version: $scope.version || '',
            assessment_countries: [{}]
        };

        var currentYear = new Date().getFullYear();
        $scope.years = [];

        for (var yearIncrement = 0; yearIncrement < 6; yearIncrement++) {
            $scope.years.push(currentYear + yearIncrement);
        }
        // TODO remove country from countries scope when added to new assessments
        $scope.addCountry = function () {
            $scope.new_assessment.assessment_countries.push({country: ''});
        };

        $scope.getAvailableMinerals = function() {
            return MINERAL_TAGS_SET;
        };

        $scope.deleteCountry = function (index) {
            $scope.new_assessment.assessment_countries.splice(index, 1);
        };

        $scope.deployAssessment = function () {
            if($scope.new_assessment.year === undefined) {
                return rgiNotifier.error('Please, select the assessment year');
            } else if($scope.new_assessment.version === undefined) {
                return rgiNotifier.error('Please, select the assessment version');
            } else if(($scope.new_assessment.version === 'mining') && ($scope.new_assessment.mineral === undefined)) {
                return rgiNotifier.error('Please, select the assessment mineral');
            }

            var countrySelected = true;

            $scope.new_assessment.assessment_countries.forEach(function(countryData) {
                if(!countryData.country) {
                    countrySelected = false;
                }
            });

            if(!countrySelected) {
                return rgiNotifier.error('Please, select the assessment country');
            }

            var new_assessment_ID, new_answer_set,
                new_assessment_set = [],
                new_assessment_year = String($scope.new_assessment.year),
                new_assessment_ver = $scope.new_assessment.version.slice(0, 2).toUpperCase(),
                timestamp = new Date().toISOString();

            $scope.disable_button = true;

            rgiAssessmentSrvc.query({year: new_assessment_year, version: $scope.new_assessment.version}, function (assessments) {
                var country_deployed = {value: false};

                assessments.forEach(function (assessment) {
                    $scope.new_assessment.assessment_countries.forEach(function(country) {
                        if (country.country.country===assessment.country) {
                            country_deployed.value = true;
                            country_deployed.country = assessment.country;
                        }
                    });
                });

                if (country_deployed.value) {
                    rgiNotifier.error(country_deployed.country + ' assessment already deployed');
                    $scope.disable_button = false;
                } else {
                    rgiQuestionSrvc.query({assessment_ID: 'base'}, function (questions) {
                        questions.forEach(function (question) {
                            if (question.assessments.indexOf(new_assessment_year + "-" + new_assessment_ver) < 0) {
                                question.assessments.push(new_assessment_year + "-" + new_assessment_ver);
                            }
                        });

                        $scope.new_assessment.assessment_countries.forEach(function (assessment_country) {
                            new_answer_set = [];

                            new_assessment_ID = assessment_country.country.iso2 + "-" + new_assessment_year + "-" + new_assessment_ver;

                            new_assessment_set.push({
                                assessment_ID: new_assessment_ID,
                                ISO3: assessment_country.country.country_ID,
                                year: $scope.new_assessment.year,
                                version: $scope.new_assessment.version,
                                mineral: $scope.new_assessment.mineral,
                                country: assessment_country.country.country,
                                created: {
                                    created_by: rgiIdentitySrvc.currentUser._id,
                                    created_date: timestamp}
                            });

                            questions.forEach(function (q) {
                                new_answer_set.push({
                                    answer_ID: new_assessment_ID + '-' + String(rgiUtilsSrvc.zeroFill(q.question_order, 3)),
                                    question_ID: q._id,
                                    question_trial: q.question_trial,
                                    assessment_ID: new_assessment_ID,
                                    year: new_assessment_year,
                                    version: new_assessment_ver,
                                    question_order: q.question_order,
                                    question_v: q.question_v + 1,
                                    last_modified: {modified_by: rgiIdentitySrvc.currentUser._id}
                                });
                            });
                            rgiAnswerMethodSrvc.insertAnswerSet(new_answer_set)
                                .then(function () {
                                }, function (reason) {rgiNotifier.error(reason);}
                            );
                        });

                        //send to mongo
                        rgiAssessmentMethodSrvc.createAssessment(new_assessment_set)
                            .then(rgiQuestionMethodSrvc.updateQuestionSet(questions))
                            .then(function () {
                                rgiNotifier.notify('Assessment deployed!');
                                $scope.closeThisDialog();
                                $route.reload();
                                $location.path('admin/assessment-admin');
                            }, function (reason) {
                                rgiNotifier.error(reason);
                            });
                    }, function(response) {
                        rgiHttpResponseProcessorSrvc.getDefaultHandler('Load question data failure')(response);
                        $scope.closeThisDialog();
                    });
                }
            }, function(response) {
                rgiHttpResponseProcessorSrvc.getDefaultHandler('Load assessment data failure')(response);
                $scope.closeThisDialog();
            });
        };
    });
<commit_msg>handle HTTP failures where the 'Country' service is used<commit_after>'use strict';

angular.module('app')
    .controller('rgiNewAssessmentDialogCtrl', function (
        $scope,
        $route,
        $rootScope,
        $location,
        rgiAnswerMethodSrvc,
        rgiAssessmentMethodSrvc,
        rgiAssessmentSrvc,
        rgiCountrySrvc,
        rgiHttpResponseProcessorSrvc,
        rgiIdentitySrvc,
        MINERAL_TAGS_SET,
        rgiNotifier,
        rgiQuestionMethodSrvc,
        rgiQuestionSrvc,
        rgiUtilsSrvc
    ) {
        rgiCountrySrvc.query({country_use: true}, function(countries) {
            $scope.countries = countries;
        }, function(response) {
            rgiHttpResponseProcessorSrvc.getDefaultHandler('Load country data failure')(response);
            $scope.closeThisDialog();
        });

        $scope.disable_button = false;
        //TODO
        //rgiCountrySrvc.query({}, function (countries) {
        //    var country_values = {},
        //        country_selector = [];
        //
        //    countries.forEach(function (el) {
        //        var add_obj = {value: el.iso2, name: el.country};
        //        country_values[el.iso2] = el;
        //        country_values[el.iso2].index = country_selector.length;
        //        country_selector.push(add_obj);
        //    });
        //    $scope.country_values = country_values;
        //    $scope.country_selector = country_selector;
        //});

        $scope.new_assessment = {
            year: $scope.year ? parseInt($scope.year) : '',
            version: $scope.version || '',
            assessment_countries: [{}]
        };

        var currentYear = new Date().getFullYear();
        $scope.years = [];

        for (var yearIncrement = 0; yearIncrement < 6; yearIncrement++) {
            $scope.years.push(currentYear + yearIncrement);
        }
        // TODO remove country from countries scope when added to new assessments
        $scope.addCountry = function () {
            $scope.new_assessment.assessment_countries.push({country: ''});
        };

        $scope.getAvailableMinerals = function() {
            return MINERAL_TAGS_SET;
        };

        $scope.deleteCountry = function (index) {
            $scope.new_assessment.assessment_countries.splice(index, 1);
        };

        $scope.deployAssessment = function () {
            if($scope.new_assessment.year === undefined) {
                return rgiNotifier.error('Please, select the assessment year');
            } else if($scope.new_assessment.version === undefined) {
                return rgiNotifier.error('Please, select the assessment version');
            } else if(($scope.new_assessment.version === 'mining') && ($scope.new_assessment.mineral === undefined)) {
                return rgiNotifier.error('Please, select the assessment mineral');
            }

            var countrySelected = true;

            $scope.new_assessment.assessment_countries.forEach(function(countryData) {
                if(!countryData.country) {
                    countrySelected = false;
                }
            });

            if(!countrySelected) {
                return rgiNotifier.error('Please, select the assessment country');
            }

            var new_assessment_ID, new_answer_set,
                new_assessment_set = [],
                new_assessment_year = String($scope.new_assessment.year),
                new_assessment_ver = $scope.new_assessment.version.slice(0, 2).toUpperCase(),
                timestamp = new Date().toISOString();

            $scope.disable_button = true;

            rgiAssessmentSrvc.query({year: new_assessment_year, version: $scope.new_assessment.version}, function (assessments) {
                var country_deployed = {value: false};

                assessments.forEach(function (assessment) {
                    $scope.new_assessment.assessment_countries.forEach(function(country) {
                        if (country.country.country===assessment.country) {
                            country_deployed.value = true;
                            country_deployed.country = assessment.country;
                        }
                    });
                });

                if (country_deployed.value) {
                    rgiNotifier.error(country_deployed.country + ' assessment already deployed');
                    $scope.disable_button = false;
                } else {
                    rgiQuestionSrvc.query({assessment_ID: 'base'}, function (questions) {
                        questions.forEach(function (question) {
                            if (question.assessments.indexOf(new_assessment_year + "-" + new_assessment_ver) < 0) {
                                question.assessments.push(new_assessment_year + "-" + new_assessment_ver);
                            }
                        });

                        $scope.new_assessment.assessment_countries.forEach(function (assessment_country) {
                            new_answer_set = [];

                            new_assessment_ID = assessment_country.country.iso2 + "-" + new_assessment_year + "-" + new_assessment_ver;

                            new_assessment_set.push({
                                assessment_ID: new_assessment_ID,
                                ISO3: assessment_country.country.country_ID,
                                year: $scope.new_assessment.year,
                                version: $scope.new_assessment.version,
                                mineral: $scope.new_assessment.mineral,
                                country: assessment_country.country.country,
                                created: {
                                    created_by: rgiIdentitySrvc.currentUser._id,
                                    created_date: timestamp}
                            });

                            questions.forEach(function (q) {
                                new_answer_set.push({
                                    answer_ID: new_assessment_ID + '-' + String(rgiUtilsSrvc.zeroFill(q.question_order, 3)),
                                    question_ID: q._id,
                                    question_trial: q.question_trial,
                                    assessment_ID: new_assessment_ID,
                                    year: new_assessment_year,
                                    version: new_assessment_ver,
                                    question_order: q.question_order,
                                    question_v: q.question_v + 1,
                                    last_modified: {modified_by: rgiIdentitySrvc.currentUser._id}
                                });
                            });
                            rgiAnswerMethodSrvc.insertAnswerSet(new_answer_set)
                                .then(function () {
                                }, function (reason) {rgiNotifier.error(reason);}
                            );
                        });

                        //send to mongo
                        rgiAssessmentMethodSrvc.createAssessment(new_assessment_set)
                            .then(rgiQuestionMethodSrvc.updateQuestionSet(questions))
                            .then(function () {
                                rgiNotifier.notify('Assessment deployed!');
                                $scope.closeThisDialog();
                                $route.reload();
                                $location.path('admin/assessment-admin');
                            }, function (reason) {
                                rgiNotifier.error(reason);
                            });
                    }, function(response) {
                        rgiHttpResponseProcessorSrvc.getDefaultHandler('Load question data failure')(response);
                        $scope.closeThisDialog();
                    });
                }
            }, function(response) {
                rgiHttpResponseProcessorSrvc.getDefaultHandler('Load assessment data failure')(response);
                $scope.closeThisDialog();
            });
        };
    });
<|endoftext|>


<commit_before>// TODO: refactor so that selectors are aware of the entire state path
// reason being that, the callers shouldn't know to make this state.sets
// right now only a few of them use the stateRoot

const stateRoot = (state) => state.sets;

// Get revision

export const getRevision = (state) => stateRoot(state).revision;

// Get last rep time

// TODO: fix bug here because I'm no longer using set's end and start time
// apparently I used it for more than just rest timer fml

export const lastRepTime = (state) => {
    var workoutData = stateRoot(state).workoutData;
    if (workoutData.length <= 0) {
        return null;
    }

    // check the current set for end time
    var currentSet = workoutData[workoutData.length-1];
    if (currentSet.endTime !== null) {
        return currentSet.endTime;
    }

    // check the previous set for end time
    if (workoutData.length > 1) {
        var previousSet = workoutData[workoutData.length-2];
        if (previousSet.endTime !== null) {
            return previousSet.endTime;
        }
    }

    // no end times found
    return null;
}

// Get Workout Sets

export const getWorkoutSets = (state) => {
    return state.workoutData;
};

// Get Expanded Workout Set

export const getExpandedWorkoutSet = (state, setID) => {
    return state.workoutData.find( set => set.setID == setID );
};

// Dictionary to Aarry

const dictToArray = (dictionary) => {
    var array = [];
    for (var property in dictionary) {
        if (dictionary.hasOwnProperty(property)) {
            array.push(dictionary[property]);
        }
    }
    return array;
};

// Get History Sets

export const getHistorySetsChronological = (state) => {
    var array = dictToArray(state.historyData);
    array.sort((set1, set2) => new Date(set1.startTime) - new Date(set2.startTime));
    return array;
};

// Get Expanded History Set

export const getExpandedHistorySet = (state, setID) => {
    var dictionary = stateRoot(state).historyData;
    for (var property in dictionary) {
        if (dictionary.hasOwnProperty(property)) {
            let set = dictionary[property];
            if (set.setID === setID) {
                return set;
            }
        }
    }
    return null;
};

// Get Sets To Upload
export const getSetsToUpload = (state) => {
    const root = stateRoot(state);
    return root.setIDsToUpload.map( setID => root.historyData[setID] );
};

// Get is uploading
export const getIsUploading = (state) => stateRoot(state).setIDsBeingUploaded.length > 0;

// Has Changes To Sync
export const hasChangesToSync = (state) => {
    const root = stateRoot(state);
    return (root.setIDsToUpload.length > 0 || root.setIDsBeingUploaded.length > 0);
};
<commit_msg>Theoretically fixed bug with end old workout<commit_after>// TODO: refactor so that selectors are aware of the entire state path
// reason being that, the callers shouldn't know to make this state.sets
// right now only a few of them use the stateRoot
import * as SetTimeCalculator from 'app/utility/transforms/SetTimeCalculator';

const stateRoot = (state) => state.sets;

// Get revision

export const getRevision = (state) => stateRoot(state).revision;

// Get last rep time

// TODO: fix bug here because I'm no longer using set's end and start time
// apparently I used it for more than just rest timer fml

export const lastRepTime = (state) => {
    // check if there's workout data
    var workoutData = stateRoot(state).workoutData;
    if (workoutData.length <= 0) {
        return null;
    }

    // check the current set for end time
    var currentSet = workoutData[workoutData.length-1];
    var endTime = SetTimeCalculator.endTime(currentSet);
    if (endTime !== null) {
        return endTime;
    }

    // check previous sets for end time
    if (workoutData.length > 1) {
        for (var i=workoutData.length-2; i>=0; i--) {
            var previousSet = workoutData[i];
            var endTime = SetTimeCalculator.endTime(previousSet);
            if (endTime !== null) {
                return endTime;
            }
        }
    }

    // no end times found
    return null;
}

// Get Workout Sets

export const getWorkoutSets = (state) => {
    return state.workoutData;
};

// Get Expanded Workout Set

export const getExpandedWorkoutSet = (state, setID) => {
    return state.workoutData.find( set => set.setID == setID );
};

// Dictionary to Aarry

const dictToArray = (dictionary) => {
    var array = [];
    for (var property in dictionary) {
        if (dictionary.hasOwnProperty(property)) {
            array.push(dictionary[property]);
        }
    }
    return array;
};

// Get History Sets

export const getHistorySetsChronological = (state) => {
    var array = dictToArray(state.historyData);
    array.sort((set1, set2) => new Date(set1.startTime) - new Date(set2.startTime));
    return array;
};

// Get Expanded History Set

export const getExpandedHistorySet = (state, setID) => {
    var dictionary = stateRoot(state).historyData;
    for (var property in dictionary) {
        if (dictionary.hasOwnProperty(property)) {
            let set = dictionary[property];
            if (set.setID === setID) {
                return set;
            }
        }
    }
    return null;
};

// Get Sets To Upload
export const getSetsToUpload = (state) => {
    const root = stateRoot(state);
    return root.setIDsToUpload.map( setID => root.historyData[setID] );
};

// Get is uploading
export const getIsUploading = (state) => stateRoot(state).setIDsBeingUploaded.length > 0;

// Has Changes To Sync
export const hasChangesToSync = (state) => {
    const root = stateRoot(state);
    return (root.setIDsToUpload.length > 0 || root.setIDsBeingUploaded.length > 0);
};
<|endoftext|>


<commit_before>var fs = require('fs');

module.exports = function linuxProvider() {
  var sysinfo = require('../../sysinfo.js')();
  var historyCpuUsage = {};

  return {
    lookup: lookup,
    clearHistory: clearHistory
  };

  function lookup(pid, options, callback) {
    if(typeof options == 'function') {
        callback = options;
        options = {};
    }
    options = options || {};

    var uptime;
    getUptime(function(err, value) {
      if(err) {
        callback(err);
      } else {
        uptime = value;
        getProcStat(pid, calculateUsage);
      }
    });

    function calculateUsage(err, stat) {
      if(err) {
        callback(err);
      } else {
        var usageData = {};

        if(historyCpuUsage[pid] && options.keepHistory) {
          var cpuUsage = calculateCpuUsageFromHistory(sysinfo, uptime, stat, historyCpuUsage[pid]);
        } else {
          var cpuUsage = calculateCpuUsage(sysinfo, uptime, stat);
        }

        // memeory info
        usageData.memory = calculateMemoryUsage(sysinfo, stat);
        usageData.memoryInfo = {
          rss: calculateMemoryUsage(sysinfo, stat),
          vsize: calculateVirtualMemoryUsage(sysinfo, stat)
        };

        // cpu info
        usageData.cpu = cpuUsage.pcpu;
        usageData.cpuInfo = {
          pcpu: cpuUsage.pcpu,
          pcpuUser: cpuUsage.pcpuUser,
          pcpuSystem: cpuUsage.pcpuSystem,
          cpuTime: cpuUsage.cpuTime
        };

        if(options.keepHistory) {
          //save totalTime in history
          historyCpuUsage[pid] = {
            timestamp: Date.now(),
            stat: stat,
            uptime: uptime
          };
        }

        callback(null, usageData);
      }
    }
  };

  function clearHistory (pid) {
    if(pid) {
      if(historyCpuUsage[pid]) {
        historyCpuUsage[pid] = null;
      }
    } else {
      historyCpuUsage = {};
    }
  }
};

function calculateCpuUsage(sysinfo, uptime, stat) {
  var userTime = stat.utime / sysinfo.HERTZ;
  var systemTime = stat.stime / sysinfo.HERTZ;
  var totalTime = (stat.stime + stat.utime) / sysinfo.HERTZ;
  var processUptime = uptime - stat.startTime / sysinfo.HERTZ;
  return {
    pcpu: (totalTime / processUptime) * 100,
    pcpuUser: (userTime / processUptime) * 100,
    pcpuSystem: (systemTime / processUptime) * 100
  };
}

function calculateCpuUsageFromHistory(sysinfo, uptime, stat, lastUsage) {
  var userTime = stat.utime / sysinfo.HERTZ;
  var systemTime = stat.stime / sysinfo.HERTZ;
  var totalTime = userTime + systemTime;

  var lastUserTime = lastUsage.stat.utime / sysinfo.HERTZ;
  var lastSystemTime = lastUsage.stat.stime / sysinfo.HERTZ;
  var lastTotalTime = lastUserTime + lastSystemTime;

  var diffTotal = totalTime - lastTotalTime;
  var diffUser = userTime - lastUserTime;
  var diffSystem = systemTime - lastSystemTime;
  var timeSpent = uptime - lastUsage.uptime;

  return {
    pcpu: (diffTotal / timeSpent) * 100,
    pcpuUser: (userTimeSinceLast / timeSpent) * 100,
    pcpuSystem: (systemTimeSinceLast / timeSpent) * 100,
    cpuTime: diffTotal
  };
}

function calculateMemoryUsage(sysinfo, stat) {
  return stat.rss * sysinfo.PAGE_SIZE;
}

function calculateVirtualMemoryUsage(sysinfo, stat) {
  return stat.vsize * sysinfo.PAGE_SIZE;
}

function getUptime(callback) {
  fs.readFile('/proc/uptime', 'utf8', function(err, data) {
    if(err) {
      callback(err);
    } else {
      var matched = data.match(/^(.*) /);
      if(matched) {
        var uptime = parseFloat(matched[1]);
        callback(null, uptime);
      } else {
        callback(new Error('Invalid formatted uptime file'));
      }
    }
  });
}

var STAT_INDEXES = {
  STIME: 11,
  UTIME: 12,
  START_TIME: 19,
  RSS: 21,
  VSIZE: 20
};

function getProcStat(pid, callback) {
  var fileName = '/proc/' + pid + '/stat';
  fs.readFile(fileName, 'utf8', function(err, data) {
    if(err) {
      callback(err);
    } else {
      data = data.substr(data.lastIndexOf(')') + 2);
      var parts = data.split(' ');
      var statObject = {
        stime: parseFloat(parts[STAT_INDEXES.STIME]),
        utime: parseFloat(parts[STAT_INDEXES.UTIME]),
        startTime: parseFloat(parts[STAT_INDEXES.START_TIME]),
        rss: parseFloat(parts[STAT_INDEXES.RSS]),
        vsize: parseFloat(parts[STAT_INDEXES.VSIZE])
      };
      callback(null, statObject);
    }
  });
}
<commit_msg>tyfo fixes<commit_after>var fs = require('fs');

module.exports = function linuxProvider() {
  var sysinfo = require('../../sysinfo.js')();
  var historyCpuUsage = {};

  return {
    lookup: lookup,
    clearHistory: clearHistory
  };

  function lookup(pid, options, callback) {
    if(typeof options == 'function') {
        callback = options;
        options = {};
    }
    options = options || {};

    var uptime;
    getUptime(function(err, value) {
      if(err) {
        callback(err);
      } else {
        uptime = value;
        getProcStat(pid, calculateUsage);
      }
    });

    function calculateUsage(err, stat) {
      if(err) {
        callback(err);
      } else {
        var usageData = {};

        if(historyCpuUsage[pid] && options.keepHistory) {
          var cpuUsage = calculateCpuUsageFromHistory(sysinfo, uptime, stat, historyCpuUsage[pid]);
        } else {
          var cpuUsage = calculateCpuUsage(sysinfo, uptime, stat);
        }

        // memeory info
        usageData.memory = calculateMemoryUsage(sysinfo, stat);
        usageData.memoryInfo = {
          rss: calculateMemoryUsage(sysinfo, stat),
          vsize: calculateVirtualMemoryUsage(sysinfo, stat)
        };

        // cpu info
        usageData.cpu = cpuUsage.pcpu;
        usageData.cpuInfo = {
          pcpu: cpuUsage.pcpu,
          pcpuUser: cpuUsage.pcpuUser,
          pcpuSystem: cpuUsage.pcpuSystem,
          cpuTime: cpuUsage.cpuTime
        };

        if(options.keepHistory) {
          //save totalTime in history
          historyCpuUsage[pid] = {
            timestamp: Date.now(),
            stat: stat,
            uptime: uptime
          };
        }

        callback(null, usageData);
      }
    }
  };

  function clearHistory (pid) {
    if(pid) {
      if(historyCpuUsage[pid]) {
        historyCpuUsage[pid] = null;
      }
    } else {
      historyCpuUsage = {};
    }
  }
};

function calculateCpuUsage(sysinfo, uptime, stat) {
  var userTime = stat.utime / sysinfo.HERTZ;
  var systemTime = stat.stime / sysinfo.HERTZ;
  var totalTime = (stat.stime + stat.utime) / sysinfo.HERTZ;
  var processUptime = uptime - stat.startTime / sysinfo.HERTZ;
  return {
    pcpu: (totalTime / processUptime) * 100,
    pcpuUser: (userTime / processUptime) * 100,
    pcpuSystem: (systemTime / processUptime) * 100
  };
}

function calculateCpuUsageFromHistory(sysinfo, uptime, stat, lastUsage) {
  var userTime = stat.utime / sysinfo.HERTZ;
  var systemTime = stat.stime / sysinfo.HERTZ;
  var totalTime = userTime + systemTime;

  var lastUserTime = lastUsage.stat.utime / sysinfo.HERTZ;
  var lastSystemTime = lastUsage.stat.stime / sysinfo.HERTZ;
  var lastTotalTime = lastUserTime + lastSystemTime;

  var diffTotal = totalTime - lastTotalTime;
  var diffUser = userTime - lastUserTime;
  var diffSystem = systemTime - lastSystemTime;
  var timeSpent = uptime - lastUsage.uptime;

  return {
    pcpu: (diffTotal / timeSpent) * 100,
    pcpuUser: (diffUser / timeSpent) * 100,
    pcpuSystem: (diffSystem / timeSpent) * 100,
    cpuTime: diffTotal
  };
}

function calculateMemoryUsage(sysinfo, stat) {
  return stat.rss * sysinfo.PAGE_SIZE;
}

function calculateVirtualMemoryUsage(sysinfo, stat) {
  return stat.vsize * sysinfo.PAGE_SIZE;
}

function getUptime(callback) {
  fs.readFile('/proc/uptime', 'utf8', function(err, data) {
    if(err) {
      callback(err);
    } else {
      var matched = data.match(/^(.*) /);
      if(matched) {
        var uptime = parseFloat(matched[1]);
        callback(null, uptime);
      } else {
        callback(new Error('Invalid formatted uptime file'));
      }
    }
  });
}

var STAT_INDEXES = {
  STIME: 11,
  UTIME: 12,
  START_TIME: 19,
  RSS: 21,
  VSIZE: 20
};

function getProcStat(pid, callback) {
  var fileName = '/proc/' + pid + '/stat';
  fs.readFile(fileName, 'utf8', function(err, data) {
    if(err) {
      callback(err);
    } else {
      data = data.substr(data.lastIndexOf(')') + 2);
      var parts = data.split(' ');
      var statObject = {
        stime: parseFloat(parts[STAT_INDEXES.STIME]),
        utime: parseFloat(parts[STAT_INDEXES.UTIME]),
        startTime: parseFloat(parts[STAT_INDEXES.START_TIME]),
        rss: parseFloat(parts[STAT_INDEXES.RSS]),
        vsize: parseFloat(parts[STAT_INDEXES.VSIZE])
      };
      callback(null, statObject);
    }
  });
}
<|endoftext|>