<commit_before>(function(Ractive, CodeMirror, _, tungsten) {
  'use strict';

  Ractive.DEBUG = false;

  var runtimeObjects = [];
  tungsten.View.prototype._initialize = tungsten.View.prototype.initialize;
  tungsten.View.prototype.initialize = function(opts) {
    if (!opts.parentView && !this.tutorialObj) {
      runtimeObjects.push(this);
    }
    this._initialize(opts);
  };
  tungsten.Model.prototype._initialize = tungsten.Model.prototype.initialize;
  tungsten.Model.prototype.initialize = function(attributes, opts) {
    opts = opts || {};
    if (!opts.parent && !opts.collection && !this.tutorialObj) {
      runtimeObjects.push(this);
    }
    this._initialize(opts);
  };
  tungsten.Collection.prototype._initialize = tungsten.Collection.prototype.initialize;
  tungsten.Collection.prototype.initialize = function(models, opts) {
    opts = opts || {};
    if (!opts.parent && !this.tutorialObj) {
      runtimeObjects.push(this);
    }
    this._initialize(opts);
  };

  var View = tungsten.View.extend({
    initDebug: _.noop,
    tutorialObj: true
  });
  var Model = tungsten.Model.extend({
    initDebug: _.noop,
    tutorialObj: true
  });
  var Collection = tungsten.Collection.extend({
    initDebug: _.noop,
    tutorialObj: true
  });
  var ComponentWidget = tungsten.ComponentWidget;

  // Code Mirror Extensions and options
  CodeMirror.defineMode('mustache', function(config, parserConfig) {
    var mustacheOverlay = {
      token: function(stream) {
        var ch;
        if (stream.match('{{')) {
          while ((ch = stream.next()) != null) {
            if (ch == '}' && stream.next() == '}') {
              stream.eat('}');
              return 'mustache';
            }
          }
        }
        while (stream.next() != null && !stream.match('{{', false)) {
        }
        return null;
      }
    };
    return CodeMirror.overlayMode(CodeMirror.getMode(config, parserConfig.backdrop || 'text/html'), mustacheOverlay);
  });

  var codeOptions = {
    lineNumbers: true,
    lineWrapping: true,
    extraKeys: {
      'Ctrl-Alt-Q': function(cm) { cm.foldCode(cm.getCursor()); },
      'Ctrl-Alt-F': function(cm) {
        cm.operation(function() {
          for (var l = cm.firstLine(); l <= cm.lastLine(); ++l) {
            cm.foldCode({
              line: l,
              ch: 0
            }, null, 'fold');
          }
        });
      },
      'Ctrl-Alt-U': function(cm) {
        cm.operation(function() {
          for (var l = cm.firstLine(); l <= cm.lastLine(); ++l) {
            cm.foldCode({
              line: l,
              ch: 0
            }, null, 'unfold');
          }
        });
      }
    },
    foldGutter: true,
    gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter']
  };

  // Views and Template
  var rawTemplates = {
    app: '
 {{#tutorial}}

 {{#steps}}
{{{index}}}
 {{/steps}}
 <button class="pure-button js-run run" id="run">Run</button>{{#step}}

{{name}}

{{{description_html}}}
 {{/step}}

{{{template}}}

{{{js}}}
 {{/tutorial}}
',
    codeMirror: ''
  };
  var compiledTemplates = tungsten._template.compileTemplates(rawTemplates);

  var CodeMirrorComponent = {
    View: View.extend({
      events: {
        'keyup': 'update',
        'input': 'update'
      },
      postInitialize: function() {
        this.listenTo(this.model, 'change:value', function(model, value) {
          this.codeMirror.setValue(value);
        });
        this.listenTo(this.model, 'change:highlights', function(model, value) {
          var codeMirror = this.codeMirror;
          _.each(value, function(highlight) {
            codeMirror.markText(highlight.start, highlight.end, {
              className: 'styled-background',
              clearOnEnter: true
            });
          });
        });
      },
      update: function() {
        this.model.updateValue(this.codeMirror.getValue());
      },
      postRender: function() {
        var self = this;
        if (!this.codeMirror) {
          setTimeout(function() {
            self.codeMirror = CodeMirror(self.el, self.model.attributes);
          });
        }
      }
    }, {debugName: 'CodeMirrorComponentView'}),
    Model: Model.extend({
      exposedEvents: ['change'],
      updateValue: function(val) {
        this.set('value', val, {silent: true});
        this.trigger('change', this);
      },
      serialize: function(data) {
        return data.value;
      }
    }, {debugName: 'CodeMirrorComponentModel'}),
    template: compiledTemplates.codeMirror,
    constructor: function(data, options) {
      if (data && data.constructor === ComponentWidget) {
        return data;
      }
      var component = new ComponentWidget(
        CodeMirrorComponent.View,
        new CodeMirrorComponent.Model(data),
        CodeMirrorComponent.template,
        options
      );

      return component;
    }
  };

  var StepSelectView = View.extend({
    events: {
      click: function() {
        this.model.trigger('selectStep', this.model);
      }
    }
  });
  var AppView = View.extend({
    events: {
      'click .js-run': 'run',
      'keydown': 'handleKeydown'
    },
    handleKeydown: function(e) {
      // shift + enter
      if (e.shiftKey && e.which === 13) {
        this.run();
        return false;
      }
      // ctrl + s
      if (e.ctrlKey && e.which === 83) {
        this.run();
        return false;
      }
      // meta + s
      if (e.metaKey && e.which === 83) {
        this.run();
        return false;
      }
    },
    run: function() {
      var newLines = /\n/g;
      var boilerplate = 'var rawTemplates = { app_view: \'' + this.model.get('template').doSerialize().replace(newLines, '') + '\' };var compiledTemplates = tungsten._template.compileTemplates(rawTemplates);';
      var evalNoContext = eval.bind(null);
      // Destroy any views that were created in the last run to ensure a fresh runtime
      _.invoke(runtimeObjects, 'destroy');
      runtimeObjects = [];
      document.getElementById('app').innerHTML = '';
      try {
        evalNoContext(boilerplate + '\n;' + this.model.get('js').doSerialize());
      } catch (e) {
        document.getElementById('app').innerHTML = '
ERROR: ' + e.toString() + '';
      }
    },
    toggleFold: function(cm, fold) {
      cm.operation(function() {
        for (var l = cm.firstLine(); l <= cm.lastLine(); ++l) {
          cm.foldCode({line: l, ch: 0}, null, fold ? 'fold' : unfold);
        }
      });
    },
    postInitialize: function() {
      var self = this;
      var debouncedRun = _.debounce(this.run, 200);
      this.listenTo(this.model, 'change:js change:template', debouncedRun);
      this.listenTo(this.model.get('tutorials'), 'selectTutorial', _.debounce(function(tutorialName) {
        var tutorial = self.model.get('tutorials').where({name: tutorialName})[0];
        self.model.unset('step');
        self.model.unset('tutorial');

        self.model.get('tutorials').each(function(tutorials) {
          tutorials.set('selected', false);
        });
        tutorial.set('selected', true);

        self.model.set('tutorial', tutorial.toJSON());
        self.listenTo(self.model.get('tutorial').get('steps'), 'selectStep', function(s) {
          self.model.get('tutorial').get('steps').each(function(step) {
            step.set('selected', false);
          });
          s.set('selected', true);
          self.model.get('tutorial').set('step', s);
          var appEl = document.getElementById('app');
          if (appEl) {
            appEl.innerHTML = '';
          }
        });
        if (self.model.get('tutorial').get('steps')) {
          // Start at the first step
          self.model.get('tutorial').get('steps').trigger('selectStep', self.model.get('tutorial').get('steps').at(0));
        } else {
          console.log('tutorial has no steps set');
        }

      }, 0));
      // Start with the first tutorial open
      this.model.get('tutorials').trigger('selectTutorial', this.model.get('tutorials').at(0).get('name'));
    },
    childViews: {
      'js-step-select': StepSelectView
    }
  });

  // Models and Collections
  var TutorialModel = Model.extend({
    derived: {
      url_name: {
        deps: ['name'],
        fn: function() {
          return encodeURI(this.get('name'));
        }
      }
    },
    relations: {
      steps: Collection.extend({
        model: Model.extend({
          defaults: {
            selected: false
          }
        })
      })
    }
  });
  var TutorialCollection = Collection.extend({
    model: TutorialModel
  });
  var AppModel = Model.extend({
    defaults: {
      js: _.extend({ mode: 'javascript', value: '' }, codeOptions),
      template: _.extend({ mode: 'mustache', value: '' }, codeOptions)
    },
    relations: {
      js: CodeMirrorComponent.constructor,
      template: CodeMirrorComponent.constructor,
      tutorials: TutorialCollection,
      tutorial: TutorialModel
    },
    postInitialize: function() {
      this.listenTo(this, 'change:tutorial change:tutorial:step', function() {
        this.get('js').set({
          value: this.getDeep('tutorial:step:js') || '',
          highlights: this.getDeep('tutorial:step:js_highlights') || []
        });
        this.get('template').set({
          value: this.getDeep('tutorial:step:template') || '',
          highlights: this.getDeep('tutorial:step:template_highlights') || []
        });
      });
    }
  });
  var appModel = new AppModel(window.data);

  // Start app
  var app = new AppView({
    el: document.getElementById('appwrapper'),
    template: compiledTemplates.app,
    model: appModel,
    dynamicInitialize: true
  });
  window.app = app;

  if (!tungsten.Backbone.history.started) {
    var Router = tungsten.Backbone.Router.extend({
      routes: {
        '*tutorialName': 'selectTutorial'
      },
      selectTutorial: function(tutorialName) {
        if (tutorialName) {
          appModel.get('tutorials').trigger('selectTutorial', tutorialName);
        }
      }
    });
    new Router();
    tungsten.Backbone.history.start();
  }

})(Ractive, CodeMirror, _, tungsten);
<commit_msg>Nested models aren't destroying right, so destroy them all individually<commit_after>(function(Ractive, CodeMirror, _, tungsten) {
  'use strict';

  Ractive.DEBUG = false;

  var runtimeObjects = [];
  tungsten.View.prototype._initialize = tungsten.View.prototype.initialize;
  tungsten.View.prototype.initialize = function(opts) {
    if (!opts.parentView && !this.tutorialObj) {
      runtimeObjects.push(this);
    }
    this._initialize(opts);
  };
  tungsten.Model.prototype._initialize = tungsten.Model.prototype.initialize;
  tungsten.Model.prototype.initialize = function(attributes, opts) {
    opts = opts || {};
    if (!this.tutorialObj) {
      runtimeObjects.push(this);
    }
    this._initialize(opts);
  };
  tungsten.Collection.prototype._initialize = tungsten.Collection.prototype.initialize;
  tungsten.Collection.prototype.initialize = function(models, opts) {
    opts = opts || {};
    if (!this.tutorialObj) {
      runtimeObjects.push(this);
    }
    this._initialize(opts);
  };

  var View = tungsten.View.extend({
    initDebug: _.noop,
    tutorialObj: true
  });
  var Model = tungsten.Model.extend({
    initDebug: _.noop,
    tutorialObj: true
  });
  var Collection = tungsten.Collection.extend({
    initDebug: _.noop,
    tutorialObj: true
  });
  var ComponentWidget = tungsten.ComponentWidget;

  // Code Mirror Extensions and options
  CodeMirror.defineMode('mustache', function(config, parserConfig) {
    var mustacheOverlay = {
      token: function(stream) {
        var ch;
        if (stream.match('{{')) {
          while ((ch = stream.next()) != null) {
            if (ch == '}' && stream.next() == '}') {
              stream.eat('}');
              return 'mustache';
            }
          }
        }
        while (stream.next() != null && !stream.match('{{', false)) {
        }
        return null;
      }
    };
    return CodeMirror.overlayMode(CodeMirror.getMode(config, parserConfig.backdrop || 'text/html'), mustacheOverlay);
  });

  var codeOptions = {
    lineNumbers: true,
    lineWrapping: true,
    extraKeys: {
      'Ctrl-Alt-Q': function(cm) { cm.foldCode(cm.getCursor()); },
      'Ctrl-Alt-F': function(cm) {
        cm.operation(function() {
          for (var l = cm.firstLine(); l <= cm.lastLine(); ++l) {
            cm.foldCode({
              line: l,
              ch: 0
            }, null, 'fold');
          }
        });
      },
      'Ctrl-Alt-U': function(cm) {
        cm.operation(function() {
          for (var l = cm.firstLine(); l <= cm.lastLine(); ++l) {
            cm.foldCode({
              line: l,
              ch: 0
            }, null, 'unfold');
          }
        });
      }
    },
    foldGutter: true,
    gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter']
  };

  // Views and Template
  var rawTemplates = {
    app: '
 {{#tutorial}}

 {{#steps}}
{{{index}}}
 {{/steps}}
 <button class="pure-button js-run run" id="run">Run</button>{{#step}}

{{name}}

{{{description_html}}}
 {{/step}}

{{{template}}}

{{{js}}}
 {{/tutorial}}
',
    codeMirror: ''
  };
  var compiledTemplates = tungsten._template.compileTemplates(rawTemplates);

  var CodeMirrorComponent = {
    View: View.extend({
      events: {
        'keyup': 'update',
        'input': 'update'
      },
      postInitialize: function() {
        this.listenTo(this.model, 'change:value', function(model, value) {
          this.codeMirror.setValue(value);
        });
        this.listenTo(this.model, 'change:highlights', function(model, value) {
          var codeMirror = this.codeMirror;
          _.each(value, function(highlight) {
            codeMirror.markText(highlight.start, highlight.end, {
              className: 'styled-background',
              clearOnEnter: true
            });
          });
        });
      },
      update: function() {
        this.model.updateValue(this.codeMirror.getValue());
      },
      postRender: function() {
        var self = this;
        if (!this.codeMirror) {
          setTimeout(function() {
            self.codeMirror = CodeMirror(self.el, self.model.attributes);
          });
        }
      }
    }, {debugName: 'CodeMirrorComponentView'}),
    Model: Model.extend({
      exposedEvents: ['change'],
      updateValue: function(val) {
        this.set('value', val, {silent: true});
        this.trigger('change', this);
      },
      serialize: function(data) {
        return data.value;
      }
    }, {debugName: 'CodeMirrorComponentModel'}),
    template: compiledTemplates.codeMirror,
    constructor: function(data, options) {
      if (data && data.constructor === ComponentWidget) {
        return data;
      }
      var component = new ComponentWidget(
        CodeMirrorComponent.View,
        new CodeMirrorComponent.Model(data),
        CodeMirrorComponent.template,
        options
      );

      return component;
    }
  };

  var StepSelectView = View.extend({
    events: {
      click: function() {
        this.model.trigger('selectStep', this.model);
      }
    }
  });
  var AppView = View.extend({
    events: {
      'click .js-run': 'run',
      'keydown': 'handleKeydown'
    },
    handleKeydown: function(e) {
      // shift + enter
      if (e.shiftKey && e.which === 13) {
        this.run();
        return false;
      }
      // ctrl + s
      if (e.ctrlKey && e.which === 83) {
        this.run();
        return false;
      }
      // meta + s
      if (e.metaKey && e.which === 83) {
        this.run();
        return false;
      }
    },
    run: function() {
      var newLines = /\n/g;
      var boilerplate = 'var rawTemplates = { app_view: \'' + this.model.get('template').doSerialize().replace(newLines, '') + '\' };var compiledTemplates = tungsten._template.compileTemplates(rawTemplates);';
      var evalNoContext = eval.bind(null);
      // Destroy any views that were created in the last run to ensure a fresh runtime
      _.invoke(runtimeObjects, 'destroy');
      runtimeObjects = [];
      document.getElementById('app').innerHTML = '';
      try {
        evalNoContext(boilerplate + '\n;' + this.model.get('js').doSerialize());
      } catch (e) {
        document.getElementById('app').innerHTML = '
ERROR: ' + e.toString() + '';
      }
    },
    toggleFold: function(cm, fold) {
      cm.operation(function() {
        for (var l = cm.firstLine(); l <= cm.lastLine(); ++l) {
          cm.foldCode({line: l, ch: 0}, null, fold ? 'fold' : unfold);
        }
      });
    },
    postInitialize: function() {
      var self = this;
      var debouncedRun = _.debounce(this.run, 200);
      this.listenTo(this.model, 'change:js change:template', debouncedRun);
      this.listenTo(this.model.get('tutorials'), 'selectTutorial', _.debounce(function(tutorialName) {
        var tutorial = self.model.get('tutorials').where({name: tutorialName})[0];
        self.model.unset('step');
        self.model.unset('tutorial');

        self.model.get('tutorials').each(function(tutorials) {
          tutorials.set('selected', false);
        });
        tutorial.set('selected', true);

        self.model.set('tutorial', tutorial.toJSON());
        self.listenTo(self.model.get('tutorial').get('steps'), 'selectStep', function(s) {
          self.model.get('tutorial').get('steps').each(function(step) {
            step.set('selected', false);
          });
          s.set('selected', true);
          self.model.get('tutorial').set('step', s);
          var appEl = document.getElementById('app');
          if (appEl) {
            appEl.innerHTML = '';
          }
        });
        if (self.model.get('tutorial').get('steps')) {
          // Start at the first step
          self.model.get('tutorial').get('steps').trigger('selectStep', self.model.get('tutorial').get('steps').at(0));
        } else {
          console.log('tutorial has no steps set');
        }

      }, 0));
      // Start with the first tutorial open
      this.model.get('tutorials').trigger('selectTutorial', this.model.get('tutorials').at(0).get('name'));
    },
    childViews: {
      'js-step-select': StepSelectView
    }
  });

  // Models and Collections
  var TutorialModel = Model.extend({
    derived: {
      url_name: {
        deps: ['name'],
        fn: function() {
          return encodeURI(this.get('name'));
        }
      }
    },
    relations: {
      steps: Collection.extend({
        model: Model.extend({
          defaults: {
            selected: false
          }
        })
      })
    }
  });
  var TutorialCollection = Collection.extend({
    model: TutorialModel
  });
  var AppModel = Model.extend({
    defaults: {
      js: _.extend({ mode: 'javascript', value: '' }, codeOptions),
      template: _.extend({ mode: 'mustache', value: '' }, codeOptions)
    },
    relations: {
      js: CodeMirrorComponent.constructor,
      template: CodeMirrorComponent.constructor,
      tutorials: TutorialCollection,
      tutorial: TutorialModel
    },
    postInitialize: function() {
      this.listenTo(this, 'change:tutorial change:tutorial:step', function() {
        this.get('js').set({
          value: this.getDeep('tutorial:step:js') || '',
          highlights: this.getDeep('tutorial:step:js_highlights') || []
        });
        this.get('template').set({
          value: this.getDeep('tutorial:step:template') || '',
          highlights: this.getDeep('tutorial:step:template_highlights') || []
        });
      });
    }
  });
  var appModel = new AppModel(window.data);

  // Start app
  var app = new AppView({
    el: document.getElementById('appwrapper'),
    template: compiledTemplates.app,
    model: appModel,
    dynamicInitialize: true
  });
  window.app = app;

  if (!tungsten.Backbone.history.started) {
    var Router = tungsten.Backbone.Router.extend({
      routes: {
        '*tutorialName': 'selectTutorial'
      },
      selectTutorial: function(tutorialName) {
        if (tutorialName) {
          appModel.get('tutorials').trigger('selectTutorial', tutorialName);
        }
      }
    });
    new Router();
    tungsten.Backbone.history.start();
  }

})(Ractive, CodeMirror, _, tungsten);
<|endoftext|>


<commit_before>exports.BattleScripts = {
  init: function() {
		// Everything learns sketch, you look at the name and tell me what I'm supposed to do :/
		this.modData.Learnsets.learnset.sketch = ['5L0'];
	}
};
<commit_msg>Update scripts.js<commit_after>exports.BattleScripts = {
        init: function() {
                for (var i in this.data.Learnsets) {
                        var learnset = this.data.Learnsets[i].learnset;
                        var sk = learnset.sketch || [];
                        if (!sk.length) {
                            this.modData('Learnsets', i).learnset.sketch = ["5E"];
                        }
                }
        }
};
<|endoftext|>


<commit_before>/*jslint browser: true*/
/*global $, lunr, Search, DOCUMENTATION_OPTIONS*/
(function ($, lunr, Search, DOCUMENTATION_OPTIONS) {
    "use strict";

    var store = Search.store,
        index = null,
        highlight = $("#ls_lunrsearch-highlight").value === "true";

    lunr.tokenizer.seperator = '.';
    index = lunr(function () {
        this.field('prefix');
        this.field('name', { boost: 10 });
        this.ref('id');
    });

    $.each(store, function (id, value) {
        index.add({
            id: id,
            name: value.name,
            prefix: value.prefix
        });
    });

    $("#ls_search-field")
        .keyup(function (event) {
            onKeyUp(event);
        })
        .keypress(function (event) {
            if (event.keyCode === 13) {
                event.preventDefault();
                var active = $('#ls_search-results li a.hover')[0];
                active.click();
            }
        })
        .focusout(function () {
            // http://stackoverflow.com/a/13980492/1079728
            window.setTimeout(function () {
                $('.results').hide();
            }, 100);
        })
        .focusin(function () {
            if ($('#ls_search-results li').length > 0) {
                $('#ls_search-results').show();
            }
        });

    function onKeyUp(event) {
        var keycode = event.keyCode || event.which,
            query = $("#ls_search-field").val(),
            ul = $('#ls_search-results'),
            i = 0,
            results = null;

        if (keycode === 13) {
            return;
        }
        if (keycode === 40 || keycode === 38) {
            return handleKeyboardNavigation(keycode);
        }
        if (query === '') {
            ul.empty().hide();
            return;
        }

        results = index.search(query);
        ul.show();

        if (results.length === 0) {
            ul.empty().append($('
No results found
'));
            return;
        }

        ul.empty();
        for (i = 0; i < Math.min(results.length, 5); i += 1) {
            ul.append(createResultListElement(store[results[i].ref]));
        }
    }  // end onKeyUp

    function handleKeyboardNavigation(keycode) {
        var ul = $('#ls_search-results'),
            active = $(ul.find('li a.hover')[0]);

        if (keycode === 40) {
            // next
            if (!active.length) {
                $(ul.find('li a')[0]).addClass('hover');
            } else {
                active.removeClass('hover');
                active.parent().next().find('a').addClass('hover');
            }
        } else if (keycode === 38) {
            // prev
            active.removeClass('hover');
            active.parent().prev().find('a').addClass('hover');
        }
    }  // end handleKeyboardNavigation

    function buildHref(s) {
        var highlightstring = highlight ? '?highlight=' + $.urlencode(s.name) : "";

        return DOCUMENTATION_OPTIONS.URL_ROOT + s.filename +
               DOCUMENTATION_OPTIONS.FILE_SUFFIX +
               highlightstring +
               '#' + s.prefix + '.' + s.name;
    } // end buildHref

    function createResultListElement(s) {
        var prefix = (s.objtype === "py:method") ? (s.last_prefix + ".") : "",
            ul = $('#ls_search-results');

        return $('
')
            .append($('')
                .attr('href', buildHref(s))
                .text(prefix + s.name)
                .mouseenter(function () {
                    ul.find('li a').removeClass('hover');
                    $(this).addClass('hover');
                })
                .mouseleave(function () {
                    $(this).removeClass('hover');
                })
                );
    } // end createResultListElement

}($, lunr, Search, DOCUMENTATION_OPTIONS));
// Search.store is a global that's in searchbox.html
<commit_msg>Widen the results list css when necessary<commit_after>/*jslint browser: true*/
/*global $, lunr, Search, DOCUMENTATION_OPTIONS*/

(function () {
    "use strict";

$.fn.textWidth = function(text, font) {
    if (!$.fn.textWidth.fakeEl) $.fn.textWidth.fakeEl = $('').hide().appendTo(document.body);
    $.fn.textWidth.fakeEl.text(text || this.val() || this.text()).css('font', font || this.css('font'));
    return $.fn.textWidth.fakeEl.width();
};

var searchModule = (function ($, lunr, Search, DOCUMENTATION_OPTIONS) {
    "use strict";

    var store = Search.store,
        index = null,
        highlight = $("#ls_lunrsearch-highlight").value === "true";

    lunr.tokenizer.seperator = '.';
    index = lunr(function () {
        this.field('prefix');
        this.field('name', { boost: 10 });
        this.ref('id');
    });

    $.each(store, function (id, value) {
        index.add({
            id: id,
            name: value.name,
            prefix: value.prefix
        });
    });

    $("#ls_search-field")
        .keyup(function (event) {
            onKeyUp(event);
        })
        .keypress(function (event) {
            if (event.keyCode === 13) {
                event.preventDefault();
                var active = $('#ls_search-results li a.hover')[0];
                active.click();
            }
        })
        .focusout(function () {
            // http://stackoverflow.com/a/13980492/1079728
            window.setTimeout(function () {
                $('.results').hide();
            }, 100);
        })
        .focusin(function () {
            if ($('#ls_search-results li').length > 0) {
                $('#ls_search-results').show();
            }
        });

    function onKeyUp(event) {
        var keycode = event.keyCode || event.which,
            query = $("#ls_search-field").val(),
            ul = $('#ls_search-results'),
            i = 0,
            results = null;

        if (keycode === 13) {
            return;
        }
        if (keycode === 40 || keycode === 38) {
            return handleKeyboardNavigation(keycode);
        }
        if (query === '') {
            ul.empty().hide();
            return;
        }

        results = index.search(query);
        ul.show();

        if (results.length === 0) {
            ul.empty().append($('
No results found
'));
            return;
        }

        ul.empty();
        for (i = 0; i < Math.min(results.length, 5); i += 1) {
            ul.append(createResultListElement(store[results[i].ref]));
        }
        ul.width(Math.max(
            $('#ls_search-field').outerWidth(),
            Math.max.apply(null, ul.children().map(function(i, o) {
                return $(o).textWidth();
            })) + 20
        ));

    }  // end onKeyUp

    function handleKeyboardNavigation(keycode) {
        var ul = $('#ls_search-results'),
            active = $(ul.find('li a.hover')[0]);

        if (keycode === 40) {
            // next
            if (!active.length) {
                $(ul.find('li a')[0]).addClass('hover');
            } else {
                active.removeClass('hover');
                active.parent().next().find('a').addClass('hover');
            }
        } else if (keycode === 38) {
            // prev
            active.removeClass('hover');
            active.parent().prev().find('a').addClass('hover');
        }
    }  // end handleKeyboardNavigation

    function buildHref(s) {
        var highlightstring = highlight ? '?highlight=' + $.urlencode(s.name) : "";

        return DOCUMENTATION_OPTIONS.URL_ROOT + s.filename +
               DOCUMENTATION_OPTIONS.FILE_SUFFIX +
               highlightstring +
               '#' + s.prefix + '.' + s.name;
    } // end buildHref

    function createResultListElement(s) {
        var prefix = (s.objtype === "py:method") ? (s.last_prefix + ".") : "",
            ul = $('#ls_search-results');

        return $('
')
            .append($('')
                .attr('href', buildHref(s))
                .text(prefix + s.name)
                .mouseenter(function () {
                    ul.find('li a').removeClass('hover');
                    $(this).addClass('hover');
                })
                .mouseleave(function () {
                    $(this).removeClass('hover');
                })
                );
    } // end createResultListElement
});

window.onload = function() {
    searchModule($, lunr, Search, DOCUMENTATION_OPTIONS);
};

}());
<|endoftext|>


<commit_before>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
(function(cloudStack) {
  cloudStack.sections.regions = {
    title: 'label.menu.regions',
    id: 'regions',
    regionSelector: {
      dataProvider: function(args) {
        $.ajax({
          url: createURL('listRegions&listAll=true'),
          success: function(json) {
            var regions = json.listregionsresponse.region;

            args.response.success({
              data: regions ? regions : [
                { id: -1, name: _l('label.no.data') }
              ]
            });
          }
        });
      }
    },
    listView: {
      section: 'regions',
      fields: {
        name: { label: 'label.name' },
        id: { label: 'ID' },
        endpoint: { label: 'label.endpoint' }
      },
      actions: {
        add: {
          label: 'label.add.region',
          messages: {
            notification: function() { return 'label.add.region'; }
          },
          createForm: {
            title: 'label.add.region',
            desc: 'message.add.region',
            fields: {
              id: { label: 'label.id', validation: { required: true } },
              name: { label: 'label.name', validation: { required: true } },
              endpoint: { label: 'label.endpoint', validation: { required: true } }
            }
          },
          action: function(args) {
						var data = {
							id: args.data.id,
							name: args.data.name,
							endpoint: args.data.endpoint
						};

            $.ajax({
              url: createURL('addRegion'),
              data: data,
              success: function(json) {
                var item = json.addregionresponse.region;
                args.response.success({data: item});
                $(window).trigger('cloudStack.refreshRegions');
              },
              error: function(json) {
                args.response.error(parseXMLHttpResponse(json));
              }
            });
          },
					notification: {
						poll: function(args) {
							args.complete();
						}
					}
        }
      },
      dataProvider: function(args) {
        $.ajax({
          url: createURL('listRegions&listAll=true'),
          success: function(json) {
            var regions = json.listregionsresponse.region

            args.response.success({
              data: regions ? regions : []
            });
          },
          error: function(json) {
            args.response.error(parseXMLHttpResponse(json));
          }
        });
      },
      detailView: {
        name: 'Region details',
        actions: {
          edit: {
            label: 'label.edit.region',
            action: function(args) {
							var data = {
							  id: args.context.regions[0].id,
								name: args.data.name,
								endpoint: args.data.endpoint
							};

              $.ajax({
                url: createURL('updateRegion'),
                data: data,
                success: function(json) {
                  args.response.success();
                  $(window).trigger('cloudStack.refreshRegions');
                },
                error: function(json) {
                  args.response.error(parseXMLHttpResponse(json));
                }
              });
            }
          },
          remove: {
            label: 'label.remove.region',
            messages: {
              notification: function() { return 'label.remove.region'; },
              confirm: function() { return 'message.remove.region'; }
            },
						preAction: function(args) {
						  var region = args.context.regions[0];

							/* e.g.
							region.endpoint	== "http://localhost:8080/client/"
							document.location.href == "http://localhost:8080/client/#"
							*/
							/*
							if(document.location.href.indexOf(region.endpoint) != -1) {
							  cloudStack.dialog.notice({ message: _l('You can not remove the region that you are currently in.') });
                return false;
							}
              */
              return true;
            },
            action: function(args) {
              var region = args.context.regions[0];

              $.ajax({
                url: createURL('removeRegion'),
                data: { id: region.id },
                success: function(json) {
                  args.response.success();
                  $(window).trigger('cloudStack.refreshRegions');
                },
                error: function(json) {
                  args.response.error(parseXMLHttpResponse(json));
                }
              });
            }
          }
        },
        tabs: {
          details: {
            title: 'label.details',
            fields: [
              {
                id: { label: 'label.id' }
              },
              {
							  name: { label: 'label.name', isEditable: true },
                endpoint: { label: 'label.endpoint', isEditable: true }
              }
            ],
            dataProvider: function(args) {
              $.ajax({
                url: createURL('listRegions&listAll=true'),
                data: { id: args.context.regions[0].id },
                success: function(json) {
                  var region = json.listregionsresponse.region

                  args.response.success({
                    data: region ? region[0] : {}
                  });
                },
                error: function(json) {
                  args.response.error(parseXMLHttpResponse(json));
                }
              });
            }
          }
        }
      }
    }
  };
})(cloudStack);
<commit_msg>CLOUDSTACK-1910: cloudstack UI - Regions menu - add new section GSLB.<commit_after>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
(function(cloudStack) {
  cloudStack.sections.regions = {
    title: 'label.menu.regions',
    id: 'regions',
    regionSelector: {
      dataProvider: function(args) {
        $.ajax({
          url: createURL('listRegions&listAll=true'),
          success: function(json) {
            var regions = json.listregionsresponse.region;

            args.response.success({
              data: regions ? regions : [
                { id: -1, name: _l('label.no.data') }
              ]
            });
          }
        });
      }
    },
		sections: {
      regions: {
				listView: {
					section: 'regions',
					id: 'regions',
          label: 'label.menu.regions',
					fields: {
						name: { label: 'label.name' },
						id: { label: 'ID' },
						endpoint: { label: 'label.endpoint' }
					},
					actions: {
						add: {
							label: 'label.add.region',
							messages: {
								notification: function() { return 'label.add.region'; }
							},
							createForm: {
								title: 'label.add.region',
								desc: 'message.add.region',
								fields: {
									id: { label: 'label.id', validation: { required: true } },
									name: { label: 'label.name', validation: { required: true } },
									endpoint: { label: 'label.endpoint', validation: { required: true } }
								}
							},
							action: function(args) {
								var data = {
									id: args.data.id,
									name: args.data.name,
									endpoint: args.data.endpoint
								};

								$.ajax({
									url: createURL('addRegion'),
									data: data,
									success: function(json) {
										var item = json.addregionresponse.region;
										args.response.success({data: item});
										$(window).trigger('cloudStack.refreshRegions');
									},
									error: function(json) {
										args.response.error(parseXMLHttpResponse(json));
									}
								});
							},
							notification: {
								poll: function(args) {
									args.complete();
								}
							}
						}
					},
					dataProvider: function(args) {
						$.ajax({
							url: createURL('listRegions&listAll=true'),
							success: function(json) {
								var regions = json.listregionsresponse.region

								args.response.success({
									data: regions ? regions : []
								});
							},
							error: function(json) {
								args.response.error(parseXMLHttpResponse(json));
							}
						});
					},
					detailView: {
						name: 'Region details',
						//viewAll: { path: 'regions.GSLB', label: 'GSLB' },
						actions: {
							edit: {
								label: 'label.edit.region',
								action: function(args) {
									var data = {
										id: args.context.regions[0].id,
										name: args.data.name,
										endpoint: args.data.endpoint
									};

									$.ajax({
										url: createURL('updateRegion'),
										data: data,
										success: function(json) {
											args.response.success();
											$(window).trigger('cloudStack.refreshRegions');
										},
										error: function(json) {
											args.response.error(parseXMLHttpResponse(json));
										}
									});
								}
							},
							remove: {
								label: 'label.remove.region',
								messages: {
									notification: function() { return 'label.remove.region'; },
									confirm: function() { return 'message.remove.region'; }
								},
								preAction: function(args) {
									var region = args.context.regions[0];

									/* e.g.
									region.endpoint	== "http://localhost:8080/client/"
									document.location.href == "http://localhost:8080/client/#"
									*/
									/*
									if(document.location.href.indexOf(region.endpoint) != -1) {
										cloudStack.dialog.notice({ message: _l('You can not remove the region that you are currently in.') });
										return false;
									}
									*/
									return true;
								},
								action: function(args) {
									var region = args.context.regions[0];

									$.ajax({
										url: createURL('removeRegion'),
										data: { id: region.id },
										success: function(json) {
											args.response.success();
											$(window).trigger('cloudStack.refreshRegions');
										},
										error: function(json) {
											args.response.error(parseXMLHttpResponse(json));
										}
									});
								}
							}
						},
						tabs: {
							details: {
								title: 'label.details',
								fields: [
									{
										id: { label: 'label.id' }
									},
									{
										name: { label: 'label.name', isEditable: true },
										endpoint: { label: 'label.endpoint', isEditable: true }
									}
								],
								dataProvider: function(args) {
									$.ajax({
										url: createURL('listRegions&listAll=true'),
										data: { id: args.context.regions[0].id },
										success: function(json) {
											var region = json.listregionsresponse.region

											args.response.success({
												data: region ? region[0] : {}
											});
										},
										error: function(json) {
											args.response.error(parseXMLHttpResponse(json));
										}
									});
								}
							}
						}
					}
				}
			}

			/*
			,
			GSLB: {
        type: 'select',
        title: 'GSLB',
        listView: {
          id: 'GSLB',
          label: 'GSLB',
          fields: {
            name: { label: 'label.name' }
          },
					dataProvider: function(args) {
            if('regions' in args.context) {
							var data = {
								regionid: args.context.regions[0].id
							};
							$.ajax({
								url: createURL('listGlobalLoadBalancerRules'),
								data: data,
								success: function(json) {
									debugger;
									var items = json.listgloballoadbalancerrulesresponse.globalloadbalancerrule;
									args.response.success({
										data: items
									});
								}
							});
						}
						else {
						  args.response.success({
								data: null
							});
						}
          }
				}
      }
      */

    }
  };
})(cloudStack);
<|endoftext|>


<commit_before>//Module is a Singelton
define(function(require) {

  var $ = require('jquery');
  var _ = require('underscore');
  var Backbone = require('backbone');
  var Store = require('localstorage');
  var Doc = require('models/doc');
  var settings = require('models/settings');

  var remoteStorageDocuments = require('remotestorage-documents');

  remoteStorage.claimAccess('documents', 'rw');

  var escapeRegExp = function(str) {
    return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  };

  var Docs = Backbone.Collection.extend({

    model: Doc,

    localStorage: remoteStorageDocuments.getBackboneStore('notes'),

    initialize: function(models) {

      this.fetch({
        success: _.bind(function() {
          if (this.isEmpty()) {
            this.addNew();
          }
        }, this)
      });

      this
        .on('change:content', this.sort)
        .on('change:lastEdited', this.saveWhenIdle)
        .on('change:title', this.updateUrl);
    },

    addNew: function() {
      this.create({
        id: _.uniqueId(),
        lastEdited: new Date().getTime()
      });
    },

    // Sort by 'lastEdited'
    comparator: function(first, second) {
      return first.get('lastEdited') > second.get('lastEdited') ? -1 : 1 ;
    },

    saveTimeout: undefined,
    saveWhenIdle: function(doc) {
      clearTimeout(this.saveTimeout);
      this.saveTimeout = setTimeout(_.bind(doc.save, doc), 300);
    },

    updateUrl: function(doc) {
      var url = encodeURI(doc.get('title').toLowerCase().replace(/\s| /g, '-'));
      if (url.length < 1) {
        doc.set('url', '');
        return;
      }
      var len = this.filter(function(doc) {
        return new RegExp('^' + escapeRegExp(url) + '(-[0-9]|$)').test(doc.get('url'));
      }).length;
      url = len < 1 ? url : url + '-' + len;
      doc.set('url', url);
    },

    deleteEmpty: function() {
      var previousDoc = this.get(settings.previous('openDocId'));
      if (previousDoc && previousDoc.isEmpty()) {
        log('here');
        previousDoc.destroy();
      }
    }

  });

  var docs = new Docs();

  var hasConnected = false;

  // TODO: remove this once event handler below is implemented.
  remoteStorage.onWidget('state', function(state) {
    if ((! hasConnected) && state == 'connected') {
      hasConnected = true;

      docs.reset(docs.localStorage.findAll());
    } else if ( state == 'disconnected') {
      docs.reset().addNew();
    }
  });

  remoteStorage.documents.onChange('notes', function(event) {
    // TODO: apply update to docs collection
  });

  return docs;

});
<commit_msg>remotestorage: reload all data on ready-event, instead of connected state.<commit_after>//Module is a Singelton
define(function(require) {

  var $ = require('jquery');
  var _ = require('underscore');
  var Backbone = require('backbone');
  var Store = require('localstorage');
  var Doc = require('models/doc');
  var settings = require('models/settings');

  var remoteStorageDocuments = require('remotestorage-documents');

  remoteStorage.claimAccess('documents', 'rw');

  var escapeRegExp = function(str) {
    return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  };

  var Docs = Backbone.Collection.extend({

    model: Doc,

    localStorage: remoteStorageDocuments.getBackboneStore('notes'),

    initialize: function(models) {

      this.fetch({
        success: _.bind(function() {
          if (this.isEmpty()) {
            this.addNew();
          }
        }, this)
      });

      this
        .on('change:content', this.sort)
        .on('change:lastEdited', this.saveWhenIdle)
        .on('change:title', this.updateUrl);
    },

    addNew: function() {

      this.create({
        id: _.uniqueId(),
        lastEdited: new Date().getTime()
      });
    },

    // Sort by 'lastEdited'
    comparator: function(first, second) {
      return first.get('lastEdited') > second.get('lastEdited') ? -1 : 1 ;
    },

    saveTimeout: undefined,
    saveWhenIdle: function(doc) {
      clearTimeout(this.saveTimeout);
      this.saveTimeout = setTimeout(_.bind(doc.save, doc), 300);
    },

    updateUrl: function(doc) {
      var url = encodeURI(doc.get('title').toLowerCase().replace(/\s| /g, '-'));
      if (url.length < 1) {
        doc.set('url', '');
        return;
      }
      var len = this.filter(function(doc) {
        return new RegExp('^' + escapeRegExp(url) + '(-[0-9]|$)').test(doc.get('url'));
      }).length;
      url = len < 1 ? url : url + '-' + len;
      doc.set('url', url);
    },

    deleteEmpty: function() {
      var previousDoc = this.get(settings.previous('openDocId'));
      if (previousDoc && previousDoc.isEmpty()) {
        log('here');
        previousDoc.destroy();
      }
    }

  });

  var docs = new Docs();

  var hasConnected = false;

  // TODO: remove this once event handler below is implemented.
  remoteStorage.onWidget('ready', function() {
    docs.reset(docs.localStorage.findAll());
  });

  remoteStorage.onWidget('state', function(state) {
    if(state == 'disconnected') {
      docs.reset().addNew();
    }
  });

  remoteStorage.documents.onChange('notes', function(event) {
    // TODO: apply update to docs collection
  });

  return docs;

});
<|endoftext|>


<commit_before>// Custom Tsunami scripts.
'use strict';

exports.BattleScripts = {
	randomTsuStaffTeam: function (side) {
		let userid = toId(side.name);
		let team = [];
		let variant = this.random(2);
		let sets = {
			// Admins:
			'~Desokoro': {
				species: 'Gyarados',
				ability: 'Wave Call',
				item: 'Leftovers',
				gender: 'M',
				shiny: true,
				moves: ['Substitute', 'Dragon Dance', 'Bounce',
				],
				signatureMove: 'Tsunami Crash',
				evs: {
					atk: 252,
					spe: 252,
					hp: 4,
				},
				nature: 'Adamant',
			},
			'~Mosmero': {
				species: 'Gastly',
				ability: 'Mosmic Power',
				item: 'Life Orb',
				gender: '',
				moves: ['Shadow Ball', 'Sludge Bomb', 'Giga Drain',
				],
				signatureMove: 'Mosmero Beam',
				evs: {
					hp: 4,
					spa: 252,
					spe: 252,
				},
				nature: 'Modest',
			},
			'~HoeenHero': {
				species: 'Ludicolo',
				ability: 'Programmer\'s Domain',
				item: 'Leftovers',
				gender: 'M',
				moves: [
					['Hydro Pump', 'Scald'][variant], 'Ice Beam', 'Giga Drain',
				],
				signatureMove: 'Scripting',
				evs: {
					spa: 252,
					spe: 252,
					hp: 4,
				},
				nature: 'Modest',
			},
			'~Tsunami Prince': {
				species: 'Darkrai',
				ability: 'Death Boost',
				item: 'Darkiniumz',
				gender: 'M',
				moves: ['Nightmare', 'Dark Pulse', 'Shadow Ball'
				],
				signatureMove: 'Overpower',
				evs: {
					spa: 252,
					spe: 252,
					hp: 6,
				},
				nature: 'Timid',
			},
			// Global Leaders:
			'&MechSteelix': {
				species: 'Mega-Steelix',
				ability: 'Sandbox',
				item: 'Lum Berry',
				gender: 'M',
				moves: ['Curse', 'Sleep Talk', 'Earthquake',
				],
				signatureMove: 'Deep Sleep',
				evs: {
					hp: 252,
					atk: 4,
					def: 252,
				},
				nature: 'Impish',
			},

			// Global Moderators:
			'@Admewn': {
				species: 'Mew',
				ability: 'Protean',
				item: 'Expert Belt',
				moves: ['Earth Power', 'Oblivion Wing', 'Shadow Ball',
				],
				signatureMove: 'Mewtation',
				evs: {
					spa: 252,
					spe: 252,
					hp: 4,
				},
				nature: 'Timid',
			},
			'@CubsFan38': {
				species: 'Mamoswine',
				ability: 'Chilly Penguinn',
				item: 'Life Orb',
				gender: 'M',
				moves: ['Ice Shard', 'Knock Off', 'Earthquake',
				],
				signatureMove: 'Penguin\'s Shower',
				evs: {
					hp: 4,
					atk: 252,
					spe: 252,
				},
				nature: 'Jolly',
			},
			'@TheRittz': {
				species: 'Mega-Venusaur',
				ability: 'Paradoxical Prowess',
				item: 'Black Sludge',
				gender: 'M',
				moves: ['Substitute', 'Leech Seed', 'Toxic',
				],
				signatureMove: 'Everlasting Annoyingness',
				evs: {
					hp: 252,
					def: 128,
					spd: 128,
				},
				nature: 'Calm',
			},
			// Global Drivers:
			'%Kraken Mare': {
				species: 'Gardevoir-Mega',
				ability: 'krakensboost',
				shiny: true,
				item: 'Focus Sash',
				gender: 'F',
				moves: ['Moonblast', 'Calm Mind', 'Psychic',
				],
				signatureMove: 'Revenge of Kraken Mare',
				evs: {
					hp: 248,
					spa: 252,
					def: 8,
				},
				nature: 'Modest',
			},
			// Bots:
			'*Tidal Wave Bot': {
				species: 'Magikarp',
				ability: 'Loading...',
				item: 'Temp. Name',
				shiny: true,
				moves: ['Wild Charge', 'Shift Gear', 'Gear Grind'
				],
				signatureMove: 'Server Guardian',
				evs: {
					hp: 4,
					atk: 252,
					spe: 252,
				},
				nature: 'Adament',
			},
			'*Stabby the Krabby': {
				species: 'Krabby',
				ability: 'Ready to Stab',
				item: 'Eviolite',
				gender: 'M',
				moves: ['Crabhammer', 'Swords Dance', 'Knock Off'
				],
				baseSignatureMove: "stabstab",
				signatureMove: 'Stab Stab',
				evs: {
					atk: 252,
					spe: 252,
					hp: 6,
				},
				nature: 'Adamant',
			},
			// Global Voices:
			'+xcmr': {
				species: 'Meowth',
				ability: 'Feline Fury',
				item: 'Eviolite',
				gender: 'M',
				moves: ['U-turn', 'Fake Out', 'Knock Off',
				],
				signatureMove: 'Kitty Crush',
				evs: {
					atk: 252,
					spd: 4,
					spe: 252,
				},
				nature: 'Jolly',
			},
			/******************
			Waiting for move to be ready.
			'+C733937123':{
				species: 'Chesnaught',
				ability: 'Paladin Armour',
				item: 'Shining Blade and Glowing Armour',
				gender: 'M',
				moves: ['Leaf Blade', 'Smart Strike', 'Sacred Sword',
				],
				signatureMove: 'Paladin Strike',
				evs: {
					atk: 252,
					spd: 128,
					spe: 128,
				},
				nature: 'Adamant',
			},
			*************************/
			//Former Staff + Regs

		};
		// convert moves to ids.
		for (let k in sets) {
			sets[k].moves = sets[k].moves.map(toId);
			sets[k].baseSignatureMove = toId(sets[k].baseSignatureMove);
		}

		// Generate the team randomly.
		let pool = Dex.shuffle(Object.keys(sets));
		for (let i = 0; i < 6; i++) {
			if (i === 1) {
 				let monIds = pool.slice(0, 6).map(function (p) {
 					return toId(p);
 				});
 				for (let mon in sets) {
 					if (toId(mon) === userid && monIds.indexOf(userid) === -1) {
 						pool[1] = mon;
 						break;
 					}
 				}
 			}
 			let set = sets[pool[i]];
			let name = this.sampleNoReplace(pool);
			let set = sets[name];
			set.level = 100;
			set.name = pool[i];
			if (!set.ivs) {
				set.ivs = {
					hp: 31,
					atk: 31,
					def: 31,
					spa: 31,
					spd: 31,
					spe: 31,
				};
			} else {
				for (let iv in {
					hp: 31,
					atk: 31,
					def: 31,
					spa: 31,
					spd: 31,
					spe: 31,
				}) {
					set.ivs[iv] = iv in set.ivs ? set.ivs[iv] : 31;
				}
			}
			// Assuming the hardcoded set evs are all legal.
			if (!set.evs) {
				set.evs = {
					hp: 84,
					atk: 84,
					def: 84,
					spa: 84,
					spd: 84,
					spe: 84,
				};
			}
			set.moves = [this.sampleNoReplace(set.moves), this.sampleNoReplace(set.moves), this.sampleNoReplace(set.moves)].concat(set.signatureMove);
			team.push(set);
		}
		return team;
	},
};
<commit_msg>Correcting me being dumb.<commit_after>// Custom Tsunami scripts.
'use strict';

exports.BattleScripts = {
	randomTsuStaffTeam: function (side) {
		let userid = toId(side.name);
		let team = [];
		let variant = this.random(2);
		let sets = {
			// Admins:
			'~Desokoro': {
				species: 'Gyarados',
				ability: 'Wave Call',
				item: 'Leftovers',
				gender: 'M',
				shiny: true,
				moves: ['Substitute', 'Dragon Dance', 'Bounce',
				],
				signatureMove: 'Tsunami Crash',
				evs: {
					atk: 252,
					spe: 252,
					hp: 4,
				},
				nature: 'Adamant',
			},
			'~Mosmero': {
				species: 'Gastly',
				ability: 'Mosmic Power',
				item: 'Life Orb',
				gender: '',
				moves: ['Shadow Ball', 'Sludge Bomb', 'Giga Drain',
				],
				signatureMove: 'Mosmero Beam',
				evs: {
					hp: 4,
					spa: 252,
					spe: 252,
				},
				nature: 'Modest',
			},
			'~HoeenHero': {
				species: 'Ludicolo',
				ability: 'Programmer\'s Domain',
				item: 'Leftovers',
				gender: 'M',
				moves: [
					['Hydro Pump', 'Scald'][variant], 'Ice Beam', 'Giga Drain',
				],
				signatureMove: 'Scripting',
				evs: {
					spa: 252,
					spe: 252,
					hp: 4,
				},
				nature: 'Modest',
			},
			'~Tsunami Prince': {
				species: 'Darkrai',
				ability: 'Death Boost',
				item: 'Darkiniumz',
				gender: 'M',
				moves: ['Nightmare', 'Dark Pulse', 'Shadow Ball'
				],
				signatureMove: 'Overpower',
				evs: {
					spa: 252,
					spe: 252,
					hp: 6,
				},
				nature: 'Timid',
			},
			// Global Leaders:
			'&MechSteelix': {
				species: 'Mega-Steelix',
				ability: 'Sandbox',
				item: 'Lum Berry',
				gender: 'M',
				moves: ['Curse', 'Sleep Talk', 'Earthquake',
				],
				signatureMove: 'Deep Sleep',
				evs: {
					hp: 252,
					atk: 4,
					def: 252,
				},
				nature: 'Impish',
			},

			// Global Moderators:
			'@Admewn': {
				species: 'Mew',
				ability: 'Protean',
				item: 'Expert Belt',
				moves: ['Earth Power', 'Oblivion Wing', 'Shadow Ball',
				],
				signatureMove: 'Mewtation',
				evs: {
					spa: 252,
					spe: 252,
					hp: 4,
				},
				nature: 'Timid',
			},
			'@CubsFan38': {
				species: 'Mamoswine',
				ability: 'Chilly Penguinn',
				item: 'Life Orb',
				gender: 'M',
				moves: ['Ice Shard', 'Knock Off', 'Earthquake',
				],
				signatureMove: 'Penguin\'s Shower',
				evs: {
					hp: 4,
					atk: 252,
					spe: 252,
				},
				nature: 'Jolly',
			},
			'@TheRittz': {
				species: 'Mega-Venusaur',
				ability: 'Paradoxical Prowess',
				item: 'Black Sludge',
				gender: 'M',
				moves: ['Substitute', 'Leech Seed', 'Toxic',
				],
				signatureMove: 'Everlasting Annoyingness',
				evs: {
					hp: 252,
					def: 128,
					spd: 128,
				},
				nature: 'Calm',
			},
			// Global Drivers:
			'%Kraken Mare': {
				species: 'Gardevoir-Mega',
				ability: 'krakensboost',
				shiny: true,
				item: 'Focus Sash',
				gender: 'F',
				moves: ['Moonblast', 'Calm Mind', 'Psychic',
				],
				signatureMove: 'Revenge of Kraken Mare',
				evs: {
					hp: 248,
					spa: 252,
					def: 8,
				},
				nature: 'Modest',
			},
			// Bots:
			'*Tidal Wave Bot': {
				species: 'Magikarp',
				ability: 'Loading...',
				item: 'Temp. Name',
				shiny: true,
				moves: ['Wild Charge', 'Shift Gear', 'Gear Grind'
				],
				signatureMove: 'Server Guardian',
				evs: {
					hp: 4,
					atk: 252,
					spe: 252,
				},
				nature: 'Adament',
			},
			'*Stabby the Krabby': {
				species: 'Krabby',
				ability: 'Ready to Stab',
				item: 'Eviolite',
				gender: 'M',
				moves: ['Crabhammer', 'Swords Dance', 'Knock Off'
				],
				baseSignatureMove: "stabstab",
				signatureMove: 'Stab Stab',
				evs: {
					atk: 252,
					spe: 252,
					hp: 6,
				},
				nature: 'Adamant',
			},
			// Global Voices:
			'+xcmr': {
				species: 'Meowth',
				ability: 'Feline Fury',
				item: 'Eviolite',
				gender: 'M',
				moves: ['U-turn', 'Fake Out', 'Knock Off',
				],
				signatureMove: 'Kitty Crush',
				evs: {
					atk: 252,
					spd: 4,
					spe: 252,
				},
				nature: 'Jolly',
			},
			/******************
			Waiting for move to be ready.
			'+C733937123':{
				species: 'Chesnaught',
				ability: 'Paladin Armour',
				item: 'Shining Blade and Glowing Armour',
				gender: 'M',
				moves: ['Leaf Blade', 'Smart Strike', 'Sacred Sword',
				],
				signatureMove: 'Paladin Strike',
				evs: {
					atk: 252,
					spd: 128,
					spe: 128,
				},
				nature: 'Adamant',
			},
			*************************/
			//Former Staff + Regs

		};
		// convert moves to ids.
		for (let k in sets) {
			sets[k].moves = sets[k].moves.map(toId);
			sets[k].baseSignatureMove = toId(sets[k].baseSignatureMove);
		}

		// Generate the team randomly.
		let pool = Dex.shuffle(Object.keys(sets));
		for (let i = 0; i < 6; i++) {
			if (i === 1) {
 				let monIds = pool.slice(0, 6).map(function (p) {
 					return toId(p);
 				});
 				for (let mon in sets) {
 					if (toId(mon) === userid && monIds.indexOf(userid) === -1) {
 						pool[1] = mon;
 						break;
 					}
 				}
 			}
 			let set = sets[pool[i]];
			set.level = 100;
			set.name = pool[i];
			if (!set.ivs) {
				set.ivs = {
					hp: 31,
					atk: 31,
					def: 31,
					spa: 31,
					spd: 31,
					spe: 31,
				};
			} else {
				for (let iv in {
					hp: 31,
					atk: 31,
					def: 31,
					spa: 31,
					spd: 31,
					spe: 31,
				}) {
					set.ivs[iv] = iv in set.ivs ? set.ivs[iv] : 31;
				}
			}
			// Assuming the hardcoded set evs are all legal.
			if (!set.evs) {
				set.evs = {
					hp: 84,
					atk: 84,
					def: 84,
					spa: 84,
					spd: 84,
					spe: 84,
				};
			}
			set.moves = [this.sampleNoReplace(set.moves), this.sampleNoReplace(set.moves), this.sampleNoReplace(set.moves)].concat(set.signatureMove);
			team.push(set);
		}
		return team;
	},
};
<|endoftext|>


<commit_before>// # Ghost jQuery Utils

/*global window, document, $ */

(function () {
    "use strict";

    // ## UTILS

    /**
     * Allows to check contents of each element exactly
     * @param obj
     * @param index
     * @param meta
     * @param stack
     * @returns {boolean}
     */
    $.expr[":"].containsExact = function (obj, index, meta, stack) {
        /*jslint unparam:true*/
        return (obj.textContent || obj.innerText || $(obj).text() || "") === meta[3];
    };

    /**
     * Center an element to the window vertically and centrally
     * @returns {*}
     */
    $.fn.center = function (options) {
        var $window = $(window),
            config = $.extend({
                animate        : true,
                successTrigger : 'centered'
            }, options);

        return this.each(function () {
            var $this = $(this);
            $this.css({
                'position': 'absolute'
            });
            if (config.animate) {
                $this.animate({
                    'left': ($window.width() / 2) - $this.outerWidth() / 2 + 'px',
                    'top': ($window.height() / 2) - $this.outerHeight() / 2 + 'px'
                });
            } else {
                $this.css({
                    'left': ($window.width() / 2) - $this.outerWidth() / 2 + 'px',
                    'top': ($window.height() / 2) - $this.outerHeight() / 2 + 'px'
                });
            }
            $(window).trigger(config.successTrigger);
        });
    };

    // ## getTransformProperty
    // This returns the transition duration for an element, good for calling things after a transition has finished.
    // **Original**: [https://gist.github.com/mandelbro/4067903](https://gist.github.com/mandelbro/4067903)
    // **returns:** the elements transition duration
    $.fn.transitionDuration = function () {
        var $this = $(this);

        // check the main transition duration property
        if ($this.css('transition-duration')) {
            return Math.round(parseFloat(this.css('transition-duration')) * 1000);
        }

        // check the vendor transition duration properties
        if (this.css('-webkit-transtion-duration')) {
            return Math.round(parseFloat(this.css('-webkit-transtion-duration')) * 1000);
        }

        if (this.css('-ms-transtion-duration')) {
            return Math.round(parseFloat(this.css('-ms-transtion-duration')) * 1000);
        }

        if (this.css('-moz-transtion-duration')) {
            return Math.round(parseFloat(this.css('-moz-transtion-duration')) * 1000);
        }

        if (this.css('-o-transtion-duration')) {
            return Math.round(parseFloat(this.css('-o-transtion-duration')) * 1000);
        }

        // if we're here, then no transition duration was found, return 0
        return 0;
    };

    // ## scrollShadow
    // This adds a 'scroll' class to the targeted element when the element is scrolled
    // **target:** The element in which the class is applied. Defaults to scrolled element.
    // **class-name:** The class which is applied.
    // **offset:** How far the user has to scroll before the class is applied.
    $.fn.scrollClass = function (options) {
        var config = $.extend({
                'target'     : '',
                'class-name' : 'scrolling',
                'offset'     : 1
            }, options);

        return this.each(function () {
            var $this = $(this),
                $target = $this;
            if (config.target) {
                $target = $(config.target);
            }
            $this.scroll(function () {
                if ($this.scrollTop() > config.offset) {
                    $target.addClass(config['class-name']);
                } else {
                    $target.removeClass(config['class-name']);
                }
            });
        });
    };

    $.fn.selectText = function () {
        var elem = this[0],
            range,
            selection;
        if (document.body.createTextRange) {
            range = document.body.createTextRange();
            range.moveToElementText(elem);
            range.select();
        } else if (window.getSelection) {
            selection = window.getSelection();
            range = document.createRange();
            range.selectNodeContents(elem);
            selection.removeAllRanges();
            selection.addRange(range);
        }
    };

    /**
     * Set interactions for all menus and overlays
     * This finds all visible 'hideClass' elements and hides them upon clicking away from the element itself.
     * A callback can be defined to customise the results. By default it will hide the element.
     * @param callback
     */
    $.fn.hideAway = function (callback) {
        var $self = $(this);
        $("body").on('click', function (event) {
            var $target = $(event.target),
                hideClass = $self.selector;
            if (!$target.parents().is(hideClass + ":visible") && !$target.is(hideClass + ":visible")) {
                if (callback) {
                    callback($("body").find(hideClass + ":visible"));
                } else {
                    $("body").find(hideClass + ":visible").fadeOut();

                    // Toggle active classes on menu headers
                    $("[data-toggle].active").removeClass("active");
                }
            }
        });

        return this;
    };

    // ## GLOBALS

    $('.overlay').hideAway();

    /**
     * Adds appropriate inflection for pluralizing the singular form of a word when appropriate.
     * This is an overly simplistic implementation that does not handle irregular plurals.
     * @param {Number} count
     * @param {String} singularWord
     * @returns {String}
     */
    $.pluralize = function inflect(count, singularWord) {
        var base = [count, ' ', singularWord];

        return (count === 1) ? base.join('') : base.concat('s').join('');
    };

}());
<commit_msg>Fix typo?<commit_after>// # Ghost jQuery Utils

/*global window, document, $ */

(function () {
    "use strict";

    // ## UTILS

    /**
     * Allows to check contents of each element exactly
     * @param obj
     * @param index
     * @param meta
     * @param stack
     * @returns {boolean}
     */
    $.expr[":"].containsExact = function (obj, index, meta, stack) {
        /*jslint unparam:true*/
        return (obj.textContent || obj.innerText || $(obj).text() || "") === meta[3];
    };

    /**
     * Center an element to the window vertically and centrally
     * @returns {*}
     */
    $.fn.center = function (options) {
        var $window = $(window),
            config = $.extend({
                animate        : true,
                successTrigger : 'centered'
            }, options);

        return this.each(function () {
            var $this = $(this);
            $this.css({
                'position': 'absolute'
            });
            if (config.animate) {
                $this.animate({
                    'left': ($window.width() / 2) - $this.outerWidth() / 2 + 'px',
                    'top': ($window.height() / 2) - $this.outerHeight() / 2 + 'px'
                });
            } else {
                $this.css({
                    'left': ($window.width() / 2) - $this.outerWidth() / 2 + 'px',
                    'top': ($window.height() / 2) - $this.outerHeight() / 2 + 'px'
                });
            }
            $(window).trigger(config.successTrigger);
        });
    };

    // ## getTransformProperty
    // This returns the transition duration for an element, good for calling things after a transition has finished.
    // **Original**: [https://gist.github.com/mandelbro/4067903](https://gist.github.com/mandelbro/4067903)
    // **returns:** the elements transition duration
    $.fn.transitionDuration = function () {
        var $this = $(this);

        // check the main transition duration property
        if ($this.css('transition-duration')) {
            return Math.round(parseFloat(this.css('transition-duration')) * 1000);
        }

        // check the vendor transition duration properties
        if (this.css('-webkit-transition-duration')) {
            return Math.round(parseFloat(this.css('-webkit-transition-duration')) * 1000);
        }

        if (this.css('-ms-transition-duration')) {
            return Math.round(parseFloat(this.css('-ms-transition-duration')) * 1000);
        }

        if (this.css('-moz-transition-duration')) {
            return Math.round(parseFloat(this.css('-moz-transition-duration')) * 1000);
        }

        if (this.css('-o-transition-duration')) {
            return Math.round(parseFloat(this.css('-o-transition-duration')) * 1000);
        }

        // if we're here, then no transition duration was found, return 0
        return 0;
    };

    // ## scrollShadow
    // This adds a 'scroll' class to the targeted element when the element is scrolled
    // **target:** The element in which the class is applied. Defaults to scrolled element.
    // **class-name:** The class which is applied.
    // **offset:** How far the user has to scroll before the class is applied.
    $.fn.scrollClass = function (options) {
        var config = $.extend({
                'target'     : '',
                'class-name' : 'scrolling',
                'offset'     : 1
            }, options);

        return this.each(function () {
            var $this = $(this),
                $target = $this;
            if (config.target) {
                $target = $(config.target);
            }
            $this.scroll(function () {
                if ($this.scrollTop() > config.offset) {
                    $target.addClass(config['class-name']);
                } else {
                    $target.removeClass(config['class-name']);
                }
            });
        });
    };

    $.fn.selectText = function () {
        var elem = this[0],
            range,
            selection;
        if (document.body.createTextRange) {
            range = document.body.createTextRange();
            range.moveToElementText(elem);
            range.select();
        } else if (window.getSelection) {
            selection = window.getSelection();
            range = document.createRange();
            range.selectNodeContents(elem);
            selection.removeAllRanges();
            selection.addRange(range);
        }
    };

    /**
     * Set interactions for all menus and overlays
     * This finds all visible 'hideClass' elements and hides them upon clicking away from the element itself.
     * A callback can be defined to customise the results. By default it will hide the element.
     * @param callback
     */
    $.fn.hideAway = function (callback) {
        var $self = $(this);
        $("body").on('click', function (event) {
            var $target = $(event.target),
                hideClass = $self.selector;
            if (!$target.parents().is(hideClass + ":visible") && !$target.is(hideClass + ":visible")) {
                if (callback) {
                    callback($("body").find(hideClass + ":visible"));
                } else {
                    $("body").find(hideClass + ":visible").fadeOut();

                    // Toggle active classes on menu headers
                    $("[data-toggle].active").removeClass("active");
                }
            }
        });

        return this;
    };

    // ## GLOBALS

    $('.overlay').hideAway();

    /**
     * Adds appropriate inflection for pluralizing the singular form of a word when appropriate.
     * This is an overly simplistic implementation that does not handle irregular plurals.
     * @param {Number} count
     * @param {String} singularWord
     * @returns {String}
     */
    $.pluralize = function inflect(count, singularWord) {
        var base = [count, ' ', singularWord];

        return (count === 1) ? base.join('') : base.concat('s').join('');
    };

}());
<|endoftext|>


<commit_before>// @flow
import os from 'os';
import { app, BrowserWindow, globalShortcut, Menu, dialog } from 'electron';
import { client } from 'electron-connect';
import { includes } from 'lodash';
import { Logger } from '../common/logging';
import { setupLogging } from './utils/setupLogging';
// import { makeEnvironmentGlobal } from './utils/makeEnvironmentGlobal';
import { createMainWindow } from './windows/main';
import { winLinuxMenu } from './menus/win-linux';
import { osxMenu } from './menus/osx';
import { installChromeExtensions } from './utils/installChromeExtensions';
import environment from '../common/environment';
import { INIT_ENVIRONMENT } from '../common/ipc-api/init-environment';
import { OPEN_ABOUT_DIALOG_CHANNEL } from '../common/ipc/open-about-dialog';
import { GO_TO_ADA_REDEMPTION_SCREEN_CHANNEL } from '../common/ipc/go-to-ada-redemption-screen';
import { GO_TO_NETWORK_STATUS_SCREEN_CHANNEL } from '../common/ipc/go-to-network-status-screen';
import mainErrorHandler from './utils/mainErrorHandler';
import { launcherConfig } from './config';
import { setupCardano } from './cardano/setup';
import { CardanoNode } from './cardano/CardanoNode';
import { safeExitWithCode } from './utils/safeExitWithCode';
import { ensureXDGDataIsSet } from './cardano/config';
import { acquireDaedalusInstanceLock } from './utils/lockFiles';
import { CardanoNodeStates } from '../common/types/cardanoNode.types';

acquireDaedalusInstanceLock();
setupLogging();
mainErrorHandler();

Logger.info(`========== Daedalus is starting at ${new Date().toString()} ==========`);

Logger.debug(`!!! Daedalus is running on ${os.platform()} version ${os.release()}
            with CPU: ${JSON.stringify(os.cpus(), null, 2)} with
            ${JSON.stringify(os.totalmem(), null, 2)} total RAM !!!`);

// Global references to windows to prevent them from being garbage collected
let mainWindow: BrowserWindow;
let cardanoNode: CardanoNode;

const openAbout = () => {
  if (mainWindow) mainWindow.webContents.send(OPEN_ABOUT_DIALOG_CHANNEL);
};

const goToAdaRedemption = () => {
  if (mainWindow) mainWindow.webContents.send(GO_TO_ADA_REDEMPTION_SCREEN_CHANNEL);
};

const goToNetworkStatus = () => {
  if (mainWindow) mainWindow.webContents.send(GO_TO_NETWORK_STATUS_SCREEN_CHANNEL);
};

const restartInSafeMode = async () => {
  Logger.info('restarting in SafeMode …');
  if (cardanoNode) await cardanoNode.stop();
  Logger.info('Exiting Daedalus with code 21.');
  safeExitWithCode(21);
};

const restartWithoutSafeMode = async () => {
  Logger.info('restarting without SafeMode …');
  if (cardanoNode) await cardanoNode.stop();
  Logger.info('Exiting Daedalus with code 22.');
  safeExitWithCode(22);
};

const menuActions = {
  openAbout,
  goToAdaRedemption,
  goToNetworkStatus,
  restartInSafeMode,
  restartWithoutSafeMode,
};

app.on('ready', async () => {
  const isProd = process.env.NODE_ENV === 'production';
  const isStartedByLauncher = !!process.env.LAUNCHER_CONFIG;
  if (isProd && !isStartedByLauncher) {
    const isWindows = process.platform === 'win32';
    const dialogTitle = 'Daedalus improperly started!';
    const dialogMessage = isWindows ?
      'Please start Daedalus using the icon in the Windows start menu or using Daedalus icon on your desktop.' :
      'Daedalus was launched without needed configuration. Please start Daedalus using the shortcut provided by the installer.';
    dialog.showErrorBox(dialogTitle, dialogMessage);
    app.quit();
  }

  ensureXDGDataIsSet();
  // makeEnvironmentGlobal(process.env);
  await installChromeExtensions(environment.isDev());

  // Detect safe mode
  const isInSafeMode = includes(process.argv.slice(1), '--safe-mode');

  mainWindow = createMainWindow(isInSafeMode);
  cardanoNode = setupCardano(launcherConfig, mainWindow);

  // send environment to renderer process
  mainWindow.webContents.send(INIT_ENVIRONMENT, environment);

  if (environment.isDev()) {
    // Connect to electron-connect server which restarts / reloads windows on file changes
    client.create(mainWindow);
  }

  // Build app menus
  let menu;
  if (process.platform === 'darwin') {
    menu = Menu.buildFromTemplate(osxMenu(app, mainWindow, menuActions, isInSafeMode));
    Menu.setApplicationMenu(menu);
  } else {
    menu = Menu.buildFromTemplate(winLinuxMenu(app, mainWindow, menuActions, isInSafeMode));
    mainWindow.setMenu(menu);
  }

  // Hide application window on Cmd+H hotkey (OSX only!)
  if (process.platform === 'darwin') {
    app.on('activate', () => {
      if (!mainWindow.isVisible()) app.show();
    });

    mainWindow.on('focus', () => {
      globalShortcut.register('CommandOrControl+H', app.hide);
    });

    mainWindow.on('blur', () => {
      globalShortcut.unregister('CommandOrControl+H');
    });
  }

  // Wait for controlled cardano-node shutdown before quitting the app
  app.on('before-quit', async (event) => {
    event.preventDefault(); // prevent Daedalus from quitting immediately
    if (cardanoNode.state === CardanoNodeStates.STOPPING) return;
    try {
      Logger.info(`Daedalus:before-quit: stopping cardano-node with PID ${cardanoNode.pid || 'null'}`);
      await cardanoNode.stop();
      Logger.info('Daedalus:before-quit: exiting Daedalus with code 0.');
      safeExitWithCode(0);
    } catch (stopError) {
      Logger.info(`Daedalus:before-quit: cardano-node did not exit correctly: ${stopError}`);
      safeExitWithCode(0);
    }
  });
});
<commit_msg>[DDW-262] Cleans up main index<commit_after>// @flow
import os from 'os';
import { app, BrowserWindow, globalShortcut, Menu, dialog } from 'electron';
import { client } from 'electron-connect';
import { includes } from 'lodash';
import { Logger } from '../common/logging';
import { setupLogging } from './utils/setupLogging';
import { createMainWindow } from './windows/main';
import { winLinuxMenu } from './menus/win-linux';
import { osxMenu } from './menus/osx';
import { installChromeExtensions } from './utils/installChromeExtensions';
import environment from '../common/environment';
import { OPEN_ABOUT_DIALOG_CHANNEL } from '../common/ipc/open-about-dialog';
import { GO_TO_ADA_REDEMPTION_SCREEN_CHANNEL } from '../common/ipc/go-to-ada-redemption-screen';
import { GO_TO_NETWORK_STATUS_SCREEN_CHANNEL } from '../common/ipc/go-to-network-status-screen';
import mainErrorHandler from './utils/mainErrorHandler';
import { launcherConfig } from './config';
import { setupCardano } from './cardano/setup';
import { CardanoNode } from './cardano/CardanoNode';
import { safeExitWithCode } from './utils/safeExitWithCode';
import { ensureXDGDataIsSet } from './cardano/config';
import { acquireDaedalusInstanceLock } from './utils/lockFiles';
import { CardanoNodeStates } from '../common/types/cardanoNode.types';

acquireDaedalusInstanceLock();
setupLogging();
mainErrorHandler();

Logger.info(`========== Daedalus is starting at ${new Date().toString()} ==========`);

Logger.debug(`!!! Daedalus is running on ${os.platform()} version ${os.release()}
            with CPU: ${JSON.stringify(os.cpus(), null, 2)} with
            ${JSON.stringify(os.totalmem(), null, 2)} total RAM !!!`);

// Global references to windows to prevent them from being garbage collected
let mainWindow: BrowserWindow;
let cardanoNode: CardanoNode;

const openAbout = () => {
  if (mainWindow) mainWindow.webContents.send(OPEN_ABOUT_DIALOG_CHANNEL);
};

const goToAdaRedemption = () => {
  if (mainWindow) mainWindow.webContents.send(GO_TO_ADA_REDEMPTION_SCREEN_CHANNEL);
};

const goToNetworkStatus = () => {
  if (mainWindow) mainWindow.webContents.send(GO_TO_NETWORK_STATUS_SCREEN_CHANNEL);
};

const restartInSafeMode = async () => {
  Logger.info('restarting in SafeMode …');
  if (cardanoNode) await cardanoNode.stop();
  Logger.info('Exiting Daedalus with code 21.');
  safeExitWithCode(21);
};

const restartWithoutSafeMode = async () => {
  Logger.info('restarting without SafeMode …');
  if (cardanoNode) await cardanoNode.stop();
  Logger.info('Exiting Daedalus with code 22.');
  safeExitWithCode(22);
};

const menuActions = {
  openAbout,
  goToAdaRedemption,
  goToNetworkStatus,
  restartInSafeMode,
  restartWithoutSafeMode,
};

app.on('ready', async () => {
  const isProd = process.env.NODE_ENV === 'production';
  const isStartedByLauncher = !!process.env.LAUNCHER_CONFIG;
  if (isProd && !isStartedByLauncher) {
    const isWindows = process.platform === 'win32';
    const dialogTitle = 'Daedalus improperly started!';
    const dialogMessage = isWindows ?
      'Please start Daedalus using the icon in the Windows start menu or using Daedalus icon on your desktop.' :
      'Daedalus was launched without needed configuration. Please start Daedalus using the shortcut provided by the installer.';
    dialog.showErrorBox(dialogTitle, dialogMessage);
    app.quit();
  }

  ensureXDGDataIsSet();
  await installChromeExtensions(environment.isDev());

  // Detect safe mode
  const isInSafeMode = includes(process.argv.slice(1), '--safe-mode');

  mainWindow = createMainWindow(isInSafeMode);
  cardanoNode = setupCardano(launcherConfig, mainWindow);

  if (environment.isDev()) {
    // Connect to electron-connect server which restarts / reloads windows on file changes
    client.create(mainWindow);
  }

  // Build app menus
  let menu;
  if (process.platform === 'darwin') {
    menu = Menu.buildFromTemplate(osxMenu(app, mainWindow, menuActions, isInSafeMode));
    Menu.setApplicationMenu(menu);
  } else {
    menu = Menu.buildFromTemplate(winLinuxMenu(app, mainWindow, menuActions, isInSafeMode));
    mainWindow.setMenu(menu);
  }

  // Hide application window on Cmd+H hotkey (OSX only!)
  if (process.platform === 'darwin') {
    app.on('activate', () => {
      if (!mainWindow.isVisible()) app.show();
    });

    mainWindow.on('focus', () => {
      globalShortcut.register('CommandOrControl+H', app.hide);
    });

    mainWindow.on('blur', () => {
      globalShortcut.unregister('CommandOrControl+H');
    });
  }

  // Wait for controlled cardano-node shutdown before quitting the app
  app.on('before-quit', async (event) => {
    event.preventDefault(); // prevent Daedalus from quitting immediately
    if (cardanoNode.state === CardanoNodeStates.STOPPING) return;
    try {
      Logger.info(`Daedalus:before-quit: stopping cardano-node with PID ${cardanoNode.pid || 'null'}`);
      await cardanoNode.stop();
      Logger.info('Daedalus:before-quit: exiting Daedalus with code 0.');
      safeExitWithCode(0);
    } catch (stopError) {
      Logger.info(`Daedalus:before-quit: cardano-node did not exit correctly: ${stopError}`);
      safeExitWithCode(0);
    }
  });
});
<|endoftext|>


<commit_before>//Module is a Singelton
define(function(require) {

  var $ = require('jquery');
  var _ = require('underscore');
  var Backbone = require('backbone');
  var Store = require('localstorage');
  var Doc = require('models/doc');
  var settings = require('models/settings');

  var remoteStorageDocuments = require('remotestorage-documents');

  remoteStorage.claimAccess('documents', 'rw');

  var Docs = Backbone.Collection.extend({

    model: Doc,

    localStorage: remoteStorageDocuments.getBackboneStore('notes'),

    initialize: function(models) {

      this.fetch({
        success: _.bind(function() {
          if (this.isEmpty()) {
            this.addNew();
          }
        }, this)
      });

      this
        .on('reset', this.updateColor)
        .on('change:content', this.sort)
        .on('change:lastEdited', this.saveWhenIdle)
        .on('change:title', this.updateUrl);
    },

    addNew: function() {
      this.create({
        id: _.uniqueId(),
        lastEdited: new Date().getTime()
      });
    },

    // Sort by 'lastEdited'
    comparator: function(first, second) {
      return first.get('lastEdited') > second.get('lastEdited') ? -1 : 1 ;
    },

    updateColor: _.throttle(function() {
      this.each(function(doc) {
        doc.calculateColor();
      });
    }, 3000),

    saveTimeout: undefined,
    saveWhenIdle: function(doc) {
      clearTimeout(this.saveTimeout);
      this.saveTimeout = setTimeout(_.bind(doc.save, doc), 300);
    },

    updateUrl: function(doc) {
      var url = encodeURI(doc.get('title').toLowerCase().replace(/\s| /g, '-'));
      if (url.length < 1) {
        doc.set('url', '');
        return;
      }
      var len = this.filter(function(doc) {
	return new RegExp('^' + url + '(-[0-9]|$)').test(doc.get('url'));
      }).length;
      url = len < 1 ? url : url + '-' + len;
      doc.set('url', url);
    },

    deleteEmpty: function() {
      var previousDoc = this.get(settings.previous('openDocId'));
      if (previousDoc && previousDoc.isEmpty()) {
        this.remove(previousDoc);
      }
    }

  });

  var docs = new Docs();

  var hasConnected = false;

  remoteStorage.onWidget('state', function(state) {
    if((! hasConnected) && state == 'connected') {
      hasConnected = true;

      docs.reset(docs.localStorage.findAll());
    }
  })

  return docs;

});
<commit_msg>fix #45<commit_after>//Module is a Singelton
define(function(require) {

  var $ = require('jquery');
  var _ = require('underscore');
  var Backbone = require('backbone');
  var Store = require('localstorage');
  var Doc = require('models/doc');
  var settings = require('models/settings');

  var remoteStorageDocuments = require('remotestorage-documents');

  remoteStorage.claimAccess('documents', 'rw');

  var Docs = Backbone.Collection.extend({

    model: Doc,

    localStorage: remoteStorageDocuments.getBackboneStore('notes'),

    initialize: function(models) {

      this.fetch({
        success: _.bind(function() {
          if (this.isEmpty()) {
            this.addNew();
          }
        }, this)
      });

      this
        .on('reset', this.updateColor)
        .on('change:content', this.sort)
        .on('change:lastEdited', this.saveWhenIdle)
        .on('change:title', this.updateUrl);
    },

    addNew: function() {
      this.create({
        id: _.uniqueId(),
        lastEdited: new Date().getTime()
      });
    },

    // Sort by 'lastEdited'
    comparator: function(first, second) {
      return first.get('lastEdited') > second.get('lastEdited') ? -1 : 1 ;
    },

    updateColor: _.throttle(function() {
      this.each(function(doc) {
        doc.calculateColor();
      });
    }, 3000),

    saveTimeout: undefined,
    saveWhenIdle: function(doc) {
      clearTimeout(this.saveTimeout);
      this.saveTimeout = setTimeout(_.bind(doc.save, doc), 300);
    },

    updateUrl: function(doc) {
      var url = encodeURI(doc.get('title').toLowerCase().replace(/\s| /g, '-'));
      if (url.length < 1) {
        doc.set('url', '');
        return;
      }
      var len = this.filter(function(doc) {
	return new RegExp('^' + url + '(-[0-9]|$)').test(doc.get('url'));
      }).length;
      url = len < 1 ? url : url + '-' + len;
      doc.set('url', url);
    },

    deleteEmpty: function() {
      var previousDoc = this.get(settings.previous('openDocId'));
      if (previousDoc && previousDoc.isEmpty()) {
        this.remove(previousDoc);
      }
    }

  });

  var docs = new Docs();

  var hasConnected = false;

  remoteStorage.onWidget('state', function(state) {
    if ((! hasConnected) && state == 'connected') {
      hasConnected = true;

      docs.reset(docs.localStorage.findAll());
    } else if ( state == 'disconnected') {
      docs.reset();
    }
  });

  return docs;

});
<|endoftext|>


<commit_before>var util = require('util');
var _ = require('lodash');

var rfUtils = require('./utils');

module.exports = function(config) {
    return new handler(config);
}

handler = function(config) {
    this.config = config;

    this.NotFoundError.prototype = Object.create(Error.prototype);
    this.AccessDeniedError.prototype = Object.create(Error.prototype);
    this.MissingParametersError.prototype = Object.create(Error.prototype);
    this.ValidationParametersError.prototype = Object.create(Error.prototype);

    return this;
}

handler.prototype.handleError = function(e, req, res, next) {

    var self = this;

    if (util.isError(e)) {

        // Better to use EventEmitter no ?
        if (this.config.debug == true) {
            console.log(e.stack)
        }

        var errorDisplayed = {error: rfUtils.errorsToString(e)};

        if (this.config.debug) {
            errorDisplayed.stack = e.stack;
        }

        // Handle default Javascript Error as Internal Error
        if (e instanceof TypeError || e instanceof ReferenceError) {
            return res.status(500).json(self.formatError(500, rfUtils.errorsToString(e), ""));
        }

        // Handle our rest-framework error
        switch (e.name) {
            case 'NotFoundError':
                return res.status(404).json(self.formatError(404, rfUtils.errorsToString(e), e.details));
                break;
            case 'ValidationParametersError':
                return res.status(400).json(self.formatError(400, rfUtils.errorsToString(e), e.details));
                break;
            case 'MissingParametersError':
                return res.status(400).json(self.formatError(400, rfUtils.errorsToString(e), e.details));
                break;
            case 'AccessDeniedError':
                return res.status(403).json(self.formatError(403, rfUtils.errorsToString(e), e.details));
                break;
        }

        // If you emit custom error with statusCode
        if (e.statusCode != undefined) {
            return res.status(e.statusCode).json(self.formatError(e.statusCode, rfUtils.errorsToString(e), e.details != undefined ? e.details : ""));
        }

        // bad use of rest-framework
        return res.status(500).json(self.formatError(500, rfUtils.errorsToString(e), e.details != undefined ? e.details : ""));
    }

    return res.status(400).json(self.formatError(500, e, ""));
}

handler.prototype.NotFoundError = function(message, type, id)
{
    var self = this;

    self.type = type;
    self.message = "NOT_FOUND";
    self.item_id = id;
    if (message != "") {
        self.message = message;
    }

    self.details = type + " not found with id: " + id;
    self.name = 'NotFoundError';

    Error.captureStackTrace(this, handler.prototype.NotFoundError);
    return self;
}

handler.prototype.AccessDeniedError = function(message, reason)
{
    var self = this;

    self.message = "NOT_ALLOWED";
    if (message != "") {
        self.message = message;
    }

    self.details = reason;
    self.reason = reason;

    self.name = 'AccessDeniedError';
    Error.captureStackTrace(this, handler.prototype.AccessDeniedError);
    return self;
}

handler.prototype.MissingParametersError = function(message, fields)
{
    var self = this;

    self.message = "MISSING_PARAMETERS";
    if (message != "") {
        self.message = message;
    }

    if (_.isArray(fields)) {
        self.details = fields.join(",");
    }
    else {
        self.details = "";
    }

    self.name = 'MissingParametersError';
    self.fields = fields;

    Error.captureStackTrace(this, handler.prototype.MissingParametersError);
    return self;
}

handler.prototype.ValidationParametersError = function(domainsErrors)
{
    var self = this;

    self.message = "INVALID_PARAMETERS";

    var messages = []
    var errorOnField = [];
    _.each(domainsErrors, function(domain) {

        try {
            var flatError = domain.flat();
            _.forIn(flatError, function(value, key) {
                errorOnField.push({
                    "field": key,
                    "error": value,
                    "on": domain.applyOn
                });
            });
        } catch (rulesError) {
            errorOnField.push({
                "field": rulesError.path,
                "error": rulesError.message,
                "on": domain.applyOn
            });
        }

        // messages.push(JSON.stringify(e.flat()));
    });

    self.details = {
        errors: _.values(errorOnField)
    }

    self.name = 'ValidationParametersError';

    Error.captureStackTrace(this, handler.prototype.ValidationParametersError);
    return self;
}

handler.prototype.formatError = function(statusCode, message, details) {

    return {
        statusCode: statusCode,
        error: message,
        details: details,
        date: new Date()
    }
}<commit_msg>bug fix<commit_after>var util = require('util');
var _ = require('lodash');

var rfUtils = require('./utils');

module.exports = function(config) {
    return new handler(config);
}

handler = function(config) {
    this.config = config;

    this.NotFoundError.prototype = Object.create(Error.prototype);
    this.AccessDeniedError.prototype = Object.create(Error.prototype);
    this.MissingParametersError.prototype = Object.create(Error.prototype);
    this.ValidationParametersError.prototype = Object.create(Error.prototype);

    return this;
}

handler.prototype.handleError = function(e, req, res, next) {

    var self = this;

    if (util.isError(e)) {

        // Better to use EventEmitter no ?
        if (this.config.debug == true) {
            console.log(e.stack)
        }

        var errorDisplayed = {error: rfUtils.errorsToString(e)};

        if (this.config.debug) {
            errorDisplayed.stack = e.stack;
        }

        // Handle default Javascript Error as Internal Error
        if (e instanceof TypeError || e instanceof ReferenceError) {
            return res.status(500).json(self.formatError(500, rfUtils.errorsToString(e), ""));
        }

        // Handle our rest-framework error
        switch (e.name) {
            case 'NotFoundError':
                return res.status(404).json(self.formatError(404, rfUtils.errorsToString(e), e.details));
                break;
            case 'ValidationParametersError':
                return res.status(400).json(self.formatError(400, rfUtils.errorsToString(e), e.details));
                break;
            case 'MissingParametersError':
                return res.status(400).json(self.formatError(400, rfUtils.errorsToString(e), e.details));
                break;
            case 'AccessDeniedError':
                return res.status(403).json(self.formatError(403, rfUtils.errorsToString(e), e.details));
                break;
        }

        // If you emit custom error with statusCode
        if (e.statusCode != undefined) {
            return res.status(e.statusCode).json(self.formatError(e.statusCode, rfUtils.errorsToString(e), e.details != undefined ? e.details : ""));
        }

        // bad use of rest-framework
        return res.status(500).json(self.formatError(500, rfUtils.errorsToString(e), e.details != undefined ? e.details : ""));
    }

    return res.status(500).json(self.formatError(500, e, ""));
}

handler.prototype.NotFoundError = function(message, type, id)
{
    var self = this;

    self.type = type;
    self.message = "NOT_FOUND";
    self.item_id = id;
    if (message != "") {
        self.message = message;
    }

    self.details = type + " not found with id: " + id;
    self.name = 'NotFoundError';

    Error.captureStackTrace(this, handler.prototype.NotFoundError);
    return self;
}

handler.prototype.AccessDeniedError = function(message, reason)
{
    var self = this;

    self.message = "NOT_ALLOWED";
    if (message != "") {
        self.message = message;
    }

    self.details = reason;
    self.reason = reason;

    self.name = 'AccessDeniedError';
    Error.captureStackTrace(this, handler.prototype.AccessDeniedError);
    return self;
}

handler.prototype.MissingParametersError = function(message, fields)
{
    var self = this;

    self.message = "MISSING_PARAMETERS";
    if (message != "") {
        self.message = message;
    }

    if (_.isArray(fields)) {
        self.details = fields.join(",");
    }
    else {
        self.details = "";
    }

    self.name = 'MissingParametersError';
    self.fields = fields;

    Error.captureStackTrace(this, handler.prototype.MissingParametersError);
    return self;
}

handler.prototype.ValidationParametersError = function(domainsErrors)
{
    var self = this;

    self.message = "INVALID_PARAMETERS";

    var messages = []
    var errorOnField = [];
    _.each(domainsErrors, function(domain) {

        try {
            var flatError = domain.flat();
            _.forIn(flatError, function(value, key) {
                errorOnField.push({
                    "field": key,
                    "error": value,
                    "on": domain.applyOn
                });
            });
        } catch (rulesError) {
            errorOnField.push({
                "field": rulesError.path,
                "error": rulesError.message,
                "on": domain.applyOn
            });
        }

        // messages.push(JSON.stringify(e.flat()));
    });

    self.details = {
        errors: _.values(errorOnField)
    }

    self.name = 'ValidationParametersError';

    Error.captureStackTrace(this, handler.prototype.ValidationParametersError);
    return self;
}

handler.prototype.formatError = function(statusCode, message, details) {

    return {
        statusCode: statusCode,
        error: message,
        details: details,
        date: new Date()
    }
}<|endoftext|>


<commit_before>// @flow
// Functions to initialize bits of the global state, as appropriate

import {NetInfo} from 'react-native-netinfo'
import {getEnabledTools} from './parts/help'
import {loadFavoriteBuildings} from './parts/buildings'
import {loadAcknowledgement} from './parts/settings'
import {loadRecentSearches, loadRecentFilters} from './parts/courses'

export async function init(store: {dispatch: any => any}) {
	// this function runs in two parts: the things that don't care about
	// network, and those that do.

	// kick off the parts that don't care about network in parallel
	await Promise.all([
		store.dispatch(loadAcknowledgement()),
		store.dispatch(loadFavoriteBuildings()),
		store.dispatch(loadRecentSearches()),
		store.dispatch(loadRecentFilters()),
	])

	// wait for our first connection check to happen
	await NetInfo.isConnected.fetch()

	// then go do the network stuff in parallel
	await Promise.all([
		store.dispatch(getEnabledTools()),
	])
}
<commit_msg>prettify<commit_after>// @flow
// Functions to initialize bits of the global state, as appropriate

import {NetInfo} from 'react-native-netinfo'
import {getEnabledTools} from './parts/help'
import {loadFavoriteBuildings} from './parts/buildings'
import {loadAcknowledgement} from './parts/settings'
import {loadRecentSearches, loadRecentFilters} from './parts/courses'

export async function init(store: {dispatch: any => any}) {
	// this function runs in two parts: the things that don't care about
	// network, and those that do.

	// kick off the parts that don't care about network in parallel
	await Promise.all([
		store.dispatch(loadAcknowledgement()),
		store.dispatch(loadFavoriteBuildings()),
		store.dispatch(loadRecentSearches()),
		store.dispatch(loadRecentFilters()),
	])

	// wait for our first connection check to happen
	await NetInfo.isConnected.fetch()

	// then go do the network stuff in parallel
	await Promise.all([store.dispatch(getEnabledTools())])
}
<|endoftext|>