<commit_before>'use strict';
var _ = require('lodash-contrib'),
    util = require('util'),
    fs = require('fs'),
    path = require('path'),
    Fields = require('./fields'),
    Promise = require('mpromise');

function create_filename(file) {
    var ext = path.extname(file.name);
    var basename = path.basename(file.name, ext);
    var filename = util.format('%s_%d%s', basename, Date.now(), ext);
    return filename;
}

module.exports = Fields.BaseField.extend({
    init: function (options) {
        options.widget = options.widget || 'FileWidget';
        if (!options.upload_to) throw new TypeError('FileField require setting "upload_to"');
        this.directory = options.upload_to;
        this._super(options);
    },
    unbind: function () {
        this._super();
        this.value = _.omit(this.value, 'ws');
        if (this.value && this.value.size === 0) this.value = null;
    },
    pre_process: function () {
        var p = new Promise;
        var self = this;

        function handleDelete(cbk) {
            if (module.knox_client) {
                // TODO: Remove file from S3 Bucket
                cbk();
            } else {
                fs.unlink(self.directory + self.value.path, cbk);
            }
            self.value = null;
        }

        function handle_upload(err) {
            if (err) console.trace(err);
            if (!self.data || !self.data[self.name] || !self.data[self.name].name) {
                p.fulfill();
                return;
            }
            var uploaded_file = self.data[self.name];
            // copy file from temp location
            if (module.knox_client) {
                var stream = fs.createReadStream(uploaded_file.path);
                var filename_to_upload = '/' + create_filename(uploaded_file.name);
                module.knox_client.putStream(stream, filename_to_upload, {'Content-Length': uploaded_file.size}, function (err, res) {
                    if (err) {
                        if (err.socket && err.socket._httpMessage) {
                            res = err;
                        } else {
                            console.error('upload to amazon failed', err.stack || err);
                            p.reject(err);
                            return;
                        }
                    }

                    fs.unlink(uploaded_file.path);
                    //noinspection JSUnresolvedVariable
                    var http_message = res.socket._httpMessage;
                    var url = http_message.url.replace(/https:/, 'http:');
                    self.value = {
                        path: uploaded_file.name,
                        url: url,
                        size: uploaded_file.size
                    };
                    p.fulfill();
                });
            } else {
                var input_stream = fs.createReadStream(uploaded_file.path);
                var filename = create_filename(uploaded_file);
                var output_stream = fs.createWriteStream(path.join(self.directory, filename));
                input_stream.pipe(output_stream);
                output_stream.on("finish", function (err) {
                    if (err) throw err;
                    fs.unlink(uploaded_file.path, function (err) {
                        if (err) throw err;
                        self.value = {
                            path: filename,
                            url: '/cdn/' + filename,
                            size: uploaded_file.size
                        };
                        p.fulfill();
                    });
                });
            }
        }

        // delete old file is requested
        if (self.value && 'path' in self.value && self.data[self.name + '_clear']) {
            handleDelete(handle_upload);
        // delete temp file
        } else if (self.data && self.data[self.name] && self.data[self.name].filename) {
            handleDelete(p.resolve.bind(p));
        } else {
            handle_upload();
        }
        return p;
    }
});

module.exports.setAmazonCredentials = function (credentials) {
    try {
        var knox = require('knox');
        module.knox_client = knox.createClient(credentials);
    } catch (e) {
        console.log(e.message);
    }
};
<commit_msg>Fix issue with FileField<commit_after>'use strict';
var _ = require('lodash-contrib'),
    util = require('util'),
    fs = require('fs'),
    path = require('path'),
    Fields = require('./fields'),
    Promise = require('mpromise');

function create_filename(file) {
    var ext = path.extname(file.name);
    var basename = path.basename(file.name, ext);
    var filename = util.format('%s_%d%s', basename, Date.now(), ext);
    return filename;
}

module.exports = Fields.BaseField.extend({
    init: function (options) {
        options.widget = options.widget || 'FileWidget';
        if (!options.upload_to) throw new TypeError('FileField require setting "upload_to"');
        this.directory = options.upload_to;
        this._super(options);
    },
    unbind: function () {
        this._super();
        this.value = _.omit(this.value, 'ws');
        if (this.value && this.value.size === 0) this.value = null;
    },
    pre_process: function () {
        var p = new Promise;
        var self = this;

        function handleDelete(cbk) {
            if (module.knox_client) {
                // TODO: Remove file from S3 Bucket
                cbk();
            } else {
                fs.unlink(self.directory + self.value.path, cbk);
            }
            self.value = null;
        }

        function handle_upload(err) {
            if (err) console.trace(err);
            if (!self.data || !self.data[self.name] || !self.data[self.name].name) {
                p.fulfill();
                return;
            }
            var uploaded_file = self.data[self.name];
            // copy file from temp location
            if (module.knox_client) {
                var stream = fs.createReadStream(uploaded_file.path);
                var filename_to_upload = '/' + create_filename(uploaded_file.name);
                module.knox_client.putStream(stream, filename_to_upload, {'Content-Length': uploaded_file.size}, function (err, res) {
                    if (err) {
                        if (err.socket && err.socket._httpMessage) {
                            res = err;
                        } else {
                            console.error('upload to amazon failed', err.stack || err);
                            p.reject(err);
                            return;
                        }
                    }

                    fs.unlink(uploaded_file.path);
                    //noinspection JSUnresolvedVariable
                    var http_message = res.socket._httpMessage;
                    var url = http_message.url.replace(/https:/, 'http:');
                    self.value = {
                        path: uploaded_file.name,
                        url: url,
                        size: uploaded_file.size
                    };
                    p.fulfill();
                });
            } else {
                var input_stream = fs.createReadStream(uploaded_file.path);
                var filename = create_filename(uploaded_file);
                var output_stream = fs.createWriteStream(path.join(self.directory, filename));
                input_stream.pipe(output_stream);
                output_stream.on("finish", function (err) {
                    if (err) throw err;
                    fs.unlink(uploaded_file.path, function (err) {
                        if (err) throw err;
                        self.value = {
                            path: filename,
                            url: '/cdn/' + filename,
                            size: uploaded_file.size
                        };
                        p.fulfill();
                    });
                });
            }
        }

        // delete old file is requested
        if (self.value && 'path' in self.value && self.data && self.data[self.name + '_clear']) {
            handleDelete(handle_upload);
        // delete temp file
        } else if (self.data && self.data[self.name] && self.data[self.name].filename) {
            handleDelete(p.resolve.bind(p));
        } else {
            handle_upload();
        }
        return p;
    }
});

module.exports.setAmazonCredentials = function (credentials) {
    try {
        var knox = require('knox');
        module.knox_client = knox.createClient(credentials);
    } catch (e) {
        console.log(e.message);
    }
};
<|endoftext|>


<commit_before>var gulp = require('gulp'),                                     // Gulp JS
    path = require('path'),                                     // Path module
    rename = require('gulp-rename'),                            // File rename
    cache = require('gulp-cached'),                             // Gulp cache module
    gulpif = require('gulp-if'),                                // Gulp if module
    notify = require('gulp-notify'),                            // Plugin for notify
    projectConfig = require('../../projectConfig'),
    notifyConfig = projectConfig.notifyConfig,                  // Notify config
    modifyDate = require('../helpers/modifyDateFormatter'),     // Date formatter for notify
    browserSync = require('browser-sync');                      // Plugin for sync with browser

// Move images from assets modules of modules
module.exports = function(cb) {

    return gulp.task('move-assets', function(cb) {
        gulp.src('./markup/modules/**/assets/**/*.*')
            .pipe(cache('move-assets'))
            .pipe(rename(function(path) {
                path.dirname = '/' + path.dirname.match(/[a-zA-Z0-9]+\//)[0];
            }))
            .on('error', notify.onError(function (error) {
                return 'Something is wrong.\nLook in console.\n' + error;
            }))
            .pipe(gulp.dest('./dev/' + projectConfig.fs.staticFolderName + '/' + projectConfig.fs.imagesFolderName + '/assets'))
            .pipe(browserSync.reload({stream:true}))
            .pipe(
                gulpif(notifyConfig.useNotify,
                    notify({
                        onLast: true,
                        sound: notifyConfig.sounds.onSuccess,
                        title: notifyConfig.title,
                        message: 'Assets\'ve been moved \n'+ notifyConfig.taskFinishedText +'<%= options.date %>',
                        templateOptions: {
                            date: modifyDate.getTimeOfModify()
                        }
                    })
                )
            );

        cb(null);
    });
};   <commit_msg>update moveAssets task<commit_after>var gulp = require('gulp'),                                     // Gulp JS
    path = require('path'),                                     // Path module
    rename = require('gulp-rename'),                            // File rename
    cache = require('gulp-cached'),                             // Gulp cache module
    gulpif = require('gulp-if'),                                // Gulp if module
    notify = require('gulp-notify'),                            // Plugin for notify
    projectConfig = require('../../projectConfig'),
    notifyConfig = projectConfig.notifyConfig,                  // Notify config
    modifyDate = require('../helpers/modifyDateFormatter'),     // Date formatter for notify
    browserSync = require('browser-sync');                      // Plugin for sync with browser

// Move images from assets modules of modules
module.exports = function(cb) {

    return gulp.task('move-assets', function(cb) {
        gulp.src('./markup/modules/**/assets/**/*.*')
            .pipe(cache('move-assets'))
            .pipe(rename(function(path) {
                path.dirname = path.dirname.match(/[a-zA-Z0-9]+\//)[0];
            }))
            .on('error', notify.onError(function (error) {
                return 'Something is wrong.\nLook in console.\n' + error;
            }))
            .pipe(gulp.dest('./dev/' + projectConfig.fs.staticFolderName + '/' + projectConfig.fs.imagesFolderName + '/assets/'))
            .pipe(browserSync.reload({stream:true}))
            .pipe(
                gulpif(notifyConfig.useNotify,
                    notify({
                        onLast: true,
                        sound: notifyConfig.sounds.onSuccess,
                        title: notifyConfig.title,
                        message: 'Assets\'ve been moved \n'+ notifyConfig.taskFinishedText +'<%= options.date %>',
                        templateOptions: {
                            date: modifyDate.getTimeOfModify()
                        }
                    })
                )
            );

        cb(null);
    });
};   <|endoftext|>


<commit_before>import * as React from "react";
import MultiActionButton from "./multi-action-button.component";
import Button from "../button";
import { Accordion } from "../accordion";

import { buttonSubtextPreview } from "../../../cypress/locators/button";
import { pressTABKey, keyCode } from "../../../cypress/support/helper";

import {
  multiActionButtonList,
  multiActionButtonText,
  multiActionButton,
  multiActionButtonComponent,
} from "../../../cypress/locators/multi-action-button";
import { accordionDefaultTitle } from "../../../cypress/locators/accordion";

import CypressMountWithProviders from "../../../cypress/support/component-helper/cypress-mount";

const testData = ["mp150ú¿¡üßä", "!@#$%^*()_+-=~[];:.,?{}&\"'<>"];
const MultiActionButtonList = ({ ...props }) => {
  return (

      <MultiActionButton {...props}>
        <Button buttonType="primary">Example Button</Button>
        <Button buttonType="secondary">Example Button with long text</Button>
        <Button buttonType="tertiary">Short</Button>
      </MultiActionButton>

  );
};

context("Tests for MultiActionButton component", () => {
  describe("check props for MultiActionButton component", () => {
    it.each(testData)(
      "should render Multi Action Button text using %s as special characters",
      (text) => {
        CypressMountWithProviders(<MultiActionButtonList text={text} />);

        multiActionButtonText().should("have.text", text);
      }
    );

    it("should check Multi Action Button data element prop", () => {
      CypressMountWithProviders(
        <MultiActionButtonList data-element="multi-action-button-cypress-element" />
      );

      multiActionButtonComponent().should(
        "have.attr",
        "data-element",
        "multi-action-button-cypress-element"
      );
    });

    it("should check Multi Action Button data role prop", () => {
      CypressMountWithProviders(
        <MultiActionButtonList data-role="multi-action-button-cypress-role" />
      );

      multiActionButtonComponent().should(
        "have.attr",
        "data-role",
        "multi-action-button-cypress-role"
      );
    });

    it.each(testData)(
      "should render Multi Action Button subtext with %s as special characters",
      (subtext) => {
        CypressMountWithProviders(
          <MultiActionButtonList size="large" subtext={subtext} />
        );

        buttonSubtextPreview().should("have.text", subtext);
      }
    );

    it.each([
      [
        "primary",
        "rgb(0, 126, 69) none repeat scroll 0% 0% / auto padding-box border-box",
        "rgb(255, 255, 255)",
        "rgba(0, 0, 0, 0)",
      ],
      [
        "secondary",
        "rgba(0, 0, 0, 0) none repeat scroll 0% 0% / auto padding-box border-box",
        "rgb(0, 126, 69)",
        "rgb(0, 126, 69)",
      ],
      [
        "tertiary",
        "rgba(0, 0, 0, 0) none repeat scroll 0% 0% / auto padding-box border-box",
        "rgb(0, 126, 69)",
        "rgba(0, 0, 0, 0)",
      ],
    ])(
      "check %s type of Multi action button uses %s as background color and %s as color and %s as border color",
      (buttonType, backgroundColor, color, borderColor) => {
        CypressMountWithProviders(
          <MultiActionButtonList buttonType={buttonType} />
        );

        multiActionButtonComponent()
          .children()
          .should("have.css", "background", backgroundColor)
          .and("have.css", "color", color)
          .and("have.css", "border-color", borderColor);
      }
    );

    it.each([
      [
        "primary",
        "rgb(0, 126, 69) none repeat scroll 0% 0% / auto padding-box border-box",
        "rgb(255, 255, 255)",
        "rgba(0, 0, 0, 0)",
      ],
      [
        "secondary",
        "rgba(0, 0, 0, 0) none repeat scroll 0% 0% / auto padding-box border-box",
        "rgb(0, 126, 69)",
        "rgb(0, 126, 69)",
      ],
      [
        "transparent",
        "rgb(239, 239, 239) none repeat scroll 0% 0% / auto padding-box border-box",
        "rgb(0, 0, 0)",
        "rgba(0, 0, 0, 0)",
      ],
    ])(
      "check %s Multi action button with %s as background color and %s as color and %s as border color",
      (as, backgroundColor, color, borderColor) => {
        CypressMountWithProviders(<MultiActionButtonList as={as} />);

        multiActionButtonComponent()
          .children()
          .should("have.css", "background", backgroundColor)
          .and("have.css", "color", color)
          .and("have.css", "border-color", borderColor);
      }
    );

    it.each([
      ["small", "32px"],
      ["medium", "40px"],
      ["large", "48px"],
    ])("should render Multi Action Button with %s size", (size, width) => {
      CypressMountWithProviders(<MultiActionButtonList size={size} />);

      multiActionButtonComponent()
        .should("have.css", "width")
        .and("contain", width);
    });

    it.each(["left", "right"])(
      "should align the button to the %s",
      (alignment) => {
        CypressMountWithProviders(<MultiActionButtonList align={alignment} />);

        multiActionButtonComponent().should("have.css", `margin-${alignment}`);
      }
    );

    it("should check Multi Action Button is disabled", () => {
      CypressMountWithProviders(
        <MultiActionButtonList disabled text="Multi Action Button" />
      );

      multiActionButtonComponent().trigger("mouseover", { force: true });
      multiActionButtonComponent()
        .children()
        .should("be.disabled")
        .and("have.attr", "disabled");
    });

    it("should invoke Multi Action Button component and expands and contains three items", () => {
      CypressMountWithProviders(<MultiActionButtonList />);

      multiActionButtonComponent().trigger("mouseover");
      multiActionButtonList()
        .eq(0)
        .should("have.text", "Example Button")
        .and("be.visible");
      multiActionButtonList()
        .eq(1)
        .should("have.text", "Example Button with long text")
        .and("be.visible");
      multiActionButtonList()
        .eq(2)
        .should("have.text", "Short")
        .and("be.visible");
    });

    it("should render Multi Action Button with golden border when hit Tab key 1 time", () => {
      CypressMountWithProviders(<MultiActionButtonList />);

      pressTABKey(1);
      multiActionButtonComponent()
        .children()
        .should("have.css", "border", "3px solid rgb(255, 181, 0)");
    });

    it("should render Multi Action Button with specific background colour when hovering", () => {
      CypressMountWithProviders(<MultiActionButtonList />);

      multiActionButtonComponent().trigger("mouseover");
      multiActionButton().should(
        "have.css",
        "background-color",
        "rgb(0, 77, 42)"
      );
    });

    it("should invoke Multi Action Button component in a hidden container", () => {
      CypressMountWithProviders(
        <Accordion title="Heading">
          <MultiActionButtonList />
        </Accordion>
      );

      accordionDefaultTitle()
        .trigger("keydown", keyCode("Enter"))
        .then(() => {
          multiActionButtonComponent().children().trigger("mouseover");
          multiActionButtonList()
            .eq(0)
            .should("have.text", "Example Button")
            .and("be.visible");
          multiActionButtonList()
            .eq(1)
            .should("have.text", "Example Button with long text")
            .and("be.visible");
          multiActionButtonList()
            .eq(2)
            .should("have.text", "Short")
            .and("be.visible");
        });
    });
  });

  describe("pressing tab while MultiActionButton is open", () => {
    it("should focus second MultiActionButton", () => {
      CypressMountWithProviders(
        <>
          <MultiActionButtonList />
          <MultiActionButtonList />
        </>
      );

      multiActionButton()
        .eq(0)
        .click()
        .then(() => {
          multiActionButtonList().eq(1).focus();
          multiActionButton().eq(0).tab();
          multiActionButton().eq(1).should("be.focused");
        });
    });
  });
});
<commit_msg>test(multi-action-button): test fix<commit_after>import * as React from "react";
import MultiActionButton from "./multi-action-button.component";
import Button from "../button";
import { Accordion } from "../accordion";

import { buttonSubtextPreview } from "../../../cypress/locators/button";
import { pressTABKey, keyCode } from "../../../cypress/support/helper";

import {
  multiActionButtonList,
  multiActionButtonText,
  multiActionButton,
  multiActionButtonComponent,
} from "../../../cypress/locators/multi-action-button";
import { accordionDefaultTitle } from "../../../cypress/locators/accordion";

import CypressMountWithProviders from "../../../cypress/support/component-helper/cypress-mount";

const testData = ["mp150ú¿¡üßä", "!@#$%^*()_+-=~[];:.,?{}&\"'<>"];
const MultiActionButtonList = ({ ...props }) => {
  return (

      <MultiActionButton {...props}>
        <Button buttonType="primary">Example Button</Button>
        <Button buttonType="secondary">Example Button with long text</Button>
        <Button buttonType="tertiary">Short</Button>
      </MultiActionButton>

  );
};

context("Tests for MultiActionButton component", () => {
  describe("check props for MultiActionButton component", () => {
    it.each(testData)(
      "should render Multi Action Button text using %s as special characters",
      (text) => {
        CypressMountWithProviders(<MultiActionButtonList text={text} />);

        multiActionButtonText().should("have.text", text);
      }
    );

    it("should check Multi Action Button data element prop", () => {
      CypressMountWithProviders(
        <MultiActionButtonList data-element="multi-action-button-cypress-element" />
      );

      multiActionButtonComponent().should(
        "have.attr",
        "data-element",
        "multi-action-button-cypress-element"
      );
    });

    it("should check Multi Action Button data role prop", () => {
      CypressMountWithProviders(
        <MultiActionButtonList data-role="multi-action-button-cypress-role" />
      );

      multiActionButtonComponent().should(
        "have.attr",
        "data-role",
        "multi-action-button-cypress-role"
      );
    });

    it.each(testData)(
      "should render Multi Action Button subtext with %s as special characters",
      (subtext) => {
        CypressMountWithProviders(
          <MultiActionButtonList size="large" subtext={subtext} />
        );

        buttonSubtextPreview().should("have.text", subtext);
      }
    );

    it.each([
      ["primary", "rgb(0, 126, 69)", "rgb(255, 255, 255)", "rgba(0, 0, 0, 0)"],
      ["secondary", "rgba(0, 0, 0, 0)", "rgb(0, 126, 69)", "rgb(0, 126, 69)"],
      ["tertiary", "rgba(0, 0, 0, 0)", "rgb(0, 126, 69)", "rgba(0, 0, 0, 0)"],
    ])(
      "check %s type of Multi action button uses %s as background color and %s as color and %s as border color",
      (buttonType, backgroundColor, color, borderColor) => {
        CypressMountWithProviders(
          <MultiActionButtonList buttonType={buttonType} />
        );

        multiActionButtonComponent()
          .children()
          .should("have.css", "background-color", backgroundColor)
          .and("have.css", "color", color)
          .and("have.css", "border-color", borderColor);
      }
    );

    it.each([
      ["primary", "rgb(0, 126, 69)", "rgb(255, 255, 255)", "rgba(0, 0, 0, 0)"],
      ["secondary", "rgba(0, 0, 0, 0)", "rgb(0, 126, 69)", "rgb(0, 126, 69)"],
      ["tertiary", "rgba(0, 0, 0, 0)", "rgb(0, 126, 69)", "rgba(0, 0, 0, 0)"],
    ])(
      "check %s Multi action button with %s as background color and %s as color and %s as border color",
      (as, backgroundColor, color, borderColor) => {
        CypressMountWithProviders(<MultiActionButtonList as={as} />);

        multiActionButtonComponent()
          .children()
          .should("have.css", "background-color", backgroundColor)
          .and("have.css", "color", color)
          .and("have.css", "border-color", borderColor);
      }
    );

    it.each([
      ["small", "32px"],
      ["medium", "40px"],
      ["large", "48px"],
    ])("should render Multi Action Button with %s size", (size, width) => {
      CypressMountWithProviders(<MultiActionButtonList size={size} />);

      multiActionButtonComponent()
        .should("have.css", "width")
        .and("contain", width);
    });

    it.each(["left", "right"])(
      "should align the button to the %s",
      (alignment) => {
        CypressMountWithProviders(<MultiActionButtonList align={alignment} />);

        multiActionButtonComponent().should("have.css", `margin-${alignment}`);
      }
    );

    it("should check Multi Action Button is disabled", () => {
      CypressMountWithProviders(
        <MultiActionButtonList disabled text="Multi Action Button" />
      );

      multiActionButtonComponent().trigger("mouseover", { force: true });
      multiActionButtonComponent()
        .children()
        .should("be.disabled")
        .and("have.attr", "disabled");
    });

    it("should invoke Multi Action Button component and expands and contains three items", () => {
      CypressMountWithProviders(<MultiActionButtonList />);

      multiActionButtonComponent().trigger("mouseover");
      multiActionButtonList()
        .eq(0)
        .should("have.text", "Example Button")
        .and("be.visible");
      multiActionButtonList()
        .eq(1)
        .should("have.text", "Example Button with long text")
        .and("be.visible");
      multiActionButtonList()
        .eq(2)
        .should("have.text", "Short")
        .and("be.visible");
    });

    it("should render Multi Action Button with golden border when hit Tab key 1 time", () => {
      CypressMountWithProviders(<MultiActionButtonList />);

      pressTABKey(1);
      multiActionButtonComponent()
        .children()
        .should("have.css", "border", "3px solid rgb(255, 181, 0)");
    });

    it("should render Multi Action Button with specific background colour when hovering", () => {
      CypressMountWithProviders(<MultiActionButtonList />);

      multiActionButtonComponent().trigger("mouseover");
      multiActionButton().should(
        "have.css",
        "background-color",
        "rgb(0, 77, 42)"
      );
    });

    it("should invoke Multi Action Button component in a hidden container", () => {
      CypressMountWithProviders(
        <Accordion title="Heading">
          <MultiActionButtonList />
        </Accordion>
      );

      accordionDefaultTitle()
        .trigger("keydown", keyCode("Enter"))
        .then(() => {
          multiActionButtonComponent().children().trigger("mouseover");
          multiActionButtonList()
            .eq(0)
            .should("have.text", "Example Button")
            .and("be.visible");
          multiActionButtonList()
            .eq(1)
            .should("have.text", "Example Button with long text")
            .and("be.visible");
          multiActionButtonList()
            .eq(2)
            .should("have.text", "Short")
            .and("be.visible");
        });
    });
  });

  describe("pressing tab while MultiActionButton is open", () => {
    it("should focus second MultiActionButton", () => {
      CypressMountWithProviders(
        <>
          <MultiActionButtonList />
          <MultiActionButtonList />
        </>
      );

      multiActionButton()
        .eq(0)
        .click()
        .then(() => {
          multiActionButtonList().eq(1).focus();
          multiActionButton().eq(0).tab();
          multiActionButton().eq(1).should("be.focused");
        });
    });
  });
});
<|endoftext|>


<commit_before>// Order here matters
var ReactDefaultBatchingStrategy = require('react/lib/ReactDefaultBatchingStrategy')
var ReactReconciler = require('react/lib/ReactReconciler')
var ReactInjection = require('react/lib/ReactInjection')
var EventPluginUtils = require('react/lib/EventPluginUtils')

var getEventTarget = require('react/lib/getEventTarget')

var patchMethod = require('../common/patchUtils').patchMethod
var nodeName = require('./utils').nodeName

var Trace = require('../transaction/trace')

function calcAvg (timings) {
  var sum = 0
  for (var j = 0; j < timings.length; j++) {
    sum += timings[j]
  }
  return sum / timings.length
}

function genTraces (componentStats, node, transactionService, transaction) {
  var child
  for (var i = 0; i < node.children.length; i++) {
    child = node.children[i]
    var trace = new Trace(transaction, child.name, 'template.component', {})
    child.trace = trace // needed to estimate children
    trace.setParent(transaction._rootTrace)
    if (child.start) {
      trace._start = child.start
      trace._end = child.end
    } else { // estimate
      if (i > 0) {
        // get start from prev child
        trace._start = node.children[i - 1].trace._end
      } else {
        // or parent
        trace._start = node.trace._start
      }

      if (!componentStats[child.name].avg) {
        componentStats[child.name].avg = calcAvg(componentStats[child.name].timings)
      }
      trace._end = trace._start + componentStats[child.name].avg
    }

    trace.end()

    genTraces(componentStats, child, transactionService, transaction)
  }
}

function RenderState () {
  return {
    'componentStats': {},
    'currRoot': {'children': []}
  }
}

module.exports = function patchReact (serviceContainer) {
  var transactionService = serviceContainer.services.transactionService

  var batchedUpdatePatch = function (delegate) {
    return function (self, args) {
      var ret
      var trace

      serviceContainer.services.zoneService.set('renderState', new RenderState())
      var batchedUpdatesStart = window.performance.now()

      ret = delegate.apply(self, args)

      var renderState = serviceContainer.services.zoneService.get('renderState')
      var componentTypes = Object.keys(renderState.componentStats)
      if (componentTypes.length > 0) {
        trace = transactionService.startTrace('batchedUpdates', 'template.update')
        trace._start = batchedUpdatesStart

        var text = componentTypes.length + ' different components'
        trace.signature = 'Render ' + text
        trace.end()

        renderState.currRoot.trace = trace
        genTraces(renderState.componentStats, renderState.currRoot, transactionService, transactionService.getCurrentTransaction())
      }
      return ret
    }
  }

  patchMethod(ReactDefaultBatchingStrategy, 'batchedUpdates', batchedUpdatePatch)
  ReactInjection.Updates.injectBatchingStrategy(ReactDefaultBatchingStrategy)

  var componentRenderPatch = function (delegate) {
    return function (self, args) {
      if (args[0] && args[0].getName) {
        var name = args[0].getName()
        if (name === 'TopLevelWrapper') {
          // TopLevelWrapper doesn't make sense to include here
          return delegate.apply(self, args)
        }

        var out
        var renderState = serviceContainer.services.zoneService.get('renderState')

        if (!renderState.componentStats[name]) {
          renderState.componentStats[name] = {'count': 0, 'timings': []}
        }
        var componentStat = renderState.componentStats[name]
        componentStat['count']++

        var shouldTrace = componentStat['count'] < 10
        var node = {'children': [], 'name': name}
        var parent = renderState.currRoot

        renderState.currRoot.children.push(node)
        renderState.currRoot = node

        if (shouldTrace) {
          var start = performance.now()
          out = delegate.apply(self, args)
          var end = performance.now()
          componentStat.timings.push(end - start)
          node.start = start
          node.end = end
        } else {
          out = delegate.apply(self, args)
        }

        renderState.currRoot = parent
        return out
      } else {
        return delegate.apply(self, args)
      }
    }
  }

  patchMethod(ReactReconciler, 'mountComponent', componentRenderPatch)
  patchMethod(ReactReconciler, 'receiveComponent', componentRenderPatch)
  patchMethod(ReactReconciler, 'performUpdateIfNecessary', componentRenderPatch)

  patchMethod(EventPluginUtils, 'executeDispatchesInOrder', function (delegate) {
    // for quick lookup, make this into an object
    var eventWhiteList = {}
    var performance = serviceContainer.services.configService.get('performance')
    var configWhiteList = performance.eventWhiteList || []
    configWhiteList.forEach(function (ev) {
      eventWhiteList[ev] = 1
    })

    return function (self, args) {
      if (args[0] && args[0]._dispatchListeners && args[0].nativeEvent) {
        var nativeEventTarget = getEventTarget(args[0].nativeEvent)
        if (nativeEventTarget) {
          // We want traces that have already started to go into a transaction
          // named after the event that fired it.

          // If we have not started a transaction through the code
          // invoked by the task, we should do so now.
          // because of ZoneTransactions, any trace started already will be
          // transferred.
          var trans = transactionService.getCurrentTransaction()
          if (trans && trans.name === 'ZoneTransaction' && args[0].nativeEvent.type in eventWhiteList) {
            var reactNode = nodeName(nativeEventTarget)
            transactionService.startTransaction(reactNode + ':' + args[0].nativeEvent.type, 'spa.action')
          }
        }
      }
      return delegate.apply(self, args)
    }
  })

  var reactDom = require('react-dom')
  patchMethod(reactDom, 'render', function (delegate) {
    return function (self, args) {
      var out
      return serviceContainer.services.zoneService.zone.run(function () {
        out = delegate.apply(self, args)
        serviceContainer.services.transactionService.detectFinish()
        return out
      })
    }
  })
}
<commit_msg>Fix problem with  components<commit_after>// Order here matters
var ReactDefaultBatchingStrategy = require('react/lib/ReactDefaultBatchingStrategy')
var ReactReconciler = require('react/lib/ReactReconciler')
var ReactInjection = require('react/lib/ReactInjection')
var EventPluginUtils = require('react/lib/EventPluginUtils')

var getEventTarget = require('react/lib/getEventTarget')

var patchMethod = require('../common/patchUtils').patchMethod
var nodeName = require('./utils').nodeName

var Trace = require('../transaction/trace')

function calcAvg (timings) {
  var sum = 0
  for (var j = 0; j < timings.length; j++) {
    sum += timings[j]
  }
  return sum / timings.length
}

function genTraces (componentStats, node, transactionService, transaction) {
  var child
  for (var i = 0; i < node.children.length; i++) {
    child = node.children[i]
    var trace = new Trace(transaction, child.name, 'template.component', {})
    child.trace = trace // needed to estimate children
    trace.setParent(transaction._rootTrace)
    if (child.start) {
      trace._start = child.start
      trace._end = child.end
    } else { // estimate
      if (i > 0) {
        // get start from prev child
        trace._start = node.children[i - 1].trace._end
      } else {
        // or parent
        trace._start = node.trace._start
      }

      if (!componentStats[child.name].avg) {
        componentStats[child.name].avg = calcAvg(componentStats[child.name].timings)
      }
      trace._end = trace._start + componentStats[child.name].avg
    }

    trace.end()

    genTraces(componentStats, child, transactionService, transaction)
  }
}

function RenderState () {
  return {
    'componentStats': {},
    'currRoot': {'children': []}
  }
}

module.exports = function patchReact (serviceContainer) {
  var transactionService = serviceContainer.services.transactionService

  var batchedUpdatePatch = function (delegate) {
    return function (self, args) {
      var ret
      var trace

      serviceContainer.services.zoneService.set('renderState', new RenderState())
      var batchedUpdatesStart = window.performance.now()

      ret = delegate.apply(self, args)

      var renderState = serviceContainer.services.zoneService.get('renderState')
      var componentTypes = Object.keys(renderState.componentStats)
      if (componentTypes.length > 0) {
        trace = transactionService.startTrace('batchedUpdates', 'template.update')
        trace._start = batchedUpdatesStart

        var text = componentTypes.length + ' different components'
        trace.signature = 'Render ' + text
        trace.end()

        renderState.currRoot.trace = trace
        genTraces(renderState.componentStats, renderState.currRoot, transactionService, transactionService.getCurrentTransaction())
      }
      return ret
    }
  }

  patchMethod(ReactDefaultBatchingStrategy, 'batchedUpdates', batchedUpdatePatch)
  ReactInjection.Updates.injectBatchingStrategy(ReactDefaultBatchingStrategy)

  var componentRenderPatch = function (delegate) {
    return function (self, args) {
      if (args[0] && args[0].getName) {
        var name = args[0].getName()
        if (name === 'TopLevelWrapper' || name === null) {
          // TopLevelWrapper or null components don't make sense to include here
          return delegate.apply(self, args)
        }

        var out
        var renderState = serviceContainer.services.zoneService.get('renderState')

        if (!renderState.componentStats[name]) {
          renderState.componentStats[name] = {'count': 0, 'timings': []}
        }
        var componentStat = renderState.componentStats[name]
        componentStat['count']++

        var shouldTrace = componentStat['count'] < 10
        var node = {'children': [], 'name': name}
        var parent = renderState.currRoot

        renderState.currRoot.children.push(node)
        renderState.currRoot = node

        if (shouldTrace) {
          var start = performance.now()
          out = delegate.apply(self, args)
          var end = performance.now()
          componentStat.timings.push(end - start)
          node.start = start
          node.end = end
        } else {
          out = delegate.apply(self, args)
        }

        renderState.currRoot = parent
        return out
      } else {
        return delegate.apply(self, args)
      }
    }
  }

  patchMethod(ReactReconciler, 'mountComponent', componentRenderPatch)
  patchMethod(ReactReconciler, 'receiveComponent', componentRenderPatch)
  patchMethod(ReactReconciler, 'performUpdateIfNecessary', componentRenderPatch)

  patchMethod(EventPluginUtils, 'executeDispatchesInOrder', function (delegate) {
    // for quick lookup, make this into an object
    var eventWhiteList = {}
    var performance = serviceContainer.services.configService.get('performance')
    var configWhiteList = performance.eventWhiteList || []
    configWhiteList.forEach(function (ev) {
      eventWhiteList[ev] = 1
    })

    return function (self, args) {
      if (args[0] && args[0]._dispatchListeners && args[0].nativeEvent) {
        var nativeEventTarget = getEventTarget(args[0].nativeEvent)
        if (nativeEventTarget) {
          // We want traces that have already started to go into a transaction
          // named after the event that fired it.

          // If we have not started a transaction through the code
          // invoked by the task, we should do so now.
          // because of ZoneTransactions, any trace started already will be
          // transferred.
          var trans = transactionService.getCurrentTransaction()
          if (trans && trans.name === 'ZoneTransaction' && args[0].nativeEvent.type in eventWhiteList) {
            var reactNode = nodeName(nativeEventTarget)
            transactionService.startTransaction(reactNode + ':' + args[0].nativeEvent.type, 'spa.action')
          }
        }
      }
      return delegate.apply(self, args)
    }
  })

  var reactDom = require('react-dom')
  patchMethod(reactDom, 'render', function (delegate) {
    return function (self, args) {
      var out
      return serviceContainer.services.zoneService.zone.run(function () {
        out = delegate.apply(self, args)
        serviceContainer.services.transactionService.detectFinish()
        return out
      })
    }
  })
}
<|endoftext|>


<commit_before>module.exports = function () {
    var winston = require('winston');
    var express = require('express');
    var app = express();

    // Models
    var Developer = require('../../models/developer');

    // Enums
    var CODE = require('../../enums/codes');

    app
        // -----------------------------------------------------------------------------------
        // --                                       POST                                    --
        // -----------------------------------------------------------------------------------

        // Description : Add a new developer
        // URL: http://localhost:8080/api/developers
        // Form params :
        //          - name
        .post('/developers', function (req, res) {
            var name = req.body.name;

            // Check if a developer already exist with this name
            Developer.findOneQ({name: name})
                .then(function (result) {
                    if (result) {
                        winston.info("Find a developer with this name : " + name);
                        res.json(CODE.ALREADY_EXIST);
                    } else {
                        // Create a new instance of the Developer model
                        var developer = new Developer();
                        developer.name = name;

                        // Save the developer and check for errors
                        developer.saveQ()
                            .then(function (developer) {
                                // Build response message
                                CODE.SUCCESS_POST.developer = developer;
                                res.json(CODE.SUCCESS);
                            })
                            .catch(function (err) {
                                console.error(err);
                                res.json(CODE.SERVER_ERROR);
                            });
                    }
                })
                .catch(function (err) {
                    console.error(err);
                    res.json(CODE.SERVER_ERROR);
                });
        })

        // -----------------------------------------------------------------------------------
        // --                                       GET                                     --
        // -----------------------------------------------------------------------------------

        // Description : Get all the developers, come with pagination params
        // URL : http://localhost:8080/api/developers/?skip=:skip&limit=:limit
        // URL params :
        //          - skip
        //          - limit
        .get('/developers', function (req, res) {

            var skip = req.param('skip');
            var limit = req.param('limit');

            winston.info("-- Searching developers with skip '" + skip + "' and limit '" + limit + "'...");

            Developer.find()
                .skip(skip)
                .limit(limit)
                .exec(function (err, developers) {
                    if (err)
                        res.send(CODE.SERVER_ERROR);

                    var count = developers.length;
                    winston.info('-- ' + count + ' developer(s) founded !');

                    // Build the response
                    CODE.SUCCESS.count = count;
                    CODE.SUCCESS.skip = skip;
                    CODE.SUCCESS.limit = limit;
                    CODE.SUCCESS.developers = developers;

                    res.json(CODE.SUCCESS);
                });
        })

        // Description : Get developers by a name
        // URL : http://localhost:8080/api/developers/by/name/:name
        .get('/developers/by/name/:developer_name', function (req, res) {
            Developer.find({name: req.params.developer_name}, function (err, developers) {
                if (err)
                    res.send(CODE.SERVER_ERROR);

                Developer.count({name: req.params.developer_name}, function (err, count) {
                    if (err)
                        res.send(CODE.SERVER_ERROR);

                    winston.info(count + ' developer(s) founded !');

                    // Build the response
                    CODE.SUCCESS.count = count;
                    CODE.SUCCESS.developers = developers;

                    res.json(CODE.SUCCESS);
                });
            });
        })

        // Description : Get a developer by an id
        // URL : http://localhost:8080/api/developers/by/:id
        .get('/developers/by/id/:developer_id', function (req, res) {
            Developer.findById(req.params.developer_id, function (err, developer) {
                if (err)
                    res.send(CODE.SERVER_ERROR);

                winston.info('Searching for developer id ' + req.params.developer_id + ' : ' + developer.name);

                // Build the response
                CODE.SUCCESS.developer = developer;

                res.json(CODE.SUCCESS);
            });
        })

        // -----------------------------------------------------------------------------------
        // --                                       PUT                                     --
        // -----------------------------------------------------------------------------------

        // Description : Update a developer with an id
        // URL : http://localhost:8080/api/developers/:developer_id
        // Param :
        //          - id
        // Form params :
        //          - Developer Object
        .put('/developers/:developer_id', function (req, res) {
            // Use our developer model to find the developer we want
            Developer.findById(req.params.developer_id, function (err, developer) {
                if (err)
                    res.send(CODE.SERVER_ERROR);

                developer.name = req.body.name;  // update the developers info
                developer.image = req.body.image;
                developer.updateDate = new Date();

                // Save the developer
                developer.save(function (err) {
                    if (err)
                        res.send(CODE.SERVER_ERROR);

                    // Build the response
                    CODE.SUCCESS_PUT.developer = developer;

                    res.json(CODE.SUCCESS);
                });
            });
        })

        // -----------------------------------------------------------------------------------
        // --                                     DELETE                                    --
        // -----------------------------------------------------------------------------------

        // Description : Delete a developer with an id
        // URL : http://localhost:8080/api/developers/:developer_id
        // Param :
        //          - id
        .delete('/developers/:developer_id', function (req, res) {
            Developer.remove({
                _id: req.params.developer_id
            }, function (err, developer) {
                if (err)
                    res.send(CODE.SERVER_ERROR);

                res.json(CODE.SUCCESS_DELETE);
            });
        });

    return app;
}();<commit_msg>Add image attribute when adding a new developer.<commit_after>module.exports = function () {
    var winston = require('winston');
    var express = require('express');
    var app = express();

    // Models
    var Developer = require('../../models/developer');

    // Enums
    var CODE = require('../../enums/codes');

    app
        // -----------------------------------------------------------------------------------
        // --                                       POST                                    --
        // -----------------------------------------------------------------------------------

        // Description : Add a new developer
        // URL: http://localhost:8080/api/developers
        // Form params :
        //          - name
        .post('/developers', function (req, res) {
            var name = req.body.name;
            var image = req.body.image;

            // Check if a developer already exist with this name
            Developer.findOneQ({name: name})
                .then(function (result) {
                    if (result) {
                        winston.info("Find a developer with this name : " + name);
                        res.json(CODE.ALREADY_EXIST);
                    } else {
                        // Create a new instance of the Developer model
                        var developer = new Developer();
                        developer.name = name;
                        developer.image = image;

                        // Save the developer and check for errors
                        developer.saveQ()
                            .then(function (developer) {
                                // Build response message
                                CODE.SUCCESS_POST.developer = developer;
                                res.json(CODE.SUCCESS);
                            })
                            .catch(function (err) {
                                console.error(err);
                                res.json(CODE.SERVER_ERROR);
                            });
                    }
                })
                .catch(function (err) {
                    console.error(err);
                    res.json(CODE.SERVER_ERROR);
                });
        })

        // -----------------------------------------------------------------------------------
        // --                                       GET                                     --
        // -----------------------------------------------------------------------------------

        // Description : Get all the developers, come with pagination params
        // URL : http://localhost:8080/api/developers/?skip=:skip&limit=:limit
        // URL params :
        //          - skip
        //          - limit
        .get('/developers', function (req, res) {

            var skip = req.param('skip');
            var limit = req.param('limit');

            winston.info("-- Searching developers with skip '" + skip + "' and limit '" + limit + "'...");

            Developer.find()
                .skip(skip)
                .limit(limit)
                .exec(function (err, developers) {
                    if (err)
                        res.send(CODE.SERVER_ERROR);

                    var count = developers.length;
                    winston.info('-- ' + count + ' developer(s) founded !');

                    // Build the response
                    CODE.SUCCESS.count = count;
                    CODE.SUCCESS.skip = skip;
                    CODE.SUCCESS.limit = limit;
                    CODE.SUCCESS.developers = developers;

                    res.json(CODE.SUCCESS);
                });
        })

        // Description : Get developers by a name
        // URL : http://localhost:8080/api/developers/by/name/:name
        .get('/developers/by/name/:developer_name', function (req, res) {
            Developer.find({name: req.params.developer_name}, function (err, developers) {
                if (err)
                    res.send(CODE.SERVER_ERROR);

                Developer.count({name: req.params.developer_name}, function (err, count) {
                    if (err)
                        res.send(CODE.SERVER_ERROR);

                    winston.info(count + ' developer(s) founded !');

                    // Build the response
                    CODE.SUCCESS.count = count;
                    CODE.SUCCESS.developers = developers;

                    res.json(CODE.SUCCESS);
                });
            });
        })

        // Description : Get a developer by an id
        // URL : http://localhost:8080/api/developers/by/:id
        .get('/developers/by/id/:developer_id', function (req, res) {
            Developer.findById(req.params.developer_id, function (err, developer) {
                if (err)
                    res.send(CODE.SERVER_ERROR);

                winston.info('Searching for developer id ' + req.params.developer_id + ' : ' + developer.name);

                // Build the response
                CODE.SUCCESS.developer = developer;

                res.json(CODE.SUCCESS);
            });
        })

        // -----------------------------------------------------------------------------------
        // --                                       PUT                                     --
        // -----------------------------------------------------------------------------------

        // Description : Update a developer with an id
        // URL : http://localhost:8080/api/developers/:developer_id
        // Param :
        //          - id
        // Form params :
        //          - Developer Object
        .put('/developers/:developer_id', function (req, res) {
            // Use our developer model to find the developer we want
            Developer.findById(req.params.developer_id, function (err, developer) {
                if (err)
                    res.send(CODE.SERVER_ERROR);

                developer.name = req.body.name;  // update the developers info
                developer.image = req.body.image;
                developer.updateDate = new Date();

                // Save the developer
                developer.save(function (err) {
                    if (err)
                        res.send(CODE.SERVER_ERROR);

                    // Build the response
                    CODE.SUCCESS_PUT.developer = developer;

                    res.json(CODE.SUCCESS);
                });
            });
        })

        // -----------------------------------------------------------------------------------
        // --                                     DELETE                                    --
        // -----------------------------------------------------------------------------------

        // Description : Delete a developer with an id
        // URL : http://localhost:8080/api/developers/:developer_id
        // Param :
        //          - id
        .delete('/developers/:developer_id', function (req, res) {
            Developer.remove({
                _id: req.params.developer_id
            }, function (err, developer) {
                if (err)
                    res.send(CODE.SERVER_ERROR);

                res.json(CODE.SUCCESS_DELETE);
            });
        });

    return app;
}();<|endoftext|>


<commit_before>var bla = {};

module.exports = bla;
<commit_msg>Added Backbone, jQuery and peutetre's SwipeView.<commit_after>'use strict';

var $ = require('jquery'),
    Backbone = require('backbone'),
    SwipeView = require('swipeview');

Backbone.$ = $;
<|endoftext|>


<commit_before>(function() {

Dagaz.AI.AI_FRAME      = 2000;
Dagaz.AI.getForcedMove = Dagaz.AI.getCheckersForcedMove;
Dagaz.AI.isForced      = Dagaz.AI.isCheckersForced;

var strictMode = false;

var checkVersion = Dagaz.Model.checkVersion;

Dagaz.Model.checkVersion = function(design, name, value) {
  if (name != "russian-checkers-extension") {
     checkVersion(design, name, value);
  }
}

var isAttacked = function(design, board, pos, empty, dir, opposite) {
  var p = design.navigate(board.player, pos, dir);
  if ((p === null) || (p == empty)) return false;
  var piece = board.getPiece(p);
  if ((p === null) || (p.player == board.player)) return false;
  p = design.navigate(board.player, pos, opposite);
  if (p === null) return false;
  return (p == empty) || (board.getPiece(p) === null);
}

Dagaz.AI.heuristic = function(ai, design, board, move) {
  if ((move.actions.length == 1) && (move.actions[0][0] !== null) && (move.actions[0][1] !== null)) {
      var nw = design.getDirection("nw"); var sw = design.getDirection("sw");
      var ne = design.getDirection("ne"); var se = design.getDirection("se");
      var sr = move.actions[0][0][0];
      var ds = move.actions[0][1][0];
      if (isAttacked(design, board, ds, sr, nw, se) ||
          isAttacked(design, board, ds, sr, ne, sw) ||
          isAttacked(design, board, ds, sr, se, nw) ||
          isAttacked(design, board, ds, sr, sw, ne)) {
          return 3;
      }
  }
  return 1;
}

Dagaz.AI.eval = function(design, params, board, player) {
  var r = 0;
  _.each(design.allPositions(), function(pos) {
      var piece = board.getPiece(pos);
      if (piece !== null) {
          var v = design.price[piece.type];
          var bonus = 6;
          if (_.indexOf([1, 23, 24, 39, 40, 62], +pos) >= 0) {
              bonus -= 3;
          }
          if (_.indexOf([7, 8, 55, 56], +pos) >= 0) {
              bonus -= 4;
          }
          if (_.indexOf([3, 5, 17, 46, 58, 60], +pos) >= 0) {
              bonus -= 2;
          }
          if (design.inZone(1, player, pos)) {
              bonus += 4;
          }
          if ((piece.type == 1) && (_.indexOf([7, 14, 21, 28, 35, 42, 49, 56], +pos) >= 0)) {
              bonus += 2;
          }
          v += bonus;
          if (!Dagaz.AI.isFriend(player, piece.player)) {
              v = -v;
          }
          r += v;
      }
  });
  return r;
}

})();
<commit_msg>Russian Checkers (heuristic)<commit_after>(function() {

Dagaz.AI.AI_FRAME      = 4000;
Dagaz.AI.MIN_DEEP      = 6;

var strictMode = false;

var checkVersion = Dagaz.Model.checkVersion;

Dagaz.Model.checkVersion = function(design, name, value) {
  if (name != "russian-checkers-extension") {
     checkVersion(design, name, value);
  }
}

var isAttacked = function(design, board, pos, empty, dir, opposite) {
  var p = design.navigate(board.player, pos, dir);
  if ((p === null) || (p == empty)) return false;
  var piece = board.getPiece(p);
  if ((p === null) || (p.player == board.player)) return false;
  p = design.navigate(board.player, pos, opposite);
  if (p === null) return false;
  return (p == empty) || (board.getPiece(p) === null);
}

Dagaz.AI.heuristic = function(ai, design, board, move) {
  var s = null;
  var d = null;
  var p = null;
  _.each(move.actions, function(a) {
      if ((a[0] !== null) && (a[1] !== null)) {
          if (s === null) s = a[0][0];
          d = a[1][0];
          if (a[2] !== null) p = a[2][0];
      }
  });
  if (p.type > 0) return 10;
  if ((s !== null) && (d !== null)) {
      var nw = design.getDirection("nw"); var sw = design.getDirection("sw");
      var ne = design.getDirection("ne"); var se = design.getDirection("se");
      var cn = 0;
      if (isAttacked(design, board, d, s, nw, se)) cn++;
      if (isAttacked(design, board, d, s, ne, sw)) cn++;
      if (isAttacked(design, board, d, s, sw, ne)) cn++;
      if (isAttacked(design, board, d, s, se, nw)) cn++;
      if (move.actions > 1) {
          if (cn == 0) return 2;
      } else {
          if (cn == 1) return 3;
          return 2;
      }
  }
  return 1;
}

Dagaz.AI.eval = function(design, params, board, player) {
  var r = 0;
  _.each(design.allPositions(), function(pos) {
      var piece = board.getPiece(pos);
      if (piece !== null) {
          var v = design.price[piece.type];
          var bonus = 6;
          if (_.indexOf([1, 23, 24, 39, 40, 62], +pos) >= 0) {
              bonus -= 3;
          }
          if (_.indexOf([7, 8, 55, 56], +pos) >= 0) {
              bonus -= 4;
          }
          if (_.indexOf([3, 5, 17, 46, 58, 60], +pos) >= 0) {
              bonus -= 2;
          }
          if (design.inZone(1, player, pos)) {
              bonus += 4;
          }
          if ((piece.type == 1) && (_.indexOf([7, 14, 21, 28, 35, 42, 49, 56], +pos) >= 0)) {
              bonus += 2;
          }
          v += bonus;
          if (!Dagaz.AI.isFriend(player, piece.player)) {
              v = -v;
          }
          r += v;
      }
  });
  return r;
}

})();
<|endoftext|>


<commit_before>import PropTypes from 'prop-types';
import React from 'react';
import { FormattedMessage, injectIntl, FormattedHTMLMessage } from 'react-intl';
import { connect } from 'react-redux';
import RaisedButton from 'material-ui/RaisedButton';
import { Row, Col } from 'react-flexbox-grid/lib';
import SourceList from '../../common/SourceList';
import CollectionSentenceCountContainer from './CollectionSentenceCountContainer';
import CollectionTopWordsContainer from './CollectionTopWordsContainer';
import CollectionGeographyContainer from './CollectionGeographyContainer';
import CollectionSourceRepresentation from './CollectionSourceRepresentation';
import CollectionSimilarContainer from './CollectionSimilarContainer';
import CollectionMetadataCoverageSummaryContainer from './CollectionMetadataCoverageSummaryContainer';
import { hasPermissions, getUserRoles, PERMISSION_MEDIA_EDIT } from '../../../lib/auth';
import { WarningNotice } from '../../common/Notice';

const localMessages = {
  searchNow: { id: 'collection.details.searchNow', defaultMessage: 'Search on the Dashboard' },
  collectionDetailsTitle: { id: 'collection.details.title', defaultMessage: 'Collection: {name}' },
  noHealth: { id: 'collection.details.noHealth', defaultMessage: 'Sorry, we can\'t show collection-level health yet.' },
  sourceTableTitle: { id: 'collection.details.sourceTable.title', defaultMessage: 'Sources' },
  sourceTableIntro: { id: 'collection.details.sources.intro',
    defaultMessage: 'This collection includes {count, plural,\n =0 {no media sources} \n =1 {one media source} \n other {# media sources}\n}.',
  },
  collectionIsOrIsnt: { id: 'collection.details.isOrIsnt', defaultMessage: 'This is a {shows, plural,\n =0 {dynamic collection; sources can be added and removed from it}\n =1 {static collection; the sources that are part of it will not change}\n}.' },
  collectionIsNotStatic: { id: 'collection.details.isStatic', defaultMessage: 'This is a dynamic collection; sources can be added and removed from it' },
  collectionIsStatic: { id: 'collection.details.isNotStatic', defaultMessage: 'This is a static collection; the sources that are part of it will not change.' },
  collectionShowOn: { id: 'collection.details.showOn', defaultMessage: 'This collection {onMedia, plural,\n =0 {does not show}\n =1 {shows}\n} up on media and {onStories, plural,\n =0 {does not show}\n =1 {shows}\n other {does not show}\n} up on stories.' },
  collectionFavorited: { id: 'collection.favorited', defaultMessage: 'Marked this as a starred collection' },
  collectionUnFavorited: { id: 'collection.unfavorited', defaultMessage: 'Remove this as a starred collection' },
  notPermitted: { id: 'collection.notPermitted', defaultMessage: 'Sorry, this is a private collection.' },
};

class CollectionDetailsContainer extends React.Component {

  searchOnDashboard = () => {
    const { collection } = this.props;
    const dashboardUrl = `https://dashboard.mediacloud.org/#query/["*"]/[{"sets":[${collection.tags_id}]}]/[]/[]/[{"uid":1,"name":"${collection.label}","color":"55868A"}]`;
    window.open(dashboardUrl, '_blank');
  }

  render() {
    const { collection, user } = this.props;
    const { formatMessage } = this.props.intl;
    const filename = `SentencesOverTime-Collection-${collection.tags_id}`;

    if (collection && (collection.show_on_media === 0) && !hasPermissions(getUserRoles(user), PERMISSION_MEDIA_EDIT)) {
      return (
        <WarningNotice><FormattedHTMLMessage {...localMessages.notPermitted} /></WarningNotice>
      );
    }

    return (

        <Row>
          <Col lg={8}>

{collection.description}

<FormattedMessage {...localMessages.collectionIsOrIsnt} values={{ shows: collection.is_static }} />

<FormattedMessage {...localMessages.collectionShowOn} values={{ onMedia: collection.show_on_media || 0, onStories: collection.show_on_stories || 0 }} />

          </Col>
          <Col lg={4}>
            <RaisedButton label={formatMessage(localMessages.searchNow)} primary onClick={this.searchOnDashboard} />
          </Col>
        </Row>
        <Row>
          <Col lg={6} xs={12}>
            <CollectionTopWordsContainer collectionId={collection.tags_id} />
          </Col>
          <Col lg={6} xs={12}>
            <CollectionSentenceCountContainer collectionId={collection.tags_id} filename={filename} />
          </Col>
        </Row>
        <Row>
          <Col lg={12} md={12} xs={12}>
            <CollectionGeographyContainer collectionId={collection.tags_id} collectionName={collection.label} />
          </Col>
        </Row>
        <Row>
          <Col lg={12} md={12} xs={12}>
            <CollectionMetadataCoverageSummaryContainer collectionId={collection.tags_id} collection={collection} sources={collection.media} />
          </Col>
        </Row>
        <Row>
          <Col lg={6} xs={12}>
            <SourceList collectionId={collection.tags_id} sources={collection.media} />
          </Col>
          <Col lg={6} xs={12}>
            <CollectionSourceRepresentation collectionId={collection.tags_id} />
            <CollectionSimilarContainer collectionId={collection.tags_id} filename={filename} />
          </Col>
        </Row>

    );
  }

}

CollectionDetailsContainer.propTypes = {
  intl: PropTypes.object.isRequired,
  // from context
  params: PropTypes.object.isRequired,       // params from router
  collectionId: PropTypes.number.isRequired,
  // from state
  collection: PropTypes.object,
  user: PropTypes.object,
};

const mapStateToProps = (state, ownProps) => ({
  collectionId: parseInt(ownProps.params.collectionId, 10),
  collection: state.sources.collections.selected.collectionDetails.object,
  user: state.user,
});

export default
  injectIntl(
    connect(mapStateToProps)(
      CollectionDetailsContainer
    )
  );
<commit_msg>Fix more true/false stuff in UI (#720)<commit_after>import PropTypes from 'prop-types';
import React from 'react';
import { FormattedMessage, injectIntl, FormattedHTMLMessage } from 'react-intl';
import { connect } from 'react-redux';
import RaisedButton from 'material-ui/RaisedButton';
import { Row, Col } from 'react-flexbox-grid/lib';
import SourceList from '../../common/SourceList';
import CollectionSentenceCountContainer from './CollectionSentenceCountContainer';
import CollectionTopWordsContainer from './CollectionTopWordsContainer';
import CollectionGeographyContainer from './CollectionGeographyContainer';
import CollectionSourceRepresentation from './CollectionSourceRepresentation';
import CollectionSimilarContainer from './CollectionSimilarContainer';
import CollectionMetadataCoverageSummaryContainer from './CollectionMetadataCoverageSummaryContainer';
import { hasPermissions, getUserRoles, PERMISSION_MEDIA_EDIT } from '../../../lib/auth';
import { WarningNotice } from '../../common/Notice';

const localMessages = {
  searchNow: { id: 'collection.details.searchNow', defaultMessage: 'Search on the Dashboard' },
  collectionDetailsTitle: { id: 'collection.details.title', defaultMessage: 'Collection: {name}' },
  noHealth: { id: 'collection.details.noHealth', defaultMessage: 'Sorry, we can\'t show collection-level health yet.' },
  sourceTableTitle: { id: 'collection.details.sourceTable.title', defaultMessage: 'Sources' },
  sourceTableIntro: { id: 'collection.details.sources.intro',
    defaultMessage: 'This collection includes {count, plural,\n =0 {no media sources} \n =1 {one media source} \n other {# media sources}\n}.',
  },
  collectionIsOrIsnt: { id: 'collection.details.isOrIsnt', defaultMessage: 'This is a {shows, plural,\n =false {dynamic collection; sources can be added and removed from it}\n =true {static collection; the sources that are part of it will not change}\n}.' },
  collectionIsNotStatic: { id: 'collection.details.isStatic', defaultMessage: 'This is a dynamic collection; sources can be added and removed from it' },
  collectionIsStatic: { id: 'collection.details.isNotStatic', defaultMessage: 'This is a static collection; the sources that are part of it will not change.' },
  collectionShowOn: { id: 'collection.details.showOn', defaultMessage: 'This collection {onMedia, plural,\n =0 {does not show}\n =true {shows}\n} up on media and {onStories, plural,\n =false {does not show}\n =true {shows}\n other {does not show}\n} up on stories.' },
  collectionFavorited: { id: 'collection.favorited', defaultMessage: 'Marked this as a starred collection' },
  collectionUnFavorited: { id: 'collection.unfavorited', defaultMessage: 'Remove this as a starred collection' },
  notPermitted: { id: 'collection.notPermitted', defaultMessage: 'Sorry, this is a private collection.' },
};

class CollectionDetailsContainer extends React.Component {

  searchOnDashboard = () => {
    const { collection } = this.props;
    const dashboardUrl = `https://dashboard.mediacloud.org/#query/["*"]/[{"sets":[${collection.tags_id}]}]/[]/[]/[{"uid":1,"name":"${collection.label}","color":"55868A"}]`;
    window.open(dashboardUrl, '_blank');
  }

  render() {
    const { collection, user } = this.props;
    const { formatMessage } = this.props.intl;
    const filename = `SentencesOverTime-Collection-${collection.tags_id}`;

    if (collection && (collection.show_on_media === 0) && !hasPermissions(getUserRoles(user), PERMISSION_MEDIA_EDIT)) {
      return (
        <WarningNotice><FormattedHTMLMessage {...localMessages.notPermitted} /></WarningNotice>
      );
    }

    return (

        <Row>
          <Col lg={8}>

{collection.description}

<FormattedMessage {...localMessages.collectionIsOrIsnt} values={{ shows: collection.is_static }} />

<FormattedMessage {...localMessages.collectionShowOn} values={{ onMedia: collection.show_on_media || 0, onStories: collection.show_on_stories || 0 }} />

          </Col>
          <Col lg={4}>
            <RaisedButton label={formatMessage(localMessages.searchNow)} primary onClick={this.searchOnDashboard} />
          </Col>
        </Row>
        <Row>
          <Col lg={6} xs={12}>
            <CollectionTopWordsContainer collectionId={collection.tags_id} />
          </Col>
          <Col lg={6} xs={12}>
            <CollectionSentenceCountContainer collectionId={collection.tags_id} filename={filename} />
          </Col>
        </Row>
        <Row>
          <Col lg={12} md={12} xs={12}>
            <CollectionGeographyContainer collectionId={collection.tags_id} collectionName={collection.label} />
          </Col>
        </Row>
        <Row>
          <Col lg={12} md={12} xs={12}>
            <CollectionMetadataCoverageSummaryContainer collectionId={collection.tags_id} collection={collection} sources={collection.media} />
          </Col>
        </Row>
        <Row>
          <Col lg={6} xs={12}>
            <SourceList collectionId={collection.tags_id} sources={collection.media} />
          </Col>
          <Col lg={6} xs={12}>
            <CollectionSourceRepresentation collectionId={collection.tags_id} />
            <CollectionSimilarContainer collectionId={collection.tags_id} filename={filename} />
          </Col>
        </Row>

    );
  }

}

CollectionDetailsContainer.propTypes = {
  intl: PropTypes.object.isRequired,
  // from context
  params: PropTypes.object.isRequired,       // params from router
  collectionId: PropTypes.number.isRequired,
  // from state
  collection: PropTypes.object,
  user: PropTypes.object,
};

const mapStateToProps = (state, ownProps) => ({
  collectionId: parseInt(ownProps.params.collectionId, 10),
  collection: state.sources.collections.selected.collectionDetails.object,
  user: state.user,
});

export default
  injectIntl(
    connect(mapStateToProps)(
      CollectionDetailsContainer
    )
  );
<|endoftext|>


<commit_before>import * as SyncStates from '../constants/SyncStates.js'

const initialState = {
  status: SyncStates.NOT_CONNECTED,
};

module.exports = function(state = initialState, action) {
  let nextState = Object.assign({}, state);

  switch(action.type) {
    case 'UPDATE_SYNC_STATE': {
      nextState.status = action.status;
      return nextState;
      break;
    }
    default: {
      /* Return original state if no actions were consumed. */
      return state;
    }
  }
}
<commit_msg>Fixes warnings<commit_after>import * as SyncStates from '../constants/SyncStates.js'

const initialState = {
  status: SyncStates.NOT_CONNECTED
};

module.exports = function(state = initialState, action) {
  let nextState = Object.assign({}, state);

  switch(action.type) {
    case 'UPDATE_SYNC_STATE': {
      nextState.status = action.status;
      return nextState;
    }
    default: {
      /* Return original state if no actions were consumed. */
      return state;
    }
  }
}
<|endoftext|>


<commit_before>var util = require('../util');
var sql = require('mssql');

var transactionDone = false;

var api = {

	get: function (req, res, next) {
		console.log('in profile GET');
		var connection = new sql.Connection(util.sqlConfiguration);
		connection.connect(function(err) {
			if (err) { res.sendStatus(500); return; }
			var sqlRequest = new sql.Request(transaction);
			var queryString = 'SELECT sid, alias FROM Users WHERE sid=@sid;';
			var preparedStatement = new sql.PreparedStatement(connection);
			preparedStatement.input('sid', sql.NVarChar);
			preparedStatement.prepare(queryString, function(err) {
				if (err) { res.sendStatus(500); return; }
				preparedStatement.execute({ sid: req.azureMobile.user.id },
					function(err, recordset, affected) {
						if (err || (typeof recordset != 'undefined' && recordset[0] != null)) {
							res.sendStatus(500); return;
						}
						preparedStatement.unprepare();
						res.sendStatus(200).type('application/json').json(recordset);
            			return next();
					}
				);
			});
		});
	},

	post: function (req, res, next) {
		var connection = new sql.Connection(util.sqlConfiguration);
		connection.connect(function(err) {
			if (err) { rollback(err, res, transaction); return; }
			var transaction = new sql.Transaction(connection);
			transaction.begin(function(err) {
				if (err) { rollback(err, res, transaction); return; }
				var sqlRequest = new sql.Request(transaction);
				var queryString = 'SELECT id FROM Users WHERE sid=@sid;';
				var preparedStatement = new sql.PreparedStatement(connection);
				transaction.on('commit', function(succeeded) { preparedStatement.unprepare(); res.sendStatus(200); });
				transaction.on('rollback', function(aborted) { rolledback = true; preparedStatement.unprepare(); res.sendStatus(500); });
				preparedStatement.input('sid', sql.NVarChar);
				preparedStatement.prepare(queryString, function(err) {
					if (err) { rollback(err, res, transaction); return; }
					preparedStatement.execute({ sid: req.azureMobile.user.id },
						function(err, recordset, affected) {
							if (err) { rollback(err, res, transaction); return; }
							if (typeof recordset != 'undefined' && recordset[0] != null) { transaction.commit(); return; }
							preparedStatement.unprepare();
							queryString = 'UPDATE Users (alias) values (@alias) WHERE sid=@sid;';
							preparedStatement.input('sid', sql.NVarChar);
							preparedStatement.input('alias', sql.NVarChar);
							preparedStatement.prepare(queryString, function(err) {
								if (err) { rollback(err, res, transaction); return; }
								preparedStatement.execute({
									sid: req.azureMobile.user.id,
									alias: 'aborba'
								}, function(err, recordset, affected) {
									if (err) { rollback(err, res, transaction); return; }
									commit(res, transaction);
								});
							});
						}
					);
				});
			});
		});
    }
};

api.access = 'authenticated';

var completeTransaction = function(err, data) {
	if (err) {
		console.log(err);
		if (!data) return;
		if (!data.transactionDone) {
			data.transactionDone = true;
			if (data.action && util.isFunction(data.action)) data.action();
			if (data.res && data.sendStatus && util.isFunction(data.res.sendStatus)) data.res.sendStatus(data.sendStatus);
		}
	}
}

var rollback = function(err, res, transaction) {
	completeTransaction(err, {
		transactionDone: transactionDone,
		action: transaction.rollback,
		res: res,
		sendStatus: 500
	});
}

var commit = function(res, transaction) {
	completeTransaction(undefined, {
		transactionDone: transactionDone,
		action: transaction.commit,
		res: res,
		sendStatus: 200
	});
}

module.exports = api;
<commit_msg>another<commit_after>var util = require('../util');
var sql = require('mssql');

var transactionDone = false;

var api = {

	get: function (req, res, next) {
		console.log('in profile GET');
		var connection = new sql.Connection(util.sqlConfiguration);
		connection.connect(function(err) {
			if (err) { res.sendStatus(500); return; }
			var sqlRequest = new sql.Request(connection);
			var queryString = 'SELECT sid, alias FROM Users WHERE sid=@sid;';
			var preparedStatement = new sql.PreparedStatement(connection);
			preparedStatement.input('sid', sql.NVarChar);
			preparedStatement.prepare(queryString, function(err) {
				if (err) { res.sendStatus(500); return; }
				preparedStatement.execute({ sid: req.azureMobile.user.id },
					function(err, recordset, affected) {
						if (err || (typeof recordset != 'undefined' && recordset[0] != null)) {
							res.sendStatus(500); return;
						}
						preparedStatement.unprepare();
						res.sendStatus(200).type('application/json').json(recordset);
            			return next();
					}
				);
			});
		});
	},

	post: function (req, res, next) {
		var connection = new sql.Connection(util.sqlConfiguration);
		connection.connect(function(err) {
			if (err) { rollback(err, res, transaction); return; }
			var transaction = new sql.Transaction(connection);
			transaction.begin(function(err) {
				if (err) { rollback(err, res, transaction); return; }
				var sqlRequest = new sql.Request(transaction);
				var queryString = 'SELECT id FROM Users WHERE sid=@sid;';
				var preparedStatement = new sql.PreparedStatement(connection);
				transaction.on('commit', function(succeeded) { preparedStatement.unprepare(); res.sendStatus(200); });
				transaction.on('rollback', function(aborted) { rolledback = true; preparedStatement.unprepare(); res.sendStatus(500); });
				preparedStatement.input('sid', sql.NVarChar);
				preparedStatement.prepare(queryString, function(err) {
					if (err) { rollback(err, res, transaction); return; }
					preparedStatement.execute({ sid: req.azureMobile.user.id },
						function(err, recordset, affected) {
							if (err) { rollback(err, res, transaction); return; }
							if (typeof recordset != 'undefined' && recordset[0] != null) { transaction.commit(); return; }
							preparedStatement.unprepare();
							queryString = 'UPDATE Users (alias) values (@alias) WHERE sid=@sid;';
							preparedStatement.input('sid', sql.NVarChar);
							preparedStatement.input('alias', sql.NVarChar);
							preparedStatement.prepare(queryString, function(err) {
								if (err) { rollback(err, res, transaction); return; }
								preparedStatement.execute({
									sid: req.azureMobile.user.id,
									alias: 'aborba'
								}, function(err, recordset, affected) {
									if (err) { rollback(err, res, transaction); return; }
									commit(res, transaction);
								});
							});
						}
					);
				});
			});
		});
    }
};

api.access = 'authenticated';

var completeTransaction = function(err, data) {
	if (err) {
		console.log(err);
		if (!data) return;
		if (!data.transactionDone) {
			data.transactionDone = true;
			if (data.action && util.isFunction(data.action)) data.action();
			if (data.res && data.sendStatus && util.isFunction(data.res.sendStatus)) data.res.sendStatus(data.sendStatus);
		}
	}
}

var rollback = function(err, res, transaction) {
	completeTransaction(err, {
		transactionDone: transactionDone,
		action: transaction.rollback,
		res: res,
		sendStatus: 500
	});
}

var commit = function(res, transaction) {
	completeTransaction(undefined, {
		transactionDone: transactionDone,
		action: transaction.commit,
		res: res,
		sendStatus: 200
	});
}

module.exports = api;
<|endoftext|>


<commit_before>define(['jquery'], function($) {
    'use strict';
    function NativeAudio() {
        this.loopTag = document.createElement('audio');
        if (!Modernizr.audio.ogg && !Modernizr.audio.mp3) {
            throw 'audio unsupported';
        }
        $(this.loopTag).attr({preload: true, autoplay: true, loop: true, volume: 1.0}).appendTo(document.body);
        if (this.loopTag.loop === undefined) {
            // thanks Firefox...
            $(this.loopTag).bind('ended', function(event) {
                event.target.currentTime = 0.0;
                event.target.play();
            });
        }
    }
    NativeAudio.prototype = {
        loopTag: null,
        tags: [],
        volume: 1.0,
        setVolume: function(volume) {
            this.volume = volume;
        },
        setLoopVolume: function(volume) {
            this.loopTag.volume = volume;
        },
        addSources: function(tag, src, translateUrl) {
            $(tag).empty().append($([['ogg', 'audio/ogg; codecs="vorbis"'], ['mp3', 'audio/mpeg; codecs="mp3"']]).filter(function(i, e) { return Modernizr.audio[e[0]]; }).map(function(i, e) {
                return $(document.createElement('source')).attr({src: translateUrl(src + '.' + e[0]), type: e[1]})[0];
            }));
        },
        playLoop: function(src, translateUrl) {
            this.addSources(this.loopTag, src, translateUrl);
        },
        play: function(src, translateUrl) {
            var tag = document.createElement('audio');
            $(tag).attr({preload: true, autoplay: true, volume: this.volume}).appendTo(document.body);
            $(tag).bind('ended', {na: this}, function(event) {
                var index = event.data.na.tags.indexOf(event.target);
                if (index !== -1) {
                    $(event.data.na.tags.splice(index, 1)).remove();
                }
            });
            this.addSources(tag, src, translateUrl);
            this.tags.push(tag);
        },
        stopLoop: function() {
            $(this.loopTag).empty();
        },
        stopSounds: function() {
            $(this.tags).remove();
            this.tags = [];
        }
    };
    return NativeAudio;
});
<commit_msg>loops should stop when asked<commit_after>define(['jquery'], function($) {
    'use strict';
    function NativeAudio() {
        if (!Modernizr.audio.ogg && !Modernizr.audio.mp3) {
            throw 'audio unsupported';
        }
    }
    NativeAudio.prototype = {
        loopTag: null,
        tags: [],
        volume: 1.0,
        loopVolume: 1.0,
        setVolume: function(volume) {
            this.volume = volume;
        },
        setLoopVolume: function(volume) {
            this.loopVolume = volume;
            if (this.loopTag) {
                this.loopTag.volume = volume;
            }
        },
        addSources: function(tag, src, translateUrl) {
            $(tag).empty().append($([['ogg', 'audio/ogg; codecs="vorbis"'], ['mp3', 'audio/mpeg; codecs="mp3"']]).filter(function(i, e) { return Modernizr.audio[e[0]]; }).map(function(i, e) {
                return $(document.createElement('source')).attr({src: translateUrl(src + '.' + e[0]), type: e[1]})[0];
            }));
        },
        playLoop: function(src, translateUrl) {
            if (this.loopTag) {
                $(this.loopTag).remove();
            }
            this.loopTag = document.createElement('audio');
            $(this.loopTag).attr({preload: true, autoplay: true, loop: true, volume: this.loopVolume}).appendTo(document.body);
            this.addSources(this.loopTag, src, translateUrl);
        },
        play: function(src, translateUrl) {
            var tag = document.createElement('audio');
            $(tag).attr({preload: true, autoplay: true, volume: this.volume}).appendTo(document.body);
            $(tag).bind('ended', {na: this}, function(event) {
                var index = event.data.na.tags.indexOf(event.target);
                if (index !== -1) {
                    $(event.data.na.tags.splice(index, 1)).remove();
                }
            });
            this.addSources(tag, src, translateUrl);
            this.tags.push(tag);
        },
        stopLoop: function() {
            $(this.loopTag).remove();
        },
        stopSounds: function() {
            $(this.tags).remove();
            this.tags = [];
        }
    };
    return NativeAudio;
});
<|endoftext|>


<commit_before>import 'aframe';
import 'babel-polyfill';
import {Animation, Entity, Scene} from 'aframe-react';
import React from 'react';
import ReactDOM from 'react-dom';

import Camera from './components/Camera';
import Cursor from './components/Cursor';
import Sky from './components/Sky';
import starData from './data/starsData';
import exoPlanetData from './data/exoPlanetsData';
import Star from './components/Star';
import ExoPlanet from './components/ExoPlanet';

class BoilerplateScene extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      color: 'red'
    }
  }

  changeColor = () => {
    const colors = ['red', 'orange', 'yellow', 'green', 'blue'];
    this.setState({
      color: colors[Math.floor(Math.random() * colors.length)],
    });
  };

  render () {
    return (
      <Scene fog="type: linear; color: #222; far: 100; near: 0">
        <Camera><Cursor/></Camera>
        <Sky/>
        {starData.map((star) => (<Star key={star.id} starData={star} />))}
        {exoPlanetData.map((exoPlanet) => (<ExoPlanet key={exoPlanet.id} exoPlanetData={exoPlanet} />))}
        <Entity light={{type: 'ambient', color: '#888'}}/>
        <Entity light={{type: 'directional', intensity: 0.5}} position={[-1, 1, 0]}/>
        <Entity light={{type: 'directional', intensity: 1}} position={[1, 1, 0]}/>

        <Entity geometry="primitive: box" material={{color: this.state.color}}
                onClick={this.changeColor}
                position="0 0 -5">
          <Animation attribute="rotation" dur="5000" repeat="indefinite" to="0 360 360"/>
        </Entity>

      </Scene>
    );
  }
}

ReactDOM.render(<BoilerplateScene/>, document.querySelector('.scene-container'));
<commit_msg>(refactor) Remove rotating cube<commit_after>import 'aframe';
import 'babel-polyfill';
import {Animation, Entity, Scene} from 'aframe-react';
import React from 'react';
import ReactDOM from 'react-dom';

import Camera from './components/Camera';
import Cursor from './components/Cursor';
import Sky from './components/Sky';
import starData from './data/starsData';
import exoPlanetData from './data/exoPlanetsData';
import Star from './components/Star';
import ExoPlanet from './components/ExoPlanet';

class BoilerplateScene extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      color: 'red'
    }
  }

  render () {
    return (
      <Scene fog="type: linear; color: #222; far: 100; near: 0">
        <Camera><Cursor/></Camera>
        <Sky/>
        {starData.map((star) => (<Star key={star.id} starData={star} />))}
        {exoPlanetData.map((exoPlanet) => (<ExoPlanet key={exoPlanet.id} exoPlanetData={exoPlanet} />))}
        <Entity light={{type: 'ambient', color: '#888'}}/>
        <Entity light={{type: 'directional', intensity: 0.5}} position={[-1, 1, 0]}/>
        <Entity light={{type: 'directional', intensity: 1}} position={[1, 1, 0]}/>

      </Scene>
    );
  }
}

ReactDOM.render(<BoilerplateScene/>, document.querySelector('.scene-container'));
<|endoftext|>