text:
define([
  'dojo/_base/declare', 'dijit/_WidgetBase', 'dojo/on',
  'dojo/dom-class',
  'dojo/text!./templates/Tnseq.html', './AppBase', 'dojo/dom-construct',
  'dojo/_base/Deferred', 'dojo/aspect', 'dojo/_base/lang', 'dojo/domReady!', 'dijit/form/NumberTextBox',
  'dojo/query', 'dojo/dom', 'dijit/popup', 'dijit/Tooltip', 'dijit/Dialog', 'dijit/TooltipDialog',
  'dojo/NodeList-traverse', '../../WorkspaceManager', 'dojo/store/Memory', 'dojox/widget/Standby'
], function (
  declare, WidgetBase, on,
  domClass,
  Template, AppBase, domConstruct,
  Deferred, aspect, lang, domReady, NumberTextBox,
  query, dom, popup, Tooltip, Dialog, TooltipDialog,
  children, WorkspaceManager, Memory, Standby
) {
  return declare([AppBase], {
    baseClass: 'App Assembly',
    templateString: Template,
    applicationName: 'TnSeq',
    requireAuth: true,
    applicationLabel: 'Tn-Seq Analysis',
    applicationDescription: 'The Tn-Seq Analysis Service facilitates determination of essential and conditionally essential regions in bacterial genomes from data generated from transposon insertion sequencing (Tn-Seq) experiments.',
    applicationHelp: 'user_guides/services/tn_seq_analysis_service.html',
    tutorialLink: 'tutorial/tn-seq/tn-seq.html',
    pageTitle: 'Tn-Seq Analysis',
    libraryData: null,
    defaultPath: '',
    startingRows: 11,
    initConditions: 5,
    maxConditions: 10,
    conditionStore: null,
    hostGenomes: {
      9606.33: '', 6239.6: '', 7955.5: '', 7227.4: '', 9031.4: '', 9544.2: '', 10090.24: '', 9669.1: '', 10116.5: '', 9823.5: ''
    },

    listValues: function (obj) {
      var results = [];
      Object.keys(obj).forEach(function (key) {
        results.append(obj[key]);
      });
    },

    constructor: function () {

      this.addedLibs = { counter: 0 };
      this.addedCond = { counter: 0 };
      // these objects map dojo attach points to desired alias for ingestAttachPoint function
      // key is attach point array of values is alias
      // if there is no alias the key in the resulting object will be the same name as attach point
      this.pairToAttachPt1 = { read1: null, read2: null };
      this.pairConditionToAttachPt = { read1: null, read2: null, condition_paired: ['condition'] };
      this.advPairToAttachPt = { interleaved: null, insert_size_mean: null, insert_size_stdev: null };
      this.paramToAttachPt = { output_path: null, output_file: null, recipe: null };
      this.singleToAttachPt = { read: null };
      this.singleConditionToAttachPt = { read: null, condition_single: ['condition'] };
      this.conditionToAttachPt = { condition: ['condition', 'id', 'label'] };
      this.targetGenomeID = '';
      this.shapes = ['icon-square', 'icon-circle'];
      this.colors = ['blue', 'green', 'red', 'purple', 'orange'];
      this.color_counter = 0;
      this.shape_counter = 0;
      this.conditionStore = new Memory({ data: [] });
      this.libraryStore = new Memory({ data: [], idProperty: 'id' });
      this.libraryID = 0;
      this.exp_design = { checked: false };
    },

    startup: function () {
      if (this._started) {
        return;
      }
      if (this.requireAuth && (window.App.authorizationToken === null || window.App.authorizationToken === undefined)) {
        return;
      }
      this.inherited(arguments);
      var _self = this;
      _self.defaultPath = WorkspaceManager.getDefaultFolder() || _self.activeWorkspacePath;
      _self.output_path.set('value', _self.defaultPath);

      // create help dialog for infobutton's with infobuttoninfo div's
      this.emptyTable(this.libsTable, this.startingRows);
      // this.emptyTable(this.condTable, this.initConditions);

      // for initial rollout use two conditions. this will change when contrasts are specified and the condition table comes back
      var control = {
        id: 'control', condition: 'control', label: 'Control', icon: this.getConditionIcon()
      };
      var treatment = {
        id: 'treatment', condition: 'treatment', label: 'Treatment', icon: this.getConditionIcon()
      };
      // temporary until contrasts table added
      this.updateConditionStore(control, false);
      this.updateConditionStore(treatment, false);
      this.addedCond.counter = 2;

      // adjust validation for each of the attach points associated with read files
      Object.keys(this.pairToAttachPt1).concat(Object.keys(this.singleToAttachPt)).forEach(lang.hitch(this, function (attachname) {
        this[attachname].searchBox.validator = lang.hitch(this[attachname].searchBox, function (/* anything */ value, /* __Constraints */ constraints) {
          return (new RegExp('^(?:' + this._computeRegexp(constraints) + ')' + (this.required ? '' : '?') + '$')).test(value) &&
            (!this._isEmpty(value)) &&
            (this._isEmpty(value) || this.parse(value, constraints) !== undefined); // Boolean
        });
      }));
      // var handle = on(this.group_switch, "click", lang.hitch(this, function(evt){
      //  this.exp_design.checked = !this.exp_design.checked ? true : false;
      //  this.exp_design.value = this.exp_design.checked ? "on" : "off";
      //  this.onDesignToggle();
      // }));
      this.condition_single.labelFunc = this.showConditionLabels;
      this.condition_paired.labelFunc = this.showConditionLabels;
      // this.block_condition.show();

      // this.read1.set('value',"/" +  window.App.user.id +"/home/");
      // this.read2.set('value',"/" +  window.App.user.id +"/home/");
      // this.single_end_libs.set('value',"/" +  window.App.user.id +"/home/");
      // this.output_path.set('value',"/" +  window.App.user.id +"/home/");
      this._started = true;
    },

    onRecipeChange: function () {
      var strategy = this.recipe.get('value');
      if (strategy == 'resampling') {
        this.exp_design.checked = true;
      }
      else {
        this.exp_design.checked = false;
      }
      this.onDesignToggle();
    },
    onDesignToggle: function () {
      var disable = !this.exp_design.checked;
      // this.condition.set("disabled", disable);
      this.condition_single.set('disabled', disable);
      this.condition_paired.set('disabled', disable);
      if (disable) {
        // this.block_condition.show();
        this.numCondWidget.set('value', Number(1));
        this.destroyLibRow(true, 'design');
        // dojo.addClass(this.condTable, "disabled");
      }
      else {
        // this.block_condition.hide();
        this.numCondWidget.set('value', Number(this.addedCond.counter));
        this.destroyLibRow(false, 'design');
        // dojo.removeClass(this.condTable, "disabled");
      }
    },

    emptyTable: function (target, rowLimit) {
      for (var i = 0; i < rowLimit; i++) {
        var tr = target.insertRow(0);// domConstr.create("tr",{},this.libsTableBody);
        domConstruct.create('td', { innerHTML: "

" }, tr);
        domConstruct.create('td', { innerHTML: "

" }, tr);
        domConstruct.create('td', { innerHTML: "

" }, tr);
      }
    },

    getValues: function () {
      var assembly_values = {};
      var values = this.inherited(arguments);
      var pairedList = this.libraryStore.query({ type: 'paired' });
      var pairedAttrs = ['read1', 'read2'];
      var singleAttrs = ['read'];
      var condList = this.conditionStore.data;
      var singleList = this.libraryStore.query({ type: 'single' });
      var condLibs = [];
      var allLibs = {};
      this.ingestAttachPoints(this.paramToAttachPt, assembly_values);
      var defaultCond = 'control';
      // for (var k in values) {
      //   if(!k.startsWith("libdat_")){
      //     assembly_values[k]=values[k];
      //   }
      // }
      var combinedList = pairedList.concat(singleList);
      assembly_values.reference_genome_id = values.genome_name;
      if (this.exp_design.checked) {
        condList.forEach(function (condRecord) {
          for (var i = 0; i < combinedList.length; i++) {
            if (combinedList[i].condition == condRecord.condition) {
              condLibs.push(condRecord.condition);
              break;
            }
          }
        });
      }
      else {
        condLibs.push(defaultCond);
      }

      pairedList.forEach(function (libRecord) {
        var toAdd = {};
        var curCond = null;
        if ('condition' in libRecord && this.exp_design.checked) {
          // toAdd['condition'] = condLibs.indexOf(libRecord['condition']) + 1;
          curCond = libRecord.condition;
        }
        else {
          curCond = defaultCond;
        }
        pairedAttrs.forEach(function (attr) {
          toAdd[attr] = libRecord[attr];
        });
        // pairedLibs.push(toAdd);
        if ( !(curCond in allLibs)) {
          allLibs[curCond] = { replicates: [], library: curCond };
        }
        allLibs[curCond].replicates.push(toAdd);
      }, this);
      // if(pairedLibs.length){
      //   assembly_values["paired_end_libs"] = pairedLibs;
      // }
      if (condLibs.length) {
        assembly_values.experimental_conditions = condLibs;
      }
      singleList.forEach(function (libRecord) {
        var toAdd = {};
        var curCond = null;
        if ('condition' in libRecord && this.exp_design.checked) {
          // toAdd['condition'] = condLibs.indexOf(libRecord['condition']) + 1;
          curCond = libRecord.condition;
        }
        else {
          curCond = defaultCond;
        }
        singleAttrs.forEach(function (attr) {
          toAdd[attr] = libRecord[attr];
        });
        if ( !(curCond in allLibs)) {
          allLibs[curCond] = { replicates: [], library: curCond };
        }
        // singleLibs.push(toAdd);
        allLibs[curCond].replicates.push(toAdd);
      }, this);
      // if(singleLibs.length){
      //   assembly_values["single_end_libs"] = singleLibs;
      // }
      assembly_values.read_files = allLibs;
      if (assembly_values.recipe == 'resampling') {
        assembly_values.contrasts = [['control', 'treatment']];
      }
      else {
        assembly_values.contrasts = [['control']];
      }

      return assembly_values;

    },
    // gets values from dojo attach points listed in input_ptsi keys.
    // aliases them to input_pts values.  validates all values present if req
    ingestAttachPoints: function (input_pts, target, req) {
      req = typeof req !== 'undefined' ? req : true;
      var success = 1;
      var prevalidate_ids = ['read1', 'read2', 'read', 'output_path', 'condition', 'condition_single', 'condition_paired'];
      target.id = this.makeLibraryID(target.type);
      var duplicate = target.id in this.libraryStore.index;
      Object.keys(input_pts).forEach(function (attachname) {
        var cur_value = null;
        var incomplete = 0;
        var prevalidate = (prevalidate_ids.indexOf(attachname) > -1);// truth variable whether to do validation separate from form
        var targetnames = [attachname];
        if (input_pts[attachname]) {
          targetnames = input_pts[attachname];
        }
        if (attachname == 'read1' || attachname == 'read2' || attachname == 'read' || attachname == 'output_path') {
          cur_value = this[attachname].searchBox.value;// ? "/_uuid/"+this[attachname].searchBox.value : "";
          if (attachname == 'read2' && this.read2.searchBox.value == this.read1.searchBox.value) {
            this.read2.searchBox.value = '';
          }
          // cur_value=this[attachname].searchBox.get('value');
          // incomplete=((cur_value.replace(/^.*[\\\/]/, '')).length==0);
        }
        else if (attachname == 'condition') {
          cur_value = this[attachname].displayedValue;// ? "/_uuid/"+this[attachname].searchBox.value : "";
          // cur_value="/_uuid/"+this[attachname].searchBox.value;
          // cur_value=this[attachname].searchBox.get('value');
        }
        else {
          cur_value = this[attachname].value;
        }

        if (typeof (cur_value) == 'string') {
          cur_value = cur_value.trim();
        }
        // set validation state for widgets since they are non-blocking presubmission fields
        if (req && (duplicate || !cur_value || incomplete)) {
          if (prevalidate) {
            if (this[attachname].searchBox) {
              this[attachname].searchBox.validate(); // this should be whats done but it doesn't actually call the new validator
              this[attachname].searchBox._set('state', 'Error');
            }
            else {
              this[attachname].validate();
              this[attachname]._set('state', 'Error');
            }
            this[attachname].focus = true;
          }
          success = 0;
        }
        else {
          this[attachname]._set('state', '');
        }
        // set alias target values to cur_value and format values in resulting object
        targetnames.forEach(function (targetname) {
          target[targetname] = cur_value;
          if (target[targetname] != '') {
            target[targetname] = target[targetname] || undefined;
          }
          else if (target[targetname] == 'true') {
            target[targetname] = true;
          }
          else if (target[targetname] == 'false') {
            target[targetname] = false;
          }
        }, target);
      }, this);
      return (success);
    },
    showConditionLabels: function (item, store) {
      var label = item.condition + ' ' + item.icon;
      return label;
    },
    makeLibraryName: function (mode) {
      if (mode == 'paired') {
        var fn = this.read1.searchBox.get('displayedValue');
        var fn2 = this.read2.searchBox.get('displayedValue');
        var maxName = 14;
        if (fn.length > maxName) {
          fn = fn.substr(0, (maxName / 2) - 2) + '...' + fn.substr((fn.length - (maxName / 2)) + 2);
        }
        if (fn2.length > maxName) {
          fn2 = fn2.substr(0, (maxName / 2) - 2) + '...' + fn2.substr((fn2.length - (maxName / 2)) + 2);
        }
        return 'P(' + fn + ', ' + fn2 + ')';
      }

      var fn = this.read.searchBox.get('displayedValue');
      maxName = 24;
      if (fn.length > maxName) {
        fn = fn.substr(0, (maxName / 2) - 2) + '...' + fn.substr((fn.length - (maxName / 2)) + 2);
      }
      return 'S(' + fn + ')';

    },
    makeLibraryID: function (mode) {
      if (mode == 'paired') {
        var fn = this.read1.searchBox.get('value');
        var fn2 = this.read2.searchBox.get('value');
        return fn + fn2;
      }

      var fn = this.read.searchBox.get('value');
      return fn;

    },

    onReset: function (evt) {
      domClass.remove(this.domNode, 'Working');
      domClass.remove(this.domNode, 'Error');
      domClass.remove(this.domNode, 'Submitted');
      var toDestroy = [];
      this.libraryStore.data.forEach(lang.hitch(this, function (lrec) {
        toDestroy.push(lrec.id);
      }));
      // because its removing rows cells from array needs separate loop
      toDestroy.forEach(lang.hitch(this, function (id) {
        this.destroyLibRow(id, 'id');
      }));
    },

    makeConditionName: function () {
      return this.condition.get('displayedValue');
    },

    // counter is a widget for requirements checking
    increaseRows: function (targetTable, counter, counterWidget) {
      counter.counter += 1;
      if (typeof counterWidget != 'undefined') {
        counterWidget.set('value', Number(counter.counter));
      }
    },
    decreaseRows: function (targetTable, counter, counterWidget) {
      counter.counter -= 1;
      if (typeof counterWidget != 'undefined') {
        counterWidget.set('value', Number(counter.counter));
      }
    },
    getConditionIcon: function (query_id) {
      var result = '';
      if (!query_id) {
        result = "";
        this.color_counter = this.color_counter + 1 < this.colors.length ? this.color_counter + 1 : 0;
        this.shape_counter = this.shape_counter + 1 < this.shapes.length ? this.shape_counter + 1 : 0;
      }
      else {
        var conditionList = this.conditionStore.query({ id: query_id });
        result = conditionList.length ? conditionList[0].icon : "";
      }
      return result;
    },

    onAddCondition: function () {
      console.log('Create New Row', domConstruct);
      var lrec = {};
      var toIngest = this.conditionToAttachPt;
      var disable = !this.exp_design.checked;
      var chkPassed = this.ingestAttachPoints(toIngest, lrec);
      var conditionSize = this.conditionStore.data.length;
      if (this.addedCond.counter < this.maxConditions) {
        this.updateConditionStore(lrec, false);
      }
      // make sure all necessary fields, not disabled, available condition slots, and checking conditionSize checks dups
      if (chkPassed && !disable && this.addedCond.counter < this.maxConditions && conditionSize < this.conditionStore.data.length) {
        lrec.icon = this.getConditionIcon();
        var tr = this.condTable.insertRow(0);
        var td = domConstruct.create('td', { 'class': 'textcol conditiondata', innerHTML: '' }, tr);
        td.libRecord = lrec;
        td.innerHTML = "
" + this.makeConditionName() + '
';
        domConstruct.create('td', { 'class': 'iconcol', innerHTML: lrec.icon }, tr);
        var td2 = domConstruct.create('td', {
          'class': 'iconcol',
          innerHTML: ""
        }, tr);
        if (this.addedCond.counter < this.initConditions) {
          this.condTable.deleteRow(-1);
        }

        var handle = on(td2, 'click', lang.hitch(this, function (evt) {
          console.log('Delete Row');
          domConstruct.destroy(tr);
          this.updateConditionStore(lrec, true);
          this.decreaseRows(this.condTable, this.addedCond, this.numCondWidget);
          if (this.addedCond.counter < this.maxConditions) {
            var ntr = this.condTable.insertRow(-1);
            domConstruct.create('td', { innerHTML: "

" }, ntr);
            domConstruct.create('td', { innerHTML: "

" }, ntr);
            domConstruct.create('td', { innerHTML: "

" }, ntr);
          }
          this.condition_single.reset();
          this.condition_paired.reset();
          handle.remove();
          this.destroyLibRow(lrec.condition, 'condition');
        }));
        this.increaseRows(this.condTable, this.addedCond, this.numCondWidget);
      }
    },

    updateConditionStore: function (record, remove) {
      // if there is no real condition specified return
      if (!record.condition.trim() || !record.condition) {
        return;
      }
      if (remove) {
        var toRemove = this.conditionStore.query({ id: record.id });
        // remove condition from data store
        toRemove.forEach(function (obj) {
          if (obj.libraries) {
            obj.libraries.forEach(function (lib_row) {
              lib_row.remove();
            });
          }
          this.conditionStore.remove(obj.id);
        }, this);
      }
      else {
        this.conditionStore.put(record);
      }
      this.condition_paired.set('store', this.conditionStore);
      this.condition_single.set('store', this.conditionStore);
    },

    onAddSingle: function () {
      console.log('Create New Row', domConstruct);
      var lrec = { type: 'single' };
      var toIngest = this.exp_design.checked ? this.singleConditionToAttachPt : this.singleToAttachPt;
      var chkPassed = this.ingestAttachPoints(toIngest, lrec);
      if (chkPassed) {
        var tr = this.libsTable.insertRow(0);
        lrec.row = tr;
        var td = domConstruct.create('td', { 'class': 'textcol singledata', innerHTML: '' }, tr);
        // td.libRecord=lrec;
        td.innerHTML = "
" + this.makeLibraryName('single') + '
';
        var advPairInfo = [];
        if (lrec.condition) {
          advPairInfo.push('Condition:' + lrec.condition);
        }
        if (advPairInfo.length) {
          var condition_icon = this.getConditionIcon(lrec.condition);
          lrec.design = true;
          var tdinfo = domConstruct.create('td', { 'class': 'iconcol', innerHTML: condition_icon }, tr);
          new Tooltip({
            connectId: [tdinfo],
            label: advPairInfo.join('
')
          });
        }
        else {
          lrec.design = false;
          var tdinfo = domConstruct.create('td', { innerHTML: '' }, tr);
        }
        var td2 = domConstruct.create('td', {
          'class': 'iconcol',
          innerHTML: ""
        }, tr);
        if (this.addedLibs.counter < this.startingRows) {
          this.libsTable.deleteRow(-1);
        }
        var handle = on(td2, 'click', lang.hitch(this, function (evt) {
          this.destroyLibRow(lrec.id, 'id');
        }));
        lrec.handle = handle;
        this.libraryStore.put(lrec);
        this.increaseRows(this.libsTable, this.addedLibs, this.numlibs);
      }
    },

    destroyLibRow: function (query_id, id_type) {
      console.log('Delete Rows');
      var query_obj = {};
      query_obj[id_type] = query_id;
      var toRemove = this.libraryStore.query(query_obj);
      toRemove.forEach(function (obj) {
        domConstruct.destroy(obj.row);
        this.decreaseRows(this.libsTable, this.addedLibs, this.numlibs);
        if (this.addedLibs.counter < this.startingRows) {
          var ntr = this.libsTable.insertRow(-1);
          domConstruct.create('td', { innerHTML: "

" }, ntr);
          domConstruct.create('td', { innerHTML: "

" }, ntr);
          domConstruct.create('td', { innerHTML: "

" }, ntr);
        }
        obj.handle.remove();
        this.libraryStore.remove(obj.id);
      }, this);
    },

    onSuggestNameChange: function () {
      // var curRecipe = this.recipe.value;
    },

    onAddPair: function () {
      console.log('Create New Row', domConstruct);
      if (this.read1.searchBox.get('value') == this.read2.searchBox.get('value')) {
        var msg = 'READ FILE 1 and READ FILE 2 cannot be the same.';
        new Dialog({ title: 'Notice', content: msg }).show();
        return;
      }
      var lrec = { type: 'paired' };
      // If you want to disable advanced parameters while not shown this would be the place.
      // but for right now, if you set them and then hide them, they are still active
      var pairToIngest = this.exp_design.checked ? this.pairConditionToAttachPt : this.pairToAttachPt1;
      // pairToIngest=pairToIngest.concat(this.advPairToAttachPt);
      var chkPassed = this.ingestAttachPoints(pairToIngest, lrec);
      // this.ingestAttachPoints(this.advPairToAttachPt, lrec, false)
      if (chkPassed && lrec.read1 != lrec.read2) {
        var tr = this.libsTable.insertRow(0);
        lrec.row = tr;
        var td = domConstruct.create('td', { 'class': 'textcol pairdata', innerHTML: '' }, tr);
        td.libRecord = lrec;
        td.innerHTML = "
" + this.makeLibraryName('paired') + '
';
        var advPairInfo = [];
        if (lrec.condition) {
          advPairInfo.push('Condition:' + lrec.condition);
        }
        if (advPairInfo.length) {
          lrec.design = true;
          var condition_icon = this.getConditionIcon(lrec.condition);
          var tdinfo = domConstruct.create('td', { 'class': 'iconcol', innerHTML: condition_icon }, tr);
          new Tooltip({
            connectId: [tdinfo],
            label: advPairInfo.join('
')
          });
        }
        else {
          lrec.design = false;
          var tdinfo = domConstruct.create('td', { innerHTML: '' }, tr);
        }
        var td2 = domConstruct.create('td', {
          'class': 'iconcol',
          innerHTML: ""
        }, tr);
        if (this.addedLibs.counter < this.startingRows) {
          this.libsTable.deleteRow(-1);
        }
        var handle = on(td2, 'click', lang.hitch(this, function (evt) {
          this.destroyLibRow(lrec.id, 'id');
        }));
        lrec.handle = handle;
        this.libraryStore.put(lrec);
        this.increaseRows(this.libsTable, this.addedLibs, this.numlibs);
      }
    }

  });
});


text:
using content::BrowserThread;

namespace policy {

namespace {

// Max retry count for token fetching requests.
const int kMaxRequestAttemptCount = 5;

// OAuth token request retry delay in milliseconds.
const int kRequestRestartDelay = 3000;

}  // namespace

PolicyOAuth2TokenFetcher::PolicyOAuth2TokenFetcher() {
}

PolicyOAuth2TokenFetcher::~PolicyOAuth2TokenFetcher() {
}

void PolicyOAuth2TokenFetcher::StartWithSigninContext(
    net::URLRequestContextGetter* auth_context_getter,
    net::URLRequestContextGetter* system_context_getter,
    const TokenCallback& callback) {
  DCHECK(!refresh_token_fetcher_ && !access_token_fetcher_);

  auth_context_getter_ = auth_context_getter;
  system_context_getter_ = system_context_getter;
  callback_ = callback;
  StartFetchingRefreshToken();
}

void PolicyOAuth2TokenFetcher::StartWithAuthCode(
    const std::string& auth_code,
    net::URLRequestContextGetter* system_context_getter,
    const TokenCallback& callback) {
  DCHECK(!refresh_token_fetcher_ && !access_token_fetcher_);

  auth_code_ = auth_code;
  system_context_getter_ = system_context_getter;
  callback_ = callback;
  StartFetchingRefreshToken();
}

void PolicyOAuth2TokenFetcher::StartWithRefreshToken(
    const std::string& oauth2_refresh_token,
    net::URLRequestContextGetter* system_context_getter,
    const TokenCallback& callback) {
  DCHECK(!refresh_token_fetcher_ && !access_token_fetcher_);

  oauth2_refresh_token_ = oauth2_refresh_token;
  system_context_getter_ = system_context_getter;
  callback_ = callback;
  StartFetchingAccessToken();
}

void PolicyOAuth2TokenFetcher::StartFetchingRefreshToken() {
  if (auth_code_.empty()) {
    refresh_token_fetcher_.reset(new GaiaAuthFetcher(
        this, GaiaConstants::kChromeSource, auth_context_getter_.get()));
    refresh_token_fetcher_->StartCookieForOAuthLoginTokenExchange(
        std::string());
  } else {
    refresh_token_fetcher_.reset(new GaiaAuthFetcher(
        this, GaiaConstants::kChromeSource, system_context_getter_.get()));
    refresh_token_fetcher_->StartAuthCodeForOAuth2TokenExchange(auth_code_);
  }
}

void PolicyOAuth2TokenFetcher::StartFetchingAccessToken() {
  std::vector<std::string> scopes;
  scopes.push_back(GaiaConstants::kDeviceManagementServiceOAuth);
  scopes.push_back(GaiaConstants::kOAuthWrapBridgeUserInfoScope);
  access_token_fetcher_.reset(
      new OAuth2AccessTokenFetcherImpl(this,
                                       system_context_getter_.get(),
                                       oauth2_refresh_token_));
  access_token_fetcher_->Start(
      GaiaUrls::GetInstance()->oauth2_chrome_client_id(),
      GaiaUrls::GetInstance()->oauth2_chrome_client_secret(),
      scopes);
}

void PolicyOAuth2TokenFetcher::OnClientOAuthSuccess(
    const GaiaAuthConsumer::ClientOAuthResult& oauth2_tokens) {
  VLOG(1) << "OAuth2 tokens for policy fetching succeeded.";
  oauth2_refresh_token_ = oauth2_tokens.refresh_token;
  retry_count_ = 0;
  StartFetchingAccessToken();
}

void PolicyOAuth2TokenFetcher::OnClientOAuthFailure(
    const GoogleServiceAuthError& error) {
  VLOG(1) << "OAuth2 tokens fetch for policy fetch failed!";
  RetryOnError(error,
               base::Bind(&PolicyOAuth2TokenFetcher::StartFetchingRefreshToken,
                          AsWeakPtr()));
}

void PolicyOAuth2TokenFetcher::OnGetTokenSuccess(
    const std::string& access_token,
    const base::Time& expiration_time) {
  VLOG(1) << "OAuth2 access token (device management) fetching succeeded.";
  oauth2_access_token_ = access_token;
  ForwardPolicyToken(access_token,
                     GoogleServiceAuthError(GoogleServiceAuthError::NONE));
}

void PolicyOAuth2TokenFetcher::OnGetTokenFailure(
    const GoogleServiceAuthError& error) {
  LOG(ERROR) << "OAuth2 access token (device management) fetching failed!";
  RetryOnError(error,
               base::Bind(&PolicyOAuth2TokenFetcher::StartFetchingAccessToken,
                          AsWeakPtr()));
}

void PolicyOAuth2TokenFetcher::RetryOnError(const GoogleServiceAuthError& error,
                                            const base::Closure& task) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  if (error.IsTransientError() && retry_count_ < kMaxRequestAttemptCount) {
    retry_count_++;
    BrowserThread::PostDelayedTask(
        BrowserThread::UI, FROM_HERE, task,
        base::TimeDelta::FromMilliseconds(kRequestRestartDelay));
    return;
  }
  LOG(ERROR) << "Unrecoverable error or retry count max reached.";
  failed_ = true;
  // Invoking the |callback_| signals to the owner of this object that it has
  // completed, and the owner may delete this object on the callback method.
  // So don't rely on |this| still being valid after ForwardPolicyToken()
  // returns i.e. don't write to |failed_| or other fields.
  ForwardPolicyToken(std::string(), error);
}

void PolicyOAuth2TokenFetcher::ForwardPolicyToken(
    const std::string& token,
    const GoogleServiceAuthError& error) {
  if (!callback_.is_null())
    callback_.Run(token, error);
}

}  // namespace policy

redpajama_set_name: RedPajamaGithub


text:
package com.thoughtworks.go.server.service.lookups;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import com.thoughtworks.go.helper.CommandSnippetMother;
import org.junit.Test;

import static java.util.Arrays.asList;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;

public class CommandSnippetsTest {
    @Test
    public void shouldOrderSnippetsByName() {
        CommandSnippet maven = CommandSnippetMother.validSnippet("maven");
        CommandSnippet copy = CommandSnippetMother.validSnippet("copy");
        CommandSnippet scp = CommandSnippetMother.validSnippet("scp");

        final List<CommandSnippet> snippets = asList(maven, copy, scp);
        CommandSnippets actual = new CommandSnippets(snippets);

        assertThat(actual, is(new CommandSnippets(Arrays.asList(copy, maven, scp))));
    }

    @Test
    public void shouldLookupCommandByMatchingPrefixAgainstStartOfSnippetNameAndOrderByBestMatch() {
        CommandSnippet scp = CommandSnippetMother.validSnippet("scp");
        CommandSnippet scp_copy = CommandSnippetMother.validSnippet("scp-copy");
        CommandSnippet copy_scp = CommandSnippetMother.validSnippet("copy-scp");

        CommandSnippets snippets = new CommandSnippets(Arrays.asList(scp_copy, scp, copy_scp));
        assertThat(snippets.filterBy("scp"), is(Arrays.asList(scp, scp_copy)));
    }

    @Test
    public void shouldLookupCommandByMatchingPrefixAgainstFullKeywordAndOrderByBestMatch() {
        CommandSnippet copy = CommandSnippetMother.validSnippetWithKeywords("COPY", "someotherthing");
        CommandSnippet robocopy = CommandSnippetMother.validSnippetWithKeywords("robocopy", "cOpY", "windows");
        CommandSnippet scp = CommandSnippetMother.validSnippetWithKeywords("scp", "copy", "ssh");

        CommandSnippets snippets = new CommandSnippets(Arrays.asList(copy, robocopy, scp));
        assertThat(snippets.filterBy("scp"), is(Arrays.asList(scp)));
        assertThat(snippets.filterBy("copy"), is(Arrays.asList(copy, robocopy, scp)));
        assertThat(snippets.filterBy("Copy"), is(Arrays.asList(copy, robocopy, scp)));
        assertThat(snippets.filterBy("windows"), is(Arrays.asList(robocopy)));
        assertThat(snippets.filterBy("wind"), is(Collections.<CommandSnippet>emptyList()));
        assertThat(snippets.filterBy("obo"), is(Collections.<CommandSnippet>emptyList()));
    }

    @Test
    public void shouldAllowNumbersAndSpacesInNameAndKeywords() throws Exception {
        CommandSnippet copy = CommandSnippetMother.validSnippetWithKeywords("COPY", "some other thing");
        CommandSnippet robocopy = CommandSnippetMother.validSnippetWithKeywords("robocopy", "cOpY12", "windows");
        CommandSnippet scp = CommandSnippetMother.validSnippetWithKeywords("scp scp", "copy12", "ssh");

        CommandSnippets snippets = new CommandSnippets(Arrays.asList(copy, robocopy, scp));
        assertThat(snippets.filterBy("scp"), is(Arrays.asList(scp)));
        assertThat(snippets.filterBy("scp scp"), is(Arrays.asList(scp)));
        assertThat(snippets.filterBy("copy"), is(Arrays.asList(copy)));
        assertThat(snippets.filterBy("copy12"), is(Arrays.asList(robocopy, scp)));
        assertThat(snippets.filterBy("some other thing"), is(Arrays.asList(copy)));
    }

    @Test
    public void shouldGetAllInvalidCommandSnippets() {
        CommandSnippet invalidSnippet1 = CommandSnippetMother.invalidSnippetWithEmptyCommand("file1");
        CommandSnippet validSnippet1 = CommandSnippetMother.validSnippet("file2");
        CommandSnippet invalidSnippet2 = CommandSnippetMother.invalidSnippetWithEmptyCommand("file3");
        CommandSnippet validSnippet2 = CommandSnippetMother.validSnippet("file4");

        CommandSnippets snippets = new CommandSnippets(Arrays.asList(invalidSnippet1, validSnippet1, invalidSnippet2, validSnippet2));
        assertThat(snippets.invalidSnippets(), is(Arrays.asList(invalidSnippet1, invalidSnippet2)));
    }

    @Test
    public void shouldGetTaskSnippetByFileName() {
        CommandSnippet maven_clean = CommandSnippetMother.validSnippetWithFileName("maven", "maven-clean");
        CommandSnippet maven_package = CommandSnippetMother.validSnippetWithFileName("maven", "maven-package");

        CommandSnippets commandSnippets = new CommandSnippets(asList(maven_clean, maven_package));
        assertThat(commandSnippets.findByRelativePath("/some/path/maven-clean.xml"), is(maven_clean));
        assertThat(commandSnippets.findByRelativePath("/some/path/maven-package.xml"), is(maven_package));
        assertThat(commandSnippets.findByRelativePath("/some/path/rake-package.xml"), is(nullValue()));
    }

    @Test
    public void shouldNotConsiderInvalidSnippetsDuringFiltering() throws Exception {
        CommandSnippet invalidSnippet1 = CommandSnippetMother.invalidSnippetWithEmptyCommand("file1");
        CommandSnippet validSnippet1 = CommandSnippetMother.validSnippet("file2");
        CommandSnippet invalidSnippet2 = CommandSnippetMother.invalidSnippetWithEmptyCommand("file3");
        CommandSnippet validSnippet2 = CommandSnippetMother.validSnippet("file4");

        CommandSnippets snippets = new CommandSnippets(Arrays.asList(invalidSnippet1, validSnippet1, invalidSnippet2, validSnippet2));
        assertThat(snippets.filterBy("file"), is(Arrays.asList(validSnippet1, validSnippet2)));
    }
}


text:
<!--
  Copyright 2013 Google Inc.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
  -->

<resources>
    <!-- Advanced widget preferences -->
    <string name="pref_clock_shortcut_title">Uhr Verknüpfung</string>
    <string name="pref_homescreen_background_opacity_title">Widgethintergrund</string>
    <string-array name="pref_homescreen_background_opacity_display_names">
        <item>komplett tansparent</item>
        <item>25% dunkel</item>
        <item>50% dunkel</item>
        <item>75% dunkel</item>
        <item>100% dunkel</item>
    </string-array>

    <string name="pref_aggressive_centering_title">Immer mittig halten</string>
    <string name="pref_aggressive_centering_description">Kann in unvorhersehbarem Verschieben des Widgets enden</string>

    <!-- Universal settings preferences -->
    <string name="pref_shortcut_title">Verknüpfung</string>
    <string name="pref_shortcut_default">(Standard)</string>

    <!-- Weather -->
    <string name="pref_weather_units_title">Wettereinheiten</string>
    <string-array name="pref_weather_units_display_names">
        <item>°F</item>
        <item>°C</item>
    </string-array>

    <!-- Gmail -->
    <string name="pref_gmail_label_title">Ungelesene Nachrichten für folgende Label anzeigen</string>
    <string-array name="pref_gmail_label_display_names">
        <item>Posteingang</item>
        <item>Wichtig</item>
    </string-array>

    <string name="pref_gmail_accounts_title">Ungelesene Nachrichten für folgende Accounts anzeigen</string>
    <plurals name="pref_gmail_accounts_summary_template">
        <item quantity="one">%1$d von %2$d Accounts ausgewählt</item>
        <item quantity="other">%1$d von %2$d Accounts ausgewählt</item>
    </plurals>

    <!-- Calendar -->
    <string name="pref_calendar_look_ahead_hours_title">Termine anzeigen in den nächsten</string>
    <string-array name="pref_calendar_look_ahead_hours_display_names">
        <item>3 Stunden</item>
        <item>6 Stunden</item>
        <item>12 Stunden</item>
        <item>24 Stunden</item>
        <item>2 Tagen</item>
        <item>7 Tagen</item>
    </string-array>
</resources>


text:
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
Object.defineProperty(exports, "__esModule", { value: true });
var core_1 = require("@angular/core");
var jQuery_service_1 = require("./jQuery.service");
var ModalTriggerDirective = /** @class */ (function () {
    function ModalTriggerDirective(ref, $) {
        this.$ = $;
        this.el = ref.nativeElement;
    }
    ModalTriggerDirective.prototype.ngOnInit = function () {
        var _this = this;
        this.el.addEventListener('click', function (e) {
            // issue: we may have many modal windows for different purpose, so need to pass id dynamically
            // this.$('#simple-modal').modal({})
            _this.$("#" + _this.modalId).modal({});
        });
    };
    __decorate([
        core_1.Input('modal-trigger'),
        __metadata("design:type", String)
    ], ModalTriggerDirective.prototype, "modalId", void 0);
    ModalTriggerDirective = __decorate([
        core_1.Directive({
            selector: '[modal-trigger]' //attribute selector
        }),
        __param(1, core_1.Inject(jQuery_service_1.JQ_TOKEN)),
        __metadata("design:paramtypes", [core_1.ElementRef, Object])
    ], ModalTriggerDirective);
    return ModalTriggerDirective;
}());
exports.ModalTriggerDirective = ModalTriggerDirective;
//# sourceMappingURL=modalTrigger.directive.js.map


text:
'use strict';

var path = require('path');
var test = require('tape');
var proxyquire = require('proxyquire');

test('resolvers', function (t) {
  var resolvers = require('../../lib/resolvers');
  t.ok(typeof resolvers.use === 'function', 'has .use method');
  t.end();
});

test('resolvers.use overrides', function (t) {
  var resolvers = require('../../lib/resolvers');
  resolvers.use({foo:'foo',bar:'bar'});
  t.equal(resolvers.foo, 'foo');
  t.equal(resolvers.bar, 'bar');
  t.end();
});

test('.use is reserved', function (t) {
  var resolvers = require('../../lib/resolvers');
  var use = resolvers.use;
  resolvers.use({use:'use'});
  t.equal(resolvers.use, use);
  t.end();
});


text:
package alien4cloud.rest.topology;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;

import org.hibernate.validator.constraints.NotBlank;

/**
 * a nodetemplate request object
 *
 * @author 'Igor Ngouagna'
 */
@Getter
@Setter
@ToString
@NoArgsConstructor
public class NodeTemplateRequest {
    /** the name of the node template */
    @NotBlank
    private String name;
    /** related NodeType id */
    @NotBlank
    private String indexedNodeTypeId;

    public NodeTemplateRequest(String name, String indexedNodeTypeId) {
        this.name = name;
        this.indexedNodeTypeId = indexedNodeTypeId;
    }
}


text:
package list.singly.reverse.all;

import algorithms.structures.SListNode;

public class Solution1B
{
	/**
	 * Reverses singly linked list that does not have cycle
	 *
	 * @param <E> Any type that implements Comparable interface
	 * @param L head node of the linked list
	 * @return the head node of the reversed list
	 *
	 * @time O(n)
	 * @space O(1)
	 **/
	public static <E extends Comparable<E>> SListNode<E> reverse(SListNode<E> L)
	{
		if (L != null)
		{
			SListNode<E> prev = null;
			SListNode<E> curr = L;

			while (curr != null)
			{
				SListNode<E> next = curr.getNext();
				curr.setNext(prev);
				prev = curr;
				curr = next;
			}

			L = prev;
		}

		return L;
	}
}


text:
using System.ComponentModel.DataAnnotations;

namespace OrchardCore.Microsoft.Authentication.ViewModels
{
    public class AzureADSettingsViewModel
    {
        [Required]
        public string DisplayName { get; set; }

        [Required(AllowEmptyStrings = false, ErrorMessage = "Application Id is required")]
        public string AppId { get; set; }

        [Required(AllowEmptyStrings = false, ErrorMessage = "Tenant Id is required")]
        public string TenantId { get; set; }

        [RegularExpression(@"\/[-A-Za-z0-9+&@#\/%?=~_|!:,.;]+[-A-Za-z0-9+&@#\/%=~_|]", ErrorMessage = "Invalid path")]
        public string CallbackPath { get; set; }
    }
}


text:
package main

import (
	"flag"
	"fmt"
	"github.com/heketi/heketi/client/go/commands"
	"io"
	"os"
)

var (
	stdout            io.Writer = os.Stdout
	options           commands.Options
	usageTemplateMain = `Heketi is a tool for managing gluster volumes.

Usage:

    heketi -server [server] [options] command [arguments]

Options are:

    -json      Returns any command in JSON format.

The commands are:

    cluster    Manage a cluster (a set of storage nodes)
    node       Register a storage system to be managed
    device     Manage raw devices in a cluster
    volume     Manage a network file system of a certain size available to be used by clients.

Use "heketi [command] -help" for more information about a command

`
)

func init() {

	flag.StringVar(&options.Url, "server", "", "server url goes here.")
	flag.BoolVar(&options.Json, "json", false, "get response as json")

	flag.Usage = func() {
		fmt.Println(usageTemplateMain)
	}
}

// ------ Main
func main() {
	flag.Parse()

	//all first level commands go here (cluster, node, device, volume)
	cmds := commands.Commands{
		commands.NewClusterCommand(&options),
		commands.NewNodeCommand(&options),
	}

	for _, cmd := range cmds {
		if flag.Arg(0) == cmd.Name() {

			err := cmd.Exec(flag.Args()[1:])
			if err != nil {
				fmt.Fprintf(stdout, "Error: %v\n", err)
				os.Exit(1)
			}
			return
		}
	}

	fmt.Println("Command not found")
}


text:
layout: page
subheadline:  ""
title: "特色炸蛋"
teaser:  ""
breadcrumb: true
category: MenuCuisine/all
permalink: /MenuCuisine/all/tesezhadan/
---

{% include cuisine-template.html item=site.data.egg.tesezhadan %}


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<title> Angularjs Estudos </title>

	<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css" />
	<link rel="stylesheet" type="text/css" href="css/style.css" />

 {{geral.title.nome}}

 {{geral.title.desc}}

Home

Imagens

Inputs

Canculadora


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from ray.rllib.agents.trainer import with_common_config
from ray.rllib.agents.trainer_template import build_trainer
from ray.rllib.agents.marwil.marwil_policy import MARWILPolicy
from ray.rllib.optimizers import SyncBatchReplayOptimizer

# yapf: disable
# __sphinx_doc_begin__
DEFAULT_CONFIG = with_common_config({
    # You should override this to point to an offline dataset (see agent.py).
    "input": "sampler",
    # Use importance sampling estimators for reward
    "input_evaluation": ["is", "wis"],

    # Scaling of advantages in exponential terms
    # When beta is 0, MARWIL is reduced to imitation learning
    "beta": 1.0,
    # Balancing value estimation loss and policy optimization loss
    "vf_coeff": 1.0,
    # Whether to calculate cumulative rewards
    "postprocess_inputs": True,
    # Whether to rollout "complete_episodes" or "truncate_episodes"
    "batch_mode": "complete_episodes",
    # Learning rate for adam optimizer
    "lr": 1e-4,
    # Number of timesteps collected for each SGD round
    "train_batch_size": 2000,
    # Number of steps max to keep in the batch replay buffer
    "replay_buffer_size": 100000,
    # Number of steps to read before learning starts
    "learning_starts": 0,
    # === Parallelism ===
    "num_workers": 0,
})
# __sphinx_doc_end__
# yapf: enable

def make_optimizer(workers, config):
    return SyncBatchReplayOptimizer(
        workers,
        learning_starts=config["learning_starts"],
        buffer_size=config["replay_buffer_size"],
        train_batch_size=config["train_batch_size"],
    )

MARWILTrainer = build_trainer(
    name="MARWIL",
    default_config=DEFAULT_CONFIG,
    default_policy=MARWILPolicy,
    make_policy_optimizer=make_optimizer)


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/activity_item_ivImage"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_marginTop="8dp"
        android:layout_marginRight="8dp"
        android:contentDescription="@null"
        android:scaleType="centerCrop"
        android:src="@drawable/global_img_default"/>

    <ImageView
        android:id="@+id/activity_item_ivDelete"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_gravity="right"
        android:scaleType="fitXY"
        android:contentDescription="@null"
        android:src="@drawable/global_icon_deletecross"
        />

</FrameLayout>


text: My Github Pages blog


text:
        <?php _e('Venue') ?>
        <input type="text" id="venue" class="large-text" name="venue" value="<?php echo htmlentities($venue); ?>" />

        <?php _e('Address 1') ?>
        <input type="text" id="address1" class="large-text" name="address1" value="<?php echo htmlentities($address1); ?>" />

        <?php _e('Address 2'); ?>
        <input type="text" id="address2" class="large-text" name="address2" value="<?php echo htmlentities($address2); ?>" />

        <?php _e('City'); ?>
        <input type="text" id="city" class="regular-text" name="city" value="<?php echo htmlentities($city); ?>" />

        <?php _e('State'); ?>
        <input type="text" id="region" class="regular-text" name="region" value="<?php echo htmlentities($region); ?>" />

        <?php _e('Country'); ?>
        <input type="text" id="country" class="regular-text" name="country" value="<?php echo htmlentities($country); ?>" />

        <?php _e('Postal Code'); ?>
        <input type="text" id="postal_code" class="regular-text" name="postal_code" value="<?php echo htmlentities($postal_code); ?>" />

        <?php _e('Latitude'); ?>
        <input type="text" id="latitude" class="regular-text" name="latitude" value="<?php echo htmlentities($latitude); ?>" />

        <?php _e('Longitude'); ?>
        <input type="text" id="longitude" class="regular-text" name="longitude" value="<?php echo htmlentities($longitude); ?>" />

            <input type='submit' class='button-secondary' id='google-map-query' value='Update Coordinates' />


text:
{% set partition_clause = "partition by adset_id order by effective_status rows
    between unbounded preceding and unbounded following" %}

with adsets_xf_adsets as (

    select  * from {{ref('fb_ads_adsets')}}

),

adsets_xf_rollup as (

    select distinct
        adset_id,
        first_value(name) over ({{partition_clause}}) as name,
        first_value(account_id) over ({{partition_clause}}) as account_id,
        first_value(campaign_id) over ({{partition_clause}}) as campaign_id,
        first_value(created_time) over ({{partition_clause}}) as created_time,
        first_value(effective_status) over ({{partition_clause}})
            as effective_status

    from adsets_xf_adsets

)

select * from adsets_xf_rollup


text:
#ifndef LIBSSH2_PRIV_H
#define LIBSSH2_PRIV_H 1

#define LIBSSH2_LIBRARY
#include "libssh2_config.h"

#ifdef HAVE_WINDOWS_H
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#undef WIN32_LEAN_AND_MEAN
#endif

#ifdef HAVE_WS2TCPIP_H
#include <ws2tcpip.h>
#endif

#include <stdio.h>
#include <time.h>

/* The following CPP block should really only be in session.c and
   packet.c.  However, AIX have #define's for 'events' and 'revents'
   and we are using those names in libssh2.h, so we need to include
   the AIX headers first, to make sure all code is compiled with
   consistent names of these fields.  While arguable the best would to
   change libssh2.h to use other names, that would break backwards
   compatibility.  For more information, see:
   http://www.mail-archive.com/libssh2-devel%40lists.sourceforge.net/msg00003.html
   http://www.mail-archive.com/libssh2-devel%40lists.sourceforge.net/msg00224.html
*/
#ifdef HAVE_POLL
# include <sys/poll.h>
#else
# if defined(HAVE_SELECT) && !defined(WIN32)
# ifdef HAVE_SYS_SELECT_H
# include <sys/select.h>
# else
# include <sys/time.h>
# include <sys/types.h>
# endif
# endif
#endif

/* Needed for struct iovec on some platforms */
#ifdef HAVE_SYS_UIO_H
#include <sys/uio.h>
#endif

#ifdef HAVE_SYS_SOCKET_H
# include <sys/socket.h>
#endif
#ifdef HAVE_SYS_IOCTL_H
# include <sys/ioctl.h>
#endif
#ifdef HAVE_INTTYPES_H
#include <inttypes.h>
#endif

#include "libssh2.h"
#include "libssh2_publickey.h"
#include "libssh2_sftp.h"
#include "misc.h" /* for the linked list stuff */

#ifndef FALSE
#define FALSE 0
#endif
#ifndef TRUE
#define TRUE 1
#endif

#ifdef _MSC_VER
/* "inline" keyword is valid only with C++ engine! */
#define inline __inline
#endif

/* Provide iovec / writev on WIN32 platform. */
#ifdef WIN32

struct iovec {
    size_t iov_len;
    void * iov_base;
};

static inline int writev(int sock, struct iovec *iov, int nvecs)
{
    DWORD ret;
    if (WSASend(sock, (LPWSABUF)iov, nvecs, &ret, 0, NULL, NULL) == 0) {
        return ret;
    }
    return -1;
}

#endif /* WIN32 */

#include "crypto.h"

#ifdef HAVE_WINSOCK2_H

#include <winsock2.h>
#include <ws2tcpip.h>

#endif

/* RFC4253 section 6.1 Maximum Packet Length says:
 *
 * "All implementations MUST be able to process packets with
 * uncompressed payload length of 32768 bytes or less and
 * total packet size of 35000 bytes or less (including length,
 * padding length, payload, padding, and MAC.)."
 */
#define MAX_SSH_PACKET_LEN 35000

#define LIBSSH2_ALLOC(session, count) \
  session->alloc((count), &(session)->abstract)
#define LIBSSH2_REALLOC(session, ptr, count) \
 ((ptr) ? session->realloc((ptr), (count), &(session)->abstract) : \
 session->alloc((count), &(session)->abstract))
#define LIBSSH2_FREE(session, ptr) \
 session->free((ptr), &(session)->abstract)
#define LIBSSH2_IGNORE(session, data, datalen) \
 session->ssh_msg_ignore((session), (data), (datalen), &(session)->abstract)
#define LIBSSH2_DEBUG(session, always_display, message, message_len, \
                      language, language_len)    \
    session->ssh_msg_debug((session), (always_display), (message), \
                           (message_len), (language), (language_len), \
                           &(session)->abstract)
#define LIBSSH2_DISCONNECT(session, reason, message, message_len, \
                           language, language_len)                \
    session->ssh_msg_disconnect((session), (reason), (message),   \
                                (message_len), (language), (language_len), \
                                &(session)->abstract)

#define LIBSSH2_MACERROR(session, data, datalen)         \
    session->macerror((session), (data), (datalen), &(session)->abstract)
#define LIBSSH2_X11_OPEN(channel, shost, sport)          \
    channel->session->x11(((channel)->session), (channel), \
                          (shost), (sport), (&(channel)->session->abstract))

#define LIBSSH2_CHANNEL_CLOSE(session, channel)          \
    channel->close_cb((session), &(session)->abstract, \
                      (channel), &(channel)->abstract)

#define LIBSSH2_SEND_FD(session, fd, buffer, length, flags) \
    session->send(fd, buffer, length, flags, &session->abstract)
#define LIBSSH2_RECV_FD(session, fd, buffer, length, flags) \
    session->recv(fd, buffer, length, flags, &session->abstract)

#define LIBSSH2_SEND(session, buffer, length, flags)  \
    LIBSSH2_SEND_FD(session, session->socket_fd, buffer, length, flags)
#define LIBSSH2_RECV(session, buffer, length, flags)                    \
    LIBSSH2_RECV_FD(session, session->socket_fd, buffer, length, flags)

typedef struct _LIBSSH2_KEX_METHOD LIBSSH2_KEX_METHOD;
typedef struct _LIBSSH2_HOSTKEY_METHOD LIBSSH2_HOSTKEY_METHOD;
typedef struct _LIBSSH2_CRYPT_METHOD LIBSSH2_CRYPT_METHOD;
typedef struct _LIBSSH2_COMP_METHOD LIBSSH2_COMP_METHOD;

typedef struct _LIBSSH2_PACKET LIBSSH2_PACKET;

typedef enum
{
    libssh2_NB_state_idle = 0,
    libssh2_NB_state_allocated,
    libssh2_NB_state_created,
    libssh2_NB_state_sent,
    libssh2_NB_state_sent1,
    libssh2_NB_state_sent2,
    libssh2_NB_state_sent3,
    libssh2_NB_state_sent4,
    libssh2_NB_state_sent5,
    libssh2_NB_state_sent6,
    libssh2_NB_state_sent7,
    libssh2_NB_state_jump1,
    libssh2_NB_state_jump2,
    libssh2_NB_state_jump3,
    libssh2_NB_state_jump4,
    libssh2_NB_state_jump5
} libssh2_nonblocking_states;

typedef struct packet_require_state_t
{
    libssh2_nonblocking_states state;
    time_t start;
} packet_require_state_t;

typedef struct packet_requirev_state_t
{
    time_t start;
} packet_requirev_state_t;

typedef struct kmdhgGPsha1kex_state_t
{
    libssh2_nonblocking_states state;
    unsigned char *e_packet;
    unsigned char *s_packet;
    unsigned char *tmp;
    unsigned char h_sig_comp[SHA_DIGEST_LENGTH];
    unsigned char c;
    size_t e_packet_len;
    size_t s_packet_len;
    size_t tmp_len;
    _libssh2_bn_ctx *ctx;
    _libssh2_bn *x;
    _libssh2_bn *e;
    _libssh2_bn *f;
    _libssh2_bn *k;
    unsigned char *s;
    unsigned char *f_value;
    unsigned char *k_value;
    unsigned char *h_sig;
    size_t f_value_len;
    size_t k_value_len;
    size_t h_sig_len;
    libssh2_sha1_ctx exchange_hash;
    packet_require_state_t req_state;
    libssh2_nonblocking_states burn_state;
} kmdhgGPsha1kex_state_t;

typedef struct key_exchange_state_low_t
{
    libssh2_nonblocking_states state;
    packet_require_state_t req_state;
    kmdhgGPsha1kex_state_t exchange_state;
    _libssh2_bn *p;             /* SSH2 defined value (p_value) */
    _libssh2_bn *g;             /* SSH2 defined value (2) */
    unsigned char request[13];
    unsigned char *data;
    size_t request_len;
    size_t data_len;
} key_exchange_state_low_t;

typedef struct key_exchange_state_t
{
    libssh2_nonblocking_states state;
    packet_require_state_t req_state;
    key_exchange_state_low_t key_state_low;
    unsigned char *data;
    size_t data_len;
    unsigned char *oldlocal;
    size_t oldlocal_len;
} key_exchange_state_t;

#define FwdNotReq "Forward not requested"

typedef struct packet_queue_listener_state_t
{
    libssh2_nonblocking_states state;
    unsigned char packet[17 + (sizeof(FwdNotReq) - 1)];
    unsigned char *host;
    unsigned char *shost;
    uint32_t sender_channel;
    uint32_t initial_window_size;
    uint32_t packet_size;
    uint32_t port;
    uint32_t sport;
    uint32_t host_len;
    uint32_t shost_len;
    LIBSSH2_CHANNEL *channel;
} packet_queue_listener_state_t;

#define X11FwdUnAvil "X11 Forward Unavailable"

typedef struct packet_x11_open_state_t
{
    libssh2_nonblocking_states state;
    unsigned char packet[17 + (sizeof(X11FwdUnAvil) - 1)];
    unsigned char *shost;
    uint32_t sender_channel;
    uint32_t initial_window_size;
    uint32_t packet_size;
    uint32_t sport;
    uint32_t shost_len;
    LIBSSH2_CHANNEL *channel;
} packet_x11_open_state_t;

struct _LIBSSH2_PACKET
{
    struct list_node node; /* linked list header */

    /* the raw unencrypted payload */
    unsigned char *data;
    size_t data_len;

    /* Where to start reading data from,
     * used for channel data that's been partially consumed */
    size_t data_head;
};

typedef struct _libssh2_channel_data
{
    /* Identifier */
    uint32_t id;

    /* Limits and restrictions */
    uint32_t window_size_initial, window_size, packet_size;

    /* Set to 1 when CHANNEL_CLOSE / CHANNEL_EOF sent/received */
    char close, eof, extended_data_ignore_mode;
} libssh2_channel_data;

struct _LIBSSH2_CHANNEL
{
    struct list_node node;

    unsigned char *channel_type;
    unsigned channel_type_len;

    /* channel's program exit status */
    int exit_status;

    /* channel's program exit signal (without the SIG prefix) */
    char *exit_signal;

    libssh2_channel_data local, remote;
    /* Amount of bytes to be refunded to receive window (but not yet sent) */
    uint32_t adjust_queue;
    /* Data immediately available for reading */
    uint32_t read_avail;

    LIBSSH2_SESSION *session;

    void *abstract;
      LIBSSH2_CHANNEL_CLOSE_FUNC((*close_cb));

    /* State variables used in libssh2_channel_setenv_ex() */
    libssh2_nonblocking_states setenv_state;
    unsigned char *setenv_packet;
    size_t setenv_packet_len;
    unsigned char setenv_local_channel[4];
    packet_requirev_state_t setenv_packet_requirev_state;

    /* State variables used in libssh2_channel_request_pty_ex()
       libssh2_channel_request_pty_size_ex() */
    libssh2_nonblocking_states reqPTY_state;
    unsigned char reqPTY_packet[41 + 256];
    size_t reqPTY_packet_len;
    unsigned char reqPTY_local_channel[4];
    packet_requirev_state_t reqPTY_packet_requirev_state;

    /* State variables used in libssh2_channel_x11_req_ex() */
    libssh2_nonblocking_states reqX11_state;
    unsigned char *reqX11_packet;
    size_t reqX11_packet_len;
    unsigned char reqX11_local_channel[4];
    packet_requirev_state_t reqX11_packet_requirev_state;

    /* State variables used in libssh2_channel_process_startup() */
    libssh2_nonblocking_states process_state;
    unsigned char *process_packet;
    size_t process_packet_len;
    unsigned char process_local_channel[4];
    packet_requirev_state_t process_packet_requirev_state;

    /* State variables used in libssh2_channel_flush_ex() */
    libssh2_nonblocking_states flush_state;
    size_t flush_refund_bytes;
    size_t flush_flush_bytes;

    /* State variables used in libssh2_channel_receive_window_adjust() */
    libssh2_nonblocking_states adjust_state;
    unsigned char adjust_adjust[9];     /* packet_type(1) + channel(4) + adjustment(4) */

    /* State variables used in libssh2_channel_read_ex() */
    libssh2_nonblocking_states read_state;

    uint32_t read_local_id;

    /* State variables used in libssh2_channel_write_ex() */
    libssh2_nonblocking_states write_state;
    unsigned char write_packet[13];
    size_t write_packet_len;
    size_t write_bufwrite;

    /* State variables used in libssh2_channel_close() */
    libssh2_nonblocking_states close_state;
    unsigned char close_packet[5];

    /* State variables used in libssh2_channel_wait_closedeof() */
    libssh2_nonblocking_states wait_eof_state;

    /* State variables used in libssh2_channel_wait_closed() */
    libssh2_nonblocking_states wait_closed_state;

    /* State variables used in libssh2_channel_free() */
    libssh2_nonblocking_states free_state;

    /* State variables used in libssh2_channel_handle_extended_data2() */
    libssh2_nonblocking_states extData2_state;

};

struct _LIBSSH2_LISTENER
{
    struct list_node node; /* linked list header */

    LIBSSH2_SESSION *session;

    char *host;
    int port;

    /* a list of CHANNELs for this listener */
    struct list_head queue;

    int queue_size;
    int queue_maxsize;

    /* State variables used in libssh2_channel_forward_cancel() */
    libssh2_nonblocking_states chanFwdCncl_state;
    unsigned char *chanFwdCncl_data;
    size_t chanFwdCncl_data_len;
};

typedef struct _libssh2_endpoint_data
{
    unsigned char *banner;

    unsigned char *kexinit;
    size_t kexinit_len;

    const LIBSSH2_CRYPT_METHOD *crypt;
    void *crypt_abstract;

    const struct _LIBSSH2_MAC_METHOD *mac;
    uint32_t seqno;
    void *mac_abstract;

    const LIBSSH2_COMP_METHOD *comp;
    void *comp_abstract;

    /* Method Preferences -- NULL yields "load order" */
    char *crypt_prefs;
    char *mac_prefs;
    char *comp_prefs;
    char *lang_prefs;
} libssh2_endpoint_data;

#define PACKETBUFSIZE (1024*16)

struct transportpacket
{
    /* ------------- for incoming data --------------- */
    unsigned char buf[PACKETBUFSIZE];
    unsigned char init[5];  /* first 5 bytes of the incoming data stream,
                               still encrypted */
    size_t writeidx;        /* at what array index we do the next write into
                               the buffer */
    size_t readidx;         /* at what array index we do the next read from
                               the buffer */
    uint32_t packet_length; /* the most recent packet_length as read from the
                               network data */
    uint8_t padding_length; /* the most recent padding_length as read from the
                               network data */
    size_t data_num;        /* How much of the total package that has been read
                               so far. */
    size_t total_num;       /* How much a total package is supposed to be, in
                               number of bytes. A full package is
                               packet_length + padding_length + 4 +
                               mac_length. */
    unsigned char *payload; /* this is a pointer to a LIBSSH2_ALLOC()
                               area to which we write decrypted data */
    unsigned char *wptr;    /* write pointer into the payload to where we
                               are currently writing decrypted data */

    /* ------------- for outgoing data --------------- */
    unsigned char outbuf[MAX_SSH_PACKET_LEN]; /* area for the outgoing data */

    int ototal_num;         /* size of outbuf in number of bytes */
    const unsigned char *odata; /* original pointer to the data */
    size_t olen;            /* original size of the data we stored in
                               outbuf */
    size_t osent;           /* number of bytes already sent */
};

struct _LIBSSH2_PUBLICKEY
{
    LIBSSH2_CHANNEL *channel;
    uint32_t version;

    /* State variables used in libssh2_publickey_packet_receive() */
    libssh2_nonblocking_states receive_state;
    unsigned char *receive_packet;
    size_t receive_packet_len;

    /* State variables used in libssh2_publickey_add_ex() */
    libssh2_nonblocking_states add_state;
    unsigned char *add_packet;
    unsigned char *add_s;

    /* State variables used in libssh2_publickey_remove_ex() */
    libssh2_nonblocking_states remove_state;
    unsigned char *remove_packet;
    unsigned char *remove_s;

    /* State variables used in libssh2_publickey_list_fetch() */
    libssh2_nonblocking_states listFetch_state;
    unsigned char *listFetch_s;
    unsigned char listFetch_buffer[12];
    unsigned char *listFetch_data;
    size_t listFetch_data_len;
};

#define LIBSSH2_SCP_RESPONSE_BUFLEN     256

struct flags {
    int sigpipe;  /* LIBSSH2_FLAG_SIGPIPE */
    int compress; /* LIBSSH2_FLAG_COMPRESS */
};

struct _LIBSSH2_SESSION
{
    /* Memory management callbacks */
    void *abstract;
      LIBSSH2_ALLOC_FUNC((*alloc));
      LIBSSH2_REALLOC_FUNC((*realloc));
      LIBSSH2_FREE_FUNC((*free));

    /* Other callbacks */
      LIBSSH2_IGNORE_FUNC((*ssh_msg_ignore));
      LIBSSH2_DEBUG_FUNC((*ssh_msg_debug));
      LIBSSH2_DISCONNECT_FUNC((*ssh_msg_disconnect));
      LIBSSH2_MACERROR_FUNC((*macerror));
      LIBSSH2_X11_OPEN_FUNC((*x11));
      LIBSSH2_SEND_FUNC((*send));
      LIBSSH2_RECV_FUNC((*recv));

    /* Method preferences -- NULL yields "load order" */
    char *kex_prefs;
    char *hostkey_prefs;

    int state;

    /* Flag options */
    struct flags flag;

    /* Agreed Key Exchange Method */
    const LIBSSH2_KEX_METHOD *kex;
    unsigned int burn_optimistic_kexinit:1;

    unsigned char *session_id;
    uint32_t session_id_len;

    /* this is set to TRUE if a blocking API behavior is requested */
    int api_block_mode;

    /* Timeout used when blocking API behavior is active */
    long api_timeout;

    /* Server's public key */
    const LIBSSH2_HOSTKEY_METHOD *hostkey;
    void *server_hostkey_abstract;

    /* Either set with libssh2_session_hostkey() (for server mode)
     * Or read from server in (eg) KEXDH_INIT (for client mode)
     */
    unsigned char *server_hostkey;
    uint32_t server_hostkey_len;
#if LIBSSH2_MD5
    unsigned char server_hostkey_md5[MD5_DIGEST_LENGTH];
    int server_hostkey_md5_valid;
#endif                          /* ! LIBSSH2_MD5 */
    unsigned char server_hostkey_sha1[SHA_DIGEST_LENGTH];

    /* (remote as source of data -- packet_read ) */
    libssh2_endpoint_data remote;

    /* (local as source of data -- packet_write ) */
    libssh2_endpoint_data local;

    /* Inbound Data linked list -- Sometimes the packet that comes in isn't the
       packet we're ready for */
    struct list_head packets;

    /* Active connection channels */
    struct list_head channels;

    uint32_t next_channel;

    struct list_head listeners; /* list of LIBSSH2_LISTENER structs */

    /* Actual I/O socket */
    libssh2_socket_t socket_fd;
    int socket_state;
    int socket_block_directions;
    int socket_prev_blockstate; /* stores the state of the socket blockiness
                                   when libssh2_session_startup() is called */

    /* Error tracking */
    const char *err_msg;
    int err_code;

    /* struct members for packet-level reading */
    struct transportpacket packet;
#ifdef LIBSSH2DEBUG
    int showmask;               /* what debug/trace messages to display */
    libssh2_trace_handler_func tracehandler; /* callback to display trace messages */
    void* tracehandler_context; /* context for the trace handler */
#endif

    /* State variables used in libssh2_banner_send() */
    libssh2_nonblocking_states banner_TxRx_state;
    char banner_TxRx_banner[256];
    ssize_t banner_TxRx_total_send;

    /* State variables used in libssh2_kexinit() */
    libssh2_nonblocking_states kexinit_state;
    unsigned char *kexinit_data;
    size_t kexinit_data_len;

    /* State variables used in libssh2_session_startup() */
    libssh2_nonblocking_states startup_state;
    unsigned char *startup_data;
    size_t startup_data_len;
    unsigned char startup_service[sizeof("ssh-userauth") + 5 - 1];
    size_t startup_service_length;
    packet_require_state_t startup_req_state;
    key_exchange_state_t startup_key_state;

    /* State variables used in libssh2_session_free() */
    libssh2_nonblocking_states free_state;

    /* State variables used in libssh2_session_disconnect_ex() */
    libssh2_nonblocking_states disconnect_state;
    unsigned char disconnect_data[256 + 13];
    size_t disconnect_data_len;

    /* State variables used in libssh2_packet_read() */
    libssh2_nonblocking_states readPack_state;
    int readPack_encrypted;

    /* State variables used in libssh2_userauth_list() */
    libssh2_nonblocking_states userauth_list_state;
    unsigned char *userauth_list_data;
    size_t userauth_list_data_len;
    packet_requirev_state_t userauth_list_packet_requirev_state;

    /* State variables used in libssh2_userauth_password_ex() */
    libssh2_nonblocking_states userauth_pswd_state;
    unsigned char *userauth_pswd_data;
    unsigned char userauth_pswd_data0;
    size_t userauth_pswd_data_len;
    char *userauth_pswd_newpw;
    int userauth_pswd_newpw_len;
    packet_requirev_state_t userauth_pswd_packet_requirev_state;

    /* State variables used in libssh2_userauth_hostbased_fromfile_ex() */
    libssh2_nonblocking_states userauth_host_state;
    unsigned char *userauth_host_data;
    size_t userauth_host_data_len;
    unsigned char *userauth_host_packet;
    size_t userauth_host_packet_len;
    unsigned char *userauth_host_method;
    size_t userauth_host_method_len;
    unsigned char *userauth_host_s;
    packet_requirev_state_t userauth_host_packet_requirev_state;

    /* State variables used in libssh2_userauth_publickey_fromfile_ex() */
    libssh2_nonblocking_states userauth_pblc_state;
    unsigned char *userauth_pblc_data;
    size_t userauth_pblc_data_len;
    unsigned char *userauth_pblc_packet;
    size_t userauth_pblc_packet_len;
    unsigned char *userauth_pblc_method;
    size_t userauth_pblc_method_len;
    unsigned char *userauth_pblc_s;
    unsigned char *userauth_pblc_b;
    packet_requirev_state_t userauth_pblc_packet_requirev_state;

    /* State variables used in libssh2_userauth_keyboard_interactive_ex() */
    libssh2_nonblocking_states userauth_kybd_state;
    unsigned char *userauth_kybd_data;
    size_t userauth_kybd_data_len;
    unsigned char *userauth_kybd_packet;
    size_t userauth_kybd_packet_len;
    unsigned int userauth_kybd_auth_name_len;
    char *userauth_kybd_auth_name;
    unsigned userauth_kybd_auth_instruction_len;
    char *userauth_kybd_auth_instruction;
    unsigned int userauth_kybd_num_prompts;
    int userauth_kybd_auth_failure;
    LIBSSH2_USERAUTH_KBDINT_PROMPT *userauth_kybd_prompts;
    LIBSSH2_USERAUTH_KBDINT_RESPONSE *userauth_kybd_responses;
    packet_requirev_state_t userauth_kybd_packet_requirev_state;

    /* State variables used in libssh2_channel_open_ex() */
    libssh2_nonblocking_states open_state;
    packet_requirev_state_t open_packet_requirev_state;
    LIBSSH2_CHANNEL *open_channel;
    unsigned char *open_packet;
    size_t open_packet_len;
    unsigned char *open_data;
    size_t open_data_len;
    uint32_t open_local_channel;

    /* State variables used in libssh2_channel_direct_tcpip_ex() */
    libssh2_nonblocking_states direct_state;
    unsigned char *direct_message;
    size_t direct_host_len;
    size_t direct_shost_len;
    size_t direct_message_len;

    /* State variables used in libssh2_channel_forward_listen_ex() */
    libssh2_nonblocking_states fwdLstn_state;
    unsigned char *fwdLstn_packet;
    uint32_t fwdLstn_host_len;
    uint32_t fwdLstn_packet_len;
    packet_requirev_state_t fwdLstn_packet_requirev_state;

    /* State variables used in libssh2_publickey_init() */
    libssh2_nonblocking_states pkeyInit_state;
    LIBSSH2_PUBLICKEY *pkeyInit_pkey;
    LIBSSH2_CHANNEL *pkeyInit_channel;
    unsigned char *pkeyInit_data;
    size_t pkeyInit_data_len;
    /* 19 = packet_len(4) + version_len(4) + "version"(7) + version_num(4) */
    unsigned char pkeyInit_buffer[19];
    size_t pkeyInit_buffer_sent; /* how much of buffer that has been sent */

    /* State variables used in libssh2_packet_add() */
    libssh2_nonblocking_states packAdd_state;
    LIBSSH2_CHANNEL *packAdd_channelp; /* keeper of the channel during EAGAIN
                                          states */
    packet_queue_listener_state_t packAdd_Qlstn_state;
    packet_x11_open_state_t packAdd_x11open_state;

    /* State variables used in fullpacket() */
    libssh2_nonblocking_states fullpacket_state;
    int fullpacket_macstate;
    size_t fullpacket_payload_len;
    int fullpacket_packet_type;

    /* State variables used in libssh2_sftp_init() */
    libssh2_nonblocking_states sftpInit_state;
    LIBSSH2_SFTP *sftpInit_sftp;
    LIBSSH2_CHANNEL *sftpInit_channel;
    unsigned char sftpInit_buffer[9];   /* sftp_header(5){excludes request_id}
                                           + version_id(4) */
    int sftpInit_sent; /* number of bytes from the buffer that have been
                          sent */

    /* State variables used in libssh2_scp_recv() */
    libssh2_nonblocking_states scpRecv_state;
    unsigned char *scpRecv_command;
    size_t scpRecv_command_len;
    unsigned char scpRecv_response[LIBSSH2_SCP_RESPONSE_BUFLEN];
    size_t scpRecv_response_len;
    long scpRecv_mode;
#if defined(HAVE_LONGLONG) && defined(HAVE_STRTOLL)
    /* we have the type and we can parse such numbers */
    long long scpRecv_size;
#define scpsize_strtol strtoll
#else
    long scpRecv_size;
#define scpsize_strtol strtol
#endif
    long scpRecv_mtime;
    long scpRecv_atime;
    LIBSSH2_CHANNEL *scpRecv_channel;

    /* State variables used in libssh2_scp_send_ex() */
    libssh2_nonblocking_states scpSend_state;
    unsigned char *scpSend_command;
    size_t scpSend_command_len;
    unsigned char scpSend_response[LIBSSH2_SCP_RESPONSE_BUFLEN];
    size_t scpSend_response_len;
    LIBSSH2_CHANNEL *scpSend_channel;

    /* Keepalive variables used by keepalive.c. */
    int keepalive_interval;
    int keepalive_want_reply;
    time_t keepalive_last_sent;
};

/* session.state bits */
#define LIBSSH2_STATE_EXCHANGING_KEYS   0x00000001
#define LIBSSH2_STATE_NEWKEYS           0x00000002
#define LIBSSH2_STATE_AUTHENTICATED     0x00000004
#define LIBSSH2_STATE_KEX_ACTIVE        0x00000008

/* session.flag helpers */
#ifdef MSG_NOSIGNAL
#define LIBSSH2_SOCKET_SEND_FLAGS(session)              \
    (((session)->flag.sigpipe) ? 0 : MSG_NOSIGNAL)
#define LIBSSH2_SOCKET_RECV_FLAGS(session)              \
    (((session)->flag.sigpipe) ? 0 : MSG_NOSIGNAL)
#else
/* If MSG_NOSIGNAL isn't defined we're SOL on blocking SIGPIPE */
#define LIBSSH2_SOCKET_SEND_FLAGS(session)      0
#define LIBSSH2_SOCKET_RECV_FLAGS(session)      0
#endif

/* --------- */

/* libssh2 extensible ssh api, ultimately I'd like to allow loading additional
   methods via .so/.dll */

struct _LIBSSH2_KEX_METHOD
{
    const char *name;

    /* Key exchange, populates session->* and returns 0 on success, non-0 on error */
    int (*exchange_keys) (LIBSSH2_SESSION * session,
                          key_exchange_state_low_t * key_state);

    long flags;
};

struct _LIBSSH2_HOSTKEY_METHOD
{
    const char *name;
    unsigned long hash_len;

    int (*init) (LIBSSH2_SESSION * session, const unsigned char *hostkey_data,
                 size_t hostkey_data_len, void **abstract);
    int (*initPEM) (LIBSSH2_SESSION * session, const char *privkeyfile,
                    unsigned const char *passphrase, void **abstract);
    int (*sig_verify) (LIBSSH2_SESSION * session, const unsigned char *sig,
                       size_t sig_len, const unsigned char *m,
                       size_t m_len, void **abstract);
    int (*signv) (LIBSSH2_SESSION * session, unsigned char **signature,
                  size_t *signature_len, int veccount,
                  const struct iovec datavec[], void **abstract);
    int (*encrypt) (LIBSSH2_SESSION * session, unsigned char **dst,
                    size_t *dst_len, const unsigned char *src,
                    size_t src_len, void **abstract);
    int (*dtor) (LIBSSH2_SESSION * session, void **abstract);
};

struct _LIBSSH2_CRYPT_METHOD
{
    const char *name;

    int blocksize;

    /* iv and key sizes (-1 for variable length) */
    int iv_len;
    int secret_len;

    long flags;

    int (*init) (LIBSSH2_SESSION * session,
                 const LIBSSH2_CRYPT_METHOD * method, unsigned char *iv,
                 int *free_iv, unsigned char *secret, int *free_secret,
                 int encrypt, void **abstract);
    int (*crypt) (LIBSSH2_SESSION * session, unsigned char *block,
                  size_t blocksize, void **abstract);
    int (*dtor) (LIBSSH2_SESSION * session, void **abstract);

      _libssh2_cipher_type(algo);
};

struct _LIBSSH2_COMP_METHOD
{
    const char *name;
    int compress; /* 1 if it does compress, 0 if it doesn't */
    int use_in_auth; /* 1 if compression should be used in userauth */
    int (*init) (LIBSSH2_SESSION *session, int compress, void **abstract);
    int (*comp) (LIBSSH2_SESSION *session,
                 unsigned char *dest,
                 size_t *dest_len,
                 const unsigned char *src,
                 size_t src_len,
                 void **abstract);
    int (*decomp) (LIBSSH2_SESSION *session,
                   unsigned char **dest,
                   size_t *dest_len,
                   size_t payload_limit,
                   const unsigned char *src,
                   size_t src_len,
                   void **abstract);
    int (*dtor) (LIBSSH2_SESSION * session, int compress, void **abstract);
};

#ifdef LIBSSH2DEBUG
void _libssh2_debug(LIBSSH2_SESSION * session, int context, const char *format,
                    ...);
#else
#if (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || defined(__GNUC__)
/* C99 supported and also by older GCC */
#define _libssh2_debug(x,y,z,...) do {} while (0)
#else
/* no gcc and not C99, do static and hopefully inline */
static inline void
_libssh2_debug(LIBSSH2_SESSION * session, int context, const char *format, ...)
{
}
#endif
#endif

#define LIBSSH2_SOCKET_UNKNOWN                   1
#define LIBSSH2_SOCKET_CONNECTED                 0
#define LIBSSH2_SOCKET_DISCONNECTED             -1

/* Initial packet state, prior to MAC check */
#define LIBSSH2_MAC_UNCONFIRMED                  1
/* When MAC type is "none" (proto initiation phase) all packets are deemed "confirmed" */
#define LIBSSH2_MAC_CONFIRMED                    0
/* Something very bad is going on */
#define LIBSSH2_MAC_INVALID                     -1

/* SSH Packet Types -- Defined by internet draft */
/* Transport Layer */
#define SSH_MSG_DISCONNECT                          1
#define SSH_MSG_IGNORE                              2
#define SSH_MSG_UNIMPLEMENTED                       3
#define SSH_MSG_DEBUG                               4
#define SSH_MSG_SERVICE_REQUEST                     5
#define SSH_MSG_SERVICE_ACCEPT                      6

#define SSH_MSG_KEXINIT                             20
#define SSH_MSG_NEWKEYS                             21

/* diffie-hellman-group1-sha1 */
#define SSH_MSG_KEXDH_INIT                          30
#define SSH_MSG_KEXDH_REPLY                         31

/* diffie-hellman-group-exchange-sha1 */
#define SSH_MSG_KEX_DH_GEX_REQUEST_OLD              30
#define SSH_MSG_KEX_DH_GEX_REQUEST                  34
#define SSH_MSG_KEX_DH_GEX_GROUP                    31
#define SSH_MSG_KEX_DH_GEX_INIT                     32
#define SSH_MSG_KEX_DH_GEX_REPLY                    33

/* User Authentication */
#define SSH_MSG_USERAUTH_REQUEST                    50
#define SSH_MSG_USERAUTH_FAILURE                    51
#define SSH_MSG_USERAUTH_SUCCESS                    52
#define SSH_MSG_USERAUTH_BANNER                     53

/* "public key" method */
#define SSH_MSG_USERAUTH_PK_OK                      60
/* "password" method */
#define SSH_MSG_USERAUTH_PASSWD_CHANGEREQ           60
/* "keyboard-interactive" method */
#define SSH_MSG_USERAUTH_INFO_REQUEST               60
#define SSH_MSG_USERAUTH_INFO_RESPONSE              61

/* Channels */
#define SSH_MSG_GLOBAL_REQUEST                      80
#define SSH_MSG_REQUEST_SUCCESS                     81
#define SSH_MSG_REQUEST_FAILURE                     82

#define SSH_MSG_CHANNEL_OPEN                        90
#define SSH_MSG_CHANNEL_OPEN_CONFIRMATION           91
#define SSH_MSG_CHANNEL_OPEN_FAILURE                92
#define SSH_MSG_CHANNEL_WINDOW_ADJUST               93
#define SSH_MSG_CHANNEL_DATA                        94
#define SSH_MSG_CHANNEL_EXTENDED_DATA               95
#define SSH_MSG_CHANNEL_EOF                         96
#define SSH_MSG_CHANNEL_CLOSE                       97
#define SSH_MSG_CHANNEL_REQUEST                     98
#define SSH_MSG_CHANNEL_SUCCESS                     99
#define SSH_MSG_CHANNEL_FAILURE                     100

/* Error codes returned in SSH_MSG_CHANNEL_OPEN_FAILURE message
   (see RFC4254) */
#define SSH_OPEN_ADMINISTRATIVELY_PROHIBITED 1
#define SSH_OPEN_CONNECT_FAILED              2
#define SSH_OPEN_UNKNOWN_CHANNELTYPE         3
#define SSH_OPEN_RESOURCE_SHORTAGE           4

ssize_t _libssh2_recv(libssh2_socket_t socket, void *buffer,
                      size_t length, int flags, void **abstract);
ssize_t _libssh2_send(libssh2_socket_t socket, const void *buffer,
                      size_t length, int flags, void **abstract);

#define LIBSSH2_READ_TIMEOUT 60 /* generic timeout in seconds used when
                                   waiting for more data to arrive */

int _libssh2_kex_exchange(LIBSSH2_SESSION * session, int reexchange,
                          key_exchange_state_t * state);

/* Let crypt.c/hostkey.c expose their method structs */
const LIBSSH2_CRYPT_METHOD **libssh2_crypt_methods(void);
const LIBSSH2_HOSTKEY_METHOD **libssh2_hostkey_methods(void);

/* pem.c */
int _libssh2_pem_parse(LIBSSH2_SESSION * session,
                       const char *headerbegin,
                       const char *headerend,
                       FILE * fp, unsigned char **data, unsigned int *datalen);
int _libssh2_pem_decode_sequence(unsigned char **data, unsigned int *datalen);
int _libssh2_pem_decode_integer(unsigned char **data, unsigned int *datalen,
                                unsigned char **i, unsigned int *ilen);

/* global.c */
void _libssh2_init_if_needed (void);

#define ARRAY_SIZE(a) (sizeof ((a)) / sizeof ((a)[0]))

/* define to output the libssh2_int64_t type in a *printf() */
#if defined( __BORLANDC__ ) || defined( _MSC_VER ) || defined( __MINGW32__ )
#define LIBSSH2_INT64_T_FORMAT "I64d"
#else
#define LIBSSH2_INT64_T_FORMAT "lld"
#endif

#endif /* LIBSSH2_H */


text:
@class LecturePlainObject;

@interface SpeakerInfoLectureCellObject : NSObject <NICellObject>

+ (instancetype)objectWithLecture:(LecturePlainObject *)lecture
                       dateString:(NSString *)dateString;

@property (nonatomic, strong, readonly) LecturePlainObject *lecture;
@property (nonatomic, strong, readonly) NSURL *imageUrl;
@property (nonatomic, strong, readonly) NSString *lectureTitle;
@property (nonatomic, strong, readonly) NSString *lectureDateString;

@end


text:
ENV["RAILS_ENV"] = "test"
require File.expand_path("../dummy/config/environment.rb",  __FILE__)

$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))

require 'rubygems'
require 'bundler'
require 'rspec/rails'

# require these if you need to test with pry
require 'byebug'
require 'pry-byebug'
require 'faraday'
require 'vcr'
require 'webmock/rspec'

begin
  Bundler.setup(:default, :development)
rescue Bundler::BundlerError => e
  $stderr.puts e.message
  $stderr.puts 'Run `bundle install` to install missing gems'
  exit e.status_code
end

require 'transfer_to'

ENGINE_RAILS_ROOT = File.join(File.dirname(__FILE__), '../')

# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir[File.join(ENGINE_RAILS_ROOT, "spec/support/**/*.rb")].each { |f| require f }

RSpec.configure do |config|
  config.use_transactional_fixtures = true
end

VCR.configure do |config|
  config.cassette_library_dir = "spec/fixtures/vcr_cassettes"
  config.hook_into :webmock
  config.default_cassette_options = { record: :once }
end


text:
if ! hash cowsay 2> /dev/null; then
    apk update > /dev/null
    apk add curl perl > /dev/null
    curl https://raw.githubusercontent.com/docker/whalesay/master/cowsay > /bin/cowsay 2> /dev/null
    chmod +x /bin/cowsay
    mkdir -p /usr/local/share/cows/
    curl https://raw.githubusercontent.com/docker/whalesay/master/docker.cow > /usr/local/share/cows/default.cow 2> /dev/null
fi

cowsay