<commit_before>/**
 * Copyright 2017, 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.
 */

'use strict';

async function analyzeLabelsGCS(gcsUri) {
  // [START video_analyze_labels_gcs]
  // Imports the Google Cloud Video Intelligence library
  const video = require('@google-cloud/video-intelligence').v1;

  // Creates a client
  const client = new video.VideoIntelligenceServiceClient();

  /**
   * TODO(developer): Uncomment the following line before running the sample.
   */
  // const gcsUri = 'GCS URI of the video to analyze, e.g. gs://my-bucket/my-video.mp4';

  const request = {
    inputUri: gcsUri,
    features: ['LABEL_DETECTION'],
  };

  // Detects labels in a video
  const [operation] = await client.annotateVideo(request);
  console.log('Waiting for operation to complete...');
  const [operationResult] = await operation.promise();

  // Gets annotations for video
  const annotations = operationResult.annotationResults[0];

  const labels = annotations.segmentLabelAnnotations;
  labels.forEach(label => {
    console.log(`Label ${label.entity.description} occurs at:`);
    label.segments.forEach(segment => {
      const time = segment.segment;
      if (time.startTimeOffset.seconds === undefined) {
        time.startTimeOffset.seconds = 0;
      }
      if (time.startTimeOffset.nanos === undefined) {
        time.startTimeOffset.nanos = 0;
      }
      if (time.endTimeOffset.seconds === undefined) {
        time.endTimeOffset.seconds = 0;
      }
      if (time.endTimeOffset.nanos === undefined) {
        time.endTimeOffset.nanos = 0;
      }
      console.log(
        `\tStart: ${time.startTimeOffset.seconds}` +
          `.${(time.startTimeOffset.nanos / 1e6).toFixed(0)}s`
      );
      console.log(
        `\tEnd: ${time.endTimeOffset.seconds}.` +
          `${(time.endTimeOffset.nanos / 1e6).toFixed(0)}s`
      );
      console.log(`\tConfidence: ${segment.confidence}`);
    });
  });
  // [END video_analyze_labels_gcs]
}

async function analyzeLabelsLocal(path) {
  // [START video_analyze_labels]
  // Imports the Google Cloud Video Intelligence library + Node's fs library
  const video = require('@google-cloud/video-intelligence').v1;
  const fs = require('fs');
  const util = require('util');

  // Creates a client
  const client = new video.VideoIntelligenceServiceClient();

  /**
   * TODO(developer): Uncomment the following line before running the sample.
   */
  // const path = 'Local file to analyze, e.g. ./my-file.mp4';

  // Reads a local video file and converts it to base64
  const readFile = util.promisify(fs.readFile);
  const file = await readFile(path);
  const inputContent = file.toString('base64');

  // Constructs request
  const request = {
    inputContent: inputContent,
    features: ['LABEL_DETECTION'],
  };

  // Detects labels in a video
  const [operation] = await client.annotateVideo(request);
  console.log('Waiting for operation to complete...');
  const [operationResult] = await operation.promise();
  // Gets annotations for video
  const annotations = operationResult.annotationResults[0];

  const labels = annotations.segmentLabelAnnotations;
  labels.forEach(label => {
    console.log(`Label ${label.entity.description} occurs at:`);
    label.segments.forEach(segment => {
      const time = segment.segment;
      if (time.startTimeOffset.seconds === undefined) {
        time.startTimeOffset.seconds = 0;
      }
      if (time.startTimeOffset.nanos === undefined) {
        time.startTimeOffset.nanos = 0;
      }
      if (time.endTimeOffset.seconds === undefined) {
        time.endTimeOffset.seconds = 0;
      }
      if (time.endTimeOffset.nanos === undefined) {
        time.endTimeOffset.nanos = 0;
      }
      console.log(
        `\tStart: ${time.startTimeOffset.seconds}` +
          `.${(time.startTimeOffset.nanos / 1e6).toFixed(0)}s`
      );
      console.log(
        `\tEnd: ${time.endTimeOffset.seconds}.` +
          `${(time.endTimeOffset.nanos / 1e6).toFixed(0)}s`
      );
      console.log(`\tConfidence: ${segment.confidence}`);
    });
  });

  // [END video_analyze_labels]
}

async function analyzeShots(gcsUri) {
  // [START video_analyze_shots]
  // Imports the Google Cloud Video Intelligence library
  const video = require('@google-cloud/video-intelligence').v1;

  // Creates a client
  const client = new video.VideoIntelligenceServiceClient();

  /**
   * TODO(developer): Uncomment the following line before running the sample.
   */
  // const gcsUri = 'GCS URI of file to analyze, e.g. gs://my-bucket/my-video.mp4';

  const request = {
    inputUri: gcsUri,
    features: ['SHOT_CHANGE_DETECTION'],
  };

  // Detects camera shot changes
  const [operation] = await client.annotateVideo(request);
  console.log('Waiting for operation to complete...');
  const [operationResult] = await operation.promise();
  // Gets shot changes
  const shotChanges = operationResult.annotationResults[0].shotAnnotations;
  console.log('Shot changes:');

  if (shotChanges.length === 1) {
    console.log(`The entire video is one shot.`);
  } else {
    shotChanges.forEach((shot, shotIdx) => {
      console.log(`Scene ${shotIdx} occurs from:`);
      if (shot.startTimeOffset === undefined) {
        shot.startTimeOffset = {};
      }
      if (shot.endTimeOffset === undefined) {
        shot.endTimeOffset = {};
      }
      if (shot.startTimeOffset.seconds === undefined) {
        shot.startTimeOffset.seconds = 0;
      }
      if (shot.startTimeOffset.nanos === undefined) {
        shot.startTimeOffset.nanos = 0;
      }
      if (shot.endTimeOffset.seconds === undefined) {
        shot.endTimeOffset.seconds = 0;
      }
      if (shot.endTimeOffset.nanos === undefined) {
        shot.endTimeOffset.nanos = 0;
      }
      console.log(
        `\tStart: ${shot.startTimeOffset.seconds}` +
          `.${(shot.startTimeOffset.nanos / 1e6).toFixed(0)}s`
      );
      console.log(
        `\tEnd: ${shot.endTimeOffset.seconds}.` +
          `${(shot.endTimeOffset.nanos / 1e6).toFixed(0)}s`
      );
    });
  }

  // [END video_analyze_shots]
}

async function analyzeSafeSearch(gcsUri) {
  // [START video_analyze_explicit_content]
  // Imports the Google Cloud Video Intelligence library
  const video = require('@google-cloud/video-intelligence').v1;

  // Creates a client
  const client = new video.VideoIntelligenceServiceClient();

  /**
   * TODO(developer): Uncomment the following line before running the sample.
   */
  // const gcsUri = 'GCS URI of video to analyze, e.g. gs://my-bucket/my-video.mp4';

  const request = {
    inputUri: gcsUri,
    features: ['EXPLICIT_CONTENT_DETECTION'],
  };

  // Human-readable likelihoods
  const likelihoods = [
    'UNKNOWN',
    'VERY_UNLIKELY',
    'UNLIKELY',
    'POSSIBLE',
    'LIKELY',
    'VERY_LIKELY',
  ];

  // Detects unsafe content
  const [opertaion] = await client.annotateVideo(request);
  console.log('Waiting for operation to complete...');
  const [operationResult] = await opertaion.promise();
  // Gets unsafe content
  const explicitContentResults =
    operationResult.annotationResults[0].explicitAnnotation;
  console.log('Explicit annotation results:');
  explicitContentResults.frames.forEach(result => {
    if (result.timeOffset === undefined) {
      result.timeOffset = {};
    }
    if (result.timeOffset.seconds === undefined) {
      result.timeOffset.seconds = 0;
    }
    if (result.timeOffset.nanos === undefined) {
      result.timeOffset.nanos = 0;
    }
    console.log(
      `\tTime: ${result.timeOffset.seconds}` +
        `.${(result.timeOffset.nanos / 1e6).toFixed(0)}s`
    );
    console.log(
      `\t\tPornography liklihood: ${likelihoods[result.pornographyLikelihood]}`
    );
  });
  // [END video_analyze_explicit_content]
}

async function analyzeVideoTranscription(gcsUri) {
  // [START video_speech_transcription_gcs_beta]
  // Imports the Google Cloud Video Intelligence library
  const videoIntelligence = require('@google-cloud/video-intelligence')
    .v1p1beta1;

  // Creates a client
  const client = new videoIntelligence.VideoIntelligenceServiceClient();

  /**
   * TODO(developer): Uncomment the following line before running the sample.
   */
  // const gcsUri = 'GCS URI of video to analyze, e.g. gs://my-bucket/my-video.mp4';

  const videoContext = {
    speechTranscriptionConfig: {
      languageCode: 'en-US',
      enableAutomaticPunctuation2: true,
    },
  };

  const request = {
    inputUri: gcsUri,
    features: ['SPEECH_TRANSCRIPTION'],
    videoContext: videoContext,
  };

  const [operation] = await client.annotateVideo(request);
  console.log('Waiting for operation to complete...');
  const [operationResult] = await operation.promise();
  console.log('Word level information:');
  const alternative =
    operationResult.annotationResults[0].speechTranscriptions[0]
      .alternatives[0];
  alternative.words.forEach(wordInfo => {
    const start_time =
      wordInfo.startTime.seconds + wordInfo.startTime.nanos * 1e-9;
    const end_time = wordInfo.endTime.seconds + wordInfo.endTime.nanos * 1e-9;
    console.log('\t' + start_time + 's - ' + end_time + 's: ' + wordInfo.word);
  });
  console.log('Transcription: ' + alternative.transcript);

  // [END video_speech_transcription_gcs_beta]
}

async function main() {
  require(`yargs`)
    .demand(1)
    .command(
      `shots <gcsUri>`,
      `Analyzes shot angles in a video stored in Google Cloud Storage using the Cloud Video Intelligence API.`,
      {},
      opts => analyzeShots(opts.gcsUri)
    )
    .command(
      `labels-gcs <gcsUri>`,
      `Labels objects in a video stored in Google Cloud Storage using the Cloud Video Intelligence API.`,
      {},
      opts => analyzeLabelsGCS(opts.gcsUri)
    )
    .command(
      `labels-file <filePath>`,
      `Labels objects in a video stored locally using the Cloud Video Intelligence API.`,
      {},
      opts => analyzeLabelsLocal(opts.filePath)
    )
    .command(
      `safe-search <gcsUri>`,
      `Detects explicit content in a video stored in Google Cloud Storage.`,
      {},
      opts => analyzeSafeSearch(opts.gcsUri)
    )
    .command(
      `transcription <gcsUri>`,
      `Extract the video transcription using the Cloud Video Intelligence API.`,
      {},
      opts => analyzeVideoTranscription(opts.gcsUri)
    )
    .example(`node $0 shots gs://demomaker/sushi.mp4`)
    .example(`node $0 labels-gcs gs://demomaker/tomatoes.mp4`)
    .example(`node $0 labels-file cat.mp4`)
    .example(`node $0 safe-search gs://demomaker/tomatoes.mp4`)
    .example(`node $0 transcription gs://demomaker/tomatoes.mp4`)
    .wrap(120)
    .recommendCommands()
    .epilogue(
      `For more information, see https://cloud.google.com/video-intelligence/docs`
    )
    .help()
    .strict().argv;
}

main().catch(console.error);
<commit_msg>chore: update samples to use GA APIs (#153)<commit_after>/**
 * Copyright 2017, 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.
 */

'use strict';

async function analyzeLabelsGCS(gcsUri) {
  // [START video_analyze_labels_gcs]
  // Imports the Google Cloud Video Intelligence library
  const video = require('@google-cloud/video-intelligence').v1;

  // Creates a client
  const client = new video.VideoIntelligenceServiceClient();

  /**
   * TODO(developer): Uncomment the following line before running the sample.
   */
  // const gcsUri = 'GCS URI of the video to analyze, e.g. gs://my-bucket/my-video.mp4';

  const request = {
    inputUri: gcsUri,
    features: ['LABEL_DETECTION'],
  };

  // Detects labels in a video
  const [operation] = await client.annotateVideo(request);
  console.log('Waiting for operation to complete...');
  const [operationResult] = await operation.promise();

  // Gets annotations for video
  const annotations = operationResult.annotationResults[0];

  const labels = annotations.segmentLabelAnnotations;
  labels.forEach(label => {
    console.log(`Label ${label.entity.description} occurs at:`);
    label.segments.forEach(segment => {
      const time = segment.segment;
      if (time.startTimeOffset.seconds === undefined) {
        time.startTimeOffset.seconds = 0;
      }
      if (time.startTimeOffset.nanos === undefined) {
        time.startTimeOffset.nanos = 0;
      }
      if (time.endTimeOffset.seconds === undefined) {
        time.endTimeOffset.seconds = 0;
      }
      if (time.endTimeOffset.nanos === undefined) {
        time.endTimeOffset.nanos = 0;
      }
      console.log(
        `\tStart: ${time.startTimeOffset.seconds}` +
          `.${(time.startTimeOffset.nanos / 1e6).toFixed(0)}s`
      );
      console.log(
        `\tEnd: ${time.endTimeOffset.seconds}.` +
          `${(time.endTimeOffset.nanos / 1e6).toFixed(0)}s`
      );
      console.log(`\tConfidence: ${segment.confidence}`);
    });
  });
  // [END video_analyze_labels_gcs]
}

async function analyzeLabelsLocal(path) {
  // [START video_analyze_labels]
  // Imports the Google Cloud Video Intelligence library + Node's fs library
  const video = require('@google-cloud/video-intelligence').v1;
  const fs = require('fs');
  const util = require('util');

  // Creates a client
  const client = new video.VideoIntelligenceServiceClient();

  /**
   * TODO(developer): Uncomment the following line before running the sample.
   */
  // const path = 'Local file to analyze, e.g. ./my-file.mp4';

  // Reads a local video file and converts it to base64
  const readFile = util.promisify(fs.readFile);
  const file = await readFile(path);
  const inputContent = file.toString('base64');

  // Constructs request
  const request = {
    inputContent: inputContent,
    features: ['LABEL_DETECTION'],
  };

  // Detects labels in a video
  const [operation] = await client.annotateVideo(request);
  console.log('Waiting for operation to complete...');
  const [operationResult] = await operation.promise();
  // Gets annotations for video
  const annotations = operationResult.annotationResults[0];

  const labels = annotations.segmentLabelAnnotations;
  labels.forEach(label => {
    console.log(`Label ${label.entity.description} occurs at:`);
    label.segments.forEach(segment => {
      const time = segment.segment;
      if (time.startTimeOffset.seconds === undefined) {
        time.startTimeOffset.seconds = 0;
      }
      if (time.startTimeOffset.nanos === undefined) {
        time.startTimeOffset.nanos = 0;
      }
      if (time.endTimeOffset.seconds === undefined) {
        time.endTimeOffset.seconds = 0;
      }
      if (time.endTimeOffset.nanos === undefined) {
        time.endTimeOffset.nanos = 0;
      }
      console.log(
        `\tStart: ${time.startTimeOffset.seconds}` +
          `.${(time.startTimeOffset.nanos / 1e6).toFixed(0)}s`
      );
      console.log(
        `\tEnd: ${time.endTimeOffset.seconds}.` +
          `${(time.endTimeOffset.nanos / 1e6).toFixed(0)}s`
      );
      console.log(`\tConfidence: ${segment.confidence}`);
    });
  });

  // [END video_analyze_labels]
}

async function analyzeShots(gcsUri) {
  // [START video_analyze_shots]
  // Imports the Google Cloud Video Intelligence library
  const video = require('@google-cloud/video-intelligence').v1;

  // Creates a client
  const client = new video.VideoIntelligenceServiceClient();

  /**
   * TODO(developer): Uncomment the following line before running the sample.
   */
  // const gcsUri = 'GCS URI of file to analyze, e.g. gs://my-bucket/my-video.mp4';

  const request = {
    inputUri: gcsUri,
    features: ['SHOT_CHANGE_DETECTION'],
  };

  // Detects camera shot changes
  const [operation] = await client.annotateVideo(request);
  console.log('Waiting for operation to complete...');
  const [operationResult] = await operation.promise();
  // Gets shot changes
  const shotChanges = operationResult.annotationResults[0].shotAnnotations;
  console.log('Shot changes:');

  if (shotChanges.length === 1) {
    console.log(`The entire video is one shot.`);
  } else {
    shotChanges.forEach((shot, shotIdx) => {
      console.log(`Scene ${shotIdx} occurs from:`);
      if (shot.startTimeOffset === undefined) {
        shot.startTimeOffset = {};
      }
      if (shot.endTimeOffset === undefined) {
        shot.endTimeOffset = {};
      }
      if (shot.startTimeOffset.seconds === undefined) {
        shot.startTimeOffset.seconds = 0;
      }
      if (shot.startTimeOffset.nanos === undefined) {
        shot.startTimeOffset.nanos = 0;
      }
      if (shot.endTimeOffset.seconds === undefined) {
        shot.endTimeOffset.seconds = 0;
      }
      if (shot.endTimeOffset.nanos === undefined) {
        shot.endTimeOffset.nanos = 0;
      }
      console.log(
        `\tStart: ${shot.startTimeOffset.seconds}` +
          `.${(shot.startTimeOffset.nanos / 1e6).toFixed(0)}s`
      );
      console.log(
        `\tEnd: ${shot.endTimeOffset.seconds}.` +
          `${(shot.endTimeOffset.nanos / 1e6).toFixed(0)}s`
      );
    });
  }

  // [END video_analyze_shots]
}

async function analyzeSafeSearch(gcsUri) {
  // [START video_analyze_explicit_content]
  // Imports the Google Cloud Video Intelligence library
  const video = require('@google-cloud/video-intelligence').v1;

  // Creates a client
  const client = new video.VideoIntelligenceServiceClient();

  /**
   * TODO(developer): Uncomment the following line before running the sample.
   */
  // const gcsUri = 'GCS URI of video to analyze, e.g. gs://my-bucket/my-video.mp4';

  const request = {
    inputUri: gcsUri,
    features: ['EXPLICIT_CONTENT_DETECTION'],
  };

  // Human-readable likelihoods
  const likelihoods = [
    'UNKNOWN',
    'VERY_UNLIKELY',
    'UNLIKELY',
    'POSSIBLE',
    'LIKELY',
    'VERY_LIKELY',
  ];

  // Detects unsafe content
  const [opertaion] = await client.annotateVideo(request);
  console.log('Waiting for operation to complete...');
  const [operationResult] = await opertaion.promise();
  // Gets unsafe content
  const explicitContentResults =
    operationResult.annotationResults[0].explicitAnnotation;
  console.log('Explicit annotation results:');
  explicitContentResults.frames.forEach(result => {
    if (result.timeOffset === undefined) {
      result.timeOffset = {};
    }
    if (result.timeOffset.seconds === undefined) {
      result.timeOffset.seconds = 0;
    }
    if (result.timeOffset.nanos === undefined) {
      result.timeOffset.nanos = 0;
    }
    console.log(
      `\tTime: ${result.timeOffset.seconds}` +
        `.${(result.timeOffset.nanos / 1e6).toFixed(0)}s`
    );
    console.log(
      `\t\tPornography liklihood: ${likelihoods[result.pornographyLikelihood]}`
    );
  });
  // [END video_analyze_explicit_content]
}

async function analyzeVideoTranscription(gcsUri) {
  // [START video_speech_transcription_gcs]
  // Imports the Google Cloud Video Intelligence library
  const videoIntelligence = require('@google-cloud/video-intelligence');

  // Creates a client
  const client = new videoIntelligence.VideoIntelligenceServiceClient();

  /**
   * TODO(developer): Uncomment the following line before running the sample.
   */
  // const gcsUri = 'GCS URI of video to analyze, e.g. gs://my-bucket/my-video.mp4';

  const videoContext = {
    speechTranscriptionConfig: {
      languageCode: 'en-US',
      enableAutomaticPunctuation2: true,
    },
  };

  const request = {
    inputUri: gcsUri,
    features: ['SPEECH_TRANSCRIPTION'],
    videoContext: videoContext,
  };

  const [operation] = await client.annotateVideo(request);
  console.log('Waiting for operation to complete...');
  const [operationResult] = await operation.promise();
  console.log('Word level information:');
  const alternative =
    operationResult.annotationResults[0].speechTranscriptions[0]
      .alternatives[0];
  alternative.words.forEach(wordInfo => {
    const start_time =
      wordInfo.startTime.seconds + wordInfo.startTime.nanos * 1e-9;
    const end_time = wordInfo.endTime.seconds + wordInfo.endTime.nanos * 1e-9;
    console.log('\t' + start_time + 's - ' + end_time + 's: ' + wordInfo.word);
  });
  console.log('Transcription: ' + alternative.transcript);

  // [END video_speech_transcription_gcs]
}

async function main() {
  require(`yargs`)
    .demand(1)
    .command(
      `shots <gcsUri>`,
      `Analyzes shot angles in a video stored in Google Cloud Storage using the Cloud Video Intelligence API.`,
      {},
      opts => analyzeShots(opts.gcsUri)
    )
    .command(
      `labels-gcs <gcsUri>`,
      `Labels objects in a video stored in Google Cloud Storage using the Cloud Video Intelligence API.`,
      {},
      opts => analyzeLabelsGCS(opts.gcsUri)
    )
    .command(
      `labels-file <filePath>`,
      `Labels objects in a video stored locally using the Cloud Video Intelligence API.`,
      {},
      opts => analyzeLabelsLocal(opts.filePath)
    )
    .command(
      `safe-search <gcsUri>`,
      `Detects explicit content in a video stored in Google Cloud Storage.`,
      {},
      opts => analyzeSafeSearch(opts.gcsUri)
    )
    .command(
      `transcription <gcsUri>`,
      `Extract the video transcription using the Cloud Video Intelligence API.`,
      {},
      opts => analyzeVideoTranscription(opts.gcsUri)
    )
    .example(`node $0 shots gs://demomaker/sushi.mp4`)
    .example(`node $0 labels-gcs gs://demomaker/tomatoes.mp4`)
    .example(`node $0 labels-file cat.mp4`)
    .example(`node $0 safe-search gs://demomaker/tomatoes.mp4`)
    .example(`node $0 transcription gs://demomaker/tomatoes.mp4`)
    .wrap(120)
    .recommendCommands()
    .epilogue(
      `For more information, see https://cloud.google.com/video-intelligence/docs`
    )
    .help()
    .strict().argv;
}

main().catch(console.error);
<|endoftext|>


<commit_before>/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/

'use strict';

/**
* Returns an accumulator function which incrementally computes an arithmetic mean.
*
* ## Method
*
* -   This implementation uses [Welford's method][algorithms-variance] for efficient computation, which can be derived as follows
*
*     ```tex
*     \begin{align*}
*     \mu_n &= \frac{1}{n} \sum_{i=0}^{n-1} x_i \\
*           &= \frac{1}{n} \biggl(x_{n-1} + \sum_{i=0}^{n-2} x_i \biggr) \\
*           &= \frac{1}{n} (x_{n-1} + (n-1)\mu_{n-1}) \\
*           &= \mu_{n-1} + \frac{1}{n} (x_{n-1} - \mu_{n-1})
*     \end{align*}
*     ```
*
* [algorithms-variance]: https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
*
* @returns {Function} accumulator function
*
* @example
* var accumulator = incrmean();
*
* var mu = accumulator();
* // returns null
*
* mu = accumulator( 2.0 );
* // returns 2.0
*
* mu = accumulator( -5.0 );
* // returns -1.5
*
* mu = accumulator();
* // returns -1.5
*/
function incrmean() {
	var delta;
	var mu;
	var N;

	mu = 0.0;
	N = 0;

	return accumulator;

	/**
	* If provided a value, the accumulator function returns an updated mean. If not provided a value, the accumulator function returns the current mean.
	*
	* @private
	* @param {number} [x] - new value
	* @returns {(number|null)} mean value or null
	*/
	function accumulator( x ) {
		if ( arguments.length === 0 ) {
			if ( N === 0 ) {
				return null;
			}
			return mu;
		}
		N += 1;
		delta = x - mu;
		mu += delta / N;
		return mu;
	}
}

// EXPORTS //

module.exports = incrmean;
<commit_msg>Remove use of intermediate variable<commit_after>/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/

'use strict';

/**
* Returns an accumulator function which incrementally computes an arithmetic mean.
*
* ## Method
*
* -   This implementation uses [Welford's method][algorithms-variance] for efficient computation, which can be derived as follows
*
*     ```tex
*     \begin{align*}
*     \mu_n &= \frac{1}{n} \sum_{i=0}^{n-1} x_i \\
*           &= \frac{1}{n} \biggl(x_{n-1} + \sum_{i=0}^{n-2} x_i \biggr) \\
*           &= \frac{1}{n} (x_{n-1} + (n-1)\mu_{n-1}) \\
*           &= \mu_{n-1} + \frac{1}{n} (x_{n-1} - \mu_{n-1})
*     \end{align*}
*     ```
*
* [algorithms-variance]: https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
*
* @returns {Function} accumulator function
*
* @example
* var accumulator = incrmean();
*
* var mu = accumulator();
* // returns null
*
* mu = accumulator( 2.0 );
* // returns 2.0
*
* mu = accumulator( -5.0 );
* // returns -1.5
*
* mu = accumulator();
* // returns -1.5
*/
function incrmean() {
	var mu;
	var N;

	mu = 0.0;
	N = 0;

	return accumulator;

	/**
	* If provided a value, the accumulator function returns an updated mean. If not provided a value, the accumulator function returns the current mean.
	*
	* @private
	* @param {number} [x] - new value
	* @returns {(number|null)} mean value or null
	*/
	function accumulator( x ) {
		if ( arguments.length === 0 ) {
			if ( N === 0 ) {
				return null;
			}
			return mu;
		}
		N += 1;
		mu += (x-mu) / N;
		return mu;
	}
}

// EXPORTS //

module.exports = incrmean;
<|endoftext|>


<commit_before>// Command-line arguments passed to npm when rebuilding binary packages.
var args = [
  "rebuild",

  // The --no-bin-links flag tells npm not to create symlinks in the
  // node_modules/.bin/ directory when rebuilding packages, which helps
  // avoid problems like https://github.com/meteor/meteor/issues/7401.
  "--no-bin-links",

  // The --update-binary flag tells node-pre-gyp to replace previously
  // installed local binaries with remote binaries:
  // https://github.com/mapbox/node-pre-gyp#options
  "--update-binary"
];

exports.get = function () {
  // Make a defensive copy.
  return args.slice(0);
};
<commit_msg>Support additional `meteor rebuild` flags via environment variable.<commit_after>// Command-line arguments passed to npm when rebuilding binary packages.
var args = [
  "rebuild",

  // The --no-bin-links flag tells npm not to create symlinks in the
  // node_modules/.bin/ directory when rebuilding packages, which helps
  // avoid problems like https://github.com/meteor/meteor/issues/7401.
  "--no-bin-links",

  // The --update-binary flag tells node-pre-gyp to replace previously
  // installed local binaries with remote binaries:
  // https://github.com/mapbox/node-pre-gyp#options
  "--update-binary"
];

// Allow additional flags to be passed via the $METEOR_NPM_REBUILD_FLAGS
// environment variable.
var flags = process.env.METEOR_NPM_REBUILD_FLAGS;
if (flags) {
  args.push.apply(args, flags.split(/\s+/g));
}

exports.get = function () {
  // Make a defensive copy.
  return args.slice(0);
};
<|endoftext|>


<commit_before>/*
Copyright 2009 University of Toronto

Licensed under the Educational Community License (ECL), Version 2.0.
ou may not use this file except in compliance with this License.

You may obtain a copy of the ECL 2.0 License at
https://source.collectionspace.org/collection-space/LICENSE.txt
*/

/*global jQuery, fluid_1_1*/

var cspace = cspace || {};

(function ($, fluid) {

    // Ultimately, the UISpec will be loaded via JSONP (see CSPACE-300). Until then,
    // load it manually via ajax
    var fetchUISpec = function (that, callback) {
        jQuery.ajax({
            url: that.options.uiSpecUrl,
            type: "GET",
            dataType: "json",
            success: callback,
            error: function (xhr, textStatus, errorThrown) {
                that.showSpecErrorMessage(that.options.strings.specFetchError + textStatus + that.options.strings.errorRecoverySuggestion);
                that.locate("messageContainer").hide();
                that.events.onError.fire("fetch UISpec");
            }
        });
    };

    displayTimestampedMessage = function (that, msg, time) {
        that.locate("feedbackMessage").text(msg);
        that.locate("timestamp").text(time);
        that.locate("messageContainer").show();

    };

    fetchAutoGeneratedNumber = function (that, callback) {
        jQuery.ajax({
            url: that.dataContext.urlFactory.urlForModelPath("*", {csid: "__auto"}),
            type: "GET",
            dataType: "json",
            success: callback,
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                that.refreshView();
            }
        });
    };

    var buildEmptyModelFromSpec = function (spec) {
        var model = {};
        for (var key in spec) {
            if (spec.hasOwnProperty(key)) {
                model[key] = (spec[key].hasOwnProperty("repeated") ? [""] : "");
            }
        }
        return model;
    };

    var makeDCErrorHandler = function (that) {
        return function(operation/*["create", "delete", "fetch", "update"]*/, modelPath, message){
            var msgKey = operation + "FailedMessage";
            var msg = that.options.strings[msgKey] + message;
            displayTimestampedMessage(that, msg, "");
            that.events.onError.fire(operation);
            if (operation === "create") {
                // This is only temporary until http://issues.collectionspace.org/browse/CSPACE-263
                // is resolved
                that.options.csid = undefined;
                that.model.csid = undefined;
            }
        };
    };

    var setupDataContext = function (that) {
        return function(spec, textStatus){
            that.spec = spec.spec;

            // insert the resourceMapper options retrieved with the UISpec into the options structure
            that.options.dataContext.options = that.options.dataContext.options || {};
            that.options.dataContext.options.modelToResourceMap = spec.modelToResourceMap;
            that.options.dataContext.options.replacements = spec.replacements;

            that.dataContext = fluid.initSubcomponent(that, "dataContext", [that.model, fluid.COMPONENT_OPTIONS]);

            bindEventHandlers(that);

            fluid.model.copyModel(that.model, buildEmptyModelFromSpec(that.spec));
            var queryParams = {};
            if (that.options.csid) {
                queryParams[that.options.idField] = that.options.csid;
                that.dataContext.fetch("*", queryParams);
            }
            else if (that.options.autoGenNumField) {
                fetchAutoGeneratedNumber(that, function (data, textStatus) {
                        that.model[that.options.autoGenNumField] = data[that.options.autoGenNumField];
                        that.refreshView();
                    }
                );
            }
            else {
                that.refreshView();
            }
        };
    };

    var bindEventHandlers = function (that) {
        that.dataContext.events.modelChanged.addListener(function (newModel, oldModel, source) {
            that.events.modelChanged.fire(newModel, oldModel, source);
            that.refreshView();
            that.locate("messageContainer").hide();
        });

        that.dataContext.events.afterCreate.addListener(function (modelPath, data) {
            that.events.afterCreateObjectDataSuccess.fire(data, that.options.strings.createSuccessfulMessage);
			displayTimestampedMessage(that, that.options.strings.createSuccessfulMessage, Date());
            that.options.csid = data.csid;
        });

        that.dataContext.events.afterUpdate.addListener(function (modelPath, data) {
            that.events.afterUpdateObjectDataSuccess.fire(data, that.options.strings.updateSuccessfulMessage);
			displayTimestampedMessage(that, that.options.strings.updateSuccessfulMessage, Date());
        });

        that.dataContext.events.onError.addListener(makeDCErrorHandler(that));
    };

    var setupDataEntry = function (that) {
        fetchUISpec(that, setupDataContext(that));
    };

    /**
     * Object Entry component
     */
    cspace.dataEntry = function (container, options) {
        var that = fluid.initView("cspace.dataEntry", container, options);
        that.model = {};
        that.spec = {};

        that.refreshView = function () {
            cspace.renderer.renderPage(that);
        };

        that.updateModel = function (newModel, source) {
            that.events.modelChanged.fire(newModel, that.model, source);
            fluid.clear(that.model);
            fluid.model.copyModel(that.model, newModel);
            that.refreshView();
        };

        that.showSpecErrorMessage = function (msg) {
            that.locate("errorMessage", "body").text(msg);
            that.locate("errorDialog", "body").dialog({
                modal: true,
                dialogClass: "fl-widget"
            });
        };

        that.save = function () {
            that.events.onSave.fire(that.model);
            if (that.options.csid) {
                that.dataContext.update("*");
            } else {
                that.model[that.options.idField] = cspace.util.newID(that.model, that.options.idField, that.options.alternateFields);    // temporary, till server returns ID
                that.dataContext.create("*");
            }
            return false;
        };

        setupDataEntry(that);
        return that;
    };

    cspace.saveId = "save";

    fluid.defaults("cspace.dataEntry", {
        dataContext: {
            type: "cspace.resourceMapperDataContext"
        },
        events: {
            modelChanged: null,
			onSave: null,
            afterCreateObjectDataSuccess: null,  // params: data, textStatus
            afterUpdateObjectDataSuccess: null,  // params: data, textStatus
            onError: null,  // params: operation
            pageRendered: null
        },
        selectors: {
            errorDialog: ".csc-error-dialog",
            errorMessage: ".csc-error-message",
            save: ".csc-save",
            saveSecondary: ".csc-save-bottom",
            messageContainer: ".csc-message-container",
            feedbackMessage: ".csc-message",
            timestamp: ".csc-timestamp"
        },
        strings: {
            specFetchError: "I'm sorry, an error has occurred fetching the UISpec: ",
            errorRecoverySuggestion: "Please try refreshing your browser",
            updateSuccessfulMessage: "Object Record successfully saved",
            createSuccessfulMessage: "New Object Record successfully created",
            updateFailedMessage: "Error saving Record: ",
            createFailedMessage: "Error creating Record: ",
            deleteFailedMessage: "Error deleting Record: ",
            fetchFailedMessage: "Error retriving Record: ",
            defaultTermIndicator: " (default)",
            noDefaultInvitation: "-- Select an item from the list --"
        },
        templates: {
            header: {
                url: "../html/header.html",
                id: "name-header"
            },
            body: {
                url: "../html/ObjectEntryTemplate.html",
                id: "csc-object-entry-template"
            },
            rightSidebar:  {
                url: "../html/right-sidebar.html",
                id: "csc-right-sidebar"
            },
            footer: {
                url: "../html/footer.html",
                id: "footer"
            }
        },
        csid: null,
        idField: "csid",
        alternateFields: [],

        autoGenNumField: null,

        // Ultimately, the UISpec will be loaded via JSONP (see CSPACE-300). Until then,
        // load it manually via ajax
        uiSpecUrl: "./schemas/collection-object/schema.json"

    });
})(jQuery, fluid_1_1);
<commit_msg>CSPACE-469: Use a ChangeApplier.<commit_after>/*
Copyright 2009 University of Toronto

Licensed under the Educational Community License (ECL), Version 2.0.
ou may not use this file except in compliance with this License.

You may obtain a copy of the ECL 2.0 License at
https://source.collectionspace.org/collection-space/LICENSE.txt
*/

/*global jQuery, fluid_1_1*/

var cspace = cspace || {};

(function ($, fluid) {

    // Ultimately, the UISpec will be loaded via JSONP (see CSPACE-300). Until then,
    // load it manually via ajax
    var fetchUISpec = function (that, callback) {
        jQuery.ajax({
            url: that.options.uiSpecUrl,
            type: "GET",
            dataType: "json",
            success: callback,
            error: function (xhr, textStatus, errorThrown) {
                that.showSpecErrorMessage(that.options.strings.specFetchError + textStatus + that.options.strings.errorRecoverySuggestion);
                that.locate("messageContainer").hide();
                that.events.onError.fire("fetch UISpec");
            }
        });
    };

    displayTimestampedMessage = function (that, msg, time) {
        that.locate("feedbackMessage").text(msg);
        that.locate("timestamp").text(time);
        that.locate("messageContainer").show();

    };

    fetchAutoGeneratedNumber = function (that, callback) {
        jQuery.ajax({
            url: that.dataContext.urlFactory.urlForModelPath("*", {csid: "__auto"}),
            type: "GET",
            dataType: "json",
            success: callback,
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                that.refreshView();
            }
        });
    };

    var buildEmptyModelFromSpec = function (spec) {
        var model = {};
        for (var key in spec) {
            if (spec.hasOwnProperty(key)) {
                model[key] = (spec[key].hasOwnProperty("repeated") ? [""] : "");
            }
        }
        return model;
    };

    var makeDCErrorHandler = function (that) {
        return function(operation/*["create", "delete", "fetch", "update"]*/, modelPath, message){
            var msgKey = operation + "FailedMessage";
            var msg = that.options.strings[msgKey] + message;
            displayTimestampedMessage(that, msg, "");
            that.events.onError.fire(operation);
            if (operation === "create") {
                // This is only temporary until http://issues.collectionspace.org/browse/CSPACE-263
                // is resolved
                that.options.csid = undefined;
                that.applier.requestChange("csid", undefined);
            }
        };
    };

    var bindEventHandlers = function (that) {

        that.dataContext.events.afterCreate.addListener(function (modelPath, data) {
            that.events.afterCreateObjectDataSuccess.fire(data, that.options.strings.createSuccessfulMessage);
			displayTimestampedMessage(that, that.options.strings.createSuccessfulMessage, Date());
            that.options.csid = data.csid;
        });

        that.dataContext.events.afterUpdate.addListener(function (modelPath, data) {
            that.events.afterUpdateObjectDataSuccess.fire(data, that.options.strings.updateSuccessfulMessage);
			displayTimestampedMessage(that, that.options.strings.updateSuccessfulMessage, Date());
        });

        that.dataContext.events.afterFetch.addListener(function (modelPath, data) {
            that.applier = fluid.makeChangeApplier(that.model);
            that.refreshView();
        });
        that.dataContext.events.onError.addListener(makeDCErrorHandler(that));
    };

    var setupDataContext = function (that) {
        return function(spec, textStatus){
            that.spec = spec.spec;

            // insert the resourceMapper options retrieved with the UISpec into the options structure
            that.options.dataContext.options = that.options.dataContext.options || {};
            that.options.dataContext.options.modelToResourceMap = spec.modelToResourceMap;
            that.options.dataContext.options.replacements = spec.replacements;

            that.dataContext = fluid.initSubcomponent(that, "dataContext", [that.model, fluid.COMPONENT_OPTIONS]);

            bindEventHandlers(that);

            fluid.model.copyModel(that.model, buildEmptyModelFromSpec(that.spec));
            var queryParams = {};
            if (that.options.csid) {
                queryParams[that.options.idField] = that.options.csid;
                that.dataContext.fetch("*", queryParams);
            }
            else if (that.options.autoGenNumField) {
                fetchAutoGeneratedNumber(that, function (data, textStatus) {
                    that.model[that.options.autoGenNumField] = data[that.options.autoGenNumField];
                    that.applier = fluid.makeChangeApplier(that.model);
                    that.refreshView();
                });
            }
            else {
                that.refreshView();
            }
        };
    };

    var setupDataEntry = function (that) {
        fetchUISpec(that, setupDataContext(that));
    };

    /**
     * Object Entry component
     */
    cspace.dataEntry = function (container, options) {
        var that = fluid.initView("cspace.dataEntry", container, options);
        that.model = {};
        that.spec = {};

        that.refreshView = function () {
            cspace.renderer.renderPage(that);
        };

        that.showSpecErrorMessage = function (msg) {
            that.locate("errorMessage", "body").text(msg);
            that.locate("errorDialog", "body").dialog({
                modal: true,
                dialogClass: "fl-widget"
            });
        };

        that.save = function () {
            that.events.onSave.fire(that.model);
            if (that.options.csid) {
                that.dataContext.update("*");
            } else {
                that.applier.requestChange(that.options.idField, cspace.util.newID(that.model, that.options.idField, that.options.alternateFields));
                that.dataContext.create("*");
            }
            return false;
        };

        setupDataEntry(that);
        return that;
    };

    cspace.saveId = "save";

    fluid.defaults("cspace.dataEntry", {
        dataContext: {
            type: "cspace.resourceMapperDataContext"
        },
        events: {
			onSave: null,
            afterCreateObjectDataSuccess: null,  // params: data, textStatus
            afterUpdateObjectDataSuccess: null,  // params: data, textStatus
            onError: null,  // params: operation
            pageRendered: null
        },
        selectors: {
            errorDialog: ".csc-error-dialog",
            errorMessage: ".csc-error-message",
            save: ".csc-save",
            saveSecondary: ".csc-save-bottom",
            messageContainer: ".csc-message-container",
            feedbackMessage: ".csc-message",
            timestamp: ".csc-timestamp"
        },
        strings: {
            specFetchError: "I'm sorry, an error has occurred fetching the UISpec: ",
            errorRecoverySuggestion: "Please try refreshing your browser",
            updateSuccessfulMessage: "Object Record successfully saved",
            createSuccessfulMessage: "New Object Record successfully created",
            updateFailedMessage: "Error saving Record: ",
            createFailedMessage: "Error creating Record: ",
            deleteFailedMessage: "Error deleting Record: ",
            fetchFailedMessage: "Error retriving Record: ",
            defaultTermIndicator: " (default)",
            noDefaultInvitation: "-- Select an item from the list --"
        },
        templates: {
            header: {
                url: "../html/header.html",
                id: "name-header"
            },
            body: {
                url: "../html/ObjectEntryTemplate.html",
                id: "csc-object-entry-template"
            },
            rightSidebar:  {
                url: "../html/right-sidebar.html",
                id: "csc-right-sidebar"
            },
            footer: {
                url: "../html/footer.html",
                id: "footer"
            }
        },
        csid: null,
        idField: "csid",
        alternateFields: [],

        autoGenNumField: null,

        // Ultimately, the UISpec will be loaded via JSONP (see CSPACE-300). Until then,
        // load it manually via ajax
        uiSpecUrl: "./schemas/collection-object/schema.json"

    });
})(jQuery, fluid_1_1);
<|endoftext|>


<commit_before>/*
 *
 * (c) Copyright Ascensio System SIA 2010-2019
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha
 * street, Riga, Latvia, EU, LV-1050.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
*/
/**
 * User: Julia.Radzhabova
 * Date: 30.07.19
 */

define([
    'core',
    'spreadsheeteditor/main/app/view/Spellcheck'
], function () {
    'use strict';

    SSE.Controllers.Spellcheck = Backbone.Controller.extend(_.extend({
        models: [],
        collections: [
        ],
        views: [
            'Spellcheck'
        ],

        initialize: function() {
            var me = this;
            this.addListeners({
                'Spellcheck': {
                    'show': function() {
                        me.loadLanguages();
                    },
                    'hide': function() {
                    }
                }
            });
        },

        events: function() {
        },

        onLaunch: function() {
            this.panelSpellcheck= this.createView('Spellcheck', {
            });
            this.panelSpellcheck.on('render:after', _.bind(this.onAfterRender, this));
            this._isDisabled = false;
        },

        setApi: function(api) {
            this.api = api;
            this.api.asc_registerCallback('asc_onSpellCheckVariantsFound', _.bind(this.onSpellCheckVariantsFound, this));
            return this;
        },

        setMode: function(mode) {
            this.mode = mode;
            if (this.panelSpellcheck) {
                this.panelSpellcheck.btnToDictionary.setVisible(mode.isDesktopApp);
            }
            return this;
        },

        onAfterRender: function(panelSpellcheck) {
            panelSpellcheck.buttonNext.on('click', _.bind(this.onClickNext, this));
            panelSpellcheck.btnToDictionary.on('click', _.bind(this.onDictionary, this));
            panelSpellcheck.cmbDictionaryLanguage.on('selected', _.bind(this.onSelectLanguage, this));
            panelSpellcheck.btnChange.on('click', _.bind(this.onClickChange, this));
            panelSpellcheck.btnIgnore.on('click', _.bind(this.onClickIgnore, this));
            panelSpellcheck.btnChange.menu.on('item:click', _.bind(this.onClickChangeMenu, this));
            panelSpellcheck.btnIgnore.menu.on('item:click', _.bind(this.onClickIgnoreMenu, this));
        },

        onClickNext: function() {
            if (this.api) {
                this.api.asc_nextWord();
            }
        },

        onDictionary: function() {
            if (this.api) {
                var rec = this.panelSpellcheck.suggestionList.getSelectedRec();
                rec && this.api.asc_AddToDictionary(rec.get('value'));
            }
        },

        SetDisabled: function(state) {
            this._isDisabled = state;
        },

        setLanguages: function (array) {
            this.languages = array;
        },

        loadLanguages: function () {
            if (this.languages && this.languages.length>0) {
                var langs = [], info,
                    allLangs = Common.util.LanguageInfo.getLanguages();
                this.languages.forEach(function (code) {
                    if (allLangs.hasOwnProperty(parseInt(code))) {
                        info = allLangs[parseInt(code)];
                        langs.push({
                            displayValue:   info[1],
                            value:          info[0],
                            code:           parseInt(code)
                        });
                    }
                });
                this.panelSpellcheck.cmbDictionaryLanguage.setData(langs);
                /*var codeCurLang = this.api.asc_getDefaultLanguage();*/
                var codeCurLang = 1036;
                var curLang = allLangs[codeCurLang][0];
                this.panelSpellcheck.cmbDictionaryLanguage.setValue(curLang);
            } else
                this.panelSpellcheck.cmbDictionaryLanguage.setDisabled(true);
        },

        onSelectLanguage: function (combo, record) {
            var lang = record.code;
            if (this.api && lang) {
                /*this.api.asc_setDefaultLanguage(lang);*/
            }
        },

        onClickChange: function (btn, e) {
            if (this.api) {
                /*this.api.asc_change();*/
            }
        },

        onClickChangeMenu: function (menu, item) {
            /*if (this.api) {
                if (item.value == 0) {
                    this.api.asc_change();
                } else if (item.value == 1) {
                    this.api.asc_changeAll();
                }
            }*/
        },

        onClickIgnore: function () {
            if (this.api) {
                /*this.api.asc_ignore();*/
            }
        },

        onClickIgnoreMenu: function () {
            /*if (this.api) {
                if (item.value == 0) {
                    this.api.asc_ignore();
                } else if (item.value == 1) {
                    this.api.asc_ignoreAll();
                }
            }*/
        },

        onSpellCheckVariantsFound: function (property) {
            var word = property.get_Word();
            this.panelSpellcheck.currentWord.setValue(word);

            var variants = property.get_Variants(),
                arr = [];
            variants.forEach(function (item) {
                var rec = new Common.UI.DataViewModel();
                rec.set({
                    value: item
                });
                arr.push(rec);
            });
            this.panelSpellcheck.suggestionList.store.reset(arr);
        }

    }, SSE.Controllers.Spellcheck || {}));
});
<commit_msg>[SSE] Apply spellcheck<commit_after>/*
 *
 * (c) Copyright Ascensio System SIA 2010-2019
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha
 * street, Riga, Latvia, EU, LV-1050.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
*/
/**
 * User: Julia.Radzhabova
 * Date: 30.07.19
 */

define([
    'core',
    'spreadsheeteditor/main/app/view/Spellcheck'
], function () {
    'use strict';

    SSE.Controllers.Spellcheck = Backbone.Controller.extend(_.extend({
        models: [],
        collections: [
        ],
        views: [
            'Spellcheck'
        ],

        initialize: function() {
            var me = this;
            this.addListeners({
                'Spellcheck': {
                    'show': function() {
                        me.loadLanguages();
                    },
                    'hide': function() {
                    }
                }
            });
        },

        events: function() {
        },

        onLaunch: function() {
            this.panelSpellcheck= this.createView('Spellcheck', {
            });
            this.panelSpellcheck.on('render:after', _.bind(this.onAfterRender, this));
            this._isDisabled = false;
        },

        setApi: function(api) {
            this.api = api;
            this.api.asc_registerCallback('asc_onSpellCheckVariantsFound', _.bind(this.onSpellCheckVariantsFound, this));
            return this;
        },

        setMode: function(mode) {
            this.mode = mode;
            if (this.panelSpellcheck) {
                this.panelSpellcheck.btnToDictionary.setVisible(mode.isDesktopApp);
            }
            return this;
        },

        onAfterRender: function(panelSpellcheck) {
            panelSpellcheck.buttonNext.on('click', _.bind(this.onClickNext, this));
            panelSpellcheck.btnToDictionary.on('click', _.bind(this.onDictionary, this));
            panelSpellcheck.cmbDictionaryLanguage.on('selected', _.bind(this.onSelectLanguage, this));
            panelSpellcheck.btnChange.on('click', _.bind(this.onClickChange, this));
            panelSpellcheck.btnIgnore.on('click', _.bind(this.onClickIgnore, this));
            panelSpellcheck.btnChange.menu.on('item:click', _.bind(this.onClickChangeMenu, this));
            panelSpellcheck.btnIgnore.menu.on('item:click', _.bind(this.onClickIgnoreMenu, this));
        },

        onClickNext: function() {
            if (this.api) {
                this.api.asc_nextWord();
            }
        },

        onDictionary: function() {
            if (this.api) {
                var rec = this.panelSpellcheck.suggestionList.getSelectedRec();
                rec && this.api.asc_AddToDictionary(rec.get('value'));
            }
        },

        SetDisabled: function(state) {
            this._isDisabled = state;
        },

        setLanguages: function (array) {
            this.languages = array;
        },

        loadLanguages: function () {
            var value = Common.localStorage.getItem("sse-spellcheck-locale");
            (!value) && (value = this.mode.lang ? parseInt(Common.util.LanguageInfo.getLocalLanguageCode(this.mode.lang)) : 0x0409);

            var combo = this.panelSpellcheck.cmbDictionaryLanguage;
            if (this.languages && this.languages.length>0) {
                var langs = [], info,
                    allLangs = Common.util.LanguageInfo.getLanguages();
                this.languages.forEach(function (code) {
                    if (allLangs.hasOwnProperty(parseInt(code))) {
                        info = allLangs[parseInt(code)];
                        langs.push({
                            displayValue:   info[1],
                            value:          parseInt(code)
                        });
                    }
                });
                combo.setData(langs);
                if (value) {
                    var item = combo.store.findWhere({value: value});
                    combo.setValue(item ? item.get('value') : 0x0409);
                    value = combo.getValue();
                } else {
                    value = this.mode.lang ? parseInt(Common.util.LanguageInfo.getLocalLanguageCode(this.mode.lang)) : 0x0409;
                    combo.setValue(Common.util.LanguageInfo.getLocalLanguageName(value)[1]);
                }
            } else {
                combo.setValue(Common.util.LanguageInfo.getLocalLanguageName(value)[1]);
                combo.setDisabled(true);
            }
            this.api.asc_setDefaultLanguage(value);
        },

        onSelectLanguage: function (combo, record) {
            var lang = record.code;
            if (this.api && lang) {
                this.api.asc_setDefaultLanguage(lang);
                Common.localStorage.setItem("sse-spellcheck-locale", this.panelSpellcheck.cmbDictionaryLanguage.getValue());
            }
        },

        onClickChange: function (btn, e) {
            if (this.api) {
                var rec = this.panelSpellcheck.suggestionList.getSelectedRec();
                rec && this.api.asc_replaceMisspelledWord(rec.get('value'), this._currentSpellObj);
            }
        },

        onClickChangeMenu: function (menu, item) {
            if (this.api) {
                var rec = this.panelSpellcheck.suggestionList.getSelectedRec();
                if (item.value == 0) {
                    rec && this.api.asc_replaceMisspelledWord(rec.get('value'), this._currentSpellObj);
                } else if (item.value == 1) {
                    rec && this.api.asc_replaceMisspelledWord(rec.get('value'), this._currentSpellObj, true);
                }
            }
        },

        onClickIgnore: function () {
            if (this.api) {
                this.api.asc_ignoreMisspelledWord(this._currentSpellObj, false)
            }
        },

        onClickIgnoreMenu: function (menu, item) {
            if (this.api) {
                if (item.value == 0) {
                    this.api.asc_ignoreMisspelledWord(this._currentSpellObj, false);
                } else if (item.value == 1) {
                    this.api.asc_ignoreMisspelledWord(this._currentSpellObj, true);
                }
            }
        },

        onSpellCheckVariantsFound: function (property) {
            this._currentSpellObj = property;

            var word = property.get_Word();
            this.panelSpellcheck.currentWord.setValue(word);

            var variants = property.get_Variants(),
                arr = [];
            variants.forEach(function (item) {
                var rec = new Common.UI.DataViewModel();
                rec.set({
                    value: item
                });
                arr.push(rec);
            });
            this.panelSpellcheck.suggestionList.store.reset(arr);
        }

    }, SSE.Controllers.Spellcheck || {}));
});
<|endoftext|>


<commit_before>import fs from 'fs'
import path from 'path'
import webpack from 'webpack'
import parents from 'parents'
import resolveFrom from 'resolve-from'
import RoleResolverPlugin from '@sanity/webpack-loader'
import ExtractTextPlugin from '@sanity/extract-text-webpack-plugin'
import postcssPlugins from './postcssPlugins'

// Webpack 2 vs 1
const OccurrenceOrderPlugin = webpack.optimize.OccurrenceOrderPlugin || webpack.optimize.OccurenceOrderPlugin

const partLoaderPath = require.resolve('@sanity/webpack-loader/src/partLoader')

export default (config = {}) => {
  const basePath = config.basePath || process.cwd()

  const reactPath = resolveFrom(basePath, 'react')
  const reactDomPath = resolveFrom(basePath, 'react-dom')
  const missing = [!reactPath && '`react`', !reactDomPath && '`react-dom`'].filter(Boolean)
  if (!reactPath || !reactDomPath) {
    const missingErr = [
      `Could not find ${missing.join(', ')} dependencies in project directory`,
      'These need to be declared in `package.json` and be installed for Sanity to work'
    ].join('\n')

    throw new Error(missingErr)
  }

  const babelConfig = tryRead(path.join(basePath, '.babelrc'))
  const env = config.env || 'development'
  const isProd = env === 'production'
  const resolvePaths = parents(basePath).map(dir => path.join(dir, 'node_modules'))

  const cssExtractor = isProd
    && new ExtractTextPlugin('css/main.css', {allChunks: true, ignoreOrder: true})

  const baseCssLoader = 'css-loader?modules&localIdentName=[name]_[local]_[hash:base64:5]&importLoaders=1'
  const cssLoader = isProd
    ? `${baseCssLoader}&minimize`
    : `${baseCssLoader}&sourceMap`

  const commonChunkPlugin = (
    typeof config.commonChunkPlugin === 'undefined'
    || config.commonChunkPlugin
  ) && new webpack.optimize.CommonsChunkPlugin('vendor', 'js/vendor.bundle.js')

  return {
    entry: {
      app: [
        require.resolve('normalize.css'),
        path.join(__dirname, '..', 'browser', 'entry')
      ],
      vendor: ['react', 'react-dom']
    },
    output: {
      path: config.outputPath || path.join(__dirname, '..', '..', 'dist'),
      filename: 'js/[name].bundle.js',
      publicPath: '/static/'
    },
    resolve: {
      fallback: resolvePaths,
      alias: {
        'react': path.dirname(reactPath),
        'react-dom': path.dirname(reactDomPath)
      }
    },
    resolveLoader: {
      root: resolvePaths
    },
    module: {
      loaders: [{
        test: /\.jsx?/,
        exclude: modPath => modPath.indexOf('/node_modules/') >= 0,
        loader: 'babel',
        query: babelConfig || {
          presets: [
            require.resolve('babel-preset-react'),
            require.resolve('babel-preset-es2015')
          ],
          plugins: [
            require.resolve('babel-plugin-syntax-class-properties'),
            require.resolve('babel-plugin-transform-class-properties')
          ],
          cacheDirectory: true
        }
      }, {
        test: /\.json$/,
        loader: 'json'
      }, {
        test: /\.css(\?|$)/,
        loader: isProd && cssExtractor.extract([cssLoader, 'postcss-loader']),
        loaders: !isProd && ['style-loader', cssLoader, 'postcss-loader']
      }, {
        test: /\.(jpe?g|png|gif|svg|webp)$/,
        loader: require.resolve('file-loader'),
        query: {
          name: 'assets/[name]-[hash].[ext]'
        }
      }, {
        test: /[?&]sanityPart=/,
        loader: partLoaderPath
      }]
    },
    plugins: [
      cssExtractor,
      new OccurrenceOrderPlugin(),
      new webpack.ResolverPlugin([new RoleResolverPlugin({basePath})], ['normal']),
      commonChunkPlugin
    ].filter(Boolean),
    postcss: postcssPlugins({basePath})
  }
}

function tryRead(filePath) {
  try {
    const content = fs.readFileSync(filePath)
    return JSON.parse(content)
  } catch (err) {
    return null
  }
}
<commit_msg>Allow passing resolver options to webpack config<commit_after>import fs from 'fs'
import path from 'path'
import webpack from 'webpack'
import parents from 'parents'
import resolveFrom from 'resolve-from'
import RoleResolverPlugin from '@sanity/webpack-loader'
import ExtractTextPlugin from '@sanity/extract-text-webpack-plugin'
import postcssPlugins from './postcssPlugins'

// Webpack 2 vs 1
const OccurrenceOrderPlugin = webpack.optimize.OccurrenceOrderPlugin || webpack.optimize.OccurenceOrderPlugin

const partLoaderPath = require.resolve('@sanity/webpack-loader/src/partLoader')

export default (config = {}) => {
  const basePath = config.basePath || process.cwd()

  const reactPath = resolveFrom(basePath, 'react')
  const reactDomPath = resolveFrom(basePath, 'react-dom')
  const missing = [!reactPath && '`react`', !reactDomPath && '`react-dom`'].filter(Boolean)
  if (!reactPath || !reactDomPath) {
    const missingErr = [
      `Could not find ${missing.join(', ')} dependencies in project directory`,
      'These need to be declared in `package.json` and be installed for Sanity to work'
    ].join('\n')

    throw new Error(missingErr)
  }

  const babelConfig = tryRead(path.join(basePath, '.babelrc'))
  const env = config.env || 'development'
  const isProd = env === 'production'
  const resolvePaths = parents(basePath).map(dir => path.join(dir, 'node_modules'))
  const resolverOpts = Object.assign({basePath}, config.resolver || {})

  const cssExtractor = isProd
    && new ExtractTextPlugin('css/main.css', {allChunks: true, ignoreOrder: true})

  const baseCssLoader = 'css-loader?modules&localIdentName=[name]_[local]_[hash:base64:5]&importLoaders=1'
  const cssLoader = isProd
    ? `${baseCssLoader}&minimize`
    : `${baseCssLoader}&sourceMap`

  const commonChunkPlugin = (
    typeof config.commonChunkPlugin === 'undefined'
    || config.commonChunkPlugin
  ) && new webpack.optimize.CommonsChunkPlugin('vendor', 'js/vendor.bundle.js')

  return {
    entry: {
      app: [
        require.resolve('normalize.css'),
        path.join(__dirname, '..', 'browser', 'entry')
      ],
      vendor: ['react', 'react-dom']
    },
    output: {
      path: config.outputPath || path.join(__dirname, '..', '..', 'dist'),
      filename: 'js/[name].bundle.js',
      publicPath: '/static/'
    },
    resolve: {
      fallback: resolvePaths,
      alias: {
        'react': path.dirname(reactPath),
        'react-dom': path.dirname(reactDomPath)
      }
    },
    resolveLoader: {
      root: resolvePaths
    },
    module: {
      loaders: [{
        test: /\.jsx?/,
        exclude: modPath => modPath.indexOf('/node_modules/') >= 0,
        loader: 'babel',
        query: babelConfig || {
          presets: [
            require.resolve('babel-preset-react'),
            require.resolve('babel-preset-es2015')
          ],
          plugins: [
            require.resolve('babel-plugin-syntax-class-properties'),
            require.resolve('babel-plugin-transform-class-properties')
          ],
          cacheDirectory: true
        }
      }, {
        test: /\.json$/,
        loader: 'json'
      }, {
        test: /\.css(\?|$)/,
        loader: isProd && cssExtractor.extract([cssLoader, 'postcss-loader']),
        loaders: !isProd && ['style-loader', cssLoader, 'postcss-loader']
      }, {
        test: /\.(jpe?g|png|gif|svg|webp)$/,
        loader: require.resolve('file-loader'),
        query: {
          name: 'assets/[name]-[hash].[ext]'
        }
      }, {
        test: /[?&]sanityPart=/,
        loader: partLoaderPath
      }]
    },
    plugins: [
      cssExtractor,
      new OccurrenceOrderPlugin(),
      new webpack.ResolverPlugin([new RoleResolverPlugin(resolverOpts)], ['normal']),
      commonChunkPlugin
    ].filter(Boolean),
    postcss: postcssPlugins({basePath})
  }
}

function tryRead(filePath) {
  try {
    const content = fs.readFileSync(filePath)
    return JSON.parse(content)
  } catch (err) {
    return null
  }
}
<|endoftext|>


<commit_before>define([
	'knockout',
	'text!./cohort-method-analysis-editor.html',
	'components/Component',
	'utils/CommonUtils',
	'const',
	'../../const',
	'utils/DataTypeConverterUtils',
	'services/analysis/ConceptSet',
	'databindings',
	'cyclops',
	'./match-args-editor',
	'./stratify-args-editor',
	'./outcome-model-args-editor',
	'featureextraction/components/covariate-settings-editor',
	'components/cohort-definition-browser',
	'less!./cohort-method-analysis.less',
], function (
	ko,
	view,
	Component,
	commonUtils,
	constants,
	estimationConstants,
	dataTypeConverterUtils,
	ConceptSet,
) {
	class CohortMethodAnalysisEditor extends Component {
		constructor(params) {
            super(params);

			this.analysis = params.analysis;
			this.constants = constants;
			this.options = estimationConstants.options;
			this.subscriptions = params.subscriptions;
			this.editorMode = ko.observable('all');
			this.isEditPermitted = params.isEditPermitted;
			this.showCovariateSelector = ko.observable(false);
			this.showControlDisplay = ko.observable(false);
			this.showPriorDisplay = ko.observable(false);
			this.showConceptSetSelector = ko.observable(false);
			this.currentConceptSet = ko.observable(null);
			this.trimSelection = ko.observable();
			this.matchStratifySelection = ko.observable();
			this.excludeCovariateIds = ko.observable(this.analysis.createPsArgs.excludeCovariateIds() && this.analysis.createPsArgs.excludeCovariateIds().length > 0 ? this.analysis.createPsArgs.excludeCovariateIds().join() : '');
			this.includeCovariateIds = ko.observable(this.analysis.createPsArgs.includeCovariateIds() && this.analysis.createPsArgs.includeCovariateIds().length > 0 ? this.analysis.createPsArgs.includeCovariateIds().join() : '');
			this.cvIncludeCovariateIds = ko.observable(this.analysis.getDbCohortMethodDataArgs.covariateSettings.includedCovariateIds() && this.analysis.getDbCohortMethodDataArgs.covariateSettings.includedCovariateIds().length > 0 ? this.analysis.getDbCohortMethodDataArgs.covariateSettings.includedCovariateIds().join() : '');
			this.trimFraction = ko.observable(this.analysis.trimByPsArgs.trimFraction() ? dataTypeConverterUtils.convertFromPercent(this.analysis.trimByPsArgs.trimFraction()) : '');
			this.bounds = ko.observable(this.analysis.trimByPsToEquipoiseArgs.bounds() && this.analysis.trimByPsToEquipoiseArgs.bounds().length > 0 ? dataTypeConverterUtils.percentArrayToCommaDelimitedList(this.analysis.trimByPsToEquipoiseArgs.bounds()) : '');
			this.studyStartDate = ko.observable(this.analysis.getDbCohortMethodDataArgs.studyStartDate() !== null ? dataTypeConverterUtils.convertFromRDateToDate(this.analysis.getDbCohortMethodDataArgs.studyStartDate()) : null);
			this.studyEndDate = ko.observable(this.analysis.getDbCohortMethodDataArgs.studyEndDate() !== null ? dataTypeConverterUtils.convertFromRDateToDate(this.analysis.getDbCohortMethodDataArgs.studyEndDate()) : null);
			this.useRegularization = ko.observable(estimationConstants.isUsingRegularization(this.analysis.createPsArgs.prior) ? true : false);

			this.subscriptions.push(this.includeCovariateIds.subscribe(newValue => {
				this.analysis.createPsArgs.includeCovariateIds(dataTypeConverterUtils.commaDelimitedListToNumericArray(newValue));
			}));

			this.subscriptions.push(this.excludeCovariateIds.subscribe(newValue => {
				this.analysis.createPsArgs.excludeCovariateIds(dataTypeConverterUtils.commaDelimitedListToNumericArray(newValue));
			}));

			this.subscriptions.push(this.cvIncludeCovariateIds.subscribe(newValue => {
				this.analysis.getDbCohortMethodDataArgs.covariateSettings.includedCovariateIds(dataTypeConverterUtils.commaDelimitedListToNumericArray(newValue));
			}));

			this.subscriptions.push(this.trimFraction.subscribe(newValue => {
				this.analysis.trimByPsArgs.trimFraction(dataTypeConverterUtils.convertToPercent(newValue));
			}));

			this.subscriptions.push(this.bounds.subscribe(newValue => {
				this.analysis.trimByPsToEquipoiseArgs.bounds(dataTypeConverterUtils.commaDelimitedListToPercentArray(newValue));
			}));

			this.subscriptions.push(this.studyStartDate.subscribe(newValue => {
				this.analysis.getDbCohortMethodDataArgs.studyStartDate(dataTypeConverterUtils.convertToDateForR(newValue));
			}));

			this.subscriptions.push(this.studyEndDate.subscribe(newValue => {
				this.analysis.getDbCohortMethodDataArgs.studyEndDate(dataTypeConverterUtils.convertToDateForR(newValue));
			}));

			this.subscriptions.push(this.trimSelection.subscribe(newValue => {
				this.analysis.trimByPs(this.trimSelection() === "byPercent");
				this.analysis.trimByPsToEquipoise(this.trimSelection() === "toEquipoise");
				this.setCreatePs();
			}));

			this.subscriptions.push(this.useRegularization.subscribe(newValue => {
				estimationConstants.setRegularization(newValue, this.analysis.createPsArgs.prior);
			}));

			// Initialize trimSelection
			if (this.analysis.trimByPs()) {
				this.trimSelection("byPercent")
			} else if (this.analysis.trimByPsToEquipoise()) {
				this.trimSelection("toEquipoise")
			} else {
				this.trimSelection("none")
			}

			// Initialize matchStratifySelection
			if (this.analysis.matchOnPs()) {
				this.matchStratifySelection("matchOnPs")
			} else if (this.analysis.matchOnPsAndCovariates()) {
				this.matchStratifySelection("matchOnPsAndCovariates")
			} else if (this.analysis.stratifyByPs()) {
				this.matchStratifySelection("stratifyByPs")
			} else if (this.analysis.stratifyByPsAndCovariates()) {
				this.matchStratifySelection("stratifyOnPsAndCovariates")
			} else {
				this.matchStratifySelection("none")
			}

			// Set the subscription
			this.subscriptions.push(this.matchStratifySelection.subscribe(newValue => {
				this.analysis.matchOnPs(this.matchStratifySelection() === "matchOnPs");
				this.analysis.matchOnPsAndCovariates(this.matchStratifySelection() === "matchOnPsAndCovariates");
				this.analysis.stratifyByPs(this.matchStratifySelection() === "stratifyByPs");
				this.analysis.stratifyByPsAndCovariates(this.matchStratifySelection() === "stratifyOnPsAndCovariates");
				this.setCreatePs();
			}));
		}

		toggleControlDisplay() {
			this.showControlDisplay(!this.showControlDisplay());
		}

		togglePriorDisplay() {
			this.showPriorDisplay(!this.showPriorDisplay());
		}

		conceptsetSelected(d) {
			this.currentConceptSet()(new ConceptSet({id: d.id, name: d.name}));
			this.showConceptSetSelector(false);
		}

		chooseIncludedCovariates() {
			this.showConceptSetSelector(true);
			this.currentConceptSet(this.analysis.getDbCohortMethodDataArgs.covariateSettings.includedCovariateConceptSet);
		}

		clearIncludedCovariates () {
			this.analysis.getDbCohortMethodDataArgs.covariateSettings.includedCovariateConceptSet(new ConceptSet());
		}

		chooseExcludedCovariates() {
			this.showConceptSetSelector(true);
			this.currentConceptSet(this.analysis.getDbCohortMethodDataArgs.covariateSettings.excludedCovariateConceptSet);
		}

		clearExcludedCovariates () {
			this.analysis.getDbCohortMethodDataArgs.covariateSettings.excludedCovariateConceptSet(new ConceptSet());
		}

		setCreatePs() {
			if (this.matchStratifySelection() && this.trimSelection()) {
				this.analysis.createPs(
					!(this.matchStratifySelection() === "none" && this.trimSelection() === "none")
				);
			}
		}

	}

	return commonUtils.build('cohort-method-analysis-editor', CohortMethodAnalysisEditor, view);
});<commit_msg>createPs is set to true when user specifies inverse probability of treatment weighting (IPTW) for the outcome model(#1657) (#2310)<commit_after>define([
	'knockout',
	'text!./cohort-method-analysis-editor.html',
	'components/Component',
	'utils/CommonUtils',
	'const',
	'../../const',
	'utils/DataTypeConverterUtils',
	'services/analysis/ConceptSet',
	'databindings',
	'cyclops',
	'./match-args-editor',
	'./stratify-args-editor',
	'./outcome-model-args-editor',
	'featureextraction/components/covariate-settings-editor',
	'components/cohort-definition-browser',
	'less!./cohort-method-analysis.less',
], function (
	ko,
	view,
	Component,
	commonUtils,
	constants,
	estimationConstants,
	dataTypeConverterUtils,
	ConceptSet,
) {
	class CohortMethodAnalysisEditor extends Component {
		constructor(params) {
            super(params);

			this.analysis = params.analysis;
			this.constants = constants;
			this.options = estimationConstants.options;
			this.subscriptions = params.subscriptions;
			this.editorMode = ko.observable('all');
			this.isEditPermitted = params.isEditPermitted;
			this.showCovariateSelector = ko.observable(false);
			this.showControlDisplay = ko.observable(false);
			this.showPriorDisplay = ko.observable(false);
			this.showConceptSetSelector = ko.observable(false);
			this.currentConceptSet = ko.observable(null);
			this.trimSelection = ko.observable();
			this.matchStratifySelection = ko.observable();
			this.excludeCovariateIds = ko.observable(this.analysis.createPsArgs.excludeCovariateIds() && this.analysis.createPsArgs.excludeCovariateIds().length > 0 ? this.analysis.createPsArgs.excludeCovariateIds().join() : '');
			this.includeCovariateIds = ko.observable(this.analysis.createPsArgs.includeCovariateIds() && this.analysis.createPsArgs.includeCovariateIds().length > 0 ? this.analysis.createPsArgs.includeCovariateIds().join() : '');
			this.cvIncludeCovariateIds = ko.observable(this.analysis.getDbCohortMethodDataArgs.covariateSettings.includedCovariateIds() && this.analysis.getDbCohortMethodDataArgs.covariateSettings.includedCovariateIds().length > 0 ? this.analysis.getDbCohortMethodDataArgs.covariateSettings.includedCovariateIds().join() : '');
			this.trimFraction = ko.observable(this.analysis.trimByPsArgs.trimFraction() ? dataTypeConverterUtils.convertFromPercent(this.analysis.trimByPsArgs.trimFraction()) : '');
			this.bounds = ko.observable(this.analysis.trimByPsToEquipoiseArgs.bounds() && this.analysis.trimByPsToEquipoiseArgs.bounds().length > 0 ? dataTypeConverterUtils.percentArrayToCommaDelimitedList(this.analysis.trimByPsToEquipoiseArgs.bounds()) : '');
			this.studyStartDate = ko.observable(this.analysis.getDbCohortMethodDataArgs.studyStartDate() !== null ? dataTypeConverterUtils.convertFromRDateToDate(this.analysis.getDbCohortMethodDataArgs.studyStartDate()) : null);
			this.studyEndDate = ko.observable(this.analysis.getDbCohortMethodDataArgs.studyEndDate() !== null ? dataTypeConverterUtils.convertFromRDateToDate(this.analysis.getDbCohortMethodDataArgs.studyEndDate()) : null);
			this.useRegularization = ko.observable(estimationConstants.isUsingRegularization(this.analysis.createPsArgs.prior) ? true : false);

			this.subscriptions.push(this.includeCovariateIds.subscribe(newValue => {
				this.analysis.createPsArgs.includeCovariateIds(dataTypeConverterUtils.commaDelimitedListToNumericArray(newValue));
			}));

			this.subscriptions.push(this.excludeCovariateIds.subscribe(newValue => {
				this.analysis.createPsArgs.excludeCovariateIds(dataTypeConverterUtils.commaDelimitedListToNumericArray(newValue));
			}));

			this.subscriptions.push(this.cvIncludeCovariateIds.subscribe(newValue => {
				this.analysis.getDbCohortMethodDataArgs.covariateSettings.includedCovariateIds(dataTypeConverterUtils.commaDelimitedListToNumericArray(newValue));
			}));

			this.subscriptions.push(this.trimFraction.subscribe(newValue => {
				this.analysis.trimByPsArgs.trimFraction(dataTypeConverterUtils.convertToPercent(newValue));
			}));

			this.subscriptions.push(this.bounds.subscribe(newValue => {
				this.analysis.trimByPsToEquipoiseArgs.bounds(dataTypeConverterUtils.commaDelimitedListToPercentArray(newValue));
			}));

			this.subscriptions.push(this.studyStartDate.subscribe(newValue => {
				this.analysis.getDbCohortMethodDataArgs.studyStartDate(dataTypeConverterUtils.convertToDateForR(newValue));
			}));

			this.subscriptions.push(this.studyEndDate.subscribe(newValue => {
				this.analysis.getDbCohortMethodDataArgs.studyEndDate(dataTypeConverterUtils.convertToDateForR(newValue));
			}));

			this.subscriptions.push(this.trimSelection.subscribe(newValue => {
				this.analysis.trimByPs(this.trimSelection() === "byPercent");
				this.analysis.trimByPsToEquipoise(this.trimSelection() === "toEquipoise");
				this.setCreatePs();
			}));

			this.subscriptions.push(this.useRegularization.subscribe(newValue => {
				estimationConstants.setRegularization(newValue, this.analysis.createPsArgs.prior);
			}));

			// Initialize trimSelection
			if (this.analysis.trimByPs()) {
				this.trimSelection("byPercent")
			} else if (this.analysis.trimByPsToEquipoise()) {
				this.trimSelection("toEquipoise")
			} else {
				this.trimSelection("none")
			}

			// Initialize matchStratifySelection
			if (this.analysis.matchOnPs()) {
				this.matchStratifySelection("matchOnPs")
			} else if (this.analysis.matchOnPsAndCovariates()) {
				this.matchStratifySelection("matchOnPsAndCovariates")
			} else if (this.analysis.stratifyByPs()) {
				this.matchStratifySelection("stratifyByPs")
			} else if (this.analysis.stratifyByPsAndCovariates()) {
				this.matchStratifySelection("stratifyOnPsAndCovariates")
			} else {
				this.matchStratifySelection("none")
			}

			// Set the subscription
			this.subscriptions.push(this.matchStratifySelection.subscribe(newValue => {
				this.analysis.matchOnPs(this.matchStratifySelection() === "matchOnPs");
				this.analysis.matchOnPsAndCovariates(this.matchStratifySelection() === "matchOnPsAndCovariates");
				this.analysis.stratifyByPs(this.matchStratifySelection() === "stratifyByPs");
				this.analysis.stratifyByPsAndCovariates(this.matchStratifySelection() === "stratifyOnPsAndCovariates");
				this.setCreatePs();
			}));

			this.subscriptions.push(this.analysis.fitOutcomeModelArgs.inversePtWeighting.subscribe(newValue => {
				this.setCreatePs();
			}));
		}

		toggleControlDisplay() {
			this.showControlDisplay(!this.showControlDisplay());
		}

		togglePriorDisplay() {
			this.showPriorDisplay(!this.showPriorDisplay());
		}

		conceptsetSelected(d) {
			this.currentConceptSet()(new ConceptSet({id: d.id, name: d.name}));
			this.showConceptSetSelector(false);
		}

		chooseIncludedCovariates() {
			this.showConceptSetSelector(true);
			this.currentConceptSet(this.analysis.getDbCohortMethodDataArgs.covariateSettings.includedCovariateConceptSet);
		}

		clearIncludedCovariates () {
			this.analysis.getDbCohortMethodDataArgs.covariateSettings.includedCovariateConceptSet(new ConceptSet());
		}

		chooseExcludedCovariates() {
			this.showConceptSetSelector(true);
			this.currentConceptSet(this.analysis.getDbCohortMethodDataArgs.covariateSettings.excludedCovariateConceptSet);
		}

		clearExcludedCovariates () {
			this.analysis.getDbCohortMethodDataArgs.covariateSettings.excludedCovariateConceptSet(new ConceptSet());
		}

		setCreatePs() {
			if (this.matchStratifySelection() && this.trimSelection()) {
				this.analysis.createPs(
					!(this.matchStratifySelection() === "none" && this.trimSelection() === "none")
				);
			}
			if (this.analysis.fitOutcomeModelArgs.inversePtWeighting()) {
				this.analysis.createPs(true);
			}
		}

	}

	return commonUtils.build('cohort-method-analysis-editor', CohortMethodAnalysisEditor, view);
});<|endoftext|>


<commit_before>import { isString, parseJSON } from '../../core/util';
import Ajax from '../../core/Ajax';
import SpatialReference from './SpatialReference';

function parse(arcConf) {
    const tileInfo = arcConf['tileInfo'],
        tileSize = [tileInfo['cols'], tileInfo['rows']],
        resolutions = [],
        lods = tileInfo['lods'];
    for (let i = 0, len = lods.length; i < len; i++) {
        resolutions.push(lods[i]['resolution']);
    }
    const fullExtent = arcConf['fullExtent'],
        origin = tileInfo['origin'],
        tileSystem = [1, -1, origin['x'], origin['y']];
    delete fullExtent['spatialReference'];
    return {
        'spatialReference': {
            'resolutions': resolutions,
            'fullExtent': fullExtent
        },
        'tileSystem': tileSystem,
        'tileSize': tileSize
    };
}

SpatialReference.loadArcgis = function (url, cb, options = { 'jsonp' : true }) {
    if (isString(url) && url.substring(0, 1) !== '{') {
        Ajax.getJSON(url, function (err, json) {
            if (err) {
                cb(err);
                return;
            }
            const spatialRef = parse(json);
            cb(null, spatialRef);
        }, options);
    } else {
        if (isString(url)) {
            url = parseJSON(url);
        }
        const spatialRef = parse(url);
        cb(null, spatialRef);

    }
    return this;
};
<commit_msg>load WMTS support<commit_after>import { isString, parseJSON } from '../../core/util';
import Ajax from '../../core/Ajax';
import SpatialReference from './SpatialReference';

function parse(arcConf) {
    const tileInfo = arcConf['tileInfo'],
        tileSize = [tileInfo['cols'], tileInfo['rows']],
        resolutions = [],
        lods = tileInfo['lods'];
    for (let i = 0, len = lods.length; i < len; i++) {
        resolutions.push(lods[i]['resolution']);
    }
    const fullExtent = arcConf['fullExtent'],
        origin = tileInfo['origin'],
        tileSystem = [1, -1, origin['x'], origin['y']];
    let projection = (fullExtent['spatialReference'].wkid || '').toString();
    projection = getProjection(projection);
    delete fullExtent['spatialReference'];
    return {
        'spatialReference': {
            'resolutions': resolutions,
            'fullExtent': fullExtent,
            'projection': projection
        },
        'tileSystem': tileSystem,
        'tileSize': tileSize
    };
}

function getProjection(projection) {
    let prj = (projection.indexOf('EPSG') > -1 ? projection : 'EPSG:' + projection);
    prj = strReplace(prj, [
        ['4490', '4326'],
        ['102100', '3857'],
        ['900913', '3857']
    ]);
    return prj;
}

function strReplace(str, repArray = []) {
    repArray.forEach(rep => {
        const [template, value] = rep;
        str = str.replace(template, value);
    });
    return str;
}

function parseWMTSXML(str, requestUrl, options) {
    //IE test success
    const parser = new DOMParser();
    const xmlDoc = parser.parseFromString(str, 'text/xml');
    const content = xmlDoc.querySelectorAll('Contents')[0];
    if (!content) {
        return [];
    }
    const layers = content.getElementsByTagName('Layer');
    if (!layers.length) {
        return [];
    }
    const TileMatrixSets = [];
    for (let i = 0, len = content.childNodes.length; i < len; i++) {
        if (content.childNodes[i].nodeName === 'TileMatrixSet') {
            TileMatrixSets.push(content.childNodes[i]);
        }
    }
    if (!TileMatrixSets.length) {
        return [];
    }
    const result = [];
    for (let i = 0, len = layers.length; i < len; i++) {
        const layer = layers[i];
        let style = layer.querySelectorAll('Style')[0];
        if (style) {
            style = style.getElementsByTagName('ows:Identifier')[0];
            if (style) {
                style = style.textContent;
            }
        }
        let layerName = layer.getElementsByTagName('ows:Identifier')[0];
        if (layerName) {
            layerName = layerName.textContent;
        }
        const resourceURL = layer.querySelectorAll('ResourceURL')[0];
        let url = '';
        if (resourceURL) {
            url = resourceURL.attributes.template.value;
        }
        const { resolutions, tileSize, tileSystem, projection, TileMatrixSet } = parseTileMatrixSet(TileMatrixSets, i, options);
        //not find ServerURL
        if (!url.length) {
            url = requestUrl.substr(0, requestUrl.lastIndexOf('?'));
            url += '?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER={LAYER}&STYLE={Style}&TILEMATRIXSET={TileMatrixSet}&FORMAT=tiles&TILEMATRIX={TileMatrix}&TILEROW={TileRow}&TILECOL={TileCol}';
        }
        const urlTemplate = strReplace(url, [
            ['{LAYER}', layerName],
            ['{Layer}', layerName],
            ['{layer}', layerName],
            ['{STYLE}', style],
            ['{Style}', style],
            ['{style}', style],
            ['{TileMatrixSet}', TileMatrixSet],
            ['{TileMatrix}', '{z}'],
            ['{TileRow}', '{y}'],
            ['{TileCol}', '{x}'],
        ]);
        result.push({
            tileSize,
            tileSystem,
            spatialReference: {
                resolutions,
                projection
            },
            urlTemplate,
            info: {
                layerName, TileMatrixSet, style, tileSize, tileSystem, resolutions, projection, urlTemplate
            }
        });
    }
    return result;
}

function parseTileMatrixSet(TileMatrixSets, index, options = {}) {
    const TileMatrixSet = TileMatrixSets[index];
    const TileMatrixs = TileMatrixSet.getElementsByTagName('TileMatrix');
    const resolutions = [], tileSystem = [], tileSize = [];
    let projection, tset;
    if (!projection) {
        const supportedCRS = TileMatrixSet.getElementsByTagName('ows:SupportedCRS')[0];
        if (supportedCRS) {
            projection = supportedCRS.textContent;
            projection = projection.split('EPSG')[1];
            while (projection.indexOf(':') > -1) {
                projection = projection.replace(':', '');
            }
            projection = getProjection(projection);
        }
    }
    if (!tset) {
        tset = TileMatrixSet.getElementsByTagName('ows:Identifier')[0];
        if (tset) {
            tset = tset.textContent;
        }
    }
    //transform value, ArcGIS is different from others
    let transformValue = 0.0002645833333333333;
    if (options.isArcgis) {
        transformValue = 0.00028;
    }
    if (projection && projection.indexOf('4326') > -1) {
        transformValue = 2.3767925226029154e-9;
        if (options.isArcgis) {
            transformValue = 2.518101729011901e-9;
        }
    }
    let minLevel = Infinity;
    for (let index = 0; index < TileMatrixs.length; index++) {
        const TileMatrix = TileMatrixs[index];
        let level = TileMatrix.getElementsByTagName('ows:Identifier')[0].textContent;
        level = parseInt(level);
        minLevel = Math.min(minLevel, level);
        const ScaleDenominator = TileMatrix.getElementsByTagName('ScaleDenominator')[0].textContent;
        const TopLeftCorner = TileMatrix.getElementsByTagName('TopLeftCorner')[0].textContent;
        const TileWidth = TileMatrix.getElementsByTagName('TileWidth')[0].textContent;
        const TileHeight = TileMatrix.getElementsByTagName('TileHeight')[0].textContent;
        if (tileSize.length === 0) {
            tileSize.push(parseInt(TileWidth), parseInt(TileHeight));
        }
        if (tileSystem.length === 0) {
            const [x, y] = TopLeftCorner.split(' ').filter(s => {
                return s !== '';
            }).map(v => {
                return parseFloat(v);
            });
            if (x > 0) {
                tileSystem.push(1, -1, y, x);
            } else {
                tileSystem.push(1, -1, x, y);
            }
        }
        const res = parseFloat(ScaleDenominator) * transformValue;
        resolutions.push(res);
    }
    //Missing LOD completion
    // such as http://t0.tianditu.gov.cn/img_w/wmts?request=GetCapabilities&service=wmts&tk=de0dc270a51aaca3dd4e64d4f8c81ff6
    if (minLevel > 0) {
        let res = resolutions[0];
        for (let i = minLevel - 1; i >= 0; i--) {
            res = res * 2;
            resolutions.splice(0, 0, res);
        }
    }
    return {
        resolutions, tileSize, tileSystem, projection, TileMatrixSet: tset
    };
}

SpatialReference.loadArcgis = function (url, cb, options = { 'jsonp': true }) {
    if (isString(url) && url.substring(0, 1) !== '{') {
        const searchParams = '?f=pjson';
        if (url.indexOf(searchParams) < 0) {
            url += searchParams;
        }
        const urlTemplate = (url + '/tile/{z}/{y}/{x}').replace(searchParams, '');
        Ajax.getJSON(url, function (err, json) {
            if (err) {
                cb(err);
                return;
            }
            const spatialRef = parse(json);
            spatialRef.urlTemplate = urlTemplate;
            cb(null, spatialRef);
        }, options);
    } else {
        if (isString(url)) {
            url = parseJSON(url);
        }
        const spatialRef = parse(url);
        cb(null, spatialRef);

    }
    return this;
};

SpatialReference.loadWMTS = function (url, cb, options = { 'jsonp': true }) {
    if (isString(url)) {
        Ajax.get(url, function (err, xml) {
            if (err) {
                cb(err);
                return;
            }
            const layers = parseWMTSXML(xml, url, options);
            cb(null, layers);
        }, options);
    }
    return this;
};
<|endoftext|>