text:
define([
  'src/main/datas',
  'src/util/api',
  'src/util/ui',
  'src/util/util',
  'src/util/debug',
  'superagent',
  'uri/URI',
  'lodash',
  'src/util/couchdbAttachments',
  'src/util/mimeTypes',
  'src/util/IDBKeyValue',
  'eventEmitter',
  './UserViewPrefs',
  './UserAnalysisResults',
], function (
  Datas,
  API,
  ui,
  Util,
  Debug,
  superagent,
  URI,
  _,
  CDB,
  mimeTypes,
  IDB,
  EventEmitter,
  UserViewPrefs,
  UserAnalysisResults,
) {
  const DataObject = Datas.DataObject;
  const eventEmitters = {};

  const objectHasOwnProperty = Object.prototype.hasOwnProperty;
  const hasOwnProperty = function (obj, prop) {
    return objectHasOwnProperty.call(obj, prop);
  };

  function setTabSavedStatus(saved) {
    if (self.IframeBridge) {
      self.IframeBridge.postMessage('tab.status', {
        saved,
      });
    }
  }

  const defaultOptions = {
    messages: {
      200: 'OK',
      201: 'Created',
      202: 'Accepted',
      204: 'No content',
      400: 'Bad request',
      401: 'Unauthorized',
      404: 'Not Found',
      409: 'Conflict',
      403: 'Forbidden',
      408: 'Request timeout',
      500: 'Internal server error',
      502: 'Bad gateway',
    },
  };

  const getTypes = [
    'get',
    'getAttachment',
    'getView',
    'getQuery',
    'getTokens',
    'getGroups',
    'getGroupsInfo',
    'getToken',
  ];

  const messagesByType = {
    get: {
      401: 'Unauthorized to get entry',
    },
    getAll: {
      401: 'Unauthorized to get all entries',
    },
    create: {
      200: 'Entry created',
      201: 'Entry created',
      401: 'Unauthorized to create entry',
    },
    update: {
      200: 'Entry updated',
      401: 'Unauthorized to update entry',
      404: 'Could not update entry: does not exist',
    },
    delete: {
      200: 'Entry deleted',
      401: 'Unauthorized to delete entry',
      404: 'Cannot delete entry: does not exist',
    },
    addAttachment: {
      200: 'Added attachment',
      401: 'Unauthorized to add attachment',
      404: 'Cannot add attachment: document does not exist',
    },
    deleteAttachment: {
      200: 'Attachment deleted',
      401: 'Unauthorized to delete attachment',
      404: 'Cannot delete attachment: does not exist',
    },
    getAttachment: {
      401: 'Unauthorized to get attachment',
      404: 'Attachment does not exist',
    },
    getView: {
      401: 'Unauthorized to get view',
      404: 'View does not exist',
    },
    getQuery: {
      401: 'Unauthorized to get query',
      404: 'Query does not exist',
    },
    getGroups: {},
    getGroupsInfo: {},
    addGroup: {
      401: 'Unauthorized to add group',
      200: 'Group added to entry',
    },
    deleteGroup: {
      401: 'Unauthorized to remove group',
      200: 'Group removed from entry',
    },
    getTokens: {},
    getToken: {},
    createToken: {
      200: 'Token created',
      401: 'Unauthorized to create token',
    },
    createUserToken: {
      200: 'Token created',
      401: 'Unauthorized to create token',
    },
    deleteToken: {
      200: 'Token deleted',
      401: 'Unauthorized to delete token',
    },
  };

  for (let key in defaultOptions.messages) {
    // For get requests default is not to show any messages
    if (key < '300') {
      for (let i = 0; i < getTypes.length; i++) {
        messagesByType[getTypes[i]][key] = '';
      }
    }
  }

  const viewSearchJsonify = ['key', 'startkey', 'endkey'];
  const viewSearch = [
    'limit',
    'mine',
    'groups',
    'descending',
    'reduce',
    'include_docs',
    'group',
    'group_level',
  ];
  const mandatoryOptions = ['url', 'database'];

  const idb = new IDB('roc-documents');

  class Roc {
    constructor(opts) {
      for (var key in opts) {
        if (hasOwnProperty(opts, key)) {
          this[key] = opts[key];
        }
      }

      for (let i = 0; i < mandatoryOptions.length; i++) {
        if (!this[mandatoryOptions[i]]) {
          throw new Error(`${mandatoryOptions[i]} is a mandatory option`);
        }
      }
      this.messages = this.messages || {};
      this.variables = {};

      this.requestUrl = new URI(opts.url);
      this.sessionUrl = new URI(opts.url)
        .segment('auth/session')
        .normalize()
        .href();
      this.databaseUrl = new URI(opts.url)
        .segment(`db/${this.database}`)
        .normalize()
        .href();
      this.entryUrl = new URI(this.databaseUrl)
        .segment('entry')
        .normalize()
        .href();
      this.trackIgnore = new Map();
      this.__ready = Promise.resolve();

      this.UserViewPrefs = new UserViewPrefs(this);
      this.UserAnalysisResults = new UserAnalysisResults(this);
    }

    async getUser() {
      await this.__ready;
      return (await fetch(this.sessionUrl, { credentials: 'include' })).json();
    }

    /**
     * Retrieve current logged in user preferences
     * @param {*} defaultPrefs
     */
    async getUserPrefs(defaultPrefs = {}) {
      await this.__ready;
      try {
        return (
          await fetch(`${this.databaseUrl}/user/_me`, {
            credentials: 'include',
          })
        ).json();
      } catch (e) {
        this.setUserPrefs(defaultPrefs);
        return defaultPrefs;
      }
    }

    /**
     * Set user personal preferences. The key of the object send are joined on the server side
     * @param {*} prefs - the prefereces to save as an object
     */
    async setUserPrefs(prefs) {
      await this.__ready;
      const res = await superagent
        .post(`${this.databaseUrl}/user/_me`)
        .withCredentials()
        .send(prefs);
      return res.body;
    }

    async getUserInfo() {
      await this.__ready;
      return (
        await fetch(`${this.databaseUrl}/userInfo/_me`, {
          credentials: 'include',
        })
      ).json();
    }

    async view(viewName, options) {
      await this.__ready;
      options = createOptions(options, 'getView');
      let requestUrl = new URI(this.databaseUrl).segment(`_view/${viewName}`);
      addSearch(requestUrl, options);

      requestUrl = requestUrl.normalize().href();

      return superagent
        .get(requestUrl)
        .withCredentials()
        .then((res) => {
          if (res && res.body && res.status === 200) {
            if (options.filter) {
              res.body = res.body.filter(options.filter);
            }
            if (options.sort) {
              res.body = res.body.sort(options.sort);
            }
            if (options.varName) {
              for (var i = 0; i < res.body.length; i++) {
                this.typeUrl(res.body[i].$content, res.body[i]);
              }
              return API.createData(options.varName, res.body).then((data) => {
                this.variables[options.varName] = {
                  type: 'view',
                  options,
                  viewName,
                  requestUrl,
                  data: data,
                };
                for (var i = 0; i < data.length; i++) {
                  data.traceSync([i]);
                }
                return data;
              });
            }
          }
          return res.body;
        })
        .then(handleSuccess(this, options))
        .catch(handleError(this, options));
    }

    async query(viewName, options) {
      await this.__ready;
      options = createOptions(options, 'getQuery');
      let requestUrl = new URI(this.databaseUrl).segment(`_query/${viewName}`);
      addSearch(requestUrl, options);
      requestUrl = requestUrl.normalize().href();
      console.log({ requestUrl });

      return superagent
        .get(requestUrl)
        .withCredentials()
        .then((res) => {
          if (res && res.body && res.status === 200) {
            if (options.filter) {
              res.body = res.body.filter(options.filter);
            }
            if (options.sort) {
              res.body = res.body.sort(options.sort);
            }
            if (options.addRightsInfo) {
              for (var i = 0; i < res.body.length; i++) {
                res.body[i].anonymousRead = {
                  type: 'boolean',
                  withCredentials: true,
                  url: `${this.entryUrl}/${res.body[i].id}/_rights/read?asAnonymous=true`,
                };
                res.body[i].userWrite = {
                  type: 'boolean',
                  withCredentials: true,
                  url: `${this.entryUrl}/${res.body[i].id}/_rights/write`,
                };
              }
            }
            for (let i = 0; i < res.body.length; i++) {
              res.body[i].document = {
                type: 'object',
                withCredentials: true,
                url: `${this.entryUrl}/${res.body[i].id}`,
              };
            }
            if (options.varName) {
              return API.createData(options.varName, res.body).then((data) => {
                this.variables[options.varName] = {
                  type: 'query',
                  options,
                  requestUrl,
                  viewName,
                  data: data,
                };
                return data;
              });
            }
          }
          return res.body;
        })
        .then(handleSuccess(this, options))
        .catch(handleError(this, options));
    }

    getDocumentEventEmitter(uuid) {
      if (!eventEmitters[uuid]) {
        // We use this object to store some state...
        eventEmitters[uuid] = {
          isSync: undefined,
          eventEmitter: new EventEmitter(),
        };
      } else {
        if (!eventEmitters[uuid].eventEmitter) {
          eventEmitters[uuid].eventEmitter = new EventEmitter();
        }
      }
      return eventEmitters[uuid].eventEmitter;
    }

    _emitSync(uuid, isSync) {
      uuid = String(uuid);
      setTabSavedStatus(isSync);
      if (eventEmitters[uuid]) {
        if (eventEmitters[uuid].isSync !== isSync) {
          eventEmitters[uuid].isSync = isSync;
          if (eventEmitters[uuid].eventEmitter) {
            eventEmitters[uuid].eventEmitter.emit(isSync ? 'sync' : 'unsync');
          }
        }
      } else {
        eventEmitters[uuid] = {
          isSync,
        };
      }
    }

    bindChange(varName) {
      const variable = this.variables[varName];
      if (!variable) return;
      this.unbindChange(varName);
      variable.onChange = () => {
        const serverJsonString = JSON.stringify(variable.data.$content);
        const uuid = String(variable.data._id);
        if (serverJsonString !== variable.serverJsonString) {
          idb.set(uuid, JSON.parse(JSON.stringify(variable.data)));
          this._emitSync(uuid, false);
        } else {
          // Going back to previous state sets the tab as saved
          idb.delete(uuid);
          this._emitSync(uuid, true);
        }
      };
      variable.data.onChange(variable.onChange);
    }

    unbindChange(varName) {
      const variable = this.variables[varName];
      if (!variable) return;
      if (!variable.onChange) return;
      variable.data.unbindChange(variable.onChange);
    }

    bindChangeByUuid(uuid) {
      for (let key in this.variables) {
        if (
          this.variables[key].type === 'document' &&
          String(this.variables[key].data._id) === String(uuid)
        ) {
          this.bindChange(key);
        }
      }
    }

    unbindChangeByUuid(uuid) {
      for (let key in this.variables) {
        if (
          this.variables[key].type === 'document' &&
          String(this.variables[key].data._id) === String(uuid)
        ) {
          this.unbindChange(key);
        }
      }
    }

    async document(uuid, options) {
      options = options || {};
      const doc = await this.get(uuid, options);
      await this.updateAttachmentList(doc);
      if (!doc) return null;
      if (options.varName) {
        this.typeUrl(doc.$content, doc);
        const data = await API.createData(options.varName, doc);
        this.variables[options.varName] = {
          type: 'document',
          data: data,
          serverJsonString: JSON.stringify(data.$content),
        };
        if (options.track) {
          this.bindChange(options.varName);
          try {
            const localEntry = await idb.get(data._id);
            if (localEntry) {
              if (localEntry._rev === doc._rev) {
                this._updateByUuid(data._id, localEntry, options);
              } else {
                // Local storage has an anterior revision
                idb.delete(data._id);
              }
            }
          } catch (e) {
            Debug.error('could not retrieve local entry', e, e.stack);
          }
        }
        return data;
      }
      return doc;
    }

    async getAll(options) {
      await this.__ready;
      options = createOptions(options, 'getAll');
      try {
        const res = await superagent
          .get(`${this.entryUrl}/_all`)
          .withCredentials();
        if (res.body && res.status === 200) {
          return res.body;
        }
        return null;
      } catch (e) {
        handleError(this, options);
        return null;
      }
    }

    async getHeader(entry, options) {
      await this.__ready;
      const uuid = getUuid(entry);
      return (
        superagent
          .head(`${this.entryUrl}/${uuid}`)
          //       .query(options.query)
          .withCredentials()
          .then((res) => {
            if (res.header && res.status === 200) {
              return res.header;
            }
            return null;
          })
          .catch(handleError(this, options))
      );
    }

    async get(entry, options) {
      await this.__ready;
      const uuid = getUuid(entry);
      options = createOptions(options, 'get');
      if (options.fromCache) {
        const e = this._findByUuid(uuid);
        if (e) return e;
        if (!options.fallback) return e;
      }
      return superagent
        .get(`${this.entryUrl}/${uuid}`)
        .query(options.query)
        .withCredentials()
        .then((res) => {
          if (res.body && res.status === 200) {
            this._defaults(res.body.$content);
            if (!options.noUpdate) {
              this._updateByUuid(uuid, res.body, options);
            }
            return res.body;
          }
          return null;
        })
        .catch(handleError(this, options));
    }

    async getById(id, options) {
      await this.__ready;
      options = createOptions(options, 'get');
      const entry = this._findById(id);
      if (!entry || options.fromCache) {
        return entry;
      }
      return this.get(entry).catch(handleError(this, options));
    }

    // Get the groups the user is owner of
    async getGroups(options) {
      await this.__ready;
      options = createOptions(options, 'getGroups');
      const groupUrl = new URI(this.databaseUrl)
        .segment('groups')
        .normalize()
        .href();
      return superagent
        .get(groupUrl)
        .withCredentials()
        .then((res) => res.body)
        .catch(handleError(this, options));
    }

    // Get basic info about every group (only name and description)
    async getGroupsInfo(options) {
      await this.__ready;
      options = createOptions(options, 'getGroupsInfo');
      const groupsInfoUrl = new URI(this.databaseUrl)
        .segment('groups/info')
        .normalize()
        .href();
      return superagent
        .get(groupsInfoUrl)
        .withCredentials()
        .then((res) => res.body)
        .catch(handleError(this, options));
    }

    // Get the groups the user is member of
    // Returns a promise that resolves with an array of strings
    async getGroupMembership(options) {
      options = createOptions(options);
      await this.__ready;
      const url = new URI(this.databaseUrl).segment('user/_me/groups');
      return superagent
        .get(url)
        .withCredentials()
        .then((res) => res.body)
        .catch(handleError(this, options));
    }

    async create(entry, options) {
      await this.__ready;
      options = createOptions(options, 'create');
      if (!entry.$kind) {
        entry.$kind = this.kind;
      }
      this._defaults(entry.$content);
      return superagent
        .post(this.entryUrl)
        .withCredentials()
        .send(entry)
        .then(handleSuccess(this, options))
        .then((res) => {
          if (res.body && (res.status === 200 || res.status === 201)) {
            return this.get(res.body.id);
          }
          return null;
        })
        .then((entry) => {
          if (!entry) return null;
          this.typeUrl(entry.$content, entry);
          let keys = Object.keys(this.variables);
          for (let i = 0; i < keys.length; i++) {
            let v = this.variables[keys[i]];
            if (v.type === 'view') {
              var idx = v.data.length;
              v.data.push(entry);
              v.data.traceSync([idx]);
              if (!options.noTrigger) {
                v.data.triggerChange();
              }
            } else if (v.type === 'query') {
              this.query(v.viewName, v.options);
            }
          }
          return entry;
        })
        .catch(handleError(this, options));
    }

    async getLastRevision(entry) {
      const uuid = getUuid(entry);
      const header = await this.getHeader(uuid);
      return header.etag.replace(/"/g, '');
    }

    async update(entry, options) {
      await this.__ready;
      options = createOptions(options, 'update');
      var reqEntry = DataObject.resurrect(entry);
      this.untypeUrl(reqEntry.$content);
      return superagent
        .put(`${this.entryUrl}/${String(entry._id)}`)
        .withCredentials()
        .send(reqEntry)
        .then(handleSuccess(this, options))
        .then((res) => {
          if (res.body && res.status === 200) {
            entry._rev = res.body.rev;
            entry.$creationDate = res.body.$creationDate;
            entry.$modificationDate = res.body.$modificationDate;
            this._updateByUuid(
              entry._id,
              entry,
              Object.assign(options, { updateServerString: true }),
            );
            idb.delete(entry._id);
          }
          return entry;
        })
        .catch(handleError(this, options));
    }

    async deleteAttachment(entry, attachments, options) {
      await this.__ready;
      options = createOptions(options, 'deleteAttachment');
      if (DataObject.getType(entry) !== 'object') {
        handleError(this, options)(new Error('invalid argument'));
        return null;
      }
      if (Array.isArray(attachments) && attachments.length === 0) return entry;
      if (!Array.isArray(attachments)) attachments = [attachments];

      attachments = attachments.map(String);
      entry = await this.get(entry, { fromCache: true, fallback: true });

      try {
        const hasDeleted = this._deleteFilename(entry.$content, attachments);
        for (let i = 0; i < attachments.length; i++) {
          delete entry._attachments[attachments[i]];
        }
        const cdb = this._getCdb(entry);
        await cdb.remove(attachments, { noRefresh: true });
        const data = await this.get(entry, { noUpdate: true });

        entry._rev = data._rev;
        entry._attachments = data._attachments;
        entry.$creationDate = data.$creationDate;
        entry.$modificationDate = data.$modificationDate;
        await this.updateAttachmentList(entry);
        if (hasDeleted) {
          await this.update(entry, options);
        } else if (entry.triggerChange && !options.noTrigger) {
          entry.triggerChange();
          handleSuccess(this, options)(entry);
        }
      } catch (e) {
        return handleError(this, options)(e);
      }
      return entry;
    }

    removeAttachment(entry, attachments, options) {
      return this.deleteAttachment(entry, attachments, options);
    }

    async unattach(entry, row, options) {
      await this.__ready;
      options = createOptions(options, 'deleteAttachment');
      if (!this.processor) throw new Error('no processor');
      if (!row.__parent) {
        throw new Error('row must be linked to parent for unattach to work');
      }
      var arr = row.__parent;
      var idx = arr.indexOf(row);
      if (idx === -1) {
        Debug.warn('element to unattach not found');
        return null;
      }

      var toDelete = this._findFilename(row);
      toDelete = toDelete.map((d) => String(d.filename));

      // We compute the difference between the delete and still present attachment
      // entries, just in case there are 2 for the same attachment. In that case the
      // attachment should not be deleted
      var toKeep = this._findFilename(entry.$content, toDelete);
      toKeep = toKeep
        .map((k) => String(k.filename))
        .filter((k) => k === row.filename);
      toDelete = _.difference(toDelete, toKeep);
      await this.deleteAttachment(entry, toDelete, options);
      arr.splice(idx, 1);
      if (!options.noTrigger) {
        arr.triggerChange();
      }
      await this.update(entry);
      return entry;
    }

    async _processAttachment(type, attachment) {
      let filename;
      if (!attachment.filename) {
        filename = await ui.enterValue('Enter a filename');
      }
      if (filename) attachment.filename = filename;
      if (!attachment.filename) {
        return false;
      }

      attachment.filename = this.processor.getFilename(
        type,
        attachment.filename,
      );

      // If we had to ask for a filename, resolve content type
      var fallback;
      if (filename) {
        fallback = attachment.contentType;
        attachment.contentType = undefined;
      }
      setContentType(attachment, fallback);
      return true;
    }

    async attachBulk(type, entry, attachments, options) {
      if (!attachments.length) return null;
      if (attachments.length === 1) {
        return this.attach(type, entry, attachments[0], options);
      }
      await this.__ready;
      const attachOptions = createOptions(options, 'attach');
      try {
        for (let i = 0; i < attachments.length; i++) {
          let attachment = attachments[i];
          if (!this._processAttachment(type, attachment)) return null;
        }
        entry = await this.get(entry, { fromCache: true, fallback: true });
        const addAttachmentOptions = createOptions(options, 'addAttachment');
        entry = await this.addAttachment(
          entry,
          attachments,
          addAttachmentOptions,
        );

        for (let i = 0; i < attachments.length; i++) {
          await this.processor.process(type, entry.$content, attachments[i]);
        }
        this.typeUrl(entry.$content, entry);
        await this.update(entry);
      } catch (e) {
        return handleError(this, attachOptions)(e);
      }
      handleSuccess(this, attachOptions)(entry);
      return entry;
    }

    async attach(type, entry, attachment, options) {
      await this.__ready;
      var attachOptions = createOptions(options, 'attach');

      try {
        const ok = this._processAttachment(type, attachment);
        if (!ok) return null;

        entry = await this.get(entry, { fromCache: true, fallback: true });
        const addAttachmentOptions = createOptions(options, 'addAttachment');
        entry = await this.addAttachment(
          entry,
          attachment,
          addAttachmentOptions,
        );
        if (!this.processor) {
          throw new Error('no processor');
        }

        await this.processor.process(
          type,
          entry.$content,
          attachment,
          attachOptions.customMetadata,
        );
        this.typeUrl(entry.$content, entry);
        await this.update(entry);
      } catch (e) {
        return handleError(this, attachOptions)(e);
      }
      handleSuccess(this, attachOptions)(entry);
      return entry;
    }

    async discardLocal(entry) {
      // entry or uuid
      const uuid = getUuid(entry);
      // Make sure the data change is not tracked
      this.unbindChangeByUuid(uuid);
      // Get from server again
      const serverEntry = await this.get(entry);
      this._updateByUuid(entry._id, serverEntry, {
        updateServerString: true,
      });
      try {
        await idb.delete(uuid);
      } catch (e) {
        // ignored error
      }
      // Track data again
      this.bindChangeByUuid(uuid);
      if (entry.triggerChange) entry.triggerChange();
      return serverEntry;
    }

    async getAttachment(entry, name, options) {
      await this.__ready;
      options = createOptions(options, 'getAttachment');
      const cdb = this._getCdb(entry);
      return cdb.get(name, options).catch(handleError(this, options));
    }

    async getAttachmentList(entry) {
      await this.__ready;
      const cdb = this._getCdb(entry);
      return cdb.list();
    }

    async updateAttachmentList(entry) {
      await this.__ready;
      const cdb = this._getCdb(entry);
      entry.attachmentList = await cdb.list();
    }

    async addAttachment(entry, attachments, options) {
      options = options || {};
      let filename = true;
      await this.__ready;
      attachments = DataObject.resurrect(attachments);
      if (attachments.length === 1) {
        attachments = attachments[0];
      }

      if (!Array.isArray(attachments)) {
        if (!attachments.filename) {
          filename = await ui.enterValue('Enter a filename');
          if (filename) attachments.filename = filename;
          if (!attachments.filename) {
            return null;
          }
          // If we had to ask for a filename, resolve content type
          var fallback = attachments.contentType;
          attachments.contentType = undefined;
          setContentType(attachments, fallback);
          attachments = [attachments];
        } else {
          attachments = [attachments];
        }
      }

      attachments.forEach((attachment) => {
        setContentType(attachment);
      });

      if (!filename) return null;

      options = createOptions(options, 'addAttachment');
      entry = await this.get(entry, { fromCache: true, fallback: true });

      try {
        const cdb = this._getCdb(entry);
        await cdb.inlineUploads(attachments, {
          noRefresh: true,
        });
        const data = await this.get(entry, { noUpdate: true });
        entry._rev = data._rev;
        entry._attachments = data._attachments;
        entry.$creationDate = data.$creationDate;
        entry.$modificationDate = data.$modificationDate;
        await this.updateAttachmentList(entry);
        if (entry.triggerChange && !options.noTrigger) {
          entry.triggerChange();
        }
      } catch (e) {
        return handleError(this, options)(e);
      }
      handleSuccess(this, options)(entry);
      return entry;
    }

    async addAttachmentById(id, attachment, options) {
      options = options || {};
      await this.__ready;
      const doc = this._findById(id);
      if (!doc) return null;
      return this.addAttachment(doc._id, attachment, options);
    }

    async getTokens(options) {
      await this.__ready;
      options = createOptions(options, 'getTokens');
      const tokenUrl = new URI(this.databaseUrl)
        .segment('token')
        .normalize()
        .href();
      return superagent
        .get(tokenUrl)
        .withCredentials()
        .then(handleSuccess(this, options))
        .then((res) => res.body)
        .catch(handleError(this, options));
    }

    async getToken(token, options) {
      await this.__ready;
      options = createOptions(options, 'getToken');
      const tokenId = getTokenId(token);
      const tokenUrl = new URI(this.databaseUrl)
        .segment(`token/${tokenId}`)
        .normalize()
        .href();
      return superagent
        .get(tokenUrl)
        .withCredentials()
        .then(handleSuccess(this, options))
        .then((res) => res.body)
        .catch(handleError(this, options));
    }

    async createToken(entry, options) {
      await this.__ready;
      options = createOptions(options, 'createToken');
      const uuid = getUuid(entry);
      const request = superagent
        .post(`${this.entryUrl}/${uuid}/_token`)
        .withCredentials();
      if (options.rights) {
        let rights = options.rights;
        if (Array.isArray(rights)) {
          rights = options.rights.join(',');
        }
        request.query({ rights });
      }
      return request
        .then(handleSuccess(this, options))
        .then((res) => res.body)
        .catch(handleError(this, options));
    }

    async createUserToken(options) {
      await this.__ready;
      options = createOptions(options, 'createUserToken');
      const request = superagent
        .post(`${this.databaseUrl}/user/_me/token`)
        .withCredentials();
      if (options.rights) {
        let rights = options.rights;
        if (Array.isArray(rights)) {
          rights = options.rights.join(',');
        }
        request.query({ rights });
      }
      return request
        .then(handleSuccess(this, options))
        .then((res) => res.body)
        .catch(handleError(this, options));
    }

    async deleteToken(token, options) {
      await this.__ready;
      options = createOptions(options, 'deleteToken');
      const tokenId = getTokenId(token);
      const tokenUrl = new URI(this.databaseUrl)
        .segment(`token/${tokenId}`)
        .normalize()
        .href();
      return superagent
        .del(tokenUrl)
        .withCredentials()
        .then(handleSuccess(this, options))
        .then((res) => res.body)
        .catch(handleError(this, options));
    }

    async addGroup(entry, group, options, remove) {
      const uuid = getUuid(entry);
      const eventEmmitter = eventEmitters[uuid];
      if (eventEmmitter && eventEmmitter.isSync === false) {
        throw new Error('Cannot update group while entry is edited');
      }
      var method = remove ? 'del' : 'put';
      await this.__ready;
      options = createOptions(options, remove ? 'deleteGroup' : 'addGroup');
      return superagent[method](
        `${this.entryUrl}/${uuid}/_owner/${String(group)}`,
      )
        .withCredentials()
        .then(handleSuccess(this, options))
        .then((res) => {
          if (!options.noUpdate) {
            return this.get(uuid).then(() => res.body);
          } else {
            return res.body;
          }
        })
        .catch(handleError(this, options));
    }

    deleteGroup(entry, group, options) {
      return this.addGroup(entry, group, options, true);
    }

    async delete(entry, options) {
      await this.__ready;
      const uuid = getUuid(entry);
      options = createOptions(options, 'delete');
      return superagent
        .del(`${this.entryUrl}/${uuid}`)
        .withCredentials()
        .then(handleSuccess(this, options))
        .then((res) => {
          if (res.body && res.status === 200) {
            for (let key in this.variables) {
              const idx = this._findIndexByUuid(uuid, key);
              if (idx !== -1) {
                this.variables[key].data.splice(idx, 1);
                if (!options.noTrigger) {
                  this.variables[key].data.triggerChange();
                }
              }
            }
          }
          return res.body;
        })
        .catch(handleError(this, options));
    }

    remove(entry, options) {
      return this.delete(entry, options);
    }

    // Private
    _getCdb(entry) {
      var uuid;
      var type = DataObject.getType(entry);
      if (type === 'object') {
        uuid = String(entry._id);
      } else {
        throw new Error('Bad arguments, entry can only be an object');
      }
      const docUrl = `${this.entryUrl}/${String(uuid)}`;
      var cdb = new CDB(docUrl);
      cdb.setDoc(entry);
      return cdb;
    }

    _findByUuid(uuid, key) {
      if (key === undefined) {
        var result;
        // Return the first one found (they are all supposed to be the same...)
        for (let key in this.variables) {
          result = this._findByUuid(uuid, key);
          if (result) return result;
        }
        return null;
      }

      if (!this.variables[key]) return null;
      if (this.variables[key].type === 'view') {
        return this.variables[key].data.find(
          (entry) => String(entry._id) === String(uuid),
        );
      } else if (this.variables[key].type === 'document') {
        if (String(this.variables[key].data._id) === String(uuid)) {
          return this.variables[key].data;
        }
      }
      return null;
    }

    _findById(id, key) {
      if (key === undefined) {
        var result;
        for (let key in this.variables) {
          result = this._findById(id, key);
          if (result) return result;
        }
        return null;
      }
      if (!this.variables[key]) return null;
      id = DataObject.resurrect(id);
      if (
        this.variables[key].type === 'document' &&
        _.isEqual(DataObject.resurrect(this.variables[key].data.$id), id)
      ) {
        return this.variables[key].data;
      } else if (this.variables[key].type === 'view') {
        return this.variables[key].data.find((entry) =>
          _.isEqual(id, DataObject.resurrect(entry.$id)),
        );
      }
      return null;
    }

    _findIndexByUuid(uuid, key) {
      if (!this.variables[key]) return -1;
      if (this.variables[key].type === 'document') {
        return -1;
      } else if (this.variables[key].type === 'view') {
        return this.variables[key].data.findIndex(
          (entry) => String(entry._id) === String(uuid),
        );
      } else if (this.variables[key].type === 'query') {
        return this.variables[key].data.findIndex(
          (entry) => String(entry.id) === String(uuid),
        );
      }
      return -1;
    }

    _updateByUuid(uuid, data, options) {
      for (let key in this.variables) {
        if (this.variables[key].type === 'view') {
          const idx = this._findIndexByUuid(uuid, key);
          if (idx !== -1) {
            this.typeUrl(data.$content, data);
            // this.variables[key].data.setChildSync([idx], data);
            let row = this.variables[key].data.getChildSync([idx]);
            this._updateDocument(row, data, options);
          }
        } else if (this.variables[key].type === 'document') {
          uuid = String(uuid);
          const _id = this.variables[key].data._id;
          if (uuid === _id) {
            // var newData = DataObject.resurrect(data);
            this.typeUrl(data.$content, data);
            let doc = this.variables[key].data;
            if (options.updateServerString) {
              this.variables[key].serverJsonString = JSON.stringify(
                doc.$content,
              );
              this._emitSync(uuid, true);
            }
            this._updateDocument(doc, data, options);
          }
        } else if (
          this.variables[key].type === 'query' &&
          this.queryAutoRefresh
        ) {
          const idx = this._findIndexByUuid(uuid, key);
          if (idx !== -1) {
            // Redo the same query
            this.query(
              this.variables[key].viewName,
              this.variables[key].options,
            );
          }
        }
      }
    }

    _updateDocument(doc, data, options) {
      if (doc && data) {
        let keys = Object.keys(data);
        for (let i = 0; i < keys.length; i++) {
          let key = keys[i];
          doc[key] = data[key];
        }
        if (doc.triggerChange && !options.noTrigger) {
          doc.triggerChange();
        }
      }
    }

    _defaults(content) {
      if (this.processor) {
        var kind = this.kind;
        if (kind) {
          this.processor.defaults(kind, content);
        }
      }
    }

    _traverseFilename(v, cb) {
      var type = DataObject.getType(v);
      var i;
      if (type === 'array') {
        for (i = 0; i < v.length; i++) {
          this._traverseFilename(v[i], cb);
        }
      } else if (type === 'object') {
        if (v.filename) {
          cb(v);
        } else {
          var keys = Object.keys(v);
          for (i = 0; i < keys.length; i++) {
            this._traverseFilename(v[keys[i]], cb);
          }
        }
      }
    }

    _findFilename(v, filename) {
      var r = [];
      if (!Array.isArray(filename) && typeof filename !== 'undefined') {
        filename = [filename];
      }
      this._traverseFilename(v, function (v) {
        if (typeof filename === 'undefined') {
          r.push(v);
        } else if (filename.indexOf(String(v.filename)) !== -1) {
          r.push(v);
        }
      });
      return r;
    }

    _deleteFilename(v, filename) {
      let hasDeleted = false;
      var filenames = this._findFilename(v, filename);
      for (var i = 0; i < filenames.length; i++) {
        hasDeleted = true;
        delete filenames[i].filename;
      }
      return hasDeleted;
    }

    untypeUrl(v) {
      this._traverseFilename(v, (v) => {
        if (v.data && v.data.url) {
          delete v.data;
        }
      });
    }

    typeUrl(content, entry) {
      this._traverseFilename(content, (v) => {
        var filename = String(v.filename);
        if (!entry._attachments) return;
        var att = entry._attachments[filename];
        if (!att) return;
        var contentType = String(att.content_type);
        var vtype = Util.contentTypeToType(contentType);
        var prop;
        if (typeValue.indexOf(vtype) !== -1) {
          prop = 'value';
        } else {
          prop = 'url';
        }

        Object.defineProperty(v, 'data', {
          value: {
            type: vtype || 'string',
          },
          enumerable: false,
          writable: true,
          configurable: true,
        });

        var dUrl = `${this.entryUrl}/${entry._id}/${encodeURIComponent(
          v.filename,
        )}`;
        v.data[prop] = dUrl;
        Object.defineProperty(v, 'dUrl', {
          value: dUrl,
          enumerable: false,
          writable: true,
        });
      });
    }
  }

  function createOptions(options, type, custom) {
    var messages = Object.assign(
      {},
      defaultOptions.messages,
      messagesByType[type],
      options && options.messages,
    );
    options = Object.assign({}, defaultOptions, options, custom);
    if (messages) options.messages = messages;
    options.type = type;
    return options;
  }

  function handleError(ctx, options) {
    return function (err) {
      if (!options.mute || !options.muteError) {
        if (err.status || err.timeout) {
          // error comes from superagent
          handleSuperagentError(err, ctx, options);
        } else {
          defaultErrorHandler(err);
        }
      }
      // Propagate error
      throw err;
    };
  }

  function handleSuccess(ctx, options) {
    return function (data) {
      if (!options.mute && !options.muteSuccess) {
        if (data.status) {
          handleSuperagentSuccess(data, ctx, options);
        } else if (options.type && options.type.match(/attachment/i)) {
          handleSuperagentSuccess({ status: 200 }, ctx, options);
        }
      }
      return data;
    };
  }

  function handleSuperagentSuccess(data, ctx, options) {
    const message = options.messages[data.status] || ctx.messages[data.status];
    if (message && !options.disableNotification) {
      ui.showNotification(message, 'success');
    }
  }

  function handleSuperagentError(err, ctx, options) {
    const message = options.messages[err.status] || ctx.messages[err.status];
    if (message && !options.disableNotification) {
      ui.showNotification(message, 'error');
      Debug.error(err, err.stack);
    }
  }

  function getUuid(entry) {
    var uuid;
    var type = DataObject.getType(entry);
    if (type === 'string') {
      uuid = entry;
    } else if (type === 'object') {
      uuid = entry._id;
    } else {
      throw new Error('Bad arguments');
    }
    return String(uuid);
  }

  function getTokenId(token) {
    var id;
    var type = DataObject.getType(token);
    if (type === 'string') {
      id = token;
    } else if (type === 'object') {
      id = token.$id;
    } else {
      throw new Error('Bad arguments');
    }
    return String(id);
  }

  function defaultErrorHandler(err) {
    ui.showNotification(`Error: ${err.message}`, 'error');
    Debug.error(err, err.stack);
  }

  function setContentType(attachment, fallback) {
    fallback = fallback || 'application/octet-stream';
    var filename = attachment.filename;
    var contentType = attachment.contentType;
    if (contentType && contentType !== 'application/octet-stream') {
      return;
    }

    // Ideally jcamp extensions should be handled by mime-types
    attachment.contentType = mimeTypes.lookup(filename, fallback) || fallback;
  }

  function addSearch(requestUrl, options) {
    for (let i = 0; i < viewSearchJsonify.length; i++) {
      if (options[viewSearchJsonify[i]]) {
        requestUrl.addSearch(
          viewSearchJsonify[i],
          JSON.stringify(options[viewSearchJsonify[i]]),
        );
      }
    }

    for (let i = 0; i < viewSearch.length; i++) {
      if (options[viewSearch[i]]) {
        requestUrl.addSearch(viewSearch[i], options[viewSearch[i]]);
      }
    }
  }

  const typeValue = ['gif', 'tiff', 'jpeg', 'jpg', 'png'];

  return Roc;
});


text:
"""Indicators for network status."""

from makani.avionics.common import cvt
from makani.avionics.common import pack_avionics_messages
from makani.gs.monitor2.apps.layout import indicator
from makani.gs.monitor2.apps.layout import stoplights
from makani.gs.monitor2.apps.plugins import common
from makani.lib.python import struct_tree

# TODO: Find a global definition source for it.
_XLR_RSSI_WARNING_THRESHOLD = -112 + 20

# The Microhard pDDL radios support the joystick traffic without
# packet drops down to an RSSI of -92 dBm. The additional free space
# loss from perch to maximal glide range is 11 dB.
_PDDL_RSSI_WARNING_THRESHOLD = -92 + 11

def _IsSwitchCommsLinkUp(switch_stats, port):
  return (switch_stats and (switch_stats.link_status_bits & (1 << port)) and
          switch_stats.stats[port].rx_multicast_packet_rate > 0)

class BaseCommsStatusIndicator(indicator.BaseAttributeIndicator):
  """Base class for comms status."""

  def __init__(self, name, node_a, port_a, node_b, port_b, message_type,
               show_label, ignore_error=False):
    super(BaseCommsStatusIndicator, self).__init__([
        (message_type, node_a, 'switch_stats'),
        (message_type, node_b, 'switch_stats'),
    ], name)

    self._ignore_error = ignore_error
    self._port_a = port_a
    self._port_b = port_b
    self._show_label = show_label

  def _ShowLinkStatus(self, is_up):
    return 'Up' if is_up else 'Down'

  def _DictToString(self, results, item_length=10):
    text = []
    keys = sorted(results.keys())
    if self._show_label:
      text.append(' '.join(k.rjust(item_length) for k in keys))
    text.append(' '.join(results[k].rjust(item_length) for k in keys))

    return '\n'.join(text)

  def _Filter(self, status_a, status_b):
    results = {}
    total_links = 0
    total_up_links = 0
    if self._port_a is None:
      results['Link A'] = '--'
    else:
      is_a_up = _IsSwitchCommsLinkUp(status_a, self._port_a)
      results['Link A'] = self._ShowLinkStatus(is_a_up)
      total_links += 1
      if is_a_up:
        total_up_links += 1

    if self._port_b is None:
      results['Link B'] = '--'
    else:
      is_b_up = _IsSwitchCommsLinkUp(status_b, self._port_b)
      results['Link B'] = self._ShowLinkStatus(is_b_up)
      total_links += 1
      if is_b_up:
        total_up_links += 1

    if self._ignore_error:
      stoplight = stoplights.STOPLIGHT_ANY
    else:
      if total_links == 0:
        stoplight = stoplights.STOPLIGHT_ANY
      elif total_up_links == total_links:
        stoplight = stoplights.STOPLIGHT_NORMAL
      elif total_up_links == 0:
        stoplight = stoplights.STOPLIGHT_ERROR
      else:
        stoplight = stoplights.STOPLIGHT_WARNING

    return self._DictToString(results), stoplight

class CommsStatusPoFIndicator(BaseCommsStatusIndicator):

  def __init__(self, name, show_label=True):
    super(CommsStatusPoFIndicator, self).__init__(
        name, 'CsGsA', 20, 'CsGsB', 20, 'CoreSwitchSlowStatus', show_label,
        ignore_error=True)

class CommsStatusEoPIndicator(BaseCommsStatusIndicator):

  def __init__(self, name, show_label=True):
    super(CommsStatusEoPIndicator, self).__init__(
        name, 'CsGsA', None, 'CsGsB', None, 'CoreSwitchSlowStatus', show_label,
        ignore_error=True)

class CommsStatusWifiIndicator(BaseCommsStatusIndicator):

  def __init__(self, name, show_label=True):
    super(CommsStatusWifiIndicator, self).__init__(
        name, 'CsGsA', 22, 'CsGsB', 18, 'CoreSwitchSlowStatus', show_label)

class JoystickRadioStatusIndicator(indicator.BaseAttributeIndicator):
  """Joystick radio status."""

  def __init__(self, name):
    super(JoystickRadioStatusIndicator, self).__init__([
        ('JoystickMonitorStatus', 'JoystickA', 'microhard_status'),
        ('TetherDown', 'CsB', 'comms_status'),
    ], name)

  def _HandleStatus(self, connected, rssi):
    if connected:
      if rssi < _PDDL_RSSI_WARNING_THRESHOLD:
        stoplight = stoplights.STOPLIGHT_WARNING
      else:
        stoplight = stoplights.STOPLIGHT_NORMAL
      return '% 4d' % rssi, stoplight
    else:
      return ' n/a', stoplights.STOPLIGHT_WARNING

  def _Filter(self, down_status, up_status):
    if struct_tree.IsValidElement(down_status):
      text, down_stoplight = self._HandleStatus(
          down_status.connected, down_status.rssi)
    else:
      text, down_stoplight = '--', stoplights.STOPLIGHT_WARNING
    result = '%s dBm down, ' % text

    if struct_tree.IsValidElement(up_status):
      is_connected = (up_status.links_up &
                      pack_avionics_messages.kTetherCommsLinkJoystick)
      text, up_stoplight = self._HandleStatus(
          is_connected, up_status.received_signal_strength)
    else:
      text, up_stoplight = '--', stoplights.STOPLIGHT_WARNING

    result += '%s dBm up' % text
    stoplight = stoplights.MostSevereStoplight(down_stoplight, up_stoplight)
    return result, stoplight

class TetherLongRangeRadioStatusIndicator(indicator.SingleAttributeIndicator):

  def __init__(self, name):
    super(TetherLongRangeRadioStatusIndicator, self).__init__(
        ('TetherDown', 'CsGsA'), name)

  def _Filter(self, tether_down):
    if not struct_tree.IsValidElement(tether_down):
      return 'Link down', stoplights.STOPLIGHT_ERROR

    down_signal_strength = tether_down.received_signal_strength
    up_signal_strength = tether_down.comms_status.received_signal_strength
    text = '% 4d dBm down, % 4d dBm up' % (
        down_signal_strength, up_signal_strength)

    if (down_signal_strength < _XLR_RSSI_WARNING_THRESHOLD or
        up_signal_strength < _XLR_RSSI_WARNING_THRESHOLD):
      stoplight = stoplights.STOPLIGHT_WARNING
    else:
      stoplight = stoplights.STOPLIGHT_NORMAL

    return text, stoplight

class BaseTetherCommsStatusIndicator(indicator.BaseAttributeIndicator):
  """Base class for tether comms status."""

  def __init__(self, name, link_type, sources_per_link, link_names, show_label,
               ignore_error=False):
    super(BaseTetherCommsStatusIndicator, self).__init__(
        self._PackArguments(sources_per_link), name)
    assert len(sources_per_link) == len(link_names)
    self._sources_per_link = sources_per_link
    self._link_names = link_names
    self._link_type = link_type
    self._show_label = show_label
    self._ignore_error = ignore_error

  def _PackArguments(self, sources_per_link):
    """Construct the list of arguments telling statuses of various links.

    Args:
      sources_per_link: A list of source list. Each source list contains
          TetherDownSources for a particular link.

    Returns:
      The packed argument list is in the form of
      [<status_link_0>, <valid_link_0>, <status_link_1>, <valid_link_1>, ...]
    """
    attributes = []
    for sources in sources_per_link:
      for source in sources:
        attributes.append(
            ('filtered', 'merge_tether_down', 'comms_status[%d]' % source))
        attributes.append(
            ('filtered', 'merge_tether_down',
             'comms_status_valid[%d]' % source))
    return attributes

  def _UnpackArguments(self, *attributes):
    """Unpack attributes to comms status, valid bits, and indices per link."""
    comms_status = attributes[0:len(attributes):2]
    valid = attributes[1:len(attributes):2]
    # A dictionary of source indices in `comms_status` and `valid` arrays
    # per link. E.g., comms_status[source_indice_per_link[0][1]] is the
    # comms_status for source 1 of link 0.
    source_indices_per_link = {}
    source_idx = 0
    for link_idx, sources in enumerate(self._sources_per_link):
      source_indices_per_link[link_idx] = range(
          source_idx, source_idx + len(sources))
      source_idx += len(sources)
    return comms_status, valid, source_indices_per_link

  def _ShowLinkStatus(self, is_up):
    return 'Up' if is_up else 'Down'

  def _DictToString(self, results, item_length=10):
    text = []
    keys = sorted(results.keys())
    if self._show_label:
      text.append(' '.join(k.rjust(item_length) for k in keys))
    text.append(' '.join(results[k].rjust(item_length) for k in keys))

    return '\n'.join(text)

  def _Filter(self, *attributes):
    comms_status, valid, source_indices_per_link = self._UnpackArguments(
        *attributes)

    results = {}
    total_links = 0
    total_up_links = 0
    # Iterate through all links in the order of _sources_per_link.
    for link_index in range(len(self._sources_per_link)):
      link_name = self._link_names[link_index]
      link_up = False
      for source_idx in source_indices_per_link[link_index]:
        if (valid[source_idx] and comms_status[source_idx].no_update_count <
            common.MAX_NO_UPDATE_COUNT_COMMS_STATUS):
          link_up = comms_status[source_idx].links_up & self._link_type
          break
      # Links are regarded as DOWN, if comms_status is obsolete.
      results[link_name] = self._ShowLinkStatus(link_up)
      total_links += 1
      total_up_links += (1 if link_up else 0)

    if self._ignore_error:
      stoplight = stoplights.STOPLIGHT_ANY
    else:
      if total_links == 0:
        stoplight = stoplights.STOPLIGHT_ANY
      elif total_up_links == total_links:
        stoplight = stoplights.STOPLIGHT_NORMAL
      elif total_up_links == 0:
        stoplight = stoplights.STOPLIGHT_ERROR
      else:
        stoplight = stoplights.STOPLIGHT_WARNING

    return self._DictToString(results), stoplight

class TetherCommsStatusPoFIndicator(BaseTetherCommsStatusIndicator):

  def __init__(self, name, show_label=True):
    super(TetherCommsStatusPoFIndicator, self).__init__(
        name, cvt.kTetherCommsLinkPof,
        [[cvt.kTetherDownSourceCsGsA, cvt.kTetherDownSourceCsA],
         [cvt.kTetherDownSourceCsB]], ['Link A', 'Link B'], show_label,
        ignore_error=True)

class TetherCommsStatusEoPIndicator(BaseTetherCommsStatusIndicator):

  def __init__(self, name, show_label=True):
    super(TetherCommsStatusEoPIndicator, self).__init__(
        name, cvt.kTetherCommsLinkEop,
        [[cvt.kTetherDownSourceCsGsA, cvt.kTetherDownSourceCsA],
         [cvt.kTetherDownSourceCsB]], ['Link A', 'Link B'], show_label,
        ignore_error=True)

class TetherCommsStatusWifiIndicator(BaseTetherCommsStatusIndicator):

  def __init__(self, name, show_label=True):
    super(TetherCommsStatusWifiIndicator, self).__init__(
        name, cvt.kTetherCommsLinkWifi,
        [[cvt.kTetherDownSourceCsGsA, cvt.kTetherDownSourceCsA],
         [cvt.kTetherDownSourceCsB]], ['Link A', 'Link B'], show_label)

redpajama_set_name: RedPajamaGithub


text:
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

using Prism.Mvvm;
using Prism.Commands;
using Prism.Events;

using BadgerJaus.Messages.Control;
using BadgerJaus.Messages.Management;
using BadgerJaus.Util;
using BadgerJaus.Services.Core;

using BadgerControlModule.Models;

namespace BadgerControlModule.ViewModels
{
    class BadgerRobotsInformationViewModel : BindableBase
    {
        protected readonly IEventAggregator _eventAggregator;
        BadgerControlSubsystem badgerControlSubsystem;
        Subsystem selectedSubsystem;
        Node selectedNode;
        BadgerJaus.Util.Component selectedComponent;
        ObservableCollection<Subsystem> discoveredSubsystems;
        List<Node> currentNodes;

        public BadgerRobotsInformationViewModel(IEventAggregator eventAggregator)
        {
            this._eventAggregator = eventAggregator;
            badgerControlSubsystem = BadgerControlSubsystem.GetInstance();
            Refresh = new DelegateCommand<object>(OnRefresh);
            Activate = new DelegateCommand<object>(OnActivate);
            Deactivate = new DelegateCommand<object>(OnDeactivate);
            RequestControl = new DelegateCommand<object>(OnRequestControl);
            ReleaseControl = new DelegateCommand<object>(OnReleaseControl);
            discoveredSubsystems = badgerControlSubsystem.DiscoveredSubsystems;
            discoveredSubsystems.CollectionChanged += DiscoveredSubsystemsUpdated;
            currentNodes = new List<Node>();
        }

        private void DiscoveredSubsystemsUpdated(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            Application.Current.Dispatcher.Invoke(new System.Action(() =>
            {
                SubsystemList = badgerControlSubsystem.DiscoveredSubsystems;
            }
            ));
        }

        public ObservableCollection<Subsystem> SubsystemList
        {
            get { return discoveredSubsystems; }
            private set
            {
                discoveredSubsystems = value;
            }
        }

        public Subsystem SelectedSubsystem
        {
            get { return selectedSubsystem; }
            set { selectedSubsystem = value; }
        }

        public List<Node> CurrentNodes
        {
            get { return currentNodes; }
            private set { currentNodes = value; }
        }

        public ICommand Refresh
        {
            get;
            private set;
        }

        public ICommand Activate
        {
            get;
            private set;
        }

        public ICommand Deactivate
        {
            get;
            private set;
        }

        public ICommand RequestControl
        {
            get;
            private set;
        }

        public ICommand ReleaseControl
        {
            get;
            private set;
        }

        public void OnRefresh(object arg)
        {
            //CurrentNodes = selectedSubsystem.NodeList;
            currentNodes.Clear();
            foreach(Node node in selectedSubsystem.NodeList)
            {
                currentNodes.Add(node);
            }
            //SubsystemList = badgerControlSubsystem.DiscoveredSubsystems;
            /*
            JausAddress targetAddress = GenerateCurrentAddress();

            if (targetAddress == null)
                return;

            QueryStatus queryStatus = new QueryStatus();
            queryStatus.SetSource(badgerControlSubsystem.LocalAddress);
            queryStatus.SetDestination(targetAddress);

            Transport.SendMessage(queryStatus);
            */
        }

        public void OnRequestControl(object arg)
        {
            JausAddress targetAddress = GenerateCurrentAddress();

            if (targetAddress == null)
                return;

            RequestControl requestControl = new RequestControl();
            requestControl.SetAuthorityCode(BadgerControlSubsystem.AUTHORITY_LEVEL);
            requestControl.SetSource(badgerControlSubsystem.LocalAddress);
            requestControl.SetDestination(targetAddress);

            Transport.SendMessage(requestControl);
        }

        public void OnReleaseControl(object arg)
        {
            JausAddress targetAddress = GenerateCurrentAddress();

            if (targetAddress == null)
                return;

            ReleaseControl releaseControl = new ReleaseControl();
            releaseControl.SetSource(badgerControlSubsystem.LocalAddress);
            releaseControl.SetDestination(targetAddress);

            Transport.SendMessage(releaseControl);
        }

        public void OnActivate(object arg)
        {
            JausAddress targetAddress = GenerateCurrentAddress();

            if (targetAddress == null)
                return;

            Resume resume = new Resume();
            resume.SetSource(badgerControlSubsystem.LocalAddress);
            resume.SetDestination(targetAddress);

            Transport.SendMessage(resume);
        }

        public void OnDeactivate(object arg)
        {
            JausAddress targetAddress = GenerateCurrentAddress();

            if (targetAddress == null)
                return;

            Shutdown shutdown = new Shutdown();
            shutdown.SetSource(badgerControlSubsystem.LocalAddress);
            shutdown.SetDestination(targetAddress);

            Transport.SendMessage(shutdown);
        }

        private JausAddress GenerateCurrentAddress()
        {
            JausAddress targetAddress;

            if (selectedSubsystem == null)
                return null;

            targetAddress = new JausAddress(selectedSubsystem.SubsystemID, 255, 255);
            if (selectedNode != null)
            {
                targetAddress.setNode(selectedNode.NodeID);
            }
            if (selectedComponent != null)
            {
                targetAddress.setComponent(selectedComponent.ComponentID);
            }

            return targetAddress;
        }

        public void SelectedNodeComponentChanged(object sender, System.Windows.RoutedPropertyChangedEventArgs<object> e)
        {
            selectedComponent = e.NewValue as Component;
            if(selectedComponent != null)
            {
                selectedNode = selectedComponent.GetNode();
            }
            else
            {
                selectedNode = e.NewValue as Node;
            }
        }

        public void SubsystemSelected(object sender, SelectionChangedEventArgs e)
        {
            currentNodes.Clear();
            foreach (Node node in selectedSubsystem.NodeList)
            {
                currentNodes.Add(node);
            }
        }
    }
}


text:
using namespace std;

namespace dai {

class FrameListener;

class PlaybackWorker : public QObject, public FrameGenerator
{
    Q_OBJECT

    friend class PlaybackControl;
    friend class FrameListener;

public:
    PlaybackWorker();
    ~PlaybackWorker();
    void pause();

public slots:
    void run();
    void stop();

protected:
    void produceFrames(QHashDataFrames &output) override;
    shared_ptr<QHashDataFrames> allocateMemory() override;

private:
    void enablePlayLoop(bool value);
    void setFPS(float fps);
    bool addInstance(shared_ptr<StreamInstance> instance);
    void removeInstance(shared_ptr<StreamInstance> instance);
    void clearInstances();

    void openAllInstances();
    void closeAllInstances();

    QList<shared_ptr<StreamInstance>>  m_instances;
    bool                               m_playloop_enabled;
    qint64                             m_slotTime;
    bool                               m_running;
    bool                               m_paused;
    DataFrame::SupportedFrames         m_supportedFrames;
};

} // End Namespace

#endif // PLAYBACKWORKER_H


text:
import win32process
import win32api
import win32con
import ctypes
import os, sys, string
TH32CS_SNAPPROCESS = 0x00000002

class PROCESSENTRY32(ctypes.Structure):
     _fields_ = [("dwSize", ctypes.c_ulong),
                 ("cntUsage", ctypes.c_ulong),
                 ("th32ProcessID", ctypes.c_ulong),
                 ("th32DefaultHeapID", ctypes.c_ulong),
                 ("th32ModuleID", ctypes.c_ulong),
                 ("cntThreads", ctypes.c_ulong),
                 ("th32ParentProcessID", ctypes.c_ulong),
                 ("pcPriClassBase", ctypes.c_ulong),
                 ("dwFlags", ctypes.c_ulong),
                 ("szExeFile", ctypes.c_char * 260)]

def getProcList():
    CreateToolhelp32Snapshot = ctypes.windll.kernel32.CreateToolhelp32Snapshot
    Process32First = ctypes.windll.kernel32.Process32First
    Process32Next = ctypes.windll.kernel32.Process32Next
    CloseHandle = ctypes.windll.kernel32.CloseHandle

    hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)

    pe32 = PROCESSENTRY32()
    pe32.dwSize = ctypes.sizeof(PROCESSENTRY32)
    if Process32First(hProcessSnap,ctypes.byref(pe32)) == False:
        return
    while True:
        yield pe32
        if Process32Next(hProcessSnap,ctypes.byref(pe32)) == False:
            break
    CloseHandle(hProcessSnap)

def GetProcessModules( pid ):
    handle   = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, False, pid )
    hModule  = win32process.EnumProcessModules(handle)
    temp=[]
    for i in hModule:
        temp.append([hex(i),debugfile(win32process.GetModuleFileNameEx(handle,i))])
    win32api.CloseHandle(handle)
    return temp

def CloseProcess( pid ):
    handle   = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, False, pid )
    exitcode = win32process.GetExitCodeProcess( handle )
    win32api.TerminateProcess(handle, exitcode)
    win32api.CloseHandle(handle)

def debugfile(file):
    if (file.split("\\")[-1]=="smss.exe"):
        file = "C:\\WINDOWS\\system32\\smss.exe"
        return file
    elif (file.split("\\")[-1]=="csrss.exe"):
        file = "C:\\WINDOWS\\system32\\csrss.exe"
        return file
    elif (file.split("\\")[-1]=="winlogon.exe"):
        file = "C:\\WINDOWS\\system32\\winlogon.exe"
        return file
    else:
        return file

if __name__ =='__main__':
    #调用procup.dll的enableDebugPriv函数对本进程提权
    procupdll=ctypes.cdll.LoadLibrary("InjectAssist.dll")
    self_pid = procupdll.GetPIDbyName('services.exe')
    print self_pid
    if procupdll.EnableOpenprocPriv()==0:
        print "提权失败"

    count = 0
    procList = getProcList()
    for proc in procList:
        count+=1
        print("name=%s\tfather=%d\tid=%d" % (proc.szExeFile, proc.th32ParentProcessID, proc.th32ProcessID))
        try:
            TempGet=GetProcessModules(proc.th32ProcessID)
        except Exception, e:
            print "pid:%d can't read"%(proc.th32ProcessID)
            continue
        #TempGet[0][1].split("\\")[-1] 路径的最后一部分

        #'''
        #枚举进程调用所有模块
        for tempnum in range(0,len(TempGet)):
            try:
                print TempGet
            except Exception,e:
                print e
        #'''

    print "进程数:%d"%(count)


text:
package com.travelport.schema.air_v29_0;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import com.travelport.schema.common_v29_0.TypeTicketStatus;

/**
 *
Java class for anonymous complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <attribute name="Number" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
 *       <attribute name="Status" use="required" type="{http://www.travelport.com/schema/common_v29_0}typeTicketStatus" />
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
@XmlRootElement(name = "ConjunctedTicketInfo")
public class ConjunctedTicketInfo {

    @XmlAttribute(name = "Number", required = true)
    protected String number;
    @XmlAttribute(name = "Status", required = true)
    protected TypeTicketStatus status;

    /**
     * Gets the value of the number property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getNumber() {
        return number;
    }

    /**
     * Sets the value of the number property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setNumber(String value) {
        this.number = value;
    }

    /**
     * Gets the value of the status property.
     *
     * @return
     *     possible object is
     *     {@link TypeTicketStatus }
     *
     */
    public TypeTicketStatus getStatus() {
        return status;
    }

    /**
     * Sets the value of the status property.
     *
     * @param value
     *     allowed object is
     *     {@link TypeTicketStatus }
     *
     */
    public void setStatus(TypeTicketStatus value) {
        this.status = value;
    }

}


text:
<!DOCTYPE html>

<meta charset="UTF-8">

<title>class RubyProf::FlatPrinter - ruby-prof</title>

<link href="../css/fonts.css" rel="stylesheet">
<link href="../css/rdoc.css" rel="stylesheet">

    Home

    Pages
    Classes
    Methods

  <form action="#" method="get" accept-charset="utf-8">

      <input id="search-field" role="combobox" aria-label="Search"
             aria-autocomplete="list" aria-controls="search-results"
             type="text" name="search" placeholder="Search" spellcheck="false"
             title="Type to search, Up and Down to navigate, Enter to load">

  </form>

Parent

RubyProf::AbstractPrinter

Methods

#sort_method

    class RubyProf::FlatPrinter

Generates flat profile
reports as text. To use the flat printer:

result = RubyProf.profile do
  [code to profile]
end

printer = RubyProf::FlatPrinter.new(result)
printer.print(STDOUT, {})

Public Instance Methods

          sort_method()

          click to toggle source

Override for this printer to sort by self time by default

# File lib/ruby-prof/printers/flat_printer.rb, line 15
def sort_method
  @options[:sort_method] || :self_time
end

Validate

Generated by RDoc 4.2.0.

Based on Darkfish by Michael Granger.


text:
/**
 * @author v.lugovksy
 * created on 16.12.2015
 */
(function () {
  'use strict';

  angular.module('BlurAdmin.theme.components')
      .directive('backTop', backTop);

  /** @ngInject */
  function backTop() {
    return {
      restrict: 'E',
      templateUrl: 'app/theme/components/backTop/backTop.html',
      controller: function () {
        $('#backTop').backTop({
          'position': 200,
          'speed': 100
        });
      }
    };
  }

})();


text:
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'safe_update'

outdated_gems = []
outdated_gems << SafeUpdate::OutdatedGem.new(
  gem_name: 'reform-rails',
  newest: '1.2.3',
  installed: '1.2.1',
  requested: '~> 1.2.0',
)

outdated_gems << SafeUpdate::OutdatedGem.new(
  gem_name: 'rspec',
  newest: '1.2.3',
  installed: '1.2.1',
  requested: '~> 1.2.0',
)

outdated_gems << SafeUpdate::OutdatedGem.new(
  gem_name: 'byebug',
  newest: '1.2.3',
  installed: '1.2.1',
  requested: '~> 1.2.0',
)

outdated_gems << SafeUpdate::OutdatedGem.new(
  gem_name: 'bullet',
  newest: '3.2.1',
  installed: '1.2.1',
)

states = [
  SafeUpdate::OutdatedGem::STATUS_PENDING,
  SafeUpdate::OutdatedGem::STATUS_UPDATING,
  SafeUpdate::OutdatedGem::STATUS_TESTING,
  SafeUpdate::OutdatedGem::STATUS_UPDATED,
  SafeUpdate::OutdatedGem::STATUS_UNCHANGED,
  SafeUpdate::OutdatedGem::STATUS_TESTS_FAIL,
]

outdated_gems.map do |outdated_gem|
  outdated_gem.instance_variable_set(
    :@current_status,
    states.sample
  )
end

presenter = SafeUpdate::Presenter.new
Thread.new { presenter.call(outdated_gems) }
20.times do
  sleep 0.25
  outdated_gems.sample.instance_variable_set(
    :@current_status,
    states.sample
  )
end
presenter.stop


text:
import unittest

from cupy import testing

@testing.gpu
class TestElementwise(unittest.TestCase):

    @testing.for_int_dtypes()
    @testing.numpy_cupy_array_equal()
    def check_unary_int(self, name, xp, dtype):
        a = xp.array([-3, -2, -1, 0, 1, 2, 3], dtype=dtype)
        return getattr(xp, name)(a)

    @testing.for_int_dtypes()
    @testing.numpy_cupy_array_equal()
    def check_binary_int(self, name, xp, dtype):
        a = xp.array([-3, -2, -1, 0, 1, 2, 3], dtype=dtype)
        b = xp.array([0, 1, 2, 3, 4, 5, 6], dtype=dtype)
        return getattr(xp, name)(a, b)

    def test_bitwise_and(self):
        self.check_binary_int('bitwise_and')

    def test_bitwise_or(self):
        self.check_binary_int('bitwise_or')

    def test_bitwise_xor(self):
        self.check_binary_int('bitwise_xor')

    def test_invert(self):
        self.check_unary_int('invert')

    def test_left_shift(self):
        self.check_binary_int('left_shift')

    def test_right_shift(self):
        self.check_binary_int('right_shift')


text:
package psidev.psi.mi.jami.utils.clone;

import psidev.psi.mi.jami.model.*;
import psidev.psi.mi.jami.model.impl.DefaultFeature;
import psidev.psi.mi.jami.model.impl.DefaultFeatureEvidence;
import psidev.psi.mi.jami.model.impl.DefaultModelledFeature;

/**
 * Utility class for cloning a participant candidate
 *
 * @author Marine Dumousseau (marine@ebi.ac.uk)
 * @version $Id$
 * @since
13/02/13

 */
public class ParticipantCandidateCloner {

    /**
     *
     * This method will copy properties of participant candidate source to participant candidate target and will override all the other properties of Target participant candidate.
     * This method will ignore interaction
     *
     * @param source a {@link psidev.psi.mi.jami.model.ExperimentalParticipantCandidate} object.
     * @param target a {@link psidev.psi.mi.jami.model.ExperimentalParticipantCandidate} object.
     * @param createNewFeature If true, this method will clone each feature from source instead of reusing the feature instances from source.
     *                         It will then set the experimental entity of the cloned features to target
     */
    public static void copyAndOverrideExperimentalCandidateProperties(ExperimentalParticipantCandidate source,
                                                                    ExperimentalParticipantCandidate target,
                                                                    boolean createNewFeature){
        if (source != null && target != null){
            target.setInteractor(source.getInteractor());
            target.setStoichiometry(source.getStoichiometry());

            // copy collections
            target.getCausalRelationships().clear();
            target.getCausalRelationships().addAll(source.getCausalRelationships());

            // copy features or create new ones
            if (!createNewFeature){
                target.getFeatures().clear();
                target.getFeatures().addAll(source.getFeatures());
            }
            else {
                target.getFeatures().clear();
                for (FeatureEvidence f : source.getFeatures()){
                    FeatureEvidence clone = new DefaultFeatureEvidence();
                    FeatureCloner.copyAndOverrideFeatureEvidenceProperties(f, clone);
                    target.addFeature(clone);
                }
            }
        }
    }

    /**
     *
     * This method will copy properties of modelled participant candidate source in modelled participant candidate target and will override all the other properties of Target modelled participant.
     * This method will ignore interaction
     *
     * @param source a {@link psidev.psi.mi.jami.model.ModelledParticipantCandidate} object.
     * @param target a {@link psidev.psi.mi.jami.model.ModelledParticipantCandidate} object.
     * @param createNewFeature If true, this method will clone each feature from source instead of reusing the feature instances from source.
     *                         It will then set the modelledParticipant of the cloned features to target
     */
    public static void copyAndOverrideModelledPCandidateProperties(ModelledParticipantCandidate source,
                                                                   ModelledParticipantCandidate target,
                                                                   boolean createNewFeature){
        if (source != null && target != null){
            target.setInteractor(source.getInteractor());
            target.setStoichiometry(source.getStoichiometry());

            // copy collections
            target.getCausalRelationships().clear();
            target.getCausalRelationships().addAll(source.getCausalRelationships());

            // copy features or create new ones
            if (!createNewFeature){
                target.getFeatures().clear();
                target.getFeatures().addAll(source.getFeatures());
            }
            else {
                target.getFeatures().clear();
                for (ModelledFeature f : source.getFeatures()){
                    ModelledFeature clone = new DefaultModelledFeature();
                    FeatureCloner.copyAndOverrideModelledFeaturesProperties(f, clone);
                    target.addFeature(clone);
                }
            }
        }
    }

    /**
     * This method will copy properties of participant candidate source in participant candidate
     * target and will override all the other properties of Target participant.
     *
     * @param source a {@link psidev.psi.mi.jami.model.ParticipantCandidate} object.
     * @param target a {@link psidev.psi.mi.jami.model.ParticipantCandidate} object.
     * @param createNewFeature If true, this method will clone each feature from source instead of reusing the feature instances from source.
     */
    public static void copyAndOverrideBasicCandidateProperties(ParticipantCandidate source,
                                                               ParticipantCandidate target,
                                                               boolean createNewFeature){
        if (source != null && target != null){
            target.setInteractor(source.getInteractor());
            target.setStoichiometry(source.getStoichiometry());

            // copy collections
            target.getCausalRelationships().clear();
            target.getCausalRelationships().addAll(source.getCausalRelationships());

            // copy features or create new ones
            if (!createNewFeature){
                target.getFeatures().clear();
                target.addAllFeatures(source.getFeatures());
            }
            else {
                target.getFeatures().clear();
                for (Object f : source.getFeatures()){
                    Feature clone = new DefaultFeature();
                    FeatureCloner.copyAndOverrideBasicFeaturesProperties((Feature)f, clone);
                    target.addFeature(clone);
                }
            }
        }
    }
}


text:
from nectar.config import key_path
from nectar.crypto import CryptoBox, SecretBox, load_key
from nectar.proto import Ack, PomaresProtocol, PubKeyReply
from nectar.proto import decompress_buff, compress_buff, encode, decode
from nectar.utils import logger
from nectar import routes
import asyncio

class PomaresClient:
    def __init__(self, address, key_path, server_pub_key, command):
        self.keyobj = load_key(key_path)
        logger.debug("client init_box pk: {}".format(self.keyobj.pk))
        logger.debug("client init_box sk: {}".format(self.keyobj.sk))
        self.command = command
        PomaresProtocol.route = self.route
        self.host, self.port = address
        self.server_pub_key = server_pub_key

        self.do_handshake_init()

    def do_handshake_init(self):
        logger.debug('do_handshake_init()')
        # send my pubkey to server
        handshk_payload = compress_buff(encode(PubKeyReply(self.keyobj.pk)))
        self.client_prot = PomaresProtocol(handshk_payload)

    def do_handshake(self, handler, msg):
        logger.debug('do_handshake()')
        # expect server to send secret key to init_box
        handler.init_box = CryptoBox(self.keyobj)
        handler.init_box.box_with(self.server_pub_key)

        # receive server secretkey
        msg = handler.init_box.decrypt(msg)
        msg = decode(msg)
        handler.box = SecretBox(key=msg.key)
        handler.handshaked = True
        logger.debug('HANDSHAKED2')

        # XXX send first command msg
        logger.debug('sending command msg')
        self.send_command(handler)

    def send_command(self, handler):
        new_msg = encode(self.command)
        new_msg = handler.box.encrypt(new_msg)
        handler.send_data(compress_buff(new_msg))

    def route(self, handler, msg):
        logger.debug('routing msg: {}'.format(msg))
        try:
            msg = decompress_buff(msg)
            logger.debug('decompressed msg: {}'.format(msg))
            if not handler.handshaked:
                logger.debug('decoded msg: {}'.format(msg))
                # at this point we can only expect PubKeyReply
                self.do_handshake(handler, msg)
            else:
                # receive messages:
                msg = handler.box.decrypt(msg)
                request = decode(msg)
                logger.debug('got request: {}'.format(request))

                # TODO treat server replies here
                routes.talk_client(handler, request)

        except Exception as err:
            logger.debug('ignoring request [bad key] {}'.format(err))
            raise

    def run(self):
        loop = asyncio.get_event_loop()
        coro = loop.create_connection(lambda: self.client_prot,
                                      self.host, self.port)
        loop.run_until_complete(coro)
        loop.run_forever()
        loop.close()

class PomaresAdminClient:
    def __init__(self, admin_sock, commands):
        """opens a client in admin_sock and iterates over commands
        using talk()"""
        self.admin_sock = admin_sock
        self.commands = commands
        self.reader = None
        self.writer = None

    @asyncio.coroutine
    def talk(self):
        self.reader, self.writer = yield from \
            asyncio.open_unix_connection(self.admin_sock)
        for cmd in iter(self.commands):
            logger.debug('sending cmd: {}'.format(cmd))
            yield from self.send(cmd)
            yield from self.read()

    @asyncio.coroutine
    def send(self, payload):
        self.writer.write(bytes('{}\n'.format(payload).encode()))
        yield from self.writer.drain()

    @asyncio.coroutine
    def read(self):
        answer = yield from self.reader.readline()
        logger.debug('got data: {}'.format(answer))
        return answer

    def run(self):
        "runs event loop"
        loop = asyncio.get_event_loop()
        tasks = asyncio.async(self.talk())
        loop.run_until_complete(tasks)
        loop.close()

if __name__ == '__main__':
    import sys
    server_pub_key = load_key(key_path+'/local.key').pk
    my_key = key_path+'/my.key'
    if len(sys.argv) > 1:
        command = sys.argv[1]
    else:
        command = "default first command message"
    c = PomaresClient(('127.0.0.1', 8080), my_key, server_pub_key,
                      Ack(command))
    c.run()


text:
package org.sezavar.cj.problem;

import org.sezavar.cj.util.GcjUtil;
import org.sezavar.cj.util.InputOutputType;

public class StoreCredit extends Problem {

	public static void main(String[] args) {
		StoreCredit storeCredit = new StoreCredit();
		storeCredit.solveSetsFor(InputOutputType.LARGE);
	}

	@Override
	protected StringBuffer _solve() {
		return this.rs;
	}

	@Override
	protected StringBuffer _solveEachSet() {
		int c = Integer.valueOf(this.reader.nextLine().trim()); // Credit amount
		int i = Integer.valueOf(this.reader.nextLine()); // Number of items
		int[] prices = GcjUtil
				.lineToArrayOfInts(this.reader.nextLine(), " ");
		for (int j = 0; j < prices.length; j++) {
			for (int k = j + 1; k < prices.length; k++) {
				if (prices[j] + prices[k] == c) {
					this.rs.append((j + 1) + " " + (k + 1));
				}
			}
		}
		return this.rs;
	}

}


text:
FOUNDATION_EXPORT double DownloadManagerVersionNumber;

//! Project version string for DownloadManager.
FOUNDATION_EXPORT const unsigned char DownloadManagerVersionString[];

// In this header, you should import all the public headers of your framework using statements like #import <DownloadManager/PublicHeader.h>


text:
<?xml version="1.0" encoding="ISO-8859-15"?>
<citygml:CityModel xmlns:gml="http://www.opengis.net/gml"
	xmlns:xlink="http://www.w3.org/1999/xlink"
	xmlns:xAL="urn:oasis:names:tc:ciq:xsdschema:xAL:2.0"
	xmlns:noise="http://www.citygml.org/ade/noise_de"
	xmlns:citygml="http://www.citygml.org/citygml/1/0/0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.citygml.org/citygml/1/0/0 ../CityGML.xsd http://www.citygml.org/ade/noise_de ./CityGML-NoiseADE-0-5-0.xsd">
	<gml:name>Eisenbahnmodell</gml:name>
	<gml:boundedBy>
		<gml:Envelope srsName="EPSG:31466">
			<gml:pos srsDimension="3">2523800.0 5705800.0 140.4</gml:pos>
			<gml:pos srsDimension="3">2526200.0 5708200.0 252.6</gml:pos>
		</gml:Envelope>
	</gml:boundedBy>
	<citygml:cityObjectMember>
		<citygml:Railway gml:id="CRW_0815">
			<gml:name>ABC-098-7654</gml:name>
			<gml:boundedBy>
				<gml:Envelope srsName="EPSG:31466">
					<gml:pos srsDimension="3">2523800.0 5705800.0 140.4</gml:pos>
					<gml:pos srsDimension="3">2526200.0 5708200.0 252.6</gml:pos>
				</gml:Envelope>
			</gml:boundedBy>
			<!--
			<citygml:creationDate>1967-08-13</citygml:creationDate>
			<citygml:terminationDate>1967-08-13</citygml:terminationDate>
			-->
			<!-- Code (fiktiv) für Straßenbahn -->
			<citygml:function>1234</citygml:function>
			<!--
			<citygml:lod0Network>
				<gml:CompositeCurve srsName="EPSG:31466">
					<gml:curveMember>
								<gml:LineString>
									<gml:coordinates decimal="." cs="," ts=" ">2524175,5707335,188 2524181,5707338,188 2524185,5707330,188 2524179,5707327,188</gml:coordinates>
								</gml:LineString>
					</gml:curveMember>
					<gml:curveMember>
								<gml:LineString>
									<gml:coordinates decimal="." cs="," ts=" ">2524175,5707335,188 2524181,5707338,188 2524185,5707330,188 2524179,5707327,188</gml:coordinates>
								</gml:LineString>
					</gml:curveMember>
				</gml:CompositeCurve>
			</citygml:lod0Network>
			-->
			<noise:noiseRailwaySegmentProperty>
				<!-- Segment 1, mit zwei Zügen -->
				<noise:NoiseRailwaySegment gml:id="CNRS_0815">
					<gml:boundedBy>
						<gml:Envelope srsName="EPSG:31466">
							<gml:pos srsDimension="3">2523800.0 5705800.0 140.4</gml:pos>
							<gml:pos srsDimension="3">2526200.0 5708200.0 252.6</gml:pos>
						</gml:Envelope>
					</gml:boundedBy>
					<!--
					<citygml:creationDate>1967-08-13</citygml:creationDate>
					<citygml:terminationDate>1967-08-13</citygml:terminationDate>
					-->
					<citygml:externalReference>
						<citygml:informationSystem>file:///L:/FB43_GeoDatZ/2006172_Laermkartierung MUNLV/Katasterbehoerde/SO/05974000.zip</citygml:informationSystem>
						<citygml:externalObject>
							<citygml:name>Eisenbahn</citygml:name>
						</citygml:externalObject>
					</citygml:externalReference>
					<!--
					<citygml:doubleAttribute name="test">
						<citygml:value>765.56</citygml:value>
					</citygml:doubleAttribute>
					-->
					<noise:railwaySurfaceMaterial>Schotterbett-Holzschwelle</noise:railwaySurfaceMaterial>
					<noise:railwaySurfaceCorrection uom="dB">3.123</noise:railwaySurfaceCorrection>
					<noise:bridge>1</noise:bridge>
					<noise:crossing>0</noise:crossing>
					<noise:curveRadius uom="m">234.56</noise:curveRadius>
					<noise:additionalCorrectionSegment uom="dB">-3.123</noise:additionalCorrectionSegment>
					<noise:lod0BaseLine>
						<gml:LineString srsName="EPSG:31466" srsDimension="3">
							<gml:coordinates decimal="." cs="," ts=" ">2524175,5707335,188 2524181,5707338,188 2524185,5707330,188 2524179,5707327,188</gml:coordinates>
						</gml:LineString>
					</noise:lod0BaseLine>
					<noise:usedBy>
						<!-- Zug 1 -->
						<noise:Train gml:id="CTR_0815">
							<!--
							<gml:description>Musterzug von A nach B, verkehrt täglich uswusw.</gml:description>
							<gml:name>Musterzug1</gml:name>
							-->
							<noise:trainType>Fahrzeuge mit Radscheibenbremsen</noise:trainType>
							<noise:trainTypeCorrection uom="dB">-2.123</noise:trainTypeCorrection>
							<noise:brakePortionDay uom="percent">12.123</noise:brakePortionDay>
							<noise:brakePortionEvening uom="percent">23.123</noise:brakePortionEvening>
							<noise:brakePortionNight uom="percent">34.123</noise:brakePortionNight>
							<noise:lengthDay uom="m">98.123</noise:lengthDay>
							<noise:lengthEvening uom="m">87.123</noise:lengthEvening>
							<noise:lengthNight uom="m">76.123</noise:lengthNight>
							<noise:speedDay uom="kmph">100.123</noise:speedDay>
							<noise:speedEvening uom="kmph">80.123</noise:speedEvening>
							<noise:speedNight uom="kmph">50.123</noise:speedNight>
							<noise:additionalCorrectionTrain uom="dB">-3.123</noise:additionalCorrectionTrain>
						</noise:Train>
					</noise:usedBy>
					<noise:usedBy>
						<!-- Zug 2 -->
						<noise:Train gml:id="CTR_0816">
							<noise:trainType>Fahrzeuge mit Radscheibenbremsen</noise:trainType>
							<noise:trainTypeCorrection uom="dB">-2.123</noise:trainTypeCorrection>
							<noise:brakePortionDay uom="percent">12.123</noise:brakePortionDay>
							<noise:brakePortionEvening uom="percent">23.123</noise:brakePortionEvening>
							<noise:brakePortionNight uom="percent">34.123</noise:brakePortionNight>
							<noise:lengthDay uom="m">98.123</noise:lengthDay>
							<noise:lengthEvening uom="m">87.123</noise:lengthEvening>
							<noise:lengthNight uom="m">76.123</noise:lengthNight>
							<noise:speedDay uom="kmph">100.123</noise:speedDay>
							<noise:speedEvening uom="kmph">80.123</noise:speedEvening>
							<noise:speedNight uom="kmph">50.123</noise:speedNight>
							<noise:additionalCorrectionTrain uom="dB">-3.123</noise:additionalCorrectionTrain>
						</noise:Train>
					</noise:usedBy>
				</noise:NoiseRailwaySegment>
			</noise:noiseRailwaySegmentProperty>
			<noise:noiseRailwaySegmentProperty>
				<!-- Segment 2 mit einem Zug -->
				<noise:NoiseRailwaySegment gml:id="CNRS_0816">
					<gml:boundedBy>
						<gml:Envelope srsName="EPSG:31466">
							<gml:pos srsDimension="3">2523800.0 5705800.0 140.4</gml:pos>
							<gml:pos srsDimension="3">2526200.0 5708200.0 252.6</gml:pos>
						</gml:Envelope>
					</gml:boundedBy>
					<!--
					<citygml:creationDate>1967-08-13</citygml:creationDate>
					<citygml:terminationDate>1967-08-13</citygml:terminationDate>
					-->
					<noise:railwaySurfaceMaterial>Schotterbett-Holzschwelle</noise:railwaySurfaceMaterial>
					<noise:railwaySurfaceCorrection uom="dB">3.123</noise:railwaySurfaceCorrection>
					<noise:bridge>true</noise:bridge>
					<noise:crossing>false</noise:crossing>
					<noise:curveRadius uom="m">234.123</noise:curveRadius>
					<noise:additionalCorrectionSegment uom="dB">-3.123</noise:additionalCorrectionSegment>
					<noise:lod0BaseLine>
						<gml:LineString srsName="EPSG:31466" srsDimension="3">
							<gml:coordinates decimal="." cs="," ts=" ">2524175,5707335,188 2524181,5707338,188 2524185,5707330,188 2524179,5707327,188</gml:coordinates>
						</gml:LineString>
					</noise:lod0BaseLine>
					<noise:usedBy>
						<noise:Train gml:id="CTR_0817">
							<noise:trainType>Fahrzeuge mit Radscheibenbremsen</noise:trainType>
							<noise:trainTypeCorrection uom="dB">-2.123</noise:trainTypeCorrection>
							<noise:brakePortionDay uom="percent">12.123</noise:brakePortionDay>
							<noise:brakePortionEvening uom="percent">23.123</noise:brakePortionEvening>
							<noise:brakePortionNight uom="percent">34.123</noise:brakePortionNight>
							<noise:lengthDay uom="m">98.123</noise:lengthDay>
							<noise:lengthEvening uom="m">87.123</noise:lengthEvening>
							<noise:lengthNight uom="m">76.123</noise:lengthNight>
							<noise:speedDay uom="kmph">100.123</noise:speedDay>
							<noise:speedEvening uom="kmph">80.123</noise:speedEvening>
							<noise:speedNight uom="kmph">50.123</noise:speedNight>
							<noise:additionalCorrectionTrain uom="dB">-3.123</noise:additionalCorrectionTrain>
						</noise:Train>
					</noise:usedBy>
				</noise:NoiseRailwaySegment>
			</noise:noiseRailwaySegmentProperty>
		</citygml:Railway>
	</citygml:cityObjectMember>
</citygml:CityModel>


text:
namespace Framework.UI.Input
{
    using System;
    using System.Threading.Tasks;

    /// <summary>
    /// This class allows delegating the commanding logic to methods passed as parameters,
    /// and enables a View to bind commands to objects that are not part of the element tree.
    /// </summary>
    /// <typeparam name="T">The type of the command parameter.</typeparam>
    public sealed class AsyncDelegateCommand<T> : AsyncCommand<T>
    {
        #region Fields

        private readonly Func<T, Task> execute;
        private readonly Func<T, bool> canExecute;

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="AsyncDelegateCommand{T}"/> class.
        /// </summary>
        /// <param name="execute">The execute.</param>
        public AsyncDelegateCommand(Func<T, Task> execute)
            : this(execute, null)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="AsyncDelegateCommand{T}"/> class.
        /// </summary>
        /// <param name="execute">The execute.</param>
        /// <param name="canExecute">The can execute.</param>
        public AsyncDelegateCommand(Func<T, Task> execute, Func<T, bool> canExecute)
        {
            this.execute = execute;
            this.canExecute = canExecute;
        }

        #endregion

        #region Command Members

        /// <summary>
        /// Determines whether this instance can execute.
        /// </summary>
        /// <param name="parameter">The command parameter.</param>
        /// <returns>
        /// <c>true</c> if this instance can execute; otherwise, <c>false</c>.
        /// </returns>
        public override bool CanExecute(T parameter)
        {
            if (this.canExecute != null)
            {
                return this.canExecute(parameter);
            }

            return true;
        }

        /// <summary>
        /// Executes this instance.
        /// </summary>
        /// <param name="parameter">The command parameter.</param>
        public override Task Execute(T parameter)
        {
            Task task = null;

            if (this.execute == null)
            {
                task = Task.FromResult<object>(null);
            }
            else
            {
                task = this.execute(parameter);
            }

            return task;
        }

        #endregion
    }
}


text:
package app

import (
	"fmt"
	"net/http"
	"strings"
	"time"

	"github.com/mattermost/platform/einterfaces"
	"github.com/mattermost/platform/model"
	"github.com/mattermost/platform/utils"
	"github.com/mssola/user_agent"
)

func AuthenticateUserForLogin(id, loginId, password, mfaToken, deviceId string, ldapOnly bool) (*model.User, *model.AppError) {
	if len(password) == 0 {
		err := model.NewLocAppError("AuthenticateUserForLogin", "api.user.login.blank_pwd.app_error", nil, "")
		err.StatusCode = http.StatusBadRequest
		return nil, err
	}

	var user *model.User
	var err *model.AppError

	if len(id) != 0 {
		if user, err = GetUser(id); err != nil {
			err.StatusCode = http.StatusBadRequest
			if einterfaces.GetMetricsInterface() != nil {
				einterfaces.GetMetricsInterface().IncrementLoginFail()
			}
			return nil, err
		}
	} else {
		if user, err = GetUserForLogin(loginId, ldapOnly); err != nil {
			if einterfaces.GetMetricsInterface() != nil {
				einterfaces.GetMetricsInterface().IncrementLoginFail()
			}
			return nil, err
		}
	}

	// and then authenticate them
	if user, err = authenticateUser(user, password, mfaToken); err != nil {
		if einterfaces.GetMetricsInterface() != nil {
			einterfaces.GetMetricsInterface().IncrementLoginFail()
		}
		return nil, err
	}

	if einterfaces.GetMetricsInterface() != nil {
		einterfaces.GetMetricsInterface().IncrementLogin()
	}

	return user, nil
}

func DoLogin(w http.ResponseWriter, r *http.Request, user *model.User, deviceId string) (*model.Session, *model.AppError) {
	session := &model.Session{UserId: user.Id, Roles: user.GetRawRoles(), DeviceId: deviceId, IsOAuth: false}

	maxAge := *utils.Cfg.ServiceSettings.SessionLengthWebInDays * 60 * 60 * 24

	if len(deviceId) > 0 {
		session.SetExpireInDays(*utils.Cfg.ServiceSettings.SessionLengthMobileInDays)

		// A special case where we logout of all other sessions with the same Id
		if err := RevokeSessionsForDeviceId(user.Id, deviceId, ""); err != nil {
			err.StatusCode = http.StatusInternalServerError
			return nil, err
		}
	} else {
		session.SetExpireInDays(*utils.Cfg.ServiceSettings.SessionLengthWebInDays)
	}

	ua := user_agent.New(r.UserAgent())

	plat := ua.Platform()
	if plat == "" {
		plat = "unknown"
	}

	os := ua.OS()
	if os == "" {
		os = "unknown"
	}

	bname, bversion := ua.Browser()
	if bname == "" {
		bname = "unknown"
	}

	if strings.Contains(r.UserAgent(), "Mattermost") {
		bname = "Desktop App"
	}

	if bversion == "" {
		bversion = "0.0"
	}

	session.AddProp(model.SESSION_PROP_PLATFORM, plat)
	session.AddProp(model.SESSION_PROP_OS, os)
	session.AddProp(model.SESSION_PROP_BROWSER, fmt.Sprintf("%v/%v", bname, bversion))

	var err *model.AppError
	if session, err = CreateSession(session); err != nil {
		err.StatusCode = http.StatusInternalServerError
		return nil, err
	}

	w.Header().Set(model.HEADER_TOKEN, session.Token)

	secure := false
	if GetProtocol(r) == "https" {
		secure = true
	}

	expiresAt := time.Unix(model.GetMillis()/1000+int64(maxAge), 0)
	sessionCookie := &http.Cookie{
		Name:     model.SESSION_COOKIE_TOKEN,
		Value:    session.Token,
		Path:     "/",
		MaxAge:   maxAge,
		Expires:  expiresAt,
		HttpOnly: true,
		Secure:   secure,
	}

	userCookie := &http.Cookie{
		Name:    model.SESSION_COOKIE_USER,
		Value:   user.Id,
		Path:    "/",
		MaxAge:  maxAge,
		Expires: expiresAt,
		Secure:  secure,
	}

	http.SetCookie(w, sessionCookie)
	http.SetCookie(w, userCookie)

	return session, nil
}

func GetProtocol(r *http.Request) string {
	if r.Header.Get(model.HEADER_FORWARDED_PROTO) == "https" || r.TLS != nil {
		return "https"
	} else {
		return "http"
	}
}


text:
from jsonloader import *
from refraction import *
from helmholtz import *
from laserstructure import *
import sys
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('filePath', type = str, nargs = '?')
parser.add_argument('steps', type = int, nargs = '?')
namespace = parser.parse_args(sys.argv[1:])
filePath = namespace.filePath
steps = namespace.steps

loader1 = JSONLoader(filePath)
loader1.loadJSON()
laser1 = Laser(loader1.parseJSONData())

calc1 = RefractionCalc(laser1.wavelength, laser1.concentration)
calc1.computeRefraction()

solver1 = HelmholtzSolver(steps, laser1.wavelength, laser1.thickness, calc1.refraction)
solver1.refractionMatrix()
solver1.find_neffective()
solver1.find_matrix()
solver1.coeffs(int(steps * 0.9))
solver1.find_Xforward()
solver1.find_Xrev()
solver1.Field()
solver1.Norm()

laser1.gridX = solver1.gridX
laser1.gridN = solver1.gridN
laser1.field = solver1.UTOTAL
laser1.plotRefraction()
laser1.plotField()


text:
"""
Premium Question
"""

__author__ = 'Daniel'

class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution:
    def __init__(self):
        self.cnt = 0

    def countUnivalSubtrees(self, root):
        """

        :type root: TreeNode
        :rtype: int
        """
        self.is_unival(root)
        return self.cnt

    def is_unival(self, cur):
        if not cur:
            return True

        is_left = self.is_unival(cur.left)
        is_right = self.is_unival(cur.right)  # attention to test condition shortcut
        if (not is_left or not is_right or
                    cur.left and cur.left.val != cur.val or
                    cur.right and cur.right.val != cur.val):
            is_uni = False
        else:
            is_uni = True
            self.cnt += 1

        return is_uni


text:
layout: default
title: Home
title: Games
---

          Games menu.

{% assign collection = site.games | sort:"display_order" | reverse %}
{% assign collection_name = "Games" %}

{% include collection_all.html %}


text:
@interface AppDelegate (AppStyle)

- (void)customAppStyle;

@end


text:
package org.kuali.coeus.common.committee.impl;

import org.kuali.coeus.sys.framework.auth.task.Task;
import org.kuali.coeus.sys.framework.auth.task.TaskAuthorizerBase;
import org.kuali.kra.infrastructure.Constants;
import org.kuali.kra.infrastructure.PermissionConstants;

/**
 * The Create Committee Authorizer checks to see if the user has
 * permission to create a committee. The user must have the ADD_COMMITTEE
 * permission in any of the units in order to create a committee.
 */
public class CreateCommitteeAuthorizer extends TaskAuthorizerBase {

    @Override
    public boolean isAuthorized(String userId, Task task) {
        return hasUnitPermission(userId, Constants.MODULE_NAMESPACE_PROTOCOL, PermissionConstants.ADD_COMMITTEE);
    }
}


text:
package com.xeiam.xchange.huobi.dto.marketdata;

import com.fasterxml.jackson.annotation.JsonProperty;

import java.math.BigDecimal;

/**
 * Created by Yingzhe on 12/30/2014.
 */
public class HuobiTicker {
    private final BigDecimal volume;
    private final BigDecimal last;
    private final BigDecimal sell;
    private final BigDecimal buy;
    private final BigDecimal high;
    private final BigDecimal low;

    public HuobiTicker(@JsonProperty("vol") BigDecimal volume, @JsonProperty("last") BigDecimal last, @JsonProperty("sell") BigDecimal sell, @JsonProperty("buy") BigDecimal buy, @JsonProperty("high") BigDecimal high, @JsonProperty("low") BigDecimal low) {
        this.volume = volume;
        this.last = last;
        this.sell = sell;
        this.buy = buy;
        this.high = high;
        this.low = low;
    }

    public BigDecimal getVolume() {
        return this.volume;
    }

    public BigDecimal getLast() {
        return this.last;
    }

    public BigDecimal getSell() {
        return this.sell;
    }

    public BigDecimal getBuy() {
        return this.buy;
    }

    public BigDecimal getHigh() {
        return this.high;
    }

    public BigDecimal getLow() {
        return this.low;
    }

    @Override
    public String toString() {
        return String.format("HuobiTicker[volume: %s, last: %s, sell: %s, buy: %s, high: %s, low: %s]", volume, last, sell, buy, high, low);
    }
}