<commit_before>// Native modules
var fs = require('fs');

// 3rd party dependencies
var lodash = require('lodash'),
    Spellchecker = require('hunspell-spellchecker'),
    globals = require('globals');

var spell = new Spellchecker(),
    dictionary,
    skipWords = lodash.union(
        lodash.keys(globals.builtin),
        lodash.keys(globals.browser),
        lodash.keys(globals.node),
        lodash.keys(globals.mocha),
        lodash.keys(globals.jasmine),
        lodash.keys(globals.jquery),
        lodash.keys(globals.shelljs),
        Object.getOwnPropertyNames(String.prototype),
        Object.getOwnPropertyNames(JSON),
        Object.getOwnPropertyNames(Math)
    );

// ESLint 3 had "eslint.version" in context. ESLint 4 does not have one.
function isEslint4OrAbove(context) {
  return !('eslint' in context);
}

module.exports = {
    // meta (object) contains metadata for the rule:
    meta: {
        // docs (object) is required for core rules of ESLint.
        // In a custom rule or plugin, you can omit docs or include any properties that you need in it.
        docs: {

            // provides the short description of the rule in the rules index
            description: 'spell check',

            // specifies the heading under which the rule is listed in the rules index
            category: 'Possible Errors',

            // is whether the 'extends': 'eslint:recommended' property in a configuration file enables the rule
            recommended: false
        },

        // fixable (string) is either 'code' or 'whitespace' if the --fix option on the command line automatically fixes problems reported by the rule
        // Important: Without the fixable property, ESLint does not apply fixes even if the rule implements fix functions. Omit the fixable property if the rule is not fixable.
        fixable: 'code',

        // specifies the options so ESLint can prevent invalid rule configurations
        schema: [
            {
                type: 'object',
                properties: {
                    comments: {
                        type: 'boolean',
                        default: true
                    },
                    strings: {
                        type: 'boolean',
                        default: true
                    },
                    identifiers: {
                        type: 'boolean',
                        default: true
                    },
                    templates: {
                        type: 'boolean',
                        default: true
                    },
                    lang: {
                        type: 'string',
                        default: 'en_US'
                    },
                    skipWords: {
                        type: 'array',
                        default: [
                            'dict',
                            'aff',
                            'hunspellchecker',
                            'hunspell',
                            'utils'
                        ]
                    },
                    skipIfMatch: {
                        type: 'array',
                        default: []
                    },
                    skipWordIfMatch: {
                        type: 'array',
                        default: []
                    },
                    minLength: {
                        type: 'number',
                        default: 1
                    }
                },
                additionalProperties: false
            }
        ]

    },

    // create (function) returns an object with methods that ESLint calls to “visit” nodes while traversing the abstract syntax tree (AST as defined by ESTree) of JavaScript code:
    create: function(context) {
        /*
        if a key is a node type, ESLint calls that visitor function while going down the tree
        if a key is a node type plus :exit, ESLint calls that visitor function while going up the tree
        if a key is an event name, ESLint calls that handler function for code path analysis
        */

        'use strict';
        var defaultOptions = {
            comments: true,
            strings: true,
            identifiers: true,
            templates: true,
            skipWords: [],
            skipIfMatch: [],
            skipWordIfMatch: [],
            minLength: 1
        },
        options = lodash.assign(defaultOptions, context.options[0]),
        lang = options.lang || 'en_US';
        dictionary = spell.parse({
          aff: fs.readFileSync(__dirname + '/utils/dicts/' + lang + '.aff'),
          dic: fs.readFileSync(__dirname + '/utils/dicts/' + lang + '.dic')
        });

        spell.use(dictionary);
        options.skipWords = new Set(lodash.union(options.skipWords, skipWords)
            .map(function (string) {
                return string.toLowerCase();
            }));

        function isSpellingError(aWord) {
            return !options.skipWords.has(aWord) && !spell.check(aWord);
        }

        function checkSpelling(aNode, value, spellingType) {
            if(!hasToSkip(value)) {
                // Regular expression matches regexp metacharacters, and any special char
                var regexp = /(\\[sSwdDB0nfrtv])|\\[0-7][0-7][0-7]|\\x[0-9A-F][0-9A-F]|\\u[0-9A-F][0-9A-F][0-9A-F][0-9A-F]|[^0-9a-zA-Z ']/g,
                    nodeWords = value.replace(regexp, ' ')
                        .replace(/([A-Z])/g, ' $1').split(' '),
                    errors;
                errors = nodeWords
                    .filter(hasToSkipWord)
                    .filter(isSpellingError)
                    .filter(function(aWord) {
                      // Split words by numbers for special cases such as test12anything78variable and to include 2nd and 3rd ordinals
                      // also for Proper names we convert to lower case in second pass.
                        var splitByNumberWords = aWord.replace(/[0-9']/g, ' ').replace(/([A-Z])/g, ' $1').toLowerCase().split(' ');
                        return splitByNumberWords.some(isSpellingError);
                    })
                    .forEach(function(aWord) {
                        context.report(
                            aNode,
                            'You have a misspelled word: {{word}} on {{spellingType}}', {
                              word: aWord,
                              spellingType: spellingType
                        });
                    });
                }
            }

        function checkComment(aNode) {
            if(options.comments) {
                checkSpelling(aNode, aNode.value, 'Comment');
            }
        }

        function checkLiteral(aNode){
            if(options.strings && typeof aNode.value === 'string') {
                checkSpelling(aNode, aNode.value, 'String');
            }
        }
        function checkTemplateElement(aNode){
            if(options.templates && typeof aNode.value.raw === 'string') {
                checkSpelling(aNode, aNode.value.raw, 'Template');
            }
        }

        function checkIdentifier(aNode) {
            if(options.identifiers) {
                checkSpelling(aNode, aNode.name, 'Identifier');
            }
        }
        /* Returns true if the string in value has to be skipped for spell checking */
        function hasToSkip(value) {
            return options.skipWords.has(value) ||
                lodash.find(options.skipIfMatch, function (aPattern) {
                    return value.match(aPattern);
                });
        }

        /**
         * returns false if the word has to be skipped
         * @param  {string}  word
         * @return {Boolean} false if skip; true if not
         */
        function hasToSkipWord(word) {
            if(word.length < options.minLength) return false;
            if(lodash.find(options.skipWordIfMatch, function (aPattern) {
                return word.match(aPattern);
            })){
                return false;
            }
            return true;
        }

        // Coverage exclusion only needed for ESLint<4
        /* istanbul ignore next */
        if (isEslint4OrAbove(context)) {
          context
            .getSourceCode()
            .getAllComments()
            .forEach(function (commentNode) {
              checkComment(commentNode);
            });
        }

        return {
            // Noop in ESLint 4+
            'BlockComment': checkComment,
            // Noop in ESLint 4+
            'LineComment': checkComment,
            'Literal': checkLiteral,
            'TemplateElement': checkTemplateElement,
            'Identifier': checkIdentifier
        };
    }
};
<commit_msg>Initialize dictionary only if lang changed<commit_after>// Native modules
var fs = require('fs');

// 3rd party dependencies
var lodash = require('lodash'),
    Spellchecker = require('hunspell-spellchecker'),
    globals = require('globals');

var spell = new Spellchecker(),
    dictionary = null,
    dictionaryLang,
    skipWords = lodash.union(
        lodash.keys(globals.builtin),
        lodash.keys(globals.browser),
        lodash.keys(globals.node),
        lodash.keys(globals.mocha),
        lodash.keys(globals.jasmine),
        lodash.keys(globals.jquery),
        lodash.keys(globals.shelljs),
        Object.getOwnPropertyNames(String.prototype),
        Object.getOwnPropertyNames(JSON),
        Object.getOwnPropertyNames(Math)
    );

// ESLint 3 had "eslint.version" in context. ESLint 4 does not have one.
function isEslint4OrAbove(context) {
  return !('eslint' in context);
}

module.exports = {
    // meta (object) contains metadata for the rule:
    meta: {
        // docs (object) is required for core rules of ESLint.
        // In a custom rule or plugin, you can omit docs or include any properties that you need in it.
        docs: {

            // provides the short description of the rule in the rules index
            description: 'spell check',

            // specifies the heading under which the rule is listed in the rules index
            category: 'Possible Errors',

            // is whether the 'extends': 'eslint:recommended' property in a configuration file enables the rule
            recommended: false
        },

        // fixable (string) is either 'code' or 'whitespace' if the --fix option on the command line automatically fixes problems reported by the rule
        // Important: Without the fixable property, ESLint does not apply fixes even if the rule implements fix functions. Omit the fixable property if the rule is not fixable.
        fixable: 'code',

        // specifies the options so ESLint can prevent invalid rule configurations
        schema: [
            {
                type: 'object',
                properties: {
                    comments: {
                        type: 'boolean',
                        default: true
                    },
                    strings: {
                        type: 'boolean',
                        default: true
                    },
                    identifiers: {
                        type: 'boolean',
                        default: true
                    },
                    templates: {
                        type: 'boolean',
                        default: true
                    },
                    lang: {
                        type: 'string',
                        default: 'en_US'
                    },
                    skipWords: {
                        type: 'array',
                        default: [
                            'dict',
                            'aff',
                            'hunspellchecker',
                            'hunspell',
                            'utils'
                        ]
                    },
                    skipIfMatch: {
                        type: 'array',
                        default: []
                    },
                    skipWordIfMatch: {
                        type: 'array',
                        default: []
                    },
                    minLength: {
                        type: 'number',
                        default: 1
                    }
                },
                additionalProperties: false
            }
        ]

    },

    // create (function) returns an object with methods that ESLint calls to “visit” nodes while traversing the abstract syntax tree (AST as defined by ESTree) of JavaScript code:
    create: function(context) {
        /*
        if a key is a node type, ESLint calls that visitor function while going down the tree
        if a key is a node type plus :exit, ESLint calls that visitor function while going up the tree
        if a key is an event name, ESLint calls that handler function for code path analysis
        */

        'use strict';
        var defaultOptions = {
            comments: true,
            strings: true,
            identifiers: true,
            templates: true,
            skipWords: [],
            skipIfMatch: [],
            skipWordIfMatch: [],
            minLength: 1
        },
        options = lodash.assign(defaultOptions, context.options[0]),
        lang = options.lang || 'en_US';

        if (dictionaryLang !== lang) { //Dictionary will only be initialized if changed
            dictionaryLang = lang;
            initializeDictionary(lang);
        }

        options.skipWords = new Set(lodash.union(options.skipWords, skipWords)
            .map(function (string) {
                return string.toLowerCase();
            }));

        function initializeDictionary(language) {
            dictionary = spell.parse({
                aff: fs.readFileSync(__dirname + '/utils/dicts/' + language + '.aff'),
                dic: fs.readFileSync(__dirname + '/utils/dicts/' + language + '.dic')
            });

            spell.use(dictionary);
        }

        function isSpellingError(aWord) {
            return !options.skipWords.has(aWord) && !spell.check(aWord);
        }

        function checkSpelling(aNode, value, spellingType) {
            if(!hasToSkip(value)) {
                // Regular expression matches regexp metacharacters, and any special char
                var regexp = /(\\[sSwdDB0nfrtv])|\\[0-7][0-7][0-7]|\\x[0-9A-F][0-9A-F]|\\u[0-9A-F][0-9A-F][0-9A-F][0-9A-F]|[^0-9a-zA-Z ']/g,
                    nodeWords = value.replace(regexp, ' ')
                        .replace(/([A-Z])/g, ' $1').split(' '),
                    errors;
                errors = nodeWords
                    .filter(hasToSkipWord)
                    .filter(isSpellingError)
                    .filter(function(aWord) {
                      // Split words by numbers for special cases such as test12anything78variable and to include 2nd and 3rd ordinals
                      // also for Proper names we convert to lower case in second pass.
                        var splitByNumberWords = aWord.replace(/[0-9']/g, ' ').replace(/([A-Z])/g, ' $1').toLowerCase().split(' ');
                        return splitByNumberWords.some(isSpellingError);
                    })
                    .forEach(function(aWord) {
                        context.report(
                            aNode,
                            'You have a misspelled word: {{word}} on {{spellingType}}', {
                              word: aWord,
                              spellingType: spellingType
                        });
                    });
                }
            }

        function checkComment(aNode) {
            if(options.comments) {
                checkSpelling(aNode, aNode.value, 'Comment');
            }
        }

        function checkLiteral(aNode){
            if(options.strings && typeof aNode.value === 'string') {
                checkSpelling(aNode, aNode.value, 'String');
            }
        }
        function checkTemplateElement(aNode){
            if(options.templates && typeof aNode.value.raw === 'string') {
                checkSpelling(aNode, aNode.value.raw, 'Template');
            }
        }

        function checkIdentifier(aNode) {
            if(options.identifiers) {
                checkSpelling(aNode, aNode.name, 'Identifier');
            }
        }
        /* Returns true if the string in value has to be skipped for spell checking */
        function hasToSkip(value) {
            return options.skipWords.has(value) ||
                lodash.find(options.skipIfMatch, function (aPattern) {
                    return value.match(aPattern);
                });
        }

        /**
         * returns false if the word has to be skipped
         * @param  {string}  word
         * @return {Boolean} false if skip; true if not
         */
        function hasToSkipWord(word) {
            if(word.length < options.minLength) return false;
            if(lodash.find(options.skipWordIfMatch, function (aPattern) {
                return word.match(aPattern);
            })){
                return false;
            }
            return true;
        }

        // Coverage exclusion only needed for ESLint<4
        /* istanbul ignore next */
        if (isEslint4OrAbove(context)) {
          context
            .getSourceCode()
            .getAllComments()
            .forEach(function (commentNode) {
              checkComment(commentNode);
            });
        }

        return {
            // Noop in ESLint 4+
            'BlockComment': checkComment,
            // Noop in ESLint 4+
            'LineComment': checkComment,
            'Literal': checkLiteral,
            'TemplateElement': checkTemplateElement,
            'Identifier': checkIdentifier
        };
    }
};
<|endoftext|>


<commit_before>const Kaba = require("kaba");

module.exports = (new Kaba())
    .addJavaScriptEntries({
        "all-tests": "tests/build/all-tests.js",
    })
    .enableTypeScript()
    .setOutputPath("tests/dist")
    .disableChunkSplitting()
    .disableFileNameHashing()
    .disableModuleConcatenation()
;
<commit_msg>Don’t use removed method<commit_after>const Kaba = require("kaba");

module.exports = (new Kaba())
    .addJavaScriptEntries({
        "all-tests": "tests/build/all-tests.js",
    })
    .setOutputPath("tests/dist")
    .disableChunkSplitting()
    .disableFileNameHashing()
    .disableModuleConcatenation()
;
<|endoftext|>


<commit_before><commit_msg>% tuned DOM.CSS performance<commit_after><|endoftext|>


<commit_before>'use strict';

/**
 *  Lints chosen source files and reports any errors.
 *
 *  Example Usage:
 *  gulp lint
 *  gulp lint --filePath js/src/app.js
 */

var gulp = require('gulp'),
    args = require('yargs').argv,
    common = require('./_common'),
    jshint = require('gulp-jshint');

gulp.task('lint', function() {
    return gulp.src(common.buildSources(args.filePath))
        .pipe(jshint())
        .pipe(jshint.reporter('jshint-stylish'));
});<commit_msg>Linter task now fails on linting errors.<commit_after>'use strict';

/**
 *  Lints chosen source files and reports any errors.
 *
 *  Example Usage:
 *  gulp lint
 *  gulp lint --filePath js/src/app.js
 */

var gulp = require('gulp'),
    args = require('yargs').argv,
    common = require('./_common'),
    jshint = require('gulp-jshint');

gulp.task('lint', function() {
    return gulp.src(common.buildSources(args.filePath))
        .pipe(jshint())
        .pipe(jshint.reporter('jshint-stylish'))
        .pipe(jshint.reporter('fail'));
});<|endoftext|>


<commit_before>function addCommas(nStr) {
  nStr += '';
  x = nStr.split('.');
  x1 = x[0];
  x2 = x.length > 1 ? '.' + x[1] : '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
  }
  return x1 + x2;
}

window.recycyledFormAttributes = ['email', 'first_name', 'last_name', 'phone', 'zip'];
function manageDataFromParams(source_key, skipped_forms_selector){
  var url_param = getParameterByName(source_key);
  if (url_param.length > 2){
    Cookies.set(source_key, getParameterByName(source_key), { expires: 7 });
  }
  var current_cookie_value = Cookies.get(source_key);
  setFormsValues(source_key, current_cookie_value, skipped_forms_selector)
}

function wrapParamForRails(param_key) {
  return param_key.replace(/(email|first_name|last_name|phone|zip)/, 'person\\[$1\\]');
}

function setFormsValues(source_key, target_value, skipped_forms_selector){
  if(typeof target_value != "undefined"){
    target_value = target_value.replace(' ','+');
    var $form = $('form').not(skipped_forms_selector);
    var input_name = wrapParamForRails(source_key);
    var target_ref = 'input[name='+input_name+'], input[name='+input_name+']';
    input_name = input_name.replace('\\[','[').replace('\\]',']')

    if($form.find(target_ref).length == 0){
      $form.append('<input type="hidden" name="'+input_name+'" value="'+target_value+'">');
    }else{
      $form.find(target_ref).val(target_value);
    }
  }
}

function setRecycledFormsInputValues($form){
  $(recycyledFormAttributes).each(function(index, attribute_key){
    var current_value = Cookies.get(attribute_key);
    setFormsValues(attribute_key, current_value);
  });
}

function setRecycledFormCookies($form){
  $(recycyledFormAttributes).each(function(index, attribute_key){
    var input_name = wrapParamForRails(attribute_key);
    var target_ref = 'input[name='+input_name+']';
    var current_value = $form.find(target_ref).val();
    if(typeof current_value != "undefined"){
      Cookies.set(attribute_key, current_value);
    }
  });
}

$(document).ready(function(){
  HeaderFooterSignupOptions = {
    submitHandler: function(form) {
      _gaq.push(['_trackEvent', 'submit', 'email_signup']);
      $form = $(form);
      var saveURI = '{{ site.services_url }}/people';
      $.post(saveURI, $form.serialize());
      $form.hide();
      $form.next().removeClass('hidden');
    }
  }

  $("header form.email-signup").validate(HeaderFooterSignupOptions);
  $("footer form.email-signup").validate(HeaderFooterSignupOptions);

  setRecycledFormsInputValues($('form'))
  $('form').on('submit', function(){
    setRecycledFormCookies($(this));
    setRecycledFormsInputValues($('form'));
  });

  manageDataFromParams('utm_source');
  manageDataFromParams('utm_medium');
  manageDataFromParams('utm_campaign');
  manageDataFromParams('email', 'header form, footer form');

  var source_url = location.protocol + '//' + location.host + location.pathname;
  $('form').append('<input type="hidden" name="source_url" value="'+source_url+'">');

});<commit_msg>Prefill: ensure city is included<commit_after>function addCommas(nStr) {
  nStr += '';
  x = nStr.split('.');
  x1 = x[0];
  x2 = x.length > 1 ? '.' + x[1] : '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
  }
  return x1 + x2;
}

window.recycyledFormAttributes = ['email', 'first_name', 'last_name', 'phone', 'zip', 'city'];
function manageDataFromParams(source_key, skipped_forms_selector){
  var url_param = getParameterByName(source_key);
  if (url_param.length > 2){
    Cookies.set(source_key, getParameterByName(source_key), { expires: 7 });
  }
  var current_cookie_value = Cookies.get(source_key);
  setFormsValues(source_key, current_cookie_value, skipped_forms_selector)
}

function wrapParamForRails(param_key) {
  return param_key.replace(/(email|first_name|last_name|phone|zip|city)/, 'person\\[$1\\]');
}

function setFormsValues(source_key, target_value, skipped_forms_selector){
  if(typeof target_value != "undefined"){
    target_value = target_value.replace(' ','+');
    var $form = $('form').not(skipped_forms_selector);
    var input_name = wrapParamForRails(source_key);
    var target_ref = 'input[name='+input_name+'], input[name='+input_name+']';
    input_name = input_name.replace('\\[','[').replace('\\]',']')

    if($form.find(target_ref).length == 0){
      $form.append('<input type="hidden" name="'+input_name+'" value="'+target_value+'">');
    }else{
      $form.find(target_ref).val(target_value);
    }
  }
}

function setRecycledFormsInputValues($form){
  $(recycyledFormAttributes).each(function(index, attribute_key){
    var current_value = Cookies.get(attribute_key);
    setFormsValues(attribute_key, current_value);
  });
}

function setRecycledFormCookies($form){
  $(recycyledFormAttributes).each(function(index, attribute_key){
    var input_name = wrapParamForRails(attribute_key);
    var target_ref = 'input[name='+input_name+']';
    var current_value = $form.find(target_ref).val();
    if(typeof current_value != "undefined"){
      Cookies.set(attribute_key, current_value);
    }
  });
}

$(document).ready(function(){
  HeaderFooterSignupOptions = {
    submitHandler: function(form) {
      _gaq.push(['_trackEvent', 'submit', 'email_signup']);
      $form = $(form);
      var saveURI = '{{ site.services_url }}/people';
      $.post(saveURI, $form.serialize());
      $form.hide();
      $form.next().removeClass('hidden');
    }
  }

  $("header form.email-signup").validate(HeaderFooterSignupOptions);
  $("footer form.email-signup").validate(HeaderFooterSignupOptions);

  setRecycledFormsInputValues($('form'))
  $('form').on('submit', function(){
    setRecycledFormCookies($(this));
    setRecycledFormsInputValues($('form'));
  });

  manageDataFromParams('utm_source');
  manageDataFromParams('utm_medium');
  manageDataFromParams('utm_campaign');
  manageDataFromParams('email', 'header form, footer form');

  var source_url = location.protocol + '//' + location.host + location.pathname;
  $('form').append('<input type="hidden" name="source_url" value="'+source_url+'">');

});<|endoftext|>


<commit_before>// Copyright 2019-2020 Google LLC
//
// 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
//
//     https://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.

/**
 * This sample demonstrates how to perform basic operations on topics with
 * the Google Cloud Pub/Sub API.
 *
 * For more information, see the README.md under /pubsub and the documentation
 * at https://cloud.google.com/pubsub/docs.
 */

'use strict';

// sample-metadata:
//   title: Publish Message
//   description: Publishes a message to a topic.
//   usage: node publishMessage.js <topic-name-or-id> <data>

function main(
  topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID',
  data = JSON.stringify({foo: 'bar'})
) {
  // [START pubsub_publish_with_error_handler]
  // [START pubsub_quickstart_publisher]
  /**
   * TODO(developer): Uncomment these variables before running the sample.
   */
  // const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID';
  // const data = JSON.stringify({foo: 'bar'});

  // Imports the Google Cloud client library
  const {PubSub} = require('@google-cloud/pubsub');

  // Creates a client; cache this for further use
  const pubSubClient = new PubSub();

  async function publishMessage() {
    // Publishes the message as a string, e.g. "Hello, world!" or JSON.stringify(someObject)
    const dataBuffer = Buffer.from(data);

    try {
      const messageId = await pubSubClient
        .topic(topicNameOrId)
        .publish(dataBuffer);
      console.log(`Message ${messageId} published.`);
    } catch (error) {
      console.error(`Received error while publishing: ${error.message}`);
      process.exitCode = 1;
    }
  }

  publishMessage();
  // [END pubsub_publish_with_error_handler]
  // [END pubsub_quickstart_publisher]
}

process.on('unhandledRejection', err => {
  console.error(err.message);
  process.exitCode = 1;
});
main(...process.argv.slice(2));
<commit_msg>samples: topic publish() method is deprecated (#1522)<commit_after>// Copyright 2019-2020 Google LLC
//
// 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
//
//     https://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.

/**
 * This sample demonstrates how to perform basic operations on topics with
 * the Google Cloud Pub/Sub API.
 *
 * For more information, see the README.md under /pubsub and the documentation
 * at https://cloud.google.com/pubsub/docs.
 */

'use strict';

// sample-metadata:
//   title: Publish Message
//   description: Publishes a message to a topic.
//   usage: node publishMessage.js <topic-name-or-id> <data>

function main(
  topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID',
  data = JSON.stringify({foo: 'bar'})
) {
  // [START pubsub_publish_with_error_handler]
  // [START pubsub_quickstart_publisher]
  /**
   * TODO(developer): Uncomment these variables before running the sample.
   */
  // const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID';
  // const data = JSON.stringify({foo: 'bar'});

  // Imports the Google Cloud client library
  const {PubSub} = require('@google-cloud/pubsub');

  // Creates a client; cache this for further use
  const pubSubClient = new PubSub();

  async function publishMessage() {
    // Publishes the message as a string, e.g. "Hello, world!" or JSON.stringify(someObject)
    const dataBuffer = Buffer.from(data);

    try {
      const messageId = await pubSubClient
        .topic(topicNameOrId)
        .publishMessage({data: dataBuffer});
      console.log(`Message ${messageId} published.`);
    } catch (error) {
      console.error(`Received error while publishing: ${error.message}`);
      process.exitCode = 1;
    }
  }

  publishMessage();
  // [END pubsub_publish_with_error_handler]
  // [END pubsub_quickstart_publisher]
}

process.on('unhandledRejection', err => {
  console.error(err.message);
  process.exitCode = 1;
});
main(...process.argv.slice(2));
<|endoftext|>


<commit_before>function getBlockElement (el, parent) {
  if (parent && el === parent) {
    return null
  }

  const
    style = window.getComputedStyle
      ? window.getComputedStyle(el)
      : el.currentStyle,
    display = style.display

  if (display === 'block' || display === 'table') {
    return el
  }

  return getBlockElement(el.parentNode)
}

function isChildOf (el, parent) {
  if (!el) {
    return false
  }
  while ((el = el.parentNode)) {
    if (el === document.body) {
      return false
    }
    if (el === parent) {
      return true
    }
  }
  return false
}

const urlRegex = /^https?:\/\//

export class Caret {
  constructor (el, vm) {
    this.el = el
    this.vm = vm
  }

  get selection () {
    if (!this.el) {
      return
    }
    const sel = document.getSelection()
    // only when the selection in element
    if (isChildOf(sel.anchorNode, this.el) && isChildOf(sel.focusNode, this.el)) {
      return sel
    }
  }

  get hasSelection () {
    return this.selection
      ? this.selection.toString().length > 0
      : null
  }

  get range () {
    const sel = this.selection

    if (!sel) {
      return
    }

    return sel.rangeCount
      ? sel.getRangeAt(0)
      : null
  }

  get parent () {
    const range = this.range
    if (!range) {
      return
    }

    const node = range.startContainer
    return node.nodeType === document.ELEMENT_NODE
      ? node
      : node.parentNode
  }

  get blockParent () {
    const parent = this.parent
    if (!parent) {
      return
    }
    return getBlockElement(parent, this.el)
  }

  save (range = this.range) {
    this._range = range
  }

  restore (range = this._range) {
    const
      r = document.createRange(),
      sel = document.getSelection()

    if (range) {
      r.setStart(range.startContainer, range.startOffset)
      r.setEnd(range.endContainer, range.endOffset)
      sel.removeAllRanges()
      sel.addRange(r)
    }
    else {
      sel.selectAllChildren(this.el)
      sel.collapseToEnd()
    }
  }

  hasParent (name, spanLevel) {
    const el = spanLevel
      ? this.parent
      : this.blockParent

    return el
      ? el.nodeName.toLowerCase() === name.toLowerCase()
      : false
  }

  hasParents (list) {
    const el = this.parent
    return el
      ? list.includes(el.nodeName.toLowerCase())
      : false
  }

  is (cmd, param) {
    switch (cmd) {
      case 'formatBlock':
        if (param === 'DIV' && this.parent === this.el) {
          return true
        }
        return this.hasParent(param, param === 'PRE')
      case 'link':
        return this.hasParent('A', true)
      case 'fontSize':
        return document.queryCommandValue(cmd) === param
      case 'fontName':
        const res = document.queryCommandValue(cmd)
        return res === `"${param}"` || res === param
      case 'fullscreen':
        return this.vm.inFullscreen
      case 'viewsource':
        return this.vm.isViewingSource
      case void 0:
        return false
      default:
        const state = document.queryCommandState(cmd)
        return param ? state === param : state
    }
  }

  getParentAttribute (attrib) {
    if (this.parent) {
      return this.parent.getAttribute(attrib)
    }
  }

  can (name) {
    if (name === 'outdent') {
      return this.hasParents(['blockquote', 'li'])
    }
    if (name === 'indent') {
      const parentName = this.parent ? this.parent.nodeName.toLowerCase() : false
      if (parentName === 'blockquote') {
        return false
      }
      if (parentName === 'li') {
        const previousEl = this.parent.previousSibling
        return previousEl && previousEl.nodeName.toLowerCase() === 'li'
      }
      return false
    }
    if (name === 'link') {
      return this.selection || this.is('link')
    }
  }

  apply (cmd, param, done = () => {}) {
    if (cmd === 'formatBlock') {
      if (['BLOCKQUOTE', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6'].includes(param) && this.is(cmd, param)) {
        cmd = 'outdent'
        param = null
      }

      if (param === 'PRE' && this.is(cmd, 'PRE')) {
        param = 'P'
      }
    }
    else if (cmd === 'print') {
      done()
      const win = window.open()
      win.document.write(`
        <!doctype html>

            <title>Print - ${document.title}</title>

${this.el.innerHTML}

      `)
      win.print()
      win.close()
      return
    }
    else if (cmd === 'link') {
      const link = this.getParentAttribute('href')
      if (!link) {
        const selection = this.selectWord(this.selection)
        const url = selection ? selection.toString() : ''
        if (!url.length) {
          return
        }
        this.vm.editLinkUrl = urlRegex.test(url) ? url : 'https://'
        document.execCommand('createLink', false, this.vm.editLinkUrl)
      }
      else {
        this.vm.editLinkUrl = link
      }
      this.vm.$nextTick(() => {
        this.range.selectNodeContents(this.parent)
        this.save()
      })
      return
    }
    else if (cmd === 'fullscreen') {
      this.vm.toggleFullscreen()
      done()
      return
    }
    else if (cmd === 'viewsource') {
      this.vm.isViewingSource = !this.vm.isViewingSource
      this.vm.setContent(this.vm.value)
      done()
      return
    }

    if (this.vm.$q.platform.is.ie === true || this.vm.$q.platform.is.edge === true) {
      // workaround for IE/Edge, otherwise it messes up
      // the DOM of toolbar
      const dummyDiv = document.createElement('div')
      this.vm.$refs.content.appendChild(dummyDiv)
      document.execCommand(cmd, false, param)
      dummyDiv.remove()
    }
    else {
      document.execCommand(cmd, false, param)
    }

    done()
  }

  selectWord (sel) {
    if (!sel || !sel.isCollapsed) {
      return sel
    }

    // Detect if selection is backwards
    const range = document.createRange()
    range.setStart(sel.anchorNode, sel.anchorOffset)
    range.setEnd(sel.focusNode, sel.focusOffset)
    const direction = range.collapsed ? ['backward', 'forward'] : ['forward', 'backward']
    range.detach()

    // modify() works on the focus of the selection
    const
      endNode = sel.focusNode,
      endOffset = sel.focusOffset
    sel.collapse(sel.anchorNode, sel.anchorOffset)
    sel.modify('move', direction[0], 'character')
    sel.modify('move', direction[1], 'word')
    sel.extend(endNode, endOffset)
    sel.modify('extend', direction[1], 'character')
    sel.modify('extend', direction[0], 'word')

    return sel
  }
}
<commit_msg>fix(QEditor): small tweak related to previous commit<commit_after>function getBlockElement (el, parent) {
  if (parent && el === parent) {
    return null
  }

  const
    style = window.getComputedStyle
      ? window.getComputedStyle(el)
      : el.currentStyle,
    display = style.display

  if (display === 'block' || display === 'table') {
    return el
  }

  return getBlockElement(el.parentNode)
}

function isChildOf (el, parent) {
  if (!el) {
    return false
  }
  while ((el = el.parentNode)) {
    if (el === document.body) {
      return false
    }
    if (el === parent) {
      return true
    }
  }
  return false
}

const urlRegex = /^https?:\/\//

export class Caret {
  constructor (el, vm) {
    this.el = el
    this.vm = vm
  }

  get selection () {
    if (!this.el) {
      return
    }
    const sel = document.getSelection()
    // only when the selection in element
    if (isChildOf(sel.anchorNode, this.el) && isChildOf(sel.focusNode, this.el)) {
      return sel
    }
  }

  get hasSelection () {
    return this.selection
      ? this.selection.toString().length > 0
      : null
  }

  get range () {
    const sel = this.selection

    if (!sel) {
      return
    }

    return sel.rangeCount
      ? sel.getRangeAt(0)
      : null
  }

  get parent () {
    const range = this.range
    if (!range) {
      return
    }

    const node = range.startContainer
    return node.nodeType === document.ELEMENT_NODE
      ? node
      : node.parentNode
  }

  get blockParent () {
    const parent = this.parent
    if (!parent) {
      return
    }
    return getBlockElement(parent, this.el)
  }

  save (range = this.range) {
    this._range = range
  }

  restore (range = this._range) {
    const
      r = document.createRange(),
      sel = document.getSelection()

    if (range) {
      r.setStart(range.startContainer, range.startOffset)
      r.setEnd(range.endContainer, range.endOffset)
      sel.removeAllRanges()
      sel.addRange(r)
    }
    else {
      sel.selectAllChildren(this.el)
      sel.collapseToEnd()
    }
  }

  hasParent (name, spanLevel) {
    const el = spanLevel
      ? this.parent
      : this.blockParent

    return el
      ? el.nodeName.toLowerCase() === name.toLowerCase()
      : false
  }

  hasParents (list) {
    const el = this.parent
    return el
      ? list.includes(el.nodeName.toLowerCase())
      : false
  }

  is (cmd, param) {
    switch (cmd) {
      case 'formatBlock':
        if (param === 'DIV' && this.parent === this.el) {
          return true
        }
        return this.hasParent(param, param === 'PRE')
      case 'link':
        return this.hasParent('A', true)
      case 'fontSize':
        return document.queryCommandValue(cmd) === param
      case 'fontName':
        const res = document.queryCommandValue(cmd)
        return res === `"${param}"` || res === param
      case 'fullscreen':
        return this.vm.inFullscreen
      case 'viewsource':
        return this.vm.isViewingSource
      case void 0:
        return false
      default:
        const state = document.queryCommandState(cmd)
        return param ? state === param : state
    }
  }

  getParentAttribute (attrib) {
    if (this.parent) {
      return this.parent.getAttribute(attrib)
    }
  }

  can (name) {
    if (name === 'outdent') {
      return this.hasParents(['blockquote', 'li'])
    }
    if (name === 'indent') {
      const parentName = this.parent ? this.parent.nodeName.toLowerCase() : false
      if (parentName === 'blockquote') {
        return false
      }
      if (parentName === 'li') {
        const previousEl = this.parent.previousSibling
        return previousEl && previousEl.nodeName.toLowerCase() === 'li'
      }
      return false
    }
    if (name === 'link') {
      return this.selection || this.is('link')
    }
  }

  apply (cmd, param, done = () => {}) {
    if (cmd === 'formatBlock') {
      if (['BLOCKQUOTE', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6'].includes(param) && this.is(cmd, param)) {
        cmd = 'outdent'
        param = null
      }

      if (param === 'PRE' && this.is(cmd, 'PRE')) {
        param = 'P'
      }
    }
    else if (cmd === 'print') {
      done()
      const win = window.open()
      win.document.write(`
        <!doctype html>

            <title>Print - ${document.title}</title>

${this.el.innerHTML}

      `)
      win.print()
      win.close()
      return
    }
    else if (cmd === 'link') {
      const link = this.getParentAttribute('href')
      if (!link) {
        const selection = this.selectWord(this.selection)
        const url = selection ? selection.toString() : ''
        if (!url.length) {
          return
        }
        this.vm.editLinkUrl = urlRegex.test(url) ? url : 'https://'
        document.execCommand('createLink', false, this.vm.editLinkUrl)
      }
      else {
        this.vm.editLinkUrl = link
      }
      this.vm.$nextTick(() => {
        this.range.selectNodeContents(this.parent)
        this.save()
      })
      return
    }
    else if (cmd === 'fullscreen') {
      this.vm.toggleFullscreen()
      done()
      return
    }
    else if (cmd === 'viewsource') {
      this.vm.isViewingSource = !this.vm.isViewingSource
      this.vm.__setContent(this.vm.value)
      done()
      return
    }

    if (this.vm.$q.platform.is.ie === true || this.vm.$q.platform.is.edge === true) {
      // workaround for IE/Edge, otherwise it messes up
      // the DOM of toolbar
      const dummyDiv = document.createElement('div')
      this.vm.$refs.content.appendChild(dummyDiv)
      document.execCommand(cmd, false, param)
      dummyDiv.remove()
    }
    else {
      document.execCommand(cmd, false, param)
    }

    done()
  }

  selectWord (sel) {
    if (!sel || !sel.isCollapsed) {
      return sel
    }

    // Detect if selection is backwards
    const range = document.createRange()
    range.setStart(sel.anchorNode, sel.anchorOffset)
    range.setEnd(sel.focusNode, sel.focusOffset)
    const direction = range.collapsed ? ['backward', 'forward'] : ['forward', 'backward']
    range.detach()

    // modify() works on the focus of the selection
    const
      endNode = sel.focusNode,
      endOffset = sel.focusOffset
    sel.collapse(sel.anchorNode, sel.anchorOffset)
    sel.modify('move', direction[0], 'character')
    sel.modify('move', direction[1], 'word')
    sel.extend(endNode, endOffset)
    sel.modify('extend', direction[1], 'character')
    sel.modify('extend', direction[0], 'word')

    return sel
  }
}
<|endoftext|>


<commit_before>import { h, ref, onUnmounted, Teleport } from 'vue'

import { noop } from '../../utils/event.js'
import { addFocusWaitFlag, removeFocusWaitFlag } from '../../utils/private/focus-manager.js'
import { createGlobalNode, removeGlobalNode } from '../../utils/private/global-nodes.js'
import { portalList } from '../../utils/private/portal.js'

function isOnGlobalDialog (vm) {
  vm = vm.parent

  while (vm !== void 0 && vm !== null) {
    if (vm.type.name === 'QGlobalDialog') {
      return true
    }
    if (vm.type.name === 'QDialog' || vm.type.name === 'QMenu') {
      return false
    }

    vm = vm.parent
  }

  return false
}

// Warning!
// You MUST specify "inheritAttrs: false" in your component

export default function (vm, innerRef, renderPortalContent, checkGlobalDialog) {
  const portalIsActive = ref(false)

  if (__QUASAR_SSR_SERVER__) {
    return {
      portalIsActive,

      showPortal: noop,
      hidePortal: noop,
      renderPortal: noop
    }
  }

  let portalEl = null
  const focusObj = {}
  const onGlobalDialog = checkGlobalDialog === true && isOnGlobalDialog(vm)

  function showPortal (isReady) {
    if (isReady === true) {
      removeFocusWaitFlag(focusObj)
      return
    }

    if (onGlobalDialog === false && portalEl === null) {
      portalEl = createGlobalNode()
    }

    portalIsActive.value = true

    // register portal
    portalList.push(vm.proxy)

    addFocusWaitFlag(focusObj)
  }

  function hidePortal () {
    removeFocusWaitFlag(focusObj)
    portalIsActive.value = false

    // unregister portal
    const index = portalList.indexOf(vm.proxy)
    if (index > -1) {
      portalList.splice(index, 1)
    }

    if (portalEl !== null) {
      removeGlobalNode(portalEl)
      portalEl = null
    }
  }

  onUnmounted(hidePortal)

  // expose publicly needed stuff for portal utils
  Object.assign(vm.proxy, { __qPortalInnerRef: innerRef })

  return {
    showPortal,
    hidePortal,

    portalIsActive,

    renderPortal: () => (
      onGlobalDialog === true
        ? renderPortalContent()
        : (
            portalIsActive.value === true
              ? [ h(Teleport, { to: portalEl }, renderPortalContent()) ]
              : void 0
          )
    )
  }
}
<commit_msg>fix(ui/portal): avoid registering portal multiple times #11767<commit_after>import { h, ref, onUnmounted, Teleport } from 'vue'

import { noop } from '../../utils/event.js'
import { addFocusWaitFlag, removeFocusWaitFlag } from '../../utils/private/focus-manager.js'
import { createGlobalNode, removeGlobalNode } from '../../utils/private/global-nodes.js'
import { portalList } from '../../utils/private/portal.js'

function isOnGlobalDialog (vm) {
  vm = vm.parent

  while (vm !== void 0 && vm !== null) {
    if (vm.type.name === 'QGlobalDialog') {
      return true
    }
    if (vm.type.name === 'QDialog' || vm.type.name === 'QMenu') {
      return false
    }

    vm = vm.parent
  }

  return false
}

// Warning!
// You MUST specify "inheritAttrs: false" in your component

export default function (vm, innerRef, renderPortalContent, checkGlobalDialog) {
  const portalIsActive = ref(false)

  if (__QUASAR_SSR_SERVER__) {
    return {
      portalIsActive,

      showPortal: noop,
      hidePortal: noop,
      renderPortal: noop
    }
  }

  let portalEl = null
  const focusObj = {}
  const onGlobalDialog = checkGlobalDialog === true && isOnGlobalDialog(vm)

  function showPortal (isReady) {
    if (isReady === true) {
      // console.log('remove 1')
      removeFocusWaitFlag(focusObj)
      return
    }

    if (portalIsActive.value === false) {
      if (onGlobalDialog === false && portalEl === null) {
        portalEl = createGlobalNode()
      }

      portalIsActive.value = true

      // register portal
      portalList.push(vm.proxy)

      // console.log('add 1')
      addFocusWaitFlag(focusObj)
    }
  }

  function hidePortal () {
    removeFocusWaitFlag(focusObj)
    portalIsActive.value = false

    // unregister portal
    const index = portalList.indexOf(vm.proxy)
    if (index > -1) {
      portalList.splice(index, 1)
    }

    if (portalEl !== null) {
      removeGlobalNode(portalEl)
      portalEl = null
    }
  }

  onUnmounted(hidePortal)

  // expose publicly needed stuff for portal utils
  Object.assign(vm.proxy, { __qPortalInnerRef: innerRef })

  return {
    showPortal,
    hidePortal,

    portalIsActive,

    renderPortal: () => (
      onGlobalDialog === true
        ? renderPortalContent()
        : (
            portalIsActive.value === true
              ? [ h(Teleport, { to: portalEl }, renderPortalContent()) ]
              : void 0
          )
    )
  }
}
<|endoftext|>


<commit_before>import React, {PropTypes} from 'react'
import buildInfluxQLQuery from 'utils/influxql'
import AutoRefresh from 'shared/components/AutoRefresh'
import LineGraph from 'shared/components/LineGraph'
import TimeRangeDropdown from 'shared/components/TimeRangeDropdown'
import underlayCallback from 'src/kapacitor/helpers/ruleGraphUnderlay'

const RefreshingLineGraph = AutoRefresh(LineGraph)

const {shape, string, func} = PropTypes
const RuleGraph = ({
  query,
  source,
  timeRange: {lower},
  timeRange,
  rule,
  onChooseTimeRange,
}) => {
  const autoRefreshMs = 30000
  const queryText = buildInfluxQLQuery({lower}, query)
  const queries = [{host: source.links.proxy, text: queryText}]
  const kapacitorLineColors = ['#4ED8A0']

  if (!queryText) {
    return (

          Select a Time-Series to preview on a graph

    )
  }

  return (

Preview Data from

        <TimeRangeDropdown
          onChooseTimeRange={onChooseTimeRange}
          selected={timeRange}
          preventCustomTimeRange={true}
        />

      <RefreshingLineGraph
        queries={queries}
        isGraphFilled={false}
        ruleValues={rule.values}
        autoRefresh={autoRefreshMs}
        overrideLineColors={kapacitorLineColors}
        underlayCallback={underlayCallback(rule)}
      />

  )
}

RuleGraph.propTypes = {
  source: shape({
    links: shape({
      proxy: string.isRequired,
    }).isRequired,
  }).isRequired,
  query: shape({}).isRequired,
  rule: shape({}).isRequired,
  timeRange: shape({}).isRequired,
  onChooseTimeRange: func.isRequired,
}

export default RuleGraph
<commit_msg>RuleGraph is always in view<commit_after>import React, {PropTypes} from 'react'
import buildInfluxQLQuery from 'utils/influxql'
import AutoRefresh from 'shared/components/AutoRefresh'
import LineGraph from 'shared/components/LineGraph'
import TimeRangeDropdown from 'shared/components/TimeRangeDropdown'
import underlayCallback from 'src/kapacitor/helpers/ruleGraphUnderlay'

const RefreshingLineGraph = AutoRefresh(LineGraph)

const {shape, string, func} = PropTypes
const RuleGraph = ({
  query,
  source,
  timeRange: {lower},
  timeRange,
  rule,
  onChooseTimeRange,
}) => {
  const autoRefreshMs = 30000
  const queryText = buildInfluxQLQuery({lower}, query)
  const queries = [{host: source.links.proxy, text: queryText}]
  const kapacitorLineColors = ['#4ED8A0']

  if (!queryText) {
    return (

          Select a Time-Series to preview on a graph

    )
  }

  return (

Preview Data from

        <TimeRangeDropdown
          onChooseTimeRange={onChooseTimeRange}
          selected={timeRange}
          preventCustomTimeRange={true}
        />

      <RefreshingLineGraph
        queries={queries}
        inView={true}
        isGraphFilled={false}
        ruleValues={rule.values}
        autoRefresh={autoRefreshMs}
        overrideLineColors={kapacitorLineColors}
        underlayCallback={underlayCallback(rule)}
      />

  )
}

RuleGraph.propTypes = {
  source: shape({
    links: shape({
      proxy: string.isRequired,
    }).isRequired,
  }).isRequired,
  query: shape({}).isRequired,
  rule: shape({}).isRequired,
  timeRange: shape({}).isRequired,
  onChooseTimeRange: func.isRequired,
}

export default RuleGraph
<|endoftext|>


<commit_before>import React, {PropTypes} from 'react'
import {OPERATORS} from 'src/kapacitor/constants'
import Dropdown from 'shared/components/Dropdown'

const mapToItems = (arr, type) => arr.map(text => ({text, type}))
const operators = mapToItems(OPERATORS, 'operator')

const Threshold = ({
  rule: {values: {operator, value, rangeValue}},
  query,
  onDropdownChange,
  onRuleTypeInputChange,
}) =>

Send Alert where

      {query.fields.length ? query.fields[0].field : 'Select a Time-Series'}

is

    <Dropdown
      className="dropdown-180"
      menuClass="dropdown-malachite"
      items={operators}
      selected={operator}
      onChoose={onDropdownChange}
    />
    <form style={{display: 'flex'}}>
      <input
        className="form-control input-sm form-malachite monotype"
        style={{width: '160px', marginLeft: '6px'}}
        type="text"
        name="lower"
        spellCheck="false"
        value={value}
        onChange={onRuleTypeInputChange}
        placeholder={
          operator === 'inside range' || operator === 'outside range'
            ? 'Lower'
            : null
        }
      />
      {(operator === 'inside range' || operator === 'outside range') &&
        <input
          className="form-control input-sm form-malachite monotype"
          name="upper"
          style={{width: '160px'}}
          placeholder="Upper"
          type="text"
          spellCheck="false"
          value={rangeValue}
          onChange={onRuleTypeInputChange}
        />}
    </form>

const {shape, string, func} = PropTypes

Threshold.propTypes = {
  rule: shape({
    values: shape({
      operator: string,
      rangeOperator: string,
      value: string,
      rangeValue: string,
    }),
  }),
  onDropdownChange: func.isRequired,
  onRuleTypeInputChange: func.isRequired,
  query: shape({}).isRequired,
}

export default Threshold
<commit_msg>Prevent form submit onEnter<commit_after>import React, {PropTypes} from 'react'
import {OPERATORS} from 'src/kapacitor/constants'
import Dropdown from 'shared/components/Dropdown'

const mapToItems = (arr, type) => arr.map(text => ({text, type}))
const operators = mapToItems(OPERATORS, 'operator')
const noopSubmit = e => e.preventDefault()

const Threshold = ({
  rule: {values: {operator, value, rangeValue}},
  query,
  onDropdownChange,
  onRuleTypeInputChange,
}) =>

Send Alert where

      {query.fields.length ? query.fields[0].field : 'Select a Time-Series'}

is

    <Dropdown
      className="dropdown-180"
      menuClass="dropdown-malachite"
      items={operators}
      selected={operator}
      onChoose={onDropdownChange}
    />
    <form style={{display: 'flex'}} onSubmit={noopSubmit}>
      <input
        className="form-control input-sm form-malachite monotype"
        style={{width: '160px', marginLeft: '6px'}}
        type="text"
        name="lower"
        spellCheck="false"
        value={value}
        onChange={onRuleTypeInputChange}
        placeholder={
          operator === 'inside range' || operator === 'outside range'
            ? 'Lower'
            : null
        }
      />
      {(operator === 'inside range' || operator === 'outside range') &&
        <input
          className="form-control input-sm form-malachite monotype"
          name="upper"
          style={{width: '160px'}}
          placeholder="Upper"
          type="text"
          spellCheck="false"
          value={rangeValue}
          onChange={onRuleTypeInputChange}
        />}
    </form>

const {shape, string, func} = PropTypes

Threshold.propTypes = {
  rule: shape({
    values: shape({
      operator: string,
      rangeOperator: string,
      value: string,
      rangeValue: string,
    }),
  }),
  onDropdownChange: func.isRequired,
  onRuleTypeInputChange: func.isRequired,
  query: shape({}).isRequired,
}

export default Threshold
<|endoftext|>


<commit_before>'use strict';

var map        = require('es5-ext/object/map')
  , isCallable = require('es5-ext/object/is-callable')
  , validValue = require('es5-ext/object/valid-value')
  , contains   = require('es5-ext/string/#/contains')

  , call = Function.prototype.call
  , defineProperty = Object.defineProperty
  , getPrototypeOf = Object.getPrototypeOf
  , hasOwnProperty = Object.prototype.hasOwnProperty
  , cacheDesc = { configurable: false, enumerable: false, writable: false,
		value: null }
  , define;

define = function (name, options) {
	var value, dgs, cacheName, desc, writable = false, resolvable
	  , flat;
	options = Object(validValue(options));
	cacheName = options.cacheName;
	flat = options.flat;
	if (cacheName == null) cacheName = name;
	delete options.cacheName;
	value = options.value;
	resolvable = isCallable(value);
	delete options.value;
	dgs = { configurable: Boolean(options.configurable),
		enumerable: Boolean(options.enumerable) };
	if (name !== cacheName) {
		dgs.get = function () {
			if (hasOwnProperty.call(this, cacheName)) return this[cacheName];
			cacheDesc.value = resolvable ? call.call(value, this, options) : value;
			cacheDesc.writable = writable;
			defineProperty(this, cacheName, cacheDesc);
			cacheDesc.value = null;
			if (desc) defineProperty(this, name, desc);
			return this[cacheName];
		};
	} else if (!flat) {
		dgs.get = function () {
			if (hasOwnProperty.call(this, name)) return value;
			desc.value = resolvable ? call.call(value, this, options) : value;
			defineProperty(this, name, desc);
			desc.value = null;
			return this[name];
		};
	} else {
		dgs.get = function () {
			var base = this;
			while (!hasOwnProperty.call(base, name)) base = getPrototypeOf(base);
			desc.value = resolvable ? call.call(value, base, options) : value;
			defineProperty(base, name, desc);
			desc.value = null;
			return base[name];
		};
	}
	dgs.set = function (value) {
		dgs.get.call(this);
		this[cacheName] = value;
	};
	if (options.desc) {
		desc = {
			configurable: contains.call(options.desc, 'c'),
			enumerable: contains.call(options.desc, 'e')
		};
		if (cacheName === name) {
			desc.writable = contains.call(options.desc, 'w');
			desc.value = null;
		} else {
			writable = contains.call(options.desc, 'w');
			desc.get = dgs.get;
			desc.set = dgs.set;
		}
		delete options.desc;
	} else if (cacheName === name) {
		desc = {
			configurable: Boolean(options.configurable),
			enumerable: Boolean(options.enumerable),
			writable: Boolean(options.writable),
			value: null
		};
	}
	delete options.configurable;
	delete options.enumerable;
	delete options.writable;
	return dgs;
};

module.exports = function (props) {
	return map(props, function (desc, name) { return define(name, desc); });
};
<commit_msg>Add fix for getter/value resolution bug in Safari<commit_after>'use strict';

var map        = require('es5-ext/object/map')
  , isCallable = require('es5-ext/object/is-callable')
  , validValue = require('es5-ext/object/valid-value')
  , contains   = require('es5-ext/string/#/contains')

  , call = Function.prototype.call
  , defineProperty = Object.defineProperty
  , getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor
  , getPrototypeOf = Object.getPrototypeOf
  , hasOwnProperty = Object.prototype.hasOwnProperty
  , cacheDesc = { configurable: false, enumerable: false, writable: false,
		value: null }
  , define;

define = function (name, options) {
	var value, dgs, cacheName, desc, writable = false, resolvable
	  , flat;
	options = Object(validValue(options));
	cacheName = options.cacheName;
	flat = options.flat;
	if (cacheName == null) cacheName = name;
	delete options.cacheName;
	value = options.value;
	resolvable = isCallable(value);
	delete options.value;
	dgs = { configurable: Boolean(options.configurable),
		enumerable: Boolean(options.enumerable) };
	if (name !== cacheName) {
		dgs.get = function () {
			if (hasOwnProperty.call(this, cacheName)) return this[cacheName];
			cacheDesc.value = resolvable ? call.call(value, this, options) : value;
			cacheDesc.writable = writable;
			defineProperty(this, cacheName, cacheDesc);
			cacheDesc.value = null;
			if (desc) defineProperty(this, name, desc);
			return this[cacheName];
		};
	} else if (!flat) {
		dgs.get = function self() {
			var ownDesc;
			if (hasOwnProperty.call(this, name)) {
				ownDesc = getOwnPropertyDescriptor(this, name);
				// It happens in Safari, that getter is still called after property
				// was defined with a value, following workarounds that
				if (ownDesc.hasOwnProperty('value')) return ownDesc.value;
				if ((typeof ownDesc.get === 'function') && (ownDesc.get !== self)) {
					return ownDesc.get.call(this);
				}
				return value;
			}
			desc.value = resolvable ? call.call(value, this, options) : value;
			defineProperty(this, name, desc);
			desc.value = null;
			return this[name];
		};
	} else {
		dgs.get = function self() {
			var base = this, ownDesc;
			if (hasOwnProperty.call(this, name)) {
				// It happens in Safari, that getter is still called after property
				// was defined with a value, following workarounds that
				ownDesc = getOwnPropertyDescriptor(this, name);
				if (ownDesc.hasOwnProperty('value')) return ownDesc.value;
				if ((typeof ownDesc.get === 'function') && (ownDesc.get !== self)) {
					return ownDesc.get.call(this);
				}
			}
			while (!hasOwnProperty.call(base, name)) base = getPrototypeOf(base);
			desc.value = resolvable ? call.call(value, base, options) : value;
			defineProperty(base, name, desc);
			desc.value = null;
			return base[name];
		};
	}
	dgs.set = function (value) {
		dgs.get.call(this);
		this[cacheName] = value;
	};
	if (options.desc) {
		desc = {
			configurable: contains.call(options.desc, 'c'),
			enumerable: contains.call(options.desc, 'e')
		};
		if (cacheName === name) {
			desc.writable = contains.call(options.desc, 'w');
			desc.value = null;
		} else {
			writable = contains.call(options.desc, 'w');
			desc.get = dgs.get;
			desc.set = dgs.set;
		}
		delete options.desc;
	} else if (cacheName === name) {
		desc = {
			configurable: Boolean(options.configurable),
			enumerable: Boolean(options.enumerable),
			writable: Boolean(options.writable),
			value: null
		};
	}
	delete options.configurable;
	delete options.enumerable;
	delete options.writable;
	return dgs;
};

module.exports = function (props) {
	return map(props, function (desc, name) { return define(name, desc); });
};
<|endoftext|>


<commit_before>var mongo = require('mongodb');
var moment = require('moment');
var math = require('mathjs')();
var Wunderground = require('node-weatherunderground');

exports.weather = function (context, entities) {
  var api = new Wunderground(process.env.WUNDERGROUND_KEY, entities.location.value);
  api.conditions('', function (err, data) {
    if (err) throw err;

    console.log(data);
    var time = moment(data.observation_epoch * 1000).fromNow();
    var msg = data.display_location.full + ' is ' + data.weather + ' and ' + data.temp_f + 'F ' + ' with ' + data.wind_mph + 'MPH winds, updated ' + time + '. Provided by Weather Underground';
    exports.reply(context, msg, data.icon_url || ':sunny:');
  });
};

exports.fixed = function (context, entities) {
  exports.reply(context, entities.response ? entities.response.value : "Are you tryina' be funny, punk?");
};

exports.echo = function (context, entities) {
  exports.reply(context, entities.message_body ? entities.message_body.value : "Okay, I didn't catch that.");
};

var greetings = ['Hey!', 'Howdy!', "'sup?", 'Yo!', 'Hey dude', "What's good?", 'Hey'];
exports.hey = function (context, entities) {
  exports.reply(context, greetings[Math.floor(Math.random() * greetings.length)]);
};

exports.ping = function (context, entities) {
  exports.reply(context, "Pong! I'm alive :)");
};

exports.time = function (context, entities) {
  if (entities && entities.assertion) {
    var from = moment(entities.assertion.value.from),
        to   = moment(entities.assertion.value.to),
        now  = moment();

    if (from.isAfter(now)) {
      exports.reply(context, "It's not " + entities.assertion.body + " for " + from.fromNow(true) + " :(");
    } else if (to.isBefore(now)) {
      exports.reply(context, "It was " + entities.assertion.body + " like " + from.fromNow() + " :(");
    } else {
      exports.reply(context, "It's " + entities.assertion.body + " already, and for " + to.fromNow(true) + "!");
    }

  } else {
    var now  = moment(),
        time = now.format('h:mm:ss a'),
        date = now.format('dddd, MMMM Do, YYYY');

    exports.reply(context, "It's " + time + " on " + date);
  }
};

exports.simple_math = function (context, entities) {
  var expr = entities.math_expression.body;

  try {
    exports.reply(context, expr + ' = ' + math.eval(expr));
  } catch (ex) {
    exports.reply(context, expr + ': ' + ex.message);
  }
};

mongo.connect(process.env.MONGOLAB_URI, {}, function(error, db) {
  console.log('MongoLAB connected:', error);
  db.collection('users', function (err, users) {
    exports._users = users;

    exports.set_service_username = function (context, entities) {
      if (!entities.service) {
        return exports.reply(context, 'Dude name a service');
      } else if (!entities.username) {
        return exports.reply(context, "I didn't catch your username");
      }

      var doc = { user_id: context.user_id, user_name: context.user_name };
      doc['usernames.' + entities.service.value] = entities.username.value;

      users.update({user_id: context.user_id}, {$set:doc}, {upsert: true}, function (err, item) {
        if (err) {
          exports.reply(context, 'Error saving to mongo :(');
          console.log(err);
        } else {
          exports.reply(context, 'I gotcha, @' + context.user_name + '! ' +
              entities.username.value + ' on ' + entities.service.value);
        }
      });
    };

    exports.get_identity = function (context, entities) {
      users.findOne({user_id: context.user_id}, function (err, item) {
        if (err) {
          exports.reply(context, 'Error reading from mongo :(');
          console.log(err);
        } else if (!item || !item.usernames) {
          exports.reply(context, "I have no dirt on you, bro.");
        } else if (!entities.service) {
          exports.reply(context, "Your accounts: " + JSON.stringify(item.usernames));
        } else if (!item.usernames[entities.service.value]) {
          exports.reply(context, "You never told me your " + entities.service.value);
        } else {
          exports.reply(context, "Your " + entities.service.value + " is " + item.usernames[entities.service.value]);
        }
      });
    };

    exports.get_someones_username = function (context, entities) {
      if (!entities.service) {
        return exports.reply(context, 'Dude what service?');
      } else if (!entities.username) {
        return exports.reply(context, "I didn't catch a username");
      }

      users.findOne({user_name: entities.username.value}, function (err, item) {
        if (err) {
          exports.reply(context, 'Error reading from mongo :(');
          console.log(err);
        } else if (!item || !item.usernames) {
          exports.reply(context, "I have no dirt on " + entities.username.value + ", bro.");
        } else if (!item.usernames[entities.service.value]) {
          exports.reply(context, "No idea what " + entities.username.value + "'s " + entities.service.value + " is.");
        } else {
          exports.reply(context, entities.username.value + "'s " + entities.service.value + " is " + item.usernames[entities.service.value]);
        }
      });
    };

    exports.play_history = function (context, entities) {
      var username = entities.username ? entities.username.value : context.user_name;

      users.findOne({user_name: username}, function (err, item) {
        if (err) {
          res.send('Error reading from mongo!');
          console.log(err);
        } else if (!item || !item.usernames) {
          res.send("I have no dirt on " + username + ", bro.");
        } else if (!item.usernames['lastfm'] && !item.usernames['listensws']) {
          res.send("No idea what " + username + "'s lastfm or listens.ws usernames are.");
        } else if (item.usernames['lastfm']) {
          require('./last').lastfm(item.usernames['lastfm'], function (text, img) {
            exports.reply(context, username + " was listening to " + text, img || ':cd:');
          });
        } else if (item.usernames['listensws']) {
          require('./last').listensws(item.usernames['listensws'], function (text, img) {
            exports.reply(context, username + " was listening to " + text, img || ':cd:');
          });
        }
      });
    }
  });
});
<commit_msg>Handle null weather results<commit_after>var mongo = require('mongodb');
var moment = require('moment');
var math = require('mathjs')();
var Wunderground = require('node-weatherunderground');

exports.weather = function (context, entities) {
  var api = new Wunderground(process.env.WUNDERGROUND_KEY, entities.location.value);
  api.conditions('', function (err, data) {
    if (err) throw err;

    if (data) {
      console.log(data);
      var time = moment(data.observation_epoch * 1000).fromNow();
      var msg = data.display_location.full + ' is ' + data.weather + ' and ' + data.temp_f + 'F ' + ' with ' + data.wind_mph + 'MPH winds, updated ' + time + '. Provided by Weather Underground';
      exports.reply(context, msg, data.icon_url || ':sunny:');
    } else {
      exports.reply(context, 'My sources have no idea where you are asking about.');
    }
  });
};

exports.fixed = function (context, entities) {
  exports.reply(context, entities.response ? entities.response.value : "Are you tryina' be funny, punk?");
};

exports.echo = function (context, entities) {
  exports.reply(context, entities.message_body ? entities.message_body.value : "Okay, I didn't catch that.");
};

var greetings = ['Hey!', 'Howdy!', "'sup?", 'Yo!', 'Hey dude', "What's good?", 'Hey'];
exports.hey = function (context, entities) {
  exports.reply(context, greetings[Math.floor(Math.random() * greetings.length)]);
};

exports.ping = function (context, entities) {
  exports.reply(context, "Pong! I'm alive :)");
};

exports.time = function (context, entities) {
  if (entities && entities.assertion) {
    var from = moment(entities.assertion.value.from),
        to   = moment(entities.assertion.value.to),
        now  = moment();

    if (from.isAfter(now)) {
      exports.reply(context, "It's not " + entities.assertion.body + " for " + from.fromNow(true) + " :(");
    } else if (to.isBefore(now)) {
      exports.reply(context, "It was " + entities.assertion.body + " like " + from.fromNow() + " :(");
    } else {
      exports.reply(context, "It's " + entities.assertion.body + " already, and for " + to.fromNow(true) + "!");
    }

  } else {
    var now  = moment(),
        time = now.format('h:mm:ss a'),
        date = now.format('dddd, MMMM Do, YYYY');

    exports.reply(context, "It's " + time + " on " + date);
  }
};

exports.simple_math = function (context, entities) {
  var expr = entities.math_expression.body;

  try {
    exports.reply(context, expr + ' = ' + math.eval(expr));
  } catch (ex) {
    exports.reply(context, expr + ': ' + ex.message);
  }
};

mongo.connect(process.env.MONGOLAB_URI, {}, function(error, db) {
  console.log('MongoLAB connected:', error);
  db.collection('users', function (err, users) {
    exports._users = users;

    exports.set_service_username = function (context, entities) {
      if (!entities.service) {
        return exports.reply(context, 'Dude name a service');
      } else if (!entities.username) {
        return exports.reply(context, "I didn't catch your username");
      }

      var doc = { user_id: context.user_id, user_name: context.user_name };
      doc['usernames.' + entities.service.value] = entities.username.value;

      users.update({user_id: context.user_id}, {$set:doc}, {upsert: true}, function (err, item) {
        if (err) {
          exports.reply(context, 'Error saving to mongo :(');
          console.log(err);
        } else {
          exports.reply(context, 'I gotcha, @' + context.user_name + '! ' +
              entities.username.value + ' on ' + entities.service.value);
        }
      });
    };

    exports.get_identity = function (context, entities) {
      users.findOne({user_id: context.user_id}, function (err, item) {
        if (err) {
          exports.reply(context, 'Error reading from mongo :(');
          console.log(err);
        } else if (!item || !item.usernames) {
          exports.reply(context, "I have no dirt on you, bro.");
        } else if (!entities.service) {
          exports.reply(context, "Your accounts: " + JSON.stringify(item.usernames));
        } else if (!item.usernames[entities.service.value]) {
          exports.reply(context, "You never told me your " + entities.service.value);
        } else {
          exports.reply(context, "Your " + entities.service.value + " is " + item.usernames[entities.service.value]);
        }
      });
    };

    exports.get_someones_username = function (context, entities) {
      if (!entities.service) {
        return exports.reply(context, 'Dude what service?');
      } else if (!entities.username) {
        return exports.reply(context, "I didn't catch a username");
      }

      users.findOne({user_name: entities.username.value}, function (err, item) {
        if (err) {
          exports.reply(context, 'Error reading from mongo :(');
          console.log(err);
        } else if (!item || !item.usernames) {
          exports.reply(context, "I have no dirt on " + entities.username.value + ", bro.");
        } else if (!item.usernames[entities.service.value]) {
          exports.reply(context, "No idea what " + entities.username.value + "'s " + entities.service.value + " is.");
        } else {
          exports.reply(context, entities.username.value + "'s " + entities.service.value + " is " + item.usernames[entities.service.value]);
        }
      });
    };

    exports.play_history = function (context, entities) {
      var username = entities.username ? entities.username.value : context.user_name;

      users.findOne({user_name: username}, function (err, item) {
        if (err) {
          res.send('Error reading from mongo!');
          console.log(err);
        } else if (!item || !item.usernames) {
          res.send("I have no dirt on " + username + ", bro.");
        } else if (!item.usernames['lastfm'] && !item.usernames['listensws']) {
          res.send("No idea what " + username + "'s lastfm or listens.ws usernames are.");
        } else if (item.usernames['lastfm']) {
          require('./last').lastfm(item.usernames['lastfm'], function (text, img) {
            exports.reply(context, username + " was listening to " + text, img || ':cd:');
          });
        } else if (item.usernames['listensws']) {
          require('./last').listensws(item.usernames['listensws'], function (text, img) {
            exports.reply(context, username + " was listening to " + text, img || ':cd:');
          });
        }
      });
    }
  });
});
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { compose } from 'redux';

import DownloadFirefoxButton from 'amo/components/DownloadFirefoxButton';
import Link from 'amo/components/Link';
import SearchForm from 'amo/components/SearchForm';
import SectionLinks from 'amo/components/SectionLinks';
import AuthenticateButton, {
  createHandleLogOutFunction,
} from 'core/components/AuthenticateButton';
import { isAuthenticated, selectDisplayName } from 'core/reducers/user';
import { VIEW_CONTEXT_HOME } from 'core/constants';
import translate from 'core/i18n/translate';
import Icon from 'ui/components/Icon';
import DropdownMenu from 'ui/components/DropdownMenu';
import DropdownMenuItem from 'ui/components/DropdownMenuItem';

import './styles.scss';

export class HeaderBase extends React.Component {
  static propTypes = {
    api: PropTypes.object.isRequired,
    displayName: PropTypes.string,
    handleLogOut: PropTypes.func.isRequired,
    i18n: PropTypes.object.isRequired,
    isAuthenticated: PropTypes.bool.isRequired,
    isHomePage: PropTypes.bool.isRequired,
    location: PropTypes.object.isRequired,
    query: PropTypes.string.isRequired,
    username: PropTypes.string,
  }

  static defaultProps = {
    isHomePage: false,
    query: '',
  }

  handleLogOut = (event) => {
    event.preventDefault();

    this.props.handleLogOut({ api: this.props.api });
  }

  render() {
    const {
      displayName,
      i18n,
      isHomePage,
      location,
      query,
      username,
    } = this.props;

    const headerLink = (
      <Link className="Header-title" to="/">
        <Icon className="Header-addons-icon" name="fox" />
        {
          // translators: "Firefox" should not be translated. :-)
          i18n.gettext('Firefox Add-ons')
        }
      </Link>
    );

    return (

          {isHomePage
            ?
{headerLink}

            : headerLink}

        <SectionLinks className="Header-SectionLinks" location={location} />

          <Link
            className="Header-developer-hub-link Header-button"
            href="/developers/"
            external
            prependClientApp={false}
          >
            {i18n.gettext('Developer Hub')}
          </Link>
          <DownloadFirefoxButton
            className="Header-download-button Header-button"
          />

          {this.props.isAuthenticated ? (
            <DropdownMenu
              text={displayName}
              className="Header-authenticate-button Header-button"
            >
              <DropdownMenuItem>{i18n.gettext('My Account')}</DropdownMenuItem>
              <DropdownMenuItem>
                <Link href={`/user/${username}/`}>
                  {i18n.gettext('View Profile')}
                </Link>
              </DropdownMenuItem>
              <DropdownMenuItem>
                <Link href="/users/edit">
                  {i18n.gettext('Edit Profile')}
                </Link>
              </DropdownMenuItem>

              <DropdownMenuItem>{i18n.gettext('Tools')}</DropdownMenuItem>
              <DropdownMenuItem>
                <Link
                  href="/developers/addon/submit/distribution"
                  prependClientApp={false}
                >
                  {i18n.gettext('Submit a New Add-on')}
                </Link>
              </DropdownMenuItem>
              <DropdownMenuItem>
                <Link
                  href="/developers/theme/submit"
                  prependClientApp={false}
                >
                  {i18n.gettext('Submit a New Theme')}
                </Link>
              </DropdownMenuItem>
              <DropdownMenuItem>
                <Link
                  href="/developers/addon/api/key/"
                  prependClientApp={false}
                >
                  {i18n.gettext('Manage API Keys')}
                </Link>
              </DropdownMenuItem>

              <DropdownMenuItem
                className={'Header-logout-button'}
                detached
                onClick={this.handleLogOut}
              >
                {i18n.gettext('Log out')}
              </DropdownMenuItem>
            </DropdownMenu>
          ) : (
            <AuthenticateButton
              className="Header-authenticate-button Header-button Button--action
              Button--outline-only Button--small"
              location={location}
              noIcon
            />
          )}

        <SearchForm
          className="Header-search-form"
          pathname="/search/"
          query={query}
        />

    );
  }
}

export const mapStateToProps = (state) => {
  return {
    api: state.api,
    displayName: selectDisplayName(state),
    isHomePage: state.viewContext.context === VIEW_CONTEXT_HOME,
    isAuthenticated: isAuthenticated(state),
    username: state.user.username,
  };
};

export const mapDispatchToProps = (dispatch, ownProps) => ({
  handleLogOut: ownProps.handleLogOut || createHandleLogOutFunction(dispatch),
});

export default compose(
  connect(mapStateToProps, mapDispatchToProps),
  translate(),
)(HeaderBase);
<commit_msg>fix: Remove API keys from header menu (fix #3686)<commit_after>import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { compose } from 'redux';

import DownloadFirefoxButton from 'amo/components/DownloadFirefoxButton';
import Link from 'amo/components/Link';
import SearchForm from 'amo/components/SearchForm';
import SectionLinks from 'amo/components/SectionLinks';
import AuthenticateButton, {
  createHandleLogOutFunction,
} from 'core/components/AuthenticateButton';
import { isAuthenticated, selectDisplayName } from 'core/reducers/user';
import { VIEW_CONTEXT_HOME } from 'core/constants';
import translate from 'core/i18n/translate';
import Icon from 'ui/components/Icon';
import DropdownMenu from 'ui/components/DropdownMenu';
import DropdownMenuItem from 'ui/components/DropdownMenuItem';

import './styles.scss';

export class HeaderBase extends React.Component {
  static propTypes = {
    api: PropTypes.object.isRequired,
    displayName: PropTypes.string,
    handleLogOut: PropTypes.func.isRequired,
    i18n: PropTypes.object.isRequired,
    isAuthenticated: PropTypes.bool.isRequired,
    isHomePage: PropTypes.bool.isRequired,
    location: PropTypes.object.isRequired,
    query: PropTypes.string.isRequired,
    username: PropTypes.string,
  }

  static defaultProps = {
    isHomePage: false,
    query: '',
  }

  handleLogOut = (event) => {
    event.preventDefault();

    this.props.handleLogOut({ api: this.props.api });
  }

  render() {
    const {
      displayName,
      i18n,
      isHomePage,
      location,
      query,
      username,
    } = this.props;

    const headerLink = (
      <Link className="Header-title" to="/">
        <Icon className="Header-addons-icon" name="fox" />
        {
          // translators: "Firefox" should not be translated. :-)
          i18n.gettext('Firefox Add-ons')
        }
      </Link>
    );

    return (

          {isHomePage
            ?
{headerLink}

            : headerLink}

        <SectionLinks className="Header-SectionLinks" location={location} />

          <Link
            className="Header-developer-hub-link Header-button"
            href="/developers/"
            external
            prependClientApp={false}
          >
            {i18n.gettext('Developer Hub')}
          </Link>
          <DownloadFirefoxButton
            className="Header-download-button Header-button"
          />

          {this.props.isAuthenticated ? (
            <DropdownMenu
              text={displayName}
              className="Header-authenticate-button Header-button"
            >
              <DropdownMenuItem>{i18n.gettext('My Account')}</DropdownMenuItem>
              <DropdownMenuItem>
                <Link href={`/user/${username}/`}>
                  {i18n.gettext('View Profile')}
                </Link>
              </DropdownMenuItem>
              <DropdownMenuItem>
                <Link href="/users/edit">
                  {i18n.gettext('Edit Profile')}
                </Link>
              </DropdownMenuItem>

              <DropdownMenuItem>{i18n.gettext('Tools')}</DropdownMenuItem>
              <DropdownMenuItem>
                <Link
                  href="/developers/addon/submit/distribution"
                  prependClientApp={false}
                >
                  {i18n.gettext('Submit a New Add-on')}
                </Link>
              </DropdownMenuItem>
              <DropdownMenuItem>
                <Link
                  href="/developers/theme/submit"
                  prependClientApp={false}
                >
                  {i18n.gettext('Submit a New Theme')}
                </Link>
              </DropdownMenuItem>

              <DropdownMenuItem
                className={'Header-logout-button'}
                detached
                onClick={this.handleLogOut}
              >
                {i18n.gettext('Log out')}
              </DropdownMenuItem>
            </DropdownMenu>
          ) : (
            <AuthenticateButton
              className="Header-authenticate-button Header-button Button--action
              Button--outline-only Button--small"
              location={location}
              noIcon
            />
          )}

        <SearchForm
          className="Header-search-form"
          pathname="/search/"
          query={query}
        />

    );
  }
}

export const mapStateToProps = (state) => {
  return {
    api: state.api,
    displayName: selectDisplayName(state),
    isHomePage: state.viewContext.context === VIEW_CONTEXT_HOME,
    isAuthenticated: isAuthenticated(state),
    username: state.user.username,
  };
};

export const mapDispatchToProps = (dispatch, ownProps) => ({
  handleLogOut: ownProps.handleLogOut || createHandleLogOutFunction(dispatch),
});

export default compose(
  connect(mapStateToProps, mapDispatchToProps),
  translate(),
)(HeaderBase);
<|endoftext|>


<commit_before>'use strict';

const passport = require('passport');
const Strategy = require('passport-local').Strategy;
const API = require('./api-proxy.js');
const mongoose = require('./mongo.js');
const Token = mongoose.model('token', require('../schemas/token.js'));

// Configure the local strategy for use by Passport.
//
// The local strategy require a `verify` function which receives the credentials
// (`username` and `password`) submitted by the user.  The function must verify
// that the password is correct and then invoke `cb` with a user object, which
// will be set at `req.user` in route handlers after authentication.

passport.use(new Strategy(
  (username, password, cb) =>
    API.authenticate(username, password)
      .then(body => {
        var token = new Token(body);
        token.save();
        cb(null, token, { message: 'Successfully logged in' });
      })
      .catch(body =>
        cb(null, false, { message: body.error_description })
      )
));

// Configure Passport authenticated session persistence.
//
// In order to restore authentication state across HTTP requests, Passport needs
// to serialize users into and deserialize users out of the session.  The
// typical implementation of this is as simple as supplying the user ID when
// serializing, and querying the user record by ID from the database when
// deserializing.

passport.serializeUser((token, cb) => cb(null, token._id));

passport.deserializeUser((id, cb) =>
  Token.findById(id)
    .then(function (token) {
      cb(null, token);
    })
    .catch(function (err) {
      cb(err);
    })
);

module.exports = passport;
<commit_msg>adds debug auth messages<commit_after>'use strict';

const passport = require('passport');
const Strategy = require('passport-local').Strategy;
const API = require('./api-proxy.js');
const mongoose = require('./mongo.js');
const Token = mongoose.model('token', require('../schemas/token.js'));

// Configure the local strategy for use by Passport.
//
// The local strategy require a `verify` function which receives the credentials
// (`username` and `password`) submitted by the user.  The function must verify
// that the password is correct and then invoke `cb` with a user object, which
// will be set at `req.user` in route handlers after authentication.

passport.use(new Strategy(
  (username, password, cb) => {
    console.log("[AUTH] Sending Username / Password to Backend");
    API.authenticate(username, password)
      .then(body => {
        console.log("[AUTH] Got positive response");
        var token = new Token(body);
        token.save();
        console.log("[AUTH] Successfully saved user");
        cb(null, token, {message: 'Successfully logged in'});
      })
      .catch(body => {
          console.log("[AUTH] Got negative response");
          cb(null, false, {message: body.error_description});
        }
      )
  }
));

// Configure Passport authenticated session persistence.
//
// In order to restore authentication state across HTTP requests, Passport needs
// to serialize users into and deserialize users out of the session.  The
// typical implementation of this is as simple as supplying the user ID when
// serializing, and querying the user record by ID from the database when
// deserializing.

passport.serializeUser((token, cb) => cb(null, token._id));

passport.deserializeUser((id, cb) => {
  console.log("[AUTH] Trying to find user in DB");
    Token.findById(id)
      .then(function (token) {
        console.log("[AUTH] Found user in DB");
        cb(null, token);
      })
      .catch(function (err) {
        console.log("[AUTH] No user found");
        cb(err);
      })
  }
);

module.exports = passport;
<|endoftext|>