      caret: this.editor.undoManager.caretPosition()
    };
    this._pasteBin.focus();
    return setTimeout((function(_this) {
      return function() {
        var pasteContent;
        _this.editor.hidePopover();
        _this.editor.body.get(0).innerHTML = state.html;
        _this.editor.undoManager.caretPosition(state.caret);
        _this.editor.body.focus();
        _this.editor.selection.reset();
        _this.editor.selection.range();
        _this._pasteInBlockEl = _this.editor.selection.blockNodes().last();
        _this._pastePlainText = _this.opts.cleanPaste || _this._pasteInBlockEl.is('pre, table');
        if (_this._pastePlainText) {
          pasteContent = _this.editor.formatter.clearHtml(_this._pasteBin.html(), true);
        } else {
          pasteContent = $('<div/>').append(_this._pasteBin.contents());
          pasteContent.find('style').remove();
          pasteContent.find('table colgroup').remove();
          _this._cleanPasteFontSize(pasteContent);
          _this.editor.formatter.format(pasteContent);
          _this.editor.formatter.decorate(pasteContent);
          _this.editor.formatter.beautify(pasteContent.children());
          pasteContent = pasteContent.contents();
        }
        _this._pasteBin.remove();
        _this._pasteBin = null;
        return callback(pasteContent);
      };
    })(this), 0);
  };


    toMathML: function (space,jax) {
      var annotation;
      if (space == null) {space = ""}
      if (jax && jax.originalText && SETTINGS.semantics)
        {annotation = MathJax.InputJax[jax.inputJax].annotationEncoding}
      var nested = (this.data[0] && this.data[0].data.length > 1);
      var tag = this.type, attr = this.toMathMLattributes();
      var data = [], SPACE = space + (annotation ? "  " + (nested ? "  " : "") : "") + "  ";
      for (var i = 0, m = this.data.length; i < m; i++) {
        if (this.data[i]) {data.push(this.data[i].toMathML(SPACE))}
          else {data.push(SPACE+"<mrow />")}
      }
      if (data.length === 0 || (data.length === 1 && data[0] === "")) {
        if (!annotation) {return "<"+tag+attr+" />"}
        data.push(SPACE+"<mrow />");
      }
      if (annotation) {
        if (nested) {data.unshift(space+"    <mrow>"); data.push(space+"    </mrow>")}
        data.unshift(space+"  <semantics>");
        var xmlEscapedTex = jax.originalText.replace(/[&<>]/g, function(item) {
            return { '>': '>', '<': '<','&': '&' }[item]
        });
        data.push(space+'    <annotation encoding="'+annotation+'">'+xmlEscapedTex+"</annotation>");
        data.push(space+"  </semantics>");
      }
      return space+"<"+tag+attr+">\n"+data.join("\n")+"\n"+space+"</"+tag+">";
    }


internals.Traceroute.trace = function (host, callback) {

    Dns.lookup(host.toUpperCase(), (err) => {

        if (err && Net.isIP(host) === 0) {
            return callback(new Error('Invalid host'));
        }

        const command = (internals.isWin ? 'tracert -d ' : 'traceroute -q 1 -n ') + host;
        Child.exec(command, (err, stdout, stderr) => {

            if (err) {
                return callback(err);
            }

            const results = internals.parseOutput(stdout);
            return callback(null, results);
        });
    });
};


function stat(dir, files, cb) {
  var batch = new Batch();

  batch.concurrency(10);

  files.forEach(function(file, i){
    batch.push(function(done){
      fs.stat(join(dir, file), done);
    });
  });

  batch.end(cb);
}


function htmlPath(dir) {
  var curr = [];
  return dir.split('/').map(function(part){
    curr.push(encodeURIComponent(part));
    return part ? '' + part + '' : '';
  }).join(' / ');
}


app.striptags = function(inp){
  return ('' + inp)
    .replace(/<[^>]+?>.*?<\/[^>]+?>/g, '') //Closed Tags
    .replace(/<[^>]+?\/\s*>/g, '') //Self-Closing Tags
    .replace(/<[^>]+?>/g, ''); //Unclosed Tags
};


    main.unsubscribeObjects = function (patterns) {
        if (!patterns) return;
        if (typeof patterns === 'object') {
            for (var s = 0; s < patterns.length; s++) {
                if (main.subscribesObjects[patterns[s]]) {
                    main.subscribesObjects[patterns[s]]--;
                }
                if (main.subscribesObjects[patterns[s]] === 0) {
                    main.socket.emit('unsubscribeObjects', patterns[s]);
                    delete main.subscribesObjects[patterns[s]];
                }
            }
        } else {
            if (main.subscribesObjects[patterns]) {
                main.subscribesObjects[patterns]--;
            }
            if (main.subscribesObjects[patterns] === 0) {
                main.socket.emit('unsubscribeObjects', patterns);
                delete main.subscribesObjects[patterns];
            }
        }
    };


    main.subscribeObjects = function (patterns) {
        if (!patterns) return;
        if (typeof patterns === 'object') {
            for (var s = 0; s < patterns.length; s++) {
                main.subscribesObjects[patterns[s]] = main.subscribesObjects[patterns[s]] || 0;
                main.subscribesObjects[patterns[s]]++;
                if (main.subscribesObjects[patterns[s]] === 1) {
                    main.socket.emit('subscribeObjects', patterns[s]);
                }
            }
        } else {
            main.subscribesObjects[patterns] = main.subscribesObjects[patterns] || 0;
            main.subscribesObjects[patterns]++;
            if (main.subscribesObjects[patterns] === 1) {
                main.socket.emit('subscribeObjects', patterns);
            }
        }
    };


        getUser:        function () {
            if (!main.currentUser) {
                main.socket.emit('authEnabled', function (auth, user) {
                    main.currentUser = 'system.user.' + user;
                    if (!auth) {
                        $('#button-logout').remove();
                    } else {
                        main._lastTimer = (new Date()).getTime();
                        monitor();
                    }
                });
            } else if (main.objects[main.currentUser]) {
                var obj = main.objects[main.currentUser];
                var name = '';
                if (!obj || !obj.common || !obj.common.name) {
                    name = main.currentUser.replace(/^system\.user\./);
                    name = name[0].toUpperCase() + name.substring(1).toLowerCase();
                } else {
                    name = translateName(obj.common.name);
                }
                if (obj && obj.common && obj.common.icon) {
                    var objs = {};
                    objs[main.currentUser] = obj;
                    $('#current-user-icon').html(main.getIcon(main.currentUser, null, objs));
                } else {
                    $('#current-user-icon').html('<i class="large material-icons">account_circle</i>');
                }
                $('#current-user').html(name);
                var groups = [];
                for (var i = 0; i < tabs.users.groups.length; i++) {
                    var group = main.objects[tabs.users.groups[i]];
                    if (group && group.common && group.common.members && group.common.members.indexOf(main.currentUser) !== -1) {
                        groups.push(_(translateName(group.common.name)));
                    }
                }
                $('#current-group').html(groups.join(', '));
            }
        },


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

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


    main.resubscribeStates = function () {
        for (var pattern in main.subscribesStates) {
            if (main.subscribesStates.hasOwnProperty(pattern) && main.subscribesStates[pattern]) {
                console.debug('Re-Subscribe: ' + pattern);
                main.socket.emit('subscribe', pattern);
            }
        }
    };


    function getVersionClass(version) {
        if (version) {
            var tmp = version.split ('.');
            if (tmp[0] === '0' && tmp[1] === '0' && tmp[2] === '0') {
                version = 'planned';
            } else if (tmp[0] === '0' && tmp[1] === '0') {
                version = 'alpha';
            } else if (tmp[0] === '0') {
                version = 'beta'
            } else if (version === 'npm error') {
                version = 'error';
            } else {
                version = 'stable';
            }
        }
        return version;
    }


DotObject.prototype.transfer = function (source, target, obj1, obj2, mods, merge) {
  if (typeof mods === 'function' || Array.isArray(mods)) {
    this.set(target,
      _process(
        this.pick(source, obj1, true),
        mods
      ), obj2, merge)
  } else {
    merge = mods
    this.set(target, this.pick(source, obj1, true), obj2, merge)
  }

  return obj2
}


DotObject.prototype.transform = function (recipe, obj, tgt) {
  obj = obj || {}
  tgt = tgt || {}
  Object.keys(recipe).forEach(function (key) {
    this.set(recipe[key], this.pick(key, obj), tgt)
  }.bind(this))
  return tgt
}


DotObject.prototype.set = function (path, val, obj, merge) {
  var i
  var k
  var keys
  var key

  // Do not operate if the value is undefined.
  if (typeof val === 'undefined') {
    return obj
  }
  keys = parsePath(path, this.separator)

  for (i = 0; i < keys.length; i++) {
    key = keys[i]
    if (i === (keys.length - 1)) {
      if (merge && isObject(val) && isObject(obj[key])) {
        for (k in val) {
          if (hasOwnProperty.call(val, k)) {
            obj[key][k] = val[k]
          }
        }
      } else if (merge && Array.isArray(obj[key]) && Array.isArray(val)) {
        for (var j = 0; j < val.length; j++) {
          obj[keys[i]].push(val[j])
        }
      } else {
        obj[key] = val
      }
    } else if (
      // force the value to be an object
      !hasOwnProperty.call(obj, key) ||
      (!isObject(obj[key]) && !Array.isArray(obj[key]))
    ) {
      // initialize as array if next key is numeric
      if (/^\d+$/.test(keys[i + 1])) {
        obj[key] = []
      } else {
        obj[key] = {}
      }
    }
    obj = obj[key]
  }
  return obj
}


DotObject.prototype.pick = function (path, obj, remove, reindexArray) {
  var i
  var keys
  var val
  var key
  var cp

  keys = parsePath(path, this.separator)
  for (i = 0; i < keys.length; i++) {
    key = parseKey(keys[i], obj)
    if (obj && typeof obj === 'object' && key in obj) {
      if (i === (keys.length - 1)) {
        if (remove) {
          val = obj[key]
          if (reindexArray && Array.isArray(obj)) {
            obj.splice(key, 1)
          } else {
            delete obj[key]
          }
          if (Array.isArray(obj)) {
            cp = keys.slice(0, -1).join('.')
            if (this.cleanup.indexOf(cp) === -1) {
              this.cleanup.push(cp)
            }
          }
          return val
        } else {
          return obj[key]
        }
      } else {
        obj = obj[key]
      }
    } else {
      return undefined
    }
  }
  if (remove && Array.isArray(obj)) {
    obj = obj.filter(function (n) { return n !== undefined })
  }
  return obj
}


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

            this.userId = data.userId;

            this.messageData['entityType'] = Espo.Utils.upperCaseFirst((this.translate(data.entityType, 'scopeNames') || '').toLowerCase());
            if (data.personEntityId) {
                this.messageData['from'] = '' + data.personEntityName + '';
            } else {
                this.messageData['from'] = data.fromString || this.translate('empty address');
            }

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

            this.createMessage();
        }


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

            this.userId = data.userId;

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

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

            this.createMessage();
        }


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

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

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

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

            this.createMessage();
        },


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

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

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

                var isYou = false;
                if (this.isUserStream) {
                    if (this.assignedUserId == this.getUser().id) {
                        isYou = true;
                    }
                }

                if (this.assignedUserId) {
                    this.messageName = 'createAssigned';

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

                        if (this.assignedUserId == this.model.get('createdById')) {
                            this.messageName += 'Self';
                        }
                    } else {
                        if (this.assignedUserId == this.model.get('createdById')) {
                            this.messageName += 'Self';
                        } else {
                            if (isYou) {
                                this.messageName += 'You';
                            }
                        }
                    }
                }

                if (data.statusField) {
                    var statusField = this.statusField = data.statusField;
                    var statusValue = data.statusValue;
                    this.statusStyle = data.statusStyle || 'default';
                    this.statusText = this.getLanguage().translateOption(statusValue, statusField, this.model.get('parentType'));
                }
            }

            this.createMessage();
        },


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

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

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

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

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

            this.messageName = 'emailReceived';

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

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

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

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

            this.createMessage();
        },

    });
});


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

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

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

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

            this.messageName = 'emailSent';

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

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

            this.createMessage();
        },


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

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

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

            this.createMessage();
        },


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


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


getItemHtml: function (value) {
            var translatedValue = this.translatedOptions[value] || value;

            var html = '' +
            '
' +
                '
' +
                    '<input data-name="translatedValue" data-value="' + value + '" class="role form-control input-sm" value="'+translatedValue+'">' +
                '
' +
                '
' +
                    '' +
                '

' +
            '
';

            return html;
        },


function usercheck_init_student(i) {
    var obj = document.getElementById('ajax_output_st');
    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;
    }
    ajax_call('Validator.php?u=' + i.value + 'stud', usercheck_callback_student, usercheck_error_student);
}


function deleteClient() {
  var tr = $(this).closest("tr");
  var id = tr.attr("data-id");
  var ip = tr.find("#ip_" + id).text();
  var name = utils.escapeHtml(tr.find("#name_" + id).text());

  if (name.length > 0) {
    ip += " (" + name + ")";
  }

  utils.disableAll();
  utils.showAlert("info", "", "Deleting client...", ip);
  $.ajax({
    url: "scripts/pi-hole/php/groups.php",
    method: "post",
    dataType: "json",
    data: { action: "delete_client", id: id, token: token },
    success: function (response) {
      utils.enableAll();
      if (response.success) {
        utils.showAlert("success", "far fa-trash-alt", "Successfully deleted client ", ip);
        table.row(tr).remove().draw(false).ajax.reload(null, false);
        reloadClientSuggestions();
      } else {
        utils.showAlert("error", "", "Error while deleting client with ID " + id, response.message);
      }
    },
    error: function (jqXHR, exception) {
      utils.enableAll();
      utils.showAlert("error", "", "Error while deleting client with ID " + id, jqXHR.responseText);
      console.log(exception); // eslint-disable-line no-console
    },
  });
}


function openExternalLink(link) {
    let u;

    try {
        u = url.parse(link);
    } catch (e) {
        return;
    }

    if (protocolRegex.test(u.protocol)) {
        shell.openExternal(link);
    }
}


function dockerContainerStats(containerIDs, callback) {

  let containerArray = [];
  // fallback - if only callback is given
  if (util.isFunction(containerIDs) && !callback) {
    callback = containerIDs;
    containerArray = ['*'];
  } else {
    containerIDs = containerIDs || '*';
    containerIDs = containerIDs.trim().toLowerCase().replace(/,+/g, '|');
    containerArray = containerIDs.split('|');
  }

  return new Promise((resolve) => {
    process.nextTick(() => {

      const result = [];

      const workload = [];
      if (containerArray.length && containerArray[0].trim() === '*') {
        containerArray = [];
        dockerContainers().then(allContainers => {
          for (let container of allContainers) {
            containerArray.push(container.id);
          }
          dockerContainerStats(containerArray.join(',')).then(result => {
            if (callback) { callback(result); }
            resolve(result);
          });
        });
      } else {
        for (let containerID of containerArray) {
          workload.push(dockerContainerStatsSingle(containerID.trim()));
        }
        if (workload.length) {
          Promise.all(
            workload
          ).then(data => {
            if (callback) { callback(data); }
            resolve(data);
          });
        } else {
          if (callback) { callback(result); }
          resolve(result);
        }
      }
    });
  });
}


function ServerStderr(channel) {
  WritableStream.call(this, { highWaterMark: MAX_WINDOW });
  this._channel = channel;
}


function reqExec(chan, cmd, opts, 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 exec'));
    }
    chan.subtype = 'exec';
    chan.allowHalfOpen = (opts.allowHalfOpen !== false);
    cb(undefined, chan);
  });

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


      function onExit(code, signal) {
        sftp.removeListener('ready', onReady);
        sftp.removeListener('error', onError);
        var msg;
        if (typeof code === 'number') {
          msg = 'Received exit code '
                + code
                + ' while establishing SFTP session';
        } else {
          msg = 'Received signal '
                + signal
                + ' while establishing SFTP session';
        }
        var err = new Error(msg);
        err.code = code;
        err.signal = signal;
        cb(err);
      }


  var extraOpts = { allowHalfOpen: (opts.allowHalfOpen !== false) };

  return openChannel(this, 'session', extraOpts, function(err, chan) {
    if (err)
      return cb(err);

    var todo = [];

    function reqCb(err) {
      if (err) {
        chan.close();
        return cb(err);
      }
      if (todo.length)
        todo.shift()();
    }

    if (self.config.allowAgentFwd === true
        || (opts
            && opts.agentForward === true
            && self.config.agent !== undefined)) {
      todo.push(function() {
        reqAgentFwd(chan, reqCb);
      });
    }

    if (typeof opts === 'object' && opts !== null) {
      if (typeof opts.env === 'object' && opts.env !== null)
        reqEnv(chan, opts.env);
      if ((typeof opts.pty === 'object' && opts.pty !== null)
          || opts.pty === true) {
        todo.push(function() { reqPty(chan, opts.pty, reqCb); });
      }
      if ((typeof opts.x11 === 'object' && opts.x11 !== null)
          || opts.x11 === 'number'
          || opts.x11 === true) {
        todo.push(function() { reqX11(chan, opts.x11, reqCb); });
      }
    }

    todo.push(function() { reqExec(chan, cmd, opts, cb); });
    todo.shift()();
  });
};


  function accept() {
    var chaninfo = {
      type: info.type,
      incoming: {
        id: localChan,
        window: Channel.MAX_WINDOW,
        packetSize: Channel.PACKET_SIZE,
        state: 'open'
      },
      outgoing: {
        id: info.sender,
        window: info.window,
        packetSize: info.packetSize,
        state: 'open'
      }
    };
    var stream = new Channel(chaninfo, self);

    self._sshstream.channelOpenConfirm(info.sender,
                                       localChan,
                                       Channel.MAX_WINDOW,
                                       Channel.PACKET_SIZE);
    return stream;
  }


    function doConnect() {
      startTimeout();
      self._sock.connect({
        host: host,
        port: self.config.port,
        localAddress: self.config.localAddress,
        localPort: self.config.localPort
      });
      self._sock.setNoDelay(true);
      self._sock.setMaxListeners(0);
      self._sock.setTimeout(typeof cfg.timeout === 'number' ? cfg.timeout : 0);
    }


  this._cbfinal = function(allowed, methodsLeft, isPartial) {
    if (!self._finalResponse) {
      self._finalResponse = true;
      cb(self, allowed, methodsLeft, isPartial);
    }
  };


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


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


        accept = function(chosenPort) {
          if (replied)
            return;
          replied = true;
          var bufPort;
          if (name === 'tcpip-forward'
              && data.bindPort === 0
              && typeof chosenPort === 'number') {
            bufPort = Buffer.allocUnsafe(4);
            writeUInt32BE(bufPort, chosenPort, 0);
          }
          setReply('SUCCESS', bufPort);
        };


  throwError: function(msg, token) {
    throw $parseMinErr('syntax',
        'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
          token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
  },


  parse: function(text) {
    return this.astCompiler.compile(text);
  }


  peek: function(i) {
    var num = i || 1;
    return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
  },


function merge(dst) {
  return baseExtend(dst, slice.call(arguments, 1), true);
}


  assign: function(id, value) {
    if (!id) return;
    this.current().body.push(id, '=', value, ';');
    return id;
  },


  'binary+': function(left, right, context) {
    return function(scope, locals, assign, inputs) {
      var lhs = left(scope, locals, assign, inputs);
      var rhs = right(scope, locals, assign, inputs);
      var arg = plusFn(lhs, rhs);
      return context ? {value: arg} : arg;
    };
  },


  member: function(left, right, computed) {
    if (computed) return this.computedMember(left, right);
    return this.nonComputedMember(left, right);
  },


  stringEscapeFn: function(c) {
    return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);
  },


function baseExtend(dst, objs, deep) {
  var h = dst.$$hashKey;

  for (var i = 0, ii = objs.length; i < ii; ++i) {
    var obj = objs[i];
    if (!isObject(obj) && !isFunction(obj)) continue;
    var keys = Object.keys(obj);
    for (var j = 0, jj = keys.length; j < jj; j++) {
      var key = keys[j];
      var src = obj[key];

      if (deep && isObject(src)) {
        if (isDate(src)) {
          dst[key] = new Date(src.valueOf());
        } else if (isRegExp(src)) {
          dst[key] = new RegExp(src);
        } else if (src.nodeName) {
          dst[key] = src.cloneNode(true);
        } else if (isElement(src)) {
          dst[key] = src.clone();
        } else {
          if (!isObject(dst[key])) dst[key] = isArray(src) ? [] : {};
          baseExtend(dst[key], [src], true);
        }
      } else {
        dst[key] = src;
      }
    }
  }

  setHashKey(dst, h);
  return dst;
}


  angular.resumeBootstrap = function(extraModules) {
    forEach(extraModules, function(module) {
      modules.push(module);
    });
    return doBootstrap();
  };


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


  nonComputedMember: function(left, right) {
    var SAFE_IDENTIFIER = /^[$_a-zA-Z][$_a-zA-Z0-9]*$/;
    var UNSAFE_CHARACTERS = /[^$_a-zA-Z0-9]/g;
    if (SAFE_IDENTIFIER.test(right)) {
      return left + '.' + right;
    } else {
      return left  + '["' + right.replace(UNSAFE_CHARACTERS, this.stringEscapeFn) + '"]';
    }
  },


    function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
      var unwatch, lastValue;
      if (parsedExpression.inputs) {
        unwatch = inputsWatchDelegate(scope, oneTimeListener, objectEquality, parsedExpression, prettyPrintExpression);
      } else {
        unwatch = scope.$watch(oneTimeWatch, oneTimeListener, objectEquality);
      }
      return unwatch;

      function oneTimeWatch(scope) {
        return parsedExpression(scope);
      }
      function oneTimeListener(value, old, scope) {
        lastValue = value;
        if (isFunction(listener)) {
          listener(value, old, scope);
        }
        if (isDefined(value)) {
          scope.$$postDigest(function() {
            if (isDefined(lastValue)) {
              unwatch();
            }
          });
        }
      }
    }


function isRegExp(value) {
  return toString.call(value) === '[object RegExp]';
}


  peekAhead: function(i, e1, e2, e3, e4) {
    if (this.tokens.length > i) {
      var token = this.tokens[i];
      var t = token.text;
      if (t === e1 || t === e2 || t === e3 || t === e4 ||
          (!e1 && !e2 && !e3 && !e4)) {
        return token;
      }
    }
    return false;
  },


var set = function set(obj, path, val) {
  var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
  var internalPath = path,
      objPart;
  options = _objectSpread({
    "transformRead": returnWhatWasGiven,
    "transformKey": returnWhatWasGiven,
    "transformWrite": returnWhatWasGiven
  }, options); // No object data

  if (obj === undefined || obj === null) {
    return;
  } // No path string

  if (!internalPath) {
    return;
  }

  internalPath = clean(internalPath); // Path is not a string, throw error

  if (typeof internalPath !== "string") {
    throw new Error("Path argument must be a string");
  }

  if ((0, _typeof2["default"])(obj) !== "object") {
    return;
  } // Path has no dot-notation, set key/value

  if (isNonCompositePath(internalPath)) {
    obj = decouple(obj, options);
    obj[options.transformKey(unEscape(internalPath))] = val;
    return obj;
  }

  var newObj = decouple(obj, options);
  var pathParts = split(internalPath);
  var pathPart = pathParts.shift();
  var transformedPathPart = options.transformKey(pathPart);
  var childPart = newObj[transformedPathPart];

  if ((0, _typeof2["default"])(childPart) !== "object") {
    // Create an object or array on the path
    if (String(parseInt(transformedPathPart, 10)) === transformedPathPart) {
      // This is an array index
      newObj[transformedPathPart] = [];
    } else {
      newObj[transformedPathPart] = {};
    }

    objPart = newObj[transformedPathPart];
  } else {
    objPart = childPart;
  }

  return set(newObj, transformedPathPart, set(objPart, pathParts.join('.'), val, options), options);
};


                    .substr(0, line.indexOf(':'))
                    .trim()
                    .toLowerCase(),
                line
            }));


function proxyConnect(port, host, destinationPort, destinationHost, callback) {
    let socket = net.connect(port, host, function() {
        socket.write('CONNECT ' + destinationHost + ':' + destinationPort + ' HTTP/1.1\r\n\r\n');

        let headers = '';
        let onSocketData = function(chunk) {
            let match;
            let remainder;

            headers += chunk.toString('binary');
            if ((match = headers.match(/\r\n\r\n/))) {
                socket.removeListener('data', onSocketData);
                remainder = headers.substr(match.index + match[0].length);
                headers = headers.substr(0, match.index);
                if (remainder) {
                    socket.unshift(Buffer.from(remainder, 'binary'));
                }
                // proxy connection is now established
                return callback(null, socket);
            }
        };
        socket.on('data', onSocketData);
    });

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


                    onUpdate: function(username, accessToken) {
                        testtoken = accessToken;
                    }.bind(this)


                onMailFrom: function(address, session, callback) {
                    if (address.args && parseInt(address.args.SIZE, 10) > 50 * 1024) {
                        return callback(new Error('452 Insufficient channel storage: ' + address.address));
                    }

                    if (!/@valid.sender/.test(address.address)) {
                        return callback(new Error('Only user@valid.sender is allowed to send mail'));
                    }

                    if (address.args.SMTPUTF8) {
                        session.smtpUtf8 = true;
                    }

                    if (address.args.BODY === '8BITMIME') {
                        session.use8BitMime = true;
                    }

                    if (/[\x80-\uFFFF]/.test(address.address) && !session.smtpUtf8) {
                        return callback(new Error('Trying to use Unicode address without declaring SMTPUTF8 first'));
                    }

                    return callback(); // Accept the address
                },


module.exports = function(options) {
    return new OAuthServer(options);
};


        function sendMessage(callback) {
            pool.send(
                {
                    data: {},
                    message: new MockBuilder(
                        {
                            from: 'test@valid.sender',
                            to: 'test@valid.recipient'
                        },
                        message
                    )
                },
                function(err) {
                    expect(err).to.not.exist;
                    callback();
                }
            );
        }

        let total = 100;
        let returned = 0;
        let cb = function() {
            let sent = 0;

            if (++returned === total) {
                expect(pool._connections.length).to.be.above(1);
                pool._connections.forEach(function(conn) {
                    expect(conn.messages).to.be.above(1);
                    sent += conn.messages;
                });

                expect(sent).to.be.equal(total);

                pool.close();
                return done();
            }
        };
        for (let i = 0; i < total; i++) {
            sendMessage(cb);
        }
    });


                onData(stream, session, callback) {
                    stream.on('data', function() {});
                    stream.on('end', callback);
                },


  remove: function (from, callback) {
    var that = this,
      cmd = '';
    fs.lstat(from, function (err, stats) {
      if (err) {
        callback(err);
      } else {
        if (that._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.replace(/ /g, '\\ ');
        }
        if (cmd) {
          child_process.exec(cmd, function (error, stdout, stderr) {
            callback && callback(error);
          });
        } else {
          callback && callback(null);
        }
      }
    });
  },


              text: src.slice(1, cap[0].length - 1)
            };
          }
        }
      }
    };


var fillTable = function(chart_data) {

                var tableRows = [],
                    rowData, rowId;
                for(i=0; i<chart_data.length; i++) {
                    rowData = chart_data[i];
                    rowId = typeof rowData.userId != 'undefined' ? rowData.userId : rowData.groupId;
                    tableRows.push('
' + rowData.label + '(id:'+ rowId +')	');
                    tableRows.push('' + rowData.data.filesizeformat() + '
');
                }

                $('#drivespaceTable tbody').html(tableRows.join(""));
                $('#drivespaceTable').show();
            };


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


String.prototype.escapeHTML = function(){
    /*
    HTML Escape Before Inserting Untrusted Data into HTML Element Content
    https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention
    _Cheat_Sheet#RULE_.231_-_HTML_Escape_Before_Inserting_Untrusted_Data_into
    _HTML_Element_Content
    */
    var s = this;
    if (!s) {
        return "";
    }
    s = s + "";
    return s.replace(/[\&"<>\\]/g, function(s) {
        switch(s) {
            case "&": return "&";
            case "\\": return "\";
            case '"': return '\"';
            case "<": return "<";
            case ">": return ">";
            default: return s;
        }
    });
};


exports.get = function(obj, path) {

	var cachekey = 'G=' + path;

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

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

	for (var i = 0, length = arr.length - 1; i < length; i++)
		builder.push('if(!w' + (!arr[i] || arr[i][0] === '[' ? '' : '.') + arr[i] + ')return');

	var v = arr[arr.length - 1];
	var fn = (new Function('w', builder.join(';') + ';return w' + (v[0] === '[' ? '' : '.') + v));
	F.temporary.other[cachekey] = fn;
	return fn(obj);
};


function cmdSet(key, val) {
  var objVal = val;

  try {
    var strTest = /^[\'\"](.*?)[\'\"]$/.exec(val);
    if (!strTest || strTest.length !== 2) { // do not parse if explicitly a string
      objVal = eval('(' + val + ')'); // attempt to parse
    } else {
      objVal = strTest[1];
    }
  } catch(ex) {
    // use as existing string
  }

  instance.setProp(key, objVal);
  rl.write(': stored as type ' + typeof objVal);

  enterCommand();
}


				query: _.bind(this._queryCirclesAutocomplete, this),

				id: function(circle) {
					return circle.unique_id;
				},

				initSelection: function(element, callback) {
					var val = $(element).val().trim();
					if (val) {
						var circleIds = val.split(','),
							circles = [];

						OCA.Circles.api.listCircles("all", '', 1, function(result) {
							_.each(circleIds, function(circleId) {
								var circle = _.find(result.data,function(circleData) {
									return circleData.unique_id == circleId;
								});
								if (!_.isUndefined(circle)) {
									circles.push(circle);
								}
							});

							callback(circles);
						});

					} else {
						callback([]);
					}
				},

				formatResult: function (circle) {
					return circle.name;
				},

				formatSelection: function (circle) {
					return circle.name;
					//return OC.SystemTags.getDescriptiveTag(tag)[0].outerHTML;
				},

				sortResults: function(results) {
					results.sort(function(a, b) {
						var aLastUsed = self._lastUsedTags.indexOf(a.id);
						var bLastUsed = self._lastUsedTags.indexOf(b.id);

						if (aLastUsed !== bLastUsed) {
							if (bLastUsed === -1) {
								return -1;
							}
							if (aLastUsed === -1) {
								return 1;
							}
							return aLastUsed < bLastUsed ? -1 : 1;
						}

						// Both not found
						return OC.Util.naturalSortCompare(a.name, b.name);
					});
					return results;
				},

				escapeMarkup: function(m) {
					// prevent double markup escape
					return m;
				},
				formatNoMatches: function() {
					return t('circles', 'No circles found');
				}
			});
			this.$filterField.on('change', _.bind(this._onTagsChanged, this));
			return this.$filterField;
		},


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


	function checkObj(instance,objTypeDef,path,additionalProp){

		if(typeof objTypeDef =='object'){
			if(typeof instance != 'object' || instance instanceof Array){
				errors.push({property:path,message:"an object is required"});
			}

			for(var i in objTypeDef){
				if(objTypeDef.hasOwnProperty(i)){
					var value = instance[i];
					// skip _not_ specified properties
					if (value === undefined && options.existingOnly) continue;
					var propDef = objTypeDef[i];
					// set default
					if(value === undefined && propDef["default"]){
						value = instance[i] = propDef["default"];
					}
					if(options.coerce && i in instance){
						value = instance[i] = options.coerce(value, propDef);
					}
					checkProp(value,propDef,path,i);
				}
			}
		}
		for(i in instance){
			if(instance.hasOwnProperty(i) && !(i.charAt(0) == '_' && i.charAt(1) == '_') && objTypeDef && !objTypeDef[i] && additionalProp===false){
				if (options.filter) {
					delete instance[i];
					continue;
				} else {
					errors.push({property:path,message:"The property " + i +
						" is not defined in the schema and the schema does not allow additional properties"});
				}
			}
			var requires = objTypeDef && objTypeDef[i] && objTypeDef[i].requires;
			if(requires && !(requires in instance)){
				errors.push({property:path,message:"the presence of the property " + i + " requires that " + requires + " also be present"});
			}
			value = instance[i];
			if(additionalProp && (!(objTypeDef && typeof objTypeDef == 'object') || !(i in objTypeDef))){
				if(options.coerce){
					value = instance[i] = options.coerce(value, additionalProp);
				}
				checkProp(value,additionalProp,path,i);
			}
			if(!_changing && value && value.$schema){
				errors = errors.concat(checkProp(value,value.$schema,path,i));
			}
		}
		return errors;
	}


  function compiler(node, file) {
    const hast = toHast(node, {allowDangerousHtml: !options.sanitize, handlers})
    // @ts-expect-error: assume root.
    const cleanHast = options.sanitize ? sanitize(hast, schema) : hast
    const result = toHtml(
      // @ts-expect-error: assume root.
      cleanHast,
      Object.assign({}, options, {allowDangerousHtml: !options.sanitize})
    )

    if (file.extname) {
      file.extname = '.html'
    }

    // Add an eof eol.
    return node &&
      node.type &&
      node.type === 'root' &&
      result &&
      /[^\r\n]/.test(result.charAt(result.length - 1))
      ? result + '\n'
      : result
  }


    convertFormDataToQueryString(formData) {
        let serialized = [];

        for (let row of formData) {
            serialized.push(encodeURIComponent(row.name) + "=" + encodeURIComponent(row.value));
        }

        return serialized.join('&');
    }


						instanceReady: function (evt) {
							evt.editor.on('blur', function () {
								evt.editor.updateElement();
							});
							if (self.isModal && self.progressInstance) {
								self.progressInstance.progressIndicator({ mode: 'hide' });
							}
						}


	function imageDimensions(src) {
		var o = getImageDimensions();
		var u = 'px';
		if (src == 'width') {
			if (o.uw == '%') u = '%';
			o.h = Math.round(o.w / imgScal);
		} else {
			if (o.uh == '%') u = '%';
			o.w = Math.round(o.h * imgScal);
		}
		if (u == '%') {
			o.w += '%';
			o.h += '%';
		}
		t.getContentElement('tab-properties', 'width').setValue(o.w),
			t.getContentElement('tab-properties', 'height').setValue(o.h);
	}


						onChange: function () {
							imagePreview('file');
						}


function readImageAsBase64(item, editor) {
	if (!item || typeof item.getAsFile !== 'function') {
		return;
	}
	var file = item.getAsFile();
	var reader = new FileReader();
	reader.onload = function (evt) {
		var element = editor.document.createElement('img', {
			attributes: {
				src: evt.target.result
			}
		});
		setTimeout(function () {
			editor.insertElement(element);
		}, 10);
	};
	reader.readAsDataURL(file);
}


    obj.refresh = function() {
        if (obj.options.responsive == true) {
            // Remove arrow
            toolbarArrow.remove();
            // Move all items to the toolbar
            while (toolbarFloating.firstChild) {
                toolbarContent.appendChild(toolbarFloating.firstChild);
            }
            // Width of the c
            var rect = el.parentNode.getBoundingClientRect();
            // Available parent space
            var available = rect.width;
            // Toolbar is larger than the parent, move elements to the floating element
            if (available < toolbarContent.offsetWidth) {
                // Give space to the floating element
                available -= 50;
                // Move to the floating option
                while (toolbarContent.lastChild && available < toolbarContent.offsetWidth) {
                    toolbarFloating.insertBefore(toolbarContent.lastChild, toolbarFloating.firstChild);
                }
            }
            // Show arrow
            if (toolbarFloating.children.length > 0) {
                toolbarContent.appendChild(toolbarArrow);
            }
        }
    }


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

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


_mdEmStrong(str) {
    return str.replace(/(^|\s|")(\\?)(\*+)(\w[^<]*?)\3/g, (all, b, esc, md, text) => {
      if (md.length == 1) return esc ? all.replace(/^\\/, '') : b + '' + text + '';
      if (md.length == 2) return esc ? all.replace(/^\\/, '') : b + '' + text + '';
      if (md.length == 3) return esc ? all.replace(/^\\/, '') : b + '' + text + '';
      return all;
    });
  }


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


  createConnection (options, callback) {
    if (isIPAddress(options.host) && isPrivateIP(options.host)) {
      callback(new Error(FORBIDDEN_IP_ADDRESS))
      return undefined
    }
    // @ts-ignore
    return super.createConnection({ ...options, lookup: dnsLookup }, callback)
  }


function isPrivateIP (ipAddress) {
  let isPrivate = false
  // Build the list of IP prefix for V4 and V6 addresses
  const ipPrefix = []
  // Add prefix for loopback addresses
  ipPrefix.push('127.')
  ipPrefix.push('0.')
  // Add IP V4 prefix for private addresses
  // See https://en.wikipedia.org/wiki/Private_network
  ipPrefix.push('10.')
  ipPrefix.push('172.16.')
  ipPrefix.push('172.17.')
  ipPrefix.push('172.18.')
  ipPrefix.push('172.19.')
  ipPrefix.push('172.20.')
  ipPrefix.push('172.21.')
  ipPrefix.push('172.22.')
  ipPrefix.push('172.23.')
  ipPrefix.push('172.24.')
  ipPrefix.push('172.25.')
  ipPrefix.push('172.26.')
  ipPrefix.push('172.27.')
  ipPrefix.push('172.28.')
  ipPrefix.push('172.29.')
  ipPrefix.push('172.30.')
  ipPrefix.push('172.31.')
  ipPrefix.push('192.168.')
  ipPrefix.push('169.254.')
  // Add IP V6 prefix for private addresses
  // See https://en.wikipedia.org/wiki/Unique_local_address
  // See https://en.wikipedia.org/wiki/Private_network
  // See https://simpledns.com/private-ipv6
  ipPrefix.push('fc')
  ipPrefix.push('fd')
  ipPrefix.push('fe')
  ipPrefix.push('ff')
  ipPrefix.push('::1')
  // Verify the provided IP address
  // Remove whitespace characters from the beginning/end of the string
  // and convert it to lower case
  // Lower case is for preventing any IPV6 case bypass using mixed case
  // depending on the source used to get the IP address
  const ipToVerify = ipAddress.trim().toLowerCase()
  // Perform the check against the list of prefix
  for (const prefix of ipPrefix) {
    if (ipToVerify.startsWith(prefix)) {
      isPrivate = true
      break
    }
  }

  return isPrivate
}


        verify: function(digest, d) {
          // remove padding
          d = _decodePkcs1_v1_5(d, key, true);
          // d is ASN.1 BER-encoded DigestInfo
          var obj = asn1.fromDer(d);
          // compare the given digest to the decrypted one
          return digest === obj.value[1].value;
        }


function renderConnection(connection, user) {
  const replaced = {};
  Object.keys(connection).forEach((key) => {
    // data is an object of values, but values may be top level too
    if (key === 'data') {
      const value = renderConnection(connection.data, user);
      connection.data = value;
    } else {
      const value = connection[key];
      if (typeof value === 'string') {
        _.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
        const compiled = _.template(value);
        replaced[key] = compiled({ user });
      } else {
        replaced[key] = value;
      }
    }
  });
  return replaced;
}


      function deleteConversation (convoId) {
        $.ajax({
          url: '/api/v1/messages/conversation/' + convoId,
          method: 'DELETE',
          success: function (response) {
            if (response.success) {
              // Check if on conversation
              var $convo = $('#message-content[data-conversation-id="' + response.conversation._id + '"]')
              if ($convo.length > 0) {
                History.pushState(null, null, '/messages', false)
              } else {
                var $convoLI = $('#convo-list').find('li[data-conversation-id="' + response.conversation._id + '"]')
                if ($convoLI.length > 0) {
                  $convoLI.remove()
                }
              }

              $.event.trigger('$trudesk:chat:conversation:deleted', {
                conversation: response.conversation
              })

              helpers.UI.showSnackbar('Conversation Deleted.', false)
            }
          },
          error: function (error) {
            console.log(error)
          }
        })
      }


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

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


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


DriveFile&&c.isEditable()||c.constructor==DropboxFile)};EditorUi.prototype.getServiceName=function(){return"draw.io"};EditorUi.prototype.addRemoteServiceSecurityCheck=function(c){c.setRequestHeader("Content-Language","da, mi, en, de-DE")};EditorUi.prototype.loadUrl=function(c,e,g,k,m,q,v,x){EditorUi.logEvent("SHOULD NOT BE CALLED: loadUrl");return this.editor.loadUrl(c,e,g,k,m,q,v,x)};EditorUi.prototype.loadFonts=function(c){EditorUi.logEvent("SHOULD NOT BE CALLED: loadFonts");return this.editor.loadFonts(c)};


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


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


function u(){mxShape.call(this)}function J(){mxShape.call(this)}function N(){mxRectangleShape.call(this)}function W(){mxShape.call(this)}function S(){mxShape.call(this)}function P(){mxShape.call(this)}function Z(){mxShape.call(this)}function oa(){mxShape.call(this)}function va(){mxCylinder.call(this)}function Aa(){mxCylinder.call(this)}function sa(){mxRectangleShape.call(this)}function Ba(){mxDoubleEllipse.call(this)}function ta(){mxDoubleEllipse.call(this)}function Na(){mxArrowConnector.call(this);
this.spacing=0}function Ca(){mxArrowConnector.call(this);this.spacing=0}function Ra(){mxActor.call(this)}function ab(){mxRectangleShape.call(this)}function Ka(){mxActor.call(this)}function bb(){mxActor.call(this)}function Pa(){mxActor.call(this)}function Za(){mxActor.call(this)}function z(){mxActor.call(this)}function L(){mxActor.call(this)}function M(){mxActor.call(this)}function T(){mxActor.call(this)}function ca(){mxActor.call(this)}function ia(){mxActor.call(this)}function ma(){mxEllipse.call(this)}


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


		function updateLinkColor()
		{
			var div = document.createElement('div');
			div.style.width = '100%';
			div.style.height = '100%';
			div.style.boxSizing = 'border-box';

			if (linkColor != null && linkColor != mxConstants.NONE)
			{
				div.style.border = '1px solid black';
				div.style.backgroundColor = linkColor;
			}
			else
			{
				div.style.backgroundPosition = 'center center';
				div.style.backgroundRepeat = 'no-repeat';
				div.style.backgroundImage = 'url(\'' + Dialog.prototype.closeImage + '\')';
			}

			linkButton.innerHTML = '';
			linkButton.appendChild(div);
		};


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


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


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


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


function addToolTipToTableCell(value) {
  if (value) {
    return `<span class="js-tooltip" data-bs-toggle="tooltip" data-bs-placement="left" title="${value}">${value}</span>`
  }
  return ''
}


  'click .js-update-oidc': (event) => {
    event.preventDefault()

    const configuration = {
      service: 'oidc',
      loginStyle: 'popup',
    }

    // Fetch the value of each input field
    Oidc.fields.forEach((field) => {
      configuration[field.property] = document.getElementById(
        `configure-oidc-${field.property}`
      ).value.replace(/^\s*|\s*$/g, '') // trim() doesnt work on IE8
    })

    configuration.idTokenWhitelistFields = configuration.idTokenWhitelistFields.split(' ')

    // Configure this login service
    Meteor.call('updateOidcSettings', configuration, (error) => {
      if (error) {
        // eslint-disable-next-line no-underscore-dangle
        Meteor._debug('Error configuring login service oidc', error)
      } else {
        showToast(t('notifications.success'))
      }
    })
  },


TrafficAnalyser.prototype.add = function (data) {

    const stream = new BinaryStream(data);
    if (argv.block) {
        console.log(hexDump(data));
        return;
    }
    const messageHeader = opcua.readMessageHeader(stream);

    if (messageHeader.msgType === "ERR") {

        var err = new s.TCPErrorMessage();
        err.decode(stream);
        console.log(" Error 0x" + err.statusCode.toString() + " reason:" + err.reason);
        console.log(hexDump(data));
    }

    const messageBuild = new MessageBuilder();
    messageBuild.on("full_message_body", function (full_message_body) {

        console.log(hexDump(full_message_body));

        try {
            analyseExtensionObject(full_message_body);
        }
        catch (err) {
            console.log(chalk.red("ERROR : "), err);
        }
    });

    switch (messageHeader.msgType) {

        case "HEL":
        case "ACK":
            if (this.id % 2) {
                console.log(chalk.red.bold(JSON.stringify(messageHeader, null, "")));
            } else {
                console.log(chalk.yellow.bold(JSON.stringify(messageHeader, null, "")));
            }
            break;

        case "OPN": // open secure channel
        case "CLO": // close secure channel
        case "MSG": // message
                    // decode secure message
            if (this.id % 2) {
                console.log(chalk.red.bold(messageHeaderToString(data)));
            } else {
                console.log(chalk.yellow.bold(messageHeaderToString(data)));
            }

            messageBuild.feed(data);
            break;
        case "ERR":
            console.log(hexDump(data));
            break;
        default:
            break;

    }

};


function startServer(holder, callback) {
    const net = require("net");
    const server_socket = new net.Server();
    holder.server_socket = server_socket;

    server_socket.listen(port);
    server_socket.on("connection", function on_connection(socket) {
        const serverChannel = new ServerSecureChannelLayer({
            timeout: 1000 * 1000
        });
        holder.serverChannel = serverChannel;
        serverChannel.timeout = 1000 * 1000;
        serverChannel.init(socket, function () {});
    });

    callback();
}


    function perform_sever_receiving_a_HEL_MESSAGE_followed_by_OpenChannelRequest_scenario(done) {
        const transport = new ServerTCP_transport();

        transport.init(fakeSocket.server, (err) => {
            assert(!err);
        });

        transport.on("message", (messageChunk) => {
            utils.compare_buffers(messageChunk, openChannelRequest);

            // it should provide bytesRead and bytesWritten
            transport.bytesRead.should.be.greaterThan(0);
            transport.bytesWritten.should.be.greaterThan(20);

            done();
        });

        let counter = 1;
        fakeSocket.client.on("data", (data) => {
            counter++;
        });

        transport.bytesRead.should.equal(0);
        transport.bytesWritten.should.equal(0);
    }


      ], function final(err) {
        client1.disconnect(function() {
          done(err);
        });
      });


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


function createSubscription(session, callback) {
  const publishingInterval = 1000;
  const createSubscriptionRequest = new CreateSubscriptionRequest({
    requestedPublishingInterval: publishingInterval,
    requestedLifetimeCount: 60,
    requestedMaxKeepAliveCount: 10,
    maxNotificationsPerPublish: 10,
    publishingEnabled: true,
    priority: 6
  });

  session.performMessageTransaction(createSubscriptionRequest, function(err/*, response*/) {
    callback(err);
  });
}


function returnImage(req, res) {
    const image = becca.getNote(req.params.noteId);

    if (!image) {
        return res.sendStatus(404);
    }
    else if (!["image", "canvas"].includes(image.type)){
        return res.sendStatus(400);
    }
    else if (image.isDeleted || image.data === null) {
        res.set('Content-Type', 'image/png');
        return res.send(fs.readFileSync(RESOURCE_DIR + '/db/image-deleted.png'));
    }

    /**
     * special "image" type. the canvas is actually type application/json
     * to avoid bitrot and enable usage as referenced image the svg is included.
     */
    if (image.type === 'canvas') {
        const content = image.getContent();
        try {
            const data = JSON.parse(content);

            const svg = data.svg || '<svg />'
            res.set('Content-Type', "image/svg+xml");
            res.set("Cache-Control", "no-cache, no-store, must-revalidate");
            res.send(svg);
        } catch(err) {
            res.status(500).send("there was an error parsing excalidraw to svg");
        }
    } else {
        res.set('Content-Type', image.mime);
        res.set("Cache-Control", "no-cache, no-store, must-revalidate");
        res.send(image.getContent());
    }
}


	run_server_script: function() {
		// DEPRECATE
		var me = this;
		if(this.frm && this.frm.docname) {
			frappe.call({
				method: "runserverobj",
				args: {'docs': this.frm.doc, 'method': this.df.options },
				btn: this.$input,
				callback: function(r) {
					if(!r.exc) {
						me.frm.refresh_fields();
					}
				}
			});
		}
	},


const sameHost = (parent, child) => {
  const p = new URL (parent);
  const c = new URL (child);
  return p.host === c.host || c.host.endsWith ('.' + p.host);
};


    function make_process(object, prop) {
        var labels = {
            from: 'Unserialize',
            to: 'Serialize'
        };
        var prefix_message = labels[prop] + ' Error: ';
        return function(data) {
            var fn = object[prop];
            try {
                if (fn) {
                    return fn(data);
                }
                return data;
            } catch (e) {
                console.warn(prefix_message + e.message);
            }
        };
    }


    function onLoad() {
        return new Promise(function(resolve) {
            window.addEventListener('load', resolve, true);
        }).then(iframeLoaded);
    }


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


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

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

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

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

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

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

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

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

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

    url = new URL(path, origin)
  }

  return url
}


acc_ctx_hints(OM_uint32 *minor_status,
	      gss_ctx_id_t *ctx,
	      spnego_gss_cred_id_t spcred,
	      gss_buffer_t *mechListMIC,
	      OM_uint32 *negState,
	      send_token_flag *return_token)
{
	OM_uint32 tmpmin, ret;
	gss_OID_set supported_mechSet;
	spnego_gss_ctx_id_t sc = NULL;

	*mechListMIC = GSS_C_NO_BUFFER;
	supported_mechSet = GSS_C_NO_OID_SET;
	*return_token = NO_TOKEN_SEND;
	*negState = REJECT;
	*minor_status = 0;

	/* A hint request must be the first token received. */
	if (*ctx != GSS_C_NO_CONTEXT)
	    return GSS_S_DEFECTIVE_TOKEN;

	ret = get_negotiable_mechs(minor_status, spcred, GSS_C_ACCEPT,
				   &supported_mechSet);
	if (ret != GSS_S_COMPLETE)
		goto cleanup;

	ret = make_NegHints(minor_status, mechListMIC);
	if (ret != GSS_S_COMPLETE)
		goto cleanup;

	sc = create_spnego_ctx();
	if (sc == NULL) {
		ret = GSS_S_FAILURE;
		goto cleanup;
	}
	if (put_mech_set(supported_mechSet, &sc->DER_mechTypes) < 0) {
		ret = GSS_S_FAILURE;
		goto cleanup;
	}
	sc->internal_mech = GSS_C_NO_OID;

	*negState = ACCEPT_INCOMPLETE;
	*return_token = INIT_TOKEN_SEND;
	sc->firstpass = 1;
	*ctx = (gss_ctx_id_t)sc;
	sc = NULL;
	ret = GSS_S_COMPLETE;

cleanup:
	release_spnego_ctx(&sc);
	gss_release_oid_set(&tmpmin, &supported_mechSet);

	return ret;
}


spnego_gss_get_mic_iov_length(OM_uint32 *minor_status,
			      gss_ctx_id_t context_handle, gss_qop_t qop_req,
			      gss_iov_buffer_desc *iov, int iov_count)
{
    return gss_get_mic_iov_length(minor_status, context_handle, qop_req, iov,
				  iov_count);
}


spnego_gss_unwrap_iov(OM_uint32 *minor_status,
		      gss_ctx_id_t context_handle,
		      int *conf_state,
		      gss_qop_t *qop_state,
		      gss_iov_buffer_desc *iov,
		      int iov_count)
{
	OM_uint32 ret;
	ret = gss_unwrap_iov(minor_status,
			     context_handle,
			     conf_state,
			     qop_state,
			     iov,
			     iov_count);
	return (ret);
}


spnego_gss_unwrap(
		OM_uint32 *minor_status,
		gss_ctx_id_t context_handle,
		gss_buffer_t input_message_buffer,
		gss_buffer_t output_message_buffer,
		int *conf_state,
		gss_qop_t *qop_state)
{
	OM_uint32 ret;
	ret = gss_unwrap(minor_status,
			context_handle,
			input_message_buffer,
			output_message_buffer,
			conf_state,
			qop_state);

	return (ret);
}


spnego_gss_complete_auth_token(
		OM_uint32 *minor_status,
		const gss_ctx_id_t context_handle,
		gss_buffer_t input_message_buffer)
{
	OM_uint32 ret;
	ret = gss_complete_auth_token(minor_status,
				      context_handle,
				      input_message_buffer);
	return (ret);
}


iakerb_gss_export_sec_context(OM_uint32 *minor_status,
                              gss_ctx_id_t *context_handle,
                              gss_buffer_t interprocess_token)
{
    OM_uint32 maj;
    iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle;

    /* We don't currently support exporting partially established contexts. */
    if (!ctx->established)
        return GSS_S_UNAVAILABLE;

    maj = krb5_gss_export_sec_context(minor_status, &ctx->gssc,
                                      interprocess_token);
    if (ctx->gssc == GSS_C_NO_CONTEXT) {
        iakerb_release_context(ctx);
        *context_handle = GSS_C_NO_CONTEXT;
    }
    return maj;
}


getprivs_ret * get_privs_2_svc(krb5_ui_4 *arg, struct svc_req *rqstp)
{
    static getprivs_ret            ret;
    gss_buffer_desc                client_name, service_name;
    OM_uint32                      minor_stat;
    kadm5_server_handle_t          handle;
    const char                     *errmsg = NULL;

    xdr_free(xdr_getprivs_ret, &ret);

    if ((ret.code = new_server_handle(*arg, rqstp, &handle)))
        goto exit_func;

    if ((ret.code = check_handle((void *)handle)))
        goto exit_func;

    ret.api_version = handle->api_version;

    if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
        ret.code = KADM5_FAILURE;
        goto exit_func;
    }

    ret.code = kadm5_get_privs((void *)handle, &ret.privs);
    if( ret.code != 0 )
        errmsg = krb5_get_error_message(handle->context, ret.code);

    log_done("kadm5_get_privs", client_name.value, errmsg,
             &client_name, &service_name, rqstp);

    if (errmsg != NULL)
        krb5_free_error_message(handle->context, errmsg);

    gss_release_buffer(&minor_stat, &client_name);
    gss_release_buffer(&minor_stat, &service_name);
exit_func:
    free_server_handle(handle);
    return &ret;
}


decode_sequence(const uint8_t *asn1, size_t len, const struct seq_info *seq,
                void *val)
{
    krb5_error_code ret;
    const uint8_t *contents;
    size_t i, j, clen;
    taginfo t;

    assert(seq->n_fields > 0);
    for (i = 0; i < seq->n_fields; i++) {
        if (len == 0)
            break;
        ret = get_tag(asn1, len, &t, &contents, &clen, &asn1, &len);
        if (ret)
            goto error;
        /*
         * Find the applicable sequence field.  This logic is a little
         * oversimplified; we could match an element to an optional extensible
         * choice or optional stored-DER type when we ought to match a
         * subsequent non-optional field.  But it's unwise and (hopefully) very
         * rare for ASN.1 modules to require such precision.
         */
        for (; i < seq->n_fields; i++) {
            if (check_atype_tag(seq->fields[i], &t))
                break;
            ret = omit_atype(seq->fields[i], val);
            if (ret)
                goto error;
        }
        /* We currently model all sequences as extensible.  We should consider
         * changing this before making the encoder visible to plugins. */
        if (i == seq->n_fields)
            break;
        ret = decode_atype(&t, contents, clen, seq->fields[i], val);
        if (ret)
            goto error;
    }
    /* Initialize any fields in the C object which were not accounted for in
     * the sequence.  Error out if any of them aren't optional. */
    for (; i < seq->n_fields; i++) {
        ret = omit_atype(seq->fields[i], val);
        if (ret)
            goto error;
    }
    return 0;

error:
    /* Free what we've decoded so far.  Free pointers in a second pass in
     * case multiple fields refer to the same pointer. */
    for (j = 0; j < i; j++)
        free_atype(seq->fields[j], val);
    for (j = 0; j < i; j++)
        free_atype_ptr(seq->fields[j], val);
    return ret;
}


asmlinkage void __sched schedule(void)
{
	struct task_struct *prev, *next;
	unsigned long *switch_count;
	struct rq *rq;
	int cpu;

need_resched:
	preempt_disable();
	cpu = smp_processor_id();
	rq = cpu_rq(cpu);
	rcu_note_context_switch(cpu);
	prev = rq->curr;

	release_kernel_lock(prev);
need_resched_nonpreemptible:

	schedule_debug(prev);

	if (sched_feat(HRTICK))
		hrtick_clear(rq);

	raw_spin_lock_irq(&rq->lock);
	clear_tsk_need_resched(prev);

	switch_count = &prev->nivcsw;
	if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
		if (unlikely(signal_pending_state(prev->state, prev))) {
			prev->state = TASK_RUNNING;
		} else {
			/*
			 * If a worker is going to sleep, notify and
			 * ask workqueue whether it wants to wake up a
			 * task to maintain concurrency.  If so, wake
			 * up the task.
			 */
			if (prev->flags & PF_WQ_WORKER) {
				struct task_struct *to_wakeup;

				to_wakeup = wq_worker_sleeping(prev, cpu);
				if (to_wakeup)
					try_to_wake_up_local(to_wakeup);
			}
			deactivate_task(rq, prev, DEQUEUE_SLEEP);
		}
		switch_count = &prev->nvcsw;
	}

	pre_schedule(rq, prev);

	if (unlikely(!rq->nr_running))
		idle_balance(cpu, rq);

	put_prev_task(rq, prev);
	next = pick_next_task(rq);

	if (likely(prev != next)) {
		sched_info_switch(prev, next);
		perf_event_task_sched_out(prev, next);

		rq->nr_switches++;
		rq->curr = next;
		++*switch_count;

		context_switch(rq, prev, next); /* unlocks the rq */
		/*
		 * The context switch have flipped the stack from under us
		 * and restored the local variables which were saved when
		 * this task called schedule() in the past. prev == current
		 * is still correct, but it can be moved to another cpu/rq.
		 */
		cpu = smp_processor_id();
		rq = cpu_rq(cpu);
	} else
		raw_spin_unlock_irq(&rq->lock);

	post_schedule(rq);

	if (unlikely(reacquire_kernel_lock(prev)))
		goto need_resched_nonpreemptible;

	preempt_enable_no_resched();
	if (need_resched())
		goto need_resched;
}


int ip_build_and_send_pkt(struct sk_buff *skb, struct sock *sk,
			  __be32 saddr, __be32 daddr, struct ip_options *opt)
{
	struct inet_sock *inet = inet_sk(sk);
	struct rtable *rt = skb_rtable(skb);
	struct iphdr *iph;

	/* Build the IP header. */
	skb_push(skb, sizeof(struct iphdr) + (opt ? opt->optlen : 0));
	skb_reset_network_header(skb);
	iph = ip_hdr(skb);
	iph->version  = 4;
	iph->ihl      = 5;
	iph->tos      = inet->tos;
	if (ip_dont_fragment(sk, &rt->dst))
		iph->frag_off = htons(IP_DF);
	else
		iph->frag_off = 0;
	iph->ttl      = ip_select_ttl(inet, &rt->dst);
	iph->daddr    = rt->rt_dst;
	iph->saddr    = rt->rt_src;
	iph->protocol = sk->sk_protocol;
	ip_select_ident(iph, &rt->dst, sk);

	if (opt && opt->optlen) {
		iph->ihl += opt->optlen>>2;
		ip_options_build(skb, opt, daddr, rt, 0);
	}

	skb->priority = sk->sk_priority;
	skb->mark = sk->sk_mark;

	/* Send it out. */
	return ip_local_out(skb);
}


static struct ip_options *tcp_v4_save_options(struct sock *sk,
					      struct sk_buff *skb)
{
	struct ip_options *opt = &(IPCB(skb)->opt);
	struct ip_options *dopt = NULL;

	if (opt && opt->optlen) {
		int opt_size = optlength(opt);
		dopt = kmalloc(opt_size, GFP_ATOMIC);
		if (dopt) {
			if (ip_options_echo(dopt, skb)) {
				kfree(dopt);
				dopt = NULL;
			}
		}
	}
	return dopt;
}


static void record_and_restart(struct perf_event *event, unsigned long val,
			       struct pt_regs *regs, int nmi)
{
	u64 period = event->hw.sample_period;
	s64 prev, delta, left;
	int record = 0;

	if (event->hw.state & PERF_HES_STOPPED) {
		write_pmc(event->hw.idx, 0);
		return;
	}

	/* we don't have to worry about interrupts here */
	prev = local64_read(&event->hw.prev_count);
	delta = check_and_compute_delta(prev, val);
	local64_add(delta, &event->count);

	/*
	 * See if the total period for this event has expired,
	 * and update for the next period.
	 */
	val = 0;
	left = local64_read(&event->hw.period_left) - delta;
	if (period) {
		if (left <= 0) {
			left += period;
			if (left <= 0)
				left = period;
			record = 1;
			event->hw.last_period = event->hw.sample_period;
		}
		if (left < 0x80000000LL)
			val = 0x80000000LL - left;
	}

	write_pmc(event->hw.idx, val);
	local64_set(&event->hw.prev_count, val);
	local64_set(&event->hw.period_left, left);
	perf_event_update_userpage(event);

	/*
	 * Finally record data if requested.
	 */
	if (record) {
		struct perf_sample_data data;

		perf_sample_data_init(&data, ~0ULL);
		data.period = event->hw.last_period;

		if (event->attr.sample_type & PERF_SAMPLE_ADDR)
			perf_get_data_addr(regs, &data.addr);

		if (perf_event_overflow(event, nmi, &data, regs))
			power_pmu_stop(event, 0);
	}
}


void handle_lddfmna(struct pt_regs *regs, unsigned long sfar, unsigned long sfsr)
{
	unsigned long pc = regs->tpc;
	unsigned long tstate = regs->tstate;
	u32 insn;
	u64 value;
	u8 freg;
	int flag;
	struct fpustate *f = FPUSTATE;

	if (tstate & TSTATE_PRIV)
		die_if_kernel("lddfmna from kernel", regs);
	perf_sw_event(PERF_COUNT_SW_ALIGNMENT_FAULTS, 1, 0, regs, sfar);
	if (test_thread_flag(TIF_32BIT))
		pc = (u32)pc;
	if (get_user(insn, (u32 __user *) pc) != -EFAULT) {
		int asi = decode_asi(insn, regs);
		u32 first, second;
		int err;

		if ((asi > ASI_SNFL) ||
		    (asi < ASI_P))
			goto daex;
		first = second = 0;
		err = get_user(first, (u32 __user *)sfar);
		if (!err)
			err = get_user(second, (u32 __user *)(sfar + 4));
		if (err) {
			if (!(asi & 0x2))
				goto daex;
			first = second = 0;
		}
		save_and_clear_fpu();
		freg = ((insn >> 25) & 0x1e) | ((insn >> 20) & 0x20);
		value = (((u64)first) << 32) | second;
		if (asi & 0x8) /* Little */
			value = __swab64p(&value);
		flag = (freg < 32) ? FPRS_DL : FPRS_DU;
		if (!(current_thread_info()->fpsaved[0] & FPRS_FEF)) {
			current_thread_info()->fpsaved[0] = FPRS_FEF;
			current_thread_info()->gsr[0] = 0;
		}
		if (!(current_thread_info()->fpsaved[0] & flag)) {
			if (freg < 32)
				memset(f->regs, 0, 32*sizeof(u32));
			else
				memset(f->regs+32, 0, 32*sizeof(u32));
		}
		*(u64 *)(f->regs + freg) = value;
		current_thread_info()->fpsaved[0] |= flag;
	} else {
daex:
		if (tlb_type == hypervisor)
			sun4v_data_access_exception(regs, sfar, sfsr);
		else
			spitfire_data_access_exception(regs, sfsr, sfar);
		return;
	}
	advance(regs);
}


int vis_emul(struct pt_regs *regs, unsigned int insn)
{
	unsigned long pc = regs->tpc;
	unsigned int opf;

	BUG_ON(regs->tstate & TSTATE_PRIV);

	perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, 0, regs, 0);

	if (test_thread_flag(TIF_32BIT))
		pc = (u32)pc;

	if (get_user(insn, (u32 __user *) pc))
		return -EFAULT;

	save_and_clear_fpu();

	opf = (insn & VIS_OPF_MASK) >> VIS_OPF_SHIFT;
	switch (opf) {
	default:
		return -EINVAL;

	/* Pixel Formatting Instructions.  */
	case FPACK16_OPF:
	case FPACK32_OPF:
	case FPACKFIX_OPF:
	case FEXPAND_OPF:
	case FPMERGE_OPF:
		pformat(regs, insn, opf);
		break;

	/* Partitioned Multiply Instructions  */
	case FMUL8x16_OPF:
	case FMUL8x16AU_OPF:
	case FMUL8x16AL_OPF:
	case FMUL8SUx16_OPF:
	case FMUL8ULx16_OPF:
	case FMULD8SUx16_OPF:
	case FMULD8ULx16_OPF:
		pmul(regs, insn, opf);
		break;

	/* Pixel Compare Instructions  */
	case FCMPGT16_OPF:
	case FCMPGT32_OPF:
	case FCMPLE16_OPF:
	case FCMPLE32_OPF:
	case FCMPNE16_OPF:
	case FCMPNE32_OPF:
	case FCMPEQ16_OPF:
	case FCMPEQ32_OPF:
		pcmp(regs, insn, opf);
		break;

	/* Edge Handling Instructions  */
	case EDGE8_OPF:
	case EDGE8N_OPF:
	case EDGE8L_OPF:
	case EDGE8LN_OPF:
	case EDGE16_OPF:
	case EDGE16N_OPF:
	case EDGE16L_OPF:
	case EDGE16LN_OPF:
	case EDGE32_OPF:
	case EDGE32N_OPF:
	case EDGE32L_OPF:
	case EDGE32LN_OPF:
		edge(regs, insn, opf);
		break;

	/* Pixel Component Distance  */
	case PDIST_OPF:
		pdist(regs, insn);
		break;

	/* Three-Dimensional Array Addressing Instructions  */
	case ARRAY8_OPF:
	case ARRAY16_OPF:
	case ARRAY32_OPF:
		array(regs, insn, opf);
		break;

	/* Byte Mask and Shuffle Instructions  */
	case BMASK_OPF:
		bmask(regs, insn);
		break;

	case BSHUFFLE_OPF:
		bshuffle(regs, insn);
		break;
	}

	regs->tpc = regs->tnpc;
	regs->tnpc += 4;
	return 0;
}


static int p4_pmu_handle_irq(struct pt_regs *regs)
{
	struct perf_sample_data data;
	struct cpu_hw_events *cpuc;
	struct perf_event *event;
	struct hw_perf_event *hwc;
	int idx, handled = 0;
	u64 val;

	perf_sample_data_init(&data, 0);

	cpuc = &__get_cpu_var(cpu_hw_events);

	for (idx = 0; idx < x86_pmu.num_counters; idx++) {
		int overflow;

		if (!test_bit(idx, cpuc->active_mask)) {
			/* catch in-flight IRQs */
			if (__test_and_clear_bit(idx, cpuc->running))
				handled++;
			continue;
		}

		event = cpuc->events[idx];
		hwc = &event->hw;

		WARN_ON_ONCE(hwc->idx != idx);

		/* it might be unflagged overflow */
		overflow = p4_pmu_clear_cccr_ovf(hwc);

		val = x86_perf_event_update(event);
		if (!overflow && (val & (1ULL << (x86_pmu.cntval_bits - 1))))
			continue;

		handled += overflow;

		/* event overflow for sure */
		data.period = event->hw.last_period;

		if (!x86_perf_event_set_period(event))
			continue;
		if (perf_event_overflow(event, 1, &data, regs))
			x86_pmu_stop(event, 0);
	}

	if (handled)
		inc_irq_stat(apic_perf_irqs);

	/*
	 * When dealing with the unmasking of the LVTPC on P4 perf hw, it has
	 * been observed that the OVF bit flag has to be cleared first _before_
	 * the LVTPC can be unmasked.
	 *
	 * The reason is the NMI line will continue to be asserted while the OVF
	 * bit is set.  This causes a second NMI to generate if the LVTPC is
	 * unmasked before the OVF bit is cleared, leading to unknown NMI
	 * messages.
	 */
	apic_write(APIC_LVTPC, APIC_DM_NMI);

	return handled;
}


static void perf_event_task_output(struct perf_event *event,
				     struct perf_task_event *task_event)
{
	struct perf_output_handle handle;
	struct perf_sample_data	sample;
	struct task_struct *task = task_event->task;
	int ret, size = task_event->event_id.header.size;

	perf_event_header__init_id(&task_event->event_id.header, &sample, event);

	ret = perf_output_begin(&handle, event,
				task_event->event_id.header.size, 0, 0);
	if (ret)
		goto out;

	task_event->event_id.pid = perf_event_pid(event, task);
	task_event->event_id.ppid = perf_event_pid(event, current);

	task_event->event_id.tid = perf_event_tid(event, task);
	task_event->event_id.ptid = perf_event_tid(event, current);

	perf_output_put(&handle, task_event->event_id);

	perf_event__output_id_sample(event, &handle, &sample);

	perf_output_end(&handle);
out:
	task_event->event_id.header.size = size;
}


struct sk_buff *sock_alloc_send_pskb(struct sock *sk, unsigned long header_len,
				     unsigned long data_len, int noblock,
				     int *errcode)
{
	struct sk_buff *skb;
	gfp_t gfp_mask;
	long timeo;
	int err;

	gfp_mask = sk->sk_allocation;
	if (gfp_mask & __GFP_WAIT)
		gfp_mask |= __GFP_REPEAT;

	timeo = sock_sndtimeo(sk, noblock);
	while (1) {
		err = sock_error(sk);
		if (err != 0)
			goto failure;

		err = -EPIPE;
		if (sk->sk_shutdown & SEND_SHUTDOWN)
			goto failure;

		if (atomic_read(&sk->sk_wmem_alloc) < sk->sk_sndbuf) {
			skb = alloc_skb(header_len, gfp_mask);
			if (skb) {
				int npages;
				int i;

				/* No pages, we're done... */
				if (!data_len)
					break;

				npages = (data_len + (PAGE_SIZE - 1)) >> PAGE_SHIFT;
				skb->truesize += data_len;
				skb_shinfo(skb)->nr_frags = npages;
				for (i = 0; i < npages; i++) {
					struct page *page;

					page = alloc_pages(sk->sk_allocation, 0);
					if (!page) {
						err = -ENOBUFS;
						skb_shinfo(skb)->nr_frags = i;
						kfree_skb(skb);
						goto failure;
					}

					__skb_fill_page_desc(skb, i,
							page, 0,
							(data_len >= PAGE_SIZE ?
							 PAGE_SIZE :
							 data_len));
					data_len -= PAGE_SIZE;
				}

				/* Full success... */
				break;
			}
			err = -ENOBUFS;
			goto failure;
		}
		set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags);
		set_bit(SOCK_NOSPACE, &sk->sk_socket->flags);
		err = -EAGAIN;
		if (!timeo)
			goto failure;
		if (signal_pending(current))
			goto interrupted;
		timeo = sock_wait_for_wmem(sk, timeo);
	}

	skb_set_owner_w(skb, sk);
	return skb;

interrupted:
	err = sock_intr_errno(timeo);
failure:
	*errcode = err;
	return NULL;
}


static int llc_ui_getname(struct socket *sock, struct sockaddr *uaddr,
			  int *uaddrlen, int peer)
{
	struct sockaddr_llc sllc;
	struct sock *sk = sock->sk;
	struct llc_sock *llc = llc_sk(sk);
	int rc = 0;

	memset(&sllc, 0, sizeof(sllc));
	lock_sock(sk);
	if (sock_flag(sk, SOCK_ZAPPED))
		goto out;
	*uaddrlen = sizeof(sllc);
	memset(uaddr, 0, *uaddrlen);
	if (peer) {
		rc = -ENOTCONN;
		if (sk->sk_state != TCP_ESTABLISHED)
			goto out;
		if(llc->dev)
			sllc.sllc_arphrd = llc->dev->type;
		sllc.sllc_sap = llc->daddr.lsap;
		memcpy(&sllc.sllc_mac, &llc->daddr.mac, IFHWADDRLEN);
	} else {
		rc = -EINVAL;
		if (!llc->sap)
			goto out;
		sllc.sllc_sap = llc->sap->laddr.lsap;

		if (llc->dev) {
			sllc.sllc_arphrd = llc->dev->type;
			memcpy(&sllc.sllc_mac, llc->dev->dev_addr,
			       IFHWADDRLEN);
		}
	}
	rc = 0;
	sllc.sllc_family = AF_LLC;
	memcpy(uaddr, &sllc, sizeof(sllc));
out:
	release_sock(sk);
	return rc;
}


static int netlink_sendmsg(struct kiocb *kiocb, struct socket *sock,
			   struct msghdr *msg, size_t len)
{
	struct sock_iocb *siocb = kiocb_to_siocb(kiocb);
	struct sock *sk = sock->sk;
	struct netlink_sock *nlk = nlk_sk(sk);
	struct sockaddr_nl *addr = msg->msg_name;
	u32 dst_pid;
	u32 dst_group;
	struct sk_buff *skb;
	int err;
	struct scm_cookie scm;

	if (msg->msg_flags&MSG_OOB)
		return -EOPNOTSUPP;

	if (NULL == siocb->scm)
		siocb->scm = &scm;

	err = scm_send(sock, msg, siocb->scm);
	if (err < 0)
		return err;

	if (msg->msg_namelen) {
		err = -EINVAL;
		if (addr->nl_family != AF_NETLINK)
			goto out;
		dst_pid = addr->nl_pid;
		dst_group = ffs(addr->nl_groups);
		err =  -EPERM;
		if (dst_group && !netlink_capable(sock, NL_NONROOT_SEND))
			goto out;
	} else {
		dst_pid = nlk->dst_pid;
		dst_group = nlk->dst_group;
	}

	if (!nlk->pid) {
		err = netlink_autobind(sock);
		if (err)
			goto out;
	}

	err = -EMSGSIZE;
	if (len > sk->sk_sndbuf - 32)
		goto out;
	err = -ENOBUFS;
	skb = alloc_skb(len, GFP_KERNEL);
	if (skb == NULL)
		goto out;

	NETLINK_CB(skb).pid	= nlk->pid;
	NETLINK_CB(skb).dst_group = dst_group;
	memcpy(NETLINK_CREDS(skb), &siocb->scm->creds, sizeof(struct ucred));

	err = -EFAULT;
	if (memcpy_fromiovec(skb_put(skb, len), msg->msg_iov, len)) {
		kfree_skb(skb);
		goto out;
	}

	err = security_netlink_send(sk, skb);
	if (err) {
		kfree_skb(skb);
		goto out;
	}

	if (dst_group) {
		atomic_inc(&skb->users);
		netlink_broadcast(sk, skb, dst_pid, dst_group, GFP_KERNEL);
	}
	err = netlink_unicast(sk, skb, dst_pid, msg->msg_flags&MSG_DONTWAIT);

out:
	scm_destroy(siocb->scm);
	return err;
}


static int netlink_sendmsg(struct kiocb *kiocb, struct socket *sock,
			   struct msghdr *msg, size_t len)
{
	struct sock_iocb *siocb = kiocb_to_siocb(kiocb);
	struct sock *sk = sock->sk;
	struct netlink_sock *nlk = nlk_sk(sk);
	struct sockaddr_nl *addr = msg->msg_name;
	u32 dst_pid;
	u32 dst_group;
	struct sk_buff *skb;
	int err;
	struct scm_cookie scm;

	if (msg->msg_flags&MSG_OOB)
		return -EOPNOTSUPP;

	if (NULL == siocb->scm)
		siocb->scm = &scm;

	err = scm_send(sock, msg, siocb->scm, true);
	if (err < 0)
		return err;

	if (msg->msg_namelen) {
		err = -EINVAL;
		if (addr->nl_family != AF_NETLINK)
			goto out;
		dst_pid = addr->nl_pid;
		dst_group = ffs(addr->nl_groups);
		err =  -EPERM;
		if (dst_group && !netlink_capable(sock, NL_NONROOT_SEND))
			goto out;
	} else {
		dst_pid = nlk->dst_pid;
		dst_group = nlk->dst_group;
	}

	if (!nlk->pid) {
		err = netlink_autobind(sock);
		if (err)
			goto out;
	}

	err = -EMSGSIZE;
	if (len > sk->sk_sndbuf - 32)
		goto out;
	err = -ENOBUFS;
	skb = alloc_skb(len, GFP_KERNEL);
	if (skb == NULL)
		goto out;

	NETLINK_CB(skb).pid	= nlk->pid;
	NETLINK_CB(skb).dst_group = dst_group;
	memcpy(NETLINK_CREDS(skb), &siocb->scm->creds, sizeof(struct ucred));

	err = -EFAULT;
	if (memcpy_fromiovec(skb_put(skb, len), msg->msg_iov, len)) {
		kfree_skb(skb);
		goto out;
	}

	err = security_netlink_send(sk, skb);
	if (err) {
		kfree_skb(skb);
		goto out;
	}

	if (dst_group) {
		atomic_inc(&skb->users);
		netlink_broadcast(sk, skb, dst_pid, dst_group, GFP_KERNEL);
	}
	err = netlink_unicast(sk, skb, dst_pid, msg->msg_flags&MSG_DONTWAIT);

out:
	scm_destroy(siocb->scm);
	return err;
}


asmlinkage long compat_sys_ptrace(compat_long_t request, compat_long_t pid,
				  compat_long_t addr, compat_long_t data)
{
	struct task_struct *child;
	long ret;

	if (request == PTRACE_TRACEME) {
		ret = ptrace_traceme();
		goto out;
	}

	child = ptrace_get_task_struct(pid);
	if (IS_ERR(child)) {
		ret = PTR_ERR(child);
		goto out;
	}

	if (request == PTRACE_ATTACH || request == PTRACE_SEIZE) {
		ret = ptrace_attach(child, request, addr, data);
		/*
		 * Some architectures need to do book-keeping after
		 * a ptrace attach.
		 */
		if (!ret)
			arch_ptrace_attach(child);
		goto out_put_task_struct;
	}

	ret = ptrace_check_attach(child, request == PTRACE_KILL ||
				  request == PTRACE_INTERRUPT);
	if (!ret)
		ret = compat_arch_ptrace(child, request, addr, data);

 out_put_task_struct:
	put_task_struct(child);
 out:
	return ret;
}


int bt_sock_recvmsg(struct kiocb *iocb, struct socket *sock,
				struct msghdr *msg, size_t len, int flags)
{
	int noblock = flags & MSG_DONTWAIT;
	struct sock *sk = sock->sk;
	struct sk_buff *skb;
	size_t copied;
	int err;

	BT_DBG("sock %p sk %p len %zu", sock, sk, len);

	if (flags & (MSG_OOB))
		return -EOPNOTSUPP;

	skb = skb_recv_datagram(sk, flags, noblock, &err);
	if (!skb) {
		if (sk->sk_shutdown & RCV_SHUTDOWN)
			return 0;
		return err;
	}

	msg->msg_namelen = 0;

	copied = skb->len;
	if (len < copied) {
		msg->msg_flags |= MSG_TRUNC;
		copied = len;
	}

	skb_reset_transport_header(skb);
	err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
	if (err == 0)
		sock_recv_ts_and_drops(msg, sk, skb);

	skb_free_datagram(sk, skb);

	return err ? : copied;
}


static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps)
{
	mutex_lock(&kvm->arch.vpit->pit_state.lock);
	memcpy(&kvm->arch.vpit->pit_state, ps, sizeof(struct kvm_pit_state));
	kvm_pit_load_count(kvm, 0, ps->channels[0].count, 0);
	mutex_unlock(&kvm->arch.vpit->pit_state.lock);
	return 0;
}


static int perf_swevent_add(struct perf_event *event, int flags)
{
	struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
	struct hw_perf_event *hwc = &event->hw;
	struct hlist_head *head;

	if (is_sampling_event(event)) {
		hwc->last_period = hwc->sample_period;
		perf_swevent_set_period(event);
	}

	hwc->state = !(flags & PERF_EF_START);

	head = find_swevent_head(swhash, event);
	if (!head) {
		/*
		 * We can race with cpu hotplug code. Do not
		 * WARN if the cpu just got unplugged.
		 */
		WARN_ON_ONCE(swhash->online);
		return -EINVAL;
	}

	hlist_add_head_rcu(&event->hlist_entry, head);
	perf_event_update_userpage(event);

	return 0;
}


void flush_tlb_page(struct vm_area_struct *vma, unsigned long start)
{
	struct mm_struct *mm = vma->vm_mm;

	preempt_disable();

	if (current->active_mm == mm) {
		if (current->mm)
			__flush_tlb_one(start);
		else
			leave_mm(smp_processor_id());
	}

	if (cpumask_any_but(mm_cpumask(mm), smp_processor_id()) < nr_cpu_ids)
		flush_tlb_others(mm_cpumask(mm), mm, start, 0UL);

	preempt_enable();
}