text:
var financeControllers = angular.module('financeControllers', []);

var dataTypes = {
  INT: "int",
  DATE: "date",
  STRING: "string"
};

financeControllers.controller('LoginController', function ($scope, $rootScope, $window, $routeParams, AuthenticationService, $http, $location, auth) {

  $scope.success = $routeParams.signup || false;
  if($scope.success) {
    $scope.message = "Sign Up success. You can Login now.";
  }

  $scope.login = function() {
    if(!$scope.user || !$scope.user.username || !$scope.user.password) {
      $scope.user = {username: "", password: ""};
    }
    $http({
      url: "/api/users/auth",
      method: "POST",
      data: angular.toJson($scope.user)
    }).then(function(response) {
          // success
          auth.setCredentials($scope.user.username, $scope.user.password);
          AuthenticationService.isLogged = true;
          $window.sessionStorage.token = response.data.token;
          $rootScope.user = response.data;
          $location.url("/dashboard");
        },
        function(response) { // optional
          // failed
          $scope.error = true;
          if(response.status === 401) {
            $scope.response = {errors:  {"username": ["Invalid username and password combination"]}};
          } else {
            $scope.response = response.data;
          }
        }
    );
  };
});

financeControllers.controller('SignupController', function ($scope, $rootScope, $location, UserService) {

  $scope.errorMessage = errorMessage;
  $scope.errorClass = errorClass;

  $scope.register = function() {
    $scope.error = false;
    $scope.message = null;
    UserService.signup($scope.user || {}).$promise.then(function() {
      $location.search('signup', 'true').path("/");
    }, function(response) {
      failure($scope, response)
    });
  };
});

financeControllers.controller('DashboardController', function ($scope, $modal, $location, $routeParams, BudgetService,
                                                               CategoryService, TransactionService, UserService) {
  $scope.usageLoaded = false;

  $scope.periods = [];

  for(var i = 0; i < 7; i++) {
    $scope.periods.push(moment().subtract(i, 'months').format("YYYY-MM"));
  }

  $scope.period = $routeParams.period || $scope.periods[0];

  $scope.reload = function() {
    $location.url("/dashboard/" + $scope.period);
  };

  var year = $scope.period.split("-")[0];
  var month = $scope.period.split("-")[1];

  $scope.usage = UserService.usage({month: month, year: year}, function() {
    $scope.usageLoaded = true;
  });

  $scope.transactionLoaded = false;
  $scope.transactionsOptions = {
    series: {
      lines: {
        show: true,
        fill: true,
        fillColor: {
          colors: [{opacity: 0}, {opacity: .3}]
        }
      },
      points: {
        show: !0,
        lineWidth: 2,
        fill: !0,
        fillColor: "#ffffff",
        symbol: "circle",
        radius: 5
      }
    },
    colors: ["#31C0BE"],
    grid: {
      hoverable: true,
      clickable: true,
      tickColor: "#f9f9f9"
    },
    xaxis: {
      mode: "time",
      timeformat: "%d-%b",
      tickSize: [1, "day"]
    },
    yaxis: {
      min: 0
    }
  };

  TransactionService.summary({month: month, year: year}, function (response) {
    $scope.transactionsData = [_.map(response, function(point) {return [point.key, point.value]})];
  });

  $scope.categoriesOptions = {
    series: {
      pie: {
        show: true,
        radius: 1,
        label: {
          show: true,
          radius: 3/4,
          formatter: labelFormatter,
          background: {
            opacity: 0.5
          }
        }
      }
    },
    colors: ["#60CD9B", "#66B5D7", "#EEC95A", "#E87352"]
  };

  CategoryService.summary({month: month, year: year}, function (response) {
    if(response.length == 0) {
      $scope.categoriesData = [{label: "No Data", data: 1}];
    } else {
      $scope.categoriesData = _.map(response, function(point) {return {label: point.label, data: point.value}});
    }
  });

  $scope.monthlyOptions = {
    series: {
      bars: {
        show: true,
        barWidth: 12*24*60*60*800,
        order: 1,
        fill: 0.9
      }
    },
    xaxis: {
      mode: "time",
      tickLength: 0,
      tickSize: [1, "month"],
      axisLabel: 'Month'
    },
    yaxis: {
      min: 0
    },
    grid: {
      hoverable: true,
      borderWidth: 0
    },
    colors: ["#60CD9B", "#66B5D7", "#EEC95A", "#E87352"]
  };

  TransactionService.monthly(function (response) {
    var spendings =
        _.chain(response)
            .filter(function(point){ return point.pointType == 'MONTHLY_SPEND'})
            .map(function(point){ return [point.key, point.value]})
            .value();
    var budgets =
        _.chain(response)
            .filter(function(point){ return point.pointType == 'MONTHLY_BUDGET'})
            .map(function(point){ return [point.key, point.value]})
            .value();

    $scope.monthlyData = [
      {label: "Budget", data: budgets},
      {label: "Spending", data: spendings}
    ];
  });

  TransactionService.todayRecurrings(function(response) {
    $scope.recurringTransactions = response;
  });

});

financeControllers.controller('ProfileController', function ($scope, UserService) {

  // method allow child controllers to access parent controller's scope
  $scope.updateSuccess = function(message) {
    $scope.success = true;
    $scope.message = message;
  };
});

financeControllers.controller('UpdateProfileController', function ($scope, $rootScope, UserService) {

  $scope.loaded = false;
  $scope.errorMessage = errorMessage;
  $scope.errorClass = errorClass;

  $scope.user = $rootScope.user = UserService.ping(function() {
    $scope.loaded = true;
  });

  $scope.updateProfile = function() {
    var user = $scope.user || {};
    UserService.update(angular.toJson(user), function() {
      // ok
      $scope.updateSuccess("Successfully update profile");
    }, function() {
      // error

    })
  };
});

financeControllers.controller('ChangePasswordController', function ($scope, UserService) {

  $scope.loaded = false;
  $scope.errorMessage = errorMessage;
  $scope.errorClass = errorClass;

  $scope.changePassword = function() {
    var password = $scope.password || {};
    UserService.changePassword(angular.toJson(password), function() {
      // ok
      $scope.updateSuccess("Successfully change password");
      $scope.password = {};
      clearErrors($scope);
    }, function(response) {
      // error
      failure($scope, response);
    })
  };
});

function labelFormatter(label, series) {
  return "
" + Math.round(series.percent) + "%
";
}

financeControllers.controller('ManageController', function ($scope, $routeParams, $modal, appConfig, BudgetService, TransactionService, UserService) {

  $scope.loaded = false;
  $scope.errorMessage = errorMessage;
  $scope.errorClass = errorClass;

  var groups = [];

  var current = moment().format("YYYY-MM");
  var period = $routeParams.period || current;
  var year = period.split("-")[0];
  var month = period.split("-")[1];

  // usage
  $scope.usageLoaded = false;
  $scope.usage = UserService.usage({month: month, year: year}, function() {
    $scope.usageLoaded = true;
  });

  for(var i = -1; i < 2; i++) {
    var now = moment(period, "YYYY-MM").toDate();
    var date = now.setMonth(now.getMonth() + i);
    var path = moment(date).format("YYYY-MM");
    groups.push({
      date: date,
      display: moment(date).format("MMM YYYY"),
      path: path,
      active: path == period,
      current: path == current
    });
  }

  $scope.groups = groups;
  $scope.summary = UserService.account({month: month, year: year}, function() {
    $scope.loaded = true;
  });

  $scope.$watch(
      "summary",
      function(summary) {
        var totalIncome = 0.0;
        var totalActual = 0.0;
        var totalProjected = 0.0;
        var  changed = false;
        _.forEach(summary.groups, function(group) {

          var projected = 0.0;
          var actual = 0.0;

          _.forEach(group.budgets, function (budget) {
            changed = true;

            if (group.type == 'INCOME') {
              // total actual income
              totalIncome += budget.actual;
            } else {
              // total spending budget
              totalProjected += budget.projected;
              // total actual spending
              totalActual += budget.actual;
            }

            budget.remaining = budget.projected - budget.actual;

            projected += budget.projected;
            actual += budget.actual;
          });

          group.projected = projected;
          group.actual = actual;
          group.remaining = group.projected - group.actual;
        });

        if(changed) {
          $scope.usage.income = totalIncome;
          $scope.usage.projected = totalProjected;
          $scope.usage.actual = totalActual;
          $scope.usage.remaining = totalProjected - totalActual;
        }
      },
      true
  );

  $scope.openBudgetModal = function (budget) {
    var modalInstance = $modal.open({
      templateUrl: 'budgetModal.html',
      controller: BudgetModalController,
      resolve: {
        budget: function() {
          return budget;
        }
      }
    });

    modalInstance.result.then(function (selected) {
      BudgetService.update(selected);
    }, function () {

    });
  };

  $scope.openTransactionModal = function (budget) {
    var modalInstance = $modal.open({
      templateUrl: 'transactionModal.html',
      controller: TransactionModalController,
      resolve: {
        budget: function() {
          return budget;
        }
      }
    });
  };

  $scope.openTransactionsModal = function (budget) {
    $scope.transactionsLoaded = false;
    $scope.transactionAction = true;
    $scope.deleteTransaction = function (transactions, transaction) {
      transaction.loading = true;
      TransactionService.delete({id: transaction.id}, function() {
        // update UI
        budget.actual = budget.actual - transaction.amount;
        transactions.splice(transactions.indexOf(transaction), 1);
      }, function(response) {
        errorModal($modal, response.data.errors);
      });
    };

    $modal.open({
      templateUrl: '/app/partials/transactions.html?' + appConfig.version,
      scope: $scope,
      controller: TransactionsModalController,
      size: 'lg',
      resolve: {
        transactions: function() {
          return BudgetService.query({id: budget.id, transactions: 'transactions'}, function() {
            $scope.transactionsLoaded = true;
          });
        },
        budget: function() {
          return budget;
        }
      }
    });
  };

  $scope.changeGroup = function(group) {

//    _.forEach($scope.data.groups, function(g) {g.active = false});
//    _.find($scope.data.groups, function(g) {
//      return g.date == group.date
//    }).active = true;
//
//    $scope.data.loaded = false;
//    var selectedDate = new Date(group.date);
//    var summaries = UserService.account({month: selectedDate.getMonth() + 1, year: selectedDate.getFullYear()}, function() {
//      $scope.data.loaded = true;
//    });
//    $scope.data.summary = summaries;
  };

  TransactionService.todayRecurrings(function(response) {
    $scope.recurringTransactions = response;
  });
});

var BudgetModalController = function ($scope, $modalInstance, budget) {

  $scope.data = {};
  $scope.selected = budget;
  $scope.original = angular.copy(budget);

  $scope.ok = function () {
    if(!$scope.selected.projected) {
      $scope.selected.projected = 0;
    }

    if(!$scope.selected.actual) {
      $scope.selected.actual = 0;
    }
    $modalInstance.close($scope.selected);
  };

  $scope.cancel = function () {
    $scope.selected.name = $scope.original.name;
    $scope.selected.projected = $scope.original.projected;
    $scope.selected.actual = $scope.original.actual;
    $modalInstance.dismiss('cancel');
  };
};

var TransactionModalController = function ($scope, $modalInstance, budget, TransactionService) {

  $scope.selected = budget;
  $scope.original = angular.copy(budget);
  $scope.transaction = {budget: {id: budget.id}};

  $scope.errorMessage = errorMessage;
  $scope.errorClass = errorClass;

  // TODO https://github.com/angular-ui/bootstrap/issues/969
  $scope.ok = function (form) {
    $scope.transaction.loading = true;
    TransactionService.save($scope.transaction).$promise.then(function() {
      budget.actual += $scope.transaction.amount;
      $scope.transaction.loading = false;
      $modalInstance.close();
    }, function(response) {
      $scope.form = form;
      $scope.transaction.loading = false;
      failure($scope, response);
    });

  };

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

var TransactionsModalController = function ($scope, $modalInstance, budget, transactions) {

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

financeControllers.controller('BudgetController', function ($scope, CategoryService, BudgetService) {

  // cache categories, reuse when validation failed.
  var categories = null;
  $scope.loaded = false;
  $scope.budget = {};

  $scope.errorMessage = errorMessage;
  $scope.errorClass = errorClass;

  CategoryService.query(function(response) {
    categories = response;
    $scope.categories = response;
    $scope.loaded = true;
  });

  $scope.createBudget = function() {
    $scope.success = false;
    $scope.error = false;
    $scope.message = null;
    var budget = $scope.budget;
    if(budget.category) {
      budget.categoryId = budget.category.id;
    } else {
      budget.categoryId = null;
    }
    BudgetService.save($scope.budget).$promise.then(function() {
      $scope.success = true;
      $scope.message = "Successfully created Budget";
      $scope.budget = {};
      success($scope);
      // repopulate categories
      $scope.categories = categories;
    }, function(response) {
      failure($scope, response);
      // repopulate categories
      $scope.categories = categories;
    });
  }
});

financeControllers.controller('CategoryController', function ($scope, CategoryService) {

  $scope.errorMessage = errorMessage;
  $scope.errorClass = errorClass;

  $scope.createCategory = function() {
    $scope.success = false;
    $scope.error = false;
    $scope.message = null;
    CategoryService.save($scope.category || {}).$promise.then(function() {
      $scope.success = true;
      $scope.message = "Successfully created Category";
      $scope.category = {};
      clearErrors($scope);
    }, function(response) {
      failure($scope, response)
    });
  }
});

financeControllers.controller('RecurringsController', function ($scope, $modal, appConfig, RecurringService) {

  $scope.loaded = false;
  $scope.recurrings = RecurringService.query(function() {
    $scope.loaded = true;
  });

  $scope.confirmDelete = function (recurring) {
    var modalInstance = $modal.open({
      templateUrl: '/app/partials/confirmDeleteModal.html?' + appConfig.version,
      controller: ConfirmDeleteModalController,
      resolve: {
        modal: function() {
          return recurring;
        },
        message: function() {
          return ' this recurring';
        }
      }
    });

    modalInstance.result.then(function (selected) {
      selected.$delete({id: selected.id});
      $scope.recurrings.splice($scope.recurrings.indexOf(selected), 1);
    }, function (response) {
      errorModal($modal, response.data.errors);
    });
  };

  $scope.openRecurringModal = function (recurring) {
    $scope.transactionsLoaded = false;

    $modal.open({
      templateUrl: '/app/partials/transactions.html',
      scope: $scope,
      controller: RecurringModalController,
      size: 'lg',
      resolve: {
        transactions: function() {
          return RecurringService.transactions({id: recurring.id, path: 'transactions'}, function() {
            $scope.transactionsLoaded = true;
          });
        },
        recurring: function() {
          return recurring;
        }
      }
    });
  };

});

financeControllers.controller('RecurringController', function ($scope, RecurringService, BudgetService) {

  // cache budgets, reuse when validation failed.
  var budgets = null;
  $scope.loaded = false;
  $scope.recurring = {};

  $scope.errorMessage = errorMessage;
  $scope.errorClass = errorClass;

  BudgetService.query(function(response) {
    budgets = response;
    $scope.budgets = response;
    $scope.loaded = true;
  });

  $scope.createRecurring = function() {
    $scope.success = false;
    $scope.error = false;
    $scope.message = null;
    var recurring = $scope.recurring;
    if(recurring.budget) {
      recurring.budgetId = recurring.budget.id;
    } else {
      recurring.budgetId = null;
    }
    RecurringService.save($scope.recurring).$promise.then(function() {
      $scope.success = true;
      $scope.message = "Successfully created Recurring";
      $scope.recurring = {};
      clearErrors($scope);
      // repopulate budgets
      $scope.budgets = budgets;
    }, function(response) {
      failure($scope, response)
      // repopulate budgets
      $scope.budgets = budgets;
    });
  }
});

financeControllers.controller('CategoriesController', function ($scope, $modal, appConfig, CategoryService) {

  $scope.loaded = false;
  $scope.categories = CategoryService.query(function() {
    $scope.loaded = true;
  });

  $scope.confirmDelete = function (category) {
    var modalInstance = $modal.open({
      templateUrl: '/app/partials/confirmDeleteModal.html?' + appConfig.version,
      controller: ConfirmDeleteModalController,
      resolve: {
        modal: function() {
          return category;
        },
        message: function() {
          return ' this category';
        }
      }
    });

    modalInstance.result.then(function (selected) {
      selected.$delete({id: selected.id}, function() {
        $scope.categories.splice($scope.categories.indexOf(selected), 1);
      }, function(response) {
        errorModal($modal, response.data.errors);
      });
    });
  };

  $scope.openBudgetsModal = function (category) {
    $scope.budgetsLoaded = false;

    $modal.open({
      templateUrl: '/app/partials/budgets.html',
      scope: $scope,
      controller: BudgetsModalController,
      size: 'lg',
      resolve: {
        category: function() {
          return category;
        },
        budgets: function() {
          return CategoryService.budgets(category, function() {
            $scope.budgetsLoaded = true;
          });
        }
      }
    });
  };
});

financeControllers.controller('BudgetsController', function ($scope, $modal, appConfig, BudgetService) {

  $scope.loaded = false;
  $scope.budgets = BudgetService.query(function() {
    $scope.loaded = true;
  });

  $scope.confirmDelete = function (budget) {
    var modalInstance = $modal.open({
      templateUrl: '/app/partials/confirmDeleteModal.html?' + appConfig.version,
      controller: ConfirmDeleteModalController,
      resolve: {
        modal: function() {
          return budget;
        },
        message: function() {
          return ' this budget';
        }
      }
    });

    modalInstance.result.then(function (selected) {
      selected.$delete({id: selected.id}, function() {
        $scope.budgets.splice($scope.budgets.indexOf(selected), 1);
      }, function(response) {
        errorModal($modal, response.data.errors);
      });
    });
  };
});

var BudgetsModalController = function ($scope, $modalInstance, category, budgets) {
  $scope.selected = category;
  $scope.budgets = budgets;
  $scope.cancel = function () {
    $modalInstance.dismiss('cancel');
  };
};

var RecurringModalController = function ($scope, $modalInstance, recurring, transactions) {

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

};

financeControllers.controller('ReportsController', function ($scope, ReportService) {

  $scope.transactionsLoaded = false;
  ReportService.transactions(angular.toJson({}), function (response) {
    $scope.transactions = response;
    $scope.transactionsLoaded = true;
  });
  $scope.doSearch = function () {
    var search = $scope.search || {};
    $scope.transactionsLoaded = false;
    ReportService.transactions(angular.toJson(search), function (response) {
      $scope.transactions = response;
      $scope.transactionsLoaded = true;
    })
  };

});

function getErrors(transaction) {
 var errors = [];

 if (isNaN(transaction.amount)) {
   errors.push("Invalid amount");
 }

 if (!transaction.transactionOn || isNaN(transaction.transactionOn.getTime())) {
   errors.push("Invalid Date");
 }

 if (!transaction.budget || (!transaction.budget.id && transaction.budget.id != 0)) {
   errors.push("Transaction must be categorized");
 }

 return errors;
}

var modifyTransactionController = function ($scope, $modalInstance, transaction, prop, dataType) {
  $scope.transaction = transaction;
  $scope.dataType = dataType;
  $scope.dataTypes = dataTypes;
  $scope.value = transaction[prop];
  $scope.validBudgets = [];
  $scope.monthNames = ['January', 'February', 'March', 'April', 'May', 'June',
                       'July', 'August', 'September', 'October', 'November', 'December'];

  $scope.valueChanged = function(value) {
    $scope.value = value;
  }

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

  $scope.ok = function() {
    if (dataType == dataTypes.DATE) {
      if ($scope.transaction[prop].getMonth() != $scope.value.getMonth() ||
          $scope.transaction[prop].getYear() != $scope.value.getYear()) {

        $scope.transaction.budget = null; // if month changes, budget is invalid

      }
    }
    $scope.transaction[prop] = $scope.value;
    $scope.transaction.errors = getErrors($scope.transaction);
    $modalInstance.dismiss('cancel');
  }
}

var chooseBudgetController = function ($scope, $modalInstance, transaction, CategoryService, BudgetService) {
  $scope.transaction = transaction;
  $scope.validBudgets = [];

  $scope.categoryChanged = function(category) {
    $scope.validBudgets = $scope.getValidBudgets(category);
    $scope.category = category;
  }

  $scope.budgetChanged = function(budget) {
    if (!budget) { return; }
    $scope.budget = budget;
    $scope.category = budget.category;
    $scope.categoryChanged($scope.category);
  }

  $scope.getValidBudgets = function(category) {
   return $scope.budgets.filter(function(budget) {
     return category == null || budget.category.id == category.id;
   });
  }

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

  $scope.ok = function() {
    $scope.transaction.budget = $scope.budget;
    $scope.transaction.errors = getErrors($scope.transaction);
    $modalInstance.dismiss('cancel');
  }

  var date = $scope.transaction.transactionOn;
  //  https://stackoverflow.com/a/16048201/1612991
  date.setTime( date.getTime() + date.getTimezoneOffset()*60*1000 );

  if (!date || isNaN(date.getDate())) {
    $scope.invalidDate = true;
  }

  var month = date.getMonth() + 1;
  var year = date.getYear() + 1900;
  BudgetService.monthly({month: month, year: year}, function(response) {
    $scope.budgets = response;
    $scope.validBudgets = $scope.getValidBudgets($scope.category);
  });

  CategoryService.query(function(response) {
    $scope.categories = response;
    $scope.budgetChanged($scope.value);
  });
}

financeControllers.controller('ImportController', function($scope, $modal, CSV, TransactionService) {
  var getInitSelect = function() {
    var select = [];
    for (var i = 0; i < 4; i++) {
      select.push({
        value: "init"
      })
    };
    return select;
  }

  var initVars = function() {
    $scope.transactionsLoaded = false;
    $scope.fileSelected = false;
    $scope.columnsConfirmed = false;
    $scope.dataTypes = dataTypes;
    $scope.showSuccess = false;
    $scope.transactionsImportedCount = 0;
    $scope.columnsConfirmed = false;
    $scope.parsedTransactions = null;
    $scope.submitting = false;
    $scope.select = getInitSelect();
  }

  initVars();

  $scope.onFileSelected = function(event) {
    initVars(); // reset vars

    var reader = new FileReader();
    reader.onload = function (loadEvent) {
      var objs = CSV.CSVToArray(loadEvent.target.result);
      var lasts = objs.map(obj => obj[obj.length - 1]);

      $scope.$apply(function() {
        $scope.fileSelected = true;
        $scope.transactionsLoaded = true;
        $scope.transactions = objs;
        $scope.transactionsArray = _.cloneDeep(objs);
      });
    }
    reader.readAsText(event.target.files[0]);
  }

  $scope.columnChanged = function(i) {
    if ($scope.select[i].value == "na") {
      var longest = 0;
      for (var n = 0; n < $scope.transactions.length; n++) {
        $scope.transactions[n].splice(i, 1);
        longest = Math.max(longest, $scope.transactions[n].length);
      }
      $scope.select.splice(i, 1);
      if (longest > $scope.select.length) {
        $scope.select.push({value: "init"});
      }
    }
  }

  $scope.confirmColumns = function() {
    var values = $scope.select.map(function (s) {
      return s.value;
    });

    var indices = {
      date: values.indexOf("date"),
      remark: values.indexOf("remark"),
      amount: values.indexOf("amount")
    };

    var t = $scope.transactions.map(function(transaction) {
      var amount = Math.abs(parseFloat(transaction[indices.amount]));
      if (isNaN(amount)) { amount = "Error"; }

      var date = new Date(transaction[indices.date]);

      var remark = transaction[indices.remark];

      return {
        amount: amount,
        transactionOn: date,
        remark: remark,
        errors: [] // only check for validity upon submission
      };
    });

    $scope.columnsConfirmed = true;
    $scope.parsedTransactions = t;
  }

  $scope.resetColumns = function() {
    $scope.transactions = _.cloneDeep($scope.transactionsArray);
    $scope.select = getInitSelect();
  }

  $scope.removeTransaction = function(index) {
    $scope.parsedTransactions.splice(index, 1);
  }

  $scope.submitTransactions = function() {
    var errorCount = 0;
    for (var i = 0; i < $scope.parsedTransactions.length; i++) {
      var t = $scope.parsedTransactions[i];
      t.errors = getErrors(t);
      if (t.errors.length != 0) { errorCount++; }
    }

    if (errorCount != 0) { return; }

    $scope.submitting = true;
    TransactionService.saveBatch($scope.parsedTransactions).$promise.then(function() {
          $scope.submitting = false;
          $scope.showSuccess = true;
          $scope.transactionsImportedCount = $scope.parsedTransactions.length;
        }, function(response) {
        });
  }

  $scope.range = function(start, end) {
    var arr = [];
    for (var i = start; i < end; i++) {
      arr.push(i);
    }
    return arr;
  }

  $scope.openEditTransactionModal = function(transaction, prop, dataType) {
    var modalInstance = $modal.open({
      templateUrl: '/app/partials/modifyTransactionModal.html',
      controller: modifyTransactionController,
      resolve: {
        transaction: function() {
          return transaction;
        },
        prop: function() {
          return prop;
        },
        dataType: function() {
          return dataType;
        }
      }
    });
  }

  $scope.openChooseBudgetModal = function(transaction) {
    var modalInstance = $modal.open({
      templateUrl: '/app/partials/chooseBudgetModal.html',
      controller: chooseBudgetController,
      resolve: {
        transaction: function() {
          return transaction;
        }
      }
    });
  }
});

financeControllers.directive('fileChanged', function() {
  return {
    restrict: 'A',
    link: function (scope, element, attrs) {
      var onChangeHandler = scope.$eval(attrs.fileChanged);
      element.bind('change', onChangeHandler);
    }
  };
});

financeControllers.controller('HelpController', function ($scope) {

});

financeControllers.controller('NotFoundController', function ($scope) {

});

financeControllers.controller('LogoutController', function ($scope, $rootScope, $location, $window, AuthenticationService, auth) {

  auth.clearCredentials();
  $location.url("/");

  $scope.logout = function() {
    auth.clearCredentials();
    AuthenticationService.isLogged = false;
    delete $window.sessionStorage.token;
    delete $rootScope.nav;
    delete $rootScope.user;
    delete $rootScope.username;
    $location.url("/");
  }
});

var ConfirmDeleteModalController = function ($scope, $modalInstance, modal, message) {

  $scope.selected = modal;
  $scope.original = angular.copy(modal);
  $scope.message = message;

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

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

var ErrorModalController = function ($scope, $modalInstance, errors) {

  $scope.errors = errors;

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

// error modal
function errorModal($modal, errors) {
  $modal.open({
    templateUrl: '/app/partials/errorModal.html',
    controller: ErrorModalController,
    resolve: {
      errors: function() {
        return errors;
      }
    }
  });
}

// validations
function success($scope) {
  $scope.response = {};
  _.each($scope.form, function (field) {
    if (field && field.$setValidity) {
      field.$dirty = false;
      field.$setValidity("server", true);
    }
  });
};

function clearErrors($scope) {
  $scope.response = {};
  _.each($scope.form, function (field) {
    if(field && field.$setValidity) {
      field.$setValidity("server", true);
    }
  });
};

function failure($scope, response) {

  $scope.response = response.data;

  _.each($scope.form, function (field) {
    if(field && field.$setValidity) {
      field.$setValidity("server", true);
    }
  });
  _.each(response.data.errors, function(errors, key) {
    _.each(errors, function(e) {
      var field = $scope.form[key];
      field.$dirty = true;
      field.$setValidity("server", false);
    });
  });
};

function errorMessage (name) {
  var scope = this;
  if(!scope.response || !scope.response.errors) {
    return "";
  }
  var results = scope.response.errors[name];
  if(results) {
    return results.join(", ");
  }
  return "";
};

function errorClass(name) {
  var s = this.form[name];
  return s.$invalid && s.$dirty ? "has-error" : "";
};


text:
package org.redisson.remote;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ConcurrentMap;

import org.redisson.client.codec.Codec;
import org.redisson.command.CommandAsyncExecutor;
import org.redisson.executor.RemotePromise;
import org.redisson.rx.CommandRxExecutor;

import io.reactivex.rxjava3.core.Completable;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.core.Maybe;
import io.reactivex.rxjava3.core.Single;

/**
 *
 * @author Nikita Koksharov
 *
 */
public class RxRemoteProxy extends AsyncRemoteProxy {

    public RxRemoteProxy(CommandAsyncExecutor commandExecutor, String name, String responseQueueName,
            ConcurrentMap<String, ResponseEntry> responses, Codec codec, String executorId,
            String cancelRequestMapName, BaseRemoteService remoteService) {
        super(commandExecutor, name, responseQueueName, responses, codec, executorId, cancelRequestMapName,
                remoteService);
    }

    @Override
    protected List<Class<?>> permittedClasses() {
        return Arrays.asList(Completable.class, Single.class, Maybe.class);
    }

    @Override
    protected Object convertResult(RemotePromise<Object> result, Class<?> returnType) {
        Flowable<Object> flowable = ((CommandRxExecutor) commandExecutor).flowable(() -> result);

        if (returnType == Completable.class) {
            return flowable.ignoreElements();
        }
        if (returnType == Single.class) {
            return flowable.singleOrError();
        }
        return flowable.singleElement();
    }

}

redpajama_set_name: RedPajamaGithub


text:
import { Injectable, Component } from '@angular/core';
import { Router } from '@angular/router';
import { NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap';
import { Testeur } from './testeur.model';
import { TesteurService } from './testeur.service';

@Injectable()
export class TesteurPopupService {
    private ngbModalRef: NgbModalRef;

    constructor(
        private modalService: NgbModal,
        private router: Router,
        private testeurService: TesteurService

    ) {
        this.ngbModalRef = null;
    }

    open(component: Component, id?: number | any): Promise<NgbModalRef> {
        return new Promise<NgbModalRef>((resolve, reject) => {
            const isOpen = this.ngbModalRef !== null;
            if (isOpen) {
                resolve(this.ngbModalRef);
            }

            if (id) {
                this.testeurService.find(id).subscribe((testeur) => {
                    this.ngbModalRef = this.testeurModalRef(component, testeur);
                    resolve(this.ngbModalRef);
                });
            } else {
                // setTimeout used as a workaround for getting ExpressionChangedAfterItHasBeenCheckedError
                setTimeout(() => {
                    this.ngbModalRef = this.testeurModalRef(component, new Testeur());
                    resolve(this.ngbModalRef);
                }, 0);
            }
        });
    }

    testeurModalRef(component: Component, testeur: Testeur): NgbModalRef {
        const modalRef = this.modalService.open(component, { size: 'lg', backdrop: 'static'});
        modalRef.componentInstance.testeur = testeur;
        modalRef.result.then((result) => {
            this.router.navigate([{ outlets: { popup: null }}], { replaceUrl: true, queryParamsHandling: 'merge' });
            this.ngbModalRef = null;
        }, (reason) => {
            this.router.navigate([{ outlets: { popup: null }}], { replaceUrl: true, queryParamsHandling: 'merge' });
            this.ngbModalRef = null;
        });
        return modalRef;
    }
}


text:
#ifndef QSCRIPTXMLPARSER_P_H
#define QSCRIPTXMLPARSER_P_H

//
//  W A R N I N G
//  -------------
//
// This file is not part of the Qt API.  It exists purely as an
// implementation detail.  This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//

#include <QtCore/qobjectdefs.h>

#include <QtCore/qmap.h>
#include <QtCore/qset.h>
#include <QtCore/qstring.h>

QT_BEGIN_NAMESPACE

class Q_AUTOTEST_EXPORT QScriptXmlParser
{
public:
    struct Result
    {
        Result(const QMap<QString, int> &fi, const QSet<int> &eln)
            : functionsInfo(fi), executableLineNumbers(eln) {}

        QMap<QString, int> functionsInfo;
        QSet<int> executableLineNumbers;
    };

    static Result parse(const QString &xml);
};

QT_END_NAMESPACE

#endif


text:
torque-duplicate-jobs
=====================

Finds dupicate jobs in torque accounting files and records them to a separate file


text: <!doctype html>


text:
#ifndef ACTIVEMQ_UTIL_PRIMITIVEVALUENODETEST_H_
#define ACTIVEMQ_UTIL_PRIMITIVEVALUENODETEST_H_

#include <activemq/util/PrimitiveValueNode.h>

#include <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>

namespace activemq{
namespace util{

    class PrimitiveValueNodeTest : public CppUnit::TestFixture
    {
        CPPUNIT_TEST_SUITE( PrimitiveValueNodeTest );
        CPPUNIT_TEST( testValueNode );
        CPPUNIT_TEST( testValueNodeCtors );
        CPPUNIT_TEST_SUITE_END();

    public:

        PrimitiveValueNodeTest(){}
        virtual ~PrimitiveValueNodeTest(){}

        void testValueNode();
        void testValueNodeCtors();

    };

}}

#endif /*ACTIVEMQ_UTIL_PRIMITIVEVALUENODETEST_H_*/


text:
@interface LinkEnhancer : NSObject <WryEnhancer>

@end


text:
<!DOCTYPE html>

<title>Classe QSplitterHandle</title>

Classe QSplitterHandle

Derivada de QWidget

Classes derivadas:

Módulo QtWidgets

Versão do Qt: 5,0,0

Construtor: QSplitterHandle():new(Qt::Orientation, QSplitter * )

Método: QSplitterHandle():opaqueResize( ) -> bool

Método: QSplitterHandle():orientation( ) -> Qt::Orientation

Método: QSplitterHandle():setOrientation(Qt::Orientation ) -> void

Método: QSplitterHandle():splitter( ) -> QSplitter *

Método: QSplitterHandle():sizeHint( ) -> QSize


text:
<?php

class ScheduleController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
                                array('allow', // allow authenticated user to perform 'create' and 'update' actions
                                        'actions'=>array( 'view', 'create','update','admin','delete','updateSchedule'),
                                        'roles'=>array('Motorista'),
                                ),
                      array('allow', // allow authenticated user to perform 'create' and 'update' actions
                                        'actions'=>array( 'view', 'admin'),
                                        'roles'=>array('Administrador'),
                                ),
                                array('deny',  // deny all users
                                        'users'=>array('*'),
                                ),
                        );
	}
              public function actionTest(){

//               $es = new EditableSaver('Schedule');
//                try {
//
//                    $es->onBeforeUpdate = function($event) {
//        $event->sender->setAttribute('arrive_date', date("y/m/d H:i:s"));
//    };
//                    $es->update();
//                } catch(CException $e) {
//                    echo CJSON::encode(array('success' => false, 'msg' => $e->getMessage()));
//                    return;
//                }
//                echo CJSON::encode(array('success' => true));

        }

        public function actionUpdateSchedule()
    {

        $es = new EditableSaver('Schedule');
//        $es->onBeforeUpdate = function($event) {
//            $event->sender->setAttribute('arrive_date', date('y-m-d H:i:s'));
 //       };
        try {
        $es->update();
    } catch(CException $e) {
        echo CJSON::encode(array('success' => false, 'msg' => $e->getMessage()));
        return;
    }
    echo CJSON::encode(array('success' => true));

        }

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($ids)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($ids),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Schedule;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		if(isset($_POST['Schedule']))
		{
			$model->attributes=$_POST['Schedule'];
                        $model->id_schedule=  uniqid()." ".date("y-m-d H:i:s");
                        $model->schedule_date=date("y-m-d H:i:s");
                             if(!empty( $model->ranch_date))
                            $model->ranch_date=Yii::app()->dateFormatter->format('yyyy-MM-dd HH:mm', $model->ranch_date);
                        else
                             $model->ranch_date=null;

                        if(!empty( $model->arrive_date))
                            $model->arrive_date=Yii::app()->dateFormatter->format('yyyy-MM-dd HH:mm', $model->arrive_date);
                        else
                             $model->arrive_date=null;
                       $inits=$model->initial_stock;
                       $ranchd=$model->ranch_diesel;
                       $do=$model->delivery_DO;
                       $fs=$model->final_stock;

                       //calulate day comsuption
                       if(empty($inits))
                            $inits=0;
                        if(empty($ranchd))
                            $ranchd=0;
                        if(empty($do))
                            $do=0;
                        if(empty($fs))
                            $fs=0;
                        $model->day_comsuption=$inits+$ranchd-$do-$fs;
                        $model->id_user=  Yii::app()->user->id;

                        $inithbb=$model->init_bb_motor;
                        $endhbb=$model->finish_bb_motor;
                        $initheb=$model->init_eb_motor;
                        $endheb=$model->finish_eb_motor;
                        //calulate total hour
                        if(empty($inithbb))
                            $inithbb=0;
                        if(empty($endhbb))
                            $endhbb=0;
                        if(empty($initheb))
                            $initheb=0;
                        if(empty($endheb))
                            $endheb=0;
                        $model->total_hours=(($endhbb-$inithbb)+($endheb-$initheb))/2;
                        if(empty($model->earthing))
                            $model->earthing=null;
			if($model->save())
				$this->redirect(array('view','ids'=>$model->id_schedule));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($ids)
	{
		$model=$this->loadModel($ids);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
                if($model->id_user!=Yii::app()->user-id)
                    throw new CHttpException(404, 'Usted no esta autorizado para realizar esta acción.');
		if(isset($_POST['Schedule']))
		{
			$model->attributes=$_POST['Schedule'];
                        if(!empty( $model->ranch_date))
                            $model->ranch_date=Yii::app()->dateFormatter->format('yyyy-MM-dd HH:mm', $model->ranch_date);
                        else
                             $model->ranch_date=null;

                        if(!empty( $model->arrive_date))
                            $model->arrive_date=Yii::app()->dateFormatter->format('yyyy-MM-dd HH:mm', $model->arrive_date);
                        else
                             $model->arrive_date=null;
                       $inits=$model->initial_stock;
                       $ranchd=$model->ranch_diesel;
                       $do=$model->delivery_DO;
                       $fs=$model->final_stock;

                       //calulate day comsuption
                       if(empty($inits))
                            $inits=0;
                        if(empty($ranchd))
                            $ranchd=0;
                        if(empty($do))
                            $do=0;
                        if(empty($fs))
                            $fs=0;
                        $model->day_comsuption=$inits+$ranchd-$do-$fs;
                        $model->id_user=  Yii::app()->user->id;

                        $inithbb=$model->init_bb_motor;
                        $endhbb=$model->finish_bb_motor;
                        $initheb=$model->init_eb_motor;
                        $endheb=$model->finish_eb_motor;
                        //calulate total hour
                        if(empty($inithbb))
                            $inithbb=0;
                        if(empty($endhbb))
                            $endhbb=0;
                        if(empty($initheb))
                            $initheb=0;
                        if(empty($endheb))
                            $endheb=0;
                        $model->total_hours=(($endhbb-$inithbb)+($endheb-$initheb))/2;
			if($model->save())
				$this->redirect(array('view','ids'=>$model->id_schedule));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($ids)
	{
		$this->loadModel($ids)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Schedule');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Schedule('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Schedule']))
			$model->attributes=$_GET['Schedule'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Schedule the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Schedule::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Schedule $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='schedule-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}


text:
<?php

namespace LoLTool\Bundle\LoLToolBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Game
 */
class Game
{
    /**
     * @var integer
     */
    private $id;

    /**
     * @var integer
     */
    private $gameId;

    /**
     * @var boolean
     */
    private $invalid;

    /**
     * @var string
     */
    private $gameMode;

    /**
     * @var string
     */
    private $gameType;

    /**
     * @var string
     */
    private $subType;

    /**
     * @var integer
     */
    private $mapId;

    /**
     * @var integer
     */
    private $playerId;

    /**
     * @var integer
     */
    private $teamId;

    /**
     * @var integer
     */
    private $championId;

    /**
     * @var integer
     */
    private $spell1;

    /**
     * @var integer
     */
    private $spell2;

    /**
     * @var integer
     */
    private $level;

    /**
     * @var integer
     */
    private $createDate;

    /**
     * @var array
     */
    private $fellowPlayers;

    /**
     * @var integer
     */
    private $statsId;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set gameId
     *
     * @param integer $gameId
     * @return Game
     */
    public function setGameId($gameId)
    {
        $this->gameId = $gameId;

        return $this;
    }

    /**
     * Get gameId
     *
     * @return integer
     */
    public function getGameId()
    {
        return $this->gameId;
    }

    /**
     * Set invalid
     *
     * @param boolean $invalid
     * @return Game
     */
    public function setInvalid($invalid)
    {
        $this->invalid = $invalid;

        return $this;
    }

    /**
     * Get invalid
     *
     * @return boolean
     */
    public function getInvalid()
    {
        return $this->invalid;
    }

    /**
     * Set gameMode
     *
     * @param string $gameMode
     * @return Game
     */
    public function setGameMode($gameMode)
    {
        $this->gameMode = $gameMode;

        return $this;
    }

    /**
     * Get gameMode
     *
     * @return string
     */
    public function getGameMode()
    {
        return $this->gameMode;
    }

    /**
     * Set gameType
     *
     * @param string $gameType
     * @return Game
     */
    public function setGameType($gameType)
    {
        $this->gameType = $gameType;

        return $this;
    }

    /**
     * Get gameType
     *
     * @return string
     */
    public function getGameType()
    {
        return $this->gameType;
    }

    /**
     * Set subType
     *
     * @param string $subType
     * @return Game
     */
    public function setSubType($subType)
    {
        $this->subType = $subType;

        return $this;
    }

    /**
     * Get subType
     *
     * @return string
     */
    public function getSubType()
    {
       switch($this->subType) {
           case 'NONE': return 'Custom Game';
           case 'NORMAL': return 'Normal 5vs5';
           case 'NORMAL_3x3': return 'Normal 3vs3';
           case 'ODIN_UNRANKED': return 'Dominion';
           case 'ARAM_UNRANKED_5x5': return 'ARAM';
           case 'BOT': return 'Bot 5vs5';
           case 'BOT_3x3': return 'Bot 3vs3';
           case 'RANKED_SOLO_5x5': return 'Solo 5vs5';
           case 'RANKED_TEAM_3x3': return 'Team 3vs3';
           case 'RANKED_TEAM_5x5': return 'Team 5vs5';
           case 'CAP_5x5': return 'Teambuilder';
           default: return $this->subType;
       }

    }

    /**
     * Set mapId
     *
     * @param integer $mapId
     * @return Game
     */
    public function setMapId($mapId)
    {
        $this->mapId = $mapId;

        return $this;
    }

    /**
     * Get mapId
     *
     * @return integer
     */
    public function getMapId()
    {
        return $this->mapId;
    }

    /**
     * Set playerId
     *
     * @param integer $playerId
     * @return Game
     */
    public function setPlayerId($playerId)
    {
        $this->playerId = $playerId;

        return $this;
    }

    /**
     * Get playerId
     *
     * @return integer
     */
    public function getPlayerId()
    {
        return $this->playerId;
    }

    /**
     * Set teamId
     *
     * @param integer $teamId
     * @return Game
     */
    public function setTeamId($teamId)
    {
        $this->teamId = $teamId;

        return $this;
    }

    /**
     * Get teamId
     *
     * @return integer
     */
    public function getTeamId()
    {
        return $this->teamId;
    }

    /**
     * Set championId
     *
     * @param integer $championId
     * @return Game
     */
    public function setChampionId($championId)
    {
        $this->championId = $championId;

        return $this;
    }

    /**
     * Get championId
     *
     * @return integer
     */
    public function getChampionId()
    {
        return $this->championId;
    }

    /**
     * Set level
     *
     * @param integer $level
     * @return Game
     */
    public function setLevel($level)
    {
        $this->level = $level;

        return $this;
    }

    /**
     * Get level
     *
     * @return integer
     */
    public function getLevel()
    {
        return $this->level;
    }

    /**
     * Set createDate
     *
     * @param integer $createDate
     * @return Game
     */
    public function setCreateDate($createDate)
    {
        $this->createDate = $createDate;

        return $this;
    }

    /**
     * Get createDate
     *
     * @return bigint
     */
    public function getCreateDate()
    {
        return $this->createDate;
    }

    /**
     * Set fellowPlayers
     *
     * @param array $fellowPlayers
     * @return Game
     */
    public function setFellowPlayers($fellowPlayers)
    {
        $this->fellowPlayers = $fellowPlayers;

        return $this;
    }

    /**
     * Get fellowPlayers
     *
     * @return array
     */
    public function getFellowPlayers()
    {
        return $this->fellowPlayers;
    }

    /**
     * Set statsId
     *
     * @param integer $statsId
     * @return Game
     */
    public function setStatsId($statsId = 0)
    {
        $this->statsId = $statsId;
        return $this;
    }

    /**
     * Get statsId
     *
     * @return integer
     */
    public function getStatsId()
    {
        return $this->statsId;
    }
    /**
     * @var \LoLTool\Bundle\LoLToolBundle\Entity\Statistics
     */
    private $statistics;

    /**
     * Set statistics
     *
     * @param \LoLTool\Bundle\LoLToolBundle\Entity\Statistics $statistics
     * @return Game
     */
    public function setStatistics(\LoLTool\Bundle\LoLToolBundle\Entity\Statistics $statistics = null)
    {
        $this->statistics = $statistics;

        return $this;
    }

    /**
     * Get statistics
     *
     * @return \LoLTool\Bundle\LoLToolBundle\Entity\Statistics
     */
    public function getStatistics()
    {
        return $this->statistics;
    }
    /**
     * @var \LoLTool\Bundle\LoLToolBundle\Entity\Champion
     */
    private $champion;

    /**
     * Set champion
     *
     * @param \LoLTool\Bundle\LoLToolBundle\Entity\Champion $champion
     * @return Game
     */
    public function setChampion(\LoLTool\Bundle\LoLToolBundle\Entity\Champion $champion = null)
    {
        $this->champion = $champion;

        return $this;
    }

    /**
     * Get champion
     *
     * @return \LoLTool\Bundle\LoLToolBundle\Entity\Champion
     */
    public function getChampion()
    {
        return $this->champion;
    }

    /**
     * Set spell1
     *
     * @param \LoLTool\Bundle\LoLToolBundle\Entity\Spell $spell1
     * @return Game
     */
    public function setSpell1(\LoLTool\Bundle\LoLToolBundle\Entity\Spell $spell1 = null)
    {
        $this->spell1 = $spell1;

        return $this;
    }

    /**
     * Get spell1
     *
     * @return \LoLTool\Bundle\LoLToolBundle\Entity\Spell
     */
    public function getSpell1()
    {
        return $this->spell1;
    }

    /**
     * Set spell2
     *
     * @param \LoLTool\Bundle\LoLToolBundle\Entity\Spell $spell2
     * @return Game
     */
    public function setSpell2(\LoLTool\Bundle\LoLToolBundle\Entity\Spell $spell2 = null)
    {
        $this->spell2 = $spell2;

        return $this;
    }

    /**
     * Get spell2
     *
     * @return \LoLTool\Bundle\LoLToolBundle\Entity\Spell
     */
    public function getSpell2()
    {
        return $this->spell2;
    }
}


text:
class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  # protect_from_forgery with: :exception
  helper_method :current_user, :login, :logged_in?, :logout!, :find_user, :bounce

  def current_user
    @user ||= User.find_by_id(session[:user_id]) if session[:user_id]
  end

  def login(user)
    session[:user_id] = user.id
  end

  def logged_in?
    current_user != nil
  end

  def logout!
    session[:user_id] = nil
  end

  def find_user
    @user ||= User.find_by(username: params[:username])
  end

  # checks your session, bounces you off a page if you don't belong
  def bounce
    redirect_to users_path unless current_user
  end

end


text:
<?php

namespace BCloud\SpoKuWaBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class AddressType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
		$builder->add('sex', 'choice', array(
			'choices'   => array('0' => 'Herr', '1' => 'Frau'),
			'required'  => false,
			'empty_value' => false,
		));
		$builder->add('f_name', 'text', array(
			'max_length' => 255,
			'required' => true,
			'trim' => true,
		));
		$builder->add('l_name', 'text', array(
			'max_length' => 255,
			'required' => true,
			'trim' => true,
		));
		$builder->add('mail', 'email', array(
			'max_length' => 255,
			'required' => true,
			'trim' => true,
		));
		$builder->add('street', 'text', array(
			'max_length' => 255,
			'required' => true,
			'trim' => true,
		));
		$builder->add('zip', 'text', array(
			'max_length' => 6,
			'required' => true,
			'trim' => true,
		));
		$builder->add('city', 'text', array(
			'max_length' => 255,
			'required' => true,
			'trim' => true,
		));
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'BCloud\SpoKuWaBundle\Entity\Address'
        ));
    }

    public function getName()
    {
        return 'address';
    }
}


text:
require File.dirname(__FILE__) + '/../../spec_helper'

describe SystemMetrics::Instrument::ActionView do
  include NotificationsSupport

  before(:each) do
    @instrument = SystemMetrics::Instrument::ActionView.new
  end

  describe '#handle?' do
    it 'should handle any event whose name ends with action_view' do
      @instrument.handles?(event(:name => 'recieve.action_view')).should be_true
      @instrument.handles?(event(:name => 'send.action_view')).should be_true
    end

    it 'should not handle an event whose name does not end with action_view' do
      @instrument.handles?(event(:name => 'do_something.else')).should be_false
      @instrument.handles?(event(:name => 'action_view.process_action')).should be_false
    end
  end

  describe '#ignore?' do
    it 'should always return false' do
      @instrument.ignore?(event(:name => 'process_action.action_view')).should be_false
      @instrument.ignore?(event(:name => 'start_processing.action_controller')).should be_false
    end
  end

  describe '#prepare' do
    it 'should try to replace any paths in payload values' do
      @instrument.mapped_paths['/abc123'] = 'A'
      e = event(:payload => {
        :path => '/abc123/more/path',
        :action => 'create'
      })
      @instrument.prepare(e)
      e.payload.should == { :path => 'A/more/path', :action => 'create' }
    end
  end
end


text:
"""
Image and tile manipulation (transforming, merging, etc).
"""
from __future__ import with_statement
from cStringIO import StringIO

from mapproxy.platform.image import Image, ImageChops
from mapproxy.image.opts import create_image, ImageFormat
from mapproxy.config import base_config
from mapproxy.srs import make_lin_transf

import logging
log = logging.getLogger('mapproxy.image')

magic_bytes = [
    ('png', ("\211PNG\r\n\032\n",)),
    ('jpeg', ("\xFF\xD8",)),
    ('tiff', ("MM\x00\x2a", "II\x2a\x00",)),
    ('gif', ("GIF87a", "GIF89a",)),
]

def peek_image_format(buf):
    buf.seek(0)
    header = buf.read(10)
    buf.seek(0)
    for format, bytes in magic_bytes:
        if header.startswith(bytes):
            return format
    return None

class ImageSource(object):
    """
    This class wraps either a PIL image, a file-like object, or a file name.
    You can access the result as an image (`as_image` ) or a file-like buffer
    object (`as_buffer`).
    """

    def __init__(self, source, size=None, image_opts=None, cacheable=True):
        """
        :param source: the image
        :type source: PIL `Image`, image file object, or filename
        :param format: the format of the ``source``
        :param size: the size of the ``source`` in pixel
        """
        self._img = None
        self._buf = None
        self._fname = None
        self.source = source
        self.image_opts = image_opts
        self._size = size
        self.cacheable = cacheable

    def _set_source(self, source):
        self._img = None
        self._buf = None
        if isinstance(source, basestring):
            self._fname = source
        elif isinstance(source, Image.Image):
            self._img = source
        else:
            self._buf = source

    def _get_source(self):
        return self._img or self._buf or self._fname

    source = property(_get_source, _set_source)

    def close_buffers(self):
        if self._buf:
            try:
                self._buf.close()
            except IOError:
                pass

        if self._img:
            self._img = None

    @property
    def filename(self):
        return self._fname

    def as_image(self):
        """
        Returns the image or the loaded image.

        :rtype: PIL `Image`
        """
        if not self._img:
            self._make_seekable_buf()
            log.debug('file(%s) -> image', self._fname or self._buf)

            try:
                img = Image.open(self._buf)
            except StandardError:
                self.close_buffers()
                raise
            self._img = img
        if self.image_opts and self.image_opts.transparent and self._img.mode == 'P':
            self._img = self._img.convert('RGBA')
        return self._img

    def _make_seekable_buf(self):
        if not self._buf and self._fname:
            self._buf = open(self._fname, 'rb')
        elif not hasattr(self._buf, 'seek'):
            # PIL needs file objects with seek
            self._buf = StringIO(self._buf.read())
        self._buf.seek(0)

    def _make_readable_buf(self):
        if not self._buf and self._fname:
            self._buf = open(self._fname, 'rb')
        elif not hasattr(self._buf, 'seek'):
            if not isinstance(self._buf, ReadBufWrapper):
                self._buf = ReadBufWrapper(self._buf)
        else:
            self._buf.seek(0)

    def as_buffer(self, image_opts=None, format=None, seekable=False):
        """
        Returns the image as a file object.

        :param format: The format to encode an image.
                       Existing files will not be re-encoded.
        :rtype: file-like object
        """
        if format:
            image_opts = (image_opts or self.image_opts).copy()
            image_opts.format = ImageFormat(format)
        if not self._buf and not self._fname:
            if image_opts is None:
                image_opts = self.image_opts
            log.debug('image -> buf(%s)' % (image_opts.format,))
            self._buf = img_to_buf(self._img, image_opts=image_opts)
        else:
            self._make_seekable_buf() if seekable else self._make_readable_buf()
            if self.image_opts and image_opts and not self.image_opts.format and image_opts.format:
                # need actual image_opts.format for next check
                self.image_opts = self.image_opts.copy()
                self.image_opts.format = peek_image_format(self._buf)
            if self.image_opts and image_opts and self.image_opts.format != image_opts.format:
                log.debug('converting image from %s -> %s' % (self.image_opts, image_opts))
                self.source = self.as_image()
                self._buf = None
                self.image_opts = image_opts
                # hide fname to prevent as_buffer from reading the file
                fname = self._fname
                self._fname = None
                self.as_buffer(image_opts)
                self._fname = fname
        return self._buf

    @property
    def size(self):
        if self._size is None:
            self._size = self.as_image().size
        return self._size

def SubImageSource(source, size, offset, image_opts, cacheable=True):
    """
    Create a new ImageSource with `size` and `image_opts` and
    place `source` image at `offset`.
    """
    # force new image to contain alpha channel
    new_image_opts = image_opts.copy()
    new_image_opts.transparent = True
    img = create_image(size, new_image_opts)

    if not hasattr(source, 'as_image'):
        source = ImageSource(source)
    subimg = source.as_image()
    img.paste(subimg, offset)
    return ImageSource(img, size=size, image_opts=image_opts, cacheable=cacheable)

class BlankImageSource(object):
    """
    ImageSource for transparent or solid-color images.
    Implements optimized as_buffer() method.
    """
    def __init__(self, size, image_opts, cacheable=False):
        self.size = size
        self.image_opts = image_opts
        self._buf = None
        self._img = None
        self.cacheable = cacheable

    def as_image(self):
        if not self._img:
            self._img = create_image(self.size, self.image_opts)
        return self._img

    def as_buffer(self, image_opts=None, format=None, seekable=False):
        if not self._buf:
            image_opts = (image_opts or self.image_opts).copy()
            if format:
                image_opts.format = ImageFormat(format)
            image_opts.colors = 0
            self._buf = img_to_buf(self.as_image(), image_opts=image_opts)
        return self._buf

    def close_buffers(self):
        pass

class ReadBufWrapper(object):
    """
    This class wraps everything with a ``read`` method and adds support
    for ``seek``, etc. A call to everything but ``read`` will create a
    StringIO object of the ``readbuf``.
    """
    def __init__(self, readbuf):
        self.ok_to_seek = False
        self.readbuf = readbuf
        self.stringio = None

    def read(self, *args, **kw):
        if self.stringio:
            return self.stringio.read(*args, **kw)
        return self.readbuf.read(*args, **kw)

    def __iter__(self):
        if self.stringio:
            return iter(self.stringio)
        else:
            return iter(self.readbuf)

    def __getattr__(self, name):
        if self.stringio is None:
            if hasattr(self.readbuf, name):
                return getattr(self.readbuf, name)
            elif name == '__length_hint__':
                raise AttributeError
            self.ok_to_seek = True
            self.stringio = StringIO(self.readbuf.read())
        return getattr(self.stringio, name)

def img_has_transparency(img):
    if img.mode == 'P':
        if img.info.get('transparency', False):
            return True
        # convert to RGBA and check alpha channel
        img = img.convert('RGBA')
    if img.mode == 'RGBA':
        # any alpha except fully opaque
        return any(img.histogram()[-256:-1])
    return False

def img_to_buf(img, image_opts):
    defaults = {}
    image_opts = image_opts.copy()
    if image_opts.mode and img.mode[0] == 'I' and img.mode != image_opts.mode:
        img = img.convert(image_opts.mode)

    if (image_opts.colors is None and base_config().image.paletted
        and image_opts.format.endswith('png')):
        # force 255 colors for png with globals.image.paletted
        image_opts.colors = 255

    format = filter_format(image_opts.format.ext)
    if format == 'mixed':
        if img_has_transparency(img):
            format = 'png'
        else:
            format = 'jpeg'
            image_opts.colors = None
            image_opts.transparent = False

    if image_opts.colors:
        quantizer = None
        if 'quantizer' in image_opts.encoding_options:
            quantizer = image_opts.encoding_options['quantizer']
        if image_opts.transparent:
            img = quantize(img, colors=image_opts.colors, alpha=True,
                defaults=defaults, quantizer=quantizer)
        else:
            img = quantize(img, colors=image_opts.colors,
                quantizer=quantizer)
        if hasattr(Image, 'RLE'):
            defaults['compress_type'] = Image.RLE

    buf = StringIO()
    if format == 'jpeg':
        img = img.convert('RGB')
        if 'jpeg_quality' in image_opts.encoding_options:
            defaults['quality'] = image_opts.encoding_options['jpeg_quality']
        else:
            defaults['quality'] = base_config().image.jpeg_quality
    img.save(buf, format, **defaults)
    buf.seek(0)
    return buf

def quantize(img, colors=256, alpha=False, defaults=None, quantizer=None):
    if hasattr(Image, 'FASTOCTREE') and quantizer in (None, 'fastoctree'):
        if not alpha:
            img = img.convert('RGB')
        img = img.quantize(colors, Image.FASTOCTREE)
    else:
        if alpha and img.mode == 'RGBA':
            img.load() # split might fail if image is not loaded
            alpha = img.split()[3]
            img = img.convert('RGB').convert('P', palette=Image.ADAPTIVE, colors=colors-1)
            mask = Image.eval(alpha, lambda a: 255 if a <=128 else 0)
            img.paste(255, mask)
            if defaults is not None:
                defaults['transparency'] = 255
        else:
            img = img.convert('RGB').convert('P', palette=Image.ADAPTIVE, colors=colors)

    return img

def filter_format(format):
    if format.lower() == 'geotiff':
        format = 'tiff'
    if format.lower().startswith('png'):
        format = 'png'
    return format

image_filter = {
    'nearest': Image.NEAREST,
    'bilinear': Image.BILINEAR,
    'bicubic': Image.BICUBIC
}

def is_single_color_image(image):
    """
    Checks if the `image` contains only one color.
    Returns ``False`` if it contains more than one color, else
    the color-tuple of the single color.
    """
    result = image.getcolors(1)
    # returns a list of (count, color), limit to one
    if result is None:
        return False

    color = result[0][1]
    if image.mode == 'P':
        palette = image.getpalette()
        return palette[color*3], palette[color*3+1], palette[color*3+2]

    return result[0][1]

def make_transparent(img, color, tolerance=10):
    """
    Create alpha channel for the given image and make each pixel
    in `color` full transparent.

    Returns an RGBA ImageSoruce.

    Modifies the image in-place, unless it needs to be converted
    first (P->RGB).

    :param color: RGB color tuple
    :param tolerance: tolerance applied to each color value
    """
    result = _make_transparent(img.as_image(), color, tolerance)
    image_opts = img.image_opts.copy()
    image_opts.transparent = True
    image_opts.mode = 'RGBA'
    return ImageSource(result, size=result.size, image_opts=image_opts)

def _make_transparent(img, color, tolerance=10):
    img.load()

    if img.mode == 'P':
        img = img.convert('RGBA')

    channels = img.split()
    mask_channels = []
    for ch, c in zip(channels, color):
        # create bit mask for each matched color
        low_c, high_c = c-tolerance, c+tolerance
        mask_channels.append(Image.eval(ch, lambda x: 255 if low_c <= x <= high_c else 0))

    # multiply channel bit masks to get a single mask
    alpha = reduce(ImageChops.multiply, mask_channels)
    # invert to get alpha channel
    alpha = ImageChops.invert(alpha)

    if len(channels) == 4:
        # multiply with existing alpha
        alpha = ImageChops.multiply(alpha, channels[-1])

    img.putalpha(alpha)
    return img

def bbox_position_in_image(bbox, size, src_bbox):
    """
    Calculate the position of ``bbox`` in an image of ``size`` and ``src_bbox``.
    Returns the sub-image size and the offset in pixel from top-left corner
    and the sub-bbox.

    >>> bbox_position_in_image((-180, -90, 180, 90), (600, 300), (-180, -90, 180, 90))
    ((600, 300), (0, 0), (-180, -90, 180, 90))
    >>> bbox_position_in_image((-200, -100, 200, 100), (600, 300), (-180, -90, 180, 90))
    ((540, 270), (30, 15), (-180, -90, 180, 90))
    >>> bbox_position_in_image((-200, -50, 200, 100), (600, 300), (-180, -90, 180, 90))
    ((540, 280), (30, 20), (-180, -50, 180, 90))
    >>> bbox_position_in_image((586400,196400,752800,362800), (256, 256), (586400,196400,752800,350000))
    ((256, 237), (0, 19), (586400, 196400, 752800, 350000))
    """
    coord_to_px = make_lin_transf(bbox, (0, 0) + size)
    offsets = [0, size[1], size[0], 0]
    sub_bbox = list(bbox)
    if src_bbox[0] > bbox[0]:
        sub_bbox[0] = src_bbox[0]
        x, y = coord_to_px((src_bbox[0], 0))
        offsets[0] = int(x)
    if src_bbox[1] > bbox[1]:
        sub_bbox[1] = src_bbox[1]
        x, y = coord_to_px((0, src_bbox[1]))
        offsets[1] = int(y)

    if src_bbox[2] < bbox[2]:
        sub_bbox[2] = src_bbox[2]
        x, y = coord_to_px((src_bbox[2], 0))
        offsets[2] = int(x)

    if src_bbox[3] < bbox[3]:
        sub_bbox[3] = src_bbox[3]
        x, y = coord_to_px((0, src_bbox[3]))
        offsets[3] = int(y)

    size = abs(offsets[2] - offsets[0]), abs(offsets[1] - offsets[3])
    return size, (offsets[0], offsets[3]), tuple(sub_bbox)


text:
using System;

namespace LiteDB
{
    public partial class LiteDatabase : IDisposable
    {
        private LiteFileStorage _fs = null;

        /// <summary>
        /// Returns a special collection for storage files/stream inside datafile
        /// </summary>
        public LiteFileStorage FileStorage
        {
            get { return _fs ?? (_fs = new LiteFileStorage(_engine.Value)); }
        }
    }
}


text:
"use strict";

describe("FM.history.HistoryCtrl", function() {

    var $rootScope, $scope, $location, $route, $httpBackend,
        PlayerHistoryResource, historyData;

    beforeEach(function (){
        module("FM.history.HistoryCtrl");
    });

     beforeEach(inject(function (_$httpBackend_) {
        $httpBackend = _$httpBackend_

        $httpBackend.whenGET(/.*player\/history/).respond(200, [{ track: { uri: "foo" } },{ track: { uri: "bar" } }], { "Total-Pages": "10", "Total-Count": "10" });
        $httpBackend.whenGET(/partials\/.*/).respond(200);
    }));

    beforeEach(inject(function ( _$rootScope_, $injector, $controller ) {
        $rootScope = _$rootScope_;
        $scope = $rootScope.$new();

        $location = $injector.get("$location");
        $route = $injector.get("$route");

        PlayerHistoryResource = $injector.get("PlayerHistoryResource");
        spyOn(PlayerHistoryResource, "query").and.callThrough();

        historyData = { items: [{ track: { uri: "foo" } },{ track: { uri: "bar" } }] };
        historyData.meta = { totalPages: 10, totalCount: 10 }

        $controller("HistoryCtrl", {
            $scope: $scope,
            PlayerHistoryResource: PlayerHistoryResource,
            historyData: historyData
        });
    }));

    afterEach(function() {
        $httpBackend.verifyNoOutstandingExpectation();
        $httpBackend.verifyNoOutstandingRequest();
    });

    it("should load views", function() {
        $location.path("/history");
        $rootScope.$digest();
        $httpBackend.flush();
        expect($route.current.controller).toBe("HistoryCtrl");
    });

    it("should attach data to $scope", function(){
        expect($scope.history).toEqual(historyData.items);
    });

    it("should query next page from PlayerHistoryResource and add data to scope", function(){
        $scope.loadMore();
        expect($scope.page.loading).toBe(true);
        expect($scope.page.pages).toEqual(2);
        $httpBackend.flush();
        expect($scope.page.loading).toBe(false);
        expect($scope.history.length).toEqual(4);
        expect($scope.page.total).toEqual(10);
    });

});


text:
(function(){
  id = Ti.App.Properties.getString("tisink", "");
  var param, xhr;
  file = Ti.Filesystem.getFile("examples/window_standalone.js");
  xhr = Ti.Network.createHTTPClient();
  xhr.open("POST", "http://tisink.nodester.com/");
  xhr.setRequestHeader("content-type", "application/json");
  param = {
    data: "" + file.read(),
    file: "window_standalone.js",
    id: id
  };
  xhr.send(JSON.stringify(param));
})();
//TISINK----------------
//
//  When you open windows outside of tab groups, they are appear on top of either
//  the current window or the current tab group.  These examples show you different ways
//  to open windows outside of tab groups.
//

var win = Ti.UI.currentWindow;

win.orientationModes = [
	Ti.UI.PORTRAIT,
	Ti.UI.LANDSCAPE_LEFT,
	Ti.UI.LANDSCAPE_RIGHT
];
win.addEventListener('focus', function()
{
	Ti.API.info('FOCUSED EVENT RECEIVED');
});

//
//  OPEN WINDOW OUTSIDE OF TAB GROUP
//
var b1 = Ti.UI.createButton({
	title:'Open (Plain)',
	width:200,
	height:40,
	top:10
});

b1.addEventListener('click', function()
{

	var w = Ti.UI.createWindow({
		backgroundColor:'#336699'
	});

	// create a button to close window
	var b = Ti.UI.createButton({
		title:'Close',
		height:30,
		width:150
	});
	w.add(b);
	b.addEventListener('click', function()
	{
		w.close();
	});

	w.open();
});

//
//  OPEN (ANIMATE FROM BOTTOM RIGHT)
//
var b2 = Ti.UI.createButton({
	title:'Open (Nav Bar Covered)',
	width:200,
	height:40,
	top:60
});

b2.addEventListener('click', function()
{
	var options = {
			height:0,
			width:0,
			backgroundColor:'#336699',
			bottom:0,
			right:0
		};
	if (Ti.Platform.name == 'android') {
		options.navBarHidden = true;
	}
	var w = Ti.UI.createWindow(options);
	var a = Ti.UI.createAnimation();

	// NOTE: good example of making dynamic platform height / width values
	// iPad vs. iPhone vs Android etc.
	a.height = Ti.Platform.displayCaps.platformHeight;
	a.width = Ti.Platform.displayCaps.platformWidth;
	a.duration = 300;

	// create a button to close window
	var b = Ti.UI.createButton({
		title:'Close',
		height:30,
		width:150
	});
	w.add(b);
	b.addEventListener('click', function()
	{
		a.height = 0;
		a.width = 0;
		w.close(a);
	});

	w.open(a);
});

//
//  TRADITIONAL MODAL (FROM 0.8.x)
//
var b3 = Ti.UI.createButton({
	title:'Traditional Modal',
	width:200,
	height:40,
	top:110
});

b3.addEventListener('click', function()
{
	var w = Ti.UI.createWindow({
		backgroundColor:'#336699',
		title:'Modal Window',
		barColor:'black',
		url:'vibrate.js'
	});
	var b = Ti.UI.createButton({
		title:'Close',
		style:Ti.UI.iPhone.SystemButtonStyle.PLAIN
	});
	w.setLeftNavButton(b);
	b.addEventListener('click',function()
	{
		w.close();
	});
	w.open({modal:true});
});

//
//  OPEN (WITH ANIMATED WOBBLE)
//
var b4 = Ti.UI.createButton({
	title:'Open (Animation Fun)',
	width:200,
	height:40,
	top:160
});

b4.addEventListener('click', function()
{
	var t = Ti.UI.create2DMatrix();
	t = t.scale(0);

	var w = Ti.UI.createWindow({
		backgroundColor:'#336699',
		borderWidth:8,
		borderColor:'#999',
		height:400,
		width:300,
		borderRadius:10,
		opacity:0.92,
		transform:t
	});

	// create first transform to go beyond normal size
	var t1 = Ti.UI.create2DMatrix();
	t1 = t1.scale(1.1);
	var a = Ti.UI.createAnimation();
	a.transform = t1;
	a.duration = 200;

	// when this animation completes, scale to normal size
	a.addEventListener('complete', function()
	{
		Ti.API.info('here in complete');
		var t2 = Ti.UI.create2DMatrix();
		t2 = t2.scale(1.0);
		w.animate({transform:t2, duration:200});

	});

	// create a button to close window
	var b = Ti.UI.createButton({
		title:'Close',
		height:30,
		width:150
	});
	w.add(b);
	b.addEventListener('click', function()
	{
		var t3 = Ti.UI.create2DMatrix();
		t3 = t3.scale(0);
		w.close({transform:t3,duration:300});
	});

	w.open(a);

});

//
// OPEN (ANIMATE FROM BOTTOM)
//
var b5 = Ti.UI.createButton({
	title:'Open (Nav Bar Visible)',
	width:200,
	height:40,
	top:210
});

b5.addEventListener('click', function()
{
	var w = Ti.UI.createWindow({
		height:0,
		backgroundColor:'#000',
		bottom:0
	});

	// create window open animation
	var a = Ti.UI.createAnimation();
	a.height = 420;
	a.duration = 300;

	// create a button to close window
	var b = Ti.UI.createButton({
		title:'Close',
		height:30,
		width:150
	});
	w.add(b);
	b.addEventListener('click', function()
	{
		a.height = 0;
		w.close(a);
	});

	w.open(a);
});

//
//  OPEN (FULLSCREEN)
//
var b6 = Ti.UI.createButton({
	title:'Open (Fullscreen)',
	width:200,
	height:40,
	top:260
});

b6.addEventListener('click', function()
{
	var w = Ti.UI.createWindow({
		backgroundColor:'#336699'
	});

	// create a button to close window
	var b = Ti.UI.createButton({
		title:'Close',
		height:30,
		width:150
	});
	w.add(b);
	b.addEventListener('click', function()
	{
		w.close();
	});

	w.open({fullscreen:true});
});

//
//  OPEN (CUSTOM TOOLBAR)
//
var b7 = Ti.UI.createButton({
	title:'Open (Toolbar)',
	width:200,
	height:40,
	top:310
});

b7.addEventListener('click', function()
{
	var label = Ti.UI.createButton({
		title:'Custom Toolbar',
		color:'#fff',
		style:Ti.UI.iPhone.SystemButtonStyle.PLAIN
	});

	var flexSpace = Ti.UI.createButton({
		systemButton:Ti.UI.iPhone.SystemButton.FLEXIBLE_SPACE
	});
	var close = Ti.UI.createButton({
		title:'Close',
		style:Ti.UI.iPhone.SystemButtonStyle.DONE
	});
	var hello = Ti.UI.createButton({
		title:'Hello',
		style:Ti.UI.iPhone.SystemButtonStyle.BORDERED
	});

	var w = Ti.UI.createWindow({
		backgroundColor:'#336699'
	});
	close.addEventListener('click', function()
	{
		Ti.API.info('IN HERE');
		w.close();
	});

	// create and add toolbar
	var toolbar = Ti.UI.createToolbar({
		items:[hello,flexSpace,label, flexSpace,close],
		top:0,
		borderTop:false,
		borderBottom:true
	});
	w.add(toolbar);

	var move = Ti.UI.createButton({
		title:'Move Toolbar',
		height:40,
		width:200
	});
	w.add(move);

	move.addEventListener('click', function()
	{
		toolbar.animate({top:20,duration:500});
	});

	w.open();
});

//
// ODD SHAPED WINDOWS
//
var t = Ti.UI.create2DMatrix();
t= t.rotate(-90);
var menuWin = Ti.UI.createWindow({
	backgroundImage:'../images/menubox.png',
	height:178,
	width:204,
	top:32,
	right:40,
	anchorPoint:{x:1,y:0},
	transform:t,
	opacity:0
});

var t2 = Ti.UI.create2DMatrix();

var navButton = Ti.UI.createButton({
	title:'Toggle Window'
});
var visible = false;
navButton.addEventListener('click', function()
{
	if (!visible)
	{
		menuWin.open();
		menuWin.animate({transform:t2,opacity:1,duration:800});
		visible=true;
	}
	else
	{
		var t = Ti.UI.create2DMatrix();
		t= t.rotate(-90);
		menuWin.animate({transform:t,opacity:0,duration:800}, function()
		{
			menuWin.close();
		});
		visible=false;
	}
});

win.add(b1);
win.add(b2);
win.add(b3);
win.add(b6);

if (Ti.Platform.name == 'iPhone OS')
{
	win.setRightNavButton(navButton);
	win.add(b7);
	win.add(b4);
	win.add(b5);
	var flexSpace = Ti.UI.createButton({
		systemButton:Ti.UI.iPhone.SystemButton.FLEXIBLE_SPACE
	});

	var b8 = Ti.UI.createButton({
		title:'Open Tab Animation',
		style:Ti.UI.iPhone.SystemButtonStyle.BORDERED
	});

	var b9 = Ti.UI.createButton({
		title:'Open Tab w/o Animation',
		style:Ti.UI.iPhone.SystemButtonStyle.BORDERED
	});

	b8.addEventListener('click', function()
	{
		var w = Ti.UI.createWindow({backgroundColor:"red"});
		var b = Ti.UI.createButton({
			title:"Close with Animation",
			width:180,
			height:40
		});
		Ti.UI.currentTab.open(w);
		w.add(b);
		b.addEventListener('click',function()
		{
			w.close({animated:true});
		});
	});

	b9.addEventListener('click', function()
	{
		var w = Ti.UI.createWindow({backgroundColor:"red"});
		var b = Ti.UI.createButton({
			title:"Close w/o Animation",
			width:180,
			height:40
		});
		Ti.UI.currentTab.open(w,{animated:false});
		w.add(b);
		b.addEventListener('click',function()
		{
			w.close({animated:false});
		});
	});

	win.setToolbar([flexSpace,b8,flexSpace,b9,flexSpace],{translucent:true});
}
else
{
	navButton.top = 310;
	navButton.width = 200;
	navButton.height = 40;
//	win.add(navButton);
}

;


text:
#ifndef TENSORFLOW_COMPILER_TF2XLA_XLA_COMPILER_H_
#define TENSORFLOW_COMPILER_TF2XLA_XLA_COMPILER_H_

#include "tensorflow/compiler/tf2xla/xla_compilation_device.h"
#include "tensorflow/compiler/xla/client/local_client.h"
#include "tensorflow/core/common_runtime/device.h"
#include "tensorflow/core/common_runtime/device_mgr.h"
#include "tensorflow/core/common_runtime/function.h"
#include "tensorflow/core/framework/function.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/notification.h"
#include "tensorflow/core/platform/thread_annotations.h"
#include "tensorflow/core/public/version.h"

namespace tensorflow {

class XlaContext;

// The XlaCompiler class is responsible for compilation of a self-contained
// subgraph of a TensorFlow computation using the XLA linear algebra runtime.
// It does a symbolic execution of the graph starting from specific input
// shapes, using a JIT device to convert operators into XLA computations.
//
// XlaCompiler is typically invoked from an `_XlaLaunch` operator once the
// shapes of all input parameters to the computation are known. This is
// because the symbolic execution requires known shapes for all operations.
//
// XlaCompiler compiles Tensorflow graphs that received inputs via _Arg nodes,
// and return outputs via _Retval nodes.
//
// The XlaCompiler requires one Argument struct for each _Arg index, that
// describes each argument. Arguments can be compile-time constants
// (kind kConstant), run-time parameters (kind kParameter), or resources
// (kind kResource).
//
// Only kParameter and initialized kResource arguments become runtime parameters
// to the generated XLA computation. The XLA computation will have run-time
// parameters in the following order:
//   +---------------------+-----------------------------------------+
//   |  kParameter values  |  Initial values of kResource arguments  |
//   +---------------------+-----------------------------------------+
// Within each block, the arguments are arranged by the _Arg index from which
// they were derived.
//
// The run-time outputs of the XLA computation are arranged in the following
// order:
//   +------------------+-----------------------------------------+
//   |  _Retval values  |  Updated values of kResource arguments  |
//   +------------------+-----------------------------------------+
// _Retval values are ordered by _Retval index, whereas kResource values are
// ordered by the original _Arg position of the variable.
//
// In both inputs and outputs, kResource values are placed the end. When
// emitting While loop bodies, we must ensure that the loop body has
// identical input and output signatures. By moving variable values
// to the end of the argument list and using the
// `return_updated_values_for_all_variables` option, we can ensure that the
// input and output values of resources appear at the same positions.
//
// Resources are passed as parameters or returned as resource updates in
// "packed" form.
// kStack resources are packed as (array, size of stack) XLA tuples.
// kTensorArray resources without gradients are packed as the array that
// backs the TensorArray. If gradients are present (`tensor_array_gradients`),
// the packed representation is a (array, gradient0, gradient1, ...) tuple,
// where gradient_k is the value of the k-th gradient in the
// `tensor_array_gradients` ordered set.
class XlaCompiler {
 public:
  // Describes how to derive the value of each _Arg node in the graph/function
  // being compiled. There must be one Argument for each _Arg index.
  struct Argument {
    enum Kind {
      // Default value; not a valid kind.
      kInvalid,

      // Argument is a compile-time constant. No associated runtime parameter.
      kConstant,

      // Argument is a Variable, TensorArray, or Stack resource. Has an
      // associated runtime parameter iff `initialized` is true.
      kResource,

      // Argument is a run-time parameter.
      kParameter,
    };

    Kind kind = kInvalid;

    // The type of the argument. If the argument is a resource, this
    // is the type of the variable's value, not DT_RESOURCE.
    DataType type;

    // The shape of the argument. For:
    // * a parameter: the shape of the parameter.
    // * a constant: ignored; the shape given by constant_value is used
    //     instead.
    // * an uninitialized resource: ignored. We don't yet know the shape of an
    //     uninitialized resource (otherwise we would have initialized it!)
    // * an initialized variable: the shape of the variable's value.
    // * an initialized TensorArray or Stack resource: the shape of an entry in
    //   the TensorArray/Stack. Note this is the size of a single entry, not the
    //   XLA data structure that represents the complete stack/array.
    TensorShape shape;

    // The value of the argument, if it is a compile-time constant. Must be a
    // host-memory tensor.
    Tensor constant_value;

    // The name of this argument, used for debugging.
    string name;

    // For a kResource, what kind of resource is it?
    XlaResource::Kind resource_kind = XlaResource::kInvalid;

    // For a kResource, has this resource been initialized?
    bool initialized = false;

    // For a TensorArray or Stack resource, what is the array's declared size?
    // (Used for lazy initialization.)
    int64 tensor_array_size = -1;

    // TensorArray resource parameters are passed as (array, gradient array 0,
    // ..., gradient array k), where the gradient arrays are in the same order
    // as `tensor_array_gradients`.
    std::set<string> tensor_array_gradients;

    bool operator==(const Argument& other) const;
  };

  // Options pertaining to an individual call to CompileGraph() or
  // CompileFunction().
  struct CompileOptions {
    // If `use_tuple_arg` is true, a single tuple parameter will be used for all
    // arguments; if false, each argument gets its own parameter.
    bool use_tuple_arg = false;

    // If 'return_updated_values_for_all_resources' is true, then updated
    // values of all resource arguments will be included in the
    // 'resource_updates' of the computation, even if the resource was not
    // modified by the computation. Used when compiling loop bodies to ensure
    // the input and output signatures match.
    bool return_updated_values_for_all_resources = false;

    // If 'resolve_compile_time_constants' is true, then outputs of a
    // computation that are known to be compile-time constants will be returned
    // as Tensors at compile-time, rather than as run-time outputs of the
    // computation.
    bool resolve_compile_time_constants = true;

    // True when compiling the entry computation, false for subcomputations
    // (while, call, etc.)
    bool is_entry_computation = true;
  };

  struct OutputDescription {
    // Type and shape of the output.
    DataType type;
    TensorShape shape;

    // Constant output value, if known to be constant at JIT compilation time.
    // 'Tensor' is in host memory.
    bool is_constant = false;
    Tensor constant_value;
  };

  // Describes a variable write side effect of the computation.
  struct ResourceUpdate {
    // Index of the input that contains the variable resource to write to.
    int input_index;

    // Type and shape of the tensor to be written back.
    // The `shape` field has the same meaning as the Argument::shape field.
    DataType type;
    TensorShape shape;

    // Was the value of the variable modified by the computation?
    // (Always true, unless `return_updated_values_for_all_resources` is true.)
    bool modified;

    // If the resource is a TensorArray, the set of gradients read or written.
    std::set<string> tensor_array_gradients_accessed;
  };

  struct CompilationResult {
    // Vector that maps from the parameters of the XLA computation to their
    // original argument positions. To handle compile-time constant inputs and
    // resources, the parameters to the XLA computation may be a subset of the
    // original arguments, and are not necessarily in the same order.)
    std::vector<int> input_mapping;

    // Input shapes of the computation.
    std::vector<xla::Shape> xla_input_shapes;

    // Output shape in XLA format. The output shape is always a tuple.
    xla::Shape xla_output_shape;

    // TensorFlow shapes of outputs, together with the values of any
    // constant arguments. Vector indexed by Tensorflow _Retval number,
    // containing both constant and non-constant results.
    std::vector<OutputDescription> outputs;

    // Resources whose values were updated by the computation, ordered
    // by return value position. Resource updates follow the non-constant
    // results in the outputs of XLA computation.
    std::vector<ResourceUpdate> resource_updates;

    // The XLA computation built from the tensorflow subgraph.
    std::shared_ptr<xla::Computation> computation;
  };

  struct Options {
    // Name of the compilation device to use. Needs to be live only during
    // XlaCompiler's constructor.
    const DeviceType* device_type = nullptr;

    xla::Client* client = nullptr;

    // Function library in which to find function definitions. Must be non-null.
    const FunctionLibraryDefinition* flib_def = nullptr;

    // The graph def version to be compiled.
    int graph_def_version = TF_GRAPH_DEF_VERSION;

    // If 'allow_cpu_custom_calls' is true, kernels may make use of CustomCall()
    // for CPU.
    bool allow_cpu_custom_calls = false;

    // If set, the XLA representation of variables represented to XLA as the
    // shape given by this shape function. Variables are reshaped to this shape
    // on write, and reshaped to their original shape on read.
    std::function<TensorShape(const TensorShape&, DataType)>
        variable_representation_shape_fn;

    // If not nullptr, populate_resource_manager is called with the
    // compilation device's resource manager when the compilation
    // device is created, and can be used to create metadata objects
    // that can be accessed by XLA op kernels.
    std::function<Status(ResourceMgr*)>* populate_resource_manager = nullptr;

    // If not nullptr, this memory allocator can be used by the compiler for
    // temporary allocations it might want to make during compilation.
    //
    // For example, the compiler may want to try out different algorithms and
    // choose the fastest one, and it might run those algorithms over buffers
    // created using this allocator.
    //
    // The compiler can function correctly without an explicit allocator given
    // here, but on some devices (notably, GPUs), TensorFlow tends to eagerly
    // allocate most or all available memory on the device, leaving none for the
    // compiler to access, unless it can use TensorFlow's allocator.
    xla::DeviceMemoryAllocator* device_allocator = nullptr;
  };

  explicit XlaCompiler(Options options);

  ~XlaCompiler();

  Status CompileFunction(const CompileOptions& options,
                         const NameAttrList& fn_name_attrs,
                         std::vector<Argument> args, CompilationResult* result);

  // Compiles a tensorflow::Graph into an xla::Computation.
  // Similar to CompileFunction, but takes a Graph as input rather than a
  // function.
  Status CompileGraph(const CompileOptions& options, string const& name,
                      std::unique_ptr<Graph> graph,
                      const std::vector<Argument>& args,
                      CompilationResult* result);

  // Returns the shape of the XLA parameter for an argument 'arg'.
  // See the class comment for more details about the argument passing
  // convention.
  Status XLAShapeForArgument(const Argument& arg, xla::Shape* xla_shape);

  // Retrieves the channel handle associated with `key`. Allocates
  // a new channel handle if none exists.
  // Channel handles can be used to communicate between different
  // computations. Computations that communicate should be compiled with the
  // same XlaCompiler.
  Status GetChannelHandle(const string& key, xla::ChannelHandle* channel);

  const Options& options() const { return options_; }
  xla::Client* client() const { return options_.client; }
  FunctionLibraryRuntime* flib_runtime() const { return flib_runtime_; }

 private:
  // Sets the function body `fbody` to the one registered as `function`.
  Status FindFunctionBody(const NameAttrList& function,
                          const FunctionBody** fbody);

  // Returns the optimized graph object in this function body.
  std::unique_ptr<Graph> GetGraph(const FunctionBody* fbody);

  // Builds XLA computations for each of the arguments to the computation.
  // `args` are the arguments to the computation.
  Status BuildArguments(const Graph& graph,
                        const std::vector<XlaCompiler::Argument>& args,
                        bool use_tuple_arg, xla::ComputationBuilder* builder,
                        XlaContext* context, std::vector<int>* arg_cores,
                        std::vector<XlaExpression>* arg_expressions,
                        std::vector<int>* input_mapping,
                        std::vector<xla::Shape>* input_shapes,
                        bool is_entry_computation);

  // Graph compiler needs to know how to get an optimized graph from a function
  // body.
  friend class GraphCompiler;
  friend class XlaCompilerTest;

  Options options_;

  // Status set to non-OK in the constructor if initialization fails.
  Status initialization_status_;

  // Returns the next step sequence number.
  int64 NextStepId();

  // Internal sequence number for steps executed on the compilation device.
  int64 next_step_id_;

  XlaCompilationDevice* device_;  // Owned by device_mgr_
  DeviceMgr device_mgr_;

  // To avoid copying the client's function library, use a local function
  // library and runtime for functions created as part of the functionalize
  // control flow transformation.
  std::unique_ptr<FunctionLibraryDefinition> local_flib_def_;
  std::unique_ptr<ProcessFunctionLibraryRuntime> pflr_;
  std::unique_ptr<ProcessFunctionLibraryRuntime> local_pflr_;

  FunctionLibraryRuntime* local_flib_runtime_;  // owned by local_pflr_.
  FunctionLibraryRuntime* flib_runtime_;        // owned by pflr_.

  struct SignatureHash {
    uint64 operator()(
        const std::pair<string, std::vector<Argument>>& signature) const;
  };

  std::unordered_map<std::pair<string, std::vector<Argument>>,
                     CompilationResult, SignatureHash>
      cache_;

  std::unordered_map<string, xla::ChannelHandle> channels_;

  TF_DISALLOW_COPY_AND_ASSIGN(XlaCompiler);
};

}  // namespace tensorflow

#endif  // TENSORFLOW_COMPILER_TF2XLA_XLA_COMPILER_H_