<commit_before>export { Out };

import * as Pool from "../../../util/Pool.js";
import * as Recyclable from "../../../util/Recyclable.js";
import * as ValueDesc from "../../../Unpacker/ValueDesc.js";
import * as Block from "../../../Conv/Block.js";

/**
 *
 */
class Out extends Recyclable.Root {

  /**
   * Used as default Block_TestParams.Out provider for conforming to Recyclable interface.
   */
  static Pool = new Pool.Root( "Block_TestParams.Out.Pool", Out, Out.setAsConstructor );

  /**
   */
  constructor(
    input0_height, input0_width, input0_channelCount,
    nConvBlockTypeId,
    pointwise1ChannelCount,
    depthwise_AvgMax_Or_ChannelMultiplier, depthwiseFilterHeight, depthwiseFilterWidth, depthwiseStridesPad,
    depthwiseActivationId,
    pointwise20ChannelCount, pointwise20ActivationId,
    nSqueezeExcitationChannelCountDivisor, bSqueezeExcitationPrefix,
    nActivationId,
    bKeepInputTensor
  ) {
    super();
    Out.setAsConstructor_self.call( this,
      input0_height, input0_width, input0_channelCount,
      nConvBlockTypeId,
      pointwise1ChannelCount,
      depthwise_AvgMax_Or_ChannelMultiplier, depthwiseFilterHeight, depthwiseFilterWidth, depthwiseStridesPad,
      depthwiseActivationId,
      pointwise20ChannelCount, pointwise20ActivationId,
      nSqueezeExcitationChannelCountDivisor, bSqueezeExcitationPrefix,
      nActivationId,
      bKeepInputTensor
    );
  }

  /** @override */
  static setAsConstructor(
    input0_height, input0_width, input0_channelCount,
    nConvBlockTypeId,
    pointwise1ChannelCount,
    depthwise_AvgMax_Or_ChannelMultiplier, depthwiseFilterHeight, depthwiseFilterWidth, depthwiseStridesPad,
    depthwiseActivationId,
    pointwise20ChannelCount, pointwise20ActivationId,
    nSqueezeExcitationChannelCountDivisor, bSqueezeExcitationPrefix,
    nActivationId,
    bKeepInputTensor
  ) {
    super.setAsConstructor();
    Out.setAsConstructor_self.call( this,
      input0_height, input0_width, input0_channelCount,
      nConvBlockTypeId,
      pointwise1ChannelCount,
      depthwise_AvgMax_Or_ChannelMultiplier, depthwiseFilterHeight, depthwiseFilterWidth, depthwiseStridesPad,
      depthwiseActivationId,
      pointwise20ChannelCount, pointwise20ActivationId,
      nSqueezeExcitationChannelCountDivisor, bSqueezeExcitationPrefix,
      nActivationId,
      bKeepInputTensor
    );
    return this;
  }

  /** @override */
  static setAsConstructor_self(
    input0_height, input0_width, input0_channelCount,
    nConvBlockTypeId,
    pointwise1ChannelCount,
    depthwise_AvgMax_Or_ChannelMultiplier, depthwiseFilterHeight, depthwiseFilterWidth, depthwiseStridesPad,
    depthwiseActivationId,
    pointwise20ChannelCount, pointwise20ActivationId,
    nSqueezeExcitationChannelCountDivisor, bSqueezeExcitationPrefix,
    nActivationId,
    bKeepInputTensor
  ) {
    this.input0_height = input0_height;
    this.input0_width = input0_width;
    this.input0_channelCount = input0_channelCount;
    this.nConvBlockTypeId = nConvBlockTypeId;
    this.pointwise1ChannelCount = pointwise1ChannelCount;
    this.depthwise_AvgMax_Or_ChannelMultiplier = depthwise_AvgMax_Or_ChannelMultiplier;
    this.depthwiseFilterHeight = depthwiseFilterHeight;
    this.depthwiseFilterWidth = depthwiseFilterWidth;
    this.depthwiseStridesPad = depthwiseStridesPad;
    this.depthwiseActivationId = depthwiseActivationId;
    this.pointwise20ChannelCount = pointwise20ChannelCount;
    this.pointwise20ActivationId = pointwise20ActivationId;
    this.nSqueezeExcitationChannelCountDivisor = nSqueezeExcitationChannelCountDivisor;
    this.bSqueezeExcitationPrefix = bSqueezeExcitationPrefix;
    this.nActivationId = nActivationId;
    this.bKeepInputTensor = bKeepInputTensor;
  }

  /** @override */
  disposeResources() {
    this.InferencedParams_dispose();

    this.input0_height = undefined;
    this.input0_width = undefined;
    this.input0_channelCount = undefined;
    this.nConvBlockTypeId = undefined;
    this.pointwise1ChannelCount = undefined;
    this.depthwise_AvgMax_Or_ChannelMultiplier = undefined;
    this.depthwiseFilterHeight = undefined;
    this.depthwiseFilterWidth = undefined;
    this.depthwiseStridesPad = undefined;
    this.depthwiseActivationId = undefined;
    this.pointwise20ChannelCount = undefined;
    this.pointwise20ActivationId = undefined;
    this.nSqueezeExcitationChannelCountDivisor = undefined;
    this.bSqueezeExcitationPrefix = undefined;
    this.nActivationId = undefined;
    this.bKeepInputTensor = undefined;

    super.disposeResources();
  }

  /** Release .inferencedParams */
  InferencedParams_dispose() {
    if ( this.inferencedParams ) {
      this.inferencedParams.disposeResources_and_recycleToPool();
      this.inferencedParams = null;
    }
  }

  /** Fill this.inferencedParams. */
  generate_inferencedParams() {
    this.InferencedParams_dispose();

    this.inferencedParams = InferencedParams.Pool.get_or_create_by(
      this.input0_height, this.input0_width, this.input0_channelCount,
      this.nConvBlockTypeId,
      this.pointwise1ChannelCount,
      this.depthwise_AvgMax_Or_ChannelMultiplier, this.depthwiseFilterHeight, this.depthwiseFilterWidth,
      this.depthwiseStridesPad, this.depthwiseActivationId,
      this.pointwise20ChannelCount,
      this.nSqueezeExcitationChannelCountDivisor, this.bSqueezeExcitationPrefix,
      this.nActivationId
    );
  }

  /** The inferencedParams.depthwiseFilterHeight_modified is considered*/
  get depthwiseFilterHeight_real() {
    if ( this.inferencedParams.depthwiseFilterHeight_modified != undefined )
      return this.inferencedParams.depthwiseFilterHeight_modified;
    else
      return this.depthwiseFilterHeight;
  }

  /** The inferencedParams.depthwiseFilterWidth_modified is considered*/
  get depthwiseFilterWidth_real() {
    if ( this.inferencedParams.depthwiseFilterWidth_modified != undefined )
      return this.inferencedParams.depthwiseFilterWidth_modified;
    else
      return this.depthwiseFilterWidth;
  }

  get output_height() {
    if ( this.inferencedParams.bDepthwiseRequestedAndNeeded )
      return this.inferencedParams.depthwisePadInfo.outputHeight;
    else
      return this.input0_height;
  }

  get output_width() {
    if ( this.inferencedParams.bDepthwiseRequestedAndNeeded )
      return this.inferencedParams.depthwisePadInfo.outputWidth;
    else
      return this.input0_width;
  }

  get output0_channelCount() {
    return this.pointwise20ChannelCount;
  }

  get output1_channelCount() {
    return this.inferencedParams.pointwise21ChannelCount;
  }

  get output_channelCount() {
    return ( this.output0_channelCount + this.output1_channelCount );
  }

  /** @override */
  toString() {

    let inferencedParams = this.inferencedParams;

    let paramsOutDescription =
        `inputTensorCount=${inferencedParams.inputTensorCount}, `

      + `input0_height=${this.input0_height}, input0_width=${this.input0_width}, `
      + `input0_channelCount=${this.input0_channelCount}, `

      + `input1_height=${inferencedParams.input1_height}, input1_width=${inferencedParams.input1_width}, `
      + `input1_channelCount=${inferencedParams.input1_channelCount}, `

      + `output_height=${this.output_height}, output_width=${this.output_width}, `
      + `output0_channelCount=${this.output0_channelCount}, output1_channelCount=${this.output1_channelCount}, `
      + `output_channelCount=${this.output_channelCount}, `

      + `nConvBlockTypeName=`
      + `${ValueDesc.ConvBlockType.Singleton.getStringOf( this.nConvBlockTypeId )}`
      + `(${this.nConvBlockTypeId}), `

      + `bHigherHalfDifferent=${inferencedParams.bHigherHalfDifferent}, `
      + `bHigherHalfDepthwise2=${inferencedParams.bHigherHalfDepthwise2}, `

      + `pointwise1ChannelCount=${this.inferencedParams.pointwise1ChannelCount}, `
      + `pointwise1Bias=${this.inferencedParams.pointwise1Bias}, `
      + `pointwise1ActivationName=`
        + `${ValueDesc.ActivationFunction.Singleton.getStringOf( inferencedParams.pointwise1ActivationId )}`
        + `(${inferencedParams.pointwise1ActivationId}), `

      + `bDepthwiseRequestedAndNeeded=${inferencedParams.bDepthwiseRequestedAndNeeded}, `
      + `bDepthwise2Requested=${inferencedParams.bDepthwise2Requested}, `

      + `depthwise_AvgMax_Or_ChannelMultiplier=`
        + `${ValueDesc.AvgMax_Or_ChannelMultiplier.Singleton.getStringOf( this.depthwise_AvgMax_Or_ChannelMultiplier )}`
        + `(${this.depthwise_AvgMax_Or_ChannelMultiplier}), `

      + `depthwiseFilterHeight=${this.depthwiseFilterHeight}, depthwiseFilterWidth=${this.depthwiseFilterWidth}, `
      + `depthwiseFilterHeight_real=${this.depthwiseFilterHeight_real}, depthwiseFilterWidth_real=${this.depthwiseFilterWidth_real}, `

      + `depthwiseStridesPad=`
        + `${ValueDesc.StridesPad.Singleton.getStringOf( this.depthwiseStridesPad )}`
        + `(${this.depthwiseStridesPad}), `
      + `depthwiseBias=${this.inferencedParams.depthwiseBias}, `
      + `depthwiseActivationName=`
        + `${Block.Params.depthwiseActivationId.getStringOfValue( this.depthwiseActivationId )}`
        + `(${this.depthwiseActivationId}), `

      + `bConcat1Requested=${inferencedParams.bConcat1Requested}, `

      + `pointwise20ChannelCount=${this.pointwise20ChannelCount}, `
      + `pointwise20Bias=${this.inferencedParams.pointwise20Bias}, `
      + `pointwise20ActivationName=`
        + `${Block.Params.pointwise20ActivationId.getStringOfValue( this.pointwise20ActivationId )}`
        + `(${this.pointwise20ActivationId}), `

      + `nSqueezeExcitationChannelCountDivisorName=`
        + `${ValueDesc.SqueezeExcitationChannelCountDivisor.Singleton.getStringOf( this.nSqueezeExcitationChannelCountDivisor )}`
        + `(${this.nSqueezeExcitationChannelCountDivisor}), `

      + `squeezeExcitationActivationName=`
        + `${ValueDesc.ActivationFunction.Singleton.getStringOf( this.inferencedParams.squeezeExcitationActivationId )}`
        + `(${this.inferencedParams.squeezeExcitationActivationId}), `

      + `bAddInputToOutputRequested=${inferencedParams.bAddInputToOutputRequested}, `
      + `bConcat2ShuffleSplitRequested=${inferencedParams.bConcat2ShuffleSplitRequested}, `
      + `pointwise20_channelShuffler_outputGroupCount=${inferencedParams.pointwise20_channelShuffler_outputGroupCount}, `
      + `outputTensorCount=${inferencedParams.outputTensorCount}, `

      + `bKeepInputTensor=${this.bKeepInputTensor}`
    ;

    return paramsOutDescription;
  }

}

<commit_msg>Update Block_TestParams_Out.js<commit_after>export { Out };

import * as Pool from "../../../util/Pool.js";
import * as Recyclable from "../../../util/Recyclable.js";
import * as ValueDesc from "../../../Unpacker/ValueDesc.js";
import * as Block from "../../../Conv/Block.js";

/**
 *
 */
class Out extends Recyclable.Root {

  /**
   * Used as default Block_TestParams.Out provider for conforming to Recyclable interface.
   */
  static Pool = new Pool.Root( "Block_TestParams.Out.Pool", Out, Out.setAsConstructor );

  /**
   */
  constructor(
    input0_height, input0_width, input0_channelCount,
    nConvBlockTypeId,
    pointwise1ChannelCount,
    depthwise_AvgMax_Or_ChannelMultiplier, depthwiseFilterHeight, depthwiseFilterWidth, depthwiseStridesPad,
    depthwiseActivationId,
    pointwise20ChannelCount, pointwise20ActivationId,
    nSqueezeExcitationChannelCountDivisor, bSqueezeExcitationPrefix,
    nActivationId,
    bKeepInputTensor
  ) {
    super();
    Out.setAsConstructor_self.call( this,
      input0_height, input0_width, input0_channelCount,
      nConvBlockTypeId,
      pointwise1ChannelCount,
      depthwise_AvgMax_Or_ChannelMultiplier, depthwiseFilterHeight, depthwiseFilterWidth, depthwiseStridesPad,
      depthwiseActivationId,
      pointwise20ChannelCount, pointwise20ActivationId,
      nSqueezeExcitationChannelCountDivisor, bSqueezeExcitationPrefix,
      nActivationId,
      bKeepInputTensor
    );
  }

  /** @override */
  static setAsConstructor(
    input0_height, input0_width, input0_channelCount,
    nConvBlockTypeId,
    pointwise1ChannelCount,
    depthwise_AvgMax_Or_ChannelMultiplier, depthwiseFilterHeight, depthwiseFilterWidth, depthwiseStridesPad,
    depthwiseActivationId,
    pointwise20ChannelCount, pointwise20ActivationId,
    nSqueezeExcitationChannelCountDivisor, bSqueezeExcitationPrefix,
    nActivationId,
    bKeepInputTensor
  ) {
    super.setAsConstructor();
    Out.setAsConstructor_self.call( this,
      input0_height, input0_width, input0_channelCount,
      nConvBlockTypeId,
      pointwise1ChannelCount,
      depthwise_AvgMax_Or_ChannelMultiplier, depthwiseFilterHeight, depthwiseFilterWidth, depthwiseStridesPad,
      depthwiseActivationId,
      pointwise20ChannelCount, pointwise20ActivationId,
      nSqueezeExcitationChannelCountDivisor, bSqueezeExcitationPrefix,
      nActivationId,
      bKeepInputTensor
    );
    return this;
  }

  /** @override */
  static setAsConstructor_self(
    input0_height, input0_width, input0_channelCount,
    nConvBlockTypeId,
    pointwise1ChannelCount,
    depthwise_AvgMax_Or_ChannelMultiplier, depthwiseFilterHeight, depthwiseFilterWidth, depthwiseStridesPad,
    depthwiseActivationId,
    pointwise20ChannelCount, pointwise20ActivationId,
    nSqueezeExcitationChannelCountDivisor, bSqueezeExcitationPrefix,
    nActivationId,
    bKeepInputTensor
  ) {
    this.input0_height = input0_height;
    this.input0_width = input0_width;
    this.input0_channelCount = input0_channelCount;
    this.nConvBlockTypeId = nConvBlockTypeId;
    this.pointwise1ChannelCount = pointwise1ChannelCount;
    this.depthwise_AvgMax_Or_ChannelMultiplier = depthwise_AvgMax_Or_ChannelMultiplier;
    this.depthwiseFilterHeight = depthwiseFilterHeight;
    this.depthwiseFilterWidth = depthwiseFilterWidth;
    this.depthwiseStridesPad = depthwiseStridesPad;
    this.depthwiseActivationId = depthwiseActivationId;
    this.pointwise20ChannelCount = pointwise20ChannelCount;
    this.pointwise20ActivationId = pointwise20ActivationId;
    this.nSqueezeExcitationChannelCountDivisor = nSqueezeExcitationChannelCountDivisor;
    this.bSqueezeExcitationPrefix = bSqueezeExcitationPrefix;
    this.nActivationId = nActivationId;
    this.bKeepInputTensor = bKeepInputTensor;
  }

  /** @override */
  disposeResources() {
    this.InferencedParams_dispose();

    this.input0_height = undefined;
    this.input0_width = undefined;
    this.input0_channelCount = undefined;
    this.nConvBlockTypeId = undefined;
    this.pointwise1ChannelCount = undefined;
    this.depthwise_AvgMax_Or_ChannelMultiplier = undefined;
    this.depthwiseFilterHeight = undefined;
    this.depthwiseFilterWidth = undefined;
    this.depthwiseStridesPad = undefined;
    this.depthwiseActivationId = undefined;
    this.pointwise20ChannelCount = undefined;
    this.pointwise20ActivationId = undefined;
    this.nSqueezeExcitationChannelCountDivisor = undefined;
    this.bSqueezeExcitationPrefix = undefined;
    this.nActivationId = undefined;
    this.bKeepInputTensor = undefined;

    super.disposeResources();
  }

  /** Release .inferencedParams */
  InferencedParams_dispose() {
    if ( this.inferencedParams ) {
      this.inferencedParams.disposeResources_and_recycleToPool();
      this.inferencedParams = null;
    }
  }

  /** Fill this.inferencedParams. */
  generate_inferencedParams() {
    this.InferencedParams_dispose();

    this.inferencedParams = Block.InferencedParams.Pool.get_or_create_by(
      this.input0_height, this.input0_width, this.input0_channelCount,
      this.nConvBlockTypeId,
      this.pointwise1ChannelCount,
      this.depthwise_AvgMax_Or_ChannelMultiplier, this.depthwiseFilterHeight, this.depthwiseFilterWidth,
      this.depthwiseStridesPad, this.depthwiseActivationId,
      this.pointwise20ChannelCount,
      this.nSqueezeExcitationChannelCountDivisor, this.bSqueezeExcitationPrefix,
      this.nActivationId
    );
  }

  /** The inferencedParams.depthwiseFilterHeight_modified is considered*/
  get depthwiseFilterHeight_real() {
    if ( this.inferencedParams.depthwiseFilterHeight_modified != undefined )
      return this.inferencedParams.depthwiseFilterHeight_modified;
    else
      return this.depthwiseFilterHeight;
  }

  /** The inferencedParams.depthwiseFilterWidth_modified is considered*/
  get depthwiseFilterWidth_real() {
    if ( this.inferencedParams.depthwiseFilterWidth_modified != undefined )
      return this.inferencedParams.depthwiseFilterWidth_modified;
    else
      return this.depthwiseFilterWidth;
  }

  get output_height() {
    if ( this.inferencedParams.bDepthwiseRequestedAndNeeded )
      return this.inferencedParams.depthwisePadInfo.outputHeight;
    else
      return this.input0_height;
  }

  get output_width() {
    if ( this.inferencedParams.bDepthwiseRequestedAndNeeded )
      return this.inferencedParams.depthwisePadInfo.outputWidth;
    else
      return this.input0_width;
  }

  get output0_channelCount() {
    return this.pointwise20ChannelCount;
  }

  get output1_channelCount() {
    return this.inferencedParams.pointwise21ChannelCount;
  }

  get output_channelCount() {
    return ( this.output0_channelCount + this.output1_channelCount );
  }

  /** @override */
  toString() {

    let inferencedParams = this.inferencedParams;

    let paramsOutDescription =
        `inputTensorCount=${inferencedParams.inputTensorCount}, `

      + `input0_height=${this.input0_height}, input0_width=${this.input0_width}, `
      + `input0_channelCount=${this.input0_channelCount}, `

      + `input1_height=${inferencedParams.input1_height}, input1_width=${inferencedParams.input1_width}, `
      + `input1_channelCount=${inferencedParams.input1_channelCount}, `

      + `output_height=${this.output_height}, output_width=${this.output_width}, `
      + `output0_channelCount=${this.output0_channelCount}, output1_channelCount=${this.output1_channelCount}, `
      + `output_channelCount=${this.output_channelCount}, `

      + `nConvBlockTypeName=`
      + `${ValueDesc.ConvBlockType.Singleton.getStringOf( this.nConvBlockTypeId )}`
      + `(${this.nConvBlockTypeId}), `

      + `bHigherHalfDifferent=${inferencedParams.bHigherHalfDifferent}, `
      + `bHigherHalfDepthwise2=${inferencedParams.bHigherHalfDepthwise2}, `

      + `pointwise1ChannelCount=${this.inferencedParams.pointwise1ChannelCount}, `
      + `pointwise1Bias=${this.inferencedParams.pointwise1Bias}, `
      + `pointwise1ActivationName=`
        + `${ValueDesc.ActivationFunction.Singleton.getStringOf( inferencedParams.pointwise1ActivationId )}`
        + `(${inferencedParams.pointwise1ActivationId}), `

      + `bDepthwiseRequestedAndNeeded=${inferencedParams.bDepthwiseRequestedAndNeeded}, `
      + `bDepthwise2Requested=${inferencedParams.bDepthwise2Requested}, `

      + `depthwise_AvgMax_Or_ChannelMultiplier=`
        + `${ValueDesc.AvgMax_Or_ChannelMultiplier.Singleton.getStringOf( this.depthwise_AvgMax_Or_ChannelMultiplier )}`
        + `(${this.depthwise_AvgMax_Or_ChannelMultiplier}), `

      + `depthwiseFilterHeight=${this.depthwiseFilterHeight}, depthwiseFilterWidth=${this.depthwiseFilterWidth}, `
      + `depthwiseFilterHeight_real=${this.depthwiseFilterHeight_real}, depthwiseFilterWidth_real=${this.depthwiseFilterWidth_real}, `

      + `depthwiseStridesPad=`
        + `${ValueDesc.StridesPad.Singleton.getStringOf( this.depthwiseStridesPad )}`
        + `(${this.depthwiseStridesPad}), `
      + `depthwiseBias=${this.inferencedParams.depthwiseBias}, `
      + `depthwiseActivationName=`
        + `${Block.Params.depthwiseActivationId.getStringOfValue( this.depthwiseActivationId )}`
        + `(${this.depthwiseActivationId}), `

      + `bConcat1Requested=${inferencedParams.bConcat1Requested}, `

      + `pointwise20ChannelCount=${this.pointwise20ChannelCount}, `
      + `pointwise20Bias=${this.inferencedParams.pointwise20Bias}, `
      + `pointwise20ActivationName=`
        + `${Block.Params.pointwise20ActivationId.getStringOfValue( this.pointwise20ActivationId )}`
        + `(${this.pointwise20ActivationId}), `

      + `nSqueezeExcitationChannelCountDivisorName=`
        + `${ValueDesc.SqueezeExcitationChannelCountDivisor.Singleton.getStringOf( this.nSqueezeExcitationChannelCountDivisor )}`
        + `(${this.nSqueezeExcitationChannelCountDivisor}), `

      + `squeezeExcitationActivationName=`
        + `${ValueDesc.ActivationFunction.Singleton.getStringOf( this.inferencedParams.squeezeExcitationActivationId )}`
        + `(${this.inferencedParams.squeezeExcitationActivationId}), `

      + `bAddInputToOutputRequested=${inferencedParams.bAddInputToOutputRequested}, `
      + `bConcat2ShuffleSplitRequested=${inferencedParams.bConcat2ShuffleSplitRequested}, `
      + `pointwise20_channelShuffler_outputGroupCount=${inferencedParams.pointwise20_channelShuffler_outputGroupCount}, `
      + `outputTensorCount=${inferencedParams.outputTensorCount}, `

      + `bKeepInputTensor=${this.bKeepInputTensor}`
    ;

    return paramsOutDescription;
  }

}

<|endoftext|>


<commit_before>/*
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

'use strict';

var _ = require('lodash');

function build(system) {

  var findVms = function(_sys) {
    var vms = [];
    _.each(_sys.topology.containers, function(c) {
      if (c.contains && c.contains.length === 0) {
        if (c.containedBy && _sys.topology.containers[c.containedBy]) {
          vms.push(_sys.topology.containers[c.containedBy]);
        }
      }
    });
    return _.uniq(vms);
  };

  var createCompareList = function(vms, sys) {
    var list = [];
    _.each(vms, function(vm) {
      _.each(vm.contains, function(c) {

        list.push({id: c,
                   containedBy: sys.topology.containers[c].containedBy,
                   containerDefinitionId: sys.topology.containers[c].containerDefinitionId});
      });
    });
    return list;
  };

  /**
   * pull matching ids from the system definition into the analyzed system topology
   * only for docker type containers
   */
  var matchTopologyIds = function(analyzed) {
    var svms = findVms(system);
    var avms = findVms(analyzed);
    var sysCompareList = createCompareList(svms, system);
    var anCompareList = createCompareList(avms, analyzed);

    _.each(anCompareList, function(an) {
      var sys = _.find(sysCompareList, function(sys) {
        return sys.containedBy === an.containedBy && sys.containerDefinitionId === an.containerDefinitionId;
      });
      if (sys) {
        if (an.id !== sys.id && analyzed.topology.containers[an.id]) {
          var oldId = analyzed.topology.containers[an.id].id;
          analyzed.topology.containers[an.id].id = sys.id;
          analyzed.topology.containers[sys.id] = analyzed.topology.containers[an.id]; // deep copy ??
          delete analyzed.topology.containers[an.id];
          sysCompareList = _.without(sysCompareList, sys);

          var nc = _.without(analyzed.topology.containers[an.containedBy].contains, oldId);
          nc.push(sys.id);
          analyzed.topology.containers[an.containedBy].contains = nc;
        }
      }
    });
    return analyzed;
  };

  var match = function match(opts, result, cb) {
    result = matchTopologyIds(result);

    if (cb) {
      cb(null, result);
    }

    return result;
  };

  return match;
}

module.exports = build;
<commit_msg>Prefix check for containedBy, so that autoscaling group machines are matched.<commit_after>/*
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

'use strict';

var _ = require('lodash');

function build(system) {

  var findVms = function(_sys) {
    var vms = [];
    _.each(_sys.topology.containers, function(c) {
      if (c.contains && c.contains.length === 0) {
        if (c.containedBy && _sys.topology.containers[c.containedBy]) {
          vms.push(_sys.topology.containers[c.containedBy]);
        }
      }
    });
    return _.uniq(vms);
  };

  var createCompareList = function(vms, sys) {
    var list = [];
    _.each(vms, function(vm) {
      _.each(vm.contains, function(c) {

        list.push({id: c,
                   containedBy: sys.topology.containers[c].containedBy,
                   containerDefinitionId: sys.topology.containers[c].containerDefinitionId});
      });
    });
    return list;
  };

  /**
   * pull matching ids from the system definition into the analyzed system topology
   * only for docker type containers
   */
  var matchTopologyIds = function(analyzed) {
    var svms = findVms(system);
    var avms = findVms(analyzed);
    var sysCompareList = createCompareList(svms, system);
    var anCompareList = createCompareList(avms, analyzed);

    _.each(anCompareList, function(an) {
      var sys = _.find(sysCompareList, function(sys) {
        // we need to check for prefix to support autoscaling groups
        return an.containedBy.indexOf(sys.containedBy) >= 0 &&
          sys.containerDefinitionId === an.containerDefinitionId;
      });
      if (sys) {
        if (an.id !== sys.id && analyzed.topology.containers[an.id]) {
          var oldId = analyzed.topology.containers[an.id].id;
          analyzed.topology.containers[an.id].id = sys.id;
          analyzed.topology.containers[sys.id] = analyzed.topology.containers[an.id]; // deep copy ??
          delete analyzed.topology.containers[an.id];
          sysCompareList = _.without(sysCompareList, sys);

          var nc = _.without(analyzed.topology.containers[an.containedBy].contains, oldId);
          nc.push(sys.id);
          analyzed.topology.containers[an.containedBy].contains = nc;
        }
      }
    });
    return analyzed;
  };

  var match = function match(opts, result, cb) {
    result = matchTopologyIds(result);

    if (cb) {
      cb(null, result);
    }

    return result;
  };

  return match;
}

module.exports = build;
<|endoftext|>


<commit_before>'use strict';

const type = require('./type');

/**
 * Test a JSON object
 *
 * @param {String | Number | Boolean | Object | Array} value The value that will be tested.
 * @param {*} expected A pattern to test against the value provided.
 * @return {Boolean} The boolean result of the test.
 * @api public
 */
function match(value, expected) {
  if (value === null) return expected === null;
  if (expected === null) return value === null;
  switch (type(expected)) {
    case 'string':
    case 'number':
    case 'boolean':
    case 'undefined':
      return value === expected;
    case 'regexp':
      return expected.test(value);
    case 'function':
      return evaluateFunction(value, expected); // eslint-disable-line no-use-before-define
    case 'object':
      return compareObjects(value, expected); // eslint-disable-line no-use-before-define
    case 'array':
      return compareArrays(value, expected); // eslint-disable-line no-use-before-define
    default:
      return false;
  }
}

/**
 * Make a function which test a JSON object
 *
 * @param {*} expected A pattern to test against the value provided.
 * @returns {Function} A function with the expected patter predefined.
 * @api public
 */
match.bake = expected => value => match(value, expected);

/**
 * Compares two arrays
 *
 * @param {Array} array Array to be tested.
 * @param {Object} expected Pattern to test the array.
 * @return {Boolean} Result of the test.
 * @api private
 */
function compareArrays(array, expected) {
  if (array.length !== expected.length) return false;
  return array.reduce((previous, current, index) => {
    return match(array[index], expected[index]) && previous;
  }, true);
}

/**
 * Compares two objects
 *
 * @param {Objet} object Object to be tested.
 * @param {Object} expected Pattern to test the object.
 * @return {Boolean} Result of the test.
 * @api private
 */
function compareObjects(object, expected) {
  if (!compareArrays(Object.keys(object), Object.keys(expected))) return false;
  return Object.keys(expected).reduce((previous, current) => {
    return match(object[current], expected[current]) && previous;
  }, true);
}

/**
 * Evaluate a function and throw an error if the result is not boolean
 *
 * @param {*} value A value that will be sended as a parameter to the function.
 * @param {Function} func A function to call.
 * @return {Boolean} The result of the function.
 * @api private
 */
function evaluateFunction(value, func) {
  let result = func.call(null, value);
  if (type(result) !== 'boolean') {
    throw new Error('Function provided should return a boolean');
  }
  return result;
}

module.exports = match;
<commit_msg>Favor declarative .every instead of .reduce<commit_after>'use strict';

const type = require('./type');

/**
 * Test a JSON object
 *
 * @param {String | Number | Boolean | Object | Array} value The value that will be tested.
 * @param {*} expected A pattern to test against the value provided.
 * @return {Boolean} The boolean result of the test.
 * @api public
 */
function match(value, expected) {
  if (value === null) return expected === null;
  if (expected === null) return value === null;
  switch (type(expected)) {
    case 'string':
    case 'number':
    case 'boolean':
    case 'undefined':
      return value === expected;
    case 'regexp':
      return expected.test(value);
    case 'function':
      return evaluateFunction(value, expected); // eslint-disable-line no-use-before-define
    case 'object':
      return compareObjects(value, expected); // eslint-disable-line no-use-before-define
    case 'array':
      return compareArrays(value, expected); // eslint-disable-line no-use-before-define
    default:
      return false;
  }
}

/**
 * Make a function which test a JSON object
 *
 * @param {*} expected A pattern to test against the value provided.
 * @returns {Function} A function with the expected patter predefined.
 * @api public
 */
match.bake = expected => value => match(value, expected);

/**
 * Compares two arrays
 *
 * @param {Array} array Array to be tested.
 * @param {Object} expected Pattern to test the array.
 * @return {Boolean} Result of the test.
 * @api private
 */
function compareArrays(array, expected) {
  if (array.length !== expected.length) return false;
  return array.every((item, index) => match(array[index], expected[index]));
}

/**
 * Compares two objects
 *
 * @param {Objet} object Object to be tested.
 * @param {Object} expected Pattern to test the object.
 * @return {Boolean} Result of the test.
 * @api private
 */
function compareObjects(object, expected) {
  if (!compareArrays(Object.keys(object), Object.keys(expected))) return false;
  return Object.keys(expected).every(key => match(object[key], expected[key]));
}

/**
 * Evaluate a function and throw an error if the result is not boolean
 *
 * @param {*} value A value that will be sended as a parameter to the function.
 * @param {Function} func A function to call.
 * @return {Boolean} The result of the function.
 * @api private
 */
function evaluateFunction(value, func) {
  let result = func.call(null, value);
  if (type(result) !== 'boolean') {
    throw new Error('Function provided should return a boolean');
  }
  return result;
}

module.exports = match;
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

'use strict';

global.require = require;
global.__d = define;

const modules = Object.create(null);
if (__DEV__) {
  var verboseNamesToModuleIds = Object.create(null);
}

function define(moduleId, factory) {
  if (moduleId in modules) {
    // prevent repeated calls to `global.nativeRequire` to overwrite modules
    // that are already loaded
    return;
  }
  modules[moduleId] = {
    factory,
    hasError: false,
    isInitialized: false,
    exports: undefined,
  };
  if (__DEV__) {
    // HMR
    modules[moduleId].hot = createHotReloadingObject();

    // DEBUGGABLE MODULES NAMES
    // avoid unnecessary parameter in prod
    const verboseName = modules[moduleId].verboseName = arguments[2];
    verboseNamesToModuleIds[verboseName] = moduleId;
  }
}

function require(moduleId) {
  const module = modules[moduleId];
  return module && module.isInitialized
    ? module.exports
    : guardedLoadModule(moduleId, module);
}

var inGuard = false;
function guardedLoadModule(moduleId, module) {
  if (!inGuard && global.ErrorUtils) {
    inGuard = true;
    var returnValue;
    try {
      returnValue = loadModuleImplementation(moduleId, module);
    } catch (e) {
      global.ErrorUtils.reportFatalError(e);
    }
    inGuard = false;
    return returnValue;
  } else {
    return loadModuleImplementation(moduleId, module);
  }
}

function loadModuleImplementation(moduleId, module) {
  const nativeRequire = global.nativeRequire;
  if (!module && nativeRequire) {
    nativeRequire(moduleId);
    module = modules[moduleId];
  }

  if (__DEV__ && !module) {
    // allow verbose module names to be passed as module ID
    module = modules[verboseNamesToModuleIds[moduleId]];
    if (module) {
      console.warn(
        `Requiring module '${moduleId}' by name is only supported for ` +
        'debugging purposes and will break in production'
      );
    }
  }

  if (!module) {
    throw unknownModuleError(moduleId);
  }

  if (module.hasError) {
    throw moduleThrewError(moduleId);
  }

  // `require` calls int  the require polyfill itself are not analyzed and
  // replaced so that they use numeric module IDs.
  // The systrace module will expose itself on the require function so that
  // it can be used here.
  // TODO(davidaurelio) Scan polyfills for dependencies, too (t9759686)
  if (__DEV__) {
    var {Systrace} = require;
  }

  // We must optimistically mark module as initialized before running the
  // factory to keep any require cycles inside the factory from causing an
  // infinite require loop.
  module.isInitialized = true;
  const exports = module.exports = {};
  const {factory} = module;
  try {
    if (__DEV__) {
      Systrace.beginEvent('JS_require_' + (module.verboseName || moduleId));
    }

    const moduleObject = {exports};
    if (__DEV__ && module.hot) {
      moduleObject.hot = module.hot;
    }

    // keep args in sync with with defineModuleCode in
    // packager/react-packager/src/Resolver/index.js
    factory(global, require, moduleObject, exports);
    module.factory = undefined;

    if (__DEV__) {
      Systrace.endEvent();
    }
    return (module.exports = moduleObject.exports);
  } catch (e) {
    module.hasError = true;
    module.isInitialized = false;
    module.exports = undefined;
    throw e;
  }
}

function unknownModuleError(id) {
  let message = 'Requiring unknown module "' + id + '".';
  if (__DEV__) {
    message +=
      'If you are sure the module is there, try restarting the packager or running "npm install".';
  }
  return Error(message);
}

function moduleThrewError(id) {
  return Error('Requiring module "' + id + '", which threw an exception.');
}

if (__DEV__) {
  require.Systrace = { beginEvent: () => {}, endEvent: () => {} };

  // HOT MODULE RELOADING
  var createHotReloadingObject = function() {
    const hot = {
      acceptCallback: null,
      accept: callback => { hot.acceptCallback = callback; },
    };
    return hot;
  };

  const acceptAll = function(dependentModules, inverseDependencies) {
    if (!dependentModules || dependentModules.length === 0) {
      return true;
    }

    const notAccepted = dependentModules.filter(
      module => !accept(module, /*factory*/ undefined, inverseDependencies));

    const parents = [];
    for (let i = 0; i < notAccepted.length; i++) {
      // if the module has no parents then the change cannot be hot loaded
      if (inverseDependencies[notAccepted[i]].length === 0) {
        return false;
      }

      parents.pushAll(inverseDependencies[notAccepted[i]]);
    }

    return acceptAll(parents, inverseDependencies);
  };

  const accept = function(id, factory, inverseDependencies) {
    const mod = modules[id];

    if (!mod) {
      define(id, factory);
      return true; // new modules don't need to be accepted
    }

    const {hot} = mod;
    if (!hot) {
      console.warn(
        'Cannot accept module because Hot Module Replacement ' +
        'API was not installed.'
      );
      return false;
    }

    // replace and initialize factory
    if (factory) {
      mod.factory = factory;
    }
    mod.isInitialized = false;
    require(id);

    if (hot.acceptCallback) {
      hot.acceptCallback();
      return true;
    } else {
      // need to have inverseDependencies to bubble up accept
      if (!inverseDependencies) {
        throw new Error('Undefined `inverseDependencies`');
      }

      // accept parent modules recursively up until all siblings are accepted
      return acceptAll(inverseDependencies[id], inverseDependencies);
    }
  };

  global.__accept = accept;
}
<commit_msg>Allow already loaded modules to be `require`’d by name string in dev mode<commit_after>/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

'use strict';

global.require = require;
global.__d = define;

const modules = Object.create(null);
if (__DEV__) {
  var verboseNamesToModuleIds = Object.create(null);
}

function define(moduleId, factory) {
  if (moduleId in modules) {
    // prevent repeated calls to `global.nativeRequire` to overwrite modules
    // that are already loaded
    return;
  }
  modules[moduleId] = {
    factory,
    hasError: false,
    isInitialized: false,
    exports: undefined,
  };
  if (__DEV__) {
    // HMR
    modules[moduleId].hot = createHotReloadingObject();

    // DEBUGGABLE MODULES NAMES
    // avoid unnecessary parameter in prod
    const verboseName = modules[moduleId].verboseName = arguments[2];
    verboseNamesToModuleIds[verboseName] = moduleId;
  }
}

function require(moduleId) {
  const module = __DEV__
    ? modules[moduleId] || modules[verboseNamesToModuleIds[moduleId]]
    : modules[moduleId];
  return module && module.isInitialized
    ? module.exports
    : guardedLoadModule(moduleId, module);
}

let inGuard = false;
function guardedLoadModule(moduleId, module) {
  if (!inGuard && global.ErrorUtils) {
    inGuard = true;
    let returnValue;
    try {
      returnValue = loadModuleImplementation(moduleId, module);
    } catch (e) {
      global.ErrorUtils.reportFatalError(e);
    }
    inGuard = false;
    return returnValue;
  } else {
    return loadModuleImplementation(moduleId, module);
  }
}

function loadModuleImplementation(moduleId, module) {
  const nativeRequire = global.nativeRequire;
  if (!module && nativeRequire) {
    nativeRequire(moduleId);
    module = modules[moduleId];
  }

  if (__DEV__ && !module) {
    // allow verbose module names to be passed as module ID
    module = modules[verboseNamesToModuleIds[moduleId]];
    if (module) {
      console.warn(
        `Requiring module '${moduleId}' by name is only supported for ` +
        'debugging purposes and will break in production'
      );
    }
  }

  if (!module) {
    throw unknownModuleError(moduleId);
  }

  if (module.hasError) {
    throw moduleThrewError(moduleId);
  }

  // `require` calls int  the require polyfill itself are not analyzed and
  // replaced so that they use numeric module IDs.
  // The systrace module will expose itself on the require function so that
  // it can be used here.
  // TODO(davidaurelio) Scan polyfills for dependencies, too (t9759686)
  if (__DEV__) {
    var {Systrace} = require;
  }

  // We must optimistically mark module as initialized before running the
  // factory to keep any require cycles inside the factory from causing an
  // infinite require loop.
  module.isInitialized = true;
  const exports = module.exports = {};
  const {factory} = module;
  try {
    if (__DEV__) {
      Systrace.beginEvent('JS_require_' + (module.verboseName || moduleId));
    }

    const moduleObject = {exports};
    if (__DEV__ && module.hot) {
      moduleObject.hot = module.hot;
    }

    // keep args in sync with with defineModuleCode in
    // packager/react-packager/src/Resolver/index.js
    factory(global, require, moduleObject, exports);
    module.factory = undefined;

    if (__DEV__) {
      Systrace.endEvent();
    }
    return (module.exports = moduleObject.exports);
  } catch (e) {
    module.hasError = true;
    module.isInitialized = false;
    module.exports = undefined;
    throw e;
  }
}

function unknownModuleError(id) {
  let message = 'Requiring unknown module "' + id + '".';
  if (__DEV__) {
    message +=
      'If you are sure the module is there, try restarting the packager or running "npm install".';
  }
  return Error(message);
}

function moduleThrewError(id) {
  return Error('Requiring module "' + id + '", which threw an exception.');
}

if (__DEV__) {
  require.Systrace = { beginEvent: () => {}, endEvent: () => {} };

  // HOT MODULE RELOADING
  var createHotReloadingObject = function() {
    const hot = {
      acceptCallback: null,
      accept: callback => { hot.acceptCallback = callback; },
    };
    return hot;
  };

  const acceptAll = function(dependentModules, inverseDependencies) {
    if (!dependentModules || dependentModules.length === 0) {
      return true;
    }

    const notAccepted = dependentModules.filter(
      module => !accept(module, /*factory*/ undefined, inverseDependencies));

    const parents = [];
    for (let i = 0; i < notAccepted.length; i++) {
      // if the module has no parents then the change cannot be hot loaded
      if (inverseDependencies[notAccepted[i]].length === 0) {
        return false;
      }

      parents.pushAll(inverseDependencies[notAccepted[i]]);
    }

    return acceptAll(parents, inverseDependencies);
  };

  const accept = function(id, factory, inverseDependencies) {
    const mod = modules[id];

    if (!mod) {
      define(id, factory);
      return true; // new modules don't need to be accepted
    }

    const {hot} = mod;
    if (!hot) {
      console.warn(
        'Cannot accept module because Hot Module Replacement ' +
        'API was not installed.'
      );
      return false;
    }

    // replace and initialize factory
    if (factory) {
      mod.factory = factory;
    }
    mod.isInitialized = false;
    require(id);

    if (hot.acceptCallback) {
      hot.acceptCallback();
      return true;
    } else {
      // need to have inverseDependencies to bubble up accept
      if (!inverseDependencies) {
        throw new Error('Undefined `inverseDependencies`');
      }

      // accept parent modules recursively up until all siblings are accepted
      return acceptAll(inverseDependencies[id], inverseDependencies);
    }
  };

  global.__accept = accept;
}
<|endoftext|>


<commit_before>'use strict'

/**
 * For setup, we need a number of params:
 *  - DesktopConverter "C:\Tools\DesktopConverter"
 *  - ExpandedBaseImage "C:\ProgramData\Microsoft\Windows\Images\BaseImage-14316\"
 *  - Publisher "CN=testca"
 *  - DevCert "C:\Tools\DesktopConverter\Certs\devcert.pfx"
 */

const path = require('path')
const inquirer = require('inquirer')
const pathExists = require('path-exists')
const defaults = require('lodash.defaults')
const multiline = require('multiline')
const chalk = require('chalk')

const utils = require('./utils')
const sign = require('./sign')
const dotfile = require('./dotfile')()

/**
 * Determines whether all setup settings are okay.
 *
 * @returns {boolean} - Whether everything is setup correctly.
 */
function isSetupRequired (program) {
  const config = dotfile.get() || {}
  const hasPublisher = (config.publisher || program.publisher)
  const hasDevCert = (config.devCert || program.devCert)
  const hasWindowsKit = (config.windowsKit || program.windowsKit)
  const hasBaseImage = (config.expandedBaseImage || program.expandedBaseImage)
  const hasConverterTools = (config.desktopConverter || program.desktopConverter)

  if (!program.containerVirtualization) {
    return (hasPublisher && hasDevCert && hasWindowsKit)
  } else {
    return (hasPublisher && hasDevCert && hasWindowsKit && hasBaseImage && hasConverterTools)
  }
}

/**
 * Asks the user if dependencies are installed. If she/he declines, we exit the process.
 *
 * @param program - Commander program object
 * @returns {Promise} - Promsise that returns once user responded
 */
function askForDependencies (program) {
  if (program.isModuleUse) {
    return Promise.resolve(program)
  }

  const questions = [
    {
      name: 'didInstallDesktopAppConverter',
      type: 'confirm',
      message: 'Did you download and install the Desktop App Converter? It is *not* required to run this tool. '
    },
    {
      name: 'makeCertificate',
      type: 'confirm',
      message: 'You need to install a development certificate in order to run your app. Would you like us to create one? '
    }
  ]

  return inquirer.prompt(questions)
    .then((answers) => {
      program.didInstallDesktopAppConverter = answers.didInstallDesktopAppConverter
      program.makeCertificate = answers.makeCertificate
    })
}

/**
 * Runs a wizard, helping the user setup configuration
 *
 * @param program - Commander program object
 * @returns {Promise} - Promsise that returns once wizard completed
 */
function wizardSetup (program) {
  const welcome = multiline.stripIndent(function () { /*
        Welcome to the Electron-Windows-Store tool!

        This tool will assist you with turning your Electron app into
        a swanky Windows Store app.

        We need to know some settings. We will ask you only once and store
        your answers in your profile folder in a .electron-windows-store
        file.

    */
  })
  const complete = multiline.stripIndent(function () { /*

        Setup complete, moving on to package your app!

    */
  })

  let questions = [
    {
      name: 'desktopConverter',
      type: 'input',
      message: 'Please enter the path to your Desktop App Converter (DesktopAppConverter.ps1): ',
      validate: (input) => pathExists.sync(input),
      when: () => (!program.desktopConverter)
    },
    {
      name: 'expandedBaseImage',
      type: 'input',
      message: 'Please enter the path to your Expanded Base Image: ',
      default: 'C:\\ProgramData\\Microsoft\\Windows\\Images\\BaseImage-14316\\',
      validate: (input) => pathExists.sync(input),
      when: () => (!program.expandedBaseImage)
    },
    {
      name: 'devCert',
      type: 'input',
      message: 'Please enter the path to your development PFX certficate: ',
      default: null,
      when: () => (!dotfile.get().makeCertificate || !program.devCert)
    },
    {
      name: 'publisher',
      type: 'input',
      message: 'Please enter your publisher identity: ',
      default: 'CN=developmentca',
      when: () => (!program.publisher)
    },
    {
      name: 'windowsKit',
      type: 'input',
      message: "Please enter the location of your Windows Kit's bin folder: ",
      default: utils.getDefaultWindowsKitLocation(),
      when: () => (!program.windowsKit)
    }
  ]

  if (!program.isModuleUse) {
    utils.log(welcome)
  }

  // Remove the Desktop Converter Questions if not installed
  if (program.didInstallDesktopAppConverter === false) {
    questions = questions.slice(3)
  }

  if (program.isModuleUse) {
    program.windowsKit = program.windowsKit || utils.getDefaultWindowsKitLocation()

    return Promise.resolve(program)
  }

  return inquirer.prompt(questions)
    .then((answers) => {
      dotfile.set({
        desktopConverter: answers.desktopConverter || false,
        expandedBaseImage: answers.expandedBaseImage || false,
        devCert: answers.devCert,
        publisher: answers.publisher,
        windowsKit: answers.windowsKit,
        makeCertificate: dotfile.get().makeCertificate
      })

      program.desktopConverter = answers.desktopConverter
      program.expandedBaseImage = answers.expandedBaseImage
      program.devCert = answers.devCert
      program.publisher = answers.publisher
      program.windowsKit = answers.windowsKit

      if (program.makeCertificate) {
        utils.log(chalk.bold.green('Creating Certficate'))
        let publisher = dotfile.get().publisher.split('=')[1]
        let certFolder = path.join(process.env.APPDATA, 'electron-windows-store', publisher)

        return sign.makeCert({publisher: publisher, certFolder: certFolder, program: program})
          .then(pfxFile => {
            utils.log('Created and installed certificate:')
            utils.log(pfxFile)
            dotfile.set({devCert: pfxFile})
          })
      }

      utils.log(complete)
    })
}

/**
 * Logs the current configuration to utils
 *
 * @param program - Commander program object
 */
function logConfiguration (program) {
  utils.log(chalk.bold.green.underline('\nConfiguration: '))
  utils.log(`Desktop Converter Location:    ${program.desktopConverter}`)
  utils.log(`Expanded Base Image:           ${program.expandedBaseImage}`)
  utils.log(`Publisher:                     ${program.publisher}`)
  utils.log(`Dev Certificate:               ${program.devCert}`)
  utils.log(`Windows Kit Location:          ${program.windowsKit}
`)
}

/**
 * Runs setup, checking if all configuration is existent,
 * and merging the dotfile with the program object
 *
 * @param program - Commander program object
 * @returns {Promise} - Promsise that returns once setup completed
 */
function setup (program) {
  return new Promise((resolve, reject) => {
    if (isSetupRequired(program)) {
      // If we're setup, merge the dotfile configuration into the program
      defaults(program, dotfile.get())
      logConfiguration(program)
      resolve()
    } else {
      // We're not setup, let's do that now
      askForDependencies(program)
        .then(() => wizardSetup(program))
        .then(() => logConfiguration(program))
        .then(() => resolve())
        .catch((e) => reject(e))
    }
  })
}

module.exports = setup
<commit_msg>Fix: typos in makeCert call<commit_after>'use strict'

/**
 * For setup, we need a number of params:
 *  - DesktopConverter "C:\Tools\DesktopConverter"
 *  - ExpandedBaseImage "C:\ProgramData\Microsoft\Windows\Images\BaseImage-14316\"
 *  - Publisher "CN=testca"
 *  - DevCert "C:\Tools\DesktopConverter\Certs\devcert.pfx"
 */

const path = require('path')
const inquirer = require('inquirer')
const pathExists = require('path-exists')
const defaults = require('lodash.defaults')
const multiline = require('multiline')
const chalk = require('chalk')

const utils = require('./utils')
const sign = require('./sign')
const dotfile = require('./dotfile')()

/**
 * Determines whether all setup settings are okay.
 *
 * @returns {boolean} - Whether everything is setup correctly.
 */
function isSetupRequired (program) {
  const config = dotfile.get() || {}
  const hasPublisher = (config.publisher || program.publisher)
  const hasDevCert = (config.devCert || program.devCert)
  const hasWindowsKit = (config.windowsKit || program.windowsKit)
  const hasBaseImage = (config.expandedBaseImage || program.expandedBaseImage)
  const hasConverterTools = (config.desktopConverter || program.desktopConverter)

  if (!program.containerVirtualization) {
    return (hasPublisher && hasDevCert && hasWindowsKit)
  } else {
    return (hasPublisher && hasDevCert && hasWindowsKit && hasBaseImage && hasConverterTools)
  }
}

/**
 * Asks the user if dependencies are installed. If she/he declines, we exit the process.
 *
 * @param program - Commander program object
 * @returns {Promise} - Promsise that returns once user responded
 */
function askForDependencies (program) {
  if (program.isModuleUse) {
    return Promise.resolve(program)
  }

  const questions = [
    {
      name: 'didInstallDesktopAppConverter',
      type: 'confirm',
      message: 'Did you download and install the Desktop App Converter? It is *not* required to run this tool. '
    },
    {
      name: 'makeCertificate',
      type: 'confirm',
      message: 'You need to install a development certificate in order to run your app. Would you like us to create one? '
    }
  ]

  return inquirer.prompt(questions)
    .then((answers) => {
      program.didInstallDesktopAppConverter = answers.didInstallDesktopAppConverter
      program.makeCertificate = answers.makeCertificate
    })
}

/**
 * Runs a wizard, helping the user setup configuration
 *
 * @param program - Commander program object
 * @returns {Promise} - Promsise that returns once wizard completed
 */
function wizardSetup (program) {
  const welcome = multiline.stripIndent(function () { /*
        Welcome to the Electron-Windows-Store tool!

        This tool will assist you with turning your Electron app into
        a swanky Windows Store app.

        We need to know some settings. We will ask you only once and store
        your answers in your profile folder in a .electron-windows-store
        file.

    */
  })
  const complete = multiline.stripIndent(function () { /*

        Setup complete, moving on to package your app!

    */
  })

  let questions = [
    {
      name: 'desktopConverter',
      type: 'input',
      message: 'Please enter the path to your Desktop App Converter (DesktopAppConverter.ps1): ',
      validate: (input) => pathExists.sync(input),
      when: () => (!program.desktopConverter)
    },
    {
      name: 'expandedBaseImage',
      type: 'input',
      message: 'Please enter the path to your Expanded Base Image: ',
      default: 'C:\\ProgramData\\Microsoft\\Windows\\Images\\BaseImage-14316\\',
      validate: (input) => pathExists.sync(input),
      when: () => (!program.expandedBaseImage)
    },
    {
      name: 'devCert',
      type: 'input',
      message: 'Please enter the path to your development PFX certficate: ',
      default: null,
      when: () => (!dotfile.get().makeCertificate || !program.devCert)
    },
    {
      name: 'publisher',
      type: 'input',
      message: 'Please enter your publisher identity: ',
      default: 'CN=developmentca',
      when: () => (!program.publisher)
    },
    {
      name: 'windowsKit',
      type: 'input',
      message: "Please enter the location of your Windows Kit's bin folder: ",
      default: utils.getDefaultWindowsKitLocation(),
      when: () => (!program.windowsKit)
    }
  ]

  if (!program.isModuleUse) {
    utils.log(welcome)
  }

  // Remove the Desktop Converter Questions if not installed
  if (program.didInstallDesktopAppConverter === false) {
    questions = questions.slice(3)
  }

  if (program.isModuleUse) {
    program.windowsKit = program.windowsKit || utils.getDefaultWindowsKitLocation()

    return Promise.resolve(program)
  }

  return inquirer.prompt(questions)
    .then((answers) => {
      dotfile.set({
        desktopConverter: answers.desktopConverter || false,
        expandedBaseImage: answers.expandedBaseImage || false,
        devCert: answers.devCert,
        publisher: answers.publisher,
        windowsKit: answers.windowsKit,
        makeCertificate: dotfile.get().makeCertificate
      })

      program.desktopConverter = answers.desktopConverter
      program.expandedBaseImage = answers.expandedBaseImage
      program.devCert = answers.devCert
      program.publisher = answers.publisher
      program.windowsKit = answers.windowsKit

      if (program.makeCertificate) {
        utils.log(chalk.bold.green('Creating Certficate'))
        let publisher = dotfile.get().publisher.split('=')[1]
        let certFolder = path.join(process.env.APPDATA, 'electron-windows-store', publisher)

        return sign.makeCert({publisherName: publisher, certFilePath: certFolder, program: program})
          .then(pfxFile => {
            utils.log('Created and installed certificate:')
            utils.log(pfxFile)
            dotfile.set({devCert: pfxFile})
          })
      }

      utils.log(complete)
    })
}

/**
 * Logs the current configuration to utils
 *
 * @param program - Commander program object
 */
function logConfiguration (program) {
  utils.log(chalk.bold.green.underline('\nConfiguration: '))
  utils.log(`Desktop Converter Location:    ${program.desktopConverter}`)
  utils.log(`Expanded Base Image:           ${program.expandedBaseImage}`)
  utils.log(`Publisher:                     ${program.publisher}`)
  utils.log(`Dev Certificate:               ${program.devCert}`)
  utils.log(`Windows Kit Location:          ${program.windowsKit}
`)
}

/**
 * Runs setup, checking if all configuration is existent,
 * and merging the dotfile with the program object
 *
 * @param program - Commander program object
 * @returns {Promise} - Promsise that returns once setup completed
 */
function setup (program) {
  return new Promise((resolve, reject) => {
    if (isSetupRequired(program)) {
      // If we're setup, merge the dotfile configuration into the program
      defaults(program, dotfile.get())
      logConfiguration(program)
      resolve()
    } else {
      // We're not setup, let's do that now
      askForDependencies(program)
        .then(() => wizardSetup(program))
        .then(() => logConfiguration(program))
        .then(() => resolve())
        .catch((e) => reject(e))
    }
  })
}

module.exports = setup
<|endoftext|>


<commit_before>var fs = require('fs');
var https = require('https');

var version = require('../package.json').version;

exports.isSSL = false;

exports.startServer = function (argv, app, cb) {

    var startCb = function() {
        console.log(('   Drakov ' + version + '     ').bold.inverse, 'Listening on port ' + argv.serverPort.toString().bold.red);
        if (argv.stealthmode) {
            console.log('   STEALTH MODE     '.grey.bold.inverse, 'running silently'.grey);
        }

        if (argv.public) {
            console.log('   PUBLIC MODE     '.grey.bold.inverse, 'running publicly'.grey);
        }

        if (cb) {
          cb();
        }
    };

    var server = null;
    if (argv.sslKeyFile && argv.sslCrtFile) {
        exports.isSSL = true;
        var sslOptions = {
            key: fs.readFileSync(argv.sslKeyFile, 'utf8' ),
            cert: fs.readFileSync(argv.sslCrtFile, 'utf8' ),
            rejectUnauthorized: false
        };
        server = https.createServer(sslOptions, app);
    } else {
        server = app;
    }

    if (argv.public) {
        return server.listen(argv.serverPort, startCb);
    }
    return server.listen(argv.serverPort, 'localhost', startCb);

};
<commit_msg>Fix function drakov.stop dosen’t work<commit_after>var fs = require('fs');
var http = require('http');
var https = require('https');
var httpShutdown = require('http-shutdown');

var version = require('../package.json').version;

exports.isSSL = false;

exports.startServer = function (argv, app, cb) {

    var server = null;

    var startCb = function() {
        console.log(('   Drakov ' + version + '     ').bold.inverse, 'Listening on port ' + argv.serverPort.toString().bold.red);
        if (argv.stealthmode) {
            console.log('   STEALTH MODE     '.grey.bold.inverse, 'running silently'.grey);
        }

        if (argv.public) {
            console.log('   PUBLIC MODE     '.grey.bold.inverse, 'running publicly'.grey);
        }

        if (cb) {
          cb();
        }
    };

    if (argv.sslKeyFile && argv.sslCrtFile) {
        exports.isSSL = true;
        var sslOptions = {
            key: fs.readFileSync(argv.sslKeyFile, 'utf8' ),
            cert: fs.readFileSync(argv.sslCrtFile, 'utf8' ),
            rejectUnauthorized: false
        };
        server = https.createServer(sslOptions, app);
    } else {
        //server = app;
        server = http.createServer(app);
    }

    server = httpShutdown(server);

    if (argv.public) {
        return server.listen(argv.serverPort, startCb);
    }
    return server.listen(argv.serverPort, 'localhost', startCb);

};
<|endoftext|>


<commit_before>import React from 'react';
import { c } from 'ttag';
import PropTypes from 'prop-types';
import { INVOICE_STATE } from 'proton-shared/lib/constants';
import { DropdownActions, useApiWithoutResult, useModal, useNotifications } from 'react-components';
import { getInvoice, getPaymentMethodStatus } from 'proton-shared/lib/api/payments';
import { openTabBlob } from 'proton-shared/lib/helpers/file';
import downloadFile from 'proton-shared/lib/helpers/downloadFile';

import PayInvoiceModal from './PayInvoiceModal';

const InvoiceActions = ({ invoice, fetchInvoices }) => {
    const { request: requestGetInvoice } = useApiWithoutResult(getInvoice);
    const { createNotification } = useNotifications();
    const { isOpen, open, close } = useModal();
    const { request: requestGetPaymentMethodStatus } = useApiWithoutResult(getPaymentMethodStatus);

    const list = [
        {
            text: c('Action').t`View`,
            type: 'button',
            async onClick() {
                const buffer = await requestGetInvoice(invoice.ID);
                const filename = c('Title for PDF file').t`ProtonMail invoice` + ` ${invoice.ID}.pdf`;
                const blob = new Blob([buffer], { type: 'application/pdf' });

                openTabBlob(blob, filename);
            }
        },
        {
            text: c('Action').t`Download`,
            type: 'button',
            async onClick() {
                const buffer = await requestGetInvoice(invoice.ID);
                const filename = c('Title for PDF file').t`ProtonMail invoice` + ` ${invoice.ID}.pdf`;
                const blob = new Blob([buffer], { type: 'application/pdf' });

                downloadFile(blob, filename);
            }
        }
    ];

    if (invoice.State === INVOICE_STATE.UNPAID) {
        list.push({
            text: c('Action').t`Pay`,
            type: 'button',
            async onClick() {
                const { Stripe, Paymentwall } = await requestGetPaymentMethodStatus();
                const canPay = Stripe || Paymentwall;

                if (!canPay) {
                    createNotification({
                        type: 'error',
                        text: c('Error').t`Payments are currently not available, please try again later`
                    });
                }

                open();
            }
        });
    }

    return (
        <>
            <DropdownActions list={list} className="pm-button--small" />
            <PayInvoiceModal invoice={invoice} show={isOpen} onClose={close} fetchInvoices={fetchInvoices} />
        </>
    );
};

InvoiceActions.propTypes = {
    invoice: PropTypes.object.isRequired,
    fetchInvoices: PropTypes.func.isRequired
};

export default InvoiceActions;
<commit_msg>Hotfix PayInvoiceModal instance<commit_after>import React from 'react';
import { c } from 'ttag';
import PropTypes from 'prop-types';
import { INVOICE_STATE } from 'proton-shared/lib/constants';
import { DropdownActions, useApiWithoutResult, useModal, useNotifications } from 'react-components';
import { getInvoice, getPaymentMethodStatus } from 'proton-shared/lib/api/payments';
import { openTabBlob } from 'proton-shared/lib/helpers/file';
import downloadFile from 'proton-shared/lib/helpers/downloadFile';

import PayInvoiceModal from './PayInvoiceModal';

const InvoiceActions = ({ invoice, fetchInvoices }) => {
    const { request: requestGetInvoice } = useApiWithoutResult(getInvoice);
    const { createNotification } = useNotifications();
    const { isOpen, open, close } = useModal();
    const { request: requestGetPaymentMethodStatus } = useApiWithoutResult(getPaymentMethodStatus);

    const list = [
        {
            text: c('Action').t`View`,
            type: 'button',
            async onClick() {
                const buffer = await requestGetInvoice(invoice.ID);
                const filename = c('Title for PDF file').t`ProtonMail invoice` + ` ${invoice.ID}.pdf`;
                const blob = new Blob([buffer], { type: 'application/pdf' });

                openTabBlob(blob, filename);
            }
        },
        {
            text: c('Action').t`Download`,
            type: 'button',
            async onClick() {
                const buffer = await requestGetInvoice(invoice.ID);
                const filename = c('Title for PDF file').t`ProtonMail invoice` + ` ${invoice.ID}.pdf`;
                const blob = new Blob([buffer], { type: 'application/pdf' });

                downloadFile(blob, filename);
            }
        }
    ];

    if (invoice.State === INVOICE_STATE.UNPAID) {
        list.push({
            text: c('Action').t`Pay`,
            type: 'button',
            async onClick() {
                const { Stripe, Paymentwall } = await requestGetPaymentMethodStatus();
                const canPay = Stripe || Paymentwall;

                if (!canPay) {
                    createNotification({
                        type: 'error',
                        text: c('Error').t`Payments are currently not available, please try again later`
                    });
                }

                open();
            }
        });
    }

    return (
        <>
            <DropdownActions list={list} className="pm-button--small" />
            {invoice.State === INVOICE_STATE.UNPAID ? (
                <PayInvoiceModal invoice={invoice} show={isOpen} onClose={close} fetchInvoices={fetchInvoices} />
            ) : null}
        </>
    );
};

InvoiceActions.propTypes = {
    invoice: PropTypes.object.isRequired,
    fetchInvoices: PropTypes.func.isRequired
};

export default InvoiceActions;
<|endoftext|>


<commit_before>'use babel';
'use strict';

const events = require('./maven-events');
const process = require('child_process');
const fs = require('fs');
const xml2js = require('xml2js').Parser({
  explicitArray: false
});

class Maven {
  constructor(pom) {
    this.pom = pom;
  }
}

Maven.prototype.registerEvent = function (eventName, callback) {
  events.on(eventName, callback);
};

Maven.prototype.execCommand = function (eventName, command) {
  var cmd = 'mvn ' + command + ' -f ' + this.pom;
  this.exec(cmd, (error) => {
    if (error) {
      events.emit(eventName + '-failed');
    } else {
      events.emit(eventName);
    }
  });
};

Maven.prototype.clean = function () {
  return this.execCommand('clean', 'clean');
};

Maven.prototype.install = function () {
  return this.execCommand('install', 'install');
};

Maven.prototype.test = function () {
  return this.execCommand('test', 'test');
};

Maven.prototype.effectivePom = function (output) {
  var self = this;
  if (output) {
    var cmd = 'mvn help:effective-pom -f ' + self.pom + ' -Doutput=' + output;
    self.exec(cmd, () => {
      xml2js.parseString(fs.readFileSync(output, 'UTF-8'), (error, result) => {
        if (error) {
          events.emit('effective-pom-failed');
        } else {
          events.emit('effective-pom', result);
        }
      });
    });
  } else {
    console.error('Please provide a file to write effective pom to.');
    events.emit('effective-pom-failed');
  }
};

Maven.prototype.exec = function (cmd, callback) {
  process.exec(cmd, function (error, stdout, stderr) {
    if (error) {
      console.error(`exec error: ${error}`);
    }
    console.debug(`stdout: ${stdout}`);
    console.debug(`stderr: ${stderr}`);
    if (callback) {
      callback(error);
    }
  });
};

module.exports = Maven;
<commit_msg>Updated event names to include pom file path, so events are unique to a single file<commit_after>'use babel';
'use strict';

const events = require('./maven-events');
const process = require('child_process');
const fs = require('fs');
const xml2js = require('xml2js').Parser({
  explicitArray: false
});

class Maven {
  constructor(pom) {
    this.pom = pom;
  }
}

Maven.prototype.registerEvent = function (eventName, callback) {
  events.on(eventName + ':' + this.pom, callback);
};

Maven.prototype.execCommand = function (eventName, command) {
  var cmd = 'mvn ' + command + ' -f ' + this.pom;
  this.exec(cmd, (error) => {
    if (error) {
      events.emit(eventName + '-failed' + ':' + this.pom);
    } else {
      events.emit(eventName + ':' + this.pom);
    }
  });
};

Maven.prototype.clean = function () {
  return this.execCommand('clean', 'clean');
};

Maven.prototype.install = function () {
  return this.execCommand('install', 'install');
};

Maven.prototype.test = function () {
  return this.execCommand('test', 'test');
};

Maven.prototype.effectivePom = function (output) {
  var self = this;
  if (output) {
    var cmd = 'mvn help:effective-pom -f ' + self.pom + ' -Doutput=' + output;
    self.exec(cmd, () => {
      xml2js.parseString(fs.readFileSync(output, 'UTF-8'), (error, result) => {
        if (error) {
          events.emit('effective-pom-failed' + ':' + this.pom);
        } else {
          events.emit('effective-pom' + ':' + this.pom, result);
        }
      });
    });
  } else {
    console.error('Please provide a file to write effective pom to.');
    events.emit('effective-pom-failed');
  }
};

Maven.prototype.exec = function (cmd, callback) {
  process.exec(cmd, function (error, stdout, stderr) {
    if (error) {
      console.error(`exec error: ${error}`);
    }
    console.debug(`stdout: ${stdout}`);
    console.debug(`stderr: ${stderr}`);
    if (callback) {
      callback(error);
    }
  });
};

module.exports = Maven;
<|endoftext|>


<commit_before>import React from 'react';
import { c } from 'ttag';
import PropTypes from 'prop-types';
import { CYCLE } from 'proton-shared/lib/constants';
import { Link } from 'react-router-dom';
import thanksForYourSupportSvg from 'design-system/assets/img/pm-images/love.svg';
import contactYourAdminSvg from 'design-system/assets/img/pm-images/settings.svg';
import upgradeToPaidPlanSvg from 'design-system/assets/img/pm-images/upgrade.svg';
import get20PerscentDiscountSvg from 'design-system/assets/img/pm-images/percent.svg';

const Panel = ({ model }) => {
    return (

{model.title}

{model.text}

                        {model.action ? (
                            <Link className="pm-button pm-button--primary" to={model.link}>
                                {model.action}
                            </Link>
                        ) : (

                        )}

    );
};

Panel.propTypes = {
    model: PropTypes.object.isRequired
};

const PromoteSection = ({ subscription, user }) => {
    const MODELS = {
        member: {
            title: c('Title').t`Need help?`,
            text: c('Info').t`Reach out to your system administrator for further assistance and support`,
            image: contactYourAdminSvg
        },
        free: {
            title: c('Title').t`Upgrade to a paid plan`,
            text: c('Info').t`Get additional storage capacity and more addresses with ProtonMail Plus.`,
            link: '/settings/subscription',
            image: upgradeToPaidPlanSvg,
            action: c('Action').t`Upgrade ProtonMail`
        },
        pay: {
            title: c('Title').t`Thanks for your support`,
            text: c('Info')
                .t`Help us improve our service and get early access to new features by enrolling in our Beta programs.`,
            link: '/settings/apps',
            image: thanksForYourSupportSvg,
            action: c('Action').t`Join`
        },
        payMonthly: {
            title: c('Title').t`Get 20% discount`,
            text: c('Info').t`Pay for both ProtonMail and ProtonVPN and get 20% off your entire subscription.`,
            link: '/settings/subscription',
            image: get20PerscentDiscountSvg,
            action: c('Action').t`Upgrade`
        }
    };

    if (user.isMember) {
        return <Panel model={MODELS.member} />;
    }

    if (user.isPaid) {
        if (subscription.Cycle === CYCLE.MONTHLY) {
            return <Panel model={MODELS.payMonthly} />;
        }

        return <Panel model={MODELS.pay} />;
    }

    return <Panel model={MODELS.free} />;
};

PromoteSection.propTypes = {
    subscription: PropTypes.object.isRequired,
    user: PropTypes.object.isRequired
};

export default PromoteSection;
<commit_msg>Review bundle condition on promote section<commit_after>import React from 'react';
import { c } from 'ttag';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import thanksForYourSupportSvg from 'design-system/assets/img/pm-images/love.svg';
import contactYourAdminSvg from 'design-system/assets/img/pm-images/settings.svg';
import upgradeToPaidPlanSvg from 'design-system/assets/img/pm-images/upgrade.svg';
import get20PerscentDiscountSvg from 'design-system/assets/img/pm-images/percent.svg';

const Panel = ({ model }) => {
    return (

{model.title}

{model.text}

                        {model.action ? (
                            <Link className="pm-button pm-button--primary" to={model.link}>
                                {model.action}
                            </Link>
                        ) : (

                        )}

    );
};

Panel.propTypes = {
    model: PropTypes.object.isRequired
};

const PromoteSection = ({ user }) => {
    const { isPaid, hasPaidMail, hasPaidVpn, isMember } = user;
    const MODELS = {
        member: {
            title: c('Title').t`Need help?`,
            text: c('Info').t`Reach out to your system administrator for further assistance and support`,
            image: contactYourAdminSvg
        },
        free: {
            title: c('Title').t`Upgrade to a paid plan`,
            text: c('Info').t`Get additional storage capacity and more addresses with ProtonMail Plus.`,
            link: '/settings/subscription',
            image: upgradeToPaidPlanSvg,
            action: c('Action').t`Upgrade ProtonMail`
        },
        pay: {
            title: c('Title').t`Thanks for your support`,
            text: c('Info')
                .t`Help us improve our service and get early access to new features by enrolling in our Beta programs.`,
            link: '/settings/apps',
            image: thanksForYourSupportSvg,
            action: c('Action').t`Join`
        },
        payBundle: {
            title: c('Title').t`Get 20% discount`,
            text: c('Info').t`Pay for both ProtonMail and ProtonVPN and get 20% off your entire subscription.`,
            link: '/settings/subscription',
            image: get20PerscentDiscountSvg,
            action: c('Action').t`Upgrade`
        }
    };

    if (isMember) {
        return <Panel model={MODELS.member} />;
    }

    if ((hasPaidMail && !hasPaidVpn) || (!hasPaidMail && hasPaidVpn)) {
        return <Panel model={MODELS.payBundle} />;
    }

    if (isPaid) {
        return <Panel model={MODELS.pay} />;
    }

    return <Panel model={MODELS.free} />;
};

PromoteSection.propTypes = {
    user: PropTypes.object.isRequired
};

export default PromoteSection;
<|endoftext|>


<commit_before>'use babel';
'use strict';

const process = require('child_process');
const fs = require('fs');
const xml2js = require('xml2js').Parser({
	explicitArray: false
});

class Maven {
	constructor(pom) {
		this.pom = pom;
	}
}

Maven.prototype.clean = function () {
	var cmd = 'mvn clean -f ' + this.pom;
	this.exec(cmd);
};

Maven.prototype.install = function () {
	var cmd = 'mvn install -f ' + this.pom;
	this.exec(cmd);
};

Maven.prototype.test = function () {
	var cmd = 'mvn test -f ' + this.pom;
	this.exec(cmd);
};

Maven.prototype.effectivePom = function (output) {
	return new Promise(function (resolve, reject) {
		if (output) {
			var cmd = 'mvn help:effective-pom -f ' + this.pom + ' -Doutput=' + output;
			this.execSync(cmd, () => {
				xml2js.parseString(fs.readFileSync(output, 'UTF-8'), (err, result) => {
					if (err) {
						console.error(err);
						reject(Error(err));
					}
					resolve(result);
				});
			});
		} else {
			reject(Error('Please provide a file to write effective pom to.'));
		}
	});
};

Maven.prototype.exec = function (cmd) {
	process.exec(cmd, function (error, stdout, stderr) {
		if (error) {
			console.error(`exec error: ${error}`);
			return;
		}
		console.debug(`stdout: ${stdout}`);
		console.debug(`stderr: ${stderr}`);
	});
};

Maven.prototype.execSync = function (cmd, callback) {
	process.execSync(cmd);
	return callback();
};

module.exports = Maven;
<commit_msg>Assign this to var self in function effectivePom.  Scope of this in Promise is the promise rather than the class.<commit_after>'use babel';
'use strict';

const process = require('child_process');
const fs = require('fs');
const xml2js = require('xml2js').Parser({
	explicitArray: false
});

class Maven {
	constructor(pom) {
		this.pom = pom;
	}
}

Maven.prototype.clean = function () {
	var cmd = 'mvn clean -f ' + this.pom;
	this.exec(cmd);
};

Maven.prototype.install = function () {
	var cmd = 'mvn install -f ' + this.pom;
	this.exec(cmd);
};

Maven.prototype.test = function () {
	var cmd = 'mvn test -f ' + this.pom;
	this.exec(cmd);
};

Maven.prototype.effectivePom = function (output) {
	var self = this;
	return new Promise(function (resolve, reject) {
		if (output) {
			var cmd = 'mvn help:effective-pom -f ' + self.pom + ' -Doutput=' + output;
			self.execSync(cmd, () => {
				xml2js.parseString(fs.readFileSync(output, 'UTF-8'), (err, result) => {
					if (err) {
						console.error(err);
						reject(Error(err));
					}
					resolve(result);
				});
			});
		} else {
			reject(Error('Please provide a file to write effective pom to.'));
		}
	});
};

Maven.prototype.exec = function (cmd) {
	process.exec(cmd, function (error, stdout, stderr) {
		if (error) {
			console.error(`exec error: ${error}`);
			return;
		}
		console.debug(`stdout: ${stdout}`);
		console.debug(`stderr: ${stderr}`);
	});
};

Maven.prototype.execSync = function (cmd, callback) {
	process.execSync(cmd);
	return callback();
};

module.exports = Maven;
<|endoftext|>