<commit_before>#! /usr/bin/env node
// export GITHUB_TOKEN=xxx
// git config --global credential.helper osxkeychain

const LabelSync = require("github-issues-label-sync"),
      eslint = require("./eslint.json"),
      shell = require("shelljs"),
      token = shell.env.GITHUB_TOKEN,
      {name} = JSON.parse(shell.cat("package.json"));

shell.echo("creating .eslintrc");
new shell.ShellString(JSON.stringify(eslint, null, 2)).to(".eslintrc");

shell.echo("creating .gitignore");
new shell.ShellString(`.DS_Store
build/
example/*.html
node_modules
test/*.html
test/*.png
`).to(".gitignore");

shell.echo("creating .npmignore");
new shell.ShellString(`build/*.zip
example/
test/
.eslintrc
.gitignore
.travis.yml
`).to(".npmignore");

shell.echo("creating .travis.yml");
new shell.ShellString(`language: node_js

node_js:
  - "node"

addons:
  apt:
    packages:
      - xvfb
install:
  - export DISPLAY=':99.0'
  - Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 &
  - npm install
  - npm link
`).to(".travis.yml");

shell.echo("creating LICENSE");
new shell.ShellString(`The MIT License (MIT)

Copyright (c) ${new Date().getFullYear()} D3plus

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
`).to("LICENSE");

// labeling system inspired by
// https://robinpowered.com/blog/best-practice-system-for-organizing-and-tagging-github-issues/
const labels = [
  {color: "#ee3f46", name: "bug"},

  {color: "#fef2c0", name: "chore"},

  {color: "#ffc274", name: "design"},

  {color: "#91ca55", name: "feature"},

  {color: "#5ebeff", name: "enhancement"},
  {color: "#5ebeff", name: "optimization"},

  {color: "#cc317c", name: "discussion"},
  {color: "#cc317c", name: "question"},

  {color: "#ededed", name: "duplicate"},
  {color: "#ededed", name: "invalid"},
  {color: "#ededed", name: "wontfix"},
  {color: "#ededed", name: "greenkeeper"}
].map(l => ({name: l.name, color: l.color.substring(1)}));

const issueSync = new LabelSync({}, "d3plus", name, token);
issueSync.updateLabels(labels).then(() => shell.echo("issue labels synced"));
<commit_msg>fixes issue label sync in d3plus-env script<commit_after>#! /usr/bin/env node
// export GITHUB_TOKEN=xxx
// git config --global credential.helper osxkeychain

const LabelSync = require("github-issues-label-sync"),
      eslint = require("./eslint.json"),
      shell = require("shelljs"),
      token = shell.env.GITHUB_TOKEN,
      {name} = JSON.parse(shell.cat("package.json"));

shell.echo("creating .eslintrc");
new shell.ShellString(JSON.stringify(eslint, null, 2)).to(".eslintrc");

shell.echo("creating .gitignore");
new shell.ShellString(`.DS_Store
build/
example/*.html
node_modules
test/*.html
test/*.png
`).to(".gitignore");

shell.echo("creating .npmignore");
new shell.ShellString(`build/*.zip
example/
test/
.eslintrc
.gitignore
.travis.yml
`).to(".npmignore");

shell.echo("creating .travis.yml");
new shell.ShellString(`language: node_js

node_js:
  - "node"

addons:
  apt:
    packages:
      - xvfb
install:
  - export DISPLAY=':99.0'
  - Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 &
  - npm install
  - npm link
`).to(".travis.yml");

shell.echo("creating LICENSE");
new shell.ShellString(`The MIT License (MIT)

Copyright (c) ${new Date().getFullYear()} D3plus

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
`).to("LICENSE");

// labeling system inspired by
// https://robinpowered.com/blog/best-practice-system-for-organizing-and-tagging-github-issues/
const labels = [
  {color: "#ee3f46", name: "bug"},

  {color: "#fef2c0", name: "chore"},

  {color: "#ffc274", name: "design"},

  {color: "#91ca55", name: "feature"},

  {color: "#5ebeff", name: "enhancement"},
  {color: "#5ebeff", name: "optimization"},

  {color: "#cc317c", name: "discussion"},
  {color: "#cc317c", name: "question"},

  {color: "#ededed", name: "duplicate"},
  {color: "#ededed", name: "invalid"},
  {color: "#ededed", name: "wontfix"},
  {color: "#ededed", name: "greenkeeper"}
].map(l => ({name: l.name, color: l.color.substring(1)}));

const issueSync = new LabelSync({}, "d3plus", name, token);
issueSync.createLabels(labels)
  .then(() => shell.echo("issue labels created"))
  .catch(err => console.log(err.toJSON()))
  .then(() => {
    issueSync.updateLabels(labels)
      .then(() => shell.echo("issue labels synced"))
      .catch(err => console.log(err.toJSON()));
  });
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { connect } from 'react-apollo';
import gql from 'graphql-tag';
import moment from 'moment';
import BalancePanel from 'components/billing/balance-panel';
import PaymentInfoPanel from 'components/billing/payment-info-panel';
import UsagePanel from 'components/billing/usage-panel';
import AddCardForm from 'containers/billing/add-card-form';
import TransactionsList from 'components/billing/transactions-list';
import 'containers/billing/billing.scss';
import { setBalance, setUsage } from 'redux/modules/transaction-group';

const transactionRangeQuery =
  gql`query usageTransactions($startDate: String!, $endDate: String!) {
      credits(startDate: $startDate, endDate: $endDate) {
        id,
        paid_amount,
        created,
        type
      }
      debits(startDate: $startDate, endDate: $endDate) {
        id,
        amount,
        created,
        type
      },
    }`;

const mapQueriesToProps = () => {
  return {
    paymentProcessor: {
      query: gql`query {
        paymentProcessor {
          id,
          name,
          billingDate,
          defaultPaymentMethod {
            merchant,
            lastFour,
            id
          },
          error
        }
      }`
    },
    transactions: {
      query: gql`query {
        credits {
          id,
          paid_amount,
          created,
          type
        },
        debits {
          id,
          amount,
          created,
          type
        }
      }`
    }
  }
};

const mapMutationsToProps = () => {
  return {
    removeCard: (paymentProcessorId, paymentMethodId) => {
      return {
        // TODO: maybe add `id,` to get query update?
        mutation: gql`
        mutation removePaymentMethod($paymentProcessorId: String!, $paymentMethodId: String!) {
          removePaymentMethod(paymentProcessorId: $paymentProcessorId, paymentMethodId: $paymentMethodId) {
            id,
            name,
            billingDate,
            defaultPaymentMethod {
              merchant,
              lastFour,
              id
            },
            error
          }
        }`,
        variables: {
          paymentProcessorId,
          paymentMethodId
        }
      };
    }
  };
};

const mapDispatchToProps = {
  setBalance,
  setUsage
};

const mapStateToProps = ({transactionGroup: {balance, usage}}) => {
  return {balance, usage};
};

let globalCounter = 0;

@connect({
  mapQueriesToProps,
  mapMutationsToProps,
  mapDispatchToProps,
  mapStateToProps
})

export default class Billing extends Component {
  componentWillReceiveProps(nextProps) {
    globalCounter++;
    if (globalCounter > 50) return;

    const {balance, usage} = nextProps;

    if (!!balance && !!usage) {
      return;
    }

    const {startDate: balanceStartDate, endDate: balanceEndDate} = this.getBalanceRange();
    const {startDate: usageStartDate, endDate: usageEndDate} = this.getUsageRange();

    if (!(balance && balance.loading)) {
      const balancePromise = this.props.query({
        query: transactionRangeQuery,
        variables: {
          startDate: balanceStartDate,
          endDate: balanceEndDate
        }
      });

      balancePromise.then(({data: {credits, debits}, loading}) => {
        const balance = this.calculateBalance(credits, debits);
        this.props.setBalance(balance);
      });
    }

    if (!(usage && usage.loading)) {
      const usagePromise = this.props.query({
        query: transactionRangeQuery,
        variables: {
          startDate: usageStartDate,
          endDate: usageEndDate
        }
      });

      usagePromise.then(({data: {credits, debits}}) => {
        const usage = this.calculateBalance(credits, debits);
        this.props.setUsage(usage);
      });
    }
  }

  getBalanceRange() {
    return this.getRange(1);
  }

  getUsageRange() {
    return this.getRange(0);
  }

  getRange(offset) {
    const {loading, paymentProcessor} = this.props.paymentProcessor;
    const billingDate = (loading || !paymentProcessor) ?
      (new Date).getDate() : paymentProcessor.billingDate;

    const format = 'YYYY-MM-DD HH:mm:ss.SSS';
    const today = new Date();
    const currentYearMonth = [
      today.getUTCFullYear(),
      // NB: add 1 to `.getUTCMonth` because `Date` uses 0 for Jan while `moment` uses 1
      today.getUTCMonth() + 1
    ];

    const dateThisMonthString = (date) => {
      return `${currentYearMonth.concat([date]).join('-')} 00:00:00.000`
    };

    const daysInMonth = moment.utc(
      dateThisMonthString(1), format
    )
      .subtract(offset, 'month')
      .add(1, 'month')
      .subtract(1, 'day')
      .date();

    const startDayOfMonth = (billingDate > daysInMonth) ? daysInMonth : billingDate;
    const startDate = moment.utc(
      dateThisMonthString(startDayOfMonth), format
    ).subtract(offset, 'month').valueOf();

    const endDate = (moment(startDate).add('1', 'month').valueOf());

    return {
      startDate,
      endDate
    };
  }

  calculateBalance(credits, debits) {
    const creditSum = credits.reduce((total, item) => {
      return total + item.paid_amount;
    }, 0);
    const debitSum = debits.reduce((total, item) => {
      return total + item.amount;
    }, 0);
    const balance = debitSum - creditSum;
    return balance;
  }

  getPaymentInfo() {
    const {loading} = this.props.paymentProcessor;

    if (loading || !this.props.paymentProcessor.paymentProcessor) {
      return {};
    }

    const {defaultPaymentMethod} = this.props.paymentProcessor.paymentProcessor;
    return defaultPaymentMethod || {};
  }

  getTransactions() {
    const {loading, credits, debits} = this.props.transactions;
    let transactions;

    if (loading || !credits || !debits) {
      return [];
    }

    const convertedCredits = credits.map((credit) => {
      const transaction = {...credit};
      transaction.amount = -credit.paid_amount;
      const titleizedType = credit.type
        .replace(/^\w/, (w) => (w.toUpperCase()));
      transaction.description = `${titleizedType} payment - Thank you!`;
      transaction.timestamp = moment.utc(credit.created).valueOf();
      transaction.created = `${moment.utc((credit.created))
        .format('MMM DD, YYYY - HH:mm')} UTC`;
      return transaction;
    });

    const convertedDebits = debits.map((debit) => {
      const transaction = {...debit};
      const titleizedType = debit.type
        .replace(/^\w/, (w) => (w.toUpperCase()));
      transaction.description = `${titleizedType} usage`;
      transaction.timestamp = Date.parse(debit.created);
      transaction.created = `${moment.utc((debit.created))
        .format('MMM DD, YYYY - HH:mm')} UTC`;
      return transaction;
    });

    transactions = [...convertedCredits, ...convertedDebits];

    return transactions.sort((t1, t2) => (t2.timestamp - t1.timestamp));
  }

  removeCard() {
    const {removeCard} = this.props.mutations;
    // TODO: use apollo watchquery correctly so we don't have to call `refetch`
    const {
      refetch, paymentProcessor: {
      id: paymentProcessorId,
      defaultPaymentMethod: {id: paymentMethodId}
    }
    } = this.props.paymentProcessor;

    removeCard(
      paymentProcessorId,
      paymentMethodId
    ).then(() => (refetch()));
  }

  render() {
    const addCreditHandler = () => {
    };
    const linkParams = '/dashboard/billing/usage';

    return (

Billing

                  Billing is in test mode and is not activated yet.
                  Don't try to submit the form.
                  We'll notify you when billing is activated.

                <BalancePanel amount={this.props.balance}
                              addCreditHandler={addCreditHandler}
                              cardData={this.getPaymentInfo()}/>

                <UsagePanel amount={this.props.usage} linkParams={linkParams}/>

                { !this.getPaymentInfo().id ? null :
                  <PaymentInfoPanel
                    removeCardHandler={this.removeCard.bind(this)}
                    paymentInfo={this.getPaymentInfo()}
                  />
                }

          { !!this.getPaymentInfo().id ? null : <AddCardForm
            // TODO: use apollo watchquery correctly so we don't have to call `refetch`
            updatePaymentInfo={this.props.paymentProcessor.refetch}/> }

          <TransactionsList transactions={this.getTransactions()}/>

    );
  }
}
<commit_msg>moar bugfixing<commit_after>import React, { Component } from 'react';
import { connect } from 'react-apollo';
import gql from 'graphql-tag';
import moment from 'moment';
import BalancePanel from 'components/billing/balance-panel';
import PaymentInfoPanel from 'components/billing/payment-info-panel';
import UsagePanel from 'components/billing/usage-panel';
import AddCardForm from 'containers/billing/add-card-form';
import TransactionsList from 'components/billing/transactions-list';
import 'containers/billing/billing.scss';
import { setBalance, setUsage } from 'redux/modules/transaction-group';

const transactionRangeQuery =
  gql`query usageTransactions($startDate: String!, $endDate: String!) {
      credits(startDate: $startDate, endDate: $endDate) {
        id,
        paid_amount,
        created,
        type
      }
      debits(startDate: $startDate, endDate: $endDate) {
        id,
        amount,
        created,
        type
      },
    }`;

const mapQueriesToProps = () => {
  return {
    paymentProcessor: {
      query: gql`query {
        paymentProcessor {
          id,
          name,
          billingDate,
          defaultPaymentMethod {
            merchant,
            lastFour,
            id
          },
          error
        }
      }`
    },
    transactions: {
      query: gql`query {
        credits {
          id,
          paid_amount,
          created,
          type
        },
        debits {
          id,
          amount,
          created,
          type
        }
      }`
    }
  }
};

const mapMutationsToProps = () => {
  return {
    removeCard: (paymentProcessorId, paymentMethodId) => {
      return {
        // TODO: maybe add `id,` to get query update?
        mutation: gql`
        mutation removePaymentMethod($paymentProcessorId: String!, $paymentMethodId: String!) {
          removePaymentMethod(paymentProcessorId: $paymentProcessorId, paymentMethodId: $paymentMethodId) {
            id,
            name,
            billingDate,
            defaultPaymentMethod {
              merchant,
              lastFour,
              id
            },
            error
          }
        }`,
        variables: {
          paymentProcessorId,
          paymentMethodId
        }
      };
    }
  };
};

const mapDispatchToProps = {
  setBalance,
  setUsage
};

const mapStateToProps = ({transactionGroup: {balance, usage}}) => {
  return {balance, usage};
};

let globalCounter = 0;

@connect({
  mapQueriesToProps,
  mapMutationsToProps,
  mapDispatchToProps,
  mapStateToProps
})

export default class Billing extends Component {
  componentWillReceiveProps(nextProps) {
    globalCounter++;
    if (globalCounter > 50) return;

    const {balance, usage} = nextProps;

    if (!!balance && !!usage) {
      return;
    }

    const {startDate: balanceStartDate, endDate: balanceEndDate} = this.getBalanceRange();
    const {startDate: usageStartDate, endDate: usageEndDate} = this.getUsageRange();

    if (!(balance && balance.loading)) {
      const balancePromise = this.props.query({
        query: transactionRangeQuery,
        variables: {
          startDate: balanceStartDate,
          endDate: balanceEndDate
        }
      });

      balancePromise.then(({data: {credits, debits}, loading}) => {
        const balance = this.calculateBalance(credits, debits);
        this.props.setBalance(balance);
      });
    }

    if (!(usage && usage.loading)) {
      const usagePromise = this.props.query({
        query: transactionRangeQuery,
        variables: {
          startDate: usageStartDate,
          endDate: usageEndDate
        }
      });

      usagePromise.then(({data: {credits, debits}}) => {
        const usage = this.calculateBalance(credits, debits);
        this.props.setUsage(usage);
      });
    }
  }

  getBalanceRange() {
    return this.getRange(1);
  }

  getUsageRange() {
    return this.getRange(0);
  }

  getRange(offset) {
    const {loading, paymentProcessor} = this.props.paymentProcessor;
    const billingDate = (loading || !paymentProcessor) ?
      (new Date).getDate() : paymentProcessor.billingDate;

    const format = 'YYYY-MM-DD HH:mm:ss.SSS';
    const today = new Date();
    const currentYearMonth = [
      today.getUTCFullYear(),
      today.getUTCMonth() + 1 - offset
    ];

    const dateThisMonthString = (date) => {
      return `${currentYearMonth.concat([date]).join('-')} 00:00:00.000`
    };

    const daysInMonth = moment.utc(
      dateThisMonthString(1), format
    )
      .subtract(offset, 'month')
      .add(1, 'month')
      .subtract(1, 'day')
      .date();

    const startDayOfMonth = (billingDate > daysInMonth) ? daysInMonth : billingDate;
    const startDate = moment.utc(
      dateThisMonthString(startDayOfMonth), format
    ).subtract(offset, 'month').valueOf();

    const endDate = (moment(startDate).add('1', 'month').valueOf());

    return {
      startDate,
      endDate
    };
  }

  calculateBalance(credits, debits) {
    const creditSum = credits.reduce((total, item) => {
      return total + item.paid_amount;
    }, 0);
    const debitSum = debits.reduce((total, item) => {
      return total + item.amount;
    }, 0);
    const balance = debitSum - creditSum;
    return balance;
  }

  getPaymentInfo() {
    const {loading} = this.props.paymentProcessor;

    if (loading || !this.props.paymentProcessor.paymentProcessor) {
      return {};
    }

    const {defaultPaymentMethod} = this.props.paymentProcessor.paymentProcessor;
    return defaultPaymentMethod || {};
  }

  getTransactions() {
    const {loading, credits, debits} = this.props.transactions;
    let transactions;

    if (loading || !credits || !debits) {
      return [];
    }

    const convertedCredits = credits.map((credit) => {
      const transaction = {...credit};
      transaction.amount = -credit.paid_amount;
      const titleizedType = credit.type
        .replace(/^\w/, (w) => (w.toUpperCase()));
      transaction.description = `${titleizedType} payment - Thank you!`;
      transaction.timestamp = moment.utc(credit.created).valueOf();
      transaction.created = `${moment.utc((credit.created))
        .format('MMM DD, YYYY - HH:mm')} UTC`;
      return transaction;
    });

    const convertedDebits = debits.map((debit) => {
      const transaction = {...debit};
      const titleizedType = debit.type
        .replace(/^\w/, (w) => (w.toUpperCase()));
      transaction.description = `${titleizedType} usage`;
      transaction.timestamp = Date.parse(debit.created);
      transaction.created = `${moment.utc((debit.created))
        .format('MMM DD, YYYY - HH:mm')} UTC`;
      return transaction;
    });

    transactions = [...convertedCredits, ...convertedDebits];

    return transactions.sort((t1, t2) => (t2.timestamp - t1.timestamp));
  }

  removeCard() {
    const {removeCard} = this.props.mutations;
    // TODO: use apollo watchquery correctly so we don't have to call `refetch`
    const {
      refetch, paymentProcessor: {
      id: paymentProcessorId,
      defaultPaymentMethod: {id: paymentMethodId}
    }
    } = this.props.paymentProcessor;

    removeCard(
      paymentProcessorId,
      paymentMethodId
    ).then(() => (refetch()));
  }

  render() {
    const addCreditHandler = () => {
    };
    const linkParams = '/dashboard/billing/usage';

    return (

Billing

                  Billing is in test mode and is not activated yet.
                  Don't try to submit the form.
                  We'll notify you when billing is activated.

                <BalancePanel amount={this.props.balance}
                              addCreditHandler={addCreditHandler}
                              cardData={this.getPaymentInfo()}/>

                <UsagePanel amount={this.props.usage} linkParams={linkParams}/>

                { !this.getPaymentInfo().id ? null :
                  <PaymentInfoPanel
                    removeCardHandler={this.removeCard.bind(this)}
                    paymentInfo={this.getPaymentInfo()}
                  />
                }

          { !!this.getPaymentInfo().id ? null : <AddCardForm
            // TODO: use apollo watchquery correctly so we don't have to call `refetch`
            updatePaymentInfo={this.props.paymentProcessor.refetch}/> }

          <TransactionsList transactions={this.getTransactions()}/>

    );
  }
}
<|endoftext|>


<commit_before>(function() {
    var lastTime = 0;
    var vendors = ['ms', 'moz', 'webkit', 'o'];
    for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
        window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
        window.cancelRequestAnimationFrame = window[vendors[x]+
                                                    'CancelRequestAnimationFrame'];
    }
    if (!window.requestAnimationFrame)
        window.requestAnimationFrame = function(callback, element) {
            var currTime = new Date().getTime();
            var timeToCall = Math.max(0, 16 - (currTime - lastTime));
            var id = window.setTimeout(function() {
                callback(currTime + timeToCall);
            }, timeToCall);
            lastTime = currTime + timeToCall;
            return id;
        };

    if (!window.cancelAnimationFrame)
        window.cancelAnimationFrame = function(id) {
            clearTimeout(id);
        };
}());
function updateStatus(message){
    var status = $("#status");
    status.text(message);
}
function serverResponse(){}
var noActiveBackstage = "none";
var WorkQueue = (function(){
    var work = [];
    var blitNeeded = false;
    var popState = function(){
        var f = work.pop();
        if(f){
            blitNeeded = blitNeeded || f();
            popState();
        }
        else{
            if(blitNeeded){
                blit();
                blitNeeded = false;
            }
        }
    }
    return {
        isAbleToWork:true,
        canWork:function(state){
            WorkQueue.isAbleToWork = state;
            if(state){
                console.log(sprintf("Enacting %s queued funcs",work.length));
                popState();
            }
        },
        enqueue:function(func){//A function returning a bool, blit needed or not.
            if(WorkQueue.isAbleToWork){
                if(func()){
                    blit();
                };
            }
            else{
                work.push(func);
            }
        }
    };
})();
var Pan = {
    shift:function(xDelta,yDelta){
        var xScale = viewboxWidth / boardWidth;
        var yScale = viewboxHeight / boardHeight;
        viewboxX -= xDelta * xScale;
        viewboxY -= yDelta * yScale;
        blit();
    }
}
var Zoom = (function(){
    var zoomFactor = 1.2;
    var maxZoomOut = 1.5;
    var maxZoomIn = 3.0;
    return {
        shift:function(scale,ignoreLimits){
            if(!ignoreLimits){
                if(viewboxWidth * scale > boardContent.width * maxZoomOut){
                    return;
                }
                else if(viewboxWidth / scale < boardWidth / maxZoomIn){
                    return;
                }
            }
            var ow = viewboxWidth;
            var oh = viewboxHeight;
            viewboxWidth *= scale;
            viewboxHeight *= scale;
            var xDelta = (ow - viewboxWidth) / 2;
            var yDelta = (oh - viewboxHeight) / 2;
            viewboxX += xDelta;
            viewboxY += yDelta;
            requestedViewboxWidth = viewboxWidth;
            requestedViewboxHeight = viewboxHeight;
            blit();
        },
        out:function(){
            Zoom.shift(zoomFactor);
        },
        "in":function(){
            Zoom.shift(1 / zoomFactor);
        }
    };
})();
var Extend = (function(){
    var factor = 0.6;
    var xExtension = function(){
        return Math.floor(viewboxWidth * factor);
    }
    var yExtension = function(){
        return Math.floor(viewboxHeight * factor);
    }
    var tween;
    var animateViewbox = function(xDelta,yDelta,onComplete){
        var interval = 300;//milis
        var startX = viewboxX;
        var startY = viewboxY;
        if(tween){
            tween.stop();
            tween = false;
        }
        tween = new TWEEN.Tween({x:0,y:0})
            .to({x:xDelta,y:yDelta}, interval)
            .easing(TWEEN.Easing.Quadratic.Out)
            .onUpdate(function(){
                viewboxX = startX + this.x;
                viewboxY = startY + this.y;
            }).onComplete(function(){
                tween = false;
                if(onComplete){
                    onComplete();
                }
                reportViewboxMoved();
            }).start();
        var update = function(t){
            if(tween){
                TWEEN.update();
                clearBoard();
                render(boardContent);//Don't go through the work queue.  We're not drawing, we're swiping.
                requestAnimationFrame(update);
            }
        }
        requestAnimationFrame(update);
    }
    return {
        up:function(){
            animateViewbox(0,-yExtension());
        },
        down:function(){
            animateViewbox(0,yExtension());
        },
        left:function(){
            animateViewbox(-xExtension(),0);
        },
        right:function(){
            animateViewbox(xExtension(),0);
        },
        shift:animateViewbox,
        center:function(x,y,onComplete){
            var targetX = x - viewboxWidth / 2;
            var targetY = y - viewboxHeight / 2;
            animateViewbox(targetX - viewboxX,targetY - viewboxY,onComplete);
        }
    }
})();
function showBackstage(id){
    console.log("showBackstage",id);
    if(id in Progress){
        Progress.call(id);
    }
    $(".backstage").hide();
    window.currentBackstage = id;
    var popup = $("#"+id+"Popup");
    popup.show();
    /*
     $(".backstageTabHeader").removeClass("activeBackstageTab");
     $(".backstage").removeClass("activeBackstageTab");
     $("#"+id).addClass("activeBackstageTab");
     $("#backstageContainer").show();
     $("#applicationMenuPopup").show();
     $("#backstageTabHeaders").show();
     $("#applicationMenuButton").addClass("activeBackstageTab");
     $("#hideBackstage").show();
     */
}
function hideBackstage(){
    window.currentBackstage = noActiveBackstage;
    Progress.call("hideBackstage");
    $(".backstage").hide();
    /*
     $(".backstageTabHeader").removeClass("activeBackstageTab");
     $(".backstage").removeClass("activeBackstageTab");
     $("#applicationMenuButton").removeClass("activeBackstageTab");
     $("#applicationMenuPopup").hide();
     $("#backstageTabHeaders").hide();
     $("#backstageContainer").hide();
     $("#hideBackstage").hide();
     */
}
$(function(){
    var heading = $("#heading");
    heading.text("Loading MeTLX...");
    var p = progress().max(8);
    p.element.prependTo($("#progress"));
    var setLoadProgress = function(value){
        p.value(value);
    };
    setLoadProgress(0);
    heading.text(sprintf("Logged in as %s",username));
    setupStatus();
    board = $("#board");
    boardContext = board[0].getContext("2d");
    heading.text("Set up board");
    setLoadProgress(1);
    $("input.toolbar").addClass("commandModeInactive").addClass(commandMode ? "commandModeActive" : "commandModeInactive");
    $("#slideContainer button").addClass("commandModeInactive").addClass(commandMode ? "commandModeActive" : "commandModeInactive");
    $("#up").click(Extend.up);
    $("#down").click(Extend.down);
    $("#left").click(Extend.left);
    $("#right").click(Extend.right);
    $("#in").click(Zoom.in);
    $("#out").click(Zoom.out);
    $("#drawMode").click(function(){
        if(Modes.currentMode != Modes.draw){
            Modes.draw.activate();
        }
    });
    $("#selectMode").click(function(){
        if(Modes.currentMode != Modes.select){
            Modes.select.activate();
        }
    });
    $("#insertMode").click(function(){
        if(Modes.currentMode != Modes.insert){
            Modes.insert.activate();
        }
    });
    $("#panMode").click(function(){
        if(Modes.currentMode != Modes.pan){
            Modes.pan.activate();
        }
    });
    $("#zoomMode").click(function(){
        if(Modes.currentMode != Modes.zoom){
            Modes.zoom.activate();
        }
    });
    $("#feedbackMode").click(function(){
        if(Modes.currentMode != Modes.feedback){
            Modes.feedback.activate();
        }
    });
    $("#tagMode").click(function(){
        if(Modes.currentMode != Modes.tag){
            Modes.tag.activate();
        }
    });
    $("#implicitlyExpanding").click(function(){
        implicitlyExpanding = $(this).is(":checked");
    });
    if(implicitlyExpanding){
        $("#implicitlyExpanding").attr("checked",implicitlyExpanding);
    }
    $("#showGrid").click(function(){
        showGrid = $(this).is(":checked");
        blit();
    });
    if(showGrid){
        $("#showGrid").attr("checked",showGrid);
    }
    setLoadProgress(2);
    $("#zoomToFull").click(zoomToFit);
    $("#zoomToPage").click(zoomToPage);
    window.currentBackstage = noActiveBackstage;
    $("#hideBackstage").click(function(){
        hideBackstage();
    });
    $("#applicationMenuButton").click(function(){
        console.log("applicationMenu click");
        if(window.currentBackstage == "applicationMenu"){
            hideBackstage();
        }
        else{
            showBackstage("applicationMenu");
        }
    });
    loadSlidesAtNativeZoom = getUserPref("loadSlidesAtNativeZoom") == "true";
    var zoom = $("#loadSlidesAtNativeZoom");
    if(getUserPref("loadSlidesAtNativeZoom") == "true"){
        zoom.attr("checked",true);
    }
    zoom.click(function(){
        loadSlidesAtNativeZoom = $(this).is(":checked");
        setUserPref("loadSlidesAtNativeZoom",loadSlidesAtNativeZoom);
        receiveHistory(boardContent);
    });
    var sizeChooser = function(pref,values){
        var container = $("<div />");
        $("<div />",{
            text:sprintf("Choose your preferred %s",pref)
        }).appendTo(container);
        var choice = function(size){
            return $("<div />")
                .text(sprintf("%s px",size))
                .addClass("preferenceChoice")
                .css({
                    width:px(size),
                    height:px(size)
                })
                .click(function(){
                    console.log("Setting user pref",pref,size);
                    setUserPref(pref,size);
                    fit();
                    render(boardContent);
                })
                .appendTo(container);
        };
        values.map(choice);
        return container;
    }
    $("#preferencesContainerRight")
        .append(sizeChooser("toolModeSize",[30,50,90]))
        .append(sizeChooser("subModeSize",[30,60,100]))
        .append(sizeChooser("thumbnailSize",[60,100,200]))
    $("#preferences")
        .click(function(){
            showBackstage("preferences");
            var inkToggle = $("#toggleHighQualityInk");
            $("#toggleHighQualityInk").attr("disabled","disabled");
        });
    var expansionAmount = 200;
    $("input[name=renderQuality]").change(function(){
        var v = $("input[name=renderQuality]:checked").val();
        pressureSimilarityThreshold = parseInt(v);
        blit();
    });
    setLoadProgress(3);
    $.each({
        red:"#FF0000",
        green:"#00FF00",
        blue:"#0000FF"
    },function(id,code){
        $("#"+id).click(function(){
            Modes.draw.drawingAttributes.color = code;
        });
    });
    $.each({
        thin:0.3,
        medium:1,
        fat:3,
        xfat:30
    },function(id,width){
        $("#"+id).attr("title",width).click(function(){
            Modes.draw.drawingAttributes.width = width;
        });
    });
    $("#toggleHighlighter").click(function(){
        Modes.draw.drawingAttributes.isHighlighter = !Modes.draw.drawingAttributes.isHighlighter;
    });
    setLoadProgress(4);
    if(window.event){
        currentSearchTerm = this.value;
        if (window.event.keyCode == 13){
            getSearchResult(currentSearchTerm);
        }
    }
    setLoadProgress(5);
    $("#openQuizzes").click(function(){
        $("#quizzingPopup").toggle();
    });
    setLoadProgress(7);
    var resetView = function(){
        window.scrollTo(0,0);
        requestedViewboxWidth = Math.max(requestedViewboxWidth,boardWidth);
        requestedViewboxHeight = Math.max(requestedViewboxHeight,boardHeight);
        fit();
        render(boardContent);
    };
    var w = $(window);
    if(window.orientation){
        w.on("orientationchange",resetView);
    }
    else{
        w.smartresize(resetView,200);
    }
    Progress.stanzaReceived["boardOnLoad"] = actOnReceivedStanza;
    Progress.viewboxMoved["boardOnLoad"] = function(){
        if(flagged){
            sendTransientStanza({
                command:"viewboxMoved",
                type:"command",
                author:username,
                timestamp:Date.now(),
                parameters:[viewboxX.toString(),viewboxY.toString(),viewboxWidth.toString(),viewboxHeight.toString()]})
        }
    };
    Modes.draw.activate();
    setLoadProgress(8);
    console.log("Setup complete");
});
<commit_msg>showing lobby now<commit_after>(function() {
    var lastTime = 0;
    var vendors = ['ms', 'moz', 'webkit', 'o'];
    for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
        window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
        window.cancelRequestAnimationFrame = window[vendors[x]+
                                                    'CancelRequestAnimationFrame'];
    }
    if (!window.requestAnimationFrame)
        window.requestAnimationFrame = function(callback, element) {
            var currTime = new Date().getTime();
            var timeToCall = Math.max(0, 16 - (currTime - lastTime));
            var id = window.setTimeout(function() {
                callback(currTime + timeToCall);
            }, timeToCall);
            lastTime = currTime + timeToCall;
            return id;
        };

    if (!window.cancelAnimationFrame)
        window.cancelAnimationFrame = function(id) {
            clearTimeout(id);
        };
    showLobby();
}());
function updateStatus(message){
    var status = $("#status");
    status.text(message);
}
function serverResponse(){}
var noActiveBackstage = "none";
var WorkQueue = (function(){
    var work = [];
    var blitNeeded = false;
    var popState = function(){
        var f = work.pop();
        if(f){
            blitNeeded = blitNeeded || f();
            popState();
        }
        else{
            if(blitNeeded){
                blit();
                blitNeeded = false;
            }
        }
    }
    return {
        isAbleToWork:true,
        canWork:function(state){
            WorkQueue.isAbleToWork = state;
            if(state){
                console.log(sprintf("Enacting %s queued funcs",work.length));
                popState();
            }
        },
        enqueue:function(func){//A function returning a bool, blit needed or not.
            if(WorkQueue.isAbleToWork){
                if(func()){
                    blit();
                };
            }
            else{
                work.push(func);
            }
        }
    };
})();
var Pan = {
    shift:function(xDelta,yDelta){
        var xScale = viewboxWidth / boardWidth;
        var yScale = viewboxHeight / boardHeight;
        viewboxX -= xDelta * xScale;
        viewboxY -= yDelta * yScale;
        blit();
    }
}
var Zoom = (function(){
    var zoomFactor = 1.2;
    var maxZoomOut = 1.5;
    var maxZoomIn = 3.0;
    return {
        shift:function(scale,ignoreLimits){
            if(!ignoreLimits){
                if(viewboxWidth * scale > boardContent.width * maxZoomOut){
                    return;
                }
                else if(viewboxWidth / scale < boardWidth / maxZoomIn){
                    return;
                }
            }
            var ow = viewboxWidth;
            var oh = viewboxHeight;
            viewboxWidth *= scale;
            viewboxHeight *= scale;
            var xDelta = (ow - viewboxWidth) / 2;
            var yDelta = (oh - viewboxHeight) / 2;
            viewboxX += xDelta;
            viewboxY += yDelta;
            requestedViewboxWidth = viewboxWidth;
            requestedViewboxHeight = viewboxHeight;
            blit();
        },
        out:function(){
            Zoom.shift(zoomFactor);
        },
        "in":function(){
            Zoom.shift(1 / zoomFactor);
        }
    };
})();
var Extend = (function(){
    var factor = 0.6;
    var xExtension = function(){
        return Math.floor(viewboxWidth * factor);
    }
    var yExtension = function(){
        return Math.floor(viewboxHeight * factor);
    }
    var tween;
    var animateViewbox = function(xDelta,yDelta,onComplete){
        var interval = 300;//milis
        var startX = viewboxX;
        var startY = viewboxY;
        if(tween){
            tween.stop();
            tween = false;
        }
        tween = new TWEEN.Tween({x:0,y:0})
            .to({x:xDelta,y:yDelta}, interval)
            .easing(TWEEN.Easing.Quadratic.Out)
            .onUpdate(function(){
                viewboxX = startX + this.x;
                viewboxY = startY + this.y;
            }).onComplete(function(){
                tween = false;
                if(onComplete){
                    onComplete();
                }
                reportViewboxMoved();
            }).start();
        var update = function(t){
            if(tween){
                TWEEN.update();
                clearBoard();
                render(boardContent);//Don't go through the work queue.  We're not drawing, we're swiping.
                requestAnimationFrame(update);
            }
        }
        requestAnimationFrame(update);
    }
    return {
        up:function(){
            animateViewbox(0,-yExtension());
        },
        down:function(){
            animateViewbox(0,yExtension());
        },
        left:function(){
            animateViewbox(-xExtension(),0);
        },
        right:function(){
            animateViewbox(xExtension(),0);
        },
        shift:animateViewbox,
        center:function(x,y,onComplete){
            var targetX = x - viewboxWidth / 2;
            var targetY = y - viewboxHeight / 2;
            animateViewbox(targetX - viewboxX,targetY - viewboxY,onComplete);
        }
    }
})();
function showBackstage(id){
    console.log("showBackstage",id);
    if(id in Progress){
        Progress.call(id);
    }
    $(".backstage").hide();
    window.currentBackstage = id;
    var popup = $("#"+id+"Popup");
    popup.show();
    /*
     $(".backstageTabHeader").removeClass("activeBackstageTab");
     $(".backstage").removeClass("activeBackstageTab");
     $("#"+id).addClass("activeBackstageTab");
     $("#backstageContainer").show();
     $("#applicationMenuPopup").show();
     $("#backstageTabHeaders").show();
     $("#applicationMenuButton").addClass("activeBackstageTab");
     $("#hideBackstage").show();
     */
}
function hideBackstage(){
    window.currentBackstage = noActiveBackstage;
    Progress.call("hideBackstage");
    $(".backstage").hide();
    /*
     $(".backstageTabHeader").removeClass("activeBackstageTab");
     $(".backstage").removeClass("activeBackstageTab");
     $("#applicationMenuButton").removeClass("activeBackstageTab");
     $("#applicationMenuPopup").hide();
     $("#backstageTabHeaders").hide();
     $("#backstageContainer").hide();
     $("#hideBackstage").hide();
     */
}
$(function(){
    var heading = $("#heading");
    heading.text("Loading MeTLX...");
    var p = progress().max(8);
    p.element.prependTo($("#progress"));
    var setLoadProgress = function(value){
        p.value(value);
    };
    setLoadProgress(0);
    heading.text(sprintf("Logged in as %s",username));
    setupStatus();
    board = $("#board");
    boardContext = board[0].getContext("2d");
    heading.text("Set up board");
    setLoadProgress(1);
    $("input.toolbar").addClass("commandModeInactive").addClass(commandMode ? "commandModeActive" : "commandModeInactive");
    $("#slideContainer button").addClass("commandModeInactive").addClass(commandMode ? "commandModeActive" : "commandModeInactive");
    $("#up").click(Extend.up);
    $("#down").click(Extend.down);
    $("#left").click(Extend.left);
    $("#right").click(Extend.right);
    $("#in").click(Zoom.in);
    $("#out").click(Zoom.out);
    $("#drawMode").click(function(){
        if(Modes.currentMode != Modes.draw){
            Modes.draw.activate();
        }
    });
    $("#selectMode").click(function(){
        if(Modes.currentMode != Modes.select){
            Modes.select.activate();
        }
    });
    $("#insertMode").click(function(){
        if(Modes.currentMode != Modes.insert){
            Modes.insert.activate();
        }
    });
    $("#panMode").click(function(){
        if(Modes.currentMode != Modes.pan){
            Modes.pan.activate();
        }
    });
    $("#zoomMode").click(function(){
        if(Modes.currentMode != Modes.zoom){
            Modes.zoom.activate();
        }
    });
    $("#feedbackMode").click(function(){
        if(Modes.currentMode != Modes.feedback){
            Modes.feedback.activate();
        }
    });
    $("#tagMode").click(function(){
        if(Modes.currentMode != Modes.tag){
            Modes.tag.activate();
        }
    });
    $("#implicitlyExpanding").click(function(){
        implicitlyExpanding = $(this).is(":checked");
    });
    if(implicitlyExpanding){
        $("#implicitlyExpanding").attr("checked",implicitlyExpanding);
    }
    $("#showGrid").click(function(){
        showGrid = $(this).is(":checked");
        blit();
    });
    if(showGrid){
        $("#showGrid").attr("checked",showGrid);
    }
    setLoadProgress(2);
    $("#zoomToFull").click(zoomToFit);
    $("#zoomToPage").click(zoomToPage);
    window.currentBackstage = noActiveBackstage;
    $("#hideBackstage").click(function(){
        hideBackstage();
    });
    $("#applicationMenuButton").click(function(){
        console.log("applicationMenu click");
        if(window.currentBackstage == "applicationMenu"){
            hideBackstage();
        }
        else{
            showBackstage("applicationMenu");
        }
    });
    loadSlidesAtNativeZoom = getUserPref("loadSlidesAtNativeZoom") == "true";
    var zoom = $("#loadSlidesAtNativeZoom");
    if(getUserPref("loadSlidesAtNativeZoom") == "true"){
        zoom.attr("checked",true);
    }
    zoom.click(function(){
        loadSlidesAtNativeZoom = $(this).is(":checked");
        setUserPref("loadSlidesAtNativeZoom",loadSlidesAtNativeZoom);
        receiveHistory(boardContent);
    });
    var sizeChooser = function(pref,values){
        var container = $("<div />");
        $("<div />",{
            text:sprintf("Choose your preferred %s",pref)
        }).appendTo(container);
        var choice = function(size){
            return $("<div />")
                .text(sprintf("%s px",size))
                .addClass("preferenceChoice")
                .css({
                    width:px(size),
                    height:px(size)
                })
                .click(function(){
                    console.log("Setting user pref",pref,size);
                    setUserPref(pref,size);
                    fit();
                    render(boardContent);
                })
                .appendTo(container);
        };
        values.map(choice);
        return container;
    }
    $("#preferencesContainerRight")
        .append(sizeChooser("toolModeSize",[30,50,90]))
        .append(sizeChooser("subModeSize",[30,60,100]))
        .append(sizeChooser("thumbnailSize",[60,100,200]))
    $("#preferences")
        .click(function(){
            showBackstage("preferences");
            var inkToggle = $("#toggleHighQualityInk");
            $("#toggleHighQualityInk").attr("disabled","disabled");
        });
    var expansionAmount = 200;
    $("input[name=renderQuality]").change(function(){
        var v = $("input[name=renderQuality]:checked").val();
        pressureSimilarityThreshold = parseInt(v);
        blit();
    });
    setLoadProgress(3);
    $.each({
        red:"#FF0000",
        green:"#00FF00",
        blue:"#0000FF"
    },function(id,code){
        $("#"+id).click(function(){
            Modes.draw.drawingAttributes.color = code;
        });
    });
    $.each({
        thin:0.3,
        medium:1,
        fat:3,
        xfat:30
    },function(id,width){
        $("#"+id).attr("title",width).click(function(){
            Modes.draw.drawingAttributes.width = width;
        });
    });
    $("#toggleHighlighter").click(function(){
        Modes.draw.drawingAttributes.isHighlighter = !Modes.draw.drawingAttributes.isHighlighter;
    });
    setLoadProgress(4);
    if(window.event){
        currentSearchTerm = this.value;
        if (window.event.keyCode == 13){
            getSearchResult(currentSearchTerm);
        }
    }
    setLoadProgress(5);
    $("#openQuizzes").click(function(){
        $("#quizzingPopup").toggle();
    });
    setLoadProgress(7);
    var resetView = function(){
        window.scrollTo(0,0);
        requestedViewboxWidth = Math.max(requestedViewboxWidth,boardWidth);
        requestedViewboxHeight = Math.max(requestedViewboxHeight,boardHeight);
        fit();
        render(boardContent);
    };
    var w = $(window);
    if(window.orientation){
        w.on("orientationchange",resetView);
    }
    else{
        w.smartresize(resetView,200);
    }
    Progress.stanzaReceived["boardOnLoad"] = actOnReceivedStanza;
    Progress.viewboxMoved["boardOnLoad"] = function(){
        if(flagged){
            sendTransientStanza({
                command:"viewboxMoved",
                type:"command",
                author:username,
                timestamp:Date.now(),
                parameters:[viewboxX.toString(),viewboxY.toString(),viewboxWidth.toString(),viewboxHeight.toString()]})
        }
    };
    Modes.draw.activate();
    setLoadProgress(8);
    console.log("Setup complete");
});
<|endoftext|>


<commit_before>/**
 * SPDX-FileCopyrightText: © 2017 Liferay, Inc. <https://liferay.com>
 * SPDX-License-Identifier: MIT
 */

const DESCRIPTION = 'destructured names in imports must be sorted';

module.exports = {
	create(context) {
		return {
			ImportDeclaration(node) {
				const specifiers = node.specifiers.filter(specifier => {
					// Just `ImportSpecifier` (ignore `ImportDefaultSpecifier`).
					return specifier.type === 'ImportSpecifier';
				});

				if (specifiers.length > 1) {
					const source = context.getSourceCode();

					if (
						source.commentsExistBetween(
							source.getTokenBefore(specifiers[0]),
							node.source
						)
					) {
						// Don't touch if any of the specifiers have
						// comments.
						return;
					}

					// Given:
					//
					//      import {a as b, c} from 'd';
					//
					// We'll have two specifiers:
					//
					// - `imported.name === 'a'`, `local.name === 'b').
					// - `imported.name === 'c'`.
					//
					// We sort by `imported` always, ignoring `local`.
					const sorted = specifiers.slice().sort((a, b) => {
						return a.imported.name > b.imported.name ? 1 : -1;
					});

					const fix = sorted.some(
						(sorted, i) => sorted !== specifiers[i]
					);

					if (fix) {
						const text =
							' '.repeat(node.start) + source.getText(node);

						const start = specifiers[0].start;
						const end = specifiers[specifiers.length - 1].end;

						let fixed = '';

						for (let i = 0; i < specifiers.length; i++) {
							fixed += source.getText(sorted[i]);

							if (i < specifiers.length - 1) {
								// Grab all text between specifier and next.
								const between = text.slice(
									specifiers[i].end,
									specifiers[i + 1].start
								);

								fixed += between;
							}
						}

						context.report({
							fix: fixer =>
								fixer.replaceTextRange([start, end], fixed),
							message: DESCRIPTION,
							node,
						});
					}
				}
			},
		};
	},

	meta: {
		docs: {
			category: 'Best Practices',
			description: DESCRIPTION,
			recommended: false,
			url: 'https://github.com/liferay/eslint-config-liferay/issues/124',
		},
		fixable: 'code',
		schema: [],
		type: 'problem',
	},
};
<commit_msg>fix: don't break when using @typescript-eslint/parser<commit_after>/**
 * SPDX-FileCopyrightText: © 2017 Liferay, Inc. <https://liferay.com>
 * SPDX-License-Identifier: MIT
 */

const DESCRIPTION = 'destructured names in imports must be sorted';

module.exports = {
	create(context) {
		return {
			ImportDeclaration(node) {
				const specifiers = node.specifiers.filter(specifier => {
					// Just `ImportSpecifier` (ignore `ImportDefaultSpecifier`).
					return specifier.type === 'ImportSpecifier';
				});

				if (specifiers.length > 1) {
					const source = context.getSourceCode();

					if (
						source.commentsExistBetween(
							source.getTokenBefore(specifiers[0]),
							node.source
						)
					) {
						// Don't touch if any of the specifiers have
						// comments.
						return;
					}

					// Given:
					//
					//      import {a as b, c} from 'd';
					//
					// We'll have two specifiers:
					//
					// - `imported.name === 'a'`, `local.name === 'b').
					// - `imported.name === 'c'`.
					//
					// We sort by `imported` always, ignoring `local`.
					const sorted = specifiers.slice().sort((a, b) => {
						return a.imported.name > b.imported.name ? 1 : -1;
					});

					const fix = sorted.some(
						(sorted, i) => sorted !== specifiers[i]
					);

					if (fix) {
						const text =
							' '.repeat(node.range[0]) + source.getText(node);

						const start = specifiers[0].range[0];
						const end = specifiers[specifiers.length - 1].range[1];

						let fixed = '';

						for (let i = 0; i < specifiers.length; i++) {
							fixed += source.getText(sorted[i]);

							if (i < specifiers.length - 1) {
								// Grab all text between specifier and next.
								const between = text.slice(
									specifiers[i].range[1],
									specifiers[i + 1].range[0]
								);

								fixed += between;
							}
						}

						context.report({
							fix: fixer =>
								fixer.replaceTextRange([start, end], fixed),
							message: DESCRIPTION,
							node,
						});
					}
				}
			},
		};
	},

	meta: {
		docs: {
			category: 'Best Practices',
			description: DESCRIPTION,
			recommended: false,
			url: 'https://github.com/liferay/eslint-config-liferay/issues/124',
		},
		fixable: 'code',
		schema: [],
		type: 'problem',
	},
};
<|endoftext|>


<commit_before>#!/usr/bin/env node

var tab = require('tabalot');
var rm = require('../lib/remotes');
var os = require('os');

var remotes = function(word, opts, cb) {
	if (word.indexOf('@') > -1) return cb(null, '@host');
	cb(null, rm.list());
};

var resolve = function(remote, opts) {
	if (!remote) return require('../lib/ui').error('Remote is required');
	return require('xtend')(rm.read(remote) || {url:remote}, opts);
};

var help = function() {
	process.stderr.write(require('fs').readFileSync(require('path').join(__dirname, 'help')));
	process.exit(1);
};

var ids = function(word, opts, cb) {
	var client = require('../');
	var name = opts._[1];

	var c = client(resolve(opts._[1], opts));
	var cached = rm.cache(name, 'ids');

	if (cached) return cb(null, cached);

	c.list(function(err, list) {
		if (err) return cb(err);

		list = list.map(function(service) {
			return service.id;
		});

		cb(null, rm.cache(name, 'ids', list));
	});
};

tab('*')
	('--force', '-f')
	('--key', '-i', '-k', '@file')
	('--passphrase');

tab('remotes')
	('--yes', '-y')
	('--fingerprint')
	('--no-fingerprint')
	(['add', 'remove', 'list'])
	(remotes)
	('@host')
	(function(cmd, remote, host, opts) {
		require('../commands/remotes')(cmd, remote, host, opts);
	});

tab('add')
	('--start', '-s')
	('--build', '-b')
	('--docks', '-d')
	('--env', '-e')
	(remotes)
	(ids)
	(function(remote, id, opts) {
		rm.cache(remote, 'ids', null);
		require('../commands/add')(resolve(remote, opts), id, opts);
	});

tab('remove')
	(remotes)
	(ids)
	(function(remote, id, opts) {
		rm.cache(remote, 'ids', null);
		require('../commands/remove')(resolve(remote, opts), id, opts);
	});

tab('update')
	('--start', '-s')
	('--build', '-b')
	('--docks', '-d')
	('--env', '-e')
	('--restart')
	('--no-start')
	('--no-build')
	('--no-docks')
	('--no-env')
	(remotes)
	(ids)
	(function(remote, id, opts) {
		require('../commands/update')(resolve(remote, opts), id, opts);
	});

tab('list')
	(remotes)
	(ids)
	(function(remote, id, opts) {
		require('../commands/list')(resolve(remote, opts), id, opts);
	});

tab('ps')
	('--env', '-e')
	(remotes)
	(ids)
	(function(remote, id, opts) {
		require('../commands/ps')(resolve(remote, opts), id, opts);
	});

tab('start')
	(remotes)
	(ids)
	(function(remote, id, opts) {
		require('../commands/start')(resolve(remote, opts), id, opts);
	});

tab('stop')
	(remotes)
	(ids)
	(function(remote, id, opts) {
		require('../commands/stop')(resolve(remote, opts), id, opts);
	});

tab('restart')
	(remotes)
	(ids)
	(function(remote, id, opts) {
		require('../commands/restart')(resolve(remote, opts), id, opts);
	});

tab('log')
	('--no-events')
	('--no-id')
	('--no-origin')
	(remotes)
	(ids)
	(function(remote, id, opts) {
		require('../commands/log')(resolve(remote, opts), id, opts);
	});

tab('sync')
	('--restart')
	(remotes)
	(ids)
	(function(remote, id, opts) {
		require('../commands/sync')(resolve(remote, opts), id, opts);
	});

tab('deploy')
	('--revision', '-r')
	(remotes)
	(ids)
	(function(remote, id, opts) {
		require('../commands/deploy')(resolve(remote, opts), id, opts);
	});

tab('tarball')
	('--out', '-o', '@file')
	(remotes)
	(ids)
	(function(remote, id, opts) {
		require('../commands/tarball')(resolve(remote, opts), id, opts);
	});

tab('dock')
	(remotes)
	('--id', '-i', os.hostname())
	('--port', '-p', 10002)
	('--db', '@file')
	(function(remote, opts) {
		require('../commands/dock')(resolve(remote, opts), opts);
	});

tab('terminal')
	('--port', '-p', 10002)
	('--dock', '-d')
	('--db', '@file')
	(function(opts) {
		require('../commands/terminal')(opts);
	});

tab()
	('--version', '-v')
	(function(opts) {
		if (opts.version) return console.log('v'+require('../package.json').version);
		help();
	});

tab.parse() || help();<commit_msg>no-log completion<commit_after>#!/usr/bin/env node

var tab = require('tabalot');
var rm = require('../lib/remotes');
var os = require('os');

var remotes = function(word, opts, cb) {
	if (word.indexOf('@') > -1) return cb(null, '@host');
	cb(null, rm.list());
};

var resolve = function(remote, opts) {
	if (!remote) return require('../lib/ui').error('Remote is required');
	return require('xtend')(rm.read(remote) || {url:remote}, opts);
};

var help = function() {
	process.stderr.write(require('fs').readFileSync(require('path').join(__dirname, 'help')));
	process.exit(1);
};

var ids = function(word, opts, cb) {
	var client = require('../');
	var name = opts._[1];

	var c = client(resolve(opts._[1], opts));
	var cached = rm.cache(name, 'ids');

	if (cached) return cb(null, cached);

	c.list(function(err, list) {
		if (err) return cb(err);

		list = list.map(function(service) {
			return service.id;
		});

		cb(null, rm.cache(name, 'ids', list));
	});
};

tab('*')
	('--force', '-f')
	('--key', '-i', '-k', '@file')
	('--passphrase');

tab('remotes')
	('--yes', '-y')
	('--fingerprint')
	('--no-fingerprint')
	(['add', 'remove', 'list'])
	(remotes)
	('@host')
	(function(cmd, remote, host, opts) {
		require('../commands/remotes')(cmd, remote, host, opts);
	});

tab('add')
	('--start', '-s')
	('--build', '-b')
	('--docks', '-d')
	('--env', '-e')
	(remotes)
	(ids)
	(function(remote, id, opts) {
		rm.cache(remote, 'ids', null);
		require('../commands/add')(resolve(remote, opts), id, opts);
	});

tab('remove')
	(remotes)
	(ids)
	(function(remote, id, opts) {
		rm.cache(remote, 'ids', null);
		require('../commands/remove')(resolve(remote, opts), id, opts);
	});

tab('update')
	('--start', '-s')
	('--build', '-b')
	('--docks', '-d')
	('--env', '-e')
	('--restart')
	('--no-start')
	('--no-build')
	('--no-docks')
	('--no-env')
	(remotes)
	(ids)
	(function(remote, id, opts) {
		require('../commands/update')(resolve(remote, opts), id, opts);
	});

tab('list')
	(remotes)
	(ids)
	(function(remote, id, opts) {
		require('../commands/list')(resolve(remote, opts), id, opts);
	});

tab('ps')
	('--env', '-e')
	(remotes)
	(ids)
	(function(remote, id, opts) {
		require('../commands/ps')(resolve(remote, opts), id, opts);
	});

tab('start')
	(remotes)
	(ids)
	(function(remote, id, opts) {
		require('../commands/start')(resolve(remote, opts), id, opts);
	});

tab('stop')
	(remotes)
	(ids)
	(function(remote, id, opts) {
		require('../commands/stop')(resolve(remote, opts), id, opts);
	});

tab('restart')
	(remotes)
	(ids)
	(function(remote, id, opts) {
		require('../commands/restart')(resolve(remote, opts), id, opts);
	});

tab('log')
	('--no-events')
	('--no-id')
	('--no-origin')
	(remotes)
	(ids)
	(function(remote, id, opts) {
		require('../commands/log')(resolve(remote, opts), id, opts);
	});

tab('sync')
	('--restart')
	(remotes)
	(ids)
	(function(remote, id, opts) {
		require('../commands/sync')(resolve(remote, opts), id, opts);
	});

tab('deploy')
	('--revision', '-r')
	('--no-log')
	(remotes)
	(ids)
	(function(remote, id, opts) {
		require('../commands/deploy')(resolve(remote, opts), id, opts);
	});

tab('tarball')
	('--out', '-o', '@file')
	(remotes)
	(ids)
	(function(remote, id, opts) {
		require('../commands/tarball')(resolve(remote, opts), id, opts);
	});

tab('dock')
	(remotes)
	('--id', '-i', os.hostname())
	('--port', '-p', 10002)
	('--db', '@file')
	(function(remote, opts) {
		require('../commands/dock')(resolve(remote, opts), opts);
	});

tab('terminal')
	('--port', '-p', 10002)
	('--dock', '-d')
	('--db', '@file')
	(function(opts) {
		require('../commands/terminal')(opts);
	});

tab()
	('--version', '-v')
	(function(opts) {
		if (opts.version) return console.log('v'+require('../package.json').version);
		help();
	});

tab.parse() || help();<|endoftext|>


<commit_before>$(document).ready(function(e) {

    function readTextFile(file) {
        var newSplitted = [];
        var rawFile = new XMLHttpRequest();
        rawFile.open("GET", file, false);
        rawFile.onreadystatechange = function () {
            if (rawFile.readyState === 4) {
                if (rawFile.status === 200 || rawFile.status == 0) {
                    var allText = rawFile.responseText;
                    var textArraySplited = allText.split("\n");
                    for (var i = 0; i < textArraySplited.length; i++) {
                        newSplitted[i] = textArraySplited[i].split("\t");
                    }
                }
            }
        }
        rawFile.send(null);

        return newSplitted;
    }

    function numberToRGB(i) {
    	// red = 0° and green = 120°
    	// we convert the input to the appropriate hue value
    	//var hue = (120 * i)/maxValue;

    	var normalizer = (maxValue/2)/255;
    	var red;
    	var green;
    	var blue;

    	if (i <= maxValue/2){
    		red = (maxValue/2 - i) /normalizer;
    		green = 0;
    		blue = 0;
    	}
    	else{
    		red = 0;
    		green = 0;
    		blue = (i - maxValue/2) /normalizer;
    	}
    	// we format to css value and return
    	return 'rgb(' + red + ',' + green + ',' + blue + ')';
	}

    function drawHeatmap(fileData, zoomRectId, canvasName,start,end) {

		start = Math.round(start);
		end = Math.round(end);

    	var canvas = document.getElementById(canvasName);
    	var context = canvas.getContext('2d');
    	context.clearRect(0, 0, canvas.width, canvas.height)
    	//context.canvas.width  = window.innerWidth;
    	//context.canvas.height = window.innerHeight;

    	var heightPixelSize = canvas.height/(end-start);
    	var widthPixelSize = heightPixelSize;

    	if (heightPixelSize < 1){
    		widthPixelSize = heightPixelSize + 1;
    	}

    	if (zoomRectId !== ''){
			var $zoomRect = $('#' + zoomRectId);
			var borderSize = $zoomRect.css("border-left-width").replace(/[^-\d\.]/g, '');
			$zoomRect.css("width",  (fileData[1].length * widthPixelSize - 2 * borderSize) + "px");
		}

    	canvas.width = fileData[1].length * widthPixelSize;

    	for (var i = start; i < end; i++) {
    		for (var j = 1; j < fileData[i].length; j++) {
    			//context.beginPath();
               /*
                if (fileData[i][j] < 100) {
                    context.fillStyle = "#00FF00";
                }
                else {
                    context.fillStyle = "#FF0000";
                }
                */
                context.fillStyle = numberToRGB(fileData[i][j]);
                context.fillRect((j - 1)* widthPixelSize, (i - start) *heightPixelSize, widthPixelSize, heightPixelSize);
                //context.fill();
            }
        }
    }

    function drawText(fileData, canvasName, start, end) {
		start = Math.round(start);
		end = Math.round(end);

   		var canvas = document.getElementById(canvasName);
    	var context = canvas.getContext('2d');
    	context.clearRect(0, 0, canvas.width, canvas.height)
    	//context.canvas.width  = window.innerWidth;
    	//context.canvas.height = window.innerHeight;

    	var heightPixelSize = canvas.height/(end-start);

    	for (var i = start; i < end; i++) {
    		context.fillStyle = "black";
  			//context.font = "bold 10px Arial";
  			context.fillText(fileData[i][0], 0, (i-start) * heightPixelSize);
        }
    }

    var fileData = readTextFile("RNA_seq.txt");

    var maxValue = fileData[1][1];
    var minValue = fileData[1][1];
    for (var i = 1; i < fileData.length; i++) {
            for (var j = 1; j < fileData[i].length; j++) {
                if (fileData[i][j] > maxValue){
                	maxValue = fileData[i][j];
                }
                if (fileData[i][j] < minValue){
                	minValue = fileData[i][j];
                }
            }
        }

        console.log("maxValue " + maxValue);
        console.log("minValue " + minValue);

    //var zoomRegionAspectRatio = $('.original.container').height()/$('.original.container .zoomRegion').height();

	var originalCanvas = document.getElementById('wholeHeatmap');
	var originalCanvasRowSizeInPixels = originalCanvas.height/(fileData.length - 1);

	var firstZoomTopMargin = $('.original.container .zoomRegion').css('margin-top').replace(/[^-\d\.]/g, '');
	var firstZoomStartRow = 1
    var firstZoomLastRow = firstZoomStartRow + $('.original.container .zoomRegion').height()/originalCanvasRowSizeInPixels;

    var firstZoomedCanvas = document.getElementById('firstZoomedHeatmap');
	var firstCanvasRowSizeInPixels = firstZoomedCanvas.height/(firstZoomLastRow - firstZoomStartRow);

	var secondZoomTopMargin = $('.firstZoom.container .zoomRegion').css('margin-top').replace(/[^-\d\.]/g, '');
	var secondZoomStartRow = 1
    var secondZoomLastRow = secondZoomStartRow + $('.firstZoom.container .zoomRegion').height()/firstCanvasRowSizeInPixels;

    drawHeatmap(fileData, 'firstZoomRect', 'wholeHeatmap', 1, fileData.length);
    drawHeatmap(fileData, 'secondZoomRect','firstZoomedHeatmap', firstZoomStartRow, firstZoomLastRow);
    drawHeatmap(fileData, '','secondZoomedHeatmap', secondZoomStartRow, secondZoomLastRow);
    drawText(fileData, 'textCanvas', secondZoomStartRow, secondZoomLastRow);

    $(document).on('mousemove', '.container', function(e) {
        var $container = $(this);
        var $zoomRegion = $container.find('.zoomRegion');
        var relY = e.pageY - $container.offset().top;
        var marginTop = relY-$zoomRegion.height()/2;

        if (marginTop > 0 && marginTop+$zoomRegion.outerHeight()<$container.height()) {
            $zoomRegion.css('margin-top', marginTop+'px');
            firstZoomTopMargin = $('.original.container .zoomRegion').css('margin-top').replace(/[^-\d\.]/g, '');
			if (firstZoomTopMargin/originalCanvasRowSizeInPixels < 1)
			{
				firstZoomStartRow = 1;
			}
			else
			{
				firstZoomStartRow = firstZoomTopMargin/originalCanvasRowSizeInPixels;
			}
    		firstZoomLastRow = firstZoomStartRow + $('.original.container .zoomRegion').height()/originalCanvasRowSizeInPixels;

    		firstZoomedCanvas = document.getElementById('firstZoomedHeatmap');
    		firstCanvasRowSizeInPixels = firstZoomedCanvas.height/(firstZoomLastRow - firstZoomStartRow);

    		secondZoomTopMargin = $('.firstZoom.container .zoomRegion').css('margin-top').replace(/[^-\d\.]/g, '');
    		if (firstZoomStartRow + secondZoomTopMargin/firstCanvasRowSizeInPixels < 1)
			{
				secondZoomStartRow = 1;
			}
			else
			{
				secondZoomStartRow = firstZoomStartRow + secondZoomTopMargin/firstCanvasRowSizeInPixels;
			}
    		secondZoomLastRow = secondZoomStartRow + $('.firstZoom.container .zoomRegion').height()/firstCanvasRowSizeInPixels;

    		drawHeatmap(fileData, 'secondZoomRect','firstZoomedHeatmap', firstZoomStartRow, firstZoomLastRow);
    		drawHeatmap(fileData, '','secondZoomedHeatmap', secondZoomStartRow, secondZoomLastRow);
    		drawText(fileData, 'textCanvas', secondZoomStartRow, secondZoomLastRow);

            /*
            var zoomMarginTop = (-1)*marginTop*zoomRegionAspectRatio;
            var zoomContainerSelector = $container.data('zoom-container');
            $(zoomContainerSelector).find('canvas').css('margin-top', zoomMarginTop+'px');
            */
        }
 	}.throttle(150));

 	var data = fileData[1];//[280, 45, 133, 166, 84, 259, 266, 960, 219, 311, 67, 89];

        var lineGraph = new RGraph.Line({
            id: 'cvs',
            data: data,
            options: {
                labels: fileData[0],
                title: "Genes",
                text: {
                	angle:90
                },
                gutter: {
                    left: 35
                }
            }
        }).draw()

});<commit_msg>improved throttle time and added margins to graph<commit_after>$(document).ready(function(e) {

    function readTextFile(file) {
        var newSplitted = [];
        var rawFile = new XMLHttpRequest();
        rawFile.open("GET", file, false);
        rawFile.onreadystatechange = function () {
            if (rawFile.readyState === 4) {
                if (rawFile.status === 200 || rawFile.status == 0) {
                    var allText = rawFile.responseText;
                    var textArraySplited = allText.split("\n");
                    for (var i = 0; i < textArraySplited.length; i++) {
                        newSplitted[i] = textArraySplited[i].split("\t");
                    }
                }
            }
        }
        rawFile.send(null);

        return newSplitted;
    }

    function numberToRGB(i) {
    	// red = 0° and green = 120°
    	// we convert the input to the appropriate hue value
    	//var hue = (120 * i)/maxValue;

    	var normalizer = (maxValue/2)/255;
    	var red;
    	var green;
    	var blue;

    	if (i <= maxValue/2){
    		red = (maxValue/2 - i) /normalizer;
    		green = 0;
    		blue = 0;
    	}
    	else{
    		red = 0;
    		green = 0;
    		blue = (i - maxValue/2) /normalizer;
    	}
    	// we format to css value and return
    	return 'rgb(' + red + ',' + green + ',' + blue + ')';
	}

    function drawHeatmap(fileData, zoomRectId, canvasName,start,end) {

		start = Math.round(start);
		end = Math.round(end);

    	var canvas = document.getElementById(canvasName);
    	var context = canvas.getContext('2d');
    	context.clearRect(0, 0, canvas.width, canvas.height)
    	//context.canvas.width  = window.innerWidth;
    	//context.canvas.height = window.innerHeight;

    	var heightPixelSize = canvas.height/(end-start);
    	var widthPixelSize = heightPixelSize;

    	if (heightPixelSize < 1){
    		widthPixelSize = heightPixelSize + 1;
    	}

    	if (zoomRectId !== ''){
			var $zoomRect = $('#' + zoomRectId);
			var borderSize = $zoomRect.css("border-left-width").replace(/[^-\d\.]/g, '');
			$zoomRect.css("width",  (fileData[1].length * widthPixelSize - 2 * borderSize) + "px");
		}

    	canvas.width = fileData[1].length * widthPixelSize;

    	for (var i = start; i < end; i++) {
    		for (var j = 1; j < fileData[i].length; j++) {
                context.fillStyle = numberToRGB(fileData[i][j]);
                context.fillRect((j - 1)* widthPixelSize, (i - start) *heightPixelSize, widthPixelSize, heightPixelSize);
            }
        }
    }

    function drawText(fileData, canvasName, start, end) {
		start = Math.round(start);
		end = Math.round(end);

   		var canvas = document.getElementById(canvasName);
    	var context = canvas.getContext('2d');
    	context.clearRect(0, 0, canvas.width, canvas.height)
    	//context.canvas.width  = window.innerWidth;
    	//context.canvas.height = window.innerHeight;

    	var heightPixelSize = canvas.height/(end-start);

    	for (var i = start; i < end; i++) {
    		context.fillStyle = "black";
  			//context.font = "bold 10px Arial";
  			context.fillText(fileData[i][0], 0, (i-start) * heightPixelSize);
        }
    }

    var fileData = readTextFile("RNA_seq.txt");

    var maxValue = fileData[1][1];
    var minValue = fileData[1][1];
    for (var i = 1; i < fileData.length; i++) {
            for (var j = 1; j < fileData[i].length; j++) {
                if (fileData[i][j] > maxValue){
                	maxValue = fileData[i][j];
                }
                if (fileData[i][j] < minValue){
                	minValue = fileData[i][j];
                }
            }
        }

    //var zoomRegionAspectRatio = $('.original.container').height()/$('.original.container .zoomRegion').height();

	var originalCanvas = document.getElementById('wholeHeatmap');
	var originalCanvasRowSizeInPixels = originalCanvas.height/(fileData.length - 1);

	var firstZoomTopMargin = $('.original.container .zoomRegion').css('margin-top').replace(/[^-\d\.]/g, '');
	var firstZoomStartRow = 1
    var firstZoomLastRow = firstZoomStartRow + $('.original.container .zoomRegion').height()/originalCanvasRowSizeInPixels;

    var firstZoomedCanvas = document.getElementById('firstZoomedHeatmap');
	var firstCanvasRowSizeInPixels = firstZoomedCanvas.height/(firstZoomLastRow - firstZoomStartRow);

	var secondZoomTopMargin = $('.firstZoom.container .zoomRegion').css('margin-top').replace(/[^-\d\.]/g, '');
	var secondZoomStartRow = 1
    var secondZoomLastRow = secondZoomStartRow + $('.firstZoom.container .zoomRegion').height()/firstCanvasRowSizeInPixels;

    drawHeatmap(fileData, 'firstZoomRect', 'wholeHeatmap', 1, fileData.length);
    drawHeatmap(fileData, 'secondZoomRect','firstZoomedHeatmap', firstZoomStartRow, firstZoomLastRow);
    drawHeatmap(fileData, '','secondZoomedHeatmap', secondZoomStartRow, secondZoomLastRow);
    drawText(fileData, 'textCanvas', secondZoomStartRow, secondZoomLastRow);

    $(document).on('mousemove', '.container', function(e) {
        var $container = $(this);
        var $zoomRegion = $container.find('.zoomRegion');
        var relY = e.pageY - $container.offset().top;
        var marginTop = relY-$zoomRegion.height()/2;

        if (marginTop > 0 && marginTop+$zoomRegion.outerHeight()<$container.height()) {
            $zoomRegion.css('margin-top', marginTop+'px');
            firstZoomTopMargin = $('.original.container .zoomRegion').css('margin-top').replace(/[^-\d\.]/g, '');
			if (firstZoomTopMargin/originalCanvasRowSizeInPixels < 1)
			{
				firstZoomStartRow = 1;
			}
			else
			{
				firstZoomStartRow = firstZoomTopMargin/originalCanvasRowSizeInPixels;
			}
    		firstZoomLastRow = firstZoomStartRow + $('.original.container .zoomRegion').height()/originalCanvasRowSizeInPixels;

    		firstZoomedCanvas = document.getElementById('firstZoomedHeatmap');
    		firstCanvasRowSizeInPixels = firstZoomedCanvas.height/(firstZoomLastRow - firstZoomStartRow);

    		secondZoomTopMargin = $('.firstZoom.container .zoomRegion').css('margin-top').replace(/[^-\d\.]/g, '');
    		if (firstZoomStartRow + secondZoomTopMargin/firstCanvasRowSizeInPixels < 1)
			{
				secondZoomStartRow = 1;
			}
			else
			{
				secondZoomStartRow = firstZoomStartRow + secondZoomTopMargin/firstCanvasRowSizeInPixels;
			}
    		secondZoomLastRow = secondZoomStartRow + $('.firstZoom.container .zoomRegion').height()/firstCanvasRowSizeInPixels;

    		drawHeatmap(fileData, 'secondZoomRect','firstZoomedHeatmap', firstZoomStartRow, firstZoomLastRow);
    		drawHeatmap(fileData, '','secondZoomedHeatmap', secondZoomStartRow, secondZoomLastRow);
    		drawText(fileData, 'textCanvas', secondZoomStartRow, secondZoomLastRow);

            /*
            var zoomMarginTop = (-1)*marginTop*zoomRegionAspectRatio;
            var zoomContainerSelector = $container.data('zoom-container');
            $(zoomContainerSelector).find('canvas').css('margin-top', zoomMarginTop+'px');
            */
        }
 	}.throttle(200));

 	var data = fileData[1];//[280, 45, 133, 166, 84, 259, 266, 960, 219, 311, 67, 89];

        var lineGraph = new RGraph.Line({
            id: 'cvs',
            data: data,
            options: {
                labels: fileData[0],
                title: "Genes",
                text: {
                	angle:45,
                },
                gutter: {
                    left: 40,
                    bottom: 70,
                }
            }
        }).draw()

});<|endoftext|>


<commit_before>// @flow
import memoize from "lru-memoize"

const fieldTypes = {
  context: "string",
  renderer: "function",
  feedsOptions: "object",
  feeds: "object",
  description: "object",
}

const validator = function(
  userConfig: Object = {}
): void {
  const errors = []

  Object.keys(userConfig).forEach((key) => {
    if (!fieldTypes[key]) {
      errors.push(
        `Unknow option '${ key }'.`
      )
    }
    else if (fieldTypes[key] !== typeof userConfig[key]) {
      errors.push(
        `Wrong type for '${ key }': expected '${ fieldTypes[key] }', ` +
        `got '${ typeof userConfig[key] }'.`
      )
    }
  })

  if (errors.length > 0) {
    throw new Error(
      `Your 'content-loader' config is invalid. Please fix the errors: \n- ` +
      errors.join("\n- ") +
      "\n\n" +
      "See 'Configuration' section in documentation."
    )
  }
}

export default memoize(10)(validator)
<commit_msg>Add defaultHead to validated content-loader options<commit_after>// @flow
import memoize from "lru-memoize"

const fieldTypes = {
  context: "string",
  renderer: "function",
  feedsOptions: "object",
  feeds: "object",
  description: "object",
  defaultHead: "object",
}

const validator = function(
  userConfig: Object = {}
): void {
  const errors = []

  Object.keys(userConfig).forEach((key) => {
    if (!fieldTypes[key]) {
      errors.push(
        `Unknow option '${ key }'.`
      )
    }
    else if (fieldTypes[key] !== typeof userConfig[key]) {
      errors.push(
        `Wrong type for '${ key }': expected '${ fieldTypes[key] }', ` +
        `got '${ typeof userConfig[key] }'.`
      )
    }
  })

  if (errors.length > 0) {
    throw new Error(
      `Your 'content-loader' config is invalid. Please fix the errors: \n- ` +
      errors.join("\n- ") +
      "\n\n" +
      "See 'Configuration' section in documentation."
    )
  }
}

export default memoize(10)(validator)
<|endoftext|>


<commit_before>'use strict'

var ObjectId = require("mongodb").ObjectId;
require('mongodb-toolkit');
var DLModels = require('dl-models');
var map = DLModels.map;
var LotMachine= DLModels.master.LotMachine;
var Product= DLModels.master.Product;
var Machine= DLModels.master.Machine;
var ProductManager = require('../master/product-manager');
var MachineManager = require('../master/machine-manager');
var BaseManager = require('../base-manager');
var i18n = require('dl-i18n');

module.exports = class LotMachineManager extends BaseManager {
    constructor(db, user) {
        super(db, user);
        this.collection = this.db.use(map.master.collection.LotMachine);
        this.productManager = new ProductManager(db, user);
        this.machineManager = new MachineManager(db, user);
    }

    _getQuery(paging) {
        var deleted = {
            _deleted: false
        };
        var query = paging.keyword ? {
            '$and': [deleted]
        } : deleted;

        if (paging.keyword) {
            var regex = new RegExp(paging.keyword, "i");
            var filterName = {
                'product.name': {
                    '$regex': regex
                }
            };
            var filterCode = {
                'product.code': {
                    '$regex': regex
                }
            };

            var $or = {
                '$or': [filterCode, filterName]
            };

            query['$and'].push($or);
        }
        return query;
    }

    _validate(lotMachine) {
        var errors = {};
        return new Promise((resolve, reject) => {
            var valid = lotMachine;
            // 1. begin: Declare promises.
            var getLotMachinePromise = this.collection.singleOrDefault({
                "$and": [{
                    "$and": [{
                        _id: {
                            '$ne': new ObjectId(valid._id)
                        }
                    }, {
                            productId: new ObjectId(valid.productId)
                        }]
                },
                {
                    _deleted:false
                } ]
            });

            var getProduct = valid.productId && ObjectId.isValid(valid.productId) ? this.productManager.getSingleByIdOrDefault(valid.productId) : Promise.resolve(null);
            var getMachine = valid.machineId && ObjectId.isValid(valid.machineId) ? this.machineManager.getSingleByIdOrDefault(valid.machineId) : Promise.resolve(null);
             Promise.all([getLotMachinePromise, getProduct, getMachine])
             .then(results =>{
                var _module = results[0];
                var _product = results[1];
                var _machine = results[2];
                var now = new Date();

                if (!_product)
                    errors["product"] = i18n.__("LotMachine.product.isRequired:%s is not exists", i18n.__("LotMachine.product._:Product"));
                else if (!valid.productId)
                    errors["product"] = i18n.__("LotMachine.product.isRequired:%s is required", i18n.__("LotMachine.product._:Product"));
                else if (valid.product) {
                    if (!valid.product._id)
                        errors["product"] = i18n.__("LotMachine.product.isRequired:%s is required", i18n.__("LotMachine.product._:Product"));
                }
                if (!_machine)
                    errors["machine"] = i18n.__("LotMachine.machine.isRequired:%s is not exists", i18n.__("LotMachine.machine._:Machine"));
                else if (!valid.productId)
                    errors["machine"] = i18n.__("LotMachine.machine.isRequired:%s is required", i18n.__("LotMachine.machine._:Machine"));
                else if (valid.machine) {
                    if (!valid.machine._id)
                        errors["machine"] = i18n.__("LotMachine.machine.isRequired:%s is required", i18n.__("LotMachine.machine._:Machine"));
                }

                if (Object.getOwnPropertyNames(errors).length > 0) {
                    var ValidationError = require('../../validation-error');
                    reject(new ValidationError('data does not pass validation', errors));
                }
                valid.machine=new Machine(_machine);
                valid.product=new Product(_product);
                valid = new LotMachine(lotMachine);

                valid.stamp(this.user.username, 'manager');
                resolve(valid);
             })
             .catch(e => {
                    reject(e);
                })
        });

    }

    getLotbyProductId(productId){

    }

    _createIndexes() {
        var dateIndex = {
            name: `ix_${map.master.collection.LotMachine}__updatedDate`,
            key: {
                _updatedDate: -1
            }
        }

        var codeIndex = {
            name: `ix_${map.master.collection.LotMachine}_productId`,
            key: {
                productId: 1
            },
            unique: true
        }

        return this.collection.createIndexes([dateIndex, codeIndex]);
    }
}
<commit_msg>fixing lot-machine manager<commit_after>'use strict'

var ObjectId = require("mongodb").ObjectId;
require('mongodb-toolkit');
var DLModels = require('dl-models');
var map = DLModels.map;
var LotMachine= DLModels.master.LotMachine;
var ProductManager = require('../master/product-manager');
var MachineManager = require('../master/machine-manager');
var BaseManager = require('../base-manager');
var i18n = require('dl-i18n');

module.exports = class LotMachineManager extends BaseManager {
    constructor(db, user) {
        super(db, user);
        this.collection = this.db.use(map.master.collection.LotMachine);
        this.productManager = new ProductManager(db, user);
        this.machineManager = new MachineManager(db, user);
    }

    _getQuery(paging) {
        var deleted = {
            _deleted: false
        };
        var query = paging.keyword ? {
            '$and': [deleted]
        } : deleted;

        if (paging.keyword) {
            var regex = new RegExp(paging.keyword, "i");
            var filterName = {
                'product.name': {
                    '$regex': regex
                }
            };
            var filterCode = {
                'product.code': {
                    '$regex': regex
                }
            };

            var $or = {
                '$or': [filterCode, filterName]
            };

            query['$and'].push($or);
        }
        return query;
    }

    _validate(lotMachine) {
        var errors = {};
        return new Promise((resolve, reject) => {
            var valid = lotMachine;
            // 1. begin: Declare promises.
            var getLotMachinePromise = this.collection.singleOrDefault({
                "$and": [{
                    "$and": [{
                        _id: {
                            '$ne': new ObjectId(valid._id)
                        }
                    }, {
                            productId: new ObjectId(valid.productId)
                        }]
                },
                {
                    _deleted:false
                } ]
            });

            var getProduct = valid.productId && ObjectId.isValid(valid.productId) ? this.productManager.getSingleByIdOrDefault(valid.productId) : Promise.resolve(null);
            var getMachine = valid.machineId && ObjectId.isValid(valid.machineId) ? this.machineManager.getSingleByIdOrDefault(valid.machineId) : Promise.resolve(null);
             Promise.all([getLotMachinePromise, getProduct, getMachine])
             .then(results =>{
                var _module = results[0];
                var _product = results[1];
                var _machine = results[2];
                var now = new Date();

                if (!_product)
                    errors["product"] = i18n.__("LotMachine.product.isRequired:%s is not exists", i18n.__("LotMachine.product._:Product"));
                else if (!valid.productId)
                    errors["product"] = i18n.__("LotMachine.product.isRequired:%s is required", i18n.__("LotMachine.product._:Product"));
                else if (valid.product) {
                    if (!valid.product._id)
                        errors["product"] = i18n.__("LotMachine.product.isRequired:%s is required", i18n.__("LotMachine.product._:Product"));
                }
                if (!_machine)
                    errors["machine"] = i18n.__("LotMachine.machine.isRequired:%s is not exists", i18n.__("LotMachine.machine._:Machine"));
                else if (!valid.productId)
                    errors["machine"] = i18n.__("LotMachine.machine.isRequired:%s is required", i18n.__("LotMachine.machine._:Machine"));
                else if (valid.machine) {
                    if (!valid.machine._id)
                        errors["machine"] = i18n.__("LotMachine.machine.isRequired:%s is required", i18n.__("LotMachine.machine._:Machine"));
                }

                if (Object.getOwnPropertyNames(errors).length > 0) {
                    var ValidationError = require('../../validation-error');
                    reject(new ValidationError('data does not pass validation', errors));
                }

                valid = new LotMachine(lotMachine);
                valid.stamp(this.user.username, 'manager');
                resolve(valid);
             })
             .catch(e => {
                    reject(e);
                })
        });

    }

    _createIndexes() {
        var dateIndex = {
            name: `ix_${map.master.collection.LotMachine}__updatedDate`,
            key: {
                _updatedDate: -1
            }
        }

        var codeIndex = {
            name: `ix_${map.master.collection.LotMachine}_productId`,
            key: {
                productId: 1
            },
            unique: true
        }

        return this.collection.createIndexes([dateIndex, codeIndex]);
    }
}
<|endoftext|>