<commit_before>var bugzilla = function() {
    var bzClient = bz.createClient();
    var pending = 0;

    var bugsFixed = function(obj, email, callback) {
        pending++;
        bzClient.countBugs({
            "field0-0-0": "attachment.is_patch",
            "type0-0-0": "equals",
            "value0-0-0": 1,
            "field0-1-0": "flagtypes.name",
            "type0-1-0": "contains",
            "value0-1-0": "+",
            email1: email,
            email1_assigned_to: 1,
            status: ['RESOLVED', 'VERIFIED'],
            resolution: ['FIXED']
        }, function(error, fixed) {
            if (error) {
                errorHandler(error);
                return;
            }
            obj.bugzilla.fixed = fixed;
            pending--;
            callback(obj, pending, save);
        });
    };

    var bugsAssigned = function(obj, email, callback) {
        pending++;
        bzClient.countBugs({
            email1: email,
            email1_assigned_to: 1
        }, function(error, assigned) {
            if (error) {
                errorHandler(error);
                return;
            }
            obj.bugzilla.assigned = assigned;
            pending--;
            callback(obj, pending, save);
        });
    }

    var components = function(obj, email, callback) {
        pending++;
        bzClient.countComponents({
            x_axis_field: "product",
            y_axis_field: "component",
            "field0-0-0": "attachment.is_patch",
            "type0-0-0": "equals",
            "value0-0-0": 1,
            "field0-1-0": "flagtypes.name",
            "type0-1-0": "contains",
            "value0-1-0": "+",
            email1: email,
            email1_assigned_to: 1,
            status: ['RESOLVED', 'VERIFIED'],
            resolution: ['FIXED']
        }, function(error, components) {
            if (error) {
                errorHandler(error);
                return;
            }
            var data = [];
            if (components && components.data && components.data.length) {
                data = data.concat.apply(data, components.data);
                for (var i = 0; i < data.length; i++) {
                    if (components.data[i/components.x_labels.length|0][i%components.x_labels.length] != 0)
                        obj.components[((components.x_labels[i%components.x_labels.length] || "") + " :: " +
                                        (components.y_labels[i/components.x_labels.length|0] || ""))
                                        .replace(/(^ :: | :: $)/g, "")] = components.data[i/components.x_labels.length|0][i%components.x_labels.length];
                }
            }
            pending--;
            callback(obj, pending, save);
        });
    }

    return {
        bugsFixed: bugsFixed,
        components: components,
        bugsAssigned: bugsAssigned
    }

}();

module.exports = bugzilla;
<commit_msg>Acquire bz module in lib/bugzilla<commit_after>var bz = require("bz")

var bugzilla = function() {
    var bzClient = bz.createClient();
    var pending = 0;

    var bugsFixed = function(obj, email, callback) {
        pending++;
        bzClient.countBugs({
            "field0-0-0": "attachment.is_patch",
            "type0-0-0": "equals",
            "value0-0-0": 1,
            "field0-1-0": "flagtypes.name",
            "type0-1-0": "contains",
            "value0-1-0": "+",
            email1: email,
            email1_assigned_to: 1,
            status: ['RESOLVED', 'VERIFIED'],
            resolution: ['FIXED']
        }, function(error, fixed) {
            if (error) {
                errorHandler(error);
                return;
            }
            obj.bugzilla.fixed = fixed;
            pending--;
            callback(obj, pending, save);
        });
    };

    var bugsAssigned = function(obj, email, callback) {
        pending++;
        bzClient.countBugs({
            email1: email,
            email1_assigned_to: 1
        }, function(error, assigned) {
            if (error) {
                errorHandler(error);
                return;
            }
            obj.bugzilla.assigned = assigned;
            pending--;
            callback(obj, pending, save);
        });
    }

    var components = function(obj, email, callback) {
        pending++;
        bzClient.countComponents({
            x_axis_field: "product",
            y_axis_field: "component",
            "field0-0-0": "attachment.is_patch",
            "type0-0-0": "equals",
            "value0-0-0": 1,
            "field0-1-0": "flagtypes.name",
            "type0-1-0": "contains",
            "value0-1-0": "+",
            email1: email,
            email1_assigned_to: 1,
            status: ['RESOLVED', 'VERIFIED'],
            resolution: ['FIXED']
        }, function(error, components) {
            if (error) {
                errorHandler(error);
                return;
            }
            var data = [];
            if (components && components.data && components.data.length) {
                data = data.concat.apply(data, components.data);
                for (var i = 0; i < data.length; i++) {
                    if (components.data[i/components.x_labels.length|0][i%components.x_labels.length] != 0)
                        obj.components[((components.x_labels[i%components.x_labels.length] || "") + " :: " +
                                        (components.y_labels[i/components.x_labels.length|0] || ""))
                                        .replace(/(^ :: | :: $)/g, "")] = components.data[i/components.x_labels.length|0][i%components.x_labels.length];
                }
            }
            pending--;
            callback(obj, pending, save);
        });
    }

    return {
        bugsFixed: bugsFixed,
        components: components,
        bugsAssigned: bugsAssigned
    }

}();

module.exports = bugzilla;
<|endoftext|>


<commit_before>/*  checkforcode.js by David Jerome @GlassToeStudio - GlassToeStudio@gmail.com

    26 May, 2018
    https://github.com/GlassToeStudio
    http://glasstoestudio.weebly.com/
    https://twitter.com/GlassToeStudio

    ------------------------------------------------------------------------
    Systematically search through Discord comments to find unformatted Code.

        * Search is based in chars in codeElements array.
            * Default:  [';', '{', '}', ')', '[', ']', '>']
        * Bot will parse the code line by line searching for
        * code elements and keep track of which line are code
        * and which are plain text.
        * The bot will do his best to only format a true code
        * block, leaving the plain text alone. One complete
        * the bot will add code block formatting around the
        * code block, with the current code Lang 'csharp'.
        * The message will be posted anew as formatted code
        * and, if possible, the old message will be deleted.
        *
        * If the unformatted code is posted in a channel with
        * 'help' in the tile, then the new message is posted
        * there.
        * If the message is posted in any other channel, the
        * new message will be posted in #programing_help (if it exists)
        * If there is no programing_help channel, the message is
        * posted in the original channel.
        *
        * When a new message is posted in a new channel, the user
        * is notified that the post has been moved, with a link
        * to the channel. The new post in the new channel will
        * also mention the user, as an added bonus to help
        * the user navigate to the new message.

    EXAMPLE-----------------------------------------------------------------

    This is not code so it is not in the code block.

    [System.Serializable]
    using UnityEngine;

    ///
    /// Class summary
    ///
    public class MyClass
    {
        ///    Summary of myFloat.
        public float myFloat;
        ///    Summary of myOtherFloat.
        public float myOtherFLoat;

        // Default constructor
        public MyClass(float _myFloat, float _myOtherFLoat)
        {
            this.myFloat = _myFloat;
            this.myOtherFLoat = _myOtherFLoat;
        }
    }

    This is not code so it is not in the code block.

    ------------------------------------------------------------------------

    Discord Markdown 101 for more formatting guidelines:
    https://support.discordapp.com/hc/en-us/articles/210298617-Markdown-Text-101-Chat-Formatting-Bold-Italic-Underline-?page=4
*/

const Confax = require('../bot.js')
const bot = Confax.bot
const config = Confax.config

// Salt to taste
const codeElements = config.codeElements
const codeLang = config.codeLang
const repostThreshold = config.repostThreshold
const selfDestructIn = config.selfDestructIn
const formatBlock = config.formatBlock

// Variables
var isFormatted = false
var totalLinesOfCode = 0
var hasFirstLine = false
var lastLine = 0

// Lets begin
bot.on('message', message => {
  if (message.content.length > 1950) return
  if (message.author.bot) {
    // Self-destruct message
    if (message.content.includes('Your unformatted code')) {
      let usr = message.mentions.users.array()[0]
      let chnl = (message.guild.channels.find('name', 'programming_help') != null)
                ? message.guild.channels.find('name', 'programming_help')
                : message.channel
      callNTimes(selfDestructIn, 1000, EditBotMessage, message, chnl, usr)
    }
    return
  }
  ParseMessage(message)
})

/**
 * Loop through each line in message and check for
 * code-like characters. If code formatting is found
 * return, else keep checking.
 * @param  {string[]} message
 */
function ParseMessage (message) {
  InitVariables()
  let lines = message.content.split('\n')
  for (let i = 0; i < lines.length; i++) {
    if (lines[i].search(formatBlock) >= 0) {
      isFormatted = true
      return
    } else {
      let line = lines[i].replace(/`/g, '')
      lines[i] = line
      line = line.trim()
      FindCodeElements(i, line, lines)
    }
  }
  if (!isFormatted) CheckMessage(lines, message)
}

/**
 * Check if this is unformatted code, if so Create New Message
 * @param  {string[]} lines
 * @param  {string} message
 */
function CheckMessage (lines, message) {
  if (IsBadCode() && !isFormatted) {
    lines[lastLine] = FormatLastLine(lines[lastLine])
    CreateNewMessage(lines, message)
  }
}

/**
 * Checks the last character in a string to see of it matches a code-like character
 * @param  {number} index
 * @param  {string} line
 * @param  {string[]} lines
 */
function FindCodeElements (index, line, lines) {
  let lineLength = line.length - 1
  for (let i = 0; i < codeElements.length; i++) {
    if (line.charAt(lineLength).valueOf() === codeElements[i].valueOf() || line.includes('public') || line.includes('class')) {
      if (!hasFirstLine) {
        lines[index] = FormatFirstLine(lines[index])
        return
      } else {
        lastLine = index
        totalLinesOfCode += 1
        return
      }
    }
  }
}

/**
 * Recreate the new message with code formatting included
 * @param  {string[]} lines
 * @param  {string[]} message
 */
function CreateNewMessage (lines, message) {
  let newMessage = ''
  for (let j = 0; j < lines.length; j++) {
    newMessage += lines[j] + '\n'
  }
  PostNewMessage(message, newMessage)
}

/**
 * Post the formatted message in the appropriate channel
 * @param  {string[]} message
 * @param  {string} newMessage
 */
function PostNewMessage (message, newMessage) {
  let channel = message.guild.channels.find('name', 'programming_help')
  let isHelp = message.channel.name.indexOf('help') > 0
    // Move to new channel
  if (channel != null && channel !== message.channel && !isHelp) {
    // TODO: Would like to add some color to this message
    message.reply(':nerd: __`Your unformatted code has been formatted and moved to`__ ' + channel + '. :nerd:' +
                  '\n\t*This message will self-destruct in ' + selfDestructIn + ' seconds*')
    channel.send(message.author + ', **★★ I have formatted your code and placed it here. Good Luck! ★★** ')
    channel.send(newMessage)
    // post is same channel
  } else {
    message.channel.send(message.author + ' **★★ I see you forgot to format your code... Let me help you. ★★** ')
    message.channel.send(newMessage)
  }
  DeleteOldMessage(message)
}

/**
 * Deletes the old unformatted message if bot has permission
 * @param  {string} message
 */
function DeleteOldMessage (message) {
  let managePerms = message.guild.member(bot.user).hasPermission('MANAGE_MESSAGES')
  if (managePerms) {
    message.delete()
  } else {
    message.channel.send('**`Tell the server\'s owner to grant me permission to delete your old message, thank\'s`** :wink:')
  }
}

/**
 *  Adds code formatting block start to the first line of code
 * @param  {string} firstLine
 */
function FormatFirstLine (firstLine) {
  /*
  What if the first line of code has some regular text at the beginning?
      "Here is my code: public int myInt = 0;"
      "Here is my code" will also be formatted.
      We do not want this.
  */
  hasFirstLine = true
  return formatBlock + codeLang + '\n' + firstLine
}

/**
 * Add formatting code bock end to the last line of code
 * @param  {string} lastLine
 */
function FormatLastLine (lastLine) {
  return lastLine.replace('`', '') + '\n' + formatBlock
}

/**
 * If total line of code is greater than repostThreshold return true
 */
function IsBadCode () {
  return (totalLinesOfCode >= repostThreshold)
}

/**
 * Initialize variables
 */
function InitVariables () {
  isFormatted = false
  hasFirstLine = false
  lastLine = 0
  totalLinesOfCode = 0
}

/**
 * Edits the instruction message once a second, decrementing the time variable by 1
 * @param  {string} usr
 * @param  {string[]} message
 * @param  {string} channel
 * @param  {number} t
 */
function EditBotMessage (usr, message, channel, t) {
  message.edit(usr + ', :nerd: __`Your unformatted code has been formatted and moved to`__ ' + channel + '. :nerd:' +
               '\n\t*This message will self-destruct in ' + t + ' seconds*')
}

/**
 * Call the passed function n times every time step.
 * @param  {number} n
 * @param  {number} time
 * @param  {function} fn
 * @param  {string[]} msg
 * @param  {string} chnl
 * @param  {string} usr
 */
function callNTimes (n, time, fn, msg, chnl, usr) {
  function callFn () {
    if (--n < 1) {
      usr = null
      msg.delete()
          .then(m => console.log(`Deleted message from ${m.author}`))
          .catch(console.error)
      return
    }
    fn(usr, msg, chnl, n)
    setTimeout(callFn, time)
  }
  setTimeout(callFn, time)
}
<commit_msg>Update checkforcode<commit_after>/*  checkforcode.js by David Jerome @GlassToeStudio - GlassToeStudio@gmail.com

    26 May, 2018
    https://github.com/GlassToeStudio
    http://glasstoestudio.weebly.com/
    https://twitter.com/GlassToeStudio

    ------------------------------------------------------------------------
    Systematically search through Discord comments to find unformatted Code.

        * Search is based in chars in codeElements array.
            * Default:  [';', '{', '}', ')', '[', ']', '>']
        * Bot will parse the code line by line searching for
        * code elements and keep track of which line are code
        * and which are plain text.
        * The bot will do his best to only format a true code
        * block, leaving the plain text alone. One complete
        * the bot will add code block formatting around the
        * code block, with the current code Lang 'csharp'.
        * The message will be posted anew as formatted code
        * and, if possible, the old message will be deleted.
        *
        * If the unformatted code is posted in a channel with
        * 'help' in the tile, then the new message is posted
        * there.
        * If the message is posted in any other channel, the
        * new message will be posted in #programing_help (if it exists)
        * If there is no programing_help channel, the message is
        * posted in the original channel.
        *
        * When a new message is posted in a new channel, the user
        * is notified that the post has been moved, with a link
        * to the channel. The new post in the new channel will
        * also mention the user, as an added bonus to help
        * the user navigate to the new message.

    EXAMPLE-----------------------------------------------------------------

    This is not code so it is not in the code block.

    [System.Serializable]
    using UnityEngine;

    ///
    /// Class summary
    ///
    public class MyClass
    {
        ///    Summary of myFloat.
        public float myFloat;
        ///    Summary of myOtherFloat.
        public float myOtherFLoat;

        // Default constructor
        public MyClass(float _myFloat, float _myOtherFLoat)
        {
            this.myFloat = _myFloat;
            this.myOtherFLoat = _myOtherFLoat;
        }
    }

    This is not code so it is not in the code block.

    ------------------------------------------------------------------------

    Discord Markdown 101 for more formatting guidelines:
    https://support.discordapp.com/hc/en-us/articles/210298617-Markdown-Text-101-Chat-Formatting-Bold-Italic-Underline-?page=4
*/

const Confax = require('../bot.js')
const bot = Confax.bot
const config = Confax.config

// Salt to taste
const codeElements = config.codeElements
const codeLang = config.codeLang
const repostThreshold = config.repostThreshold
const selfDestructIn = config.selfDestructIn
const formatBlock = config.formatBlock

// Variables
var isFormatted = false
var totalLinesOfCode = 0
var hasFirstLine = false
var lastLine = 0

// Lets begin
bot.on('message', message => {
  if (message.content.length > 1950) return
  if (message.author.bot) {
    // Self-destruct message
    if (message.content.includes('Your unformatted code')) {
      let usr = message.mentions.users.array()[0]
      let chnl = (message.guild.channels.find('name', 'programming_help') != null)
                ? message.guild.channels.find('name', 'programming_help')
                : message.channel
      callNTimes(selfDestructIn, 1000, EditBotMessage, message, chnl, usr)
    }
    return
  }
  ParseMessage(message)
})

/**
 * Loop through each line in message and check for
 * code-like characters. If code formatting is found
 * return, else keep checking.
 * @param  {string[]} message
 */
function ParseMessage (message) {
  InitVariables()
  let lines = message.content.split('\n')
  for (let i = 0; i < lines.length; i++) {
    if (lines[i].search(formatBlock) >= 0) {
      isFormatted = true
      return
    } else {
      let line = lines[i].replace(/`/g, '')
      lines[i] = line
      line = line.trim()
      FindCodeElements(i, line, lines)
    }
  }
  if (!isFormatted) CheckMessage(lines, message)
}

/**
 * Check if this is unformatted code, if so Create New Message
 * @param  {string[]} lines
 * @param  {string} message
 */
function CheckMessage (lines, message) {
  if (IsBadCode() && !isFormatted) {
    lines[lastLine] = FormatLastLine(lines[lastLine])
    CreateNewMessage(lines, message)
  }
}

/**
 * Checks the last character in a string to see of it matches a code-like character
 * @param  {number} index
 * @param  {string} line
 * @param  {string[]} lines
 */
function FindCodeElements (index, line, lines) {
  let lineLength = line.length - 1
  for (let i = 0; i < codeElements.length; i++) {
    if (line.charAt(lineLength).valueOf() === codeElements[i].valueOf() || line.includes('public') || line.includes('class')) {
      if (!hasFirstLine) {
        lines[index] = FormatFirstLine(lines[index])
        return
      } else {
        lastLine = index
        totalLinesOfCode += 1
        return
      }
    }
  }
}

/**
 * Recreate the new message with code formatting included
 * @param  {string[]} lines
 * @param  {string[]} message
 */
function CreateNewMessage (lines, message) {
  let newMessage = ''
  for (let j = 0; j < lines.length; j++) {
    newMessage += lines[j] + '\n'
  }
  PostNewMessage(message, newMessage)
}

/**
 * Post the formatted message in the appropriate channel
 * @param  {string[]} message
 * @param  {string} newMessage
 */
function PostNewMessage (message, newMessage) {
  let channel = message.guild.channels.find('name', 'programming_help')
  let isHelp = message.channel.name.indexOf('help') > 0
    // Move to new channel
  if (channel != null && channel !== message.channel && !isHelp) {
    // TODO: Would like to add some color to this message
    message.reply(':nerd: __`Your unformatted code has been formatted and moved to`__ ' + channel + '. :nerd:' +
                  '\n\t*This message will self-destruct in ' + selfDestructIn + ' seconds*')
    channel.send(message.author + ', **★★ I have formatted your code and placed it here. Good Luck! ★★** ')
    channel.send(newMessage)
    // post is same channel
  } else {
    message.channel.send(message.author + ' **★★ I see you forgot to format your code... Let me help you. ★★** ')
    message.channel.send(newMessage)
  }
  DeleteOldMessage(message)
}

/**
 * Deletes the old unformatted message if bot has permission
 * @param  {string} message
 */
function DeleteOldMessage (message) {
  let managePerms = message.guild.member(bot.user).hasPermission('MANAGE_MESSAGES')
  if (managePerms) {
    message.delete()
  } else {
    message.channel.send('**`Tell the server\'s owner to grant me permission to delete your old message, thank\'s`** :wink:')
  }
}

/**
 *  Adds code formatting block start to the first line of code
 * @param  {string} firstLine
 */
function FormatFirstLine (firstLine) {
  /*
  What if the first line of code has some regular text at the beginning?
      "Here is my code: public int myInt = 0;"
      "Here is my code" will also be formatted.
      We do not want this.
  */
  hasFirstLine = true
  return formatBlock + codeLang + '\n' + firstLine
}

/**
 * Add formatting code bock end to the last line of code
 * @param  {string} lastLine
 */
function FormatLastLine (lastLine) {
  return lastLine.replace(/`/g, '') + '\n' + formatBlock
}

/**
 * If total line of code is greater than repostThreshold return true
 */
function IsBadCode () {
  return (totalLinesOfCode >= repostThreshold)
}

/**
 * Initialize variables
 */
function InitVariables () {
  isFormatted = false
  hasFirstLine = false
  lastLine = 0
  totalLinesOfCode = 0
}

/**
 * Edits the instruction message once a second, decrementing the time variable by 1
 * @param  {string} usr
 * @param  {string[]} message
 * @param  {string} channel
 * @param  {number} t
 */
function EditBotMessage (usr, message, channel, t) {
  message.edit(usr + ', :nerd: __`Your unformatted code has been formatted and moved to`__ ' + channel + '. :nerd:' +
               '\n\t*This message will self-destruct in ' + t + ' seconds*')
}

/**
 * Call the passed function n times every time step.
 * @param  {number} n
 * @param  {number} time
 * @param  {function} fn
 * @param  {string[]} msg
 * @param  {string} chnl
 * @param  {string} usr
 */
function callNTimes (n, time, fn, msg, chnl, usr) {
  function callFn () {
    if (--n < 1) {
      usr = null
      msg.delete()
          .then(m => console.log(`Deleted message from ${m.author}`))
          .catch(console.error)
      return
    }
    fn(usr, msg, chnl, n)
    setTimeout(callFn, time)
  }
  setTimeout(callFn, time)
}
<|endoftext|>


<commit_before>var _= require('underscore'),
    async= require('async');

var __steps= function (rcurrent, rtarget, wcurrent, wtarget)
{
    var _steps= function (current, target)
        {
            var diff= target-current,
                steps= diff>0 ? (diff > current*2 ? [] : [target]) : [target];

            if (!steps.length)
            {
               while ((current=current*2)<target)
                   steps.push(current);

               var delta= target-steps[steps.length-1];

               if (delta>0)
                 steps.push(target);
            }

            return steps;
        },
        _fill= function (arr,len)
        {
           var diff= len-arr.length,
               last= arr[arr.length-1];

           _(diff).times(function () { arr.push(last); });
        };

    var rsteps= _steps(rcurrent,rtarget),
        wsteps= _steps(wcurrent,wtarget);

    if (rsteps.length>wsteps.length)
      _fill(wsteps,rsteps.length);
    else
    if (wsteps.length>rsteps.length)
      _fill(rsteps,wsteps.length);

    return _.zip(rsteps,wsteps);
}

module.exports= function (dyn,table,read,write)
{
    var p= dyn.promise(),
        _check= function (cb)
        {
              dyn.describeTable(table,
              function (err,data)
              {
                  if (err)
                    p.trigger.error(err);
                  else
                  if (data.Table.TableStatus=='UPDATING')
                    setTimeout(_check,5000,cb);
                  else
                  {
                    table._dynamo= data.Table;
                    cb();
                  }
              });
        };

    if (!read||!write)
      process.nextTick(function ()
      { p.trigger.error(new Error('You should specify read and write ProvisionedThroughput')) });
    else
        dyn.describeTable(table,
        function (err,data)
        {
              if (err)
                  p.trigger.error(err);
              else
              {
                  var current= data.Table.ProvisionedThroughput;

                  if (current.ReadCapacityUnits==read
                    &&current.WriteCapacityUnits==write)
                    p.trigger.success();
                  else
                  {
                     console.log('This may take a while...'.yellow);

                     var steps= __steps(current.ReadCapacityUnits,
                                        read,
                                        current.WriteCapacityUnits,
                                        write);

                     async.forEachSeries(steps,function (step,done)
                     {
                         var sread= step[0], swrite= step[1];

                         dyn.updateTable(table,sread,swrite,
                         function (err,data)
                         {
                            if (err)
                              done(err);
                            else
                              setTimeout(_check,5000,function ()
                              {
                                 if (sread==read&&swrite==write)
                                   console.log(('current capacity: '+sread+' read '+swrite+' write')
                                   .green);
                                 else
                                   console.log(('current capacity: '+sread+' read '+swrite+' write')
                                   .yellow);

                                 done();
                              });
                         });
                     },
                     p.should('success'));
                  }
              }
        });

    return p;
};
<commit_msg>fix capacity<commit_after>var _= require('underscore'),
    async= require('async');

var __steps= function (rcurrent, rtarget, wcurrent, wtarget)
{
    var _steps= function (current, target)
        {
            var diff= target-current,
                steps= diff>0 ? (diff > current ? [] : [target]) : [target];

            if (!steps.length)
            {
               while ((current=current*2)<target)
                   steps.push(current);

               var delta= target-steps[steps.length-1];

               if (delta>0)
                 steps.push(target);
            }

            return steps;
        },
        _fill= function (arr,len)
        {
           var diff= len-arr.length,
               last= arr[arr.length-1];

           _(diff).times(function () { arr.push(last); });
        };

    var rsteps= _steps(rcurrent,rtarget),
        wsteps= _steps(wcurrent,wtarget);

    if (rsteps.length>wsteps.length)
      _fill(wsteps,rsteps.length);
    else
    if (wsteps.length>rsteps.length)
      _fill(rsteps,wsteps.length);

    return _.zip(rsteps,wsteps);
}

module.exports= function (dyn,table,read,write)
{
    var p= dyn.promise(),
        _check= function (cb)
        {
              dyn.describeTable(table,
              function (err,data)
              {
                  if (err)
                    p.trigger.error(err);
                  else
                  if (data.Table.TableStatus=='UPDATING')
                    setTimeout(_check,5000,cb);
                  else
                  {
                    table._dynamo= data.Table;
                    cb();
                  }
              });
        };

    if (!read||!write)
      process.nextTick(function ()
      { p.trigger.error(new Error('You should specify read and write ProvisionedThroughput')) });
    else
        dyn.describeTable(table,
        function (err,data)
        {
              if (err)
                  p.trigger.error(err);
              else
              {
                  var current= data.Table.ProvisionedThroughput;

                  if (current.ReadCapacityUnits==read
                    &&current.WriteCapacityUnits==write)
                    p.trigger.success();
                  else
                  {
                     console.log('This may take a while...'.yellow);

                     var steps= __steps(current.ReadCapacityUnits,
                                        read,
                                        current.WriteCapacityUnits,
                                        write);

                     async.forEachSeries(steps,function (step,done)
                     {
                         var sread= step[0], swrite= step[1];

                         dyn.updateTable(table,sread,swrite,
                         function (err,data)
                         {
                            if (err)
                              done(err);
                            else
                              setTimeout(_check,5000,function ()
                              {
                                 if (sread==read&&swrite==write)
                                   console.log(('current capacity: '+sread+' read '+swrite+' write')
                                   .green);
                                 else
                                   console.log(('current capacity: '+sread+' read '+swrite+' write')
                                   .yellow);

                                 done();
                              });
                         });
                     },
                     p.should('success'));
                  }
              }
        });

    return p;
};
<|endoftext|>


<commit_before>/*
  A ping pong bot, whenever you send "ping", it replies "pong".
*/

// Import the discord.js module
const Discord = require('discord.js');

// Create an instance of a Discord client
const client = new Discord.Client();

// The token of your bot - https://discordapp.com/developers/applications/me
const token = 'your bot token here';

// The ready event is vital, it means that your bot will only start reacting to information
// from Discord _after_ ready is emitted
client.on('ready', () => {
  console.log('I am ready!');
});

// Create an event listener for messages
client.on('message', message => {
  // If the message is "ping"
  if (message.content === 'ping') {
    // Send "pong" to the same channel
    message.channel.send('pong');
  }
});

// Log our bot in
client.login(token);
<commit_msg>Update checkforcode.js<commit_after>/*
    Systematically search through Discord comments to find unformatted Code.

    * Look for lines ending in ;
    * Look for lines ending in )
    * Look for lines ending in { or }
    * If found, Locate the first Code Block Line
    * If found, Locate the last Code Block Line
    * RePost the message surrounded by ```csharp ```

    EXAMPLE

    ```csharp
    using UnityEngine;

    /// <summary>
    /// Class for holding Navigation variables. Used for the main game
    /// logic by PlayerNavigate to
    /// </summary>
    public class ChangeDirection
    {
        /// <summary>   The angle by which we should rotate. </summary>
        public float newAngle;
        /// <summary>   The time at which we should change direction.</summary>
        public float changeTime;

        public ChangeDirection(float _newAngle, float _changeTime)
        {
            this.newAngle = _newAngle;
            this.changeTime = _changeTime;
        }
    }
    ```
*/

// Import the discord.js module
const Discord = require('discord.js');

// The token of your bot - https://discordapp.com/developers/applications/me
const token = 'your bot token here';

// Guess this was for name and whatnot
const Confax = require('../bot.js')

// This is the bot
const bot = Confax.bot

// Prob dont need config
const config = Confax.config

var isFormatted = false;
var totalLinesOfCode = 0;
var lines = [];
var codeLines = [];

// Create an event listener for messages to parse
client.on('message', message => {
  // If the message is "ping"

    this.lines = message.content.split('\n')

    this.checkMessageForCode(lines);

    if(this.isBadCode && !this.isFormatted){
        var firstLine = Math.min(...this.codeLines);
        var lastLine = Math.max(...this.codeLines);

        this.lines.splice(firstLine, 0, '```\n');
        this.lines.splice(lastLine, 0, '\n```\n');
        message = this.lines;
        message.channel.send(message); # idk abou this really.
    }

    if (message.content === 'ping') {
    // Send "pong" to the same channel
    message.channel.send('pong');
  }
});

function checkMessageForCode(inputLines){
    for(var i = 0; i < inputLines.length; i++){
        var line = inputLines[i].replace('\s','');
        if(line.search('```') >= 0){
            this.isFormatted = true;
            return;
        }
        else{
            checkLastCharacter(i, line, ';')
            checkLastCharacter(i, line, '{')
            checkLastCharacter(i, line, '}')
            checkLastCharacter(i, line, ')')
        }
    }
}

function checkLastCharacter(index, inLine, inChar){
    if(inLine.charAt(inLine.length-1).valueOf() == inChar.valueOf()){
        this.codeLines.push(index);
        this.totalLinesOfCode += 1;
    }
}

<|endoftext|>


<commit_before>/**
 * CLI/make
 * ========
 *
 * Этот файл запускает сборку из командной строки.
 */
var MakePlatform = require('../make');
var makePlatform = new MakePlatform();
var path = require('path');
var Vow = require('vow');

module.exports = function (program) {
    program.command('make')
        .option('-n, --no-cache', 'drop cache before running make')
        .option('-d, --dir <dir>', 'custom project root', process.cwd())
        .option('-h, --hide-warnings', 'hides warnings')
        .option('--graph', 'draws build graph')
        .description('build specified targets')
        .action(function () {
            var args = program.args.slice(0);
            var cmd = args.pop();
            makePlatform.init(path.resolve(cmd.dir)).then((function () {
                if (cmd.hideWarnings) {
                    makePlatform.getLogger().hideWarnings();
                }
                if (cmd.cache) {
                    makePlatform.loadCache();
                }
                return makePlatform.build(args).then(function () {
                    if (cmd.graph) {
                        console.log(makePlatform.getBuildGraph().render());
                    }
                    return Vow.when(makePlatform.saveCache(), makePlatform.destruct.bind(makePlatform));
                });
            }))
            .then(null, function (err) {
                if (cmd.graph) {
                    console.log(makePlatform.getBuildGraph().render());
                }
                console.error(err.stack);
                process.exit(1);
            });
        });
};
<commit_msg>Use saveCacheAsync()<commit_after>/**
 * CLI/make
 * ========
 *
 * Этот файл запускает сборку из командной строки.
 */
var MakePlatform = require('../make');
var makePlatform = new MakePlatform();
var path = require('path');
var Vow = require('vow');

module.exports = function (program) {
    program.command('make')
        .option('-n, --no-cache', 'drop cache before running make')
        .option('-d, --dir <dir>', 'custom project root', process.cwd())
        .option('-h, --hide-warnings', 'hides warnings')
        .option('--graph', 'draws build graph')
        .description('build specified targets')
        .action(function () {
            var args = program.args.slice(0);
            var cmd = args.pop();
            makePlatform.init(path.resolve(cmd.dir)).then((function () {
                if (cmd.hideWarnings) {
                    makePlatform.getLogger().hideWarnings();
                }
                if (cmd.cache) {
                    makePlatform.loadCache();
                }
                return makePlatform.build(args).then(function () {
                    if (cmd.graph) {
                        console.log(makePlatform.getBuildGraph().render());
                    }
                    return Vow.when(makePlatform.saveCacheAsync(), makePlatform.destruct.bind(makePlatform));
                });
            }))
            .then(null, function (err) {
                if (cmd.graph) {
                    console.log(makePlatform.getBuildGraph().render());
                }
                console.error(err.stack);
                process.exit(1);
            });
        });
};
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();

var bodyParser = require("body-parser");
var path = require('path');
var _ = require('lodash');

var UsersManager = require("../lib/UsersManager");
var DatabaseManager = require("../lib/DatabaseManager");
var Utils = require("../lib/Utils");
var Const = require("../const");
var Settings = require("../lib/Settings");
var async = require('async');
var formidable = require('formidable');
var fs = require('fs-extra');
var path = require('path');
var mime = require('mime');

var Settings = require("../lib/Settings");

var WebAPIHandler ={

    init: function(app,express){

        var self = this;

        app.use(Settings.options.urlPrefix,express.static(__dirname + '/../../../public'));
        app.use(bodyParser.json());

        /*
        app.use(function(err, req, res, next) {
          console.error(err.stack);
          res.status(500).send('Something broke!');
        });
        */

        // HTTP Routes

        router.use("/user/login", require('./LoginHandler'));
        router.use("/temp", require('./TempHandler'));
        router.use("/message/list", require('./MessageListHandler'));
        router.use("/message/new", require('./NewMessageListHandler'));
        router.use("/message/latest", require('./LatestMessageListHandler').router);
        router.use("/user/list", require('./UserListHandler'));
        router.use("/message/sendFile", require('./SendFileAsMessageHandler'));
        router.use("/file/upload", require('./FileUploadHandler'));
        router.use("/file/download", require('./FileDownloadHandler'));
        router.use("/test", require('./TestHandler'));

        WebAPIHandler.router = router;
        app.use(Settings.options.urlPrefix + "/v1", router);

    }
}

module["exports"] = WebAPIHandler;<commit_msg>forget to remove this..<commit_after>var express = require('express');
var router = express.Router();

var bodyParser = require("body-parser");
var path = require('path');
var _ = require('lodash');

var UsersManager = require("../lib/UsersManager");
var DatabaseManager = require("../lib/DatabaseManager");
var Utils = require("../lib/Utils");
var Const = require("../const");
var Settings = require("../lib/Settings");
var async = require('async');
var formidable = require('formidable');
var fs = require('fs-extra');
var path = require('path');
var mime = require('mime');

var Settings = require("../lib/Settings");

var WebAPIHandler ={

    init: function(app,express){

        var self = this;

        app.use(Settings.options.urlPrefix,express.static(__dirname + '/../../../public'));
        app.use(bodyParser.json());

        /*
        app.use(function(err, req, res, next) {
          console.error(err.stack);
          res.status(500).send('Something broke!');
        });
        */

        // HTTP Routes

        router.use("/user/login", require('./LoginHandler'));
        router.use("/temp", require('./TempHandler'));
        router.use("/message/list", require('./MessageListHandler'));
        router.use("/message/latest", require('./LatestMessageListHandler').router);
        router.use("/user/list", require('./UserListHandler'));
        router.use("/message/sendFile", require('./SendFileAsMessageHandler'));
        router.use("/file/upload", require('./FileUploadHandler'));
        router.use("/file/download", require('./FileDownloadHandler'));
        router.use("/test", require('./TestHandler'));

        WebAPIHandler.router = router;
        app.use(Settings.options.urlPrefix + "/v1", router);

    }
}

module["exports"] = WebAPIHandler;<|endoftext|>


<commit_before>
// using SendGrid's v3 Node.js Library
// https://github.com/sendgrid/sendgrid-nodejs
const helper = require('sendgrid').mail;
const fromEmail = new helper.Email('test@example.com');
const toEmail = new helper.Email('test@example.com');
const subject = 'Sending with SendGrid is Fun';
const content = new helper.Content('text/plain', 'and easy to do anywhere, even with Node.js');
const mail = new helper.Mail(fromEmail, subject, toEmail, content);

const sg = require('sendgrid')(process.env.SENDGRID_API_KEY);
const request = sg.emptyRequest({
  method: 'POST',
  path: '/v3/mail/send',
  body: mail.toJSON()
});

sg.API(request, function (error, response) {
  if (error) {
    console.log('Error response received');
  }
  console.log(response.statusCode);
  console.log(response.body);
  console.log(response.headers);
});

/**
 * default node mailer before added node sendgrid
*/
const nodemailer = require('nodemailer');

const transporter = nodemailer.createTransport({
  service: 'SendGrid',
  auth: {
    user: process.env.SENDGRID_USER,
    pass: process.env.SENDGRID_PASSWORD
  }
});

/**
 * GET /contact
 * Contact form page.
 */
exports.getContact = (req, res) => {
  res.render('contact', {
    title: 'Contact'
  });
};

/**
 * POST /contact
 * Send a contact form via Nodemailer.
 */
exports.postContact = (req, res) => {
  req.assert('name', 'Name cannot be blank').notEmpty();
  req.assert('email', 'Email is not valid').isEmail();
  req.assert('message', 'Message cannot be blank').notEmpty();

  req.getValidationResult()
    .then(errors => {
      if (!errors.isEmpty()) {
        req.flash('errors', errors);
        return res.redirect('/contact');
      }
      const mailOptions = {
        to: 'your@email.com',
        from: `${req.body.name} <${req.body.email}>`,
        subject: 'Contact Form | Enneagram Starter',
        text: req.body.message
      };

      transporter.sendMail(mailOptions, (err) => {
        if (err) {
          req.flash('errors', { msg: err.message });
          return res.redirect('/contact');
        }
        req.flash('success', { msg: 'Email has been sent successfully!' });
        res.redirect('/contact');
      });

    });

};
<commit_msg>added linked in auth<commit_after>
// using SendGrid's v3 Node.js Library
// https://github.com/sendgrid/sendgrid-nodejs
const helper = require('sendgrid').mail;
const fromEmail = new helper.Email('test@example.com');
const toEmail = new helper.Email('test@example.com');
const subject = 'Sending with SendGrid is Fun';
const content = new helper.Content('text/plain', 'and easy to do anywhere, even with Node.js');
const mail = new helper.Mail(fromEmail, subject, toEmail, content);

const sg = require('sendgrid')(process.env.SENDGRID_API_KEY);
const request = sg.emptyRequest({
  method: 'POST',
  path: '/v3/mail/send',
  body: mail.toJSON()
});

sg.API(request, function (error, response) {
  if (error) {
    console.log('Error response received');
  }
  console.log(response.statusCode);
  console.log(response.body);
  console.log(response.headers);
});

/**
 * default node mailer before added node sendgrid
*/
const nodemailer = require('nodemailer');

const transporter = nodemailer.createTransport({
  service: 'SendGrid',
  auth: {
    user: process.env.SENDGRID_USER,
    pass: process.env.SENDGRID_PASSWORD
  }
});

/**
 * GET /contact
 * Contact form page.
 */
exports.getContact = (req, res) => {
  res.render('contact', {
    title: 'Contact'
  });
};

/**
 * POST /contact
 * Send a contact form via Nodemailer.
 */
exports.postContact = (req, res) => {
  req.assert('name', 'Name cannot be blank').notEmpty();
  req.assert('email', 'Email is not valid').isEmail();
  req.assert('message', 'Message cannot be blank').notEmpty();

  req.getValidationResult()
    .then(errors => {
      if (!errors.isEmpty()) {
        req.flash('errors', errors);
        return res.redirect('/contact');
      }
      const mailOptions = {
        to: 'jb@yodacom.com',
        from: `${req.body.name} <${req.body.email}>`,
        subject: 'Contact Form | Enneagram Starter',
        text: req.body.message
      };

      transporter.sendMail(mailOptions, (err) => {
        if (err) {
          req.flash('errors', { msg: err.message });
          return res.redirect('/contact');
        }
        req.flash('success', { msg: 'Email has been sent successfully!' });
        res.redirect('/contact');
      });

    });
};
<|endoftext|>


<commit_before>var Mailgun = require('mailgun-js');
var models = require('../models');

//Your api key, from Mailgun’s Control Panel
var apiKey = process.env.MAILGUN_KEY;

//Your domain, from the Mailgun Control Panel
var domain = process.env.MAILGUN_DOMAIN;

module.exports = function(req, res) {
  // find customer
  models.customers.findById(req.params.id, function(err, customer) {
    if (err) {
      res.json({error:{message:err}});
    }
    else {
      if (customer) {
        var now = new Date();
        // get count log by client_id, ip address and date
        models.logs.count({
          'client_id': req.params.id,
          'ip': req.heroku.ip,
          'created_at': {
            $lte: now
          }
        }, function(err, count) {
          if (err) {
            res.json({error:{message:err}});
          }
          else if (count <= process.env.LIMIT) {
            var from = req.body.from;
            var to = customer.to;
            var subject = req.body.subject;
            var message = req.body.message;

            var mailgun = new Mailgun({apiKey: apiKey, domain: domain});

            var data = {
              from: from,
              to: to,
              subject: subject,
              html: message
            };

            mailgun.messages().send(data, function(err, body) {
              var log = new models.logs;
              log.from = from;
              log.subject = subject;
              log.message = message;
              log.status = (err) ? false : true;
              log.ip = req.heroku.ip;
              log.save(function(error) {
                if (error) {
                  res.json({error:{message:error.message}});
                }
                else if (err) {
                  res.json({error:{message:err.message}});
                }
                else {
                  res.json({response:'Mensaje enviado'});
                }
              });
            });
          }
          else {
            res.json({error:{message:'No puedes enviar más de ' + limit + ' mensajes por día.'}});
          }
        });
      }
      else {
        res.json({error:{message:'El usuario no existe'}});
      }
    }
  });
};
<commit_msg>added client_id to log<commit_after>var Mailgun = require('mailgun-js');
var models = require('../models');

//Your api key, from Mailgun’s Control Panel
var apiKey = process.env.MAILGUN_KEY;

//Your domain, from the Mailgun Control Panel
var domain = process.env.MAILGUN_DOMAIN;

module.exports = function(req, res) {
  // find customer
  models.customers.findById(req.params.id, function(err, customer) {
    if (err) {
      res.json({error:{message:err}});
    }
    else {
      if (customer) {
        var now = new Date();
        // get count log by client_id, ip address and date
        models.logs.count({
          'client_id': req.params.id,
          'ip': req.heroku.ip,
          'created_at': {
            $lte: now
          }
        }, function(err, count) {
          if (err) {
            res.json({error:{message:err}});
          }
          else if (count <= process.env.LIMIT) {
            var from = req.body.from;
            var to = customer.to;
            var subject = req.body.subject;
            var message = req.body.message;

            var mailgun = new Mailgun({apiKey: apiKey, domain: domain});

            var data = {
              from: from,
              to: to,
              subject: subject,
              html: message
            };

            mailgun.messages().send(data, function(err, body) {
              var log = new models.logs;
              log.from = from;
              log.subject = subject;
              log.message = message;
              log.status = (err) ? false : true;
              log.ip = req.heroku.ip;
              log['client_id'] = req.params.id;
              log.save(function(error) {
                if (error) {
                  res.json({error:{message:error.message}});
                }
                else if (err) {
                  res.json({error:{message:err.message}});
                }
                else {
                  res.json({response:'Mensaje enviado'});
                }
              });
            });
          }
          else {
            res.json({error:{message:'No puedes enviar más de ' + limit + ' mensajes por día.'}});
          }
        });
      }
      else {
        res.json({error:{message:'El usuario no existe'}});
      }
    }
  });
};
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

KylinApp.controller('ModelSchemaCtrl', function ($scope, QueryService, UserService, ProjectService, $q, AuthenticationService, $filter, ModelService, MetaModel, CubeDescModel, CubeList, TableModel, ProjectModel, $log, SweetAlert, modelsManager) {

  $scope.modelsManager = modelsManager;
  $scope.projectModel = ProjectModel;
  $scope.projects = [];
  $scope.newDimension = null;
  $scope.newMeasure = null;

  $scope.forms = {};

  $scope.wizardSteps = [
    {title: 'Model Info', src: 'partials/modelDesigner/model_info.html', isComplete: false, form: 'model_info_form'},
    {title: 'Data Model', src: 'partials/modelDesigner/data_model.html', isComplete: false, form: 'data_model_form'},
    {
      title: 'Dimensions',
      src: 'partials/modelDesigner/model_dimensions.html',
      isComplete: false,
      form: 'model_dimensions_form'
    },
    {
      title: 'Measures',
      src: 'partials/modelDesigner/model_measures.html',
      isComplete: false,
      form: 'model_measure_form'
    },
    {
      title: 'Settings',
      src: 'partials/modelDesigner/conditions_settings.html',
      isComplete: false,
      form: 'model_setting_form'
    }
  ];

  $scope.curStep = $scope.wizardSteps[0];

  // ~ init
  if (!$scope.state) {
    $scope.state = {mode: "view"};
  }
  //init modelsManager
  if ($scope.state.mode == "edit") {
    var defer = $q.defer();
    var queryParam = {};
    if (!$scope.projectModel.isSelectedProjectValid()) {
      return;
    }
    queryParam.projectName = $scope.projectModel.selectedProject;
    modelsManager.list(queryParam).then(function (resp) {
      defer.resolve(resp);
      modelsManager.loading = false;
      return defer.promise;
    });
  }

  $scope.$watch('model', function (newValue, oldValue) {
    if (!newValue) {
      return;
    }
    if ($scope.modelMode == "editExistModel" && newValue && !newValue.project) {
      initProject();
    }

  });

  // ~ public methods
  $scope.filterProj = function (project) {
    return $scope.userService.hasRole('ROLE_ADMIN') || $scope.hasPermission(project, $scope.permissions.ADMINISTRATION.mask);
  };

  $scope.removeElement = function (arr, element) {
    var index = arr.indexOf(element);
    if (index > -1) {
      arr.splice(index, 1);
    }
  };

  $scope.open = function ($event) {
    $event.preventDefault();
    $event.stopPropagation();

    $scope.opened = true;
  };

  $scope.preView = function () {
    var stepIndex = $scope.wizardSteps.indexOf($scope.curStep);
    if (stepIndex >= 1) {
      $scope.curStep.isComplete = false;
      $scope.curStep = $scope.wizardSteps[stepIndex - 1];
    }
  };

  $scope.nextView = function () {
    var stepIndex = $scope.wizardSteps.indexOf($scope.curStep);

    if (stepIndex < ($scope.wizardSteps.length - 1)) {
      $scope.curStep.isComplete = true;
      $scope.curStep = $scope.wizardSteps[stepIndex + 1];

      AuthenticationService.ping(function (data) {
        UserService.setCurUser(data);
      });
    }
  };

  $scope.checkForm = function () {
    if (!$scope.curStep.form) {
      return true;
    }
    if ($scope.state.mode === 'view') {
      return true;
    }
    else {
      //form validation
      if ($scope.forms[$scope.curStep.form].$invalid) {
        $scope.forms[$scope.curStep.form].$sbumitted = true;
        return false;
      } else {
        //business rule check
        switch ($scope.curStep.form) {
          case 'data_model_form':
            return $scope.check_data_model();
            break;
          case 'model_info_form':
            return $scope.check_model_info();
            break;
          case 'model_dimensions_form':
            return $scope.check_model_dimensions();
            break;
          case 'model_measure_form':
            return $scope.check_model_measure();
            break;
          case 'model_setting_form':
            return $scope.check_model_setting();
            break;
          default:
            return true;
            break;
        }
      }
    }
  };

  $scope.check_model_info = function () {

    var modelName = $scope.modelsManager.selectedModel.name.toUpperCase();
    var models = $scope.modelsManager.modelNameList;
    if ($scope.modelMode=="addNewModel") {
      if(models.indexOf(modelName) != -1 || models.indexOf(modelName.toLowerCase()) !=-1){
        SweetAlert.swal('', "Model named [" + modelName + "] already exist!", 'warning');
        return false;
      }
    }
    return true;
  }

  /*
   * lookups can't be null
   */
  $scope.check_data_model = function () {
    var errors = [];
//        if(!modelsManager.selectedModel.lookups.length){
//            errors.push("No lookup table defined");
//        }
    var errorInfo = "";
    angular.forEach(errors, function (item) {
      errorInfo += "\n" + item;
    });
    if (errors.length) {
      SweetAlert.swal('', errorInfo, 'warning');
      return false;
    } else {
      return true;
    }

  }

  /*
   * dimensions validation
   * 1.dimension can't be null
   */
  $scope.check_model_dimensions = function () {

    var errors = [];
    if (!modelsManager.selectedModel.dimensions.length) {
      errors.push("No dimensions defined.");
    }
    angular.forEach(modelsManager.selectedModel.dimensions, function (_dimension) {
      if (!_dimension.columns || !_dimension.columns.length) {
        errors.push("No dimension columns defined for Table[" + _dimension.table + "]");
      }
    });
    var errorInfo = "";
    angular.forEach(errors, function (item) {
      errorInfo += "\n" + item;
    });
    if (errors.length) {
      SweetAlert.swal('Oops...', errorInfo, 'warning');
      return false;
    } else {
      return true;
    }

  };

  /*
   * dimensions validation
   * 1.metric can't be null
   */
  $scope.check_model_measure = function () {

    var errors = [];
    if (!modelsManager.selectedModel.metrics || !modelsManager.selectedModel.metrics.length) {
      errors.push("Please define your metrics.");
    }
    var errorInfo = "";
    angular.forEach(errors, function (item) {
      errorInfo += "\n" + item;
    });
    if (errors.length) {
      SweetAlert.swal('', errorInfo, 'warning');
      return false;
    } else {
      return true;
    }

  };
  $scope.check_model_setting = function () {
    var errors = [];
    if (modelsManager.selectedModel.partition_desc.partition_date_column != null && modelsManager.selectedModel.partition_desc.partition_date_start == null) {
      errors.push("Please indicate start date when partition date column selected.");
    }
    var errorInfo = "";
    angular.forEach(errors, function (item) {
      errorInfo += "\n" + item;
    });
    if (errors.length) {
      SweetAlert.swal('', errorInfo, 'warning');
      return false;
    } else {
      return true;
    }
  }

  $scope.goToStep = function (stepIndex) {
    if ($scope.state.mode == "edit") {
      if (stepIndex + 1 >= $scope.curStep.step) {
        return;
      }
    }
    for (var i = 0; i < $scope.wizardSteps.length; i++) {
      if (i <= stepIndex) {
        $scope.wizardSteps[i].isComplete = true;
      } else {
        $scope.wizardSteps[i].isComplete = false;
      }
    }
    if (stepIndex < ($scope.wizardSteps.length)) {
      $scope.curStep = $scope.wizardSteps[stepIndex];

      AuthenticationService.ping(function (data) {
        UserService.setCurUser(data);
      });
    }
  }

  // ~ private methods
  function initProject() {

  }
});
<commit_msg>KYLIN-919 validate model dimensions rule update<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

KylinApp.controller('ModelSchemaCtrl', function ($scope, QueryService, UserService, ProjectService, $q, AuthenticationService, $filter, ModelService, MetaModel, CubeDescModel, CubeList, TableModel, ProjectModel, $log, SweetAlert, modelsManager) {

  $scope.modelsManager = modelsManager;
  $scope.projectModel = ProjectModel;
  $scope.projects = [];
  $scope.newDimension = null;
  $scope.newMeasure = null;

  $scope.forms = {};

  $scope.wizardSteps = [
    {title: 'Model Info', src: 'partials/modelDesigner/model_info.html', isComplete: false, form: 'model_info_form'},
    {title: 'Data Model', src: 'partials/modelDesigner/data_model.html', isComplete: false, form: 'data_model_form'},
    {
      title: 'Dimensions',
      src: 'partials/modelDesigner/model_dimensions.html',
      isComplete: false,
      form: 'model_dimensions_form'
    },
    {
      title: 'Measures',
      src: 'partials/modelDesigner/model_measures.html',
      isComplete: false,
      form: 'model_measure_form'
    },
    {
      title: 'Settings',
      src: 'partials/modelDesigner/conditions_settings.html',
      isComplete: false,
      form: 'model_setting_form'
    }
  ];

  $scope.curStep = $scope.wizardSteps[0];

  // ~ init
  if (!$scope.state) {
    $scope.state = {mode: "view"};
  }
  //init modelsManager
  if ($scope.state.mode == "edit") {
    var defer = $q.defer();
    var queryParam = {};
    if (!$scope.projectModel.isSelectedProjectValid()) {
      return;
    }
    queryParam.projectName = $scope.projectModel.selectedProject;
    modelsManager.list(queryParam).then(function (resp) {
      defer.resolve(resp);
      modelsManager.loading = false;
      return defer.promise;
    });
  }

  $scope.$watch('model', function (newValue, oldValue) {
    if (!newValue) {
      return;
    }
    if ($scope.modelMode == "editExistModel" && newValue && !newValue.project) {
      initProject();
    }

  });

  // ~ public methods
  $scope.filterProj = function (project) {
    return $scope.userService.hasRole('ROLE_ADMIN') || $scope.hasPermission(project, $scope.permissions.ADMINISTRATION.mask);
  };

  $scope.removeElement = function (arr, element) {
    var index = arr.indexOf(element);
    if (index > -1) {
      arr.splice(index, 1);
    }
  };

  $scope.open = function ($event) {
    $event.preventDefault();
    $event.stopPropagation();

    $scope.opened = true;
  };

  $scope.preView = function () {
    var stepIndex = $scope.wizardSteps.indexOf($scope.curStep);
    if (stepIndex >= 1) {
      $scope.curStep.isComplete = false;
      $scope.curStep = $scope.wizardSteps[stepIndex - 1];
    }
  };

  $scope.nextView = function () {
    var stepIndex = $scope.wizardSteps.indexOf($scope.curStep);

    if (stepIndex < ($scope.wizardSteps.length - 1)) {
      $scope.curStep.isComplete = true;
      $scope.curStep = $scope.wizardSteps[stepIndex + 1];

      AuthenticationService.ping(function (data) {
        UserService.setCurUser(data);
      });
    }
  };

  $scope.checkForm = function () {
    if (!$scope.curStep.form) {
      return true;
    }
    if ($scope.state.mode === 'view') {
      return true;
    }
    else {
      //form validation
      if ($scope.forms[$scope.curStep.form].$invalid) {
        $scope.forms[$scope.curStep.form].$sbumitted = true;
        return false;
      } else {
        //business rule check
        switch ($scope.curStep.form) {
          case 'data_model_form':
            return $scope.check_data_model();
            break;
          case 'model_info_form':
            return $scope.check_model_info();
            break;
          case 'model_dimensions_form':
            return $scope.check_model_dimensions();
            break;
          case 'model_measure_form':
            return $scope.check_model_measure();
            break;
          case 'model_setting_form':
            return $scope.check_model_setting();
            break;
          default:
            return true;
            break;
        }
      }
    }
  };

  $scope.check_model_info = function () {

    var modelName = $scope.modelsManager.selectedModel.name.toUpperCase();
    var models = $scope.modelsManager.modelNameList;
    if ($scope.modelMode=="addNewModel") {
      if(models.indexOf(modelName) != -1 || models.indexOf(modelName.toLowerCase()) !=-1){
        SweetAlert.swal('', "Model named [" + modelName + "] already exist!", 'warning');
        return false;
      }
    }
    return true;
  }

  /*
   * lookups can't be null
   */
  $scope.check_data_model = function () {
    var errors = [];
//        if(!modelsManager.selectedModel.lookups.length){
//            errors.push("No lookup table defined");
//        }
    var errorInfo = "";
    angular.forEach(errors, function (item) {
      errorInfo += "\n" + item;
    });
    if (errors.length) {
      SweetAlert.swal('', errorInfo, 'warning');
      return false;
    } else {
      return true;
    }

  }

  /*
   * dimensions validation
   * 1.dimension can't be null
   */
  $scope.check_model_dimensions = function () {

    var errors = [];
    if (!modelsManager.selectedModel.dimensions.length) {
      errors.push("No dimensions defined.");
    }
    var isDimensionDefined = false;
    angular.forEach(modelsManager.selectedModel.dimensions, function (_dimension) {
      if(_dimension.columns && _dimension.columns.length){
        isDimensionDefined = true;
      }
    });
    if(!isDimensionDefined){
      errors.push("No dimensions defined.");
    }
    var errorInfo = "";
    angular.forEach(errors, function (item) {
      errorInfo += "\n" + item;
    });
    if (errors.length) {
      SweetAlert.swal('Oops...', errorInfo, 'warning');
      return false;
    } else {
      return true;
    }

  };

  /*
   * dimensions validation
   * 1.metric can't be null
   */
  $scope.check_model_measure = function () {

    var errors = [];
    if (!modelsManager.selectedModel.metrics || !modelsManager.selectedModel.metrics.length) {
      errors.push("Please define your metrics.");
    }
    var errorInfo = "";
    angular.forEach(errors, function (item) {
      errorInfo += "\n" + item;
    });
    if (errors.length) {
      SweetAlert.swal('', errorInfo, 'warning');
      return false;
    } else {
      return true;
    }

  };
  $scope.check_model_setting = function () {
    var errors = [];
    if (modelsManager.selectedModel.partition_desc.partition_date_column != null && modelsManager.selectedModel.partition_desc.partition_date_start == null) {
      errors.push("Please indicate start date when partition date column selected.");
    }
    var errorInfo = "";
    angular.forEach(errors, function (item) {
      errorInfo += "\n" + item;
    });
    if (errors.length) {
      SweetAlert.swal('', errorInfo, 'warning');
      return false;
    } else {
      return true;
    }
  }

  $scope.goToStep = function (stepIndex) {
    if ($scope.state.mode == "edit") {
      if (stepIndex + 1 >= $scope.curStep.step) {
        return;
      }
    }
    for (var i = 0; i < $scope.wizardSteps.length; i++) {
      if (i <= stepIndex) {
        $scope.wizardSteps[i].isComplete = true;
      } else {
        $scope.wizardSteps[i].isComplete = false;
      }
    }
    if (stepIndex < ($scope.wizardSteps.length)) {
      $scope.curStep = $scope.wizardSteps[stepIndex];

      AuthenticationService.ping(function (data) {
        UserService.setCurUser(data);
      });
    }
  }

  // ~ private methods
  function initProject() {

  }
});
<|endoftext|>


<commit_before>var request = require('request');
var story = require('storyboard').mainStory;
var fs = require('fs');
var path = require('path');
var decache = require('decache');

var langfile = require('../langfile');
var db = require('./db/sql_db');
var plugged = require('./client');

var commands = {};
var filelist = [];

loadCommands();

commands.reloadcommands = {
    handler: function (data) {
        redis.hget('user:roles', data.id).then(function (perm) {
            perm = parseInt(perm, 10);
            if (perm > 2) {
                filelist.forEach(function (e) {
                    decache(e);
                });
                commands = {};
                loadCommands();
                plugged.sendChat(uils.replace(langfile.commands.reload_commands, {username: data.username}), 45);
            }
        });
        plugged.removeChatMessage(data.cid);
    }
};

function loadCommands() {
    fs.readdir(path.resolve(__dirname, 'commands'), function (err, files) {
        if (err) {
            story.fatal('Cannot load commands', {attach: err});
            process.exit(1);
        } else {
            files.forEach(function (file) {
                try {
                    var command = require(path.resolve(__dirname, 'commands/' + file));
                    command.names.forEach(function (name) {
                        commands[name] = command;
                    });
                    filelist.push(path.resolve(__dirname, 'commands/' + file));
                    story.debug('Loaded command ' + command.names[0]);
                } catch (e) {
                    story.warn('Failed to load command.', {attach: e});
                }
            });
            story.info('Loaded ' + (files.length + 1) + ' commands.');
        }
    });
}

module.exports = commands;<commit_msg>fix reloadcommands<commit_after>var request = require('request');
var story = require('storyboard').mainStory;
var fs = require('fs');
var path = require('path');
var decache = require('decache');

var langfile = require('../langfile');
var db = require('./db/sql_db');
var plugged = require('./client');
var redis = require('./db/redis_db');
var utils = require('./utils');

var commands = {};
var filelist = [];

loadCommands();

commands.reloadcommands = {
    handler: function (data) {
        redis.hget('user:roles', data.id).then(function (perm) {
            perm = parseInt(perm, 10);
            if (perm > 2) {
                filelist.forEach(function (e) {
                    decache(e);
                });
                commands = {};
                loadCommands();
                plugged.sendChat(utils.replace(langfile.commands.reload_commands, {username: data.username}), 45);
            }
        });
        plugged.removeChatMessage(data.cid);
    }
};

function loadCommands() {
    fs.readdir(path.resolve(__dirname, 'commands'), function (err, files) {
        if (err) {
            story.fatal('Cannot load commands', {attach: err});
            process.exit(1);
        } else {
            files.forEach(function (file) {
                try {
                    var command = require(path.resolve(__dirname, 'commands/' + file));
                    command.names.forEach(function (name) {
                        commands[name] = command;
                    });
                    filelist.push(path.resolve(__dirname, 'commands/' + file));
                    story.debug('Loaded command ' + command.names[0]);
                } catch (e) {
                    story.warn('Failed to load command.', {attach: e});
                }
            });
            story.info('Loaded ' + (files.length + 1) + ' commands.');
        }
    });
}

module.exports = commands;<|endoftext|>