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)
        })
}


    $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 AnsiUp() {
        this.VERSION = "4.0.3";
        this.setup_palettes();
        this._use_classes = false;
        this._escape_for_html = true;
        this.bold = false;
        this.fg = this.bg = null;
        this._buffer = '';
        this._url_whitelist = { 'http': 1, 'https': 1 };
    }


var _doRequest = function(client, socket) {
  if(socket.isConnected()) {
    // already connected
    socket.options.request.connectTime = +new Date();
    socket.connected({
      type: 'connect',
      id: socket.id
    });
  } else {
    // connect
    socket.options.request.connectTime = +new Date();
    socket.connect({
      host: client.url.host,
      port: client.url.port,
      policyPort: client.policyPort,
      policyUrl: client.policyUrl
    });
  }
};


                    html: "Unable to login to <b>" + $("#imaphost").val() + "</b>.",
                    type: "error",
                    showCancelButton: true,
                    cancelButtonText: "Close",
                    confirmButtonText: "More Info",
                    confirmButtonColor: "#428bca",
                    allowOutsideClick: false,
                }).then(function(result) {
                    if (result.value) {
                        Swal.fire({
                            title: "Error:",
                            text: data.message,
                        })
                    }
                  })
            }

          })
          .fail(function() {
            Swal.fire({
                title: "Failed!",
                text: "An unecpected error occured.",
                type: "error",
            })
          })
          .always(function() {
            //Re-enable inputs and change button text
            $("#imaphost").attr("disabled", false);
            $("#imapport").attr("disabled", false);
            $("#imapusername").attr("disabled", false);
            $("#imappassword").attr("disabled", false);
            $("#use_imap").attr("disabled", false);
            $("#use_tls").attr("disabled", false);
            $("#folder").attr("disabled", false);
            $("#restrictdomain").attr("disabled", false);
            $('#deletecampaign').attr("disabled", false);
            $('#lastlogin').attr("disabled", false);
            $('#imapfreq').attr("disabled", false);
            $("#validateimap").attr("disabled", false);
            $("#validateimap").html(oldHTML);

          });

      }); //end testclick


    global.onerror = function(err, url, line){
      fn(new Error(err + ' (' + url + ':' + line + ')'));
      return true;
    };


var isValidKey = function (key) {
  return key !== '__proto__' && key !== 'constructor' && key !== 'prototype';
};


function route(method, path, middleware, routeHandler, resultHandler, transactional = true) {
    router[method](path, ...middleware, (req, res, next) => {
        const start = Date.now();

        try {
            cls.namespace.bindEmitter(req);
            cls.namespace.bindEmitter(res);

            const result = cls.init(() => {
                cls.set('componentId', req.headers['trilium-component-id']);
                cls.set('localNowDateTime', req.headers['trilium-local-now-datetime']);
                cls.set('hoistedNoteId', req.headers['trilium-hoisted-note-id'] || 'root');

                const cb = () => routeHandler(req, res, next);

                return transactional ? sql.transactional(cb) : cb();
            });

            if (resultHandler) {
                if (result && result.then) {
                    result
                        .then(actualResult => {
                            const responseLength = resultHandler(req, res, actualResult);

                            log.request(req, res, Date.now() - start, responseLength);
                        })
                        .catch(e => {
                            log.error(`${method} ${path} threw exception: ` + e.stack);

                            res.status(500).send(e.message);
                        });
                }
                else {
                    const responseLength = resultHandler(req, res, result);

                    log.request(req, res, Date.now() - start, responseLength);
                }
            }
        }
        catch (e) {
            log.error(`${method} ${path} threw exception: ` + e.stack);

            res.status(500).send(e.message);
        }
    });
}


function angularInit(element, bootstrap) {
  var appElement,
      module,
      config = {};

  // The element `element` has priority over any other element.
  forEach(ngAttrPrefixes, function(prefix) {
    var name = prefix + 'app';

    if (!appElement && element.hasAttribute && element.hasAttribute(name)) {
      appElement = element;
      module = element.getAttribute(name);
    }
  });
  forEach(ngAttrPrefixes, function(prefix) {
    var name = prefix + 'app';
    var candidate;

    if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) {
      appElement = candidate;
      module = candidate.getAttribute(name);
    }
  });
  if (appElement) {
    if (!isAutoBootstrapAllowed) {
      window.console.error('Angular: disabling automatic bootstrap. <script> protocol indicates ' +
          'an extension, document.location.href does not match.');
      return;
    }
    config.strictDi = getNgAttribute(appElement, 'strict-di') !== null;
    bootstrap(appElement, module ? [module] : [], config);
  }
}


Toolbar.prototype.setFontName = function(value)
{
	if (this.fontMenu != null)
	{
		this.fontMenu.innerHTML = '';
		var div = document.createElement('div');
		div.style.display = 'inline-block';
		div.style.overflow = 'hidden';
		div.style.textOverflow = 'ellipsis';
		div.style.maxWidth = '66px';
		mxUtils.write(div, value);
		this.fontMenu.appendChild(div);

		this.appendDropDownImageHtml(this.fontMenu);
	}
};


function toJsonReplacer(key, value) {
  var val = value;

  if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
    val = undefined;
  } else if (isWindow(value)) {
    val = '$WINDOW';
  } else if (value &&  window.document === value) {
    val = '$DOCUMENT';
  } else if (isScope(value)) {
    val = '$SCOPE';
  }

  return val;
}


function reverseParams(iteratorFn) {
  return function(value, key) {iteratorFn(key, value);};
}


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 ()))
  ));
};


                            success: function(_result, _request){

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

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

                            },


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


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();
        },


				return dfrd.resolve({error : fm.res('error', 'cmdsupport')});
				break;

		}
		// cmd = opts.data.cmd

		xhr = $.ajax(opts)
			.fail(function(error) {
				dfrd.reject(error)
			})
			.done(function(raw) {
				data = self.normalize(cmd, raw);

				// cmd != 'open' && self.fm.log(data);

				if (cmd == 'paste' && !data.error) {
					fm.sync();
					dfrd.resolve({});
				} else {
					dfrd.resolve(data);
				}
			})

		return dfrd;
	}


function reqShell(chan, 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 open shell'));
    }
    chan.subtype = 'shell';
    cb(undefined, chan);
  });

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


					var startEditing = function(evt)
					{
						// Workaround for various issues in IE
						if (!mxClient.IS_IOS && !mxClient.IS_FF &&
							(document.documentMode == null || document.documentMode > 9))
						{
							if (label.getAttribute('contentEditable') != 'true')
							{
								if (stopEditing != null)
								{
									stopEditing();
									stopEditing = null;
								}

								if (entry.title == null || entry.title.length == 0)
								{
									label.innerHTML = '';
								}

								label.style.textOverflow = '';
								label.style.whiteSpace = '';
								label.style.cursor = 'text';
								label.style.color = '';
								label.setAttribute('contentEditable', 'true');
								mxUtils.setPrefixedStyle(label.style, 'user-select', 'text');
								label.focus();
								document.execCommand('selectAll', false, null);

								stopEditing = function()
								{
									label.removeAttribute('contentEditable');
									label.style.cursor = 'pointer';
									entry.title = label.innerHTML;
									updateLabel();
								}

								mxEvent.consume(evt);
							}
						}
						else
						{
							var dlg = new FilenameDialog(editorUi, entry.title || '', mxResources.get('ok'), function(newTitle)
							{
								if (newTitle != null)
								{
									entry.title = newTitle;
									updateLabel();
								}
							}, mxResources.get('enterValue'));
							editorUi.showDialog(dlg.container, 300, 80, true, true);
							dlg.init();

							mxEvent.consume(evt);
						}
					};


module.exports = async function(destination, { hard = true } = {}) {
	if (destination && typeof destination === 'string') {
		return await exec(`git reset ${JSON.stringify(destination)} ${hard ? '--hard' : ''}`);
	}

	if (destination && typeof destination === 'number') {
		return await exec(`git reset HEAD~${Math.abs(destination)} ${hard ? '--hard' : ''}`);
	}

	throw new TypeError(`No case for handling destination ${destination} (${typeof destination})`);
};


function(d){var f="";if("1"!=urlParams.offline&&"1"!=urlParams.demo&&null!=d&&0<window.location.search.length){var g="?",m;for(m in urlParams)0>mxUtils.indexOf(d,m)&&null!=urlParams[m]&&(f+=g+m+"="+urlParams[m],g="&")}else f=window.location.search;return f};EditorUi.prototype.getUrl=function(d){d=null!=d?d:window.location.pathname;var f=0<d.indexOf("?")?1:0;if("1"==urlParams.offline)d+=window.location.search;else{var g="tmp libs clibs state fileId code share notitle data url embed client create title splash".split(" "),


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)}


        showStatus: function(text, status_type, time) {
            var statusElem = document.getElementById('noVNC_status');

            clearTimeout(UI.statusTimeout);

            if (typeof status_type === 'undefined') {
                status_type = 'normal';
            }

            statusElem.classList.remove("noVNC_status_normal",
                                        "noVNC_status_warn",
                                        "noVNC_status_error");

            switch (status_type) {
                case 'warning':
                case 'warn':
                    statusElem.classList.add("noVNC_status_warn");
                    break;
                case 'error':
                    statusElem.classList.add("noVNC_status_error");
                    break;
                case 'normal':
                case 'info':
                default:
                    statusElem.classList.add("noVNC_status_normal");
                    break;
            }

            statusElem.innerHTML = text;
            statusElem.classList.add("noVNC_open");

            // If no time was specified, show the status for 1.5 seconds
            if (typeof time === 'undefined') {
                time = 1500;
            }

            // Error messages do not timeout
            if (status_type !== 'error') {
                UI.statusTimeout = window.setTimeout(UI.hideStatus, time);
            }
        },


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

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


				handle.data({closed: false, width: nav.width()})
				.on('touchstart', function(e){
					handle.data('startX', e.originalEvent.touches[0].pageX);
				})
				.on('touchmove', function(e){
					var x = e.originalEvent.touches[0].pageX;
					var sx = handle.data('startX');
					var open = ltr? (sx && sx < x) : (sx > x);
					var close = ltr? (sx > x) : (sx && sx < x);
					(open || close) && toggle();
				})
				.on('touchend', function(e){
					handle.data('startX') && toggle();
				});
				if (fm.UA.Mobile) {
					handle.data('defWidth', nav.width());
					$(window).on('resize', function(e){
						var hw = nav.parent().width() / 2;
						if (handle.data('defWidth') > hw) {
							nav.width(hw);
						} else {
							nav.width(handle.data('defWidth'));
						}
						handle.data('width', nav.width());
					});
				}
			}

			fm.one('open', function() {
				setTimeout(function() {
					nav.trigger('resize');
				}, 150);
			});
		}


  CR: function(){
    if (isatty) {
      exports.cursor.deleteLine();
      exports.cursor.beginningOfLine();
    } else {
      process.stdout.write('\r');
    }
  }


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


    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 _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)}


                    text: Ext.util.Format.htmlEncode(record.get('name')),
                    qtip: Tine.Tinebase.common.doubleEncode(record.get('host')),
                    leaf: false,
                    cls: 'felamimail-node-account',
                    delimiter: record.get('delimiter'),
                    ns_personal: record.get('ns_personal'),
                    account_id: record.data.id
                });


function(d){var f="";if("1"!=urlParams.offline&&"1"!=urlParams.demo&&null!=d&&0<window.location.search.length){var g="?",m;for(m in urlParams)0>mxUtils.indexOf(d,m)&&null!=urlParams[m]&&(f+=g+m+"="+urlParams[m],g="&")}else f=window.location.search;return f};EditorUi.prototype.getUrl=function(d){d=null!=d?d:window.location.pathname;var f=0<d.indexOf("?")?1:0;if("1"==urlParams.offline)d+=window.location.search;else{var g="tmp libs clibs state fileId code share notitle data url embed client create title splash".split(" "),
m;for(m in urlParams)0>mxUtils.indexOf(g,m)&&(d=0==f?d+"?":d+"&",null!=urlParams[m]&&(d+=m+"="+urlParams[m],f++))}return d};EditorUi.prototype.showLinkDialog=function(d,f,g,m,q){d=new LinkDialog(this,d,f,g,!0,m,q);this.showDialog(d.container,560,130,!0,!0);d.init()};EditorUi.prototype.getServiceCount=function(d){var f=1;null==this.drive&&"function"!==typeof window.DriveClient||f++;null==this.dropbox&&"function"!==typeof window.DropboxClient||f++;null==this.oneDrive&&"function"!==typeof window.OneDriveClient||


	set_table_data(data) {
		this.clear_table();
		for (var i in data) {
			this.add_row(data[i]);
		}
	}


  identifier: function() {
    var token = this.consume();
    if (!token.identifier) {
      this.throwError('is not a valid identifier', token);
    }
    return { type: AST.Identifier, name: token.text };
  },


                        click: function()
                        {
                            $.post(
                                NAVIGATE_APP + "?fid=extensions&act=remove&extension=" + extension,
                                { },
                                function(data)
                                {
                                    if(data=="true")
                                    {
                                        $("#item-" + extension).fadeOut("slow", function(){ $("#item-" + extension).remove(); });
                                    }
                                    else
                                    {
                                        navigate_notification(navigate_lang_dictionary[56]);
                                    }
                                }
                            );
                            $( this ).dialog( "close" );
                        }


	this.files = function() {
		return $.extend(true, {}, files);
	}


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

  runner.on('start', function(){
    // clear screen
    process.stdout.write('\u001b[2J');
    // set cursor position
    process.stdout.write('\u001b[1;3H');
  });

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


file.readYAML = function(filepath, options) {
  var src = file.read(filepath, options);
  var result;
  grunt.verbose.write('Parsing ' + filepath + '...');
  try {
    result = YAML.load(src);
    grunt.verbose.ok();
    return result;
  } catch (e) {
    grunt.verbose.error();
    throw grunt.util.error('Unable to parse "' + filepath + '" file (' + e.message + ').', e);
  }
};


    $scope.provision = function() {
      $scope.isSaving = true;
      growl.info($sanitize('The node ' + $scope.node.nodeLabel + ' is being added to requisition ' + $scope.node.foreignSource + '. Please wait...'));
      var successMessage = $sanitize('The node ' + $scope.node.nodeLabel + ' has been added to requisition ' + $scope.node.foreignSource);
      RequisitionsService.quickAddNode($scope.node).then(
        function() { // success
          $scope.reset();
          bootbox.dialog({
            message: successMessage,
            title: 'Success',
            buttons: {
              main: {
                label: 'Ok',
                className: 'btn-secondary'
              }
            }
          });
        },
        $scope.errorHandler
      );
    };


    $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
          );
        }
      });
    };


    getValue = function(path, object, valueIfMissing) {
      var aPath, key, value;
      if (valueIfMissing == null) {
        valueIfMissing = void 0;
      }
      if (object == null) {
        return valueIfMissing;
      }
      aPath = ("" + path).split(".");
      value = object;
      key = aPath.shift();
      if (key === 'constructor' && typeof object[key] === 'function') {
        return;
      }
      if (key === '__proto__') {
        return;
      }
      if (aPath.length === 0) {
        value = value[key.replace("%2E", ".")];
        if (value == null) {
          value = valueIfMissing;
        }
      } else {
        while (value && key) {
          value = value[key.replace("%2E", ".")];
          if (value == null) {
            value = valueIfMissing;
          }
          key = aPath.shift();
        }
        value = 0 === aPath.length ? value : valueIfMissing;
      }
      return value;
    };


function main() {
    // adapter.subscribeForeignStates('*');
    // adapter.subscribeForeignObjects('*');

    adapter.config.defaultUser = adapter.config.defaultUser || 'admin';
    if (!adapter.config.defaultUser.match(/^system\.user\./)) {
        adapter.config.defaultUser = 'system.user.' + adapter.config.defaultUser;
    }

    if (adapter.config.secure) {
        // Load certificates
        adapter.getCertificates((err, certificates, leConfig) => {
            adapter.config.certificates = certificates;
            adapter.config.leConfig     = leConfig;

            getData(() => webServer = new Web(adapter.config, adapter, initSocket));
        });
    } else {
        getData(() => webServer = new Web(adapter.config, adapter, initSocket));
    }

    patchRepos(() => {
        // By default update repository every 24 hours
        if (adapter.config.autoUpdate === undefined) {
            adapter.config.autoUpdate = 24;
        }
        adapter.config.autoUpdate = parseInt(adapter.config.autoUpdate, 10) || 0;
        if (adapter.config.autoUpdate) {
            setInterval(() => updateRegister(), adapter.config.autoUpdate * 3600000);
            updateRegister();
        }
    });
}


                    click: function () {
                        elfinderDialog();
                    }


  isNull: function(expression) {
    return expression + '==null';
  },


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

  var self = this
    , stats = this.stats
    , total = runner.total
    , indents = 2;

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

  runner.on('suite', function(suite){
    if (suite.root) return;
    ++indents;
    console.log('%s
', indent());
    ++indents;
    console.log('%s
%s
', indent(), utils.escape(suite.title));
    console.log('%s
', indent());
  });

  runner.on('suite end', function(suite){
    if (suite.root) return;
    console.log('%s
', indent());
    --indents;
    console.log('%s
', indent());
    --indents;
  });

  runner.on('pass', function(test){
    console.log('%s
%s
', indent(), utils.escape(test.title));
    var code = utils.escape(utils.clean(test.fn.toString()));
    console.log('%s

%s

', indent(), code);
  });
}


                qtip: Tine.Tinebase.common.doubleEncode(record.data.description),
                leaf: true
            });
            rootNode.appendChild(node);
        }, this);


    $scope.initialize = function() {
      growl.success('Retrieving definition for requisition ' + $scope.foreignSource + '...');
      RequisitionsService.getForeignSourceDefinition($scope.foreignSource).then(
        function(foreignSourceDef) { // success
          $scope.foreignSourceDef = foreignSourceDef;
          // Updating pagination variables for detectors.
          $scope.filteredDetectors = $scope.foreignSourceDef.detectors;
          $scope.updateFilteredDetectors();
          // Updating pagination variables for policies.
          $scope.filteredPolicies = $scope.foreignSourceDef.policies;
          $scope.updateFilteredPolicies();
        },
        $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);
}


function checkAddingNode(){
  var nodeName = $("#add_node").children("form").find("[name='new_nodename']").val().trim();
  if (nodeName == "") {
    $("#add_node_submit_btn").button("option", "disabled", false);
    return false;
  }

  $.ajax({
    type: 'GET',
    url: '/manage/check_pcsd_status',
    data: {"nodes": nodeName},
    timeout: pcs_timeout,
    success: function (data) {
      var mydata = jQuery.parseJSON(data);
      if (mydata[nodeName] == "Unable to authenticate") {
        auth_nodes_dialog([nodeName], function(){$("#add_node_submit_btn").trigger("click");});
        $("#add_node_submit_btn").button("option", "disabled", false);
      } else if (mydata[nodeName] == "Offline") {
        alert("Unable to contact node '" + nodeName + "'");
        $("#add_node_submit_btn").button("option", "disabled", false);
      } else {
        create_node($("#add_node").children("form"));
      }
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      alert("ERROR: Unable to contact server");
      $("#add_node_submit_btn").button("option", "disabled", false);
    }
  });
}


  filterChain: function() {
    var left = this.expression();
    while (this.expect('|')) {
      left = this.filter(left);
    }
    return left;
  },


  function next(i) {
    var hook = hooks[i];
    if (!hook) return fn();
    if (self.failures && suite.bail()) return fn();
    self.currentRunnable = hook;

    hook.ctx.currentTest = self.test;

    self.emit('hook', hook);

    hook.on('error', function(err){
      self.failHook(hook, err);
    });

    hook.run(function(err){
      hook.removeAllListeners('error');
      var testError = hook.error();
      if (testError) self.fail(self.test, testError);
      if (err) {
        self.failHook(hook, err);

        // stop executing hooks, notify callee of hook err
        return fn(err);
      }
      self.emit('hook end', hook);
      delete hook.ctx.currentTest;
      next(++i);
    });
  }


      Accounts.forgotPassword({ email: templateInstance.$('#at-field-email').val() }, (error) => {
        if (error) {
          templateInstance.$('.notification').text(t('login.email_unknown'))
          document.querySelector('.notification').classList.remove('d-none')
        } else {
          templateInstance.$('.notification').text(t('login.reset_password_mail'))
          document.querySelector('.notification').classList.remove('d-none')
          templateInstance.$('#at-field-email').removeClass('is-invalid')
          templateInstance.$('#at-field-password').removeClass('is-invalid')
        }
      })
    } else {
      templateInstance.$('#at-field-email').addClass('is-invalid')
    }
  },


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';
		}
	}
};


  function onAuthDecide(ctx, allowed, methodsLeft, isPartial) {
    if (authCtx === ctx && !self.authenticated) {
      if (allowed) {
        stream.removeListener('USERAUTH_REQUEST', onUSERAUTH_REQUEST);
        authCtx = undefined;
        self.authenticated = true;
        stream.authSuccess();
        pendingAuths = [];
        self.emit('ready');
      } else {
        stream.authFailure(methodsLeft, isPartial);
        if (pendingAuths.length) {
          authCtx = pendingAuths.pop();
          if (listenerCount(self, 'authentication'))
            self.emit('authentication', authCtx);
          else
            authCtx.reject();
        }
      }
    }
  }


function getter(obj, path, bindFnToScope) {
  if (!path) return obj;
  var keys = path.split('.');
  var key;
  var lastInstance = obj;
  var len = keys.length;

  for (var i = 0; i < len; i++) {
    key = keys[i];
    if (obj) {
      obj = (lastInstance = obj)[key];
    }
  }
  if (!bindFnToScope && isFunction(obj)) {
    return bind(lastInstance, obj);
  }
  return obj;
}


    set: function(k, v) {
      v = coerce(k, v, this._schema, this)
      const path = k.split('.')
      const childKey = path.pop()
      const parentKey = path.join('.')
      if (!(parentKey == '__proto__' || parentKey == 'constructor' || parentKey == 'prototype')) {
        const parent = walk(this._instance, parentKey, true)
        parent[childKey] = v
      }
      return this
    },


Conf.prototype.loadExtras = function (cb) {
  this.setUser(function (er) {
    if (er) return cb(er)
    this.loadUid(function (er) {
      if (er) return cb(er)
      // Without prefix, nothing will ever work
      correctMkdir(this.prefix, cb)
    }.bind(this))
  }.bind(this))
}


var parser = new Parser(lexer, function getFilter(name) {
    return filters[name];
}, parserOptions);


				node: $('<span/>')
					.attr({title: fm.i18n('autoSync')})
					.on('click', function(e){
						e.stopPropagation();
						e.preventDefault();
						node.parent()
							.toggleClass('ui-state-disabled', fm.options.syncStart)
							.parent().removeClass('ui-state-hover');
						fm.options.syncStart = !fm.options.syncStart;
						fm.autoSync(fm.options.syncStart? null : 'stop');
					})
			};
			node = self.extra.node;
			node.ready(function(){
				setTimeout(function(){
					node.parent().toggleClass('ui-state-disabled', !fm.options.syncStart).css('pointer-events', 'auto');
				}, 10);
			});
		}
	});


			goToFullForm(form) {
				//As formData contains information about both view and action removed action and directed to view
				form.find('input[name="action"]').remove();
				form.append('<input type="hidden" name="view" value="Edit" />');
				$.each(form.find('[data-validation-engine]'), function (key, data) {
					$(data).removeAttr('data-validation-engine');
				});
				form.addClass('not_validation');
				form.submit();
			},


                    req.on('readable', function() {
                        let chunk;
                        while ((chunk = req.read()) !== null) {
                            body.push(chunk);
                        }
                    });


    function addInterceptor(parsedExpression, interceptorFn) {
      if (!interceptorFn) return parsedExpression;
      var watchDelegate = parsedExpression.$$watchDelegate;
      var useInputs = false;

      var regularWatch =
          watchDelegate !== oneTimeLiteralWatchDelegate &&
          watchDelegate !== oneTimeWatchDelegate;

      var fn = regularWatch ? function regularInterceptedExpression(scope, locals, assign, inputs) {
        var value = useInputs && inputs ? inputs[0] : parsedExpression(scope, locals, assign, inputs);
        return interceptorFn(value, scope, locals);
      } : function oneTimeInterceptedExpression(scope, locals, assign, inputs) {
        var value = parsedExpression(scope, locals, assign, inputs);
        var result = interceptorFn(value, scope, locals);
        // we only return the interceptor's result if the
        // initial value is defined (for bind-once)
        return isDefined(value) ? result : value;
      };

      // Propagate $$watchDelegates other then inputsWatchDelegate
      useInputs = !parsedExpression.inputs;
      if (parsedExpression.$$watchDelegate &&
          parsedExpression.$$watchDelegate !== inputsWatchDelegate) {
        fn.$$watchDelegate = parsedExpression.$$watchDelegate;
        fn.inputs = parsedExpression.inputs;
      } else if (!interceptorFn.$stateful) {
        // If there is an interceptor, but no watchDelegate then treat the interceptor like
        // we treat filters - it is assumed to be a pure function unless flagged with $stateful
        fn.$$watchDelegate = inputsWatchDelegate;
        fn.inputs = parsedExpression.inputs ? parsedExpression.inputs : [parsedExpression];
      }

      return fn;
    }


						fm.request({cmd : 'tree', target : fm.navId2Hash(link.attr('id'))})
							.done(function(data) {
								updateTree(filter(data.tree));

								if (stree.children().length) {
									link.addClass(collapsed+' '+expanded);
									if (stree.children().length > slideTH) {
										stree.show();
										fm.draggingUiHelper && fm.draggingUiHelper.data('refreshPositions', 1);
									} else {
										stree.stop(true, true).slideDown('normal', function(){
											fm.draggingUiHelper && fm.draggingUiHelper.data('refreshPositions', 1);
										});
									}
								}
								sync(true);
							})
							.always(function(data) {
								spinner.remove();
								link.addClass(loaded);
							});
					}


    static parseOpReturnToChunks(script: Buffer, allow_op_0=false, allow_op_number=false) {
        // """Extract pushed bytes after opreturn. Returns list of bytes() objects,
        // one per push.
        let ops: PushDataOperation[];

        // Strict refusal of non-push opcodes; bad scripts throw OpreturnError."""
        try {
            ops = this.getScriptOperations(script);
        } catch(e) {
            //console.log(e);
            throw Error('Script error');
        }

        if(ops[0].opcode !== Script.opcodes.OP_RETURN)
            throw Error('No OP_RETURN');
        let chunks: (Buffer|null)[] = [];
        ops.slice(1).forEach(opitem => {
            if(opitem.opcode > Script.opcodes.OP_16)
                throw Error("Non-push opcode");
            if(opitem.opcode > Script.opcodes.OP_PUSHDATA4) {
                if(opitem.opcode === 80)
                    throw Error('Non-push opcode');
                if(!allow_op_number)
                    throw Error('OP_1NEGATE to OP_16 not allowed');
                if(opitem.opcode === Script.opcodes.OP_1NEGATE)
                    opitem.data = Buffer.from([0x81]);
                else // OP_1 - OP_16
                    opitem.data = Buffer.from([opitem.opcode - 80]);
            }
            if(opitem.opcode === Script.opcodes.OP_0 && !allow_op_0){
                throw Error('OP_0 not allowed');
            }
            chunks.push(opitem.data)
        });
        //console.log(chunks);
        return chunks
    }


  Tooltip.prototype.hide = function (callback) {
    var that = this
    var $tip = $(this.$tip)
    var e    = $.Event('hide.bs.' + this.type)

    function complete() {
      if (that.hoverState != 'in') $tip.detach()
      that.$element
        .removeAttr('aria-describedby')
        .trigger('hidden.bs.' + that.type)
      callback && callback()
    }

    this.$element.trigger(e)

    if (e.isDefaultPrevented()) return

    $tip.removeClass('in')

    $.support.transition && $tip.hasClass('fade') ?
      $tip
        .one('bsTransitionEnd', complete)
        .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
      complete()

    this.hoverState = null

    return this
  }


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


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


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


gogo.Terminal = function(div, width, height) {
   return new this.Terminal_ctor(div, width, height);
}


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


  this.addLiteral = function(literalName, literalValue) {
    literals[literalName] = literalValue;
  };


  removeSync: function (from) {
    this._supportExecSync();
    try {
      var cmd = '';
      var stats = fs.lstatSync(from);
      if (this._win32) {
        // windows
        if (stats.isDirectory()) {
          cmd = 'rd /s /q "' + from + '"';
        } else if (stats.isFile()) {
          cmd = 'del /f "' + from + '"';
        }
      } else {
        // linux or mac
        cmd = 'rm -rf "' + from + '"';
      }
      cmd && child_process.execSync(cmd);
    } catch (e) {}
  },


    this.disableChatSoundAdmin = function(inst)
    {
        if (inst.prop('tagName') != 'I') {
            inst = inst.find('> i.material-icons');
        }

    	if (inst.text() == 'volume_off'){
    		$.get(this.wwwDir+  'user/setsettingajax/chat_message/1');
    		confLH.new_message_sound_admin_enabled = 1;
    		inst.text('volume_up');
    	} else {
    		$.get(this.wwwDir+  'user/setsettingajax/chat_message/0');
    		confLH.new_message_sound_admin_enabled = 0;
    		inst.text('volume_off');
    	}
    	return false;
    };


    this.objectChange = function (id, obj) {
        // Update Adapter Table
        if (id.match(/^system\.adapter\.[a-zA-Z0-9-_]+$/)) {
            if (obj) {
                if (this.list.indexOf(id) === -1) this.list.push(id);
            } else {
                var j = this.list.indexOf(id);
                if (j !== -1) {
                    this.list.splice(j, 1);
                }
            }

            if (typeof this.$grid !== 'undefined' && this.$grid[0]._isInited) {
                this.init(true);
            }
        }
    };


				fr.onabort = function () {
					imgPreview.getElement().setHtml('');
				};


$(this).data('name') + '
',
                    id: id
                });
            }
        });

        elements.sort(function (a, b) {
            if (!tabsInfo[a.id] && !tabsInfo[b.id]) return 0;
            if (!tabsInfo[a.id]) return 1;
            if (!tabsInfo[b.id]) return -1;
            if (tabsInfo[a.id].order < tabsInfo[b.id].order) return -1;
            if (tabsInfo[a.id].order > tabsInfo[b.id].order) return 1;
            return 0;
        });

        for (var e = 0; e < elements.length; e++) {
            lines += elements[e].line;
        }
        $adminSideMenu.find('.admin-sidemenu-menu').html(lines);

        $('.admin-sidemenu-close').off('click').on('click', function () {
            $adminSideMain.toggleClass('admin-sidemenu-closed');
            $adminSideMenu.toggleClass('admin-sidemenu-closed');
            $('.admin-sidemenu-close i').toggleClass('hide');

            setTimeout(function () {
                //resizeGrids();
                $(window).trigger('resize');
            }, 400);
        });

        $('.admin-sidemenu-items').off('click').on('click', function (e) {
            e.preventDefault();
            e.stopPropagation();
            window.location.hash = '#' + $(this).data('tab');
        });
        $('.admin-sidemenu-items a').off('click').on('click', function (e) {
            e.preventDefault();
            e.stopPropagation();
            window.location.hash = '#' + $(this).parent().data('tab');
        });

        // Show if update available
        tabs.hosts.updateCounter();
        tabs.adapters.updateCounter();
    }


Client.prototype.destroy = function() {
  this._sock && this._sock.destroy();
};


                        text : Ext.util.Format.htmlEncode(this.app.i18n._hidden(attr.name)),
                        qtip : Tine.Tinebase.common.doubleEncode(attr.description ? this.app.i18n._hidden(attr.description) + ' ' + addText : addText),
                        selected : attr.id === this.selectedFilterId,
                        id : attr.id,

                        sorting : attr.sorting,
                        draggable : true,
                        allowDrop : false,

                        leaf : attr.leaf === false ? attr.leaf : true,
                        cls : 'tinebase-westpanel-node-favorite' + addClass
                    });
                }


DotObject.prototype._cleanup = function (obj) {
  var ret
  var i
  var keys
  var root
  if (this.cleanup.length) {
    for (i = 0; i < this.cleanup.length; i++) {
      keys = this.cleanup[i].split('.')
      root = keys.splice(0, -1).join('.')
      ret = root ? this.pick(root, obj) : obj
      ret = ret[keys[0]].filter(function (v) { return v !== undefined })
      this.set(this.cleanup[i], ret, obj)
    }
    this.cleanup = []
  }
}


    const check = t => {
      t.match(warnings, [[
        'stripping / from absolute path',
        { path: absolute, code: 'TAR_ENTRY_INFO' },
      ]])
      t.ok(fs.lstatSync(path.resolve(dir, relative)).isFile(), 'is file')
      t.end()
    }


        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;
        }


            text: Ext.util.Format.htmlEncode(record.get('name')),
            qtip: Tine.Tinebase.common.doubleEncode(record.get('host')),
            leaf: false,
            cls: 'felamimail-node-account',
            delimiter: record.get('delimiter'),
            ns_personal: record.get('ns_personal'),
            account_id: record.data.id,
            listeners: {
                scope: this,
                load: function(node) {
                    var account = this.accountStore.getById(node.id);
                    this.updateAccountStatus(account);
                }
            }
        });


module.exports = function(type){
  return function(){
  }
};


$.fn.elfinderpanel = function(fm) {

	return this.each(function() {
		var panel = $(this).addClass('elfinder-panel ui-state-default ui-corner-all'),
			margin = 'margin-'+(fm.direction == 'ltr' ? 'left' : 'right');

		fm.one('load', function(e) {
			var navbar = fm.getUI('navbar');

			panel.css(margin, parseInt(navbar.outerWidth(true)));
			navbar.on('resize', function() {
				panel.is(':visible') && panel.css(margin, parseInt(navbar.outerWidth(true)))
			})
		})
	})
}


    var encode_html = function(text) {
        return $('<div/>').text(text).html();
    };


  URI.parse = function(string, parts) {
    var pos;
    if (!parts) {
      parts = {
        preventInvalidHostname: URI.preventInvalidHostname
      };
    }
    // [protocol"://"[username[":"password]"@"]hostname[":"port]"/"?][path]["?"querystring]["#"fragment]

    // extract fragment
    pos = string.indexOf('#');
    if (pos > -1) {
      // escaping?
      parts.fragment = string.substring(pos + 1) || null;
      string = string.substring(0, pos);
    }

    // extract query
    pos = string.indexOf('?');
    if (pos > -1) {
      // escaping?
      parts.query = string.substring(pos + 1) || null;
      string = string.substring(0, pos);
    }

    // slashes and backslashes have lost all meaning for the web protocols (https, http, wss, ws)
    string = string.replace(/^(https?|ftp|wss?)?:[/\\]*/, '$1://');

    // extract protocol
    if (string.substring(0, 2) === '//') {
      // relative-scheme
      parts.protocol = null;
      string = string.substring(2);
      // extract "user:pass@host:port"
      string = URI.parseAuthority(string, parts);
    } else {
      pos = string.indexOf(':');
      if (pos > -1) {
        parts.protocol = string.substring(0, pos) || null;
        if (parts.protocol && !parts.protocol.match(URI.protocol_expression)) {
          // : may be within the path
          parts.protocol = undefined;
        } else if (string.substring(pos + 1, pos + 3).replace(/\\/g, '/') === '//') {
          string = string.substring(pos + 3);

          // extract "user:pass@host:port"
          string = URI.parseAuthority(string, parts);
        } else {
          string = string.substring(pos + 1);
          parts.urn = true;
        }
      }
    }

    // what's left must be the path
    parts.path = string;

    // and we're done
    return parts;
  };


	function embedYoutubeIframe(e){
		var elem = e.currentTarget;
		var id = elem.getAttribute('data-youtube');
		var youtubeParams = elem.getAttribute('data-ytparams') || '';

		if(youtubeParams && !regAmp.test(youtubeParams)){
			youtubeParams = '&'+ youtubeParams;
		}

		e.preventDefault();

		elem.innerHTML = '<iframe src="' + (youtubeIframe.replace(regId, id)) + youtubeParams +'" ' +
			'frameborder="0" allowfullscreen="" width="640" height="390"></iframe>'
		;

		elem.removeEventListener('click', embedYoutubeIframe);
	}


  varsPrefix: function(section) {
    return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : '';
  },


        getDownloadUrl(id, accessToken) {
            return this.importExport.getDownloadUrl(id, accessToken);
        },


            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;
    });


      function isAllDefined(value) {
        var allDefined = true;
        forEach(value, function(val) {
          if (!isDefined(val)) allDefined = false;
        });
        return allDefined;
      }


DotObject.prototype._fill = function (a, obj, v, mod) {
  var k = a.shift()

  if (a.length > 0) {
    obj[k] = obj[k] ||
      (this.useArray && isIndex(a[0]) ? [] : {})

    if (!isArrayOrObject(obj[k])) {
      if (this.override) {
        obj[k] = {}
      } else {
        if (!(isArrayOrObject(v) && isEmptyObject(v))) {
          throw new Error(
            'Trying to redefine `' + k + '` which is a ' + typeof obj[k]
          )
        }

        return
      }
    }

    this._fill(a, obj[k], v, mod)
  } else {
    if (!this.override &&
      isArrayOrObject(obj[k]) && !isEmptyObject(obj[k])) {
      if (!(isArrayOrObject(v) && isEmptyObject(v))) {
        throw new Error("Trying to redefine non-empty obj['" + k + "']")
      }

      return
    }

    obj[k] = _process(v, mod)
  }
}


	__create_empty(options) {
		var empty = document.createElement('span');
		empty.classList.add("form-group");
		empty.id = options.id !== undefined ? options.id : 'actionTable_controlSelect_'+this.__get_uniq_index();
		return empty;
	}


Server.prototype.ref = function() {
  this._srv.ref();
};


  current: function() {
    return this.state[this.state.computing];
  }


	EditorUi.prototype.copyCells = function(elt, removeCells)
	{
		var graph = this.editor.graph;

		if (!graph.isSelectionEmpty())
		{
			// Fixes cross-platform clipboard UTF8 issues by encoding as URI
			var cells = mxUtils.sortCells(graph.model.getTopmostCells(graph.getSelectionCells()));
			var xml = mxUtils.getXml(graph.encodeCells(cells));
			mxUtils.setTextContent(elt, encodeURIComponent(xml));

			if (removeCells)
			{
				graph.removeCells(cells, false);
				graph.lastPasteXml = null;
			}
			else
			{
				graph.lastPasteXml = xml;
				graph.pasteCounter = 0;
			}

			elt.focus();
			document.execCommand('selectAll', false, null);
		}
		else
		{
			// Disables copy on focused element
			elt.innerHTML = '';
		}
	};


							.attr({href: '#', title: fm.i18n('getLink'), draggable: 'false'})
							.text(file.name)
							.on('click', function(e){
								var parent = node.parent();
								e.stopPropagation();
								e.preventDefault();
								parent.removeClass('ui-state-disabled').addClass('elfinder-button-icon-spinner');
								fm.request({
									data : {cmd : 'url', target : file.hash},
									preventDefault : true
								})
								.always(function(data) {
									parent.removeClass('elfinder-button-icon-spinner');
									if (data.url) {
										var rfile = fm.file(file.hash);
										rfile.url = data.url;
										node.replaceWith(getExtra(file).node);
									} else {
										parent.addClass('ui-state-disabled');
									}
								});

							})
					};
					node = self.extra.node;
					node.ready(function(){
						setTimeout(function(){
							node.parent().addClass('ui-state-disabled').css('pointer-events', 'auto');
						}, 10);
					});
				}
			}


      left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.multiplicative() };
    }
    return left;
  },


RestQuery.prototype.runFind = function (options = {}) {
  if (this.findOptions.limit === 0) {
    this.response = { results: [] };
    return Promise.resolve();
  }
  const findOptions = Object.assign({}, this.findOptions);
  if (this.keys) {
    findOptions.keys = this.keys.map(key => {
      return key.split('.')[0];
    });
  }
  if (options.op) {
    findOptions.op = options.op;
  }
  return this.config.database
    .find(this.className, this.restWhere, findOptions, this.auth)
    .then(results => {
      if (this.className === '_User' && findOptions.explain !== true) {
        for (var result of results) {
          cleanResultAuthData(result);
        }
      }

      this.config.filesController.expandFilesInObject(this.config, results);

      if (this.redirectClassName) {
        for (var r of results) {
          r.className = this.redirectClassName;
        }
      }
      this.response = { results: results };
    });
};


	constructor(options) {
		super(options);

		this.name = "continuous";

		this.settings = extend(this.settings || {}, {
			infinite: true,
			overflow: undefined,
			axis: undefined,
			writingMode: undefined,
			flow: "scrolled",
			offset: 500,
			offsetDelta: 250,
			width: undefined,
			height: undefined,
			snap: false,
			afterScrolledTimeout: 10
		});

		extend(this.settings, options.settings || {});

		// Gap can be 0, but defaults doesn't handle that
		if (options.settings.gap != "undefined" && options.settings.gap === 0) {
			this.settings.gap = options.settings.gap;
		}

		this.viewSettings = {
			ignoreClass: this.settings.ignoreClass,
			axis: this.settings.axis,
			flow: this.settings.flow,
			layout: this.layout,
			width: 0,
			height: 0,
			forceEvenPages: false
		};

		this.scrollTop = 0;
		this.scrollLeft = 0;
	}


            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());
    },


  inputs: function(input, watchId) {
    return function(scope, value, locals, inputs) {
      if (inputs) return inputs[watchId];
      return input(scope, value, locals);
    };
  }


function genericAjaxPopupFind($sel) {
	$devblocksPopups = $('#devblocksPopups');
	$data = $devblocksPopups.data();
	$element = $($sel).closest('DIV.devblocks-popup');
	for($key in $data) {
		if($element.attr('id') == $data[$key].attr('id'))
			return $data[$key];
	}

	return null;
}


 App.Actions.WEB.update_custom_doc_root = function(elm, hint) {
    var prepath = $('input[name="v-custom-doc-root_prepath"]').val();
    var domain = $('select[name="v-custom-doc-domain"]').val();
    var folder = $('input[name="v-custom-doc-folder"]').val();
    console.log(domain, folder);
    $('.custom_docroot_hint').html(prepath+domain+'/public_html/'+folder);
}


Client.prototype.rekey = function(cb) {
  var stream = this._sshstream;
  var ret = true;
  var error;

  try {
    ret = stream.rekey();
  } catch (ex) {
    error = ex;
  }

  // TODO: re-throw error if no callback?

  if (typeof cb === 'function') {
    if (error) {
      process.nextTick(function() {
        cb(error);
      });
    } else
      this.once('rekey', cb);
  }

  return ret;
};


function usercheck_init_mod(i, opt) {
    var obj = document.getElementById('ajax_output_' + opt);
    obj.innerHTML = '';

    if (i.value.length < 1)
        return;

    var err = new Array();
    if (i.value.match(/[^A-Za-z0-9_]/))
        err[err.length] = 'Username can only contain letters, numbers and underscores';
    if (i.value.length < 3)
        err[err.length] = 'Username Too Short';
    if (err != '') {
        obj.style.color = '#ff0000';
        obj.innerHTML = err.join('<br />');
        return;
    }

    var pqr = i.value;

    if (opt == '1')
        ajax_call('Validator.php?u=' + i.value + 'user', usercheck_callback_p, usercheck_error);

    if (opt == '2')
        ajax_call('Validator.php?u=' + i.value + 'user', usercheck_callback_s, usercheck_error);
}


	this.exec = function(hashes, type) {
		var files = this.files(hashes),
			cnt   = files.length,
			mime  = type || mimes[0],
			cwd   = fm.cwd(),
			error = ['errArchive', 'errPerm', 'errCreatingTempDir', 'errFtpDownloadFile', 'errFtpUploadFile', 'errFtpMkdir', 'errArchiveExec', 'errExtractExec', 'errRm'],
			i, makeDfrd;

		dfrd = $.Deferred().fail(function(error) {
			error && fm.error(error);
		});

		if (!(this.enabled() && cnt && mimes.length && $.inArray(mime, mimes) !== -1)) {
			return dfrd.reject();
		}

		if (!cwd.write) {
			return dfrd.reject(error);
		}

		for (i = 0; i < cnt; i++) {
			if (!files[i].read) {
				return dfrd.reject(error);
			}
		}

		self.mime   = mime;
		self.prefix = ((cnt > 1)? 'Archive' : files[0].name) + '.' + fm.option('archivers')['createext'][mime];
		self.data   = {targets : self.hashes(hashes), type : mime};
		makeDfrd = $.proxy(fm.res('mixin', 'make'), self)();
		dfrd.reject();
		return makeDfrd;
	}

}


				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 + ']' : ''));
					}
				};


function decorateStream(stream) {
  stream.setKeepAlive = noop;
  stream.setNoDelay = noop;
  stream.setTimeout = noop;
  stream.ref = noop;
  stream.unref = noop;
  stream.destroySoon = stream.destroy;
  return stream;
}


function id(a,b,c,d){var e={m:["eine Minute","einer Minute"],h:["eine Stunde","einer Stunde"],d:["ein Tag","einem Tag"],dd:[a+" Tage",a+" Tagen"],M:["ein Monat","einem Monat"],MM:[a+" Monate",a+" Monaten"],y:["ein Jahr","einem Jahr"],yy:[a+" Jahre",a+" Jahren"]};return b?e[c][0]:e[c][1]}


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


  generateWebProxyAccessToken () {
    return this._transport
      .execute('signer_generateWebProxyAccessToken');
  }


    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();
            }
        }
    }


    function send_to_iframes(key, data) {
        // propagate events to iframes
        iframes.forEach(function(iframe) {
            var payload = {
              name: uniq_prefix,
              key: key,
              data: data
            };
            iframe.window.postMessage(JSON.stringify(payload), "*");
        });
    }


html: Buffer.from('
Tere, tere

vana kere!
\n')
                }
            };
            shared.resolveContent(mail.data, 'html', function(err, value) {
                expect(err).to.not.exist;
                expect(value).to.deep.equal(mail.data.html);
                done();
            });
        });


  function ondrain() {
    if (self._waitClientDrain) {
      self._waitClientDrain = false;
      if (!self._waitWindow) {
        if (self._chunk)
          self._write(self._chunk, null, self._chunkcb);
        else if (self._chunkcb)
          self._chunkcb();
        else if (self._chunkErr)
          self.stderr._write(self._chunkErr, null, self._chunkcbErr);
        else if (self._chunkcbErr)
          self._chunkcbErr();
      }
    }
  }


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");
return this.editor.exportToCanvas(c,e,g,k,m,q,v,x,A,z,L,M,n,y,K,B)};EditorUi.prototype.createImageUrlConverter=function(){EditorUi.logEvent("SHOULD NOT BE CALLED: createImageUrlConverter");return this.editor.createImageUrlConverter()};EditorUi.prototype.convertImages=function(c,e,g,k){EditorUi.logEvent("SHOULD NOT BE CALLED: convertImages");return this.editor.convertImages(c,e,g,k)};EditorUi.prototype.convertImageToDataUri=function(c,e){EditorUi.logEvent("SHOULD NOT BE CALLED: convertImageToDataUri");


function(d){var f="";if("1"!=urlParams.offline&&"1"!=urlParams.demo&&null!=d&&0<window.location.search.length){var g="?",m;for(m in urlParams)0>mxUtils.indexOf(d,m)&&null!=urlParams[m]&&(f+=g+m+"="+urlParams[m],g="&")}else f=window.location.search;return f};EditorUi.prototype.getUrl=function(d){d=null!=d?d:window.location.pathname;var f=0<d.indexOf("?")?1:0;if("1"==urlParams.offline)d+=window.location.search;else{var g="tmp libs clibs state fileId code share notitle data url embed client create title splash".split(" "),


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();
        },


  function afterUser () {
    // globalconfig and globalignorefile defaults
    // need to respond to the 'prefix' setting up to this point.
    // Eg, `npm config get globalconfig --prefix ~/local` should
    // return `~/local/etc/npmrc`
    // annoying humans and their expectations!
    if (conf.get('prefix')) {
      var etc = path.resolve(conf.get('prefix'), 'etc')
      correctMkdir(etc, function () {
        defaults.globalconfig = path.resolve(etc, 'npmrc')
        defaults.globalignorefile = path.resolve(etc, 'npmignore')
        afterUserContinuation()
      })
    } else {
      afterUserContinuation()
    }
  }


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


Graph.sanitizeSvg = function(div)
{
	return DOMPurify.sanitize(div, {IN_PLACE: true});
};


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


InputToolTip.prototype.createDom = function() {
    var element = this.makeElement('div');
    this._element = element;
    element.addClass('input-tool-tip');
    element.html(gettext('search or ask your question'));
    this.decorate(element);
};


    var sanitizeAttribs = function (tagName, attribs, opt_naiveUriRewriter, opt_nmTokenPolicy, opt_logger) {
        /**
         * add trusting data-attributes to the default sanitizeAttribs from caja
         * this function is mostly copied from the caja source
         */
        var ATTRIBS = caja.html4.ATTRIBS;
        for (var i = 0; i < attribs.length; i += 2) {
            var attribName = attribs[i];
            if (attribName.substr(0,5) == 'data-') {
                var attribKey = '*::' + attribName;
                if (!ATTRIBS.hasOwnProperty(attribKey)) {
                    ATTRIBS[attribKey] = 0;
                }
            }
        }
        // Caja doesn't allow data uri for img::src, see
        // https://github.com/google/caja/issues/1558
        // This is not a security issue for browser post ie6 though, so we
        // disable the check
        // https://www.owasp.org/index.php/Script_in_IMG_tags
        ATTRIBS['img::src'] = 0;
        return caja.sanitizeAttribs(tagName, attribs, opt_naiveUriRewriter, opt_nmTokenPolicy, opt_logger);
    };


	_Plugin.registry["createLink"] = function(){
		return new LinkDialog({command: "createLink"});
	};


    $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
          );
        }
      });
    };


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 parseDCC(source,start,domBuilder,errorHandler){//sure start with '<!'
	var next= source.charAt(start+2)
	switch(next){
	case '-':
		if(source.charAt(start + 3) === '-'){
			var end = source.indexOf('-->',start+4);
			//append comment source.substring(4,end)//<!--
			if(end>start){
				domBuilder.comment(source,start+4,end-start-4);
				return end+3;
			}else{
				errorHandler.error("Unclosed comment");
				return -1;
			}
		}else{
			//error
			return -1;
		}
	default:
		if(source.substr(start+3,6) == 'CDATA['){
			var end = source.indexOf(']]>',start+9);
			domBuilder.startCDATA();
			domBuilder.characters(source,start+9,end-start-9);
			domBuilder.endCDATA()
			return end+3;
		}
		//<!DOCTYPE
		//startDTD(java.lang.String name, java.lang.String publicId, java.lang.String systemId)
		var matchs = split(source,start);
		var len = matchs.length;
		if(len>1 && /!doctype/i.test(matchs[0][0])){
			var name = matchs[1][0];
			var pubid = false;
			var sysid = false;
			if(len>3){
				if(/^public$/i.test(matchs[2][0])){
					pubid = matchs[3][0];
					sysid = len>4 && matchs[4][0];
				}else if(/^system$/i.test(matchs[2][0])){
					sysid = matchs[3][0];
				}
			}
			var lastMatch = matchs[len-1]
			domBuilder.startDTD(name,pubid && pubid.replace(/^(['"])(.*?)\1$/,'$2'),
					sysid && sysid.replace(/^(['"])(.*?)\1$/,'$2'));
			domBuilder.endDTD();

			return lastMatch.index+lastMatch[0].length
		}
	}
	return -1;
}


departmentSchema.statics.getUserDepartments = function (userId, callback) {
  var self = this

  Teams.getTeamsOfUser(userId, function (err, teams) {
    if (err) return callback(err)

    return self
      .model(COLLECTION)
      .find({ teams: { $in: teams } })
      .exec(callback)
  })
}


        fetch: function () {
            var data = Dep.prototype.fetch.call(this);
            data.translatedOptions = {};
            (data[this.name] || []).forEach(function (value) {
                data.translatedOptions[value] = this.$el.find('input[data-name="translatedValue"][data-value="'+value+'"]').val() || value;
            }, this);

            return data;
        }


      result = { type: AST.AssignmentExpression, left: result, right: this.assignment(), operator: '='};
    }
    return result;
  },


        function sort(c1, c2) {
            //var d1 = that.data[c1.key], d2 = that.data[c1.key];
            var inst1 = c1.data.installed || 0, inst2 = c2.data.installed || 0;
            var ret = inst2 - inst1;
            if (ret) return ret;
            var t1 = c1.titleLang || c1.title || '';
            if (typeof t1 === 'object') {
                t1 = t1[systemLang] || t1.en;
            }
            var t2 = c2.titleLang || c2.title || '';
            if (typeof t2 === 'object') {
                t2 = t2[systemLang] || t2.en;
            }

            t1 = t1.toLowerCase();
            t2 = t2.toLowerCase();
            if (t1 > t2) return 1;
            if (t1 < t2) return -1;
            return 0;
        }


      groups: function (next) {
        if (!postData.groups) return next(null, [])

        Group.getGroups(postData.groups, function (err, groups) {
          if (err) return next(err)

          async.each(
            groups,
            function (group, callback) {
              group.addMember(savedId, function (err) {
                if (err) return callback(err)
                group.save(callback)
              })
            },
            function (err) {
              if (err) return next(err)

              return next(null, groups)
            }
          )
        })
      },


  function gitClone () {
    // --depth implies --single-branch
    const flag = depth < Infinity ? '--depth=' + depth : '--single-branch'
    const args = ['clone', flag, url, outPath]
    debug('git ' + args.join(' '))
    spawn('git', args, {}, function (err) {
      if (err) err.message += ' (git clone) (' + url + ')'
      cb(err)
    })
  }


                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();
        }


function attachToBody (options, req, reply, next) {
  if (req.raw[kMultipart] !== true) {
    next()
    return
  }

  const consumerStream = options.onFile || defaultConsumer
  const body = {}
  const mp = req.multipart((field, file, filename, encoding, mimetype) => {
    body[field] = body[field] || []
    body[field].push({
      data: [],
      filename,
      encoding,
      mimetype,
      limit: false
    })

    const result = consumerStream(field, file, filename, encoding, mimetype, body)
    if (result && typeof result.then === 'function') {
      result.catch((err) => {
        // continue with the workflow
        err.statusCode = 500
        file.destroy(err)
      })
    }
  }, function (err) {
    if (!err) {
      req.body = body
    }
    next(err)
  }, options)

  mp.on('field', (key, value) => {
    if (key === '__proto__') {
      mp.destroy(new Error('__proto__ is not allowed as field name'))
      return
    }
    if (body[key] === undefined) {
      body[key] = value
    } else if (Array.isArray(body[key])) {
      body[key].push(value)
    } else {
      body[key] = [body[key], value]
    }
  })
}


GraphViewer.processElements = function(classname)
{
	mxUtils.forEach(GraphViewer.getElementsByClassName(classname || 'mxgraph'), function(div)
	{
		try
		{
			div.innerHTML = '';
			GraphViewer.createViewerForElement(div);
		}
		catch (e)
		{
			div.innerHTML = e.message;

			if (window.console != null)
			{
				console.error(e);
			}
		}
	});
};


Server.createServer = function(cfg, listener) {
  return new Server(cfg, listener);
};


Runner.prototype.hookDown = function(name, fn){
  var suites = [this.suite].concat(this.parents());
  this.hooks(name, suites, fn);
};


  constructor (p, opt) {
    opt = opt || {}
    super(opt)
    if (typeof p !== 'string')
      throw new TypeError('path is required')
    this.path = p
    // suppress atime, ctime, uid, gid, uname, gname
    this.portable = !!opt.portable
    // until node has builtin pwnam functions, this'll have to do
    this.myuid = process.getuid && process.getuid()
    this.myuser = process.env.USER || ''
    this.maxReadSize = opt.maxReadSize || maxReadSize
    this.linkCache = opt.linkCache || new Map()
    this.statCache = opt.statCache || new Map()
    this.preservePaths = !!opt.preservePaths
    this.cwd = opt.cwd || process.cwd()
    this.strict = !!opt.strict
    this.noPax = !!opt.noPax
    this.noMtime = !!opt.noMtime
    this.mtime = opt.mtime || null

    if (typeof opt.onwarn === 'function')
      this.on('warn', opt.onwarn)

    let pathWarn = false
    if (!this.preservePaths && path.win32.isAbsolute(p)) {
      // absolutes on posix are also absolutes on win32
      // so we only need to test this one to get both
      const parsed = path.win32.parse(p)
      this.path = p.substr(parsed.root.length)
      pathWarn = parsed.root
    }

    this.win32 = !!opt.win32 || process.platform === 'win32'
    if (this.win32) {
      this.path = winchars.decode(this.path.replace(/\\/g, '/'))
      p = p.replace(/\\/g, '/')
    }

    this.absolute = opt.absolute || path.resolve(this.cwd, p)

    if (this.path === '')
      this.path = './'

    if (pathWarn) {
      this.warn('TAR_ENTRY_INFO', `stripping ${pathWarn} from absolute path`, {
        entry: this,
        path: pathWarn + this.path,
      })
    }

    if (this.statCache.has(this.absolute))
      this[ONLSTAT](this.statCache.get(this.absolute))
    else
      this[LSTAT]()
  }


            value: (add_as_favorite? 1 : 0)
        },
        function(data)
        {
            $(el).find("img").removeClass("silk-heart_add");
            $(el).find("img").removeClass("silk-heart_delete");

            if(data=="true")
            {
                if(add_as_favorite)
                {
                    $(el).parent().attr("favorite", 1);
                    $(el).find("img").addClass("silk-heart_delete");
                }
                else
                {
                    $(el).parent().attr("favorite", 0);
                    $(el).find("img").addClass("silk-heart_add");
                }
            }
            else
            {
                // show error
                navigate_notification(navigate_lang_dictionary[56]);
            }

            navigate_extensions_refresh();
        });
});


	i18n : function() {
		var self = this,
			messages = this.messages,
			input    = [],
			ignore   = [],
			message = function(m) {
				var file;
				if (m.indexOf('#') === 0) {
					if ((file = self.file(m.substr(1)))) {
						return file.name;
					}
				}
				return m;
			},
			i, j, m;

		for (i = 0; i< arguments.length; i++) {
			m = arguments[i];

			if (typeof m == 'string') {
				input.push(message(m));
			} else if ($.isArray(m)) {
				for (j = 0; j < m.length; j++) {
					if (typeof m[j] == 'string') {
						input.push(message(m[j]));
					} else if (m[j] instanceof jQuery) {
						// jQuery object is HTML element
						input.push(m[j]);
					}
				}
			} else if (m instanceof jQuery) {
				// jQuery object is HTML element
				input.push(m[j]);
			}
		}

		for (i = 0; i < input.length; i++) {
			// dont translate placeholders
			if ($.inArray(i, ignore) !== -1) {
				continue;
			}
			m = input[i];
			if (typeof m == 'string') {
				// translate message
				m = messages[m] || self.escape(m);
				// replace placeholders in message
				m = m.replace(/\$(\d+)/g, function(match, placeholder) {
					placeholder = i + parseInt(placeholder);
					if (placeholder > 0 && input[placeholder]) {
						ignore.push(placeholder)
					}
					return self.escape(input[placeholder]) || '';
				});
			} else {
				// get HTML from jQuery object
				m = m.get(0).outerHTML;
			}

			input[i] = m;
		}

		return $.map(input, function(m, i) { return $.inArray(i, ignore) === -1 ? m : null; }).join('<br>');
	},


function formcheck_Timetable_course_F4(this_DET) {
  var this_button_id = this_DET.id;

  var frmvalidator = new Validator("F4", this_button_id);

  var subject_id = document.getElementById("subject_id_div").value;
  if (subject_id == "new") {
    frmvalidator.addValidation(
      "tables[course_subjects][new][TITLE]",
      "req",
      "Please enter the subject name"
    );
    frmvalidator.addValidation(
      "tables[course_subjects][new][TITLE]",
      "maxlen=100",
      "Max length for subject is 100 characters"
    );
  } else {
    frmvalidator.addValidation(
      "inputtables[course_subjects][" + subject_id + "][TITLE]",
      "req",
      "Please enter the course title "
    );
    frmvalidator.addValidation(
      "inputtables[course_subjects][" + subject_id + "][TITLE]",
      "maxlen=100",
      "Max length for course title is 100 characters"
    );
  }
}


		isit = function(sel, match, expect) {
			equal( jQuery( sel ).is( match ), expect, "jQuery( " + sel + " ).is( " + match + " )" );
		};


    $scope.initialize = function() {
      growl.success('Retrieving definition for requisition ' + $scope.foreignSource + '...');
      RequisitionsService.getForeignSourceDefinition($scope.foreignSource).then(
        function(foreignSourceDef) { // success
          $scope.foreignSourceDef = foreignSourceDef;
          // Updating pagination variables for detectors.
          $scope.filteredDetectors = $scope.foreignSourceDef.detectors;
          $scope.updateFilteredDetectors();
          // Updating pagination variables for policies.
          $scope.filteredPolicies = $scope.foreignSourceDef.policies;
          $scope.updateFilteredPolicies();
        },
        $scope.errorHandler
      );
    };


    var iter = function(value, prefix) {
      if (!prefix) prefix = [];

      if (Array.isArray(value)) {
        value.forEach(function(arrValue, idx) {
          iter(arrValue, prefix.concat(idx));
        });
      } else if (isPlainObject(value)) {
        Object.keys(value).forEach(function(key) {
          iter(value[key], prefix.concat(key));
        });
      } else {
        entries.push({key: prefix, value: value});
      }
    };


		var getExtTemplates = function(isSearch)
		{
			list.style.display = 'none';
			searchBox.style.display = 'none';
			div.style.left = '30px';

			setActiveTab(isSearch? -1 : 1); //deselect all of them if isSearch

			if (oldTemplates == null)
			{
				oldTemplates = templates;
			}

			div.scrollTop = 0;
			div.innerHTML = '';
			spinner.spin(div);

			var callback2 = function(docList, errorMsg, searchImportCats)
			{
				i0 = 0;
				spinner.stop();
				templates = docList;
				searchImportCats = searchImportCats || {};
				var importListsCount = 0;

				for (var cat in searchImportCats)
				{
					importListsCount += searchImportCats[cat].length;
				}

				if (errorMsg)
				{
					div.innerHTML = errorMsg;
				}
				else if (docList.length == 0 && importListsCount == 0)
				{
					div.innerHTML = mxUtils.htmlEntities(mxResources.get('noDiagrams', null, 'No Diagrams Found'));
				}
				else
				{
					div.innerHTML = '';

					if (importListsCount > 0)
					{
						list.style.display = '';
						div.style.left = '160px';
						list.innerHTML = '';

						customCatCount = 0;
						categories = {'draw.io': docList};

						for (var cat in searchImportCats)
						{
							categories[cat] = searchImportCats[cat];
						}

						initUi();
					}
					else
					{
						addTemplates(true);
					}
				}
			}

			if (isSearch)
			{
				searchDocsCallback(searchInput.value, callback2);
			}
			else
			{
				recentDocsCallback(callback2);
			}
		}


Suite.prototype.afterEach = function(fn){
  if (this.pending) return this;
  var hook = new Hook('"after each" hook', fn);
  hook.parent = this;
  hook.timeout(this.timeout());
  hook.slow(this.slow());
  hook.ctx = this.ctx;
  this._afterEach.push(hook);
  this.emit('afterEach', hook);
  return this;
};


  getStringValue: function(item) {
    this.assign(item, 'getStringValue(' + item + ')');
  },


function escapeShellArg(arg) {
  return arg.replace(/"/g, `""`);
}


function assignableAST(ast) {
  if (ast.body.length === 1 && isAssignable(ast.body[0].expression)) {
    return {type: AST.AssignmentExpression, left: ast.body[0].expression, right: {type: AST.NGValueParameter}, operator: '='};
  }
}


MyFilters.prototype._load_default_subscriptions = function() {
  var result = {};
  // Returns the ID of the list appropriate for the user's locale, or ''
  function listIdForThisLocale() {
    var language = determineUserLanguage();
    switch(language) {
      case 'bg': return 'easylist_plus_bulgarian';
      case 'cs': return 'czech';
      case 'cu': return 'easylist_plus_bulgarian';
      case 'da': return 'danish';
      case 'de': return 'easylist_plus_german';
      case 'el': return 'easylist_plus_greek';
      case 'fi': return 'easylist_plus_finnish';
      case 'fr': return 'easylist_plus_french';
      case 'he': return 'israeli';
      case 'hu': return 'hungarian';
      case 'it': return 'italian';
      case 'id': return 'easylist_plus_indonesian';
      case 'ja': return 'japanese';
      case 'ko': return 'easylist_plun_korean';
      case 'lv': return 'latvian';
      case 'nl': return 'dutch';
      case 'no': return 'norwegian';
      case 'pl': return 'easylist_plus_polish';
      case 'ro': return 'easylist_plus_romanian';
      case 'ru': return 'russian';
      case 'sk': return 'czech';
      case 'sv': return 'swedish';
      case 'tr': return 'turkish';
      case 'uk': return 'russian';
      case 'zh': return 'chinese';
      default: return '';
    }
  }
  //Update will be done immediately after this function returns
  result["adblock_custom"] = { subscribed: true };
  result["easylist"] = { subscribed: true };
  var list_for_lang = listIdForThisLocale();
  if (list_for_lang)
    result[list_for_lang] = { subscribed: true };
  return result;
}


function reqPty(chan, opts, cb) {
  var rows = 24;
  var cols = 80;
  var width = 640;
  var height = 480;
  var term = 'vt100';
  var modes = null;

  if (typeof opts === 'function')
    cb = opts;
  else if (typeof opts === 'object' && opts !== null) {
    if (typeof opts.rows === 'number')
      rows = opts.rows;
    if (typeof opts.cols === 'number')
      cols = opts.cols;
    if (typeof opts.width === 'number')
      width = opts.width;
    if (typeof opts.height === 'number')
      height = opts.height;
    if (typeof opts.term === 'string')
      term = opts.term;
    if (typeof opts.modes === 'object')
      modes = opts.modes;
  }

  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 a pseudo-terminal'));
      }
      cb();
    });
  }

  return chan._client._sshstream.pty(chan.outgoing.id,
                                     rows,
                                     cols,
                                     height,
                                     width,
                                     term,
                                     modes,
                                     wantReply);
}


export function esc(value) {
	if (typeof value !== 'string') return value;
	let last=ESCAPE.lastIndex=0, tmp=0, out='';
	while (ESCAPE.test(value)) {
		tmp = ESCAPE.lastIndex - 1;
		out += value.substring(last, tmp) + CHARS[value[tmp]];
		last = tmp + 1;
	}
	return out + value.substring(last);
}


    $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
          );
        }
      });
    };


	wp.updates.requestForCredentialsModalClose = function() {
		$( '#request-filesystem-credentials-dialog' ).hide();
		$( 'body' ).removeClass( 'modal-open' );
		wp.updates.$elToReturnFocusToFromCredentialsModal.focus();
	};


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]}


            value = value.replace(/src=" *javascript\:(.*?)"/gi, function(m, $1) {
                return 'removed=""';
            });


        click: function(p,o) {
            p.on(o.event, o.children, function(e){
                if(f.detect.leftMouse(e)) {
                    if ($(e.target).hasClass('ch-toggle') ||
                        $(e.target).hasClass('check-label') ||
                        ( $(e.target).hasClass('l-unit-toolbar__col--left')) ) {

                        var c = f.get.clicks(p,o,$(this));

                        var ref = $(e.target);
                        if (ref.parents('.l-unit').hasClass('selected') && $('.l-unit.selected').length == 1) {
                            ref.parents('.l-unit').find('.ch-toggle').attr('checked', false);
                            ref.parents('.l-unit').removeClass('selected');
                            ref.parents('.l-unit').removeClass('selected-current');
                            $('.toggle-all').removeClass('clicked-on');
                            return;
                        }

                        if (!(f.detect.ctrl(e) && o.enableCtrlClick) && (f.detect.shift(e) && o.enableShiftClick)) {
                            f.t.deleteSelection(o);
                            f.t.shiftClick(p,c,o);
                        }

                        if (((f.detect.ctrl(e) && o.enableCtrlClick) || (f.detect.touch() && o.enableTouchCtrlDefault) || o.enableDesktopCtrlDefault) && !(f.detect.shift(e) && o.enableShiftClick)) {
                            f.t.toggleClick(p,c,o);
                        }

                        if (!(f.detect.ctrl(e) && o.enableCtrlClick) && !(f.detect.shift(e) && o.enableShiftClick) && o.enableSingleClick && !o.enableDesktopCtrlDefault) {
                            f.t.singleClick(p,c,o);
                        }
                    }
                }

                o.onFinish(e);
            });
        },


labels: templateInstance.topTasks.get().map((task) => task._id),


module.exports = function correctMkdir (path, cb) {
  cb = dezalgo(cb)
  cb = inflight('correctMkdir:' + path, cb)
  if (!cb) {
    return log.silly('correctMkdir', path, 'correctMkdir already in flight; waiting')
  } else {
    log.silly('correctMkdir', path, 'correctMkdir not in flight; initializing')
  }
  var stats = {}

  if (stats[path]) return cb(null, stats[path])

  fs.stat(path, function (er, st) {
    if (er) return makeDirectory(path, stats, cb)

    if (!st.isDirectory()) {
      log.error('correctMkdir', 'invalid dir %s', path)
      return cb(er)
    }

    var ownerStats = calculateOwner()
    // there's always a chance the permissions could have been frobbed, so fix
    if (st.uid !== ownerStats.uid) {
      stats[path] = ownerStats
      setPermissions(path, ownerStats, cb)
    } else {
      stats[path] = st
      cb(null, stats[path])
    }
  })
}


	this.getUI = function(ui) {
		return this.ui[ui] || node;
	}


                formatItem: function(data) {
                    var s = data[options.nameKey];

                    if (options.descKey) {
                        s += " <span>(" + data[options.descKey] + ")</span>";
                    }

                    return s;
                },


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


var manualLowercase = function(s) {
  /* eslint-disable no-bitwise */
  return isString(s)
      ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
      : s;
  /* eslint-enable */
};


    $scope.clone = function(foreignSource) {
      var availableForeignSources = [];
      angular.forEach($scope.requisitionsData.requisitions, function(r) {
        if (r.foreignSource !== foreignSource) {
          availableForeignSources.push(r.foreignSource);
        }
      });
      var modalInstance = $uibModal.open({
        backdrop: 'static',
        keyboard: false,
        controller: 'CloneForeignSourceController',
        templateUrl: cloneForeignsourceView,
        resolve: {
          foreignSource: function() { return foreignSource; },
          availableForeignSources: function() { return availableForeignSources; }
        }
      });
      modalInstance.result.then(function(targetForeignSource) {
        bootbox.confirm('This action will override the existing foreign source definition for the requisition named ' + targetForeignSource + ', using ' + foreignSource + ' as a template. Are you sure you want to continue ? This cannot be undone.', function(ok) {
          if (!ok) {
            return;
          }
          RequisitionsService.startTiming();
          RequisitionsService.cloneForeignSourceDefinition(foreignSource, targetForeignSource).then(
            function() { // success
              growl.success('The foreign source definition for ' + foreignSource + ' has been cloned to ' + targetForeignSource);
            },
            $scope.errorHandler
          );
        });
      });
    };


                    let errHandler = function(err) {
                        callback(err);
                    };


function set_utilization(type, entity_id, name, value) {
  var data = {
    name: name,
    value: value
  };
  if (type == "node") {
    data["node"] = entity_id;
  } else if (type == "resource") {
    data["resource_id"] = entity_id;
  } else return false;
  var url = get_cluster_remote_url() + "set_" + type + "_utilization";

  $.ajax({
    type: 'POST',
    url: url,
    data: data,
    timeout: pcs_timeout,
    error: function (xhr, status, error) {
      alert(
        "Unable to set utilization: "
        + ajax_simple_error(xhr, status, error)
      );
    },
    complete: function() {
      Pcs.update();
    }
  });
}


                        oauth2: new XOAuth2({
                            user: 'testuser',
                            clientId: '{Client ID}',
                            clientSecret: '{Client Secret}',
                            refreshToken: 'refresh-token',
                            accessToken: 'uuuuu',
                            accessUrl: 'http://localhost:' + XOAUTH_PORT
                        })
                    },
                    function(err) {
                        expect(err).to.not.exist;
                        expect(client.authenticated).to.be.true;
                        done();
                    }
                );
            });


    $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 ?
        }
      });
    };


function concat(array1, array2, index) {
  return array1.concat(slice.call(array2, index));
}


function next() {
  if (++f < files.length) {
    spawn(process.argv[0], [ files[f] ], { stdio: 'inherit' })
      .on('exit', function(code) {
        if (code === 0)
          process.nextTick(next);
        else
          process.exit(code);
      });
  }
}


Context.prototype.inspect = function(){
  return JSON.stringify(this, function(key, val){
    if ('_runnable' == key) return;
    if ('test' == key) return;
    return val;
  }, 2);
};


export function isOriginPotentiallyTrustworthy(url) {
	// 1. If origin is an opaque origin, return "Not Trustworthy".
	// Not applicable

	// 2. Assert: origin is a tuple origin.
	// Not for implementations

	// 3. If origin's scheme is either "https" or "wss", return "Potentially Trustworthy".
	if (/^(http|ws)s:$/.test(url.protocol)) {
		return true;
	}

	// 4. If origin's host component matches one of the CIDR notations 127.0.0.0/8 or ::1/128 [RFC4632], return "Potentially Trustworthy".
	const hostIp = url.host.replace(/(^\[)|(]$)/g, '');
	const hostIPVersion = isIP(hostIp);

	if (hostIPVersion === 4 && /^127\./.test(hostIp)) {
		return true;
	}

	if (hostIPVersion === 6 && /^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(hostIp)) {
		return true;
	}

	// 5. If origin's host component is "localhost" or falls within ".localhost", and the user agent conforms to the name resolution rules in [let-localhost-be-localhost], return "Potentially Trustworthy".
	// We are returning FALSE here because we cannot ensure conformance to
	// let-localhost-be-loalhost (https://tools.ietf.org/html/draft-west-let-localhost-be-localhost)
	if (/^(.+\.)*localhost$/.test(url.host)) {
		return false;
	}

	// 6. If origin's scheme component is file, return "Potentially Trustworthy".
	if (url.protocol === 'file:') {
		return true;
	}

	// 7. If origin's scheme component is one which the user agent considers to be authenticated, return "Potentially Trustworthy".
	// Not supported

	// 8. If origin has been configured as a trustworthy origin, return "Potentially Trustworthy".
	// Not supported

	// 9. Return "Not Trustworthy".
	return false;
}


					slug: $( this ).data( 'slug' )
				}
			};

			target.postMessage( JSON.stringify( job ), window.location.origin );
		});


function setHashKey(obj, h) {
  if (h) {
    obj.$$hashKey = h;
  } else {
    delete obj.$$hashKey;
  }
}