    send(envelope, message, done) {
        if (!message) {
            return done(this._formatError('Empty message', 'EMESSAGE', false, 'API'));
        }

        const isDestroyedMessage = this._isDestroyedMessage('send message');
        if (isDestroyedMessage) {
            return done(this._formatError(isDestroyedMessage, 'ECONNECTION', false, 'API'));
        }

        // reject larger messages than allowed
        if (this._maxAllowedSize && envelope.size > this._maxAllowedSize) {
            return setImmediate(() => {
                done(this._formatError('Message size larger than allowed ' + this._maxAllowedSize, 'EMESSAGE', false, 'MAIL FROM'));
            });
        }

        // ensure that callback is only called once
        let returned = false;
        let callback = function() {
            if (returned) {
                return;
            }
            returned = true;

            done(...arguments);
        };

        if (typeof message.on === 'function') {
            message.on('error', err => callback(this._formatError(err, 'ESTREAM', false, 'API')));
        }

        let startTime = Date.now();
        this._setEnvelope(envelope, (err, info) => {
            if (err) {
                return callback(err);
            }
            let envelopeTime = Date.now();
            let stream = this._createSendStream((err, str) => {
                if (err) {
                    return callback(err);
                }

                info.envelopeTime = envelopeTime - startTime;
                info.messageTime = Date.now() - envelopeTime;
                info.messageSize = stream.outByteCount;
                info.response = str;

                return callback(null, info);
            });
            if (typeof message.pipe === 'function') {
                message.pipe(stream);
            } else {
                stream.write(message);
                stream.end();
            }
        });
    }


0),!1,null,0,v));c.push(new mxConnectionConstraint(new mxPoint(0,0),!1,null,0,.5*v));return c};Ka.prototype.getConstraints=function(c,l,x){c=[];var p=Math.max(0,Math.min(l,parseFloat(mxUtils.getValue(this.style,"dx",this.dx)))),v=Math.max(0,Math.min(x,parseFloat(mxUtils.getValue(this.style,"dy",this.dy))));c.push(new mxConnectionConstraint(new mxPoint(0,0),!1));c.push(new mxConnectionConstraint(new mxPoint(.5,0),!1));c.push(new mxConnectionConstraint(new mxPoint(1,0),!1));c.push(new mxConnectionConstraint(new mxPoint(0,
0),!1,null,l,.5*v));c.push(new mxConnectionConstraint(new mxPoint(0,0),!1,null,l,v));c.push(new mxConnectionConstraint(new mxPoint(0,0),!1,null,.5*(l+p),v));c.push(new mxConnectionConstraint(new mxPoint(0,0),!1,null,p,v));c.push(new mxConnectionConstraint(new mxPoint(0,0),!1,null,p,.5*(x+v)));c.push(new mxConnectionConstraint(new mxPoint(0,0),!1,null,p,x));c.push(new mxConnectionConstraint(new mxPoint(0,0),!1,null,.5*p,x));c.push(new mxConnectionConstraint(new mxPoint(0,.5),!1));c.push(new mxConnectionConstraint(new mxPoint(0,
1),!1));return c};bb.prototype.constraints=[new mxConnectionConstraint(new mxPoint(0,0),!1),new mxConnectionConstraint(new mxPoint(0,.5),!1),new mxConnectionConstraint(new mxPoint(0,1),!1),new mxConnectionConstraint(new mxPoint(.25,.5),!1),new mxConnectionConstraint(new mxPoint(.5,.5),!1),new mxConnectionConstraint(new mxPoint(.75,.5),!1),new mxConnectionConstraint(new mxPoint(1,0),!1),new mxConnectionConstraint(new mxPoint(1,.5),!1),new mxConnectionConstraint(new mxPoint(1,1),!1)];Za.prototype.getConstraints=


  function tryNextAuth() {
    hasSentAuth = false;
    var auth = authHandler(curAuthsLeft, curPartial, doNextAuth);
    if (hasSentAuth || auth === undefined)
      return;
    doNextAuth(auth);
  }


emailIconClassName: this.getMetadata().get(['clientDefs', 'Email', 'iconClass']) || ''
            }, Dep.prototype.data.call(this));
        },

        setup: function () {
            var data = this.model.get('data') || {};

            this.emailId = data.emailId;
            this.emailName = data.emailName;

            if (
                this.parentModel
                &&
                (this.model.get('parentType') == this.parentModel.name && this.model.get('parentId') == this.parentModel.id)
            ) {
                if (this.model.get('post')) {
                    this.createField('post', null, null, 'views/stream/fields/post');
                    this.hasPost = true;
                }
                if ((this.model.get('attachmentsIds') || []).length) {
                    this.createField('attachments', 'attachmentMultiple', {}, 'views/stream/fields/attachment-multiple');
                    this.hasAttachments = true;
                }
            }

            this.messageData['email'] = '' + data.emailName + '';

            this.messageName = 'emailSent';

            this.messageData['by'] = '' + data.personEntityName + '';

            if (this.isThis) {
                this.messageName += 'This';
            }

            this.createMessage();
        },

    });
});


		function addEntryHandler(cat, entry, subCat)
		{
			mxEvent.addListener(entry, 'click', function()
			{
				if (currentEntry != entry)
				{
					currentEntry.style.backgroundColor = '';
					currentEntry = entry;
					currentEntry.style.backgroundColor = leftHighlight;

					div.scrollTop = 0;
					div.innerHTML = '';
					i0 = 0;

					templates = subCat? subCategories[cat][subCat] : categories[cat];
					oldTemplates = null;
					addTemplates(false);
				}
			});
		};


setup: function () {
            var data = this.model.get('data') || {};

            this.style = data.style || 'text-muted';

            this.messageTemplate = this.model.get('message') || data.message || '';

            this.userId = data.userId;

            this.messageData['entityType'] = Espo.Utils.upperCaseFirst((this.translate(data.entityType, 'scopeNames') || '').toLowerCase());

            this.messageData['user'] = '' + data.userName + '';
            this.messageData['entity'] = '' + data.entityName + '';

            this.createMessage();
        }


EditorUi.prototype.createSvgDataUri=function(c){EditorUi.logEvent("SHOULD NOT BE CALLED: createSvgDataUri");return Editor.createSvgDataUri(c)};EditorUi.prototype.embedCssFonts=function(c,e){EditorUi.logEvent("SHOULD NOT BE CALLED: embedCssFonts");return this.editor.embedCssFonts(c,e)};EditorUi.prototype.embedExtFonts=function(c){EditorUi.logEvent("SHOULD NOT BE CALLED: embedExtFonts");return this.editor.embedExtFonts(c)};EditorUi.prototype.exportToCanvas=function(c,e,g,k,m,q,v,x,A,z,L,M,n,y,K,B){EditorUi.logEvent("SHOULD NOT BE CALLED: exportToCanvas");


Progress.prototype.update = function(n){
  this.percent = n;
  return this;
};


  function onUSERAUTH_INFO_REQUEST(name, instructions, lang, prompts) {
    var nprompts = (Array.isArray(prompts) ? prompts.length : 0);
    if (nprompts === 0) {
      debug('DEBUG: Client: Sending automatic USERAUTH_INFO_RESPONSE');
      return stream.authInfoRes();
    }
    // we sent a keyboard-interactive user authentication request and now the
    // server is sending us the prompts we need to present to the user
    self.emit('keyboard-interactive',
              name,
              instructions,
              lang,
              prompts,
              function(answers) {
                stream.authInfoRes(answers);
              }
    );
  }


(function(a){"function"===typeof define&&define.amd?define(["jquery","datatables.net"],function(b){return a(b,window,document)}):"object"===typeof exports?module.exports=function(b,d){b||(b=window);if(!d||!d.fn.dataTable)d=require("datatables.net")(b,d).$;return a(d,b,b.document)}:a(jQuery,window,document)})(function(a){var b=a.fn.dataTable;a.extend(!0,b.defaults,{dom:'<"fg-toolbar ui-toolbar ui-widget-header ui-helper-clearfix ui-corner-tl ui-corner-tr"lfr>t<"fg-toolbar ui-toolbar ui-widget-header ui-helper-clearfix ui-corner-bl ui-corner-br"ip>',


            qtip: Tine.Tinebase.common.doubleEncode(attr.name),
            leaf: !!attr.account_grants,
            allowDrop: !!attr.account_grants && attr.account_grants.addGrant
        });

        // copy 'real' data to container space
        attr.container = Ext.copyTo({}, attr, Tine.Tinebase.Model.Container.getFieldNames());
    },


  beginningOfLine: function(){
    isatty && process.stdout.write('\u001b[0G');
  },


function parseURL (url) {
  if (typeof url === 'string') {
    url = new URL(url)
  }

  if (!url || typeof url !== 'object') {
    throw new InvalidArgumentError('invalid url')
  }

  if (url.port != null && url.port !== '' && !Number.isFinite(parseInt(url.port))) {
    throw new InvalidArgumentError('invalid port')
  }

  if (url.path != null && typeof url.path !== 'string') {
    throw new InvalidArgumentError('invalid path')
  }

  if (url.pathname != null && typeof url.pathname !== 'string') {
    throw new InvalidArgumentError('invalid pathname')
  }

  if (url.hostname != null && typeof url.hostname !== 'string') {
    throw new InvalidArgumentError('invalid hostname')
  }

  if (url.origin != null && typeof url.origin !== 'string') {
    throw new InvalidArgumentError('invalid origin')
  }

  if (!/^https?:/.test(url.origin || url.protocol)) {
    throw new InvalidArgumentError('invalid protocol')
  }

  if (!(url instanceof URL)) {
    const port = url.port != null
      ? url.port
      : (url.protocol === 'https:' ? 443 : 80)
    const origin = url.origin != null
      ? url.origin
      : `${url.protocol}//${url.hostname}:${port}`
    const path = url.path != null
      ? url.path
      : `${url.pathname || ''}${url.search || ''}`

    url = new URL(path, origin)
  }

  return url
}


function detectIE() {
    var ua = window.navigator.userAgent;

    var msie = ua.indexOf('MSIE ');
    if (msie > 0) {
        // IE 10 or older => return version number
        return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
    }

    var trident = ua.indexOf('Trident/');
    if (trident > 0) {
        // IE 11 => return version number
        var rv = ua.indexOf('rv:');
        return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
    }

    var edge = ua.indexOf('Edge/');
    if (edge > 0) {
        // Edge (IE 12+) => return version number
        return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
    }

    // other browser
    return false;
}


    AnsiUp.prototype.transform_to_html = function (fragment) {
        var txt = fragment.text;
        if (txt.length === 0)
            return txt;
        if (this._escape_for_html)
            txt = this.escape_txt_for_html(txt);
        if (!fragment.bold && fragment.fg === null && fragment.bg === null)
            return txt;
        var styles = [];
        var classes = [];
        var fg = fragment.fg;
        var bg = fragment.bg;
        if (fragment.bold)
            styles.push('font-weight:bold');
        if (!this._use_classes) {
            if (fg)
                styles.push("color:rgb(" + fg.rgb.join(',') + ")");
            if (bg)
                styles.push("background-color:rgb(" + bg.rgb + ")");
        }
        else {
            if (fg) {
                if (fg.class_name !== 'truecolor') {
                    classes.push(fg.class_name + "-fg");
                }
                else {
                    styles.push("color:rgb(" + fg.rgb.join(',') + ")");
                }
            }
            if (bg) {
                if (bg.class_name !== 'truecolor') {
                    classes.push(bg.class_name + "-bg");
                }
                else {
                    styles.push("background-color:rgb(" + bg.rgb.join(',') + ")");
                }
            }
        }
        var class_string = '';
        var style_string = '';
        if (classes.length)
            class_string = " class=\"" + classes.join(' ') + "\"";
        if (styles.length)
            style_string = " style=\"" + styles.join(';') + "\"";
        return "<span" + style_string + class_string + ">" + txt + "</span>";
    };


                sort_key: (tagset_id ? all_tags[tagset_id].t.toLowerCase() :
                           '') + text.toLowerCase()
            };
            var div = $(create_tag_html(
                text, description, my_name, new_tag_counter,
                tagset ? tagset.attr('data-id') : null));
            div.addClass('ui-selected').on('click', tag_click).tooltip({
                track: true,
                show: false,
                hide: false,
                items: '[data-content]',
                content: function() {
                    return $(this).data('content');
                }
            });
            $("div.ui-selected", div_selected_tags).removeClass('ui-selected');
            div_selected_tags.append(div);
            tag_input.val('').trigger('focus');
            description_input.val('');
            enable_buttons();
        }


setup: function () {
            var data = this.model.get('data') || {};

            this.userId = data.userId;

            this.messageData['entityType'] = Espo.Utils.upperCaseFirst((this.translate(data.entityType, 'scopeNames') || '').toLowerCase());
            this.messageData['entity'] = '' + data.entityName + '';

            this.createMessage();
        },


function normalizePath(path) {
  return (
    pathCache.get(path) ||
    pathCache.set(
      path,
      split(path).map(function(part) {
        return part.replace(CLEAN_QUOTES_REGEX, '$2')
      })
    )
  )
}


Server.prototype.listen = function() {
  this._srv.listen.apply(this._srv, arguments);
  return this;
};


_currentRules:function _currentRules() {
        if (this.conditionStack.length && this.conditionStack[this.conditionStack.length - 1]) {
            return this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules;
        } else {
            return this.conditions["INITIAL"].rules;
        }
    },


'select': function(e) {

		if((e.hasAttribute('multiple') === false) && $(e).hasClass('nosearch') === false) {
			$(e).select2({
				dropdownAutoWidth : true,
				// break a select option item into multi lines
				templateResult: function(item) {
					var selectionText = item.text.split('\n');
					var returnString = $('');
					$.each(selectionText, function(index, value){
						line = value === undefined ? '' : value;
						returnString.append(line + '
');
					})

					return returnString;
				}
			});
			$(e).on('select2:close', function() {
				$(this).focus();
			});
			$(e).on('select2:open', function(e2){

				$('.dynamic_combo_btn').remove();

				var target_id = $(e2.target).attr('id');
				var search_btn = $('#_'+target_id+'_search').clone();
				var add_btn = $('#_'+target_id+'_add').clone();
				$(search_btn).addClass('dynamic_combo_btn');
				$(add_btn).addClass('dynamic_combo_btn');
				$(search_btn).removeAttr('id hidden');
				$(add_btn).removeAttr('id hidden');

				$('.select2-dropdown').append(search_btn);
				if($(add_btn) !== 'undefined')
					$('.select2-dropdown').append(add_btn);
				$(search_btn).add(add_btn).click(function(){
					$('select').select2('close');
				});

			});
		}
	}


this.spacing=0}function Ca(){mxArrowConnector.call(this);this.spacing=0}function Ra(){mxActor.call(this)}function ab(){mxRectangleShape.call(this)}function Ka(){mxActor.call(this)}function bb(){mxActor.call(this)}function Pa(){mxActor.call(this)}function Za(){mxActor.call(this)}function z(){mxActor.call(this)}function L(){mxActor.call(this)}function M(){mxActor.call(this)}function T(){mxActor.call(this)}function ca(){mxActor.call(this)}function ia(){mxActor.call(this)}function ma(){mxEllipse.call(this)}


  parse() {
    // 获取数据
    const info = antSword['ipcRenderer'].sendSync('shell-findOne', this.manager.opt['_id']);
    const conf = info['database'] || {};
    // 刷新UI
    // 1.清空数据
    this.tree.deleteChildItems(0);
    // 2.添加数据
    let items = [];
    for (let _ in conf) {
      items.push({
        id: `conn::${_}`,
        text: `${conf[_]['type']}:\/\/${conf[_]['user']}@${conf[_]['host']}`,
        im0: this.manager.list.imgs[0],
        im1: this.manager.list.imgs[0],
        im2: this.manager.list.imgs[0]
      });
    }
    // 3.刷新UI
    this.tree.parse({
      id: 0,
      item: items
    }, 'json');
    // 禁用按钮
    this.disableToolbar();
    this.disableEditor();
  }


data: function () {
            return _.extend({
                relatedTypeString: this.translateEntityType(this.entityType)
            }, Dep.prototype.data.call(this));
        },

        init: function () {
            if (this.getUser().isAdmin()) {
                this.isRemovable = true;
            }
            Dep.prototype.init.call(this);
        },

        setup: function () {
            var data = this.model.get('data') || {};

            this.entityType = this.model.get('relatedType') || data.entityType || null;
            this.entityId = this.model.get('relatedId') || data.entityId || null;
            this.entityName = this.model.get('relatedName') ||  data.entityName || null;

            this.messageData['relatedEntityType'] = this.translateEntityType(this.entityType);
            this.messageData['relatedEntity'] = '' + this.entityName +'';

            this.createMessage();
        },
    });
});


function filterLeaks(ok, globals) {
  return filter(globals, function(key){
    // Firefox and Chrome exposes iframes as index inside the window object
    if (/^d+/.test(key)) return false;

    // in firefox
    // if runner runs in an iframe, this iframe's window.getInterface method not init at first
    // it is assigned in some seconds
    if (global.navigator && /^getInterface/.test(key)) return false;

    // an iframe could be approached by window[iframeIndex]
    // in ie6,7,8 and opera, iframeIndex is enumerable, this could cause leak
    if (global.navigator && /^\d+/.test(key)) return false;

    // Opera and IE expose global variables for HTML element IDs (issue #243)
    if (/^mocha-/.test(key)) return false;

    var matched = filter(ok, function(ok){
      if (~ok.indexOf('*')) return 0 == key.indexOf(ok.split('*')[0]);
      return key == ok;
    });
    return matched.length == 0 && (!global.navigator || 'onerror' !== key);
  });
}


        updateWizard:   function () {
            var $wizard = $('#button-wizard');
            if (main.objects['system.adapter.discovery.0']) {
                if (!$wizard.data('inited')) {
                    $wizard.data('inited', true);
                    $wizard/*.button({
                        icons: {primary: ' ui-icon-search'},
                        text: false
                    })*/.on('click', function () {
                        // open configuration dialog
                        main.navigate({
                            tab: 'instances',
                            dialog: 'config',
                            params: 'system.adapter.discovery.0'
                        });
                    }).attr('title', _('Device discovery'));
                }
                $wizard.show();

                // Show wizard dialog
                if (!main.systemConfig.common.wizard && main.systemConfig.common.licenseConfirmed) {
                    $wizard.trigger('click');
                }
            } else {
                $wizard.hide();
            }
        },


  handler: function () {
    this.connector = new PassiveConnector(this);
    return this.connector.setupServer()
    .then((server) => {
      const {port} = server.address();

      return this.reply(229, `EPSV OK (|||${port}|)`);
    });
  },


    $scope.reset = function() {
      bootbox.confirm('Are you sure you want to reset the foreign source definition to the default ?', function(ok) {
        if (ok) {
          RequisitionsService.startTiming();
          RequisitionsService.deleteForeignSourceDefinition($scope.foreignSource).then(
            function() { // success
              growl.success('The foreign source definition for ' + $scope.foreignSource + 'has been reseted.');
              $scope.initialize();
            },
            $scope.errorHandler
          );
        }
      });
    };


                            success: function(_result, _request){

                                var nodeData = Ext.util.JSON.decode(_result.responseText);
                                node.setText(_text);

                                this.scope.fireEvent('containerrename', nodeData, node, _text);

                            },


                filters.push({'condition': 'AND', 'filters': this.filterPanels[id].getValue(), 'id': id, label: this.filterPanels[id].title});
            }
        }

        // NOTE: always trigger a OR condition, otherwise we sould loose inactive FilterPanles
        //return filters.length == 1 ? filters[0].filters : [{'condition': 'OR', 'filters': filters}];
        return [{'condition': 'OR', 'filters': filters}];
    },


$.fn.elfindermkdirbutton = function(cmd) {
	return this.each(function() {
		var button = $(this).elfinderbutton(cmd);

		cmd.change(function() {
			button.attr('title', cmd.value);
		});
	});
}


setup: function () {
            var data = this.model.get('data');

            this.assignedUserId = data.assignedUserId || null;
            this.assignedUserName = data.assignedUserName || null;

            this.messageData['assignee'] = '' + data.assignedUserName + '';

            if (this.isUserStream) {
                if (this.assignedUserId) {
                    if (this.assignedUserId == this.model.get('createdById')) {
                        this.messageName += 'Self';
                    } else {
                        if (this.assignedUserId == this.getUser().id) {
                            this.messageName += 'You';
                        }
                    }
                } else {
                    this.messageName += 'Void';
                }
            } else {
                if (this.assignedUserId) {
                    if (this.assignedUserId == this.model.get('createdById')) {
                        this.messageName += 'Self';
                    }
                } else {
                    this.messageName += 'Void';
                }
            }

            this.createMessage();
        },


Client.prototype.forwardOut = function(boundAddr, boundPort, remoteAddr,
                                       remotePort, cb) {
  var opts = {
    boundAddr: boundAddr,
    boundPort: boundPort,
    remoteAddr: remoteAddr,
    remotePort: remotePort
  };
  return openChannel(this, 'forwarded-tcpip', opts, cb);
};


    $scope.save = function() {
      var form = this.fsForm;
      RequisitionsService.startTiming();
      RequisitionsService.saveForeignSourceDefinition($scope.foreignSourceDef).then(
        function() { // success
          growl.success('The definition for the requisition ' + $scope.foreignSource + ' has been saved.');
          form.$dirty = false;
        },
        $scope.errorHandler
      );
    };


			create    = function(dir, hash) {
				return $(tpl.replace(/\{id\}/, hash2id(dir? dir.hash : hash))
						.replace(/\{name\}/, fm.escape(dir? dir.name : hash))
						.replace(/\{cssclass\}/, dir? (fm.UA.Touch ? 'elfinder-touch ' : '')+fm.perms2class(dir) : '')
						.replace(/\{permissions\}/, (dir && (!dir.read || !dir.write))? ptpl : '')
						.replace(/\{title\}/, (dir && dir.path)? fm.escape(dir.path) : '')
						.replace(/\{symlink\}/, '')
						.replace(/\{style\}/, ''));
			},


        path: f.replace(/^(\/|[a-z]:\\\\)/, ''),
        mode: 0o644,
        size: 512,
        linkpath: null,
        uname: 'isaacs',
        gname: null,
        devmaj: 0,
        devmin: 0,
      })
      t.end()
    })


	this.openUrl = function(hash, download) {
		var file = files[hash],
			url  = '';

		if (!file || !file.read) {
			return '';
		}

		if (!download) {
			if (file.url) {
				if (file.url != 1) {
					return file.url;
				}
			} else if (cwdOptions.url && file.hash.indexOf(self.cwd().volumeid) === 0) {
				return cwdOptions.url + $.map(this.path2array(hash), function(n) { return encodeURIComponent(n); }).slice(1).join('/');
			}
		}

		url = this.options.url;
		url = url + (url.indexOf('?') === -1 ? '?' : '&')
			+ (this.oldAPI ? 'cmd=open&current='+file.phash : 'cmd=file')
			+ '&target=' + file.hash;

		if (download) {
			url += '&download=1';
		}

		$.each(this.options.customData, function(key, val) {
			url += '&' + encodeURIComponent(key) + '=' + encodeURIComponent(val);
		});

		return url;
	}


  deleteLine: function(){
    isatty && process.stdout.write('\u001b[2K');
  },


EditorUi.prototype.setStatusText = function(value)
{
	this.statusContainer.innerHTML = value;

	// Wraps simple status messages in a div for styling
	if (this.statusContainer.getElementsByTagName('div').length == 0)
	{
		this.statusContainer.innerHTML = '';
		var div = this.createStatusDiv(value);
		this.statusContainer.appendChild(div);
	}
};


export const redirectAnyRequest = response => {
  const {headers: {location}} = Response.message (response);
  const original = Response.request (response);
  const oldUrl = Request.url (original);
  const newUrl = mergeUrls (oldUrl, location);
  const request = Request (Request.options (original))
                          (newUrl)
                          (Request.body (original));

  return sameHost (oldUrl, newUrl) ? request : overHeaders (request, xs => (
    xs.filter (([name]) => !confidentialHeaders.includes (name.toLowerCase ()))
  ));
};


        function onSTAT(reqid, path) {
          if (path !== '/tmp/foo.txt')
            return sftpStream.status(reqid, STATUS_CODE.FAILURE);
          var mode = constants.S_IFREG; // Regular file
          mode |= constants.S_IRWXU; // read, write, execute for user
          mode |= constants.S_IRWXG; // read, write, execute for group
          mode |= constants.S_IRWXO; // read, write, execute for other
          sftpStream.attrs(reqid, {
            mode: mode,
            uid: 0,
            gid: 0,
            size: 3,
            atime: Date.now(),
            mtime: Date.now()
          });
        }
      });
    });


    $scope.addRequisition = function() {
      bootbox.prompt('A requisition is required, please enter the name for a new requisition', function(foreignSource) {
        if (foreignSource) {
          RequisitionsService.addRequisition(foreignSource).then(
            function() { // success
              RequisitionsService.synchronizeRequisition(foreignSource, false).then(
                function() {
                  growl.success('The requisition ' + foreignSource + ' has been created and synchronized.');
                  $scope.foreignSources.push(foreignSource);
                },
                $scope.errorHandler
              );
            },
            $scope.errorHandler
          );
        } else {
          window.location.href = Util.getBaseHref() + 'admin/opennms/index.jsp'; // TODO Is this the best way ?
        }
      });
    };


  _xmlEscape(str) {
    return str.replace(/[&<>']/g, (m) => XML_ESCAPE[m]);
  }


				name : function(f) {
					var name = fm.escape(f.name);
					!list && (name = name.replace(/([_.])/g, '$1'));
					return name;
				},


    render: function(relations) {
        if ((! relations) || (relations.length == 0)) {
            return '';
        }

        if (! this.recordClass) {
            if (! Tine[this.foreignApp]) {
                Tine.log.warn('Tine.widgets.relation.GridRenderer::render - ForeignApp not found: ' + this.foreignApp);
                return '';
            }

            this.recordClass = Tine[this.foreignApp].Model[this.foreignModel];
        }

        for (var index = 0; index < relations.length; index++) {
            var el = relations[index];
            if (el.type == this.type && el.related_model == this.relModel) {
                var record = new this.recordClass(el.related_record);
                return record.getTitle();
            }
        }
    }


var create_tag_html = function(text, description, owner, id, parent_id,
                                   is_tagset) {
        var cls = is_tagset ? "alltags-tagset" :
            (parent_id ? "alltags-childtag" : "alltags-tag");
        var html = "<div class='" + cls + "' data-id='" + id + "'";
        var tagset;
        if (parent_id) {
            html += " data-set='" + parent_id + "'";
            tagset = all_tags[parent_id].t;
        }
        if (id < 0) { // new tag, save description
            html += " data-description='" + encode_html(description) + "'";
        }
        var title = create_tag_title(description, owner, tagset);
        // Add content even if it is empty
        // and handle case for no tooltip in the tooltip code
        html += " data-content='" + title.replace(/'/g, "'") + "'";
        html += ">" + encode_html(text) + "
";
        return html;
    };


    $scope.removeAllNodes = function(foreignSource) {
      bootbox.confirm('Are you sure you want to remove all the nodes from ' + foreignSource + '?', function(ok) {
        if (ok) {
          RequisitionsService.startTiming();
          RequisitionsService.removeAllNodesFromRequisition(foreignSource).then(
            function() { // success
              growl.success('All the nodes from ' + foreignSource + ' have been removed, and the requisition has been synchronized.');
              var req = $scope.requisitionsData.getRequisition(foreignSource);
              req.reset();
            },
            $scope.errorHandler
          );
        }
      });
    };


    authHandler = function authHandler(authsLeft, partial, cb) {
      if (authPos === authsAllowed.length)
        return false;
      return authsAllowed[authPos++];
    };


Suite.prototype.beforeAll = function(fn){
  if (this.pending) return this;
  var hook = new Hook('"before all" hook', fn);
  hook.parent = this;
  hook.timeout(this.timeout());
  hook.slow(this.slow());
  hook.ctx = this.ctx;
  this._beforeAll.push(hook);
  this.emit('beforeAll', hook);
  return this;
};


    function draw(plot, ctx){
        var plotOffset = plot.getPlotOffset();

        ctx.save();
        ctx.translate(plotOffset.left, plotOffset.top);
        $.each(plot.getData(), function (i, s) {
            if (s.points.errorbars && (s.points.xerr.show || s.points.yerr.show))
                drawSeriesErrors(plot, ctx, s);
        });
        ctx.restore();
    }


	__get_uniq_index() {
		this.__globalCounter++;
		return this.__globalCounter-1;
	}


    main.resubscribeObjects = function () {
        for (var pattern in main.subscribesObjects) {
            if (main.subscribesObjects.hasOwnProperty(pattern) && main.subscribesObjects[pattern]) {
                main.socket.emit('subscribeObjects', pattern);
            }
        }
    };


const mergeUrls = base => input => (
  typeof input === 'string' ?
  new URL (input, base).href :
  base
);


Runnable.prototype.run = function(fn){
  var self = this
    , ms = this.timeout()
    , start = new Date
    , ctx = this.ctx
    , finished
    , emitted;

  if (ctx) ctx.runnable(this);

  // timeout
  if (this.async) {
    if (ms) {
      this.timer = setTimeout(function(){
        done(new Error('timeout of ' + ms + 'ms exceeded'));
        self.timedOut = true;
      }, ms);
    }
  }

  // called multiple times
  function multiple(err) {
    if (emitted) return;
    emitted = true;
    self.emit('error', err || new Error('done() called multiple times'));
  }

  // finished
  function done(err) {
    if (self.timedOut) return;
    if (finished) return multiple(err);
    self.clearTimeout();
    self.duration = new Date - start;
    finished = true;
    fn(err);
  }

  // for .resetTimeout()
  this.callback = done;

  // async
  if (this.async) {
    try {
      this.fn.call(ctx, function(err){
        if (err instanceof Error || toString.call(err) === "[object Error]") return done(err);
        if (null != err) return done(new Error('done() invoked with non-Error: ' + err));
        done();
      });
    } catch (err) {
      done(err);
    }
    return;
  }

  if (this.asyncOnly) {
    return done(new Error('--async-only option in use without declaring `done()`'));
  }

  // sync
  try {
    if (!this.pending) this.fn.call(ctx);
    this.duration = new Date - start;
    fn();
  } catch (err) {
    fn(err);
  }
};


  function onClose() {
    if (arguments.length >= 3) {
      assert(!self.state.clientClose,
             makeMsg(self.what, 'Received multiple close events for client'));
      self.state.clientClose = true;
    } else {
      assert(!self.state.serverClose,
             makeMsg(self.what, 'Received multiple close events for server'));
      self.state.serverClose = true;
    }
    if (self.state.clientClose && self.state.serverClose)
      next();
  }


function makeMsg(what, msg) {
  return '[' + group + what + ']: ' + msg;
}


module.exports = async function unadded() {
	const output = await exec('git add --dry-run .');

	return output
		.split('\n')
		.map(extract)
		.filter(Boolean)
	;
};


Runnable.prototype.globals = function(arr){
  var self = this;
  this._allowedGlobals = arr;
};


  function onCLOSE() {
    ending = true;
    self.emit('close');
  }


  deriveVersion: function (req, ctx) {
    return req.headers['accept-version']
  }


				function updatePageName()
				{
					pageMenu.innerHTML = '';

					if (ui.currentPage != null)
					{
						mxUtils.write(pageMenu, ui.currentPage.getName());
						var n = (ui.pages != null) ? ui.pages.length : 1;
						var idx = ui.getPageIndex(ui.currentPage);
						idx = (idx != null) ? idx + 1 : 1;
						var id = ui.currentPage.getId();
						pageMenu.setAttribute('title', ui.currentPage.getName() +
							' (' + idx + '/' + n + ')' + ((id != null) ?
							' [' + id + ']' : ''));
					}
				};


	var apply = function(color, disableUpdate, forceUpdate)
	{
		if (!applying)
		{
			var defaultValue = (defaultColor == 'null') ? null : defaultColor;

			applying = true;
			color = (/(^#?[a-zA-Z0-9]*$)/.test(color)) ? color : defaultValue;
			var tempColor = (color != null && color != mxConstants.NONE) ? color : defaultValue;

			var div = document.createElement('div');
			div.style.width = '36px';
			div.style.height = '12px';
			div.style.margin = '3px';
			div.style.border = '1px solid black';
			div.style.backgroundColor = (tempColor == 'default') ? defaultColorValue : tempColor;
			btn.innerHTML = '';
			btn.appendChild(div);

			if (color != null && color != mxConstants.NONE && color.length > 1 && typeof color === 'string')
			{
				var clr = (color.charAt(0) == '#') ? color.substring(1).toUpperCase() : color;
				var name = ColorDialog.prototype.colorNames[clr];
				btn.setAttribute('title', (name != null) ? name + ' (' + title + ')' : title);
			}

			if (color != null && color != mxConstants.NONE)
			{
				cb.setAttribute('checked', 'checked');
				cb.defaultChecked = true;
				cb.checked = true;
			}
			else
			{
				cb.removeAttribute('checked');
				cb.defaultChecked = false;
				cb.checked = false;
			}

			btn.style.display = (cb.checked || hideCheckbox) ? '' : 'none';

			if (callbackFn != null)
			{
				callbackFn(color == 'null' ? null : color);
			}

			value = color;

			if (!disableUpdate)
			{
				// Checks if the color value needs to be updated in the model
				if (forceUpdate || hideCheckbox || getColorFn() != value)
				{
					setColorFn(value == 'null' ? null : value, value);
				}
			}

			applying = false;
		}
	};


TagCreationContainer.prototype._tagInputEnd = function (event, span, textfield) {
    var that = this;
    if (textfield.val() == '' || textfield.val() == '#') { // if no input, get rid of new tag
        that._removeTag (span);
        that._unlockCreateTag(); // we're done with this tag, so a let another get created
    } else { // create new tag
        var value = textfield.val();
        value = value.replace(/#/g, ''); // strip illegal chars
        value = '#' + encodeURIComponent(value); // format into a tag

        that._afterCreateNewTag (textfield, value, span);

        that._unlockCreateTag(); // we're done with this tag, so a let another get created
    }
};


    $scope.addRequisition = function() {
      bootbox.prompt('A requisition is required, please enter the name for a new requisition', function(foreignSource) {
        if (foreignSource) {
          RequisitionsService.addRequisition(foreignSource).then(
            function() { // success
              RequisitionsService.synchronizeRequisition(foreignSource, false).then(
                function() {
                  growl.success('The requisition ' + foreignSource + ' has been created and synchronized.');
                  $scope.foreignSources.push(foreignSource);
                },
                $scope.errorHandler
              );
            },
            $scope.errorHandler
          );
        } else {
          window.location.href = Util.getBaseHref() + 'admin/opennms/index.jsp'; // TODO Is this the best way ?
        }
      });
    };


setup: function () {
            var data = this.model.get('data') || {};

            this.emailId = data.emailId;
            this.emailName = data.emailName;

            if (
                this.parentModel
                &&
                (this.model.get('parentType') == this.parentModel.name && this.model.get('parentId') == this.parentModel.id)
            ) {
                if (this.model.get('post')) {
                    this.createField('post', null, null, 'views/stream/fields/post');
                    this.hasPost = true;
                }
                if ((this.model.get('attachmentsIds') || []).length) {
                    this.createField('attachments', 'attachmentMultiple', {}, 'views/stream/fields/attachment-multiple');
                    this.hasAttachments = true;
                }
            }

            this.messageData['email'] = '' + data.emailName + '';

            this.messageName = 'emailSent';

            this.messageData['by'] = '' + data.personEntityName + '';

            if (this.isThis) {
                this.messageName += 'This';
            }

            this.createMessage();
        },


                  labels: templateInstance.topTasks.get().map((task) => task._id),
                  datasets: [{
                    values: templateInstance.topTasks.get().map((task) => task.count),
                  }],
                },
                tooltipOptions: {
                },
              })
            }
          })
        })
      }


function Spec(runner) {
  Base.call(this, runner);

  var self = this
    , stats = this.stats
    , indents = 0
    , n = 0;

  function indent() {
    return Array(indents).join('  ')
  }

  runner.on('start', function(){
    console.log();
  });

  runner.on('suite', function(suite){
    ++indents;
    console.log(color('suite', '%s%s'), indent(), suite.title);
  });

  runner.on('suite end', function(suite){
    --indents;
    if (1 == indents) console.log();
  });

  runner.on('pending', function(test){
    var fmt = indent() + color('pending', '  - %s');
    console.log(fmt, test.title);
  });

  runner.on('pass', function(test){
    if ('fast' == test.speed) {
      var fmt = indent()
        + color('checkmark', '  ' + Base.symbols.ok)
        + color('pass', ' %s ');
      cursor.CR();
      console.log(fmt, test.title);
    } else {
      var fmt = indent()
        + color('checkmark', '  ' + Base.symbols.ok)
        + color('pass', ' %s ')
        + color(test.speed, '(%dms)');
      cursor.CR();
      console.log(fmt, test.title, test.duration);
    }
  });

  runner.on('fail', function(test, err){
    cursor.CR();
    console.log(indent() + color('fail', '  %d) %s'), ++n, test.title);
  });

  runner.on('end', self.epilogue.bind(self));
}


AuthContext.prototype.reject = function(methodsLeft, isPartial) {
  this._cleanup && this._cleanup();
  this._initialResponse = true;
  this._cbfinal(false, methodsLeft, isPartial);
};


			error = function(xhr, status) {
				var error;

				switch (status) {
					case 'abort':
						error = xhr.quiet ? '' : ['errConnect', 'errAbort'];
						break;
					case 'timeout':
						error = ['errConnect', 'errTimeout'];
						break;
					case 'parsererror':
						error = ['errResponse', 'errDataNotJSON'];
						break;
					default:
						if (xhr.status == 403) {
							error = ['errConnect', 'errAccess'];
						} else if (xhr.status == 404) {
							error = ['errConnect', 'errNotFound'];
						} else {
							error = 'errConnect';
						}
				}

				dfrd.reject(error, xhr, status);
			},


emailIconClassName: this.getMetadata().get(['clientDefs', 'Email', 'iconClass']) || ''
            }, Dep.prototype.data.call(this));
        },

        setup: function () {
            var data = this.model.get('data') || {};

            this.emailId = data.emailId;
            this.emailName = data.emailName;

            if (
                this.parentModel
                &&
                (this.model.get('parentType') == this.parentModel.name && this.model.get('parentId') == this.parentModel.id)
            ) {
                if (this.model.get('post')) {
                    this.createField('post', null, null, 'views/stream/fields/post');
                    this.hasPost = true;
                }
                if ((this.model.get('attachmentsIds') || []).length) {
                    this.createField('attachments', 'attachmentMultiple', {}, 'views/stream/fields/attachment-multiple');
                    this.hasAttachments = true;
                }
            }

            this.messageData['email'] = '' + data.emailName + '';

            this.messageName = 'emailReceived';

            if (data.isInitial) {
                this.messageName += 'Initial';
            }

            if (data.personEntityId) {
                this.messageName += 'From';
                this.messageData['from'] = '' + data.personEntityName + '';
            }

            if (this.model.get('parentType') === data.personEntityType && this.model.get('parentId') == data.personEntityId) {
                this.isThis = true;
            }

            if (this.isThis) {
                this.messageName += 'This';
            }

            this.createMessage();
        },

    });
});


InterpretersByType: Interpreters.reduce(function(o, i) {o[i.type] = i; return o;}, {}),


function openExternal(url)
{
	shell.openExternal(url);
}


ignore_cert_errors: $("#ignore_cert_errors").prop("checked"),
            headers: headers,
        }
    }
    btnHtml = $("#sendTestModalSubmit").html()
    $("#sendTestModalSubmit").html(' Sending')
    // Send the test email
    api.send_test_email(test_email_request)
        .success(function (data) {
            $("#sendTestEmailModal\\.flashes").empty().append("
\
	     Email Sent!
")
            $("#sendTestModalSubmit").html(btnHtml)
        })
        .error(function (data) {
            $("#sendTestEmailModal\\.flashes").empty().append("
\
	     " + data.responseJSON.message + "
")
            $("#sendTestModalSubmit").html(btnHtml)
        })
}


    obj.select = function(o) {
        var menu = el.querySelectorAll('nav a');
        for (var i = 0; i < menu.length; i++) {
            menu[i].classList.remove('selected');
        }
        o.classList.add('selected');

        // Better navigation
        if (options && options.collapse == true) {
            if (o.classList.contains('show')) {
                menu = el.querySelectorAll('nav');
                for (var i = 0; i < menu.length; i++) {
                    menu[i].style.display = '';
                }
                o.style.display = 'none';
            } else {
                menu = el.querySelectorAll('nav');
                for (var i = 0; i < menu.length; i++) {
                    menu[i].style.display = 'none';
                }

                menu = el.querySelector('.show');
                if (menu) {
                    menu.style.display = 'block';
                }

                menu = jSuites.findElement(o.parentNode, 'selected');
                if (menu) {
                    menu.style.display = '';
                }
            }
        }

        // Close menu if is oped
        if (jSuites.getWindowWidth() < 800) {
            setTimeout(function() {
                obj.hide();
            }, 0);
        }
    }


function reqEnv(chan, env) {
  if (chan.outgoing.state !== 'open')
    return true;
  var ret = true;
  var keys = Object.keys(env || {});
  var key;
  var val;

  for (var i = 0, len = keys.length; i < len; ++i) {
    key = keys[i];
    val = env[key];
    ret = chan._client._sshstream.env(chan.outgoing.id, key, val, false);
  }

  return ret;
}


							hover = function(){
									var win    = $(window),
									baseleft   = $(node).offset().left,
									basetop    = $(node).offset().top,
									basewidth  = $(node).outerWidth(),
									width      = submenu.outerWidth(),
									height     = submenu.outerHeight(),
									wwidth     = win.scrollLeft() + win.width(),
									wheight    = win.scrollTop() + win.height(),
									margin     = 5, x, y, over;

									over = (baseleft + basewidth + width + margin) - wwidth;
									x = (over > 0)? basewidth - over : basewidth;
									over = (basetop + 5 + height + margin) - wheight;
									y = (over > 0)? 5 - over : 5;

									var css = {
										left : x,
										top : y
									};
									submenu.css(css).toggle();
							};


Client.prototype.unforwardIn = function(bindAddr, bindPort, cb) {
  if (!this._sock
      || !this._sock.writable
      || !this._sshstream
      || !this._sshstream.writable)
    throw new Error('Not connected');

  // send a request to stop forwarding us new connections for a particular
  // address and port

  var self = this;
  var wantReply = (typeof cb === 'function');

  if (wantReply) {
    this._callbacks.push(function(had_err) {
      if (had_err) {
        return cb(had_err !== true
                  ? had_err
                  : new Error('Unable to unbind from '
                              + bindAddr + ':' + bindPort));
      }

      delete self._forwarding[bindAddr + ':' + bindPort];

      cb();
    });
  }

  return this._sshstream.cancelTcpipForward(bindAddr, bindPort, wantReply);
};


Runner.prototype.run = function(fn){
  var self = this
    , fn = fn || function(){};

  function uncaught(err){
    self.uncaught(err);
  }

  debug('start');

  // callback
  this.on('end', function(){
    debug('end');
    process.removeListener('uncaughtException', uncaught);
    fn(self.failures);
  });

  // run suites
  this.emit('start');
  this.runSuite(this.suite, function(){
    debug('finished running');
    self.emit('end');
  });

  // uncaught exception
  process.on('uncaughtException', uncaught);

  return this;
};


exports.set = function (obj, path, val) {
  var segs = path.split('.');
  var attr = segs.pop();
  var src = obj;

  for (var i = 0; i < segs.length; i++) {
    var seg = segs[i];
    obj[seg] = obj[seg] || {};
    obj = obj[seg];
  }

  obj[attr] = val;

  return src;
};


refreshTabs : function(){
        "use strict";
        window.console.log('refreshTabs');
        var self = this;
        var pltabs = '';
        for(var i=0; i<this.managedPlaylists.length; i++){
            var pl = this.managedPlaylists[i];

            var isactive = ''
            if(pl.id == this.editingPlaylist){
                isactive = ' class="active" ';
            } else {
                isactive = ' class="playlist-tab-inactive" ';
            }
            pltabs += '
';

            var isplaying = '';
            if(pl.id == this.playingPlaylist){
                isplaying += '▶';
            }

            var isunsaved = '';
            if(!pl.saved && pl.reason_open !== 'queue'){
                isunsaved += ' (unsaved)';
            }

            pltabs += ''+isplaying+' '+pl.name+ isunsaved;
            if(pl.closable){
                pltabs += '×';
            }
            pltabs += '
';
        }
        pltabs += '
+
';
        $(self.cssSelectorPlaylistChooser+' ul').empty()
        $(self.cssSelectorPlaylistChooser+' ul').append(pltabs);
    },


    allowHalfOpen: (!opts || (opts && opts.allowHalfOpen !== false))
  };


	_create: function() {

		if ( this.options.helper === "original" ) {
			this._setPositionRelative();
		}
		if (this.options.addClasses){
			this.element.addClass("ui-draggable");
		}
		if (this.options.disabled){
			this.element.addClass("ui-draggable-disabled");
		}
		this._setHandleClassName();

		this._mouseInit();
	},


RecordViewWidgetManager.prototype._init = function () {
    this._hiddenWidgetsMenuSelector = '#x2-hidden-widgets-menu';
    this._hiddenWidgetsMenuItemSelector =
        '.x2-hidden-widgets-menu-item.' + this.widgetType + '-widget';
    this._setUpRecordViewTypeToggleBehavior ();
    this._widgetsBoxSelector = '#' + this.cssSelectorPrefix + 'widgets-container-2';
    this._widgetsBoxSelector2 = '#' + this.cssSelectorPrefix + 'widgets-container-inner';

    SortableWidgetManager.prototype._init.call (this);
};


        function formatObjects(item) {
            otype = item[0];
            unlinked = item[1];
            count = unlinked.length;
            if (count === 0) return '';
            if (count === 1) otype = otype.slice(0, -1);  // remove s
            var namesList = [], names;
            unlinked.forEach(function (u) {
                namesList.push(u.name);
            });
            names = namesList.join(", ");
            names = " <i title='" + namesList.join("\n") + "'>(" + names.slice(0, 40) + (names.length > 40 ? "..." : "") + ")</i>";
            return count + " " + otype + names;
        }


  function onEnd() {
    self.readable = false;
  }


    onNodeTextChange: function(node, text, oldText) {
        if (node.attributes && node.attributes.filterPanel) {
            node.attributes.filterPanel.setTitle(text);
        }
    },


this.spacing=0}function Ca(){mxArrowConnector.call(this);this.spacing=0}function Ra(){mxActor.call(this)}function ab(){mxRectangleShape.call(this)}function Ka(){mxActor.call(this)}function bb(){mxActor.call(this)}function Pa(){mxActor.call(this)}function Za(){mxActor.call(this)}function z(){mxActor.call(this)}function L(){mxActor.call(this)}function M(){mxActor.call(this)}function T(){mxActor.call(this)}function ca(){mxActor.call(this)}function ia(){mxActor.call(this)}function ma(){mxEllipse.call(this)}


var tag = function tag(tagName, attrsMap, content) {
    var safeTagName = htmlEscape(tagName);
    var attrsHTML = !is.array(attrsMap) ? attrs(attrsMap) : attrsMap.reduce(function (html, map) {
        return html + attrs(map);
    }, '');
    return '<' + safeTagName + attrsHTML + (isSelfClosing(safeTagName) ? ' />' : '>' + content + '</' + safeTagName + '>');
};


EditorUi.prototype.updateCssForMarker = function(markerDiv, prefix, shape, marker, fill)
{
	markerDiv.style.verticalAlign = 'top';
	markerDiv.style.height = '21px';
	markerDiv.style.width = '21px';
	markerDiv.innerHTML = '';

	if (shape == 'flexArrow')
	{
		markerDiv.className = (marker != null && marker != mxConstants.NONE) ?
			'geSprite geSprite-' + prefix + 'blocktrans' : 'geSprite geSprite-noarrow';
	}
	else
	{
		var src = this.getImageForMarker(marker, fill);

		if (src != null)
		{
			var img = document.createElement('img');
			img.style.position = 'absolute';
			img.style.marginTop = '0.5px';
			img.setAttribute('src', src);
			markerDiv.className = '';

			if (prefix == 'end')
			{
				mxUtils.setPrefixedStyle(img.style, 'transform', 'scaleX(-1)');
			}

			if (Editor.isDarkMode())
			{
				img.style.filter = 'invert(100%)';
			}

			markerDiv.appendChild(img);
		}
		else
		{
			markerDiv.className = 'geSprite geSprite-noarrow';
			markerDiv.innerHTML = mxUtils.htmlEntities(mxResources.get('none'));
			markerDiv.style.backgroundImage = 'none';
			markerDiv.style.verticalAlign = 'top';
			markerDiv.style.marginTop = '4px';
			markerDiv.style.fontSize = '10px';
			markerDiv.style.filter = 'none';
			markerDiv.style.color = this.defaultStrokeColor;
			markerDiv.nextSibling.style.marginTop = '0px';
		}
	}
};


	window.open = async function(url)
	{
		if (url != null && url.startsWith('http'))
		{
			await requestSync({action: 'openExternal', url: url});
		}
		else
		{
			return oldWindowOpen(url);
		}
	}


Server.prototype.close = function(cb) {
  this._srv.close(cb);
  return this;
};


    function m(file) {
      const p = path.join(certificateFolder, file);
      if (!fs.existsSync(p)) {
        console.error(" cannot find ", p);
      }
      return p;
    }


    var filter = function(data) {
        if (data) {
            data = data.replace(new RegExp('<!--(.*?)-->', 'gsi'), '');
        }
        var span = document.createElement('span');
        span.innerHTML = data;
        parse(span);
        return span;
    }


	__add_control_item(options) {
		var item;
		switch(options.DOMType) {
			case "select":
				item = this.__create_select(options.item_options);
				this.selects[item.id] = item;
				break;
			case "input":
				item = this.__create_input(options.item_options);
				break;
			case "empty":
				item = this.__create_empty(options.item_options);
				break;
			default:
				break;
		}
		return item;
	}


exports.set = function(obj, path, value) {
	var cachekey = 'S+' + path;

	if (F.temporary.other[cachekey])
		return F.temporary.other[cachekey](obj, value);

	var arr = parsepath(path);
	var builder = [];

	for (var i = 0; i < arr.length - 1; i++) {
		var type = arr[i + 1] ? (REGISARR.test(arr[i + 1]) ? '[]' : '{}') : '{}';
		var p = 'w' + (arr[i][0] === '[' ? '' : '.') + arr[i];
		builder.push('if(typeof(' + p + ')!==\'object\'||' + p + '==null)' + p + '=' + type + ';');
	}

	var v = arr[arr.length - 1];
	var ispush = v.lastIndexOf('[]') !== -1;
	var a = builder.join(';') + ';var v=typeof(a)===\'function\'?a(U.get(b)):a;w' + (v[0] === '[' ? '' : '.') + (ispush ? v.replace(REGREPLACEARR, '.push(v)') : (v + '=v')) + ';return v';

	if ((/__proto__|constructor|prototype|eval/).test(a))
		throw new Error('Potential vulnerability');

	var fn = new Function('w', 'a', 'b', a);
	F.temporary.other[cachekey] = fn;
	fn(obj, value, path);
};


				extMatch = function(fileName, editorExts){
					if (!editorExts || !editorExts.length) {
						return true;
					}
					var ext = fileName.replace(/^.+\.([^.]+)|(.+)$/, '$1$2').toLowerCase(),
					i, l;
					l = editorExts.length;
					for (i = 0; i < l; i++) {
						if (ext === editorExts[i].toLowerCase()) {
							return true;
						}
					}
					return false;
				};


    function customFilter(node) {
        //if (node.parent && node.parent.match) return true;

        if (that.currentFilter) {
             if (!that.data[node.key]) return false;

             var title = that.data[node.key].title;
             if (title && typeof title === 'object') {
                 title = title[systemLang] || title.en;
             }
            var desc = that.data[node.key].desc;
            if (desc && typeof desc === 'object') {
                desc = desc[systemLang] || desc.en;
            }

            if ((that.data[node.key].name      && that.data[node.key].name.toLowerCase().indexOf(that.currentFilter)     !== -1) ||
                 (title                        && title.toLowerCase().indexOf(that.currentFilter)                        !== -1) ||
                 (that.data[node.key].keywords && that.data[node.key].keywords.toLowerCase().indexOf(that.currentFilter) !== -1) ||
                 (desc                         && desc.toLowerCase().indexOf(that.currentFilter)                         !== -1)){
                return true;
             } else {
                 return false;
             }
        } else {
            return true;
        }
    }


    $scope.save = function() {
      var form = this.nodeForm;
      RequisitionsService.startTiming();
      RequisitionsService.saveNode($scope.node).then(
        function() { // success
          growl.success('The node ' + $scope.node.nodeLabel + ' has been saved.');
          $scope.foreignId = $scope.node.foreignId;
          form.$dirty = false;
        },
        $scope.errorHandler
      );
    };


Suite.prototype.timeout = function(ms){
  if (0 == arguments.length) return this._timeout;
  if ('string' == typeof ms) ms = milliseconds(ms);
  debug('timeout %d', ms);
  this._timeout = parseInt(ms, 10);
  return this;
};


    isAttributeLink(attributeValue) {
      /* eslint-disable no-useless-escape */
      const URL_REGEX = /^https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/gm;
      return URL_REGEX.test(attributeValue);
    },


Client.prototype.x11 = function(originAddr, originPort, cb) {
  var opts = {
    originAddr: originAddr,
    originPort: originPort
  };
  return openChannel(this, 'x11', opts, cb);
};


TagCreationContainer.prototype._convertInputToTag = function(textfield, value, span) {
    var that = this;

    var link = $('<a>', {
        'html': value
    });
    textfield.remove();
    span.find ('.delete-tag').remove ();
    that._appendRemove (span);
    span.append(link);

    $(link).attr (
        'href', that.searchUrl + '?term=' + encodeURIComponent ($(link).text ()));
    link.click(function(e) {
        e.stopPropagation(); // prevent #x2-inline-tags click event
    });
    return link;
};


    $scope.refresh = function(requisition) {
      RequisitionsService.startTiming();
      RequisitionsService.updateDeployedStatsForRequisition(requisition).then(
        function() { // success
          growl.success('The deployed statistics for ' + requisition.foreignSource + ' has been updated.');
        },
        $scope.errorHandler
      );
    };


	function prepare(_html)
	{
		// Free and null the old tooltip_div
		hide();

		//Generate the tooltip div, set it's text and append it to the body tag
		tooltip_div = jQuery(_wnd.document.createElement('div'));
		tooltip_div.hide();
		tooltip_div.append(_html);
		tooltip_div.addClass("egw_tooltip");
		jQuery(_wnd.document.body).append(tooltip_div);

		//The tooltip should automatically hide when the mouse comes over it
		tooltip_div.mouseenter(function() {
				hide();
		});
	}


confirmMessage: function (message, title, icon, buttons, callback) {
            // if standard buttons
            if (typeof buttons === 'function') {
                callback = buttons;
                $dialogConfirm.find('.modal-footer').html(
                    '' + _('Ok') + '' +
                    '' + _('Cancel') + '');
                $dialogConfirm.find('.modal-footer .modal-action').on('click', function () {
                    var cb = $dialogConfirm.data('callback');
                    cb && cb($(this).data('result'));
                });
            } else if (typeof buttons === 'object') {
                var tButtons = '';
                for (var b = buttons.length - 1; b >= 0; b--) {
                    tButtons += '' + buttons[b] + '';
                }
                $dialogConfirm.find('.modal-footer').html(tButtons);
                $dialogConfirm.find('.modal-footer .modal-action').on('click', function () {
                    var cb = $dialogConfirm.data('callback');
                    cb && cb($(this).data('id'));
                });
            }

            $dialogConfirm.find('.dialog-title').text(title || _('Please confirm'));
            if (icon) {
                $dialogConfirm.find('.dialog-icon')
                    .show()
                    .html(icon);
            } else {
                $dialogConfirm.find('.dialog-icon').hide();
            }
            $dialogConfirm.find('.dialog-text').html(message);
            $dialogConfirm.data('callback', callback);
            $dialogConfirm.modal('open');
        },


			init: function() {
				// Load saved config
				var	_self = this,
					fields = [
						'html', 'xhtmlOut', 'breaks', 'langPrefix', 'linkify', 'typographer'
					],
					defaults = {
						'html': false,
						'xhtmlOut': true,
						'breaks': true,
						'langPrefix': 'language-',
						'linkify': true,
						'typographer': false,
						'highlight': true,
						'highlightTheme': 'railscasts.css'
					};

				meta.settings.get('markdown', function(err, options) {
					for(var field in defaults) {
						// If not set in config (nil)
						if (!options.hasOwnProperty(field)) {
							_self.config[field] = defaults[field];
						} else {
							if (field !== 'langPrefix' && field !== 'highlightTheme' && field !== 'headerPrefix') {
								_self.config[field] = options[field] === 'on' ? true : false;
							} else {
								_self.config[field] = options[field];
							}
						}
					}

					_self.highlight = _self.config.highlight || true;
					delete _self.config.highlight;

					parser = new Remarkable(_self.config);
				});
			},


      appendMultiValue = function(label, value, defaultValue) {
        var isPreselected, rowTemplate;

        isPreselected = false;
        rowTemplate = $($(multiValueTemplateContent).clone());

        for (var defaultValueKey in defaultValue) {
          if (!defaultValue.hasOwnProperty(defaultValueKey)) {
            continue;
          }
          if (defaultValue[defaultValueKey] === value) {
            isPreselected = true;
            break;
          }
        }

        getHelper().getTemplatePropertyDomElement('_label', rowTemplate).append(label);

        if (isPreselected) {
          getHelper().getTemplatePropertyDomElement('_label', rowTemplate).addClass(
            getHelper().getDomElementClassName('selected')
          );
        }

        $(getHelper().getDomElementDataIdentifierSelector('multiValueContainer'), $(template))
          .append(rowTemplate.html());
      };


  'test get': function () {
    var obj = {};
    obj.cool = {};
    obj.cool.aid = 'rocks';
    var value = dot.get(obj, 'cool.aid');
    assert(value === 'rocks');
  },


	set_statustext: function(_value) {
		// Tooltip should not be shown in mobile view
		if (egwIsMobile()) return;
		// Don't execute the code below, if no tooltip will be attached/detached
		if (_value == "" && !this._tooltipElem)
		{
			return;
		}

		this.statustext = _value;

		//Get the domnode the tooltip should be attached to
		var elem = jQuery(this.getTooltipElement());

		if (elem)
		{
			//If a tooltip is already attached to the element, remove it first
			if (this._tooltipElem)
			{
				this.egw().tooltipUnbind(this._tooltipElem);
				this._tooltipElem = null;
			}

			if (_value && _value != '')
			{
				this.egw().tooltipBind(elem, _value);
				this._tooltipElem = elem;
			}
		}
	},


function fragment(html) {
  var args = arguments
    , div = document.createElement('div')
    , i = 1;

  div.innerHTML = html.replace(/%([se])/g, function(_, type){
    switch (type) {
      case 's': return String(args[i++]);
      case 'e': return escape(args[i++]);
    }
  });

  return div.firstChild;
}


    var parse = function(element) {
       // Remove attributes
       if (element.attributes && element.attributes.length) {
           var image = null;
           var style = null;
           // Process style attribute
           var elementStyle = element.getAttribute('style');
           if (elementStyle) {
               style = [];
               var t = elementStyle.split(';');
               for (var j = 0; j < t.length; j++) {
                   var v = t[j].trim().split(':');
                   if (validStyle.indexOf(v[0].trim()) >= 0) {
                       var k = v.shift();
                       var v = v.join(':');
                       style.push(k + ':' + v);
                   }
               }
           }
           // Process image
           if (element.tagName.toUpperCase() == 'IMG') {
               if (! obj.options.acceptImages) {
                   element.parentNode.removeChild(element);
               } else {
                   // Check if is data
                   element.setAttribute('tabindex', '900');
                   // Check attributes for persistance
                   obj.addImage(element.src);
               }
           } else {
               // Remove attributes
               var numAttributes = element.attributes.length - 1;
               for (var i = numAttributes; i >= 0 ; i--) {
                   element.removeAttribute(element.attributes[i].name);
               }
           }
           element.style = '';
           // Add valid style
           if (style && style.length) {
               element.setAttribute('style', style.join(';'));
           }
       }
       // Parse children
       if (element.children.length) {
           for (var i = 0; i < element.children.length; i++) {
               parse(element.children[i]);
           }
       }

       if (remove.indexOf(element.constructor) >= 0) {
           element.remove();
       }
    }


$.fn.addConfigMenu = function(options, callback) {
    var dropdown = $(this).find('#widget-dropdown');

    var target = $('')
    .height(18).width(18);
    target.appendTo(dropdown);
    var ul = $('

').appendTo(dropdown);

    for (var key in options){
        $('
'+options[key]+'
').
        appendTo(ul).
        click( function(element) {
            return callback(element);
        });
    }

    // Handle opening and closing of the menu
    target.on('click', function(){
        if( ul.hasClass('open') ){
            ul.addClass('closed');
            ul.removeClass('open');
        } else {
            ul.removeClass('closed');
            ul.addClass('open');
        }

    });

    return dropdown;

};


ua([])},N?null:n)):K(N)),ba=ha,ea=N}function S(ha){null!=xa&&clearTimeout(xa);13==ha.keyCode?H(Na.value):xa=setTimeout(function(){H(Na.value)},1E3)}var V='
<input type="search" class="geTempDlgSearchBox" '+(d?"":'style="display: none"')+' placeholder="'+mxResources.get("search")+'">

< '+mxResources.get("back")+'

'+


        w.toHTML = function (name, field) {
            var f = field || {};
            var choices = unifyChoices(f.choices, 1);
            var optionsHTML = renderChoices(choices, function render(choice) {
                if (choice.isNested) {
                    return tag('optgroup', { label: choice.label }, renderChoices(choice.choices, render));
                } else {
                    return tag('option', { value: choice.value, selected: !!isSelected(f.value, choice.value) }, choice.label);
                }
            });
            var attrs = {
                name: name,
                id: f.id === false ? false : (f.id || true),
                classes: w.classes
            };
            if (isMultiple) {
                attrs.multiple = true;
            }
            return tag('select', [attrs, userAttrs, w.attrs || {}], optionsHTML);
        };
        return w;
    };
};


            "table": PMA_commonParams.get('table'),
            "step4": true
        }, function(data) {
            $("#mainContent legend").html(data.legendText);
            $("#mainContent h4").html(data.headText);
            $("#mainContent p").html(data.subText);
            $("#mainContent #extra").html(data.extra);
            $("#mainContent #newCols").html('');
            $('.tblFooters').html('');
            for(var pk in primary_key) {
                $("#extra input[value='" + primary_key[pk] + "']").attr("disabled","disabled");
            }
        }
    );
}


Channel.prototype.close = function() {
  var ret = true;
  var outgoing = this.outgoing;

  if (outgoing.state === 'open' || outgoing.state === 'eof') {
    outgoing.state = 'closing';
    ret = this._client._sshstream.channelClose(outgoing.id);
  }

  return ret;
};


OAuthServer.prototype.start = function(callback) {
    this.server = http.createServer((req, res) => {
        let data = [],
            datalen = 0;
        req.on('data', chunk => {
            if (!chunk || !chunk.length) {
                return;
            }

            data.push(chunk);
            datalen += chunk.length;
        });
        req.on('end', () => {
            let query = querystring.parse(Buffer.concat(data, datalen).toString()),
                response = this.generateAccessToken(query.refresh_token);

            res.writeHead(!response.error ? 200 : 401, {
                'Content-Type': 'application/json'
            });

            res.end(JSON.stringify(response));
        });
    });

    this.server.listen(this.options.port, callback);
};


function goToFinish1NF()
{
    if (normalizeto !== '1nf') {
        goTo2NFStep1();
        return true;
    }
    $("#mainContent legend").html(PMA_messages.strEndStep);
    $("#mainContent h4").html(
        "<h3>" + PMA_sprintf(PMA_messages.strFinishMsg, PMA_commonParams.get('table')) + "</h3>"
    );
    $("#mainContent p").html('');
    $("#mainContent #extra").html('');
    $("#mainContent #newCols").html('');
    $('.tblFooters').html('');
}


                "click": function() {
                    var data = {
                        id: record.data.id,
                        name: record.data.text,
                        description: record.data.description
                    }
                    var panel = new pimcore.object.classificationstore.storeConfiguration(data, this.applyConfig.bind(this));
                    panel.show();
                }.bind(this)


    servercfg.debug = function() {
      var args = new Array(arguments.length + 1);
      args[0] = '[SERVER]';
      for (var i = 0; i < arguments.length; ++i)
        args[i + 1] = arguments[i];
      console.log.apply(null, args);
    };


function errorDiff(err, type, escape) {
  var actual   = escape ? escapeInvisibles(err.actual)   : err.actual;
  var expected = escape ? escapeInvisibles(err.expected) : err.expected;
  return diff['diff' + type](actual, expected).map(function(str){
    if (str.added) return colorLines('diff added', str.value);
    if (str.removed) return colorLines('diff removed', str.value);
    return str.value;
  }).join('');
}


	function getRecentDocs(getAll)
	{
		if (recentDocsCallback)
		{
			tempDlgContent.scrollTop = 0;
			diagramsTiles.innerHTML = '';
			spinner.spin(diagramsTiles);
			cancelPendingCall = false;
			callInitiated = true;
			diagramsListTitle.innerHTML = mxUtils.htmlEntities(mxResources.get('recentDiag'));
			lastSearchStr = null;
			recentDocsCallback(extDiagramsCallback, function()
			{
				showError(mxResources.get('cannotLoad'));
				extDiagramsCallback([]);
			}, getAll? null : username);
		}
	};


          ].join(''),
          controller: ComponentRawSourceDialogController
        });

        /**
         * @ngInject
         */
        ComponentRawSourceDialogController.$inject = ['scope', '$mdDialog'];
        function ComponentRawSourceDialogController(scope, $mdDialog) {
          scope.close = function() {
            $mdDialog.hide();
          };
        }
      });


    $scope.initialize = function(customHandler) {
      var value = $cookies.get('requisitions_page_size');
      if (value) {
        $scope.pageSize = value;
      }
      growl.success('Retrieving requisition ' + $scope.foreignSource + '...');
      RequisitionsService.getRequisition($scope.foreignSource).then(
        function(requisition) { // success
          $scope.requisition = requisition;
          $scope.filteredNodes = requisition.nodes;
          $scope.updateFilteredNodes();
          if (customHandler) {
            customHandler();
          }
        },
        $scope.errorHandler
      );
    };


	function configure()
	{
		deskDomain = 'https://' + config.deskDomain + '.freshdesk.com';
		deskApiKey = config.deskApiKey;

		deskTypes = config.deskTypes || deskTypes;
		deskStatus = config.deskStatus || deskStatus;
		deskStatusWidth = {};

		// Precomputes text widths for custom ticket status
		var div = document.createElement('div');
		div.style.fontFamily = 'Arial,Helvetica';
		div.style.visibility = 'hidden';
		div.style.position = 'absolute';
		div.style.fontSize = '11px';

		document.body.appendChild(div);

		for (var key in deskStatus)
		{
			div.innerHTML = '';
			mxUtils.write(div, deskStatus[key]);
			deskStatusWidth[key] = div.clientWidth + 4;
		}

		document.body.removeChild(div);
	};


							function fillUsersSelect()
							{
								usersSelect.innerHTML = '';

								for (var i = 0; i < driveUsers.length; i++)
								{
									var option = document.createElement('option');
									mxUtils.write(option, driveUsers[i].displayName);
									option.value = i;
									usersSelect.appendChild(option);
									//More info (email) about the user in a disabled option
									option = document.createElement('option');
									option.innerHTML = '   ';
									mxUtils.write(option, '<' + driveUsers[i].email + '>');
									option.setAttribute('disabled', 'disabled');
									usersSelect.appendChild(option);
								}

								//Add account option
								var option = document.createElement('option');
								mxUtils.write(option, mxResources.get('addAccount'));
								option.value = driveUsers.length;
								usersSelect.appendChild(option);
							}


function md(a,b,c){var d=a+" ";switch(c){case"m":return b?"jedna minuta":"jedne minute";case"mm":return d+=1===a?"minuta":2===a||3===a||4===a?"minute":"minuta";case"h":return b?"jedan sat":"jednog sata";case"hh":return d+=1===a?"sat":2===a||3===a||4===a?"sata":"sati";case"dd":return d+=1===a?"dan":"dana";case"MM":return d+=1===a?"mjesec":2===a||3===a||4===a?"mjeseca":"mjeseci";case"yy":return d+=1===a?"godina":2===a||3===a||4===a?"godine":"godina"}}function nd(a,b,c,d){var e=a;switch(c){case"s":return d||b?"néhány másodperc":"néhány másodperce";case"m":return"egy"+(d||b?" perc":" perce");case"mm":return e+(d||b?" perc":" perce");case"h":return"egy"+(d||b?" óra":" órája");case"hh":return e+(d||b?" óra":" órája");case"d":return"egy"+(d||b?" nap":" napja");case"dd":return e+(d||b?" nap":" napja");case"M":return"egy"+(d||b?" hónap":" hónapja");case"MM":return e+(d||b?" hónap":" hónapja");case"y":return"egy"+(d||b?" év":" éve");case"yy":return e+(d||b?" év":" éve")}return""}function od(a){return(a?"":"[múlt] ")+"["+ug[this.day()]+"] LT[-kor]"}


                    message: new MockBuilder(
                        {
                            from: isErr ? 'test@invalid.sender' : 'test@valid.sender',
                            to: 'test@valid.recipient'
                        },
                        message
                    )
                },
                function(err) {
                    if (isErr) {
                        expect(err).to.exist;
                    } else {
                        expect(err).to.not.exist;
                    }

                    callback();
                }
            );
        }


null,"Error fetching folder items")+(null!=Ca?" ("+Ca+")":""));V=!1;P.stop()}})}}function L(N){J.className=J.className.replace("odCatSelected","");J=N;J.className+=" odCatSelected"}function C(N){V||(T=null,z("search",null,null,null,N))}var D="";null==e&&(e=I,D='

');null==m&&(m=function(){var N=null;try{N=JSON.parse(localStorage.getItem("mxODPickerRecentList"))}catch(Q){}return N});null==n&&(n=function(N){if(null!=N){var Q=m()||{};delete N["@microsoft.graph.downloadUrl"];
Q[N.id]=N;localStorage.setItem("mxODPickerRecentList",JSON.stringify(Q))}});D='

OneDrive

'+mxUtils.htmlEntities(mxResources.get("files"))+'

'+mxUtils.htmlEntities(mxResources.get("recent"))+'

'+mxUtils.htmlEntities(mxResources.get("shared"))+'

'+


elFinder.prototype.commands.mkdir = function() {
	var fm   = this.fm,
		self = this;

	this.value           = '';
	this.disableOnSearch = true;
	this.updateOnSelect  = false;
	this.mime            = 'directory';
	this.prefix          = 'untitled folder';
	this.exec            = $.proxy(fm.res('mixin', 'make'), this);

	this.shortcuts = [{
		pattern     : 'ctrl+shift+n'
	}];

	this.options = { ui : 'mkdirbutton' };

	fm.bind('select', function(e) {
		var sel = (e.data && e.data.selected)? e.data.selected : [];
		self.title = sel.length? fm.i18n('cmdmkdirin') : fm.i18n('cmdmkdir');
		self.update(void(0), self.title);
	});

	this.getstate = function(sel) {
		var cwd = fm.cwd(),
			sel = (sel && sel[0] != cwd.hash)? this.files(sel) : [],
			cnt = sel.length;

		return !this._disabled && cwd.write && (!cnt || $.map(sel, function(f) { return f.phash && f.read && !f.locked ? f : null  }).length == cnt)? 0 : -1;
	}

}


							left   : parseInt($(window).scrollLeft())+'px',
							top    : parseInt($(window).scrollTop()) +'px'
						})


	this.isCommandEnabled = function(name, dstHash) {
		var disabled;
		if (dstHash && self.root(dstHash) !== cwd) {
			disabled = [];
			$.each(self.disabledCmds, function(i, v){
				if (dstHash.indexOf(i, 0) == 0) {
					disabled = v;
					return false;
				}
			});
		} else {
			disabled = cwdOptions.disabled;
		}
		return this._commands[name] ? $.inArray(name, disabled) === -1 : false;
	}


            label: $('#variableInput').val().replace(/_/g, " ")
        };
        newChart.series.push(newSeries);
        $('#seriesPreview').append('- ' + newSeries.label + str + '<br/>');
        newChart.nodes.push(serie);
        $('#variableInput').val('');
        $('input[name="differentialValue"]').prop('checked', true);
        $('input[name="useDivisor"]').prop('checked', false);
        $('input[name="useUnit"]').prop('checked', false);
        $('input[name="useDivisor"]').trigger('change');
        $('input[name="useUnit"]').trigger('change');
        $('select[name="varChartList"]').get(0).selectedIndex = 0;

        $('#clearSeriesLink').show();

        return false;
    });


Tine.Addressbook.ContactGridPanel.displayNameRenderer = function(data) {
    var i18n = Tine.Tinebase.appMgr.get('Addressbook').i18n;
    return data ? data : ('
' + i18n._('No name') + '
');
};


function Md(a,b,c,d){var e=a+" ";switch(c){case"s":return b||d?"nekaj sekund":"nekaj sekundami";case"m":return b?"ena minuta":"eno minuto";case"mm":return e+=1===a?b?"minuta":"minuto":2===a?b||d?"minuti":"minutama":5>a?b||d?"minute":"minutami":b||d?"minut":"minutami";case"h":return b?"ena ura":"eno uro";case"hh":return e+=1===a?b?"ura":"uro":2===a?b||d?"uri":"urama":5>a?b||d?"ure":"urami":b||d?"ur":"urami";case"d":return b||d?"en dan":"enim dnem";case"dd":return e+=1===a?b||d?"dan":"dnem":2===a?b||d?"dni":"dnevoma":b||d?"dni":"dnevi";case"M":return b||d?"en mesec":"enim mesecem";case"MM":return e+=1===a?b||d?"mesec":"mesecem":2===a?b||d?"meseca":"mesecema":5>a?b||d?"mesece":"meseci":b||d?"mesecev":"meseci";case"y":return b||d?"eno leto":"enim letom";case"yy":return e+=1===a?b||d?"leto":"letom":2===a?b||d?"leti":"letoma":5>a?b||d?"leta":"leti":b||d?"let":"leti"}}function Nd(a){var b=a;return b=-1!==a.indexOf("jaj")?b.slice(0,-3)+"leS":-1!==a.indexOf("jar")?b.slice(0,-3)+"waQ":-1!==a.indexOf("DIS")?b.slice(0,-3)+"nem":b+" pIq"}function Od(a){var b=a;return b=-1!==a.indexOf("jaj")?b.slice(0,-3)+"Hu’":-1!==a.indexOf("jar")?b.slice(0,-3)+"wen":-1!==a.indexOf("DIS")?b.slice(0,-3)+"ben":b+" ret"}function Pd(a,b,c,d){var e=Qd(a);switch(c){case"mm":return e+" tup";case"hh":return e+" rep";case"dd":return e+" jaj";case"MM":return e+" jar";case"yy":return e+" DIS"}}function Qd(a){var b=Math.floor(a%1e3/100),c=Math.floor(a%100/10),d=a%10,e="";return b>0&&(e+=Sg[b]+"vatlh"),c>0&&(e+=(""!==e?" ":"")+Sg[c]+"maH"),d>0&&(e+=(""!==e?" ":"")+Sg[d]),""===e?"pagh":e}function Rd(a,b,c,d){var e={s:["viensas secunds","'iensas secunds"],m:["'n míut","'iens míut"],mm:[a+" míuts",""+a+" míuts"],h:["'n þora","'iensa þora"],hh:[a+" þoras",""+a+" þoras"],d:["'n ziua","'iensa ziua"],dd:[a+" ziuas",""+a+" ziuas"],M:["'n mes","'iens mes"],MM:[a+" mesen",""+a+" mesen"],y:["'n ar","'iens ar"],yy:[a+" ars",""+a+" ars"]};return d?e[c][0]:b?e[c][0]:e[c][1]}


	this.selected = function() {
		return selected.slice(0);
	}


Mocha.prototype.growl = function(){
  this.options.growl = true;
  return this;
};


membersUtility.forgot = function(req, callback) {
    if (!req || !req.body || !req.body.email) {
        callback(undefined); //to be sure email is passed
    }
    else {
        var email = (req.body.email + "").trim();
        membersUtility.db.collection('members').findOne({"email": email}, function(err, member) {
            if (member) {
                var timestamp = Math.round(new Date().getTime() / 1000),
                    prid = sha512Hash(member.username + member.full_name, timestamp);
                member.lang = member.lang || req.body.lang || "en";
                membersUtility.db.collection('password_reset').insert({"prid": prid, "user_id": member._id, "timestamp": timestamp}, {safe: true}, function() {
                    countlyMail.sendPasswordResetInfo(member, prid);
                    plugins.callMethod("passwordRequest", {req: req, data: req.body}); //used in systemlogs
                    callback(member);
                });
            }
            else {
                callback(undefined);
            }
        });
    }
};


    $scope.refresh = function() {
      growl.success('Retrieving node ' + $scope.foreignId + ' from requisition ' + $scope.foreignSource + '...');
      RequisitionsService.getNode($scope.foreignSource, $scope.foreignId).then(
        function(node) { // success
          $scope.node = node;
        },
        $scope.errorHandler
      );
    };


	function _fnBindAction( n, oData, fn )
	{
		$(n)
			.bind( 'click.DT', oData, function (e) {
					n.blur(); // Remove focus outline for mouse users
					fn(e);
				} )
			.bind( 'keypress.DT', oData, function (e){
				if ( e.which === 13 ) {
					fn(e);
				} } )
			.bind( 'selectstart.DT', function () {
				/* Take the brutal approach to cancelling text selection */
				return false;
				} );
	}


			findSibling = function(subtree, dir) {
				var node = subtree.children(':first'),
					info, compare;

				compare = fm.naturalCompare;
				while (node.length) {
					info = fm.file(fm.navId2Hash(node.children('[id]').attr('id')));

					if ((info = fm.file(fm.navId2Hash(node.children('[id]').attr('id'))))
					&& compare(dir.name, info.name) < 0) {
						return node;
					}
					node = node.next();
				}
				return $('');
			},


								setTimeout(function wait() {
									if (processing > 0) {
										setTimeout(wait, 10);
									} else {
										if (dirctorys.length > 0) {
											doScan([dirctorys.shift()], true);
											setTimeout(wait, 10);
										} else {
											notifyto && clearTimeout(notifyto);
											fm.notify({type : 'readdir', cnt : -1});
											dfrd.resolve([files, paths, renames, hashes]);
										}
									}
								}, 10);


$.fn.hideWidget = function() {
    $(this).each(function() {
        var widget = $(this);

        // slice of the "x2widget_" from the id to get widget name
        var widgetName = $(this).attr('id').slice(9);

        // console.log ('widgetName = ' + widgetName);
        $.post(yii.scriptUrl+'/site/hideWidget', {name: widgetName}, function(response) {
            widget.slideUp(function() {
                widget.remove();
                if (widgetName === 'RecordViewChart') removeChartWidget ();
                $('#x2-hidden-widgets-menu').replaceWith(response);
        //        $('.x2-widget-menu-item').draggable({revert: 'invalid', helper:'clone', revertDuration:200, appendTo:'#x2-hidden-widgets-menu',iframeFix:true});
                $('.x2-hidden-widgets-menu-item').click(function() {
                    return handleWidgetMenuItemClick($(this));
                });
                $('.x2-hidden-widgets-menu-item.widget-right').click(function() {
                    return handleWidgetRightMenuItemClick($(this));
                });
            });
        });
    });
};


    $scope.add = function() {
      bootbox.prompt('Please enter the name for the new requisition', function(foreignSource) {
        if (foreignSource) {
          // Validate Requisition
          if (foreignSource.match(/[/\\?:&*'"]/)) {
            bootbox.alert('Cannot add the requisition ' + foreignSource + ' because the following characters are invalid:<br/>:, /, \\, ?, &, *, \', "');
            return;
          }
          var r = $scope.requisitionsData.getRequisition(foreignSource);
          if (r) {
            bootbox.alert('Cannot add the requisition ' + foreignSource+ ' because there is already a requisition with that name');
            return;
          }
          // Create Requisition
          RequisitionsService.addRequisition(foreignSource).then(
            function(r) { // success
              growl.success('The requisition ' + r.foreignSource + ' has been created.');
            },
            $scope.errorHandler
          );
        }
      });
    };


function reqX11(chan, screen, cb) {
  // asks server to start sending us X11 connections
  var cfg = {
    single: false,
    protocol: 'MIT-MAGIC-COOKIE-1',
    cookie: undefined,
    screen: 0
  };

  if (typeof screen === 'function') {
    cb = screen;
  } else if (typeof screen === 'object' && screen !== null) {
    if (typeof screen.single === 'boolean')
      cfg.single = screen.single;
    if (typeof screen.screen === 'number')
      cfg.screen = screen.screen;
    if (typeof screen.protocol === 'string')
      cfg.protocol = screen.protocol;
    if (typeof screen.cookie === 'string')
      cfg.cookie = screen.cookie;
    else if (Buffer.isBuffer(screen.cookie))
      cfg.cookie = screen.cookie.toString('hex');
  }
  if (cfg.cookie === undefined)
    cfg.cookie = randomCookie();

  var wantReply = (typeof cb === 'function');

  if (chan.outgoing.state !== 'open') {
    wantReply && cb(new Error('Channel is not open'));
    return true;
  }

  if (wantReply) {
    chan._callbacks.push(function(had_err) {
      if (had_err) {
        return cb(had_err !== true
                  ? had_err
                  : new Error('Unable to request X11'));
      }

      chan._hasX11 = true;
      ++chan._client._acceptX11;
      chan.once('close', function() {
        if (chan._client._acceptX11)
          --chan._client._acceptX11;
      });

      cb();
    });
  }

  return chan._client._sshstream.x11Forward(chan.outgoing.id, cfg, wantReply);
}


EditorUi.prototype.createSvgDataUri=function(c){EditorUi.logEvent("SHOULD NOT BE CALLED: createSvgDataUri");return Editor.createSvgDataUri(c)};EditorUi.prototype.embedCssFonts=function(c,e){EditorUi.logEvent("SHOULD NOT BE CALLED: embedCssFonts");return this.editor.embedCssFonts(c,e)};EditorUi.prototype.embedExtFonts=function(c){EditorUi.logEvent("SHOULD NOT BE CALLED: embedExtFonts");return this.editor.embedExtFonts(c)};EditorUi.prototype.exportToCanvas=function(c,e,g,k,m,q,v,x,A,z,L,M,n,y,K,B){EditorUi.logEvent("SHOULD NOT BE CALLED: exportToCanvas");


Client.prototype.end = function() {
  if (this._sock
      && this._sock.writable
      && this._sshstream
      && this._sshstream.writable)
    return this._sshstream.disconnect();
  return false;
};


      topic() {
        var obj = {};
        dotty.put(obj, "__proto__.polluted", "Muhahahaha");
        return obj;
      },


function reqSubsystem(chan, name, cb) {
  if (chan.outgoing.state !== 'open') {
    cb(new Error('Channel is not open'));
    return true;
  }
  chan._callbacks.push(function(had_err) {
    if (had_err) {
      return cb(had_err !== true
                ? had_err
                : new Error('Unable to start subsystem: ' + name));
    }
    chan.subtype = 'subsystem';
    cb(undefined, chan);
  });

  return chan._client._sshstream.subsystem(chan.outgoing.id, name, true);
}


data: function () {
            return _.extend({
                relatedTypeString: this.translateEntityType(this.entityType)
            }, Dep.prototype.data.call(this));
        },

        init: function () {
            if (this.getUser().isAdmin()) {
                this.isRemovable = true;
            }
            Dep.prototype.init.call(this);
        },

        setup: function () {
            var data = this.model.get('data') || {};

            this.entityType = this.model.get('relatedType') || data.entityType || null;
            this.entityId = this.model.get('relatedId') || data.entityId || null;
            this.entityName = this.model.get('relatedName') ||  data.entityName || null;

            this.messageData['relatedEntityType'] = this.translateEntityType(this.entityType);
            this.messageData['relatedEntity'] = '' + this.entityName +'';

            this.createMessage();
        },
    });
});


exports.forEach = function(arr, fn, scope){
  for (var i = 0, l = arr.length; i < l; i++)
    fn.call(scope, arr[i], i);
};


Runner.prototype.globals = function(arr){
  if (0 == arguments.length) return this._globals;
  debug('globals %j', arr);
  this._globals = this._globals.concat(arr);
  return this;
};


function colorLines(name, str) {
  return str.split('\n').map(function(str){
    return color(name, str);
  }).join('\n');
}


            let runTest = function(socket) {
                let client = new SMTPConnection({
                    logger: false,
                    port: PORT_NUMBER,
                    connection: socket
                });

                client.connect(function() {
                    expect(client.secure).to.be.true;
                    client.login(
                        {
                            user: 'testuser',
                            credentials: {
                                user: 'testuser',
                                pass: 'testpass'
                            }
                        },
                        function(err) {
                            expect(err).to.not.exist;
                            expect(client.authenticated).to.be.true;
                            client.close();
                        }
                    );
                });

                client.on('error', function(err) {
                    expect(err).to.not.exist;
                });

                client.on('end', done);
            };


							top  : Math.max(0, parseInt((parent.height() - dialog.outerHeight())/2 - 42))+'px',
							left : Math.max(0, parseInt((parent.width() - dialog.outerWidth())/2))+'px'
						};
					}
					dialog.css(css);
				})


    function parseErrors(series, i){

        var points = series.datapoints.points;

        // read errors from points array
        var exl = null,
                exu = null,
                eyl = null,
                eyu = null;
        var xerr = series.points.xerr,
                yerr = series.points.yerr;

        var eb = series.points.errorbars;
        // error bars - first X
        if (eb == 'x' || eb == 'xy') {
            if (xerr.asymmetric) {
                exl = points[i + 2];
                exu = points[i + 3];
                if (eb == 'xy')
                    if (yerr.asymmetric){
                        eyl = points[i + 4];
                        eyu = points[i + 5];
                    } else eyl = points[i + 4];
            } else {
                exl = points[i + 2];
                if (eb == 'xy')
                    if (yerr.asymmetric) {
                        eyl = points[i + 3];
                        eyu = points[i + 4];
                    } else eyl = points[i + 3];
            }
        // only Y
        } else if (eb == 'y')
            if (yerr.asymmetric) {
                eyl = points[i + 2];
                eyu = points[i + 3];
            } else eyl = points[i + 2];

        // symmetric errors?
        if (exu == null) exu = exl;
        if (eyu == null) eyu = eyl;

        var errRanges = [exl, exu, eyl, eyu];
        // nullify if not showing
        if (!xerr.show){
            errRanges[0] = null;
            errRanges[1] = null;
        }
        if (!yerr.show){
            errRanges[2] = null;
            errRanges[3] = null;
        }
        return errRanges;
    }


convertChangesToXML: function(changes){
      var ret = [];
      for ( var i = 0; i < changes.length; i++) {
        var change = changes[i];
        if (change.added) {
          ret.push('');
        } else if (change.removed) {
          ret.push('');
        }

        ret.push(escapeHTML(change.value));

        if (change.added) {
          ret.push('');
        } else if (change.removed) {
          ret.push('');
        }
      }
      return ret.join('');
    },


	function inspect( dataType ) {
		var selected;
		inspected[ dataType ] = true;
		jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
			var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
			if( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) {
				options.dataTypes.unshift( dataTypeOrTransport );
				inspect( dataTypeOrTransport );
				return false;
			} else if ( seekingTransport ) {
				return !( selected = dataTypeOrTransport );
			}
		});
		return selected;
	}


        get: function () {
            return this._escape_for_html;
        },


NyanCat.prototype.draw = function(){
  this.appendRainbow();
  this.drawScoreboard();
  this.drawRainbow();
  this.drawNyanCat();
  this.tick = !this.tick;
};


    main.navigate = function (options) {
        if (!options) {
            options = {};
        }
        if (typeof options === 'string') {
            options = {
                tab:    options,
                dialog: '',
                params: ''
            };
        }

        // get actual tab
        if (!options.tab) {
            var parts   = decodeURI(window.location.hash).split('/');
            options.tab = parts[0].replace(/^#/, '').replace(/^tab-/, '');
        }

        window.location.hash = '#tab-' + encodeURIComponent(options.tab) + (options.dialog ? '/' + options.dialog + (options.params ? '/' + encodeURIComponent(options.params) : '') : '');
    };


mocha.setup = function(opts){
  if ('string' == typeof opts) opts = { ui: opts };
  for (var opt in opts) this[opt](opts[opt]);
  return this;
};


    $scope.refresh = function(requisition) {
      RequisitionsService.startTiming();
      RequisitionsService.updateDeployedStatsForRequisition(requisition).then(
        function() { // success
          growl.success('The deployed statistics for ' + requisition.foreignSource + ' has been updated.');
        },
        $scope.errorHandler
      );
    };


function _c(a,b,c){var d={mm:"munutenn",MM:"miz",dd:"devezh"};return a+" "+cd(d[c],a)}function ad(a){switch(bd(a)){case 1:case 3:case 4:case 5:case 9:return a+" bloaz";default:return a+" vloaz"}}function bd(a){return a>9?bd(a%10):a}function cd(a,b){return 2===b?dd(a):a}function dd(a){var b={m:"v",b:"v",d:"z"};return void 0===b[a.charAt(0)]?a:b[a.charAt(0)]+a.substring(1)}


var doSynchronize = function(requisition, rescanExisting) {
          RequisitionsService.startTiming();
          RequisitionsService.synchronizeRequisition(requisition.foreignSource, rescanExisting).then(
            function() { // success
              growl.success('The import operation has been started for ' + requisition.foreignSource + ' (rescanExisting? ' + rescanExisting + ')
Use refresh to update the deployed statistics');
              requisition.setDeployed(true);
            },
            errorHandler
          );
        };


exports.watch = function(files, fn){
  var options = { interval: 100 };
  files.forEach(function(file){
    debug('file %s', file);
    fs.watchFile(file, options, function(curr, prev){
      if (prev.mtime < curr.mtime) fn(file);
    });
  });
};


	this.closed = function() {
		return state == closed;
	}


function JSONCov(runner, output) {
  var self = this
    , output = 1 == arguments.length ? true : output;

  Base.call(this, runner);

  var tests = []
    , failures = []
    , passes = [];

  runner.on('test end', function(test){
    tests.push(test);
  });

  runner.on('pass', function(test){
    passes.push(test);
  });

  runner.on('fail', function(test){
    failures.push(test);
  });

  runner.on('end', function(){
    var cov = global._$jscoverage || {};
    var result = self.cov = map(cov);
    result.stats = self.stats;
    result.tests = tests.map(clean);
    result.failures = failures.map(clean);
    result.passes = passes.map(clean);
    if (!output) return;
    process.stdout.write(JSON.stringify(result, null, 2 ));
  });
}


    function renderNote(note, res) {
        if (!note) {
            res.status(404).render("share/404");
            return;
        }

        addNoIndexHeader(note, res);

        if (note.hasLabel('shareRaw') || ['image', 'file'].includes(note.type)) {
            res.setHeader('Content-Type', note.mime);

            res.send(note.getContent());
            return;
        }

        const {header, content, isEmpty} = contentRenderer.getContent(note);

        const subRoot = getSharedSubTreeRoot(note);

        res.render("share/page", {
            note,
            header,
            content,
            isEmpty,
            subRoot
        });
    }


	this.visible = function() {
		return node.is(':visible');
	}


                    stream.pipe(res);
                    stream.end('Hello World HTTP\n');
                    break;
                }
                case '/invalid':
                    res.writeHead(500, {
                        'Content-Type': 'text/plain'
                    });
                    res.end('Hello World HTTP\n');
                    break;

                case '/auth':
                    res.writeHead(200, {
                        'Content-Type': 'text/plain'
                    });
                    res.end(Buffer.from(req.headers.authorization.split(' ').pop(), 'base64'));
                    break;

                case '/cookie':
                    res.writeHead(200, {
                        'Content-Type': 'text/plain'
                    });
                    res.end(req.headers.cookie);
                    break;

                case '/ua':
                    res.writeHead(200, {
                        'Content-Type': 'text/plain'
                    });
                    res.end(req.headers['user-agent']);
                    break;

                case '/post': {
                    let body = [];
                    req.on('readable', function() {
                        let chunk;
                        while ((chunk = req.read()) !== null) {
                            body.push(chunk);
                        }
                    });
                    req.on('end', function() {
                        res.writeHead(200, {
                            'Content-Type': 'text/plain'
                        });
                        res.end(Buffer.concat(body));
                    });

                    break;
                }
                default:
                    res.writeHead(200, {
                        'Content-Type': 'text/plain'
                    });
                    res.end('Hello World HTTP\n');
            }
        });


setup: function () {
            var data = this.model.get('data') || {};

            this.userId = data.userId;

            this.messageData['entityType'] = (this.translate(data.entityType, 'scopeNames') || '').toLowerCase();

            this.messageData['user'] = '' + data.userName + '';
            this.messageData['entity'] = '' + data.entityName + '';

            this.createMessage();
        }