<commit_before>var game = {}; // Game Object
var up = 87, left = 65, down = 83, right = 68; // KeyCodes end
var ROWS = 100, COLS = 100;

include("location.js");

game.init = function () {
    game.keypressed = null;

    game.num_dots = 3;
    game.dots = [];
    game.dots.get_head = function () {
        return game.dots[game.dots.length - 1];
    };
    game.dots.is_inside = function (loc) {
        return game.dots.filter(function (dot) { return is_same_location(dot, loc); }).length !== 0;
    };
    game.dots.find_empty_location = function () {
        while (true) {
            var loc = random_location();
            if (!game.dots.is_inside(loc))
                return loc;
        }
    };

    game.direction = null;

    game.food = null;

    game.dots.push(game.dots.find_empty_location());
    game.food = game.dots.find_empty_location();

    game.direction_changed = false;

    game.total_wait = 0;
};

game.update = function (delta) {

    game.total_wait += delta * 100;
    if (game.total_wait <= 5 || game.dots.length === 0) {
        return;
    }
    game.total_wait = 0;

    var last_dot = game.dots.get_head();

    if (is_same_location(last_dot, game.food)) {
        game.num_dots += 1;
        game.food = game.dots.find_empty_location();
    }

    // Movement
    if (game.direction !== null) {
        var is_off_screen = function (dot) {
            return dot.x < 0 || dot.x > (ROWS) ||
                   dot.y < 0 || dot.y > (COLS);
        };
        var next = make_location_to(game.direction, last_dot);

        // Fail states
        if (is_off_screen(next) || game.dots.is_inside(next)) {
            game.init();
            return;
        }

        // If we didn't die, take this new location and push it into the snake.
        game.dots.push(next);
        game.direction_changed = false;
    }

    // Remove oldest dots from snake.
    while (game.dots.length > game.num_dots)
        game.dots.shift();

};

game.render = function () {
    var draw_type = function (type) {
        return function (location) { draw(type, location.x / ROWS, location.y / COLS); }
    };
    var draw_snake = draw_type("snake");
    var draw_food  = draw_type("apple");

    // Draw the snake
    game.dots.forEach(draw_snake);
    if (game.food)
        draw_food(game.food);
};

game.keypress = function (key, pressed) {

    // Prevent switching the snake's direction twice in the same update loop.
    if (game.direction_changed)
        return;

    // Only handle when they click a key we care about (up, down, left, right).
    if (!pressed || [up, down, left, right].indexOf(key) === -1)
        return;

    // Make sure the player doesn't move into themselves.
    var is_conflicting = function (a, b) {
        return game.direction === a && key === b || game.direction === b && key === a;
    };
    if (is_conflicting(up, down) || is_conflicting(left, right))
        return;

    // Update the direction
    game.direction = key;
    game.direction_changed = true;
};<commit_msg>Prevent moving juuust outside of the map.<commit_after>var game = {}; // Game Object
var up = 87, left = 65, down = 83, right = 68; // KeyCodes end
var ROWS = 100, COLS = 100;

include("location.js");

game.init = function () {
    game.keypressed = null;

    game.num_dots = 3;
    game.dots = [];
    game.dots.get_head = function () {
        return game.dots[game.dots.length - 1];
    };
    game.dots.is_inside = function (loc) {
        return game.dots.filter(function (dot) { return is_same_location(dot, loc); }).length !== 0;
    };
    game.dots.find_empty_location = function () {
        while (true) {
            var loc = random_location();
            if (!game.dots.is_inside(loc))
                return loc;
        }
    };

    game.direction = null;

    game.food = null;

    game.dots.push(game.dots.find_empty_location());
    game.food = game.dots.find_empty_location();

    game.direction_changed = false;

    game.total_wait = 0;
};

game.update = function (delta) {

    game.total_wait += delta * 100;
    if (game.total_wait <= 5 || game.dots.length === 0) {
        return;
    }
    game.total_wait = 0;

    var last_dot = game.dots.get_head();

    if (is_same_location(last_dot, game.food)) {
        game.num_dots += 1;
        game.food = game.dots.find_empty_location();
    }

    // Movement
    if (game.direction !== null) {
        var is_off_screen = function (dot) {
            return dot.x < 0 || dot.x > (ROWS - 1) ||
                   dot.y < 0 || dot.y > (COLS - 1);
        };
        var next = make_location_to(game.direction, last_dot);

        // Fail states
        if (is_off_screen(next) || game.dots.is_inside(next)) {
            game.init();
            return;
        }

        // If we didn't die, take this new location and push it into the snake.
        game.dots.push(next);
        game.direction_changed = false;
    }

    // Remove oldest dots from snake.
    while (game.dots.length > game.num_dots)
        game.dots.shift();

};

game.render = function () {
    var draw_type = function (type) {
        return function (location) { draw(type, location.x / ROWS, location.y / COLS); }
    };
    var draw_snake = draw_type("snake");
    var draw_food  = draw_type("apple");

    // Draw the snake
    game.dots.forEach(draw_snake);
    if (game.food)
        draw_food(game.food);
};

game.keypress = function (key, pressed) {

    // Prevent switching the snake's direction twice in the same update loop.
    if (game.direction_changed)
        return;

    // Only handle when they click a key we care about (up, down, left, right).
    if (!pressed || [up, down, left, right].indexOf(key) === -1)
        return;

    // Make sure the player doesn't move into themselves.
    var is_conflicting = function (a, b) {
        return game.direction === a && key === b || game.direction === b && key === a;
    };
    if (is_conflicting(up, down) || is_conflicting(left, right))
        return;

    // Update the direction
    game.direction = key;
    game.direction_changed = true;
};<|endoftext|>


<commit_before>/**
 *
 * Copyright (c) Chong-U Lim
 * http://github.com/chongdashu
 */
this.chongdashu = this.chongdashu||{};

(function() {
    "use strict";

/**
 * SpriteMovementSystem
 * @class SpriteMovementSystem
 * @constructor
 **/
var SpriteMovementSystem = function(game) {
    this.init_(game);
};
var p = SpriteMovementSystem.prototype = chongdashu.System;
SpriteMovementSystem.prototype.constructor = SpriteMovementSystem;

    p.keyStates = {};

    p.keyboard = null;
    p.group = null;

    SpriteMovementSystem.UP = "up";
    SpriteMovementSystem.JUST_UP = "just_up";
    SpriteMovementSystem.DOWN = "down";
    SpriteMovementSystem.JUST_DOWN = "just_down";

    p.doJump = false;

    p.init_ = function(game)
    {
        console.log("[SpriteMovementSystem], init()");
        p = SpriteMovementSystem.prototype = new chongdashu.System(game);

        this.keyboard = p.state.game.input.keyboard;
        this.group = p.state.agentGroup;

        console.log(this.group);

        this.keyStates = {};

        this.keyStates[Phaser.Keyboard.W] = SpriteMovementSystem.UP;
        this.keyStates[Phaser.Keyboard.A] = SpriteMovementSystem.UP;
        this.keyStates[Phaser.Keyboard.S] = SpriteMovementSystem.UP;
        this.keyStates[Phaser.Keyboard.D] = SpriteMovementSystem.UP;
        this.keyStates[Phaser.Keyboard.SPACEBAR] = SpriteMovementSystem.UP;

    };

    p.isJustDown = function(keycode) {
        return this.keyStates[keycode] && (this.keyStates[keycode] === SpriteMovementSystem.JUST_DOWN);
    };

    p.isDown = function(keycode) {
        return this.keyStates[keycode] && (this.isJustDown(keycode) || (this.keyStates[keycode] === SpriteMovementSystem.DOWN));
    };

    p.isJustUp = function(keycode) {
        return this.keyStates[keycode] && (this.keyStates[keycode] === SpriteMovementSystem.JUST_UP);
    };

    p.isUp = function(keycode) {
        return this.keyStates[keycode] && (this.isJustUp(keycode) || (this.keyStates[keycode] === SpriteMovementSystem.UP));
    };

    p.addSprite = function(sprite) {
        this.sprites.push(sprite);
    };

    p.update = function() {
        // console.log("[SpriteMovementSystem], update()");
        p.update.call(this);
        $.each(p.components, function(index, component) {
            component.update();
        });

        this.updateGroup();
        this.updateKeyStates();

    };

    p.updateGroup = function() {
        var self = this;
        if (this.group) {
            this.group.forEach(function(sprite) {

                if (self.isDown(Phaser.Keyboard.W) && !self.isJustDown(Phaser.Keyboard.W)) {

                    if (self.doJump) {
                        console.log(sprite.anchor);
                        var squashTween = p.game.add.tween(sprite.scale).to({
                            x: 1.25,
                            y: 0.75
                        }, 200, Phaser.Easing.Exponential.Out, true);

                        squashTween.onComplete.add(function() {
                            sprite.body.velocity.y = -GLOBAL_JUMP_SPEED;
                            var squeezeTween = p.game.add.tween(sprite.scale).to({
                                x: 0.8,
                                y: 1.25
                            }, 80, Phaser.Easing.Exponential.InOut, true);

                            squeezeTween.onComplete.add(function() {
                                // sprite.anchor.set(0.5, 0.5);
                                sprite.scale.set(1,1);
                            });
                        });
                        self.doJump =false;
                    }

                }

                if (self.isJustDown(Phaser.Keyboard.W)) {

                    if (!self.doJump) {
                        sprite.anchor.set(0.5, 0.5);
                        sprite.update();

                        self.doJump = true;
                    }
                }

                if (self.isDown(Phaser.Keyboard.A)) {
                    sprite.body.velocity.x = -GLOBAL_MOVEMENT_SPEED;
                }
                if (self.isDown(Phaser.Keyboard.D)) {
                    sprite.body.velocity.x = GLOBAL_MOVEMENT_SPEED;
                }
            }, this);
        }
    };

    p.updateKeyStates = function() {
        var self = this;

        if (this.keyboard) {
            $.each(this.keyStates, function(key, state) {
                if (self.keyboard.isDown(key)) {
                    if (state == SpriteMovementSystem.JUST_UP || state == SpriteMovementSystem.UP) {
                        self.keyStates[key] = SpriteMovementSystem.JUST_DOWN;
                    }
                    else {
                        self.keyStates[key] = SpriteMovementSystem.DOWN;
                    }
                }
                else if (!self.keyboard.isDown(key)) {
                    if (state == SpriteMovementSystem.JUST_DOWN || state == SpriteMovementSystem.DOWN) {
                        self.keyStates[key] = SpriteMovementSystem.JUST_UP;
                    }
                    else {
                        self.keyStates[key] = SpriteMovementSystem.UP;
                    }
                }
            });
        }
    };

    p.render = function() {
        // console.log("[SpriteMovementSystem], render()");
        p.render.call(this);
        p.game.debug.spriteInfo(p.state.player, 16, 16);
        p.game.debug.bodyInfo(p.state.player, 16, 16);
    };

// Link
// ----
chongdashu.SpriteMovementSystem = SpriteMovementSystem;

}());

<commit_msg>Fine tune squash/squeeze of jump<commit_after>/**
 *
 * Copyright (c) Chong-U Lim
 * http://github.com/chongdashu
 */
this.chongdashu = this.chongdashu||{};

(function() {
    "use strict";

/**
 * SpriteMovementSystem
 * @class SpriteMovementSystem
 * @constructor
 **/
var SpriteMovementSystem = function(game) {
    this.init_(game);
};
var p = SpriteMovementSystem.prototype = chongdashu.System;
SpriteMovementSystem.prototype.constructor = SpriteMovementSystem;

    p.keyStates = {};

    p.keyboard = null;
    p.group = null;

    SpriteMovementSystem.UP = "up";
    SpriteMovementSystem.JUST_UP = "just_up";
    SpriteMovementSystem.DOWN = "down";
    SpriteMovementSystem.JUST_DOWN = "just_down";

    p.doJump = false;

    p.init_ = function(game)
    {
        console.log("[SpriteMovementSystem], init()");
        p = SpriteMovementSystem.prototype = new chongdashu.System(game);

        this.keyboard = p.state.game.input.keyboard;
        this.group = p.state.agentGroup;

        console.log(this.group);

        this.keyStates = {};

        this.keyStates[Phaser.Keyboard.W] = SpriteMovementSystem.UP;
        this.keyStates[Phaser.Keyboard.A] = SpriteMovementSystem.UP;
        this.keyStates[Phaser.Keyboard.S] = SpriteMovementSystem.UP;
        this.keyStates[Phaser.Keyboard.D] = SpriteMovementSystem.UP;
        this.keyStates[Phaser.Keyboard.SPACEBAR] = SpriteMovementSystem.UP;

    };

    p.isJustDown = function(keycode) {
        return this.keyStates[keycode] && (this.keyStates[keycode] === SpriteMovementSystem.JUST_DOWN);
    };

    p.isDown = function(keycode) {
        return this.keyStates[keycode] && (this.isJustDown(keycode) || (this.keyStates[keycode] === SpriteMovementSystem.DOWN));
    };

    p.isJustUp = function(keycode) {
        return this.keyStates[keycode] && (this.keyStates[keycode] === SpriteMovementSystem.JUST_UP);
    };

    p.isUp = function(keycode) {
        return this.keyStates[keycode] && (this.isJustUp(keycode) || (this.keyStates[keycode] === SpriteMovementSystem.UP));
    };

    p.addSprite = function(sprite) {
        this.sprites.push(sprite);
    };

    p.update = function() {
        // console.log("[SpriteMovementSystem], update()");
        p.update.call(this);
        $.each(p.components, function(index, component) {
            component.update();
        });

        this.updateKeyStates();
        this.updateGroup();

    };

    p.updateGroup = function() {
        var self = this;
        if (this.group) {
            this.group.forEach(function(sprite) {

                if (self.isDown(Phaser.Keyboard.W) && !self.isJustDown(Phaser.Keyboard.W)) {

                    if (self.doJump) {
                        console.log(sprite.anchor);
                        var squashTween = p.game.add.tween(sprite.scale).to({
                            x: 1.25,
                            y: 0.75
                        }, 125, Phaser.Easing.Exponential.Out, true);

                        squashTween.onComplete.add(function() {
                            sprite.body.allowGravity = true;
                            sprite.anchor.set(0.5, 0.5);
                            sprite.position.y -= 32;
                            sprite.body.velocity.y = -GLOBAL_JUMP_SPEED;
                            var squeezeTween = p.game.add.tween(sprite.scale).to({
                                x: 0.7,
                                y: 1.25
                            }, 100, Phaser.Easing.Exponential.InOut, true);

                            squeezeTween.onComplete.add(function() {
                                sprite.anchor.set(0.5, 0.5);
                                sprite.scale.set(1,1);
                            });
                        });
                        self.doJump =false;
                    }

                }

                if (self.isJustDown(Phaser.Keyboard.W)) {

                    if (!self.doJump) {
                        sprite.anchor.set(0.5, 1);
                        sprite.position.y += 32;
                        sprite.update();
                        sprite.body.allowGravity = false;
                        self.doJump = true;
                    }
                }

                if (self.isDown(Phaser.Keyboard.A)) {
                    sprite.body.velocity.x = -GLOBAL_MOVEMENT_SPEED;
                }
                if (self.isDown(Phaser.Keyboard.D)) {
                    sprite.body.velocity.x = GLOBAL_MOVEMENT_SPEED;
                }
            }, this);
        }
    };

    p.updateKeyStates = function() {
        var self = this;

        if (this.keyboard) {
            $.each(this.keyStates, function(key, state) {
                if (self.keyboard.isDown(key)) {
                    if (state == SpriteMovementSystem.JUST_UP || state == SpriteMovementSystem.UP) {
                        self.keyStates[key] = SpriteMovementSystem.JUST_DOWN;
                    }
                    else {
                        self.keyStates[key] = SpriteMovementSystem.DOWN;
                    }
                }
                else if (!self.keyboard.isDown(key)) {
                    if (state == SpriteMovementSystem.JUST_DOWN || state == SpriteMovementSystem.DOWN) {
                        self.keyStates[key] = SpriteMovementSystem.JUST_UP;
                    }
                    else {
                        self.keyStates[key] = SpriteMovementSystem.UP;
                    }
                }
            });
        }
    };

    p.render = function() {
        // console.log("[SpriteMovementSystem], render()");
        p.render.call(this);
        p.game.debug.spriteInfo(p.state.player, 16, 16);
        p.game.debug.bodyInfo(p.state.player, 16, 16);
    };

// Link
// ----
chongdashu.SpriteMovementSystem = SpriteMovementSystem;

}());

<|endoftext|>


<commit_before>import { markdownDocumentationLinkBuilder } from '../../storybook-utilities/markdownDocumentationLinkBuilder';

export default {
  title: 'Components/Promo',
  decorators: [(story) => `<div class="sprk-o-Box">${story()}</div>`],
  parameters: {
    info: `
${markdownDocumentationLinkBuilder('promo')}
    `,
    docs: { iframeHeight: 430 },
  },
};

export const defaultStory = () => `

        Title

        Subtitle

        Lorem ipsum dolor. Sit amet pede. Tempus donec et. Suspendisse
        id inventore integer eum non enim diam habitant. Maecenas nunc
        per lacus neque egestas. Diam quod curabitur.

          Learn More

`;

defaultStory.story = {
  name: 'Default',
};

export const flag = () => `

        Lorem ipsum dolor. Sit amet pede. Tempus donec et. Suspendisse
        id inventore integer eum non enim diam habitant. Maecenas nunc
        per lacus neque egestas. Diam quod curabitur.

`;

flag.story = {
  parameters: {
    docs: { iframeHeight: 300 },
  },
};

export const withImage = () => `

        Title

        Subtitle

        Lorem ipsum dolor. Sit amet pede. Tempus donec et. Suspendisse
        id inventore integer eum non enim diam habitant. Maecenas nunc
        per lacus neque egestas. Diam quod curabitur.

          Learn More

  `;

export const withReversedImage = () => `

        Title

        Subtitle

        Lorem ipsum dolor. Sit amet pede. Tempus donec et. Suspendisse
        id inventore integer eum non enim diam habitant. Maecenas nunc
        per lacus neque egestas. Diam quod curabitur.

          Learn More

`;
<commit_msg>move html default promo cta to the right<commit_after>import { markdownDocumentationLinkBuilder } from '../../storybook-utilities/markdownDocumentationLinkBuilder';

export default {
  title: 'Components/Promo',
  decorators: [(story) => `<div class="sprk-o-Box">${story()}</div>`],
  parameters: {
    info: `
${markdownDocumentationLinkBuilder('promo')}
    `,
    docs: { iframeHeight: 430 },
  },
};

export const defaultStory = () => `

        Title

        Subtitle

        Lorem ipsum dolor. Sit amet pede. Tempus donec et. Suspendisse
        id inventore integer eum non enim diam habitant. Maecenas nunc
        per lacus neque egestas. Diam quod curabitur.

          Learn More

`;

defaultStory.story = {
  name: 'Default',
};

export const flag = () => `

        Lorem ipsum dolor. Sit amet pede. Tempus donec et. Suspendisse
        id inventore integer eum non enim diam habitant. Maecenas nunc
        per lacus neque egestas. Diam quod curabitur.

`;

flag.story = {
  parameters: {
    docs: { iframeHeight: 300 },
  },
};

export const withImage = () => `

        Title

        Subtitle

        Lorem ipsum dolor. Sit amet pede. Tempus donec et. Suspendisse
        id inventore integer eum non enim diam habitant. Maecenas nunc
        per lacus neque egestas. Diam quod curabitur.

          Learn More

  `;

export const withReversedImage = () => `

        Title

        Subtitle

        Lorem ipsum dolor. Sit amet pede. Tempus donec et. Suspendisse
        id inventore integer eum non enim diam habitant. Maecenas nunc
        per lacus neque egestas. Diam quod curabitur.

          Learn More

`;
<|endoftext|>


<commit_before>var gulp = require('gulp');
var fs = require('fs');
var util = require('util');
var config = require('../config').appx;
var xml2js = require('xml2js');
var parser = new xml2js.Parser();
var builder = new xml2js.Builder();
var argv = require('yargs').argv;

function manifest() {
  var url = 'http://localhost:3000';
  if (argv.ngrok) {
    url = 'http://' + argv.ngrok + '.ngrok.com';
  } else if (argv.url) {
    url = argv.url;
  }
  var dest = argv.packaged ? config.dest : config.src;
  var buffer = fs.readFileSync(config.src, 'utf-8');
  var manifest = buffer.split('\n');
  var updated = [];
  var versionBump = '';
  manifest.forEach(function(line) {
    if (~line.indexOf('<!--Build ')) {
      versionBump = line.replace(/\d+/, function(n){ return ++n; });
    }
  });
  parser.parseString(buffer, function(err, result) {
    //console.log(util.inspect(result, false, null));
    var urlSections = result.Package.Applications[0].Application[0];
    var startPage = urlSections['$'];
    var acur = urlSections['uap:ApplicationContentUriRules'][0]['uap:Rule'][0]['$'];
    acur.Match = url;
    startPage.StartPage = url;
    var xml = builder.buildObject(result);
    var xmlArray = xml.split('\n');
    xmlArray.push(versionBump);
    fs.writeFileSync(dest, xmlArray.join('\n'));
  });
}

gulp.task('manifest', manifest);
<commit_msg>fixed ngrok url<commit_after>var gulp = require('gulp');
var fs = require('fs');
var util = require('util');
var config = require('../config').appx;
var xml2js = require('xml2js');
var parser = new xml2js.Parser();
var builder = new xml2js.Builder();
var argv = require('yargs').argv;

function manifest() {
  var url = 'http://localhost:3000';
  if (argv.ngrok) {
    url = 'https://' + argv.ngrok + '.ngrok.com';
  } else if (argv.url) {
    url = argv.url;
  }
  var dest = argv.packaged ? config.dest : config.src;
  var buffer = fs.readFileSync(config.src, 'utf-8');
  var manifest = buffer.split('\n');
  var updated = [];
  var versionBump = '';
  manifest.forEach(function(line) {
    if (~line.indexOf('<!--Build ')) {
      versionBump = line.replace(/\d+/, function(n){ return ++n; });
    }
  });
  parser.parseString(buffer, function(err, result) {
    var urlSections = result.Package.Applications[0].Application[0];
    var startPage = urlSections['$'];
    var acur = urlSections['uap:ApplicationContentUriRules'][0]['uap:Rule'][0]['$'];
    acur.Match = url;
    startPage.StartPage = url;
    var xml = builder.buildObject(result);
    var xmlArray = xml.split('\n');
    xmlArray.push(versionBump);
    fs.writeFileSync(dest, xmlArray.join('\n'));
  });
}

gulp.task('manifest', manifest);
<|endoftext|>


<commit_before>UrlsApp.factory('webhoseFactory', ['$resource', function($resource) {
  self = {};

  self.webhoseSuggestions = function(topicKeyword, newsSource) {
    var webhoseResource = $resource("https://webhose.io/search?token=b68bbb9d-dd4d-4179-95c1-d60a3cdbd303&format=json&q=politics%20" + topicKeyword + "%20site%3A"+ newsSource + ".co.uk");
    return webhoseResource.get();
  };

  return self;
}]);
<commit_msg>Fix webhose url<commit_after>UrlsApp.factory('webhoseFactory', ['$resource', function($resource) {
  self = {};

  self.webhoseSuggestions = function(topicKeyword, newsSource) {
    var webhoseResource = $resource("https://webhose.io/search?token=b68bbb9d-dd4d-4179-95c1-d60a3cdbd303&format=json&q=" + topicKeyword + "%20site%3A"+ newsSource + ".co.uk");
    return webhoseResource.get();
  };

  return self;
}]);
<|endoftext|>


<commit_before>/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
ABOUT THIS NODE.JS EXAMPLE: This example works with AWS SDK for JavaScript version 3 (v3),
which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at
https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/ses-examples.html.

Purpose:
sesClient.js is a helper function that creates an Amazon Simple Email Services (Amazon SES) service client.

Inputs (replace in code):
- REGION

*/
// snippet-start:[ses.JavaScript.createclientv3]
import  { SESClient }  from  "@aws-sdk/client-ses";
// Set the AWS Region.
const REGION = "REGION"; //e.g. "us-east-1"
// Create SNS service object.
const sesClient = new SESClient({ region: REGION });
export  { sesClient };
// snippet-end:[ses.JavaScript.createclientv3]
<commit_msg>Fix typo<commit_after>/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
ABOUT THIS NODE.JS EXAMPLE: This example works with AWS SDK for JavaScript version 3 (v3),
which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at
https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/ses-examples.html.

Purpose:
sesClient.js is a helper function that creates an Amazon Simple Email Services (Amazon SES) service client.

Inputs (replace in code):
- REGION

*/
// snippet-start:[ses.JavaScript.createclientv3]
import  { SESClient }  from  "@aws-sdk/client-ses";
// Set the AWS Region.
const REGION = "REGION"; //e.g. "us-east-1"
// Create SES service object.
const sesClient = new SESClient({ region: REGION });
export  { sesClient };
// snippet-end:[ses.JavaScript.createclientv3]
<|endoftext|>


<commit_before>'use strict';

const fastGlob = require('fast-glob');
const fs = require('fs-extra');
const klaw = require('klaw');
const path = require('path');
const {bgWhite, cyan} = require('kleur/colors');
const {log} = require('../common/logging');
const {runReleaseJob} = require('./release-job');
const {Storage} = require('@google-cloud/storage');
const {timedExecOrDie} = require('../pr-check/utils');
const zlib = require('zlib');

/**
 * @fileoverview Script that uploads a release build.
 */

const jobName = 'upload-release.js';

const SRCS_DIR = '/tmp/restored-workspace/releases';
const DEST_DIR = '/tmp/release';
const ARTIFACT_FILE_NAME = '/tmp/release.tar.gz';

const PROGRESS_WIDTH = 40;

/**
 * Merge the outputs of the flavor (both module/nomodule) into the dest dir.
 * @param {string} flavor
 */
function mergeOutputs_(flavor) {
  for (const esm of fs.readdirSync(path.join(SRCS_DIR, flavor))) {
    log('Merging', cyan(flavor), 'flavor', cyan(esm), 'build');
    fs.copySync(path.join(SRCS_DIR, flavor, esm), DEST_DIR, {
      overwrite: true,
      filter: (src) => !src.endsWith('/files.txt'),
    });
  }
}

/**
 * Merge the files.txt files for the flavor's module/nomodule outputs.
 * @param {string} flavor
 */
function mergeFilesTxt_(flavor) {
  const /** @type Map<string, Set<string>> */ filesByRtv = new Map();

  const filesTxtPaths = fastGlob.sync(
    path.join(SRCS_DIR, flavor, '*/org-cdn/rtv/*/files.txt')
  );
  for (const filesTxtPath of filesTxtPaths) {
    // filesTxtPath is guaranteed to end with '/<15-digits-rtv>/files.txt', so
    // we can extract the RTV with simple negative start/end indexes.
    const rtv = filesTxtPath.slice(-25, -10);
    if (!filesByRtv.has(rtv)) {
      filesByRtv.set(rtv, new Set());
    }

    // Add all files in this module/nomodule directory's RTV to the set.
    fs.readFileSync(filesTxtPath, {encoding: 'utf-8'})
      .trim()
      .split('\n')
      .forEach((file) => {
        filesByRtv.get(rtv)?.add(file);
      });
  }

  filesByRtv.forEach((files, rtv) => {
    log('Writing merged', cyan('files.txt'), 'for RTV', cyan(rtv));
    fs.writeFileSync(
      path.join(DEST_DIR, '/org-cdn/rtv', rtv, 'files.txt'),
      [...files].sort().join('\n')
    );
  });
}

let printProgressReady = true;

/**
 * Logs file processing progress every 1 second.
 *
 * @param {number} totalFiles
 * @param {number} processedFiles
 */
function logProgress_(totalFiles, processedFiles) {
  const percentage = Math.round((processedFiles / totalFiles) * PROGRESS_WIDTH);
  if (printProgressReady || processedFiles === totalFiles) {
    log(
      '[' +
        bgWhite(' '.repeat(percentage)) +
        '.'.repeat(PROGRESS_WIDTH - percentage) +
        ']',
      cyan(processedFiles),
      '/',
      cyan(totalFiles)
    );

    printProgressReady = false;
    setTimeout(() => {
      printProgressReady = true;
    }, 1000);
  }
}

/**
 * Compresses a single file with Brotli and writes it to ${path}.br.
 * @param {string} path
 * @param {number} sizeHint
 * @return {Promise<void>}
 */
async function brotliCompressFile_(path, sizeHint) {
  const readStream = fs.createReadStream(path);
  const writeStream = fs.createWriteStream(`${path}.br`);
  const brotli = zlib.createBrotliCompress({
    params: {
      [zlib.constants.BROTLI_PARAM_QUALITY]: zlib.constants.BROTLI_MAX_QUALITY,
      [zlib.constants.BROTLI_PARAM_SIZE_HINT]: sizeHint,
    },
  });

  return new Promise((resolve, reject) => {
    readStream
      .pipe(brotli)
      .pipe(writeStream)
      .on('finish', resolve)
      .on('error', reject);
  });
}

/**
 * Compresses all files with Brotli.
 * @return {Promise<void>}
 */
async function brotliCompressAll_() {
  let totalFiles = 0;
  for await (const {stats} of klaw(DEST_DIR)) {
    if (stats.isFile()) {
      totalFiles++;
    }
  }

  log('Brotli compression of', cyan(totalFiles), 'files:');
  const compressPromises = [];
  let compressedFiles = 0;
  for await (const {path, stats} of klaw(DEST_DIR)) {
    if (!stats.isFile()) {
      continue;
    }

    compressPromises.push(
      brotliCompressFile_(path, stats.size).then(() => {
        logProgress_(totalFiles, ++compressedFiles);
      })
    );
  }

  await Promise.all(compressPromises);
  log('Finished Brotli compression of all files.');
}

/**
 * Uploads release files to Google Cloud Storage.
 * @return {Promise<void>}
 */
async function uploadFiles_() {
  const {GCLOUD_SERVICE_KEY} = process.env;
  if (!GCLOUD_SERVICE_KEY) {
    throw new Error(
      'CircleCI job is missing the GCLOUD_SERVICE_KEY env variable'
    );
  }

  const credentials = JSON.parse(GCLOUD_SERVICE_KEY);
  if (
    !credentials.client_email ||
    !credentials.private_key ||
    !credentials.project_id
  ) {
    throw new Error(
      'GCLOUD_SERVICE_KEY is not a Google Cloud JSON service key'
    );
  }

  const storage = new Storage({credentials, projectId: credentials.project_id});
  const bucket = storage.bucket('org-cdn');

  let totalFiles = 0;
  for await (const {stats} of klaw(DEST_DIR)) {
    if (stats.isFile()) {
      totalFiles++;
    }
  }

  log('Uploading', cyan(totalFiles), 'files to storage:');
  const uploadsPromises = [];
  let uploadedFiles = 0;
  for await (const {path, stats} of klaw(DEST_DIR)) {
    if (!stats.isFile()) {
      continue;
    }

    const destination = path.slice(DEST_DIR.length + 1);
    uploadsPromises.push(
      bucket.upload(path, {destination, resumable: false}).then(() => {
        logProgress_(totalFiles, ++uploadedFiles);
      })
    );
  }

  await Promise.all(uploadsPromises);
  log('Finished uploading all files.');
}

runReleaseJob(jobName, async () => {
  fs.ensureDirSync(DEST_DIR);

  for (const flavor of fs.readdirSync(SRCS_DIR)) {
    mergeOutputs_(flavor);
    mergeFilesTxt_(flavor);
  }

  await brotliCompressAll_();
  await uploadFiles_();

  log('Archiving releases to', cyan(ARTIFACT_FILE_NAME));
  timedExecOrDie(`cd ${DEST_DIR} && tar -czf ${ARTIFACT_FILE_NAME} *`);

  log('Persisting AMP version number to workspace');
  const [versionsFile] = fastGlob.sync(
    path.join(DEST_DIR, 'org-cdn/rtv/01*/version.txt')
  );
  fs.copySync(versionsFile, '/tmp/workspace/AMP_VERSION');
});
<commit_msg>Ignore errors when trying to re-upload a file that already exists (#38301)<commit_after>'use strict';

const fastGlob = require('fast-glob');
const fs = require('fs-extra');
const klaw = require('klaw');
const path = require('path');
const {bgWhite, cyan} = require('kleur/colors');
const {log} = require('../common/logging');
const {runReleaseJob} = require('./release-job');
const {Storage} = require('@google-cloud/storage');
const {ApiError} = require('@google-cloud/common');
const {timedExecOrDie} = require('../pr-check/utils');
const zlib = require('zlib');

/**
 * @fileoverview Script that uploads a release build.
 */

const jobName = 'upload-release.js';

const SRCS_DIR = '/tmp/restored-workspace/releases';
const DEST_DIR = '/tmp/release';
const ARTIFACT_FILE_NAME = '/tmp/release.tar.gz';

const PROGRESS_WIDTH = 40;

/**
 * Merge the outputs of the flavor (both module/nomodule) into the dest dir.
 * @param {string} flavor
 */
function mergeOutputs_(flavor) {
  for (const esm of fs.readdirSync(path.join(SRCS_DIR, flavor))) {
    log('Merging', cyan(flavor), 'flavor', cyan(esm), 'build');
    fs.copySync(path.join(SRCS_DIR, flavor, esm), DEST_DIR, {
      overwrite: true,
      filter: (src) => !src.endsWith('/files.txt'),
    });
  }
}

/**
 * Merge the files.txt files for the flavor's module/nomodule outputs.
 * @param {string} flavor
 */
function mergeFilesTxt_(flavor) {
  const /** @type Map<string, Set<string>> */ filesByRtv = new Map();

  const filesTxtPaths = fastGlob.sync(
    path.join(SRCS_DIR, flavor, '*/org-cdn/rtv/*/files.txt')
  );
  for (const filesTxtPath of filesTxtPaths) {
    // filesTxtPath is guaranteed to end with '/<15-digits-rtv>/files.txt', so
    // we can extract the RTV with simple negative start/end indexes.
    const rtv = filesTxtPath.slice(-25, -10);
    if (!filesByRtv.has(rtv)) {
      filesByRtv.set(rtv, new Set());
    }

    // Add all files in this module/nomodule directory's RTV to the set.
    fs.readFileSync(filesTxtPath, {encoding: 'utf-8'})
      .trim()
      .split('\n')
      .forEach((file) => {
        filesByRtv.get(rtv)?.add(file);
      });
  }

  filesByRtv.forEach((files, rtv) => {
    log('Writing merged', cyan('files.txt'), 'for RTV', cyan(rtv));
    fs.writeFileSync(
      path.join(DEST_DIR, '/org-cdn/rtv', rtv, 'files.txt'),
      [...files].sort().join('\n')
    );
  });
}

let printProgressReady = true;

/**
 * Logs file processing progress every 1 second.
 *
 * @param {number} totalFiles
 * @param {number} processedFiles
 */
function logProgress_(totalFiles, processedFiles) {
  const percentage = Math.round((processedFiles / totalFiles) * PROGRESS_WIDTH);
  if (printProgressReady || processedFiles === totalFiles) {
    log(
      '[' +
        bgWhite(' '.repeat(percentage)) +
        '.'.repeat(PROGRESS_WIDTH - percentage) +
        ']',
      cyan(processedFiles),
      '/',
      cyan(totalFiles)
    );

    printProgressReady = false;
    setTimeout(() => {
      printProgressReady = true;
    }, 1000);
  }
}

/**
 * Compresses a single file with Brotli and writes it to ${path}.br.
 * @param {string} path
 * @param {number} sizeHint
 * @return {Promise<void>}
 */
async function brotliCompressFile_(path, sizeHint) {
  const readStream = fs.createReadStream(path);
  const writeStream = fs.createWriteStream(`${path}.br`);
  const brotli = zlib.createBrotliCompress({
    params: {
      [zlib.constants.BROTLI_PARAM_QUALITY]: zlib.constants.BROTLI_MAX_QUALITY,
      [zlib.constants.BROTLI_PARAM_SIZE_HINT]: sizeHint,
    },
  });

  return new Promise((resolve, reject) => {
    readStream
      .pipe(brotli)
      .pipe(writeStream)
      .on('finish', resolve)
      .on('error', reject);
  });
}

/**
 * Compresses all files with Brotli.
 * @return {Promise<void>}
 */
async function brotliCompressAll_() {
  let totalFiles = 0;
  for await (const {stats} of klaw(DEST_DIR)) {
    if (stats.isFile()) {
      totalFiles++;
    }
  }

  log('Brotli compression of', cyan(totalFiles), 'files:');
  const compressPromises = [];
  let compressedFiles = 0;
  for await (const {path, stats} of klaw(DEST_DIR)) {
    if (!stats.isFile()) {
      continue;
    }

    compressPromises.push(
      brotliCompressFile_(path, stats.size).then(() => {
        logProgress_(totalFiles, ++compressedFiles);
      })
    );
  }

  await Promise.all(compressPromises);
  log('Finished Brotli compression of all files.');
}

/**
 * Rethrows an error, unless the error indicates that the upload failed because the file already exists in the storage bucket.
 * @param {ApiError | Error} error
 */
function ignoreErrorWhenFileAlreadyExists_(error) {
  if (
    error instanceof ApiError &&
    error.message.includes('does not have storage.objects.delete access')
  ) {
    return;
  }
  throw error;
}

/**
 * Uploads release files to Google Cloud Storage.
 * @return {Promise<void>}
 */
async function uploadFiles_() {
  const {GCLOUD_SERVICE_KEY} = process.env;
  if (!GCLOUD_SERVICE_KEY) {
    throw new Error(
      'CircleCI job is missing the GCLOUD_SERVICE_KEY env variable'
    );
  }

  const credentials = JSON.parse(GCLOUD_SERVICE_KEY);
  if (
    !credentials.client_email ||
    !credentials.private_key ||
    !credentials.project_id
  ) {
    throw new Error(
      'GCLOUD_SERVICE_KEY is not a Google Cloud JSON service key'
    );
  }

  const storage = new Storage({credentials, projectId: credentials.project_id});
  const bucket = storage.bucket('org-cdn');

  let totalFiles = 0;
  for await (const {stats} of klaw(DEST_DIR)) {
    if (stats.isFile()) {
      totalFiles++;
    }
  }

  log('Uploading', cyan(totalFiles), 'files to storage:');
  const uploadsPromises = [];
  let uploadedFiles = 0;
  for await (const {path, stats} of klaw(DEST_DIR)) {
    if (!stats.isFile()) {
      continue;
    }

    const destination = path.slice(DEST_DIR.length + 1);
    uploadsPromises.push(
      bucket
        .upload(path, {destination, resumable: false})
        .catch(ignoreErrorWhenFileAlreadyExists_)
        .then(() => {
          logProgress_(totalFiles, ++uploadedFiles);
        })
    );
  }

  await Promise.all(uploadsPromises);
  log('Finished uploading all files.');
}

runReleaseJob(jobName, async () => {
  fs.ensureDirSync(DEST_DIR);

  for (const flavor of fs.readdirSync(SRCS_DIR)) {
    mergeOutputs_(flavor);
    mergeFilesTxt_(flavor);
  }

  await brotliCompressAll_();
  await uploadFiles_();

  log('Archiving releases to', cyan(ARTIFACT_FILE_NAME));
  timedExecOrDie(`cd ${DEST_DIR} && tar -czf ${ARTIFACT_FILE_NAME} *`);

  log('Persisting AMP version number to workspace');
  const [versionsFile] = fastGlob.sync(
    path.join(DEST_DIR, 'org-cdn/rtv/01*/version.txt')
  );
  fs.copySync(versionsFile, '/tmp/workspace/AMP_VERSION');
});
<|endoftext|>


<commit_before>/* eslint-env jest */
/* globals document */

beforeEach(() => {
  jest.resetModules()
  jest.clearAllMocks()
})

function getDocHTML () {
  return '' +
    "

" +
    "

"
}

describe('background in extension new tab page', () => {
  test('getBackgroundSettings calls localStorage as expected', () => {
    jest.mock('../localstorage-mgr', () => {
      return {
        getItem: (item) => {
          switch (item) {
            case 'tabExt.user.background.option':
              return 'photo'
            case 'tabExt.user.background.customImage':
              return 'http://foo.com/tree.png'
            case 'tabExt.user.background.color':
              return '#CDCDCD'
            case 'tabExt.user.background.imageURL':
              return 'http://example.com/my-img.png'
            default:
              return null
          }
        },
        setItem: jest.fn()
      }
    })
    const getBackgroundSettings = require('../background').getBackgroundSettings
    const settings = getBackgroundSettings()
    expect(settings).toEqual({
      backgroundOption: 'photo',
      customImage: 'http://foo.com/tree.png',
      backgroundColor: '#CDCDCD',
      imageURL: 'http://example.com/my-img.png'
    })
  })

  test('updateBackgroundSettings calls localStorage as expected', () => {
    jest.mock('../localstorage-mgr', () => {
      return {
        getItem: jest.fn(),
        setItem: jest.fn()
      }
    })
    const localStorageMgr = require('../localstorage-mgr')
    const fakeSettings = {
      backgroundOption: 'color',
      customImage: 'http://foo.com/tree.png',
      backgroundColor: '#CDCDCD',
      imageURL: 'http://example.com/my-img.png'
    }
    const updateBackgroundSettings = require('../background').updateBackgroundSettings
    updateBackgroundSettings(fakeSettings)
    expect(localStorageMgr.setItem.mock.calls).toEqual([
      ['tabExt.user.background.option', 'color'],
      ['tabExt.user.background.customImage', 'http://foo.com/tree.png'],
      ['tabExt.user.background.color', '#CDCDCD'],
      ['tabExt.user.background.imageURL', 'http://example.com/my-img.png']
    ])
  })

  test('showBackgroundColor works as expected', () => {
    // Set up our document body
    document.body.innerHTML = getDocHTML()
    const bkgElem = document.getElementById('user-background')
    expect(bkgElem.style.background).toBe('')
    const showBackgroundColor = require('../background').showBackgroundColor
    showBackgroundColor('#FF0000')

    // Background
    expect(bkgElem.style.background).toBe('rgb(255, 0, 0)')
    expect(bkgElem.style.opacity).toEqual('1')

    // Background tint
    const bkgTintElem = document.getElementById('background-tint')
    expect(bkgTintElem.style.backgroundColor).toEqual('rgba(0, 0, 0, 0.03)')
    expect(bkgTintElem.style.opacity).toEqual('1')
  })

  test('showBackgroundImg works as expected', () => {
    // Set up our document body
    document.body.innerHTML = getDocHTML()

    const showBackgroundImg = require('../background').showBackgroundImg
    const fakeImgSrc = 'http://example.com/my-img.png'
    showBackgroundImg(fakeImgSrc)

    // Check style of background element.
    const bkgElem = document.getElementById('user-background')
    expect(bkgElem.style.backgroundImage).toEqual('url(http://example.com/my-img.png)')
    expect(bkgElem.style.opacity).toEqual('1')

    //  Background tint
    const bkgTintElem = document.getElementById('background-tint')
    expect(bkgTintElem.style.backgroundColor).toEqual('rgba(0, 0, 0, 0.2)')
    expect(bkgTintElem.style.opacity).toEqual('1')
  })
})
<commit_msg>Fix tests.<commit_after>/* eslint-env jest */
/* globals document */

beforeEach(() => {
  jest.resetModules()
  jest.clearAllMocks()
})

function getDocHTML () {
  return '' +
    "

" +
    "

"
}

describe('background in extension new tab page', () => {
  test('getBackgroundSettings calls localStorage as expected', () => {
    jest.mock('../localstorage-mgr', () => {
      return {
        getItem: (item) => {
          switch (item) {
            case 'tabExt.user.background.option':
              return 'photo'
            case 'tabExt.user.background.customImage':
              return 'http://foo.com/tree.png'
            case 'tabExt.user.background.color':
              return '#CDCDCD'
            case 'tabExt.user.background.imageURL':
              return 'http://example.com/my-img.png'
            default:
              return null
          }
        },
        setItem: jest.fn()
      }
    })
    const getBackgroundSettings = require('../background').getBackgroundSettings
    const settings = getBackgroundSettings()
    expect(settings).toEqual({
      backgroundOption: 'photo',
      customImage: 'http://foo.com/tree.png',
      backgroundColor: '#CDCDCD',
      imageURL: 'http://example.com/my-img.png'
    })
  })

  test('updateBackgroundSettings calls localStorage as expected', () => {
    jest.mock('../localstorage-mgr', () => {
      return {
        getItem: jest.fn(),
        setItem: jest.fn()
      }
    })
    const localStorageMgr = require('../localstorage-mgr')
    const fakeSettings = {
      backgroundOption: 'color',
      customImage: 'http://foo.com/tree.png',
      backgroundColor: '#CDCDCD',
      imageURL: 'http://example.com/my-img.png'
    }
    const updateBackgroundSettings = require('../background').updateBackgroundSettings
    updateBackgroundSettings(fakeSettings)
    expect(localStorageMgr.setItem.mock.calls).toEqual([
      ['tabExt.user.background.option', 'color'],
      ['tabExt.user.background.customImage', 'http://foo.com/tree.png'],
      ['tabExt.user.background.color', '#CDCDCD'],
      ['tabExt.user.background.imageURL', 'http://example.com/my-img.png']
    ])
  })

  test('showBackgroundColor works as expected', () => {
    // Set up our document body
    document.body.innerHTML = getDocHTML()
    const bkgElem = document.getElementById('user-background')
    expect(bkgElem.style.background).toBe('')
    const showBackgroundColor = require('../background').showBackgroundColor
    showBackgroundColor('#FF0000')

    // Background
    expect(bkgElem.style.background).toBe('rgb(255, 0, 0)')
    expect(bkgElem.style.opacity).toEqual('1')

    // Background tint
    const bkgTintElem = document.getElementById('background-tint')
    expect(bkgTintElem.style.backgroundColor).toEqual('rgba(0, 0, 0, 0.03)')
    expect(bkgTintElem.style.opacity).toEqual('1')
  })

  test('showBackgroundImg works as expected', () => {
    // Set up our document body
    document.body.innerHTML = getDocHTML()

    const showBackgroundImg = require('../background').showBackgroundImg
    const fakeImgSrc = 'http://example.com/my-img.png'
    showBackgroundImg(fakeImgSrc)

    // Check style of background element.
    const bkgElem = document.getElementById('user-background')
    expect(bkgElem.style.backgroundImage).toEqual('url(http://example.com/my-img.png)')
    expect(bkgElem.style.opacity).toEqual('1')

    //  Background tint
    const bkgTintElem = document.getElementById('background-tint')
    expect(bkgTintElem.style.backgroundColor).toEqual('rgba(0, 0, 0, 0.15)')
    expect(bkgTintElem.style.opacity).toEqual('1')
  })
})
<|endoftext|>


<commit_before>$(document).ready(function () {
    $.getJSON(USER_URL + USER_INFO_URL, function(data) {
        var roleSwitcherButton = '';
        var createTenderButton = '';
        var loggedUserName = '';
        var options = {};
        options.path = "/";
        setCookie("roleNumber", data.roles.length, options);
        var role = data.roles[0].toString()
        if (getCookie("userRole") == undefined) {
            setCookie("userRole", role, options)
        }
        setCookie("login", data.login, options);

        if (getCookie("userRole") != undefined){
            CURRENT_ROLE = getCookie("userRole");
        }else{
            deleteCookie("userRole");
        }
        if (getCookie("roleNumber") != 0) {
            if (CURRENT_ROLE.search(CUSTOMER) != -1 & (getCookie("roleNumber") > 1)) {
                roleSwitcherButton = '<button type="button" class="btn btn-default nav_button" onclick="roleSwitcher()">Switch to Seller View</button>';
            } else if (CURRENT_ROLE.search(SELLER) != -1 & (getCookie("roleNumber") > 1)) {
                roleSwitcherButton = '<button type="button" class="btn btn-default nav_button" onclick="roleSwitcher()">Switch to Customer View</button>';
            }
            if (CURRENT_ROLE.search(CUSTOMER) != -1 & (getCookie("roleNumber") >= 1)) {
                createTenderButton = '<button type="button" class="btn btn-default nav_button" data-toggle="modal" data-target="#createTenderWindow">Create tender</button>'
            } else if (CURRENT_ROLE.search(SELLER) != -1 & (getCookie("roleNumber") >= 1)) {
                createTenderButton = '';
            }
        }
        if (getCookie("login") != null){
            loggedUserName = '
' + getCookie("login") + '
'
        }
        $('#logged_user_name').html(loggedUserName);
        $('#role_switcher_button').html(roleSwitcherButton);
        $('#create_tender_button_onHeader').html(createTenderButton);

        $.getJSON(PROPOSALS_URL + "?isNew=true&userRole=" + getCookie("userRole"), function(data){
            var newProposalsNumber = data;
            if(newProposalsNumber > 0) {
                $("#my_tenders_btn").html("My tenders " + newProposalsNumber + "");
            }
        });
    });

    /*$.getJSON(PROPOSALS_URL + "?isNew=true&userRole=" + getCookie("userRole"), function(data){
        var newProposalsNumber = data;
        if(newProposalsNumber > 0) {
            $("#my_tenders_btn").html("My tenders " + newProposalsNumber + "");
        }
    });*/
});

function goToMyTenders() {
    var options = {};
    options.path = "/";
    setCookie("roleFlag", "true", options);
    window.location.href = HOME_PAGE_URL;
}

function goToHomePage() {
    deleteCookie("roleFlag");
    var options = {};
    options.path = "/";
    setCookie("roleFlag", "false", options);
    window.location.href = HOME_PAGE_URL;
}

function goLogOut() {
    deleteCookie("roleFlag");
    var options = {};
    options.path = "/";
    setCookie("roleFlag", "false", options);
    deleteCookie("userRole");
    window.location.href = LOG_OUT;
}

function goToUserProfilePage() {
    window.location.href = USER_PROFILE_PAGE_URL;
}

function goToRegistrationPage() {
    window.location.href = REGISTRATION_PAGE_URL;
}

function goToMyDealsPage() {
    window.location.href = MYDEALS_PAGE_URL;
}

function roleSwitcher(){
    var options = {};
    options.path = "/";
    if (CURRENT_ROLE.search(CUSTOMER) != -1){
        setCookie("userRole", SELLER, options);
    }else if (CURRENT_ROLE.search(SELLER)!=-1){
        setCookie("userRole", CUSTOMER, options);
    }
    window.location.href = HOME_PAGE_URL;
}
<commit_msg>Delete comment<commit_after>$(document).ready(function () {
    $.getJSON(USER_URL + USER_INFO_URL, function(data) {
        var roleSwitcherButton = '';
        var createTenderButton = '';
        var loggedUserName = '';
        var options = {};
        options.path = "/";
        setCookie("roleNumber", data.roles.length, options);
        var role = data.roles[0].toString()
        if (getCookie("userRole") == undefined) {
            setCookie("userRole", role, options)
        }
        setCookie("login", data.login, options);

        if (getCookie("userRole") != undefined){
            CURRENT_ROLE = getCookie("userRole");
        }else{
            deleteCookie("userRole");
        }
        if (getCookie("roleNumber") != 0) {
            if (CURRENT_ROLE.search(CUSTOMER) != -1 & (getCookie("roleNumber") > 1)) {
                roleSwitcherButton = '<button type="button" class="btn btn-default nav_button" onclick="roleSwitcher()">Switch to Seller View</button>';
            } else if (CURRENT_ROLE.search(SELLER) != -1 & (getCookie("roleNumber") > 1)) {
                roleSwitcherButton = '<button type="button" class="btn btn-default nav_button" onclick="roleSwitcher()">Switch to Customer View</button>';
            }
            if (CURRENT_ROLE.search(CUSTOMER) != -1 & (getCookie("roleNumber") >= 1)) {
                createTenderButton = '<button type="button" class="btn btn-default nav_button" data-toggle="modal" data-target="#createTenderWindow">Create tender</button>'
            } else if (CURRENT_ROLE.search(SELLER) != -1 & (getCookie("roleNumber") >= 1)) {
                createTenderButton = '';
            }
        }
        if (getCookie("login") != null){
            loggedUserName = '
' + getCookie("login") + '
'
        }
        $('#logged_user_name').html(loggedUserName);
        $('#role_switcher_button').html(roleSwitcherButton);
        $('#create_tender_button_onHeader').html(createTenderButton);

        $.getJSON(PROPOSALS_URL + "?isNew=true&userRole=" + getCookie("userRole"), function(data){
            var newProposalsNumber = data;
            if(newProposalsNumber > 0) {
                $("#my_tenders_btn").html("My tenders " + newProposalsNumber + "");
            }
        });
    });
});

function goToMyTenders() {
    var options = {};
    options.path = "/";
    setCookie("roleFlag", "true", options);
    window.location.href = HOME_PAGE_URL;
}

function goToHomePage() {
    deleteCookie("roleFlag");
    var options = {};
    options.path = "/";
    setCookie("roleFlag", "false", options);
    window.location.href = HOME_PAGE_URL;
}

function goLogOut() {
    deleteCookie("roleFlag");
    var options = {};
    options.path = "/";
    setCookie("roleFlag", "false", options);
    deleteCookie("userRole");
    window.location.href = LOG_OUT;
}

function goToUserProfilePage() {
    window.location.href = USER_PROFILE_PAGE_URL;
}

function goToRegistrationPage() {
    window.location.href = REGISTRATION_PAGE_URL;
}

function goToMyDealsPage() {
    window.location.href = MYDEALS_PAGE_URL;
}

function roleSwitcher(){
    var options = {};
    options.path = "/";
    if (CURRENT_ROLE.search(CUSTOMER) != -1){
        setCookie("userRole", SELLER, options);
    }else if (CURRENT_ROLE.search(SELLER)!=-1){
        setCookie("userRole", CUSTOMER, options);
    }
    window.location.href = HOME_PAGE_URL;
}
<|endoftext|>


<commit_before>"use strict";

var MAX_STATES = 100;

// ----------------------------------------------------------------------------

function GameRunner (game, lag) {
  this._game = game;
  this._lag = typeof lag === "number" ? lag : 0;

  this._states = [{
    state: game.init (),
    frame: 0,
    inputs: []
  }];

  this._clientSockets = [];
  this._oldestModifiedInput = -1;
  this._ackInputs = [];
  this._stepInterval = -1;
}

GameRunner.prototype.removeClientSocket = function (socket) {
  var index = this._clientSockets.indexOf (socket);
  if (index >= 0) {
    this._clientSockets.splice (index, 1);
  }
  if (this._clientSockets.length < 1) {
    clearInterval (this._stepInterval);
  }
}

GameRunner.prototype.addClientSocket = function (socket) {
  if (this._clientSockets.length >= this._game.players) return null;
  if (this._clientSockets.indexOf (socket) >= 0) return null;
  this._clientSockets.push (socket);

  var firstInput = this._game.defaultInput ();
  firstInput.id = Math.random().toString().substr(2);
  this._states[0].inputs.push (firstInput);

  if (this._stepInterval < 0) {
    this._stepInterval = setInterval (this._step.bind(this), this._game.dt);
  }

  return new ConnectedClient (this, firstInput.id);
}

GameRunner.prototype._step = function () {
  if (this._oldestModifiedInput >= 0) {
    for (var i = 0; i < this._states.length; ++i) {
      if (this._states[i].frame === this._oldestModifiedInput) break;
    }
    while (i > 0) {
      states[i-1] = {
        state: this._game.step (this._states[i].inputs, this._states[i].state),
        frame: this._states[i].frame + 1,
        inputs: this._states[i-1].inputs
      };
      i--;
    }
    this._oldestModifiedInput = -1;
  }

  var oldState = this._states[0];
  var newState = {
    state: this._game.step (oldState.inputs, oldState.state),
    frame: oldState.frame + 1,
    inputs: oldState.inputs.slice()
  };

  if (this._ackInputs.length > 0) {
    newState.ackInputs = this._ackInputs;
    this._ackInputs = [];
  }

  this._states.unshift (newState);
  if (this._states.length > MAX_STATES) this._states.pop ();

  if (this._lag) {
    setTimeout (function(){ this._sendState (newState); }, this._lag);
  } else {
    this._sendState (newState);
  }
}

GameRunner.prototype._sendState = function (state) {
  console.log (state);
  console.log (this._clientSockets.length);
  for (var i = 0; i < this._clientSockets.length; ++i) {
    this._clientSockets[i].volatile.json.send (state);
  }
}

// ----------------------------------------------------------------------------

function ConnectedClient (runner, inputId) {
  this._inputId = inputId;
  this._runner = runner;
}

ConnectedClient.prototype.acceptInput = function (ackId, frame, input) {
  this._runner._oldestModifiedInput = frame;
  this._runner._ackInputs.push (ackId);
  input.id = this._inputId;

  console.log ("accepted input");
  console.log (this._runner._states[0].frame);

  var states = this._runner._states;

  for (var i = 0; i < states.length; ++i) {
    if (states[i].frame === frame) {
      for (var j = 0; j < states[i].inputs.length; ++j) {
        if (states[i].inputs[j].id === input.id) {
          while (i >= 0) {
            states[i].inputs[j] = input;
            i--;
          }
          return;
        }
      }
    }
  }
}

// ----------------------------------------------------------------------------

module.exports = GameRunner;

<commit_msg>Removed debug console logs<commit_after>"use strict";

var MAX_STATES = 100;

// ----------------------------------------------------------------------------

function GameRunner (game, lag) {
  this._game = game;
  this._lag = typeof lag === "number" ? lag : 0;

  this._states = [{
    state: game.init (),
    frame: 0,
    inputs: []
  }];

  this._clientSockets = [];
  this._oldestModifiedInput = -1;
  this._ackInputs = [];
  this._stepInterval = -1;
}

GameRunner.prototype.removeClientSocket = function (socket) {
  var index = this._clientSockets.indexOf (socket);
  if (index >= 0) {
    this._clientSockets.splice (index, 1);
  }
  if (this._clientSockets.length < 1) {
    clearInterval (this._stepInterval);
  }
}

GameRunner.prototype.addClientSocket = function (socket) {
  if (this._clientSockets.length >= this._game.players) return null;
  if (this._clientSockets.indexOf (socket) >= 0) return null;
  this._clientSockets.push (socket);

  var firstInput = this._game.defaultInput ();
  firstInput.id = Math.random().toString().substr(2);
  this._states[0].inputs.push (firstInput);

  if (this._stepInterval < 0) {
    this._stepInterval = setInterval (this._step.bind(this), this._game.dt);
  }

  return new ConnectedClient (this, firstInput.id);
}

GameRunner.prototype._step = function () {
  if (this._oldestModifiedInput >= 0) {
    for (var i = 0; i < this._states.length; ++i) {
      if (this._states[i].frame === this._oldestModifiedInput) break;
    }
    while (i > 0) {
      states[i-1] = {
        state: this._game.step (this._states[i].inputs, this._states[i].state),
        frame: this._states[i].frame + 1,
        inputs: this._states[i-1].inputs
      };
      i--;
    }
    this._oldestModifiedInput = -1;
  }

  var oldState = this._states[0];
  var newState = {
    state: this._game.step (oldState.inputs, oldState.state),
    frame: oldState.frame + 1,
    inputs: oldState.inputs.slice()
  };

  if (this._ackInputs.length > 0) {
    newState.ackInputs = this._ackInputs;
    this._ackInputs = [];
  }

  this._states.unshift (newState);
  if (this._states.length > MAX_STATES) this._states.pop ();

  if (this._lag) {
    setTimeout (function(){ this._sendState (newState); }, this._lag);
  } else {
    this._sendState (newState);
  }
}

GameRunner.prototype._sendState = function (state) {
  for (var i = 0; i < this._clientSockets.length; ++i) {
    this._clientSockets[i].volatile.json.send (state);
  }
}

// ----------------------------------------------------------------------------

function ConnectedClient (runner, inputId) {
  this._inputId = inputId;
  this._runner = runner;
}

ConnectedClient.prototype.acceptInput = function (ackId, frame, input) {
  this._runner._oldestModifiedInput = frame;
  this._runner._ackInputs.push (ackId);
  input.id = this._inputId;

  var states = this._runner._states;

  for (var i = 0; i < states.length; ++i) {
    if (states[i].frame === frame) {
      for (var j = 0; j < states[i].inputs.length; ++j) {
        if (states[i].inputs[j].id === input.id) {
          while (i >= 0) {
            states[i].inputs[j] = input;
            i--;
          }
          return;
        }
      }
    }
  }
}

// ----------------------------------------------------------------------------

module.exports = GameRunner;

<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * 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.
 */
CLASS({
  package: 'foam.tutorials.todo.ui',
  name: 'TodoCitationView',
  extendsModel: 'foam.ui.DetailView',
  requires: [
    'foam.tutorials.todo.model.Todo',
  ],

  imports: [
    'dao',
  ],

  properties: [
    {
      model_: 'foam.core.types.DAOProperty',
      name: 'dao',
      onDAOUpdate: 'onDAOUpdate',
    },
    {
      name: 'className',
      defaultValue: 'todo-citation',
    },
    {
      name: 'subtaskCount',
    },
    {
      name: 'completedSubtaskCount',
    },
    {
      name: 'subtaskFraction',
      view: 'foam.ui.ProgressView',
      dynamicValue: function() {
        this.subtaskCount; this.completedSubtaskCount;
        return this.subtaskCount > 0 ?
            100 * (this.completedSubtaskCount || 0) / this.subtaskCount : 0;
      }
    },
  ],

  listeners: [
    {
      name: 'onDAOUpdate',
      isFramed: true,
      code: function() {
        if (!this.data) return;
        var d = this.dao.where(EQ(this.Todo.PARENT, this.data.id));
        apar(
          d.select(COUNT()),
          d.where(EQ(this.Todo.COMPLETED, true)).select(COUNT())
        )(function(all, complete) {
          this.subtaskCount = all.count;
          this.completedSubtaskCount = complete.count;
        }.bind(this));
      }
    },
  ],

  templates: [
    function CSS() {/*
      .todo-citation {
        align-items: center;
        border-bottom: 1px solid #eee;
        display: flex;
        font-size: 14px;
        height: 56px;
      }
      .todo-citation input {
        margin-right: 12px;
      }
      .todo-hidden {
        display: none;
      }
      .todo-subtasks {
        margin-left: 12px;
      }
    */},
    function toHTML() {/*
      <div id="<%= this.id %>" <%= this.cssClassAttr() %>>
        $$completed{ label: '' }
        $$description{ mode: 'read-only', floatingLabel: false }
        <span id="<%= this.id %>-subtasks" class="todo-hidden todo-subtasks">
          $$subtaskFraction
          <%# this.completedSubtaskCount %> / <%# this.subtaskCount %>

        <% this.setClass('todo-hidden', function() {
          return ! (self.subtaskCount > 0);
        }, this.id + '-subtasks'); %>

    */},
  ]
});
<commit_msg>TodoApp: Make the todo description grow, make progress bar smaller.<commit_after>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * 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.
 */
CLASS({
  package: 'foam.tutorials.todo.ui',
  name: 'TodoCitationView',
  extendsModel: 'foam.ui.DetailView',
  requires: [
    'foam.tutorials.todo.model.Todo',
  ],

  imports: [
    'dao',
  ],

  properties: [
    {
      model_: 'foam.core.types.DAOProperty',
      name: 'dao',
      onDAOUpdate: 'onDAOUpdate',
    },
    {
      name: 'className',
      defaultValue: 'todo-citation',
    },
    {
      name: 'subtaskCount',
    },
    {
      name: 'completedSubtaskCount',
    },
    {
      name: 'subtaskFraction',
      view: 'foam.ui.ProgressView',
      dynamicValue: function() {
        this.subtaskCount; this.completedSubtaskCount;
        return this.subtaskCount > 0 ?
            100 * (this.completedSubtaskCount || 0) / this.subtaskCount : 0;
      }
    },
  ],

  listeners: [
    {
      name: 'onDAOUpdate',
      isFramed: true,
      code: function() {
        if (!this.data) return;
        var d = this.dao.where(EQ(this.Todo.PARENT, this.data.id));
        apar(
          d.select(COUNT()),
          d.where(EQ(this.Todo.COMPLETED, true)).select(COUNT())
        )(function(all, complete) {
          this.subtaskCount = all.count;
          this.completedSubtaskCount = complete.count;
        }.bind(this));
      }
    },
  ],

  templates: [
    function CSS() {/*
      .todo-citation {
        align-items: center;
        border-bottom: 1px solid #eee;
        display: flex;
        font-size: 14px;
        height: 56px;
      }
      .todo-citation input {
        margin-right: 12px;
      }
      .todo-hidden {
        display: none;
      }
      .todo-subtasks {
        margin: 0 12px;
        white-space: nowrap;
      }
      .todo-subtasks progress {
        width: 6em;
      }
    */},
    function toHTML() {/*
      <div id="<%= this.id %>" <%= this.cssClassAttr() %>>
        $$completed{ label: '' }

$$description{ mode: 'read-only', floatingLabel: false }

        <span id="<%= this.id %>-subtasks" class="todo-hidden todo-subtasks">
          $$subtaskFraction
          <%# this.completedSubtaskCount %> / <%# this.subtaskCount %>

        <% this.setClass('todo-hidden', function() {
          return ! (self.subtaskCount > 0);
        }, this.id + '-subtasks'); %>

    */},
  ]
});
<|endoftext|>


<commit_before>// Generated on 2014-12-12 using generator-angular 0.10.0
'use strict';

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'

module.exports = function (grunt) {

  // Load grunt tasks automatically
  require('load-grunt-tasks')(grunt);

  // Time how long tasks take. Can help when optimizing build times
  require('time-grunt')(grunt);

  // Configurable paths for the application
  var appConfig = {
    app: require('./bower.json').appPath || 'app',
    dist: '../'
  };

  // Define the configuration for all the tasks
  grunt.initConfig({

    // Project settings
    yeoman: appConfig,

    // Watches files for changes and runs tasks based on the changed files
    watch: {
      bower: {
        files: ['bower.json'],
        tasks: ['wiredep']
      },
      js: {
        files: ['<%= yeoman.app %>/scripts/{,*/}*.js'],
        tasks: ['newer:jshint:all'],
        options: {
          livereload: '<%= connect.options.livereload %>'
        }
      },
      jsTest: {
        files: ['test/spec/{,*/}*.js'],
        tasks: ['newer:jshint:test', 'karma']
      },
      compass: {
        files: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
        tasks: ['compass:server', 'autoprefixer']
      },
      gruntfile: {
        files: ['Gruntfile.js']
      },
      livereload: {
        options: {
          livereload: '<%= connect.options.livereload %>'
        },
        files: [
          '<%= yeoman.app %>/{,*/}*.html',
          '.tmp/styles/{,*/}*.css',
          '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
        ]
      }
    },

    // The actual grunt server settings
    connect: {
      options: {
        port: 9000,
        // Change this to '0.0.0.0' to access the server from outside.
        hostname: 'localhost',
        livereload: 35729
      },
      livereload: {
        options: {
          open: true,
          middleware: function (connect) {
            return [
              connect.static('.tmp'),
              connect().use(
                '/bower_components',
                connect.static('./bower_components')
              ),
              connect.static(appConfig.app)
            ];
          }
        }
      },
      test: {
        options: {
          port: 9001,
          middleware: function (connect) {
            return [
              connect.static('.tmp'),
              connect.static('test'),
              connect().use(
                '/bower_components',
                connect.static('./bower_components')
              ),
              connect.static(appConfig.app)
            ];
          }
        }
      },
      dist: {
        options: {
          open: true,
          base: '<%= yeoman.dist %>'
        }
      }
    },

    // Make sure code styles are up to par and there are no obvious mistakes
    jshint: {
      options: {
        jshintrc: '.jshintrc',
        reporter: require('jshint-stylish')
      },
      all: {
        src: [
          'Gruntfile.js',
          '<%= yeoman.app %>/scripts/{,*/}*.js'
        ]
      },
      test: {
        options: {
          jshintrc: 'test/.jshintrc'
        },
        src: ['test/spec/{,*/}*.js']
      }
    },

    // Empties folders to start fresh
    clean: {
      dist: {
        files: [{
          dot: true,
          src: [
            '.tmp',
            '<%= yeoman.dist %>/{,*/}*',
            '!<%= yeoman.dist %>/.git{,*/}*',
            '!<%= yeoman.dist %>/src{,*/}*',
            '!<%= yeoman.dist %>/README.md'
          ]
        }]
      },
      server: '.tmp'
    },

    // Add vendor prefixed styles
    autoprefixer: {
      options: {
        browsers: ['last 1 version']
      },
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/styles/',
          src: '{,*/}*.css',
          dest: '.tmp/styles/'
        }]
      }
    },

    // Automatically inject Bower components into the app
    wiredep: {
      app: {
        src: ['<%= yeoman.app %>/index.html'],
        ignorePath:  /\.\.\//
      },
      sass: {
        src: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
        ignorePath: /(\.\.\/){1,2}bower_components\//
      }
    },

    // Compiles Sass to CSS and generates necessary files if requested
    compass: {
      options: {
        sassDir: '<%= yeoman.app %>/styles',
        cssDir: '.tmp/styles',
        generatedImagesDir: '.tmp/images/generated',
        imagesDir: '<%= yeoman.app %>/images',
        javascriptsDir: '<%= yeoman.app %>/scripts',
        fontsDir: '<%= yeoman.app %>/styles/fonts',
        importPath: './bower_components',
        httpImagesPath: '/images',
        httpGeneratedImagesPath: '/images/generated',
        httpFontsPath: '/styles/fonts',
        relativeAssets: false,
        assetCacheBuster: false,
        raw: 'Sass::Script::Number.precision = 10\n'
      },
      dist: {
        options: {
          generatedImagesDir: '<%= yeoman.dist %>/images/generated'
        }
      },
      server: {
        options: {
          debugInfo: true
        }
      }
    },

    // Renames files for browser caching purposes
    filerev: {
      dist: {
        src: [
          '<%= yeoman.dist %>/scripts/{,*/}*.js',
          '<%= yeoman.dist %>/styles/{,*/}*.css',
          '<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
          '<%= yeoman.dist %>/styles/fonts/*'
        ]
      }
    },

    // Reads HTML for usemin blocks to enable smart builds that automatically
    // concat, minify and revision files. Creates configurations in memory so
    // additional tasks can operate on them
    useminPrepare: {
      html: '<%= yeoman.app %>/index.html',
      options: {
        dest: '<%= yeoman.dist %>',
        flow: {
          html: {
            steps: {
              js: ['concat', 'uglifyjs'],
              css: ['cssmin']
            },
            post: {}
          }
        }
      }
    },

    // Performs rewrites based on filerev and the useminPrepare configuration
    usemin: {
      html: ['<%= yeoman.dist %>/{,*/}*.html'],
      css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
      options: {
        assetsDirs: ['<%= yeoman.dist %>','<%= yeoman.dist %>/images']
      }
    },

    // The following *-min tasks will produce minified files in the dist folder
    // By default, your `index.html`'s <!-- Usemin block --> will take care of
    // minification. These next options are pre-configured if you do not wish
    // to use the Usemin blocks.
    // cssmin: {
    //   dist: {
    //     files: {
    //       '<%= yeoman.dist %>/styles/main.css': [
    //         '.tmp/styles/{,*/}*.css'
    //       ]
    //     }
    //   }
    // },
    // uglify: {
    //   dist: {
    //     files: {
    //       '<%= yeoman.dist %>/scripts/scripts.js': [
    //         '<%= yeoman.dist %>/scripts/scripts.js'
    //       ]
    //     }
    //   }
    // },
    // concat: {
    //   dist: {}
    // },

    imagemin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/images',
          src: '{,*/}*.{png,jpg,jpeg,gif}',
          dest: '<%= yeoman.dist %>/images'
        }]
      }
    },

    svgmin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/images',
          src: '{,*/}*.svg',
          dest: '<%= yeoman.dist %>/images'
        }]
      }
    },

    htmlmin: {
      dist: {
        options: {
          collapseWhitespace: true,
          conservativeCollapse: true,
          collapseBooleanAttributes: true,
          removeCommentsFromCDATA: true,
          removeOptionalTags: true
        },
        files: [{
          expand: true,
          cwd: '<%= yeoman.dist %>',
          src: ['*.html', 'views/{,*/}*.html'],
          dest: '<%= yeoman.dist %>'
        }]
      }
    },

    // ng-annotate tries to make the code safe for minification automatically
    // by using the Angular long form for dependency injection.
    ngAnnotate: {
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/concat/scripts',
          src: ['*.js', '!oldieshim.js'],
          dest: '.tmp/concat/scripts'
        }]
      }
    },

    // Replace Google CDN references
    cdnify: {
      dist: {
        html: ['<%= yeoman.dist %>/*.html']
      }
    },

    // Copies remaining files to places other tasks can use
    copy: {
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%= yeoman.app %>',
          dest: '<%= yeoman.dist %>',
          src: [
            '*.{ico,png,txt}',
            '.htaccess',
            '*.html',
            'views/{,*/}*.html',
            'images/{,*/}*.{webp}',
            'fonts/{,*/}*.*'
          ]
        }, {
          expand: true,
          cwd: '.tmp/images',
          dest: '<%= yeoman.dist %>/images',
          src: ['generated/*']
        }, {
          expand: true,
          cwd: '.',
          src: 'bower_components/bootstrap-sass-official/assets/fonts/bootstrap/*',
          dest: '<%= yeoman.dist %>'
        }]
      },
      styles: {
        expand: true,
        cwd: '<%= yeoman.app %>/styles',
        dest: '.tmp/styles/',
        src: '{,*/}*.css'
      }
    },

    // Run some tasks in parallel to speed up the build process
    concurrent: {
      server: [
        'compass:server'
      ],
      test: [
        'compass'
      ],
      dist: [
        'compass:dist',
        'imagemin',
        'svgmin'
      ]
    },

    // Test settings
    karma: {
      unit: {
        configFile: 'test/karma.conf.js',
        singleRun: true
      }
    }
  });

  grunt.registerTask('serve', 'Compile then start a connect web server', function (target) {
    if (target === 'dist') {
      return grunt.task.run(['build', 'connect:dist:keepalive']);
    }

    grunt.task.run([
      'clean:server',
      'wiredep',
      'concurrent:server',
      'autoprefixer',
      'connect:livereload',
      'watch'
    ]);
  });

  grunt.registerTask('server', 'DEPRECATED TASK. Use the "serve" task instead', function (target) {
    grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
    grunt.task.run(['serve:' + target]);
  });

  grunt.registerTask('test', [
    'clean:server',
    'concurrent:test',
    'autoprefixer',
    'connect:test',
    'karma'
  ]);

  grunt.registerTask('build', [
    'clean:dist',
    'wiredep',
    'useminPrepare',
    'concurrent:dist',
    'autoprefixer',
    'concat',
    'ngAnnotate',
    'copy:dist',
    'cdnify',
    'cssmin',
    'uglify',
    'filerev',
    'usemin',
    'htmlmin'
  ]);

  grunt.registerTask('default', [
    'newer:jshint',
    'test',
    'build'
  ]);
};
<commit_msg>gruntfile is coping the fonts from 76d-social-icons<commit_after>// Generated on 2014-12-12 using generator-angular 0.10.0
'use strict';

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'

module.exports = function (grunt) {

  // Load grunt tasks automatically
  require('load-grunt-tasks')(grunt);

  // Time how long tasks take. Can help when optimizing build times
  require('time-grunt')(grunt);

  // Configurable paths for the application
  var appConfig = {
    app: require('./bower.json').appPath || 'app',
    dist: '../'
  };

  // Define the configuration for all the tasks
  grunt.initConfig({

    // Project settings
    yeoman: appConfig,

    // Watches files for changes and runs tasks based on the changed files
    watch: {
      bower: {
        files: ['bower.json'],
        tasks: ['wiredep']
      },
      js: {
        files: ['<%= yeoman.app %>/scripts/{,*/}*.js'],
        tasks: ['newer:jshint:all'],
        options: {
          livereload: '<%= connect.options.livereload %>'
        }
      },
      jsTest: {
        files: ['test/spec/{,*/}*.js'],
        tasks: ['newer:jshint:test', 'karma']
      },
      compass: {
        files: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
        tasks: ['compass:server', 'autoprefixer']
      },
      gruntfile: {
        files: ['Gruntfile.js']
      },
      livereload: {
        options: {
          livereload: '<%= connect.options.livereload %>'
        },
        files: [
          '<%= yeoman.app %>/{,*/}*.html',
          '.tmp/styles/{,*/}*.css',
          '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
        ]
      }
    },

    // The actual grunt server settings
    connect: {
      options: {
        port: 9000,
        // Change this to '0.0.0.0' to access the server from outside.
        hostname: 'localhost',
        livereload: 35729
      },
      livereload: {
        options: {
          open: true,
          middleware: function (connect) {
            return [
              connect.static('.tmp'),
              connect().use(
                '/bower_components',
                connect.static('./bower_components')
              ),
              connect.static(appConfig.app)
            ];
          }
        }
      },
      test: {
        options: {
          port: 9001,
          middleware: function (connect) {
            return [
              connect.static('.tmp'),
              connect.static('test'),
              connect().use(
                '/bower_components',
                connect.static('./bower_components')
              ),
              connect.static(appConfig.app)
            ];
          }
        }
      },
      dist: {
        options: {
          open: true,
          base: '<%= yeoman.dist %>'
        }
      }
    },

    // Make sure code styles are up to par and there are no obvious mistakes
    jshint: {
      options: {
        jshintrc: '.jshintrc',
        reporter: require('jshint-stylish')
      },
      all: {
        src: [
          'Gruntfile.js',
          '<%= yeoman.app %>/scripts/{,*/}*.js'
        ]
      },
      test: {
        options: {
          jshintrc: 'test/.jshintrc'
        },
        src: ['test/spec/{,*/}*.js']
      }
    },

    // Empties folders to start fresh
    clean: {
      dist: {
        files: [{
          dot: true,
          src: [
            '.tmp',
            '<%= yeoman.dist %>/{,*/}*',
            '!<%= yeoman.dist %>/.git{,*/}*',
            '!<%= yeoman.dist %>/src{,*/}*',
            '!<%= yeoman.dist %>/README.md'
          ]
        }]
      },
      server: '.tmp'
    },

    // Add vendor prefixed styles
    autoprefixer: {
      options: {
        browsers: ['last 1 version']
      },
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/styles/',
          src: '{,*/}*.css',
          dest: '.tmp/styles/'
        }]
      }
    },

    // Automatically inject Bower components into the app
    wiredep: {
      app: {
        src: ['<%= yeoman.app %>/index.html'],
        ignorePath:  /\.\.\//
      },
      sass: {
        src: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
        ignorePath: /(\.\.\/){1,2}bower_components\//
      }
    },

    // Compiles Sass to CSS and generates necessary files if requested
    compass: {
      options: {
        sassDir: '<%= yeoman.app %>/styles',
        cssDir: '.tmp/styles',
        generatedImagesDir: '.tmp/images/generated',
        imagesDir: '<%= yeoman.app %>/images',
        javascriptsDir: '<%= yeoman.app %>/scripts',
        fontsDir: '<%= yeoman.app %>/styles/fonts',
        importPath: './bower_components',
        httpImagesPath: '/images',
        httpGeneratedImagesPath: '/images/generated',
        httpFontsPath: '/styles/fonts',
        relativeAssets: false,
        assetCacheBuster: false,
        raw: 'Sass::Script::Number.precision = 10\n'
      },
      dist: {
        options: {
          generatedImagesDir: '<%= yeoman.dist %>/images/generated'
        }
      },
      server: {
        options: {
          debugInfo: true
        }
      }
    },

    // Renames files for browser caching purposes
    filerev: {
      dist: {
        src: [
          '<%= yeoman.dist %>/scripts/{,*/}*.js',
          '<%= yeoman.dist %>/styles/{,*/}*.css',
          '<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
          '<%= yeoman.dist %>/styles/fonts/*'
        ]
      }
    },

    // Reads HTML for usemin blocks to enable smart builds that automatically
    // concat, minify and revision files. Creates configurations in memory so
    // additional tasks can operate on them
    useminPrepare: {
      html: '<%= yeoman.app %>/index.html',
      options: {
        dest: '<%= yeoman.dist %>',
        flow: {
          html: {
            steps: {
              js: ['concat', 'uglifyjs'],
              css: ['cssmin']
            },
            post: {}
          }
        }
      }
    },

    // Performs rewrites based on filerev and the useminPrepare configuration
    usemin: {
      html: ['<%= yeoman.dist %>/{,*/}*.html'],
      css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
      options: {
        assetsDirs: ['<%= yeoman.dist %>','<%= yeoman.dist %>/images']
      }
    },

    // The following *-min tasks will produce minified files in the dist folder
    // By default, your `index.html`'s <!-- Usemin block --> will take care of
    // minification. These next options are pre-configured if you do not wish
    // to use the Usemin blocks.
    // cssmin: {
    //   dist: {
    //     files: {
    //       '<%= yeoman.dist %>/styles/main.css': [
    //         '.tmp/styles/{,*/}*.css'
    //       ]
    //     }
    //   }
    // },
    // uglify: {
    //   dist: {
    //     files: {
    //       '<%= yeoman.dist %>/scripts/scripts.js': [
    //         '<%= yeoman.dist %>/scripts/scripts.js'
    //       ]
    //     }
    //   }
    // },
    // concat: {
    //   dist: {}
    // },

    imagemin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/images',
          src: '{,*/}*.{png,jpg,jpeg,gif}',
          dest: '<%= yeoman.dist %>/images'
        }]
      }
    },

    svgmin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= yeoman.app %>/images',
          src: '{,*/}*.svg',
          dest: '<%= yeoman.dist %>/images'
        }]
      }
    },

    htmlmin: {
      dist: {
        options: {
          collapseWhitespace: true,
          conservativeCollapse: true,
          collapseBooleanAttributes: true,
          removeCommentsFromCDATA: true,
          removeOptionalTags: true
        },
        files: [{
          expand: true,
          cwd: '<%= yeoman.dist %>',
          src: ['*.html', 'views/{,*/}*.html'],
          dest: '<%= yeoman.dist %>'
        }]
      }
    },

    // ng-annotate tries to make the code safe for minification automatically
    // by using the Angular long form for dependency injection.
    ngAnnotate: {
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/concat/scripts',
          src: ['*.js', '!oldieshim.js'],
          dest: '.tmp/concat/scripts'
        }]
      }
    },

    // Replace Google CDN references
    cdnify: {
      dist: {
        html: ['<%= yeoman.dist %>/*.html']
      }
    },

    // Copies remaining files to places other tasks can use
    copy: {
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%= yeoman.app %>',
          dest: '<%= yeoman.dist %>',
          src: [
            '*.{ico,png,txt}',
            '.htaccess',
            '*.html',
            'views/{,*/}*.html',
            'images/{,*/}*.{webp}',
            'fonts/{,*/}*.*'
          ]
        }, {
          expand: true,
          cwd: '.tmp/images',
          dest: '<%= yeoman.dist %>/images',
          src: ['generated/*']
        }, {
          expand: true,
          cwd: '.',
          src: 'bower_components/bootstrap-sass-official/assets/fonts/bootstrap/*',
          dest: '<%= yeoman.dist %>'
        },
        {
            expand: true,
            cwd: '.',
            src: 'bower_components/76d-social-icons/assets/fonts/*',
            dest: '<%= yeoman.dist %>'
        }]
      },
      styles: {
        expand: true,
        cwd: '<%= yeoman.app %>/styles',
        dest: '.tmp/styles/',
        src: '{,*/}*.css'
      }
    },

    // Run some tasks in parallel to speed up the build process
    concurrent: {
      server: [
        'compass:server'
      ],
      test: [
        'compass'
      ],
      dist: [
        'compass:dist',
        'imagemin',
        'svgmin'
      ]
    },

    // Test settings
    karma: {
      unit: {
        configFile: 'test/karma.conf.js',
        singleRun: true
      }
    }
  });

  grunt.registerTask('serve', 'Compile then start a connect web server', function (target) {
    if (target === 'dist') {
      return grunt.task.run(['build', 'connect:dist:keepalive']);
    }

    grunt.task.run([
      'clean:server',
      'wiredep',
      'concurrent:server',
      'autoprefixer',
      'connect:livereload',
      'watch'
    ]);
  });

  grunt.registerTask('server', 'DEPRECATED TASK. Use the "serve" task instead', function (target) {
    grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
    grunt.task.run(['serve:' + target]);
  });

  grunt.registerTask('test', [
    'clean:server',
    'concurrent:test',
    'autoprefixer',
    'connect:test',
    'karma'
  ]);

  grunt.registerTask('build', [
    'clean:dist',
    'wiredep',
    'useminPrepare',
    'concurrent:dist',
    'autoprefixer',
    'concat',
    'ngAnnotate',
    'copy:dist',
    'cdnify',
    'cssmin',
    'uglify',
    'filerev',
    'usemin',
    'htmlmin'
  ]);

  grunt.registerTask('default', [
    'newer:jshint',
    'test',
    'build'
  ]);
};
<|endoftext|>


<commit_before>define(['lodash'], function(_) {
	var util = {
		// Returns the static URL for the application with the path appended.
		// If no static url is defined (global variable), it returns the
		// default.
		staticUrl: function(path) {
			var defaultStaticUrl = '/static/';
			var staticUrl = window.appStaticUrl || defaultStaticUrl;
			return staticUrl + path;
		},

		// Returns the symbol associated with the text (if there is one),
		// otherwise it returns the text unchanged. This
		convertSymbols: function(text) {
			var rules = [
				[/&dim;/g,"\u00b0"], //	diminished and half-diminished signs
				[/&hdim;/g,"\u2300"],
				[/&3;/g,"\u00b3"],//	figured bass
				[/&6;/g,"\u2076"],
				[/&7;/g,"\u2077"],
				[/&42;/g,"\u2074\u2082"],
				[/&43;/g,"\u2074\u2083"],
				[/&52;/g,"\u2075\u2082"],
				[/&53;/g,"\u2075\u2083"],
				[/&54;/g,"\u2075\u2084"],
				[/&64;/g,"\u2076\u2084"],
				[/&65;/g,"\u2076\u2085"],
				[/&73;/g,"\u2077\u2083"],
				[/&75;/g,"\u2077\u2085"],
				//[/&d5;/g,"5\u0337"],			figured bass chord of the false fifth
				//[/&d7;/g,"7\u0337"],			figured bass diminished seveth
				[/&b;/g,"\u266d"],		//	flat
				//[/&#;/g,"\u266f"],			sharp
				//[/&n;/g,"\u266e"],			natural
				//[/&bb;/g,"\ud834\udd2b"],		double flat
				//[/&##;/g,"\ud834\udd2A"],		double sharp
				["ı","\u0131"],		//	i for fake "Fi" ligature
				[/([cdefgab])b([ :])/i,"$1\u266d$2"],	//	necessary for key labels but could be changed
				[/b([0-9])/,"\u266d$1"],			//	necessary for figured bass and scale degrees but could be changed
				[/^([cdefgab])n /i,"$1\u266e "],
				[/^n([0-9])$/i,"\u266e$1"],
				[/^n$/i,"\u266e"],
				[' ', '']
			];
			var i, rule, len;

			for(i = 0, len = rules.length; i < len; i++) {
				rule = rules[i];
				text = text.replace(rule[0], rule[1]);
			}

			return text;
		},

		// Takes a triplet of hue, saturation, and color [H,S,L] and returns a
		// color string suitable for CSS or Canvas.
		toHSLString: function(color) {
			return 'hsl('+color[0]+','+color[1]+'%,'+color[2]+'%)';
		}
	};
	return util;
});
<commit_msg>added jsdoc to utils<commit_after>/**
 * @fileoverview Defines a namespace for common utility functions.
 */
define(['lodash'], function(_) {

	/**
	 * Defines a namespace for utility functions.
	 *
	 * @namespace
	 */
	var util = {

        /**
         * Returns the application-specific static URL for a given path.
		 *
		 * Note, this function depends on the global window.appStaticUrl
		 * property. The application must initialize this value, otherwise
		 * it will return the path appended to the default static URL.
         *
         * @param {string} path
         * @return {string} The static URL.
         */
		staticUrl: function(path) {
			var defaultStaticUrl = '/static/';
			var staticUrl = window.appStaticUrl || defaultStaticUrl;
			return staticUrl + path;
		},

		/**
		 * Converts or maps symbols in a text string to unicode characters.
		 *
		 * This method is primarily used in rendering musical analysis.
		 *
		 * @param {string} text
		 * @return {string} Text with the symbols replaced with their unicode
		 * values.
		 */
		convertSymbols: function(text) {
			var rules = [
				[/&dim;/g,"\u00b0"], //	diminished and half-diminished signs
				[/&hdim;/g,"\u2300"],
				[/&3;/g,"\u00b3"],//	figured bass
				[/&6;/g,"\u2076"],
				[/&7;/g,"\u2077"],
				[/&42;/g,"\u2074\u2082"],
				[/&43;/g,"\u2074\u2083"],
				[/&52;/g,"\u2075\u2082"],
				[/&53;/g,"\u2075\u2083"],
				[/&54;/g,"\u2075\u2084"],
				[/&64;/g,"\u2076\u2084"],
				[/&65;/g,"\u2076\u2085"],
				[/&73;/g,"\u2077\u2083"],
				[/&75;/g,"\u2077\u2085"],
				//[/&d5;/g,"5\u0337"],			figured bass chord of the false fifth
				//[/&d7;/g,"7\u0337"],			figured bass diminished seveth
				[/&b;/g,"\u266d"],		//	flat
				//[/&#;/g,"\u266f"],			sharp
				//[/&n;/g,"\u266e"],			natural
				//[/&bb;/g,"\ud834\udd2b"],		double flat
				//[/&##;/g,"\ud834\udd2A"],		double sharp
				["ı","\u0131"],		//	i for fake "Fi" ligature
				[/([cdefgab])b([ :])/i,"$1\u266d$2"],	//	necessary for key labels but could be changed
				[/b([0-9])/,"\u266d$1"],			//	necessary for figured bass and scale degrees but could be changed
				[/^([cdefgab])n /i,"$1\u266e "],
				[/^n([0-9])$/i,"\u266e$1"],
				[/^n$/i,"\u266e"],
				[' ', '']
			];
			var i, rule, len;

			for(i = 0, len = rules.length; i < len; i++) {
				rule = rules[i];
				text = text.replace(rule[0], rule[1]);
			}

			return text;
		},

        /**
         * Takes an HSL triplet (hue, saturation, color) and returns the
		 * equivalent color string suitable for CSS/Canvas.
		 *
         * @param {Array} color The [H,S,L] triplet.
         * @return {string}
         */
		toHSLString: function(color) {
			return 'hsl('+color[0]+','+color[1]+'%,'+color[2]+'%)';
		}
	};

	return util;
});
<|endoftext|>