<commit_before>/*
Gradebook from Names and Scores

I worked on this challenge [by myself, with:]
This challenge took me [#] hours.

You will work with the following two variables.  The first, students, holds the names of four students.
The second, scores, holds groups of test scores.  The relative positions of elements within the two
variables match (i.e., 'Joseph' is the first element in students; his scores are the first value in scores.).

Do not alter the students and scores code.

*/

var students = ["Joseph", "Susan", "William", "Elizabeth"];

var scores = [ [80, 70, 70, 100],
               [85, 80, 90, 90],
               [75, 70, 80, 75],
               [100, 90, 95, 85] ];

// __________________________________________
// Write your code below.

var gradebook = students.reduce(function(array, value){
  array[value]={}
  return array
},{});

for (var i in Object.keys(gradebook)){
  gradebook[Object.keys(gradebook)[i]]["testScores"]=scores[i]
};

gradebook.addScore = function(name,score) {
  gradebook[name]["testScores"].push(score);
};

gradebook.getAverage = function(name) {
  return average(gradebook[name].testScores);
};

function average(array){
  var sum = 0;
  for (var i in array){
    sum += array[i]
  };
  return sum/array.length;
};

// __________________________________________
// Refactored Solution

var gradebook = new Object();

for (var i in students){
  gradebook[students[i]]={"testScores": scores[i]}
}

gradebook.addScore = function(name,score) {
  gradebook[name]["testScores"].push(score);
};

gradebook.getAverage = function(name) {
  return average(gradebook[name].testScores);
};

function average(array){
  var sum = 0;
  for (var i in array){
    sum += array[i]
  };
  return sum/array.length;
};

// __________________________________________
// Reflect

/*
What did you learn about adding functions to objects?
Functions in javascript are treated like items within an object
(much different than how ruby and classes in ruby works)

How did you iterate over nested arrays in JavaScript?
We had to iterate over the array of object keys in order to access
the values we needed.

Were there any new methods you were able to incorporate? If so,
what were they and how did they work?
Two new methods! Reduce, Object.keys. You give reduce a function whose
parameters represent items in the array reduce is called on. Then you
tell reduce (in the block) what to return given the values (which
represent all values in the array). You also have to give reduce (after
the block), the value you'd like the operation to start with. Object.keys
takes an object and turns all of its keys into an array. This is useful
if you want to use an array method on elements of an object.*/

// __________________________________________
// Test Code:  Do not alter code below this line.

function assert(test, message, test_number) {
  if (!test) {
    console.log(test_number + "false");
    throw "ERROR: " + message;
  }
  console.log(test_number + "true");
  return true;
}

assert(
  (gradebook instanceof Object),
  "The value of gradebook should be an Object.\n",
  "1. "
)

assert(
  (gradebook["Elizabeth"] instanceof Object),
  "gradebook's Elizabeth property should be an object.",
  "2. "
)

assert(
  (gradebook.William.testScores === scores[2]),
  "William's testScores should equal the third element in scores.",
  "3. "
)

assert(
  (gradebook.addScore instanceof Function),
  "The value of gradebook's addScore property should be a Function.",
  "4. "
)

gradebook.addScore("Susan", 80)

assert(
  (gradebook.Susan.testScores.length === 5
   && gradebook.Susan.testScores[4] === 80),
  "Susan's testScores should have a new score of 80 added to the end.",
  "5. "
)

assert(
  (gradebook.getAverage instanceof Function),
  "The value of gradebook's getAverage property should be a Function.",
  "6. "
)

assert(
  (average instanceof Function),
  "The value of average should be a Function.\n",
  "7. "
)
assert(
  average([1, 2, 3]) === 2,
  "average should return the average of the elements in the array argument.\n",
  "8. "
)

assert(
  (gradebook.getAverage("Joseph") === 80),
  "gradebook's getAverage should return 80 if passed 'Joseph'.",
  "9. "
)<commit_msg>Update gradebook.js<commit_after>/*
Gradebook from Names and Scores

I worked on this challenge [with Jonathan]
This challenge took me [#] hours.

You will work with the following two variables.  The first, students, holds the names of four students.
The second, scores, holds groups of test scores.  The relative positions of elements within the two
variables match (i.e., 'Joseph' is the first element in students; his scores are the first value in scores.).

Do not alter the students and scores code.

*/

var students = ["Joseph", "Susan", "William", "Elizabeth"];

var scores = [ [80, 70, 70, 100],
               [85, 80, 90, 90],
               [75, 70, 80, 75],
               [100, 90, 95, 85] ];

// __________________________________________
// Write your code below.

var gradebook = students.reduce(function(array, value){
  array[value]={}
  return array
},{});

for (var i in Object.keys(gradebook)){
  gradebook[Object.keys(gradebook)[i]]["testScores"]=scores[i]
};

gradebook.addScore = function(name,score) {
  gradebook[name]["testScores"].push(score);
};

gradebook.getAverage = function(name) {
  return average(gradebook[name].testScores);
};

function average(array){
  var sum = 0;
  for (var i in array){
    sum += array[i]
  };
  return sum/array.length;
};

// __________________________________________
// Refactored Solution

var gradebook = new Object();

for (var i in students){
  gradebook[students[i]]={"testScores": scores[i]}
}

gradebook.addScore = function(name,score) {
  gradebook[name]["testScores"].push(score);
};

gradebook.getAverage = function(name) {
  return average(gradebook[name].testScores);
};

function average(array){
  var sum = 0;
  for (var i in array){
    sum += array[i]
  };
  return sum/array.length;
};

// __________________________________________
// Reflect

/*
What did you learn about adding functions to objects?
Functions in javascript are treated like items within an object
(much different than how ruby and classes in ruby works)

How did you iterate over nested arrays in JavaScript?
We had to iterate over the array of object keys in order to access
the values we needed.

Were there any new methods you were able to incorporate? If so,
what were they and how did they work?
Two new methods! Reduce, Object.keys. You give reduce a function whose
parameters represent items in the array reduce is called on. Then you
tell reduce (in the block) what to return given the values (which
represent all values in the array). You also have to give reduce (after
the block), the value you'd like the operation to start with. Object.keys
takes an object and turns all of its keys into an array. This is useful
if you want to use an array method on elements of an object.*/

// __________________________________________
// Test Code:  Do not alter code below this line.

function assert(test, message, test_number) {
  if (!test) {
    console.log(test_number + "false");
    throw "ERROR: " + message;
  }
  console.log(test_number + "true");
  return true;
}

assert(
  (gradebook instanceof Object),
  "The value of gradebook should be an Object.\n",
  "1. "
)

assert(
  (gradebook["Elizabeth"] instanceof Object),
  "gradebook's Elizabeth property should be an object.",
  "2. "
)

assert(
  (gradebook.William.testScores === scores[2]),
  "William's testScores should equal the third element in scores.",
  "3. "
)

assert(
  (gradebook.addScore instanceof Function),
  "The value of gradebook's addScore property should be a Function.",
  "4. "
)

gradebook.addScore("Susan", 80)

assert(
  (gradebook.Susan.testScores.length === 5
   && gradebook.Susan.testScores[4] === 80),
  "Susan's testScores should have a new score of 80 added to the end.",
  "5. "
)

assert(
  (gradebook.getAverage instanceof Function),
  "The value of gradebook's getAverage property should be a Function.",
  "6. "
)

assert(
  (average instanceof Function),
  "The value of average should be a Function.\n",
  "7. "
)
assert(
  average([1, 2, 3]) === 2,
  "average should return the average of the elements in the array argument.\n",
  "8. "
)

assert(
  (gradebook.getAverage("Joseph") === 80),
  "gradebook's getAverage should return 80 if passed 'Joseph'.",
  "9. "
)
<|endoftext|>


<commit_before>
angular.module('omniwallet')
  .factory('wallet_balances_template', function($q, $http) {
    var deferred = $q.defer();

    $http.get('/partials/wallet_address_list.html').then(function(result) {
      deferred.resolve(result.data);
    });

    return deferred.promise;
  })
  .factory('wallet_balances_data', function($http, $q, $timeout, $injector, Account) {
    var count = 1;
    return {
      "getData": function() {
        var deferred = $q.defer();

        _.defer(function() {
          var wallet = Account.wallet;
          if (wallet && wallet.addresses.length > 0) {
            var requests = [];

            var balances = {};
            var invalidAddresses = [];
            var currencyInfo;
            var emptyAddresses = [];

            var appraiser = $injector.get('appraiser');

            wallet.addresses.forEach(function(addr) {
              requests.push($injector.get('balanceService').balance(addr.address).then(function(result) {
                if (result.data.balance.length == 0) {
                  console.log('No balances for ' + addr.address + ', invalid address?');
                  invalidAddresses.push(addr.address);
                } else {
                  result.data.balance.forEach(function(currencyItem) {
                    if(currencyItem.divisible)
                      var value=new Big(currencyItem.value).times(WHOLE_UNIT).valueOf();
                    if (!balances.hasOwnProperty(currencyItem.symbol)) {
                      balances[currencyItem.symbol] = {
                        "symbol": currencyItem.symbol,
                        "balance": +value || currencyItem.value,
                        "value": appraiser.getValue(currencyItem.value, currencyItem.symbol, currencyItem.divisible),
                        "addresses": {}
                      };
                    } else {
                      balances[currencyItem.symbol].balance += +value || currencyItem.value;
                      balances[currencyItem.symbol].value += appraiser.getValue(currencyItem.value, currencyItem.symbol, currencyItem.divisible);
                    }

                    if (currencyItem.symbol == 'BTC') {
                      balances[currencyItem.symbol].name = "Bitcoin"
                    }
            		    if (addr.privkey) {
            			   hasPrivate=true;
            		    } else {
            			   hasPrivate=false;
            		    }
            		    if (addr.pubkey) {
                     isOffline=true;
                    } else {
                     isOffline=false;
                    }
                    balances[currencyItem.symbol].addresses[result.data.address] = {
                      "address": result.data.address,
                      "balance": +value || currencyItem.value,
                      "value": appraiser.getValue(currencyItem.value, currencyItem.symbol, currencyItem.divisible),
		                  "private": hasPrivate,
		                  "offline": isOffline
                    };
                  });
                }
              }));
            });
            // First, the standard currencies.
            requests.push($http.get('/v1/transaction/values.json').then(function(result) {
              currencyInfo = result.data;
            }
            ));
            $q.all(requests).then(function(responses) {
              if (currencyInfo) {
                currencyInfo.forEach(function(item) {
                  if (balances.hasOwnProperty(item.currency))
                    balances[item.currency].name = item.name;
                });

                // Now, any applicable smart properties.
                var spReqs = [];

                for (var b in balances) {
                  var spMatch = balances[b].symbol.match(/^SP([0-9]+)$/);
                  if (spMatch != null) {
                    var updateFunction = function(result) {
                      if (result.status == 200) {
                        this.property_type = result.data[0].formatted_property_type
                        this.name = result.data[0].propertyName + ' (' + this.symbol.match(/^SP([0-9]+)$/)[1] + ')';
                      }
                    };
                    spReqs.push($http.get('/v1/property/' + spMatch[1] + '.json').then(updateFunction.bind(balances[b])));
                  }
                }

                if (spReqs.length > 0) {
                  $q.all(spReqs).then(function() {
                    deferred.resolve(
                    {
                      balances: balances,
                      currencies: currencyInfo
                    });
                  });
                } else {
                  deferred.resolve(
                  {
                    balances: balances,
                    currencies: currencyInfo
                  });
                }
              }
            });
          } else {
            $http.get('/v1/transaction/values.json').then(function(currencyInfo) {
              deferred.resolve({
                currencies: currencyInfo
              });
            }
            );
          }
        });

        return deferred.promise;
      }
    };
  })
  .directive('showWalletBalances', function($compile, $injector) {
    return {
      scope: true,
      link: function(scope, element, attrs) {
        var el;

        attrs.$observe('template', function(tpl) {
          if (angular.isDefined(tpl)) {
            // compile the provided template against the current scope
            el = $compile(tpl)(scope);

            // stupid way of emptying the element
            element.html("");

            // add the template content
            element.append(el);
          }
        });
      }
    }
  })
  .controller('WalletBalancesController', function($modal, $rootScope, $injector, $scope, wallet_balances_data, wallet_balances_template, Account) {

  var appraiser = $injector.get('appraiser');
  $rootScope.$on('APPRAISER_VALUE_CHANGED', function() {
    $scope.refresh();
  });

  $scope.openDeleteConfirmForm = function(addritem) {
    if (!$scope.modalOpened) {
      $scope.modalOpened = true;
      var modalInstance = $modal.open({
        templateUrl: '/partials/delete_address_modal.html',
        controller: DeleteBtcAddressModal,
        resolve: {
          address: function() {
            return addritem;
          }
        }
      });
      modalInstance.result.then(function() {
	      Account.removeAddress(addritem.address);
        $scope.modalOpened=false;
	      $scope.refresh();
        },
        function() {
  	     $scope.modalOpened=false;
      });
    }
  };

  $scope.broadcastTransaction = function(signedHex, from, $modalScope){
    var walletTransactionService = $injector.get('walletTransactionService');
    walletTransactionService.getArmoryRaw(signedHex).then(function(result){
      var finalTransaction = result.data.rawTransaction;

      //Showing the user the transaction hash doesn't work right now
      //var transactionHash = Bitcoin.Util.bytesToHex(transaction.getHash().reverse());

      walletTransactionService.pushSignedTransaction(finalTransaction).then(function(successData) {
        var successData = successData.data;
        if (successData.pushed.match(/submitted|success/gi) != null) {
          $modalScope.waiting = false;
          $modalScope.transactionSuccess = true;
        if(TESTNET)
          $modalScope.url = 'http://tbtc.blockr.io/tx/info/' + successData.tx;
        else
          $modalScope.url = 'http://blockchain.info/address/' + from + '?sort=0';
        } else {
          $modalScope.waiting = false;
          $modalScope.transactionError = true;
          $modalScope.error = successData.pushed; //Unspecified error, show user
        }
      }, function(errorData) {
        $modalScope.waiting = false;
        $modalScope.transactionError = true;
        if (errorData.message)
          $modalScope.error = 'Server error: ' + errorData.message;
        else
          if (errorData.data)
            $modalScope.error = 'Server error: ' + errorData.data;
          else
            $modalScope.error = 'Unknown Server Error';
        console.error(errorData);
      });
    })
  };

  $scope.openBroadcastTransactionForm =function(address){
    var modalInstance = $modal.open({
        templateUrl: "/partials/wallet_broadcast_modal.html",
        controller: function($scope, $modalInstance, address, broadcastTransaction) {
          $scope.broadcastAddress = address;

          $scope.ok = function(signedHex) {
            $scope.clicked = true;
            $scope.waiting = true;
            broadcastTransaction(signedHex, address, $scope);
          };

          $scope.cancel = function () {
            $modalInstance.dismiss('cancel');
          };

          $scope.close = function () {
            $modalInstance.dismiss('close');
          };
        },
        resolve: {
          broadcastTransaction: function() {
              return $scope.broadcastTransaction;
          }, address: function(){
            return address;
          }
        }
      });
  };

  $scope.refresh = function() {

    $scope.items = wallet_balances_data.getData().then(function(balances) {
      $scope.balances = balances;
      wallet_balances_template.then(function(templ) {
        _.defer(function() {
          $scope.template = templ;
          $scope.$apply();
        });
      });
    });
  };
});

var DeleteBtcAddressModal = function($scope, $modalInstance, address) {
  $scope.address = address.address;
  $scope.private = address.private;

  $scope.ok = function() {
    $modalInstance.close();
  };

  $scope.cancel = function() {
    $modalInstance.dismiss('cancel');
  };
};

<commit_msg>Get balances from the Address models for My Addresses page<commit_after>
angular.module('omniwallet')
  .factory('wallet_balances_template', function($q, $http) {
    var deferred = $q.defer();

    $http.get('/partials/wallet_address_list.html').then(function(result) {
      deferred.resolve(result.data);
    });

    return deferred.promise;
  })
  .factory('wallet_balances_data', function($http, $q, $timeout, $injector, Account) {
    var count = 1;
    return {
      "getData": function() {
        var deferred = $q.defer();

        _.defer(function() {
          var wallet = Account.wallet;
          if (wallet && wallet.addresses.length > 0) {
            var requests = [];

            var balances = {};
            var invalidAddresses = [];
            var currencyInfo;
            var emptyAddresses = [];

            var appraiser = $injector.get('appraiser');

            wallet.addresses.forEach(function(addr) {
              if (addr.balance.length == 0) {
                console.log('No balances for ' + addr.address + ', invalid address?');
                invalidAddresses.push(addr.address);
              } else {
                addr.balance.forEach(function(currencyItem) {
                  if(currencyItem.divisible)
                    var value=new Big(currencyItem.value).times(WHOLE_UNIT).valueOf();
                  if (!balances.hasOwnProperty(currencyItem.symbol)) {
                    balances[currencyItem.symbol] = {
                      "symbol": currencyItem.symbol,
                      "balance": +value || currencyItem.value,
                      "value": appraiser.getValue(currencyItem.value, currencyItem.symbol, currencyItem.divisible),
                      "addresses": {}
                    };
                  } else {
                    balances[currencyItem.symbol].balance += +value || currencyItem.value;
                    balances[currencyItem.symbol].value += appraiser.getValue(currencyItem.value, currencyItem.symbol, currencyItem.divisible);
                  }

                  if (currencyItem.symbol == 'BTC') {
                    balances[currencyItem.symbol].name = "Bitcoin"
                  }
          		    if (addr.privkey) {
          			   hasPrivate=true;
          		    } else {
          			   hasPrivate=false;
          		    }
          		    if (addr.pubkey) {
                   isOffline=true;
                  } else {
                   isOffline=false;
                  }
                  balances[currencyItem.symbol].addresses[addr.address] = {
                    "address": result.data.address,
                    "balance": +value || currencyItem.value,
                    "value": appraiser.getValue(currencyItem.value, currencyItem.symbol, currencyItem.divisible),
	                  "private": hasPrivate,
	                  "offline": isOffline
                  };
                });
              }
            });
            // First, the standard currencies.
            $http.get('/v1/transaction/values.json').then(function(result) {
              currencyInfo = result.data;
              currencyInfo.forEach(function(item) {
                if (balances.hasOwnProperty(item.currency))
                  balances[item.currency].name = item.name;
              });

              // Now, any applicable smart properties.
              var spReqs = [];

              for (var b in balances) {
                var spMatch = balances[b].symbol.match(/^SP([0-9]+)$/);
                if (spMatch != null) {
                  var updateFunction = function(result) {
                    if (result.status == 200) {
                      this.property_type = result.data[0].formatted_property_type
                      this.name = result.data[0].propertyName + ' (' + this.symbol.match(/^SP([0-9]+)$/)[1] + ')';
                    }
                  };
                  spReqs.push($http.get('/v1/property/' + spMatch[1] + '.json').then(updateFunction.bind(balances[b])));
                }
              }

              if (spReqs.length > 0) {
                $q.all(spReqs).then(function() {
                  deferred.resolve(
                  {
                    balances: balances,
                    currencies: currencyInfo
                  });
                });
              } else {
                deferred.resolve(
                {
                  balances: balances,
                  currencies: currencyInfo
                });
              }
            });
          } else {
            $http.get('/v1/transaction/values.json').then(function(currencyInfo) {
              deferred.resolve({
                currencies: currencyInfo
              });
            }
            );
          }
        });

        return deferred.promise;
      }
    };
  })
  .directive('showWalletBalances', function($compile, $injector) {
    return {
      scope: true,
      link: function(scope, element, attrs) {
        var el;

        attrs.$observe('template', function(tpl) {
          if (angular.isDefined(tpl)) {
            // compile the provided template against the current scope
            el = $compile(tpl)(scope);

            // stupid way of emptying the element
            element.html("");

            // add the template content
            element.append(el);
          }
        });
      }
    }
  })
  .controller('WalletBalancesController', function($modal, $rootScope, $injector, $scope, wallet_balances_data, wallet_balances_template, Account) {

  var appraiser = $injector.get('appraiser');
  $rootScope.$on('APPRAISER_VALUE_CHANGED', function() {
    $scope.refresh();
  });

  $scope.openDeleteConfirmForm = function(addritem) {
    if (!$scope.modalOpened) {
      $scope.modalOpened = true;
      var modalInstance = $modal.open({
        templateUrl: '/partials/delete_address_modal.html',
        controller: DeleteBtcAddressModal,
        resolve: {
          address: function() {
            return addritem;
          }
        }
      });
      modalInstance.result.then(function() {
	      Account.removeAddress(addritem.address);
        $scope.modalOpened=false;
	      $scope.refresh();
        },
        function() {
  	     $scope.modalOpened=false;
      });
    }
  };

  $scope.broadcastTransaction = function(signedHex, from, $modalScope){
    var walletTransactionService = $injector.get('walletTransactionService');
    walletTransactionService.getArmoryRaw(signedHex).then(function(result){
      var finalTransaction = result.data.rawTransaction;

      //Showing the user the transaction hash doesn't work right now
      //var transactionHash = Bitcoin.Util.bytesToHex(transaction.getHash().reverse());

      walletTransactionService.pushSignedTransaction(finalTransaction).then(function(successData) {
        var successData = successData.data;
        if (successData.pushed.match(/submitted|success/gi) != null) {
          $modalScope.waiting = false;
          $modalScope.transactionSuccess = true;
        if(TESTNET)
          $modalScope.url = 'http://tbtc.blockr.io/tx/info/' + successData.tx;
        else
          $modalScope.url = 'http://blockchain.info/address/' + from + '?sort=0';
        } else {
          $modalScope.waiting = false;
          $modalScope.transactionError = true;
          $modalScope.error = successData.pushed; //Unspecified error, show user
        }
      }, function(errorData) {
        $modalScope.waiting = false;
        $modalScope.transactionError = true;
        if (errorData.message)
          $modalScope.error = 'Server error: ' + errorData.message;
        else
          if (errorData.data)
            $modalScope.error = 'Server error: ' + errorData.data;
          else
            $modalScope.error = 'Unknown Server Error';
        console.error(errorData);
      });
    })
  };

  $scope.openBroadcastTransactionForm =function(address){
    var modalInstance = $modal.open({
        templateUrl: "/partials/wallet_broadcast_modal.html",
        controller: function($scope, $modalInstance, address, broadcastTransaction) {
          $scope.broadcastAddress = address;

          $scope.ok = function(signedHex) {
            $scope.clicked = true;
            $scope.waiting = true;
            broadcastTransaction(signedHex, address, $scope);
          };

          $scope.cancel = function () {
            $modalInstance.dismiss('cancel');
          };

          $scope.close = function () {
            $modalInstance.dismiss('close');
          };
        },
        resolve: {
          broadcastTransaction: function() {
              return $scope.broadcastTransaction;
          }, address: function(){
            return address;
          }
        }
      });
  };

  $scope.refresh = function() {

    $scope.items = wallet_balances_data.getData().then(function(balances) {
      $scope.balances = balances;
      wallet_balances_template.then(function(templ) {
        _.defer(function() {
          $scope.template = templ;
          $scope.$apply();
        });
      });
    });
  };
});

var DeleteBtcAddressModal = function($scope, $modalInstance, address) {
  $scope.address = address.address;
  $scope.private = address.private;

  $scope.ok = function() {
    $modalInstance.close();
  };

  $scope.cancel = function() {
    $modalInstance.dismiss('cancel');
  };
};

<|endoftext|>


<commit_before>/**
 * All errors an adapter could potentially return
 */

module.exports = {
  // Primary key errors
  PrimaryKeyUpdate: 'Primary key cannot be updated',
  PrimaryKeyMissing: 'Primary key was not set and is not auto increment',
  PrimaryKeyCollision: 'A record with that primary key has already been created',

  // Not found
  NotFound: 'Record with the provided criteria was not found',

  // Uniqueness
  NotUnique: 'Record does not satisfy unique constraints',

  // Not registered
  CollectionNotRegistered: 'Unable to find registered collection',

  // Group by criteria not present
  GroupBy: 'Cannot groupBy without a calculation',

  // Authentication failure
  AuthFailure: 'Could not authenticate using credentials provided',

  // Invalid attribute passed that is auto increment
  InvalidAutoIncrement: 'An attribute that is auto increment cannot be set',
};<commit_msg>add new error for v0.10 adapters<commit_after>/**
 * All errors an adapter could potentially return
 */

module.exports = {
  // Primary key errors
  PrimaryKeyUpdate: 'Primary key cannot be updated',
  PrimaryKeyMissing: 'Primary key was not set and is not auto increment',
  PrimaryKeyCollision: 'A record with that primary key has already been created',

  // Not found
  NotFound: 'Record with the provided criteria was not found',

  // Uniqueness
  NotUnique: 'Record does not satisfy unique constraints',

  // Not registered
  CollectionNotRegistered: 'Unable to find registered collection',

  // Group by criteria not present
  GroupBy: 'Cannot groupBy without a calculation',

  // Authentication failure
  AuthFailure: 'Could not authenticate using credentials provided',

  // Invalid attribute passed that is auto increment
  InvalidAutoIncrement: 'An attribute that is auto increment cannot be set',

  // Invalid connection name passed
  InvalidConnection: 'Invalid connection name specified'
};<|endoftext|>


<commit_before>var Faker = require('faker');

/**
 * Generates an array of objects of fake data based off of the props
 * @method generateFakeData
 * @param {Object{ name(propertyName), type(type of data to create) }} props
 * @param {Number} count
 */

function generateFakeData(props, count, localization) {
  if(localization) {
    Faker.locale = localization;
  }
  var resultArr = []
  for(var index = 0; index < count; index++) {
    var newObj = {};
    for(var propIndex in props) {
      if(typeof(prop.type) === 'function') {
        newObj[prop.name] = prop.type(index, prop);
      }
      else if(prop.type !== undefined){
        newObj[prop.name] = Faker.fake(prop.type);
      }
      else {
        newObj[prop.name] = prop.name+index;
      };
    };
    resultArr.push(newObj);
  }
  return resultArr;
}

module["exports"] = generateFakeData<commit_msg>Add comment to faker-data<commit_after>var Faker = require('faker');

/**
 * Generates an array of objects of fake data based off of the props
 * @method generateFakeData
 * @param {Object{ name(propertyName), type(type of data to create) }} props
 * @param {Number} count
 */

function generateFakeData(props, count, localization) {
  if(localization) {
    Faker.locale = localization;
  }
  var resultArr = []
  for(var index = 0; index < count; index++) {
    var newObj = {};
		//Iterate through every property
    for(var propIndex in props) {
      if(typeof(prop.type) === 'function') {
        newObj[prop.name] = prop.type(index, prop);
      }
      else if(prop.type !== undefined){
        newObj[prop.name] = Faker.fake(prop.type);
      }
      else {
        newObj[prop.name] = prop.name+index;
      };
    };
    resultArr.push(newObj);
  }
  return resultArr;
}

module["exports"] = generateFakeData<|endoftext|>


<commit_before>var arDrone = require('ar-drone');
var client = arDrone.createClient();
client.config('general:navdata_demo', 'FALSE');
var Myo = require('myo');
var myMyo = Myo.create();
var altitude = navdata.demo.altitudeMeters;
var nextaltitude = altitude + 500; //add 500 mm, or .50 m to height

//Edge is true if it's the start of the pose, false if it's the end of the pose

myMyo.on('fingers_spread', function(edge){
  myMyo.timer(edge, 500, function(){
    console.log('spreading fingers detected');
    client.takeoff();
  })
});

myMyo.on('fist', function(edge){
  myMyo.timer(edge, 500, function(){
    console.log('fist detected');
    //take photo
  })
});

myMyo.on('wave_in', function(edge){
  myMyo.timer(edge, 500, function(){
    console.log('wave in detected');
    altitude = navdata.demo.altitudeMeters;
    nextaltitude = altitude + 500; //add 500 mm, or .50 m to height
    while (altitude !== nextaltitude) {
      client.up(0.3);
      altitude = navdata.demo.altitudeMeters;
    }
    client.stop();
  })
});

myMyo.on('wave_out', function(edge){
  myMyo.timer(edge, 500, function(){
    console.log('wave in detected');
    altitude = navdata.demo.altitudeMeters;
    nextaltitude = altitude +- 500; //subtract 500 mm, or .50 m to height
    while (altitude !== nextaltitude) {
      client.down(0.3);
      altitude = navdata.demo.altitudeMeters;
    }
    client.stop();
  })
});

myMyo.on('orientation', function(data){
  if(data.x > .4){
    alert('left hand tilt detected')
    client.front(.3)
  }
});

myMyo.on('orientation', function(data){
  if(data.x < -.2){
    client.back(.3)
  }
});
<commit_msg>edited rotation quaternion for front/back<commit_after>var arDrone = require('ar-drone');
var client = arDrone.createClient();
client.config('general:navdata_demo', 'FALSE');
var Myo = require('myo');
var myMyo = Myo.create();
var altitude = navdata.demo.altitudeMeters;
var nextaltitude = altitude + 500; //add 500 mm, or .50 m to height

//Edge is true if it's the start of the pose, false if it's the end of the pose

myMyo.on('fingers_spread', function(edge){
  myMyo.timer(edge, 500, function(){
    console.log('spreading fingers detected');
    client.takeoff();
  })
});

myMyo.on('fist', function(edge){
  myMyo.timer(edge, 500, function(){
    console.log('fist detected');
    //take photo
  })
});

myMyo.on('wave_in', function(edge){
  myMyo.timer(edge, 500, function(){
    console.log('wave in detected');
    altitude = navdata.demo.altitudeMeters;
    nextaltitude = altitude + 500; //add 500 mm, or .50 m to height
    while (altitude !== nextaltitude) {
      client.up(0.3);
      altitude = navdata.demo.altitudeMeters;
    }
    client.stop();
  })
});

myMyo.on('wave_out', function(edge){
  myMyo.timer(edge, 500, function(){
    console.log('wave in detected');
    altitude = navdata.demo.altitudeMeters;
    nextaltitude = altitude +- 500; //subtract 500 mm, or .50 m to height
    while (altitude !== nextaltitude) {
      client.down(0.3);
      altitude = navdata.demo.altitudeMeters;
    }
    client.stop();
  })
});

myMyo.on('orientation', function(data){
  if(data.x < -.4){
    alert('left hand tilt detected')
    client.front(.3)
  }
});

myMyo.on('orientation', function(data){
  if(data.x > .4){
    client.back(.3)
  }
});
<|endoftext|>


<commit_before>module.exports = function() {
  // create a new function for StructureSpawn
  StructureSpawn.prototype.createCustomCreep = function(energy, roleName) {
    // create a balanced body as big as possible with the given energy
    var numberOfParts = Math.floor(energy / 200);
    var body = [];
    for (let i = 0; i < numberOfParts; i++) {
      body.push(WORK);
    }
    for (let i = 0; i < numberOfParts; i++) {
      body.push(CARRY);
    }
    for (let i = 0; i < numberOfParts; i++) {
      body.push(MOVE);
    }

    // create creep with the created body and the given role
    return this.createCreep(body, undefined, {
      role: roleName,
      working: false
    });
  };
};
<commit_msg>Changed name-generation for new spawned creeps<commit_after>module.exports = function() {
  // create a new function for StructureSpawn
  StructureSpawn.prototype.createCustomCreep = function(energy, roleName) {
    // create a balanced body as big as possible with the given energy
    var numberOfParts = Math.floor(energy / 200);
    var body = [];
    for (let i = 0; i < numberOfParts; i++) {
      body.push(WORK);
    // body.push(WORK);
    }
    for (let i = 0; i < numberOfParts; i++) {
      body.push(CARRY);
    }
    for (let i = 0; i < numberOfParts; i++) {
      body.push(MOVE);
    }

    // create creep with the created body and the given role
    return this.createCreep(body, (roleName.substr(0, 1).toUpperCase() + "-" + numberOfParts + "-" + Math.floor((Math.random() * 1000) + 1)).toString(), {
      role: roleName,
      working: false
    });
  };
};
<|endoftext|>


<commit_before>import {
  PrimaryButton,
  SecondaryButton,
  Guest as TertiaryButton,
} from "./buttons";

const SecondaryLayout = ({ authorized, register }) => {
  if (!authorized && !Meteor.userId()) {
    return (
      <SecondaryButton

        onClick={register}
      />
    );
  }
  return null;
}

const TertiaryLayout = ({ disabledGuest, disabled, giveAsGuest }) => {
  if (!disabledGuest && !Meteor.userId()) {
    return (
      <TertiaryButton
        disabled={disabled}
        onClick={giveAsGuest}
      />
    );
  }
  return null;
}

const ChangePaymentsLayout = ({ savedPayments, hideCard, changePayments }) => {
  if (savedPayments && savedPayments.length && !hideCard && Meteor.userId()) {
    return (
      <TertiaryButton
        onClick={changePayments}
        text={"Change payment account"}
      />
    );
  }
  return null;
}

const Layout = (props) => (

    <PrimaryButton
      theme={props.theme}
      classes={props.classes}
      text={props.text}
      onClick={props.onClick}
      value={props.value}
      style={props.style || {}}
      dataId={props.dataId}
      savedPayments={props.savedPayments}
      hideCard={props.hideCard}
      getAccount={props.getAccount}
      disabled={props.disabled}
    />
    <SecondaryLayout
      authorized={props.authorized}
      register={props.register}
    />
    <TertiaryLayout
      disabledGuest={props.disabledGuest}
      disabled={props.disabled}
      giveAsGuest={props.giveAsGuest}
    />
    <ChangePaymentsLayout
      savedPayments={props.savedPayments}
      hideCard={props.hideCard}
      changePayments={props.changePayments}
    />

);

export default Layout;

<commit_msg>lint action buttons layout<commit_after>import { PropTypes } from "react";

import {
  PrimaryButton,
  SecondaryButton,
  Guest as TertiaryButton,
} from "./buttons";

const SecondaryLayout = ({ authorized, register }) => {
  if (!authorized && !Meteor.userId()) {
    return (
      <SecondaryButton
        onClick={register}
      />
    );
  }
  return null;
};

SecondaryLayout.propTypes = {
  authorized: PropTypes.bool,
  register: PropTypes.func,
};

const TertiaryLayout = ({ disabledGuest, disabled, giveAsGuest }) => {
  if (!disabledGuest && !Meteor.userId()) {
    return (
      <TertiaryButton
        disabled={disabled}
        onClick={giveAsGuest}
      />
    );
  }
  return null;
};

TertiaryLayout.propTypes = {
  disabled: PropTypes.bool,
  disabledGuest: PropTypes.bool,
  giveAsGuest: PropTypes.func,
};

const ChangePaymentsLayout = ({ savedPayments, hideCard, changePayments }) => {
  if (savedPayments && savedPayments.length && !hideCard && Meteor.userId()) {
    return (
      <TertiaryButton
        onClick={changePayments}
        text={"Change payment account"}
      />
    );
  }
  return null;
};

ChangePaymentsLayout.propTypes = {
  changePayments: PropTypes.func,
  hideCard: PropTypes.bool,
  savedPayments: PropTypes.array,
};

const Layout = ({
  authorized,
  changePayments,
  classes,
  dataId,
  disabled,
  disabledGuest,
  getAccount,
  giveAsGuest,
  hideCard,
  onClick,
  register,
  savedPayments,
  style,
  theme,
  text,
  value,
}) => (

    <PrimaryButton
      theme={theme}
      classes={classes}
      text={text}
      onClick={onClick}
      value={value}
      style={style || {}}
      dataId={dataId}
      savedPayments={savedPayments}
      hideCard={hideCard}
      getAccount={getAccount}
      disabled={disabled}
    />
    <SecondaryLayout
      authorized={authorized}
      register={register}
    />
    <TertiaryLayout
      disabledGuest={disabledGuest}
      disabled={disabled}
      giveAsGuest={giveAsGuest}
    />
    <ChangePaymentsLayout
      savedPayments={savedPayments}
      hideCard={hideCard}
      changePayments={changePayments}
    />

);

Layout.propTypes = {
  authorized: PropTypes.bool,
  changePayments: PropTypes.func,
  classes: PropTypes.array,
  dataId: PropTypes.string,
  disabled: PropTypes.bool,
  disabledGuest: PropTypes.bool,
  getAccount: PropTypes.func,
  giveAsGuest: PropTypes.func,
  hideCard: PropTypes.bool,
  onClick: PropTypes.func,
  register: PropTypes.func,
  savedPayments: PropTypes.array,
  style: PropTypes.object,
  theme: PropTypes.string,
  text: PropTypes.string,
  value: PropTypes.string,
};

export default Layout;
<|endoftext|>


<commit_before>module.exports = function () {
    StructureSpawn.prototype.createCustomCreep =
    function(energy, roleName) {
        // Defined variable numberOfParts
        var numberOfParts = Math.floor(energy / 85);
            console.log(numberOfParts);
        // Define Body to be an array
        var body = [];
            //
            for (let i = 0; i < numberOfParts; i++) {
                body.push(WORK);
            }
            for (let i = 0; i < numberOfParts; i++) {
                body.push(WORK);
            }
            for (let i = 0; i < numberOfParts; i++) {
                body.push(WORK);
            }
            for (let i = 0; i < numberOfParts; i++) {
                body.push(WORK);
            }
            for (let i = 0; i < numberOfParts; i++) {
                body.push(WORK);
            }
            for (let i = 0; i < numberOfParts; i++) {
                body.push(CARRY);
            }
            for (let i = 0; i < numberOfParts; i++) {
                body.push(CARRY);
            }
            for (let i = 0; i < numberOfParts; i++) {
                body.push(CARRY);
            }
            for (let i = 0; i < numberOfParts; i++) {
                body.push(CARRY);
            }
            for (let i = 0; i < numberOfParts; i++) {
                body.push(MOVE);
            }
            for (let i = 0; i < numberOfParts; i++) {
                body.push(MOVE);
            }
            for (let i = 0; i < numberOfParts; i++) {
                body.push(MOVE);
            }
            for (let i = 0; i < numberOfParts; i++) {
                body.push(MOVE);
            }
            for (let i = 0; i < numberOfParts; i++) {
                body.push(MOVE);
            }
            for (let i = 0; i < numberOfParts; i++) {
                body.push(MOVE);
            }
        return this.createCreep(body, undefined, {role: roleName, working: false });
    };

};
<commit_msg>One less move<commit_after>module.exports = function () {
    StructureSpawn.prototype.createCustomCreep =
    function(energy, roleName) {
        // Defined variable numberOfParts
        var numberOfParts = Math.floor(energy / 85);
            console.log(numberOfParts);
        // Define Body to be an array
        var body = [];
            //
            for (let i = 0; i < numberOfParts; i++) {
                body.push(WORK);
            }
            for (let i = 0; i < numberOfParts; i++) {
                body.push(WORK);
            }
            for (let i = 0; i < numberOfParts; i++) {
                body.push(WORK);
            }
            for (let i = 0; i < numberOfParts; i++) {
                body.push(WORK);
            }
            for (let i = 0; i < numberOfParts; i++) {
                body.push(WORK);
            }
            for (let i = 0; i < numberOfParts; i++) {
                body.push(CARRY);
            }
            for (let i = 0; i < numberOfParts; i++) {
                body.push(CARRY);
            }
            for (let i = 0; i < numberOfParts; i++) {
                body.push(CARRY);
            }
            for (let i = 0; i < numberOfParts; i++) {
                body.push(CARRY);
            }
            for (let i = 0; i < numberOfParts; i++) {
                body.push(MOVE);
            }
            for (let i = 0; i < numberOfParts; i++) {
                body.push(MOVE);
            }
            for (let i = 0; i < numberOfParts; i++) {
                body.push(MOVE);
            }
            for (let i = 0; i < numberOfParts; i++) {
                body.push(MOVE);
            }
            for (let i = 0; i < numberOfParts; i++) {
                body.push(MOVE);
            }
        return this.createCreep(body, undefined, {role: roleName, working: false });
    };

};
<|endoftext|>


<commit_before>function Elevator() {
  // body...
  this.currentFloor = (Math.random() * 100) + 1;
  this.startingFloor = Math.floor(this.currentFloor / 5);
  this.child = new Plucky;
  this.player = new Player;
  this.rollcount = 0;
  this.yourtrys = 3;
}

Elevator.prototype.go_up = function () {
  // body...
  this.currentFloor += 1;
};

Elevator.prototype.go_down = function () {
  // body...
  this.currentFloor -= 1;
};

Elevator.prototype.myInfo = function () {
  // body...
  console.log('current floor', this.currentFloor);
  console.log('desired floor', this.player.desiredFloor);
  var goal = ['Goal: You are trying to get to floor', this.player.desiredFloor].join(" ");
  var start = ['You are on the', this.startingFloor, 'floor'].join(" ");

  // document.getElementById('results').innerHTML = [goal, start].join("
");
};

Elevator.prototype.roll = function () {
  // body...
  this.rollcount += 1;
  this.diff = Math.abs(this.currentFloor - this.player.desiredFloor);
  if (this.currentFloor != this.player.desiredFloor && this.player.desiredFloor > this.currentFloor) {
    this.child.reroll();
    this.rollcount += 1;
    for (var i = 0; i < this.diff / 2; i++) {
      this.calculateCurrentFloor();
    }
    for (var i = 0; i < this.player.wins; i++) {
      this.currentFloor += 1;
      if (this.currentFloor == this.player.desiredFloor){
        console.log('the player has won');
        var results = 'The player has won!';
        var survived = ['You made it through', this.rollcount , 'floors'].join(" ");
        document.getElementById('results').innerHTML = [results, survived].join("
");
        break;
      }
    }
    console.log(this.currentFloor);

  } else if(this.currentFloor == this.player.desiredFloor){
      var results = 'The player has won!';
      var survived = ['You made it through', this.rollcount , 'floors'].join(" ");
      console.log('You won');
      document.getElementById('results').innerHTML = [results, survived].join("
");
  } else if(this.rollcount >= this.yourtrys){
    var mytest = Math.abs(this.diff - this.rollcount);
    var results = ('Sorry. You died of starvation.');
    var test = ['Your current floor was:', this.currentFloor].join(" ");
    var survived = ['You made it through', this.rollcount , 'floors'].join(" ");
    document.getElementById('results').innerHTML = [results, test, survived].join("
");
    document.getElementById('roll').disabled = true;
  }

};
Elevator.prototype.calculateCurrentFloor = function () {
  // body...
  this.child.reroll();
  if (this.child.chanceOfPushingButton > 60) {
    this.child.wins += 1;
  } else {
    this.player.wins += 1;
  }
};

function Player(number){
  this.desiredFloor = 87;
  this.wins = 0;
};

function Plucky(){
  this.chanceOfPushingButton = Math.floor((Math.random() * 100) + 20);
  this.wins = 0;
};

Plucky.prototype.reroll = function () {
  // body...
  this.chanceOfPushingButton = Math.floor((Math.random() * 100) + 20);
};

function play(){
game = new Elevator();
game.myInfo();
document.getElementById('roll').disabled = false;
};

function roll(){
  game.roll();
};

thisgame = new Elevator();
thisgame.myInfo();
thisgame.roll();
thisgame.myInfo();
thisgame.roll();
thisgame.myInfo();
thisgame.roll();
<commit_msg>Add project stylesheets<commit_after>function Elevator() {
  // body...
  this.currentFloor = Math.floor((Math.random() * 100) + 1);
  this.startingFloor = Math.floor((this.currentFloor / 5));
  this.child = new Plucky;
  this.player = new Player;
  this.rollcount = 0;
  this.yourtrys = 3;
}

Elevator.prototype.go_up = function () {
  // body...
  this.currentFloor += 1;
};

Elevator.prototype.go_down = function () {
  // body...
  this.currentFloor -= 1;
};

Elevator.prototype.myInfo = function () {
  // body...
  console.log('current floor', this.currentFloor);
  console.log('desired floor', this.player.desiredFloor);
  var goal = ['Goal: You are trying to get to floor', this.player.desiredFloor].join(" ");
  var start = ['You are on the', this.startingFloor, 'floor'].join(" ");

  // document.getElementById('results').innerHTML = [goal, start].join("
");
};

Elevator.prototype.roll = function () {
  // body...
  this.rollcount += 1;
  this.diff = Math.abs(this.currentFloor - this.player.desiredFloor);
  if (this.currentFloor != this.player.desiredFloor && this.player.desiredFloor > this.currentFloor) {
    this.child.reroll();
    this.rollcount += 1;
    for (var i = 0; i < this.diff / 2; i++) {
      this.calculateCurrentFloor();
    }
    for (var i = 0; i < this.player.wins; i++) {
      this.currentFloor += 1;
      if (this.currentFloor == this.player.desiredFloor){
        console.log('the player has won');
        var results = 'The player has won!';
        var survived = ['You made it through', this.rollcount , 'floors'].join(" ");
        document.getElementById('results').innerHTML = [results, survived].join("
");
        break;
      }
    }
    console.log(this.currentFloor);

  } else if(this.currentFloor == this.player.desiredFloor){
      var results = 'The player has won!';
      var survived = ['You made it through', this.rollcount , 'floors'].join(" ");
      console.log('You won');
      document.getElementById('results').innerHTML = [results, survived].join("
");
  } else if(this.rollcount >= this.yourtrys){
    var mytest = Math.abs(this.diff - this.rollcount);
    var results = ('Sorry. You died of starvation.');
    var test = ['Your current floor was:', this.currentFloor].join(" ");
    var survived = ['You made it through', this.rollcount , 'floors'].join(" ");
    document.getElementById('results').innerHTML = [results, test, survived].join("
");
    document.getElementById('roll').disabled = true;
  }

};
Elevator.prototype.calculateCurrentFloor = function () {
  // body...
  this.child.reroll();
  if (this.child.chanceOfPushingButton > 60) {
    this.child.wins += 1;
  } else {
    this.player.wins += 1;
  }
};

function Player(number){
  this.desiredFloor = 87;
  this.wins = 0;
};

function Plucky(){
  this.chanceOfPushingButton = Math.floor((Math.random() * 100) + 20);
  this.wins = 0;
};

Plucky.prototype.reroll = function () {
  // body...
  this.chanceOfPushingButton = Math.floor((Math.random() * 100) + 20);
};

function play(){
game = new Elevator();
game.myInfo();
document.getElementById('roll').disabled = false;
};

function roll(){
  game.roll();
};

thisgame = new Elevator();
thisgame.myInfo();
thisgame.roll();
thisgame.myInfo();
thisgame.roll();
thisgame.myInfo();
thisgame.roll();
<|endoftext|>


<commit_before>/**
 * @fileOverview
 * Dashboard module

 * @author Shmidt Ivan
 * @version 0.0.1
 * @module Dashboard
 * @requires DashboardConfig
 * @requires Widget
 * @requires Filter
 * @requires MessageCenter
 * @requires jQuery
 * @todo Delete jQuery dependency
 */
define([
    'DashboardConfig',
    'Widget',
    'Filter',
    'MessageCenter',
    "WidgetMap"
], function (DashboardConfiguration, Widget, Filter, mc, WidgetMap) {
    'use strict';
    /**
     * @class
     * @class Dashboard
     * @alias module:Dashboard
     * @listens module:MessageCenter#filters_acquired
     * @fires module:MessageCenter#filters_requested
     * @return {Dashboard} New dashboard object
     */
    function Dashboard(dashName) {
        /**@lends module:Dashboard#*/
        /**
         * Array of Widget objects
         * @var {Array<module:Widget>}
         * @name module:Dashboard#widgets
         * @todo Make this one private
         */
        this.widgets = [];
        /**
         * Flag, that shows current active widget
         * @var {number} module:Dashboard#activeWidget
         * @public
         */
        this.activeWidget = undefined;
        this.subs = [];
        /**
         * Dashboard config
         * @var {module:DashboardConfig} module:Dashboard#config
         */
        this.config = new DashboardConfiguration();
        /****
        Methods
        *****/
        this.createHolder();
        this.onDashboardDataAcquired = function (d) {
            $("#btnMainFilter").show();
            if(d === "null"){
            //No widgets in dashboard
                return;
            }
            App.filters = [];
            var requestedFiltersForCube = [];
            var widgets = d.children;
            var self = this;
            for (var i = 0; i < widgets.length; i++) {

                var widget = widgets[i];
                var widget_config = WidgetMap[widget.type];
                if (!widget_config) {
                    widget_config = WidgetMap["null"]
                }
                widget_config.datasource = {
                    data: {
                        MDX: widget.mdx
                    }
                };
                widget_config.filters = [];
                _.each(widget.children, function (filter) {
                    widget_config.filters.push({
                        name: filter.label,
                        path: filter.path,
                        value: filter.value
                    });
                });

                widget_config.config.title = {
                    text: widget.title
                };
                self.addWidget(widget_config);
                self.widgets[self.widgets.length - 1].cube = widgets[i].cube;
                if (widgets[i].cube) {
                    mc.publish('filters_requested', {cube: widgets[i].cube, widget: self.widgets[self.widgets.length - 1]});
                }
                widget = null;
                widget_config = null;
            };
            self = null;

        };
        this.subs.push(mc.subscribe("data_acquired:dashboard", {
            subscriber: this,
            callback: this.onDashboardDataAcquired
        }));
        mc.publish("data_requested:dashboard", dashName);

        this.removeRefs = function () {
            var self = this;
            for (var i = 0; i < this.subs.length; i++) {
                mc.remove(this.subs[i]);
                self.subs[i] = null;
            };
            this.subs = [];
            self = null;

        };
        mc.subscribe("clear:dashboard", {
            subscriber: this,
            callback: this.removeRefs,
            once: true
        });
    };
    /**
     * @name module:Dashboard#toString
     * @function
     * @return {String} Module name
     */
    Dashboard.prototype.toString = function () {
        return "Dashboard";
    };
/**
         * Renders up the whole dashboard with its widgets and so on.
         * @function module:Dashboard#addWidget
         * @param config {Object}  Configuration object for Widget
         * @example
         *  a.addWidget({
        title: "Очередь пациентов по профилям",
        amconfig: {
            "type": "serial",
            "pathToImages": "http://cdn.amcharts.com/lib/3/images/",
            "categoryField": "category",
            "rotate": true,
            "startDuration": 1,
            "categoryAxis": {
                "autoRotateCount": -5,
                "gridPosition": "start",
                "inside": true
            },
            "trendLines": [],
            "graphs": [
                {
                    "balloonText": "[[title]] of [[category]]:[[value]]",
                    "fillAlphas": 1,
                    "id": "AmGraph-1",
                    "title": "",
                    "type": "column",
                    "valueField": "value"
      }
     ],
            "guides": [],
            "valueAxes": [
                {
                    "axisTitleOffset": -7,
                    "id": "ValueAxis-1",
                    "title": "Кол-во человек"
      }
     ],
            "allLabels": [],
            "balloon": {},
            "titles": [
                {
                    "id": "Title-1",
                    "size": 15,
                    "text": ""
      }
     ],

        },
        datasource: {
            data: {
                MDX: 'SELECT NON EMPTY {TOPPERCENT(ORDER([ProfileMODep].[H1].[Profile].Members,Measures.[%COUNT],BDESC),80),%LABEL(SUM(BOTTOMPERCENT(ORDER([ProfileMODep].[H1].[Profile].Members,Measures.[%COUNT],BDESC),20)),"Другой",,,,"font-style:italic;")} ON 1 FROM [QueueCube]'
            }
        },
        filters: [{
            name: "status",
            path: "[status].[H1].[status]",
            value: "&[0]",
            valueName: "0"
        }]
    });
         */
    Dashboard.prototype.addWidget = function (config) {
            var self = this;
            var def = $.Deferred();
            var config = config || {};
            config.dashboard = this;
            config.id = this.widgets.length;
            config.promise = def;
            //Put promise to widget constructor
            var widget = new Widget(config);
            this.widgets[this.widgets.length] = widget;
            if (this.activeWidget == null) {
                this.activeWidget = 0;
                App.setTitle(widget.name);
                //mc.publish("set_active_widget", { id: 0 });
            }

        /** TODO: make widget page change from popover
            var name = widget.name;
            if (!name) name = "Widget #" + this.widgets.length.toString();
            var el = $("
" + name + "
");
            el.on("tap", function(e) {
                var slide = $(self.config.holder).find(".slide").get(0);
                var offset = (parseInt($(e.target).attr("num"))-1) * slide.offsetWidth;
                // Move slide
                var slider = $(self.config.holder).find('.slide-group').get(0);
                slider.style['-webkit-transition-duration'] = '.2s';
                slider.style.webkitTransform = 'translate3d(-' + offset + 'px,0,0)';
                $("#widgetList").removeClass("visible");
                $('div.backdrop').remove();
            });
            $("#widgetList").find(".table-view").append(el);
**/
            widget = null;
            return def.promise();
        };

        Dashboard.prototype.createHolder = function(){
            var holder = (this.config && this.config.holder) ? this.config.holder : "mainScreen > .content";

            //temp//
            /*$(holder + " > *").remove();
            var tbl = $("

");
            tbl.appendTo(holder);
            return;*/
            ///////////

                require(['text!../views/Dashboard.html'], function (html) {
                    $(holder + " > *").remove();
                    $(holder).append(html);
                });
        };
             /**
         * Renders up the whole dashboard with its widgets and so on.
         * @function module:Dashboard#render
         */

        Dashboard.prototype.render = function () {
            App.setTitle("");
            for (var i = 0; i < this.widgets.length; i++) {
                this.widgets[i].renderWidget();
            }
            var self = this;
            //Handling active widget change
            $(this.config.holder).off("slide").on("slide", function (e) {
                if (self.activeWidget != e.originalEvent.detail.slideNumber) {
                    self.activeWidget = e.originalEvent.detail.slideNumber;
                    var w = App.a.widgets[self.activeWidget];
                    $("#btnMainBack").hide();
                    $("#btnMainDrillthrough").hide();
                    if (w.pivot) {
                        $("#btnMainDrillthrough").show();
                        if (w.pivot.pivotView.tablesStack.length > 1) $("#btnMainBack").show();
                    }
                    App.setTitle(w.name);
                    if (mc) mc.publish("set_active_widget", {
                        id: self.activeWidget
                    });
                }
            });

           // setTimeout(this.tileView, 1000);

            return this;
        };

        Dashboard.prototype.tileView = function() {
            var slide = $(App.a.config.holder).find('.slide-group');
            var tbl = $("

");
            var tr = null;
            var td = null;
            var c = 0;
            slide.find(".slide").each(function(n, e){
                if (c == 0) {
                    tr = $("

");
                }
                tr.appendTo(tbl);
                td = $("	");
                $(e).find("div:eq(0)").appendTo(td);
                td.appendTo(tr);
                c++;
                if (c == 2) c = 0;
                console.log(e);
            });

            tbl.css("width", "300px")
                .css("border", "1px solid")
                .appendTo(App.a.config.holder);

            $(App.a.config.holder).find(".slider").remove();
        }

    return Dashboard;

})<commit_msg>pivot support left-right markers<commit_after>/**
 * @fileOverview
 * Dashboard module

 * @author Shmidt Ivan
 * @version 0.0.1
 * @module Dashboard
 * @requires DashboardConfig
 * @requires Widget
 * @requires Filter
 * @requires MessageCenter
 * @requires jQuery
 * @todo Delete jQuery dependency
 */
define([
    'DashboardConfig',
    'Widget',
    'Filter',
    'MessageCenter',
    "WidgetMap"
], function (DashboardConfiguration, Widget, Filter, mc, WidgetMap) {
    'use strict';
    /**
     * @class
     * @class Dashboard
     * @alias module:Dashboard
     * @listens module:MessageCenter#filters_acquired
     * @fires module:MessageCenter#filters_requested
     * @return {Dashboard} New dashboard object
     */
    function Dashboard(dashName) {
        /**@lends module:Dashboard#*/
        /**
         * Array of Widget objects
         * @var {Array<module:Widget>}
         * @name module:Dashboard#widgets
         * @todo Make this one private
         */
        this.widgets = [];
        /**
         * Flag, that shows current active widget
         * @var {number} module:Dashboard#activeWidget
         * @public
         */
        this.activeWidget = undefined;
        this.subs = [];
        /**
         * Dashboard config
         * @var {module:DashboardConfig} module:Dashboard#config
         */
        this.config = new DashboardConfiguration();
        /****
        Methods
        *****/
        this.createHolder();
        this.onDashboardDataAcquired = function (d) {
            $("#btnMainFilter").show();
            if(d === "null"){
            //No widgets in dashboard
                return;
            }
            App.filters = [];
            var requestedFiltersForCube = [];
            var widgets = d.children;
            var self = this;
            for (var i = 0; i < widgets.length; i++) {

                var widget = widgets[i];
                var widget_config = WidgetMap[widget.type];
                if (!widget_config) {
                    widget_config = WidgetMap["null"]
                }
                widget_config.datasource = {
                    pivot: widget.dataSource,
                    data: {
                        MDX: widget.mdx
                    }
                };

                if (widget.type == "pivot") {
                    widget_config.datasource.data.MDX = widget.basemdx;
                }
                widget_config.filters = [];
                _.each(widget.children, function (filter) {
                    widget_config.filters.push({
                        name: filter.label,
                        path: filter.path,
                        value: filter.value
                    });
                });

                widget_config.config.title = {
                    text: widget.title
                };
                self.addWidget(widget_config);
                self.widgets[self.widgets.length - 1].cube = widgets[i].cube;
                if (widgets[i].cube) {
                    mc.publish('filters_requested', {cube: widgets[i].cube, widget: self.widgets[self.widgets.length - 1]});
                }
                if (widgets[i].controls) {
                    self.widgets[self.widgets.length - 1].controls = [];
                    for (var k = 0; k < widgets[i].controls.length; k++) if (widgets[i].controls[k].value != ""){
                        self.widgets[self.widgets.length - 1].controls.push(widgets[i].controls[k]);
                    }
                }

                widget = null;
                widget_config = null;
            };
            self = null;
            this.updateMarkers();
        };

        this.subs.push(mc.subscribe("data_acquired:dashboard", {
            subscriber: this,
            callback: this.onDashboardDataAcquired
        }));
        mc.publish("data_requested:dashboard", dashName);

        this.removeRefs = function () {
            this.hideMarkers();
            var self = this;
            for (var i = 0; i < this.subs.length; i++) {
                mc.remove(this.subs[i]);
                self.subs[i] = null;
            };
            this.subs = [];
            self = null;

        };
        mc.subscribe("set_active_widget", {
            subscriber: this,
            callback: this.updateMarkers
        });
        mc.subscribe("clear:dashboard", {
            subscriber: this,
            callback: this.removeRefs,
            once: true
        });
    };

    Dashboard.prototype.hideMarkers = function() {
        $(".tri-left").hide();
        $(".tri-right").hide();
    };

    Dashboard.prototype.updateMarkers = function() {
        $(".tri-left").hide();
        $(".tri-right").hide();
        if (App.a.widgets.length == 0) return;
        if (App.a.activeWidget == 0) {
            $(".tri-right").show();
            return;
        }
        if (App.a.activeWidget == App.a.widgets.length - 1) {
            $(".tri-left").show();
            return;
        }
        $(".tri-right").show();
        $(".tri-left").show();
    }

    /**
     * @name module:Dashboard#toString
     * @function
     * @return {String} Module name
     */
    Dashboard.prototype.toString = function () {
        return "Dashboard";
    };
/**
         * Renders up the whole dashboard with its widgets and so on.
         * @function module:Dashboard#addWidget
         * @param config {Object}  Configuration object for Widget
         * @example
         *  a.addWidget({
        title: "Очередь пациентов по профилям",
        amconfig: {
            "type": "serial",
            "pathToImages": "http://cdn.amcharts.com/lib/3/images/",
            "categoryField": "category",
            "rotate": true,
            "startDuration": 1,
            "categoryAxis": {
                "autoRotateCount": -5,
                "gridPosition": "start",
                "inside": true
            },
            "trendLines": [],
            "graphs": [
                {
                    "balloonText": "[[title]] of [[category]]:[[value]]",
                    "fillAlphas": 1,
                    "id": "AmGraph-1",
                    "title": "",
                    "type": "column",
                    "valueField": "value"
      }
     ],
            "guides": [],
            "valueAxes": [
                {
                    "axisTitleOffset": -7,
                    "id": "ValueAxis-1",
                    "title": "Кол-во человек"
      }
     ],
            "allLabels": [],
            "balloon": {},
            "titles": [
                {
                    "id": "Title-1",
                    "size": 15,
                    "text": ""
      }
     ],

        },
        datasource: {
            data: {
                MDX: 'SELECT NON EMPTY {TOPPERCENT(ORDER([ProfileMODep].[H1].[Profile].Members,Measures.[%COUNT],BDESC),80),%LABEL(SUM(BOTTOMPERCENT(ORDER([ProfileMODep].[H1].[Profile].Members,Measures.[%COUNT],BDESC),20)),"Другой",,,,"font-style:italic;")} ON 1 FROM [QueueCube]'
            }
        },
        filters: [{
            name: "status",
            path: "[status].[H1].[status]",
            value: "&[0]",
            valueName: "0"
        }]
    });
         */
    Dashboard.prototype.addWidget = function (config) {
            var self = this;
            var def = $.Deferred();
            var config = config || {};
            config.dashboard = this;
            config.id = this.widgets.length;
            config.promise = def;
            //Put promise to widget constructor
            var widget = new Widget(config);
            this.widgets[this.widgets.length] = widget;
            if (this.activeWidget == null) {
                this.activeWidget = 0;
                App.setTitle(widget.name);
                widget.onActivate();
                //mc.publish("set_active_widget", { id: 0 });
            }

        /** TODO: make widget page change from popover
            var name = widget.name;
            if (!name) name = "Widget #" + this.widgets.length.toString();
            var el = $("
" + name + "
");
            el.on("tap", function(e) {
                var slide = $(self.config.holder).find(".slide").get(0);
                var offset = (parseInt($(e.target).attr("num"))-1) * slide.offsetWidth;
                // Move slide
                var slider = $(self.config.holder).find('.slide-group').get(0);
                slider.style['-webkit-transition-duration'] = '.2s';
                slider.style.webkitTransform = 'translate3d(-' + offset + 'px,0,0)';
                $("#widgetList").removeClass("visible");
                $('div.backdrop').remove();
            });
            $("#widgetList").find(".table-view").append(el);
**/
            widget = null;
            return def.promise();
        };

        Dashboard.prototype.createHolder = function(){
            var holder = (this.config && this.config.holder) ? this.config.holder : "mainScreen > .content";

            //temp//
            /*$(holder + " > *").remove();
            var tbl = $("

");
            tbl.appendTo(holder);
            return;*/
            ///////////

                require(['text!../views/Dashboard.html'], function (html) {
                    $(holder + " > *").remove();
                    $(holder).append(html);
                });
        };
             /**
         * Renders up the whole dashboard with its widgets and so on.
         * @function module:Dashboard#render
         */

        Dashboard.prototype.render = function () {
            App.setTitle("");
            for (var i = 0; i < this.widgets.length; i++) {
                this.widgets[i].renderWidget();
            }
            var self = this;
            //Handling active widget change
            $(this.config.holder).off("slide").on("slide", function (e) {
                if (self.activeWidget != e.originalEvent.detail.slideNumber) {
                    var oldWidget = App.a.widgets[self.activeWidget];
                    if (oldWidget) oldWidget.onDeactivate();
                    self.activeWidget = e.originalEvent.detail.slideNumber;
                    var w = App.a.widgets[self.activeWidget];
                    if (w) w.onActivate();

                    $("#btnMainBack").hide();
                    $("#btnMainDrillthrough").hide();
                    if (w.pivot) {
                        $("#btnMainDrillthrough").show();
                        if (w.pivot.pivotView.tablesStack.length > 1) $("#btnMainBack").show();
                    }
                    App.setTitle(w.name);
                    if (mc) mc.publish("set_active_widget", {
                        id: self.activeWidget
                    });
                }
            });

           // setTimeout(this.tileView, 1000);

            return this;
        };

        Dashboard.prototype.tileView = function() {
            var slide = $(App.a.config.holder).find('.slide-group');
            var tbl = $("

");
            var tr = null;
            var td = null;
            var c = 0;
            slide.find(".slide").each(function(n, e){
                if (c == 0) {
                    tr = $("

");
                }
                tr.appendTo(tbl);
                td = $("	");
                $(e).find("div:eq(0)").appendTo(td);
                td.appendTo(tr);
                c++;
                if (c == 2) c = 0;
                console.log(e);
            });

            tbl.css("width", "300px")
                .css("border", "1px solid")
                .appendTo(App.a.config.holder);

            $(App.a.config.holder).find(".slider").remove();
        }

    return Dashboard;

})<|endoftext|>


<commit_before>var web = require('browser_process');
var util = require('util');
var rdbg = require('rdbg');
var temp = require('temp');

var debug = util.debuglog('amok-browser');

function plugin(command, args, output) {
  if (typeof args === 'undefined') {
    args = [];
  } else {
    args = args.slice(0);
  }

  return function browser(client, runner, done) {
    var url = runner.get('url');
    var port = runner.get('port');

    temp.track(true);
    temp.mkdir('amok', function (error, dirname) {
      args.unshift.apply(args, web.options(command, {
        profile: dirname,
        url: url,
        debug: port,
      }));

      debug('spawn %s %s', command, args.join(' '));
      web.spawn(command, args, function (error, browser) {
        if (error) {
          debug('bail %s', error.description);
          return done(error);
        }

        if (output) {
          browser.stdout.pipe(output);
          browser.stderr.pipe(output);
        }

        runner.once('close', function kill() {
          debug('kill');
          browser.kill('SIGTERM');
        });

        debug('find %s', url);

        process.nextTick(function find() {
          rdbg.get(port, 'localhost', function (error, targets) {
            if (error) {
              return process.nextTick(find);
            }

            var target = targets.filter(function (target) {
              return url === target.url;
            })[0];

            if (!target) {
              return process.nextTick(find);
            }

            debug('ready');
            done();
          });
        });
      });
    });
  };
}

module.exports = plugin;
<commit_msg>Use no first run and no default browser check options when spawning browsers<commit_after>var web = require('browser_process');
var util = require('util');
var rdbg = require('rdbg');
var temp = require('temp');

var debug = util.debuglog('amok-browser');

function plugin(command, args, output) {
  if (typeof args === 'undefined') {
    args = [];
  } else {
    args = args.slice(0);
  }

  return function browser(client, runner, done) {
    var url = runner.get('url');
    var port = runner.get('port');

    temp.track(true);

    // TODO, move into browser_process.createProfile, deleting the first run file
    // should be equivilent of providing these options, and be compatible with how firefox does it.
    args.unshift('--no-first-run', '--no-default-browser-check');
    temp.mkdir('amok', function (error, dirname) {
      args.unshift.apply(args, web.options(command, {
        profile: dirname,
        url: url,
        debug: port,
      }));

      debug('spawn %s %s', command, args.join(' '));
      web.spawn(command, args, function (error, browser) {
        if (error) {
          debug('bail %s', error.description);
          return done(error);
        }

        if (output) {
          browser.stdout.pipe(output);
          browser.stderr.pipe(output);
        }

        runner.once('close', function kill() {
          debug('kill');
          browser.kill('SIGTERM');
        });

        debug('find %s', url);

        process.nextTick(function find() {
          rdbg.get(port, 'localhost', function (error, targets) {
            if (error) {
              return process.nextTick(find);
            }

            var target = targets.filter(function (target) {
              return url === target.url;
            })[0];

            if (!target) {
              return process.nextTick(find);
            }

            debug('ready');
            done();
          });
        });
      });
    });
  };
}

module.exports = plugin;
<|endoftext|>


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

export default class Animation {
	constructor(element, newPosition, duration, easing = 'linear', options = {}) {
		this.element = element;

		this.startingPosition = getElementTransformTranslateX(element);
		this.currentPosition = this.startingPosition;
		this.newPosition = newPosition;
		this.animationBezierCurve = getCubicBezierForEasing(easing);

		this.onStart = options.onStart;
		this.onEnd = options.onEnd;
		this.onStep = options.onStep;

		this.startTime;
		this.previousStepTime;
		this.duration = duration;
	}

	start() {
		this.requestId = window.requestAnimationFrame((time) => {
			this.startTime = time;
			this.step(time);
		});

		if (this.hasOwnProperty('onStart') && typeof this.onStart === 'function') {
			this.onStart();
		}
	}

	end() {
		if (this.requestId) {
			this.destroy();

			if (this.hasOwnProperty('onEnd') && typeof this.onEnd === 'function') {
				this.onEnd();
			}
		}
	}

	destroy() {
		if (this.requestId) {
			window.cancelAnimationFrame(this.requestId);
			delete this.requestId;
		}
	}

	step(currentTime) {
		let time = currentTime - this.startTime;
		let distance = this.newPosition - this.startingPosition;
		let positionChange = calculatePositionChange(time, distance, this.duration, this.animationBezierCurve);

		this.currentPosition = this.startingPosition + positionChange;

		renderElementAtHorizontalOffset(this.element, this.currentPosition);

		if (this.hasOwnProperty('onStep') && typeof this.onStep === 'function') {
			this.onStep();
		}

		if (this.currentPosition !== this.newPosition) {
			this.requestId = window.requestAnimationFrame(this.step.bind(this));
		} else {
			this.end();
		}
	}
}

function getCubicBezierForEasing(easing) {
	if (typeof easing === 'object' && easing.length === 4) {
		return CubicBezier.createCustomAnimation(
			easing[0],
			easing[1],
			easing[2],
			easing[3]
		);
	}

	switch (easing) {
		case 'ease':
			return CubicBezier.createEase();
		case 'easeIn':
			return CubicBezier.createEaseIn();
		case 'easeOut':
			return CubicBezier.createEaseOut();
		case 'easeInOut':
			return CubicBezier.createEaseInOut();
		case 'linear':
		default:
			return CubicBezier.createLinear();
	}
}

function renderElementAtHorizontalOffset(element, offset) {
	if (element instanceof Element) {
		element.style.transform = `translateX(${offset}px)`;
	}
}

function calculatePositionChange(time, distance, duration, animationBezierCurve) {
	let progress = time / duration;
	let positionChange = distance * animationBezierCurve.calculateVerticalForTime(progress);

	return positionChange;
}

function getElementTransformTranslateX(element) {
	if (window.getComputedStyle) {
		let style = window.getComputedStyle(element);
		let calculatedTransformation = style.transform || style.webkitTransform || style.mozTransform;

		let transformationMatrix3D = calculatedTransformation.match(/^matrix3d\((.+)\)$/);
		if (transformationMatrix3D) {
			return parseFloat(transformationMatrix3D[1].split(', ')[13]);
		}

		let transformationMatrix = calculatedTransformation.match(/^matrix\((.+)\)$/);
		if (transformationMatrix) {
			return parseFloat(transformationMatrix[1].split(', ')[4]);
		}
	}

	return 0;
}
<commit_msg>translateZ on transform<commit_after>import CubicBezier from './CubicBezier';

export default class Animation {
	constructor(element, newPosition, duration, easing = 'linear', options = {}) {
		this.element = element;

		this.startingPosition = getElementTransformTranslateX(element);
		this.currentPosition = this.startingPosition;
		this.newPosition = newPosition;
		this.animationBezierCurve = getCubicBezierForEasing(easing);

		this.onStart = options.onStart;
		this.onEnd = options.onEnd;
		this.onStep = options.onStep;

		this.startTime;
		this.previousStepTime;
		this.duration = duration;
	}

	start() {
		this.requestId = window.requestAnimationFrame((time) => {
			this.startTime = time;
			this.step(time);
		});

		if (this.hasOwnProperty('onStart') && typeof this.onStart === 'function') {
			this.onStart();
		}
	}

	end() {
		if (this.requestId) {
			this.destroy();

			if (this.hasOwnProperty('onEnd') && typeof this.onEnd === 'function') {
				this.onEnd();
			}
		}
	}

	destroy() {
		if (this.requestId) {
			window.cancelAnimationFrame(this.requestId);
			delete this.requestId;
		}
	}

	step(currentTime) {
		let time = currentTime - this.startTime;
		let distance = this.newPosition - this.startingPosition;
		let positionChange = calculatePositionChange(time, distance, this.duration, this.animationBezierCurve);

		this.currentPosition = this.startingPosition + positionChange;

		renderElementAtHorizontalOffset(this.element, this.currentPosition);

		if (this.hasOwnProperty('onStep') && typeof this.onStep === 'function') {
			this.onStep();
		}

		if (this.currentPosition !== this.newPosition) {
			this.requestId = window.requestAnimationFrame(this.step.bind(this));
		} else {
			this.end();
		}
	}
}

function getCubicBezierForEasing(easing) {
	if (typeof easing === 'object' && easing.length === 4) {
		return CubicBezier.createCustomAnimation(
			easing[0],
			easing[1],
			easing[2],
			easing[3]
		);
	}

	switch (easing) {
		case 'ease':
			return CubicBezier.createEase();
		case 'easeIn':
			return CubicBezier.createEaseIn();
		case 'easeOut':
			return CubicBezier.createEaseOut();
		case 'easeInOut':
			return CubicBezier.createEaseInOut();
		case 'linear':
		default:
			return CubicBezier.createLinear();
	}
}

function renderElementAtHorizontalOffset(element, offset) {
	if (element instanceof Element) {
		element.style.transform = `translateX(${offset}px) translateZ(0)`;
	}
}

function calculatePositionChange(time, distance, duration, animationBezierCurve) {
	let progress = time / duration;
	let positionChange = distance * animationBezierCurve.calculateVerticalForTime(progress);

	return positionChange;
}

function getElementTransformTranslateX(element) {
	if (window.getComputedStyle) {
		let style = window.getComputedStyle(element);
		let calculatedTransformation = style.transform || style.webkitTransform || style.mozTransform;

		let transformationMatrix3D = calculatedTransformation.match(/^matrix3d\((.+)\)$/);
		if (transformationMatrix3D) {
			return parseFloat(transformationMatrix3D[1].split(', ')[13]);
		}

		let transformationMatrix = calculatedTransformation.match(/^matrix\((.+)\)$/);
		if (transformationMatrix) {
			return parseFloat(transformationMatrix[1].split(', ')[4]);
		}
	}

	return 0;
}
<|endoftext|>


<commit_before>var assert = require("assert");

function FiberPool(targetFiberCount) {
  assert.ok(this instanceof FiberPool);
  assert.strictEqual(typeof targetFiberCount, "number");

  var fiberStack = [];

  function makeNewFiber(Fiber) {
    // Just in case someone tampers with Fiber.yield, don't let that interfere
    // with our processing of the callback queue.
    var originalYield = Fiber.yield;

    var fiber = new Fiber(function () {
      while (true) {
        // Call Fiber.yield() to await further instructions.
        var entry = originalYield.call(Fiber);

        // Ensure this Fiber is no longer in the pool once it begins to
        // execute an entry.
        assert.strictEqual(fiberStack.indexOf(fiber), -1);

        if (entry.dynamics) {
          // Restore the dynamic environment of this fiber as if
          // entry.callback had been wrapped by Meteor.bindEnvironment.
          Object.keys(entry.dynamics).forEach(function (key) {
            fiber[key] = entry.dynamics[key];
          });
        }

        try {
          var result = entry.callback.apply(
            entry.context || null,
            entry.args || []
          );

          setImmediate(entry.resolve.bind(entry, result));

        } catch (error) {
          entry.reject(error);
        }

        // Remove all own properties of the fiber before returning it to
        // the pool.
        Object.keys(fiber).forEach(function (key) {
          delete fiber[key];
        });

        if (fiberStack.length < targetFiberCount) {
          fiberStack.push(fiber);
        } else {
          // If the pool has already reached the target maximum number of
          // Fibers, don't bother recycling this Fiber.
          break;
        }
      }
    });

    // Run the new Fiber up to the first yield point, so that it will be
    // ready to receive entries.
    fiber.run();

    return fiber;
  }

  // Run the entry.callback function in a Fiber either taken from the pool
  // or created anew if the pool is empty. This method returns a Promise
  // for the eventual result of the entry.callback function.
  this.run = function (entry, Promise) {
    assert.strictEqual(typeof entry, "object");
    assert.strictEqual(typeof entry.callback, "function");

    if (typeof Promise.Fiber !== "function") {
      return new Promise(function (resolve) {
        resolve(entry.callback.apply(
          entry.context || null,
          entry.args
        ));
      });
    }

    var fiber = fiberStack.pop() || makeNewFiber(Promise.Fiber);

    var promise = new Promise(function (resolve, reject) {
      entry.resolve = resolve;
      entry.reject = reject;
    });

    fiber.run(entry);

    return promise;
  };

  // Limit the maximum number of idle Fibers that may be kept in the
  // pool. Note that the run method will never refuse to create a new
  // Fiber if the pool is empty; it's just that excess Fibers might be
  // thrown away upon completion, if the pool is full.
  this.setTargetFiberCount = function (limit) {
    assert.strictEqual(typeof limit, "number");

    targetFiberCount = Math.max(limit, 0);

    if (targetFiberCount < fiberStack.length) {
      // If the requested target count is less than the current length of
      // the stack, truncate the stack and terminate any surplus Fibers.
      fiberStack.splice(targetFiberCount).forEach(function (fiber) {
        fiber.reset();
      });
    }

    return this;
  };
}

// Call pool.drain() to terminate all Fibers waiting in the pool and
// signal to any outstanding Fibers that they should exit upon completion,
// instead of reinserting themselves into the pool.
FiberPool.prototype.drain = function () {
  return this.setTargetFiberCount(0);
};

exports.makePool = function (targetFiberCount) {
  return new FiberPool(targetFiberCount || 20);
};
<commit_msg>Also use setImmediate for rejection scheduling.<commit_after>var assert = require("assert");

function FiberPool(targetFiberCount) {
  assert.ok(this instanceof FiberPool);
  assert.strictEqual(typeof targetFiberCount, "number");

  var fiberStack = [];

  function makeNewFiber(Fiber) {
    // Just in case someone tampers with Fiber.yield, don't let that interfere
    // with our processing of the callback queue.
    var originalYield = Fiber.yield;

    var fiber = new Fiber(function () {
      while (true) {
        // Call Fiber.yield() to await further instructions.
        var entry = originalYield.call(Fiber);

        // Ensure this Fiber is no longer in the pool once it begins to
        // execute an entry.
        assert.strictEqual(fiberStack.indexOf(fiber), -1);

        if (entry.dynamics) {
          // Restore the dynamic environment of this fiber as if
          // entry.callback had been wrapped by Meteor.bindEnvironment.
          Object.keys(entry.dynamics).forEach(function (key) {
            fiber[key] = entry.dynamics[key];
          });
        }

        try {
          var result = entry.callback.apply(
            entry.context || null,
            entry.args || []
          );

          setImmediate(entry.resolve.bind(entry, result));

        } catch (error) {
          setImmediate(entry.reject.bind(entry, error));
        }

        // Remove all own properties of the fiber before returning it to
        // the pool.
        Object.keys(fiber).forEach(function (key) {
          delete fiber[key];
        });

        if (fiberStack.length < targetFiberCount) {
          fiberStack.push(fiber);
        } else {
          // If the pool has already reached the target maximum number of
          // Fibers, don't bother recycling this Fiber.
          break;
        }
      }
    });

    // Run the new Fiber up to the first yield point, so that it will be
    // ready to receive entries.
    fiber.run();

    return fiber;
  }

  // Run the entry.callback function in a Fiber either taken from the pool
  // or created anew if the pool is empty. This method returns a Promise
  // for the eventual result of the entry.callback function.
  this.run = function (entry, Promise) {
    assert.strictEqual(typeof entry, "object");
    assert.strictEqual(typeof entry.callback, "function");

    if (typeof Promise.Fiber !== "function") {
      return new Promise(function (resolve) {
        resolve(entry.callback.apply(
          entry.context || null,
          entry.args
        ));
      });
    }

    var fiber = fiberStack.pop() || makeNewFiber(Promise.Fiber);

    var promise = new Promise(function (resolve, reject) {
      entry.resolve = resolve;
      entry.reject = reject;
    });

    fiber.run(entry);

    return promise;
  };

  // Limit the maximum number of idle Fibers that may be kept in the
  // pool. Note that the run method will never refuse to create a new
  // Fiber if the pool is empty; it's just that excess Fibers might be
  // thrown away upon completion, if the pool is full.
  this.setTargetFiberCount = function (limit) {
    assert.strictEqual(typeof limit, "number");

    targetFiberCount = Math.max(limit, 0);

    if (targetFiberCount < fiberStack.length) {
      // If the requested target count is less than the current length of
      // the stack, truncate the stack and terminate any surplus Fibers.
      fiberStack.splice(targetFiberCount).forEach(function (fiber) {
        fiber.reset();
      });
    }

    return this;
  };
}

// Call pool.drain() to terminate all Fibers waiting in the pool and
// signal to any outstanding Fibers that they should exit upon completion,
// instead of reinserting themselves into the pool.
FiberPool.prototype.drain = function () {
  return this.setTargetFiberCount(0);
};

exports.makePool = function (targetFiberCount) {
  return new FiberPool(targetFiberCount || 20);
};
<|endoftext|>