<commit_before>var page = require('webpage').create(),
    fs = require('fs'),
    system = require('system'),
    system_args_len = system.args.length,
    phantom_exit = function(code, message){
      if (message) {
        console.log(message);
      }

      if (page) {
        page.close();
      }

      phantom.exit(code || 0);
    };
if (system_args_len < 3 || system_args_len > 12) {
  phantom_exit(1, "Usage: phantomjs rasterize.js SOURCE DESTINATION [paperWidth*paperHeight|paperFormat] [header] [footer] [margin] [orientation] [zoom] [cookie_file] [render_timeout] [timeout]\n     : paper (pdf output) examples: \"5in*7.5in\", \"10cm*20cm\", \"A4\", \"Letter\"");
}

var // PhantomJS CAN NOT handle images in custom header/footer,
    // and this is used to fix the issue.
    io_images = [],

    is_http = function(s){
      return /https?:\/\/.+?/i.test(s) === true;
    },
    is_html = function(s){
      return /<([a-z]+?\d*?)[^>]*?>[^\0]*?<\/\1>/i.test(s) === true;
    }

    extract_images = function(html){
      var image_tags = html.match(/]+?src=(["'])https?:\/\/[^>]+?\1[^>]*?\/?>/ig),
          image_tags_len,
          i, image;
      if (image_tags === null) {
        return;
      }

      image_tags_len = image_tags.length;
      for (i=0; i<image_tags_len; i++) {
        image = image_tags[i].match(/src=(["'])(https?:\/\/[^>]+?)\1/i);

        if (image.length == 3 && io_images.indexOf(image[2]) < 0) {
          io_images[io_images.length] = image[2];
        }
      }
    },
    inject_images = function(html){
      var images_num = io_images.length;
      if (images_num < 1) {
        return html;
      }

      var klass, klasses = [],
          html_injected, html_temp,
          i, fragments = ['';
      fragments[fragments.length] = '

';

      html_injected = fragments.join('');

      html_temp = html.split('');
      if (html_temp.length > 1) {
        html_temp[html_temp.length - 1] = html_injected + html_temp.slice(-1)[0];

        html = html_temp.join('');
      } else {
        html = html + html_injected;
      }

      return html;
    },

    render_pdf = function(html){
      if (typeof(html) == 'string') {
        page.content = inject_images(html);
      }

      window.setTimeout(function(){
        var output_tmp = output + '_tmp.pdf';

        page.render(output_tmp);
        if (!fs.exists(output_tmp)) {
          phantom_exit(1, 'Failed to render pdf tmp file!');
        }

        if (fs.exists(output)) {
          fs.remove(output);
        }

        try {
          fs.move(output_tmp, output);

          // return pdf file path
          console.log(output);
        } catch (e) {
          phantom_exit(1, e.message);
        }

        phantom_exit()
      }, render_timeout);
    },

    input = system.args[1],
    output = system.args[2],

    margin = system.args[6] || '0cm',
    orientation = system.args[7] || 'portrait',
    zoom = system.args[8] || '1.0',

    cookie_file = system.args[9],
    cookies = {},

    render_timeout = system.args[10] || 10000,
    timeout = system.args[11] || 90000;

window.setTimeout(function(){
  phantom_exit(1, "Shit's being weird no result within " + timeout + "ms");
}, timeout);

page.viewportSize = { width:600, height:600 };
if (output.substr(-4) === '.pdf') {
  var size, header, footer,
      paper_size_options = {};
  if (system_args_len > 3) {
    size = system.args[3].split('*');
    paper_size_options = size.length === 2 ? {width:size[0], height:size[1], margin:'0px'} : {format:system.args[3], orientation:orientation, margin:margin};
  }

  if (system_args_len > 4) {
    header = system.args[4].split('*');
    if (header.length >= 2) {
      extract_images(header.join('*'));

      paper_size_options['header'] = {
        height: header.shift(),
        contents: phantom.callback(function(pageNum, pageTotal){
          return header.join('*').replace(new RegExp('%{pageNum}', 'g'), pageNum).replace(new RegExp('%{pageTotal}', 'g'), pageTotal);
        })
      };
    }
  }

  if (system_args_len > 5) {
    footer = system.args[5].split('*');
    if (footer.length >= 2) {
      extract_images(footer.join('*'));

      paper_size_options['footer'] = {
        height: footer.shift(),
        contents: phantom.callback(function(pageNum, pageTotal){
          return footer.join('*').replace(new RegExp('%{pageNum}', 'g'), pageNum).replace(new RegExp('%{pageTotal}', 'g'), pageTotal);
        })
      };
    }
  }

  page.paperSize = paper_size_options;
}
page.zoomFactor = zoom;

// cookies injection
if (cookie_file) {
  try {
    fd = fs.open(cookie_file, 'r');
    cookies = JSON.parse(fd.read());
    fs.remove(cookie_file);

    phantom.cookiesEnabled = true;
    phantom.cookies = cookies;
  } catch (e) {
    // ignore
  }
}

if (is_html(input)) {  // for html string
  render_pdf(input);
} else {  // for url resource
  // determine the resourceStatusCode
  var resourceStatusCode = null;
  page.onResourceReceived = function(resource){
    if (new RegExp('^'+input).test(resource.url)) {
      resourceStatusCode = resource.status;
    }
  };

  page.open(input, function(status){
    if (status !== 'success' || (resourceStatusCode !== null && resourceStatusCode != 200)) {
      console.log(resourceStatusCode, 'Failed to load the input!');

      if (fs.exists(output)) {
        fs.remove(output);
      }

      try {
        fs.touch(output);
      } catch (e) {
        phantom_exit(1, e.message);
      }

      phantom_exit(1);
    } else {
      render_pdf(is_http(input) ? null : page.content);
    }
  });
}
<commit_msg>fix global timeout and render timeout bug<commit_after>var page = require('webpage').create(),
    fs = require('fs'),
    system = require('system'),
    system_args_len = system.args.length,
    timer = null,
    phantom_exit = function(code, message){
      if (message) {
        console.log(message);
      }

      if (page) {
        page.close();
      }

      if (timer) {
        clearTimeout(timer);
      }

      phantom.exit(code || 0);
    };
if (system_args_len < 3 || system_args_len > 12) {
  phantom_exit(1, "Usage: phantomjs rasterize.js SOURCE DESTINATION [paperWidth*paperHeight|paperFormat] [header] [footer] [margin] [orientation] [zoom] [cookie_file] [render_timeout] [timeout]\n     : paper (pdf output) examples: \"5in*7.5in\", \"10cm*20cm\", \"A4\", \"Letter\"");
}

var input = system.args[1],
    output = system.args[2],

    margin = system.args[6] || '0cm',
    orientation = system.args[7] || 'portrait',
    zoom = system.args[8] || '1.0',

    cookie_file = system.args[9],
    cookies = {},

    render_timeout = system.args[10] || 10000,
    timeout = system.args[11] || 90000,

    // PhantomJS CAN NOT handle images in custom header/footer,
    // and this is used to fix the issue.
    // NOTE: You must pass HTML content if you want to use this feature!
    io_images = [],

    is_http = function(s){
      return /https?:\/\/.+?/i.test(s) === true;
    },
    is_html = function(s){
      return /<([a-z]+?\d*?)[^>]*?>[^\0]*?<\/\1>/i.test(s) === true;
    }

    extract_images = function(html){
      var image_tags = html.match(/]+?src=(["'])https?:\/\/[^>]+?\1[^>]*?\/?>/ig),
          image_tags_len,
          i, image;
      if (image_tags === null) {
        return;
      }

      image_tags_len = image_tags.length;
      for (i=0; i<image_tags_len; i++) {
        image = image_tags[i].match(/src=(["'])(https?:\/\/[^>]+?)\1/i);

        if (image.length == 3 && io_images.indexOf(image[2]) < 0) {
          io_images[io_images.length] = image[2];
        }
      }
    },
    inject_images = function(html){
      var images_num = io_images.length;
      if (images_num < 1) {
        return html;
      }

      var klass, klasses = [],
          html_injected, html_temp,
          i, fragments = ['';
      fragments[fragments.length] = '

';

      html_injected = fragments.join('');

      html_temp = html.split('');
      if (html_temp.length > 1) {
        html_temp[html_temp.length - 1] = html_injected + html_temp.slice(-1)[0];

        html = html_temp.join('');
      } else {
        html = html + html_injected;
      }

      return html;
    },

    render_pdf = function(html){
      if (typeof(html) == 'string') {
        page.content = inject_images(html);
      }

      timer = window.setTimeout(function(){
        var output_tmp = output + '_tmp.pdf';

        page.render(output_tmp);
        if (!fs.exists(output_tmp)) {
          phantom_exit(1, 'Failed to render pdf tmp file!');
        }

        if (fs.exists(output)) {
          fs.remove(output);
        }

        try {
          fs.move(output_tmp, output);

          // return pdf file path
          console.log(output);
        } catch (e) {
          phantom_exit(1, e.message);
        }

        phantom_exit()
      }, render_timeout);
    };

var overtimer = window.setTimeout(function(){
  clearTimeout(overtimer);
  phantom_exit(1, "Shit's being weird no result within " + timeout + "ms");
}, timeout);

page.viewportSize = { width:600, height:600 };
if (output.substr(-4) === '.pdf') {
  var size, header, footer,
      paper_size_options = {};
  if (system_args_len > 3) {
    size = system.args[3].split('*');
    paper_size_options = size.length === 2 ? {width:size[0], height:size[1], margin:'0px'} : {format:system.args[3], orientation:orientation, margin:margin};
  }

  if (system_args_len > 4) {
    header = system.args[4].split('*');
    if (header.length >= 2) {
      extract_images(header.join('*'));

      paper_size_options['header'] = {
        height: header.shift(),
        contents: phantom.callback(function(pageNum, pageTotal){
          return header.join('*').replace(new RegExp('%{pageNum}', 'g'), pageNum).replace(new RegExp('%{pageTotal}', 'g'), pageTotal);
        })
      };
    }
  }

  if (system_args_len > 5) {
    footer = system.args[5].split('*');
    if (footer.length >= 2) {
      extract_images(footer.join('*'));

      paper_size_options['footer'] = {
        height: footer.shift(),
        contents: phantom.callback(function(pageNum, pageTotal){
          return footer.join('*').replace(new RegExp('%{pageNum}', 'g'), pageNum).replace(new RegExp('%{pageTotal}', 'g'), pageTotal);
        })
      };
    }
  }

  page.paperSize = paper_size_options;
}
page.zoomFactor = zoom;

// cookies injection
if (cookie_file) {
  try {
    fd = fs.open(cookie_file, 'r');
    cookies = JSON.parse(fd.read());
    fs.remove(cookie_file);

    phantom.cookiesEnabled = true;
    phantom.cookies = cookies;
  } catch (e) {
    // ignore
  }
}

if (is_html(input)) {  // for html string
  render_pdf(input);
} else {  // for url resource
  // determine the resourceStatusCode
  var resourceStatusCode = null;
  page.onResourceReceived = function(resource){
    if (new RegExp('^'+input).test(resource.url)) {
      resourceStatusCode = resource.status;
    }
  };

  page.open(input, function(status){
    if (status !== 'success' || (resourceStatusCode !== null && resourceStatusCode != 200)) {
      console.log(resourceStatusCode, 'Failed to load the input!');

      if (fs.exists(output)) {
        fs.remove(output);
      }

      try {
        fs.touch(output);
      } catch (e) {
        phantom_exit(1, e.message);
      }

      phantom_exit(1);
    } else {
      render_pdf(is_http(input) ? null : page.content);
    }
  });
}
<|endoftext|>


<commit_before>define(["backbone", "app", "underscore"], function(Backbone, app, _) {
    return Backbone.Model.extend({
    //data attributes
    defauls:{
    	validateHashes: {}
    },

    //converter
    finish: function(){
    	//match values
  		if(_.contains(validateHashes, "attr.ecol")){
  			app.ratings.addBaseValue("colors", this.get("attr").ecol);
  		};
  		if(_.contains(validateHashes, "category")){
  			app.ratings.addBaseValue("carclasses", this.get("category"));
  		};
  		//TODO get seats
  		if(_.contains(validateHashes, "seats")){
  			app.ratings.addBaseValue("seats", seats);
  		};
  		if(_.contains(validateHashes, "attr.price.grs.ammount")){
  			app.ratings.addBaseValue("priceclasses", app.ratings.getPriceCategory(this.get("attr").price.grs.ammount));
  		};
    	app.blacklist.addId(this.id);
    },

    setValue: function(key){
    	validateHashes[key] = key;
    },

    unsetValue: function(key){
    	delete validateHashes[key];
    },

    });
});<commit_msg>refactored finishing<commit_after>define(["backbone", "app", "underscore"], function(Backbone, app, _) {
    return Backbone.Model.extend({
    // data attributes
    defauls:{
    	validateHashes: {}
    },

    // converter
    finish: function(detailsModel) {
      var baseValueMapping = {
        "color": "colors",
        "carclass": "carclasses",
        "numSeat": "seats",
        "price": function(value) { app.ratings.addBaseValue("priceclasses", app.ratings.getPriceCategory(value)); }
      };

      _.each(baseValueMapping, function(mappingKey, key) {
        if (this.attributes.validateHashes[key]) {
          if (_.isString(this.attributes.validateHashes)) {
            app.ratings.addBaseValue(mappingKey, this.attributes.validateHashes[key]);
          } else if (_.isFunction(mappingKey)) {
            mappingKey(this.attributes.validateHashes[key]);
          }
        }
      });

    	app.blacklistService.addId(this.id);
    },

    setValue: function(key, value) {
    	this.attributes.validateHashes[key] = value;
    },

    unsetValue: function(key) {
    	delete this.attributes.validateHashes[key];
    },

    });
});
<|endoftext|>


<commit_before>/*
Input Mask plugin extentions
http://github.com/RobinHerbots/jquery.inputmask
Copyright (c) 2010 Robin Herbots
Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
Version: 0.0.1

Optional extentions on the jquery.inputmask base
*/
(function($) {
    //extra definitions
    $.extend($.inputmask.defaults.definitions, {
        'h': { //hours
            validator: "[01][0-9]|2[0-3]",
            cardinality: 2,
            prevalidator: [{ validator: "[0-2]", cardinality: 1}]
        },
        's': { //seconds || minutes
            validator: "[0-5][0-9]",
            cardinality: 2,
            prevalidator: [{ validator: "[0-5]", cardinality: 1}]
        },
        'd': { //day
            validator: "0[1-9]|[12][0-9]|3[01]",
            cardinality: 2,
            prevalidator: [{ validator: "[0-3]", cardinality: 1}]
        },
        'm': { //month
            validator: "0[1-9]|1[012]",
            cardinality: 2,
            prevalidator: [{ validator: "[01]", cardinality: 1}]
        },
        'y': { //year
            validator: "(19|20)\\d\\d",
            cardinality: 4,
            prevalidator: [
                        { validator: "[12]", cardinality: 1 },
                        { validator: "(19|20)", cardinality: 2 },
                        { validator: "(19|20)\\d", cardinality: 3 }
                        ]
        },
        'A': {
            validator: "[A-Za-z]",
            cardinality: 1,
            casing: "upper"
        }
    });
    //aliases
    $.extend($.inputmask.defaults.aliases, {
        'dd/mm/yyyy': {
            mask: "d/m/y",
            placeholder: "dd/mm/yyyy",
            regex: {
                monthpre: new RegExp("[01]"),
                month: new RegExp("((0[1-9]|[12][0-9])\/(0[1-9]|1[012]))|(30\/(0[13-9]|1[012]))|(31\/(0[13578]|1[02]))"),
                year: new RegExp("(19|20)\\d\\d"),
                daypre: new RegExp("[0-3]"),
                day: new RegExp("0[1-9]|[12][0-9]|3[01]")
            },
            definitions: {
                'd': { //day
                    validator: function(chrs, buffer, pos, strict, opts) {
                        var isValid = opts.regex.day.test(chrs);
                        if (!strict && !isValid) {
                            if (chrs.charAt(1) == '/') {
                                isValid = opts.regex.day.test("0" + chrs.charAt(0));
                                if (isValid) {
                                    buffer[pos - 1] = "0";
                                    buffer[pos] = chrs.charAt(0);
                                    pos++;
                                    return pos;
                                }
                            }
                        }
                        return isValid;
                    },
                    cardinality: 2,
                    prevalidator: [{ validator: function(chrs, buffer, pos, strict, opts) {
                        var isValid = opts.regex.daypre.test(chrs);
                        if (!strict && !isValid) {
                            isValid = opts.regex.day.test("0" + chrs);
                            if (isValid) {
                                buffer[pos] = "0";
                                pos++;
                                return pos;
                            }
                        }
                        return isValid;
                    }, cardinality: 1}]
                    },
                    'm': { //month
                        validator: function(chrs, buffer, pos, strict, opts) {
                            var dayValue = buffer.join('').substr(0, 3);
                            var isValid = opts.regex.month.test(dayValue + chrs);
                            if (!strict && !isValid) {
                                if (chrs.charAt(1) == '/') {
                                    isValid = opts.regex.month.test(dayValue + "0" + chrs.charAt(0));
                                    if (isValid) {
                                        buffer[pos - 1] = "0";
                                        buffer[pos] = chrs.charAt(0);
                                        pos++;
                                        return pos;
                                    }
                                }
                            }
                            return isValid;
                        },
                        cardinality: 2,
                        prevalidator: [{ validator: function(chrs, buffer, pos, strict, opts) {
                            var isValid = opts.regex.monthpre.test(chrs);
                            if (!strict && !isValid) {
                                var dayValue = buffer.join('').substr(0, 3);
                                isValid = opts.regex.month.test(dayValue + "0" + chrs);
                                if (isValid) {
                                    buffer[pos] = "0";
                                    pos++;
                                    return pos;
                                }
                            }
                            return isValid;
                        }, cardinality: 1}]
                        },
                        'y': { //year
                            validator: function(chrs, buffer, pos, strict, opts) {
                                if (opts.regex.year.test(chrs)) {
                                    var dayMonthValue = buffer.join('').substr(0, 6);
                                    if (dayMonthValue != "29/02/")
                                        return true;
                                    else {
                                        var year = parseInt(chrs);  //detect leap year
                                        if (year % 4 == 0)
                                            if (year % 100 == 0)
                                            if (year % 400 == 0)
                                            return true;
                                        else return false;
                                        else return true;
                                        else return false;
                                    }
                                } else return false;
                            },
                            cardinality: 4,
                            prevalidator: [
                        { validator: "[12]", cardinality: 1 },
                        { validator: "(19|20)", cardinality: 2 },
                        { validator: "(19|20)\\d", cardinality: 3 }
                        ]
                        }
                    },
                    insertMode: false,
                    autoUnmask: false
                },
                'mm/dd/yyyy': {
                    mask: "m/d/y",
                    placeholder: "mm/dd/yyyy",
                    regex: {
                        day: new RegExp("((0[1-9]|1[012])\/(0[1-9]|[12][0-9]))|((0[13-9]|1[012])\/30)|((0[13578]|1[02])\/31)"),
                        daypre: new RegExp("((0[13-9]|1[012])\/[0-3])|(02\/[0-2])"),
                        month: new RegExp("0[1-9]|1[012]"),
                        monthpre: new RegExp("[01]"),
                        year: new RegExp("(19|20)\\d\\d")
                    },
                    definitions: {
                        'd': { //day
                            validator: function(chrs, buffer, pos, strict, opts) {
                                var monthValue = buffer.join('').substr(0, 3);
                                var isValid = opts.regex.day.test(monthValue + chrs);
                                if (!strict && !isValid) {
                                    if (chrs.charAt(1) == '/') {
                                        isValid = opts.regex.day.test(monthValue + "0" + chrs.charAt(0));
                                        if (isValid) {
                                            buffer[pos - 1] = "0";
                                            buffer[pos] = chrs.charAt(0);
                                            pos++;
                                            return pos;
                                        }
                                    }
                                }
                                return isValid;
                            },
                            cardinality: 2,
                            prevalidator: [{ validator: function(chrs, buffer, pos, strict, opts) {
                                var monthValue = buffer.join('').substr(0, 3);
                                var isValid = opts.regex.daypre.test(monthValue + chrs);
                                if (!strict && !isValid) {
                                    isValid = opts.regex.day.test(monthValue + "0" + chrs);
                                    if (isValid) {
                                        buffer[pos] = "0";
                                        pos++;
                                        return pos;
                                    }
                                }
                                return isValid;
                            },
                                cardinality: 1}]
                            },
                            'm': { //month
                                validator: function(chrs, buffer, pos, strict, opts) {
                                    var isValid = opts.regex.month.test(chrs);
                                    if (!strict && !isValid) {
                                        if (chrs.charAt(1) == '/') {
                                            isValid = opts.regex.month.test("0" + chrs.charAt(0));
                                            if (isValid) {
                                                buffer[pos - 1] = "0";
                                                buffer[pos] = chrs.charAt(0);
                                                pos++;
                                                return pos;
                                            }
                                        }
                                    }
                                    return isValid;
                                },
                                cardinality: 2,
                                prevalidator: [{ validator: function(chrs, buffer, pos, strict, opts) {
                                    var isValid = opts.regex.monthpre.test(chrs);
                                    if (!strict && !isValid) {
                                        isValid = opts.regex.month.test("0" + chrs);
                                        if (isValid) {
                                            buffer[pos] = "0";
                                            pos++;
                                            return pos;
                                        }
                                    }
                                    return isValid;
                                }, cardinality: 1}]
                                },
                                'y': { //year
                                    validator: function(chrs, buffer, pos, strict, opts) {
                                        if (opts.regex.year.test(chrs)) {
                                            var monthDayValue = buffer.join('').substr(0, 6);
                                            if (monthDayValue != "02/29/")
                                                return true;
                                            else {
                                                var year = parseInt(chrs);  //detect leap year
                                                if (year % 4 == 0)
                                                    if (year % 100 == 0)
                                                    if (year % 400 == 0)
                                                    return true;
                                                else return false;
                                                else return true;
                                                else return false;
                                            }
                                        } else return false;
                                    },
                                    cardinality: 4,
                                    prevalidator: [
                        { validator: "[12]", cardinality: 1 },
                        { validator: "(19|20)", cardinality: 2 },
                        { validator: "(19|20)\\d", cardinality: 3 }
                        ]
                                }
                            },
                            insertMode: false,
                            autoUnmask: false
                        },
                        'hh:mm:ss': {
                            mask: "h:s:s",
                            autoUnmask: false
                        },
                        'hh:mm': {
                            mask: "h:s",
                            autoUnmask: false
                        },
                        'date': {
                            alias: "dd/mm/yyyy" // "mm/dd/yyyy"
                        },
                        'datetime': {
                            mask: "d/m/y h:s",
                            placeholder: "dd/mm/yyyy hh:mm",
                            regex: {
                                month: new RegExp("((0[1-9]|[12][0-9])\/(0[1-9]|1[012]))|(30\/(0[13-9]|1[012]))|(31\/(0[13578]|1[02]))"),
                                year: new RegExp("(19|20)\\d\\d")
                            },
                            definitions: {
                                'm': { //month
                                    validator: function(chrs, buffer, pos, strict, opts) {
                                        var dayValue = buffer.join('').substr(0, 3);
                                        return opts.regex.month.test(dayValue + chrs);
                                    },
                                    cardinality: 2,
                                    prevalidator: [{ validator: "[01]", cardinality: 1}]
                                },
                                'y': { //year
                                    validator: function(chrs, buffer, pos, strict, opts) {
                                        if (opts.regex.year.test(chrs)) {
                                            var dayMonthValue = buffer.join('').substr(0, 6);
                                            if (dayMonthValue != "29/02/")
                                                return true;
                                            else {
                                                var year = parseInt(chrs);  //detect leap year
                                                if (year % 4 == 0)
                                                    if (year % 100 == 0)
                                                    if (year % 400 == 0)
                                                    return true;
                                                else return false;
                                                else return true;
                                                else return false;
                                            }
                                        } else return false;
                                    },
                                    cardinality: 4,
                                    prevalidator: [
                        { validator: "[12]", cardinality: 1 },
                        { validator: "(19|20)", cardinality: 2 },
                        { validator: "(19|20)\\d", cardinality: 3 }
                        ]
                                }
                            },
                            insertMode: false,
                            autoUnmask: false
                        },
                        //number aliases by Dean (datimson)
                        'decimal': {
                            mask: "~",
                            placeholder: "",
                            repeat: 10,
                            greedy: false,
                            radixPoint: "\.", // | ","
                            regex: {
                                real: function(radixPoint) { return new RegExp("^([\+\-]?[0-9]*[" + radixPoint + "]?[0-9]*)$"); }
                            },
                            definitions: {
                                '~': { //real number
                                    validator: function(chrs, buffer, pos, strict, opts) {
                                        var myBuffer = buffer.slice();
                                        myBuffer.splice(pos, 0, chrs);
                                        var test = myBuffer.join('');
                                        var isValid = opts.regex.real(opts.radixPoint).test(test);
                                        return isValid;
                                    },
                                    cardinality: 1,
                                    prevalidator: null
                                }
                            },
                            insertMode: true
                        },
                        'non-negative-decimal': {
                            mask: "~",
                            placeholder: "",
                            repeat: 10,
                            greedy: false,
                            radixPoint: "\.", // | ","
                            regex: {
                                decimal: function(radixPoint) { return new RegExp("^([0-9]+[" + radixPoint + "]?[0-9]*)$"); }
                            },
                            definitions: {
                                '~': {
                                    validator: function(chrs, buffer, pos, strict, opts) {
                                        var myBuffer = buffer.slice();
                                        myBuffer.splice(pos, 0, chrs);
                                        var test = myBuffer.join('');
                                        var isValid = opts.regex.decimal(opts.radixPoint).test(test);
                                        return isValid;
                                    },
                                    cardinality: 1,
                                    prevalidator: null
                                }
                            },
                            insertMode: true
                        },
                        'integer': {
                            mask: "~",
                            placeholder: "",
                            repeat: 10,
                            greedy: false,
                            numericInput: true,
                            regex: {
                                integer: new RegExp("^([\+\-]?[0-9]*)$")
                            },
                            definitions: {
                                '~': {
                                    validator: function(chrs, buffer, pos, strict, opts) {
                                        var myBuffer = buffer.slice();
                                        myBuffer.splice(pos, 0, chrs);
                                        var test = myBuffer.join('');
                                        var isValid = opts.regex.integer.test(test);
                                        return isValid;
                                    },
                                    cardinality: 1,
                                    prevalidator: null
                                }
                            },
                            insertMode: true
                        }
                    });
                })(jQuery);<commit_msg>new datetime alias<commit_after>/*
Input Mask plugin extentions
http://github.com/RobinHerbots/jquery.inputmask
Copyright (c) 2010 Robin Herbots
Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
Version: 0.0.2

Optional extentions on the jquery.inputmask base
*/
(function($) {
    //extra definitions
    $.extend($.inputmask.defaults.definitions, {
        'h': { //hours
            validator: "[01][0-9]|2[0-3]",
            cardinality: 2,
            prevalidator: [{ validator: "[0-2]", cardinality: 1}]
        },
        's': { //seconds || minutes
            validator: "[0-5][0-9]",
            cardinality: 2,
            prevalidator: [{ validator: "[0-5]", cardinality: 1}]
        },
        'd': { //basic day
            validator: "0[1-9]|[12][0-9]|3[01]",
            cardinality: 2,
            prevalidator: [{ validator: "[0-3]", cardinality: 1}]
        },
        'm': { //basic month
            validator: "0[1-9]|1[012]",
            cardinality: 2,
            prevalidator: [{ validator: "[01]", cardinality: 1}]
        },
        'y': { //basic year
            validator: "(19|20)\\d\\d",
            cardinality: 4,
            prevalidator: [
                        { validator: "[12]", cardinality: 1 },
                        { validator: "(19|20)", cardinality: 2 },
                        { validator: "(19|20)\\d", cardinality: 3 }
                        ]
        },
        'A': {
            validator: "[A-Za-z]",
            cardinality: 1,
            casing: "upper"
        }
    });
    //aliases
    $.extend($.inputmask.defaults.aliases, {
        'dd/mm/yyyy': {
            mask: "d/m/y",
            placeholder: "dd/mm/yyyy",
            regex: {
                monthpre: new RegExp("[01]"),
                month: new RegExp("((0[1-9]|[12][0-9])\/(0[1-9]|1[012]))|(30\/(0[13-9]|1[012]))|(31\/(0[13578]|1[02]))"),
                year: new RegExp("(19|20)\\d\\d"),
                daypre: new RegExp("[0-3]"),
                day: new RegExp("0[1-9]|[12][0-9]|3[01]")
            },
            definitions: {
                'd': { //day
                    validator: function(chrs, buffer, pos, strict, opts) {
                        var isValid = opts.regex.day.test(chrs);
                        if (!strict && !isValid) {
                            if (chrs.charAt(1) == '/') {
                                isValid = opts.regex.day.test("0" + chrs.charAt(0));
                                if (isValid) {
                                    buffer[pos - 1] = "0";
                                    buffer[pos] = chrs.charAt(0);
                                    pos++;
                                    return pos;
                                }
                            }
                        }
                        return isValid;
                    },
                    cardinality: 2,
                    prevalidator: [{ validator: function(chrs, buffer, pos, strict, opts) {
                        var isValid = opts.regex.daypre.test(chrs);
                        if (!strict && !isValid) {
                            isValid = opts.regex.day.test("0" + chrs);
                            if (isValid) {
                                buffer[pos] = "0";
                                pos++;
                                return pos;
                            }
                        }
                        return isValid;
                    }, cardinality: 1}]
                    },
                    'm': { //month
                        validator: function(chrs, buffer, pos, strict, opts) {
                            var dayValue = buffer.join('').substr(0, 3);
                            var isValid = opts.regex.month.test(dayValue + chrs);
                            if (!strict && !isValid) {
                                if (chrs.charAt(1) == '/') {
                                    isValid = opts.regex.month.test(dayValue + "0" + chrs.charAt(0));
                                    if (isValid) {
                                        buffer[pos - 1] = "0";
                                        buffer[pos] = chrs.charAt(0);
                                        pos++;
                                        return pos;
                                    }
                                }
                            }
                            return isValid;
                        },
                        cardinality: 2,
                        prevalidator: [{ validator: function(chrs, buffer, pos, strict, opts) {
                            var isValid = opts.regex.monthpre.test(chrs);
                            if (!strict && !isValid) {
                                var dayValue = buffer.join('').substr(0, 3);
                                isValid = opts.regex.month.test(dayValue + "0" + chrs);
                                if (isValid) {
                                    buffer[pos] = "0";
                                    pos++;
                                    return pos;
                                }
                            }
                            return isValid;
                        }, cardinality: 1}]
                        },
                        'y': { //year
                            validator: function(chrs, buffer, pos, strict, opts) {
                                if (opts.regex.year.test(chrs)) {
                                    var dayMonthValue = buffer.join('').substr(0, 6);
                                    if (dayMonthValue != "29/02/")
                                        return true;
                                    else {
                                        var year = parseInt(chrs);  //detect leap year
                                        if (year % 4 == 0)
                                            if (year % 100 == 0)
                                            if (year % 400 == 0)
                                            return true;
                                        else return false;
                                        else return true;
                                        else return false;
                                    }
                                } else return false;
                            },
                            cardinality: 4,
                            prevalidator: [
                        { validator: "[12]", cardinality: 1 },
                        { validator: "(19|20)", cardinality: 2 },
                        { validator: "(19|20)\\d", cardinality: 3 }
                        ]
                        }
                    },
                    insertMode: false,
                    autoUnmask: false
                },
                'mm/dd/yyyy': {
                    mask: "m/d/y",
                    placeholder: "mm/dd/yyyy",
                    regex: {
                        day: new RegExp("((0[1-9]|1[012])\/(0[1-9]|[12][0-9]))|((0[13-9]|1[012])\/30)|((0[13578]|1[02])\/31)"),
                        daypre: new RegExp("((0[13-9]|1[012])\/[0-3])|(02\/[0-2])"),
                        month: new RegExp("0[1-9]|1[012]"),
                        monthpre: new RegExp("[01]"),
                        year: new RegExp("(19|20)\\d\\d")
                    },
                    definitions: {
                        'd': { //day
                            validator: function(chrs, buffer, pos, strict, opts) {
                                var monthValue = buffer.join('').substr(0, 3);
                                var isValid = opts.regex.day.test(monthValue + chrs);
                                if (!strict && !isValid) {
                                    if (chrs.charAt(1) == '/') {
                                        isValid = opts.regex.day.test(monthValue + "0" + chrs.charAt(0));
                                        if (isValid) {
                                            buffer[pos - 1] = "0";
                                            buffer[pos] = chrs.charAt(0);
                                            pos++;
                                            return pos;
                                        }
                                    }
                                }
                                return isValid;
                            },
                            cardinality: 2,
                            prevalidator: [{ validator: function(chrs, buffer, pos, strict, opts) {
                                var monthValue = buffer.join('').substr(0, 3);
                                var isValid = opts.regex.daypre.test(monthValue + chrs);
                                if (!strict && !isValid) {
                                    isValid = opts.regex.day.test(monthValue + "0" + chrs);
                                    if (isValid) {
                                        buffer[pos] = "0";
                                        pos++;
                                        return pos;
                                    }
                                }
                                return isValid;
                            },
                                cardinality: 1}]
                            },
                            'm': { //month
                                validator: function(chrs, buffer, pos, strict, opts) {
                                    var isValid = opts.regex.month.test(chrs);
                                    if (!strict && !isValid) {
                                        if (chrs.charAt(1) == '/') {
                                            isValid = opts.regex.month.test("0" + chrs.charAt(0));
                                            if (isValid) {
                                                buffer[pos - 1] = "0";
                                                buffer[pos] = chrs.charAt(0);
                                                pos++;
                                                return pos;
                                            }
                                        }
                                    }
                                    return isValid;
                                },
                                cardinality: 2,
                                prevalidator: [{ validator: function(chrs, buffer, pos, strict, opts) {
                                    var isValid = opts.regex.monthpre.test(chrs);
                                    if (!strict && !isValid) {
                                        isValid = opts.regex.month.test("0" + chrs);
                                        if (isValid) {
                                            buffer[pos] = "0";
                                            pos++;
                                            return pos;
                                        }
                                    }
                                    return isValid;
                                }, cardinality: 1}]
                                },
                                'y': { //year
                                    validator: function(chrs, buffer, pos, strict, opts) {
                                        if (opts.regex.year.test(chrs)) {
                                            var monthDayValue = buffer.join('').substr(0, 6);
                                            if (monthDayValue != "02/29/")
                                                return true;
                                            else {
                                                var year = parseInt(chrs);  //detect leap year
                                                if (year % 4 == 0)
                                                    if (year % 100 == 0)
                                                    if (year % 400 == 0)
                                                    return true;
                                                else return false;
                                                else return true;
                                                else return false;
                                            }
                                        } else return false;
                                    },
                                    cardinality: 4,
                                    prevalidator: [
                        { validator: "[12]", cardinality: 1 },
                        { validator: "(19|20)", cardinality: 2 },
                        { validator: "(19|20)\\d", cardinality: 3 }
                        ]
                                }
                            },
                            insertMode: false,
                            autoUnmask: false
                        },
                        'hh:mm:ss': {
                            mask: "h:s:s",
                            autoUnmask: false
                        },
                        'hh:mm': {
                            mask: "h:s",
                            autoUnmask: false
                        },
                        'date': {
                            alias: "dd/mm/yyyy" // "mm/dd/yyyy"
                        },
                        'datetime': {
                            mask: "d/m/y h:s",
                            placeholder: "dd/mm/yyyy hh:mm",
                            alias: "date"
                        },
                        //number aliases by Dean (datimson)
                        'decimal': {
                            mask: "~",
                            placeholder: "",
                            repeat: 10,
                            greedy: false,
                            radixPoint: "\.", // | ","
                            regex: {
                                real: function(radixPoint) { return new RegExp("^([\+\-]?[0-9]*[" + radixPoint + "]?[0-9]*)$"); }
                            },
                            definitions: {
                                '~': { //real number
                                    validator: function(chrs, buffer, pos, strict, opts) {
                                        var myBuffer = buffer.slice();
                                        myBuffer.splice(pos, 0, chrs);
                                        var test = myBuffer.join('');
                                        var isValid = opts.regex.real(opts.radixPoint).test(test);
                                        return isValid;
                                    },
                                    cardinality: 1,
                                    prevalidator: null
                                }
                            },
                            insertMode: true
                        },
                        'non-negative-decimal': {
                            mask: "~",
                            placeholder: "",
                            repeat: 10,
                            greedy: false,
                            radixPoint: "\.", // | ","
                            regex: {
                                decimal: function(radixPoint) { return new RegExp("^([0-9]+[" + radixPoint + "]?[0-9]*)$"); }
                            },
                            definitions: {
                                '~': {
                                    validator: function(chrs, buffer, pos, strict, opts) {
                                        var myBuffer = buffer.slice();
                                        myBuffer.splice(pos, 0, chrs);
                                        var test = myBuffer.join('');
                                        var isValid = opts.regex.decimal(opts.radixPoint).test(test);
                                        return isValid;
                                    },
                                    cardinality: 1,
                                    prevalidator: null
                                }
                            },
                            insertMode: true
                        },
                        'integer': {
                            mask: "~",
                            placeholder: "",
                            repeat: 10,
                            greedy: false,
                            numericInput: true,
                            regex: {
                                integer: new RegExp("^([\+\-]?[0-9]*)$")
                            },
                            definitions: {
                                '~': {
                                    validator: function(chrs, buffer, pos, strict, opts) {
                                        var myBuffer = buffer.slice();
                                        myBuffer.splice(pos, 0, chrs);
                                        var test = myBuffer.join('');
                                        var isValid = opts.regex.integer.test(test);
                                        return isValid;
                                    },
                                    cardinality: 1,
                                    prevalidator: null
                                }
                            },
                            insertMode: true
                        }
                    });
                })(jQuery);<|endoftext|>


<commit_before>
/**
 * @ngdoc directive
 * @name ionSlides
 * @module ionic
 * @delegate ionic.service:$ionicSlideBoxDelegate
 * @restrict E
 * @description
 * The Slides component is a powerful multi-page container where each page can be swiped or dragged between.
 *
 * Note: this is a new version of the Ionic Slide Box based on the [Swiper](http://www.idangero.us/swiper/#.Vmc1J-ODFBc) widget from
 * [idangerous](http://www.idangero.us/).
 *
 * ![SlideBox](http://ionicframework.com.s3.amazonaws.com/docs/controllers/slideBox.gif)
 *
 * @usage
 * ```html
 * <ion-slides on-slide-changed="slideHasChanged($index)">
 *   <ion-slide-page>
 *     <div class="box blue"><h1>BLUE</h1></div>
 *   </ion-slide-page>
 *   <ion-slide-page>
 *     <div class="box yellow"><h1>YELLOW</h1></div>
 *   </ion-slide-page>
 *   <ion-slide-page>
 *     <div class="box pink"><h1>PINK</h1></div>
 *   </ion-slide-page>
 * </ion-slides>
 * ```
 *
 * @param {string=} delegate-handle The handle used to identify this slideBox
 * with {@link ionic.service:$ionicSlideBoxDelegate}.
 * @param {object=} options to pass to the widget. See the full ist here: [http://www.idangero.us/swiper/api/](http://www.idangero.us/swiper/api/)
 */
IonicModule
.directive('ionSlides', [
  '$animate',
  '$timeout',
function($animate, $timeout) {
  return {
    restrict: 'E',
    transclude: true,
    scope: {
      options: '=',
      slider: '='
    },
    template: '
' +
      '
' +
      '
' +
        '

' +
      '
',
    controller: ['$scope', '$element', function($scope, $element) {
      var _this = this;

      this.update = function() {
        $timeout(function() {
          _this.__slider.update();
          if (_this._options.loop) {
            _this.__slider.createLoop();
          }

          // Don't allow pager to show with > 10 slides
          if (_this.__slider.slides.length > 10) {
            $scope.showPager = false;
          }
        });
      };

      this.rapidUpdate = ionic.debounce(function() {
        _this.update();
      }, 50);

      this.getSlider = function() {
        return _this.__slider;
      };

      var options = $scope.options || {};

      var newOptions = angular.extend({
        pagination: '.swiper-pagination',
        paginationClickable: true,
        lazyLoading: true,
        preloadImages: false
      }, options);

      this._options = newOptions;

      $timeout(function() {
        var slider = new ionic.views.Swiper($element.children()[0], newOptions, $scope);

        _this.__slider = slider;
        $scope.slider = _this.__slider;

        $scope.$on('$destroy', function() {
          slider.destroy();
        });
      });

    }],

    link: function($scope, $element) {
      $scope.showPager = true;
      // Disable ngAnimate for slidebox and its children
      $animate.enabled(false, $element);
    }
  };
}])
.directive('ionSlidePage', [function() {
  return {
    restrict: 'E',
    require: '?^ionSlides',
    transclude: true,
    replace: true,
    template: '

',
    link: function($scope, $element, $attr, ionSlidesCtrl) {
      ionSlidesCtrl.rapidUpdate();
    }
  };
}]);
<commit_msg>fix(slides): check for slide first before update. Fixes #4870<commit_after>
/**
 * @ngdoc directive
 * @name ionSlides
 * @module ionic
 * @delegate ionic.service:$ionicSlideBoxDelegate
 * @restrict E
 * @description
 * The Slides component is a powerful multi-page container where each page can be swiped or dragged between.
 *
 * Note: this is a new version of the Ionic Slide Box based on the [Swiper](http://www.idangero.us/swiper/#.Vmc1J-ODFBc) widget from
 * [idangerous](http://www.idangero.us/).
 *
 * ![SlideBox](http://ionicframework.com.s3.amazonaws.com/docs/controllers/slideBox.gif)
 *
 * @usage
 * ```html
 * <ion-slides on-slide-changed="slideHasChanged($index)">
 *   <ion-slide-page>
 *     <div class="box blue"><h1>BLUE</h1></div>
 *   </ion-slide-page>
 *   <ion-slide-page>
 *     <div class="box yellow"><h1>YELLOW</h1></div>
 *   </ion-slide-page>
 *   <ion-slide-page>
 *     <div class="box pink"><h1>PINK</h1></div>
 *   </ion-slide-page>
 * </ion-slides>
 * ```
 *
 * @param {string=} delegate-handle The handle used to identify this slideBox
 * with {@link ionic.service:$ionicSlideBoxDelegate}.
 * @param {object=} options to pass to the widget. See the full ist here: [http://www.idangero.us/swiper/api/](http://www.idangero.us/swiper/api/)
 */
IonicModule
.directive('ionSlides', [
  '$animate',
  '$timeout',
function($animate, $timeout) {
  return {
    restrict: 'E',
    transclude: true,
    scope: {
      options: '=',
      slider: '='
    },
    template: '
' +
      '
' +
      '
' +
        '

' +
      '
',
    controller: ['$scope', '$element', function($scope, $element) {
      var _this = this;

      this.update = function() {
        $timeout(function() {
          if(!_this.__slider) {
            return;
          }

          _this.__slider.update();
          if (_this._options.loop) {
            _this.__slider.createLoop();
          }

          // Don't allow pager to show with > 10 slides
          if (_this.__slider.slides.length > 10) {
            $scope.showPager = false;
          }
        });
      };

      this.rapidUpdate = ionic.debounce(function() {
        _this.update();
      }, 50);

      this.getSlider = function() {
        return _this.__slider;
      };

      var options = $scope.options || {};

      var newOptions = angular.extend({
        pagination: '.swiper-pagination',
        paginationClickable: true,
        lazyLoading: true,
        preloadImages: false
      }, options);

      this._options = newOptions;

      $timeout(function() {
        var slider = new ionic.views.Swiper($element.children()[0], newOptions, $scope);

        _this.__slider = slider;
        $scope.slider = _this.__slider;

        $scope.$on('$destroy', function() {
          slider.destroy();
        });
      });

    }],

    link: function($scope, $element) {
      $scope.showPager = true;
      // Disable ngAnimate for slidebox and its children
      $animate.enabled(false, $element);
    }
  };
}])
.directive('ionSlidePage', [function() {
  return {
    restrict: 'E',
    require: '?^ionSlides',
    transclude: true,
    replace: true,
    template: '

',
    link: function($scope, $element, $attr, ionSlidesCtrl) {
      ionSlidesCtrl.rapidUpdate();
    }
  };
}]);
<|endoftext|>


<commit_before>// Theme colors
export const TITLE_COLOR = '#171A20';
export const SECONDARY_GRAY = '#383F4E';
export const SECONDARY_BLUE = '#0069D2';

export const PRIMARY_THEME_COLOR = '#FF3A00';
export const GRADIENT_ORANGE_COLOR = '#FF7F00';

// Social media colors
export const FACEBOOK_COLOR = '#39479A';
export const FACEBOOK_GRADIENT_COLOR = '#39579A';

// Basic colors
export const WHITE = '#ffffff';
export const TRANSPARENT = 'transparent';
export const BLACK = '#000000';
export const DARK_GRAY = '#453333';
export const GRAY = '#938989';

// Badge colors
export const BADGE_COLOR_ACTIVE = 'seagreen';
export const BADGE_COLOR_UNASSIGNED = 'goldenrod';
export const BADGE_COLOR_DEFAULT = 'grey';
export const BADGE_COLOR_RED = '#D50000';
export const BADGE_TEXT_SHADOW = 'rgba(0, 0, 0, 0.1)';
<commit_msg>add material design color used for icons<commit_after>// Theme colors
export const TITLE_COLOR = '#171A20';
export const SECONDARY_GRAY = '#383F4E';
export const SECONDARY_BLUE = '#0069D2';

export const PRIMARY_THEME_COLOR = '#FF3A00';
export const GRADIENT_ORANGE_COLOR = '#FF7F00';

// Social media colors
export const FACEBOOK_COLOR = '#39479A';
export const FACEBOOK_GRADIENT_COLOR = '#39579A';

// Basic colors
export const WHITE = '#ffffff';
export const TRANSPARENT = 'transparent';
export const BLACK = '#000000';
export const DARK_GRAY = '#453333';
export const GRAY = '#938989';

// Badge colors
export const BADGE_COLOR_ACTIVE = 'seagreen';
export const BADGE_COLOR_UNASSIGNED = 'goldenrod';
export const BADGE_COLOR_DEFAULT = 'grey';
export const BADGE_COLOR_RED = '#D50000';
export const BADGE_TEXT_SHADOW = 'rgba(0, 0, 0, 0.1)';
export const ICON = '#757575';
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief test the task manager
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2012 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Jan Steemann
/// @author Copyright 2012, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

var jsunity = require("jsunity");

var arangodb = require("org/arangodb");
var internal = require("internal");
var db = arangodb.db;
var tasks = require("org/arangodb/tasks");

////////////////////////////////////////////////////////////////////////////////
/// @brief test suite
////////////////////////////////////////////////////////////////////////////////

function TaskSuite () {
  var cn = "UnitTestsTasks";

  var cleanTasks = function () {
    tasks.get().forEach(function(task) {
      if (task.id.match(/^UnitTest/) || task.name.match(/^UnitTest/)) {
        tasks.unregister(task);
      }
    });
  };

  var getTasks = function () {
    var sorter = function (l, r) {
      if (l.id !== r.id) {
        return (l.id < r.id ? -1 : 1);
      }
      return 0;
    };

    return tasks.get().filter(function (task) {
      return task.name.match(/^UnitTest/);
    }).sort(sorter);
  };

  return {

////////////////////////////////////////////////////////////////////////////////
/// @brief set up
////////////////////////////////////////////////////////////////////////////////

    setUp : function () {
      cleanTasks();
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief tear down
////////////////////////////////////////////////////////////////////////////////

    tearDown : function () {
      cleanTasks();

      db._drop(cn);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief create a task without an id
////////////////////////////////////////////////////////////////////////////////

    testCreateTaskNoId : function () {
      try {
        tasks.register({ });
        fail();
      }
      catch (err) {
        assertEqual(internal.errors.ERROR_BAD_PARAMETER.code, err.errorNum);
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief create a task with an invalid period
////////////////////////////////////////////////////////////////////////////////

    testCreateTaskInvalidPeriod1 : function () {
      try {
        tasks.register({ id: "UnitTestsNoPeriod", period: -1, command: "1+1;" });
        fail();
      }
      catch (err) {
        assertEqual(internal.errors.ERROR_BAD_PARAMETER.code, err.errorNum);
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief create a task with an invalid period
////////////////////////////////////////////////////////////////////////////////

    testCreateTaskInvalidPeriod2 : function () {
      try {
        tasks.register({ id: "UnitTestsNoPeriod", period: 0, command: "1+1;" });
        fail();
      }
      catch (err) {
        assertEqual(internal.errors.ERROR_BAD_PARAMETER.code, err.errorNum);
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief create a task without a command
////////////////////////////////////////////////////////////////////////////////

    testCreateTaskNoCommand : function () {
      try {
        tasks.register({ id: "UnitTestsNoPeriod", period: 1 });
        fail();
      }
      catch (err) {
        assertEqual(internal.errors.ERROR_BAD_PARAMETER.code, err.errorNum);
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief create a task with an automatic id
////////////////////////////////////////////////////////////////////////////////

    testCreateTaskAutomaticId : function () {
      var task = tasks.register({ name: "UnitTests1", command: "1+1;", period: 1 });

      assertMatch(/^\d+$/, task.id);
      assertEqual("UnitTests1", task.name);
      assertEqual("periodic", task.type);
      assertEqual(1, task.period);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief create a task with a duplicate id
////////////////////////////////////////////////////////////////////////////////

    testCreateTaskDuplicateId : function () {
      var task = tasks.register({ id: "UnitTests1", name: "UnitTests1", command: "1+1;", period: 1 });

      assertEqual("UnitTests1", task.id);
      assertEqual("UnitTests1", task.name);
      assertEqual("periodic", task.type);

      assertEqual(1, task.period);

      try {
        tasks.register({ id: "UnitTests1", name: "UnitTests1", command: "1+1;", period: 1 });
        fail();
      }
      catch (err) {
        assertEqual(internal.errors.ERROR_TASK_DUPLICATE_ID.code, err.errorNum);
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief remove without an id
////////////////////////////////////////////////////////////////////////////////

    testCreateTaskRemoveWithoutId : function () {
      try {
        tasks.unregister();
        fail();
      }
      catch (err) {
        assertEqual(internal.errors.ERROR_BAD_PARAMETER.code, err.errorNum);
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief create a task and remove it
////////////////////////////////////////////////////////////////////////////////

    testCreateTaskRemoveByTask : function () {
      var task = tasks.register({ id: "UnitTests1", name: "UnitTests1", command: "1+1;", period: 1 });

      assertEqual("UnitTests1", task.id);
      assertEqual("UnitTests1", task.name);
      assertEqual("periodic", task.type);
      assertEqual(1, task.period);

      tasks.unregister(task);

      try {
        // deleting again should fail
        tasks.unregister(task);
        fail();
      }
      catch (err) {
        assertEqual(internal.errors.ERROR_TASK_NOT_FOUND.code, err.errorNum);
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief create a task and remove it
////////////////////////////////////////////////////////////////////////////////

    testCreateTaskRemoveById : function () {
      var task = tasks.register({ id: "UnitTests1", name: "UnitTests1", command: "1+1;", period: 1 });

      assertEqual("UnitTests1", task.id);
      assertEqual("UnitTests1", task.name);
      assertEqual("periodic", task.type);
      assertEqual(1, task.period);

      tasks.unregister(task.id);

      try {
        // deleting again should fail
        tasks.unregister(task.id);
        fail();
      }
      catch (err) {
        assertEqual(internal.errors.ERROR_TASK_NOT_FOUND.code, err.errorNum);
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief get a single task
////////////////////////////////////////////////////////////////////////////////

    testGetTask : function () {
      var task = tasks.register({
        id: "UnitTests1",
        name: "UnitTests1",
        command: "1+1;",
        period: 1
      });

      var t = tasks.get(task);

      assertEqual(task.id, t.id);
      assertEqual(task.name, t.name);
      assertEqual(task.type, t.type);
      assertEqual(task.period, t.period);
      assertEqual(task.database, t.database);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief get a single task
////////////////////////////////////////////////////////////////////////////////

    testGetTaskById : function () {
      var task = tasks.register({
        id: "UnitTests1",
        name: "UnitTests1",
        command: "1+1;",
        period: 1
      });

      var t = tasks.get(task.id);

      assertEqual(task.id, t.id);
      assertEqual(task.name, t.name);
      assertEqual(task.type, t.type);
      assertEqual(task.period, t.period);
      assertEqual(task.database, t.database);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief get list of tasks
////////////////////////////////////////////////////////////////////////////////

    testGetTasks : function () {
      var task1 = tasks.register({
        id: "UnitTests1",
        name: "UnitTests1",
        command: "1+1;",
        period: 1
      });

      var task2 = tasks.register({
        id: "UnitTests2",
        name: "UnitTests2",
        command: "2+2;",
        period: 2
      });

      var task3 = tasks.register({
        id: "UnitTests3",
        name: "UnitTests3",
        command: "3+3;",
        offset: 30
      });

      var t = getTasks();

      assertEqual(3, t.length);
      assertEqual(task1.id, t[0].id);
      assertEqual(task1.name, t[0].name);
      assertEqual(task1.type, t[0].type);
      assertEqual("periodic", t[0].type);
      assertEqual(task1.period, t[0].period);
      assertEqual(1, t[0].period);
      assertEqual(task1.database, t[0].database);
      assertEqual("_system", t[0].database);

      assertEqual(task2.id, t[1].id);
      assertEqual(task2.name, t[1].name);
      assertEqual(task2.type, t[1].type);
      assertEqual("periodic", t[1].type);
      assertEqual(task2.period, t[1].period);
      assertEqual(2, t[1].period);
      assertEqual(task2.database, t[1].database);
      assertEqual("_system", t[1].database);

      assertEqual(task3.id, t[2].id);
      assertEqual(task3.name, t[2].name);
      assertEqual(task3.type, t[2].type);
      assertEqual("timed", t[2].type);
      assertEqual(30, t[2].offset);
      assertEqual(task3.database, t[2].database);
      assertEqual("_system", t[2].database);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief get list of tasks pre and post task deletion
////////////////////////////////////////////////////////////////////////////////

    testGetTasksPrePost : function () {
      var task1 = tasks.register({
        id: "UnitTests1",
        name: "UnitTests1",
        command: "1+1;",
        period: 1
      });

      var t = getTasks();

      assertEqual(1, t.length);
      assertEqual(task1.id, t[0].id);
      assertEqual(task1.name, t[0].name);
      assertEqual(task1.type, t[0].type);
      assertEqual(task1.period, t[0].period);
      assertEqual(task1.database, t[0].database);

      var task2 = tasks.register({
        id: "UnitTests2",
        name: "UnitTests2",
        command: "2+2;",
        period: 2
      });

      t = getTasks();

      assertEqual(2, t.length);
      assertEqual(task1.id, t[0].id);
      assertEqual(task1.name, t[0].name);
      assertEqual(task1.type, t[0].type);
      assertEqual(task1.period, t[0].period);
      assertEqual(task1.database, t[0].database);
      assertEqual(task2.id, t[1].id);
      assertEqual(task2.name, t[1].name);
      assertEqual(task2.type, t[1].type);
      assertEqual(task2.period, t[1].period);
      assertEqual(task2.database, t[1].database);

      tasks.unregister(task1);

      t = getTasks();

      assertEqual(1, t.length);
      assertEqual(task2.id, t[0].id);
      assertEqual(task2.name, t[0].name);
      assertEqual(task2.type, t[0].type);
      assertEqual(task2.period, t[0].period);
      assertEqual(task2.database, t[0].database);

      tasks.unregister(task2);

      t = getTasks();

      assertEqual(0, t.length);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief create a timer task and run it
////////////////////////////////////////////////////////////////////////////////

    testTimerTask : function () {
      db._drop(cn);
      db._create(cn);

      assertEqual(0, db[cn].count());

      var command = "require('internal').db." + cn + ".save({ value: params });";

      var task = tasks.register({
        id: "UnitTests1",
        name: "UnitTests1",
        command: command,
        offset: 2,
        params: 23
      });

      assertEqual("UnitTests1", task.id);
      assertEqual("UnitTests1", task.name);
      assertEqual("timed", task.type);
      assertEqual(2, task.offset);
      assertEqual("_system", task.database);

      internal.wait(7);

      assertEqual(1, db[cn].count());
      assertEqual(1, db[cn].byExample({ value: 23 }).count());

      // task should have gone by now
      t = getTasks();
      assertEqual(0, t.length);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief create a timer task and kill it before execution
////////////////////////////////////////////////////////////////////////////////

    testKillTimerTask : function () {
      db._drop(cn);
      db._create(cn);

      assertEqual(0, db[cn].count());

      var command = "require('internal').db." + cn + ".save({ value: params });";

      var task = tasks.register({
        id: "UnitTests1",
        name: "UnitTests1",
        command: command,
        offset: 10,
        params: 23
      });

      assertEqual("UnitTests1", task.id);
      assertEqual("UnitTests1", task.name);
      assertEqual("timed", task.type);
      assertEqual(10, task.offset);
      assertEqual("_system", task.database);

      tasks.unregister(task);

      internal.wait(5);

      assertEqual(0, db[cn].count());
      assertEqual(0, db[cn].byExample({ value: 23 }).count());

      t = getTasks();
      assertEqual(0, t.length);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief create a task and run it
////////////////////////////////////////////////////////////////////////////////

    testCreateStringCommand : function () {
      db._drop(cn);
      db._create(cn);

      assertEqual(0, db[cn].count());

      var command = "require('internal').db." + cn + ".save({ value: params });";

      var task = tasks.register({
        id: "UnitTests1",
        name: "UnitTests1",
        command: command,
        period: 1,
        offset: 0,
        params: 23
      });

      assertEqual("UnitTests1", task.id);
      assertEqual("UnitTests1", task.name);
      assertEqual("periodic", task.type);
      assertEqual(1, task.period);
      assertEqual("_system", task.database);

      internal.wait(7);

      tasks.unregister(task);

      assertTrue(db[cn].count() > 0);
      assertTrue(db[cn].byExample({ value: 23 }).count() > 0);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief create a task and run it
////////////////////////////////////////////////////////////////////////////////

    testCreateFunctionCommand : function () {
      db._drop(cn);
      db._create(cn);

      assertEqual(0, db[cn].count());

      var command = function (params) {
        require('internal').db[params.cn].save({ value: params.val });
      };

      var task = tasks.register({
        id: "UnitTests1",
        name: "UnitTests1",
        command: command,
        period: 1,
        offset: 0,
        params: { cn: cn, val: 42 }
      });

      assertEqual("UnitTests1", task.id);
      assertEqual("UnitTests1", task.name);
      assertEqual("periodic", task.type);
      assertEqual(1, task.period);
      assertEqual("_system", task.database);

      internal.wait(7);

      tasks.unregister(task);

      assertTrue(db[cn].count() > 0);
      assertTrue(db[cn].byExample({ value: 23 }).count() === 0);
      assertTrue(db[cn].byExample({ value: 42 }).count() > 0);
    }

  };
}

// -----------------------------------------------------------------------------
// --SECTION--                                                              main
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief executes the test suite
////////////////////////////////////////////////////////////////////////////////

jsunity.run(TaskSuite);

return jsunity.done();

// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// @addtogroup\\|// --SECTION--\\|/// @page\\|/// @}\\)"
// End:
<commit_msg>adjusted test<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief test the task manager
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2012 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Jan Steemann
/// @author Copyright 2012, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

var jsunity = require("jsunity");

var arangodb = require("org/arangodb");
var internal = require("internal");
var db = arangodb.db;
var tasks = require("org/arangodb/tasks");

////////////////////////////////////////////////////////////////////////////////
/// @brief test suite
////////////////////////////////////////////////////////////////////////////////

function TaskSuite () {
  var cn = "UnitTestsTasks";

  var cleanTasks = function () {
    tasks.get().forEach(function(task) {
      if (task.id.match(/^UnitTest/) || task.name.match(/^UnitTest/)) {
        tasks.unregister(task);
      }
    });
  };

  var getTasks = function () {
    var sorter = function (l, r) {
      if (l.id !== r.id) {
        return (l.id < r.id ? -1 : 1);
      }
      return 0;
    };

    return tasks.get().filter(function (task) {
      return task.name.match(/^UnitTest/);
    }).sort(sorter);
  };

  return {

////////////////////////////////////////////////////////////////////////////////
/// @brief set up
////////////////////////////////////////////////////////////////////////////////

    setUp : function () {
      cleanTasks();
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief tear down
////////////////////////////////////////////////////////////////////////////////

    tearDown : function () {
      cleanTasks();

      db._drop(cn);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief create a task without an id
////////////////////////////////////////////////////////////////////////////////

    testCreateTaskNoId : function () {
      try {
        tasks.register({ });
        fail();
      }
      catch (err) {
        assertEqual(internal.errors.ERROR_BAD_PARAMETER.code, err.errorNum);
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief create a task with an invalid period
////////////////////////////////////////////////////////////////////////////////

    testCreateTaskInvalidPeriod1 : function () {
      try {
        tasks.register({ id: "UnitTestsNoPeriod", period: -1, command: "1+1;" });
        fail();
      }
      catch (err) {
        assertEqual(internal.errors.ERROR_BAD_PARAMETER.code, err.errorNum);
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief create a task with an invalid period
////////////////////////////////////////////////////////////////////////////////

    testCreateTaskInvalidPeriod2 : function () {
      try {
        tasks.register({ id: "UnitTestsNoPeriod", period: 0, command: "1+1;" });
        fail();
      }
      catch (err) {
        assertEqual(internal.errors.ERROR_BAD_PARAMETER.code, err.errorNum);
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief create a task without a command
////////////////////////////////////////////////////////////////////////////////

    testCreateTaskNoCommand : function () {
      try {
        tasks.register({ id: "UnitTestsNoPeriod", period: 1 });
        fail();
      }
      catch (err) {
        assertEqual(internal.errors.ERROR_BAD_PARAMETER.code, err.errorNum);
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief create a task with an automatic id
////////////////////////////////////////////////////////////////////////////////

    testCreateTaskAutomaticId : function () {
      var task = tasks.register({ name: "UnitTests1", command: "1+1;", period: 1 });

      assertMatch(/^\d+$/, task.id);
      assertEqual("UnitTests1", task.name);
      assertEqual("periodic", task.type);
      assertEqual(1, task.period);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief create a task with a duplicate id
////////////////////////////////////////////////////////////////////////////////

    testCreateTaskDuplicateId : function () {
      var task = tasks.register({ id: "UnitTests1", name: "UnitTests1", command: "1+1;", period: 1 });

      assertEqual("UnitTests1", task.id);
      assertEqual("UnitTests1", task.name);
      assertEqual("periodic", task.type);

      assertEqual(1, task.period);

      try {
        tasks.register({ id: "UnitTests1", name: "UnitTests1", command: "1+1;", period: 1 });
        fail();
      }
      catch (err) {
        assertEqual(internal.errors.ERROR_TASK_DUPLICATE_ID.code, err.errorNum);
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief remove without an id
////////////////////////////////////////////////////////////////////////////////

    testCreateTaskRemoveWithoutId : function () {
      try {
        tasks.unregister();
        fail();
      }
      catch (err) {
        assertEqual(internal.errors.ERROR_BAD_PARAMETER.code, err.errorNum);
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief create a task and remove it
////////////////////////////////////////////////////////////////////////////////

    testCreateTaskRemoveByTask : function () {
      var task = tasks.register({ id: "UnitTests1", name: "UnitTests1", command: "1+1;", period: 1 });

      assertEqual("UnitTests1", task.id);
      assertEqual("UnitTests1", task.name);
      assertEqual("periodic", task.type);
      assertEqual(1, task.period);

      tasks.unregister(task);

      try {
        // deleting again should fail
        tasks.unregister(task);
        fail();
      }
      catch (err) {
        assertEqual(internal.errors.ERROR_TASK_NOT_FOUND.code, err.errorNum);
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief create a task and remove it
////////////////////////////////////////////////////////////////////////////////

    testCreateTaskRemoveById : function () {
      var task = tasks.register({ id: "UnitTests1", name: "UnitTests1", command: "1+1;", period: 1 });

      assertEqual("UnitTests1", task.id);
      assertEqual("UnitTests1", task.name);
      assertEqual("periodic", task.type);
      assertEqual(1, task.period);

      tasks.unregister(task.id);

      try {
        // deleting again should fail
        tasks.unregister(task.id);
        fail();
      }
      catch (err) {
        assertEqual(internal.errors.ERROR_TASK_NOT_FOUND.code, err.errorNum);
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief get a single task
////////////////////////////////////////////////////////////////////////////////

    testGetTask : function () {
      var task = tasks.register({
        id: "UnitTests1",
        name: "UnitTests1",
        command: "1+1;",
        period: 1
      });

      var t = tasks.get(task);

      assertEqual(task.id, t.id);
      assertEqual(task.name, t.name);
      assertEqual(task.type, t.type);
      assertEqual(task.period, t.period);
      assertEqual(task.database, t.database);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief get a single task
////////////////////////////////////////////////////////////////////////////////

    testGetTaskById : function () {
      var task = tasks.register({
        id: "UnitTests1",
        name: "UnitTests1",
        command: "1+1;",
        period: 1
      });

      var t = tasks.get(task.id);

      assertEqual(task.id, t.id);
      assertEqual(task.name, t.name);
      assertEqual(task.type, t.type);
      assertEqual(task.period, t.period);
      assertEqual(task.database, t.database);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief get list of tasks
////////////////////////////////////////////////////////////////////////////////

    testGetTasks : function () {
      var task1 = tasks.register({
        id: "UnitTests1",
        name: "UnitTests1",
        command: "1+1;",
        period: 1
      });

      var task2 = tasks.register({
        id: "UnitTests2",
        name: "UnitTests2",
        command: "2+2;",
        period: 2
      });

      var task3 = tasks.register({
        id: "UnitTests3",
        name: "UnitTests3",
        command: "3+3;",
        offset: 30
      });

      var t = getTasks();

      assertEqual(3, t.length);
      assertEqual(task1.id, t[0].id);
      assertEqual(task1.name, t[0].name);
      assertEqual(task1.type, t[0].type);
      assertEqual("periodic", t[0].type);
      assertEqual(task1.period, t[0].period);
      assertEqual(1, t[0].period);
      assertEqual(task1.database, t[0].database);
      assertEqual("_system", t[0].database);

      assertEqual(task2.id, t[1].id);
      assertEqual(task2.name, t[1].name);
      assertEqual(task2.type, t[1].type);
      assertEqual("periodic", t[1].type);
      assertEqual(task2.period, t[1].period);
      assertEqual(2, t[1].period);
      assertEqual(task2.database, t[1].database);
      assertEqual("_system", t[1].database);

      assertEqual(task3.id, t[2].id);
      assertEqual(task3.name, t[2].name);
      assertEqual(task3.type, t[2].type);
      assertEqual("timed", t[2].type);
      assertEqual(30, t[2].offset);
      assertEqual(task3.database, t[2].database);
      assertEqual("_system", t[2].database);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief get list of tasks pre and post task deletion
////////////////////////////////////////////////////////////////////////////////

    testGetTasksPrePost : function () {
      var task1 = tasks.register({
        id: "UnitTests1",
        name: "UnitTests1",
        command: "1+1;",
        period: 1
      });

      var t = getTasks();

      assertEqual(1, t.length);
      assertEqual(task1.id, t[0].id);
      assertEqual(task1.name, t[0].name);
      assertEqual(task1.type, t[0].type);
      assertEqual(task1.period, t[0].period);
      assertEqual(task1.database, t[0].database);

      var task2 = tasks.register({
        id: "UnitTests2",
        name: "UnitTests2",
        command: "2+2;",
        period: 2
      });

      t = getTasks();

      assertEqual(2, t.length);
      assertEqual(task1.id, t[0].id);
      assertEqual(task1.name, t[0].name);
      assertEqual(task1.type, t[0].type);
      assertEqual(task1.period, t[0].period);
      assertEqual(task1.database, t[0].database);
      assertEqual(task2.id, t[1].id);
      assertEqual(task2.name, t[1].name);
      assertEqual(task2.type, t[1].type);
      assertEqual(task2.period, t[1].period);
      assertEqual(task2.database, t[1].database);

      tasks.unregister(task1);

      t = getTasks();

      assertEqual(1, t.length);
      assertEqual(task2.id, t[0].id);
      assertEqual(task2.name, t[0].name);
      assertEqual(task2.type, t[0].type);
      assertEqual(task2.period, t[0].period);
      assertEqual(task2.database, t[0].database);

      tasks.unregister(task2);

      t = getTasks();

      assertEqual(0, t.length);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief create a timer task and run it
////////////////////////////////////////////////////////////////////////////////

    testTimerTask : function () {
      db._drop(cn);
      db._create(cn);

      assertEqual(0, db[cn].count());

      var command = "require('internal').db." + cn + ".save({ value: params });";

      var task = tasks.register({
        id: "UnitTests1",
        name: "UnitTests1",
        command: command,
        offset: 5,
        params: 23
      });

      assertEqual("UnitTests1", task.id);
      assertEqual("UnitTests1", task.name);
      assertEqual("timed", task.type);
      assertEqual(5, task.offset);
      assertEqual("_system", task.database);

      t = getTasks();
      assertEqual(1, t.length);

      internal.wait(15);

      assertEqual(1, db[cn].count());
      assertEqual(1, db[cn].byExample({ value: 23 }).count());

      // task should have gone by now
      t = getTasks();
      assertEqual(0, t.length);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief create a timer task and kill it before execution
////////////////////////////////////////////////////////////////////////////////

    testKillTimerTask : function () {
      db._drop(cn);
      db._create(cn);

      assertEqual(0, db[cn].count());

      var command = "require('internal').db." + cn + ".save({ value: params });";

      var task = tasks.register({
        id: "UnitTests1",
        name: "UnitTests1",
        command: command,
        offset: 10,
        params: 23
      });

      assertEqual("UnitTests1", task.id);
      assertEqual("UnitTests1", task.name);
      assertEqual("timed", task.type);
      assertEqual(10, task.offset);
      assertEqual("_system", task.database);

      tasks.unregister(task);

      internal.wait(5);

      assertEqual(0, db[cn].count());
      assertEqual(0, db[cn].byExample({ value: 23 }).count());

      t = getTasks();
      assertEqual(0, t.length);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief create a task and run it
////////////////////////////////////////////////////////////////////////////////

    testCreateStringCommand : function () {
      db._drop(cn);
      db._create(cn);

      assertEqual(0, db[cn].count());

      var command = "require('internal').db." + cn + ".save({ value: params });";

      var task = tasks.register({
        id: "UnitTests1",
        name: "UnitTests1",
        command: command,
        period: 1,
        offset: 0,
        params: 23
      });

      assertEqual("UnitTests1", task.id);
      assertEqual("UnitTests1", task.name);
      assertEqual("periodic", task.type);
      assertEqual(1, task.period);
      assertEqual("_system", task.database);

      internal.wait(7);

      tasks.unregister(task);

      assertTrue(db[cn].count() > 0);
      assertTrue(db[cn].byExample({ value: 23 }).count() > 0);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief create a task and run it
////////////////////////////////////////////////////////////////////////////////

    testCreateFunctionCommand : function () {
      db._drop(cn);
      db._create(cn);

      assertEqual(0, db[cn].count());

      var command = function (params) {
        require('internal').db[params.cn].save({ value: params.val });
      };

      var task = tasks.register({
        id: "UnitTests1",
        name: "UnitTests1",
        command: command,
        period: 1,
        offset: 0,
        params: { cn: cn, val: 42 }
      });

      assertEqual("UnitTests1", task.id);
      assertEqual("UnitTests1", task.name);
      assertEqual("periodic", task.type);
      assertEqual(1, task.period);
      assertEqual("_system", task.database);

      internal.wait(7);

      tasks.unregister(task);

      assertTrue(db[cn].count() > 0);
      assertTrue(db[cn].byExample({ value: 23 }).count() === 0);
      assertTrue(db[cn].byExample({ value: 42 }).count() > 0);
    }

  };
}

// -----------------------------------------------------------------------------
// --SECTION--                                                              main
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief executes the test suite
////////////////////////////////////////////////////////////////////////////////

jsunity.run(TaskSuite);

return jsunity.done();

// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// @addtogroup\\|// --SECTION--\\|/// @page\\|/// @}\\)"
// End:
<|endoftext|>