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

'use strict';

if (process.argv[2]) {
  var no_build = process.argv[2].toLowerCase() == '--nobuild';
  if (no_build == false) {
    console.log(
      'Incorrect arg. Please use --nobuild if you would like to download without api key.'
    );
    process.exit(1);
  }
} else {
  var no_build = false;
  console.log(
    '\n' +
      'Please note: If you do not have the crowdin API key and would like to download the ' +
      'translations without building anyways, please make sure your English files are the same ' +
      'version as crowdin, and then run this script with --nobuild\n\n' +
      'eg. "node crowdin_download.js --nobuild"\n\n'
  );
}

var fs = require('fs');
var path = require('path');
var https = require('https');
var AdmZip = require('adm-zip');

var crowdin_identifier = 'copay';

var local_file_name2 = path.join(__dirname, 'docs/appstore_en.txt');
var local_file_name3 = path.join(__dirname, 'docs/updateinfo_en.txt');

try {
  fs.statSync(local_file_name2);
  fs.statSync(local_file_name3);
} catch (e) {
  console.log(
    '\n### ABORTING ### One of the following files does not exist:\n' +
      local_file_name2 +
      '\n' +
      local_file_name3
  );
  process.exit(1);
}

try {
  // obtain the crowdin api key
  var crowdin_api_key = fs.readFileSync(
    path.join(__dirname, 'crowdin_api_key.txt'),
    'utf8'
  );
} catch (e) {
  console.log(
    '### ERROR ### You do not have the crowdin api key in ./crowdin_api_key.txt'
  );
  process.exit(1);
}

if (no_build == false) {
  // Reminder: Any changes to the script below must also be made to the else clause and vice versa.

  // This call will tell the server to generate a new zip file for you based on most recent translations.
  https
    .get(
      'https://api.crowdin.com/api/project/' +
        crowdin_identifier +
        '/export?key=' +
        crowdin_api_key,
      function(res) {
        console.log('Export Got response: ' + res.statusCode);

        res.on('data', function(chunk) {
          var resxml = chunk.toString('utf8');
          console.log(resxml);

          if (resxml.indexOf('status="skipped"') >= 0) {
            console.log(
              'Translation build was skipped due to either:\n' +
                '1. No changes since last translation build, or\n' +
                '2. API limit of once per 30 minutes has not been waited.\n\n' +
                'Since we can not guarantee that translations have been built properly, this script will end here.\n' +
                'Log in to Copay\'s Crowdin Settings and click the "Build Project" button to assure it is built recently, and then run this ' +
                'script again with the --nobuild arg to download translations without checking if built.'
            );
            process.exit(1);
          }

          // Download most recent translations for all languages.
          https.get(
            'https://crowdin.com/download/project/' +
              crowdin_identifier +
              '.zip',
            function(res) {
              var data = [],
                dataLen = 0;

              res
                .on('data', function(chunk) {
                  data.push(chunk);
                  dataLen += chunk.length;
                })
                .on('end', function() {
                  var buf = new Buffer(dataLen);
                  for (var i = 0, len = data.length, pos = 0; i < len; i++) {
                    data[i].copy(buf, pos);
                    pos += data[i].length;
                  }
                  var zip = new AdmZip(buf);
                  zip.extractAllTo('./', true);
                  console.log('Done extracting ZIP file.');

                  var files = fs.readdirSync('./docs');

                  for (var i in files) {
                    debugger;
                    if (
                      files[i].slice(0, 9) == 'appstore_' &&
                      files[i].slice(-4) == '.txt' &&
                      files[i] != 'appstore_en.txt'
                    ) {
                      var english_file = fs.readFileSync(
                        local_file_name2,
                        'utf8'
                      );
                      var compare_file = fs.readFileSync(
                        path.join(__dirname, 'docs/' + files[i]),
                        'utf8'
                      );
                      english_file = english_file.replace(/\r\n/g, '\n');
                      compare_file = compare_file.replace(/\r\n/g, '\n');
                      if (compare_file == english_file) {
                        fs.unlinkSync(path.join(__dirname, 'docs/' + files[i]));
                      }
                    }
                    if (
                      files[i].slice(0, 11) == 'updateinfo_' &&
                      files[i].slice(-4) == '.txt' &&
                      files[i] != 'updateinfo_en.txt'
                    ) {
                      var english_file = fs.readFileSync(
                        local_file_name3,
                        'utf8'
                      );
                      var compare_file = fs.readFileSync(
                        path.join(__dirname, 'docs/' + files[i]),
                        'utf8'
                      );
                      english_file = english_file.replace(/\r\n/g, '\n');
                      compare_file = compare_file.replace(/\r\n/g, '\n');
                      if (compare_file == english_file) {
                        fs.unlinkSync(path.join(__dirname, 'docs/' + files[i]));
                      }
                    }
                  }

                  console.log(
                    'Cleaned out completely untranslated appstore docs.'
                  );

                  var files = fs.readdirSync('./po');

                  for (var i in files) {
                    if (files[i] != 'template.pot') {
                      var po_file = fs.readFileSync(
                        path.join(__dirname, 'po/' + files[i]),
                        'utf8'
                      );
                      var po_array = po_file.split('\n');
                      for (var j in po_array) {
                        if (po_array[j].slice(0, 5) == 'msgid') {
                          var source_text = po_array[j].slice(5);
                        } else if (po_array[j].slice(0, 6) == 'msgstr') {
                          var translate_text = po_array[j].slice(6);
                          // if a line is not == English, it means there is translation. Keep this file.
                          if (source_text != translate_text) {
                            // erase email addresses of last translator for privacy
                            po_file = po_file.replace(/ <.+@.+\..+>/, '');
                            fs.writeFileSync(
                              path.join(__dirname, 'po/' + files[i]),
                              po_file
                            );

                            // split the file into 3 parts, before locale, locale, and after locale.
                            var lang_pos = po_file.search('"Language: ') + 11;
                            var po_start = po_file.slice(0, lang_pos);
                            var po_locale = po_file.slice(
                              lang_pos,
                              lang_pos + 5
                            );
                            var po_end = po_file.slice(lang_pos + 5);

                            // check for underscore, if it's there, only take the first 2 letters and reconstruct the po file.
                            if (po_locale.search('_') > 0) {
                              fs.writeFileSync(
                                path.join(__dirname, 'po/' + files[i]),
                                po_start + po_locale.slice(0, 2) + po_end
                              );
                              po_start = '';
                              po_locale = '';
                              po_end = '';
                            }
                            break;
                          }
                        }
                        if (j == po_array.length - 1) {
                          // All strings are exactly identical to English. Delete po file.
                          fs.unlinkSync(path.join(__dirname, 'po/' + files[i]));
                        }
                      }
                    }
                  }

                  console.log('Cleaned out completely untranslated po files.');
                });
            }
          );
        });
      }
    )
    .on('error', function(e) {
      console.log('Export Got error: ' + e.message);
    });
} else {
  // Reminder: Any changes to the script below must also be made to the above and vice versa.

  // Download most recent translations for all languages.
  https.get(
    'https://api.crowdin.com/api/project/' +
      crowdin_identifier +
      '/download/all.zip?key=' +
      crowdin_api_key,
    function(res) {
      var data = [],
        dataLen = 0;

      res
        .on('data', function(chunk) {
          data.push(chunk);
          dataLen += chunk.length;
        })
        .on('end', function() {
          var buf = new Buffer(dataLen);
          for (var i = 0, len = data.length, pos = 0; i < len; i++) {
            data[i].copy(buf, pos);
            pos += data[i].length;
          }
          var zip = new AdmZip(buf);
          zip.extractAllTo('./', true);
          console.log('Done extracting ZIP file.');

          var files = fs.readdirSync('./docs');

          for (var i in files) {
            if (
              files[i].slice(0, 9) == 'appstore_' &&
              files[i].slice(-4) == '.txt' &&
              files[i] != 'appstore_en.txt'
            ) {
              var english_file = fs.readFileSync(local_file_name2, 'utf8');
              var compare_file = fs.readFileSync(
                path.join(__dirname, 'docs/' + files[i]),
                'utf8'
              );
              english_file = english_file.replace(/\r\n/g, '\n');
              compare_file = compare_file.replace(/\r\n/g, '\n');
              if (compare_file == english_file) {
                fs.unlinkSync(path.join(__dirname, 'docs/' + files[i]));
              }
            }
            if (
              files[i].slice(0, 11) == 'updateinfo_' &&
              files[i].slice(-4) == '.txt' &&
              files[i] != 'updateinfo_en.txt'
            ) {
              var english_file = fs.readFileSync(local_file_name3, 'utf8');
              var compare_file = fs.readFileSync(
                path.join(__dirname, 'docs/' + files[i]),
                'utf8'
              );
              english_file = english_file.replace(/\r\n/g, '\n');
              compare_file = compare_file.replace(/\r\n/g, '\n');
              if (compare_file == english_file) {
                fs.unlinkSync(path.join(__dirname, 'docs/' + files[i]));
              }
            }
          }

          console.log('Cleaned out completely untranslated appstore docs.');

          var files = fs.readdirSync('./po');

          for (var i in files) {
            if (files[i] != 'template.pot') {
              var po_file = fs.readFileSync(
                path.join(__dirname, 'po/' + files[i]),
                'utf8'
              );
              var po_array = po_file.split('\n');
              for (var j in po_array) {
                if (po_array[j].slice(0, 5) == 'msgid') {
                  var source_text = po_array[j].slice(5);
                } else if (po_array[j].slice(0, 6) == 'msgstr') {
                  var translate_text = po_array[j].slice(6);
                  // if a line is not == English, it means there is translation. Keep this file.
                  if (source_text != translate_text) {
                    // erase email addresses of last translator for privacy
                    po_file = po_file.replace(/ <.+@.+\..+>/, '');
                    fs.writeFileSync(
                      path.join(__dirname, 'po/' + files[i]),
                      po_file
                    );

                    // split the file into 3 parts, before locale, locale, and after locale.
                    var lang_pos = po_file.search('"Language: ') + 11;
                    var po_start = po_file.slice(0, lang_pos);
                    var po_locale = po_file.slice(lang_pos, lang_pos + 5);
                    var po_end = po_file.slice(lang_pos + 5);

                    // check for underscore, if it's there, only take the first 2 letters and reconstruct the po file.
                    if (po_locale.search('_') > 0) {
                      fs.writeFileSync(
                        path.join(__dirname, 'po/' + files[i]),
                        po_start + po_locale.slice(0, 2) + po_end
                      );
                      po_start = '';
                      po_locale = '';
                      po_end = '';
                    }
                    break;
                  }
                }
                if (j == po_array.length - 1) {
                  // All strings are exactly identical to English. Delete po file.
                  fs.unlinkSync(path.join(__dirname, 'po/' + files[i]));
                }
              }
            }
          }

          console.log('Cleaned out completely untranslated po files.');
        });
    }
  );
}
<commit_msg>Fix: crowndin download script<commit_after>#!/usr/bin/env node

'use strict';

console.log(
  '\nPlease remember to build translations ' +
  'before to download and commit new changes\n'
);

var fs = require('fs');
var path = require('path');
var https = require('https');
var AdmZip = require('adm-zip');

var crowdin_identifier = 'copay';

var local_file_name2 = path.join(__dirname, 'docs/appstore_en.txt');
var local_file_name3 = path.join(__dirname, 'docs/updateinfo_en.txt');

try {
  fs.statSync(local_file_name2);
  fs.statSync(local_file_name3);
} catch (e) {
  console.log(
    '\n### ABORTING ### One of the following files does not exist:\n' +
      local_file_name2 +
      '\n' +
      local_file_name3
  );
  process.exit(1);
}

try {
  // obtain the crowdin api key
  var crowdin_api_key = fs.readFileSync(
    path.join(__dirname, 'crowdin_api_key.txt'),
    'utf8'
  );
} catch (e) {
  console.log(
    '### ERROR ### You do not have the crowdin api key in ./crowdin_api_key.txt'
  );
  process.exit(1);
}

// Download most recent translations for all languages.
https.get(
  'https://api.crowdin.com/api/project/' +
    crowdin_identifier +
    '/download/all.zip?key=' +
    crowdin_api_key,
  function(res) {
    var data = [],
      dataLen = 0;

    res
      .on('data', function(chunk) {
        data.push(chunk);
        dataLen += chunk.length;
      })
      .on('end', function() {
        var buf = new Buffer.alloc(dataLen);
        for (var i = 0, len = data.length, pos = 0; i < len; i++) {
          data[i].copy(buf, pos);
          pos += data[i].length;
        }
        var zip = new AdmZip(buf);
        zip.extractAllTo('/tmp/copay', true);
        console.log('Done extracting ZIP file.');

        var files = fs.readdirSync('/tmp/copay/docs');

        for (var i in files) {
          if (
            files[i].slice(0, 9) == 'appstore_' &&
            files[i].slice(-4) == '.txt' &&
            files[i] != 'appstore_en.txt'
          ) {
            var english_file = fs.readFileSync(local_file_name2, 'utf8');
            var compare_file = fs.readFileSync(
              path.join(__dirname, 'docs/' + files[i]),
              'utf8'
            );
            english_file = english_file.replace(/\r\n/g, '\n');
            compare_file = compare_file.replace(/\r\n/g, '\n');
            if (compare_file == english_file) {
              fs.unlinkSync(path.join(__dirname, 'docs/' + files[i]));
            }
          }
          if (
            files[i].slice(0, 11) == 'updateinfo_' &&
            files[i].slice(-4) == '.txt' &&
            files[i] != 'updateinfo_en.txt'
          ) {
            var english_file = fs.readFileSync(local_file_name3, 'utf8');
            var compare_file = fs.readFileSync(
              path.join(__dirname, 'docs/' + files[i]),
              'utf8'
            );
            english_file = english_file.replace(/\r\n/g, '\n');
            compare_file = compare_file.replace(/\r\n/g, '\n');
            if (compare_file == english_file) {
              fs.unlinkSync(path.join(__dirname, 'docs/' + files[i]));
            }
          }
        }

        console.log('Cleaned out completely untranslated appstore docs.');

        var files = fs.readdirSync('/tmp/copay/po');

        for (var i in files) {
          var po_file = fs.readFileSync(
            '/tmp/copay/po/' + files[i],
            'utf8'
          );
          var po_array = po_file.split('\n');
          for (var j in po_array) {
            if (po_array[j].slice(0, 5) == 'msgid') {
              var source_text = po_array[j].slice(5);
            } else if (po_array[j].slice(0, 6) == 'msgstr') {
              var translate_text = po_array[j].slice(6);
              // if a line is not == English, it means there is translation. Keep this file.
              if (source_text != translate_text) {
                // erase email addresses of last translator for privacy
                po_file = po_file.replace(/ <.+@.+\..+>/, '');
                fs.writeFileSync(
                  path.join(__dirname, '../src/assets/i18n/' + files[i]),
                  po_file
                );

                // split the file into 3 parts, before locale, locale, and after locale.
                var lang_pos = po_file.search('"Language: ') + 11;
                var po_start = po_file.slice(0, lang_pos);
                var po_locale = po_file.slice(lang_pos, lang_pos + 5);
                var po_end = po_file.slice(lang_pos + 5);

                // check for underscore, if it's there, only take the first 2 letters and reconstruct the po file.
                if (po_locale.search('_') > 0) {
                  fs.writeFileSync(
                    path.join(__dirname, '../src/assets/i18n/' + files[i]),
                    po_start + po_locale.slice(0, 2) + po_end
                  );
                  po_start = '';
                  po_locale = '';
                  po_end = '';
                }
                break;
              }
            }
            if (j == po_array.length - 1) {
              // All strings are exactly identical to English. Delete po file.
              fs.unlinkSync(path.join(__dirname, '../src/assets/i18n/' + files[i]));
            }
          }
        }

        console.log('Cleaned out completely untranslated po files.');
      });
  }
);
<|endoftext|>


<commit_before>/*jshint node: true, -W106 */
'use strict';

/*
* Name : functionHelper.js
* Module : FunctionHelper
* Location : /lib/helpers
*
* History :
*
* Version   Date         Programmer         Description
* =========================================================
* 0.0.1     2015-05-14   Matteo Furlan    Initial code
* =========================================================
*/
String.prototype.replaceAll = function(target, replacement) {
	return this.split(target).join(replacement);
};
module.exports.isHEX= function(hex){
	return (/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(hex));
};
module.exports.getCorrectType= function(str){
	var arr=str.split('\'');
	if(arr.length===3){ // is a string 'hello'
		return arr[1];
	}else{
		str=str.replaceAll('\'', '');
		if(isNaN(str)){ // is a malformed string 'hello
			return str;
		}else{ // is a number -2.948
			return parseFloat(str);
		}
	}
};
module.exports.parseCondition= function(cond){
	//   <   <=   >   >=   !=   ==
	// splitting string
	var array=cond.split('==');
	var operator='==';
	if(array.length!==2){
		array=cond.split('!=');
		operator='!=';
		if(array.length!==2){
			array=cond.split('>=');
			operator='>=';
			if(array.length!==2){
				array=cond.split('<=');
				operator='<=';
				if(array.length!==2){
					array=cond.split('>');
					operator='>';
					if(array.length!==2){
						array=cond.split('<');
						operator='<';
						if(array.length!==2){
							console.log('Error: 701');
							return 701;
						}
					}
				}
			}
		}
	}
	var key=array[0].trim();
	var value=array[1].trim();
	if(key.length===0 || value.length===0){
		console.log('Error: 701');
		return 701;
	}
	return {
		key: module.exports.getCorrectType(key),
		operator: operator,
		value: module.exports.getCorrectType(value)
	};
};
module.exports.converter= function(record,key,format){
	if(record===undefined || record===null || record[key]===undefined){
		return null;
	}
	switch(format) {
    case 'toInt':
		record[key]=record[key].replaceAll('\'', '').replaceAll('"', '').trim();
		if(isNaN(record[key])){
			return null;
		}
		record[key]=parseInt(record[key],10);
		break;
    case 'toFloat':
		record[key]=record[key].replaceAll('\'', '').replaceAll('"', '').trim();
		if(isNaN(record[key])){
			return null;
		}
		record[key]=parseFloat(record[key]);
		break;
    default:
        return null;
	}
	return record;
};
module.exports.isValidFormat= function(format){
	switch(format) {
    case 'toInt':
		break;
    case 'toFloat':
		break;
    default:
        return false;
	}
	return true;
};
module.exports.isValidMapFormat= function(format){
	switch(format) {
    case 'coordinates':
		break;
    case 'geographic':
		break;
    default:
        return false;
	}
	return true;
};
module.exports.isValidMarker= function(marker){
	switch(marker) {
    case 'none':
		break;
    case 'square':
		break;
	case 'triangle':
		break;
	case 'circle':
		break;
	case 'diamond':
		break;
    default:
        return false;
	}
	return true;
};
module.exports.isValidMapMarker= function(marker){
	if (marker!==undefined || typeof marker==='object'){
		if (marker.type!==undefined){
			if (marker.type==='shape' && marker.shape!==undefined){
				switch(marker.shape) {
				case 'square':
					break;
				case 'triangle':
					break;
				case 'circle':
					break;
				case 'diamond':
					break;
				default:
					return false;
				}
				return true;
			}
			if (marker.type==='icon' && marker.icon!==undefined && typeof marker.icon==='string'){
				//may check if file exists
				return true;
			}
			if (marker.type==='text' &&
				marker.text!==undefined && typeof marker.text==='string' &&
				marker.color!==undefined && this.isHEX(marker.color)){
				return true;
			}
		}
	}
	return false;
};
module.exports.isValidInterpolation= function(interpolation){
	switch(interpolation) {
    case 'linear':
		break;
    case 'step':
		break;
	case 'basis':
		break;
	case 'cardinal':
		break;
	case 'monotone':
		break;
    default:
        return false;
	}
	return true;
};

module.exports.isValidTrace= function(trace){
	if (trace!==undefined || typeof trace==='object'){
		if (trace.type!==undefined){
			if (trace.type==='none'){
				return true;
			}
			if (trace.type==='line' || trace.type==='poly'){
				if (trace.coordinates!==undefined && Array.isArray(trace.coordinates) && trace.coordinates.length>=2){
					if (trace.strokeColor!==undefined && this.isHEX(trace.strokeColor) &&
						trace.fillColor!==undefined && this.isHEX(trace.fillColor)){
						var nCoordinates=trace.coordinates.length;
						for (var i=0; i<nCoordinates; i++){
							if (trace.coordinates[i]===undefined || !Array.isArray(trace.coordinates[i]) || trace.coordinates[i].length!==2){
								return false;
							}
							if (typeof trace.coordinates[i][0]!=='number' || typeof trace.coordinates[i][1]!=='number'){
								return false;
							}
						}
						//every coordinate is valid
						return true;
					}
				}
			}
		}
	}
	return false;
};<commit_msg>add area type and fillColor optional<commit_after>/*jshint node: true, -W106 */
'use strict';

/*
* Name : functionHelper.js
* Module : FunctionHelper
* Location : /lib/helpers
*
* History :
*
* Version   Date         Programmer         Description
* =========================================================
* 0.0.1     2015-05-14   Matteo Furlan    Initial code
* =========================================================
*/
String.prototype.replaceAll = function(target, replacement) {
	return this.split(target).join(replacement);
};
module.exports.isHEX= function(hex){
	return (/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(hex));
};
module.exports.getCorrectType= function(str){
	var arr=str.split('\'');
	if(arr.length===3){ // is a string 'hello'
		return arr[1];
	}else{
		str=str.replaceAll('\'', '');
		if(isNaN(str)){ // is a malformed string 'hello
			return str;
		}else{ // is a number -2.948
			return parseFloat(str);
		}
	}
};
module.exports.parseCondition= function(cond){
	//   <   <=   >   >=   !=   ==
	// splitting string
	var array=cond.split('==');
	var operator='==';
	if(array.length!==2){
		array=cond.split('!=');
		operator='!=';
		if(array.length!==2){
			array=cond.split('>=');
			operator='>=';
			if(array.length!==2){
				array=cond.split('<=');
				operator='<=';
				if(array.length!==2){
					array=cond.split('>');
					operator='>';
					if(array.length!==2){
						array=cond.split('<');
						operator='<';
						if(array.length!==2){
							console.log('Error: 701');
							return 701;
						}
					}
				}
			}
		}
	}
	var key=array[0].trim();
	var value=array[1].trim();
	if(key.length===0 || value.length===0){
		console.log('Error: 701');
		return 701;
	}
	return {
		key: module.exports.getCorrectType(key),
		operator: operator,
		value: module.exports.getCorrectType(value)
	};
};
module.exports.converter= function(record,key,format){
	if(record===undefined || record===null || record[key]===undefined){
		return null;
	}
	switch(format) {
    case 'toInt':
		record[key]=record[key].replaceAll('\'', '').replaceAll('"', '').trim();
		if(isNaN(record[key])){
			return null;
		}
		record[key]=parseInt(record[key],10);
		break;
    case 'toFloat':
		record[key]=record[key].replaceAll('\'', '').replaceAll('"', '').trim();
		if(isNaN(record[key])){
			return null;
		}
		record[key]=parseFloat(record[key]);
		break;
    default:
        return null;
	}
	return record;
};
module.exports.isValidFormat= function(format){
	switch(format) {
    case 'toInt':
		break;
    case 'toFloat':
		break;
    default:
        return false;
	}
	return true;
};
module.exports.isValidMapFormat= function(format){
	switch(format) {
    case 'coordinates':
		break;
    case 'geographic':
		break;
    default:
        return false;
	}
	return true;
};
module.exports.isValidMarker= function(marker){
	switch(marker) {
    case 'none':
		break;
    case 'square':
		break;
	case 'triangle':
		break;
	case 'circle':
		break;
	case 'diamond':
		break;
    default:
        return false;
	}
	return true;
};
module.exports.isValidMapMarker= function(marker){
	if (marker!==undefined || typeof marker==='object'){
		if (marker.type!==undefined){
			if (marker.type==='shape' && marker.shape!==undefined){
				switch(marker.shape) {
				case 'square':
					break;
				case 'triangle':
					break;
				case 'circle':
					break;
				case 'diamond':
					break;
				default:
					return false;
				}
				return true;
			}
			if (marker.type==='icon' && marker.icon!==undefined && typeof marker.icon==='string'){
				//may check if file exists
				return true;
			}
			if (marker.type==='text' &&
				marker.text!==undefined && typeof marker.text==='string' &&
				marker.color!==undefined && this.isHEX(marker.color)){
				return true;
			}
		}
	}
	return false;
};
module.exports.isValidInterpolation= function(interpolation){
	switch(interpolation) {
    case 'linear':
		break;
    case 'step':
		break;
	case 'basis':
		break;
	case 'cardinal':
		break;
	case 'monotone':
		break;
    default:
        return false;
	}
	return true;
};

module.exports.isValidTrace= function(trace){
	if (trace!==undefined || typeof trace==='object'){
		if (trace.type!==undefined){
			if (trace.type==='none'){
				return true;
			}
			if (trace.type==='area' || trace.type==='poly'){
				if (trace.coordinates!==undefined && Array.isArray(trace.coordinates) && trace.coordinates.length>=2){
					if (trace.strokeColor!==undefined && this.isHEX(trace.strokeColor) ){
						if (trace.fillColor!==undefined && !this.isHEX(trace.fillColor)){
							return false;
						}
						var nCoordinates=trace.coordinates.length;
						for (var i=0; i<nCoordinates; i++){
							if (trace.coordinates[i]===undefined || !Array.isArray(trace.coordinates[i]) || trace.coordinates[i].length!==2){
								return false;
							}
							if (typeof trace.coordinates[i][0]!=='number' || typeof trace.coordinates[i][1]!=='number'){
								return false;
							}
						}
						//every coordinate is valid
						return true;
					}
				}
			}
		}
	}
	return false;
};<|endoftext|>


<commit_before>/**
 *
 * This wait command is your universal weapon if you want to wait on
 * something. It expects a condition and waits until that condition
 * is fulfilled with an truthy value. A condition can be either a promise
 * or a command that returns a promise.
 *
 * A common example is to wait until a certain element contains a certain
 * text.
 *
 * <example>
    :example.html

I am some text

    :waitUntil.js
    client.waitUntil(function() {
      return this.getText('#someText').then(function(text) {
        return text === 'I am now different'
      });
    });
 * </example>
 *
 *
 * @param {Function|Promise} condition  condition to wait on
 * @param {Number=}          timeout    timeout in ms (default: 500)
 * @param {Number=}          interval   interval between condition checks (default: 250)
 *
 * @uses utility/pause
 * @type utility
 *
 */

var q = require('q'),
    ErrorHandler = require('../utils/ErrorHandler.js'),
    reject = function(d) {
        d.reject(new ErrorHandler.CommandError('Promise never resolved with an truthy value'));
    };

function waitUntilPrivate(condition, timeout, interval, starttime) {
    var self = this,
        defer = q.defer(),
        promise;

    if(typeof condition === 'function') {
        promise = condition.call(this);
    } else if(q.isPromiseAlike(condition)) {
        promise = condition;
    } else {
        throw new ErrorHandler.CommandError('waitUntil condition needs to be a promise or a function that returns a promise');
    }

    var now = new Date().getTime();
    var timeLeft = timeout - (now - starttime);
    timeLeft = timeLeft < 0 ? 0 : timeLeft;

    if(!timeLeft) {
        reject(defer);
        return defer.promise;
    }

    var timeoutId = setTimeout(function() {
        reject(defer);
    }, timeLeft < 0 ? 0 : timeLeft);

    promise.then(function(res) {
        clearTimeout(timeoutId);

        if(!res) {
            if(q.isPromiseAlike(condition)) {
                defer.reject(new ErrorHandler.CommandError('Promise was fulfilled with a falsy value'));
            }
            return defer.resolve(self.pause(interval)
                .then(waitUntilPrivate.bind(self, condition, timeout, interval, starttime)));
        }

        defer.resolve(res);

    }, function(err) {
        clearTimeout(timeout);

        defer.reject(new ErrorHandler.CommandError('Promise was fulfilled but got rejected with the following reason: ' + err));

    });

    return defer.promise;

}

module.exports = function waitUntil(condition, timeout, interval) {
    /*!
     * ensure that ms and interval are set properly
     */
    if (typeof timeout !== 'number') {
        timeout = this.options.waitforTimeout;
    }

    if (typeof interval !== 'number') {
        interval = this.options.waitforInterval;
    }

    var starttime = new Date().getTime();

    return waitUntilPrivate.call(this, condition, timeout, interval, starttime);
};
<commit_msg>fix var renaming<commit_after>/**
 *
 * This wait command is your universal weapon if you want to wait on
 * something. It expects a condition and waits until that condition
 * is fulfilled with an truthy value. A condition can be either a promise
 * or a command that returns a promise.
 *
 * A common example is to wait until a certain element contains a certain
 * text.
 *
 * <example>
    :example.html

I am some text

    :waitUntil.js
    client.waitUntil(function() {
      return this.getText('#someText').then(function(text) {
        return text === 'I am now different'
      });
    });
 * </example>
 *
 *
 * @param {Function|Promise} condition  condition to wait on
 * @param {Number=}          timeout    timeout in ms (default: 500)
 * @param {Number=}          interval   interval between condition checks (default: 250)
 *
 * @uses utility/pause
 * @type utility
 *
 */

var q = require('q'),
    ErrorHandler = require('../utils/ErrorHandler.js'),
    reject = function(d) {
        d.reject(new ErrorHandler.CommandError('Promise never resolved with an truthy value'));
    };

function waitUntilPrivate(condition, timeout, interval, starttime) {
    var self = this,
        defer = q.defer(),
        promise;

    if(typeof condition === 'function') {
        promise = condition.call(this);
    } else if(q.isPromiseAlike(condition)) {
        promise = condition;
    } else {
        throw new ErrorHandler.CommandError('waitUntil condition needs to be a promise or a function that returns a promise');
    }

    var now = new Date().getTime();
    var timeLeft = timeout - (now - starttime);
    timeLeft = timeLeft < 0 ? 0 : timeLeft;

    if(!timeLeft) {
        reject(defer);
        return defer.promise;
    }

    var timeoutId = setTimeout(function() {
        reject(defer);
    }, timeLeft < 0 ? 0 : timeLeft);

    promise.then(function(res) {
        clearTimeout(timeoutId);

        if(!res) {
            if(q.isPromiseAlike(condition)) {
                defer.reject(new ErrorHandler.CommandError('Promise was fulfilled with a falsy value'));
            }
            return defer.resolve(self.pause(interval)
                .then(waitUntilPrivate.bind(self, condition, timeout, interval, starttime)));
        }

        defer.resolve(res);

    }, function(err) {
        clearTimeout(timeoutId);

        defer.reject(new ErrorHandler.CommandError('Promise was fulfilled but got rejected with the following reason: ' + err));

    });

    return defer.promise;

}

module.exports = function waitUntil(condition, timeout, interval) {
    /*!
     * ensure that ms and interval are set properly
     */
    if (typeof timeout !== 'number') {
        timeout = this.options.waitforTimeout;
    }

    if (typeof interval !== 'number') {
        interval = this.options.waitforInterval;
    }

    var starttime = new Date().getTime();

    return waitUntilPrivate.call(this, condition, timeout, interval, starttime);
};
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright The Closure Library Authors.
 * SPDX-License-Identifier: Apache-2.0
 */

/**
 * @fileoverview Error classes for the IndexedDB wrapper.
 */

// TODO(user): We're trying to migrate all ES5 subclasses of Closure
// Library to ES6. In ES6 this cannot be referenced before super is called. This
// file has at least one this before a super call (in ES5) and cannot be
// automatically upgraded to ES6 as a result. Please fix this if you have a
// chance. Note: This can sometimes be caused by not calling the super
// constructor at all. You can run the conversion tool yourself to see what it
// does on this file: blaze run //javascript/refactoring/es6_classes:convert.

goog.provide('goog.db.Error');

goog.require('goog.asserts');
goog.require('goog.debug.Error');

/**
 * A database error. Since the stack trace can be unhelpful in an asynchronous
 * context, the error provides a message about where it was produced.
 *
 * @param {number|!DOMError|!goog.db.Error.DOMErrorLike} error The DOMError
 *     instance returned by the browser for Chrome22+, or an error code for
 *     previous versions.
 * @param {string} context A description of where the error occurred.
 * @param {string=} opt_message Additional message.
 * @constructor
 * @extends {goog.debug.Error}
 * @final
 */
goog.db.Error = function(error, context, opt_message) {
  'use strict';
  var errorCode = null;
  var internalError = null;
  if (typeof error === 'number') {
    errorCode = error;
    internalError = {name: goog.db.Error.getName(errorCode)};
  } else {
    internalError = error;
    errorCode = goog.db.Error.getCode(error.name);
  }

  /**
   * The code for this error.
   *
   * @type {number}
   */
  this.code = errorCode;

  /**
   * The DOMException as returned by the browser.
   *
   * @type {!goog.db.Error.DOMErrorLike}
   * @private
   */
  this.error_ = internalError;

  var msg = 'Error ' + context + ': ' + this.getName();
  if (opt_message) {
    msg += ', ' + opt_message;
  }
  goog.db.Error.base(this, 'constructor', msg);
};
goog.inherits(goog.db.Error, goog.debug.Error);

/**
 * @return {string} The name of the error.
 */
goog.db.Error.prototype.getName = function() {
  'use strict';
  return this.error_.name || '';
};

/**
 * A specific kind of database error. If a Version Change is unable to proceed
 * due to other open database connections, it will block and this error will be
 * thrown.
 *
 * @constructor
 * @extends {goog.debug.Error}
 * @final
 */
goog.db.Error.VersionChangeBlockedError = function() {
  'use strict';
  goog.db.Error.VersionChangeBlockedError.base(
      this, 'constructor', 'Version change blocked');
};
goog.inherits(goog.db.Error.VersionChangeBlockedError, goog.debug.Error);

/**
 * Synthetic error codes for database errors, for use when IndexedDB
 * support is not available. This numbering differs in practice
 * from the browser implementations, but it is not meant to be reliable:
 * this object merely ensures that goog.db.Error is loadable on platforms
 * that do not support IndexedDB.
 *
 * @enum {number}
 * @private
 */
goog.db.Error.DatabaseErrorCode_ = {
  UNKNOWN_ERR: 1,
  NON_TRANSIENT_ERR: 2,
  NOT_FOUND_ERR: 3,
  CONSTRAINT_ERR: 4,
  DATA_ERR: 5,
  NOT_ALLOWED_ERR: 6,
  TRANSACTION_INACTIVE_ERR: 7,
  ABORT_ERR: 8,
  READ_ONLY_ERR: 9,
  TRANSIENT_ERR: 10,
  TIMEOUT_ERR: 11,
  QUOTA_ERR: 12,
  INVALID_ACCESS_ERR: 13,
  INVALID_STATE_ERR: 14
};

/**
 * Error codes for database errors.
 * @see http://www.w3.org/TR/IndexedDB/#idl-def-IDBDatabaseException
 *
 * @enum {number}
 * @suppress {missingProperties} Obsolete IndexDb exception objects
 */
goog.db.Error.ErrorCode = {
  UNKNOWN_ERR: (goog.global.IDBDatabaseException ||
                goog.global.webkitIDBDatabaseException ||
                goog.db.Error.DatabaseErrorCode_)
                   .UNKNOWN_ERR,
  NON_TRANSIENT_ERR: (goog.global.IDBDatabaseException ||
                      goog.global.webkitIDBDatabaseException ||
                      goog.db.Error.DatabaseErrorCode_)
                         .NON_TRANSIENT_ERR,
  NOT_FOUND_ERR: (goog.global.IDBDatabaseException ||
                  goog.global.webkitIDBDatabaseException ||
                  goog.db.Error.DatabaseErrorCode_)
                     .NOT_FOUND_ERR,
  CONSTRAINT_ERR: (goog.global.IDBDatabaseException ||
                   goog.global.webkitIDBDatabaseException ||
                   goog.db.Error.DatabaseErrorCode_)
                      .CONSTRAINT_ERR,
  DATA_ERR: (goog.global.IDBDatabaseException ||
             goog.global.webkitIDBDatabaseException ||
             goog.db.Error.DatabaseErrorCode_)
                .DATA_ERR,
  NOT_ALLOWED_ERR: (goog.global.IDBDatabaseException ||
                    goog.global.webkitIDBDatabaseException ||
                    goog.db.Error.DatabaseErrorCode_)
                       .NOT_ALLOWED_ERR,
  TRANSACTION_INACTIVE_ERR: (goog.global.IDBDatabaseException ||
                             goog.global.webkitIDBDatabaseException ||
                             goog.db.Error.DatabaseErrorCode_)
                                .TRANSACTION_INACTIVE_ERR,
  ABORT_ERR: (goog.global.IDBDatabaseException ||
              goog.global.webkitIDBDatabaseException ||
              goog.db.Error.DatabaseErrorCode_)
                 .ABORT_ERR,
  READ_ONLY_ERR: (goog.global.IDBDatabaseException ||
                  goog.global.webkitIDBDatabaseException ||
                  goog.db.Error.DatabaseErrorCode_)
                     .READ_ONLY_ERR,
  TIMEOUT_ERR: (goog.global.IDBDatabaseException ||
                goog.global.webkitIDBDatabaseException ||
                goog.db.Error.DatabaseErrorCode_)
                   .TIMEOUT_ERR,
  QUOTA_ERR: (goog.global.IDBDatabaseException ||
              goog.global.webkitIDBDatabaseException ||
              goog.db.Error.DatabaseErrorCode_)
                 .QUOTA_ERR,
  INVALID_ACCESS_ERR:
      (goog.global.DOMException || goog.db.Error.DatabaseErrorCode_)
          .INVALID_ACCESS_ERR,
  INVALID_STATE_ERR:
      (goog.global.DOMException || goog.db.Error.DatabaseErrorCode_)
          .INVALID_STATE_ERR
};

/**
 * Translates an error code into a more useful message.
 *
 * @param {number} code Error code.
 * @return {string} A debug message.
 */
goog.db.Error.getMessage = function(code) {
  'use strict';
  switch (code) {
    case goog.db.Error.ErrorCode.UNKNOWN_ERR:
      return 'Unknown error';
    case goog.db.Error.ErrorCode.NON_TRANSIENT_ERR:
      return 'Invalid operation';
    case goog.db.Error.ErrorCode.NOT_FOUND_ERR:
      return 'Required database object not found';
    case goog.db.Error.ErrorCode.CONSTRAINT_ERR:
      return 'Constraint unsatisfied';
    case goog.db.Error.ErrorCode.DATA_ERR:
      return 'Invalid data';
    case goog.db.Error.ErrorCode.NOT_ALLOWED_ERR:
      return 'Operation disallowed';
    case goog.db.Error.ErrorCode.TRANSACTION_INACTIVE_ERR:
      return 'Transaction not active';
    case goog.db.Error.ErrorCode.ABORT_ERR:
      return 'Request aborted';
    case goog.db.Error.ErrorCode.READ_ONLY_ERR:
      return 'Modifying operation not allowed in a read-only transaction';
    case goog.db.Error.ErrorCode.TIMEOUT_ERR:
      return 'Transaction timed out';
    case goog.db.Error.ErrorCode.QUOTA_ERR:
      return 'Database storage space quota exceeded';
    case goog.db.Error.ErrorCode.INVALID_ACCESS_ERR:
      return 'Invalid operation';
    case goog.db.Error.ErrorCode.INVALID_STATE_ERR:
      return 'Invalid state';
    default:
      return 'Unrecognized exception with code ' + code;
  }
};

/** @record */
goog.db.Error.DOMErrorLike = function() {};

/** @type {string|undefined} */
goog.db.Error.DOMErrorLike.prototype.name;

/**
 * Names of all possible errors as returned from the browser.
 * @see http://www.w3.org/TR/IndexedDB/#exceptions
 * @enum {string}
 */
goog.db.Error.ErrorName = {
  ABORT_ERR: 'AbortError',
  CONSTRAINT_ERR: 'ConstraintError',
  DATA_CLONE_ERR: 'DataCloneError',
  DATA_ERR: 'DataError',
  INVALID_ACCESS_ERR: 'InvalidAccessError',
  INVALID_STATE_ERR: 'InvalidStateError',
  NOT_FOUND_ERR: 'NotFoundError',
  QUOTA_EXCEEDED_ERR: 'QuotaExceededError',
  READ_ONLY_ERR: 'ReadOnlyError',
  SYNTAX_ERROR: 'SyntaxError',
  TIMEOUT_ERR: 'TimeoutError',
  TRANSACTION_INACTIVE_ERR: 'TransactionInactiveError',
  UNKNOWN_ERR: 'UnknownError',
  VERSION_ERR: 'VersionError'
};

/**
 * Translates an error name to an error code. This is purely kept for backwards
 * compatibility with Chrome21.
 *
 * @param {string|undefined} name The name of the erorr.
 * @return {number} The error code corresponding to the error.
 */
goog.db.Error.getCode = function(name) {
  'use strict';
  switch (name) {
    case goog.db.Error.ErrorName.UNKNOWN_ERR:
      return goog.db.Error.ErrorCode.UNKNOWN_ERR;
    case goog.db.Error.ErrorName.NOT_FOUND_ERR:
      return goog.db.Error.ErrorCode.NOT_FOUND_ERR;
    case goog.db.Error.ErrorName.CONSTRAINT_ERR:
      return goog.db.Error.ErrorCode.CONSTRAINT_ERR;
    case goog.db.Error.ErrorName.DATA_ERR:
      return goog.db.Error.ErrorCode.DATA_ERR;
    case goog.db.Error.ErrorName.TRANSACTION_INACTIVE_ERR:
      return goog.db.Error.ErrorCode.TRANSACTION_INACTIVE_ERR;
    case goog.db.Error.ErrorName.ABORT_ERR:
      return goog.db.Error.ErrorCode.ABORT_ERR;
    case goog.db.Error.ErrorName.READ_ONLY_ERR:
      return goog.db.Error.ErrorCode.READ_ONLY_ERR;
    case goog.db.Error.ErrorName.TIMEOUT_ERR:
      return goog.db.Error.ErrorCode.TIMEOUT_ERR;
    case goog.db.Error.ErrorName.QUOTA_EXCEEDED_ERR:
      return goog.db.Error.ErrorCode.QUOTA_ERR;
    case goog.db.Error.ErrorName.INVALID_ACCESS_ERR:
      return goog.db.Error.ErrorCode.INVALID_ACCESS_ERR;
    case goog.db.Error.ErrorName.INVALID_STATE_ERR:
      return goog.db.Error.ErrorCode.INVALID_STATE_ERR;
    default:
      return goog.db.Error.ErrorCode.UNKNOWN_ERR;
  }
};

/**
 * Converts an error code used by the old spec, to an error name used by the
 * latest spec.
 * @see http://www.w3.org/TR/IndexedDB/#exceptions
 *
 * @param {!goog.db.Error.ErrorCode|number} code The error code to convert.
 * @return {!goog.db.Error.ErrorName} The corresponding name of the error.
 */
goog.db.Error.getName = function(code) {
  'use strict';
  switch (code) {
    case goog.db.Error.ErrorCode.UNKNOWN_ERR:
      return goog.db.Error.ErrorName.UNKNOWN_ERR;
    case goog.db.Error.ErrorCode.NOT_FOUND_ERR:
      return goog.db.Error.ErrorName.NOT_FOUND_ERR;
    case goog.db.Error.ErrorCode.CONSTRAINT_ERR:
      return goog.db.Error.ErrorName.CONSTRAINT_ERR;
    case goog.db.Error.ErrorCode.DATA_ERR:
      return goog.db.Error.ErrorName.DATA_ERR;
    case goog.db.Error.ErrorCode.TRANSACTION_INACTIVE_ERR:
      return goog.db.Error.ErrorName.TRANSACTION_INACTIVE_ERR;
    case goog.db.Error.ErrorCode.ABORT_ERR:
      return goog.db.Error.ErrorName.ABORT_ERR;
    case goog.db.Error.ErrorCode.READ_ONLY_ERR:
      return goog.db.Error.ErrorName.READ_ONLY_ERR;
    case goog.db.Error.ErrorCode.TIMEOUT_ERR:
      return goog.db.Error.ErrorName.TIMEOUT_ERR;
    case goog.db.Error.ErrorCode.QUOTA_ERR:
      return goog.db.Error.ErrorName.QUOTA_EXCEEDED_ERR;
    case goog.db.Error.ErrorCode.INVALID_ACCESS_ERR:
      return goog.db.Error.ErrorName.INVALID_ACCESS_ERR;
    case goog.db.Error.ErrorCode.INVALID_STATE_ERR:
      return goog.db.Error.ErrorName.INVALID_STATE_ERR;
    default:
      return goog.db.Error.ErrorName.UNKNOWN_ERR;
  }
};

/**
 * Constructs an goog.db.Error instance from an IDBRequest. This abstraction is
 * necessary to provide backwards compatibility with Chrome21.
 *
 * @param {!IDBRequest} request The request that failed.
 * @param {string} message The error message to add to err if it's wrapped.
 * @return {!goog.db.Error} The error that caused the failure.
 */
goog.db.Error.fromRequest = function(request, message) {
  'use strict';
  if ('error' in request) {
    // Chrome 22+
    return new goog.db.Error(goog.asserts.assert(request.error), message);
  } else {
    return new goog.db.Error(
        {name: goog.db.Error.ErrorName.UNKNOWN_ERR}, message);
  }
};

/**
 * Constructs an goog.db.Error instance from an DOMException. This abstraction
 * is necessary to provide backwards compatibility with Chrome21.
 *
 * @param {!DOMError|!DOMException} ex The exception that was thrown.
 * @param {string} message The error message to add to err if it's wrapped.
 * @return {!goog.db.Error} The error that caused the failure.
 */
goog.db.Error.fromException = function(ex, message) {
  'use strict';
  if ('name' in ex) {
    // Chrome 22+.
    var errorMessage = message + ': ' + ex.message;
    return new goog.db.Error(ex, errorMessage);
  } else if ('code' in ex) {
    // Chrome 21 and before.
    var errorName = goog.db.Error.getName(ex.code);
    var errorMessage = message + ': ' + ex.message;
    return new goog.db.Error({name: errorName}, errorMessage);
  } else {
    return new goog.db.Error(
        {name: goog.db.Error.ErrorName.UNKNOWN_ERR}, message);
  }
};
<commit_msg>Remove special support for Chrome 21- in goog.db.Error<commit_after>/**
 * @license
 * Copyright The Closure Library Authors.
 * SPDX-License-Identifier: Apache-2.0
 */

/**
 * @fileoverview Error classes for the IndexedDB wrapper.
 */

// TODO(user): We're trying to migrate all ES5 subclasses of Closure
// Library to ES6. In ES6 this cannot be referenced before super is called. This
// file has at least one this before a super call (in ES5) and cannot be
// automatically upgraded to ES6 as a result. Please fix this if you have a
// chance. Note: This can sometimes be caused by not calling the super
// constructor at all. You can run the conversion tool yourself to see what it
// does on this file: blaze run //javascript/refactoring/es6_classes:convert.

goog.provide('goog.db.Error');

goog.require('goog.asserts');
goog.require('goog.debug.Error');

/**
 * A database error. Since the stack trace can be unhelpful in an asynchronous
 * context, the error provides a message about where it was produced.
 *
 * @param {number|!DOMError|!goog.db.Error.DOMErrorLike} error The DOMError
 *     instance returned by the browser for Chrome22+, or an error code for
 *     previous versions.
 * @param {string} context A description of where the error occurred.
 * @param {string=} opt_message Additional message.
 * @constructor
 * @extends {goog.debug.Error}
 * @final
 */
goog.db.Error = function(error, context, opt_message) {
  'use strict';
  var errorCode = null;
  var internalError = null;
  if (typeof error === 'number') {
    errorCode = error;
    internalError = {name: goog.db.Error.getName(errorCode)};
  } else {
    internalError = error;
    errorCode = goog.db.Error.getCode(error.name);
  }

  /**
   * The code for this error.
   *
   * @type {number}
   */
  this.code = errorCode;

  /**
   * The DOMException as returned by the browser.
   *
   * @type {!goog.db.Error.DOMErrorLike}
   * @private
   */
  this.error_ = internalError;

  var msg = 'Error ' + context + ': ' + this.getName();
  if (opt_message) {
    msg += ', ' + opt_message;
  }
  goog.db.Error.base(this, 'constructor', msg);
};
goog.inherits(goog.db.Error, goog.debug.Error);

/**
 * @return {string} The name of the error.
 */
goog.db.Error.prototype.getName = function() {
  'use strict';
  return this.error_.name || '';
};

/**
 * A specific kind of database error. If a Version Change is unable to proceed
 * due to other open database connections, it will block and this error will be
 * thrown.
 *
 * @constructor
 * @extends {goog.debug.Error}
 * @final
 */
goog.db.Error.VersionChangeBlockedError = function() {
  'use strict';
  goog.db.Error.VersionChangeBlockedError.base(
      this, 'constructor', 'Version change blocked');
};
goog.inherits(goog.db.Error.VersionChangeBlockedError, goog.debug.Error);

/**
 * Synthetic error codes for database errors, for use when IndexedDB
 * support is not available. This numbering differs in practice
 * from the browser implementations, but it is not meant to be reliable:
 * this object merely ensures that goog.db.Error is loadable on platforms
 * that do not support IndexedDB.
 *
 * @enum {number}
 * @private
 */
goog.db.Error.DatabaseErrorCode_ = {
  UNKNOWN_ERR: 1,
  NON_TRANSIENT_ERR: 2,
  NOT_FOUND_ERR: 3,
  CONSTRAINT_ERR: 4,
  DATA_ERR: 5,
  NOT_ALLOWED_ERR: 6,
  TRANSACTION_INACTIVE_ERR: 7,
  ABORT_ERR: 8,
  READ_ONLY_ERR: 9,
  TRANSIENT_ERR: 10,
  TIMEOUT_ERR: 11,
  QUOTA_ERR: 12,
  INVALID_ACCESS_ERR: 13,
  INVALID_STATE_ERR: 14
};

/**
 * Error codes for database errors.
 * @see http://www.w3.org/TR/IndexedDB/#idl-def-IDBDatabaseException
 *
 * @enum {number}
 * @suppress {missingProperties} Obsolete IndexDb exception objects
 */
goog.db.Error.ErrorCode = {
  UNKNOWN_ERR: (goog.global.IDBDatabaseException ||
                goog.global.webkitIDBDatabaseException ||
                goog.db.Error.DatabaseErrorCode_)
                   .UNKNOWN_ERR,
  NON_TRANSIENT_ERR: (goog.global.IDBDatabaseException ||
                      goog.global.webkitIDBDatabaseException ||
                      goog.db.Error.DatabaseErrorCode_)
                         .NON_TRANSIENT_ERR,
  NOT_FOUND_ERR: (goog.global.IDBDatabaseException ||
                  goog.global.webkitIDBDatabaseException ||
                  goog.db.Error.DatabaseErrorCode_)
                     .NOT_FOUND_ERR,
  CONSTRAINT_ERR: (goog.global.IDBDatabaseException ||
                   goog.global.webkitIDBDatabaseException ||
                   goog.db.Error.DatabaseErrorCode_)
                      .CONSTRAINT_ERR,
  DATA_ERR: (goog.global.IDBDatabaseException ||
             goog.global.webkitIDBDatabaseException ||
             goog.db.Error.DatabaseErrorCode_)
                .DATA_ERR,
  NOT_ALLOWED_ERR: (goog.global.IDBDatabaseException ||
                    goog.global.webkitIDBDatabaseException ||
                    goog.db.Error.DatabaseErrorCode_)
                       .NOT_ALLOWED_ERR,
  TRANSACTION_INACTIVE_ERR: (goog.global.IDBDatabaseException ||
                             goog.global.webkitIDBDatabaseException ||
                             goog.db.Error.DatabaseErrorCode_)
                                .TRANSACTION_INACTIVE_ERR,
  ABORT_ERR: (goog.global.IDBDatabaseException ||
              goog.global.webkitIDBDatabaseException ||
              goog.db.Error.DatabaseErrorCode_)
                 .ABORT_ERR,
  READ_ONLY_ERR: (goog.global.IDBDatabaseException ||
                  goog.global.webkitIDBDatabaseException ||
                  goog.db.Error.DatabaseErrorCode_)
                     .READ_ONLY_ERR,
  TIMEOUT_ERR: (goog.global.IDBDatabaseException ||
                goog.global.webkitIDBDatabaseException ||
                goog.db.Error.DatabaseErrorCode_)
                   .TIMEOUT_ERR,
  QUOTA_ERR: (goog.global.IDBDatabaseException ||
              goog.global.webkitIDBDatabaseException ||
              goog.db.Error.DatabaseErrorCode_)
                 .QUOTA_ERR,
  INVALID_ACCESS_ERR:
      (goog.global.DOMException || goog.db.Error.DatabaseErrorCode_)
          .INVALID_ACCESS_ERR,
  INVALID_STATE_ERR:
      (goog.global.DOMException || goog.db.Error.DatabaseErrorCode_)
          .INVALID_STATE_ERR
};

/**
 * Translates an error code into a more useful message.
 *
 * @param {number} code Error code.
 * @return {string} A debug message.
 */
goog.db.Error.getMessage = function(code) {
  'use strict';
  switch (code) {
    case goog.db.Error.ErrorCode.UNKNOWN_ERR:
      return 'Unknown error';
    case goog.db.Error.ErrorCode.NON_TRANSIENT_ERR:
      return 'Invalid operation';
    case goog.db.Error.ErrorCode.NOT_FOUND_ERR:
      return 'Required database object not found';
    case goog.db.Error.ErrorCode.CONSTRAINT_ERR:
      return 'Constraint unsatisfied';
    case goog.db.Error.ErrorCode.DATA_ERR:
      return 'Invalid data';
    case goog.db.Error.ErrorCode.NOT_ALLOWED_ERR:
      return 'Operation disallowed';
    case goog.db.Error.ErrorCode.TRANSACTION_INACTIVE_ERR:
      return 'Transaction not active';
    case goog.db.Error.ErrorCode.ABORT_ERR:
      return 'Request aborted';
    case goog.db.Error.ErrorCode.READ_ONLY_ERR:
      return 'Modifying operation not allowed in a read-only transaction';
    case goog.db.Error.ErrorCode.TIMEOUT_ERR:
      return 'Transaction timed out';
    case goog.db.Error.ErrorCode.QUOTA_ERR:
      return 'Database storage space quota exceeded';
    case goog.db.Error.ErrorCode.INVALID_ACCESS_ERR:
      return 'Invalid operation';
    case goog.db.Error.ErrorCode.INVALID_STATE_ERR:
      return 'Invalid state';
    default:
      return 'Unrecognized exception with code ' + code;
  }
};

/** @record */
goog.db.Error.DOMErrorLike = function() {};

/** @type {string|undefined} */
goog.db.Error.DOMErrorLike.prototype.name;

/**
 * Names of all possible errors as returned from the browser.
 * @see http://www.w3.org/TR/IndexedDB/#exceptions
 * @enum {string}
 */
goog.db.Error.ErrorName = {
  ABORT_ERR: 'AbortError',
  CONSTRAINT_ERR: 'ConstraintError',
  DATA_CLONE_ERR: 'DataCloneError',
  DATA_ERR: 'DataError',
  INVALID_ACCESS_ERR: 'InvalidAccessError',
  INVALID_STATE_ERR: 'InvalidStateError',
  NOT_FOUND_ERR: 'NotFoundError',
  QUOTA_EXCEEDED_ERR: 'QuotaExceededError',
  READ_ONLY_ERR: 'ReadOnlyError',
  SYNTAX_ERROR: 'SyntaxError',
  TIMEOUT_ERR: 'TimeoutError',
  TRANSACTION_INACTIVE_ERR: 'TransactionInactiveError',
  UNKNOWN_ERR: 'UnknownError',
  VERSION_ERR: 'VersionError'
};

/**
 * Translates an error name to an error code. This is purely kept for backwards
 * compatibility with Chrome21.
 *
 * @param {string|undefined} name The name of the erorr.
 * @return {number} The error code corresponding to the error.
 */
goog.db.Error.getCode = function(name) {
  'use strict';
  switch (name) {
    case goog.db.Error.ErrorName.UNKNOWN_ERR:
      return goog.db.Error.ErrorCode.UNKNOWN_ERR;
    case goog.db.Error.ErrorName.NOT_FOUND_ERR:
      return goog.db.Error.ErrorCode.NOT_FOUND_ERR;
    case goog.db.Error.ErrorName.CONSTRAINT_ERR:
      return goog.db.Error.ErrorCode.CONSTRAINT_ERR;
    case goog.db.Error.ErrorName.DATA_ERR:
      return goog.db.Error.ErrorCode.DATA_ERR;
    case goog.db.Error.ErrorName.TRANSACTION_INACTIVE_ERR:
      return goog.db.Error.ErrorCode.TRANSACTION_INACTIVE_ERR;
    case goog.db.Error.ErrorName.ABORT_ERR:
      return goog.db.Error.ErrorCode.ABORT_ERR;
    case goog.db.Error.ErrorName.READ_ONLY_ERR:
      return goog.db.Error.ErrorCode.READ_ONLY_ERR;
    case goog.db.Error.ErrorName.TIMEOUT_ERR:
      return goog.db.Error.ErrorCode.TIMEOUT_ERR;
    case goog.db.Error.ErrorName.QUOTA_EXCEEDED_ERR:
      return goog.db.Error.ErrorCode.QUOTA_ERR;
    case goog.db.Error.ErrorName.INVALID_ACCESS_ERR:
      return goog.db.Error.ErrorCode.INVALID_ACCESS_ERR;
    case goog.db.Error.ErrorName.INVALID_STATE_ERR:
      return goog.db.Error.ErrorCode.INVALID_STATE_ERR;
    default:
      return goog.db.Error.ErrorCode.UNKNOWN_ERR;
  }
};

/**
 * Converts an error code used by the old spec, to an error name used by the
 * latest spec.
 * @see http://www.w3.org/TR/IndexedDB/#exceptions
 *
 * @param {!goog.db.Error.ErrorCode|number} code The error code to convert.
 * @return {!goog.db.Error.ErrorName} The corresponding name of the error.
 */
goog.db.Error.getName = function(code) {
  'use strict';
  switch (code) {
    case goog.db.Error.ErrorCode.UNKNOWN_ERR:
      return goog.db.Error.ErrorName.UNKNOWN_ERR;
    case goog.db.Error.ErrorCode.NOT_FOUND_ERR:
      return goog.db.Error.ErrorName.NOT_FOUND_ERR;
    case goog.db.Error.ErrorCode.CONSTRAINT_ERR:
      return goog.db.Error.ErrorName.CONSTRAINT_ERR;
    case goog.db.Error.ErrorCode.DATA_ERR:
      return goog.db.Error.ErrorName.DATA_ERR;
    case goog.db.Error.ErrorCode.TRANSACTION_INACTIVE_ERR:
      return goog.db.Error.ErrorName.TRANSACTION_INACTIVE_ERR;
    case goog.db.Error.ErrorCode.ABORT_ERR:
      return goog.db.Error.ErrorName.ABORT_ERR;
    case goog.db.Error.ErrorCode.READ_ONLY_ERR:
      return goog.db.Error.ErrorName.READ_ONLY_ERR;
    case goog.db.Error.ErrorCode.TIMEOUT_ERR:
      return goog.db.Error.ErrorName.TIMEOUT_ERR;
    case goog.db.Error.ErrorCode.QUOTA_ERR:
      return goog.db.Error.ErrorName.QUOTA_EXCEEDED_ERR;
    case goog.db.Error.ErrorCode.INVALID_ACCESS_ERR:
      return goog.db.Error.ErrorName.INVALID_ACCESS_ERR;
    case goog.db.Error.ErrorCode.INVALID_STATE_ERR:
      return goog.db.Error.ErrorName.INVALID_STATE_ERR;
    default:
      return goog.db.Error.ErrorName.UNKNOWN_ERR;
  }
};

/**
 * Constructs an goog.db.Error instance from an IDBRequest. This abstraction is
 * necessary to provide backwards compatibility with Chrome21.
 *
 * @param {!IDBRequest} request The request that failed.
 * @param {string} message The error message to add to err if it's wrapped.
 * @return {!goog.db.Error} The error that caused the failure.
 */
goog.db.Error.fromRequest = function(request, message) {
  'use strict';
  if ('error' in request) {
    // Chrome 22+
    return new goog.db.Error(goog.asserts.assert(request.error), message);
  } else {
    return new goog.db.Error(
        {name: goog.db.Error.ErrorName.UNKNOWN_ERR}, message);
  }
};

/**
 * Constructs an goog.db.Error instance from an DOMException. This abstraction
 * is necessary to provide backwards compatibility with Chrome21.
 *
 * @param {!DOMError|!DOMException} ex The exception that was thrown.
 * @param {string} message The error message to add to err if it's wrapped.
 * @return {!goog.db.Error} The error that caused the failure.
 */
goog.db.Error.fromException = function(ex, message) {
  'use strict';
  if ('name' in ex) {
    let errorMessage = message + ': ' + ex.message;
    return new goog.db.Error(ex, errorMessage);
  } else {
    // TODO(sdh): Is this branch unreachable?
    return new goog.db.Error(
        {name: goog.db.Error.ErrorName.UNKNOWN_ERR}, message);
  }
};
<|endoftext|>


<commit_before>// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP

import path from 'path';

export function getPackageJSON () {
  delete require.cache[require.resolve('./package.json')];
  var packageJSON = require('./package.json');
  delete packageJSON.config;
  delete packageJSON.scripts;
  packageJSON.main = 'index.js';
  return packageJSON;
}

export default {
  dist: path.resolve(__dirname, 'dist'),
  copyAssets: [
    'README.md',
    {
      asset: 'src/js/**',
      babel: true,
      ignores: ['.DS_Store']
    },
    {
      asset: 'src/scss/**',
      dist: 'dist/scss/'
    },
    {
      asset: 'src/img/**',
      dist: 'dist/img/'
    },
    {
      filename: 'package.json',
      asset: JSON.stringify(getPackageJSON(), null, 2)
    }
  ],
  scssAssets: ['src/scss/**/*.scss'],
  jsAssets: ['src/js/**/*.js'],
  mainJs: 'src/js/index.js',
  mainScss: 'src/scss/grommet-core/index.scss',
  // icons: {
  //   source: 'src/img/icons',
  //   destination: 'src/js/components/icons/base',
  //   context: '../../../'
  // },
  sync: {
    hostname: 'grommet.io',
    username: 'grommet',
    remoteDestination: '/var/www/html/assets/' + getPackageJSON().version
  },
  webpack: {
    output: {
      filename: 'grommet.min.js',
      libraryTarget: 'var',
      library: 'Grommet'
    },
    resolve: {
      alias: {
        'grommet': path.resolve(__dirname, 'src/js')
      },
      modulesDirectories: ['node_modules', 'src/js', 'src/scss']
    },
    externals: {
      'react': 'React',
      'react-dom': 'ReactDOM',
      'react-addons-transition-group': 'React.addons.TransitionGroup'
    }
  },
  distPreprocess: ['generate-index-icons', 'generate-icon-messages', 'dist-css'],
  testPaths: [
    '__tests__',
    '!__tests__/utils/',
    '!__tests__/mocks/'
  ],
  preCommitTasks: ['generate-icons', 'jslint', 'scsslint', 'test']
};
<commit_msg>Adding react-intl as an external.<commit_after>// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP

import path from 'path';

export function getPackageJSON () {
  delete require.cache[require.resolve('./package.json')];
  var packageJSON = require('./package.json');
  delete packageJSON.config;
  delete packageJSON.scripts;
  packageJSON.main = 'index.js';
  return packageJSON;
}

export default {
  dist: path.resolve(__dirname, 'dist'),
  copyAssets: [
    'README.md',
    {
      asset: 'src/js/**',
      babel: true,
      ignores: ['.DS_Store']
    },
    {
      asset: 'src/scss/**',
      dist: 'dist/scss/'
    },
    {
      asset: 'src/img/**',
      dist: 'dist/img/'
    },
    {
      filename: 'package.json',
      asset: JSON.stringify(getPackageJSON(), null, 2)
    }
  ],
  scssAssets: ['src/scss/**/*.scss'],
  jsAssets: ['src/js/**/*.js'],
  mainJs: 'src/js/index.js',
  mainScss: 'src/scss/grommet-core/index.scss',
  // icons: {
  //   source: 'src/img/icons',
  //   destination: 'src/js/components/icons/base',
  //   context: '../../../'
  // },
  sync: {
    hostname: 'grommet.io',
    username: 'grommet',
    remoteDestination: '/var/www/html/assets/' + getPackageJSON().version
  },
  webpack: {
    output: {
      filename: 'grommet.min.js',
      libraryTarget: 'var',
      library: 'Grommet'
    },
    resolve: {
      alias: {
        'grommet': path.resolve(__dirname, 'src/js')
      },
      modulesDirectories: ['node_modules', 'src/js', 'src/scss']
    },
    externals: {
      'react': 'React',
      'react-dom': 'ReactDOM',
      'react-intl': 'ReactIntl',
      'react-addons-transition-group': 'React.addons.TransitionGroup'
    }
  },
  distPreprocess: ['generate-index-icons', 'generate-icon-messages', 'dist-css'],
  testPaths: [
    '__tests__',
    '!__tests__/utils/',
    '!__tests__/mocks/'
  ],
  preCommitTasks: ['generate-icons', 'jslint', 'scsslint', 'test']
};
<|endoftext|>


<commit_before>exports.BattlePokedex = {
        latias: {
                inherit: true,
                types: ["Dragon","Fairy"]
                baseStats: {hp:90,atk:65,def:100,spa:105,spd:140,spe:110}
       },
       flygon: {
                inherit: true,
                types: ["Bug","Ground"]
                abilites: {0:"Levtitate",1:"Compoundeyes",H:"Tinted Lens"}
                baseStats: {hp:80,atk:110,def:100,spa:80,spd:95,spe:105}
       },
       mew: {
                inherit: true,
                types: ["Psychic","Fairy"]
                abilites: {0:"Regenerator",H:"Synchronoise"}
       },
       celebi: {
                inherit: true,
                types: ["Grass","Fairy"]
       },
       jirachi: {
                inherit: true,
                types: ["Steel","Fairy"]
                abilites: {0:"Synchronoise",H:"Illuminate"}
       },
       manaphy: {
                inherit: true,
                types: ["Water","Fairy"]
                abilites: {0:"Hydraition",H:"Swift Swim"}
       },
       shaymin: {
                inherit: true,
                types: ["Grass","Normal"]
                abilites: {0:"Unaware"}
       },
       meloetta: {
                inherit: true,
                abilites: {0:"Stance Change"}
       },
       victini: {
                inherit: true,
                types: ["Fire","Fairy"]
                abilites: {0:"Victory Star",H:"Pixilate"}
       },
       abomasnowmega: {
                inherit: true,
                abilites: {0:"Analytic"}
                baseStats: {hp:100,atk:140,def:90,spa:165,spd:95,spe:30}
       },
       garchompmega: {
                inherit: true,
                types: ["Dragon","Fighting"]
                abilites: {0:"Tough Claws"}
                baseStats: {hp:110,atk:175,def:110,spa:110,spd:100,spe:98}
       },
       heracrossmega: {
                inherit: true,
                abilites: {0:"Scrappy"}
                baseStats: {hp:80,atk:165,def:90,spa:85,spd:90,spe:100}
       },
       gyaradosmega: {
                inherit: true,
                abilites: {0:"Moxie"}
                baseStats: {hp:100,atk:165,def:90,spa:85,spd:110,spe:100}
       },
       flygon: {
                inherit: true,
                types: ["Bug","Ground"]
                abilites: {0:"Levtitate",1:"Compoundeyes",H:"Tinted Lens"}
                baseStats: {hp:80,atk:110,def:100,spa:80,spd:95,spe:105}
       },
       xerneas:{num:716,species:"Xerneas",types:["Fairy"],gender:"N",baseStats:{hp:126,atk:131,def:95,spa:131,spd:98,spe:99},abilities:{0:"Fairy Aura"},heightm:3,weightkg:215,color:"",eggGroups:["No Eggs"],otherFormes:["xerneasmega"]},
yveltal:{num:717,species:"Yveltal",types:["Dark","Flying"],gender:"N",baseStats:{hp:126,atk:131,def:95,spa:131,spd:98,spe:99},abilities:{0:"Dark Aura"},heightm:5.8,weightkg:203,color:"",eggGroups:["No Eggs"],otherFormes:["yveltalmega"]},
       xerneasmega:{num:716,species:"Xerneas-Mega",baseSpecies:"Xerneas",forme:"Mega",formeLetter:"M",types:["Fairy","Grass"],gender:"N",baseStats:{hp:165,atk:60,def:135,spa:115,spd:165,spe:105},abilities:{0:"Natural Cure"},heightm:3,weightkg:215,color:"",eggGroups:["No Eggs"]},
       yveltalmega:{num:717,species:"Yveltal-Mega",baseSpecies:"Yveltal",forme:"Mega",formeLetter:"M",types:["Dark","Flying"],gender:"N",baseStats:{hp:105,atk:185,def:90,spa:175,spd:85,spe:115},abilities:{0:"Gale Wings"},heightm:5.8,weightkg:203,color:"",eggGroups:["No Eggs"]},
};
<commit_msg>fix something<commit_after>exports.BattlePokedex = {
        latias: {
                inherit: true,
                types: ["Dragon","Fairy"]
                baseStats: {hp:90,atk:65,def:100,spa:105,spd:140,spe:110}
       },
       flygon: {
                inherit: true,
                types: ["Bug","Ground"]
                abilites: {0:"Levtitate",1:"Compoundeyes",H:"Tinted Lens"}
                baseStats: {hp:80,atk:110,def:100,spa:80,spd:95,spe:105}
       },
       mew: {
                inherit: true,
                types: ["Psychic","Fairy"]
                abilites: {0:"Regenerator",H:"Synchronoise"}
       },
       celebi: {
                inherit: true,
                types: ["Grass","Fairy"]
       },
       jirachi: {
                inherit: true,
                types: ["Steel","Fairy"]
                abilites: {0:"Synchronoise",H:"Illuminate"}
       },
       manaphy: {
                inherit: true,
                types: ["Water","Fairy"]
                abilites: {0:"Hydraition",H:"Swift Swim"}
       },
       shaymin: {
                inherit: true,
                types: ["Grass","Normal"]
                abilites: {0:"Unaware"}
       },
       meloetta: {
                inherit: true,
                abilites: {0:"Stance Change"}
       },
       victini: {
                inherit: true,
                types: ["Fire","Fairy"]
                abilites: {0:"Victory Star",H:"Pixilate"}
       },
       abomasnowmega: {
                inherit: true,
                abilites: {0:"Analytic"}
                baseStats: {hp:100,atk:140,def:90,spa:165,spd:95,spe:30}
       },
       garchompmega: {
                inherit: true,
                types: ["Dragon","Fighting"]
                abilites: {0:"Tough Claws"}
                baseStats: {hp:110,atk:175,def:110,spa:110,spd:100,spe:98}
       },
       heracrossmega: {
                inherit: true,
                abilites: {0:"Scrappy"}
                baseStats: {hp:80,atk:165,def:90,spa:85,spd:90,spe:100}
       },
       gyaradosmega: {
                inherit: true,
                abilites: {0:"Moxie"}
                baseStats: {hp:100,atk:165,def:90,spa:85,spd:110,spe:100}
       },
       flygon: {
                inherit: true,
                types: ["Bug","Ground"]
                abilites: {0:"Levtitate",1:"Compoundeyes",H:"Tinted Lens"}
                baseStats: {hp:80,atk:110,def:100,spa:80,spd:95,spe:105}
       },
       xerneas:{num:716,species:"Xerneas",types:["Fairy"],gender:"N",baseStats:{hp:126,atk:131,def:95,spa:131,spd:98,spe:99},abilities:{0:"Fairy Aura"},heightm:3,weightkg:215,color:"",eggGroups:["No Eggs"],otherFormes:["xerneasmega"]},
       yveltal:{num:717,species:"Yveltal",types:["Dark","Flying"],gender:"N",baseStats:{hp:126,atk:131,def:95,spa:131,spd:98,spe:99},abilities:{0:"Dark Aura"},heightm:5.8,weightkg:203,color:"",eggGroups:["No Eggs"],otherFormes:["yveltalmega"]},
       xerneasmega:{num:716,species:"Xerneas-Mega",baseSpecies:"Xerneas",forme:"Mega",formeLetter:"M",types:["Fairy","Grass"],gender:"N",baseStats:{hp:165,atk:60,def:135,spa:115,spd:165,spe:105},abilities:{0:"Natural Cure"},heightm:3,weightkg:215,color:"",eggGroups:["No Eggs"]},
       yveltalmega:{num:717,species:"Yveltal-Mega",baseSpecies:"Yveltal",forme:"Mega",formeLetter:"M",types:["Dark","Flying"],gender:"N",baseStats:{hp:105,atk:185,def:90,spa:175,spd:85,spe:115},abilities:{0:"Gale Wings"},heightm:5.8,weightkg:203,color:"",eggGroups:["No Eggs"]},
};
<|endoftext|>


<commit_before>// TODO only load tawkto if production
Meteor.startup(function() {

  // TODO dont have to load env each time, can store it in session?
  Meteor.call("getEnv", function(error, result) {
    if (error) {
      // abort abort, we don't have env ready?
      console.log('error from getEnv: ', error);
    } else {
      console.log('method call to getEnv result: ',result);
      // console.log('callback from getEnv, this: ',this);
      if (result.NODE_ENV != "production") {
        return;
      }
    }

    // <!--Start of Tawk.to Script-->
    // <script type="text/javascript">
    // var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
    (function(){
    var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
    s1.async=true;
    s1.src='https://embed.tawk.to/569317501df5fe345b098dc2/default';
    s1.charset='UTF-8';
    s1.setAttribute('crossorigin','*');
    s0.parentNode.insertBefore(s1,s0);
    })();
    // </script>
    // <!--End of Tawk.to Script-->

  });
});

// clear or show the tawk widget
function showTawk(toShow, countdown, foundTawk) {
  if (countdown < 0) return;
  if (typeof(Tawk_API) != "undefined" && Tawk_API.toggle) {
    if (toShow) {
      Tawk_API.toggle();
      Tawk_API.toggle();
      Tawk_API.showWidget();
      Tawk_API.showWidget();
    } else {
      Tawk_API.hideWidget();
      Tawk_API.hideWidget();
    }
    if (!foundTawk) {  // do yet another delay and another attempt
      Meteor.setTimeout(function() {
        showTawk(toShow, countdown-1, true);
      }, 600);
    }
  } else {
    Meteor.setTimeout(function() {
      showTawk(toShow, countdown-1, false);
    }, 300);
  }
}

// Only show tawk chat when route is "help"
// TODO make this configurable per user Settings
/*
Meteor.startup(function() {
  Meteor.autorun(function() {
    var routeName = FlowRouter.getRouteName(); // reactive
    if (routeName === "help") {
      showTawk(true, 1000);
    } else {
      showTawk(false, 1000);
    }
  });
});
 */

Session.setDefault('backgroundMainStyle1', true);
// Session.setDefault('notificationCount', 4);
/*
Meteor.setInterval(function(){
  var c = Math.floor(13 * Random.fraction() - 3);
  if (c > 0 ) {
    Session.set('notificationCount', c);
  } else {
    Session.set('notificationCount', "");
  }
}, 5000);
 */

Template.navNotifyCount.helpers({
  notifyCount: function () {
    // return Session.get('notificationCount');
    var c = Notifications.find().count();
    if (c > 0) {
      return c;
    } else {
      return '';
    }
  },
});

Template.navNotificationsList.helpers({
  notificationList: function() {
    // relies on the published messages filtering by targetUserId = this userId
    return Notifications.find({}, {sort: {dateTime: -1}, limit: 4});
  },
});

Template.navConnection.helpers({
  connectionStatus: function () {
    return Meteor.status();
  },
});

Template.navToggleBackground.events({
  'click #toggleBackground': function (event) {
    switchBackground();
  },
});

Template.navLogout.events({
  // TODO error handling on logout
  'click': function (event) {
    Accounts.logout();
  },
});

// Disable nav search input and button when route is search
Template.main.onRendered(function() {
  this.autorun(function() {
    var routeName = FlowRouter.getRouteName(); // reactive
    if (routeName === "search") {
      // clear and disable search input and button
      $('#navSearchText').val("");
      $('#navSearchText').attr('disabled','disabled');
      $('.navSearchButton').attr('disabled','disabled');
    } else {
      $('#navSearchText').attr('disabled', null);
      $('.navSearchButton').attr('disabled', null);
    }
  });
});

Template.navSearchForm.events({
  'submit': function (event) {
    // Prevent browser from restarting
    event.preventDefault();
    var queryParams = {};
    // search text into queryParams
    var text = event.target.navSearchText.value;
    if (text) queryParams['q'] = text;
    // pass search the context of which screen is on before searching
    if (FlowRouter.current().route.name != "search") queryParams['p'] = FlowRouter.current().route.name;
    FlowRouter.go("search", {}, queryParams);
    return false; // Prevent default form submit
  },
});

Template.navProfilePic.helpers({
  pathForProfile: function() {
    var params = {
      personId: Meteor.userId(),
    };
    var path = FlowRouter.path("profile", params);
    return path;
  },
});

function switchBackground() {
  if (Session.get('backgroundMainStyle1')) {
    $("#backgroundMain").removeClass("backgroundMainStyle1").addClass("backgroundMainStyle2");
    // $(window).resize(); // TODO is resize needed?
    Session.set('backgroundMainStyle1', false);
  } else {
    $("#backgroundMain").removeClass("backgroundMainStyle2").addClass("backgroundMainStyle1");
    // $(window).resize(); // TODO is resize needed?
    Session.set('backgroundMainStyle1', true);
  }
};
<commit_msg>Remove console log<commit_after>// TODO only load tawkto if production
Meteor.startup(function() {

  // TODO dont have to load env each time, can store it in session?
  Meteor.call("getEnv", function(error, result) {
    if (error) {
      // abort abort, we don't have env ready?
      console.log('error from getEnv: ', error);
    } else {
      // console.log('method call to getEnv result: ',result);
      // console.log('callback from getEnv, this: ',this);
      if (result.NODE_ENV != "production") {
        return;
      }
    }

    // <!--Start of Tawk.to Script-->
    // <script type="text/javascript">
    // var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
    (function(){
    var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
    s1.async=true;
    s1.src='https://embed.tawk.to/569317501df5fe345b098dc2/default';
    s1.charset='UTF-8';
    s1.setAttribute('crossorigin','*');
    s0.parentNode.insertBefore(s1,s0);
    })();
    // </script>
    // <!--End of Tawk.to Script-->

  });
});

// clear or show the tawk widget
function showTawk(toShow, countdown, foundTawk) {
  if (countdown < 0) return;
  if (typeof(Tawk_API) != "undefined" && Tawk_API.toggle) {
    if (toShow) {
      Tawk_API.toggle();
      Tawk_API.toggle();
      Tawk_API.showWidget();
      Tawk_API.showWidget();
    } else {
      Tawk_API.hideWidget();
      Tawk_API.hideWidget();
    }
    if (!foundTawk) {  // do yet another delay and another attempt
      Meteor.setTimeout(function() {
        showTawk(toShow, countdown-1, true);
      }, 600);
    }
  } else {
    Meteor.setTimeout(function() {
      showTawk(toShow, countdown-1, false);
    }, 300);
  }
}

// Only show tawk chat when route is "help"
// TODO make this configurable per user Settings
/*
Meteor.startup(function() {
  Meteor.autorun(function() {
    var routeName = FlowRouter.getRouteName(); // reactive
    if (routeName === "help") {
      showTawk(true, 1000);
    } else {
      showTawk(false, 1000);
    }
  });
});
 */

Session.setDefault('backgroundMainStyle1', true);
// Session.setDefault('notificationCount', 4);
/*
Meteor.setInterval(function(){
  var c = Math.floor(13 * Random.fraction() - 3);
  if (c > 0 ) {
    Session.set('notificationCount', c);
  } else {
    Session.set('notificationCount', "");
  }
}, 5000);
 */

Template.navNotifyCount.helpers({
  notifyCount: function () {
    // return Session.get('notificationCount');
    var c = Notifications.find().count();
    if (c > 0) {
      return c;
    } else {
      return '';
    }
  },
});

Template.navNotificationsList.helpers({
  notificationList: function() {
    // relies on the published messages filtering by targetUserId = this userId
    return Notifications.find({}, {sort: {dateTime: -1}, limit: 4});
  },
});

Template.navConnection.helpers({
  connectionStatus: function () {
    return Meteor.status();
  },
});

Template.navToggleBackground.events({
  'click #toggleBackground': function (event) {
    switchBackground();
  },
});

Template.navLogout.events({
  // TODO error handling on logout
  'click': function (event) {
    Accounts.logout();
  },
});

// Disable nav search input and button when route is search
Template.main.onRendered(function() {
  this.autorun(function() {
    var routeName = FlowRouter.getRouteName(); // reactive
    if (routeName === "search") {
      // clear and disable search input and button
      $('#navSearchText').val("");
      $('#navSearchText').attr('disabled','disabled');
      $('.navSearchButton').attr('disabled','disabled');
    } else {
      $('#navSearchText').attr('disabled', null);
      $('.navSearchButton').attr('disabled', null);
    }
  });
});

Template.navSearchForm.events({
  'submit': function (event) {
    // Prevent browser from restarting
    event.preventDefault();
    var queryParams = {};
    // search text into queryParams
    var text = event.target.navSearchText.value;
    if (text) queryParams['q'] = text;
    // pass search the context of which screen is on before searching
    if (FlowRouter.current().route.name != "search") queryParams['p'] = FlowRouter.current().route.name;
    FlowRouter.go("search", {}, queryParams);
    return false; // Prevent default form submit
  },
});

Template.navProfilePic.helpers({
  pathForProfile: function() {
    var params = {
      personId: Meteor.userId(),
    };
    var path = FlowRouter.path("profile", params);
    return path;
  },
});

function switchBackground() {
  if (Session.get('backgroundMainStyle1')) {
    $("#backgroundMain").removeClass("backgroundMainStyle1").addClass("backgroundMainStyle2");
    // $(window).resize(); // TODO is resize needed?
    Session.set('backgroundMainStyle1', false);
  } else {
    $("#backgroundMain").removeClass("backgroundMainStyle2").addClass("backgroundMainStyle1");
    // $(window).resize(); // TODO is resize needed?
    Session.set('backgroundMainStyle1', true);
  }
};
<|endoftext|>


<commit_before>(function (env) {
    "use strict";
    env.ddg_spice_vrc_teams = function(team_data) {
        if (!team_data || team_data.status !== 1 || team_data.size === 0 || team_data.result[0].is_registered === "0") {
            return Spice.failed('vrc_teams');
        }

        //infobox data for statistics
        function infobox(ranking, skills){
            var l = []
            if (ranking.status === 1 && ranking.size > 0){
                l.push({heading: 'Qualifying Matches'});
                var total_wins = 0,
                    total_losses = 0,
                    total_ties = 0,
                    total_ccwm = 0.0,
                    max_score = 0,
                    latest = ranking.result[0];

                $.each(ranking.result, function(ind, i){
                    total_wins += parseInt(i.wins);
                    total_losses += parseInt(i.losses);
                    total_ties += parseInt(i.ties);
                    total_ccwm += parseFloat(i.ccwm);
                    max_score = Math.max(max_score, parseInt(i.max_score));
                });

                var total_wlt = total_wins + '-' + total_losses + '-' + total_ties;
                var latest_wlt = latest.wins + '-' + latest.losses + '-' + latest.ties;
                l.push({label: 'Total W-L-T', value: total_wlt});
                l.push({label: 'Latest W-L-T', value: latest_wlt});
                l.push({label: 'Greatest Match Score', value: max_score});

                var average_ccwm = total_ccwm / ranking.size;
                l.push({label: 'Average CCWM', value: average_ccwm.toFixed(2)});
                l.push({label: 'Latest CCWM', value: parseFloat(latest.ccwm).toFixed(2)});
            }
            if (skills.status === 1 && skills.size > 0){
                l.push({heading: 'Best Skills'});
                var best_robot = 0,
                    best_programming = 0;

                $.each(skills.result, function(ind, i){
                    if (i.type === "0" && parseInt(i.score) > best_robot){
                        best_robot = parseInt(i.score);
                    }
                    if (i.type === "1" && parseInt(i.score) > best_programming){
                        best_programming = parseInt(i.score);
                    }
                });

                l.push({label: 'Robot', value: best_robot});
                l.push({label: 'Programming', value: best_programming});
            }

            console.log(l);
            return l.length ? l : undefined;
        }

        //description data for team location and grade
        function description(team){
            return team.grade + ' team from ' + team.city + ', ' + team.region + ', ' + team.country;
        }

        var team = team_data.result[0], ranking_data, skills_data;

        Spice.add({
            id: "vrc_teams",
            name: "VRC Team",
            data: team,
            meta: {
                sourceName: "VexDB.io",
                sourceUrl: 'http://vexdb.io/teams/view/' + team.number,
                rerender: ['infoboxData']
            },
            normalize: function(item) {
                return {
                    title: item.team_name,
                    subtitle: item.program + ' Team ' + item.number + ' — ' + item.organisation,
                    description: description(item)
                    //infoboxData: infobox(ranking_data, skills_data)
                };
            },
            templates: {
                group: 'info',
                options: {
                    moreAt: true
                }
            },
            onItemShown: function(item){
                //the api splits the data up into multiple endpoints, fire them simultaneously
                $.when(
                    $.getJSON('/js/spice/vrc/rankings/' + team.number, function(res){
                        ranking_data = res;
                    }),
                    $.getJSON('/js/spice/vrc/skills/' + team.number, function(res){
                        skills_data = res;
                    })
                ).then(function(){
                    item.set({infoboxData: infobox(ranking_data, skills_data)});
                });
            }
        });
    };
}(this));
<commit_msg>VRCTeams: revert back to original with slow-displaying IA<commit_after>(function (env) {
    "use strict";
    env.ddg_spice_vrc_teams = function(team_data) {
        if (!team_data || team_data.status !== 1 || team_data.size === 0 || team_data.result[0].is_registered === "0") {
            return Spice.failed('vrc_teams');
        }

        //infobox data for statistics
        function infobox(ranking, skills){
            var l = []
            if (ranking.status === 1 && ranking.size > 0){
                l.push({heading: 'Qualifying Matches'});
                var total_wins = 0,
                    total_losses = 0,
                    total_ties = 0,
                    total_ccwm = 0.0,
                    max_score = 0,
                    latest = ranking.result[0];

                $.each(ranking.result, function(ind, i){
                    total_wins += parseInt(i.wins);
                    total_losses += parseInt(i.losses);
                    total_ties += parseInt(i.ties);
                    total_ccwm += parseFloat(i.ccwm);
                    max_score = Math.max(max_score, parseInt(i.max_score));
                });

                var total_wlt = total_wins + '-' + total_losses + '-' + total_ties;
                var latest_wlt = latest.wins + '-' + latest.losses + '-' + latest.ties;
                l.push({label: 'Total W-L-T', value: total_wlt});
                l.push({label: 'Latest W-L-T', value: latest_wlt});
                l.push({label: 'Greatest Match Score', value: max_score});

                var average_ccwm = total_ccwm / ranking.size;
                l.push({label: 'Average CCWM', value: average_ccwm.toFixed(2)});
                l.push({label: 'Latest CCWM', value: parseFloat(latest.ccwm).toFixed(2)});
            }
            if (skills.status === 1 && skills.size > 0){
                l.push({heading: 'Best Skills'});
                var best_robot = 0,
                    best_programming = 0;

                $.each(skills.result, function(ind, i){
                    if (i.type === "0" && parseInt(i.score) > best_robot){
                        best_robot = parseInt(i.score);
                    }
                    if (i.type === "1" && parseInt(i.score) > best_programming){
                        best_programming = parseInt(i.score);
                    }
                });

                l.push({label: 'Robot', value: best_robot});
                l.push({label: 'Programming', value: best_programming});
            }

            return l.length ? l : undefined;
        }

        //description data for team location and grade
        function description(team){
            return team.grade + ' team from ' + team.city + ', ' + team.region + ', ' + team.country;
        }

        var team = team_data.result[0], ranking_data, skills_data;

        //the api splits the data up into multiple endpoints, fire them simultaneously
        $.when(
            $.getJSON('/js/spice/vrc/rankings/' + team.number, function(res){
                ranking_data = res;
            }),
            $.getJSON('/js/spice/vrc/skills/' + team.number, function(res){
                skills_data = res;
            })
        ).then(function(){
            Spice.add({
                id: "vrc_teams",
                name: "VRC Team",
                data: team,
                meta: {
                    sourceName: "VexDB.io",
                    sourceUrl: 'http://vexdb.io/teams/view/' + team.number
                },
                normalize: function(item) {
                    return {
                        title: item.team_name,
                        subtitle: item.program + ' Team ' + item.number + ' — ' + item.organisation,
                        description: description(item),
                        infoboxData: infobox(ranking_data, skills_data)
                    };
                },
                templates: {
                    group: 'info',
                    options: {
                        moreAt: true
                    }
                }
            });
        }, function(){
            //one of these requests failed
            Spice.failed('vrc_teams');
        });
    };
}(this));
<|endoftext|>


<commit_before>/**
 * Migrates the database from one version to another.
 */
function migrateStorage() {
	var extensionVersion = getExtensionVersion().major;

	getStorageVersion(function(storageVersion) {
		if (extensionVersion != storageVersion) {
			console.log("Extension and storage versions are not equal", extensionVersion, storageVersion);
			setStorageVersion(extensionVersion);

			if (storageVersion == 1) {
				if (extensionVersion.major == 2) {
					// Migrate from a database from 1.x.x to 2.x.x
					migrate_1_to_2(function() {
						console.log("Migration from 1.x.x to 2.x.x complete");
					});
				}
			}
		}
	});
}<commit_msg>Fix version check for extension version.<commit_after>/**
 * Migrates the database from one version to another.
 */
function migrateStorage() {
	var extensionVersion = getExtensionVersion().major;

	getStorageVersion(function(storageVersion) {
		if (extensionVersion != storageVersion) {
			console.log("Extension and storage versions are not equal", extensionVersion, storageVersion);
			setStorageVersion(extensionVersion);

			if (storageVersion == 1) {
				if (extensionVersion == 2) {
					// Migrate from a database from 1.x.x to 2.x.x
					migrate_1_to_2(function() {
						console.log("Migration from 1.x.x to 2.x.x complete");
					});
				}
			}
		}
	});
}<|endoftext|>


<commit_before>define( function( require ) {
    'use strict';

    var PreferencesManager = brackets.getModule( 'preferences/PreferencesManager' ),
        Defaults = require( 'modules/Defaults' ),
        preferences = PreferencesManager.getExtensionPrefs( 'mikaeljorhult.bracketsAutoprefixer' );

    // Define preferences.
    preferences.definePreference( 'enabled', 'boolean', false );
    preferences.definePreference( 'onChange', 'boolean', false );
    preferences.definePreference( 'visualCascade', 'boolean', false );
    preferences.definePreference( 'browsers', 'object', Defaults.browsers );

    /**
     * Get value of preference.
     */
    function get( property ) {
        return preferences.get( property );
    }

    /**
     * Set value of preference.
     */
    function set( property, value ) {
        return preferences.set( property, value );
    }

    /**
     * Save preferences.
     */
    function save() {
        return preferences.save();
    }

    // Return module object.
    return {
        defaults: Defaults,
        get: get,
        set: set,
        save: save
    };
} );<commit_msg>Cast browsers preference as array.<commit_after>define( function( require ) {
    'use strict';

    var PreferencesManager = brackets.getModule( 'preferences/PreferencesManager' ),
        Defaults = require( 'modules/Defaults' ),
        preferences = PreferencesManager.getExtensionPrefs( 'mikaeljorhult.bracketsAutoprefixer' );

    // Define preferences.
    preferences.definePreference( 'enabled', 'boolean', false );
    preferences.definePreference( 'onChange', 'boolean', false );
    preferences.definePreference( 'visualCascade', 'boolean', false );
    preferences.definePreference( 'browsers', 'array', Defaults.browsers );

    /**
     * Get value of preference.
     */
    function get( property ) {
        return preferences.get( property );
    }

    /**
     * Set value of preference.
     */
    function set( property, value ) {
        return preferences.set( property, value );
    }

    /**
     * Save preferences.
     */
    function save() {
        return preferences.save();
    }

    // Return module object.
    return {
        defaults: Defaults,
        get: get,
        set: set,
        save: save
    };
} );<|endoftext|>


<commit_before>"use strict";

const { TABLES, COLUMNS, TYPES, ROLES } = require("../../lib/schema");
let constants = require("../../lib/constants"),
	Counter = require("../../lib/counter"),
	{ bus, cache } = require("../../core");

bus.on("setstate", (changes, next) => {
	if(!changes.entities) return;

	let counter = new Counter();

	for (let id in changes.entities) {
		let entity = changes.entities[id];

		// 1. Increment children counts on parents
		if (
			entity.type === constants.TYPE_TEXT ||
			entity.type === constants.TYPE_THREAD
		) {
			let inc;

			if (entity.createtime) {
				inc = 1;
			} else if (entity.deletetime) {
				inc = -1;
			} else {
				continue;
			}

			let parent = changes.entities[entity.parents[0][0]] || {};

			parent.counts = parent.counts || {};
			parent.counts.children = inc;
			parent.id = entity.parents[0][0];
			parent.type = ( entity.type === constants.TYPE_TEXT ) ?
				constants.TYPE_THREAD : constants.TYPE_ROOM;
			changes.entities[entity.parents[0][0]] = parent;

			// 2. Increment text/thread count of user

			let user = changes.entities[entity.creator] || {};
			user.counts = user.counts || {};
			user.counts[TABLES[entity.type]] = inc;
			user.id = entity.creator;
			changes.entities[entity.creator] = user;
		}

		 // 3. Increment related counts on items

		if (
			entity.type === constants.TYPE_TEXTREL ||
			entity.type === constants.TYPE_THREADREL ||
			entity.type === constants.TYPE_ROOMREL ||
			entity.type === constants.TYPE_PRIVREL ||
			entity.type === constants.TYPE_TOPICREL
		) {
			let item = changes.entities[entity.item] || {};

			item.counts = item.counts || {};

			if (entity.__op__ && entity.__op__.role && entity.__op__.roles[0] === "union") {
				let rem = entity.__op__.roles[0].slice(1);
				rem.forEach((role) => {
					if (ROLES[role]) {
						item.counts[ROLES[role]] = -1
					}
				});
			}

			entity.roles.forEach((role) => {
				if (ROLES[role]) {
					item.counts[ROLES[role]] = 1;
				}
			})

			item.id = entity.item;

			switch(entity.type) {
				case constants.TYPE_TEXTREL:
					item.type = constants.TYPE_TEXT;
					break;
				case constants.TYPE_THREADREL:
					item.type = constants.TYPE_THREAD;
					break;
				case constants.TYPE_ROOMREL:
					item.type = constants.TYPE_ROOM;
					break;
				case constants.TYPE_PRIVREL:
					item.type = constants.TYPE_PRIV;
					break;
				case constants.TYPE_TOPICREL:
					item.type = constants.TYPE_TOPIC;
					break;
			}

			changes.entities[entity.item] = item;
		}
	}
	next();
}, "modifier");
<commit_msg>modified count module<commit_after>"use strict";

const { TABLES, COLUMNS, TYPES, ROLES } = require("../../lib/schema");
let constants = require("../../lib/constants"),
	{ bus, cache } = require("../../core");

bus.on("setstate", (changes, next) => {
	if(!changes.entities) return next();

	for (let id in changes.entities) {
		let entity = changes.entities[id];

		// 1. Increment children counts on parents
		if (
			entity.type === constants.TYPE_TEXT ||
			entity.type === constants.TYPE_THREAD
		) {
			let inc;

			if (entity.createtime) {
				inc = 1;
			} else if (entity.deletetime) {
				inc = -1;
			} else {
				continue;
			}

			let parent = changes.entities[entity.parents[0][0]] || {};

			parent.counts = parent.counts || {};
			parent.counts.children = inc;
			parent.id = entity.parents[0][0];
			parent.type = ( entity.type === constants.TYPE_TEXT ) ?
				constants.TYPE_THREAD : constants.TYPE_ROOM;
			changes.entities[entity.parents[0][0]] = parent;

			// 2. Increment text/thread count of user

			let user = changes.entities[entity.creator] || {};
			user.counts = user.counts || {};
			user.counts[TABLES[entity.type]] = inc;
			user.id = entity.creator;
			changes.entities[entity.creator] = user;
		}

		 // 3. Increment related counts on items

		if (
			entity.type === constants.TYPE_TEXTREL ||
			entity.type === constants.TYPE_THREADREL ||
			entity.type === constants.TYPE_ROOMREL ||
			entity.type === constants.TYPE_PRIVREL ||
			entity.type === constants.TYPE_TOPICREL
		) {
			let item = changes.entities[entity.item] || {};

			item.counts = item.counts || {};

			if (entity.__op__ && entity.__op__.role && entity.__op__.roles[0] === "union") {
				let rem = entity.__op__.roles[0].slice(1);
				rem.forEach((role) => {
					if (ROLES[role]) {
						item.counts[ROLES[role]] = -1
					}
				});
			}

			entity.roles.forEach((role) => {
				if (ROLES[role]) {
					item.counts[ROLES[role]] = 1;
				}
			})

			item.id = entity.item;

			switch(entity.type) {
				case constants.TYPE_TEXTREL:
					item.type = constants.TYPE_TEXT;
					break;
				case constants.TYPE_THREADREL:
					item.type = constants.TYPE_THREAD;
					break;
				case constants.TYPE_ROOMREL:
					item.type = constants.TYPE_ROOM;
					break;
				case constants.TYPE_PRIVREL:
					item.type = constants.TYPE_PRIV;
					break;
				case constants.TYPE_TOPICREL:
					item.type = constants.TYPE_TOPIC;
					break;
			}
			changes.entities[entity.item] = item;
		}
	}
	next();
}, "modifier");
<|endoftext|>