<commit_before>import { Collectives } from '../collectives/Collectives';
import { Transactions } from './Transactions';
import { showFullName } from '../../startup/both/modules/utils';
import { guidGenerator } from '../../startup/both/modules/crypto';

/**
* @summary create a new transaction between two parties
* @param {string} senderId - user or collective allocating the funds
* @param {string} receiverId - user or collective receiving the funds
* @param {object} settings - additional settings to be stored on the ledger
*/
const _createTransaction = (senderId, receiverId, quantity, settings) => {
  console.log('[_createTransaction] creating new transaction...');
  console.log('[_createTransaction] sender: ' + senderId);
  console.log('[_createTransaction] receiver: ' + receiverId);

  // default settings
  let defaultSettings = {};
  defaultSettings = {
    currency: 'VOTES',
    kind: 'VOTE',
    contractId: false // _getContractId(senderId, receiverId, settings.kind),
  };

  if (settings == undefined) {
    var settings = new Object();
    settings = defaultSettings;
  } else {
    settings = Object.assign(defaultSettings, settings);
  };

  //build transaction
  var newTransaction =  {
    input: {
      entityId: senderId,
      address: _getWalletAddress(senderId),
      entityType: _getEntityType(senderId),
      quantity: quantity,
      currency: settings.currency
    },
    output: {
      entityId: receiverId,
      address: _getWalletAddress(receiverId),
      entityType: _getEntityType(receiverId),
      quantity: quantity,
      currency: settings.currency
    },
    kind: settings.kind,
    contractId: settings.contractId,
    timestamp: new Date(),
    status: 'PENDING',
    condition: settings.condition
  };

  console.log('[_createTransaction] generated new transaction settings');

  //executes the transaction
  var txId = Transactions.insert(newTransaction);
  if (_processTransaction(txId)) { return txId; };
  return newTransaction;
}

/***
* processes de transaction after insert and updates wallet of involved parties
* @param {string} txId - transaction identificator
***/
let _processTransaction = (txId) => {

  var transaction = Transactions.findOne({ _id: txId });
  var senderProfile = _getProfile(transaction.input);
  var receiverProfile = _getProfile(transaction.output);

  //TODO all transactions are for VOTE type, develop in the future transactions for BITCOIN or multi-currency conversion.
  //TODO verification of funds

  var sender = senderProfile.wallet;

  sender.ledger.push({
    txId: txId,
    quantity: parseInt(0 - transaction.input.quantity),
    entityId: transaction.output.entityId,
    entityType: transaction.output.entityType,
    currency: transaction.input.currency
  });
  sender.placed += parseInt(transaction.input.quantity);
  sender.available = sender.balance - sender.placed;
  senderProfile.wallet = Object.assign(senderProfile.wallet, sender);

  if (senderProfile.firstName) {
    console.log('[_processTransaction] sender in transaction is entity: ' + showFullName(senderProfile.firstName, senderProfile.lastName));
  } else {
    console.log('[_processTransaction] sender in transaction is a Contract with title: ' + senderProfile.title);
  }

  var receiver = receiverProfile.wallet;
  receiver.ledger.push({
    txId: txId,
    quantity: parseInt(transaction.output.quantity),
    entityId: transaction.input.entityId,
    entityType: transaction.input.entityType,
    currency: transaction.output.currency
  });
  receiver.available += parseInt(transaction.output.quantity);
  receiver.balance += receiver.available;

  console.log('[_processTransaction] checking if ballot stored in this transaction...');
  if (transaction.condition.ballot) {
    console.log('[_processTransaction] found ballot in this transaction');
    fullBallot = new Array();
    last = receiver.ledger.length - 1;

    for (k in transaction.condition.ballot) {
      fullBallot.push(transaction.condition.ballot[k])
    };
    console.log('[_processTransaction] ballot content:');
    console.log(fullBallot);
    receiver.ledger[last] = Object.assign(receiver.ledger[last], {ballot: fullBallot});
  } else {
    console.log('[_processTransaction] no ballot found.');
  }
  receiverProfile.wallet = Object.assign(receiverProfile.wallet, receiver);

  if (receiverProfile.firstName) {
    console.log('[_processTransaction] receiver in transaction is entity: ' + showFullName(receiverProfile.firstName, receiverProfile.lastName));
  } else {
    console.log('[_processTransaction] receiver in transaction is a Contract with title: ' + receiverProfile.title);
  }

  //update wallets
  _updateWallet(transaction.input.entityId, transaction.input.entityType, senderProfile);
  _updateWallet(transaction.output.entityId, transaction.output.entityType, receiverProfile);

  //set this transaction as processed
  return Transactions.update({ _id: txId }, { $set: { status : 'CONFIRMED' }});

}

/*
let _updateBalance = (wallet) => {
  var balance = new Number(0);
  for (i in wallet.ledger) {
      wallet.ledger[]
  }
}
*/

/***
* returns the profile object of an entity from a transaction
* @param {string} transactionSignal - input or output of a transaction object
* @return {object} profile - profile object of entity
***/
let _getProfile = (transactionSignal) => {
  switch (transactionSignal.entityType) {
    case 'INDIVIDUAL':
      return Meteor.users.findOne( { _id: transactionSignal.entityId }).profile;
      break;
    case 'COLLECTIVE':
      return Collectives.findOne( { _id: transactionSignal.entityId }).profile;
      break;
    case 'CONTRACT':
      return Contracts.findOne({ _id: transactionSignal.entityId });
      break;
  }
}

/***
* updates wallet object of an individual or collective
* @param {string} entityId - entity
* @param {string} entityType -  individual or collective
* @param {object} wallet - wallet object of entity
***/
let _updateWallet = (entityId, entityType, profile) => {
  console.log('[_updateWallet] updating wallet of entityId :' + entityId);
  switch (entityType) {
    case 'INDIVIDUAL':
      Meteor.users.update( { _id: entityId }, { $set : { profile : profile } });
      break;
    case 'COLLECTIVE':
      Collectives.update( { _id: entityId }, { $set : { profile : profile } });
      break;
    case 'CONTRACT':
      Contracts.update({ _id: entityId }, { $set: { wallet: profile.wallet }});
      break;
  }
}

/***
* generates a contract specifying details of this transaction
* @param {string} senderId - user or collective allocating the funds
* @param {string} receiverId - user or collective receiving the funds
* @param {string} kind - type of contract, VOTE, DELEGATION or MEMBERSHIP
* @return {string} id - contract id of the reference agreement
****/
let _getContractId = (senderId, receiverId, kind) => {
  //TODO
}

/***
* looks at what type of entity (collective or individual) doing transaction
* @return {string} entityType - a string with constant of entity type
***/
let _getEntityType = (entityId) => {
  if (Meteor.users.findOne({ _id: entityId })) {
    return 'INDIVIDUAL';
  } else if (Collectives.findOne({ _id: entityId })) {
    return 'COLLECTIVE';
  } else if (Contracts.findOne({ _id: entityId})) {
    return 'CONTRACT';
  } else {
    return 'UNKNOWN';
  };
}

/***
* looks for an appropiate address to use for this user
* @param {string} entityId - id of the user's wallet being used
* @return {string} hash - a string with a wallet address direction for a user
***/
let _getWalletAddress = (entityId) => {
  var entityType = _getEntityType(entityId);

  switch (entityType) {
    case 'INDIVIDUAL':
      var user = Meteor.users.findOne({ _id: entityId });
      break;
    case 'COLLECTIVE':
      var user = Collectives.findOne({ _id: entityId });
      break;
    case 'CONTRACT':
      var user = Contracts.findOne({ _id: entityId});
      break;
    default:
      console.log('[_getWalletAddress] ERROR: entityId ' + entityId + ' could not be found.');
      return false;
  }

  if (user.profile != undefined) {
    var wallet = user.profile.wallet;
  } else {
    var wallet = user.wallet; //entity is a contract
  }
  var collectiveId = Meteor.settings.public.Collective._id;

  console.log('[_getWalletAddress] getting info for entityId ' + entityId + '.');

  if (wallet.address != undefined && wallet.address.length > 0) {
    console.log('[_getWalletAddress] entity wallet already has an address.');
    return _getAddressHash(wallet.address, collectiveId);
  } else {
    console.log('[_getWalletAddress] generating a new address for this collective...');
    wallet = _generateWalletAddress(wallet);
    switch (entityType) {
      case 'INDIVIDUAL':
        user.profile.wallet = wallet;
        Meteor.users.update({ _id: entityId }, { $set: { profile: user.profile } });
        break;
      case 'COLLECTIVE':
        user.profile.wallet = wallet;
        Collectives.update({ _id: entityId }, { $set: { profile: user.profile } });
        break;
      case 'CONTRACT':
        Contracts.update({ _id: entityId }, { $set: { wallet: wallet } });
        break;
      default:
        console.log('[_getWalletAddress] ERROR: entityId ' + entityId + ' could not be found.');
        return false;
    }
    return _getAddressHash(wallet.address, collectiveId);
  }
};

/**
* returns the has for the address that is from corresponding collective
* @param {array} address - a wallet from a user containing all directions
* @param {string} collectiveId - matching collective
***/
let _getAddressHash = (address, collectiveId) => {
  for (var i = 0; i < address.length; i ++) {
    if (address[i].collectiveId == collectiveId) {
      return address[i].hash;
    }
  }
}

/**
* @summary generates a new address given a wallet
* @param {object} wallet - a wallet from a user containing all directions
***/
const _generateWalletAddress = (wallet) => {
  console.log('[_generateWalletAddress] generating a new address for wallet entered as parameter.');
  wallet.address.push(_getCollectiveAddress());
  return wallet;
};

/***
* generates a new address specific to the collective running this instance
* @return {object} object - returns an object containing a new hash and this collective Id.
***/
let _getCollectiveAddress = () => {
  console.log('[_getCollectiveAddress] generating new address specific to the collective running this instance...');
  return {
    hash: guidGenerator(),
    collectiveId: Meteor.settings.public.Collective._id
  };
};

export const processTransaction = _processTransaction;
export const generateWalletAddress = _generateWalletAddress;
export const transact = _createTransaction;
<commit_msg>missed import in transaction<commit_after>import { Meteor } from 'meteor/meteor';

import { Contracts } from '/imports/api/contracts/Contracts';
import { Collectives } from '/imports/api/collectives/Collectives';
import { showFullName } from '/imports/startup/both/modules/utils';
import { guidGenerator } from '/imports/startup/both/modules/crypto';
import { Transactions } from './Transactions';

/**
* @summary create a new transaction between two parties
* @param {string} senderId - user or collective allocating the funds
* @param {string} receiverId - user or collective receiving the funds
* @param {object} settings - additional settings to be stored on the ledger
*/
const _createTransaction = (senderId, receiverId, quantity, settings) => {
  console.log('[_createTransaction] creating new transaction...');
  console.log('[_createTransaction] sender: ' + senderId);
  console.log('[_createTransaction] receiver: ' + receiverId);

  // default settings
  let defaultSettings = {};
  defaultSettings = {
    currency: 'VOTES',
    kind: 'VOTE',
    contractId: false // _getContractId(senderId, receiverId, settings.kind),
  };

  if (settings == undefined) {
    var settings = new Object();
    settings = defaultSettings;
  } else {
    settings = Object.assign(defaultSettings, settings);
  };

  //build transaction
  var newTransaction =  {
    input: {
      entityId: senderId,
      address: _getWalletAddress(senderId),
      entityType: _getEntityType(senderId),
      quantity: quantity,
      currency: settings.currency
    },
    output: {
      entityId: receiverId,
      address: _getWalletAddress(receiverId),
      entityType: _getEntityType(receiverId),
      quantity: quantity,
      currency: settings.currency
    },
    kind: settings.kind,
    contractId: settings.contractId,
    timestamp: new Date(),
    status: 'PENDING',
    condition: settings.condition
  };

  console.log('[_createTransaction] generated new transaction settings');

  //executes the transaction
  var txId = Transactions.insert(newTransaction);
  if (_processTransaction(txId)) { return txId; };
  return newTransaction;
}

/***
* processes de transaction after insert and updates wallet of involved parties
* @param {string} txId - transaction identificator
***/
let _processTransaction = (txId) => {

  var transaction = Transactions.findOne({ _id: txId });
  var senderProfile = _getProfile(transaction.input);
  var receiverProfile = _getProfile(transaction.output);

  //TODO all transactions are for VOTE type, develop in the future transactions for BITCOIN or multi-currency conversion.
  //TODO verification of funds

  var sender = senderProfile.wallet;

  sender.ledger.push({
    txId: txId,
    quantity: parseInt(0 - transaction.input.quantity),
    entityId: transaction.output.entityId,
    entityType: transaction.output.entityType,
    currency: transaction.input.currency
  });
  sender.placed += parseInt(transaction.input.quantity);
  sender.available = sender.balance - sender.placed;
  senderProfile.wallet = Object.assign(senderProfile.wallet, sender);

  if (senderProfile.firstName) {
    console.log('[_processTransaction] sender in transaction is entity: ' + showFullName(senderProfile.firstName, senderProfile.lastName));
  } else {
    console.log('[_processTransaction] sender in transaction is a Contract with title: ' + senderProfile.title);
  }

  var receiver = receiverProfile.wallet;
  receiver.ledger.push({
    txId: txId,
    quantity: parseInt(transaction.output.quantity),
    entityId: transaction.input.entityId,
    entityType: transaction.input.entityType,
    currency: transaction.output.currency
  });
  receiver.available += parseInt(transaction.output.quantity);
  receiver.balance += receiver.available;

  console.log('[_processTransaction] checking if ballot stored in this transaction...');
  if (transaction.condition.ballot) {
    console.log('[_processTransaction] found ballot in this transaction');
    fullBallot = new Array();
    last = receiver.ledger.length - 1;

    for (k in transaction.condition.ballot) {
      fullBallot.push(transaction.condition.ballot[k])
    };
    console.log('[_processTransaction] ballot content:');
    console.log(fullBallot);
    receiver.ledger[last] = Object.assign(receiver.ledger[last], {ballot: fullBallot});
  } else {
    console.log('[_processTransaction] no ballot found.');
  }
  receiverProfile.wallet = Object.assign(receiverProfile.wallet, receiver);

  if (receiverProfile.firstName) {
    console.log('[_processTransaction] receiver in transaction is entity: ' + showFullName(receiverProfile.firstName, receiverProfile.lastName));
  } else {
    console.log('[_processTransaction] receiver in transaction is a Contract with title: ' + receiverProfile.title);
  }

  //update wallets
  _updateWallet(transaction.input.entityId, transaction.input.entityType, senderProfile);
  _updateWallet(transaction.output.entityId, transaction.output.entityType, receiverProfile);

  //set this transaction as processed
  return Transactions.update({ _id: txId }, { $set: { status : 'CONFIRMED' }});

}

/*
let _updateBalance = (wallet) => {
  var balance = new Number(0);
  for (i in wallet.ledger) {
      wallet.ledger[]
  }
}
*/

/***
* returns the profile object of an entity from a transaction
* @param {string} transactionSignal - input or output of a transaction object
* @return {object} profile - profile object of entity
***/
let _getProfile = (transactionSignal) => {
  switch (transactionSignal.entityType) {
    case 'INDIVIDUAL':
      return Meteor.users.findOne( { _id: transactionSignal.entityId }).profile;
      break;
    case 'COLLECTIVE':
      return Collectives.findOne( { _id: transactionSignal.entityId }).profile;
      break;
    case 'CONTRACT':
      return Contracts.findOne({ _id: transactionSignal.entityId });
      break;
  }
}

/***
* updates wallet object of an individual or collective
* @param {string} entityId - entity
* @param {string} entityType -  individual or collective
* @param {object} wallet - wallet object of entity
***/
let _updateWallet = (entityId, entityType, profile) => {
  console.log('[_updateWallet] updating wallet of entityId :' + entityId);
  switch (entityType) {
    case 'INDIVIDUAL':
      Meteor.users.update( { _id: entityId }, { $set : { profile : profile } });
      break;
    case 'COLLECTIVE':
      Collectives.update( { _id: entityId }, { $set : { profile : profile } });
      break;
    case 'CONTRACT':
      Contracts.update({ _id: entityId }, { $set: { wallet: profile.wallet }});
      break;
  }
}

/***
* generates a contract specifying details of this transaction
* @param {string} senderId - user or collective allocating the funds
* @param {string} receiverId - user or collective receiving the funds
* @param {string} kind - type of contract, VOTE, DELEGATION or MEMBERSHIP
* @return {string} id - contract id of the reference agreement
****/
let _getContractId = (senderId, receiverId, kind) => {
  //TODO
}

/***
* looks at what type of entity (collective or individual) doing transaction
* @return {string} entityType - a string with constant of entity type
***/
let _getEntityType = (entityId) => {
  if (Meteor.users.findOne({ _id: entityId })) {
    return 'INDIVIDUAL';
  } else if (Collectives.findOne({ _id: entityId })) {
    return 'COLLECTIVE';
  } else if (Contracts.findOne({ _id: entityId})) {
    return 'CONTRACT';
  } else {
    return 'UNKNOWN';
  };
}

/***
* looks for an appropiate address to use for this user
* @param {string} entityId - id of the user's wallet being used
* @return {string} hash - a string with a wallet address direction for a user
***/
let _getWalletAddress = (entityId) => {
  var entityType = _getEntityType(entityId);

  switch (entityType) {
    case 'INDIVIDUAL':
      var user = Meteor.users.findOne({ _id: entityId });
      break;
    case 'COLLECTIVE':
      var user = Collectives.findOne({ _id: entityId });
      break;
    case 'CONTRACT':
      var user = Contracts.findOne({ _id: entityId});
      break;
    default:
      console.log('[_getWalletAddress] ERROR: entityId ' + entityId + ' could not be found.');
      return false;
  }

  if (user.profile != undefined) {
    var wallet = user.profile.wallet;
  } else {
    var wallet = user.wallet; //entity is a contract
  }
  var collectiveId = Meteor.settings.public.Collective._id;

  console.log('[_getWalletAddress] getting info for entityId ' + entityId + '.');

  if (wallet.address != undefined && wallet.address.length > 0) {
    console.log('[_getWalletAddress] entity wallet already has an address.');
    return _getAddressHash(wallet.address, collectiveId);
  } else {
    console.log('[_getWalletAddress] generating a new address for this collective...');
    wallet = _generateWalletAddress(wallet);
    switch (entityType) {
      case 'INDIVIDUAL':
        user.profile.wallet = wallet;
        Meteor.users.update({ _id: entityId }, { $set: { profile: user.profile } });
        break;
      case 'COLLECTIVE':
        user.profile.wallet = wallet;
        Collectives.update({ _id: entityId }, { $set: { profile: user.profile } });
        break;
      case 'CONTRACT':
        Contracts.update({ _id: entityId }, { $set: { wallet: wallet } });
        break;
      default:
        console.log('[_getWalletAddress] ERROR: entityId ' + entityId + ' could not be found.');
        return false;
    }
    return _getAddressHash(wallet.address, collectiveId);
  }
};

/**
* returns the has for the address that is from corresponding collective
* @param {array} address - a wallet from a user containing all directions
* @param {string} collectiveId - matching collective
***/
let _getAddressHash = (address, collectiveId) => {
  for (var i = 0; i < address.length; i ++) {
    if (address[i].collectiveId == collectiveId) {
      return address[i].hash;
    }
  }
}

/**
* @summary generates a new address given a wallet
* @param {object} wallet - a wallet from a user containing all directions
***/
const _generateWalletAddress = (wallet) => {
  console.log('[_generateWalletAddress] generating a new address for wallet entered as parameter.');
  wallet.address.push(_getCollectiveAddress());
  return wallet;
};

/***
* generates a new address specific to the collective running this instance
* @return {object} object - returns an object containing a new hash and this collective Id.
***/
let _getCollectiveAddress = () => {
  console.log('[_getCollectiveAddress] generating new address specific to the collective running this instance...');
  return {
    hash: guidGenerator(),
    collectiveId: Meteor.settings.public.Collective._id
  };
};

export const processTransaction = _processTransaction;
export const generateWalletAddress = _generateWalletAddress;
export const transact = _createTransaction;
<|endoftext|>


<commit_before>import React from 'react';
import {Link} from 'react-router';

export default function Auth(props) {
  return (

<Link to="/auth/login">Login</Link>

<Link to="/auth/register">Register</Link>

            {props.children}

  );
}<commit_msg>Update auth.<commit_after>import React from 'react';
import {Link} from 'react-router';

export default function Auth(props) {
  return (

<Link to="/auth/login">Login</Link>

<Link to="/auth/register">Register</Link>

              {props.children}

  );
}
<|endoftext|>


<commit_before>var jasmine = require('jasmine-node');
var sys = require('sys'),
    Path= require('path');

var SPEC_FOLDER= Path.join(process.cwd(), 'spec'),
    SPEC_MATCHER_REGEX= "^.+[-_]spec\.(js|coffee)$",
    HELPER_MATCHER_REGEX= "^.+[-_]helper\.(js|coffee)$";

for (var key in jasmine)
  global[key] = jasmine[key];

var isVerbose = false;
var showColors = true;

process.argv.forEach(function(arg){
  switch(arg)
  {
    case '--color':
      showColors = true;
      break;
    case '--noColor':
      showColors = false;
      break;
    case '--verbose':
      isVerbose = true;
      break;
  }
});

jasmine.loadHelpersInFolder(SPEC_FOLDER, HELPER_MATCHER_REGEX);
jasmine.executeSpecsInFolder(SPEC_FOLDER, function(runner, log){
  if (runner.results().failedCount() == 0) {
    process.exit(0);
  } else {
    process.exit(1);
  }
}, isVerbose, showColors, SPEC_MATCHER_REGEX);
<commit_msg>added unknown option reporting to cli.js; removed broken method calls<commit_after>var jasmine = require('jasmine-node');
var sys = require('sys'),
    Path= require('path');

var SPEC_FOLDER= Path.join(process.cwd(), 'spec'),
    SPEC_MATCHER_REGEX= "^.+[-_]spec\.(js|coffee)$",
    HELPER_MATCHER_REGEX= "^.+[-_]helper\.(js|coffee)$";

for (var key in jasmine)
  global[key] = jasmine[key];

var isVerbose = false;
var showColors = true;

process.argv.slice(2).forEach(function(arg){
  switch(arg)
  {
    case '--color':
      showColors = true;
      break;
    case '--noColor':
      showColors = false;
      break;
    case '--verbose':
      isVerbose = true;
      break;
    default:
      sys.puts("unknown option: " + arg);
      process.exit(1);
      break;
  }
});

//TODO: implement this
//jasmine.loadHelpersInFolder(SPEC_FOLDER, HELPER_MATCHER_REGEX);
jasmine.executeSpecsInFolder(SPEC_FOLDER, function(runner, log){
  if (runner.results().failedCount == 0) {
    process.exit(0);
  } else {
    process.exit(1);
  }
}, isVerbose, showColors, SPEC_MATCHER_REGEX);
<|endoftext|>


<commit_before>import * as pg from './periodic';
import * as ps from './symmetries';

const ops = pg.ops;

const _solveInRows = (v, M) => {
  const tmp = ops.solution(ops.transposed(M), ops.transposed(v));
  return tmp && ops.transposed(tmp);
};

const _traversal = function* _traversal(
  graph,
  v0,
  transform,
  adj = pg.adjacencies(graph),
  pos = pg.barycentricPlacement(graph))
{
  const zero = ops.vector(graph.dim);

  const old2new = {[v0]: 1};
  const newPos = {[v0]: zero};
  const queue = [v0];
  const essentialShifts = [];

  let next = 2;
  let basisAdjustment = null;

  while (queue.length) {
    const vo = queue.shift();
    const vn = old2new[vo];
    const pv = newPos[vo];

    const incident = pg.allIncidences(graph, vo, adj);
    const M = ops.times(incident.map(e => pg.edgeVector(e, pos)), transform);

    const neighbors = incident
      .map((e, i) => [ops.plus(pv, M[i]), e.tail])
      .sort(([sa, wa], [sb, wb]) => ops.cmp(sa, sb));

    for (const [s, wo] of neighbors) {
      const wn = old2new[wo];
      if (wn == null) {
        yield pg.makeEdge(vn, next, zero);
        old2new[wo] = next++;
        newPos[wo] = s;
        queue.push(wo);
      }
      else if (wn < vn) {
        continue;
      }
      else {
        const rawShift = ops.minus(s, newPos[wo]);
        let shift;
        if (basisAdjustment != null) {
          shift = ops.times(rawShift, basisAdjustment);
        }
        else if (ops.sgn(rawShift) == 0) {
          shift = rawShift;
        }
        else {
          if (essentialShifts.length) {
            shift = _solveInRows(rawShift, essentialShifts);
          }
          if (shift == null) {
            shift = ops.unitVector(graph.dim, essentialShifts.length);
            essentialShifts.push(rawShift);
            if (essentialShifts.length == graph.dim) {
              basisAdjustment = ops.inverse(ops.transposed(essentialShifts));
            }
          }
        }
        if (vn < wn || (vn == wn && ops.sgn(shift) < 0)) {
          yield pg.makeEdge(vn, wn, shift);
        }
      }
    }
  }
};

export function invariant(
  graph,
  adj = pg.adjacencies(graph),
  pos = pg.barycentricPlacement(graph),
  bases = ps.characteristicBases(graph, adj, pos),
  sym = ps.symmetries(graph, adj, pos, bases))
{
  for (const basis of sym.representativeBases) {
    const v = basis[0].head;
    const transform = ops.inverse(basis.map(e => pg.edgeVector(e, pos)));
    const trav = _traversal(graph, v, transform, adj, pos);
    console.log(`basis = ${basis}`);
    console.log(`transform = ${transform}`);
    for (const e of trav)
      console.log(e);
    console.log();
  }
}

if (require.main == module) {
  Array.prototype.toString = function() {
    return `[ ${this.map(x => x.toString()).join(', ')} ]`;
  };

  const test = g => {
    invariant(g);
  };

  test(pg.make([ [ 1, 2, [ 0, 0, 0 ] ],
                 [ 1, 2, [ 1, 0, 0 ] ],
                 [ 1, 2, [ 0, 1, 0 ] ],
                 [ 1, 2, [ 0, 0, 1 ] ] ]));

  test(pg.make([ [ 1, 2, [ 0, 0 ] ],
                 [ 1, 2, [ 1, 0 ] ],
                 [ 2, 3, [ 0, 0 ] ],
                 [ 2, 3, [ 0, 1 ] ],
                 [ 1, 3, [ 0, 0 ] ],
                 [ 1, 3, [ 1, 1 ] ] ]));
}
<commit_msg>use a more elementary form for traversal results<commit_after>import * as pg from './periodic';
import * as ps from './symmetries';

const ops = pg.ops;

const _solveInRows = (v, M) => {
  const tmp = ops.solution(ops.transposed(M), ops.transposed(v));
  return tmp && ops.transposed(tmp);
};

const _traversal = function* _traversal(
  graph,
  v0,
  transform,
  adj = pg.adjacencies(graph),
  pos = pg.barycentricPlacement(graph))
{
  const zero = ops.vector(graph.dim);

  const old2new = {[v0]: 1};
  const newPos = {[v0]: zero};
  const queue = [v0];
  const essentialShifts = [];

  let next = 2;
  let basisAdjustment = null;

  while (queue.length) {
    const vo = queue.shift();
    const vn = old2new[vo];
    const pv = newPos[vo];

    const incident = pg.allIncidences(graph, vo, adj);
    const M = ops.times(incident.map(e => pg.edgeVector(e, pos)), transform);

    const neighbors = incident
      .map((e, i) => [ops.plus(pv, M[i]), e.tail])
      .sort(([sa, wa], [sb, wb]) => ops.cmp(sa, sb));

    for (const [s, wo] of neighbors) {
      const wn = old2new[wo];
      if (wn == null) {
        yield [vn, next, zero];
        old2new[wo] = next++;
        newPos[wo] = s;
        queue.push(wo);
      }
      else if (wn < vn) {
        continue;
      }
      else {
        const rawShift = ops.minus(s, newPos[wo]);
        let shift;
        if (basisAdjustment != null) {
          shift = ops.times(rawShift, basisAdjustment);
        }
        else if (ops.sgn(rawShift) == 0) {
          shift = rawShift;
        }
        else {
          if (essentialShifts.length) {
            shift = _solveInRows(rawShift, essentialShifts);
          }
          if (shift == null) {
            shift = ops.unitVector(graph.dim, essentialShifts.length);
            essentialShifts.push(rawShift);
            if (essentialShifts.length == graph.dim) {
              basisAdjustment = ops.inverse(ops.transposed(essentialShifts));
            }
          }
        }
        if (vn < wn || (vn == wn && ops.sgn(shift) < 0)) {
          yield [vn, wn, shift];
        }
      }
    }
  }
};

export function invariant(
  graph,
  adj = pg.adjacencies(graph),
  pos = pg.barycentricPlacement(graph),
  bases = ps.characteristicBases(graph, adj, pos),
  sym = ps.symmetries(graph, adj, pos, bases))
{
  for (const basis of sym.representativeBases) {
    const v = basis[0].head;
    const transform = ops.inverse(basis.map(e => pg.edgeVector(e, pos)));
    const trav = _traversal(graph, v, transform, adj, pos);
    console.log(`basis = ${basis}`);
    console.log(`transform = ${transform}`);
    for (const e of trav)
      console.log(e);
    console.log();
  }
}

if (require.main == module) {
  Array.prototype.toString = function() {
    return `[ ${this.map(x => x.toString()).join(', ')} ]`;
  };

  const test = g => {
    invariant(g);
  };

  test(pg.make([ [ 1, 2, [ 0, 0, 0 ] ],
                 [ 1, 2, [ 1, 0, 0 ] ],
                 [ 1, 2, [ 0, 1, 0 ] ],
                 [ 1, 2, [ 0, 0, 1 ] ] ]));

  test(pg.make([ [ 1, 2, [ 0, 0 ] ],
                 [ 1, 2, [ 1, 0 ] ],
                 [ 2, 3, [ 0, 0 ] ],
                 [ 2, 3, [ 0, 1 ] ],
                 [ 1, 3, [ 0, 0 ] ],
                 [ 1, 3, [ 1, 1 ] ] ]));
}
<|endoftext|>


<commit_before>export default class Pickathing {
	constructor(elementId, hasSearch, options) {
		if (options) {
			this.filterAnotherBy = options.filterAttr;
			this.filterAnother = options.filter;
		}

		this.element = document.getElementById(elementId);
		this.parentEl = this.element.parentNode;
		this.hasSearch = typeof hasSearch === 'undefined' ? true : hasSearch;
		this.required = this.element.hasAttribute('data-required');

		this.wrapper = document.createElement('div');
		this.wrapper.className = 'Pickathing';
		this.wrapper = this.parentEl.insertBefore(this.wrapper, this.element);

		if (this.required) {
			this.wrapper.setAttribute('data-required', '');
			this.element.removeAttribute('data-required');
		}

		this.optionElements = [];
		this.options = this.element.options;
		this.selectedOption;

		this.multiple = this.element.multiple;

		if (this.multiple) {
			this.wrapper.classList.add('Pickathing--multiple');
			this.value = {};
		} else {
			this.value = this.element.value;
		}

		this.searchField;

		this.create();
		this.bindEvents();
	}

	create() {
		let self = this;

		this.addSelectedField();
		this.addDropdown();
		if (this.hasSearch) {
			this.addSearchField();
		}
		this.addList();

		for (let i = 0; i < this.options.length; i++) {
			self.addOption(self.options[i]);
		}

		this.checkSelected();
	}

	addSelectedField() {
		this.selectedField = document.createElement('div');
		this.selectedField.type = '';
		this.selectedField.setAttribute('data-client-input', '');
		this.selectedField.className = 'Pickathing-selectedField';
		this.wrapper.appendChild(this.selectedField);
	}

	addDropdown() {
		this.dropdown = document.createElement('div');
		this.dropdown.className = 'Pickathing-dropdown';
		this.wrapper.appendChild(this.dropdown);
	}

	addList() {
		this.list = document.createElement('div');
		this.list.className = 'Pickathing-list';
		this.dropdown.appendChild(this.list);
	}

	addSearchField() {
		this.searchField = document.createElement('input');
		this.searchField.type = 'text';
		this.searchField.className = 'Pickathing-searchField';
		this.dropdown.appendChild(this.searchField);
	}

	addOption(option) {
		let value = option.value;
		let text = option.innerHTML;
		let element;

		if (value == '' || option.disabled) {
			element = document.createElement('button');
			element.disabled = true;
		} else {
			element = document.createElement('div');
		}

		element.innerHTML = text;
		element.className = 'Pickathing-option'
		element.setAttribute('data-option', value);
		element.setAttribute('data-label', text);

		let dataAttributes = [].filter.call(option.attributes, (at) => /^data-/.test(at.name));
		if (dataAttributes.length > 0) {
			dataAttributes.map((data) => {
				element.setAttribute(data.name, data.value);
			});
		}

		this.list.appendChild(element);
		this.optionElements.push(element);
	}

	enable() {
		this.selectedField.disabled = false;
	}

	disable() {
		this.selectedField.disabled = true;
	}

	checkSelected() {
		for (let i = 0; i < this.options.length; i++) {
			if (this.options[i].selected) {
				if (!this.multiple) {
					let label = this.optionElements[i].getAttribute('data-label');
					this.optionElements[i].classList.add('Pickathing-option--selected');
					this.selectedField.innerHTML = label;
					this.selectedOption = this.optionElements[i];

					return;
				} else {
					this.setMultiOption(this.optionElements[i]);
					this.optionElements[i].disabled = true;
				}
			}
		}
	}

	setMultiOption(option) {
		option.classList.add('Pickathing-option--selected');
		let label = option.getAttribute('data-label');
		let value = option.getAttribute('data-option');
		let selectedFlag = document.createElement('span');
		let dataAttributes = [].filter.call(option.attributes, (at) => /^data-/.test(at.name));
		if (dataAttributes.length > 0) {
			dataAttributes.map((data) => {
				selectedFlag.setAttribute(data.name, data.value);
			});
		}
		selectedFlag.classList.add('Pickathing-selectedFlag');
		selectedFlag.setAttribute('data-option', value);
		selectedFlag.innerHTML = label;
		this.selectedField.appendChild(selectedFlag);
		this.value[value] = option;
	}

	onChange() {
		// silence is golden
	}

	setOptionByIndex(index, fireOnChange) {
		let value = this.optionElements[index].getAttribute('data-option');
		let label = this.optionElements[index].getAttribute('data-label');

		this.optionElements.map((opt) => {
			opt.classList.remove('Pickathing-option--selected');
		});

		this.optionElements[index].classList.add('Pickathing-option--selected');
		this.selectedField.innerHTML = label;
		this.element.value = value;
		this.value = value;
		this.selectedOption = this.optionElements[index];

		if (typeof fireOnChange == 'undefined' || fireOnChange == true) {
			this.onChange();
		}
	}

	reset(fireOnChange) {
		if (!this.multiple) {
			this.setOptionByIndex(0, fireOnChange);
		} else {
			for (let val in this.value) {
				this.deselectMultiOption(val);
			}

			if (fireOnChange) {
				this.onChange();
			}
		}
	}

	deselectMultiOption(value) {
		let element = this.wrapper.querySelectorAll('.Pickathing-option[data-option="' + value + '"]');
		let flagToRemove = this.wrapper.querySelectorAll('.Pickathing-selectedFlag[data-option="' + value + '"]');
		flagToRemove[0].remove();
		element[0].classList.remove('Pickathing-option--selected');
		delete this.value[value];
	}

	filter(query, field) {
		this.optionElements.map((el) => {
			let label = el.getAttribute(field);
			el.style.display = 'block';
			if (label && query != null) {
				if (label.match(query)) {
					el.style.display = 'block';
				} else {
					el.style.display = 'none';
				}
			}
		});
	}

	bindEvents() {
		let self = this;
		if (this.hasSearch) {
			this.searchField.addEventListener('keyup', (e) => {
				let query = new RegExp(self.searchField.value, 'gi');
				self.filter(query, 'data-label');
			});
		}

		document.addEventListener('click', (e) => {
			let el = e.target;

			if (el != this.selectedField && el != this.searchField) {
				if (el.classList.contains('Pickathing-option') && this.multiple) {
					// do nothing
				} else {
					this.wrapper.classList.remove('Pickathing--open');
				}
			}
		});

		this.wrapper.addEventListener('click', (e) => {
			let el = e.target;
			if (el.classList.contains('Pickathing-option')) {

				if (!this.multiple) {
					self.wrapper.classList.remove('Pickathing--open');
				}

				let value = el.getAttribute('data-option');
				let label = el.getAttribute('data-label');

				if (!this.multiple) {
					this.optionElements.map((opt) => {
						opt.classList.remove('Pickathing-option--selected');
					});
					el.classList.add('Pickathing-option--selected');
					this.selectedOption = el;
					this.selectedField.innerHTML = label;
					this.element.value = value;
					this.value = value;
				} else {
					if (!el.classList.contains('Pickathing-option--selected')) {
						let selectedFlag = document.createElement('span');
						selectedFlag.classList.add('Pickathing-selectedFlag');
						selectedFlag.innerHTML = label;
						selectedFlag.setAttribute('data-option', value);
						let dataAttributes = [].filter.call(el.attributes, (at) => /^data-/.test(at.name));
						if (dataAttributes.length > 0) {
							dataAttributes.map((data) => {
								selectedFlag.setAttribute(data.name, data.value);
							});
						}
						this.value[value] = el;
						this.selectedField.appendChild(selectedFlag);
						el.classList.add('Pickathing-option--selected');
					} else {
						deselectMultiOption(value);
					}
				}

				if (self.filterAnother) {
					self.filterAnother.filter(self.selectedOption.getAttribute(self.filterAnotherBy), self.filterAnotherBy);
					if (!self.filterAnother.multiple
						&& self.filterAnother.selectedOption.getAttribute(self.filterAnotherBy) != self.selectedOption.getAttribute(self.filterAnotherBy)) {
						self.filterAnother.reset(true);
					}

					if (self.filterAnother.multiple) {
						self.filterAnother.reset(true);
					}
				}

				this.onChange(this.value);
			}

			if (el.classList.contains('Pickathing-selectedField')) {
				e.preventDefault();
				self.wrapper.classList.toggle('Pickathing--open');
			}

			if (el.classList.contains('Pickathing-selectedFlag')) {
				e.stopPropagation();
				if (this.wrapper.classList.contains('Pickathing--open')) {
					let flagToRemove = this.wrapper.querySelectorAll('.Pickathing-option--selected[data-option="' + el.getAttribute('data-option') + '"]');
					flagToRemove[0].classList.remove('Pickathing-option--selected');
					delete this.value[el.getAttribute('data-option')];
					el.remove();
				} else {
					this.wrapper.classList.add('Pickathing--open');
				}

				this.onChange(this.value);
			}

		});
	}
}<commit_msg>updated export file, bumped up version<commit_after>export default class Pickathing {
	constructor(elementId, hasSearch, options) {
		this.transTimeout;
		this.transTimeoutDelay = 201;

		if (options) {
			this.filterAnotherBy = options.filterAttr;
			this.filterAnother = options.filter;
			this.transTimeoutDelay = options.focusDelay + 1;
		}

		this.element = document.getElementById(elementId);
		this.parentEl = this.element.parentNode;
		this.hasSearch = typeof hasSearch === 'undefined' ? true : hasSearch;
		this.required = this.element.hasAttribute('data-required');

		this.wrapper = document.createElement('div');
		this.wrapper.className = 'Pickathing';
		this.wrapper = this.parentEl.insertBefore(this.wrapper, this.element);

		if (this.required) {
			this.wrapper.setAttribute('data-required', '');
			this.element.removeAttribute('data-required');
		}

		this.optionElements = [];
		this.options = this.element.options;
		this.selectedOption;

		this.multiple = this.element.multiple;

		if (this.multiple) {
			this.wrapper.classList.add('Pickathing--multiple');
			this.value = {};
		} else {
			this.value = this.element.value;
		}

		this.searchField;

		this.focusedOption = -1;
		if (!this.hasSearch) {
			this.focusedOption = 0;
		}
		this.focusableOptions;

		this.create();
		this.bindEvents();
	}

	create() {
		let self = this;

		this.addSelectedField();
		this.addDropdown();
		if (this.hasSearch) {
			this.addSearchField();
		}
		this.addList();

		for (let i = 0; i < this.options.length; i++) {
			self.addOption(self.options[i]);
		}

		this.focusableOptions = this.optionElements;

		this.checkSelected();
	}

	addSelectedField() {
		this.selectedField = document.createElement('div');
		this.selectedField.type = '';
		this.selectedField.setAttribute('data-client-input', '');
		this.selectedField.className = 'Pickathing-selectedField';
		this.wrapper.appendChild(this.selectedField);
	}

	addDropdown() {
		this.dropdown = document.createElement('div');
		this.dropdown.className = 'Pickathing-dropdown';
		this.wrapper.appendChild(this.dropdown);
	}

	addList() {
		this.list = document.createElement('div');
		this.list.className = 'Pickathing-list';
		this.dropdown.appendChild(this.list);
	}

	addSearchField() {
		this.searchField = document.createElement('input');
		this.searchField.type = 'text';
		this.searchField.placeholder = 'Search...';
		this.searchField.className = 'Pickathing-searchField';
		this.dropdown.appendChild(this.searchField);
	}

	addOption(option) {
		let value = option.value;
		let text = option.innerHTML;
		let element;

		if (value == '' || option.disabled) {
			element = document.createElement('button');
			element.disabled = true;
		} else {
			element = document.createElement('button');
		}

		element.innerHTML = text;
		element.className = 'Pickathing-option'
		element.setAttribute('data-option', value);
		element.setAttribute('data-label', text);

		let dataAttributes = [].filter.call(option.attributes, (at) => /^data-/.test(at.name));
		if (dataAttributes.length > 0) {
			dataAttributes.map((data) => {
				element.setAttribute(data.name, data.value);
			});
		}

		this.list.appendChild(element);
		this.optionElements.push(element);
	}

	enable() {
		this.selectedField.disabled = false;
	}

	disable() {
		this.selectedField.disabled = true;
	}

	checkSelected() {
		for (let i = 0; i < this.options.length; i++) {
			if (this.options[i].selected) {
				if (!this.multiple) {
					let label = this.optionElements[i].getAttribute('data-label');
					this.optionElements[i].classList.add('Pickathing-option--selected');
					this.selectedField.innerHTML = label;
					this.selectedOption = this.optionElements[i];

					return;
				} else {
					this.setMultiOption(this.optionElements[i]);
					this.optionElements[i].disabled = true;
				}
			}
		}
	}

	setMultiOption(option) {
		option.classList.add('Pickathing-option--selected');
		let label = option.getAttribute('data-label');
		let value = option.getAttribute('data-option');
		let selectedFlag = document.createElement('span');
		let dataAttributes = [].filter.call(option.attributes, (at) => /^data-/.test(at.name));
		if (dataAttributes.length > 0) {
			dataAttributes.map((data) => {
				selectedFlag.setAttribute(data.name, data.value);
			});
		}
		selectedFlag.classList.add('Pickathing-selectedFlag');
		selectedFlag.setAttribute('data-option', value);
		selectedFlag.innerHTML = label;
		this.selectedField.appendChild(selectedFlag);
		this.value[value] = option;
	}

	onChange() {
		// silence is golden
	}

	setOptionByIndex(index, fireOnChange) {
		let value = this.optionElements[index].getAttribute('data-option');
		let label = this.optionElements[index].getAttribute('data-label');

		this.optionElements.map((opt) => {
			opt.classList.remove('Pickathing-option--selected');
		});

		this.optionElements[index].classList.add('Pickathing-option--selected');
		this.selectedField.innerHTML = label;
		this.element.value = value;
		this.value = value;
		this.selectedOption = this.optionElements[index];

		if (typeof fireOnChange == 'undefined' || fireOnChange == true) {
			this.onChange();
		}
	}

	reset(fireOnChange) {
		if (!this.multiple) {
			this.setOptionByIndex(0, fireOnChange);
		} else {
			for (let val in this.value) {
				this.deselectMultiOption(val);
			}

			if (fireOnChange) {
				this.onChange();
			}
		}
	}

	deselectMultiOption(value) {
		let element = this.wrapper.querySelectorAll('.Pickathing-option[data-option="' + value + '"]');
		let flagToRemove = this.wrapper.querySelectorAll('.Pickathing-selectedFlag[data-option="' + value + '"]');
		flagToRemove[0].remove();
		element[0].classList.remove('Pickathing-option--selected');
		delete this.value[value];
	}

	filter(query, field) {
		this.optionElements.map((el) => {
			let label = el.getAttribute(field);
			el.style.display = 'block';
			if (label && query != null) {
				if (label.match(query)) {
					el.style.display = 'block';
				} else {
					el.style.display = 'none';
				}
			}
		});
	}

	focusNextOption() {
		if (this.optionElements.length > this.focusedOption + 1) {
			this.focusedOption += 1;
			this.focusOption();
		}
	}

	focusPreviousOption() {
		if (this.hasSearch) {
			if (this.focusedOption > -1) {
				this.focusedOption -= 1;
				if (this.focusedOption == -1) {
					this.searchField.focus();
				} else {
					this.focusOption();
				}
			}
		} else {
			if (this.focusedOption > 0) {
				this.focusedOption -= 1;
				this.focusOption();
			}
		}
	}

	focusOption() {
		this.focusableOptions[this.focusedOption].focus();
	}

	toggleState() {
		let self = this;
		self.wrapper.classList.toggle('Pickathing--open');
		if (this.hasSearch) {
			this.focusedOption = -1;
		} else {
			this.focusedOption = 0;
		}
		if (self.hasSearch) {
			clearTimeout(self.transTimeout);
			self.transTimeout = setTimeout(() => {
				self.searchField.focus();
			}, self.transTimeoutDelay);
		} else {
			clearTimeout(self.transTimeout);
			self.transTimeout = setTimeout(() => {
				self.focusableOptions[0].focus();
			}, self.transTimeoutDelay);
		}
	}

	bindEvents() {
		let self = this;
		if (this.hasSearch) {
			this.searchField.addEventListener('keyup', (e) => {
				let query = new RegExp(self.searchField.value, 'gi');
				self.filter(query, 'data-label');
			});
		}

		document.addEventListener('click', (e) => {
			let el = e.target;

			if (el != this.selectedField && el != this.searchField) {
				if (el.classList.contains('Pickathing-option') && this.multiple) {
					// do nothing
				} else {
					this.wrapper.classList.remove('Pickathing--open');
				}
			}
		});

		this.wrapper.addEventListener('click', (e) => {
			let el = e.target;
			if (el.classList.contains('Pickathing-option')) {

				if (!this.multiple) {
					self.wrapper.classList.remove('Pickathing--open');
				}

				let value = el.getAttribute('data-option');
				let label = el.getAttribute('data-label');

				this.focusedOption = this.focusableOptions.indexOf(el);

				if (!this.multiple) {
					this.optionElements.map((opt) => {
						opt.classList.remove('Pickathing-option--selected');
					});
					el.classList.add('Pickathing-option--selected');
					this.selectedOption = el;
					this.selectedField.innerHTML = label;
					this.element.value = value;
					this.value = value;
				} else {
					if (!el.classList.contains('Pickathing-option--selected')) {
						let selectedFlag = document.createElement('span');
						selectedFlag.classList.add('Pickathing-selectedFlag');
						selectedFlag.innerHTML = label;
						selectedFlag.setAttribute('data-option', value);
						let dataAttributes = [].filter.call(el.attributes, (at) => /^data-/.test(at.name));
						if (dataAttributes.length > 0) {
							dataAttributes.map((data) => {
								selectedFlag.setAttribute(data.name, data.value);
							});
						}
						this.value[value] = el;
						this.selectedField.appendChild(selectedFlag);
						el.classList.add('Pickathing-option--selected');
					} else {
						this.deselectMultiOption(value);
					}
				}

				if (self.filterAnother) {
					self.filterAnother.filter(self.selectedOption.getAttribute(self.filterAnotherBy), self.filterAnotherBy);
					if (!self.filterAnother.multiple
						&& self.filterAnother.selectedOption.getAttribute(self.filterAnotherBy) != self.selectedOption.getAttribute(self.filterAnotherBy)) {
						self.filterAnother.reset(true);
					}

					if (self.filterAnother.multiple) {
						self.filterAnother.reset(true);
					}
				}

				this.onChange(this.value);
			}

			if (el.classList.contains('Pickathing-selectedField')) {
				e.preventDefault();
				this.toggleState();
			}

			if (el.classList.contains('Pickathing-selectedFlag')) {
				e.stopPropagation();
				if (this.wrapper.classList.contains('Pickathing--open')) {
					let flagToRemove = this.wrapper.querySelectorAll('.Pickathing-option--selected[data-option="' + el.getAttribute('data-option') + '"]');
					flagToRemove[0].classList.remove('Pickathing-option--selected');
					delete this.value[el.getAttribute('data-option')];
					el.remove();
				} else {
					this.wrapper.classList.add('Pickathing--open');
				}

				this.onChange(this.value);
			}

		});

		this.wrapper.addEventListener('keyup', (e) => {
			e.preventDefault();
			if (e.which == 40) { // down arrow
				this.focusNextOption();
			} else if (e.which == 38) { // up arrow
				e.preventDefault();
				this.focusPreviousOption();
			} else if (e.which == 27) {
				this.toggleState();
			}
		})
	}
}<|endoftext|>


<commit_before>import {Vector3} from 'three';

import {Loop} from '../../core/Loop';
import {ThreeOrbitControls} from './lib/ThreeOrbitControls';

export class OrbitModule {
  constructor(params = {}) {
    this.params = Object.assign({
      target: new Vector3(0, 0, 0),
      follow: false
    }, params);
  }

  manager(manager) {
    this.controls = new ThreeOrbitControls(
      manager.get('camera').native,
      manager.get('renderer').domElement
    );

    manager.update({
      camera: (camera) => {
        this.controls.object = camera.native;
      }
    });
  }

  integrate(self) {
    const {params, controls} = self;

    const updateProcessor = params.follow ? (c) => {
      controls.update(c.getDelta());
      controls.target.copy(params.target);
    } : (c) => {
      controls.update(c.getDelta());
    };

    self.updateLoop = new Loop(updateProcessor).start(this);

    controls.target.copy(params.target);
  }
}
<commit_msg>CSF. OrbitModule<commit_after>import {Vector3} from 'three';

import {Loop} from '../../core/Loop';
import {ThreeOrbitControls} from './lib/ThreeOrbitControls';

export class OrbitModule {
  constructor(params = {}) {
    this.params = Object.assign({
      target: new Vector3(0, 0, 0),
      follow: false
    }, params);
  }

  manager(manager) {
    this.controls = new ThreeOrbitControls(
      manager.get('camera').native,
      manager.get('renderer').domElement
    );

    manager.update({
      camera: camera => {
        this.controls.object = camera.native;
      }
    });
  }

  integrate(self) {
    const {params, controls} = self;

    const updateProcessor = params.follow ? c => {
      controls.update(c.getDelta());
      controls.target.copy(params.target);
    } : c => {
      controls.update(c.getDelta());
    };

    self.updateLoop = new Loop(updateProcessor).start(this);

    controls.target.copy(params.target);
  }
}
<|endoftext|>


<commit_before>var PromiseConstructor = typeof Promise === 'undefined' ? require('promise') : Promise,
    contexts = require("./contexts"),
    Parser = require('./parser/parser'),
    PluginManager = require('./plugin-manager');

module.exports = function(environment, ParseTree, ImportManager) {
    var render = function (input, options, callback) {
        options = options || {};

        if (typeof(options) === 'function') {
            callback = options;
            options = {};
        }

        if (callback) {
            render.call(this, input, options)
                .then(function(css) {
                    callback(null, css);
                },
                function(error) {
                    callback(error);
                });
        } else {
            var context,
                rootFileInfo,
                pluginManager = new PluginManager(this);

            pluginManager.addPlugins(options.plugins);
            options.pluginManager = pluginManager;

            context = new contexts.Parse(options);

            if (options.rootFileInfo) {
                rootFileInfo = options.rootFileInfo;
            } else {
                var filename = options.filename || "input";
                var entryPath = filename.replace(/[^\/\\]*$/, "");
                rootFileInfo = {
                    filename: filename,
                    relativeUrls: context.relativeUrls,
                    rootpath: context.rootpath || "",
                    currentDirectory: entryPath,
                    entryPath: entryPath,
                    rootFilename: filename
                };
            }

            var imports = new ImportManager(context, rootFileInfo);
            var parser = new Parser(context, imports, rootFileInfo);

            return new PromiseConstructor(function (resolve, reject) {
                parser.parse(input, function (e, root) {
                    if (e) { return reject(e); }
                    try {
                        var parseTree = new ParseTree(root, imports);
                        var result = parseTree.toCSS(options);
                        resolve(result);
                    }
                    catch (err) { reject( err); }
                }, options);
            });
        }
    };
    return render;
};
<commit_msg>fix rootpath without / at the end handling<commit_after>var PromiseConstructor = typeof Promise === 'undefined' ? require('promise') : Promise,
    contexts = require("./contexts"),
    Parser = require('./parser/parser'),
    PluginManager = require('./plugin-manager');

module.exports = function(environment, ParseTree, ImportManager) {
    var render = function (input, options, callback) {
        options = options || {};

        if (typeof(options) === 'function') {
            callback = options;
            options = {};
        }

        if (callback) {
            render.call(this, input, options)
                .then(function(css) {
                    callback(null, css);
                },
                function(error) {
                    callback(error);
                });
        } else {
            var context,
                rootFileInfo,
                pluginManager = new PluginManager(this);

            pluginManager.addPlugins(options.plugins);
            options.pluginManager = pluginManager;

            context = new contexts.Parse(options);

            if (options.rootFileInfo) {
                rootFileInfo = options.rootFileInfo;
            } else {
                var filename = options.filename || "input";
                var entryPath = filename.replace(/[^\/\\]*$/, "");
                rootFileInfo = {
                    filename: filename,
                    relativeUrls: context.relativeUrls,
                    rootpath: context.rootpath || "",
                    currentDirectory: entryPath,
                    entryPath: entryPath,
                    rootFilename: filename
                };
            }

            if (rootFileInfo.rootpath && rootFileInfo.rootpath.slice(-1) !== "/")
                rootFileInfo.rootpath += "/";

            var imports = new ImportManager(context, rootFileInfo);
            var parser = new Parser(context, imports, rootFileInfo);

            return new PromiseConstructor(function (resolve, reject) {
                parser.parse(input, function (e, root) {
                    if (e) { return reject(e); }
                    try {
                        var parseTree = new ParseTree(root, imports);
                        var result = parseTree.toCSS(options);
                        resolve(result);
                    }
                    catch (err) { reject( err); }
                }, options);
            });
        }
    };
    return render;
};
<|endoftext|>


<commit_before>// NodeMCU Handler
goog.provide('bounce.Nodemcu');
goog.provide('bounce.Nodemcu.scan');

goog.require('goog.string');
goog.require('goog.async.Delay');

/**
 * Class to handle the interactions with the NodeMCU device
 *
 * @param output_console to write output to
 * @param serial_port_path The serial port to make this with.
 *
 * @constructor
 */
bounce.Nodemcu = function(serial_port_path, output_console) {
    this.port = serial_port_path;

    this.disconnect = function() {
        hrome.serial.disconnect(this.connection_info.connectionId);
    };

    this.connect = function (connected) {
        chrome.serial.connect(serial_port_path, {bitrate: 9600}, connected);
    };

    this.array_buffer_to_string = function(buffer_data) {
        var str = '';
        for (var i=0; i<buffer_data.length; i++) {
            str += String.fromCharCode(buffer_data[i]);
        }
        return str;
    };

    this.string_to_array_buffer = function(string_data) {
        var buf=new ArrayBuffer(string_data.length);
        var bufView=new Uint8Array(buf);
        for (var i=0; i<string_data.length; i++) {
            bufView[i]=string_data.charCodeAt(i);
      }
      return buf;
    };

    this.send_data = function(data) {
        chrome.serial.send(this.connection_info.connectionId, this.string_to_array_buffer(data), function(){});
        chrome.serial.flush(this.connection_info.connectionId, function() {});
    };

    var string_received = "";

    this.receive_callback=function(info) {
        if(info.connectionId == this.connection_info.connectionId && info.data) {
            var str = this.array_buffer_to_string(info.data);
            output_console.write(str);
            if (str.charAt(str.length-1) === '\n') {
                this.string_received += str.substring(0, str.length-1);
                this.on_line_received(this.string_received);
                this.string_received = '';
            } else {
                this.string_received += str;
            }
        }
    };

    this.validate = function(found_callback) {
        var node_instance = this;
        this.connect(function(connectionInfo) {
            node_instance.connection_info = connectionInfo;
            chrome.serial.onReceive.addListener(node_instance.receive_callback);
            // We need two events here:
                // - A receive - the node response confirms it - cancel the timeout.
                // - A timeout - it didn't respond confirming - disconnect the port.
            var timeout = new goog.async.Delay(function() {
                node_instance.disconnect();
            }, 2000);

            this.on_line_received = function(line) {
                if(goog.string.contains(line, 'node mcu confirmed')) {
                    found_callback(node_instance);
                    timeout.stop();
                }
            };
            node_instance.send_data("print('node mcu confirmed')\n");

        });
    };
};

/**
 * Scan for NodeMCU boards connected
 *
 * @param found_callback Called when it's found with the Serial path.
 * @param comsole - output goes here.
 */
bounce.Nodemcu.scan = function(console, found_callback) {
    console.writeLine("Starting scan...");
    var onGetDevices = function(ports) {
        for (var i = 0; i < ports.length; i++) {
            console.writeLine('Found serial port ' + ports[i].path + '. Testing...');
            var mcu = new bounce.Nodemcu(ports[i].path, console);
            mcu.validate(found_callback);
        }
    };

    chrome.serial.getDevices(onGetDevices);
};<commit_msg>We've confirmed two way communication!<commit_after>// NodeMCU Handler
goog.provide('bounce.Nodemcu');
goog.provide('bounce.Nodemcu.scan');

goog.require('goog.string');
goog.require('goog.async.Delay');

// Utility bits

var array_buffer_to_string = function(buffer_data) {
    return String.fromCharCode.apply(null, new Uint8Array(buffer_data));
};

var string_to_array_buffer = function(string_data) {
    var buf=new ArrayBuffer(string_data.length);
    var bufView=new Uint8Array(buf);
    for (var i=0; i<string_data.length; i++) {
        bufView[i]=string_data.charCodeAt(i);
  }
  return buf;
};

/**
 * Class to handle the interactions with the NodeMCU device
 *
 * @param output_console to write output to
 * @param serial_port_path The serial port to make this with.
 *
 * @constructor
 */
bounce.Nodemcu = function(serial_port_path, output_console) {
    this.port = serial_port_path;
    this.on_line_received = null; // Set this to get callbacks for each line?
    var _connection_info = null; //If connected - the chrome connection info.
    var _received_str = '';
    var _node_instance = this;
    /**
     * Listener for data - assembling into lines.
     * @param info
     * @private
     */
    function _data_received(info) {
        if(info.connectionId == _connection_info.connectionId && info.data) {
            var str = array_buffer_to_string(info.data);
            output_console.write(str);
            if (str.charAt(str.length-1) === '\n') {
                _received_str += str.substring(0, str.length-1);
                _node_instance.on_line_received(_received_str);
                _received_str = '';
            } else {
                _received_str += str;
            }
        }
    }

    function _setup_data_listener() {
        chrome.serial.onReceive.addListener(_data_received);
    }

    this.connect = function (connected_callback) {
        function connected_inner(connectionInfo) {
            _connection_info = connectionInfo;
            _setup_data_listener();
            connected_callback();
        }
        output_console.writeLine("Connecting to device on " + serial_port_path);
        chrome.serial.connect(serial_port_path, {bitrate: 9600}, connected_inner);
    };

    this.disconnect = function(disconnected_calback) {
        chrome.serial.onReceive.removeListener(_data_received);
        chrome.serial.disconnect(_connection_info.connectionId, disconnected_calback);
    };

    /**
     *
     * @param data Data to send to the device. Always flushed for now.
     */
    this.send_data = function(data) {
        chrome.serial.send(_connection_info.connectionId, string_to_array_buffer(data), function(){});
        chrome.serial.flush(_connection_info.connectionId, function() {});
    };

    this.validate = function(found_callback) {
        // Validate by attempting a connection
        output_console.writeLine("Attempting connection");
        this.connect(function() {
            output_console.writeLine("Connected");
            // We need two events here:
            // - A timeout - it didn't respond confirming - disconnect the port.
            var timeout = new goog.async.Delay(function() {
                output_console.writeLine("Timed out - not running NodeMCU");
                _node_instance.disconnect();
            }, 2000);
            // - A receive - the node response confirms it - cancel the timeout.
            _node_instance.on_line_received = function(line) {
                if(goog.string.contains(line, 'node mcu confirmed')) {
                    output_console.writeLine("Confirmed - NodeMCU found");
                    _node_instance.disconnect(found_callback);
                    timeout.stop();
                }
            };
            output_console.writeLine("Sending confirmation test");
            _node_instance.send_data("print('node mcu confirmed')\n");
        });
    };
};

/**
 * Scan for NodeMCU boards connected
 *
 * @param found_callback Called when it's found with the Serial path.
 * @param console - output goes here.
 */
bounce.Nodemcu.scan = function(console, found_callback) {
    console.writeLine("Starting scan...");
    var onGetDevices = function(ports) {
        for (var i = 0; i < ports.length; i++) {
            console.writeLine('Found serial port ' + ports[i].path + '. Testing...');
            var mcu = new bounce.Nodemcu(ports[i].path, console);
            mcu.validate(found_callback);
        }
    };

    chrome.serial.getDevices(onGetDevices);
};
<|endoftext|>


<commit_before>var fs = require('fs');
var mkdirp = require('mkdirp');

function linkModules(opts, toDir, dirName) {
  mkdirp.sync(toDir);
  copyWebpackModules(opts, toDir);
}

function copyWebpackModules(opts, toDir) {
  var fromDir = __dirname + '/../../..';
  console.warn("fromDir: " + fromDir);
  console.warn("toDir: " + toDir);
  var modules = require(fromDir + '/package.json').dependencies;

  Object.keys(modules).forEach(function(packageName) {
    var srcModule = fromDir + '/node_modules/' + packageName;
    var destModule = toDir + '/' + packageName;

    if (!fs.existsSync(srcModule)) {
      if (opts.debug) {
        console.warn("Doesn't exist: " + srcModule);
        console.warn('Error! Make sure you have run npm install in reapp-pack');
      }
    }
    else {
      if (!fs.existsSync(destModule)) {
        try {
          fs.symlinkSync(srcModule, destModule, 'dir');
        }
        catch (e) {
          console.log('Error', e);
          console.log("This may be because your server_modules isn't linked properly, try wiping ./server_modules and running again.");
        }
      }
    }
  });
}

module.exports = linkModules;<commit_msg>remove console warns.<commit_after>var fs = require('fs');
var mkdirp = require('mkdirp');

function linkModules(opts, toDir, dirName) {
  mkdirp.sync(toDir);
  copyWebpackModules(opts, toDir);
}

function copyWebpackModules(opts, toDir) {
  var fromDir = __dirname + '/../../..';
  var modules = require(fromDir + '/package.json').dependencies;

  Object.keys(modules).forEach(function(packageName) {
    var srcModule = fromDir + '/node_modules/' + packageName;
    var destModule = toDir + '/' + packageName;

    if (!fs.existsSync(srcModule)) {
      if (opts.debug) {
        console.warn("Doesn't exist: " + srcModule);
        console.warn('Error! Make sure you have run npm install in reapp-pack');
      }
    }
    else {
      if (!fs.existsSync(destModule)) {
        try {
          fs.symlinkSync(srcModule, destModule, 'dir');
        }
        catch (e) {
          console.log('Error', e);
          console.log("This may be because your server_modules isn't linked properly, try wiping ./server_modules and running again.");
        }
      }
    }
  });
}

module.exports = linkModules;<|endoftext|>


<commit_before>'use strict';
/**
 * List all deployed aliases
 */

const BbPromise = require('bluebird');
const _ = require('lodash');
const chalk = require('chalk');

module.exports = {

	listDescribeStack(stackName) {

		return this._provider.request('CloudFormation',
			'describeStackResources',
			{ StackName: stackName },
			this._options.stage,
			this._options.region);
	},

	listAliases() {

		console.log(chalk.yellow('aliases:'));

		return BbPromise.join(
			BbPromise.bind(this).then(this.aliasStackLoadCurrentTemplate),
			BbPromise.bind(this).then(this.aliasStackLoadAliasTemplates)
		)
		.spread((currentTemplate, aliasStackTemplates) => {
			return BbPromise.mapSeries(aliasStackTemplates, aliasTemplate => {

				const aliasName = _.get(aliasTemplate, 'Outputs.ServerlessAliasName.Value');
				if (aliasName) {
					console.log(chalk.white(`  ${aliasName}`));

					if (this._options.verbose) {
						return this.listDescribeStack(`${this._provider.naming.getStackName()}-${aliasName}`)
						.then(resources => {
							const versions = _.filter(resources.StackResources, [ 'ResourceType', 'AWS::Lambda::Version' ]);

							console.log(chalk.white('    Functions:'));
							_.forEach(versions, version => {
								const functionName = /:function:(.*):/.exec(version.PhysicalResourceId)[1];
								const functionVersion = _.last(version.PhysicalResourceId.split(':'));

								console.log(chalk.yellow(`      ${functionName} -> ${functionVersion}`));
							});

							return BbPromise.resolve();
						});
					}
				}
			});
		});
	}

};
<commit_msg>Issue #2 Prepare APIG info output<commit_after>'use strict';
/**
 * List all deployed aliases
 */

const BbPromise = require('bluebird');
const _ = require('lodash');
const chalk = require('chalk');

/* eslint no-console: "off" */

module.exports = {

	listDescribeApiStage(apiId, stageName) {

		if (!apiId) {
			return BbPromise.resolve(null);
		}

		return this._provider.request('APIGateway',
			'getStage',
			{
				restApiId: apiId,
				stageName: stageName
			},
			this._options.stage,
			this._options.region)
		.then(stage => {
			return this._provider.request('APIGateway',
				'getDeployment',
				{
					restApiId: apiId,
					deploymentId: stage.deploymentId
				},
				this._options.stage,
				this._options.region);
		})
		.catch(err => {
			if (/^Invalid stage/.test(err.message)) {
				return BbPromise.resolve(null);
			}
			return BbPromise.reject(err);
		});
	},

	listDescribeStack(stackName) {

		return this._provider.request('CloudFormation',
			'describeStackResources',
			{ StackName: stackName },
			this._options.stage,
			this._options.region);
	},

	listGetApiId(stackName) {

		return this._provider.request('CloudFormation',
			'describeStackResource',
			{
				LogicalResourceId: 'ApiGatewayRestApi',
				StackName: stackName
			},
			this._options.stage,
			this._options.region)
		.then(cfData => cfData.StackResourceDetail.PhysicalResourceId)
		.catch(() => BbPromise.resolve(null));
	},

	listAliases() {

		console.log(chalk.yellow('aliases:'));

		return BbPromise.join(
			BbPromise.bind(this).then(this.aliasStackLoadAliasTemplates),
			this.listGetApiId(this._provider.naming.getStackName())
		)
		.spread((aliasStackTemplates, apiId) => {
			return BbPromise.mapSeries(aliasStackTemplates, aliasTemplate => {

				const aliasName = _.get(aliasTemplate, 'Outputs.ServerlessAliasName.Value');
				if (aliasName) {
					console.log(chalk.white(`  ${aliasName}`));

					if (this._options.verbose) {
						return BbPromise.join(
							this.listDescribeStack(`${this._provider.naming.getStackName()}-${aliasName}`),
							this.listDescribeApiStage(apiId, aliasName)
						)
						.spread((resources /*, apiStage */) => {
							const versions = _.filter(resources.StackResources, [ 'ResourceType', 'AWS::Lambda::Version' ]);

							console.log(chalk.white('    Functions:'));
							_.forEach(versions, version => {
								const functionName = /:function:(.*):/.exec(version.PhysicalResourceId)[1];
								const functionVersion = _.last(version.PhysicalResourceId.split(':'));

								console.log(chalk.yellow(`      ${functionName} -> ${functionVersion}`));

								// Print deployed endpoints for the function
								// FIXME: Check why APIG getStage and getDeployment do not return the stage API layout.

							});

							return BbPromise.resolve();
						});
					}
				}
			});
		});
	}

};
<|endoftext|>


<commit_before>/*
 * Copyright (c) Maximilian Antoni <max@javascript.studio>
 */
'use strict';

const request = require('./request');

const BUILD_STATUS = {
  CREATED: 'Build pending',
  ANALYZING: 'Analyzing',
  ERROR: 'Build error',
  FAILED: 'Build completed with issues',
  SUCCESS: 'Build completed'
};
const STATUS_TIMEOUTS = {
  CREATED: 15000,
  ANALYZING: 35000
};
const FINAL = {
  ERROR: true,
  FAILED: true,
  SUCCESS: true
};
const SYMBOLS = {
  ERROR: '🚨 ',
  FAILED: '⚠ ',
  SUCCESS: '✅ '
};

module.exports = function (config, report_number, argv, spinner, callback) {

  const start = Date.now();
  let delay = 250;
  let path = `/uploads/${report_number}`;
  if (argv.exceptions) {
    path += '?exceptions=1';
  }

  function load_report() {
    request(config, {
      path,
      timeout: 5000,
      expect: 200
    }, null, (err, json) => {
      if (err) {
        callback(err);
        return;
      }

      const status = BUILD_STATUS[json.status];
      if (!status) {
        throw new Error(`Unknown build status "${json.status}"`);
      }

      spinner.text = status;

      if (FINAL[json.status]) {
        spinner.stopAndPersist({
          symbol: SYMBOLS[json.status]
        });
        callback(null, json);
      } else if (Date.now() - start > STATUS_TIMEOUTS[json.status]) {
        callback(new Error('Timeout'));
      } else {
        delay = Math.min(delay * 2, 4000);
        setTimeout(load_report, delay);
      }
    });
  }

  setTimeout(load_report, delay);
};
<commit_msg>Increase timeout for `CREATED` builds<commit_after>/*
 * Copyright (c) Maximilian Antoni <max@javascript.studio>
 */
'use strict';

const request = require('./request');

const BUILD_STATUS = {
  CREATED: 'Build pending',
  ANALYZING: 'Analyzing',
  ERROR: 'Build error',
  FAILED: 'Build completed with issues',
  SUCCESS: 'Build completed'
};
const STATUS_TIMEOUTS = {
  CREATED: 35000,
  ANALYZING: 35000
};
const FINAL = {
  ERROR: true,
  FAILED: true,
  SUCCESS: true
};
const SYMBOLS = {
  ERROR: '🚨 ',
  FAILED: '⚠ ',
  SUCCESS: '✅ '
};

module.exports = function (config, report_number, argv, spinner, callback) {

  const start = Date.now();
  let delay = 250;
  let path = `/uploads/${report_number}`;
  if (argv.exceptions) {
    path += '?exceptions=1';
  }

  function load_report() {
    request(config, {
      path,
      timeout: 5000,
      expect: 200
    }, null, (err, json) => {
      if (err) {
        callback(err);
        return;
      }

      const status = BUILD_STATUS[json.status];
      if (!status) {
        throw new Error(`Unknown build status "${json.status}"`);
      }

      spinner.text = status;

      if (FINAL[json.status]) {
        spinner.stopAndPersist({
          symbol: SYMBOLS[json.status]
        });
        callback(null, json);
      } else if (Date.now() - start > STATUS_TIMEOUTS[json.status]) {
        callback(new Error('Timeout'));
      } else {
        delay = Math.min(delay * 2, 4000);
        setTimeout(load_report, delay);
      }
    });
  }

  setTimeout(load_report, delay);
};
<|endoftext|>


<commit_before>({
    /*******************************************************************************
    * @description Receives an event from lightning web component geTemplateBuilder
    * to open a modal using the aura overlay library. We're opting to use this library
    * to get out-of-the-box acccessibility modal features like focus trapping,
    * input focus, and tabbing.
    *
    * In the then() method of the showCustomModal promise, we register
    * an event listener for custom event 'geTemplateBuilderSectionModalBodyEvent' which gets
    * dispatched from the modal's body lightning web component 'geTemplateBuilderSectionModalBody'.
    */
    handleShowModal: function (component, event, helper) {
        $A.createComponents([
            ["c:geTemplateBuilderSectionModalBody", { modalData: event.getParams('section') }]
        ],
            function (components, status, errorMessage) {
                if (status === "SUCCESS") {
                    const modalBody = components[0];

                    let modalReference = component.find('overlayLib').showCustomModal({
                        header: 'Section Settings',
                        body: modalBody,
                        showCloseButton: true,
                        cssClass: component.getName() + ' customModal'
                    });

                    component.set('v.modal', modalReference);
                }
            }
        );
    },

    /*******************************************************************************
    * @description Action for the aura change handler on the attribute
    * 'sectionBeingEdited'. Fires a public method 'notify' on the lightning web component
    * geTemplateBuilder and passes that change down to be handled there.
    */
    handleSectionModalEvent: function (component, event, helper) {
        const details = event.getParams();

        if (details.action === 'delete' || details.action === 'save') {
            component.find('templateBuilder').notify(details);
        }

        component.get('v.modal').then(modal => {
            modal.close();
        });
    }
})<commit_msg>Update src/aura/GE_TemplateBuilder/GE_TemplateBuilderController.js<commit_after>({
    /*******************************************************************************
    * @description Receives an event from lightning web component geTemplateBuilder
    * to open a modal using the aura overlay library. We're opting to use this library
    * to get out-of-the-box accessibility modal features like focus trapping,
    * input focus, and tabbing.
    *
    * In the then() method of the showCustomModal promise, we register
    * an event listener for custom event 'geTemplateBuilderSectionModalBodyEvent' which gets
    * dispatched from the modal's body lightning web component 'geTemplateBuilderSectionModalBody'.
    */
    handleShowModal: function (component, event, helper) {
        $A.createComponents([
            ["c:geTemplateBuilderSectionModalBody", { modalData: event.getParams('section') }]
        ],
            function (components, status, errorMessage) {
                if (status === "SUCCESS") {
                    const modalBody = components[0];

                    let modalReference = component.find('overlayLib').showCustomModal({
                        header: 'Section Settings',
                        body: modalBody,
                        showCloseButton: true,
                        cssClass: component.getName() + ' customModal'
                    });

                    component.set('v.modal', modalReference);
                }
            }
        );
    },

    /*******************************************************************************
    * @description Action for the aura change handler on the attribute
    * 'sectionBeingEdited'. Fires a public method 'notify' on the lightning web component
    * geTemplateBuilder and passes that change down to be handled there.
    */
    handleSectionModalEvent: function (component, event, helper) {
        const details = event.getParams();

        if (details.action === 'delete' || details.action === 'save') {
            component.find('templateBuilder').notify(details);
        }

        component.get('v.modal').then(modal => {
            modal.close();
        });
    }
})
<|endoftext|>


<commit_before>import { h, Component } from 'preact' /** @jsx h */
import { ViewPager, Frame, Track, View, AnimatedView } from 'react-view-pager'
import {
  ButtonPrimary,
  MemorySummary,
  Quote,
  SectionHeader,
  SectionPrimary,
} from '~src/views/components'
import * as paths from '~src/paths'
import './slider.scss'

const Memory = ({ memory }) => (

    <MemorySummary
      name={memory.victimName}
      owner={memory.ownerFirstName}
      birthYear={memory.victimBornAt}
      deathYear={memory.victimDeadAt}
      description={memory.victimHistory}
      image={`${process.env.SERVER_DOMAIN}${memory.victimPhoto}`}
      imageWidth="164px"
      imageHeight="132px"
      imageAlignment="left"
      distanceY="100px"
      distanceX="36%"
      width="63%"
    />
    <Quote>
      {memory.victimRememberText}
    </Quote>
    <ButtonPrimary href={paths.memory(memory.id)}>
      Ver homenagem completa
    </ButtonPrimary>

)

class FeaturedMemoriesSection extends Component {
  constructor(props) {
    super(props)
    this.state = {
      currentView: 0,
    }
  }

  render() {
    const { loading, memories, className } = this.props
    return loading ? null : (
      <SectionPrimary
        className={`section--featured-memories ${className}`}
        header={<SectionHeader title="Homenagens" />}
      >
        <ViewPager>
          <Frame className="frame" autoSize="height">
            <Track
              infinite
              viewsToShow={1}
              className="track"
              ref={(track) => { this.track = track }}
              onViewChange={(indicies) => {
                this.setState({ currentView: indicies[0] })
              }}
            >
              {memories.map(memory => (
                <View className="view">

                      <div
                        className="image"
                        style={{
                          backgroundImage: `url('${process.env.SERVER_DOMAIN}${memory.victimPhoto}')`,
                          width: 164,
                          height: 132,
                          left: 0,
                        }}
                      />

{memory.victimName}

                            {memory.victimBornAt} / {memory.victimDeadAt}

Homenageada por: {memory.ownerFirstName}

                            {memory.victimHistory.substring(0, 50) + (memory.victimHistory.length > 50 ? '...' : '')}

                      {memory.victimRememberText.substring(0, 100) + (memory.victimRememberText.length > 100 ? '...' : '')}

                </View>
              ))}
            </Track>
          </Frame>

            {Array(memories.length).fill('').map((element, index) => (
              <button
                type="button"
                className={`pager-control ${this.state.currentView === index ? 'active' : ''}`}
                onClick={() => this.track.scrollTo(index)}
              >
                {index + 1}
              </button>
            ))}

          <a
            type="button"
            className="button-primary"
            href={`/memory/${newMemories[this.state.currentView].id}`}
          >
            Ver homenagem completa

        </ViewPager>
      </SectionPrimary>
    )
  }
}

FeaturedMemoriesSection.defaultProps = {
  className: '',
}

export default FeaturedMemoriesSection
<commit_msg>fix typo 2<commit_after>import { h, Component } from 'preact' /** @jsx h */
import { ViewPager, Frame, Track, View, AnimatedView } from 'react-view-pager'
import {
  ButtonPrimary,
  MemorySummary,
  Quote,
  SectionHeader,
  SectionPrimary,
} from '~src/views/components'
import * as paths from '~src/paths'
import './slider.scss'

const Memory = ({ memory }) => (

    <MemorySummary
      name={memory.victimName}
      owner={memory.ownerFirstName}
      birthYear={memory.victimBornAt}
      deathYear={memory.victimDeadAt}
      description={memory.victimHistory}
      image={`${process.env.SERVER_DOMAIN}${memory.victimPhoto}`}
      imageWidth="164px"
      imageHeight="132px"
      imageAlignment="left"
      distanceY="100px"
      distanceX="36%"
      width="63%"
    />
    <Quote>
      {memory.victimRememberText}
    </Quote>
    <ButtonPrimary href={paths.memory(memory.id)}>
      Ver homenagem completa
    </ButtonPrimary>

)

class FeaturedMemoriesSection extends Component {
  constructor(props) {
    super(props)
    this.state = {
      currentView: 0,
    }
  }

  render() {
    const { loading, memories, className } = this.props
    return loading ? null : (
      <SectionPrimary
        className={`section--featured-memories ${className}`}
        header={<SectionHeader title="Homenagens" />}
      >
        <ViewPager>
          <Frame className="frame" autoSize="height">
            <Track
              infinite
              viewsToShow={1}
              className="track"
              ref={(track) => { this.track = track }}
              onViewChange={(indicies) => {
                this.setState({ currentView: indicies[0] })
              }}
            >
              {memories.map(memory => (
                <View className="view">

                      <div
                        className="image"
                        style={{
                          backgroundImage: `url('${process.env.SERVER_DOMAIN}${memory.victimPhoto}')`,
                          width: 164,
                          height: 132,
                          left: 0,
                        }}
                      />

{memory.victimName}

                            {memory.victimBornAt} / {memory.victimDeadAt}

Homenageada por: {memory.ownerFirstName}

                            {memory.victimHistory.substring(0, 50) + (memory.victimHistory.length > 50 ? '...' : '')}

                      {memory.victimRememberText.substring(0, 100) + (memory.victimRememberText.length > 100 ? '...' : '')}

                </View>
              ))}
            </Track>
          </Frame>

            {Array(memories.length).fill('').map((element, index) => (
              <button
                type="button"
                className={`pager-control ${this.state.currentView === index ? 'active' : ''}`}
                onClick={() => this.track.scrollTo(index)}
              >
                {index + 1}
              </button>
            ))}

          <a
            type="button"
            className="button-primary"
            href={`/memory/${memories[this.state.currentView].id}`}
          >
            Ver homenagem completa

        </ViewPager>
      </SectionPrimary>
    )
  }
}

FeaturedMemoriesSection.defaultProps = {
  className: '',
}

export default FeaturedMemoriesSection
<|endoftext|>


<commit_before>import findUserWebpackConfig from '../findUserWebpackConfig';

const cwd = process.cwd();
afterEach(() => {
	process.chdir(cwd);
});

it('should return path to create-react-app Webpack config', () => {
	process.chdir('test/apps/cra');
	const result = findUserWebpackConfig();
	console.error('CWD1: ' + result + '\nCWD1: ' + process.cwd());  // eslint-disable-line no-console
	expect(result).toMatch(/^react-scripts\//);
});

it('should return an absolute path to user Webpack config located in project root folder', () => {
	process.chdir('test/apps/basic');
	const result = findUserWebpackConfig();
	console.error('CWD2: ' + result + '\nCWD2: ' + process.cwd());  // eslint-disable-line no-console
	expect(result).toMatch(/^\//);
	expect(result).toMatch(/webpack.config.js$/);
});

it('should return an absolute path to user Webpack config located in nested folder', () => {
	process.chdir('test/apps/webpack-nested');
	const result = findUserWebpackConfig();
	console.error('CWD3: ' + result + '\nCWD3: ' + process.cwd());  // eslint-disable-line no-console
	expect(result).toMatch(/^\//);
	expect(result).toMatch(/webpack.config.js$/);
});
<commit_msg>Test: Remove debug info<commit_after>import findUserWebpackConfig from '../findUserWebpackConfig';

const cwd = process.cwd();
afterEach(() => {
	process.chdir(cwd);
});

it('should return path to create-react-app Webpack config', () => {
	process.chdir('test/apps/cra');
	const result = findUserWebpackConfig();
	expect(result).toMatch(/^react-scripts\//);
});

it('should return an absolute path to user Webpack config located in project root folder', () => {
	process.chdir('test/apps/basic');
	const result = findUserWebpackConfig();
	expect(result).toMatch(/^\//);
	expect(result).toMatch(/webpack.config.js$/);
});

it('should return an absolute path to user Webpack config located in nested folder', () => {
	process.chdir('test/apps/webpack-nested');
	const result = findUserWebpackConfig();
	expect(result).toMatch(/^\//);
	expect(result).toMatch(/webpack.config.js$/);
});
<|endoftext|>


<commit_before>
var HangarXPLOR = HangarXPLOR || {};

HangarXPLOR.Filter = function(list, filter)
{
  switch (filter) {
    case "HasLTI":
      list = $.grep(list, function(item) { return item.hasLTI; });
      break;
    case "!HasLTI":
      list = $.grep(list, function(item) { return !item.hasLTI; });
      break;
    case "IsGiftable":
      list = $.grep(list, function(item) { return item.isGiftable; });
      break;
    case "!IsGiftable":
      list = $.grep(list, function(item) { return !item.isGiftable; });
      break;
    case "IsShip":
      list = $.grep(list, function(item) { return item.isShip && !item.isPackage; });
      break;
    case "HasShip":
      list = $.grep(list, function(item) { return item.hasShip; });
      break;
    case "IsPackage":
      list = $.grep(list, function(item) { return item.isPackage; });
      break;
    case "!IsPackage":
      list = $.grep(list, function(item) { return !item.isPackage && item.hasShip; });
      break;
    case "IsWarbond":
      list = $.grep(list, function(item) { return item.isWarbond && item.hasShip; });
      break;
    case "!IsWarbond":
      list = $.grep(list, function(item) { return !item.isWarbond && item.hasShip; });
      break;
    case "IsCombo":
      list = $.grep(list, function(item) { return item.isCombo; });
      break;
    case "IsUpgrade":
      list = $.grep(list, function(item) { return item.isUpgrade; });
      break;
    case "IsUpgraded":
      list = $.grep(list, function(item) { return item.isUpgraded; });
      break;
    case "!IsUpgraded":
      list = $.grep(list, function(item) { return !item.isUpgraded; });
      break;
    case "IsAddOn":
      list = $.grep(list, function(item) { return item.isAddOn; });
      break;
    case "IsPaint":
      list = $.grep(list, function(item) { return item.isPaint; });
      break;
    case "IsExtra":
      list = $.grep(list, function(item) { return item.isAddOn || item.isUpgrade; });
      break;
    case "IsFlair":
      list = $.grep(list, function(item) { return item.isFlair; });
      break;
    case "HasValue":
      list = $.grep(list, function(item) { return item.hasValue; });
      break;
    case "!HasValue":
      list = $.grep(list, function(item) { return !item.hasValue; });
      break;
    case "IsMeltable":
      list = $.grep(list, function(item) { return item.isMeltable; });
      break;
    case "!IsMeltable":
      list = $.grep(list, function(item) { return !item.isMeltable; });
      break;
    case "IsModel":
      list = $.grep(list, function(item) { return item.isModel; });
      break;
    case "IsPoster":
      list = $.grep(list, function(item) { return item.isPoster; });
      break;
    case "IsPlant":
      list = $.grep(list, function(item) { return item.isSpacePlant; });
      break;
    case "IsDecoration":
      list = $.grep(list, function(item) { return item.isDecoration; });
      break;
    case "IsComponent":
      list = $.grep(list, function(item) { return item.isComponent; });
      break;
    case "IsReward":
      list = $.grep(list, function(item) { return item.isReward; });
      break;
    case "!IsReward":
      list = $.grep(list, function(item) { return !item.isReward; });
      break;
    case "IsSelected":
      list = $.grep(list, function(item) { return item.isSelected; });
      break;
    case "IsFreeCCU":
      list = $.grep(list, function(item) { return item.isUpgrade && !item.hasValue; });
      break;
    case "!IsFreeCCU":
      list = $.grep(list, function(item) { return !item.isUpgrade || item.hasValue; });
      break;
  }

  return list;
}
<commit_msg>Add Warbond Upgrade in Warbond Filter<commit_after>
var HangarXPLOR = HangarXPLOR || {};

HangarXPLOR.Filter = function(list, filter)
{
  switch (filter) {
    case "HasLTI":
      list = $.grep(list, function(item) { return item.hasLTI; });
      break;
    case "!HasLTI":
      list = $.grep(list, function(item) { return !item.hasLTI; });
      break;
    case "IsGiftable":
      list = $.grep(list, function(item) { return item.isGiftable; });
      break;
    case "!IsGiftable":
      list = $.grep(list, function(item) { return !item.isGiftable; });
      break;
    case "IsShip":
      list = $.grep(list, function(item) { return item.isShip && !item.isPackage; });
      break;
    case "HasShip":
      list = $.grep(list, function(item) { return item.hasShip; });
      break;
    case "IsPackage":
      list = $.grep(list, function(item) { return item.isPackage; });
      break;
    case "!IsPackage":
      list = $.grep(list, function(item) { return !item.isPackage && item.hasShip; });
      break;
    case "IsWarbond":
      list = $.grep(list, function(item) { return item.isWarbond && (item.hasShip || item.isUpgrade); });
      break;
    case "!IsWarbond":
      list = $.grep(list, function(item) { return !item.isWarbond && (item.hasShip || item.isUpgrade); });
      break;
    case "IsCombo":
      list = $.grep(list, function(item) { return item.isCombo; });
      break;
    case "IsUpgrade":
      list = $.grep(list, function(item) { return item.isUpgrade; });
      break;
    case "IsUpgraded":
      list = $.grep(list, function(item) { return item.isUpgraded; });
      break;
    case "!IsUpgraded":
      list = $.grep(list, function(item) { return !item.isUpgraded; });
      break;
    case "IsAddOn":
      list = $.grep(list, function(item) { return item.isAddOn; });
      break;
    case "IsPaint":
      list = $.grep(list, function(item) { return item.isPaint; });
      break;
    case "IsExtra":
      list = $.grep(list, function(item) { return item.isAddOn || item.isUpgrade; });
      break;
    case "IsFlair":
      list = $.grep(list, function(item) { return item.isFlair; });
      break;
    case "HasValue":
      list = $.grep(list, function(item) { return item.hasValue; });
      break;
    case "!HasValue":
      list = $.grep(list, function(item) { return !item.hasValue; });
      break;
    case "IsMeltable":
      list = $.grep(list, function(item) { return item.isMeltable; });
      break;
    case "!IsMeltable":
      list = $.grep(list, function(item) { return !item.isMeltable; });
      break;
    case "IsModel":
      list = $.grep(list, function(item) { return item.isModel; });
      break;
    case "IsPoster":
      list = $.grep(list, function(item) { return item.isPoster; });
      break;
    case "IsPlant":
      list = $.grep(list, function(item) { return item.isSpacePlant; });
      break;
    case "IsDecoration":
      list = $.grep(list, function(item) { return item.isDecoration; });
      break;
    case "IsComponent":
      list = $.grep(list, function(item) { return item.isComponent; });
      break;
    case "IsReward":
      list = $.grep(list, function(item) { return item.isReward; });
      break;
    case "!IsReward":
      list = $.grep(list, function(item) { return !item.isReward; });
      break;
    case "IsSelected":
      list = $.grep(list, function(item) { return item.isSelected; });
      break;
    case "IsFreeCCU":
      list = $.grep(list, function(item) { return item.isUpgrade && !item.hasValue; });
      break;
    case "!IsFreeCCU":
      list = $.grep(list, function(item) { return !item.isUpgrade || item.hasValue; });
      break;
  }

  return list;
}
<|endoftext|>