<commit_before>'use strict';

const _ = require('lodash');
const Script = require('smooch-bot').Script;
var pg = require('pg');
var Q = require("q");
var request = require("request");
var newUser = require("./db");

const scriptRules = require('./script.json');

function wait(ms) {
    return new Promise((resolve) => {
        setTimeout(resolve, ms);
    });
}

//move to separeate file
var promises = [];
function nlp(query,sessionId){
	var deferred = Q.defer();
	var options = {
		"method" : "POST",
		"url" : "https://api.api.ai/v1/query?v=20150910",
		"json" : {
			"query" : query,
			"lang" : "en",
			"sessionId" : sessionId
		},
		"headers" : {
			"Authorization" : "Bearer " + process.env.API_AI_TOKEN,
			"Content-Type" : "application/json"
		}
	};

	console.log("===nlp");
	console.log("===query: ",query);
	console.log("===sessionId",sessionId);
	request(options,function(err,response,body){
		if(err){
			console.log("===nlp failed because: ",err.message);
			deferred.reject(err);
		}else{
			body.sessionId = sessionId;
			if(response.statusCode == 200){
				console.log("===nlp succeeded ");
				deferred.resolve(body);
			}else{
				deferred.reject(body);
			}
		}
	});
	return deferred.promise;
}

module.exports = new Script({
    processing: {
        //prompt: (bot) => bot.say('Beep boop...'),
        receive: () => 'processing'
    },

    start: {
        receive: (bot) => {
            return bot.say('Get started by saying BOT.')
                .then(() => 'speak');
        }
    },

    speak: {
        receive: (bot, message) => {
            console.log("===bot user ",bot.userId);

            console.log("===before db");
            promises.fnapply(newUser(bot));
            console.log("===after db");

            let upperText = message.text.trim().toUpperCase();

            function updateSilent() {
                switch (upperText) {
                    case "CONNECT ME":
                        return bot.setProp("silent", true);
                    case "@Support":
                        return bot.setProp("silent", true);
                    case "DISCONNECT":
                        return bot.setProp("silent", false);
                    default:
                        return Promise.resolve();
                }
            }

            function getSilent() {
                return bot.getProp("silent");
            }

            function processMessage(isSilent) {
                if (isSilent) {
                    return Promise.resolve("speak");
                }

                var source;
                var fulfillmentSpeech;
                var simplified;
                promises.push(nlp(upperText, bot.userId));

                Q.all(promises)
                .then(function(responses) {
                    // response is the JSON from API.ai
                    responses.forEach(function(response) {
                        console.log("===in Q.all");
                        console.log("===received result from API.ai",response);
                        source = response.result.source;
                        if (source && source !== 'agent')
                        {
                            fulfillmentSpeech = response.result.fulfillment.speech;
                            simplified = response.result.parameters.simplified;
                        }
                        console.log("source: ", source);
                        console.log("fulfillmentSpeech: ", fulfillmentSpeech);
                        console.log("simplified: ", simplified);

                        respondMessage(source, fulfillmentSpeech, simplified);
                    });
                }, function(error) {
                    console.log("===Q all error ", error);
                });
                //return next();

            }

            function respondMessage(source, fulfillmentSpeech, simplified)
            {
                console.log("source: ", source);
                console.log("fulfillmentSpeech: ", fulfillmentSpeech);
                console.log("simplified: ", simplified);
                if (source != 'agent')
                {
                    console.log("===source is ", source);
                    if (fulfillmentSpeech)
                    {
                        console.log("fulfillmentSpeech is: ", fulfillmentSpeech);
                        return bot.say(fulfillmentSpeech).then(() => 'speak');
                    }
                    else if (simplified)
                    {
                        console.log("simplified is: ", simplified);
                        upperText = simplified.toUpperCase();
                    }
                }

                if (!_.has(scriptRules, upperText)) {
                    return bot.say(`So, I'm good at structured conversations but stickers, emoji and sentences still confuse me. Say 'more' to chat about something else.`).then(() => 'speak');
                }

                var response = scriptRules[upperText];
                var lines = response.split('\n');

                var p = Promise.resolve();
                _.each(lines, function(line) {
                    line = line.trim();
                    p = p.then(function() {
                        console.log(line);
                        return wait(50).then(function() {
                            return bot.say(line);
                        });
                    });
                });

                return p.then(() => 'speak');
            }

            return updateSilent()
                .then(getSilent)
                .then(processMessage);
        }
    }
});
<commit_msg>nfapply<commit_after>'use strict';

const _ = require('lodash');
const Script = require('smooch-bot').Script;
var pg = require('pg');
var Q = require("q");
var request = require("request");
var newUser = require("./db");

const scriptRules = require('./script.json');

function wait(ms) {
    return new Promise((resolve) => {
        setTimeout(resolve, ms);
    });
}

//move to separeate file
var promises = [];
function nlp(query,sessionId){
	var deferred = Q.defer();
	var options = {
		"method" : "POST",
		"url" : "https://api.api.ai/v1/query?v=20150910",
		"json" : {
			"query" : query,
			"lang" : "en",
			"sessionId" : sessionId
		},
		"headers" : {
			"Authorization" : "Bearer " + process.env.API_AI_TOKEN,
			"Content-Type" : "application/json"
		}
	};

	console.log("===nlp");
	console.log("===query: ",query);
	console.log("===sessionId",sessionId);
	request(options,function(err,response,body){
		if(err){
			console.log("===nlp failed because: ",err.message);
			deferred.reject(err);
		}else{
			body.sessionId = sessionId;
			if(response.statusCode == 200){
				console.log("===nlp succeeded ");
				deferred.resolve(body);
			}else{
				deferred.reject(body);
			}
		}
	});
	return deferred.promise;
}

module.exports = new Script({
    processing: {
        //prompt: (bot) => bot.say('Beep boop...'),
        receive: () => 'processing'
    },

    start: {
        receive: (bot) => {
            return bot.say('Get started by saying BOT.')
                .then(() => 'speak');
        }
    },

    speak: {
        receive: (bot, message) => {
            console.log("===bot user ",bot.userId);

            console.log("===before db");
            promises.nfapply(newUser(bot));
            console.log("===after db");

            let upperText = message.text.trim().toUpperCase();

            function updateSilent() {
                switch (upperText) {
                    case "CONNECT ME":
                        return bot.setProp("silent", true);
                    case "@Support":
                        return bot.setProp("silent", true);
                    case "DISCONNECT":
                        return bot.setProp("silent", false);
                    default:
                        return Promise.resolve();
                }
            }

            function getSilent() {
                return bot.getProp("silent");
            }

            function processMessage(isSilent) {
                if (isSilent) {
                    return Promise.resolve("speak");
                }

                var source;
                var fulfillmentSpeech;
                var simplified;
                promises.push(nlp(upperText, bot.userId));

                Q.all(promises)
                .then(function(responses) {
                    // response is the JSON from API.ai
                    responses.forEach(function(response) {
                        console.log("===in Q.all");
                        console.log("===received result from API.ai",response);
                        source = response.result.source;
                        if (source && source !== 'agent')
                        {
                            fulfillmentSpeech = response.result.fulfillment.speech;
                            simplified = response.result.parameters.simplified;
                        }
                        console.log("source: ", source);
                        console.log("fulfillmentSpeech: ", fulfillmentSpeech);
                        console.log("simplified: ", simplified);

                        respondMessage(source, fulfillmentSpeech, simplified);
                    });
                }, function(error) {
                    console.log("===Q all error ", error);
                });
                //return next();

            }

            function respondMessage(source, fulfillmentSpeech, simplified)
            {
                console.log("source: ", source);
                console.log("fulfillmentSpeech: ", fulfillmentSpeech);
                console.log("simplified: ", simplified);
                if (source != 'agent')
                {
                    console.log("===source is ", source);
                    if (fulfillmentSpeech)
                    {
                        console.log("fulfillmentSpeech is: ", fulfillmentSpeech);
                        return bot.say(fulfillmentSpeech).then(() => 'speak');
                    }
                    else if (simplified)
                    {
                        console.log("simplified is: ", simplified);
                        upperText = simplified.toUpperCase();
                    }
                }

                if (!_.has(scriptRules, upperText)) {
                    return bot.say(`So, I'm good at structured conversations but stickers, emoji and sentences still confuse me. Say 'more' to chat about something else.`).then(() => 'speak');
                }

                var response = scriptRules[upperText];
                var lines = response.split('\n');

                var p = Promise.resolve();
                _.each(lines, function(line) {
                    line = line.trim();
                    p = p.then(function() {
                        console.log(line);
                        return wait(50).then(function() {
                            return bot.say(line);
                        });
                    });
                });

                return p.then(() => 'speak');
            }

            return updateSilent()
                .then(getSilent)
                .then(processMessage);
        }
    }
});
<|endoftext|>


<commit_before>"use strict";
var gulp = require('gulp');
var runSequence = require('run-sequence').use(gulp);
var browserSync = require('browser-sync');
var reload = browserSync.reload;

gulp.task('styleguides', function(callback) {
  runSequence(
    'styleguide--scripts',
    'styleguide--styles',
    'styleguide--compile',
    'styleguide--inject',
    callback
  );
});
<commit_msg>Rename styleguide task<commit_after>"use strict";
var gulp = require('gulp');
var runSequence = require('run-sequence').use(gulp);
var browserSync = require('browser-sync');
var reload = browserSync.reload;

gulp.task('styleguide', function(callback) {
  runSequence(
    'styleguide--scripts',
    'styleguide--styles',
    'styleguide--compile',
    'styleguide--inject',
    callback
  );
});
<|endoftext|>


<commit_before>/*
 Copyright 2008-present Shaiksphere, 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.
 */

test("format should format the string", () => {
    let str1 = "Hello";
    let str2 = "World";

    expect(mindsmine.String.format("Let us combine {0} and {1} together.", str1, str2))
        .toBe("Let us combine Hello and World together.");
});

const decodedStr = "Hello World";
const encodedStr = "<a target='_blank' href='http://www.google.com'><span>Hello World</span></a>";

test("htmlEncode should encode the HTML content", () => {
    expect(mindsmine.String.htmlEncode(decodedStr)).toBe(encodedStr);
});

test("htmlDecode should decode the HTML content", () => {
    expect(mindsmine.String.htmlDecode(encodedStr)).toBe(decodedStr);
});

test("isEmpty should check for string emptiness", () => {
    expect(mindsmine.String.isEmpty(null)).toBeTruthy();
    expect(mindsmine.String.isEmpty(undefined)).toBeTruthy();
    expect(mindsmine.String.isEmpty(NaN)).toBeTruthy();
    expect(mindsmine.String.isEmpty(123)).toBeTruthy();
    expect(mindsmine.String.isEmpty("")).toBeTruthy();
    expect(mindsmine.String.isEmpty("Some String")).toBeFalsy();
});

test("urlAppend should append to the URL", () => {
    const url = "http://www.google.com",
        urlQ = `${url}?param1=value1`,
        query = "param2=value2";

    expect(mindsmine.String.urlAppend(url, query)).toBe("http://www.google.com?param2=value2");
    expect(mindsmine.String.urlAppend(urlQ, query)).toBe("http://www.google.com?param1=value1&param2=value2");
});

test("getNullSafe should get null safe strings", () => {
    expect(mindsmine.String.getNullSafe(null)).toBe("");
    expect(mindsmine.String.getNullSafe(undefined)).toBe("");
    expect(mindsmine.String.getNullSafe(NaN)).toBe("");
    expect(mindsmine.String.getNullSafe(100)).toBe("");
    expect(mindsmine.String.getNullSafe("")).toBe("");
    expect(mindsmine.String.getNullSafe("hello")).toBe("hello");
    expect(mindsmine.String.getNullSafe(true)).toBe("");
});

describe("areEqual", () => {
    test("should test string equality, leniently", () => {
        expect(mindsmine.String.areEqual(null, null, true)).toBeTruthy();
        expect(mindsmine.String.areEqual(null, "", true)).toBeTruthy();
        expect(mindsmine.String.areEqual("", null, true)).toBeTruthy();
        expect(mindsmine.String.areEqual("", "", true)).toBeTruthy();
        expect(mindsmine.String.areEqual("   ", "", true)).toBeTruthy();
        expect(mindsmine.String.areEqual(" abc", "abc ", true)).toBeTruthy();
        expect(mindsmine.String.areEqual("", "abc", true)).toBeFalsy();
        expect(mindsmine.String.areEqual("ab c", "abc", true)).toBeFalsy();
        expect(mindsmine.String.areEqual("ABC", "abc", true)).toBeTruthy();
        expect(mindsmine.String.areEqual("abc", "abc", true)).toBeTruthy();
    });

    test("should test string equality, strictly", () => {
        expect(mindsmine.String.areEqual(null, null, false)).toBeFalsy();
        expect(mindsmine.String.areEqual(null, "", false)).toBeFalsy();
        expect(mindsmine.String.areEqual("", null, false)).toBeFalsy();
        expect(mindsmine.String.areEqual("", "", false)).toBeTruthy();
        expect(mindsmine.String.areEqual("   ", "", false)).toBeFalsy();
        expect(mindsmine.String.areEqual(" abc", "abc ", false)).toBeFalsy();
        expect(mindsmine.String.areEqual("", "abc", false)).toBeFalsy();
        expect(mindsmine.String.areEqual("ab c", "abc", false)).toBeFalsy();
        expect(mindsmine.String.areEqual("ABC", "abc", false)).toBeFalsy();
        expect(mindsmine.String.areEqual("abc", "abc", false)).toBeTruthy();
    });

    test("should test string equality, default", () => {
        expect(mindsmine.String.areEqual(null, null)).toBeTruthy();
        expect(mindsmine.String.areEqual(null, "")).toBeTruthy();
        expect(mindsmine.String.areEqual("", null)).toBeTruthy();
        expect(mindsmine.String.areEqual("", "")).toBeTruthy();
        expect(mindsmine.String.areEqual("   ", "")).toBeTruthy();
        expect(mindsmine.String.areEqual(" abc", "abc ")).toBeTruthy();
        expect(mindsmine.String.areEqual("", "abc")).toBeFalsy();
        expect(mindsmine.String.areEqual("ab c", "abc")).toBeFalsy();
        expect(mindsmine.String.areEqual("ABC", "abc")).toBeTruthy();
        expect(mindsmine.String.areEqual("abc", "abc")).toBeTruthy();
    });
});

describe("isPalindrome", () => {
    test("should perform palindrome test, leniently", () => {
        expect(mindsmine.String.isPalindrome(null, true)).toBeTruthy();
        expect(mindsmine.String.isPalindrome("", true)).toBeTruthy();
        expect(mindsmine.String.isPalindrome("   ", true)).toBeTruthy();
        expect(mindsmine.String.isPalindrome(" aba", true)).toBeTruthy();
        expect(mindsmine.String.isPalindrome("aba", true)).toBeTruthy();
        expect(mindsmine.String.isPalindrome("mAdAm", true)).toBeTruthy();
        expect(mindsmine.String.isPalindrome("madAm", true)).toBeTruthy();
        expect(mindsmine.String.isPalindrome("madam", true)).toBeTruthy();
        expect(mindsmine.String.isPalindrome("Madam", true)).toBeTruthy();
        expect(mindsmine.String.isPalindrome("hello", true)).toBeFalsy();
    });

    test("should perform palindrome test, strictly", () => {
        expect(mindsmine.String.isPalindrome(null, false)).toBeFalsy();
        expect(mindsmine.String.isPalindrome("", false)).toBeTruthy();
        expect(mindsmine.String.isPalindrome("   ", false)).toBeTruthy();
        expect(mindsmine.String.isPalindrome(" aba", false)).toBeFalsy();
        expect(mindsmine.String.isPalindrome("aba", false)).toBeTruthy();
        expect(mindsmine.String.isPalindrome("mAdAm", false)).toBeTruthy();
        expect(mindsmine.String.isPalindrome("madAm", false)).toBeFalsy();
        expect(mindsmine.String.isPalindrome("madam", false)).toBeTruthy();
        expect(mindsmine.String.isPalindrome("Madam", false)).toBeFalsy();
        expect(mindsmine.String.isPalindrome("hello", false)).toBeFalsy();
    });

    test("should perform palindrome test, default", () => {
        expect(mindsmine.String.isPalindrome(null)).toBeTruthy();
        expect(mindsmine.String.isPalindrome("")).toBeTruthy();
        expect(mindsmine.String.isPalindrome("   ")).toBeTruthy();
        expect(mindsmine.String.isPalindrome(" aba")).toBeTruthy();
        expect(mindsmine.String.isPalindrome("aba")).toBeTruthy();
        expect(mindsmine.String.isPalindrome("mAdAm")).toBeTruthy();
        expect(mindsmine.String.isPalindrome("madAm")).toBeTruthy();
        expect(mindsmine.String.isPalindrome("madam")).toBeTruthy();
        expect(mindsmine.String.isPalindrome("Madam")).toBeTruthy();
        expect(mindsmine.String.isPalindrome("hello")).toBeFalsy();
    });
});
<commit_msg>Updating test code<commit_after>/*
 Copyright 2008-present Shaiksphere, 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.
 */

test("mindsmine.String.format should format the string", () => {
    let str1 = "Hello";
    let str2 = "World";

    expect(mindsmine.String.format("Let us combine {0} and {1} together.", str1, str2))
        .toBe("Let us combine Hello and World together.");
});

const decodedStr = "Hello World";
const encodedStr = "<a target='_blank' href='http://www.google.com'><span>Hello World</span></a>";

test("mindsmine.String.htmlEncode should encode the HTML content", () => {
    expect(mindsmine.String.htmlEncode(decodedStr)).toBe(encodedStr);
});

test("mindsmine.String.htmlDecode should decode the HTML content", () => {
    expect(mindsmine.String.htmlDecode(encodedStr)).toBe(decodedStr);
});

test("mindsmine.String.isEmpty should check for string emptiness", () => {
    expect(mindsmine.String.isEmpty(null)).toBeTruthy();
    expect(mindsmine.String.isEmpty(undefined)).toBeTruthy();
    expect(mindsmine.String.isEmpty(NaN)).toBeTruthy();
    expect(mindsmine.String.isEmpty(123)).toBeTruthy();
    expect(mindsmine.String.isEmpty("")).toBeTruthy();
    expect(mindsmine.String.isEmpty("Some String")).toBeFalsy();
});

test("mindsmine.String.urlAppend should append to the URL", () => {
    const url = "http://www.google.com",
        urlQ = `${url}?param1=value1`,
        query = "param2=value2";

    expect(mindsmine.String.urlAppend(url, query)).toBe("http://www.google.com?param2=value2");
    expect(mindsmine.String.urlAppend(urlQ, query)).toBe("http://www.google.com?param1=value1&param2=value2");
});

test("mindsmine.String.getNullSafe should get null safe strings", () => {
    expect(mindsmine.String.getNullSafe(null)).toBe("");
    expect(mindsmine.String.getNullSafe(undefined)).toBe("");
    expect(mindsmine.String.getNullSafe(NaN)).toBe("");
    expect(mindsmine.String.getNullSafe(100)).toBe("");
    expect(mindsmine.String.getNullSafe("")).toBe("");
    expect(mindsmine.String.getNullSafe("hello")).toBe("hello");
    expect(mindsmine.String.getNullSafe(true)).toBe("");
});

describe("mindsmine.String.areEqual", () => {
    test("should test string equality, leniently", () => {
        expect(mindsmine.String.areEqual(null, null, true)).toBeTruthy();
        expect(mindsmine.String.areEqual(null, "", true)).toBeTruthy();
        expect(mindsmine.String.areEqual("", null, true)).toBeTruthy();
        expect(mindsmine.String.areEqual("", "", true)).toBeTruthy();
        expect(mindsmine.String.areEqual("   ", "", true)).toBeTruthy();
        expect(mindsmine.String.areEqual(" abc", "abc ", true)).toBeTruthy();
        expect(mindsmine.String.areEqual("", "abc", true)).toBeFalsy();
        expect(mindsmine.String.areEqual("ab c", "abc", true)).toBeFalsy();
        expect(mindsmine.String.areEqual("ABC", "abc", true)).toBeTruthy();
        expect(mindsmine.String.areEqual("abc", "abc", true)).toBeTruthy();
    });

    test("should test string equality, strictly", () => {
        expect(mindsmine.String.areEqual(null, null, false)).toBeFalsy();
        expect(mindsmine.String.areEqual(null, "", false)).toBeFalsy();
        expect(mindsmine.String.areEqual("", null, false)).toBeFalsy();
        expect(mindsmine.String.areEqual("", "", false)).toBeTruthy();
        expect(mindsmine.String.areEqual("   ", "", false)).toBeFalsy();
        expect(mindsmine.String.areEqual(" abc", "abc ", false)).toBeFalsy();
        expect(mindsmine.String.areEqual("", "abc", false)).toBeFalsy();
        expect(mindsmine.String.areEqual("ab c", "abc", false)).toBeFalsy();
        expect(mindsmine.String.areEqual("ABC", "abc", false)).toBeFalsy();
        expect(mindsmine.String.areEqual("abc", "abc", false)).toBeTruthy();
    });

    test("should test string equality, default", () => {
        expect(mindsmine.String.areEqual(null, null)).toBeTruthy();
        expect(mindsmine.String.areEqual(null, "")).toBeTruthy();
        expect(mindsmine.String.areEqual("", null)).toBeTruthy();
        expect(mindsmine.String.areEqual("", "")).toBeTruthy();
        expect(mindsmine.String.areEqual("   ", "")).toBeTruthy();
        expect(mindsmine.String.areEqual(" abc", "abc ")).toBeTruthy();
        expect(mindsmine.String.areEqual("", "abc")).toBeFalsy();
        expect(mindsmine.String.areEqual("ab c", "abc")).toBeFalsy();
        expect(mindsmine.String.areEqual("ABC", "abc")).toBeTruthy();
        expect(mindsmine.String.areEqual("abc", "abc")).toBeTruthy();
    });
});

describe("mindsmine.String.isPalindrome", () => {
    test("should perform palindrome test, leniently", () => {
        expect(mindsmine.String.isPalindrome(null, true)).toBeTruthy();
        expect(mindsmine.String.isPalindrome("", true)).toBeTruthy();
        expect(mindsmine.String.isPalindrome("   ", true)).toBeTruthy();
        expect(mindsmine.String.isPalindrome(" aba", true)).toBeTruthy();
        expect(mindsmine.String.isPalindrome("aba", true)).toBeTruthy();
        expect(mindsmine.String.isPalindrome("mAdAm", true)).toBeTruthy();
        expect(mindsmine.String.isPalindrome("madAm", true)).toBeTruthy();
        expect(mindsmine.String.isPalindrome("madam", true)).toBeTruthy();
        expect(mindsmine.String.isPalindrome("Madam", true)).toBeTruthy();
        expect(mindsmine.String.isPalindrome("hello", true)).toBeFalsy();
    });

    test("should perform palindrome test, strictly", () => {
        expect(mindsmine.String.isPalindrome(null, false)).toBeFalsy();
        expect(mindsmine.String.isPalindrome("", false)).toBeTruthy();
        expect(mindsmine.String.isPalindrome("   ", false)).toBeTruthy();
        expect(mindsmine.String.isPalindrome(" aba", false)).toBeFalsy();
        expect(mindsmine.String.isPalindrome("aba", false)).toBeTruthy();
        expect(mindsmine.String.isPalindrome("mAdAm", false)).toBeTruthy();
        expect(mindsmine.String.isPalindrome("madAm", false)).toBeFalsy();
        expect(mindsmine.String.isPalindrome("madam", false)).toBeTruthy();
        expect(mindsmine.String.isPalindrome("Madam", false)).toBeFalsy();
        expect(mindsmine.String.isPalindrome("hello", false)).toBeFalsy();
    });

    test("should perform palindrome test, default", () => {
        expect(mindsmine.String.isPalindrome(null)).toBeTruthy();
        expect(mindsmine.String.isPalindrome("")).toBeTruthy();
        expect(mindsmine.String.isPalindrome("   ")).toBeTruthy();
        expect(mindsmine.String.isPalindrome(" aba")).toBeTruthy();
        expect(mindsmine.String.isPalindrome("aba")).toBeTruthy();
        expect(mindsmine.String.isPalindrome("mAdAm")).toBeTruthy();
        expect(mindsmine.String.isPalindrome("madAm")).toBeTruthy();
        expect(mindsmine.String.isPalindrome("madam")).toBeTruthy();
        expect(mindsmine.String.isPalindrome("Madam")).toBeTruthy();
        expect(mindsmine.String.isPalindrome("hello")).toBeFalsy();
    });
});
<|endoftext|>


<commit_before>
describe("cartodb.models.Map", function() {

  var map;
  beforeEach(function() {
    map = new cdb.admin.Map();
  });

  it("should trigger change:dataLayer when datalayer changes", function() {
    var s = {
      changed: function() {}
    };
    spyOn(s, 'changed');
    map.bind('change:dataLayer', s.changed);
    map.addDataLayer(new cdb.admin.MapLayer());
    expect(s.changed).toHaveBeenCalled();
  });

  it("should trigger change:dataLayer when 2 layers are added", function() {
    var s = {
      changed: function() {}
    };
    spyOn(s, 'changed');
    map.bind('change:dataLayer', s.changed);
    map.layers.reset([
      new cdb.admin.MapLayer(),
      new cdb.admin.MapLayer()
    ]);
    expect(s.changed).toHaveBeenCalled();
  });

});
<commit_msg>fixed tests<commit_after>
describe("cartodb.models.Map", function() {

  var map;
  beforeEach(function() {
    map = new cdb.admin.Map();
  });

  it("should trigger change:dataLayer when datalayer changes", function() {
    var s = {
      changed: function() {}
    };
    spyOn(s, 'changed');
    map.bind('change:dataLayer', s.changed);
    map.addDataLayer(new cdb.geo.MapLayer());
    expect(s.changed).toHaveBeenCalled();
  });

  it("should trigger change:dataLayer when 2 layers are added", function() {
    var s = {
      changed: function() {}
    };
    spyOn(s, 'changed');
    map.bind('change:dataLayer', s.changed);
    map.layers.reset([
      new cdb.geo.MapLayer(),
      new cdb.geo.MapLayer()
    ]);
    expect(s.changed).toHaveBeenCalled();
  });

});
<|endoftext|>


<commit_before>/**
# Iterators

    makeArray(arrayish) // => [array]

Creates a proper array from annoying array-like objects,
like *NodeLists* and *arguments* (although *don't use arguments, use ...args**).

    last(array) // => last element of array or null

Returns the last element of the array passed, or null if the array is empty.

    forEach(array, (val, idx) => {...});

Just like `Array.prototype.forEach` except you can interrupt it by returning `false`.

    forEachKey(object, (value, key) => {...});

Exactly like forEach except it iterates on the object's keys.

    mapKeys(object, (value, key) => {... return ...}) // => [map]

Just like map, except it creates an array from an object (using its keys).

    mapEachKey(object, (value, key) => {... return ...}) // => {map}

Just like map, except it creates an object from an object instead of an array
from an array.

    findKey(object, value => { ... return true|false } )
    // => first key whose corresponding value passes the test.

Like findIndex for arrays, but returns key instead.

    filter(array, value => ... test conditions ...); // filters array in place

Just like filter except it modifies the array in place (using splice).

    filterKeys(object, value => { ... return true|false })
    // => array of keys whose corresponding values pass the test

Returns a list of keys whose corresponding values pass the test.

    findValue(object, predicateMethod) // => returns first value that passes
predicateMethod

Like find for arrays, but iterates over keys to find the value.

    assignValues(dest, source); // returns modified dest

This works like object.assign but skips the functions. (It does this
recursively, except for class instances.)

~~~~
Test(() => document.querySelectorAll('div') instanceof Array).shouldBe(false);
Test(() => b8r.makeArray(document.querySelectorAll('div')) instanceof
Array).shouldBe(true);
Test(() => {
  const obj = {a: 10, b: 5};
  const s = [];
  b8r.forEachKey(obj, (val, key) => s.push(key + '=' + val));
  return s.join(',');
}).shouldBe('a=10,b=5');
Test(() => {
  const obj = {a: 10, b: 12, c: 5};
  const map = b8r.mapKeys(obj, (val, key) => `${key} ${val}`);
  return JSON.stringify(map)
}).shouldBe('["a 10","b 12","c 5"]');
Test(() => {
  const obj = {a: 10, b: 5};
  const map = b8r.mapEachKey(obj, (val, key) => key.charCodeAt(0) + val);
  return JSON.stringify(map);
}).shouldBe('{"a":107,"b":103}');
Test(() => {
  const obj = {a: 10, b: 12, c: 5};
  return b8r.findKey(obj, val => val % 3 === 0);
}).shouldBe('b');
Test(() => {
  const a = [1,2,3,4,5,6,7,8,9];
  b8r.filter(a, x => x % 2 && x % 3);
  return a;
}).shouldBeJSON([1,5,7]);
Test(() => {
  const obj = {a: 10, b: 12, c: 5};
  return JSON.stringify(b8r.filterKeys(obj, val => val % 5 === 0));
}).shouldBe('["a","c"]');
Test(() => {
  const obj = {foo: {a: 1, b: 'hello'}, bar: {a: 17, b: 'world'}};
  return b8r.findValue(obj, value => value.a === 17).b;
}).shouldBe('world');
Test(() => {
  const obj = {a: 10, b: 12, c: 5};
  return JSON.stringify(b8r.filterObject(obj, val => val % 5 === 0));
}).shouldBe('{"a":10,"c":5}');
Test(() => {
  const obj = {a: 10, b: 12, c: 5};
  return JSON.stringify(b8r.filterObject(obj, (val, key) => ['b', 'c'].includes(key)));
}).shouldBe('{"b":12,"c":5}');
~~~~
*/
/* global module */

'use strict';

const makeArray = arrayish => [...arrayish];

const forEach = (array, method) => {
  for (var i = 0; i < array.length; i++) {
    if (method(array[i]) === false) {
      break;
    }
  }
};

const last = array => array.length ? array[array.length - 1] : null;

const forEachKey = (object, method) => {
  var key;
  for (var i = 0, keys = Object.keys(object); i < keys.length; i++) {
    key = keys[i];
    if (method(object[key], key) === false) {
      break;
    }
  }
};

const mapKeys = (object, method) => {
  const map = [];
  forEachKey(object, (val, key) => map.push(method(val, key)));
  return map;
};

const mapEachKey = (object, method) => {
  const map = {};
  forEachKey(object, (val, key) => map[key] = method(val, key));
  return map;
};

const findKey = (object, test) => {
  var foundKey = null;
  forEachKey(object, (val, key) => {
    if (test(val)) {
      foundKey = key;
      return false;
    }
  });
  return foundKey;
};

const findValue = (object, test) => {
  const key = findKey(object, test);
  return key ? object[key] : null;
};

const filter = (list, test) => {
  for(let i = list.length - 1; i >= 0; i--) {
    if (! test(list[i])) {
      list.splice(i, 1);
    }
  }
};

const filterKeys = (object, test) => {
  var filtered = [];
  forEachKey(object, (val, key) => {
    if (test(val)) {
      filtered.push(key);
    }
  });
  return filtered;
};

const filterObject = (object, test) => {
  var filtered = {};
  forEachKey(object, (val, key) => {
    if (test(val, key)) {
      filtered[key] = val;
    }
  });
  return filtered;
};

const assignValues = (object, ancestor) => {
  forEachKey(ancestor, (val, key) => {
    if (typeof val !== 'function') {
      if (val && val.constructor === Object) {
        object[key] = assignValues({}, val);
      } else {
        object[key] = val;
      }
    }
  });
  return object;
};

module.exports = {
  makeArray,
  last,
  forEach,
  forEachKey,
  mapKeys,
  mapEachKey,
  findKey,
  findValue,
  filter,
  filterKeys,
  filterObject,
  assignValues,
};
<commit_msg>modernize, simplify, and optimize iterators document filterObject<commit_after>/**
# Iterators

    makeArray(arrayish) // => [array]

Creates a proper array from annoying array-like objects,
like *NodeLists* and *arguments* (although *don't use arguments, use ...args**).

    last(array) // => last element of array or null

Returns the last element of the array passed, or null if the array is empty.

    forEach(array, (val, idx) => {...});

Just like `Array.prototype.forEach` except you can interrupt it by returning `false`.

    forEachKey(object, (value, key) => {...});

Exactly like forEach except it iterates on the object's keys.

    mapKeys(object, (value, key) => {... return ...}) // => [map]

Just like map, except it creates an array from an object (using its keys).

    mapEachKey(object, (value, key) => {... return ...}) // => {map}

Just like map, except it creates an object from an object instead of an array
from an array.

    findKey(object, value => { ... return true|false } )
    // => first key whose corresponding value passes the test.

Like findIndex for arrays, but returns key instead.

    filter(array, value => ... test conditions ...); // filters array in place

Just like filter except it modifies the array in place (using splice).

    filterKeys(object, value => { ... return true|false })
    // => array of keys whose corresponding values pass the test

Returns a list of keys whose corresponding values pass the test.

    filterObject(object, (value, key) => {});

Filters an object in place (deletes keys that don't pass a the lest).

    findValue(object, predicateMethod) // => returns first value that passes
predicateMethod

Like find for arrays, but iterates over keys to find the value.

    assignValues(dest, source); // returns modified dest

This works like object.assign but skips the functions. (It does this
recursively, except for class instances.)

~~~~
Test(() => document.querySelectorAll('div') instanceof Array).shouldBe(false);
Test(() => b8r.makeArray(document.querySelectorAll('div')) instanceof
Array).shouldBe(true);
Test(() => {
  const obj = {a: 10, b: 5};
  const s = [];
  b8r.forEachKey(obj, (val, key) => s.push(key + '=' + val));
  return s.join(',');
}).shouldBe('a=10,b=5');
Test(() => {
  const obj = {a: 10, b: 12, c: 5};
  const map = b8r.mapKeys(obj, (val, key) => `${key} ${val}`);
  return JSON.stringify(map)
}).shouldBe('["a 10","b 12","c 5"]');
Test(() => {
  const obj = {a: 10, b: 5};
  const map = b8r.mapEachKey(obj, (val, key) => key.charCodeAt(0) + val);
  return JSON.stringify(map);
}).shouldBe('{"a":107,"b":103}');
Test(() => {
  const obj = {a: 10, b: 12, c: 5};
  return b8r.findKey(obj, val => val % 3 === 0);
}).shouldBe('b');
Test(() => {
  const a = [1,2,3,4,5,6,7,8,9];
  b8r.filter(a, x => x % 2 && x % 3);
  return a;
}).shouldBeJSON([1,5,7]);
Test(() => {
  const obj = {a: 10, b: 12, c: 5};
  return JSON.stringify(b8r.filterKeys(obj, val => val % 5 === 0));
}).shouldBe('["a","c"]');
Test(() => {
  const obj = {foo: {a: 1, b: 'hello'}, bar: {a: 17, b: 'world'}};
  return b8r.findValue(obj, value => value.a === 17).b;
}).shouldBe('world');
Test(() => {
  const obj = {a: 10, b: 12, c: 5};
  return JSON.stringify(b8r.filterObject(obj, val => val % 5 === 0));
}).shouldBe('{"a":10,"c":5}');
Test(() => {
  const obj = {a: 10, b: 12, c: 5};
  return JSON.stringify(b8r.filterObject(obj, (val, key) => ['b', 'c'].includes(key)));
}).shouldBe('{"b":12,"c":5}');
~~~~
*/
/* global module */

'use strict';

const makeArray = arrayish => [...arrayish];

const forEach = (array, method) => {
  for (let i = 0; i < array.length; i++) {
    if (method(array[i]) === false) {
      break;
    }
  }
};

const last = array => array.length ? array[array.length - 1] : null;

const forEachKey = (object, method) => {
  const keys = Object.keys(object);
  for (const key of keys) if (method(object[key], key) === false) break;
};

const mapKeys = (object, method) => {
  const keys = Object.keys(object);
  const map = [];
  for (const key of keys) map.push(method(object[key], key));
  return map;
};

const mapEachKey = (object, method) => {
  const keys = Object.keys(object);
  const map = {};
  for (const key of keys) map[key] = method(object[key], key);
  return map;
};

const findKey = (object, test) => {
  const keys = Object.keys(object);
  for(const key of keys) if (test(object[key], key)) return key;
  return null;
};

const findValue = (object, test) => {
  const key = findKey(object, test);
  return key ? object[key] : null;
};

const filter = (list, test) => {
  for(let i = list.length - 1; i >= 0; i--) if (! test(list[i])) list.splice(i, 1);
  return list;
};

const filterKeys = (object, test) => {
  const keys = Object.keys(object);
  let filtered = [];
  for(const key of keys) if (test(object[key], key)) filtered.push(key);
  return filtered;
};

const filterObject = (object, test) => {
  const keys = Object.keys(object);
  for(const key of keys) if (! test(object[key], key)) delete object[key];
  return object;
};

const assignValues = (object, ancestor) => {
  forEachKey(ancestor, (val, key) => {
    if (typeof val !== 'function') {
      if (val && val.constructor === Object) {
        object[key] = assignValues({}, val);
      } else {
        object[key] = val;
      }
    }
  });
  return object;
};

module.exports = {
  makeArray,
  last,
  forEach,
  forEachKey,
  mapKeys,
  mapEachKey,
  findKey,
  findValue,
  filter,
  filterKeys,
  filterObject,
  assignValues,
};
<|endoftext|>


<commit_before>
function Session( session_type, callback ) {
	this.brush = null;

	this.TYPE

	var session_id = null;
	this.user_id = null;

	function initialize() {
		// get session info from
		$.ajax({
		    // FIXME: request with previous user_id
		    url: "/api/session/join?type="+session_type,
		    ataType: "json",
		    type: 'GET',
		    context: this,
		    success: function( user_id ){
			this.user_id = user_id;

			// FIXME: set cookie with user_id for next time
			alert('got user id : ' + this.user_id );

			callback( this );
		    }
		});
	}

	initialize();
}

Session.prototype.SESSION_JOIN = "/api/session/join";
Session.prototype.SESSION_LEAVE = "/api/session/leave";
Session.prototype.TYPE_DRAW = "draw";
Session.prototype.TYPE_VIEW = "view";

<commit_msg>js session: declared some SESSION_* constants.<commit_after>
const SESSION_URL_JOIN = "/api/session/join";
const SESSION_URL_LEAVE = "/api/session/leave";
const SESSION_TYPE_DRAW = "draw";
const SESSION_TYPE_VIEW = "view";

function Session( session_type, callback ) {
	this.brush = null;

	var session_id = null;
	this.user_id = null;

	// get session info from
	$.ajax({
	    // FIXME: request with previous user_id
	    url: SESSION_URL_JOIN + "?type=" + session_type,
	    ataType: "json",
	    type: 'GET',
	    context: this,
	    success: function( user_id ){
		this.user_id = user_id;

		// FIXME: set cookie with user_id for next time
		console.log('got user id : ' + this.user_id );

		callback( this );
	    }
	});
}

<|endoftext|>


<commit_before>var React = require('react');
var addClass = require('./add-class');

module.exports = React.createClass({

  propTypes: {

    /**
     * The value that will be send to the `onSelect` handler of the
     * parent Combobox.
    */
    value: React.PropTypes.any.isRequired,

    /**
     * What value to put into the input element when this option is
     * selected, defaults to its children coerced to a string.
    */
    label: React.PropTypes.string
  },

  getDefaultProps: function() {
    return {
      role: 'option',
      tabIndex: '-1',
      className: 'rf-combobox-option',
      isSelected: false
    };
  },

  render: function() {
    var className = this.props.className;
    if (this.props.isSelected)
      className = addClass(this.props.className, 'rf-combobox-selected');

    return <div {...props} className={className}/>;
  }

});

<commit_msg>Missing 'this'<commit_after>var React = require('react');
var addClass = require('./add-class');

module.exports = React.createClass({

  propTypes: {

    /**
     * The value that will be send to the `onSelect` handler of the
     * parent Combobox.
    */
    value: React.PropTypes.any.isRequired,

    /**
     * What value to put into the input element when this option is
     * selected, defaults to its children coerced to a string.
    */
    label: React.PropTypes.string
  },

  getDefaultProps: function() {
    return {
      role: 'option',
      tabIndex: '-1',
      className: 'rf-combobox-option',
      isSelected: false
    };
  },

  render: function() {
    var className = this.props.className;
    if (this.props.isSelected)
      className = addClass(this.props.className, 'rf-combobox-selected');

    return <div {...this.props} className={className}/>;
  }

});

<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.
 */

import {Observable} from 'rxjs/Observable';
import {Subject} from 'rxjs/Subject';
import 'rxjs/add/observable/race';
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/pluck';
import 'rxjs/add/operator/take';
import 'rxjs/add/operator/toPromise';

/**
 * Simple implementation of workers pool.
 */
export default class SimpleWorkerPool {
    constructor(name, WorkerClass, poolSize = (navigator.hardwareConcurrency || 4), dbg = false) {
        this._name = name;
        this._WorkerClass = WorkerClass;
        this._tasks = [];
        this._msgId = 0;
        this.messages$ = new Subject();
        this.errors$ = new Subject();
        this.__dbg = dbg;

        this._workers = _.range(poolSize).map(() => {
            const worker = new this._WorkerClass();

            worker.onmessage = (m) => {
                this.messages$.next({tid: worker.tid, m});

                worker.tid = null;

                this._run();
            };

            worker.onerror = (e) => {
                this.errors$.next({tid: worker.tid, e});

                worker.tid = null;

                this._run();
            };

            return worker;
        });
    }

    _makeTaskID() {
        return this._msgId++;
    }

    _getNextWorker() {
        return this._workers.find((w) => !w.tid);
    }

    _getNextTask() {
        return this._tasks.shift();
    }

    _run() {
        const worker = this._getNextWorker();

        if (!worker || !this._tasks.length)
            return;

        const task = this._getNextTask();

        worker.tid = task.tid;

        if (this.__dbg)
            console.time(`Post message[pool=${this._name}]`);

        worker.postMessage(task.data);

        if (this.__dbg)
            console.timeEnd('Post message');
    }

    terminate() {
        this._workers.forEach((w) => w.terminate());

        this.messages$.complete();
        this.errors$.complete();

        this._workers = null;
    }

    postMessage(data) {
        const tid = this._makeTaskID();

        this._tasks.push({tid, data});

        if (this.__dbg)
            console.log(`Pool: [name=${this._name}, queue=${this._tasks.length}]`);

        this._run();

        return Observable.race(
            this.messages$.filter((e) => e.tid === tid).take(1).pluck('m', 'data'),
            this.errors$.filter((e) => e.tid === tid).take(1).map((e) => {
                throw e.e;
            }))
            .take(1).toPromise();
    }
}
<commit_msg>IGNITE-6926) Web console: Fixed SimpleWorkerPool next worker selection logic.<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.
 */

import {Observable} from 'rxjs/Observable';
import {Subject} from 'rxjs/Subject';
import 'rxjs/add/observable/race';
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/pluck';
import 'rxjs/add/operator/take';
import 'rxjs/add/operator/toPromise';

/**
 * Simple implementation of workers pool.
 */
export default class SimpleWorkerPool {
    constructor(name, WorkerClass, poolSize = (navigator.hardwareConcurrency || 4), dbg = false) {
        this._name = name;
        this._WorkerClass = WorkerClass;
        this._tasks = [];
        this._msgId = 0;
        this.messages$ = new Subject();
        this.errors$ = new Subject();
        this.__dbg = dbg;

        this._workers = _.range(poolSize).map(() => {
            const worker = new this._WorkerClass();

            worker.onmessage = (m) => {
                this.messages$.next({tid: worker.tid, m});

                worker.tid = null;

                this._run();
            };

            worker.onerror = (e) => {
                this.errors$.next({tid: worker.tid, e});

                worker.tid = null;

                this._run();
            };

            return worker;
        });
    }

    _makeTaskID() {
        return this._msgId++;
    }

    _getNextWorker() {
        return this._workers.find((w) => _.isNil(w.tid));
    }

    _getNextTask() {
        return this._tasks.shift();
    }

    _run() {
        const worker = this._getNextWorker();

        if (!worker || !this._tasks.length)
            return;

        const task = this._getNextTask();

        worker.tid = task.tid;

        if (this.__dbg)
            console.time(`Post message[pool=${this._name}]`);

        worker.postMessage(task.data);

        if (this.__dbg)
            console.timeEnd('Post message');
    }

    terminate() {
        this._workers.forEach((w) => w.terminate());

        this.messages$.complete();
        this.errors$.complete();

        this._workers = null;
    }

    postMessage(data) {
        const tid = this._makeTaskID();

        this._tasks.push({tid, data});

        if (this.__dbg)
            console.log(`Pool: [name=${this._name}, tid=${tid}, queue=${this._tasks.length}]`);

        this._run();

        return Observable.race(
            this.messages$.filter((e) => e.tid === tid).take(1).pluck('m', 'data'),
            this.errors$.filter((e) => e.tid === tid).take(1).map((e) => {
                throw e.e;
            }))
            .take(1).toPromise();
    }
}
<|endoftext|>


<commit_before>import Ember from 'ember'
import layout from './template'

const {
  Component,
  computed,
  defineProperty
} = Ember

export default Component.extend({
  classNameBindings: ['isInvalid:has-error', 'isValid:has-success'],
  classNames: ['rui-validatable-input'],
  layout,
  model: null,
  placeholder: '',
  type: 'text',
  valuePath: '',
  async: false,

  init() {
    this._super(...arguments)
    const valuePath = this.get('valuePath')
    defineProperty(this, 'validation', computed.oneWay(`model.validations.attrs.${valuePath}`))
    defineProperty(this, 'value', computed.alias(`model.${valuePath}`))
  },

  // This method ensures that if presence is required
  // But the initial value is undefined or an empty string
  // (the case with new records) we can still validate even though
  // the `didChange` attr would report it had not

  validatePresenceWithEmptyDefault: computed('value', function() {
    const validationOptions = Object.keys(
      this.get(`model.validations.attrs.${this.get('valuePath')}.options`))

    return (validationOptions.indexOf('presence') !== -1) &&
      (this.get('value') === '') ||
      (this.get('value') === undefined)
  }),

  // The attribute has changed UNLESS
  // the validator includes presence and
  // the value is undefined or empty

  didChange: computed('value', 'model.hasDirtyAttributes', 'isSaving', function() {
    if (this.get('validatePresenceWithEmptyDefault')) {
        return true
    }

    const attrsChanged = this.get('model') ? this.get('model').changedAttributes() : {}
    return this.get('valuePath') in attrsChanged
  }),

  // Compute the property to give priority to
  // `isSaving` property if found on controller

  isSavingComputed: computed('model.isSaving', 'targetObject.isSaving', function() {
    const isSavingFromController = this.get('targetObject.isSaving')
    if ((typeof isSavingFromController !== 'undefined') &&
      (isSavingFromController !== null)) {
        return isSavingFromController
      }
    return this.get('model.isSaving')
  }),

  // Checks for in processing statuses
  // Ensures validations don't show when:
  // input is clean, is validating, model is saving

  validatable: computed(
    'didChange',
    'validation.isValidating',
    'isSavingComputed',
    function() {
      return this.get('didChange') &&
      !this.get('validation.isValidating') &&
      !this.get('isSavingComputed')
    }
  ),

  // Base values that compute validation state

  _isInvalid: computed.and('validation.isInvalid', 'validatable'),
  _isValid: computed.and('validation.isValid', 'validatable'),

  // Checks property `didValidate` on controller
  // Used to only show validation if `async` is true

  didValidate: computed.oneWay('targetObject.didValidate'),

  // Validation binding attributes with check for async settings
  // if async is true, don't display either until `didValidate`

  isInvalid: computed('_isInvalid', 'didValidate', function() {
    if (this.get('async')) {
      return this.get('_isInvalid') && this.get('didValidate')
    }
    return this.get('_isInvalid')
  }),

  isValid: computed('_isValid', 'didValidate', function() {
    if (this.get('async')) {
      return this.get('_isValid') && this.get('didValidate')
    }
    return this.get('_isValid')
  })
})
<commit_msg>Make if statement one liner<commit_after>import Ember from 'ember'
import layout from './template'

const {
  Component,
  computed,
  defineProperty
} = Ember

export default Component.extend({
  classNameBindings: ['isInvalid:has-error', 'isValid:has-success'],
  classNames: ['rui-validatable-input'],
  layout,
  model: null,
  placeholder: '',
  type: 'text',
  valuePath: '',
  async: false,

  init() {
    this._super(...arguments)
    const valuePath = this.get('valuePath')
    defineProperty(this, 'validation', computed.oneWay(`model.validations.attrs.${valuePath}`))
    defineProperty(this, 'value', computed.alias(`model.${valuePath}`))
  },

  // This method ensures that if presence is required
  // But the initial value is undefined or an empty string
  // (the case with new records) we can still validate even though
  // the `didChange` attr would report it had not

  validatePresenceWithEmptyDefault: computed('value', function() {
    const validationOptions = Object.keys(
      this.get(`model.validations.attrs.${this.get('valuePath')}.options`))

    return (validationOptions.indexOf('presence') !== -1) &&
      (this.get('value') === '') ||
      (this.get('value') === undefined)
  }),

  // The attribute has changed UNLESS
  // the validator includes presence and
  // the value is undefined or empty

  didChange: computed('value', 'model.hasDirtyAttributes', 'isSaving', function() {
    if (this.get('validatePresenceWithEmptyDefault')) { return true }

    const attrsChanged = this.get('model') ? this.get('model').changedAttributes() : {}
    return this.get('valuePath') in attrsChanged
  }),

  // Compute the property to give priority to
  // `isSaving` property if found on controller

  isSavingComputed: computed('model.isSaving', 'targetObject.isSaving', function() {
    const isSavingFromController = this.get('targetObject.isSaving')
    if ((typeof isSavingFromController !== 'undefined') &&
      (isSavingFromController !== null)) {
        return isSavingFromController
      }
    return this.get('model.isSaving')
  }),

  // Checks for in processing statuses
  // Ensures validations don't show when:
  // input is clean, is validating, model is saving

  validatable: computed(
    'didChange',
    'validation.isValidating',
    'isSavingComputed',
    function() {
      return this.get('didChange') &&
      !this.get('validation.isValidating') &&
      !this.get('isSavingComputed')
    }
  ),

  // Base values that compute validation state

  _isInvalid: computed.and('validation.isInvalid', 'validatable'),
  _isValid: computed.and('validation.isValid', 'validatable'),

  // Checks property `didValidate` on controller
  // Used to only show validation if `async` is true

  didValidate: computed.oneWay('targetObject.didValidate'),

  // Validation binding attributes with check for async settings
  // if async is true, don't display either until `didValidate`

  isInvalid: computed('_isInvalid', 'didValidate', function() {
    if (this.get('async')) {
      return this.get('_isInvalid') && this.get('didValidate')
    }
    return this.get('_isInvalid')
  }),

  isValid: computed('_isValid', 'didValidate', function() {
    if (this.get('async')) {
      return this.get('_isValid') && this.get('didValidate')
    }
    return this.get('_isValid')
  })
})
<|endoftext|>


<commit_before>module.exports = {
  pageTitle: 'Review your Request',
  changePersonalInfoButton: 'Edit Personal Info & Documents',
  agreementLabel: 'Authorize your update request',
  doYouAgreeLabel: '{name}, do you agree?',
  agreeLabel: 'Yes, I agree',
  submitButton: 'Submit Application',
    applicantTitle:'Account Holder Information',
    applicantLinkTitle:'EDIT PERSONAL INFORMATION',
  tryAgainWithCaptcha: 'Please try again to enter the text you see above',
  agreement: 'I have received information about MSP and agree to abide by its terms and conditions. I understand the information I have given is collected under the authority of the Medicare Protection Act and may be used to assess eligibility for other Ministry of Health programs, and that practitioners who provide service(s) under MSP are required under the Medicare Protection Act to release information relative to those services to MSP to support claims for benefits.

I declare that all information provided is true and I understand that the Ministry of Health and/or Health Insurance BC may verify this information with immigration authorities, law enforcement authorities and other public authorities, agencies and persons, as appropriate.

I agree to keep my address up to date with Health Insurance BC, notifying them of any changes within 10 days of moving. I declare that all persons listed are residents of British Columbia. Resident means a person who is a citizen of Canada or is lawfully admitted to Canada for permanent residence, who makes his or her home in British Columbia, and is physically present in British Columbia for at least six months in a calendar year, or a shorter prescribed period, and includes a person who is deemed under the regulations to be a resident, but does not include a tourist or visitor to British Columbia.',
    docTitle:'Supporting Documentation',
    docConfirmTitle:'You have uploaded the following documents. Please review to confirm that they are the correct documents and are readable (click for full size).'
}
<commit_msg>Changed label<commit_after>module.exports = {
  pageTitle: 'Review your Request',
  changePersonalInfoButton: 'Edit Personal Info & Documents',
  agreementLabel: 'Authorize your update request',
  doYouAgreeLabel: '{name}, do you agree?',
  agreeLabel: 'Yes, I agree',
  submitButton: 'Submit Request',
    applicantTitle:'Account Holder Information',
    applicantLinkTitle:'EDIT PERSONAL INFORMATION',
  tryAgainWithCaptcha: 'Please try again to enter the text you see above',
  agreement: 'I have received information about MSP and agree to abide by its terms and conditions. I understand the information I have given is collected under the authority of the Medicare Protection Act and may be used to assess eligibility for other Ministry of Health programs, and that practitioners who provide service(s) under MSP are required under the Medicare Protection Act to release information relative to those services to MSP to support claims for benefits.

I declare that all information provided is true and I understand that the Ministry of Health and/or Health Insurance BC may verify this information with immigration authorities, law enforcement authorities and other public authorities, agencies and persons, as appropriate.

I agree to keep my address up to date with Health Insurance BC, notifying them of any changes within 10 days of moving. I declare that all persons listed are residents of British Columbia. Resident means a person who is a citizen of Canada or is lawfully admitted to Canada for permanent residence, who makes his or her home in British Columbia, and is physically present in British Columbia for at least six months in a calendar year, or a shorter prescribed period, and includes a person who is deemed under the regulations to be a resident, but does not include a tourist or visitor to British Columbia.',
    docTitle:'Supporting Documentation',
    docConfirmTitle:'You have uploaded the following documents. Please review to confirm that they are the correct documents and are readable (click for full size).'
}
<|endoftext|>


<commit_before>import Ember from 'ember';
import config from '../config/environment';

var getLatLng = function (obj) {
  return new google.maps.LatLng(obj.latitude, obj.longitude);
};

var getLatLngArray = function (arr) {
  var result = [];
  arr.forEach(function (obj) {
    result.push(getLatLng(obj));
  });

  return result;
};

/* globals google */
export default Ember.Route.extend({
  ajax: Ember.inject.service(),
  errorHandler: Ember.inject.service(),

  actions: {
    didTransition() {
      Ember.run.scheduleOnce('afterRender', this, () => {
        window.map_callback = () => {
          Ember.$('#loading-message').remove();

          var mapOptions = {
            zoom: config.APP.map.zoom,
            center: getLatLng(config.APP.map.center),
            mapTypeId: google.maps.MapTypeId.SATELLITE
          };

          var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

          var bounds = new google.maps.Polygon({
            paths: getLatLngArray(config.APP.map.bounds),
            strokeColor: '#FFAA00',
            strokeOpacity: 0.6,
            strokeWeight: 2,
            fillColor: '#00FF00',
            fillOpacity: 0.08,
            clickable: false
          });

          bounds.setMap(map);

          this.get('ajax').request('/status/infections').then((results) => {
            var min = config.APP.map.viewBounds.min;
            var max = config.APP.map.viewBounds.max;

            var removeCount = 0;
            var locations = results.infections.filter((inf) => {
              if (!inf.hasLocation) {
                return false;
              }

              if(inf.latitude < min.latitude || inf.longitude < min.longitude ||
                  inf.latitude > max.latitude || inf.longitude > max.longitude) {
                ++removeCount;
                return false;
              }

              return true;
            }).map((inf) => {
              return {location: new google.maps.LatLng(inf.latitude, inf.longitude), weight: 1};
            });

            console.log("Removed " + locations + " locations as out of bounds");

            var heatmap = new google.maps.visualization.HeatmapLayer({data: locations});
            heatmap.setMap(map);
          }).catch((err) => {
            this.get('errorHandler').handleError(err, 'Unable to retrieve infections.');
          });
        };

        Ember.$.getScript("http://maps.google.com/maps/api/js?libraries=visualization&callback=map_callback");
      });
    }
  }
});
<commit_msg>fix https issue<commit_after>import Ember from 'ember';
import config from '../config/environment';

var getLatLng = function (obj) {
  return new google.maps.LatLng(obj.latitude, obj.longitude);
};

var getLatLngArray = function (arr) {
  var result = [];
  arr.forEach(function (obj) {
    result.push(getLatLng(obj));
  });

  return result;
};

/* globals google */
export default Ember.Route.extend({
  ajax: Ember.inject.service(),
  errorHandler: Ember.inject.service(),

  actions: {
    didTransition() {
      Ember.run.scheduleOnce('afterRender', this, () => {
        window.map_callback = () => {
          Ember.$('#loading-message').remove();

          var mapOptions = {
            zoom: config.APP.map.zoom,
            center: getLatLng(config.APP.map.center),
            mapTypeId: google.maps.MapTypeId.SATELLITE
          };

          var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

          var bounds = new google.maps.Polygon({
            paths: getLatLngArray(config.APP.map.bounds),
            strokeColor: '#FFAA00',
            strokeOpacity: 0.6,
            strokeWeight: 2,
            fillColor: '#00FF00',
            fillOpacity: 0.08,
            clickable: false
          });

          bounds.setMap(map);

          this.get('ajax').request('/status/infections').then((results) => {
            var min = config.APP.map.viewBounds.min;
            var max = config.APP.map.viewBounds.max;

            var removeCount = 0;
            var locations = results.infections.filter((inf) => {
              if (!inf.hasLocation) {
                return false;
              }

              if(inf.latitude < min.latitude || inf.longitude < min.longitude ||
                  inf.latitude > max.latitude || inf.longitude > max.longitude) {
                ++removeCount;
                return false;
              }

              return true;
            }).map((inf) => {
              return {location: new google.maps.LatLng(inf.latitude, inf.longitude), weight: 1};
            });

            console.log("Removed " + locations + " locations as out of bounds");

            var heatmap = new google.maps.visualization.HeatmapLayer({data: locations});
            heatmap.setMap(map);
          }).catch((err) => {
            this.get('errorHandler').handleError(err, 'Unable to retrieve infections.');
          });
        };

        Ember.$.getScript("//maps.google.com/maps/api/js?libraries=visualization&callback=map_callback");
      });
    }
  }
});
<|endoftext|>


<commit_before>/* globals $, toastr */
import * as app from 'app';
import { postsData } from 'data';
import { templates } from 'templates';
import * as nav from 'update-nav';
import * as widgets from 'widgets';
import * as error from 'error';

let allPosts = false;
let postsList;
let pageCount;
let category;
let subCategory;

// Fetches posts from DB, fetches template for post list
const fetchPostsData = (response) => {
  postsList = response;
  pageCount = Math.ceil(postsList.count / 12);
  category = postsList.category;
  subCategory = postsList.subCategory;
  postsList.posts.forEach((post) => {
      if (post.content.length > 100) {
        post.content = post.content.slice(0, 100) + '...';
      }
      if (post.title.length > 25) {
        post.title = post.title.slice(0, 25) + '...';
      }
    });
  return templates.get('posts-list');
};

// Renders post list, fetches template for pagination
const renderPostsList = (template) => {
  $(app.contentContainer).html(template({
    allPosts,
    category,
    subCategory,
    postsList,
  }));
  return templates.get('pagination');
};

// Renders pagination
const renderPagination = (template) => {
  $(app.paginationContainer).html(template({
    pageCount,
    category,
    allPosts,
  }));
  allPosts = false;
  window.scrollTo(0, 0);
  $('.pagination').removeClass('hidden');
  app.router.updatePageLinks();
};

const createPost = () => {
  const postData = {
    title: $('#tb-post-title').val(),
    content: $('#tb-post-content').val(),
    category: $('#tb-post-category').val(),
    subCategory: $('#tb-post-subCategory').val(),
  };
  if (!postData.title
    || !postData.content
    || !postData.category
    || !postData.subCategory) {
    return toastr.error('Post data cannot be empty!');
  }

  let postId;

  return postsData.post(postData)
    .then((response) => {
      postId = response.postId;
    })
    .then(nav.update)
    .then(nav.hideLoadingScreen)
    .then(() => {
      toastr.success('Successfuly created post!');
      const postUrl = `/posts/${postId}`;
      app.router.navigate(postUrl);
    })
    .catch(error.handle);
};

const getAll = (params) => {
  params = params || {};
  const page = params.page || 1;
  allPosts = true;
  postsData.getByCategory(null, 'all', page)
    .then(fetchPostsData)
    .then(renderPostsList)
    .then(renderPagination);
};

const getById = (params) => {
  const id = params.id;
  const postData = {};
  postsData.getById(id)
    .then((response) => {
      response.post.content = response.post.content.split('\n');
      postData.post = response.post;
      postData.commentCount = response.post.comments.length;
      return templates.get('post-details');
    })
    .then((template) => {
      $(app.contentContainer).html(template(postData));
      $(app.paginationContainer).addClass('hidden');
      widgets.commentsNav();
      app.router.updatePageLinks();
    });
};

const getByCategory = (params) => {
  const postsCategory = params.category;
  const type = params.type;
  const page = params.page;
  postsData.getByCategory(postsCategory, type, page)
    .then(fetchPostsData)
    .then(renderPostsList)
    .then(renderPagination);
};

const getCategories = () => {
  return postsData.getCategories();
};

export {
  createPost,
  getAll,
  getByCategory,
  getById,
  getCategories,
};
<commit_msg>Fixed small issue with displaying posts<commit_after>/* globals $, toastr */
import * as app from 'app';
import { postsData } from 'data';
import { templates } from 'templates';
import * as nav from 'update-nav';
import * as widgets from 'widgets';
import * as error from 'error';

let allPosts = false;
let postsList;
let pageCount;
let category;
let subCategory;

// Fetches posts from DB, fetches template for post list
const fetchPostsData = (response) => {
  postsList = response;
  pageCount = Math.ceil(postsList.count / 12);
  category = postsList.category;
  subCategory = postsList.subCategory;
  postsList.posts.forEach((post) => {
      if (post.content.length > 100) {
        post.content = post.content.slice(0, 100) + '...';
      }
      if (post.title.length > 25) {
        post.title = post.title.slice(0, 25) + '...';
      }
    });
  return templates.get('posts-list');
};

// Renders post list, fetches template for pagination
const renderPostsList = (template) => {
  $(app.contentContainer).html(template({
    allPosts,
    category,
    subCategory,
    postsList,
  }));
  return templates.get('pagination');
};

// Renders pagination
const renderPagination = (template) => {
  $(app.paginationContainer).html(template({
    pageCount,
    category,
    allPosts,
  }));
  allPosts = false;
  window.scrollTo(0, 0);
  $('.pagination').removeClass('hidden');
  app.router.updatePageLinks();
};

const createPost = () => {
  const postData = {
    title: $('#tb-post-title').val(),
    content: $('#tb-post-content').val(),
    category: $('#tb-post-category').val(),
    subCategory: $('#tb-post-subCategory').val(),
  };
  if (!postData.title
    || !postData.content
    || !postData.category
    || !postData.subCategory) {
    return toastr.error('Post data cannot be empty!');
  }

  let postId;

  return postsData.post(postData)
    .then((response) => {
      postId = response.postId;
    })
    .then(nav.update)
    .then(nav.hideLoadingScreen)
    .then(() => {
      toastr.success('Successfuly created post!');
      const postUrl = `/posts/${postId}`;
      app.router.navigate(postUrl);
    })
    .catch(error.handle);
};

const getAll = (params) => {
  params = params || {};
  const page = params.page || 1;
  allPosts = true;
  postsData.getByCategory(null, 'all', page)
    .then(fetchPostsData)
    .then(renderPostsList)
    .then(renderPagination);
};

const getById = (params) => {
  const id = params.id;
  const postData = {};
  postsData.getById(id)
    .then((response) => {
      response.post.content = response.post.content.split('\n');
      postData.post = response.post;
      postData.commentCount = response.post.comments.length;
      return templates.get('post-details');
    })
    .then((template) => {
      $(app.contentContainer).html(template(postData));
      $(app.paginationContainer).addClass('hidden');
      widgets.commentsNav();
      window.scrollTo(0, 0);
      app.router.updatePageLinks();
    });
};

const getByCategory = (params) => {
  const postsCategory = params.category;
  const type = params.type;
  const page = params.page;
  postsData.getByCategory(postsCategory, type, page)
    .then(fetchPostsData)
    .then(renderPostsList)
    .then(renderPagination);
};

const getCategories = () => {
  return postsData.getCategories();
};

export {
  createPost,
  getAll,
  getByCategory,
  getById,
  getCategories,
};
<|endoftext|>


<commit_before>define(
  'ephox.alloy.spec.FlatgridSpec',

  [
    'ephox.alloy.construct.EventHandler',
    'ephox.alloy.menu.build.ItemType',
    'ephox.alloy.menu.build.SeparatorType',
    'ephox.alloy.menu.build.WidgetType',
    'ephox.alloy.menu.util.ItemEvents',
    'ephox.alloy.menu.util.MenuEvents',
    'ephox.alloy.menu.util.MenuMarkers',
    'ephox.alloy.registry.Tagger',
    'ephox.alloy.spec.SpecSchema',
    'ephox.alloy.spec.UiSubstitutes',
    'ephox.boulder.api.FieldPresence',
    'ephox.boulder.api.FieldSchema',
    'ephox.boulder.api.Objects',
    'ephox.boulder.api.ValueSchema',
    'ephox.compass.Arr',
    'ephox.compass.Obj',
    'ephox.highway.Merger',
    'ephox.numerosity.api.JSON',
    'ephox.peanut.Fun',
    'global!Error'
  ],

  function (EventHandler, ItemType, SeparatorType, WidgetType, ItemEvents, MenuEvents, MenuMarkers, Tagger, SpecSchema, UiSubstitutes, FieldPresence, FieldSchema, Objects, ValueSchema, Arr, Obj, Merger, Json, Fun, Error) {
    var itemSchema = ValueSchema.choose(
      'type',
      {
        widget: WidgetType,
        item: ItemType,
        separator: SeparatorType
      }
    );

    var menuSchema = [
      FieldSchema.strict('items'),
      FieldSchema.strict('dom'),
      FieldSchema.strict('components'),
      FieldSchema.field(
        'markers',
        'markers',
        FieldPresence.strict(),
        MenuMarkers.itemSchema()
      ),
      FieldSchema.field(
        'members',
        'members',
        FieldPresence.strict(),
        ValueSchema.objOf([
          FieldSchema.strict('item')
        ])
      )
    ];

    var placeholder = function (label, replacements) {
      var called = false;

      var used = function () {
        return called;
      };

      var replace = function () {
        if (called === true) throw new Error(
          'Trying to use the same placeholder more than once: ' + label
        );
        called = true;
        return replacements;
      };

      return {
        name: Fun.constant(label),
        used: used,
        replace: replace
      };
    };

    var make = function (spec) {
      var detail = SpecSchema.asStructOrDie('flatgrid.spec', menuSchema, spec, [ ]);
      var builtItems = Arr.map(detail.items(), function (i) {
        var munged = detail.members().item().munge(i);
        var fallbackUid = Tagger.generate('');
        var merged = Merger.deepMerge({
          uid: fallbackUid
        }, i, munged);

        var itemInfo = ValueSchema.asStructOrDie('flatgrid.spec item', itemSchema, merged);

        return itemInfo.builder()(itemInfo);
      });

      var placeholders = {
        '<alloy.menu.items>': placeholder(
          'alloy.menu.items',
          UiSubstitutes.multiple(builtItems)
        )
      };

      var components = UiSubstitutes.substituteAll(detail, detail.components(), { }, placeholders);

      Obj.each(placeholders, function (p) {
        if (p.used() === false) throw new Error(
          'Placeholder: ' + p.name() + ' was not found in components list\nComponents: ' +
          Json.stringify(detail.components(), null, 2)
        );
      });

      return {
        uiType: 'custom',
        dom: detail.dom(),
        uid: detail.uid(),
        highlighting: {
          // Highlighting for a menu is selecting items inside the menu
          highlightClass: detail.markers().selectedItem(),
          itemClass: detail.markers().item()
        },
        events: Objects.wrapAll([
          {
            key: ItemEvents.focus(),
            value: EventHandler.nu({
              run: function (menu, simulatedEvent) {
                // Highlight the item
                var event = simulatedEvent.event();
                menu.getSystem().getByDom(event.target()).each(function (item) {
                  menu.apis().highlight(item);

                  simulatedEvent.stop();

                  // Trigger the focus event on the menu.
                  var focusTarget = menu.element();
                  menu.getSystem().triggerEvent(MenuEvents.focus(), focusTarget, {
                    target: Fun.constant(focusTarget),
                    menu: Fun.constant(menu),
                    item: item
                  });
                });
              }
            })
          }
        ]),
        representing: {
          query: function () {
            return detail.value();
          },
          set: function () { }
        },
        components: components
      };
    };

    return {
      schema: Fun.constant(menuSchema),
      make: make
    };
  }
);<commit_msg>VAN-44-wheel-hackery: Flat grid spec<commit_after>define(
  'ephox.alloy.spec.FlatgridSpec',

  [
    'ephox.alloy.construct.EventHandler',
    'ephox.alloy.menu.build.ItemType',
    'ephox.alloy.menu.build.SeparatorType',
    'ephox.alloy.menu.build.WidgetType',
    'ephox.alloy.menu.util.ItemEvents',
    'ephox.alloy.menu.util.MenuEvents',
    'ephox.alloy.menu.util.MenuMarkers',
    'ephox.alloy.registry.Tagger',
    'ephox.alloy.spec.SpecSchema',
    'ephox.alloy.spec.UiSubstitutes',
    'ephox.boulder.api.FieldPresence',
    'ephox.boulder.api.FieldSchema',
    'ephox.boulder.api.Objects',
    'ephox.boulder.api.ValueSchema',
    'ephox.compass.Arr',
    'ephox.highway.Merger',
    'ephox.peanut.Fun',
    'ephox.perhaps.Option',
    'global!Error'
  ],

  function (EventHandler, ItemType, SeparatorType, WidgetType, ItemEvents, MenuEvents, MenuMarkers, Tagger, SpecSchema, UiSubstitutes, FieldPresence, FieldSchema, Objects, ValueSchema, Arr, Merger, Fun, Option, Error) {
    var itemSchema = ValueSchema.choose(
      'type',
      {
        widget: WidgetType,
        item: ItemType,
        separator: SeparatorType
      }
    );

    var menuSchema = [
      FieldSchema.strict('items'),
      FieldSchema.strict('dom'),
      FieldSchema.strict('components'),
      FieldSchema.field(
        'markers',
        'markers',
        FieldPresence.strict(),
        MenuMarkers.itemSchema()
      ),
      FieldSchema.field(
        'members',
        'members',
        FieldPresence.strict(),
        ValueSchema.objOf([
          FieldSchema.strict('item')
        ])
      )
    ];

    var make = function (spec) {
      var detail = SpecSchema.asStructOrDie('flatgrid.spec', menuSchema, spec, [ ]);
      var builtItems = Arr.map(detail.items(), function (i) {
        var munged = detail.members().item().munge(i);
        var fallbackUid = Tagger.generate('');
        var merged = Merger.deepMerge({
          uid: fallbackUid
        }, i, munged);

        var itemInfo = ValueSchema.asStructOrDie('flatgrid.spec item', itemSchema, merged);

        return itemInfo.builder()(itemInfo);
      });

      var placeholders = {
        '<alloy.menu.items>': UiSubstitutes.multiple(builtItems)
      };

      var components = UiSubstitutes.substitutePlaces(Option.none(), detail, detail.components(), placeholders, { });

      return {
        uiType: 'custom',
        dom: detail.dom(),
        uid: detail.uid(),
        highlighting: {
          // Highlighting for a menu is selecting items inside the menu
          highlightClass: detail.markers().selectedItem(),
          itemClass: detail.markers().item()
        },
        events: Objects.wrapAll([
          {
            key: ItemEvents.focus(),
            value: EventHandler.nu({
              run: function (menu, simulatedEvent) {
                // Highlight the item
                var event = simulatedEvent.event();
                menu.getSystem().getByDom(event.target()).each(function (item) {
                  menu.apis().highlight(item);

                  simulatedEvent.stop();

                  // Trigger the focus event on the menu.
                  var focusTarget = menu.element();
                  menu.getSystem().triggerEvent(MenuEvents.focus(), focusTarget, {
                    target: Fun.constant(focusTarget),
                    menu: Fun.constant(menu),
                    item: item
                  });
                });
              }
            })
          }
        ]),
        representing: {
          query: function () {
            return detail.value();
          },
          set: function () { }
        },
        components: components
      };
    };

    return {
      schema: Fun.constant(menuSchema),
      make: make
    };
  }
);<|endoftext|>


<commit_before>'use strict';

/**
 * This file/module contains all configuration for nw things
 */

// NPM modules
var _ = require('lodash');
var nw = require('nw');

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

// Platforms to expect for the compression
var platforms = ['win64', 'osx64', 'linux64'];

/*
 * Helper function to generate our compress object
 */
var nwCompress = function(platforms) {

  // Start up an empty
  var compress = {};

  // Iterate through our platforms and add to the compress array
  _.forEach(platforms, function(platform) {

    // Our zippy ext is different depending on the platform
    var zippyExt = (_.includes(platform, 'win')) ? '.zip' : '.tar.gz';

    // Build our copress object
    compress[platform] = {
      options: {
        archive: 'dist/kalabox-' + platform + '-' + version + zippyExt
      },
      files: [
        {
          expand: true,
          cwd: 'nw/kalabox/' + platform + '/',
          src: ['**'],
          dest: 'Kalabox/'
        }
      ]
    };

  });

  // And finally return that which is compressed
  return compress;

};

/*
 * Helper function to generate our nw-builder objects
 * NOTE: we need to do this because our deps are different for each
 * platform
 */
var nwBuilder = function(platforms) {

  // Start up an empty
  var builder = {};

  // Iterate through our platforms and add to the build array
  _.forEach(platforms, function(platform) {

    // Command options to build the nw app.
    builder[platform] = {
      options: {
        version: '0.12.3',
        platforms: [platform],
        buildDir: 'nw',
        macIcns: './build/images/kalabox.icns'
        // @todo: Breaks mac build, see kalabox/kalabox#929
        //winIco: './build/images/kalabox.ico'
      },
      src: [
        './build/*',
        './build/assets/**/*',
        './build/deps/iso/*',
        './build/deps/' + platform + '/*',
        './build/deps/images/*',
        './build/images/**/*',
        './build/node_modules/**/*',
        './build/src/**/*'
      ]
    };

  });

  // And finally return the nwjs-builder commands.
  return builder;

};

/*
 * Helper function to generate npm build commands for a given platform
 */
var npmBuildCmd = function(grunt) {

  // Start a command collector
  var cmd = [];

  // Normal CMDz
  cmd.push('cd ./<%= buildDir %>');
  cmd.push('&&');
  cmd.push('npm install');

  // Allow non-production packages to be created
  if (!grunt.option('dev')) {
    cmd.push('--production');
  }

  // Give up all the glory
  return cmd.join(' ');

};

// Return the codes
module.exports = {

  /*
   * Compress our built NW packages
   */
  compress: nwCompress(platforms),

  /*
   * Build our NW packages
   */
  nwjs: nwBuilder(platforms),

  copy: {
    icns: {
      files: [
        {
          src: 'src/images/kalabox.icns',
          dest: 'nw/Kalabox/osx64/Kalabox.app/Contents/Resources/nw.icns'
        }
      ]
    },
    docs: {
      files: [
        { src: 'README.md', dest: 'nw/Kalabox/osx64/README.md' },
        { src: 'README.md', dest: 'nw/Kalabox/linux64/README.md' },
        { src: 'README.md', dest: 'nw/Kalabox/win64/README.md' },
        {
          src: 'node_modules/kalabox/scripts/uninstall-darwin.sh',
          dest: 'nw/Kalabox/osx64/uninstall.sh'
        },
        {
          src: 'node_modules/kalabox/scripts/uninstall-linux.sh',
          dest: 'nw/Kalabox/linux64/uninstall.sh'
        },
        {
          src: 'node_modules/kalabox/scripts/uninstall-win32.bat',
          dest: 'nw/Kalabox/win64/uninstall.bat'
        }
      ]
    }
  },

  /*
   * Helpers shell commands
   */
  shell: {

    /*
     * Run our NW app from built source
     */
    nw: {
      command: nw.findpath() + ' <%= buildDir %>',
      options: {
        execOptions: {
          maxBuffer: Infinity
        }
      }
    },

    /*
     * Npm install our prod deps before we nwjs task
     */
    build: npmBuildCmd

  },

  /**
   * Clean out the nw dirs
   */
  clean: {
    nw: [
      './nw',
      './dist'
    ]
  }

};
<commit_msg>kalabox/kalabox#997: formatting to appease the linting gods.<commit_after>'use strict';

/**
 * This file/module contains all configuration for nw things
 */

// NPM modules
var _ = require('lodash');
var nw = require('nw');

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

// Platforms to expect for the compression
var platforms = ['win64', 'osx64', 'linux64'];

/*
 * Helper function to generate our compress object
 */
var nwCompress = function(platforms) {

  // Start up an empty
  var compress = {};

  // Iterate through our platforms and add to the compress array
  _.forEach(platforms, function(platform) {

    // Our zippy ext is different depending on the platform
    var zippyExt = (_.includes(platform, 'win')) ? '.zip' : '.tar.gz';

    // Build our copress object
    compress[platform] = {
      options: {
        archive: 'dist/kalabox-' + platform + '-' + version + zippyExt
      },
      files: [
        {
          expand: true,
          cwd: 'nw/kalabox/' + platform + '/',
          src: ['**'],
          dest: 'Kalabox/'
        }
      ]
    };

  });

  // And finally return that which is compressed
  return compress;

};

/*
 * Helper function to generate our nw-builder objects
 * NOTE: we need to do this because our deps are different for each
 * platform
 */
var nwBuilder = function(platforms) {

  // Start up an empty
  var builder = {};

  // Iterate through our platforms and add to the build array
  _.forEach(platforms, function(platform) {

    // Command options to build the nw app.
    builder[platform] = {
      options: {
        version: '0.12.3',
        platforms: [platform],
        buildDir: 'nw',
        macIcns: './build/images/kalabox.icns'
        // @todo: Breaks mac build, see kalabox/kalabox#929
        //winIco: './build/images/kalabox.ico'
      },
      src: [
        './build/*',
        './build/assets/**/*',
        './build/deps/iso/*',
        './build/deps/' + platform + '/*',
        './build/deps/images/*',
        './build/images/**/*',
        './build/node_modules/**/*',
        './build/src/**/*'
      ]
    };

  });

  // And finally return the nwjs-builder commands.
  return builder;

};

/*
 * Helper function to generate npm build commands for a given platform
 */
var npmBuildCmd = function(grunt) {

  // Start a command collector
  var cmd = [];

  // Normal CMDz
  cmd.push('cd ./<%= buildDir %>');
  cmd.push('&&');
  cmd.push('npm install');

  // Allow non-production packages to be created
  if (!grunt.option('dev')) {
    cmd.push('--production');
  }

  // Give up all the glory
  return cmd.join(' ');

};

// Return the codes
module.exports = {

  /*
   * Compress our built NW packages
   */
  compress: nwCompress(platforms),

  /*
   * Build our NW packages
   */
  nwjs: nwBuilder(platforms),

  copy: {
    icns: {
      files: [
        {
          src: 'src/images/kalabox.icns',
          dest: 'nw/Kalabox/osx64/Kalabox.app/Contents/Resources/nw.icns'
        }
      ]
    },
    docs: {
      files: [
        {src: 'README.md', dest: 'nw/Kalabox/osx64/README.md'},
        {src: 'README.md', dest: 'nw/Kalabox/linux64/README.md'},
        {src: 'README.md', dest: 'nw/Kalabox/win64/README.md'},
        {
          src: 'node_modules/kalabox/scripts/uninstall-darwin.sh',
          dest: 'nw/Kalabox/osx64/uninstall.sh'
        },
        {
          src: 'node_modules/kalabox/scripts/uninstall-linux.sh',
          dest: 'nw/Kalabox/linux64/uninstall.sh'
        },
        {
          src: 'node_modules/kalabox/scripts/uninstall-win32.bat',
          dest: 'nw/Kalabox/win64/uninstall.bat'
        }
      ]
    }
  },

  /*
   * Helpers shell commands
   */
  shell: {

    /*
     * Run our NW app from built source
     */
    nw: {
      command: nw.findpath() + ' <%= buildDir %>',
      options: {
        execOptions: {
          maxBuffer: Infinity
        }
      }
    },

    /*
     * Npm install our prod deps before we nwjs task
     */
    build: npmBuildCmd

  },

  /**
   * Clean out the nw dirs
   */
  clean: {
    nw: [
      './nw',
      './dist'
    ]
  }

};
<|endoftext|>


<commit_before>/* This loader renders the template with underscore if no other loader was found */
'use strict';

const _ = require('lodash');
const loaderUtils = require('loader-utils');

module.exports = function (source) {
  if (this.cacheable) {
    this.cacheable();
  }
  const allLoadersButThisOne = this.loaders.filter(function (loader) {
    // Loader API changed from `loader.module` to `loader.normal` in Webpack 2.
    return (loader.module || loader.normal) !== module.exports;
  });
  // This loader shouldn't kick in if there is any other loader
  if (allLoadersButThisOne.length > 0) {
    return source;
  }
  // Skip .js files
  if (/\.js$/.test(this.resourcePath)) {
    return source;
  }

  // The following part renders the template with lodash as aminimalistic loader
  //
  // Get templating options
  const options = this.query !== '' ? loaderUtils.getOptions(this) : {};
  const template = _.template(source, _.defaults(options, { variable: 'data' }));
  // Require !!lodash - using !! will disable all loaders (e.g. babel)
  return 'var _ = require(' + loaderUtils.stringifyRequest(this, '!!' + require.resolve('lodash')) + ');' +
    'module.exports = function (templateParams) { with(templateParams) {' +
      // Execute the lodash template
      'return (' + template.source + ')();' +
    '}}';
};
<commit_msg>feat: support ES6 template string in default loader<commit_after>/* This loader renders the template with underscore if no other loader was found */
'use strict';

const _ = require('lodash');
const loaderUtils = require('loader-utils');

module.exports = function (source) {
  if (this.cacheable) {
    this.cacheable();
  }
  const allLoadersButThisOne = this.loaders.filter(function (loader) {
    // Loader API changed from `loader.module` to `loader.normal` in Webpack 2.
    return (loader.module || loader.normal) !== module.exports;
  });
  // This loader shouldn't kick in if there is any other loader
  if (allLoadersButThisOne.length > 0) {
    return source;
  }
  // Skip .js files
  if (/\.js$/.test(this.resourcePath)) {
    return source;
  }

  // The following part renders the template with lodash as aminimalistic loader
  //
  // Get templating options
  const options = this.query !== '' ? loaderUtils.getOptions(this) : {};
  const template = _.template(source, _.defaults(options, { interpolate: /<%=([\s\S]+?)%>/g, variable: 'data' }));
  // Require !!lodash - using !! will disable all loaders (e.g. babel)
  return 'var _ = require(' + loaderUtils.stringifyRequest(this, '!!' + require.resolve('lodash')) + ');' +
    'module.exports = function (templateParams) { with(templateParams) {' +
      // Execute the lodash template
      'return (' + template.source + ')();' +
    '}}';
};
<|endoftext|>


<commit_before>
var args = require('minimist')(process.argv.slice(2));
var gulp = require('gulp');
var map = require('map-stream');
var global = require('./global-variables');

gulp.task('pre-analyze:missing-events', function() {
  return gulp
    .src([global.bowerDir + "*/iron-a11y-keys.html",
          global.bowerDir + "*/paper-tabs.html"
          ])
    .pipe(map(function(file, cb) {
      file.contents = new Buffer(String(file.contents)
          // iron-a11y-keys lacks the fire-keys-pressed annotation.
          .replace(/(\n.*?_fireKeysPressed:)/, function(m, $1) {
             console.log("WARNING: patching " + file.relative + " event keys-pressed");
             return  "\n" +
                     "/**\n" +
                     " * @event keys-pressed\n" +
                     " * @param {Object} detail\n" +
                     " *  @param {boolean} detail.shift true if shift key is pressed\n" +
                     " *  @param {boolean} detail.ctrl true if ctrl key is pressed\n" +
                     " *  @param {boolean} detail.meta true if meta key is pressed\n" +
                     " *  @param {boolean} detail.alt true if alt key is pressed\n" +
                     " *  @param {String} detail.key the normalized key\n" +
                     " */" + $1;
          })
          // paper-tabs lacks select and deselect event annotations.
          .replace(/(\n.*?')(iron-select|iron-deselect)(':)/g, function(m, $1, $2, $3) {
            console.log("WARNING: patching " + file.relative + " event " + $2);
            return "\n/**\n" +
                   " * @event " + $2 + "\n" +
                   " * @param {Object} detail\n" +
                   " *  @param {Object} detail.item the item element\n" +
                   " */" + $1 + $2 + $3;
          })

      );
      cb(null, file);
    }))
    .pipe(gulp.dest(global.bowerDir));
});

gulp.task('pre-analyze:missing-behaviors', function() {
  return gulp
    .src([
          global.bowerDir + "*/paper-button-behavior.html",
          global.bowerDir + "*paper-behaviors/bower.json"
          ])
    .pipe(map(function(file, cb) {
      file.contents = new Buffer(String(file.contents)
          // paper-button-behavior is bad documented
          // TODO: remove when merged:
          // https://github.com/PolymerElements/paper-behaviors/commit/1ed3301da4f9ed873e19df1e76c6291b510ce9e2
          .replace(/\/\*\* @polymerBehavior \*\//, function(m) {
             console.log("WARNING: patching " + file.relative);
             return  "/** @polymerBehavior Polymer.PaperButtonBehavior */";
          })
          .replace(/"paper-radio-button-behavior.html"/, function(m) {
             console.log("WARNING: patching " + file.relative);
             return  '"paper-inky-focus-behavior.html"';
          })
      );
      cb(null, file);
    }))
    .pipe(gulp.dest(global.bowerDir));
});

// Hydrolysis does not support yet new events syntax
gulp.task('pre-analyze:new-syntax-events', function() {
  return gulp
    .src([global.bowerDir + "*/*.html"])
    .pipe(map(function(file, cb) {
      file.contents = new Buffer(
          String(file.contents).replace(/([ \t]+\* +)@event +([\w\-]+) +\{\{(.+)\}\} *detail.*\n/g, function(m, $1, $2, $3) {
            var ret = $1 + "@event " + $2 + "\n" +
                      $1 + " @param {Object} detail\n";

            var detail = $3.split(/ *, */);
            for (i in detail) {
              ret += detail[i].replace(/(\w+): *(\w+)/g, $1 + "  @param {$2} detail.$1 \n")
            }

            console.log("WARNING: patching event: " + $2 + " in component " + file.relative);
            return ret;
        }));
      cb(null, file);
    }))
    .pipe(gulp.dest(global.bowerDir));
});

gulp.task('pre-analyze', [
                          'pre-analyze:missing-events',
                          'pre-analyze:new-syntax-events',
                          'pre-analyze:missing-behaviors'
                         ])
<commit_msg>Fix iron-selectable annotations<commit_after>
var args = require('minimist')(process.argv.slice(2));
var gulp = require('gulp');
var map = require('map-stream');
var global = require('./global-variables');

gulp.task('pre-analyze:missing-events', function() {
  return gulp
    .src([global.bowerDir + "*/iron-a11y-keys.html",
          global.bowerDir + "*/iron-selectable.html"
          ])
    .pipe(map(function(file, cb) {
      file.contents = new Buffer(String(file.contents)
          // iron-a11y-keys lacks the fire-keys-pressed annotation.
          .replace(/(\n.*?_fireKeysPressed:)/, function(m, $1) {
             console.log("WARNING: patching " + file.relative + " event keys-pressed");
             return  "\n" +
                     "/**\n" +
                     " * @event keys-pressed\n" +
                     " * @param {Object} detail\n" +
                     " *  @param {boolean} detail.shift true if shift key is pressed\n" +
                     " *  @param {boolean} detail.ctrl true if ctrl key is pressed\n" +
                     " *  @param {boolean} detail.meta true if meta key is pressed\n" +
                     " *  @param {boolean} detail.alt true if alt key is pressed\n" +
                     " *  @param {String} detail.key the normalized key\n" +
                     " */" + $1;
          })
          // iron-selectable lacks details
          .replace(/(\n.*)(@event )(iron-select|iron-deselect|iron-activate)/g, function(m, $1, $2, $3) {
            console.log("WARNING: patching " + file.relative + " event " + $3);
            return $1 + $2 + $3 +
                   $1 + " @param {Object} detail" +
                   $1 + "  @param {Object} detail.item the item element";
          })
      );
      cb(null, file);
    }))
    .pipe(gulp.dest(global.bowerDir));
});

gulp.task('pre-analyze:missing-behaviors', function() {
  return gulp
    .src([
          global.bowerDir + "*/paper-button-behavior.html",
          global.bowerDir + "*paper-behaviors/bower.json"
          ])
    .pipe(map(function(file, cb) {
      file.contents = new Buffer(String(file.contents)
          // paper-button-behavior is bad documented
          // TODO: remove when merged:
          // https://github.com/PolymerElements/paper-behaviors/commit/1ed3301da4f9ed873e19df1e76c6291b510ce9e2
          .replace(/\/\*\* @polymerBehavior \*\//, function(m) {
             console.log("WARNING: patching " + file.relative);
             return  "/** @polymerBehavior Polymer.PaperButtonBehavior */";
          })
          .replace(/"paper-radio-button-behavior.html"/, function(m) {
             console.log("WARNING: patching " + file.relative);
             return  '"paper-inky-focus-behavior.html"';
          })
      );
      cb(null, file);
    }))
    .pipe(gulp.dest(global.bowerDir));
});

// Hydrolysis does not support yet new events syntax
gulp.task('pre-analyze:new-syntax-events', function() {
  return gulp
    .src([global.bowerDir + "*/*.html"])
    .pipe(map(function(file, cb) {
      file.contents = new Buffer(
          String(file.contents).replace(/([ \t]+\* +)@event +([\w\-]+) +\{\{(.+)\}\} *detail.*\n/g, function(m, $1, $2, $3) {
            var ret = $1 + "@event " + $2 + "\n" +
                      $1 + " @param {Object} detail\n";

            var detail = $3.split(/ *, */);
            for (i in detail) {
              ret += detail[i].replace(/(\w+): *(\w+)/g, $1 + "  @param {$2} detail.$1 \n")
            }

            console.log("WARNING: patching event: " + $2 + " in component " + file.relative);
            return ret;
        }));
      cb(null, file);
    }))
    .pipe(gulp.dest(global.bowerDir));
});

gulp.task('pre-analyze', [
                          'pre-analyze:missing-events',
                          'pre-analyze:new-syntax-events',
                          'pre-analyze:missing-behaviors'
                         ])
<|endoftext|>