function sharingGroupPopulateOrganisations() {
	$('input[id=SharingGroupOrganisations]').val(JSON.stringify(organisations));
	$('.orgRow').remove();
	var id = 0;
	var html = '';
	organisations.forEach(function(org) {
		html = '
';
		html += '' + org.type + ' 	';
		html += '' + org.name + ' 	';
		html += '' + org.uuid + ' 	';
		html += '';
		if (org.removable == 1) {
			html += '<input id="orgExtend' + id + '" type="checkbox" onClick="sharingGroupExtendOrg(' + id + ')" ';
			if (org.extend) html+= 'checked';
			html += '></input>';
		} else {
			html += ''
		}
		html +='	';
		html += '';
		if (org.removable == 1) html += '';
		html += '
';
		$('#organisations_table tr:last').after(html);
		id++;
	});
}


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


  async fn(inputs, exits) {
    const { currentUser } = this.req;

    const { attachment, card, project } = await sails.helpers.attachments
      .getProjectPath(inputs.id)
      .intercept('pathNotFound', () => Errors.ATTACHMENT_NOT_FOUND);

    const isBoardMember = await sails.helpers.users.isBoardMember(currentUser.id, card.boardId);

    if (!isBoardMember) {
      const isProjectManager = await sails.helpers.users.isProjectManager(
        currentUser.id,
        project.id,
      );

      if (!isProjectManager) {
        throw Errors.ATTACHMENT_NOT_FOUND; // Forbidden
      }
    }

    if (!attachment.image) {
      throw Errors.ATTACHMENT_NOT_FOUND;
    }

    const filePath = path.join(
      sails.config.custom.attachmentsPath,
      attachment.dirname,
      'thumbnails',
      inputs.filename,
    );

    if (!fs.existsSync(filePath)) {
      throw Errors.ATTACHMENT_NOT_FOUND;
    }

    this.res.type(attachment.filename);
    this.res.set('Cache-Control', 'private, max-age=900'); // TODO: move to config

    return exits.success(fs.createReadStream(filePath));
  },


function set (obj, path, value) {
  if(!obj) throw new Error('libnested.set: first arg must be an object')
  if(isBasic(path)) return obj[path] = value
  for(var i = 0; i < path.length; i++)
    if(i === path.length - 1)
      obj[path[i]] = value
    else if(null == obj[path[i]])
      obj = (obj[path[i]] = isNonNegativeInteger(path[i+1]) ? [] : {})
    else if (!(isPrototypePolluted(path[i])))
      obj = obj[path[i]]
  return value
}


                            success: function(_result, _request){

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

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

                            },


Cache.prototype.set = function(key, value) {
  this._size >= this._maxSize && this.clear()
  if (!(key in this._values)) this._size++

  return (this._values[key] = value)
}


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

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


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


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

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

'+


static get lokadIdHex() { return "534c5000" }


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


						top  : Math.max(0, y - scrolltop + mh + height < wheight ? y + mh : (y - mh - height > 0 ? y - mh - height : y + mh)),
						left : Math.max(0, x - scrollleft + mw + width < wwidth  ? x + mw :  x - mw - width)
					};


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

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

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

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

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

            this.messageName = 'emailSent';

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

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

            this.createMessage();
        },

    });
});


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

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

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

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

            done(...arguments);
        };

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

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

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

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


    function (done) {
      cp.exec(gitApp + ' add ' + files, gitExtra, done);
    },


function ffprobe(file) {
    return new Promise((resolve, reject) => {
        if (!file)
            throw new Error('no file provided');
        fs_1.stat(file, (err, stats) => {
            if (err)
                throw err;
            child_process_1.exec('ffprobe -v quiet -print_format json -show_format -show_streams ' + file, (error, stdout, stderr) => {
                if (error)
                    return reject(error);
                if (!stdout)
                    return reject(new Error("can't probe file " + file));
                let ffprobed;
                try {
                    ffprobed = JSON.parse(stdout);
                }
                catch (err) {
                    return reject(err);
                }
                for (let i = 0; i < ffprobed.streams.length; i++) {
                    if (ffprobed.streams[i].codec_type === 'video')
                        ffprobed.video = ffprobed.streams[i];
                    if (ffprobed.streams[i].codec_type === 'audio' && ffprobed.streams[i].channels)
                        ffprobed.audio = ffprobed.streams[i];
                }
                resolve(ffprobed);
            });
        });
    });
}


NyanCat.prototype.drawScoreboard = function(){
  var stats = this.stats;
  var colors = Base.colors;

  function draw(color, n) {
    write(' ');
    write('\u001b[' + color + 'm' + n + '\u001b[0m');
    write('\n');
  }

  draw(colors.green, stats.passes);
  draw(colors.fail, stats.failures);
  draw(colors.pending, stats.pending);
  write('\n');

  this.cursorUp(this.numberOfLines);
};


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


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

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

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

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

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

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

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

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

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

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


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

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

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


function _showSelectDialog(title, label, options, button, callbackFcn, callbackArg, defaultValue) {
    var dialog = dialogs[title+label];
    if (dialog) {
        $("bgDialogDiv").show();
    }
    else {
        var fields = createElement("p", null, []);
	fields.appendChild(document.createTextNode(label));
        var select = createElement("select"); //, null, null, { cname: name } );
	fields.appendChild(select);
        var values = $H(options).keys();
        for (var i = 0; i < values.length; i++) {
            var option = createElement("option", null, null,
                                       { value: values[i] }, null, select);
            option.appendChild(document.createTextNode(options[values[i]]));
        }
        fields.appendChild(createElement("br"));

        fields.appendChild(createButton(null,
                                        button,
                                        callbackFcn.bind(select, callbackArg)));
	fields.appendChild(createButton(null,
                                        _("Cancel"),
                                        disposeDialog));
        dialog = createDialog(null,
                              title,
                              null,
                              fields,
                              "none");
        document.body.appendChild(dialog);
        dialogs[title+label] = dialog;
    }
    if (defaultValue)
	defaultOption = dialog.down('option[value="'+defaultValue+'"]').selected = true;
    if (Prototype.Browser.IE)
        jQuery('#bgDialogDiv').css('opacity', 0.4);
    jQuery(dialog).fadeIn('fast');
}


relatedTypeString: this.translateEntityType(this.entityType),
                iconHtml: this.getIconHtml(this.entityType, this.entityId)
            }, Dep.prototype.data.call(this));
        },

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

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

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

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

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


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

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


PostgreSQL.prototype.buildExpression = function(columnName, operator,
  operatorValue, propertyDefinition) {
  switch (operator) {
    case 'like':
      return new ParameterizedSQL(columnName + "::TEXT LIKE ? ESCAPE E'\\\\'",
        [operatorValue]);
    case 'ilike':
      return new ParameterizedSQL(columnName + "::TEXT ILIKE ? ESCAPE E'\\\\'",
        [operatorValue]);
    case 'nlike':
      return new ParameterizedSQL(columnName + "::TEXT NOT LIKE ? ESCAPE E'\\\\'",
        [operatorValue]);
    case 'nilike':
      return new ParameterizedSQL(columnName + "::TEXT NOT ILIKE ? ESCAPE E'\\\\'",
        [operatorValue]);
    case 'regexp':
      if (operatorValue.global)
        g.warn('{{PostgreSQL}} regex syntax does not respect the {{`g`}} flag');

      if (operatorValue.multiline)
        g.warn('{{PostgreSQL}} regex syntax does not respect the {{`m`}} flag');

      const regexOperator = operatorValue.ignoreCase ? ' ~* ?' : ' ~ ?';
      return new ParameterizedSQL(columnName + regexOperator,
        [operatorValue.source]);
    case 'contains':
      return new ParameterizedSQL(columnName + ' @> array[' + operatorValue.map((v) => `'${v}'`) + ']::'
        + propertyDefinition.postgresql.dataType);
    case 'match':
      return new ParameterizedSQL(`to_tsvector(${columnName}) @@ to_tsquery('${operatorValue}')`);
    default:
      // invoke the base implementation of `buildExpression`
      return this.invokeSuper('buildExpression', columnName, operator,
        operatorValue, propertyDefinition);
  }
};


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

            return data;
        }


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

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

  if (!this.config.strictVendor
      || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) {
    if (wantReply) {
      this._callbacks.push(function(had_err) {
        if (had_err) {
          return cb(had_err !== true
                    ? had_err
                    : new Error('Unable to disable future sessions'));
        }

        cb();
      });
    }

    return this._sshstream.openssh_noMoreSessions(wantReply);
  } else if (wantReply) {
    process.nextTick(function() {
      cb(new Error('strictVendor enabled and server is not OpenSSH or compatible version'));
    });
  }

  return true;
};


	get_DOM_row(row_pos) {
		var row_id = this.tr_id_mapping[row_pos];
		var tr = document.getElementById(row_id);
		return tr;
	}


  removeCustomField: function removeCustomField({ _id }) {
    check(_id, String)
    checkAuthentication(this)
    if (!CustomFields.findOne({ _id })) {
      throw new Meteor.Error('error-custom-field-not-found', 'Custom field not found', { method: 'removeCustomField' })
    }
    CustomFields.remove({ _id })
  },


            url: getPath() + "/shutdown",
            data: {"parameter":2},
            success: function success(data) {
                $("#spinner2").hide();
                $("#DialogContent").html(data.text);
                $("#DialogFinished").removeClass("hidden");
            }
        });
    });


        var record_messages = function (msg, opts) {
            console.log("HTML Sanitizer", msg, opts);
        };


elFinder.prototype.commands.opendir = function() {
	this.alwaysEnabled = true;

	this.getstate = function() {
		var sel = this.fm.selected(),
			cnt = sel.length,
			cwdWrapper;
		if (cnt !== 1) {
			return -1;
		}
		cwdWrapper = this.fm.getUI('cwd').parent();
		return cwdWrapper.hasClass('elfinder-search-result')? 0 : -1;
	}

	this.exec = function(hashes) {
		var fm    = this.fm,
			dfrd  = $.Deferred(),
			files = this.files(hashes),
			cnt   = files.length,
			hash, pcheck = null;

		if (!cnt || !files[0].phash) {
			return dfrd.reject();
		}

		hash = files[0].phash;
		if (!fm.file(hash)) {
			// parents check
			pcheck = fm.request({
				data   : {cmd  : 'parents', target : hash},
				syncOnFail : false
			});
		}
		// open folder
		$.when(pcheck)
		.done(function(data){
			fm.trigger('searchend', { noupdate: true });
			fm.request({
				data   : {cmd  : 'open', target : hash},
				notify : {type : 'open', cnt : 1, hideCnt : true},
				syncOnFail : false
			});
		});

		return dfrd;
	}

}


				cancel = function(e) {
					e.stopPropagation();
					dfrd.reject();
				},


  'unary+': function(argument, context) {
    return function(scope, locals, assign, inputs) {
      var arg = argument(scope, locals, assign, inputs);
      if (isDefined(arg)) {
        arg = +arg;
      } else {
        arg = 0;
      }
      return context ? {value: arg} : arg;
    };
  },


HTML.prototype.testURL = function(test){
  return '?grep=' + encodeURIComponent(test.fullTitle());
};


function PKAuthContext(stream, username, service, method, pkInfo, cb) {
  AuthContext.call(this, stream, username, service, method, cb);

  this.key = { algo: pkInfo.keyAlgo, data: pkInfo.key };
  this.signature = pkInfo.signature;
  var sigAlgo;
  if (this.signature) {
    // TODO: move key type checking logic to ssh2-streams
    switch (pkInfo.keyAlgo) {
      case 'ssh-rsa':
      case 'ssh-dss':
        sigAlgo = 'sha1';
        break;
      case 'ssh-ed25519':
        sigAlgo = null;
        break;
      case 'ecdsa-sha2-nistp256':
        sigAlgo = 'sha256';
        break;
      case 'ecdsa-sha2-nistp384':
        sigAlgo = 'sha384';
        break;
      case 'ecdsa-sha2-nistp521':
        sigAlgo = 'sha512';
        break;
    }
  }
  this.sigAlgo = sigAlgo;
  this.blob = pkInfo.blob;
}


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


    var onlink = function () {
      if (win32) return next() // skip links on win for now before it can be tested
      xfs.unlink(name, function () {
        var srcpath = path.resolve(cwd, header.linkname)

        xfs.link(srcpath, name, function (err) {
          if (err && err.code === 'EPERM' && opts.hardlinkAsFilesFallback) {
            stream = xfs.createReadStream(srcpath)
            return onfile()
          }

          stat(err)
        })
      })
    }


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

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

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


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


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

	/**
	 * Command options
	 *
	 * @type  Object
	 */
	this.options = {ui : 'sortbutton'};

	fm.bind('open sortchange', function() {
		self.variants = [];
		$.each(fm.sortRules, function(name, value) {
			var sort = {
					type  : name,
					order : name == fm.sortType ? fm.sortOrder == 'asc' ? 'desc' : 'asc' : fm.sortOrder
				};
			var arr = name == fm.sortType ? (sort.order == 'asc'? 'n' : 's') : '';
			self.variants.push([sort, (arr? '' : '') + ' ' + fm.i18n('sort'+name)]);
		});
	});

	fm.bind('open sortchange viewchange search searchend', function() {
		timer && clearTimeout(timer);
		timer = setTimeout(function(){
			var cols = $(fm.cwd).find('div.elfinder-cwd-wrapper-list table');
			if (cols.length) {
				$.each(fm.sortRules, function(name, value) {
					var td = cols.find('thead tr td.elfinder-cwd-view-th-'+name);
					if (td.length) {
						var current = ( name == fm.sortType),
						sort = {
							type  : name,
							order : current ? fm.sortOrder == 'asc' ? 'desc' : 'asc' : fm.sortOrder
						},arr;
						if (current) {
							td.addClass('ui-state-active');
							arr = fm.sortOrder == 'asc' ? 'n' : 's';
							$('').appendTo(td);
						}
						$(td).on('click', function(e){
							e.stopPropagation();
							self.exec([], sort);
						})
						.hover(function() {
							$(this).addClass('ui-state-hover');
						},function() {
							$(this).removeClass('ui-state-hover');
						});
					}

				});
			}
		}, 100);
	});

	this.getstate = function() {
		return 0;
	};

	this.exec = function(hashes, sortopt) {
		var fm = this.fm,
			sort = $.extend({
				type  : fm.sortType,
				order : fm.sortOrder,
				stick : fm.sortStickFolders
			}, sortopt);

		this.fm.setSort(sort.type, sort.order, sort.stick);
		return $.Deferred().resolve();
	};

};


Suite.prototype.fullTitle = function(){
  if (this.parent) {
    var full = this.parent.fullTitle();
    if (full) return full + ' ' + this.title;
  }
  return this.title;
};


                    function register_some_node(callback) {

                        session.registerNodes(nodesToRegister, function (err, _registeredNodeIds) {
                            if (err) {
                                return callback(err);
                            }
                            registeredNodeIds = _registeredNodeIds;
                            callback();
                        });
                    },


	_mouseStop: function(event, noPropagation) {

		if(!event) {
			return;
		}

		//If we are using droppables, inform the manager about the drop
		if ($.ui.ddmanager && !this.options.dropBehaviour) {
			$.ui.ddmanager.drop(this, event);
		}

		if(this.options.revert) {
			var that = this,
				cur = this.placeholder.offset(),
				axis = this.options.axis,
				animation = {};

			if ( !axis || axis === "x" ) {
				animation.left = cur.left - this.offset.parent.left - this.margins.left + (this.offsetParent[0] === this.document[0].body ? 0 : this.offsetParent[0].scrollLeft);
			}
			if ( !axis || axis === "y" ) {
				animation.top = cur.top - this.offset.parent.top - this.margins.top + (this.offsetParent[0] === this.document[0].body ? 0 : this.offsetParent[0].scrollTop);
			}
			this.reverting = true;
			$(this.helper).animate( animation, parseInt(this.options.revert, 10) || 500, function() {
				that._clear(event);
			});
		} else {
			this._clear(event, noPropagation);
		}

		return false;

	},


              updatedAt: new Date(),
              recentMessage: message.owner.fullname + ': ' + message.body
            })

            var $injector = angular.injector(['ng', 'trudesk'])
            $injector.invoke([
              '$compile',
              '$rootScope',
              function ($compile, $rootScope) {
                var $scope = convoUL.prepend(newLI).scope()
                $compile(convoUL)($scope || $rootScope)
                $rootScope.$digest()
              }
            ])
          }
        }

        UIKit.$html.trigger('changed.uk.dom')
        helpers.scrollToBottom($messageScroller)
      })


function bindJQuery() {
  var originalCleanData;

  if (bindJQueryFired) {
    return;
  }

  // bind to jQuery if present;
  var jqName = jq();
  jQuery = isUndefined(jqName) ? window.jQuery :   // use jQuery (if present)
           !jqName             ? undefined     :   // use jqLite
                                 window[jqName];   // use jQuery specified by `ngJq`

  // Use jQuery if it exists with proper functionality, otherwise default to us.
  // Angular 1.2+ requires jQuery 1.7+ for on()/off() support.
  // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older
  // versions. It will not work for sure with jQuery <1.7, though.
  if (jQuery && jQuery.fn.on) {
    jqLite = jQuery;
    extend(jQuery.fn, {
      scope: JQLitePrototype.scope,
      isolateScope: JQLitePrototype.isolateScope,
      controller: JQLitePrototype.controller,
      injector: JQLitePrototype.injector,
      inheritedData: JQLitePrototype.inheritedData
    });

    // All nodes removed from the DOM via various jQuery APIs like .remove()
    // are passed through jQuery.cleanData. Monkey-patch this method to fire
    // the $destroy event on all removed nodes.
    originalCleanData = jQuery.cleanData;
    jQuery.cleanData = function(elems) {
      var events;
      for (var i = 0, elem; (elem = elems[i]) != null; i++) {
        events = jQuery._data(elem, 'events');
        if (events && events.$destroy) {
          jQuery(elem).triggerHandler('$destroy');
        }
      }
      originalCleanData(elems);
    };
  } else {
    jqLite = JQLite;
  }

  angular.element = jqLite;

  // Prevent double-proxying.
  bindJQueryFired = true;
}


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


    context.describe.only = function(title, fn){
      var suite = context.describe(title, fn);
      mocha.grep(suite.fullTitle());
      return suite;
    };


function updateRegister() {
    adapter.log.info('Request actual repository...');
    adapter.getForeignObject('system.config', (err, data) => {
        if (data && data.common) {
            adapter.sendToHost(adapter.host, 'getRepository', {
                repo:   data.common.activeRepo,
                update: true
            }, _repository => {
                if (_repository === 'permissionError') {
                    adapter.log.error('May not read "getRepository"');
                } else {
                    adapter.log.info('Repository received successfully.');

                    socket && socket.repoUpdated();
                }
            });
        }
    });
}


						fm.trigger('unlockfiles', {files : helper.data('files'), helper: helper});
					},


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

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

  if (!this.config.strictVendor
      || (this.config.strictVendor && RE_OPENSSH.test(this._remoteVer))) {
    if (wantReply) {
      this._callbacks.push(function(had_err) {
        if (had_err) {
          return cb(had_err !== true
                    ? had_err
                    : new Error('Unable to unbind on ' + socketPath));
        }
        delete self._forwardingUnix[socketPath];
        cb();
      });
    }

    return this._sshstream.openssh_cancelStreamLocalForward(socketPath,
                                                            wantReply);
  } else if (wantReply) {
    process.nextTick(function() {
      cb(new Error('strictVendor enabled and server is not OpenSSH or compatible version'));
    });
  }

  return true;
};


var AST = function AST(lexer, options) {
  this.lexer = lexer;
  this.options = options;
};


        success:function (data, textStatus) {
            showMessage('success', 'Homepage set.');
            $('#setHomePage').addClass('orange');
        },


html: function (element, attrs, content) {
				return '
' + content + '
';
			},


		cache = function(data) {
			var l = data.length, f, i;

			for (i = 0; i < l; i++) {
				f = data[i];
				if (f.name && f.hash && f.mime) {
					if (!f.phash) {
						var name = 'volume_'+f.name,
							i18 = self.i18n(name);

						if (name != i18) {
							f.i18 = i18;
						}

						// set disabledCmds, tmbUrls for each volume
						if (f.volumeid) {
							f.disabled && (self.disabledCmds[f.volumeid] = f.disabled);
							if (f.tmbUrl) {
								self.tmbUrls[f.volumeid] = f.tmbUrl;
							}
							self.roots[f.volumeid] = f.hash;
						}
					}
					files[f.hash] = f;
				}
			}
		},


    context.it.only = function(title, fn){
      var test = context.it(title, fn);
      var reString = '^' + utils.escapeRegexp(test.fullTitle()) + '$';
      mocha.grep(new RegExp(reString));
      return test;
    };


  { run: function() {
      var client;
      var server;
      var r;

      r = setup(
        this,
        { username: USER,
          privateKey: CLIENT_KEY_RSA_RAW
        },
        { hostKeys: [HOST_KEY_RSA] }
      );
      client = r.client;
      server = r.server;

      server.on('connection', function(conn) {
        conn.on('authentication', function(ctx) {
          if (ctx.method === 'none')
            return ctx.reject();
          assert(ctx.method === 'publickey',
                 makeMsg('Unexpected auth method: ' + ctx.method));
          assert(ctx.username === USER,
                 makeMsg('Unexpected username: ' + ctx.username));
          assert(ctx.key.algo === 'ssh-rsa',
                 makeMsg('Unexpected key algo: ' + ctx.key.algo));
          assert.deepEqual(CLIENT_KEY_RSA.getPublicSSH(),
                           ctx.key.data,
                           makeMsg('Public key mismatch'));
          if (ctx.signature) {
            assert(CLIENT_KEY_RSA.verify(ctx.blob, ctx.signature) === true,
                   makeMsg('Could not verify PK signature'));
            ctx.accept();
          } else
            ctx.accept();
        }).on('ready', function() {
          conn.end();
        });
      });
    },


function HostbasedAuthContext(stream, username, service, method, pkInfo, cb) {
  AuthContext.call(this, stream, username, service, method, cb);

  this.key = { algo: pkInfo.keyAlgo, data: pkInfo.key };
  this.signature = pkInfo.signature;
  var sigAlgo;
  if (this.signature) {
    // TODO: move key type checking logic to ssh2-streams
    switch (pkInfo.keyAlgo) {
      case 'ssh-rsa':
      case 'ssh-dss':
        sigAlgo = 'sha1';
        break;
      case 'ssh-ed25519':
        sigAlgo = null;
        break;
      case 'ecdsa-sha2-nistp256':
        sigAlgo = 'sha256';
        break;
      case 'ecdsa-sha2-nistp384':
        sigAlgo = 'sha384';
        break;
      case 'ecdsa-sha2-nistp521':
        sigAlgo = 'sha512';
        break;
    }
  }
  this.sigAlgo = sigAlgo;
  this.blob = pkInfo.blob;
  this.localHostname = pkInfo.localHostname;
  this.localUsername = pkInfo.localUsername;
}


    function checkDependencies(dependencies) {
        if (!dependencies) return '';
        // like [{"js-controller": ">=0.10.1"}]
        var adapters;
        if (dependencies instanceof Array) {
            adapters = {};
            for (var a = 0; a < dependencies.length; a++) {
                if (typeof dependencies[a] === 'string') continue;
                for (var b in dependencies[a]) {
                    if (dependencies[a].hasOwnProperty(b)) {
                        adapters[b] = dependencies[a][b];
                    }
                }
            }
        } else {
            adapters = dependencies;
        }

        for (var adapter in adapters) {
            if (adapters.hasOwnProperty(adapter)) {
                if (adapter === 'js-controller') {
                    if (!semver.satisfies(that.main.objects['system.host.' + that.main.currentHost].common.installedVersion, adapters[adapter])) return _('Invalid version of %s. Required %s', adapter, adapters[adapter]);
                } else {
                    if (!that.main.objects['system.adapter.' + adapter] || !that.main.objects['system.adapter.' + adapter].common || !that.main.objects['system.adapter.' + adapter].common.installedVersion) return _('No version of %s', adapter);
                    if (!semver.satisfies(that.main.objects['system.adapter.' + adapter].common.installedVersion, adapters[adapter])) return _('Invalid version of %s', adapter);
                }
            }
        }
        return '';
    }


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


StyleFormatPanel.prototype.addEffects = function(div)
{
	var ui = this.editorUi;
	var editor = ui.editor;
	var graph = editor.graph;
	var ss = ui.getSelectionState();

	div.style.paddingTop = '4px';
	div.style.paddingBottom = '0px';

	var table = document.createElement('table');

	table.style.width = '210px';
	table.style.fontWeight = 'bold';
	table.style.tableLayout = 'fixed';
	var tbody = document.createElement('tbody');
	var row = document.createElement('tr');
	row.style.padding = '0px';
	var left = document.createElement('td');
	left.style.padding = '0px';
	left.style.width = '50%';
	left.setAttribute('valign', 'top');

	var right = left.cloneNode(true);
	right.style.paddingLeft = '8px';
	row.appendChild(left);
	row.appendChild(right);
	tbody.appendChild(row);
	table.appendChild(tbody);
	div.appendChild(table);

	var current = left;
	var count = 0;

	var addOption = mxUtils.bind(this, function(label, key, defaultValue)
	{
		var opt = this.createCellOption(label, key, defaultValue);
		opt.style.width = '100%';
		current.appendChild(opt);
		current = (current == left) ? right : left;
		count++;
	});

	var listener = mxUtils.bind(this, function(sender, evt, force)
	{
		ss = ui.getSelectionState();

		left.innerHTML = '';
		right.innerHTML = '';
		current = left;

		if (ss.rounded)
		{
			addOption(mxResources.get('rounded'), mxConstants.STYLE_ROUNDED, 0);
		}

		if (ss.swimlane)
		{
			addOption(mxResources.get('divider'), 'swimlaneLine', 1);
		}

		if (!ss.containsImage)
		{
			addOption(mxResources.get('shadow'), mxConstants.STYLE_SHADOW, 0);
		}

		if (ss.glass)
		{
			addOption(mxResources.get('glass'), mxConstants.STYLE_GLASS, 0);
		}

		addOption(mxResources.get('sketch'), 'sketch', 0);
	});

	graph.getModel().addListener(mxEvent.CHANGE, listener);
	this.listeners.push({destroy: function() { graph.getModel().removeListener(listener); }});
	listener();

	return div;
}


export const parseUrl = function(url) {
  const props = ['protocol', 'hostname', 'port', 'pathname', 'search', 'hash', 'host'];

  // add the url to an anchor and let the browser parse the URL
  let a = document.createElement('a');

  a.href = url;

  // IE8 (and 9?) Fix
  // ie8 doesn't parse the URL correctly until the anchor is actually
  // added to the body, and an innerHTML is needed to trigger the parsing
  const addToBody = (a.host === '' && a.protocol !== 'file:');
  let div;

  if (addToBody) {
    div = document.createElement('div');
    div.innerHTML = `<a href="${url}"></a>`;
    a = div.firstChild;
    // prevent the div from affecting layout
    div.setAttribute('style', 'display:none; position:absolute;');
    document.body.appendChild(div);
  }

  // Copy the specific URL properties to a new object
  // This is also needed for IE8 because the anchor loses its
  // properties when it's removed from the dom
  const details = {};

  for (let i = 0; i < props.length; i++) {
    details[props[i]] = a[props[i]];
  }

  // IE9 adds the port to the host property unlike everyone else. If
  // a port identifier is added for standard ports, strip it.
  if (details.protocol === 'http:') {
    details.host = details.host.replace(/:80$/, '');
  }

  if (details.protocol === 'https:') {
    details.host = details.host.replace(/:443$/, '');
  }

  if (!details.protocol) {
    details.protocol = window.location.protocol;
  }

  if (addToBody) {
    document.body.removeChild(div);
  }

  return details;
};


function main() {
	var shortdesc = mw.config.get( 'wgShortDesc' ),
		tagline;

	if ( shortdesc ) {
		tagline = document.getElementById( 'siteSub' );
		// Wikipedia uses shortdescription class
		// Added for gadgets and extension compatibility
		tagline.classList.add( 'ext-shortdesc', 'shortdescription' );
		tagline.innerHTML = shortdesc;
	}
}


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


const meta = async (req, res) => {
  try {
    logger.debug('URL file import handler running', null, req.id)
    const { debug } = req.companion.options
    if (!validateURL(req.body.url, debug)) {
      logger.debug('Invalid request body detected. Exiting url meta handler.', null, req.id)
      return res.status(400).json({ error: 'Invalid request body' })
    }

    const urlMeta = await getURLMeta(req.body.url, !debug)
    return res.json(urlMeta)
  } catch (err) {
    logger.error(err, 'controller.url.meta.error', req.id)
    // @todo send more meaningful error message and status code to client if possible
    return res.status(err.status || 500).json({ message: 'failed to fetch URL metadata' })
  }
}


export default function parseUrl(href, part, parseQuery) {
    href = String(href);
    var match = href.match(_parse_url_exp)
        , map = _parse_url_map
        , i, ret = false
        ;
    if (match) {
        if (part && part in map) {
            ret = match[map[part]] || NIL;
            if (part == 'pathname') {
                if (!ret) ret = '/';
            }
            if (parseQuery && part == 'query') {
                ret = toObject(ret || NIL);
            }
        }
        else {
            let _ = this;
            if(typeof _ != 'function') {
                _ = typeof URL == 'function' && URL.createObjectURL ? URL : Object;
                ret = new _(href);
                // ret.toString = function _uri_to_string_() {
                //     return fromLocation(this);
                // };
            }
            else {
                ret = new _(); // URLJS() constructor?
            }

            for (i in map) if (map.hasOwnProperty(i)) {
                ret[i] = match[map[i]] || NIL;
            }
            if (part && part in ret) return ret[part];

            if (!ret.pathname) ret.pathname = '/';
            if (!ret.path) ret.path = ret.pathname + ret.search;
            if (!ret.origin) ret.origin = ret.protocol + '//' + ret.host;
            if (!ret.domain) ret.domain = getDomainName(ret.hostname);
            if (parseQuery) ret.query = toObject(ret.query || NIL);
            if (!ret.origin) ret.href = String(href); // ??? may need some parse

            if (part) ret = ret[part];
        }
    }
    return ret;
}


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


    MediaFinder.prototype.dispose = function() {
        this.$el.off('click', '.find-button', this.proxy(this.onClickFindButton))
        this.$el.off('click', '.find-remove-button', this.proxy(this.onClickRemoveButton))
        this.$el.off('dispose-control', this.proxy(this.dispose))
        this.$el.removeData('oc.mediaFinder')

        this.$findValue = null
        this.$el = null

        // In some cases options could contain callbacks,
        // so it's better to clean them up too.
        this.options = null

        BaseProto.dispose.call(this)
    }


  key.verify = function(digest, signature, scheme) {
    if(typeof scheme === 'string') {
      scheme = scheme.toUpperCase();
    } else if(scheme === undefined) {
      scheme = 'RSASSA-PKCS1-V1_5';
    }

    if(scheme === 'RSASSA-PKCS1-V1_5') {
      scheme = {
        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;
        }
      };
    } else if(scheme === 'NONE' || scheme === 'NULL' || scheme === null) {
      scheme = {
        verify: function(digest, d) {
          // remove padding
          d = _decodePkcs1_v1_5(d, key, true);
          return digest === d;
        }
      };
    }

    // do rsa decryption w/o any decoding, then verify -- which does decoding
    var d = pki.rsa.decrypt(signature, key, true, false);
    return scheme.verify(digest, d, key.n.bitLength());
  };


				update: function(container, p) {

					// 1. If a className is set as 'placeholder option, we don't force sizes - the class is responsible for that
					// 2. The option 'forcePlaceholderSize can be enabled to force it even if a class name is specified
					if(className && !o.forcePlaceholderSize) {
						return;
					}

					//If the element doesn't have a actual height by itself (without styles coming from a stylesheet), it receives the inline height from the dragged item
					if(!p.height()) { p.height(that.currentItem.innerHeight() - parseInt(that.currentItem.css("paddingTop")||0, 10) - parseInt(that.currentItem.css("paddingBottom")||0, 10)); }
					if(!p.width()) { p.width(that.currentItem.innerWidth() - parseInt(that.currentItem.css("paddingLeft")||0, 10) - parseInt(that.currentItem.css("paddingRight")||0, 10)); }
				}


function authenticate (keys, key) {
  return keys.findIndex((a) => compare(a, key)) !== -1
}


function getValueOf(value) {
  return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);
}


show_status: function() {
    return ''
      + this.get('status') + (this.get("is_unmanaged") ? " (unmanaged)" : "")
      + '';
  }.property("status_style", "disabled"),


          prefix: current.literal(sql.quoteTable.call(current.dialect.QueryGenerator, { tableName: 'User' }))
        }, {
          mariadb: "(json_unquote(json_extract(`User`.`data`,'$.nested.attribute')) = 'value' AND json_unquote(json_extract(`User`.`data`,'$.nested.prop')) != 'None')",
          mysql: "((`User`.`data`->>'$.\\\"nested\\\".\\\"attribute\\\"') = 'value' AND (`User`.`data`->>'$.\\\"nested\\\".\\\"prop\\\"') != 'None')",
          postgres: "((\"User\".\"data\"#>>'{nested,attribute}') = 'value' AND (\"User\".\"data\"#>>'{nested,prop}') != 'None')",
          sqlite: "(json_extract(`User`.`data`, '$.nested.attribute') = 'value' AND json_extract(`User`.`data`, '$.nested.prop') != 'None')"
        });


      git.commit = function (files, message, newVer, tagName, callback) {
        assert.equal(message, 'Message');
        assert.equal(newVer, '1.0.0');
        assert.equal(files[0], expectedPath);
        assert.equal(tagName, 'v1.0.0');
        return callback(null);
      };


async function httpProxy (fastify, opts) {
  if (!opts.upstream) {
    throw new Error('upstream must be specified')
  }

  const preHandler = opts.preHandler || opts.beforeHandler
  const rewritePrefix = opts.rewritePrefix || ''

  const fromOpts = Object.assign({}, opts)
  fromOpts.base = opts.upstream
  fromOpts.prefix = undefined

  const oldRewriteHeaders = (opts.replyOptions || {}).rewriteHeaders
  const replyOpts = Object.assign({}, opts.replyOptions, {
    rewriteHeaders
  })
  fromOpts.rewriteHeaders = rewriteHeaders

  fastify.register(From, fromOpts)

  if (opts.proxyPayloads !== false) {
    fastify.addContentTypeParser('application/json', bodyParser)
    fastify.addContentTypeParser('*', bodyParser)
  }

  function rewriteHeaders (headers) {
    const location = headers.location
    if (location) {
      headers.location = location.replace(rewritePrefix, fastify.prefix)
    }
    if (oldRewriteHeaders) {
      headers = oldRewriteHeaders(headers)
    }
    return headers
  }

  function bodyParser (req, payload, done) {
    done(null, payload)
  }

  fastify.route({
    url: '/',
    method: httpMethods,
    preHandler,
    config: opts.config || {},
    handler
  })
  fastify.route({
    url: '/*',
    method: httpMethods,
    preHandler,
    config: opts.config || {},
    handler
  })

  function handler (request, reply) {
    let dest = request.raw.url
    dest = dest.replace(this.prefix, rewritePrefix)
    reply.from(dest || '/', replyOpts)
  }

  if (opts.websocket) {
    setupWebSocketProxy(fastify, opts)
  }
}


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


          this.goto_url('export', { _source: this.env.source, _gid: this.env.group, _cid: this.contact_list.get_selection().join(',') });
        }
        break;

      case 'upload-photo':
        this.upload_contact_photo(props || this.gui_objects.uploadform);
        break;

      case 'delete-photo':
        this.replace_contact_photo('-del-');
        break;

      // user settings commands
      case 'preferences':
      case 'identities':
      case 'responses':
      case 'folders':
        this.goto_url('settings/' + command);
        break;

      case 'undo':
        this.http_request('undo', '', this.display_message('', 'loading'));
        break;

      // unified command call (command name == function name)
      default:
        var func = command.replace(/-/g, '_');
        if (this[func] && typeof this[func] === 'function') {
          ret = this[func](props, obj, event);
        }
        break;
    }

    if (!aborted && this.triggerEvent('after'+command, props) === false)
      ret = false;
    this.triggerEvent('actionafter', { props:props, action:command, aborted:aborted });

    return ret === false ? false : obj ? false : true;
  };


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


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


Graph.prototype.getTooltipForCell = function(cell)
{
	var tip = '';

	if (mxUtils.isNode(cell.value))
	{
		var tmp = null;

		if (Graph.translateDiagram && Graph.diagramLanguage != null)
		{
			tmp = cell.value.getAttribute('tooltip_' + Graph.diagramLanguage);
		}

		if (tmp == null)
		{
			tmp = cell.value.getAttribute('tooltip');
		}

		if (tmp != null)
		{
			if (tmp != null && this.isReplacePlaceholders(cell))
			{
				tmp = this.replacePlaceholders(cell, tmp);
			}

			tip = this.sanitizeHtml(tmp);
		}
		else
		{
			var ignored = this.builtInProperties;
			var attrs = cell.value.attributes;
			var temp = [];

			// Hides links in edit mode
			if (this.isEnabled())
			{
				ignored.push('linkTarget');
				ignored.push('link');
			}

			for (var i = 0; i < attrs.length; i++)
			{
				if (mxUtils.indexOf(ignored, attrs[i].nodeName) < 0 && attrs[i].nodeValue.length > 0)
				{
					temp.push({name: attrs[i].nodeName, value: attrs[i].nodeValue});
				}
			}

			// Sorts by name
			temp.sort(function(a, b)
			{
				if (a.name  b.name)
				{
					return 1;
				}
				else
				{
					return 0;
				}
			});

			for (var i = 0; i < temp.length; i++)
			{
				if (temp[i].name != 'link' || !this.isCustomLink(temp[i].value))
				{
					tip += ((temp[i].name != 'link') ? '' + temp[i].name + ': ' : '') +
						mxUtils.htmlEntities(temp[i].value) + '\n';
				}
			}

			if (tip.length > 0)
			{
				tip = tip.substring(0, tip.length - 1);

				if (mxClient.IS_SVG)
				{
					tip = '
' +
						tip + '
';
				}
			}
		}
	}

	return tip;
};


Channel.prototype.exit = function(name, coreDumped, msg) {
  if (!this.server)
    throw new Error('Server-only method called in client mode');

  if (this.type === 'session'
      && this.writable
      && this.outgoing.state === 'open') {
    if (typeof name === 'number')
      return this._client._sshstream.exitStatus(this.outgoing.id, name);
    else {
      return this._client._sshstream.exitSignal(this.outgoing.id,
                                                name,
                                                coreDumped,
                                                msg);
    }
  }

  return true;
};


function isObject(value) {
  // http://jsperf.com/isobject4
  return value !== null && typeof value === 'object';
}


    return function randomCookie() {
      crypto.randomFillSync(buffer, 0, 16);
      return buffer.toString('hex');
    };


                qtip: Tine.Tinebase.common.doubleEncode(attr.name.name)
            });
        }

        // copy 'real' data to a node record NOTE: not a full record as we have no record reader here
        var nodeData = Ext.copyTo({}, attr, Tine.Filemanager.Model.Node.getFieldNames());
        attr.nodeRecord = new Tine.Filemanager.Model.Node(nodeData);
    },


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


$.fn.elfinder = function(o) {

	if (o == 'instance') {
		return this.getElFinder();
	}

	return this.each(function() {

		var cmd = typeof(o) == 'string' ? o : '';
		if (!this.elfinder) {
			new elFinder(this, typeof(o) == 'object' ? o : {})
		}

		switch(cmd) {
			case 'close':
			case 'hide':
				this.elfinder.hide();
				break;

			case 'open':
			case 'show':
				this.elfinder.show();
				break;

			case'destroy':
				this.elfinder.destroy();
				break;
		}

	})
}


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

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

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

		document.body.appendChild(div);

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

		document.body.removeChild(div);
	};


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


function getDatesFromQuerystring(a){var b=[],c;if(void 0!=a){a=a.split("&");for(var e=0;e<a.length;e++)c=a[e].split("="),b.push(c[1]),b[c[0]]=c[1]}return b}function match_class_prefix(a,b){for(var c=b.prop("class").split(" "),e=new RegExp("^"+a+"(.+)","g"),d=0;d<c.length;d++){var f=e.exec(c[d]);if(null!==f)return f[1]}}


    var actionDown = function(e) {
        if (e.target.tagName == 'H2') {
            if (e.target.parentNode.classList.contains('selected')) {
                e.target.parentNode.classList.remove('selected');
                localStorage.setItem('jmenu-' + e.target.parentNode.getAttribute('data-id'), 0);
            } else {
                e.target.parentNode.classList.add('selected');
                localStorage.setItem('jmenu-' + e.target.parentNode.getAttribute('data-id'), 1);
            }
        } else if (e.target.tagName == 'A') {
            // Mark link as selected
            obj.select(e.target);
        }
    }


function isString(value) {return typeof value === 'string';}


  value: function(value, context) {
    return function() { return context ? {context: undefined, name: undefined, value: value} : value; };
  },


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


function loadSessionsTable(sessions) {
  $.each(sessions, function(index, session) {
    $("#interactive-sessions .sessions-table-body").append(
      "<tr>" +
        tdWrap(uiLink("session/" + session.id, session.id)) +
        tdWrap(appIdLink(session)) +
        tdWrap(session.name) +
        tdWrap(session.owner) +
        tdWrap(session.proxyUser) +
        tdWrap(session.kind) +
        tdWrap(session.state) +
        tdWrap(logLinks(session, "session")) +
        "</tr>"
    );
  });
}


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

  var self = this;

  // start an SFTP session
  return openChannel(this, 'session', function(err, chan) {
    if (err)
      return cb(err);

    reqSubsystem(chan, 'sftp', function(err, stream) {
      if (err)
        return cb(err);

      var serverIdentRaw = self._sshstream._state.incoming.identRaw;
      var cfg = { debug: self.config.debug };
      var sftp = new SFTPStream(cfg, serverIdentRaw);

      function onError(err) {
        sftp.removeListener('ready', onReady);
        stream.removeListener('exit', onExit);
        cb(err);
      }

      function onReady() {
        sftp.removeListener('error', onError);
        stream.removeListener('exit', onExit);
        cb(undefined, new SFTPWrapper(sftp));
      }

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

      sftp.once('error', onError)
          .once('ready', onReady)
          .once('close', function() {
            stream.end();
          });

      // OpenSSH server sends an exit-status if there was a problem spinning up
      // an sftp server child process, so we listen for that here in order to
      // properly raise an error.
      stream.once('exit', onExit);

      sftp.pipe(stream).pipe(sftp);
    });
  });
};


delObject:      function ($tree, id, callback) {
            var leaf = $tree ? $tree.selectId('getTreeInfo', id) : null;
            if (main.objects[id]) {
                if (leaf && leaf.children) {
                    // ask if only object must be deleted or just this one
                    main.confirmMessage(_('Do you want to delete just one object or all children of %s too?', id), null, 'help_outline', [_('_All'), _('Only one'), _('Cancel')], function (result) {
                        // If all
                        if (result === 0) {
                            main._delObjects(id, true, callback);
                        } else
                        // if only one object
                        if (result === 1) {
                            main._delObjects(id, false, callback);
                        } // else do nothing
                    });
                } else {
                    main.confirmMessage(_('Are you sure to delete %s?', id), null, 'help_outline', function (result) {
                        // If all
                        if (result) main._delObjects(id, true, callback);
                    });
                }
            } else if (leaf && leaf.children) {
                main.confirmMessage(_('Are you sure to delete all children of %s?', id), null, 'help_outline', function (result) {
                    // If all
                    if (result) main._delObjects(id, true, callback);
                });
            } else {
                main.showMessage(_('Object "%s" does not exists. Update the page.', id), _('Error'), 'help_outline', function (result) {
                    // If all
                    if (result) main._delObjects(id, true, callback);
                });
            }
        }


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


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


function encodeUriSegment(val) {
  return encodeUriQuery(val, true).
             replace(/%26/gi, '&').
             replace(/%3D/gi, '=').
             replace(/%2B/gi, '+');
}


  this.goto_url = function(action, query, lock)
  {
    this.redirect(this.url(action, query), lock);
  };


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


  'test delete': function () {
    var obj = {};
    obj.cool = {};
    obj.cool.aid = 'rocks';
    obj.cool.hello = ['world'];
    dot.delete(obj, 'cool.aid');
    dot.delete(obj, 'cool.hello.0');
    assert(!obj.cool.hasOwnProperty('aid'))
    assert(obj.cool.hello.length == 0);
  }


V,X,"shape=image;noLabel=1;verticalAlign=top;aspect=fixed;imageAspect=0;image="+b.convertDataUri(W)+";"),M.setAttributeForCell(p,"plantUmlData",JSON.stringify({data:U,format:Q},null,2))}finally{M.getModel().endUpdate()}null!=p&&(M.setSelectionCell(p),M.scrollCellToVisible(p))},M=b.editor.graph,n="plantUmlTxt"==x?"txt":"plantUmlPng"==x?"png":"svg";"@startuml\nskinparam shadowing false\nAlice -> Bob: Authentication Request\nBob --\x3e Alice: Authentication Response\n\nAlice -> Bob: Another authentication Request\nAlice <-- Bob: Another authentication Response\n@enduml"==


  _extendedFormatting(str) {
    const zeroTo99 = '0[0-9]|[1-9][0-9]';
    const colorRe = new RegExp('\x03(' + zeroTo99 + ')(?:,(' + zeroTo99 + '))?([^\x03]*)', 'g');

    return str.replace(colorRe, (all, fg, bg, text) => text).replace(/[\x02\x03\x1d\x1f\x1e\x11\x16\x0f]/g, '');
  }


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


exports.json = function(req, res, files){
  files = JSON.stringify(files);
  res.setHeader('Content-Type', 'application/json');
  res.setHeader('Content-Length', files.length);
  res.end(files);
};


				done: function(fm, data){
					var self = this;
					if (data.mode == 'makebtn') {
						self.inputs.host.find('span').removeClass("elfinder-info-spinner");
						self.inputs.host.find('input').hover(function(){$(this).toggleClass("ui-state-hover");});
						self.inputs.host[1].value = "";
					} else {
						self.inputs.host.find('span').removeClass("elfinder-info-spinner");
						self.inputs.host.find('span').html("Dropbox.com");
						self.inputs.host[1].value = "dropbox";
						self.inputs.user.val("done");
						self.inputs.pass.val("done");
					}
				}


  function tryNextAgentKey() {
    if (curAuth === 'agent') {
      if (agentKeyPos >= agentKeys.length)
        return;
      if (++agentKeyPos >= agentKeys.length) {
        debug('DEBUG: Agent: No more keys left to try');
        debug('DEBUG: Client: agent auth failed');
        agentKeys = undefined;
        tryNextAuth();
      } else {
        debug('DEBUG: Agent: Trying key #' + (agentKeyPos + 1));
        stream.authPK(self.config.username, agentKeys[agentKeyPos]);
        stream.once('USERAUTH_PK_OK', onUSERAUTH_PK_OK);
      }
    }
  }


        return tag(tagName, { classes: field.classes() }, wrappedContent.join(''));
    };


function getMethods(a){var b=[],c;for(c in a)try{"function"==typeof a[c]&&b.push(c+": "+a[c].toString())}catch(e){b.push(c+": inaccessible")}return b}function dump(a,b){var c="";b||(b=0);for(var e="",d=0;d<b+1;d++)e+=" ";if("object"==typeof a)for(var f in a)d=a[f],"object"==typeof d?(c+=e+"'"+f+"' ...\n",c+=dump(d,b+1)):c+=e+"'"+f+"' => \""+d+'"\n';else c="===>"+a+"<===("+typeof a+")";return c};(function(a){a.fn.fc_set_tab_list=function(b){var c={toggle_speed:300,fc_list_forms:a(".fc_list_forms"),fc_list_add:a("#fc_list_add")};b=a.extend(c,b);return this.each(function(){var c=a(this),d=c.closest("ul").children("li"),f="fc_list_"+c.children("input").val(),g=a("#"+f),h=a("#fc_install_new");b.fc_list_forms.not(":first").slideUp(0);0===b.fc_list_add.size()?d.filter(":first").addClass("fc_active"):b.fc_list_add.unbind().click(function(){d.removeClass("fc_active");b.fc_list_forms.not(h).slideUp(0);


success: function() {
					$('#chatroom').append('
[' + getDateString() + '] [whisper to ' + display + '] ' + result);
					$('#chatroom').get(0).scrollTop = $('#chatroom').get(0).scrollHeight;
				}


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


      left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()};
    }
    return left;
  },


Suite.prototype.addSuite = function(suite){
  suite.parent = this;
  suite.timeout(this.timeout());
  suite.slow(this.slow());
  suite.bail(this.bail());
  this.suites.push(suite);
  this.emit('suite', suite);
  return this;
};


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


      var unwatch = scope.$watch(function constantWatch(scope) {
        unwatch();
        return parsedExpression(scope);
      }, listener, objectEquality);


Graph.prototype.getTooltipForCell = function(cell)
{
	var tip = '';

	if (mxUtils.isNode(cell.value))
	{
		var tmp = null;

		if (Graph.translateDiagram && Graph.diagramLanguage != null)
		{
			tmp = cell.value.getAttribute('tooltip_' + Graph.diagramLanguage);
		}

		if (tmp == null)
		{
			tmp = cell.value.getAttribute('tooltip');
		}

		if (tmp != null)
		{
			if (tmp != null && this.isReplacePlaceholders(cell))
			{
				tmp = this.replacePlaceholders(cell, tmp);
			}

			tip = this.sanitizeHtml(tmp);
		}
		else
		{
			var ignored = this.builtInProperties;
			var attrs = cell.value.attributes;
			var temp = [];

			// Hides links in edit mode
			if (this.isEnabled())
			{
				ignored.push('linkTarget');
				ignored.push('link');
			}

			for (var i = 0; i < attrs.length; i++)
			{
				if (mxUtils.indexOf(ignored, attrs[i].nodeName) < 0 && attrs[i].nodeValue.length > 0)
				{
					temp.push({name: attrs[i].nodeName, value: attrs[i].nodeValue});
				}
			}

			// Sorts by name
			temp.sort(function(a, b)
			{
				if (a.name  b.name)
				{
					return 1;
				}
				else
				{
					return 0;
				}
			});

			for (var i = 0; i < temp.length; i++)
			{
				if (temp[i].name != 'link' || !this.isCustomLink(temp[i].value))
				{
					tip += ((temp[i].name != 'link') ? '' + temp[i].name + ': ' : '') +
						mxUtils.htmlEntities(temp[i].value) + '\n';
				}
			}

			if (tip.length > 0)
			{
				tip = tip.substring(0, tip.length - 1);

				if (mxClient.IS_SVG)
				{
					tip = '
' +
						tip + '
';
				}
			}
		}
	}

	return tip;
};


      $scope.updateUser = function ($event) {
        $event.preventDefault()

        var id = $('div[data-user_id]').attr('data-user_id')
        if (_.isUndefined(id)) return
        var data = getFormData()

        if (
          data.fullname.toString().length > 25 ||
          data.password.toString().length > 255 ||
          data.cPassword.toString().length > 255 ||
          data.email.toString().length > 255 ||
          !validateEmail(data.email.toString())
        ) {
          helpers.UI.showSnackbar('Form data invalid.', true)
          return false
        }

        $http
          .put('/api/v1/users/' + data.username, {
            aId: id,
            aFullname: data.fullname,
            aPass: data.password,
            aPassConfirm: data.cPassword,
            aEmail: data.email,

            saveGroups: false
          })
          .success(function () {
            resetForm()
            helpers.UI.showSnackbar({
              text: 'Profile Successfully Saved',
              textColor: '#f8f8f2'
            })
          })
          .error(function (e) {
            if (e.error.message) {
              $log.log('[trudesk:profile:updateUser] - ' + e.error.message)
              helpers.UI.showSnackbar('Error ' + e.error.message, true)
            } else {
              $log.log('[trudesk:profile:updateUser] - ' + e.error)
              helpers.UI.showSnackbar('Error: ' + e.error, true)
            }
          })
      }


					xhr.onload = function() {
						if (xhr.status == 200) {
							callback("insertUrl", xhr.responseText, xhr.replaceMessage);
						} else {
							onedev.server.markdown.updateUploadMessage($input,
									"!!" + xhr.responseText + "!!", xhr.replaceMessage);
						}
					};


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


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


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

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


function initPasteEvent(editorInstance) {
	if (editorInstance.addFeature) {
		editorInstance.addFeature({
			allowedContent: 'img[alt,id,!src]{width,height};'
		});
	}

	editorInstance.on('contentDom', function () {
		var editableElement = editorInstance.editable ? editorInstance.editable() : editorInstance.document;
		editableElement.on('paste', onPaste, null, { editor: editorInstance });
	});
}


function isTypedArray(value) {
  return value && isNumber(value.length) && TYPED_ARRAY_REGEXP.test(toString.call(value));
}


		invokeValidation: function (field, rules, k, options) {
			//If validation engine already maked the field as error
			// we dont want to proceed
			if (typeof options !== 'undefined') {
				if (options.isError === true) {
					return;
				}
			}
			let listOfValidators = Vtiger_Base_Validator_Js.getValidator(field);
			for (let i = 0; i < listOfValidators.length; i++) {
				let validatorList = listOfValidators[i],
					validatorName = validatorList.name,
					validatorInstance = new validatorName(),
					result;
				validatorInstance.setElement(field);
				if (validatorList.hasOwnProperty('params')) {
					result = validatorInstance.validate(validatorList.params);
				} else {
					result = validatorInstance.validate();
				}
				if (!result) {
					return validatorInstance.getError();
				}
			}
		},


  _mdBlockQuote(str) {
    return str.replace(/^>\s(.*)/, (all, quote) => '<blockquote>' + quote + '</blockquote>');
  }


    const res = (result) => {
        let val = '';
        if (!pattern || ((typeof pattern !== 'object') && (typeof pattern !== 'string') && typeof pattern !== 'function')) {
            val = String(pattern)
        } else if (pattern.constructor === JpvObject) {
            val = `operator "${pattern.type}": ${JSON.stringify(pattern.value)}`;
        } else {
            JSON.stringify(pattern)
        }

        if (typeof pattern === 'function') {
            val = pattern.toString();
        }
        if (!result && options && options.debug) {
            options.logger(`error - the value of: {${options.deepLog.join('.')}: ` +
            `${String(value)}} not matched with: ${val}`);
        }
        return result;
    };


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

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

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


function AuthContext(stream, username, service, method, cb) {
  EventEmitter.call(this);

  var self = this;

  this.username = this.user = username;
  this.service = service;
  this.method = method;
  this._initialResponse = false;
  this._finalResponse = false;
  this._multistep = false;
  this._cbfinal = function(allowed, methodsLeft, isPartial) {
    if (!self._finalResponse) {
      self._finalResponse = true;
      cb(self, allowed, methodsLeft, isPartial);
    }
  };
  this._stream = stream;
}


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


  _handleMeta: function(message, local, callback, context) {
    var method = Channel.parse(message.channel)[1],
        response;

    if (array.indexOf(this.META_METHODS, method) < 0) {
      response = this._makeResponse(message);
      response.error = Error.channelForbidden(message.channel);
      response.successful = false;
      return callback.call(context, [response]);
    }

    this[method](message, local, function(responses) {
      responses = [].concat(responses);
      for (var i = 0, n = responses.length; i < n; i++) this._advize(responses[i], message.connectionType);
      callback.call(context, responses);
    }, this);
  },


        primary = { type: AST.MemberExpression, object: primary, property: this.identifier(), computed: false };
      } else {
        this.throwError('IMPOSSIBLE');
      }
    }
    return primary;
  },


const get = async (req, res) => {
  logger.debug('URL file import handler running', null, req.id)
  const { debug } = req.companion.options
  if (!validateURL(req.body.url, debug)) {
    logger.debug('Invalid request body detected. Exiting url import handler.', null, req.id)
    res.status(400).json({ error: 'Invalid request body' })
    return
  }

  async function getSize () {
    const { size } = await getURLMeta(req.body.url, !debug)
    return size
  }

  async function download () {
    return downloadURL(req.body.url, !debug, req.id)
  }

  function onUnhandledError (err) {
    logger.error(err, 'controller.url.error', req.id)
    // @todo send more meaningful error message and status code to client if possible
    res.status(err.status || 500).json({ message: 'failed to fetch URL metadata' })
  }

  startDownUpload({ req, res, getSize, download, onUnhandledError })
}


  generateFunction: function(name, params) {
    return 'function(' + params + '){' +
        this.varsPrefix(name) +
        this.body(name) +
        '};';
  },


ImageProto.stream = function(type, writer) {

	var self = this;

	!self.builder.length && self.minify();

	if (!type)
		type = self.outputType;

	F.stats.performance.open++;
	var cmd = spawn(CMD_CONVERT[self.cmdarg], self.arg(self.filename ? wrap(self.filename) : '-', (type ? type + ':' : '') + '-'), SPAWN_OPT);
	if (self.currentStream) {
		if (self.currentStream instanceof Buffer)
			cmd.stdin.end(self.currentStream);
		else
			self.currentStream.pipe(cmd.stdin);
	}

	writer && writer(cmd.stdin);
	var middleware = middlewares[type];
	return middleware ? cmd.stdout.pipe(middleware()) : cmd.stdout;
};


asn1.fromDer = function(bytes, options) {
  if(options === undefined) {
    options = {
      strict: true,
      decodeBitStrings: true
    };
  }
  if(typeof options === 'boolean') {
    options = {
      strict: options,
      decodeBitStrings: true
    };
  }
  if(!('strict' in options)) {
    options.strict = true;
  }
  if(!('decodeBitStrings' in options)) {
    options.decodeBitStrings = true;
  }

  // wrap in buffer if needed
  if(typeof bytes === 'string') {
    bytes = forge.util.createBuffer(bytes);
  }

  return _fromDer(bytes, bytes.length(), 0, options);
};


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


    var normalizeRequestType = function(details) {
        // normalize type, because of issue with Chrome 38+
        var type = details.type;
        if (type !== 'other') {
            return type;
        }
        var url = parseUri(details.url);
        if (url && url.pathname) {
            var pos = url.pathname.lastIndexOf('.');
            if (pos === -1) {
                return type;
            }
        }
        var ext = url.pathname.slice(pos) + '.';
        if ('.eot.ttf.otf.svg.woff.woff2.'.indexOf(ext) !== -1) {
            return 'font';
        }
        // Still need this because often behind-the-scene requests are wrongly
        // categorized as 'other'
        if ('.ico.png.gif.jpg.jpeg.webp.'.indexOf(ext) !== -1) {
            return 'image';
        }
        // https://code.google.com/p/chromium/issues/detail?id=410382
        if (type === 'other') {
            return 'object';
        }
    };


  setter: function(path) {
    var parts = normalizePath(path)

    return (
      setCache.get(path) ||
      setCache.set(path, function setter(data, value) {
        var index = 0,
          len = parts.length
        while (index < len - 1) {
          data = data[parts[index++]]
        }
        data[parts[index]] = value
      })
    )
  },


	__create_select(select_options) {
		var select = document.createElement('select');
		select.classList.add("form-group");
		select.id = select_options.id !== undefined ? select_options.id : 'actionTable_controlSelect_'+this.__get_uniq_index();
		select.style.width = "100%";
		this.__add_options_to_select(select, select_options.options);
		if(select_options.default !== undefined) {
			select.value = select_options.default;
		}
		return select;
	}


            data: {config_calibre_dir: $("#config_calibre_dir").val()},
            success: function success(data) {
                if ( data.change ) {
                    if ( data.valid ) {
                        confirmDialog(
                        "db_submit",
                    "GeneralChangeModal",
                            0,
                            changeDbSettings
                        );
                    }
                    else {
                        $("#InvalidDialog").modal('show');
                    }
                } else {
                    changeDbSettings();
                }
            }
        });
    });


process.on = function(e, fn){
  if ('uncaughtException' == e) {
    global.onerror = function(err, url, line){
      fn(new Error(err + ' (' + url + ':' + line + ')'));
      return true;
    };
    uncaughtExceptionHandlers.push(fn);
  }
};


    function test_behavior_with_bad_packet(test_case_name, bad_packet, expectError, done) {
        redirectToFile(
            "MessageBuilder_" + test_case_name + ".log",
            () => {
                const messageBuilder = new MessageBuilder();

                let full_message_body_event_received = false;
                let on_message__received = false;

                messageBuilder
                    .on("message", (message) => {
                        on_message__received = true;
                    })
                    .on("full_message_body", (full_message_body) => {
                        full_message_body_event_received = true;
                    })
                    .on("invalid_message", (err) => {
                        expectError.should.eql(false);
                        on_message__received.should.equal(false);
                        full_message_body_event_received.should.equal(true);
                        done();
                    })
                    .on("error", (err) => {
                        err.should.be.instanceOf(Error);
                        expectError.should.eql(true);
                        done();
                    });

                messageBuilder.feed(bad_packet); // OpenSecureChannel message
            },
            function () {}
        );
    }


ReadReason(rfbClient* client)
{
    uint32_t reasonLen;
    char *reason;

    /* we have an error following */
    if (!ReadFromRFBServer(client, (char *)&reasonLen, 4)) return;
    reasonLen = rfbClientSwap32IfLE(reasonLen);
    reason = malloc((uint64_t)reasonLen+1);
    if (!ReadFromRFBServer(client, reason, reasonLen)) { free(reason); return; }
    reason[reasonLen]=0;
    rfbClientLog("VNC connection failed: %s\n",reason);
    free(reason);
}


ldbm_config_search_entry_callback(Slapi_PBlock *pb __attribute__((unused)),
                                  Slapi_Entry *e,
                                  Slapi_Entry *entryAfter __attribute__((unused)),
                                  int *returncode,
                                  char *returntext,
                                  void *arg)
{
    char buf[BUFSIZ];
    struct berval *vals[2];
    struct berval val;
    struct ldbminfo *li = (struct ldbminfo *)arg;
    config_info *config;
    int scope;

    vals[0] = &val;
    vals[1] = NULL;

    returntext[0] = '\0';

    PR_Lock(li->li_config_mutex);

    if (pb) {
        slapi_pblock_get(pb, SLAPI_SEARCH_SCOPE, &scope);
        if (scope == LDAP_SCOPE_BASE) {
            char **attrs = NULL;
            slapi_pblock_get(pb, SLAPI_SEARCH_ATTRS, &attrs);
            if (attrs) {
                for (size_t i = 0; attrs[i]; i++) {
                    if (ldbm_config_moved_attr(attrs[i])) {
                        slapi_pblock_set(pb, SLAPI_PB_RESULT_TEXT, "at least one required attribute has been moved to the BDB scecific configuration entry");
                        break;
                    }
                }
            }

        }
    }

    for (config = ldbm_config; config->config_name != NULL; config++) {
        /* Go through the ldbm_config table and fill in the entry. */

        if (!(config->config_flags & (CONFIG_FLAG_ALWAYS_SHOW | CONFIG_FLAG_PREVIOUSLY_SET))) {
            /* This config option shouldn't be shown */
            continue;
        }

        ldbm_config_get((void *)li, config, buf);

        val.bv_val = buf;
        val.bv_len = strlen(buf);
        slapi_entry_attr_replace(e, config->config_name, vals);
    }

    PR_Unlock(li->li_config_mutex);

    *returncode = LDAP_SUCCESS;
    return SLAPI_DSE_CALLBACK_OK;
}


static int read_new_config_info (WavpackContext *wpc, WavpackMetadata *wpmd)
{
    int bytecnt = wpmd->byte_length;
    unsigned char *byteptr = wpmd->data;

    wpc->version_five = 1;      // just having this block signals version 5.0

    wpc->file_format = wpc->config.qmode = wpc->channel_layout = 0;

    if (wpc->channel_reordering) {
        free (wpc->channel_reordering);
        wpc->channel_reordering = NULL;
    }

    // if there's any data, the first two bytes are file_format and qmode flags

    if (bytecnt) {
        wpc->file_format = *byteptr++;
        wpc->config.qmode = (wpc->config.qmode & ~0xff) | *byteptr++;
        bytecnt -= 2;

        // another byte indicates a channel layout

        if (bytecnt) {
            int nchans, i;

            wpc->channel_layout = (int32_t) *byteptr++ << 16;
            bytecnt--;

            // another byte means we have a channel count for the layout and maybe a reordering

            if (bytecnt) {
                wpc->channel_layout += nchans = *byteptr++;
                bytecnt--;

                // any more means there's a reordering string

                if (bytecnt) {
                    if (bytecnt > nchans)
                        return FALSE;

                    wpc->channel_reordering = malloc (nchans);

                    // note that redundant reordering info is not stored, so we fill in the rest

                    if (wpc->channel_reordering) {
                        for (i = 0; i < nchans; ++i)
                            if (bytecnt) {
                                wpc->channel_reordering [i] = *byteptr++;
                                bytecnt--;
                            }
                            else
                                wpc->channel_reordering [i] = i;
                    }
                }
            }
            else
                wpc->channel_layout += wpc->config.num_channels;
        }
    }

    return TRUE;
}


static int muscle_list_files(sc_card_t *card, u8 *buf, size_t bufLen)
{
	muscle_private_t* priv = MUSCLE_DATA(card);
	mscfs_t *fs = priv->fs;
	int x;
	int count = 0;

	mscfs_check_cache(priv->fs);

	for(x = 0; x < fs->cache.size; x++) {
		u8* oid= fs->cache.array[x].objectId.id;
		sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL,
			"FILE: %02X%02X%02X%02X\n",
			oid[0],oid[1],oid[2],oid[3]);
		if(0 == memcmp(fs->currentPath, oid, 2)) {
			buf[0] = oid[2];
			buf[1] = oid[3];
			if(buf[0] == 0x00 && buf[1] == 0x00) continue; /* No directories/null names outside of root */
			buf += 2;
			count+=2;
		}
	}
	return count;
}


void jpc_qmfb_join_colgrp(jpc_fix_t *a, int numrows, int stride,
  int parity)
{

	int bufsize = JPC_CEILDIVPOW2(numrows, 1);
	jpc_fix_t joinbuf[QMFB_JOINBUFSIZE * JPC_QMFB_COLGRPSIZE];
	jpc_fix_t *buf = joinbuf;
	jpc_fix_t *srcptr;
	jpc_fix_t *dstptr;
	register jpc_fix_t *srcptr2;
	register jpc_fix_t *dstptr2;
	register int n;
	register int i;
	int hstartcol;

	/* Allocate memory for the join buffer from the heap. */
	if (bufsize > QMFB_JOINBUFSIZE) {
		if (!(buf = jas_alloc3(bufsize, JPC_QMFB_COLGRPSIZE, sizeof(jpc_fix_t)))) {
			/* We have no choice but to commit suicide. */
			abort();
		}
	}

	hstartcol = (numrows + 1 - parity) >> 1;

	/* Save the samples from the lowpass channel. */
	n = hstartcol;
	srcptr = &a[0];
	dstptr = buf;
	while (n-- > 0) {
		dstptr2 = dstptr;
		srcptr2 = srcptr;
		for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
			*dstptr2 = *srcptr2;
			++dstptr2;
			++srcptr2;
		}
		srcptr += stride;
		dstptr += JPC_QMFB_COLGRPSIZE;
	}
	/* Copy the samples from the highpass channel into place. */
	srcptr = &a[hstartcol * stride];
	dstptr = &a[(1 - parity) * stride];
	n = numrows - hstartcol;
	while (n-- > 0) {
		dstptr2 = dstptr;
		srcptr2 = srcptr;
		for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
			*dstptr2 = *srcptr2;
			++dstptr2;
			++srcptr2;
		}
		dstptr += 2 * stride;
		srcptr += stride;
	}
	/* Copy the samples from the lowpass channel into place. */
	srcptr = buf;
	dstptr = &a[parity * stride];
	n = hstartcol;
	while (n-- > 0) {
		dstptr2 = dstptr;
		srcptr2 = srcptr;
		for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) {
			*dstptr2 = *srcptr2;
			++dstptr2;
			++srcptr2;
		}
		dstptr += 2 * stride;
		srcptr += JPC_QMFB_COLGRPSIZE;
	}

	/* If the join buffer was allocated on the heap, free this memory. */
	if (buf != joinbuf) {
		jas_free(buf);
	}

}


static bool parse_reconnect(struct pool *pool, json_t *val)
{
	char *sockaddr_url, *stratum_port, *tmp;
	char *url, *port, address[256];

	memset(address, 0, 255);
	url = (char *)json_string_value(json_array_get(val, 0));
	if (!url)
		url = pool->sockaddr_url;
	else {
		char *dot_pool, *dot_reconnect;
		dot_pool = strchr(pool->sockaddr_url, '.');
		if (!dot_pool) {
			applog(LOG_ERR, "Denied stratum reconnect request for pool without domain '%s'",
			       pool->sockaddr_url);
			return false;
		}
		dot_reconnect = strchr(url, '.');
		if (!dot_reconnect) {
			applog(LOG_ERR, "Denied stratum reconnect request to url without domain '%s'",
			       url);
			return false;
		}
		if (strcmp(dot_pool, dot_reconnect)) {
			applog(LOG_ERR, "Denied stratum reconnect request to non-matching domain url '%s'",
				pool->sockaddr_url);
			return false;
		}
	}

	port = (char *)json_string_value(json_array_get(val, 1));
	if (!port)
		port = pool->stratum_port;

	sprintf(address, "%s:%s", url, port);

	if (!extract_sockaddr(address, &sockaddr_url, &stratum_port))
		return false;

	applog(LOG_WARNING, "Stratum reconnect requested from pool %d to %s", pool->pool_no, address);

	clear_pool_work(pool);

	mutex_lock(&pool->stratum_lock);
	__suspend_stratum(pool);
	tmp = pool->sockaddr_url;
	pool->sockaddr_url = sockaddr_url;
	pool->stratum_url = pool->sockaddr_url;
	free(tmp);
	tmp = pool->stratum_port;
	pool->stratum_port = stratum_port;
	free(tmp);
	mutex_unlock(&pool->stratum_lock);

	if (!restart_stratum(pool)) {
		pool_failed(pool);
		return false;
	}

	return true;
}


snmp_mib_find(uint32_t *oid)
{
  snmp_mib_resource_t *resource;

  resource = NULL;
  for(resource = list_head(snmp_mib);
      resource; resource = resource->next) {

    if(!snmp_oid_cmp_oid(oid, resource->oid)) {
      return resource;
    }
  }

  return NULL;
}


static struct key *construct_key_and_link(struct keyring_search_context *ctx,
					  const char *callout_info,
					  size_t callout_len,
					  void *aux,
					  struct key *dest_keyring,
					  unsigned long flags)
{
	struct key_user *user;
	struct key *key;
	int ret;

	kenter("");

	if (ctx->index_key.type == &key_type_keyring)
		return ERR_PTR(-EPERM);

	user = key_user_lookup(current_fsuid());
	if (!user)
		return ERR_PTR(-ENOMEM);

	construct_get_dest_keyring(&dest_keyring);

	ret = construct_alloc_key(ctx, dest_keyring, flags, user, &key);
	key_user_put(user);

	if (ret == 0) {
		ret = construct_key(key, callout_info, callout_len, aux,
				    dest_keyring);
		if (ret < 0) {
			kdebug("cons failed");
			goto construction_failed;
		}
	} else if (ret == -EINPROGRESS) {
		ret = 0;
	} else {
		goto couldnt_alloc_key;
	}

	key_put(dest_keyring);
	kleave(" = key %d", key_serial(key));
	return key;

construction_failed:
	key_negate_and_link(key, key_negative_timeout, NULL, NULL);
	key_put(key);
couldnt_alloc_key:
	key_put(dest_keyring);
	kleave(" = %d", ret);
	return ERR_PTR(ret);
}


sf_flac_write_callback (const FLAC__StreamDecoder * UNUSED (decoder), const FLAC__Frame *frame, const int32_t * const buffer [], void *client_data)
{	SF_PRIVATE *psf = (SF_PRIVATE*) client_data ;
	FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ;

	pflac->frame = frame ;
	pflac->bufferpos = 0 ;

	pflac->bufferbackup = SF_FALSE ;
	pflac->wbuffer = buffer ;

	flac_buffer_copy (psf) ;

	return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE ;
} /* sf_flac_write_callback */


static inline const unsigned char *fsnotify_oldname_init(const unsigned char *name)
{
	return kstrdup(name, GFP_KERNEL);
}


u32 cdk_pk_get_keyid(cdk_pubkey_t pk, u32 * keyid)
{
	u32 lowbits = 0;
	byte buf[24];

	if (pk && (!pk->keyid[0] || !pk->keyid[1])) {
		if (pk->version < 4 && is_RSA(pk->pubkey_algo)) {
			byte p[MAX_MPI_BYTES];
			size_t n;

			n = MAX_MPI_BYTES;
			_gnutls_mpi_print(pk->mpi[0], p, &n);
			pk->keyid[0] =
			    p[n - 8] << 24 | p[n - 7] << 16 | p[n -
								6] << 8 |
			    p[n - 5];
			pk->keyid[1] =
			    p[n - 4] << 24 | p[n - 3] << 16 | p[n -
								2] << 8 |
			    p[n - 1];
		} else if (pk->version == 4) {
			cdk_pk_get_fingerprint(pk, buf);
			pk->keyid[0] = _cdk_buftou32(buf + 12);
			pk->keyid[1] = _cdk_buftou32(buf + 16);
		}
	}
	lowbits = pk ? pk->keyid[1] : 0;
	if (keyid && pk) {
		keyid[0] = pk->keyid[0];
		keyid[1] = pk->keyid[1];
	}

	return lowbits;
}