<commit_before>// Copyright 2012 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

goog.require('axs.AuditRule');
goog.require('axs.AuditRule');
goog.require('axs.AuditRules');
goog.require('axs.constants.Severity');

axs.AuditRule.specs.nonExistentAriaLabelledbyElement = {
    name: 'nonExistentAriaLabelledbyElement',
    severity: axs.constants.Severity.Warning,
    relevantNodesSelector: function(scope) {
        return scope.querySelectorAll('[aria-labelledby]');
    },
    test: function(element) {
        var labelledBy = element.getAttribute('aria-labelledby');
        var labelledByValues = labelledBy.split(/\s+/);
        for (var i = 0; i < labelledByValues.length; i++) {
            var labelElement = document.getElementById(labelledByValues[i]);
            if (!labelElement)
                return true;
        }
        return false;
    },
    code: 'AX_ARIA_02'
};
<commit_msg>Remove duplicate require line in NonExistentAriaLabeledBy.js<commit_after>// Copyright 2012 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

goog.require('axs.AuditRule');
goog.require('axs.AuditRules');
goog.require('axs.constants.Severity');

axs.AuditRule.specs.nonExistentAriaLabelledbyElement = {
    name: 'nonExistentAriaLabelledbyElement',
    severity: axs.constants.Severity.Warning,
    relevantNodesSelector: function(scope) {
        return scope.querySelectorAll('[aria-labelledby]');
    },
    test: function(element) {
        var labelledBy = element.getAttribute('aria-labelledby');
        var labelledByValues = labelledBy.split(/\s+/);
        for (var i = 0; i < labelledByValues.length; i++) {
            var labelElement = document.getElementById(labelledByValues[i]);
            if (!labelElement)
                return true;
        }
        return false;
    },
    code: 'AX_ARIA_02'
};
<|endoftext|>


<commit_before>import React, { Component } from "react";
import RNDrawer from "react-native-drawer";
import PropTypes from "prop-types";

export default class Drawer extends Component {
	constructor(props) {
		super(props);
	}
	render() {
		return <RNDrawer ref={c => (this._root = c)} {...this.props} />;
	}
}

Drawer.defaultProps = {
	type: "overlay",
	tapToClose: true,
	openDrawerOffset: 0.2,
	panCloseMask: 0.2,
	closedDrawerOffset: 0,
	styles: {
		drawer: {
			shadowColor: "#000000",
			shadowOpacity: 0,
			shadowRadius: 0,
			elevation: 5,
		},
		mainOverlay: {
			opacity: 0,
			backgroundColor: "rgba(0, 0, 0, 0.8)",
			elevation: 8,
		},
	},
	tweenHandler: ratio => ({
		mainOverlay: { opacity: ratio / 2 },
	}),
};
<commit_msg>fix android drawer overlay<commit_after>import React, { Component } from "react";
import RNDrawer from "react-native-drawer";
import PropTypes from "prop-types";

export default class Drawer extends Component {
	constructor(props) {
		super(props);
	}
	render() {
		return <RNDrawer ref={c => (this._root = c)} {...this.props} />;
	}
}

Drawer.defaultProps = {
	type: "overlay",
	tapToClose: true,
	openDrawerOffset: 0.2,
	panCloseMask: 0.2,
	closedDrawerOffset: 0,
	styles: {
		drawer: {
			shadowColor: "#000000",
			shadowOpacity: 0,
			shadowRadius: 0,
			elevation: 5,
		},
		mainOverlay: {
			opacity: 0,
			backgroundColor: "rgba(0, 0, 0, 0.8)",
			elevation: 0,
		},
	},
	tweenHandler: ratio => ({
		mainOverlay: { opacity: ratio / 2 },
	}),
};
<|endoftext|>


<commit_before>"use strict";

const assert = require("assert");
const helpers = require("../helpers.js");

let app;
var workingDir;
var saversDir;
const SaverPrefs = require("../../src/lib/prefs.js");

describe("Settings", function() {
  const fakeDialogOpts = [ { method: "showOpenDialog", value: ["/not/a/real/path"] } ];
  const closeWindowDelay = 750;
  const TEXT_ON_SCREEN = "Be careful with these!";

  before(function() {
    if ( process.env.CI && process.env.TRAVIS_OS_NAME == "osx") {
      // eslint-disable-next-line no-console
      console.log("Cowardly skipping test in OSX CI");
      this.skip();
      return;
    }
  });

  helpers.setupTest(this);

  let pickSettingsWindow = function() {
    return helpers.getWindowByTitle(app, "Before Dawn: Settings");
  };

  let currentPrefs = function() {
    return new SaverPrefs(workingDir);
  };

  beforeEach(() => {
    workingDir = helpers.getTempDir();
    saversDir = helpers.getTempDir();

    helpers.setupConfig(workingDir);
    helpers.addLocalSource(workingDir, saversDir);
    helpers.addSaver(saversDir, "saver-one", "saver.json");

    app = helpers.application(workingDir, true);
    return app.start().
              then(() => app.fakeDialog.mock(fakeDialogOpts)).
              then(() => app.client.waitUntilWindowLoaded() ).
              then(() => app.electron.ipcRenderer.send("open-prefs")).
              then(() => helpers.waitForWindow(app, "Before Dawn: Preferences") ).
              then(() => app.client.click("button.settings")).
              then(() => helpers.waitForWindow(app, "Before Dawn: Settings") );
  });

	afterEach(function() {
    if (this.currentTest.state === "failed") {
      helpers.outputLogs(app);
    }

    return helpers.stopApp(app);
	});

  it("toggles checkboxes", function() {
    let oldConfig = currentPrefs();

    return pickSettingsWindow().
      then(() => app.client.waitUntilTextExists("body", TEXT_ON_SCREEN)).
      then(() => app.client.click("label*=Lock screen after running")).
      then(() => app.client.click("label*=Disable when on battery?")).
      then(() => app.client.click("label*=Auto start on login?")).
      then(() => app.client.click("label*=Only run on the primary display?")).
      then(() => app.client.click("button.save")).
      then(() => helpers.sleep(closeWindowDelay)).
      then(() => {
        let updatedPrefs = currentPrefs();
        assert.equal(!oldConfig.lock, updatedPrefs.lock);
        assert.equal(!oldConfig.disableOnBattery, updatedPrefs.disableOnBattery);
        assert.equal(!oldConfig.auto_start, updatedPrefs.auto_start);
        assert.equal(!oldConfig.runOnSingleDisplay, updatedPrefs.runOnSingleDisplay);
      });
  });

  it("leaves checkboxes", function() {
    let oldConfig = currentPrefs();

    return pickSettingsWindow().
      then(() => app.client.waitUntilTextExists("body", TEXT_ON_SCREEN)).
      then(() => app.client.click("button.save")).
      then(() => helpers.sleep(closeWindowDelay)).
      then(() => {
        let updatedPrefs = currentPrefs();
        assert.equal(oldConfig.lock, updatedPrefs.lock);
        assert.equal(oldConfig.disableOnBattery, updatedPrefs.disableOnBattery);
        assert.equal(oldConfig.auto_start, updatedPrefs.auto_start);
        assert.equal(oldConfig.runOnSingleDisplay, updatedPrefs.runOnSingleDisplay);
      });
  });

  it("allows setting path via dialog", function() {
    return pickSettingsWindow().
      then(() => app.webContents
        .executeJavaScript("document.querySelector(\"button.pick\").scrollIntoView()")).
      then(() => app.client.click("button.pick")).
      then(() => helpers.sleep(50)).
      then(() => app.client.click("button.save")).
      then(() => helpers.sleep(closeWindowDelay)).
      then(function() {
        assert.equal("/not/a/real/path", currentPrefs().localSource);
      });
  });

  it("clears localSource", function() {
    return pickSettingsWindow().
      then(() => app.client.waitUntilTextExists("body", TEXT_ON_SCREEN)).
      then(function() {
        let ls = currentPrefs().localSource;
        assert( ls != "" && ls !== undefined);
      }).
      then(() => app.webContents
        .executeJavaScript("document.querySelector(\"button.clear\").scrollIntoView()")).
      then(() => app.client.click("button.clear")).
      then(() => helpers.sleep(50)).
      then(() => app.client.click("button.save")).
      then(() => helpers.sleep(closeWindowDelay)).
      then(function() {
        assert.equal("", currentPrefs().localSource);
      });
  });

  it("resets defaults", function() {
    const resetDialogOpts = [ { method: "showMessageBoxSync", value: 1 } ];

    return pickSettingsWindow().
      then(() => app.fakeDialog.mock(resetDialogOpts)).
      then(() => app.webContents
        .executeJavaScript("document.querySelector(\"button.reset-to-defaults\").scrollIntoView()")).
      then(() => app.client.click("button.reset-to-defaults")).
      then(() => app.client.waitUntilTextExists("body", "Settings reset")).
      then(() => helpers.sleep(closeWindowDelay)).
      then(function() {
        assert.equal("", currentPrefs().localSource);
      });
  });
});
<commit_msg>Fix test<commit_after>"use strict";

const assert = require("assert");
const helpers = require("../helpers.js");

let app;
var workingDir;
var saversDir;
const SaverPrefs = require("../../src/lib/prefs.js");

describe("Settings", function() {
  const fakeDialogOpts = [ { method: "showOpenDialog", value: { filePaths: ["/not/a/real/path"] } } ];
  const closeWindowDelay = 750;
  const TEXT_ON_SCREEN = "Be careful with these!";

  before(function() {
    if ( process.env.CI && process.env.TRAVIS_OS_NAME == "osx") {
      // eslint-disable-next-line no-console
      console.log("Cowardly skipping test in OSX CI");
      this.skip();
      return;
    }
  });

  helpers.setupTest(this);

  let pickSettingsWindow = function() {
    return helpers.getWindowByTitle(app, "Before Dawn: Settings");
  };

  let currentPrefs = function() {
    return new SaverPrefs(workingDir);
  };

  beforeEach(() => {
    workingDir = helpers.getTempDir();
    saversDir = helpers.getTempDir();

    helpers.setupConfig(workingDir);
    helpers.addLocalSource(workingDir, saversDir);
    helpers.addSaver(saversDir, "saver-one", "saver.json");

    app = helpers.application(workingDir, true);
    return app.start().
              then(() => app.fakeDialog.mock(fakeDialogOpts)).
              then(() => app.client.waitUntilWindowLoaded() ).
              then(() => app.electron.ipcRenderer.send("open-prefs")).
              then(() => helpers.waitForWindow(app, "Before Dawn: Preferences") ).
              then(() => app.client.click("button.settings")).
              then(() => helpers.waitForWindow(app, "Before Dawn: Settings") );
  });

	afterEach(function() {
    if (this.currentTest.state === "failed") {
      helpers.outputLogs(app);
    }

    return helpers.stopApp(app);
	});

  it("toggles checkboxes", function() {
    let oldConfig = currentPrefs();

    return pickSettingsWindow().
      then(() => app.client.waitUntilTextExists("body", TEXT_ON_SCREEN)).
      then(() => app.client.click("label*=Lock screen after running")).
      then(() => app.client.click("label*=Disable when on battery?")).
      then(() => app.client.click("label*=Auto start on login?")).
      then(() => app.client.click("label*=Only run on the primary display?")).
      then(() => app.client.click("button.save")).
      then(() => helpers.sleep(closeWindowDelay)).
      then(() => {
        let updatedPrefs = currentPrefs();
        assert.equal(!oldConfig.lock, updatedPrefs.lock);
        assert.equal(!oldConfig.disableOnBattery, updatedPrefs.disableOnBattery);
        assert.equal(!oldConfig.auto_start, updatedPrefs.auto_start);
        assert.equal(!oldConfig.runOnSingleDisplay, updatedPrefs.runOnSingleDisplay);
      });
  });

  it("leaves checkboxes", function() {
    let oldConfig = currentPrefs();

    return pickSettingsWindow().
      then(() => app.client.waitUntilTextExists("body", TEXT_ON_SCREEN)).
      then(() => app.client.click("button.save")).
      then(() => helpers.sleep(closeWindowDelay)).
      then(() => {
        let updatedPrefs = currentPrefs();
        assert.equal(oldConfig.lock, updatedPrefs.lock);
        assert.equal(oldConfig.disableOnBattery, updatedPrefs.disableOnBattery);
        assert.equal(oldConfig.auto_start, updatedPrefs.auto_start);
        assert.equal(oldConfig.runOnSingleDisplay, updatedPrefs.runOnSingleDisplay);
      });
  });

  it("allows setting path via dialog", function() {
    return pickSettingsWindow().
      then(() => app.webContents
        .executeJavaScript("document.querySelector(\"button.pick\").scrollIntoView()")).
      then(() => app.client.click("button.pick")).
      then(() => helpers.sleep(50)).
      then(() => app.client.click("button.save")).
      then(() => helpers.sleep(closeWindowDelay)).
      then(function() {
        assert.equal("/not/a/real/path", currentPrefs().localSource);
      });
  });

  it("clears localSource", function() {
    return pickSettingsWindow().
      then(() => app.client.waitUntilTextExists("body", TEXT_ON_SCREEN)).
      then(function() {
        let ls = currentPrefs().localSource;
        assert( ls != "" && ls !== undefined);
      }).
      then(() => app.webContents
        .executeJavaScript("document.querySelector(\"button.clear\").scrollIntoView()")).
      then(() => app.client.click("button.clear")).
      then(() => helpers.sleep(50)).
      then(() => app.client.click("button.save")).
      then(() => helpers.sleep(closeWindowDelay)).
      then(function() {
        assert.equal("", currentPrefs().localSource);
      });
  });

  it("resets defaults", function() {
    const resetDialogOpts = [ { method: "showMessageBoxSync", value: 1 } ];

    return pickSettingsWindow().
      then(() => app.fakeDialog.mock(resetDialogOpts)).
      then(() => app.webContents
        .executeJavaScript("document.querySelector(\"button.reset-to-defaults\").scrollIntoView()")).
      then(() => app.client.click("button.reset-to-defaults")).
      then(() => app.client.waitUntilTextExists("body", "Settings reset")).
      then(() => helpers.sleep(closeWindowDelay)).
      then(function() {
        assert.equal("", currentPrefs().localSource);
      });
  });
});
<|endoftext|>


<commit_before>import cloud from './CloudLayout';
import {transforms, Transform} from 'vega-dataflow';
import {constant, inherits, isFunction, truthy} from 'vega-util';
import {scale} from 'vega-scale';

var output = ['x', 'y', 'font', 'fontSize', 'fontStyle', 'fontWeight', 'angle'];

export default function Wordcloud(params) {
  Transform.call(this, cloud(), params);
}

var prototype = inherits(Wordcloud, Transform);

prototype.transform = function(_, pulse) {
  var mod = _.modified(),
      run = mod
        || pulse.changed(pulse.ADD_REM)
        || isFunction(_.text) && pulse.modified(_.text.fields)
        || isFunction(_.font) && pulse.modified(_.font.fields)
        || isFunction(_.rotate) && pulse.modified(_.rotate.fields)
        || isFunction(_.fontSize) && pulse.modified(_.fontSize.fields)
        || isFunction(_.fontStyle) && pulse.modified(_.fontStyle.fields)
        || isFunction(_.fontWeight) && pulse.modified(_.fontWeight.fields);
  if (!run) return;

  var layout = this.value,
      as = _.as || output,
      fontSize = _.fontSize || 14,
      range, fsize, sizeScale, words;

  isFunction(fontSize)
    ? (range = _.fontSizeRange)
    : (fontSize = constant(fontSize));

  // create font size scaling function as needed
  if (range) {
    fsize = fontSize;
    sizeScale = scale('sqrt')().domain(extent(fsize, pulse)).range(range);
    fontSize = function(x) { return sizeScale(fsize(x)); };
  }

  var data = pulse.materialize(pulse.SOURCE).source;
  data.forEach(function(t) {
    t[as[0]] = NaN;
    t[as[1]] = NaN;
    t[as[3]] = 0;
  });

  // configure layout
  words = layout
    .words(data)
    .text(_.text)
    .size(_.size || [500, 500])
    .padding(_.padding || 1)
    .spiral(_.spiral || 'archimedean')
    .rotate(_.rotate || 0)
    .font(_.font || 'sans-serif')
    .fontStyle(_.fontStyle || 'normal')
    .fontWeight(_.fontWeight || 'normal')
    .fontSize(fontSize)
    .layout();

  var size = layout.size(),
      dx = size[0] >> 1,
      dy = size[1] >> 1,
      i = 0,
      n = words.length,
      w, t;

  for (; i<n; ++i) {
    w = words[i];
    t = w.datum;
    t[as[0]] = w.x + dx;
    t[as[1]] = w.y + dy;
    t[as[2]] = w.font;
    t[as[3]] = w.size;
    t[as[4]] = w.style;
    t[as[5]] = w.weight;
    t[as[6]] = w.rotate;
  }

  return pulse.reflow(mod).modifies(as);
};

function extent(size, pulse) {
  var e = new transforms.Extent();
  e.transform({field: size, modified: truthy}, pulse);
  return e.value;
}
<commit_msg>Clean up Wordcloud modification tracking.<commit_after>import cloud from './CloudLayout';
import {transforms, Transform} from 'vega-dataflow';
import {constant, inherits, isFunction, truthy} from 'vega-util';
import {scale} from 'vega-scale';

var output = ['x', 'y', 'font', 'fontSize', 'fontStyle', 'fontWeight', 'angle'];
var params = ['text', 'font', 'rotate', 'fontSize', 'fontStyle', 'fontWeight'];

export default function Wordcloud(params) {
  Transform.call(this, cloud(), params);
}

var prototype = inherits(Wordcloud, Transform);

prototype.transform = function(_, pulse) {
  function modp(param) {
    var p = _[param];
    return isFunction(p) && pulse.modified(p.fields);
  }

  var mod = _.modified();
  if (!(mod || pulse.changed(pulse.ADD_REM) || params.some(modp))) return;

  var layout = this.value,
      as = _.as || output,
      fontSize = _.fontSize || 14,
      range, fsize, sizeScale, words;

  isFunction(fontSize)
    ? (range = _.fontSizeRange)
    : (fontSize = constant(fontSize));

  // create font size scaling function as needed
  if (range) {
    fsize = fontSize;
    sizeScale = scale('sqrt')().domain(extent(fsize, pulse)).range(range);
    fontSize = function(x) { return sizeScale(fsize(x)); };
  }

  var data = pulse.materialize(pulse.SOURCE).source;
  data.forEach(function(t) {
    t[as[0]] = NaN;
    t[as[1]] = NaN;
    t[as[3]] = 0;
  });

  // configure layout
  words = layout
    .words(data)
    .text(_.text)
    .size(_.size || [500, 500])
    .padding(_.padding || 1)
    .spiral(_.spiral || 'archimedean')
    .rotate(_.rotate || 0)
    .font(_.font || 'sans-serif')
    .fontStyle(_.fontStyle || 'normal')
    .fontWeight(_.fontWeight || 'normal')
    .fontSize(fontSize)
    .layout();

  var size = layout.size(),
      dx = size[0] >> 1,
      dy = size[1] >> 1,
      i = 0,
      n = words.length,
      w, t;

  for (; i<n; ++i) {
    w = words[i];
    t = w.datum;
    t[as[0]] = w.x + dx;
    t[as[1]] = w.y + dy;
    t[as[2]] = w.font;
    t[as[3]] = w.size;
    t[as[4]] = w.style;
    t[as[5]] = w.weight;
    t[as[6]] = w.rotate;
  }

  return pulse.reflow(mod).modifies(as);
};

function extent(size, pulse) {
  var e = new transforms.Extent();
  e.transform({field: size, modified: truthy}, pulse);
  return e.value;
}
<|endoftext|>


<commit_before>const assert = require('assert');
const Version = require('../index');
const Sequelize = require('sequelize');
const cls = require('continuation-local-storage');
const env = process.env;

const namespace = cls.createNamespace('my-very-own-namespace');
Sequelize.useCLS(namespace);

function getRawData(instance){
    return JSON.parse(JSON.stringify(instance));
}

function getVersionFields(prefix){
    const versionFieldId = `${prefix}_id`;
    const versionFieldType = `${prefix}_type`;
    const versionFieldTimestamp = `${prefix}_timestamp`;
    return [versionFieldId, versionFieldType, versionFieldTimestamp];
}

const sequelize = new Sequelize(env.DB_TEST, env.DB_USER, env.DB_PWD, {
    logging: console.log,
    dialect: 'postgres',
});

const TestModel = sequelize.define('test', {
    id: {
        type: Sequelize.BIGINT,
        autoIncrement: true,
        primaryKey: true,
    },
    name: {
        type: Sequelize.STRING,
        allowNull: false,
        defaultValue: 'test defaultValue',
        unique: true,
    },
    simple: Sequelize.STRING,
    createdAt: Sequelize.DATE,
});

const VersionModel = new Version(TestModel);

const versionFields = getVersionFields(Version.defaults.prefix);

before(done => {

    sequelize.sync({force: true}).then(() => done()).catch(err => done(err));

});

describe('sequelize-version', () => {

    beforeEach(done => {
        Promise.all([
            TestModel.destroy({truncate : true, restartIdentity: true}),
            VersionModel.destroy({truncate: true, restartIdentity: true})
        ]).then(() => done()).catch(err => done(err));
    })

    it ('basic usage', done => {

        const test = async() => {

            try{

                const testInstance = await TestModel.build({name: 'test'}).save();

                const versionInstance = await VersionModel.find({where : {
                    id: testInstance.id
                }});

                const versionsInstance = await VersionModel.findAll({where : {
                    id: testInstance.id
                }});

                const attributes = Object.keys(TestModel.attributes);
                const versionAttributes = Object.keys(VersionModel.attributes);

                attributes.forEach(attr => {
                    assert.deepEqual(versionInstance[attr], testInstance[attr])
                })

                assert.equal(1, versionsInstance.length);
                assert.equal(attributes.length + 3, versionAttributes.length);

                const versionAttrsCreated = versionAttributes.filter(attr => versionFields.includes(attr));

                assert.equal(versionAttrsCreated.length, versionFields.length)

            }catch(err){

                return err;
            }

        }

        test().then(result => done(result)).catch(err => done(err));

    })

    it ('all hooks working', done => {

        const test = async() => {

            try{

                let testInstance = await TestModel.build({name: 'test'}).save();
                testInstance.name = 'test changed';

                await testInstance.save();
                await testInstance.destroy();

                const versionsInstance = await VersionModel.findAll({where : {
                    id: testInstance.id
                }});

                return versionsInstance;

            }catch(err){

                return err;
            }

        }

        test().then(result => {

            if (typeof result === 'error') {
                done(result);
            }else{
                assert.equal(result.length, 3);
                assert.equal(Version.VersionType.CREATED, result[0].version_type);
                assert.equal(Version.VersionType.UPDATED, result[1].version_type);
                assert.equal(Version.VersionType.DELETED, result[2].version_type);
                done();
            }

        }).catch(err => done(err));

    })

    it ('must support transaction with cls', done => {

        const ERR_MSG = 'ROLLBACK_CLS_TEST';

        const test = async() => {

            try{

                await sequelize.transaction(async() => {

                    return Promise.all([
                         TestModel.build({name: 'test transaction cls'}).save().then(() => Promise.reject(new Error(ERR_MSG))),
                    ]);

                }).catch(async err => {

                    if (err.message === ERR_MSG){
                        const versions = await VersionModel.findAll();
                        assert.equal(versions.length, 0);

                    }else{
                        assert.fail(err);
                    }

                });

            }catch(err){

                return err;

            }

        }

        test().then(result => done(result)).catch(err => done(err));

    });

    it ('must support custom options', done => {

        const schema = 'test2';
        const prefix = 'audit';
        const suffix = 'log';

        const V2 = new Version(TestModel, {schema, prefix, suffix});

        assert.equal(V2.options.schema, schema)
        assert.equal(true, new RegExp(`^${prefix}`).test(V2.options.tableName));
        assert.equal(true, new RegExp(`${suffix}$`).test(V2.options.tableName));

        const test = async() => {

            try{

                await sequelize.query(`CREATE SCHEMA IF NOT EXISTS ${schema}`);

                await V2.sync({force: true});

                const testInstance = await TestModel.build({name: 'test'}).save();

                return Promise.all([
                    VersionModel.findAll({where: {id: testInstance.id}}),
                    V2.findAll({where: {id: testInstance.id}}),
                    Promise.resolve(testInstance)
                ]);

            }catch(err){

                return err;
            }

        }

        test().then(result => {

            if (typeof result === 'error') return done(result);

            const vs1 = result[0];
            const vs2 = result[1];
            const testInstance = result[2];

            const attributes = Object.keys(TestModel.attributes);

            attributes.forEach(attr => {
                assert.deepEqual(vs1[0][attr], testInstance[attr])
                assert.deepEqual(vs2[0][attr], testInstance[attr])
            });

            done();

        }).catch(err => done(err));

    });

    it ('must support global options', done => {

        const schema = 'test3';
        const prefix = 'version';
        const suffix = 'log';

        Version.defaults.schema = schema;
        Version.defaults.prefix = prefix;
        Version.defaults.suffix = suffix;

        const V3 = new Version(TestModel);

        assert.equal(V3.options.schema, schema)
        assert.equal(true, new RegExp(`^${prefix}`).test(V3.options.tableName));
        assert.equal(true, new RegExp(`${suffix}$`).test(V3.options.tableName));

        const test = async() => {

            try{

                await sequelize.query(`CREATE SCHEMA IF NOT EXISTS ${schema}`);

                await V3.sync({force: true});

                const testInstance = await TestModel.build({name: 'test'}).save();

                return Promise.all([
                    VersionModel.findAll({where: {id: testInstance.id}}),
                    V3.findAll({where: {id: testInstance.id}}),
                    Promise.resolve(testInstance)
                ]);

            }catch(err){

                return err;
            }

        }

        test().then(result => {

            if (typeof result === 'error') return done(result);

            const vs1 = result[0];
            const vs2 = result[1];
            const testInstance = result[2];

            const attributes = Object.keys(TestModel.attributes);

            attributes.forEach(attr => {
                assert.deepEqual(vs1[0][attr], testInstance[attr])
                assert.deepEqual(vs2[0][attr], testInstance[attr])
            });

            done();

        }).catch(err => done(err));

    })

});<commit_msg>test travis<commit_after>const assert = require('assert');
const Version = require('../index');
const Sequelize = require('sequelize');
const cls = require('continuation-local-storage');
const env = process.env;

const namespace = cls.createNamespace('my-very-own-namespace');
Sequelize.useCLS(namespace);

function getRawData(instance){
    return JSON.parse(JSON.stringify(instance));
}

function getVersionFields(prefix){
    const versionFieldId = `${prefix}_id`;
    const versionFieldType = `${prefix}_type`;
    const versionFieldTimestamp = `${prefix}_timestamp`;
    return [versionFieldId, versionFieldType, versionFieldTimestamp];
}

const sequelize = new Sequelize(env.DB_TEST, env.DB_USER, env.DB_PWD, {
    logging: console.log,
    dialect: 'postgres',
});

const TestModel = sequelize.define('test', {
    id: {
        type: Sequelize.BIGINT,
        autoIncrement: true,
        primaryKey: true,
    },
    name: {
        type: Sequelize.STRING,
        allowNull: false,
        defaultValue: 'test defaultValue',
        unique: true,
    },
    simple: Sequelize.STRING,
    createdAt: Sequelize.DATE,
});

const VersionModel = new Version(TestModel);

const versionFields = getVersionFields(Version.defaults.prefix);

before(done => {

    sequelize.sync({force: true}).then(() => done()).catch(err => done(err));

});

describe('sequelize-version', () => {

    beforeEach(done => {
        Promise.all([
            TestModel.destroy({truncate : true, restartIdentity: true}),
            VersionModel.destroy({truncate: true, restartIdentity: true})
        ]).then(() => done()).catch(err => done(err));
    })

    it ('basic usage', done => {

        const test = async() => {

            try{

                const testInstance = await TestModel.build({name: 'test'}).save();

                const versionInstance = await VersionModel.find({where : {
                    id: testInstance.id
                }});

                const versionsInstance = await VersionModel.findAll({where : {
                    id: testInstance.id
                }});

                const attributes = Object.keys(TestModel.attributes);
                const versionAttributes = Object.keys(VersionModel.attributes);

                attributes.forEach(attr => {
                    assert.deepEqual(versionInstance[attr], testInstance[attr])
                })

                assert.equal(1, versionsInstance.length);
                assert.equal(attributes.length + 3, versionAttributes.length);

                const versionAttrsCreated = versionAttributes.filter(attr => versionFields.includes(attr));

                assert.equal(versionAttrsCreated.length, versionFields.length)

            }catch(err){

                return err;
            }

        }

        test().then(result => done(result)).catch(err => done(err));

    })

    it ('all hooks working', done => {

        const test = async() => {

            try{

                let testInstance = await TestModel.build({name: 'test'}).save();
                testInstance.name = 'test changed';

                await testInstance.save();
                await testInstance.destroy();

                const versionsInstance = await VersionModel.findAll({where : {
                    id: testInstance.id
                }});

                return versionsInstance;

            }catch(err){

                return err;
            }

        }

        test().then(result => {

            if (typeof result === 'error') {
                done(result);
            }else{
                assert.equal(result.length, 3);
                assert.equal(Version.VersionType.CREATED, result[0].version_type);
                assert.equal(Version.VersionType.UPDATED, result[1].version_type);
                assert.equal(Version.VersionType.DELETED, result[2].version_type);
                done();
            }

        }).catch(err => done(err));

    })

    it ('must support transaction with cls', done => {

        const ERR_MSG = 'ROLLBACK_CLS_TEST';

        const test = async() => {

            try{

                await sequelize.transaction(async() => {

                    return Promise.all([
                         TestModel.build({name: 'test transaction cls'}).save().then(() => Promise.reject(new Error(ERR_MSG))),
                    ]);

                }).catch(async err => {

                    if (err.message === ERR_MSG){
                        const versions = await VersionModel.findAll();
                        assert.equal(versions.length, 0);

                    }else{
                        assert.fail(err);
                    }

                });

            }catch(err){

                return err;

            }

        }

        test().then(result => done(result)).catch(err => done(err));

    });

    it ('must support custom options', done => {

        const schema = 'test2';
        const prefix = 'audit';
        const suffix = 'log';

        const V2 = new Version(TestModel, {schema, prefix, suffix});

        assert.equal(V2.options.schema, schema)
        assert.equal(true, new RegExp(`^${prefix}`).test(V2.options.tableName));
        assert.equal(true, new RegExp(`${suffix}$`).test(V2.options.tableName));

        const test = async() => {

            try{

                await sequelize.query(`CREATE SCHEMA IF NOT EXISTS ${schema}`);

                await V2.sync({force: true});

                const testInstance = await TestModel.build({name: 'test'}).save();

                return Promise.all([
                    VersionModel.findAll({where: {id: testInstance.id}}),
                    V2.findAll({where: {id: testInstance.id}}),
                    Promise.resolve(testInstance)
                ]);

            }catch(err){

                return err;
            }

        }

        test().then(result => {

            if (typeof result === 'error') return done(result);

            const vs1 = result[0];
            const vs2 = result[1];
            const testInstance = result[2];

            const attributes = Object.keys(TestModel.attributes);

            attributes.forEach(attr => {
                assert.deepEqual(vs1[0][attr], testInstance[attr])
                assert.deepEqual(vs2[0][attr], testInstance[attr])
            });

            done();

        }).catch(err => done(err));

    });

    it ('must support global options', done => {

        const schema = 'test3';
        const prefix = 'version';
        const suffix = 'log';

        Version.defaults.schema = schema;
        Version.defaults.prefix = prefix;
        Version.defaults.suffix = suffix;

        const V3 = new Version(TestModel);

        assert.equal(V3.options.schema, schema)
        assert.equal(true, new RegExp(`^${prefix}`).test(V3.options.tableName));
        assert.equal(true, new RegExp(`${suffix}$`).test(V3.options.tableName));

        const test = async() => {

            try{

                await sequelize.query(`CREATE SCHEMA IF NOT EXISTS ${schema}`);

                await V3.sync({force: true});

                const testInstance = await TestModel.build({name: 'test'}).save();

                const result = await Promise.all([
                    VersionModel.findAll({where: {id: testInstance.id}}),
                    V3.findAll({where: {id: testInstance.id}}),
                    Promise.resolve(testInstance)
                ]);

                console.log('RESULT', result);

                return result;

            }catch(err){

                return err;
            }

        }

        test().then(result => {

            if (typeof result === 'error') return done(result);

                console.log('RESULT', result);

            const vs1 = result[0];
            const vs2 = result[1];
            const testInstance = result[2];

            const attributes = Object.keys(TestModel.attributes);

            attributes.forEach(attr => {
                assert.deepEqual(vs1[0][attr], testInstance[attr])
                assert.deepEqual(vs2[0][attr], testInstance[attr])
            });

            done();

        }).catch(err => done(err));

    })

});<|endoftext|>


<commit_before>/**
 * An example filter; it accepts the gettext object as its first argument, and
 * should invoke the callback with an error object and the modified translation
 * table.
 *
 * This filter removes translations that are used only in backend templates.
 *
 * @param gt
 * @param callback
 */
module.exports = function filter(gt, callback) {
	var clientSideSource = '/frontend/';
	var err;

	gt.listKeys("et").forEach(function(key) {
		var comment = gt.getComment("et", "", key);
		if (comment) {
			console.log(comment);
			if (comment.code && comment.code.indexOf(clientSideSource) === -1) {
				gt.deleteTranslation("et", "", key);
			}
		}
	});

	callback(err, gt._domains[gt._textdomain]._translationTable);
};
<commit_msg>Removing console.log<commit_after>/**
 * An example filter; it accepts the gettext object as its first argument, and
 * should invoke the callback with an error object and the modified translation
 * table.
 *
 * This filter removes translations that are used only in backend templates.
 *
 * @param gt
 * @param callback
 */
module.exports = function filter(gt, callback) {
	var clientSideSource = '/frontend/';
	var err;

	gt.listKeys("et").forEach(function(key) {
		var comment = gt.getComment("et", "", key);
		if (comment) {
			if (comment.code && comment.code.indexOf(clientSideSource) === -1) {
				gt.deleteTranslation("et", "", key);
			}
		}
	});

	callback(err, gt._domains[gt._textdomain]._translationTable);
};
<|endoftext|>


<commit_before>'use strict';

import querystring from 'querystring';
import Parse from './_parse.js';

/**
 * db base class
 * @type {Class}
 */
export default class extends Parse {
  /**
   * init
   * @return {} []
   */
  init(){
    super.init(config);
    this.sql = '';
    this.lastInsertId = 0;
    this.socket = null;
  }
  /**
   * get socket instance, override by sub class
   * @return {Object} [socket instance]
   */
  getSocketInstance(){

  }
  /**
   * insert data
   * @param  {Object} data    []
   * @param  {Object} options []
   * @param  {Boolean} replace []
   * @return {Promise}         []
   */
  add(data = {}, options = {}, replace){
    let values = [];
    let fields = [];
    for(let key in data){
      let val = data[key];
      val = this.parseValue(val);
      if (think.isString(val)) {
        values.push(val);
        fields.push(this.parseKey(key));
      }
    }
    let sql = (replace ? 'REPLACE' : 'INSERT') + ' INTO ';
    sql += this.parseTable(options.table) + ' (' + fields.join(',') + ') ';
    sql += 'VALUES(' + values.join(',') + ')';
    sql += this.parseLock(options.lock) + this.parseComment(options.comment);
    return this.execute(sql);
  }
  /**
   * insert multi data
   * @param  {Array} data    [data list]
   * @param  {Object} options []
   * @param  {Boolean} replace []
   * @return {Promise}         []
   */
  addMany(data, options, replace){
    let fields = Object.keys(data[0]);
    fields = fields.map(item => this.parseKey(item)).join(',');
    let values = data.map(item => {
      let value = [];
      for(let key in item){
        let val = item[key];
        val = this.parseValue(val);
        if (think.isString(val) || think.isBoolean(val) || think.isNumber(val)) {
          value.push(val);
        }
      }
      return '(' + value.join(',') + ')';
    }).join(',');
    let sql = replace ? 'REPLACE' : 'INSERT';
    sql += ' INTO ' + this.parseTable(options.table) + '(' + fields + ') VALUES ' + values;
    return this.execute(sql);
  }
  /**
   * select data
   * @param  {String} fields  []
   * @param  {String} table   []
   * @param  {Object} options []
   * @return {Promise}         []
   */
  selectAdd(fields, table, options = {}){
    if (think.isString(fields)) {
      fields = fields.split(',');
    }
    fields = fields.map(item => this.parseKey(item));
    let sql = 'INSERT INTO ' + this.parseTable(table) + ' (' + fields.join(',') + ') ';
    sql += this.buildSelectSql(options);
    return this.execute(sql);
  }
  /**
   * delete data
   * @param  {Object} options []
   * @return {Promise}         []
   */
  delete(options = {}){
    this.model = options.model;
    let sql = [
      'DELETE FROM ',
      this.parseTable(options.table),
      this.parseWhere(options.where),
      this.parseOrder(options.order),
      this.parseLimit(options.limit),
      this.parseLock(options.lock),
      this.parseComment(options.comment)
    ].join('');
    return this.execute(sql);
  }
  /**
   * update data
   * @param  {Object} data    []
   * @param  {Object} options []
   * @return {Promise}         []
   */
  update(data, options = {}){
    this.model = options.model;
    let sql = [
      'UPDATE ',
      this.parseTable(options.table),
      this.parseSet(data),
      this.parseWhere(options.where),
      this.parseOrder(options.order),
      this.parseLimit(options.limit),
      this.parseLock(options.lock),
      this.parseComment(options.comment)
    ].join('');
    return this.execute(sql);
  }
  /**
   * select
   * @param  {Object} options []
   * @return {Promise}         []
   */
  select(options = {}, cache){
    let sql;
    if(think.isObject(options)){
      sql = this.buildSelectSql(options);
      cache = options.cache;
    }else{
      sql = options;
    }
    if (!think.isEmpty(cache) && this.config.cache.on) {
      let key = cache.key || think.md5(sql);
      return think.cache(key, () => this.query(sql), cache);
    }
    return this.query(sql);
  }
  /**
   * escape string
   * @param  {String} str []
   * @return {String}     []
   */
  escapeString(str){
    if (!str) {
      return '';
    }
    return str.replace(/[\0\n\r\b\t\\\'\"\x1a]/g, s =>  {
      switch(s) {
        case '\0':
          return '\\0';
        case '\n':
          return '\\n';
        case '\r':
          return '\\r';
        case '\b':
          return '\\b';
        case '\t':
          return '\\t';
        case '\x1a':
          return '\\Z';
        default:
          return '\\'+s;
      }
    });
  }
  /**
   * get last sql
   * @return {String}       []
   */
  getLastSql(){
    return this.sql;
  }
  /**
   * get last insert id
   * @return {String} []
   */
  getLastInsertId(){
    return this.lastInsertId;
  }
  /**
   * query string
   * @param  string str
   * @return promise
   */
  query(str){
    return think.await(str, () => {
      return this.getSocketInstance().query(str).then(data => {
        return this.bufferToString(data);
      });
    })
  }
  /**
   * buffer to string
   * @param  {Array} data []
   * @return {Array}      []
   */
  bufferToString(data){
    if (!this.config.buffer_tostring || !think.isArray(data)) {
      return data;
    }
    for(let i = 0, length = data.length; i < length; i++){
      for(let key in data[i]){
        if(think.isBuffer(data[i][key])){
          data[i][key] = data[i][key].toString();
        }
      }
    }
    return data;
  }
  /**
   * execute sql
   * @param  {String} str []
   * @return {}     []
   */
  execute(str){
    return this.getSocketInstance().execute(str).then(data => {
      if (data.insertId) {
        this.lastInsertId = data.insertId;
      }
      return data.affectedRows || 0;
    });
  }
  /**
   * close connect
   * @return {} []
   */
  close(){
    if (this.socket) {
      this.socket.close();
      this.socket = null;
    }
  }
}<commit_msg>fix add data error when item data type is number<commit_after>'use strict';

import querystring from 'querystring';
import Parse from './_parse.js';

/**
 * db base class
 * @type {Class}
 */
export default class extends Parse {
  /**
   * init
   * @return {} []
   */
  init(){
    super.init(config);
    this.sql = '';
    this.lastInsertId = 0;
    this.socket = null;
  }
  /**
   * get socket instance, override by sub class
   * @return {Object} [socket instance]
   */
  getSocketInstance(){

  }
  /**
   * insert data
   * @param  {Object} data    []
   * @param  {Object} options []
   * @param  {Boolean} replace []
   * @return {Promise}         []
   */
  add(data = {}, options = {}, replace){
    let values = [];
    let fields = [];
    for(let key in data){
      let val = data[key];
      val = this.parseValue(val);
      if (think.isString(val) || think.isBoolean(val) || think.isNumber(val)) {
        values.push(val);
        fields.push(this.parseKey(key));
      }
    }
    let sql = (replace ? 'REPLACE' : 'INSERT') + ' INTO ';
    sql += this.parseTable(options.table) + ' (' + fields.join(',') + ') ';
    sql += 'VALUES(' + values.join(',') + ')';
    sql += this.parseLock(options.lock) + this.parseComment(options.comment);
    return this.execute(sql);
  }
  /**
   * insert multi data
   * @param  {Array} data    [data list]
   * @param  {Object} options []
   * @param  {Boolean} replace []
   * @return {Promise}         []
   */
  addMany(data, options, replace){
    let fields = Object.keys(data[0]);
    fields = fields.map(item => this.parseKey(item)).join(',');
    let values = data.map(item => {
      let value = [];
      for(let key in item){
        let val = item[key];
        val = this.parseValue(val);
        if (think.isString(val) || think.isBoolean(val) || think.isNumber(val)) {
          value.push(val);
        }
      }
      return '(' + value.join(',') + ')';
    }).join(',');
    let sql = replace ? 'REPLACE' : 'INSERT';
    sql += ' INTO ' + this.parseTable(options.table) + '(' + fields + ') VALUES ' + values;
    return this.execute(sql);
  }
  /**
   * select data
   * @param  {String} fields  []
   * @param  {String} table   []
   * @param  {Object} options []
   * @return {Promise}         []
   */
  selectAdd(fields, table, options = {}){
    if (think.isString(fields)) {
      fields = fields.split(',');
    }
    fields = fields.map(item => this.parseKey(item));
    let sql = 'INSERT INTO ' + this.parseTable(table) + ' (' + fields.join(',') + ') ';
    sql += this.buildSelectSql(options);
    return this.execute(sql);
  }
  /**
   * delete data
   * @param  {Object} options []
   * @return {Promise}         []
   */
  delete(options = {}){
    this.model = options.model;
    let sql = [
      'DELETE FROM ',
      this.parseTable(options.table),
      this.parseWhere(options.where),
      this.parseOrder(options.order),
      this.parseLimit(options.limit),
      this.parseLock(options.lock),
      this.parseComment(options.comment)
    ].join('');
    return this.execute(sql);
  }
  /**
   * update data
   * @param  {Object} data    []
   * @param  {Object} options []
   * @return {Promise}         []
   */
  update(data, options = {}){
    this.model = options.model;
    let sql = [
      'UPDATE ',
      this.parseTable(options.table),
      this.parseSet(data),
      this.parseWhere(options.where),
      this.parseOrder(options.order),
      this.parseLimit(options.limit),
      this.parseLock(options.lock),
      this.parseComment(options.comment)
    ].join('');
    return this.execute(sql);
  }
  /**
   * select
   * @param  {Object} options []
   * @return {Promise}         []
   */
  select(options = {}, cache){
    let sql;
    if(think.isObject(options)){
      sql = this.buildSelectSql(options);
      cache = options.cache;
    }else{
      sql = options;
    }
    if (!think.isEmpty(cache) && this.config.cache.on) {
      let key = cache.key || think.md5(sql);
      return think.cache(key, () => this.query(sql), cache);
    }
    return this.query(sql);
  }
  /**
   * escape string
   * @param  {String} str []
   * @return {String}     []
   */
  escapeString(str){
    if (!str) {
      return '';
    }
    return str.replace(/[\0\n\r\b\t\\\'\"\x1a]/g, s =>  {
      switch(s) {
        case '\0':
          return '\\0';
        case '\n':
          return '\\n';
        case '\r':
          return '\\r';
        case '\b':
          return '\\b';
        case '\t':
          return '\\t';
        case '\x1a':
          return '\\Z';
        default:
          return '\\'+s;
      }
    });
  }
  /**
   * get last sql
   * @return {String}       []
   */
  getLastSql(){
    return this.sql;
  }
  /**
   * get last insert id
   * @return {String} []
   */
  getLastInsertId(){
    return this.lastInsertId;
  }
  /**
   * query string
   * @param  string str
   * @return promise
   */
  query(str){
    return think.await(str, () => {
      return this.getSocketInstance().query(str).then(data => {
        return this.bufferToString(data);
      });
    })
  }
  /**
   * buffer to string
   * @param  {Array} data []
   * @return {Array}      []
   */
  bufferToString(data){
    if (!this.config.buffer_tostring || !think.isArray(data)) {
      return data;
    }
    for(let i = 0, length = data.length; i < length; i++){
      for(let key in data[i]){
        if(think.isBuffer(data[i][key])){
          data[i][key] = data[i][key].toString();
        }
      }
    }
    return data;
  }
  /**
   * execute sql
   * @param  {String} str []
   * @return {}     []
   */
  execute(str){
    return this.getSocketInstance().execute(str).then(data => {
      if (data.insertId) {
        this.lastInsertId = data.insertId;
      }
      return data.affectedRows || 0;
    });
  }
  /**
   * close connect
   * @return {} []
   */
  close(){
    if (this.socket) {
      this.socket.close();
      this.socket = null;
    }
  }
}<|endoftext|>


<commit_before>import React, { Component } from 'react';
require('smoothscroll-polyfill').polyfill();

class About extends Component {

  scrollToAbout() {
    document.querySelector('.about').scrollIntoView({
      behavior: 'smooth'
    });
  }

  render() {
    return (

Cal Factor Calculator

        <button
          className="button button--about"
          name="learn more"
          onClick={this.scrollToAbout}>
          Learn More
        </button>

About

The Cal Factor Calculator is a simple app intended to help Medtronic MiniMed insulin pump users calibrate their CGM sensors. Please note that the medical equipment itself is obviously more sophisticated and takes into account additional variables including your sensor's history. This app will help you calculate your "cal factor" and warn you about the most obvious of errors. To report an issue or request a feature please visit the GitHub repository.

Calibration Factor Equation

          Cal Factor = (Blood Glucose ÷ Interstitial Signal)

Useful Tips

Blood glucose must be between 40 - 400 or you will not be able to calibrate. (source)

Cal factor should be between 3 - 8 or the calibration will likely be rejected.

Wait at least 15 minutes between calibrations.  (source)

Do not calibrate if your blood glucose is rapidly rising or lowering. (source)

Your first couple of calibrations are the most important. Make sure these are very stable.

Hydration can potentially impact the accuracy of your ISIG value. Make sure you are not dehydrated when calibrating.

Experiences will vary from person to person. Although this app doesn't guarantee success hopefully it will help you avoid the unnecessary "Cal Error" warning.

⚠ Disclaimer

This website is not intended to serve as formal medical advice. Please consult your doctor regarding your health. For specific technical assistance with your insulin pump or CGM sensor contact the device manufacture. This website is not in any way affiliated with Medtronic MiniMed.

Last updated: June, 2017.

    );
  }
}

export default About;
<commit_msg>Fixing target=_blank links per security recommendation<commit_after>import React, { Component } from 'react';
require('smoothscroll-polyfill').polyfill();

class About extends Component {

  scrollToAbout() {
    document.querySelector('.about').scrollIntoView({
      behavior: 'smooth'
    });
  }

  render() {
    return (

Cal Factor Calculator

        <button
          className="button button--about"
          name="learn more"
          onClick={this.scrollToAbout}>
          Learn More
        </button>

About

The Cal Factor Calculator is a simple app intended to help Medtronic MiniMed insulin pump users calibrate their CGM sensors. Please note that the medical equipment itself is obviously more sophisticated and takes into account additional variables including your sensor's history. This app will help you calculate your "cal factor" and warn you about the most obvious of errors. To report an issue or request a feature please visit the GitHub repository.

Calibration Factor Equation

          Cal Factor = (Blood Glucose ÷ Interstitial Signal)

Useful Tips

Blood glucose must be between 40 - 400 or you will not be able to calibrate. (source)

Cal factor should be between 3 - 8 or the calibration will likely be rejected.

Wait at least 15 minutes between calibrations.  (source)

Do not calibrate if your blood glucose is rapidly rising or lowering. (source)

Your first couple of calibrations are the most important. Make sure these are very stable.

Hydration can potentially impact the accuracy of your ISIG value. Make sure you are not dehydrated when calibrating.

Experiences will vary from person to person. Although this app doesn't guarantee success hopefully it will help you avoid the unnecessary "Cal Error" warning.

⚠ Disclaimer

This website is not intended to serve as formal medical advice. Please consult your doctor regarding your health. For specific technical assistance with your insulin pump or CGM sensor contact the device manufacture. This website is not in any way affiliated with Medtronic MiniMed.

Last updated: June, 2017.

    );
  }
}

export default About;
<|endoftext|>


<commit_before>import React from 'react';
import _ from 'underscore';
import ReactTimeout from 'react-timeout'
import Column from './Column';
import TaskWrapper from './TaskWrapper';

import {
  PanResponder,
  Animated,
  ScrollView
} from 'react-native';

class Board extends React.Component {
  MAX_RANGE = 100
  MAX_DEG = 30
  TRESHOLD = 35

  constructor(props) {
    super(props);

    this.verticalOffset = 0;

    this.state = {
      rotate: new Animated.Value(0),
      startingX: 0,
      startingY: 0,
      x: 0,
      y: 0,
      movingMode: false,
    };

    this.panResponder = PanResponder.create({
      onStartShouldSetPanResponder: () => this.state.movingMode,
      onMoveShouldSetPanResponder: () => this.state.movingMode,
      onPanResponderTerminationRequest: () => !this.state.movingMode,
      onPanResponderMove: this.onPanResponderMove.bind(this),
      onPanResponderRelease: this.onPanResponderRelease.bind(this),
      onPanResponderTerminate: this.onPanResponderRelease.bind(this)
    })
  }

  componentWillUnmount() {
    this.unsubscribeFromMovingMode();
  }

  onPanResponderMove(event, gesture, callback) {
    const leftTopCornerX = this.state.startingX + gesture.dx;
    const leftTopCornerY = this.state.startingY + gesture.dy;
    if (this.state.movingMode) {
      const draggedItem = this.state.draggedItem;
      this.x = event.nativeEvent.pageX;
      this.y = event.nativeEvent.pageY;
      const columnAtPosition = this.props.rowRepository.move(draggedItem, this.x, this.y);
      if (columnAtPosition) {
        let { scrolling, offset } = this.props.rowRepository.scrollingPosition(columnAtPosition, this.x, this.y);
        if (this.shouldScroll(scrolling, offset, columnAtPosition)) {
          this.scroll(columnAtPosition, draggedItem, offset);
        }
      }

      this.setState({
        x: leftTopCornerX,
        y: leftTopCornerY
      });
    }
  }

  shouldScroll(scrolling, offset, column) {
    const placeToScroll = ((offset < 0 && column.scrollOffset() > 0) || (offset > 0 && column.scrollOffset() < column.contentHeight()));

    return scrolling && offset != 0 && placeToScroll;
  }

  onScrollingStarted() {
    this.scrolling = true;
  }

  onScrollingEnded() {
    this.scrolling = false;
  }

  isScrolling() {
    return this.scrolling;
  }

  scroll(column, draggedItem, anOffset) {
    if (!this.isScrolling()) {
      this.onScrollingStarted();
      const scrollOffset = column.scrollOffset() + 200 * anOffset;
      this.props.rowRepository.setScrollOffset(column.id(), scrollOffset);

      column.listView().scrollTo({ y: scrollOffset });
    }

    this.props.rowRepository.move(draggedItem, this.x, this.y);
    let { scrolling, offset } = this.props.rowRepository.scrollingPosition(column, this.x, this.y);
    if (this.shouldScroll(scrolling, offset, column)) {
      this.props.requestAnimationFrame(() => {
        this.scroll(column, draggedItem, offset);
      });
    }
  }

  endMoving() {
    this.setState({ movingMode: false });
    const { srcColumnId, draggedItem } = this.state;
    const { rowRepository, onDragEnd } = this.props;
    rowRepository.show(draggedItem.columnId(), draggedItem);
    rowRepository.notify(draggedItem.columnId(), 'reload');

    const destColumnId = draggedItem.columnId();
    onDragEnd && onDragEnd(srcColumnId, destColumnId, draggedItem);
  }

  onPanResponderRelease(e, gesture) {
    this.x = null;
    this.y = null;
    if (this.state.movingMode) {
      this.rotateBack();
      this.props.setTimeout(this.endMoving.bind(this), 200);
    } else if (this.isScrolling()) {
      this.unsubscribeFromMovingMode();
    }
  }

  rotateTo(value) {
    Animated.spring(
      this.state.rotate,
      {
        toValue: value,
        duration: 5000
      }
    ).start();
  }

  rotate() {
    this.rotateTo(this.MAX_DEG);
  }

  rotateBack() {
    this.rotateTo(0);
  }

  open(row) {
    this.props.open(row);
  }

  cancelMovingSubscription() {
    this.props.clearTimeout(this.movingSubscription);
  }

  unsubscribeFromMovingMode() {
    this.cancelMovingSubscription();
  }

  onPressIn(columnId, item, columnCallback) {
    return () => {
      if (item.isLocked() && this.isScrolling()) {
        this.unsubscribeFromMovingMode();
        return;
      }
      this.movingSubscription = this.props.setTimeout(() => {
        const { x, y } = item.layout();
        this.props.rowRepository.hide(columnId, item);
        this.setState({
          movingMode: true,
          draggedItem: item,
          srcColumnId: item.columnId(),
          startingX: x,
          startingY: y,
          x: x,
          y: y,
        });
        columnCallback();
        this.rotate();
      }, 200);
    }
  }

  onPress(item) {
    return () => {
      this.unsubscribeFromMovingMode();

      if (item.isLocked()) {
        return;
      }

      if (!this.state.movingMode) {
        this.open(item.row());
      } else {
        this.endMoving();
      }
    }
  }

  onScroll() {
    this.cancelMovingSubscription();
  }

  onScrollEnd(event) {
    this.props.rowRepository.updateColumnsLayoutAfterVisibilityChanged();
    this.verticalOffset = event.nativeEvent.contentOffset.x;
  }

  movingStyle(zIndex) {
    var interpolatedRotateAnimation = this.state.rotate.interpolate({
      inputRange: [-this.MAX_RANGE, 0, this.MAX_RANGE],
      outputRange: [`-${this.MAX_DEG}deg`, '0deg', `${this.MAX_DEG}deg`]
    });
    return {
      transform: [{rotate: interpolatedRotateAnimation}],
      position: 'absolute',
      zIndex: zIndex,
      top: this.state.y - this.TRESHOLD,
      left: this.verticalOffset + this.state.x
    };
  }

  movingTask() {
    const { draggedItem, movingMode } = this.state;
    // Without this when you drop a task it's impossible to drag it again...
    // And -1 is really needed for Android
    const zIndex = movingMode ? 1 : -1;
    const data = { item: draggedItem, hidden: !movingMode, style: this.movingStyle(zIndex) };
    return this.renderWrapperRow(data);
  }

  renderWrapperRow(data) {
    const { renderRow } = this.props;
    return (
      <TaskWrapper {...data}>
        {renderRow && data.item && renderRow(data.item.row())}
      </TaskWrapper>
    );
  }

  render() {
    const columns = this.props.rowRepository.columns();
    const columnWrappers = columns.map((column) => {
      const columnComponent = (
        <Column
          column={column}
          movingMode={this.state.movingMode}
          rowRepository={this.props.rowRepository}
          onPressIn={this.onPressIn.bind(this)}
          onPress={this.onPress.bind(this)}
          onPanResponderMove={this.onPanResponderMove.bind(this)}
          onPanResponderRelease={this.onPanResponderRelease.bind(this)}
          renderWrapperRow={this.renderWrapperRow.bind(this)}
          onScrollingStarted={this.onScrollingStarted.bind(this)}
          onScrollingEnded={this.onScrollingEnded.bind(this)}
          unsubscribeFromMovingMode={this.cancelMovingSubscription.bind(this)}
        />
      );
      return this.props.renderColumnWrapper(column.data(), column.index(), columnComponent);
    });

    return (
      <ScrollView
        style={this.props.style}
        scrollEnabled={!this.state.movingMode}
        onScroll={this.onScroll.bind(this)}
        onScrollEndDrag={this.onScrollEnd.bind(this)}
        onMomentumScrollEnd={this.onScrollEnd.bind(this)}
        horizontal={true}
        {...this.panResponder.panHandlers}
        {...this.props}
      >
        {this.movingTask()}
        {columnWrappers}
      </ScrollView>
    )
  }
}

export default ReactTimeout(Board);
<commit_msg>Scrolling is was fast.<commit_after>import React from 'react';
import _ from 'underscore';
import ReactTimeout from 'react-timeout'
import Column from './Column';
import TaskWrapper from './TaskWrapper';

import {
  PanResponder,
  Animated,
  ScrollView
} from 'react-native';

class Board extends React.Component {
  MAX_RANGE = 100
  MAX_DEG = 30
  TRESHOLD = 35

  constructor(props) {
    super(props);

    this.verticalOffset = 0;

    this.state = {
      rotate: new Animated.Value(0),
      startingX: 0,
      startingY: 0,
      x: 0,
      y: 0,
      movingMode: false,
    };

    this.panResponder = PanResponder.create({
      onStartShouldSetPanResponder: () => this.state.movingMode,
      onMoveShouldSetPanResponder: () => this.state.movingMode,
      onPanResponderTerminationRequest: () => !this.state.movingMode,
      onPanResponderMove: this.onPanResponderMove.bind(this),
      onPanResponderRelease: this.onPanResponderRelease.bind(this),
      onPanResponderTerminate: this.onPanResponderRelease.bind(this)
    })
  }

  componentWillUnmount() {
    this.unsubscribeFromMovingMode();
  }

  onPanResponderMove(event, gesture, callback) {
    const leftTopCornerX = this.state.startingX + gesture.dx;
    const leftTopCornerY = this.state.startingY + gesture.dy;
    if (this.state.movingMode) {
      const draggedItem = this.state.draggedItem;
      this.x = event.nativeEvent.pageX;
      this.y = event.nativeEvent.pageY;
      const columnAtPosition = this.props.rowRepository.move(draggedItem, this.x, this.y);
      if (columnAtPosition) {
        let { scrolling, offset } = this.props.rowRepository.scrollingPosition(columnAtPosition, this.x, this.y);
        if (this.shouldScroll(scrolling, offset, columnAtPosition)) {
          this.scroll(columnAtPosition, draggedItem, offset);
        }
      }

      this.setState({
        x: leftTopCornerX,
        y: leftTopCornerY
      });
    }
  }

  shouldScroll(scrolling, offset, column) {
    const placeToScroll = ((offset < 0 && column.scrollOffset() > 0) || (offset > 0 && column.scrollOffset() < column.contentHeight()));

    return scrolling && offset != 0 && placeToScroll;
  }

  onScrollingStarted() {
    this.scrolling = true;
  }

  onScrollingEnded() {
    this.scrolling = false;
  }

  isScrolling() {
    return this.scrolling;
  }

  scroll(column, draggedItem, anOffset) {
    if (!this.isScrolling()) {
      this.onScrollingStarted();
      const scrollOffset = column.scrollOffset() + 70 * anOffset;
      this.props.rowRepository.setScrollOffset(column.id(), scrollOffset);

      column.listView().scrollTo({ y: scrollOffset });
    }

    this.props.rowRepository.move(draggedItem, this.x, this.y);
    let { scrolling, offset } = this.props.rowRepository.scrollingPosition(column, this.x, this.y);
    if (this.shouldScroll(scrolling, offset, column)) {
      this.props.requestAnimationFrame(() => {
        this.scroll(column, draggedItem, offset);
      });
    }
  }

  endMoving() {
    this.setState({ movingMode: false });
    const { srcColumnId, draggedItem } = this.state;
    const { rowRepository, onDragEnd } = this.props;
    rowRepository.show(draggedItem.columnId(), draggedItem);
    rowRepository.notify(draggedItem.columnId(), 'reload');

    const destColumnId = draggedItem.columnId();
    onDragEnd && onDragEnd(srcColumnId, destColumnId, draggedItem);
  }

  onPanResponderRelease(e, gesture) {
    this.x = null;
    this.y = null;
    if (this.state.movingMode) {
      this.rotateBack();
      this.props.setTimeout(this.endMoving.bind(this), 200);
    } else if (this.isScrolling()) {
      this.unsubscribeFromMovingMode();
    }
  }

  rotateTo(value) {
    Animated.spring(
      this.state.rotate,
      {
        toValue: value,
        duration: 5000
      }
    ).start();
  }

  rotate() {
    this.rotateTo(this.MAX_DEG);
  }

  rotateBack() {
    this.rotateTo(0);
  }

  open(row) {
    this.props.open(row);
  }

  cancelMovingSubscription() {
    this.props.clearTimeout(this.movingSubscription);
  }

  unsubscribeFromMovingMode() {
    this.cancelMovingSubscription();
  }

  onPressIn(columnId, item, columnCallback) {
    return () => {
      if (item.isLocked() && this.isScrolling()) {
        this.unsubscribeFromMovingMode();
        return;
      }
      this.movingSubscription = this.props.setTimeout(() => {
        const { x, y } = item.layout();
        this.props.rowRepository.hide(columnId, item);
        this.setState({
          movingMode: true,
          draggedItem: item,
          srcColumnId: item.columnId(),
          startingX: x,
          startingY: y,
          x: x,
          y: y,
        });
        columnCallback();
        this.rotate();
      }, 200);
    }
  }

  onPress(item) {
    return () => {
      this.unsubscribeFromMovingMode();

      if (item.isLocked()) {
        return;
      }

      if (!this.state.movingMode) {
        this.open(item.row());
      } else {
        this.endMoving();
      }
    }
  }

  onScroll() {
    this.cancelMovingSubscription();
  }

  onScrollEnd(event) {
    this.props.rowRepository.updateColumnsLayoutAfterVisibilityChanged();
    this.verticalOffset = event.nativeEvent.contentOffset.x;
  }

  movingStyle(zIndex) {
    var interpolatedRotateAnimation = this.state.rotate.interpolate({
      inputRange: [-this.MAX_RANGE, 0, this.MAX_RANGE],
      outputRange: [`-${this.MAX_DEG}deg`, '0deg', `${this.MAX_DEG}deg`]
    });
    return {
      transform: [{rotate: interpolatedRotateAnimation}],
      position: 'absolute',
      zIndex: zIndex,
      top: this.state.y - this.TRESHOLD,
      left: this.verticalOffset + this.state.x
    };
  }

  movingTask() {
    const { draggedItem, movingMode } = this.state;
    // Without this when you drop a task it's impossible to drag it again...
    // And -1 is really needed for Android
    const zIndex = movingMode ? 1 : -1;
    const data = { item: draggedItem, hidden: !movingMode, style: this.movingStyle(zIndex) };
    return this.renderWrapperRow(data);
  }

  renderWrapperRow(data) {
    const { renderRow } = this.props;
    return (
      <TaskWrapper {...data}>
        {renderRow && data.item && renderRow(data.item.row())}
      </TaskWrapper>
    );
  }

  render() {
    const columns = this.props.rowRepository.columns();
    const columnWrappers = columns.map((column) => {
      const columnComponent = (
        <Column
          column={column}
          movingMode={this.state.movingMode}
          rowRepository={this.props.rowRepository}
          onPressIn={this.onPressIn.bind(this)}
          onPress={this.onPress.bind(this)}
          onPanResponderMove={this.onPanResponderMove.bind(this)}
          onPanResponderRelease={this.onPanResponderRelease.bind(this)}
          renderWrapperRow={this.renderWrapperRow.bind(this)}
          onScrollingStarted={this.onScrollingStarted.bind(this)}
          onScrollingEnded={this.onScrollingEnded.bind(this)}
          unsubscribeFromMovingMode={this.cancelMovingSubscription.bind(this)}
        />
      );
      return this.props.renderColumnWrapper(column.data(), column.index(), columnComponent);
    });

    return (
      <ScrollView
        style={this.props.style}
        scrollEnabled={!this.state.movingMode}
        onScroll={this.onScroll.bind(this)}
        onScrollEndDrag={this.onScrollEnd.bind(this)}
        onMomentumScrollEnd={this.onScrollEnd.bind(this)}
        horizontal={true}
        {...this.panResponder.panHandlers}
        {...this.props}
      >
        {this.movingTask()}
        {columnWrappers}
      </ScrollView>
    )
  }
}

export default ReactTimeout(Board);
<|endoftext|>


<commit_before>// A fake socket for minions

function MinionSocket(gameServer) {
    this.server = gameServer;
    this.isCloseRequested = false;
}

module.exports = MinionSocket;

MinionSocket.prototype.sendPacket = function (packet) {
    // Fakes sending a packet
    return;
};

MinionSocket.prototype.close = function (error) {
    // Removes the minion
    this.isCloseRequest = true;
};<commit_msg>Delete MinionSocket.js<commit_after><|endoftext|>


<commit_before>import React, { Component } from 'react'
import {
  Box,
  Container,
  Flex,
  Heading,
  Text,
  Label,
  Input,
  Button,
  LargeButton,
  mediaQueries,
  colors
} from '@hackclub/design-system'
import { Prompt } from 'react-static'

export const Error = Text.extend.attrs({
  className: 'error',
  color: 'error',
  f: 1,
  ml: 1
})`
  text-transform: lowercase;
  &:before { content: '— '; }
`

export class ConfirmClose extends Component {
  componentWillMount() {
    // https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm
    https: window.onbeforeunload = () => window.confirm()
  }

  componentWillUnmount() {
    window.onbeforeunload = null
  }

  render() {
    return (
      <Prompt message="Hold on, you're about to lose unsaved changes! Sure you want to leave?" />
    )
  }
}

export const Optional = Text.span.extend.attrs({
  children: '(optional)',
  className: 'optional',
  f: 1,
  ml: 1,
  color: 'muted'
})`
font-style: italic;
`

export class Field extends Component {
  componentWillMount() {
    const { type } = this.props
    const Tag = Input.withComponent(
      ['textarea', 'select'].indexOf(type) === -1 ? 'input' : type
    )

    this.setState({ Tag: Tag })
  }

  render() {
    const {
      type = 'text',
      name = 'name',
      label,
      p,
      children,
      error,
      optional
    } = this.props

    const { Tag } = this.state

    return (
      <Label className={type} mb={2} id={name}>
        <Flex align="center" mb="25rem" style={{ display: 'inline' }} wrap>
          {label}
          {optional ? <Optional /> : null}
          {error && <Error children={error} />}
        </Flex>
        <Tag
          name={name}
          type={type}
          height={type === 'textarea' ? '10rem' : 'inherit'}
          placeholder={p}
          children={children}
          {...this.props}
        />
      </Label>
    )
  }
}

export const Submit = ({ lg, ...props }) => {
  const Tag = props.lg
    ? LargeButton.withComponent('input')
    : Button.withComponent('input')
  return <Tag type="submit" {...props} />
}

export const FormWrapper = Flex.withComponent(Container).extend`
  flex-direction: column;
`

export const Form = Container.withComponent('form').extend.attrs({
  py: 4,
  px: 3,
  maxWidth: 48
})`
  display: grid;
  grid-gap: 1rem;
  ${mediaQueries[1]} {
    grid-template-columns: repeat(1, 1fr);
    h2, .textarea { grid-column: 1 / -1; }
  }
`

export const Subheading = Heading.h2.extend.attrs({
  f: 4,
  color: 'primary'
})`
  text-transform: capitalize;
`

const HeadingBox = Box.extend.attrs({
  mr: 3
})`
  text-align: left;
  order: 1;
  flex-grow: 0;
  flex-shrink: 0;
  flex-basis: auto;
  ${mediaQueries[1]} {
    flex-basis: 7rem;
    text-align: right;
  }
`

const FieldsBox = Box.extend.attrs({})`
  order: 2;
  flex-grow: 1;
`

export const Fieldset = props => (
  <Flex flexDirection={['column', 'row']}>
    <HeadingBox>
      <Subheading id={props.section}>{props.section}</Subheading>
    </HeadingBox>
    <FieldsBox>{props.children}</FieldsBox>
  </Flex>
)

export const Aside = props => <Box bg="snow" {...props} />
<commit_msg>Remove italics bc we don't have the license for it<commit_after>import React, { Component } from 'react'
import {
  Box,
  Container,
  Flex,
  Heading,
  Text,
  Label,
  Input,
  Button,
  LargeButton,
  mediaQueries,
  colors
} from '@hackclub/design-system'
import { Prompt } from 'react-static'

export const Error = Text.extend.attrs({
  className: 'error',
  color: 'error',
  f: 1,
  ml: 1
})`
  text-transform: lowercase;
  &:before { content: '— '; }
`

export class ConfirmClose extends Component {
  componentWillMount() {
    // https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm
    https: window.onbeforeunload = () => window.confirm()
  }

  componentWillUnmount() {
    window.onbeforeunload = null
  }

  render() {
    return (
      <Prompt message="Hold on, you're about to lose unsaved changes! Sure you want to leave?" />
    )
  }
}

export const Optional = Text.span.extend.attrs({
  children: '(optional)',
  className: 'optional',
  f: 1,
  ml: 1,
  color: 'muted'
})``

export class Field extends Component {
  componentWillMount() {
    const { type } = this.props
    const Tag = Input.withComponent(
      ['textarea', 'select'].indexOf(type) === -1 ? 'input' : type
    )

    this.setState({ Tag: Tag })
  }

  render() {
    const {
      type = 'text',
      name = 'name',
      label,
      p,
      children,
      error,
      optional
    } = this.props

    const { Tag } = this.state

    return (
      <Label className={type} mb={2} id={name}>
        <Flex align="center" mb="25rem" style={{ display: 'inline' }} wrap>
          {label}
          {optional ? <Optional /> : null}
          {error && <Error children={error} />}
        </Flex>
        <Tag
          name={name}
          type={type}
          height={type === 'textarea' ? '10rem' : 'inherit'}
          placeholder={p}
          children={children}
          {...this.props}
        />
      </Label>
    )
  }
}

export const Submit = ({ lg, ...props }) => {
  const Tag = props.lg
    ? LargeButton.withComponent('input')
    : Button.withComponent('input')
  return <Tag type="submit" {...props} />
}

export const FormWrapper = Flex.withComponent(Container).extend`
  flex-direction: column;
`

export const Form = Container.withComponent('form').extend.attrs({
  py: 4,
  px: 3,
  maxWidth: 48
})`
  display: grid;
  grid-gap: 1rem;
  ${mediaQueries[1]} {
    grid-template-columns: repeat(1, 1fr);
    h2, .textarea { grid-column: 1 / -1; }
  }
`

export const Subheading = Heading.h2.extend.attrs({
  f: 4,
  color: 'primary'
})`
  text-transform: capitalize;
`

const HeadingBox = Box.extend.attrs({
  mr: 3
})`
  text-align: left;
  order: 1;
  flex-grow: 0;
  flex-shrink: 0;
  flex-basis: auto;
  ${mediaQueries[1]} {
    flex-basis: 7rem;
    text-align: right;
  }
`

const FieldsBox = Box.extend.attrs({})`
  order: 2;
  flex-grow: 1;
`

export const Fieldset = props => (
  <Flex flexDirection={['column', 'row']}>
    <HeadingBox>
      <Subheading id={props.section}>{props.section}</Subheading>
    </HeadingBox>
    <FieldsBox>{props.children}</FieldsBox>
  </Flex>
)

export const Aside = props => <Box bg="snow" {...props} />
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import { string, boolean } from 'prop-types'

import commonPropTypes from './commonPropTypes'

class Image extends Component {

  static propTypes = {
    ...commonPropTypes,
    src: string.isRequired,
    srcset: string,
    noscript: boolean,
    alt: string
  }

  get fallback() {
    const { fallback } = this.props
    if (fallback) {
      return
{fallback}

    } else {
      return null
    }
  }

  get noscript() {
    const { noscript, src, width, height, alt } = this.props
    if (noscript) {
      return (

      )
    } else {
      return null
    }
  }

  get properties() {
    let {
      noloading,
      placeholder,
      fallback, // eslint-disable-line no-unused-vars, prefer-const
      noscript, // eslint-disable-line no-unused-vars, prefer-const
      ...rest // eslint-disable-line prefer-const
    } = this.props
    noloading = noloading && ''
    placeholder = placeholder && ''
    return { noloading, placeholder, ...rest }
  }

  render() {
    return (
      <amp-img {...{ ...this.properties } }>
        {this.fallback}
        {this.noscript}
      </amp-img>
    )
  }
}

export default Image
<commit_msg>Small beautification<commit_after>import React, { Component } from 'react'
import { string, boolean } from 'prop-types'

import commonPropTypes from './commonPropTypes'

class Image extends Component {

  static propTypes = {
    ...commonPropTypes,
    src: string.isRequired,
    srcset: string,
    noscript: boolean,
    alt: string
  }

  get fallback() {
    const { fallback } = this.props
    if (fallback) {
      return
{fallback}

    } else {
      return null
    }
  }

  get noscript() {
    const { noscript, src, width, height, alt } = this.props
    if (noscript) {
      return (

      )
    } else {
      return null
    }
  }

  get properties() {
    const {
      noloading,
      placeholder,
      fallback, // eslint-disable-line no-unused-vars
      ...rest
    } = this.props
    return {
      noloading: noloading && '',
      placeholder: placeholder && '',
      ...rest
    }
  }

  render() {
    return (
      <amp-img {...{ ...this.properties } }>
        {this.fallback}
        {this.noscript}
      </amp-img>
    )
  }
}

export default Image
<|endoftext|>


<commit_before>(function($) {
$.fn.bkviewer_index = function(options) {
return this.each(function() {
	var t = $(this), columns;

	function add_box(target, cur_box, item, prev) {
		var box;

		if (cur_box.height() > 500) {
			box = $('<ul />').addClass('bk-box')
					 .appendTo(target);

			if (prev && prev.hasClass('bk-category')) {
				box.append(prev);
			}

			box.append(item);
		} else {
			box = cur_box;
		}

		return box;
	}

	t.show_bookmarks({
		init: function(target, context) {
			context.cur_box = $('<ul />').addClass('bk-box')
						     .appendTo(target);
		},
		add_category_view: function(json, target, context) {
			var box, cur_box = context.cur_box;

			box = $('<li />').text(json['title'])
					 .addClass('bk-category')
					 .appendTo(cur_box);

			context.cur_box = add_box(target, cur_box, box,
						  context.prev);
			context.prev = box;
		},

		add_item_view: function(json, target, context) {
			var box, cur_box = context.cur_box, atag;

			box = $('<li />').addClass('bk-item')
					 .appendTo(cur_box);

			atag = $('<a />').text(json['title'])
				  .attr({'href': json['uri']})
				  .addClass('bk-item')
				  .appendTo(box);

			$('<img />').addClass('favicon')
				    .attr({'src': json['favicon']})
				    .prependTo(atag);

			context.cur_box = add_box(target, cur_box, box,
						  context.prev);
			context.prev = box;
		}
	});

	columns = $('.bk-box');

	columns.css({"height": 500});
	t.addClass('bv-clearfix');

	$(window).resize(function() {
				equal_spacing(t, columns);
			 });

	equal_spacing(t, columns);

	function equal_spacing(box, contents) {
		var box_width, item_width, items_num, margin, first_margin;
		var is_little = false;

		box_width = box.innerWidth() - 1;
		item_width = contents.outerWidth() + 1;

		items_num = Math.floor(box_width / item_width);
		if (items_num > contents.length) {
			items_num = contents.length;
			is_little = true;
		}

		margin = Math.floor((box_width % item_width) / items_num / 2);
		contents.css({"margin-right": margin, "margin-left": margin})

		if (is_little) {
			/* Don't do equal spacing it there is not enough
			   items */
			first_margin = items_num * (2 * margin + item_width);
			first_margin = box_width - first_margin;
			first_margin = Math.floor(margin + first_margin / 2);
			contents.first()
				.css({"margin-right": margin,
				      "margin-left": first_margin});
		}
	}
})}} (jQuery));
<commit_msg>index: Fixes missing return of the handle of <img><commit_after>(function($) {
$.fn.bkviewer_index = function(options) {
return this.each(function() {
	var t = $(this), columns;

	function add_box(target, cur_box, item, prev) {
		var box;

		if (cur_box.height() > 500) {
			box = $('<ul />').addClass('bk-box')
					 .appendTo(target);

			if (prev && prev.hasClass('bk-category')) {
				box.append(prev);
			}

			box.append(item);
		} else {
			box = cur_box;
		}

		return box;
	}

	t.show_bookmarks({
		init: function(target, context) {
			context.cur_box = $('<ul />').addClass('bk-box')
						     .appendTo(target);
		},
		add_category_view: function(json, target, context) {
			var box, cur_box = context.cur_box;

			box = $('<li />').text(json['title'])
					 .addClass('bk-category')
					 .appendTo(cur_box);

			context.cur_box = add_box(target, cur_box, box,
						  context.prev);
			context.prev = box;
		},

		add_item_view: function(json, target, context) {
			var box, cur_box = context.cur_box, atag, img;

			box = $('<li />').addClass('bk-item')
					 .appendTo(cur_box);

			atag = $('<a />').text(json['title'])
				  .attr({'href': json['uri']})
				  .addClass('bk-item')
				  .appendTo(box);

			img = $('<img />').addClass('favicon')
					  .attr({'src': json['favicon']})
					  .prependTo(atag);

			context.cur_box = add_box(target, cur_box, box,
						  context.prev);
			context.prev = box;

			return img;
		}
	});

	columns = $('.bk-box');

	columns.css({"height": 500});
	t.addClass('bv-clearfix');

	$(window).resize(function() {
				equal_spacing(t, columns);
			 });

	equal_spacing(t, columns);

	function equal_spacing(box, contents) {
		var box_width, item_width, items_num, margin, first_margin;
		var is_little = false;

		box_width = box.innerWidth() - 1;
		item_width = contents.outerWidth() + 1;

		items_num = Math.floor(box_width / item_width);
		if (items_num > contents.length) {
			items_num = contents.length;
			is_little = true;
		}

		margin = Math.floor((box_width % item_width) / items_num / 2);
		contents.css({"margin-right": margin, "margin-left": margin})

		if (is_little) {
			/* Don't do equal spacing it there is not enough
			   items */
			first_margin = items_num * (2 * margin + item_width);
			first_margin = box_width - first_margin;
			first_margin = Math.floor(margin + first_margin / 2);
			contents.first()
				.css({"margin-right": margin,
				      "margin-left": first_margin});
		}
	}
})}} (jQuery));
<|endoftext|>


<commit_before>/*
 * jQuery File Upload Plugin JS Example 8.8.2
 * https://github.com/blueimp/jQuery-File-Upload
 *
 * Copyright 2010, Sebastian Tschan
 * https://blueimp.net
 *
 * Licensed under the MIT license:
 * http://www.opensource.org/licenses/MIT
 */

/*jslint nomen: true, regexp: true */
/*global $, window, blueimp */
'use strict';

let dominator = {

  init: function(DOMelement) {
    this.el = DOMelement;
    this.files = new Map();   // Metadata related to uploaded files
    this.queueFiles = 0;      // Files in the process queue
    this.queueReady = false;
    this.processedFiles = 0;  // Number of succesfully processed files
  },

  /**
   * Callback function triggered when files have been added to upload queue
   */
  add: (e, data) => {
    dominator.queueFiles++
    let element = $('select#' + data.files[0].name.split('.')[0]);
    if(dominator.queueFiles <= 2) {
      dominator.files.set(element[0].id,
        {
          type: ''
        }
      );
      element.on('change', (e) => {
        dominator.setType(element[0].id, e.currentTarget.value);
      });
    } else {
      console.log('aborta mision');
      data.abort(); // TODO make it abort add
    }
    if(dominator.queueFiles == 2) {
      // TODO I thougt I could re-enable buttons here but no
    }
  },

  beforeUpload: data => {
    if(dominator.queueFiles == 2) {
      let name = data.data.get('file').name.split('.')[0];
      let file_type = data.data.get('file').name.split('.')[0].type;
      data.data.set('file_type', dominator.files.get(file_type));
      $('button.process').removeAttr('disabled');
    } else {
      alert('There must be at least 2 files to upload!');
    }
  },

  /**
   * Callback function to send uploaded files to processing in sqlizer
   */
  processFiles: data => {
    let key = undefined;
    let file = data.result.files[0];
    $.get('/process/' + file.resource_id,
      {},
      function(response) {
        if(response.Status === 'Complete') {
          if(dominator.processedFiles < 2) {
            dominator.files.get(response.FileName.split('.')[0]).data = response
            dominator.processedFiles++;
          }
          if(dominator.processedFiles == 2) {
            //Send only file type and name of the table created.
            let data = {};
            dominator.files.forEach((k, v) => {
              data[k.type] = k.data.TableName;
            });
            dominator.processed(data);
          }
        }
    });
  },

  /**
   * Callback funtion that triggers when each file returns a succesful state
   * from sqlizer
   */
  processed: data => {
    console.log('FALTA BLOQUEAR PANTALLA');
    $.get('/postproc/',
      data,
      function(response) {
        console.log(response);
    });
    console.log('LIBERAR PANTALLA');
  },

  /**
   * Mutex function for file types
   */
  setType: (file_id, file_type) => {
    console.log(file_id + ' '+file_type);
    if(dominator.files.has(file_id)) {
      dominator.files.get(file_id).type = file_type;
    }

    // Enable start upoad button only when files have file type
    let count = 0;
    dominator.files.forEach((v, k) => {
      if(v.type != undefined && v.type.length != 0
        && dominator.queueFiles == 2) {
        count++;
        if(count == 2) {
          dominator.queueReady = true;
          $('button.start').removeAttr('disabled');
        }
      }
    });
  },

}

$(function () {
  'use strict';

  dominator.init($('#fileupload')); // Initialize the dominator

    // Initialize the jQuery File Upload widget:
    $('#fileupload').fileupload({
      uploadTemplate: dominator.uploadTemplate
    })
    .on('fileuploadadded', dominator.add)
    .on('fileuploadsend', function(e, data) {
     dominator.beforeUpload(data);
    })
    .on('fileuploadcompleted', function(e, data) {
      $('#fileupload_control .process').on('click',
        dominator.processFiles(data));
    });

    // Enable iframe cross-domain access via redirect option:
    $('#fileupload').fileupload(
        'option',
        'redirect',
        window.location.href.replace(
            /\/[^\/]*$/,
            '/cors/result.html?%s'
        )
    );
});
<commit_msg>FIX undefined was sent in FormData when upload for the file_type<commit_after>/*
 * jQuery File Upload Plugin JS Example 8.8.2
 * https://github.com/blueimp/jQuery-File-Upload
 *
 * Copyright 2010, Sebastian Tschan
 * https://blueimp.net
 *
 * Licensed under the MIT license:
 * http://www.opensource.org/licenses/MIT
 */

/*jslint nomen: true, regexp: true */
/*global $, window, blueimp */
'use strict';

let dominator = {

  init: function(DOMelement) {
    this.el = DOMelement;
    this.files = new Map();   // Metadata related to uploaded files
    this.queueFiles = 0;      // Files in the process queue
    this.queueReady = false;
    this.processedFiles = 0;  // Number of succesfully processed files
  },

  /**
   * Callback function triggered when files have been added to upload queue
   */
  add: (e, data) => {
    dominator.queueFiles++
    let element = $('select#' + data.files[0].name.split('.')[0]);
    if(dominator.queueFiles <= 2) {
      dominator.files.set(element[0].id,
        {
          type: ''
        }
      );
      element.on('change', (e) => {
        dominator.setType(element[0].id, e.currentTarget.value);
      });
    } else {
      console.log('aborta mision');
      data.abort(); // TODO make it abort add
    }
    if(dominator.queueFiles == 2) {
      // TODO I thougt I could re-enable buttons here but no
    }
  },

  beforeUpload: data => {
    if(dominator.queueFiles == 2) {
      let name = data.get('file').name.split('.')[0];
      let file_type = dominator.files.get(name).type;
      data.set('file_type', file_type);
      $('button.process').removeAttr('disabled');
    } else {
      alert('There must be at least 2 files to upload!');
    }
    return data;
  },

  /**
   * Callback function to send uploaded files to processing in sqlizer
   */
  processFiles: data => {
    let key = undefined;
    let file = data.result.files[0];
    $.get('/process/' + file.resource_id,
      {},
      function(response) {
        if(response.Status === 'Complete') {
          if(dominator.processedFiles < 2) {
            dominator.files.get(response.FileName.split('.')[0]).data = response
            dominator.processedFiles++;
          }
          if(dominator.processedFiles == 2) {
            //Send only file type and name of the table created.
            let data = {};
            dominator.files.forEach((k, v) => {
              data[k.type] = k.data.TableName;
            });
            dominator.processed(data);
          }
        }
    });
  },

  /**
   * Callback funtion that triggers when each file returns a succesful state
   * from sqlizer
   */
  processed: data => {
    console.log('FALTA BLOQUEAR PANTALLA');
    $.get('/postproc/',
      data,
      function(response) {
        console.log(response);
    });
    console.log('LIBERAR PANTALLA');
  },

  /**
   * Mutex function for file types
   */
  setType: (file_id, file_type) => {
    if(dominator.files.has(file_id)) {
      dominator.files.get(file_id).type = file_type;
    }

    // Enable start upoad button only when files have file type
    let count = 0;
    dominator.files.forEach((v, k) => {
      if(v.type != undefined && v.type.length != 0
        && dominator.queueFiles == 2) {
        count++;
        if(count == 2) {
          dominator.queueReady = true;
          $('button.start').removeAttr('disabled');
        }
      }
    });
  },

}

$(function () {
  'use strict';

  dominator.init($('#fileupload')); // Initialize the dominator

    // Initialize the jQuery File Upload widget:
    $('#fileupload').fileupload({
      uploadTemplate: dominator.uploadTemplate
    })
    .on('fileuploadadded', dominator.add)
    .on('fileuploadsend', function(e, data) {
      console.log(data.data.values());
     data.data = dominator.beforeUpload(data.data);
      console.log(data.data.values());
    })
    .on('fileuploadcompleted', function(e, data) {
      $('#fileupload_control .process').on('click',
        dominator.processFiles(data));
    });

    // Enable iframe cross-domain access via redirect option:
    $('#fileupload').fileupload(
        'option',
        'redirect',
        window.location.href.replace(
            /\/[^\/]*$/,
            '/cors/result.html?%s'
        )
    );
});
<|endoftext|>


<commit_before>/*!
 * angular-masonry <%= pkg.version %>
 * Pascal Hartig, weluse GmbH, http://weluse.de/
 * License: MIT
 */
(function () {
  'use strict';

  angular.module('wu.masonry', [])
    .controller('MasonryCtrl', function controller($scope, $element, $timeout) {
      var bricks = {};
      var schedule = [];
      var destroyed = false;
      var self = this;
      var timeout = null;

      this.scheduleMasonryOnce = function scheduleMasonryOnce() {
        var args = arguments;
        var found = schedule.filter(function (item) {
          return item[0] === args[0];
        }).length > 0;

        if (!found) {
          this.scheduleMasonry.apply(null, arguments);
        }
      };

      // Make sure it's only executed once within a reasonable time-frame in
      // case multiple elements are removed or added at once.
      this.scheduleMasonry = function scheduleMasonry() {
        if (timeout) {
          $timeout.cancel(timeout);
        }

        schedule.push([].slice.call(arguments));

        timeout = $timeout(function runMasonry() {
          if (destroyed) {
            return;
          }
          schedule.forEach(function (args) {
            $element.masonry.apply($element, args);
          });
          schedule = [];
        }, 30);
      };

      function defaultLoaded($element) {
        $element.addClass('loaded');
      }

      this.appendBrick = function appendBrick(element, id) {
        if (destroyed) {
          return;
        }

        function _append() {
          if (Object.keys(bricks).length === 0) {
            $element.masonry('resize');
          }

          if (bricks[id] === undefined) {
            // I wanted to make this dynamic but ran into huuuge memory leaks
            // that I couldn't fix. If you know how to dynamically add a
            // callback so one could say <masonry loaded="callback($element)">
            // please submit a pull request!
            defaultLoaded(element);

            // Keep track of added elements.
            bricks[id] = true;
            $element.masonry('appended', element, true);
            self.scheduleMasonryOnce('layout');
          }
        }

        element.imagesLoaded(_append);
      };

      this.removeBrick = function removeBrick(id, element) {
        if (destroyed) {
          return;
        }

        delete bricks[id];
        $element.masonry('remove', element);
        this.scheduleMasonryOnce('layout');
      };

      this.destroy = function destroy() {
        destroyed = true;

        if ($element.data('masonry')) {
          // Gently uninitialize if still present
          $element.masonry('destroy');
        }

        bricks = [];
      };

    }).directive('masonry', function () {
      return {
        restrict: 'AE',
        controller: 'MasonryCtrl',
        link: function postLink(scope, element, attrs, ctrl) {
          var attrOptions = scope.$eval(attrs.options);
          var options = angular.extend(attrOptions || {}, {
            itemSelector: attrs.itemSelector || '.masonry-brick',
            columnWidth: parseInt(attrs.columnWidth, 10)
          });
          element.masonry(options);

          scope.$on('$destroy', ctrl.destroy);
        }
      };
    }).directive('masonryBrick', function () {
      return {
        restrict: 'AC',
        require: '^masonry',
        scope: true,
        link: function postLink(scope, element, attrs, ctrl) {
          var id = scope.$id;

          ctrl.appendBrick(element, id);
          element.on('$destroy', function () {
            ctrl.removeBrick(id, element);
          });
        }
      };
    });
}());
<commit_msg>feat(app): emit create/destroy events<commit_after>/*!
 * angular-masonry <%= pkg.version %>
 * Pascal Hartig, weluse GmbH, http://weluse.de/
 * License: MIT
 */
(function () {
  'use strict';

  angular.module('wu.masonry', [])
    .controller('MasonryCtrl', function controller($scope, $element, $timeout) {
      var bricks = {};
      var schedule = [];
      var destroyed = false;
      var self = this;
      var timeout = null;

      this.scheduleMasonryOnce = function scheduleMasonryOnce() {
        var args = arguments;
        var found = schedule.filter(function (item) {
          return item[0] === args[0];
        }).length > 0;

        if (!found) {
          this.scheduleMasonry.apply(null, arguments);
        }
      };

      // Make sure it's only executed once within a reasonable time-frame in
      // case multiple elements are removed or added at once.
      this.scheduleMasonry = function scheduleMasonry() {
        if (timeout) {
          $timeout.cancel(timeout);
        }

        schedule.push([].slice.call(arguments));

        timeout = $timeout(function runMasonry() {
          if (destroyed) {
            return;
          }
          schedule.forEach(function (args) {
            $element.masonry.apply($element, args);
          });
          schedule = [];
        }, 30);
      };

      function defaultLoaded($element) {
        $element.addClass('loaded');
      }

      this.appendBrick = function appendBrick(element, id) {
        if (destroyed) {
          return;
        }

        function _append() {
          if (Object.keys(bricks).length === 0) {
            $element.masonry('resize');
          }

          if (bricks[id] === undefined) {
            // I wanted to make this dynamic but ran into huuuge memory leaks
            // that I couldn't fix. If you know how to dynamically add a
            // callback so one could say <masonry loaded="callback($element)">
            // please submit a pull request!
            defaultLoaded(element);

            // Keep track of added elements.
            bricks[id] = true;
            $element.masonry('appended', element, true);
            self.scheduleMasonryOnce('layout');
          }
        }

        element.imagesLoaded(_append);
      };

      this.removeBrick = function removeBrick(id, element) {
        if (destroyed) {
          return;
        }

        delete bricks[id];
        $element.masonry('remove', element);
        this.scheduleMasonryOnce('layout');
      };

      this.destroy = function destroy() {
        destroyed = true;

        if ($element.data('masonry')) {
          // Gently uninitialize if still present
          $element.masonry('destroy');
        }
        $scope.$emit('masonry.destroyed');

        bricks = [];
      };

    }).directive('masonry', function () {
      return {
        restrict: 'AE',
        controller: 'MasonryCtrl',
        link: function postLink(scope, element, attrs, ctrl) {
          var attrOptions = scope.$eval(attrs.options);
          var options = angular.extend(attrOptions || {}, {
            itemSelector: attrs.itemSelector || '.masonry-brick',
            columnWidth: parseInt(attrs.columnWidth, 10)
          });
          element.masonry(options);

          scope.$emit('masonry.created', element);

          scope.$on('$destroy', ctrl.destroy);
        }
      };
    }).directive('masonryBrick', function () {
      return {
        restrict: 'AC',
        require: '^masonry',
        scope: true,
        link: function postLink(scope, element, attrs, ctrl) {
          var id = scope.$id;

          ctrl.appendBrick(element, id);
          element.on('$destroy', function () {
            ctrl.removeBrick(id, element);
          });
        }
      };
    });
}());
<|endoftext|>