<commit_before>'use strict'

var db = require('../../db');
var Members = {};

  // ID
  // Name
  // Email
  // Enabled

Members.getAll = function(req, res) {
  var data = [];
  db.each('SELECT ROWID as id, name, email, enabled FROM members', function(err, row) {
    if (err) { res.send(err); throw err; }
    else {
      data.push({
        id: row.id,
        name: row.name,
        email: row.email,
        enabled: row.enabled == 1 ? true : false
      });
    }
  }, function(err) {
    if (err) { res.send(err); throw err; }
    res.send(data);
  });
};

Members.getById = function(req, res) {
  db.get('SELECT ROWID as id, name, email, enabled FROM members WHERE ROWID = $id', [req.params.id], function(err, row) {
    if (err) { res.send(err); throw err; }
    else res.send(
      {
        id: row.id,
        name: row.name,
        email: row.email,
        enabled: row.enabled == 1 ? true : false
      }
    );
  });
};

Members.create = function(req, res) {
  res.status(201).end()
};

Members.updateById = function(req, res) {
  res.status(200).end()
};

Members.deleteById = function(req, res) {
  db.run('DELETE FROM members WHERE ROWID = $id', [req.params.id], function(err) {
      if (err) { res.send(err); throw err; }
      else res.status(200).end()
  });
};

module.exports = Members;
<commit_msg>Adds sql for adding and updating members<commit_after>'use strict'

var db = require('../../db');
var Members = {};

  // ID
  // Name
  // Email
  // Enabled

Members.getAll = function(req, res) {
  var data = [];
  db.each('SELECT ROWID as id, name, email, enabled FROM members', function(err, row) {
    if (err) { res.send(err); throw err; }
    else {
      data.push({
        id: row.id,
        name: row.name,
        email: row.email,
        enabled: row.enabled == 1 ? true : false
      });
    }
  }, function(err) {
    if (err) { res.send(err); throw err; }
    res.send(data);
  });
};

Members.getById = function(req, res) {
  db.get('SELECT ROWID as id, name, email, enabled FROM members WHERE ROWID = $id', [req.params.id], function(err, row) {
    if (err) { res.send(err); throw err; }
    else res.send(
      {
        id: row.id,
        name: row.name,
        email: row.email,
        enabled: row.enabled == 1 ? true : false
      }
    );
  });
};

Members.create = function(req, res) {
  var body = req.body
  var inserts =
    [ body.name
    , body.email
    ]
  db.run('INSERT INTO members (name, email, enabled) VALUES (?,?, 1)', inserts, function(e, row){
    if(e) {
      res.send(e);
      return console.error('Error - Member Create: ', e.stack || e);
    }

    res.status(201).send({success: true})
  })
};

Members.updateById = function(req, res) {
  var body = req.body
  var inserts =
  [ body.name
  , body.email
  , body.enabled
  , req.params.id
  ]
  var stmt = 'UPDATE members SET name = ?, email = ?, enabled = ? WHERE ROWID = ?'
  db.run(stmt, inserts, function(e, row){
    if(e) {
      res.send(e);
      return console.error('Error - Member Update: ', e.stack || e)
    }
    res.send({success: true})
  })
};

Members.deleteById = function(req, res) {
  db.run('DELETE FROM members WHERE ROWID = $id', [req.params.id], function(err) {
      if (err) { res.send(err); throw err; }
      else res.status(200).end()
  });
};

module.exports = Members;
<|endoftext|>


<commit_before>  var blocks = {
    highSchool: {
      "regular":[
        {"start":"7:45","end":"9:06","name":"Block 1","bold":false,"startHour":7,"startMinute":45,"endHour":9,"endMinute":6},
        {"start":"9:06","end":"9:16","name":"Break","bold":true,"startHour":9,"startMinute":6,"endHour":9,"endMinute":16},
        {"start":"9:21","end":"10:53","name":"Block 2","bold":false,"startHour":9,"startMinute":21,"endHour":10,"endMinute":53},
        {"start":"10:58","end":"12:19","name":"Block 3","bold":false,"startHour":10,"startMinute":58,"endHour":12,"endMinute":19},
        {"start":"12:19","end":"12:44","name":"Intervention","bold":false,"startHour":12,"startMinute":19,"endHour":12,"endMinute":44},
        {"start":"12:44","end":"1:14","name":"Lunch","bold":true,"startHour":12,"startMinute":44,"endHour":13,"endMinute":14},
        {"start":"1:19","end":"2:40","name":"Block 4","bold":false,"startHour":13,"startMinute":19,"endHour":14,"endMinute":40}
      ],

      "articulation":[
        {"start":"7:45","end":"8:53","name":"Block 1","bold":false,"startHour":7,"startMinute":45,"endHour":8,"endMinute":53},
        {"start":"8:58","end":"10:14","name":"Block 2","bold":false,"startHour":8,"startMinute":58,"endHour":10,"endMinute":14},
        {"start":"10:14","end":"10:34","name":"Break/Lunch","bold":true,"startHour":10,"startMinute":14,"endHour":10,"endMinute":34},
        {"start":"10:39","end":"11:47","name":"Block 3","bold":false,"startHour":10,"startMinute":39,"endHour":11,"endMinute":47},
        {"start":"11:52","end":"1:00","name":"Block 4","bold":false,"startHour":11,"startMinute":52,"endHour":13,"endMinute":0}
      ]
    },

    middleSchool: {
      "regular": [
        {"start":"7:30","end":"8:20","name":"0 Period","bold":false,"startHour":7,"startMinute":30,"endHour":8,"endMinute":20},
        {"start":"8:30","end":"8:37","name":"Homeroom","bold":false,"startHour":8,"startMinute":30,"endHour":8,"endMinute":37},
        {"start":"8:40","end":"9:27","name":"Period 1","bold":false,"startHour":8,"startMinute":40,"endHour":9,"endMinute":27},
        {"start":"9:30","end":"10:17","name":"Period 2","bold":false,"startHour":9,"startMinute":30,"endHour":10,"endMinute":17},
        {"start":"10:17","end":"10:25","name":"Break","bold":true,"startHour":10,"startMinute":17,"endHour":10,"endMinute":25},
        {"start":"10:25","end":"11:12","name":"Period 3","bold":false,"startHour":10,"startMinute":25,"endHour":11,"endMinute":12},
        {"start":"11:15","end":"12:02","name":"Period 4","bold":false,"startHour":11,"startMinute":15,"endHour":12,"endMinute":2},
        {"start":"12:05","end":"12:46","name":"First Lunch","bold":true,"startHour":12,"startMinute":5,"endHour":12,"endMinute":46},
        {"start":"12:49","end":"1:30","name":"Second Lunch","bold":true,"startHour":12,"startMinute":49,"endHour":1,"endMinute":30},
        {"start":"1:33","end":"2:20","name":"Period 6","bold":false,"startHour":13,"startMinute":33,"endHour":14,"endMinute":20},
        {"start":"2:23","end":"3:10","name":"Period 7","bold":false,"startHour":14,"startMinute":23,"endHour":15,"endMinute":10}
      ],

      "articulation":[
        {"start":"7:30","end":"8:20","name":"0 Period","bold":false,"startHour":7,"startMinute":30,"endHour":8,"endMinute":20},
        {"start":"8:30","end":"8:37","name":"Homeroom","bold":false,"startHour":8,"startMinute":30,"endHour":8,"endMinute":37},
        {"start":"8:40","end":"9:17","name":"Period 1","bold":false,"startHour":8,"startMinute":40,"endHour":9,"endMinute":17},
        {"start":"9:20","end":"9:57","name":"Period 2","bold":false,"startHour":9,"startMinute":20,"endHour":9,"endMinute":57},
        {"start":"9:57","end":"10:04","name":"Break","bold":true,"startHour":9,"startMinute":57,"endHour":10,"endMinute":4},
        {"start":"10:04","end":"10:41","name":"Period 3","bold":false,"startHour":10,"startMinute":4,"endHour":10,"endMinute":41},
        {"start":"10:44","end":"11:21","name":"Period 4","bold":false,"startHour":10,"startMinute":44,"endHour":11,"endMinute":21},
        {"start":"11:24","end":"11:58","name":"First Lunch","bold":true,"startHour":11,"startMinute":24,"endHour":11,"endMinute":58},
        {"start":"12:02","end":"12:36","name":"Second Lunch","bold":true,"startHour":12,"startMinute":2,"endHour":12,"endMinute":36},
        {"start":"12:39","end":"1:16","name":"Period 6","bold":false,"startHour":12,"startMinute":39,"endHour":13,"endMinute":16},
        {"start":"1:19","end":"1:56","name":"Period 7","bold":false,"startHour":13,"startMinute":19,"endHour":13,"endMinute":56}
      ]
    }
  };

  // Maintenance Note: Change `return blocks.middleSchool` to `return` when editing code

 var data = getSchool();

 function getSchool () {
   //var $Data = JSON.parse(blocks);
   var $Data = blocks;
   if (document.getElementsByName('school').value === 'high') {

   } else if (document.getElementsByName('school').value === 'middle') {

   } else {
     return $Data.highSchool;
   }
 }

 function getTimeAdv (date) {
   return [ date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds() ];
 }

 function getNext () {
   var i;
   var cycle = true;
   var days = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ];
   var date = new Date();
   var render;
   var currentEvent;
   var time = getTimeAdv(date);

   if (date.getDay() !== 0 || date.getDay() !== 6) {
     if (date.getDay() === 1) {
       render = data.articulation;
     } else {
       render = data.regular;
     }

     var currentTime = 0;
     var nextTime = 0;
     var hoursLeft = 0;
     var minutesLeft = 0;
     for (i = 0; i < render.length; i++) {
       currentTime = (time[0] * 60) + time[1];
       nextTime = (render[i].endHour * 60) + render[i].endMinute;
       if (currentTime < nextTime) {
         hoursLeft = Math.floor((nextTime - currentTime) / 60);
         minutesLeft = Math.floor((nextTime - (hoursLeft * 60)) - currentTime);
         if (hoursLeft === 0) {
           return minutesLeft + ' minutes until the end of ' + render[i].name;
         } else if (hoursLeft !== 0) {
           return hoursLeft + ' hours and ' + minutesLeft + ' minutes until the end of ' + render[i].name;
         }
       }
     }
     return 'School is over.';
   }
 }

 $(document).ready(function () {
   var days = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ];
   var i;
   var date = new Date();
   var render;
   if (date.getDay() === 1) {
     render = data.articulation;
     for (i = 0; i < render.length; i++) {
       if (!render[i].bold) {
         $('#display').append('
' + render[i].name + ':	' + render[i].start + '-' + render[i].end + '
');
       } else if (render[i].bold) {
         $('#display').append('
' + render[i].name + ':	' + render[i].start + '-' + render[i].end + '
');
       }
     }
     document.getElementsByTagName('title')[0].innerHTML += ': ' + days[new Date().getDay()];
   } else if (date.getDay() === 2 || date.getDay() === 3 || date.getDay() === 4 || date.getDay() === 5) {
     render = data.regular;
     for (i = 0; i < render.length; i++) {
       if (!render[i].bold) {
         $('#display').append('
' + render[i].name + ':	' + render[i].start + '-' + render[i].end + '
');
       } else if (render[i].bold) {
         $('#display').append('
' + render[i].name + ':	' + render[i].start + '-' + render[i].end + '
');
       }
     }
     document.getElementsByTagName('title')[0].innerHTML += ': ' + days[new Date().getDay()];
   } else if (date.getDay() === 0 || date.getDay() === 6) {
     document.getElementsByTagName('title')[0].innerHTML += ': ' + days[new Date().getDay()];
     $('#text').show();
     $('#text').text("No school today, it's " + days[date.getDay()] + "!");
   }
 });

 function nav () {
   $('#side-nav').toggle();
   $('#show').toggle();
 }

 function school (level) {
   //var pa = JSON.parse(blocks);
   var pa = data;
   if (level === 'high') {
     data = pa.highSchool;
   } else if (level === 'middle') {
     data = pa.middleSchool;
   }

   var days = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ];
   var i;
   var date = new Date();
   var render;
   if (date.getDay() === 1) {
     render = data.articulation;
     for (i = 0; i < render.length; i++) {
       if (!render[i].bold) {
         $('#display').append('
' + render[i].name + ':	' + render[i].start + '-' + render[i].end + '
');
       } else if (render[i].bold) {
         $('#display').append('
' + render[i].name + ':	' + render[i].start + '-' + render[i].end + '
');
       }
     }
     document.getElementsByTagName('title')[0].innerHTML += ': ' + days[new Date().getDay()];
   } else if (date.getDay() === 2 || date.getDay() === 3 || date.getDay() === 4 || date.getDay() === 5) {
     render = data.regular;
     for (i = 0; i < render.length; i++) {
       if (!render[i].bold) {
         $('#display').append('
' + render[i].name + ':	' + render[i].start + '-' + render[i].end + '
');
       } else if (render[i].bold) {
         $('#display').append('
' + render[i].name + ':	' + render[i].start + '-' + render[i].end + '
');
       }
     }
     document.getElementsByTagName('title')[0].innerHTML += ': ' + days[new Date().getDay()];
   } else if (date.getDay() === 0 || date.getDay() === 6) {
     document.getElementsByTagName('title')[0].innerHTML += ': ' + days[new Date().getDay()];
     $('#text').show();
     $('#text').text("No school today, it's " + days[date.getDay()] + "!");
   }
 }

 /*var timeUpdate = setInterval(function () {
   $('#time').html('The time is currently ' + new Date().toLocaleTimeString() + '.');
   $('#next').html(getNext());
 }, 500);*/
<commit_msg>Update schedule.js<commit_after>  var blocks = {
    highSchool: {
      "regular":[
        {"start":"7:45","end":"9:06","name":"Block 1","bold":false,"startHour":7,"startMinute":45,"endHour":9,"endMinute":6},
        {"start":"9:06","end":"9:16","name":"Break","bold":true,"startHour":9,"startMinute":6,"endHour":9,"endMinute":16},
        {"start":"9:21","end":"10:53","name":"Block 2","bold":false,"startHour":9,"startMinute":21,"endHour":10,"endMinute":53},
        {"start":"10:58","end":"12:19","name":"Block 3","bold":false,"startHour":10,"startMinute":58,"endHour":12,"endMinute":19},
        {"start":"12:19","end":"12:44","name":"Intervention","bold":false,"startHour":12,"startMinute":19,"endHour":12,"endMinute":44},
        {"start":"12:44","end":"1:14","name":"Lunch","bold":true,"startHour":12,"startMinute":44,"endHour":13,"endMinute":14},
        {"start":"1:19","end":"2:40","name":"Block 4","bold":false,"startHour":13,"startMinute":19,"endHour":14,"endMinute":40}
      ],

      "articulation":[
        {"start":"7:45","end":"8:53","name":"Block 1","bold":false,"startHour":7,"startMinute":45,"endHour":8,"endMinute":53},
        {"start":"8:58","end":"10:14","name":"Block 2","bold":false,"startHour":8,"startMinute":58,"endHour":10,"endMinute":14},
        {"start":"10:14","end":"10:34","name":"Break/Lunch","bold":true,"startHour":10,"startMinute":14,"endHour":10,"endMinute":34},
        {"start":"10:39","end":"11:47","name":"Block 3","bold":false,"startHour":10,"startMinute":39,"endHour":11,"endMinute":47},
        {"start":"11:52","end":"1:00","name":"Block 4","bold":false,"startHour":11,"startMinute":52,"endHour":13,"endMinute":0}
      ]
    },

    middleSchool: {
      "regular": [
        {"start":"7:30","end":"8:20","name":"0 Period","bold":false,"startHour":7,"startMinute":30,"endHour":8,"endMinute":20},
        {"start":"8:30","end":"8:37","name":"Homeroom","bold":false,"startHour":8,"startMinute":30,"endHour":8,"endMinute":37},
        {"start":"8:40","end":"9:27","name":"Period 1","bold":false,"startHour":8,"startMinute":40,"endHour":9,"endMinute":27},
        {"start":"9:30","end":"10:17","name":"Period 2","bold":false,"startHour":9,"startMinute":30,"endHour":10,"endMinute":17},
        {"start":"10:17","end":"10:25","name":"Break","bold":true,"startHour":10,"startMinute":17,"endHour":10,"endMinute":25},
        {"start":"10:25","end":"11:12","name":"Period 3","bold":false,"startHour":10,"startMinute":25,"endHour":11,"endMinute":12},
        {"start":"11:15","end":"12:02","name":"Period 4","bold":false,"startHour":11,"startMinute":15,"endHour":12,"endMinute":2},
        {"start":"12:05","end":"12:46","name":"First Lunch","bold":true,"startHour":12,"startMinute":5,"endHour":12,"endMinute":46},
        {"start":"12:49","end":"1:30","name":"Second Lunch","bold":true,"startHour":12,"startMinute":49,"endHour":1,"endMinute":30},
        {"start":"1:33","end":"2:20","name":"Period 6","bold":false,"startHour":13,"startMinute":33,"endHour":14,"endMinute":20},
        {"start":"2:23","end":"3:10","name":"Period 7","bold":false,"startHour":14,"startMinute":23,"endHour":15,"endMinute":10}
      ],

      "articulation":[
        {"start":"7:30","end":"8:20","name":"0 Period","bold":false,"startHour":7,"startMinute":30,"endHour":8,"endMinute":20},
        {"start":"8:30","end":"8:37","name":"Homeroom","bold":false,"startHour":8,"startMinute":30,"endHour":8,"endMinute":37},
        {"start":"8:40","end":"9:17","name":"Period 1","bold":false,"startHour":8,"startMinute":40,"endHour":9,"endMinute":17},
        {"start":"9:20","end":"9:57","name":"Period 2","bold":false,"startHour":9,"startMinute":20,"endHour":9,"endMinute":57},
        {"start":"9:57","end":"10:04","name":"Break","bold":true,"startHour":9,"startMinute":57,"endHour":10,"endMinute":4},
        {"start":"10:04","end":"10:41","name":"Period 3","bold":false,"startHour":10,"startMinute":4,"endHour":10,"endMinute":41},
        {"start":"10:44","end":"11:21","name":"Period 4","bold":false,"startHour":10,"startMinute":44,"endHour":11,"endMinute":21},
        {"start":"11:24","end":"11:58","name":"First Lunch","bold":true,"startHour":11,"startMinute":24,"endHour":11,"endMinute":58},
        {"start":"12:02","end":"12:36","name":"Second Lunch","bold":true,"startHour":12,"startMinute":2,"endHour":12,"endMinute":36},
        {"start":"12:39","end":"1:16","name":"Period 6","bold":false,"startHour":12,"startMinute":39,"endHour":13,"endMinute":16},
        {"start":"1:19","end":"1:56","name":"Period 7","bold":false,"startHour":13,"startMinute":19,"endHour":13,"endMinute":56}
      ]
    }
  };

  // Maintenance Note: Change `return blocks.middleSchool` to `return` when editing code

 var data = getSchool();

 function getSchool () {
   var $Data = JSON.parse(blocks);
   //var $Data = blocks;
   if (document.getElementsByName('school').value === 'high') {

   } else if (document.getElementsByName('school').value === 'middle') {

   } else {
     return $Data.highSchool;
   }
 }

 function getTimeAdv (date) {
   return [ date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds() ];
 }

 function getNext () {
   var i;
   var cycle = true;
   var days = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ];
   var date = new Date();
   var render;
   var currentEvent;
   var time = getTimeAdv(date);

   if (date.getDay() !== 0 || date.getDay() !== 6) {
     if (date.getDay() === 1) {
       render = data.articulation;
     } else {
       render = data.regular;
     }

     var currentTime = 0;
     var nextTime = 0;
     var hoursLeft = 0;
     var minutesLeft = 0;
     for (i = 0; i < render.length; i++) {
       currentTime = (time[0] * 60) + time[1];
       nextTime = (render[i].endHour * 60) + render[i].endMinute;
       if (currentTime < nextTime) {
         hoursLeft = Math.floor((nextTime - currentTime) / 60);
         minutesLeft = Math.floor((nextTime - (hoursLeft * 60)) - currentTime);
         if (hoursLeft === 0) {
           return minutesLeft + ' minutes until the end of ' + render[i].name;
         } else if (hoursLeft !== 0) {
           return hoursLeft + ' hours and ' + minutesLeft + ' minutes until the end of ' + render[i].name;
         }
       }
     }
     return 'School is over.';
   }
 }

 $(document).ready(function () {
   var days = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ];
   var i;
   var date = new Date();
   var render;
   if (date.getDay() === 1) {
     render = data.articulation;
     for (i = 0; i < render.length; i++) {
       if (!render[i].bold) {
         $('#display').append('
' + render[i].name + ':	' + render[i].start + '-' + render[i].end + '
');
       } else if (render[i].bold) {
         $('#display').append('
' + render[i].name + ':	' + render[i].start + '-' + render[i].end + '
');
       }
     }
     document.getElementsByTagName('title')[0].innerHTML += ': ' + days[new Date().getDay()];
   } else if (date.getDay() === 2 || date.getDay() === 3 || date.getDay() === 4 || date.getDay() === 5) {
     render = data.regular;
     for (i = 0; i < render.length; i++) {
       if (!render[i].bold) {
         $('#display').append('
' + render[i].name + ':	' + render[i].start + '-' + render[i].end + '
');
       } else if (render[i].bold) {
         $('#display').append('
' + render[i].name + ':	' + render[i].start + '-' + render[i].end + '
');
       }
     }
     document.getElementsByTagName('title')[0].innerHTML += ': ' + days[new Date().getDay()];
   } else if (date.getDay() === 0 || date.getDay() === 6) {
     document.getElementsByTagName('title')[0].innerHTML += ': ' + days[new Date().getDay()];
     $('#text').show();
     $('#text').text("No school today, it's " + days[date.getDay()] + "!");
   }
 });

 function nav () {
   $('#side-nav').toggle();
   $('#show').toggle();
 }

 function school (level) {
   $('#display').empty();
   var pa = JSON.parse(blocks);
   //var pa = blocks;
   if (level === 'high') {
     data = pa.highSchool;
   } else if (level === 'middle') {
     data = pa.middleSchool;
   }

   var days = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ];
   var i;
   var date = new Date();
   var render;
   if (date.getDay() === 1) {
     render = data.articulation;
     for (i = 0; i < render.length; i++) {
       if (!render[i].bold) {
         $('#display').append('
' + render[i].name + ':	' + render[i].start + '-' + render[i].end + '
');
       } else if (render[i].bold) {
         $('#display').append('
' + render[i].name + ':	' + render[i].start + '-' + render[i].end + '
');
       }
     }
     document.getElementsByTagName('title')[0].innerHTML += ': ' + days[new Date().getDay()];
   } else if (date.getDay() === 2 || date.getDay() === 3 || date.getDay() === 4 || date.getDay() === 5) {
     render = data.regular;
     for (i = 0; i < render.length; i++) {
       if (!render[i].bold) {
         $('#display').append('
' + render[i].name + ':	' + render[i].start + '-' + render[i].end + '
');
       } else if (render[i].bold) {
         $('#display').append('
' + render[i].name + ':	' + render[i].start + '-' + render[i].end + '
');
       }
     }
     document.getElementsByTagName('title')[0].innerHTML += ': ' + days[new Date().getDay()];
   } else if (date.getDay() === 0 || date.getDay() === 6) {
     document.getElementsByTagName('title')[0].innerHTML += ': ' + days[new Date().getDay()];
     $('#text').show();
     $('#text').text("No school today, it's " + days[date.getDay()] + "!");
   }
 }

 var timeUpdate = setInterval(function () {
   $('#time').html('The time is currently ' + new Date().toLocaleTimeString() + '.');
   $('#next').html(getNext());
 }, 500);
<|endoftext|>


<commit_before>module.exports = {

  nodeSourceMap: {},

  /**
   * Initialize the node service
   */
  init: function () {
    this._loadSourceMap();
  },

  /**
   * Attempt to add a new node if it is a node ID that hasn't been seen before
   * @param nodeId
   * @param name
   * @param source
   */
  addNode: function (nodeId, name, source) {
    var that = this;
    // First check to see if we have a node for this node ID
    this.getNode(nodeId, function (results) {
      if (!results) {
        that._saveNode(nodeId, name, source);
      }
    });
  },

  getNode: function (nodeId, cb) {
    Node.findOne({id: nodeId}).populate('capabilities').exec(
      function (err, results) {
        if (!err) {
          return cb(
            NodeService.flattenCapabilities(results)
          );
        }
      }
    );
  },

  query: function (limit, offset, cb) {
    Node.find({skip: offset, limit: limit}).sort({createdAt: -1}).populate('capabilities').exec(
      function (err, results) {
        if (!err) {

          // Flatten the capability objects
          var nodes = [];
          _.each(results, function (node) {
            nodes.push(NodeService.flattenCapabilities(node));
          });

          return cb(nodes);
        }
      }
    );
  },

  flattenCapabilities: function(node) {
    var capabilities = _.pluck(node.capabilities, 'capability');
    return {
      id: node.id,
      name: node.name,
      source: node.source,
      createdAt: node.createdAt,
      capabilities: capabilities
    };
  },

  clear: function () {
    Node.drop();
  },

  /**
   * Load the nodes from storage into the source map
   */
  _loadSourceMap: function () {
    var that = this;

    Node.find().exec(
      function callback(error, nodes) {
        if (error) {
          sails.log.error(error);
        } else {
          _.each(nodes, function (node) {
            sails.log.debug('Loading nodeId:' + node.id + ' to source ' + node.source);

            // Only map external sources
            if (node.source != 'mqtt') {
              that.nodeSourceMap[node.id] = node.source;
            }
          });
        }
      }
    );
  },

  /**
   * Add a node capabilities
   */
  addNodeCapabilities: function (nodeId, capabilities) {
    var that = this;

    _.each(capabilities, function (capability) {
      that.addNodeCapability(nodeId, capability);
    });
  },

  /**
   * Add a node capability
   */
  addNodeCapability: function (nodeId, capability) {
    var that = this;

    Capability.count(
      {
        node: nodeId,
        capability: capability
      }).exec(
      function callback(error, numFound) {
        if (error) {
          sails.log.error(error);
        } else if (numFound == 0) {
          that._saveNodeCapability(nodeId, capability);
        }
      }
    );
  },

  /**
   * Save the node to storage
   */
  _saveNode: function (nodeId, name, source) {

    NodeService.nodeSourceMap[nodeId] = source;

    var timestamp = sails.moment();

    Node.create(
      {
        id: nodeId,
        name: name,
        source: source,
        createdAt: timestamp.toDate()
      }).exec(
      function callback(error, created) {
        if (error) {
          sails.log.error(error);
        } else {
          sails.sockets.broadcast('node', 'node_created', created);

          sails.log.debug("[" + timestamp.format() + "] node " + nodeId + " saved");
        }
      }
    );
  },

  /**
   * Save the node capability to storage
   */
  _saveNodeCapability: function (nodeId, capability) {
    Capability.create(
      {
        node: nodeId,
        capability: capability
      }).exec(
      function callback(error, created) {
        if (error) {
          sails.log.error(error);
        } else {
          sails.log.debug("node " + nodeId + " capability " + capability + " saved");
        }
      }
    );
  }

};<commit_msg>Fixing build unhappiness.<commit_after>module.exports = {

  nodeSourceMap: {},

  /**
   * Initialize the node service
   */
  init: function () {
    this._loadSourceMap();
  },

  /**
   * Attempt to add a new node if it is a node ID that hasn't been seen before
   * @param nodeId
   * @param name
   * @param source
   */
  addNode: function (nodeId, name, source) {
    var that = this;
    // First check to see if we have a node for this node ID
    this.getNode(nodeId, function (results) {
      if (!results) {
        that._saveNode(nodeId, name, source);
      }
    });
  },

  getNode: function (nodeId, cb) {
    var ns = this;

    Node.findOne({id: nodeId}).populate('capabilities').exec(
      function (err, results) {
        if (!err) {
          return cb(
            ns.flattenCapabilities(results)
          );
        }
      }
    );
  },

  query: function (limit, offset, cb) {
    var ns = this;

    Node.find({skip: offset, limit: limit}).sort({createdAt: -1}).populate('capabilities').exec(
      function (err, results) {
        if (!err) {

          // Flatten the capability objects
          var nodes = [];
          _.each(results, function (node) {
            nodes.push(ns.flattenCapabilities(node));
          });

          return cb(nodes);
        }
      }
    );
  },

  flattenCapabilities: function(node) {
    var capabilities = _.pluck(node.capabilities, 'capability');
    return {
      id: node.id,
      name: node.name,
      source: node.source,
      createdAt: node.createdAt,
      capabilities: capabilities
    };
  },

  clear: function () {
    Node.drop();
  },

  /**
   * Load the nodes from storage into the source map
   */
  _loadSourceMap: function () {
    var that = this;

    Node.find().exec(
      function callback(error, nodes) {
        if (error) {
          sails.log.error(error);
        } else {
          _.each(nodes, function (node) {
            sails.log.debug('Loading nodeId:' + node.id + ' to source ' + node.source);

            // Only map external sources
            if (node.source != 'mqtt') {
              that.nodeSourceMap[node.id] = node.source;
            }
          });
        }
      }
    );
  },

  /**
   * Add a node capabilities
   */
  addNodeCapabilities: function (nodeId, capabilities) {
    var that = this;

    _.each(capabilities, function (capability) {
      that.addNodeCapability(nodeId, capability);
    });
  },

  /**
   * Add a node capability
   */
  addNodeCapability: function (nodeId, capability) {
    var that = this;

    Capability.count(
      {
        node: nodeId,
        capability: capability
      }).exec(
      function callback(error, numFound) {
        if (error) {
          sails.log.error(error);
        } else if (numFound == 0) {
          that._saveNodeCapability(nodeId, capability);
        }
      }
    );
  },

  /**
   * Save the node to storage
   */
  _saveNode: function (nodeId, name, source) {

    NodeService.nodeSourceMap[nodeId] = source;

    var timestamp = sails.moment();

    Node.create(
      {
        id: nodeId,
        name: name,
        source: source,
        createdAt: timestamp.toDate()
      }).exec(
      function callback(error, created) {
        if (error) {
          sails.log.error(error);
        } else {
          sails.sockets.broadcast('node', 'node_created', created);

          sails.log.debug("[" + timestamp.format() + "] node " + nodeId + " saved");
        }
      }
    );
  },

  /**
   * Save the node capability to storage
   */
  _saveNodeCapability: function (nodeId, capability) {
    Capability.create(
      {
        node: nodeId,
        capability: capability
      }).exec(
      function callback(error, created) {
        if (error) {
          sails.log.error(error);
        } else {
          sails.log.debug("node " + nodeId + " capability " + capability + " saved");
        }
      }
    );
  }

};<|endoftext|>


<commit_before>'use strict';

/**
 * SVGO is a Nodejs-based tool for optimizing SVG vector graphics files.
 *
 * @see https://github.com/svg/svgo
 *
 * @author Kir Belevich <kir@soulshine.in> (https://github.com/deepsweet)
 * @copyright © 2012 Kir Belevich
 * @license MIT https://raw.githubusercontent.com/svg/svgo/master/LICENSE
 */

var CONFIG = require('./svgo/config.js'),
    SVG2JS = require('./svgo/svg2js.js'),
    PLUGINS = require('./svgo/plugins.js'),
    JSAPI = require('./svgo/jsAPI.js'),
    encodeSVGDatauri = require('./svgo/tools.js').encodeSVGDatauri,
    JS2SVG = require('./svgo/js2svg.js');

var SVGO = function(config) {
    this.config = CONFIG(config);
};

SVGO.prototype.optimize = function(svgstr, info) {
    return new Promise((resolve, reject) => {
        if (this.config.error) {
            reject(this.config.error);
            return;
        }

        var config = this.config,
            maxPassCount = config.multipass ? 10 : 1,
            counter = 0,
            prevResultSize = Number.POSITIVE_INFINITY,
            optimizeOnceCallback = (svgjs) => {
                if (svgjs.error) {
                    reject(svgjs.error);
                    return;
                }

                if (++counter < maxPassCount && svgjs.data.length < prevResultSize) {
                    prevResultSize = svgjs.data.length;
                    this._optimizeOnce(svgjs.data, info, optimizeOnceCallback);
                } else {
                    if (config.datauri) {
                        svgjs.data = encodeSVGDatauri(svgjs.data, config.datauri);
                    }
                    if (info && info.path) {
                        svgjs.path = info.path;
                    }
                    resolve(svgjs);
                }
            };

        this._optimizeOnce(svgstr, info, optimizeOnceCallback);
    });
};

SVGO.prototype._optimizeOnce = function(svgstr, info, callback) {
    var config = this.config;

    SVG2JS(svgstr, function(svgjs) {
        if (svgjs.error) {
            callback(svgjs);
            return;
        }

        svgjs = PLUGINS(svgjs, info, config.plugins);

        callback(JS2SVG(svgjs, config.js2svg));
    });
};

/**
 * The factory that creates a content item with the helper methods.
 *
 * @param {Object} data which passed to jsAPI constructor
 * @returns {JSAPI} content item
 */
SVGO.prototype.createContentItem = function(data) {
    return new JSAPI(data);
};

module.exports = SVGO;
// Offer ES module interop compatibility.
module.exports.default = SVGO;
<commit_msg>Export config function to enable to use<commit_after>'use strict';

/**
 * SVGO is a Nodejs-based tool for optimizing SVG vector graphics files.
 *
 * @see https://github.com/svg/svgo
 *
 * @author Kir Belevich <kir@soulshine.in> (https://github.com/deepsweet)
 * @copyright © 2012 Kir Belevich
 * @license MIT https://raw.githubusercontent.com/svg/svgo/master/LICENSE
 */

var CONFIG = require('./svgo/config.js'),
    SVG2JS = require('./svgo/svg2js.js'),
    PLUGINS = require('./svgo/plugins.js'),
    JSAPI = require('./svgo/jsAPI.js'),
    encodeSVGDatauri = require('./svgo/tools.js').encodeSVGDatauri,
    JS2SVG = require('./svgo/js2svg.js');

var SVGO = function(config) {
    this.config = CONFIG(config);
};

SVGO.prototype.optimize = function(svgstr, info) {
    return new Promise((resolve, reject) => {
        if (this.config.error) {
            reject(this.config.error);
            return;
        }

        var config = this.config,
            maxPassCount = config.multipass ? 10 : 1,
            counter = 0,
            prevResultSize = Number.POSITIVE_INFINITY,
            optimizeOnceCallback = (svgjs) => {
                if (svgjs.error) {
                    reject(svgjs.error);
                    return;
                }

                if (++counter < maxPassCount && svgjs.data.length < prevResultSize) {
                    prevResultSize = svgjs.data.length;
                    this._optimizeOnce(svgjs.data, info, optimizeOnceCallback);
                } else {
                    if (config.datauri) {
                        svgjs.data = encodeSVGDatauri(svgjs.data, config.datauri);
                    }
                    if (info && info.path) {
                        svgjs.path = info.path;
                    }
                    resolve(svgjs);
                }
            };

        this._optimizeOnce(svgstr, info, optimizeOnceCallback);
    });
};

SVGO.prototype._optimizeOnce = function(svgstr, info, callback) {
    var config = this.config;

    SVG2JS(svgstr, function(svgjs) {
        if (svgjs.error) {
            callback(svgjs);
            return;
        }

        svgjs = PLUGINS(svgjs, info, config.plugins);

        callback(JS2SVG(svgjs, config.js2svg));
    });
};

/**
 * The factory that creates a content item with the helper methods.
 *
 * @param {Object} data which passed to jsAPI constructor
 * @returns {JSAPI} content item
 */
SVGO.prototype.createContentItem = function(data) {
    return new JSAPI(data);
};

SVGO.Config = CONFIG;

module.exports = SVGO;
// Offer ES module interop compatibility.
module.exports.default = SVGO;
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012 Dmitri Melikyan
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to permit
 * persons to whom the Software is furnished to do so, subject to the
 * following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
 * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
 * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

var nt = require('./nodetime');
var request = require('./request');
var gd = require('./gd.agent.sync');

if(!nt.payload) {
  nt.payload = {};
  nt.syncRetry = 0;
  nt.nextId = Math.round(Math.random() * Math.pow(10, 9));
}

function clone(source, depth) {
  if(!depth) depth = 0;
  if(depth > 20) return {};

  var target = {};

  for(var prop in source) {
    var val = source[prop];
    if(val == undefined || prop.match(/^_/)) continue;

    if(typeof val === 'string' || typeof val === 'number') {
      target[prop] = source[prop];
    }
    else if(typeof val === 'object') {
      target[prop] = clone(val, depth + 1);
    }
  }

  return target;
}

exports.add = function(type, obj) {
  obj._id = nt.nextId++;

    if(type === 'samples') {
      // remove heavy 'blob' data // obj['In-time operations'] = obj._related;
      // obj['Application state'] = obj._state;
      // obj['Node information'] = obj._info;

    nt.emit('sample', clone(obj));
  }

  if(nt.headless) return;

  if(nt.payload[type]) {
    nt.payload[type].push(obj);
  }
  else {
    nt.payload[type] = [obj];
  }

  // cleanup
  if(nt.payload.length > 1000) {
    nt.payload.splice(1000);
  }
};

var hasData = function() {
  for(var key in nt.payload) {
    return true;
  }
};

var send = function() {
    debugger;
  if(nt.headless) return;

  // nothing to send or emit
  if(!hasData()) return;

  // worker without token
  if(!(nt.master || nt.token)) return;

  nt.payload['version'] = nt.version;

  nt.dump(nt.payload);

  if(!nt.payloadSending) {
    nt.payloadSending = nt.payload;
    nt.payload = {};
  }

  if(nt.gdSync) {
      gd.push(nt.gdSync, nt.payloadSending, function(err) {
          if(err) {
              nt.error(err);
              return;
          }
          nt.log('GraphDat payload pushed');
      });
  }

  if(nt.netSync) {
      request.post(nt.serverUrl ? nt.serverUrl : 'https://nodetime.com/upload' + (nt.token ? '?token=' + nt.token : ''), nt.payloadSending, function(err, headers, buf) {
        if(err) {
          if(nt.syncRetry++ > 1) {
            nt.payloadSending = null;
            nt.syncRetry = 0;
          }

          nt.error(err);
          return;
        }

        var ret = JSON.parse(buf.toString());
        if(!nt.token) {
          if(ret.token) {
              nt.token = ret.token;
              if(nt.serverUrl) {
                console.log("\033[1mNodetime:\033[0m Sending data to custom Url. The token for this instance is \033[33m" + nt.token + "\033[0m");
              } else {
                console.log("\033[1mNodetime:\033[0m profiler console for this instance is at \033[33mhttps://nodetime.com/" + nt.token + "\033[0m");
              }
              nt.emit('session', ret.token);
          } else {
              nt.token = -1;
              console.log("\033[1mNodetime:\033[0m Sending data to custom Url. No token received.");
          }
        }

        nt.log('uploaded payload');
      });
  }

  // cleanup
    nt.payloadSending = null;
    nt.syncRetry = 0;

}

if(!nt.syncIntervalId) {
  nt.syncIntervalId = setInterval(function() {
    try {
      send();
    }
    catch(e) {
      nt.error(e);
    }
  }, 900);
}
<commit_msg>remove debugger stmt<commit_after>/*
 * Copyright (c) 2012 Dmitri Melikyan
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to permit
 * persons to whom the Software is furnished to do so, subject to the
 * following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
 * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
 * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

var nt = require('./nodetime');
var request = require('./request');
var gd = require('./gd.agent.sync');

if(!nt.payload) {
  nt.payload = {};
  nt.syncRetry = 0;
  nt.nextId = Math.round(Math.random() * Math.pow(10, 9));
}

function clone(source, depth) {
  if(!depth) depth = 0;
  if(depth > 20) return {};

  var target = {};

  for(var prop in source) {
    var val = source[prop];
    if(val == undefined || prop.match(/^_/)) continue;

    if(typeof val === 'string' || typeof val === 'number') {
      target[prop] = source[prop];
    }
    else if(typeof val === 'object') {
      target[prop] = clone(val, depth + 1);
    }
  }

  return target;
}

exports.add = function(type, obj) {
  obj._id = nt.nextId++;

    if(type === 'samples') {
      // remove heavy 'blob' data // obj['In-time operations'] = obj._related;
      // obj['Application state'] = obj._state;
      // obj['Node information'] = obj._info;

    nt.emit('sample', clone(obj));
  }

  if(nt.headless) return;

  if(nt.payload[type]) {
    nt.payload[type].push(obj);
  }
  else {
    nt.payload[type] = [obj];
  }

  // cleanup
  if(nt.payload.length > 1000) {
    nt.payload.splice(1000);
  }
};

var hasData = function() {
  for(var key in nt.payload) {
    return true;
  }
};

var send = function() {
  if(nt.headless) return;

  // nothing to send or emit
  if(!hasData()) return;

  // worker without token
  if(!(nt.master || nt.token)) return;

  nt.payload['version'] = nt.version;

  nt.dump(nt.payload);

  if(!nt.payloadSending) {
    nt.payloadSending = nt.payload;
    nt.payload = {};
  }

  if(nt.gdSync) {
      gd.push(nt.gdSync, nt.payloadSending, function(err) {
          if(err) {
              nt.error(err);
              return;
          }
          nt.log('GraphDat payload pushed');
      });
  }

  if(nt.netSync) {
      request.post(nt.serverUrl ? nt.serverUrl : 'https://nodetime.com/upload' + (nt.token ? '?token=' + nt.token : ''), nt.payloadSending, function(err, headers, buf) {
        if(err) {
          if(nt.syncRetry++ > 1) {
            nt.payloadSending = null;
            nt.syncRetry = 0;
          }

          nt.error(err);
          return;
        }

        var ret = JSON.parse(buf.toString());
        if(!nt.token) {
          if(ret.token) {
              nt.token = ret.token;
              if(nt.serverUrl) {
                console.log("\033[1mNodetime:\033[0m Sending data to custom Url. The token for this instance is \033[33m" + nt.token + "\033[0m");
              } else {
                console.log("\033[1mNodetime:\033[0m profiler console for this instance is at \033[33mhttps://nodetime.com/" + nt.token + "\033[0m");
              }
              nt.emit('session', ret.token);
          } else {
              nt.token = -1;
              console.log("\033[1mNodetime:\033[0m Sending data to custom Url. No token received.");
          }
        }

        nt.log('uploaded payload');
      });
  }

  // cleanup
    nt.payloadSending = null;
    nt.syncRetry = 0;

}

if(!nt.syncIntervalId) {
  nt.syncIntervalId = setInterval(function() {
    try {
      send();
    }
    catch(e) {
      nt.error(e);
    }
  }, 900);
}
<|endoftext|>


<commit_before>// Copyright 2014, Renasar Technologies Inc.
/* jshint: node:true */
'use strict';

var di = require('di');

module.exports = factory;
di.annotate(factory, new di.Provide('Task.Task'));
    di.annotate(factory,
    new di.Inject(
        'Protocol.Task',
        'Protocol.Events',
        'Logger',
        'Assert',
        'Errors',
        'Constants',
        'uuid',
        'Promise',
        '_',
        di.Injector
    )
);

/**
 * Injectable wrapper for dependencies
 * @param logger
 */
function factory(taskProtocol, eventsProtocol, Logger, assert, Errors, constants,
        uuid, Promise, _, injector) {

    var RUNNING = constants.TaskStates.RUNNING;
    var SUCCEEDED = constants.TaskStates.SUCCEEDED;
    var FAILED = constants.TaskStates.FAILED;
    var CANCELLED = constants.TaskStates.CANCELLED;
    var TIMEOUT = constants.TaskStates.TIMEOUT;
    var PENDING = constants.TaskStates.PENDING;

    var logger = Logger.initialize(factory);

    /**
     *
     * @param taskGraph
     * @param optionOverrides
     * @returns {factory.Task}
     * @constructor
     */
    function Task(definition, taskOverrides, context) {
        var self = this;

        assert.object(definition, 'Task definition data');
        assert.string(definition.friendlyName, 'Task definition friendly name');
        assert.string(definition.implementsTask, 'Task definition implementsTask');
        assert.string(definition.runJob, 'Task definition job name');
        assert.object(definition.options, 'Task definition option');
        assert.object(definition.properties, 'Task definition properties');
        assert.object(context, 'Task shared context object');

        self.definition = _.cloneDeep(definition);
        self.options = self.definition.options;

        // run state related properties
        self.cancelled = false;
        self.retriesAttempted = 0;
        taskOverrides = taskOverrides || {};
        self.retriesAllowed = taskOverrides.retriesAllowed || 5;

        self.instanceId = taskOverrides.instanceId || uuid.v4();
        self.name = taskOverrides.name || self.definition.injectableName;
        self.friendlyName = taskOverrides.friendlyName || self.definition.friendlyName;
        self.waitingOn = taskOverrides.waitingOn || [];
        self.ignoreFailure = taskOverrides.ignoreFailure || false;
        self.tags = [];
        self.subscriptions = {};

        // tags for categorization and hinting functionality
        self.properties = definition.properties;

        self.context = {};
        // State bag shared throughout tasks in a TaskGraph
        self.parentContext = context;
        self.parentContext[self.instanceId] = self.context;

        // state of the current object
        self.state = PENDING;

        // hint to whatever is running the task when it is successful
        self.successStates = [SUCCEEDED];
        // hint to whatever is running the task when it has failed
        self.failedStates = [FAILED, TIMEOUT, CANCELLED];

        return self;
    }

    Task.prototype.instantiateJob = function() {
        assert.string(this.definition.runJob, 'Task.definition.runJob injector string');
        // This should already have been validated to exist
        var Job = injector.get(this.definition.runJob);
        this.job = new Job(this.options, this.parentContext, this.instanceId);
        assert.func(this.job.run, "Task Job run method");
        assert.func(this.job.cancel, "Task Job cancel method");
    };

    Task.prototype.publishFinished = function() {
        var self = this;
        return eventsProtocol.publishTaskFinished(self.instanceId)
        .catch(function(error) {
            logger.error("Error publishing Task finished event.", {
                error: error,
                taskId: self.instanceId,
                taskName: self.name,
                job: self.definition.runJob
            });
        });
    };

    Task.prototype._run = function () {
        var self = this;

        logger.info("Running task job.", {
            taskId: self.instanceId,
            name: self.definition.friendlyName,
            job: self.definition.runJob
        });

        // return for test
        return self.job.run()
        .then(function() {
            self.state = SUCCEEDED;
        })
        .catch(Errors.TaskCancellationError, function(e) {
            self.state = CANCELLED;
            self.error = e;
        })
        .catch(function(e) {
            self.state = FAILED;
            self.error = e;
        })
        .finally(function() {
            return self.finish();
        });
    };

    Task.prototype.run = function() {
        if (this.state === RUNNING) {
            return Promise.resolve();
        }
        this.state = RUNNING;

        try {
            this.instantiateJob();
        } catch (e) {
            this.state = FAILED;
            this.error = e;
            return this.finish();
        }

        return this._run();
    };

    Task.prototype.finish = function() {
        var self = this;
        // Because we're in a Promise.finally block, make sure any
        // exceptions are caught within these functions and
        // not bubbled up.
        return self.publishFinished()
        .then(function() {
            return self.cleanup();
        });
    };

    Task.prototype.cleanup = function() {
        var self = this;

        return Promise.all(_.map(self.subscriptions, function(subscription) {
            return subscription.dispose();
        }))
        .catch(function(error) {
            logger.error("Error cleaning up Task job.", {
                error: error,
                taskId: self.instanceId,
                taskName: self.name,
                job: self.definition.runJob
            });
        });
    };

    Task.prototype.cancel = function(error) {
        if (this.state === PENDING) {
            // This block handles cancellation before run() has
            // been called (i.e. the task has been created, but not
            // yet scheduled to run by the scheduler via taskProtocol.subscribeRun
            this.state = CANCELLED;
            if (error) {
                this.error = error;
            }
            return this.finish();
        } else if (this.state !== CANCELLED) {
            // Task cancellation is passed down to the job first
            // and then bubbled up into the promise chain
            // created in this.run()
            if (error) {
                this.error = error;
            }
            this.job.cancel(error);
        }
    };

    Task.prototype.start = function start() {
        var self = this;
        return Promise.all([
            taskProtocol.subscribeRun(self.instanceId, self.run.bind(self)),
            taskProtocol.subscribeCancel(self.instanceId, self.cancel.bind(self))
        ]).spread(function(runSubscription, cancelSubscription) {
            self.subscriptions.run = runSubscription;
            self.subscriptions.cancel = cancelSubscription;
            logger.info("Starting task.", {
                taskId: self.instanceId,
                name: self.definition.friendlyName
            });
        }).catch(function(error) {
            logger.error("Error starting Task subscriptions.", {
                error: error,
                taskId: self.instanceId,
                taskName: self.name
            });
        });
    };

    // enables JSON.stringify(this)
    Task.prototype.toJSON = function toJSON() {
        return this.serialize();
    };

    Task.prototype.serialize = function serialize() {
        var redactKeys = ['subscriptions', '_events', '_cancellable'];
        var obj = _.transform(this, function(result, v, k) {
            if (!_.contains(redactKeys, k)) {
                result[k] = v;
            }
        }, {});

        if (this.job) {
            obj.job = this.job.serialize();
        }

        return obj;
    };

    Task.create = function create(definition, taskOverrides, context) {
        var task = new Task(definition, taskOverrides, context);
        return task;
    };

    Task.createRegistryObject = function (definition) {
        var _definition = _.cloneDeep(definition);
        return {
            create: function(definitionOverrides, taskOverrides, context) {
                var instanceDefinition = _.defaults(definitionOverrides, _definition);
                return Task.create(instanceDefinition, taskOverrides, context);
            },
            definition: _definition
        };
    };

    return Task;
}
<commit_msg>Update capitalization style for Constants.TaskStates<commit_after>// Copyright 2014, Renasar Technologies Inc.
/* jshint: node:true */
'use strict';

var di = require('di');

module.exports = factory;
di.annotate(factory, new di.Provide('Task.Task'));
    di.annotate(factory,
    new di.Inject(
        'Protocol.Task',
        'Protocol.Events',
        'Logger',
        'Assert',
        'Errors',
        'Constants',
        'uuid',
        'Promise',
        '_',
        di.Injector
    )
);

/**
 * Injectable wrapper for dependencies
 * @param logger
 */
function factory(taskProtocol, eventsProtocol, Logger, assert, Errors, Constants,
        uuid, Promise, _, injector) {

    var TaskStates = Constants.TaskStates;
    var logger = Logger.initialize(factory);

    /**
     *
     * @param taskGraph
     * @param optionOverrides
     * @returns {factory.Task}
     * @constructor
     */
    function Task(definition, taskOverrides, context) {
        var self = this;

        assert.object(definition, 'Task definition data');
        assert.string(definition.friendlyName, 'Task definition friendly name');
        assert.string(definition.implementsTask, 'Task definition implementsTask');
        assert.string(definition.runJob, 'Task definition job name');
        assert.object(definition.options, 'Task definition option');
        assert.object(definition.properties, 'Task definition properties');
        assert.object(context, 'Task shared context object');

        self.definition = _.cloneDeep(definition);
        self.options = self.definition.options;

        // run state related properties
        self.cancelled = false;
        self.retriesAttempted = 0;
        taskOverrides = taskOverrides || {};
        self.retriesAllowed = taskOverrides.retriesAllowed || 5;

        self.instanceId = taskOverrides.instanceId || uuid.v4();
        self.name = taskOverrides.name || self.definition.injectableName;
        self.friendlyName = taskOverrides.friendlyName || self.definition.friendlyName;
        self.waitingOn = taskOverrides.waitingOn || [];
        self.ignoreFailure = taskOverrides.ignoreFailure || false;
        self.tags = [];
        self.subscriptions = {};

        // tags for categorization and hinting functionality
        self.properties = definition.properties;

        self.context = {};
        // State bag shared throughout tasks in a TaskGraph
        self.parentContext = context;
        self.parentContext[self.instanceId] = self.context;

        // state of the current object
        self.state = TaskStates.Pending;

        // hint to whatever is running the task when it is successful
        self.successStates = [TaskStates.Succeeded];
        // hint to whatever is running the task when it has failed
        self.failedStates = [TaskStates.Failed, TaskStates.Timeout, TaskStates.Cancelled];

        return self;
    }

    Task.prototype.instantiateJob = function() {
        assert.string(this.definition.runJob, 'Task.definition.runJob injector string');
        // This should already have been validated to exist
        var Job = injector.get(this.definition.runJob);
        this.job = new Job(this.options, this.parentContext, this.instanceId);
        assert.func(this.job.run, "Task Job run method");
        assert.func(this.job.cancel, "Task Job cancel method");
    };

    Task.prototype.publishFinished = function() {
        var self = this;
        return eventsProtocol.publishTaskFinished(self.instanceId)
        .catch(function(error) {
            logger.error("Error publishing Task finished event.", {
                error: error,
                taskId: self.instanceId,
                taskName: self.name,
                job: self.definition.runJob
            });
        });
    };

    Task.prototype._run = function () {
        var self = this;

        logger.info("Running task job.", {
            taskId: self.instanceId,
            name: self.definition.friendlyName,
            job: self.definition.runJob
        });

        // return for test
        return self.job.run()
        .then(function() {
            self.state = TaskStates.Succeeded;
        })
        .catch(Errors.TaskCancellationError, function(e) {
            self.state = TaskStates.Cancelled;
            self.error = e;
        })
        .catch(function(e) {
            self.state = TaskStates.Failed;
            self.error = e;
        })
        .finally(function() {
            return self.finish();
        });
    };

    Task.prototype.run = function() {
        if (this.state === TaskStates.Running) {
            return Promise.resolve();
        }
        this.state = TaskStates.Running;

        try {
            this.instantiateJob();
        } catch (e) {
            this.state = TaskStates.Failed;
            this.error = e;
            return this.finish();
        }

        return this._run();
    };

    Task.prototype.finish = function() {
        var self = this;
        // Because we're in a Promise.finally block, make sure any
        // exceptions are caught within these functions and
        // not bubbled up.
        return self.publishFinished()
        .then(function() {
            return self.cleanup();
        });
    };

    Task.prototype.cleanup = function() {
        var self = this;

        return Promise.all(_.map(self.subscriptions, function(subscription) {
            return subscription.dispose();
        }))
        .catch(function(error) {
            logger.error("Error cleaning up Task job.", {
                error: error,
                taskId: self.instanceId,
                taskName: self.name,
                job: self.definition.runJob
            });
        });
    };

    Task.prototype.cancel = function(error) {
        if (this.state === TaskStates.Pending) {
            // This block handles cancellation before run() has
            // been called (i.e. the task has been created, but not
            // yet scheduled to run by the scheduler via taskProtocol.subscribeRun
            this.state = TaskStates.Cancelled;
            if (error) {
                this.error = error;
            }
            return this.finish();
        } else if (this.state !== TaskStates.Cancelled) {
            // Task cancellation is passed down to the job first
            // and then bubbled up into the promise chain
            // created in this.run()
            if (error) {
                this.error = error;
            }
            this.job.cancel(error);
        }
    };

    Task.prototype.start = function start() {
        var self = this;
        return Promise.all([
            taskProtocol.subscribeRun(self.instanceId, self.run.bind(self)),
            taskProtocol.subscribeCancel(self.instanceId, self.cancel.bind(self))
        ]).spread(function(runSubscription, cancelSubscription) {
            self.subscriptions.run = runSubscription;
            self.subscriptions.cancel = cancelSubscription;
            logger.info("Starting task.", {
                taskId: self.instanceId,
                name: self.definition.friendlyName
            });
        }).catch(function(error) {
            logger.error("Error starting Task subscriptions.", {
                error: error,
                taskId: self.instanceId,
                taskName: self.name
            });
        });
    };

    // enables JSON.stringify(this)
    Task.prototype.toJSON = function toJSON() {
        return this.serialize();
    };

    Task.prototype.serialize = function serialize() {
        var redactKeys = ['subscriptions', '_events', '_cancellable'];
        var obj = _.transform(this, function(result, v, k) {
            if (!_.contains(redactKeys, k)) {
                result[k] = v;
            }
        }, {});

        if (this.job) {
            obj.job = this.job.serialize();
        }

        return obj;
    };

    Task.create = function create(definition, taskOverrides, context) {
        var task = new Task(definition, taskOverrides, context);
        return task;
    };

    Task.createRegistryObject = function (definition) {
        var _definition = _.cloneDeep(definition);
        return {
            create: function(definitionOverrides, taskOverrides, context) {
                var instanceDefinition = _.defaults(definitionOverrides, _definition);
                return Task.create(instanceDefinition, taskOverrides, context);
            },
            definition: _definition
        };
    };

    return Task;
}
<|endoftext|>


<commit_before>window.ContactManager = {
  Models: {},
  Collections: {},
  Views: {},

  start: function(data) {
    var contacts = new ContactManager.Collections.Contacts(data.contacts),
        router = new ContactManager.Router();

    router.on('route:home', function() {
      router.navigate('contacts', {
        trigger: true,
        replace: true
      });
    });

    router.on('route:showContacts', function() {
      var contactsView = new ContactManager.Views.Contacts({
        collection: contacts
      });

      $('.main-container').html(contactsView.render().$el);
    });

    router.on('route:newContact', function() {
      var newContactForm = new ContactManager.Views.ContactForm();

      newContactForm.on('form:submitted', function(attrs) {
        attrs.id = contacts.isEmpty() ? 1 : (_.max(contacts.pluck('id')) + 1);
        contacts.add(attrs);
        router.navigate('contacts', true);
      });

      $('.main-container').html(newContactForm.render().$el);
    });

    router.on('route:editContact', function(id) {
      console.log('Edit contact');
    });

    Backbone.history.start();
  }
};
<commit_msg>Show empty ContactForm on #/contacts/new/:id path<commit_after>window.ContactManager = {
  Models: {},
  Collections: {},
  Views: {},

  start: function(data) {
    var contacts = new ContactManager.Collections.Contacts(data.contacts),
        router = new ContactManager.Router();

    router.on('route:home', function() {
      router.navigate('contacts', {
        trigger: true,
        replace: true
      });
    });

    router.on('route:showContacts', function() {
      var contactsView = new ContactManager.Views.Contacts({
        collection: contacts
      });

      $('.main-container').html(contactsView.render().$el);
    });

    router.on('route:newContact', function() {
      var newContactForm = new ContactManager.Views.ContactForm();

      newContactForm.on('form:submitted', function(attrs) {
        attrs.id = contacts.isEmpty() ? 1 : (_.max(contacts.pluck('id')) + 1);
        contacts.add(attrs);
        router.navigate('contacts', true);
      });

      $('.main-container').html(newContactForm.render().$el);
    });

    router.on('route:editContact', function(id) {
      var contact = contacts.get(id),
          editContactForm;

      if (contact) {
        editContactForm = new ContactManager.Views.ContactForm({
            model: contact
        });

        $('.main-container').html(editContactForm.render().$el);
      } else {
        router.navigate('contacts', true);
      }
    });

    Backbone.history.start();
  }
};
<|endoftext|>


<commit_before>$( document ).ready(function() {
	var height = $(window).height();
	var width = $(window).width();
	d3.select(".can")
			.attr("width",width)
			.attr("height",height);
	d3.select("svg .canvas")
			.attr("width",width)
			.attr("height",height);
	var rectangles = [];
	//I know you can do it using a color scale but I think this way you get more control
	var colorH = d3.scale.linear().domain([0,height]).range([0,255]);
	var colorW = d3.scale.linear().domain([0,width]).range([0,255]);
	var colorB = d3.scale.linear().domain([0,(width+height)]).range([255,0]);
	function toRGB (color){
		color = color.replace("rgb(","");
		color = color.replace(")","");
		color = color.split(",");
		return color.map(function (x) {
	    		return parseInt(x);
			});
	}
	function colorChanger(x,y,sign,amount){
		var currentColor  = rectangles[x][y].attr("fill");
		var colors = toRGB(currentColor);
		var k = colors[0];
		var l = colors[1];
		if(sign == '+'){
			k = colors[0]+amount;
			l = colors[1]+amount;
		}else{
			k = colors[0]-amount;
			l = colors[1]-amount;
		}

		var newColor = "rgb("+k+","+l+","+Math.floor((l+k)/2)+")";	return newColor;;
	}
	function change(x,u,c,s,a){
		try{
			currentCircle(x,u,c,s,a);
		}catch(err){};
	}
	function rippleEffect(x,y){
		var max = 120;
		var newcounter = 0;
		var counter = 0;
		for(var i = 0; i < max; i++){
			setTimeout(function(){
					if(newcounter < (max-5)){
						change(x,y,newcounter,'+',2);
						currentCircle(x,y,newcounter-1,'+',2);
						currentCircle(x,y,newcounter-2,'+',2);
						currentCircle(x,y,newcounter-3,'+',2);
						currentCircle(x,y,newcounter-4,'+',2);
					}
					if(newcounter >=5){
						currentCircle(x,y,(newcounter-5),'-',2);
					}
					if(newcounter >=7){
						currentCircle(x,y,(newcounter-7),'-',2);
					}
					if(newcounter >=9){
							currentCircle(x,y,(newcounter-9),'-',2);
					}
					if(newcounter >=11){
							currentCircle(x,y,(newcounter-11),'-',2);
					}
					if(newcounter >=13){
							currentCircle(x,y,(newcounter-13),'-',2);
					}
					newcounter++;
				}, counter++*60);
		}

		newcounter = 0;
		counter = 0;
	}
	function makeripple(x,y){

	}
	function rectangleChanger(x,y,sign,amount){
		try{
			rectangles[x][y].attr("fill",colorChanger(x,y,sign,amount));
		}catch(err){}
	}
	function currentCircle(x0,y0,radius,sign,amount){
		//MidPoint_Circle_Algarithm
		var x = radius;
		var y = 0;
		var decisionOver2 = 1-x;
		while(x >= y){
			rectangleChanger(y0+y,x0+x,sign,amount);
			rectangleChanger(y0+y,x0+x,sign,amount);
			rectangleChanger(y0-y,x0+x,sign,amount);
			rectangleChanger(y0-y,x0-x,sign,amount);
			rectangleChanger(y0+y,x0-x,sign,amount);
			rectangleChanger(y0+x,x0-y,sign,amount);
			rectangleChanger(y0+x,x0+y,sign,amount);
			rectangleChanger(y0-x,x0+y,sign,amount);
			rectangleChanger(y0-x,x0-y,sign,amount);
		y++;
		if(decisionOver2 <0){
			decisionOver2 += 2 * y + 1;
		}else{
			x--;
			decisionOver2 += 2 * (y - x) +1;
		}
		}
	}
	var r = window.prompt("please enter indivudual width, smaller = better quality but more graphically intensive(between 5-10 for normal power computers)", 10);
	var squarerectangles = {width: parseInt(r),height: parseInt(r)};
	var x = 0;
	var y = 0;
	for (var i = 0; i < width; i = i + squarerectangles.width){
		var row = [];
		for (var k = 0; k < height; k = k + squarerectangles.height){
			row.push(d3.select(".canvas").append("circle")
				.attr("fill",function(){
					return "rgb("+Math.floor(colorW(i))+","+Math.floor(colorH(k))+","+Math.floor(colorB((i+k)))+")";
				})
				.attr("cx",i)
				.attr("cy",k)
				.attr("r",squarerectangles.width)
				.attr("id",x+++","+y)
				.on("click",function(d){
					var position = this.id.split(",");
					rippleEffect(parseInt(position[0]),parseInt(position[1]))
				})
				)
			}
		y++;
		rectangles.push(row);
		row = [];
		x = 0;
	}
});
<commit_msg>Update Starter.js<commit_after>$( document ).ready(function() {
	var height = $(window).height();
	var width = $(window).width();
	d3.select(".can")
			.attr("width",width)
			.attr("height",height);
	d3.select("svg .canvas")
			.attr("width",width)
			.attr("height",height);
	var rectangles = [];
	//I know you can do it using a color scale but I think this way you get more control
	var colorH = d3.scale.linear().domain([0,height]).range([0,255]);
	var colorW = d3.scale.linear().domain([0,width]).range([0,255]);
	var colorB = d3.scale.linear().domain([0,(width+height)]).range([255,0]);
	function toRGB (color){
		color = color.replace("rgb(","");
		color = color.replace(")","");
		color = color.split(",");
		return color.map(function (x) {
	    		return parseInt(x);
			});
	}
	function colorChanger(x,y,sign,amount){
		var currentColor  = rectangles[x][y].attr("fill");
		var colors = toRGB(currentColor);
		var k = colors[0];
		var l = colors[1];
		if(sign == '+'){
			k = colors[0]+amount;
			l = colors[1]+amount;
		}else{
			k = colors[0]-amount;
			l = colors[1]-amount;
		}

		var newColor = "rgb("+k+","+l+","+"0"+")";	return newColor;;
	}
	function change(x,u,c,s,a){
		try{
			currentCircle(x,u,c,s,a);
		}catch(err){};
	}
	function rippleEffect(x,y){
		var max = 120;
		var newcounter = 0;
		var counter = 0;
		for(var i = 0; i < max; i++){
			setTimeout(function(){
					if(newcounter < (max-5)){
						change(x,y,newcounter,'+',2);
						currentCircle(x,y,newcounter-1,'+',2);
						currentCircle(x,y,newcounter-2,'+',2);
						currentCircle(x,y,newcounter-3,'+',2);
						currentCircle(x,y,newcounter-4,'+',2);
					}
					if(newcounter >=5){
						currentCircle(x,y,(newcounter-5),'-',2);
					}
					if(newcounter >=7){
						currentCircle(x,y,(newcounter-7),'-',2);
					}
					if(newcounter >=9){
							currentCircle(x,y,(newcounter-9),'-',2);
					}
					if(newcounter >=11){
							currentCircle(x,y,(newcounter-11),'-',2);
					}
					if(newcounter >=13){
							currentCircle(x,y,(newcounter-13),'-',2);
					}
					newcounter++;
				}, counter++*60);
		}

		newcounter = 0;
		counter = 0;
	}
	function makeripple(x,y){

	}
	function rectangleChanger(x,y,sign,amount){
		try{
			rectangles[x][y].attr("fill",colorChanger(x,y,sign,amount));
		}catch(err){}
	}
	function currentCircle(x0,y0,radius,sign,amount){
		//MidPoint_Circle_Algarithm
		var x = radius;
		var y = 0;
		var decisionOver2 = 1-x;
		while(x >= y){
			rectangleChanger(y0+y,x0+x,sign,amount);
			rectangleChanger(y0+y,x0+x,sign,amount);
			rectangleChanger(y0-y,x0+x,sign,amount);
			rectangleChanger(y0-y,x0-x,sign,amount);
			rectangleChanger(y0+y,x0-x,sign,amount);
			rectangleChanger(y0+x,x0-y,sign,amount);
			rectangleChanger(y0+x,x0+y,sign,amount);
			rectangleChanger(y0-x,x0+y,sign,amount);
			rectangleChanger(y0-x,x0-y,sign,amount);
		y++;
		if(decisionOver2 <0){
			decisionOver2 += 2 * y + 1;
		}else{
			x--;
			decisionOver2 += 2 * (y - x) +1;
		}
		}
	}
	var r = window.prompt("please enter indivudual width, smaller = better quality but more graphically intensive(between 5-10 for normal power computers)", 10);
	var squarerectangles = {width: parseInt(r),height: parseInt(r)};
	var x = 0;
	var y = 0;
	for (var i = 0; i < width; i = i + squarerectangles.width){
		var row = [];
		for (var k = 0; k < height; k = k + squarerectangles.height){
			row.push(d3.select(".canvas").append("circle")
				.attr("fill",function(){
					return "rgb("+Math.floor(colorW(i))+","+Math.floor(colorH(k))+",0"+")";
				})
				.attr("cx",i)
				.attr("cy",k)
				.attr("r",squarerectangles.width)
				.attr("id",x+++","+y)
				.on("click",function(d){
					var position = this.id.split(",");
					rippleEffect(parseInt(position[0]),parseInt(position[1]))
				})
				)
			}
		y++;
		rectangles.push(row);
		row = [];
		x = 0;
	}
});
<|endoftext|>


<commit_before>'use strict';

var app = angular.module('app', [
  'app.constants',
  'app.helpers',
  'app.i18n',
  'pascalprecht.translate',
  'app.filters',
  'app.services',
  'app.directives',
  'app.vis',
  'ngSanitize',
  'ui.utils',
  'ui.showhide',
  'ui.select2',
  'ui.validate',
  'ui.bootstrap',
  'ui.bootstrap.tpls'
  ])
  .directive('dynamic', function ($compile) {
    return {
      restrict: 'A',
      replace: true,
      link: function (scope, ele, attrs) {
        scope.$watch(attrs.dynamic, function(html) {
          ele.html(html);
          $compile(ele.contents())(scope);
        });
      }
    };
  })
  .config(function($tooltipProvider, $httpProvider, $translateProvider, DEFAULT_LANG) {

      $translateProvider.preferredLanguage(DEFAULT_LANG);

      $translateProvider.useStaticFilesLoader({
          prefix: './locale/',
          suffix: '.json'
      });
    // Add the X-Requested-With header back in when we configure http provider; otherwise, making POST requests doesn't work
    // version 1.1.* and above of AngularJS dropped this default behavior
    // see here for related info http://django-angular.readthedocs.org/en/latest/integration.html
    $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
    $tooltipProvider.options({
      appendToBody: true
    });
  })
  // angular-ui config
  .value('ui.config', {
    animate: 'ui-hide',
  })
  .run(function ($filter, $log, $rootScope, $timeout, $window,
                 $translate, apiSrvc, gaMgr, modelSrvc, ENUMS, EXTERNAL_URL, LANTERNUI_VER, MODAL, CONTACT_FORM_MAXLEN) {
    var CONNECTIVITY = ENUMS.CONNECTIVITY,
        MODE = ENUMS.MODE,
        i18nFltr = $filter('i18n'),
        jsonFltr = $filter('json'),
        model = modelSrvc.model,
        prettyUserFltr = $filter('prettyUser'),
        reportedStateFltr = $filter('reportedState');

    // for easier inspection in the JavaScript console
    $window.rootScope = $rootScope;
    $window.model = model;

    $rootScope.EXTERNAL_URL = EXTERNAL_URL;
    $rootScope.lanternUiVersion = LANTERNUI_VER.join('.');
    $rootScope.model = model;
    $rootScope.DEFAULT_AVATAR_URL = 'img/default-avatar.png';
    $rootScope.CONTACT_FORM_MAXLEN = CONTACT_FORM_MAXLEN;

    angular.forEach(ENUMS, function(val, key) {
      $rootScope[key] = val;
    });

    $rootScope.$watch('model.settings.autoReport', function (autoReport, autoReportOld) {
      if (!model.setupComplete) return;
      if (!autoReport && autoReportOld) {
        gaMgr.stopTracking();
      } else if (autoReport && !autoReportOld) {
        gaMgr.startTracking();
      }
    });

    $rootScope.$watch('model.modal', function (modal, modalOld) {
      if (!model.setupComplete || !model.settings.autoReport || angular.isUndefined(modalOld)) {
        return;
      }
      gaMgr.trackPageView('start');
    });

    $rootScope.$watch('model.notifications', function (notifications) {
      _.each(notifications, function(notification, id) {
        if (notification.autoClose) {
          $timeout(function() {
            $rootScope.interaction(INTERACTION.close, {notification: id, auto: true});
          }, notification.autoClose * 1000);
        }
      });
    }, true);

    $rootScope.$watch('model.settings.mode', function (mode) {
      $rootScope.inGiveMode = mode === MODE.give;
      $rootScope.inGetMode = mode === MODE.get;
    });

    $rootScope.$watch('model.mock', function (mock) {
      $rootScope.mockBackend = !!mock;
    });

    $rootScope.$watch('model.location.country', function (country) {
      if (country && model.countries[country]) {
        $rootScope.inCensoringCountry = model.countries[country].censors;
      }
    });

    $rootScope.$watch('model.globalStats', function (stats) {
      $rootScope.statsLoaded = !!stats && !_.isEmpty(stats.gauges);
    });

    $rootScope.$watch('model.roster', function (roster) {
      if (!roster) return;
      updateContactCompletions();
    }, true);

    $rootScope.$watch('model.friends', function (friends) {
      if (!friends) return;
      $rootScope.nfriends = 0;
      $rootScope.nfriendSuggestions = 0;
      $rootScope.friendSuggestions = [];
      $rootScope.friendsByEmail = {};
      for (var i=0, l=friends.length, ii=friends[i]; ii; ii=friends[++i]) {
        $rootScope.friendsByEmail[ii.email] = ii;
        if (ii.status === FRIEND_STATUS.pending) {
          if (model.remainingFriendingQuota || ii.freeToFriend) {
            $rootScope.nfriendSuggestions++;
            $rootScope.friendSuggestions.push(ii);
          }
        } else if (ii.status == FRIEND_STATUS.friend) {
          $rootScope.nfriends++;
        }
      }
      updateContactCompletions();
    }, true);

    function updateContactCompletions() {
      var roster = model.roster;
      if (!roster) return;
      var completions = {};
      _.each(model.friends, function (friend) {
        if (friend.status !== FRIEND_STATUS.friend) {
          completions[friend.email] = friend;
        }
      });
      if ($rootScope.friendsByEmail) {
        _.each(roster, function (contact) {
          var email = contact.email, friend = email && $rootScope.friendsByEmail[email];
          if (email && (!friend || friend.status !== FRIEND_STATUS.friend)) {
            // if an entry for this email was added in the previous loop, we want
            // this entry to overwrite it since the roster object has more data
            completions[contact.email] = contact;
          }
        });
      }
      //completions = _.sortBy(completions, function (i) { return prettyUserFltr(i); }); // XXX sort by contact frequency instead
      $rootScope.contactCompletions = completions;
    }

    $rootScope.reload = function () {
      location.reload(true); // true to bypass cache and force request to server
    };

    $rootScope.switchLang = function (lang) {
        $rootScope.lang = lang;
        $translate.use(lang);
    };

    $rootScope.interaction = function (interactionid, extra) {
      var stopTracking = interactionid === INTERACTION.reset && model.modal === MODAL.confirmReset;
      return apiSrvc.interaction(interactionid, extra)
        .success(function(data, status, headers, config) {
          if (extra && extra.lang !== 'undefined') {
              $rootScope.switchLang(extra.lang);
          }
          $log.debug('interaction(', interactionid, extra || '', ') successful');
          if (stopTracking) {
            gaMgr.stopTracking();
          }
        })
        .error(function(data, status, headers, config) {
          $log.error('interaction(', interactionid, extra, ') failed');
          apiSrvc.exception({data: data, status: status, headers: headers, config: config});
        });
    };

    $rootScope.changeSetting = function(key, val) {
      var update = {path: '/settings/'+key, value: val};
      return $rootScope.interaction(INTERACTION.set, update);
    };

    $rootScope.changeLang = function(lang) {
      return $rootScope.interaction(INTERACTION.changeLang, {lang: lang});
    };

    $rootScope.openRouterConfig = function() {
      return $rootScope.interaction(INTERACTION.routerConfig);
    };

    $rootScope.openExternal = function(url) {
      if ($rootScope.mockBackend) {
        return $window.open(url);
      } else {
        return $rootScope.interaction(INTERACTION.url, {url: url});
      }
    };

    $rootScope.resetContactForm = function (scope) {
      if (scope.show) {
        var reportedState = jsonFltr(reportedStateFltr(model));
        scope.diagnosticInfo = reportedState;
      }
    };

    $rootScope.interactionWithNotify = function (interactionid, scope, reloadAfter) {
      var extra;
      if (scope.notify) {
        var diagnosticInfo = scope.diagnosticInfo;
        if (diagnosticInfo) {
          try {
            diagnosticInfo = angular.fromJson(diagnosticInfo);
          } catch (e) {
            $log.debug('JSON decode diagnosticInfo', diagnosticInfo, 'failed, passing as-is');
          }
        }
        extra = {
          context: model.modal,
          message: scope.message,
          diagnosticInfo: diagnosticInfo
        };
      }
      $rootScope.interaction(interactionid, extra).then(function () {
        if (reloadAfter) $rootScope.reload();
      });
    };

    /**
     * Checks whether the backend is gone (based on last successful connect time).
     */
    $rootScope.backendIsGone = false;
    $rootScope.$watch("cometdConnected", function(cometdConnected) {
      var MILLIS_UNTIL_BACKEND_CONSIDERED_GONE = 10000;
      if (!cometdConnected) {
        // In 11 seconds, check if we're still not connected
        $timeout(function() {
          var lastConnectedAt = $rootScope.cometdLastConnectedAt;
          if (lastConnectedAt) {
            var timeSinceLastConnected = new Date().getTime() - lastConnectedAt.getTime();
            $log.debug("Time since last connect", timeSinceLastConnected);
            if (timeSinceLastConnected > MILLIS_UNTIL_BACKEND_CONSIDERED_GONE) {
              // If it's been more than 10 seconds since we last connect,
              // treat the backend as gone
              $log.debug("Backend is gone");
              $rootScope.backendIsGone = true;
              window.close();
            } else {
              $rootScope.backendIsGone = false;
            }
          }
        }, MILLIS_UNTIL_BACKEND_CONSIDERED_GONE + 1);
      }
    });
  });
<commit_msg>remove synchronous ajax request in version file<commit_after>'use strict';

var app = angular.module('app', [
  'app.constants',
  'app.helpers',
  'app.i18n',
  'pascalprecht.translate',
  'app.filters',
  'app.services',
  'app.directives',
  'app.vis',
  'ngSanitize',
  'ui.utils',
  'ui.showhide',
  'ui.select2',
  'ui.validate',
  'ui.bootstrap',
  'ui.bootstrap.tpls'
  ])
  .directive('dynamic', function ($compile) {
    return {
      restrict: 'A',
      replace: true,
      link: function (scope, ele, attrs) {
        scope.$watch(attrs.dynamic, function(html) {
          ele.html(html);
          $compile(ele.contents())(scope);
        });
      }
    };
  })
  .config(function($tooltipProvider, $httpProvider, $translateProvider, DEFAULT_LANG) {

      $translateProvider.preferredLanguage(DEFAULT_LANG);

      $translateProvider.useStaticFilesLoader({
          prefix: './locale/',
          suffix: '.json'
      });
    // Add the X-Requested-With header back in when we configure http provider; otherwise, making POST requests doesn't work
    // version 1.1.* and above of AngularJS dropped this default behavior
    // see here for related info http://django-angular.readthedocs.org/en/latest/integration.html
    $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
    $tooltipProvider.options({
      appendToBody: true
    });
  })
  // angular-ui config
  .value('ui.config', {
    animate: 'ui-hide',
  })
  .run(function ($filter, $log, $rootScope, $timeout, $window,
                 $translate, $http, apiSrvc, gaMgr, modelSrvc, ENUMS, EXTERNAL_URL, MODAL, CONTACT_FORM_MAXLEN) {
    var CONNECTIVITY = ENUMS.CONNECTIVITY,
        MODE = ENUMS.MODE,
        i18nFltr = $filter('i18n'),
        jsonFltr = $filter('json'),
        model = modelSrvc.model,
        prettyUserFltr = $filter('prettyUser'),
        reportedStateFltr = $filter('reportedState');

    // for easier inspection in the JavaScript console
    $window.rootScope = $rootScope;
    $window.model = model;

    $rootScope.EXTERNAL_URL = EXTERNAL_URL;

    $http.get('data/package.json').
      success(function(pkg, status, headers, config) {
      var version = pkg.version,
        components = version.split('.'),
        major = components[0],
        minor = components[1],
        patch = (components[2] || '').split('-')[0];
        $rootScope.lanternUiVersion = [major, minor, patch].join('.');
    }).error(function(data, status, headers, config) {
       console.log("Error retrieving UI version!");
    });

    $rootScope.model = model;
    $rootScope.DEFAULT_AVATAR_URL = 'img/default-avatar.png';
    $rootScope.CONTACT_FORM_MAXLEN = CONTACT_FORM_MAXLEN;

    angular.forEach(ENUMS, function(val, key) {
      $rootScope[key] = val;
    });

    $rootScope.$watch('model.settings.autoReport', function (autoReport, autoReportOld) {
      if (!model.setupComplete) return;
      if (!autoReport && autoReportOld) {
        gaMgr.stopTracking();
      } else if (autoReport && !autoReportOld) {
        gaMgr.startTracking();
      }
    });

    $rootScope.$watch('model.modal', function (modal, modalOld) {
      if (!model.setupComplete || !model.settings.autoReport || angular.isUndefined(modalOld)) {
        return;
      }
      gaMgr.trackPageView('start');
    });

    $rootScope.$watch('model.notifications', function (notifications) {
      _.each(notifications, function(notification, id) {
        if (notification.autoClose) {
          $timeout(function() {
            $rootScope.interaction(INTERACTION.close, {notification: id, auto: true});
          }, notification.autoClose * 1000);
        }
      });
    }, true);

    $rootScope.$watch('model.settings.mode', function (mode) {
      $rootScope.inGiveMode = mode === MODE.give;
      $rootScope.inGetMode = mode === MODE.get;
    });

    $rootScope.$watch('model.mock', function (mock) {
      $rootScope.mockBackend = !!mock;
    });

    $rootScope.$watch('model.location.country', function (country) {
      if (country && model.countries[country]) {
        $rootScope.inCensoringCountry = model.countries[country].censors;
      }
    });

    $rootScope.$watch('model.globalStats', function (stats) {
      $rootScope.statsLoaded = !!stats && !_.isEmpty(stats.gauges);
    });

    $rootScope.$watch('model.roster', function (roster) {
      if (!roster) return;
      updateContactCompletions();
    }, true);

    $rootScope.$watch('model.friends', function (friends) {
      if (!friends) return;
      $rootScope.nfriends = 0;
      $rootScope.nfriendSuggestions = 0;
      $rootScope.friendSuggestions = [];
      $rootScope.friendsByEmail = {};
      for (var i=0, l=friends.length, ii=friends[i]; ii; ii=friends[++i]) {
        $rootScope.friendsByEmail[ii.email] = ii;
        if (ii.status === FRIEND_STATUS.pending) {
          if (model.remainingFriendingQuota || ii.freeToFriend) {
            $rootScope.nfriendSuggestions++;
            $rootScope.friendSuggestions.push(ii);
          }
        } else if (ii.status == FRIEND_STATUS.friend) {
          $rootScope.nfriends++;
        }
      }
      updateContactCompletions();
    }, true);

    function updateContactCompletions() {
      var roster = model.roster;
      if (!roster) return;
      var completions = {};
      _.each(model.friends, function (friend) {
        if (friend.status !== FRIEND_STATUS.friend) {
          completions[friend.email] = friend;
        }
      });
      if ($rootScope.friendsByEmail) {
        _.each(roster, function (contact) {
          var email = contact.email, friend = email && $rootScope.friendsByEmail[email];
          if (email && (!friend || friend.status !== FRIEND_STATUS.friend)) {
            // if an entry for this email was added in the previous loop, we want
            // this entry to overwrite it since the roster object has more data
            completions[contact.email] = contact;
          }
        });
      }
      //completions = _.sortBy(completions, function (i) { return prettyUserFltr(i); }); // XXX sort by contact frequency instead
      $rootScope.contactCompletions = completions;
    }

    $rootScope.reload = function () {
      location.reload(true); // true to bypass cache and force request to server
    };

    $rootScope.switchLang = function (lang) {
        $rootScope.lang = lang;
        $translate.use(lang);
    };

    $rootScope.interaction = function (interactionid, extra) {
      var stopTracking = interactionid === INTERACTION.reset && model.modal === MODAL.confirmReset;
      return apiSrvc.interaction(interactionid, extra)
        .success(function(data, status, headers, config) {
          if (extra && extra.lang !== 'undefined') {
              $rootScope.switchLang(extra.lang);
          }
          $log.debug('interaction(', interactionid, extra || '', ') successful');
          if (stopTracking) {
            gaMgr.stopTracking();
          }
        })
        .error(function(data, status, headers, config) {
          $log.error('interaction(', interactionid, extra, ') failed');
          apiSrvc.exception({data: data, status: status, headers: headers, config: config});
        });
    };

    $rootScope.changeSetting = function(key, val) {
      var update = {path: '/settings/'+key, value: val};
      return $rootScope.interaction(INTERACTION.set, update);
    };

    $rootScope.changeLang = function(lang) {
      return $rootScope.interaction(INTERACTION.changeLang, {lang: lang});
    };

    $rootScope.openRouterConfig = function() {
      return $rootScope.interaction(INTERACTION.routerConfig);
    };

    $rootScope.openExternal = function(url) {
      if ($rootScope.mockBackend) {
        return $window.open(url);
      } else {
        return $rootScope.interaction(INTERACTION.url, {url: url});
      }
    };

    $rootScope.resetContactForm = function (scope) {
      if (scope.show) {
        var reportedState = jsonFltr(reportedStateFltr(model));
        scope.diagnosticInfo = reportedState;
      }
    };

    $rootScope.interactionWithNotify = function (interactionid, scope, reloadAfter) {
      var extra;
      if (scope.notify) {
        var diagnosticInfo = scope.diagnosticInfo;
        if (diagnosticInfo) {
          try {
            diagnosticInfo = angular.fromJson(diagnosticInfo);
          } catch (e) {
            $log.debug('JSON decode diagnosticInfo', diagnosticInfo, 'failed, passing as-is');
          }
        }
        extra = {
          context: model.modal,
          message: scope.message,
          diagnosticInfo: diagnosticInfo
        };
      }
      $rootScope.interaction(interactionid, extra).then(function () {
        if (reloadAfter) $rootScope.reload();
      });
    };

    /**
     * Checks whether the backend is gone (based on last successful connect time).
     */
    $rootScope.backendIsGone = false;
    $rootScope.$watch("cometdConnected", function(cometdConnected) {
      var MILLIS_UNTIL_BACKEND_CONSIDERED_GONE = 10000;
      if (!cometdConnected) {
        // In 11 seconds, check if we're still not connected
        $timeout(function() {
          var lastConnectedAt = $rootScope.cometdLastConnectedAt;
          if (lastConnectedAt) {
            var timeSinceLastConnected = new Date().getTime() - lastConnectedAt.getTime();
            $log.debug("Time since last connect", timeSinceLastConnected);
            if (timeSinceLastConnected > MILLIS_UNTIL_BACKEND_CONSIDERED_GONE) {
              // If it's been more than 10 seconds since we last connect,
              // treat the backend as gone
              $log.debug("Backend is gone");
              $rootScope.backendIsGone = true;
              window.close();
            } else {
              $rootScope.backendIsGone = false;
            }
          }
        }, MILLIS_UNTIL_BACKEND_CONSIDERED_GONE + 1);
      }
    });
  });
<|endoftext|>


<commit_before>var React = require('react-native')

var {
  StyleSheet,
  Text,
  View,
  TouchableHighlight,
  ActivityIndicatorIOS,
  TextInput,
  ListView
} = React;

var styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
  },
  buttonText: {
    fontSize: 18,
    color: 'white'
  },
  button: {
    height: 60,
    backgroundColor: '#48BBEC',
    flex: 3,
    alignItems: 'center',
    justifyContent: 'center'
  },
  searchInput: {
    height: 60,
    padding: 10,
    fontSize: 18,
    color: '#111',
    flex: 10
  },
  rowContainer: {
    padding: 10,
  },
  footerContainer: {
    backgroundColor: '#E3E3E3',
    alignItems: 'center',
    flexDirection: 'row'
  }
});

class PastTrips extends React.Component{
  constructor(props){
    super(props);
    this.ds = new ListView.DataSource({rowHasChanged: (row1, row2) => row1 !== row2})
    this.state = {
      dataSource: this.ds.cloneWithRows(this.props.trips),
      error: ''
    }
  }
  // handleChange(e){
  //   this.setState({
  //     trip: e.nativeEvent.text
  //   })
  // }
    //   this.setState({
    //     dataSource: this.ds.cloneWithRows(data)
    //   })
    // })

  renderRow(rowData){
    return (
      <View>
        <View style={styles.rowContainer}>
          <Text> {rowData.name} </Text>
        </View>
      </View>
    )
  }

  render(){
    return (
      <View style={styles.container}>
          <ListView
            dataSource={this.state.dataSource}
            renderRow={this.renderRow} />
      </View>
    )
  }
};

module.exports = PastTrips;<commit_msg>Remove comments from past trips<commit_after>var React = require('react-native')

var {
  StyleSheet,
  Text,
  View,
  TouchableHighlight,
  ActivityIndicatorIOS,
  TextInput,
  ListView
} = React;

var styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
  },
  buttonText: {
    fontSize: 18,
    color: 'white'
  },
  button: {
    height: 60,
    backgroundColor: '#48BBEC',
    flex: 3,
    alignItems: 'center',
    justifyContent: 'center'
  },
  searchInput: {
    height: 60,
    padding: 10,
    fontSize: 18,
    color: '#111',
    flex: 10
  },
  rowContainer: {
    padding: 10,
  },
  footerContainer: {
    backgroundColor: '#E3E3E3',
    alignItems: 'center',
    flexDirection: 'row'
  }
});

class PastTrips extends React.Component{
  constructor(props){
    super(props);
    this.ds = new ListView.DataSource({rowHasChanged: (row1, row2) => row1 !== row2})
    this.state = {
      dataSource: this.ds.cloneWithRows(this.props.trips),
      error: ''
    }
  }

  renderRow(rowData){
    return (
      <View>
        <View style={styles.rowContainer}>
          <Text> {rowData.name} </Text>
        </View>
      </View>
    )
  }

  render(){
    return (
      <View style={styles.container}>
          <ListView
            dataSource={this.state.dataSource}
            renderRow={this.renderRow} />
      </View>
    )
  }
};

module.exports = PastTrips;<|endoftext|>


<commit_before>import React from 'react'
import { bool, object } from 'prop-types'

import { FinishPostDonation } from 'bonde-webpage/lib/plugins/donation/components'

console.log(FinishPostDonation)

const DonationFinishPostDonation = ({ preview, mobilization, widget }) => {
  return (

teste

  )
}

DonationFinishPostDonation.propTypes = {
  preview: bool,
  mobilization: object.isRequired,
  widget: object.isRequired
}

export default DonationFinishPostDonation
<commit_msg>feat(admin): refactor plugin admin page<commit_after>import React from 'react'
import { bool, object } from 'prop-types'

import { FinishPostDonation } from 'bonde-webpage/lib/plugins/donation/components'

console.log(FinishPostDonation)

const DonationFinishPostDonation = ({ preview, mobilization, widget }) => {
  return (

        teste

  )
}

DonationFinishPostDonation.propTypes = {
  preview: bool,
  mobilization: object.isRequired,
  widget: object.isRequired
}

export default DonationFinishPostDonation
<|endoftext|>