text:
var agroind = angular.module('agroind', [
  'ui.router',
  'ipCookie',
  'ng-token-auth',
  'angular-loading-bar',
  'ngAnimate',
  'ngMessages',
  'pouchdb',
  'usersService',
  'profilesService',
  'landsService',
  'indicatorsService',
  'variablesService',
  'evaluationsService',
  'scoresService',
  'statisticsService',
  'colorCodesService',
  'ncy-angular-breadcrumb'
]);
var compareTo = function() {
    return {
        require: "ngModel",
        scope: {
            otherModelValue: "=compareTo"
        },
        link: function(scope, element, attributes, ngModel) {

            ngModel.$validators.compareTo = function(modelValue) {
                return modelValue == scope.otherModelValue;
            };

            scope.$watch("otherModelValue", function() {
                ngModel.$validate();
            });
        }
    };
};

agroind.directive("compareTo", compareTo);
agroind.factory('ConnectionStatus', function($rootScope, $q) {
  return {
    request: function(config) {
      return config;
    },
    requestError: function(config) {
      return config;
    },
    response: function(response) {
      $rootScope.online = "on";
      return response;
    },
    responseError: function(rejection) {
      if(rejection.status <= 0) {
          Materialize.toast("Sin conexion", 4000);
          $rootScope.online = "off";
          return rejection;
      }
      return $q.reject(rejection);
    }
  };
});

agroind.constant('config', {
 //apiRoot: 'http://localhost:3000',
   apiRoot: 'http://ec2-54-207-63-95.sa-east-1.compute.amazonaws.com:3000',
 //apiUrl: 'http://localhost:3000/api/v1',
   apiUrl: 'http://ec2-54-207-63-95.sa-east-1.compute.amazonaws.com:3000/api/v1',
  // apiUrl: 'https://agroind-api-jsvelasquezv.c9users.io/api/v1',
  // localDBName: "agroind-local"
});

// Configuration of router service
agroind.config(function($stateProvider, $urlRouterProvider, $httpProvider) {

  $httpProvider.interceptors.push('ConnectionStatus');

  $urlRouterProvider.otherwise("/");

  $stateProvider
    .state('home', {
      url: '/home',
      templateUrl: 'pages/home.html',
      ncyBreadcrumb: {
        label: 'Home'
      }
    })
    .state('login', {
      url: '/',
      templateUrl: 'pages/login.html'
      // controller: 'authController'
    })
    .state('newUser', {
      url: '/newUser',
      templateUrl: 'pages/users/new.html',
      controller: 'usersController'
    })
    .state('myAccount', {
      url: '/myAccount',
      templateUrl: 'pages/users/myAccount.html',
      controller: 'usersController'
    })
    .state('recoverPassword', {
      url: '/recoverPassword',
      templateUrl: 'pages/resetPassword.html'
    })
    .state('users', {
      url: '/users',
      templateUrl: 'pages/users/index.html',
      controller: 'usersController'
    })
    .state('editUser', {
      url: '/editUser/:id',
      templateUrl: 'pages/users/edit.html',
      controller: 'usersController'
    })
    .state('profiles', {
      url: '/profiles',
      templateUrl: 'pages/profiles/index.html',
      controller: 'profilesController'
    })
    .state('newProfile', {
      url: '/newProfile',
      templateUrl: 'pages/profiles/new.html',
      controller: 'profilesController'
    })
    .state('editProfile', {
      url: '/editProfile/:id',
      templateUrl: 'pages/profiles/edit.html',
      controller: 'profilesController'
    })
    .state('cloneProfile', {
      url: '/cloneProfile/:id',
      templateUrl: 'pages/profiles/clone.html',
      controller: 'profilesController'
    })
    .state('indicators', {
      url: '/indicators',
      templateUrl: 'pages/indicators/index.html',
      controller: 'indicatorsController'
    })
    .state('localIndicators', {
      url: '/localIndicators',
      templateUrl: 'pages/indicators/local/index.html',
      controller: 'indicatorsController'
    })
    .state('newIndicator', {
      url: '/newIndicator',
      templateUrl: 'pages/indicators/new.html',
      controller: 'indicatorsController'
    })
    .state('editIndicator', {
      url: '/editIndicator/:id',
      templateUrl: 'pages/indicators/edit.html',
      controller: 'indicatorsController'
    })
    .state('variables', {
      url: '/variables',
      templateUrl: 'pages/variables/index.html',
      controller: 'variablesController'
    })
    .state('localVariables', {
      url: '/localVariables',
      templateUrl: 'pages/variables/local/index.html',
      controller: 'variablesController'
    })
    .state('newVariable', {
      url: '/newVariable',
      templateUrl: 'pages/variables/new.html',
      controller: 'variablesController'
    })
    .state('editVariable', {
      url: '/editVariable/:id',
      templateUrl: 'pages/variables/edit.html',
      controller: 'variablesController'
    })
    .state('lands', {
      url: '/lands',
      templateUrl: 'pages/lands/index.html',
      controller: 'landsController'
    })
    .state('localLands', {
      url: '/localLands',
      templateUrl: 'pages/lands/local/index.html',
      controller: 'landsController'
    })
    .state('newLand', {
      url: '/newLand/:id',
      templateUrl: 'pages/lands/new.html',
      controller: 'landsController'
    })
    .state('editLand', {
      url: '/editLand/:id',
      templateUrl: 'pages/lands/edit.html',
      controller: 'landsController'
    })
    .state('evaluations', {
      url: '/evaluations',
      templateUrl: 'pages/evaluations/index.html',
      controller: 'evaluationsController'
    })
    .state('localEvaluations', {
      url: '/localEvaluations',
      templateUrl: 'pages/evaluations/local/index.html',
      controller: 'evaluationsController'
    })
    .state('newEvaluation', {
      url: '/newEvaluation',
      templateUrl: 'pages/evaluations/new.html',
      controller: 'evaluationsController'
    })
    .state('newLocalEvaluation', {
      url: '/newLocalEvaluation',
      templateUrl: 'pages/evaluations/local/new.html',
      controller: 'evaluationsController'
    })
    .state('qualifyIndicators', {
      url: '/qualifyIndicators/:evaluation_id',
      templateUrl: 'pages/qualifications/index.html',
      controller: 'evaluationsController'
    })
    .state('qualifyIndicator', {
      url: '/qualifyIndicator/:indicator_id',
      templateUrl: 'pages/qualifications/indicator.html',
      controller: 'evaluationsController'
    })
    .state('localQualifyIndicators', {
      url: '/localQualifyIndicators/:evaluation_id',
      templateUrl: 'pages/qualifications/local/index.html',
      controller: 'evaluationsController'
    })
    .state('localQualifyIndicator', {
      url: '/localQualifyIndicator/:indicator_id',
      templateUrl: 'pages/qualifications/local/indicator.html',
      controller: 'evaluationsController'
    })
    .state('ranking', {
      url: '/ranking',
      templateUrl: 'pages/statistics/rankings.html',
      controller: 'statisticsController'
    })
    .state('radarGraphicDates', {
      url: '/radarGraphicDates',
      templateUrl: 'pages/statistics/average_radar_graphic.html',
      controller: 'statisticsController'
    })
    .state('evaluationReport', {
      url: '/evaluationReport/:evaluation_id',
      templateUrl: 'pages/statistics/evaluation_report.html',
      controller: 'statisticsController'
    })
    .state('recommendations', {
      url: '/recommendations/:evaluation_id',
      templateUrl: 'pages/evaluations/recommendations.html',
      controller: 'evaluationsController'
    })
    .state('colorCodes', {
      url: '/colorCode',
      templateUrl: 'pages/colorCodes/index.html',
      controller: 'colorCodesController'
    })
    .state('editColorCode', {
      url: '/editColorCode/:id',
      templateUrl: 'pages/colorCodes/edit.html',
      controller: 'colorCodesController'
    })
});

//Configuration of authentication service
agroind.config(function($authProvider) {
  $authProvider.configure({
   //apiUrl: 'http://localhost:3000/api/v1',
      apiUrl: 'http://ec2-54-207-63-95.sa-east-1.compute.amazonaws.com:3000/api/v1',
     //apiUrl: 'https://agroind-api-jsvelasquezv.c9users.io/api/v1',
    storage: 'localStorage'
  });
});

//Controladores

agroind.controller('mainController', function($scope, $rootScope, $state, $http, pouchDB, Users, Profiles, Lands, Indicators, Variables, Evaluations, Scores, config) {

  $scope.reconnect = function () {
    $http.get(config.apiRoot + '/ping').then(function (response) {
      if (response.data == 'ok') {
        Materialize.toast('Conectado', 4000);
        $rootScope.online = true;
      }
    })
  }

  $scope.checkLogin = function () {
    // config.apiUrl;
    $rootScope.loggedIn = !$rootScope.loggedIn;
    // $rootScope.online = false;
  };

  $rootScope.$on('auth:login-success', function(ev, user) {
    Materialize.toast('Inicio de sesion correcto!', 4000);
    $rootScope.loggedIn = true;
    $rootScope.loggedUser = user;
    Profiles.getProfile(user.profile_id).then(function (response) {
      $rootScope.loggedProfile = response.data;
    });
    $state.go('home');
  });

  $rootScope.$on('auth:login-error', function(ev) {
    Materialize.toast('Correo o contraseña incorrectos!', 4000);
  });

  $scope.$on('auth:registration-email-success', function(ev, message) {
    Materialize.toast('Registro de usuario correcto!', 4000);
    $state.go('users');
  });

  $scope.$on('auth:registration-email-error', function(ev, reason) {
    Materialize.toast('Error al registrar el usuario!', 4000);
  });

  $scope.$on('auth:account-update-success', function(ev) {
    Materialize.toast('Se actualizo la informacion correctamente!', 4000);
  });

  $scope.$on('auth:account-update-error', function(ev, reason) {
    alert("Registration failed: " + reason.errors[0]);
  });

  $rootScope.$on('auth:logout-success', function(ev) {
    Materialize.toast('Cierre de sesion correcto!', 4000);
    $rootScope.loggedIn = false;
    $state.go('login');
  });

  $rootScope.$on('auth:logout-error', function(ev) {
    Materialize.toast('Error al cerrar sesion');
  });

  $rootScope.$on('auth:password-reset-request-success', function(ev) {
    Materialize.toast('Ok');
  });

  $rootScope.$on('auth:password-reset-request-error', function(ev) {
    Materialize.toast('No');
  });

  $scope.syncLands = function () {
    Lands.getLands().then(function (response) {
      $scope.allLands = response.data;
      Lands.saveToLocal($scope.allLands).then(function (response) {
        Materialize.toast("Se ha sincronizado correctamente la información");
      });
    })
    .catch(function (error) {
      Materialize.toast("Error al sincronizar la información");
    });
  }

  $scope.syncIndicators = function () {
    Indicators.getIndicators().then(function (response) {
      $scope.allIndicators = response.data;
      Indicators.saveToLocal($scope.allIndicators).then(function (response) {
        Materialize.toast("Se ha sincronizado correctamente la información");
        $scope.allIndicators = null;
      });
    })
    .catch(function (error) {
      Materialize.toast("Error al sincronizar la información");
    });
  }

  $scope.syncVariables = function () {
    Variables.getVariables().then(function (response) {
      $scope.allVariables = response.data;
      Variables.saveToLocal($scope.allVariables).then(function (response) {
        Materialize.toast("Se ha sincronizado correctamente la información", 4000);
        $scope.allVariables = null;
      });
    })
    .catch(function (error) {
      Materialize.toast("Error al sincronizar la información", 4000);
    });
  }

  $scope.clearLocalScores = function() {
    Scores.clearLocalScores();
    // .then(function (response) {
    //   Materialize.toast("Datos eliminados", 4000);
    // }).catch(function (error) {
    //   console.log(error);
    // })
  }

  $scope.syncEvaluations = function () {
    Scores.pushToRemote().then(function (responsePushScores) {
      Materialize.toast("Calificaciones cargadas correctamente", 4000);
      Scores.clearLocalScores();
      Evaluations.getUserEvaluations($rootScope.loggedUser.id).then(function (responseGetEvaluations) {
        Evaluations.saveToLocal(responseGetEvaluations.data).then(function (responseSaveEvaluations) {
          Materialize.toast("Evaluaciones sincronizadas correctamente", 4000);
        })
      })
    }).catch(function (error) {
      console.log(error);
    });
  }

});

//Controlador para la gestion de usuarios
agroind.controller('usersController', function ($scope, $rootScope, $stateParams, $state, $auth, Users, config, Profiles) {

 $scope.loadMyAccountForm = function () {
    var user = $rootScope.loggedUser;
    $scope.updateAccountForm = {
      name: user.name,
      last_name: user.last_name,
      address: user.address,
      email: user.email
    };
  }

  $scope.indexUser = function () {
    Users.getUsers().then(function (response) {
      $scope.allUsers = response.data;
    });
  }

  $scope.viewUser = function () {
    Users.getUser($stateParams.id).then(function (response) {
      $scope.user = response.data;
      $scope.profile_id = response.data.profile_id;
    });
  }

  $scope.newUser = function () {
    Users.newUser($scope.newUserForm).then(function (response) {
      Materialize.toast("Usuario registrado correctamente", 4000);
      $state.go('users');
    });
  }

  $scope.editUser = function (id, name, last_name, address, email, profile_id) {
    user = $scope.user;
    Users.editUser(user.id,
                   user.name,
                   user.last_name,
                   user.address,
                   user.email,
                   user.profile_id).then(function (response) {
                     Materialize.toast('Se ha actualizado el usuario correctamente!', 4000);
                     $state.go('users');
                   });
  }

  $scope.listProfiles = function () {
     Profiles.getProfiles().then(function (response) {
      $scope.allProfiles = response.data;
    });
  }

  $scope.delete = function (id) {
    var updatedAllUsers;
    Users.deleteUser(id).then(function (response) {
      // updatedAllUsers = $scope.allUsers.filter(function (user) {
      //   return user.id !== id;
      // });
      // $scope.allUsers = updatedAllUsers;
      $scope.indexUser();
      Materialize.toast('Se ha eliminado el usuario', 4000);
    });
  }

});

// Controlador para la gestion de perfiles
agroind.controller('profilesController', function ($scope, $stateParams, $state, Profiles, config) {

  $scope.indexProfile = function () {
    Profiles.getProfiles().then(function (response) {
      $scope.allProfiles = response.data;
    });
  }

  $scope.viewProfile = function () {
    Profiles.getProfile($stateParams.id).then(function (response) {
      $scope.profile = {
        id: response.data.id,
        name: response.data.name,
        users_permission: response.data.users_permission,
        list_users: response.data.list_users,
        create_users: response.data.create_users,
        edit_users: response.data.edit_users,
        deactivate_users: response.data.deactivate_users,
        indicators_permission: response.data.indicators_permission,
        reports_permission: response.data.reports_permission,
        statistics_permission: response.data.statistics_permission,
        profiles_permission: response.data.profiles_permission,
        list_profiles: response.data.list_profiles,
        create_profiles: response.data.create_profiles,
        edit_profiles: response.data.edit_profiles,
        clone_profiles: response.data.clone_profiles
      }
    });
  }

  $scope.newProfile = function () {
    Profiles.newProfile($scope.name,
                        $scope.users_permission,
                        $scope.list_users,
                        $scope.create_users,
                        $scope.edit_users,
                        $scope.deactivate_users,
                        $scope.indicators_permission,
                        $scope.reports_permission,
                        $scope.statistics_permission,
                        $scope.profiles_permission,
                        $scope.list_profiles,
                        $scope.create_profiles,
                        $scope.edit_profiles,
                        $scope.clone_profiles
                        ).then(function (response) {
                          Materialize.toast('Se ha creado el perfil correctamente!', 4000);
                          $state.go('profiles');
                        }).catch(function (error) {
                          for (var i = error.data['name'].length - 1; i >= 0; i--) {
                            Materialize.toast(error.data['name'][i],4000);
                          }
                        });
  }

  $scope.editProfile = function () {
    profile = $scope.profile;
    Profiles.editProfile(profile.id,
                         profile.name,
                         profile.users_permission,
                         profile.list_users,
                         profile.create_users,
                         profile.edit_users,
                         profile.deactivate_users,
                         profile.indicators_permission,
                         profile.reports_permission,
                         profile.statistics_permission,
                         profile.profiles_permission,
                         profile.list_profiles,
                         profile.create_profiles,
                         profile.edit_profiles,
                         profile.clone_profiles).then(function (response) {
                          Materialize.toast('Se ha editado el perfil correctamente!', 4000);
                          $state.go('profiles');
                         }).catch(function (error) {
                          for (var i = error.data['name'].length - 1; i >= 0; i--) {
                            Materialize.toast(error.data['name'][i],4000);
                          }
                         });
  }

  $scope.cloneProfile = function (id) {
    profile = $scope.profile;
    Profiles.newProfile(profile.name,
                        profile.users_permission,
                        profile.list_users,
                        profile.create_users,
                        profile.edit_users,
                        profile.deactivate_users,
                        profile.indicators_permission,
                        profile.reports_permission,
                        profile.statistics_permission,
                        profile.profiles_permission,
                        profile.list_profiles,
                        profile.create_profiles,
                        profile.edit_profiles,
                        profile.clone_profiles).then(function (response) {
                         Materialize.toast('Se ha clonado el perfil correctamente!', 4000);
                         $state.go('profiles');
                        }).catch(function (error) {
                         for (var i = error.data['name'].length - 1; i >= 0; i--) {
                           Materialize.toast(error.data['name'][i],4000);
                         }
                        });
  }

  $scope.deleteProfile = function (id) {
    Profiles.deleteProfile(id).then(function (response) {
      $scope.indexProfile();
      console.log("Perfil eliminado correctamente");
    });
  }
});

agroind.controller('landsController', function ($scope, $stateParams, $state, Lands, Users, config) {

  $scope.allUsers = function () {
    Users.getUsers().then(function (response) {
      $scope.allUsers = response.data;
    })
  }

  $scope.indexLands = function () {
    Lands.getLands().then(function (response) {
      $scope.allLands = response.data;
    });
  }

  $scope.viewLand = function () {
    Lands.getLand($stateParams.id).then(function (response) {
      $scope.land = response.data;
    });
  }

  $scope.newLand = function () {
    Lands.newLand($scope.newLandForm).then(function (response) {
      Materialize.toast("Se ha registrado la propiedad", 4000);
      $state.go('lands');
    });
  }

  $scope.editLand = function () {
    Lands.editLand($scope.land).then(function (response) {
      Materialize.toast("Se han guardado los cambios", 4000);
      $state.go('lands');
    });
  }

  $scope.downloadLands = function () {
    Lands.saveToLocal($scope.allLands).then(function (response) {
      Materialize.toast("Se ha descargado correctamente la informacion");
    }).catch(function (error) {
      Materialize.toast("Error al descargar la informacion");
    });
  }

  $scope.downloadedLands = function () {
    Lands.loadFromLocal().then(function (response) {
      $scope.localAllLands = response.rows.map(function(row) {return row.doc;});
    }).catch(function (error) {
      console.log(error);
    });
  }

});

// Controlador para la gestion de indicadores
agroind.controller('indicatorsController', function ($scope, $stateParams, $state, Indicators, config) {

  $scope.indexIndicators = function () {
    Indicators.getIndicators().then(function (response) {
      $scope.allIndicators = response.data;
    });
  }

  $scope.viewIndicator = function () {
    Indicators.getIndicator($stateParams.id).then(function (response) {
      $scope.indicator = response.data;
    });
  }

  $scope.newIndicator = function () {
    Indicators.newIndicator($scope.newIndicatorForm).then(function (response) {
      Materialize.toast("Se ha creado el indicador", 4000);
      $state.go('indicators');
    });
  }

  $scope.editIndicator = function () {
    Indicators.editIndicator($scope.indicator).then(function (response) {
      Materialize.toast("Se han guardado los cambios", 4000);
      $state.go('indicators');
    });
  }

  $scope.downloadIndicators = function () {
    Indicators.saveToLocal($scope.allIndicators).then(function (response) {
      Materialize.toast("Se ha descargado correctamente la informacion");
    }).catch(function (error) {
      console.log(error);
      Materialize.toast("Error al descargar la informacion");
    });
  }

  $scope.downloadedIndicators = function () {
    Indicators.loadFromLocal().then(function (response) {
      $scope.localAllIndicators = response.rows.map(function(row) {return row.doc;});
    }).catch(function (error) {
      console.log(error);
    });
  }

});

// Controller for variables
agroind.controller('variablesController', function ($scope, $stateParams, $state, Variables, Indicators, config) {

  $scope.allIndicators = function () {
    Indicators.getIndicators().then(function (response) {
      $scope.allIndicators = response.data;
    })
  }

  $scope.indexVariables = function () {
    Variables.getVariables().then(function (response) {
      $scope.allVariables = response.data;
    });
  }

  $scope.viewVariable = function () {
    Variables.getIndicator($stateParams.id).then(function (response) {
      $scope.variable = response.data;
    });
  }

  $scope.loadVariable = function () {
    Variables.getVariable($stateParams.id).then(function (response) {
      $scope.variable = response.data;
    });
  }

  $scope.newVariable = function () {
    Variables.newVariable($scope.newVariableForm).then(function (response) {
      Materialize.toast("Se ha creado la variable", 4000);
      $state.go('variables');
    });
  }

  $scope.editVariable = function () {
    Variables.editVariable($scope.variable).then(function (response) {
      Materialize.toast("Se han guardado los cambios", 4000);
      $state.go('variables');
    });
  }

  $scope.downloadVariables = function () {
    Variables.saveToLocal($scope.allVariables).then(function (response) {
      Materialize.toast("Se ha descargado correctamente la informacion");
    }).catch(function (error) {
      console.log(error);
      Materialize.toast("Error al descargar la informacion");
    });
  }

  $scope.downloadedVariables = function () {
    Variables.loadFromLocal().then(function (response) {
      $scope.localAllVariables = response.rows.map(function(row) {return row.doc;});
    }).catch(function (error) {
      console.log(error);
    });
  }

});

agroind.controller('evaluationsController', function ($scope, $rootScope, $stateParams, $state, Indicators, Users, Lands, Evaluations, Variables, Scores, config) {

  $scope.scores = {};
  $scope.localScores = {};

  $scope.loadQualificationsForm = function () {
    var indicator_id = $stateParams.indicator_id;
    Indicators.getIndicator(indicator_id).then(function (response) {
      $scope.indicator = response.data;
    });

    Evaluations.getQualifications($rootScope.currentEvaluationId, indicator_id).then(function (response) {
      var scores = {};
      response.data.forEach(function (score, key) {
        scores[parseFloat(score.variable_id)] = parseFloat(score.score);
      });
      $scope.scores = scores;
    });
  }

  $scope.localLoadQualificationsForm = function () {
    Variables.localVariablesFromIndicator($stateParams.indicator_id).then(function (response) {
      $scope.variables = response.rows.map(function(row) {return row.doc;});
    }).catch(function (error) {
      console.log(error);
    });
    Scores.loadScores($rootScope.localCurrentEvaluationId,$stateParams.indicator_id).then(function (response) {
      var scores = {};
      data = response.rows.map(function(row) {return row.doc;});
      data[0].qualifications.forEach(function (score, key) {
        scores[parseFloat(score.variable_id)] = parseFloat(score.score);
      });
      $scope.qualificationsRevision = data[0]._rev;
      $scope.localScores = scores;
    }).catch(function (error) {
      console.log(error);
    })
  }

  $scope.allIndicators = function () {
    $rootScope.currentEvaluationId = $stateParams.evaluation_id;
    Indicators.getIndicators().then(function (response) {
      $scope.allIndicators = response.data;
    });
    Evaluations.getEvaluation($stateParams.evaluation_id).then(function (response) {
      $scope.evaluation = response.data;
      $scope.recommendations = $scope.evaluation.recommendations;
      $scope.analysis = $scope.evaluation.analysis;
    })
  }

  // $scope.saveRecommendation

  $scope.allLands = function () {
    Lands.getLands().then(function (response) {
      $scope.allLands = response.data;
    });
  }

  $scope.allUsers = function () {
    Users.getUsers().then(function (response) {
      $scope.allUsers = response.data;
    })
  }

  $scope.allEvaluations = function () {
    Evaluations.getEvaluations().then(function (response) {
      $scope.allEvaluations = response.data;
    });
  }

  $scope.getIndicatorsAverages = function () {
    Evaluations.getIndicatorsAverages($stateParams.evaluation_id).then(function (response) {
      $scope.allIndicatorsAverages = response.data;
    });
  }

  $scope.newEvaluation = function () {
    var evaluation = {
      land_id: $scope.land_id,
      user_id: $rootScope.loggedUser.id,
      assignment_date: $scope.assignment_date,
      evaluator_id: $scope.evaluator_id
    }
    // console.log(evaluation);
    Evaluations.newEvaluation(evaluation).then(function (response) {
      Materialize.toast("Evaluacion creada", 4000);
      $state.go('evaluations');
    });
  }

  $scope.saveRecommendations = function () {
    Evaluations.saveRecommendations($stateParams.evaluation_id, $scope.recommendations).then(function (response) {
      Materialize.toast("Se ha guardado la recomendación", 4000);
    });
  }

  $scope.saveAnalysis = function () {
    Evaluations.saveAnalysis($stateParams.evaluation_id, $scope.analysis).then(function (response) {
      Materialize.toast("Se ha guardado el analisis", 4000);
    });
  }

  $scope.newLocalEvaluation = function () {
    Lands.getLocalLand($scope.evaluation.land_id).then(function (land) {
      var evaluation = {
        land_id: $scope.evaluation.land_id,
        user_id: $rootScope.loggedUser.id,
        land: land,
        user: $rootScope.loggedUser
      };
      Evaluations.newLocalEvaluation(evaluation).then(function (response) {
        Materialize.toast("Evaluacion creada", 4000);
        $state.go('localEvaluations');
      }).catch(function (error) {
        console.log(error);
      });
    }).catch(function (error) {
        console.log(error);
    })
  }

  $scope.downloadedIndicators = function () {
    $rootScope.localCurrentEvaluationId = $stateParams.evaluation_id;
    Indicators.loadFromLocal().then(function (response) {
      $scope.localAllIndicators = response.rows.map(function(row) {return row.doc;});
    }).catch(function (error) {
      console.log(error);
    });
  }

  $scope.downloadedVariables = function () {
    Variables.loadFromLocal().then(function (response) {
      $scope.localAllVariables = response.rows.map(function(row) {return row.doc;});
    }).catch(function (error) {
      console.log(error);
    });
  }

  $scope.downloadedLands = function () {
    Lands.loadFromLocal().then(function (response) {
      $scope.localAllLands = response.rows.map(function(row) {return row.doc;});
    }).catch(function (error) {
      console.log(error);
    });
  }

  $scope.downloadEvaluations = function () {
    Evaluations.saveToLocal($scope.allEvaluations).then(function (response) {
      Materialize.toast("Se ha descargado correctamente la informacion");
    }).catch(function (error) {
      console.log(error);
      Materialize.toast("Error al descargar la informacion");
    });
  }

  $scope.downloadedEvaluations = function () {
    Evaluations.loadFromLocal().then(function (response) {
      $scope.localAllEvaluations = response.rows.map(function(row) {return row.doc;});
    }).catch(function (error) {
      console.log(error);
    });
  }

  $scope.uploadEvaluations = function () {
    var evaluationsToCreate = [];
    var evaluationsToUpdate = [];
    $scope.localAllEvaluations.forEach(function (evaluation, index) {
      var temp_evaluation = {};
      if (evaluation.id) {
        temp_evaluation.id = evaluation.id;
        temp_evaluation.land_id = evaluation.land_id;
        temp_evaluation.user_id = evaluation.user_id;
        evaluationsToUpdate.push(temp_evaluation);
      } else {
        temp_evaluation.land_id = evaluation.land_id;
        temp_evaluation.user_id = evaluation.user_id;
        evaluationsToCreate.push(temp_evaluation);
      }
    });

    if (evaluationsToCreate.length > 0) {
      var data = {evaluations: evaluationsToCreate};

      Evaluations.batchCreate(data).then(function (response) {
        Materialize.toast("Datos creados correctamente", 4000);
      }).catch(function (error) {
        console.log(error);
      });
    }

    if (evaluationsToUpdate.length > 0) {
      var data = {evaluations: evaluationsToUpdate};

      Evaluations.batchUpdate(data).then(function (response) {
        Materialize.toast("Datos actualizados correctamente", 4000);
      }).catch(function (error) {
        console.log(error);
      });
    }
  }

  $scope.qualify = function () {
    var qualifications = [];
    var qualification = {};
    var data = {};
    Object.keys($scope.scores).forEach(function (key) {
      qualification = {
        variable_id: key,
        score: $scope.scores[key]
      };
      qualifications.push(qualification);
    });
    data = {
      evaluation_id: $rootScope.currentEvaluationId,
      indicator_id: $stateParams.indicator_id,
      qualifications: qualifications
    };
    Evaluations.qualifyEvaluation(data).then(function (response) {
      Materialize.toast("Se han registrado las calificaciones", 4000);
      $state.go('qualifyIndicator', {indicator_id: $stateParams.indicator_id});
    });
  }

  $scope.localQualify = function () {
    var qualifications = [];
    var qualification = {};
    var data = {};
    Object.keys($scope.localScores).forEach(function (key) {
      qualification = {
        variable_id: key,
        score: $scope.localScores[key]
      };
      qualifications.push(qualification);
    });
    data = {
      evaluation_id: $rootScope.localCurrentEvaluationId,
      indicator_id: $stateParams.indicator_id,
      qualifications: qualifications
    };
    if ($scope.qualificationsRevision) {
      data._rev = $scope.qualificationsRevision;
    }
    if (qualifications.length > 0) {
      Scores.saveToLocal(data).then(function (response) {
        Materialize.toast("Calificacion registrada correctamente", 4000);
      }).catch(function (error) {
        console.log(error);
      });
    }
  }

  // $scope.loadScores = function () {
  //   Scores.pushToRemote().then(function (response) {
  //     console.log(response);
  //   }).catch(function (error) {
  //     console.log(error);
  //   })
  // }

});

agroind.controller('statisticsController', function ($scope, $stateParams, $state, Statistics, config) {

  $scope.loadEvaluationReport = function () {
    Statistics.getEvaluationReport().then(function (response) {
      $scope.evaluationReport = response.data;
    })
  }

  $scope.loadBestRanking = function () {
    Statistics.getBestRanking().then(function (response) {
      $scope.bestRanking = response.data;
    })
  }

  $scope.loadWorstRanking = function () {
    Statistics.getWorstRanking().then(function (response) {
      $scope.worstRanking = response.data;
    })
  }

  $scope.loadAverageRadarDates = function () {
    Statistics.getRadarData($scope.start_date, $scope.end_date).then(function (response) {
      var ctx = document.getElementById("average-radar-dates-graphic");
      $scope.summary = response.data.summary;
      var data = {
        labels: response.data.labels,
        datasets: response.data.datasets
      };
      var averageRadarChartDates = new Chart(ctx, {
        type: 'radar',
        data: data
      });
    })
  }

  $scope.loadEvaluationReport = function () {
    Statistics.getEvaluationReport($stateParams.evaluation_id).then(function (response) {
      $scope.evaluation_report = response.data;
      console.log(response.data);
      chartData = response.data.chartData;
      console.log(chartData);
      var ctx = document.getElementById("average-radar-indicator-chart");
      var averageRadarChartIndicator = new Chart(ctx, {
        type: 'radar',
        data: chartData
      });
    })
  }

});

agroind.controller('colorCodesController', function ($scope, $stateParams, $state, config, ColorCodes) {

  $scope.allColorCodes = function () {
    ColorCodes.getColorCodes().then(function (response) {
      $scope.allColorCodes = response.data;
    });
  }

  $scope.loadColorCode = function () {
    ColorCodes.getColorCode($stateParams.id).then(function (response) {
      $scope.colorCode = response.data;
    });
  }

  $scope.editColorCode = function () {
    ColorCodes.editColorCode($scope.colorCode).then(function (response) {
      $scope.colorCode = response.data;
      Materialize.toast('El estado de alerta se ha actualizado correctamente', 4000);
      $state.go('colorCodes');
    });
  }
})

//Controlador de autenticacion

agroind.controller('authController', function ($scope, $auth, $rootScope) {
  $scope.handleRegBtnClick = function() {
    $auth.submitRegistration($scope.submitRegistrationForm)
      .then(function (resp) {
        console.log("ok");
        console.log(resp);
      })
      .catch(function (err) {
        console.log("err");
        console.log(err);
      });
  };

  $scope.handleLoginBtnClick = function() {
    $auth.submitLogin($scope.loginForm)
      .then(function(resp) {
        $rootScope.loggedIn = true;
        console.log($rootScope.loggedIn);
      })
      .catch(function(err) {
        console.log("err");
        console.log(err);
      });
  };

  $scope.handleSignOutBtnClick = function() {
    $auth.signOut()
      .then(function(resp) {
        $rootScope.loggedIn = false;
      })
      .catch(function(resp) {
        // handle error response
      });
  };

  $scope.handlePwdResetBtnClick = function() {
    $auth.requestPasswordReset($scope.pwdResetForm)
      .then(function(resp) {
        // handle success response
      })
      .catch(function(resp) {
        // handle error response
      });
  };

  $scope.handleUpdatePasswordBtnClick = function() {
      $auth.updatePassword($scope.updatePasswordForm)
        .then(function(resp) {
          // handle success response
        })
        .catch(function(resp) {
          // handle error response
        });

    };

});


text:
namespace Simple.Data.UnitTest
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using NUnit.Framework;

    [TestFixture]
    public class ObjectReferenceTest
    {
        static readonly dynamic Db = new Database(null);

        [Test]
        public void ObjectReferenceWithEqualsMakesExpression()
        {
            AssertHelper(Db.foo.id == 1, SimpleExpressionType.Equal, 1);
        }

        [Test]
        public void ObjectReferenceWithNotEqualsMakesExpression()
        {
            AssertHelper(Db.foo.id != 1, SimpleExpressionType.NotEqual, 1);
        }

        [Test]
        public void ObjectReferenceWithGreaterThanMakesExpression()
        {
            AssertHelper(Db.foo.id > 1, SimpleExpressionType.GreaterThan, 1);
        }

        [Test]
        public void ObjectReferenceWithLessThanMakesExpression()
        {
            AssertHelper(Db.foo.id < 1, SimpleExpressionType.LessThan, 1);
        }

        [Test]
        public void ObjectReferenceWithGreaterThanOrEqualMakesExpression()
        {
            AssertHelper(Db.foo.id >= 1, SimpleExpressionType.GreaterThanOrEqual, 1);
        }

        [Test]
        public void ObjectReferenceWithLessThanOrEqualMakesExpression()
        {
            AssertHelper(Db.foo.id <= 1, SimpleExpressionType.LessThanOrEqual, 1);
        }

        [Test]
        public void GetTopReturnsTopReference()
        {
            var foo = new ObjectReference("foo");
            var bar = new ObjectReference("bar", foo);
            var quux = new ObjectReference("quux", bar);

            Assert.AreEqual(foo, quux.GetTop());
        }

        private static void AssertHelper<T>(SimpleExpression actual, SimpleExpressionType expectedType, T expectedRightOperand)
        {
            Assert.AreEqual(Db.foo.id, actual.LeftOperand);
            Assert.AreEqual(expectedType, actual.Type);
            Assert.AreEqual(expectedRightOperand, actual.RightOperand);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.netcracker.specifications.impl;

import com.netcracker.entities.Label;
import com.netcracker.queries.QueriesSpecification;
import com.netcracker.specifications.SqlSpecification;
import com.netcracker.specifications.utils.SpecificationUtils;

import java.util.List;

/**
 * @author logariett.
 */
public class LabelFilterByRatings implements SqlSpecification {

    private String ratings;
    private String labelIds;

    public LabelFilterByRatings(List<Integer> ratings, List<Label> labels) {
        this.ratings = SpecificationUtils.convertNumberArrayToString(ratings);
        this.labelIds = SpecificationUtils.extractIdsAsString(labels);
    }

    @Override
    public String toSqlQuery() {
        return String.format(
                QueriesSpecification.FILTER_LABELS_BY_RATINGS,
                ratings,
                labelIds
        );
    }
}


text:
/*
 *
 * ProblemExamplesPage
 *
 */

import React, { PropTypes } from 'react';
import { gql, graphql } from 'react-apollo';

import ProblemExamples from '../../components/ProblemExamples';
import { loadable } from '../../utils/render';

const ProblemExamplesForLayout = gql`
  query ProblemExamplesForLayout($problemId: Int!) {
    problem(id: $problemId) {
      id
      examples {
        id
        number
        input
        result
        explanation
      }
    }
  }
`;

@graphql(ProblemExamplesForLayout, {
  options: ({ problemId }) => ({ variables: { problemId } }),
  skip: ({ defer }) => defer,
})
@loadable({ found: (props) => props.data.problem !== null })
// eslint-disable-next-line react/prefer-stateless-function
export default class ProblemExamplesPage extends React.PureComponent {
  render() {
    return <ProblemExamples examples={this.props.data.problem.examples} />;
  }
}

ProblemExamplesPage.propTypes = {
  data: PropTypes.object,
};


text:
<?php

/**
 * for test
 */
namespace __Test;

use Ytake\LaravelAspect\Annotation\LogExceptions;
use Ytake\LaravelAspect\Exception\FileNotFoundException;

class AspectLogExceptions
{
    /**
     * @LogExceptions(driver="custom")
     * @param null $id
     * @return null
     * @throws \Exception
     */
    public function normalLog($id = null)
    {
        throw new \Exception;
        return $id;
    }

    /**
     * @LogExceptions(expect="\LogicException",driver="custom")
     */
    public function expectException()
    {
        throw new \LogicException;
    }

    /**
     * @LogExceptions(expect="\LogicException")
     */
    public function expectNoException()
    {
        throw new FileNotFoundException(__DIR__);
    }

    /**
     * @return int
     */
    public function noException()
    {
        return 1;
    }
}


text:
<!---->
<quill-editor
  class="editor-{{ type }}"
  [ngClass]="{ focused: focused, hideToolbar: hideToolbar }"
  [ngModel]="content"
  (ngModelChange)="onChange($event)"
  [theme]="theme"
  [placeholder]="_placeholderCurrent"
  [style.height]="editorHeight"
  [style.maxHeight]="editorHeight"
  [style.minHeight]="editorHeight"
  [modules]="modulesToolbar"
  [readOnly]="disabled"
  [required]="required"
>
</quill-editor>


text:
package io.cattle.platform.iaas.api.auth;

import io.cattle.platform.archaius.util.ArchaiusUtil;
import io.cattle.platform.iaas.api.auth.integration.azure.AzureConstants;
import io.cattle.platform.iaas.api.auth.integration.ldap.OpenLDAP.OpenLDAPConstants;
import io.cattle.platform.iaas.api.auth.integration.ldap.ad.ADConstants;
import io.cattle.platform.iaas.api.auth.integration.local.LocalAuthConstants;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import com.netflix.config.DynamicBooleanProperty;
import com.netflix.config.DynamicLongProperty;
import com.netflix.config.DynamicStringProperty;

public class SecurityConstants {

    public static final String ENABLED = "enabled";
    public static final String SECURITY_SETTING = "api.security.enabled";
    public static final DynamicBooleanProperty SECURITY = ArchaiusUtil.getBoolean(SECURITY_SETTING);
    public static final String AUTH_PROVIDER_SETTING = "api.auth.provider.configured";
    public static final DynamicStringProperty AUTH_PROVIDER = ArchaiusUtil.getString(AUTH_PROVIDER_SETTING);
    public static final String ROLE_SETTING_BASE = "api.security.role.priority.";

    public static final String NO_PROVIDER = "none";
    public static final String CODE = "code";
    public static final String TOKEN_VERSION = "v1";
    public static final DynamicLongProperty TOKEN_EXPIRY_MILLIS = ArchaiusUtil.getLong("api.auth.jwt.token.expiry");
    public static final String HAS_LOGGED_IN = "hasLoggedIn";
    public static final String AUTH_ENABLER = "api.auth.enabler";
    public static final DynamicStringProperty AUTH_ENABLER_SETTING = ArchaiusUtil.getString(AUTH_ENABLER);
    public static final List<String> INTERNAL_AUTH_PROVIDERS = Collections.unmodifiableList(
            Arrays.asList(new String[] {AzureConstants.CONFIG, ADConstants.CONFIG, OpenLDAPConstants.CONFIG, LocalAuthConstants.CONFIG}));
}


text:
FROM node:16

WORKDIR /app

COPY package*.json .
RUN npm ci

COPY client client
COPY api api

ENV AUTH0_DOMAIN=buddyduel.us.auth0.com
ENV BASE_URL=https://buddyduel.net
ENV DATABASE_NAME=prod
ENV NODE_ENV=production
ENV PORT=8080

RUN npm run build-api
RUN npm run build-client-prod

EXPOSE 8080

CMD ["npm", "start"]


text:
require 'test_helper'

class Ccls::AbstractTest < ActiveSupport::TestCase

	assert_should_belong_to :study_subject
	assert_should_protect( :study_subject_id, :study_subject, :entry_1_by_uid,
		:entry_2_by_uid, :merged_by_uid )
	assert_should_not_require( *Abstract.db_fields )

	assert_should_require_length(
		:response_classification_day_7,
		:response_classification_day_14,
		:response_classification_day_28,
			:maximum => 2 )

	assert_should_require_length(
		:cytogen_chromosome_number,
			:maximum => 3 )

	assert_should_require_length(
		:flow_cyto_other_marker_1,
		:flow_cyto_other_marker_2,
		:flow_cyto_other_marker_3,
		:flow_cyto_other_marker_4,
		:flow_cyto_other_marker_5,
		:response_other1_value_day_7,
		:response_other1_value_day_14,
		:response_other2_value_day_7,
		:response_other2_value_day_14,
		:response_other3_value_day_14,
		:response_other4_value_day_14,
		:response_other5_value_day_14,
			:maximum => 4 )

	assert_should_require_length(
		:normal_cytogen,
		:is_cytogen_hosp_fish_t1221_done,
		:is_karyotype_normal,
		:physical_neuro,
		:physical_other_soft_2,
		:physical_gingival,
		:physical_leukemic_skin,
		:physical_lymph,
		:physical_spleen,
		:physical_testicle,
		:physical_other_soft,
		:is_hypodiploid,
		:is_hyperdiploid,
		:is_diploid,
		:dna_index,
		:cytogen_is_hyperdiploidy,
			:maximum => 5 )

	assert_should_require_length(
		:cytogen_t1221,
		:cytogen_inv16,
		:cytogen_t119,
		:cytogen_t821,
		:cytogen_t1517,
			:maximum => 9 )

	assert_should_require_length(
		:response_tdt_day_7,
		:response_tdt_day_14,
		:response_cd10_day_7,
		:response_cd10_day_14,
		:response_cd13_day_7,
		:response_cd13_day_14,
		:response_cd14_day_7,
		:response_cd14_day_14,
		:response_cd15_day_7,
		:response_cd15_day_14,
		:response_cd19_day_7,
		:response_cd19_day_14,
		:response_cd19cd10_day_7,
		:response_cd19cd10_day_14,
		:response_cd1a_day_14,
		:response_cd2a_day_14,
		:response_cd20_day_7,
		:response_cd20_day_14,
		:response_cd3_day_7,
		:response_cd3a_day_14,
		:response_cd33_day_7,
		:response_cd33_day_14,
		:response_cd34_day_7,
		:response_cd34_day_14,
		:response_cd4a_day_14,
		:response_cd5a_day_14,
		:response_cd56_day_14,
		:response_cd61_day_14,
		:response_cd7a_day_14,
		:response_cd8a_day_14,
		:flow_cyto_cd10,
		:flow_cyto_igm,
		:flow_cyto_bm_kappa,
		:flow_cyto_bm_lambda,
		:flow_cyto_cd10_19,
		:flow_cyto_cd19,
		:flow_cyto_cd20,
		:flow_cyto_cd21,
		:flow_cyto_cd22,
		:flow_cyto_cd23,
		:flow_cyto_cd24,
		:flow_cyto_cd40,
		:flow_cyto_surface_ig,
		:flow_cyto_cd1a,
		:flow_cyto_cd2,
		:flow_cyto_cd3,
		:flow_cyto_cd3_cd4,
		:flow_cyto_cd3_cd8,
		:flow_cyto_cd4,
		:flow_cyto_cd5,
		:flow_cyto_cd7,
		:flow_cyto_cd8,
		:flow_cyto_cd11b,
		:flow_cyto_cd11c,
		:flow_cyto_cd13,
		:flow_cyto_cd15,
		:flow_cyto_cd33,
		:flow_cyto_cd41,
		:flow_cyto_cdw65,
		:flow_cyto_cd34,
		:flow_cyto_cd61,
		:flow_cyto_cd14,
		:flow_cyto_glycoa,
		:flow_cyto_cd16,
		:flow_cyto_cd56,
		:flow_cyto_cd57,
		:flow_cyto_cd9,
		:flow_cyto_cd25,
		:flow_cyto_cd38,
		:flow_cyto_cd45,
		:flow_cyto_cd71,
		:flow_cyto_tdt,
		:flow_cyto_hladr,
		:response_hladr_day_7,
		:response_hladr_day_14,
			:maximum => 10 )

	assert_should_require_length(
		:response_blasts_units_day_7,
		:response_blasts_units_day_14,
		:response_blasts_units_day_28,
		:other_dna_measure,
		:response_fab_subtype,
			:maximum => 15 )

	assert_should_require_length(
		:flow_cyto_other_marker_1_name,
		:flow_cyto_other_marker_2_name,
		:flow_cyto_other_marker_3_name,
		:flow_cyto_other_marker_4_name,
		:flow_cyto_other_marker_5_name,
			:maximum => 20 )

	assert_should_require_length(
		:response_other1_name_day_7,
		:response_other1_name_day_14,
		:response_other2_name_day_7,
		:response_other2_name_day_14,
		:response_other3_name_day_14,
		:response_other4_name_day_14,
		:response_other5_name_day_14,
			:maximum => 25 )

	assert_should_require_length(
		:cytogen_other_trans_1,
		:cytogen_other_trans_2,
		:cytogen_other_trans_3,
		:cytogen_other_trans_4,
		:cytogen_other_trans_5,
		:cytogen_other_trans_6,
		:cytogen_other_trans_7,
		:cytogen_other_trans_8,
		:cytogen_other_trans_9,
		:cytogen_other_trans_10,
			:maximum => 35 )

	assert_should_require_length(
		:flow_cyto_igm_text,
		:flow_cyto_bm_kappa_text,
		:flow_cyto_bm_lambda_text,
		:flow_cyto_cd10_text,
		:flow_cyto_cd19_text,
		:flow_cyto_cd10_19_text,
		:flow_cyto_cd20_text,
		:flow_cyto_cd21_text,
		:flow_cyto_cd22_text,
		:flow_cyto_cd23_text,
		:flow_cyto_cd24_text,
		:flow_cyto_cd40_text,
		:flow_cyto_surface_ig_text,
		:flow_cyto_cd1a_text,
		:flow_cyto_cd2_text,
		:flow_cyto_cd3_text,
		:flow_cyto_cd4_text,
		:flow_cyto_cd5_text,
		:flow_cyto_cd7_text,
		:flow_cyto_cd8_text,
		:flow_cyto_cd3_cd4_text,
		:flow_cyto_cd3_cd8_text,
		:flow_cyto_cd11b_text,
		:flow_cyto_cd11c_text,
		:flow_cyto_cd13_text,
		:flow_cyto_cd15_text,
		:flow_cyto_cd33_text,
		:flow_cyto_cd41_text,
		:flow_cyto_cdw65_text,
		:flow_cyto_cd34_text,
		:flow_cyto_cd61_text,
		:flow_cyto_cd14_text,
		:flow_cyto_glycoa_text,
		:flow_cyto_cd16_text,
		:flow_cyto_cd56_text,
		:flow_cyto_cd57_text,
		:flow_cyto_cd9_text,
		:flow_cyto_cd25_text,
		:flow_cyto_cd38_text,
		:flow_cyto_cd45_text,
		:flow_cyto_cd71_text,
		:flow_cyto_tdt_text,
		:flow_cyto_hladr_text,
		:flow_cyto_other_marker_1_text,
		:flow_cyto_other_marker_2_text,
		:flow_cyto_other_marker_3_text,
		:flow_cyto_other_marker_4_text,
		:flow_cyto_other_marker_5_text,
		:ucb_fish_results,
		:fab_classification,
		:diagnosis_icdo_number,
		:cytogen_t922,
			:maximum => 50 )

	assert_should_require_length(
		:diagnosis_icdo_description,
			:maximum => 55 )

	assert_should_require_length(
		:ploidy_comment,
			:maximum => 100 )

	assert_should_require_length(
		:csf_red_blood_count_text,
		:blasts_are_present,
		:peripheral_blood_in_csf,
		:chemo_protocol_name,
		:conventional_karyotype_results,
		:hospital_fish_results,
		:hyperdiploidy_by,
			:maximum => 250 )

	assert_should_require_length(
		:marrow_biopsy_diagnosis,
		:marrow_aspirate_diagnosis,
		:csf_white_blood_count_text,
		:csf_comment,
		:chemo_protocol_agent_description,
		:chest_imaging_comment,
		:cytogen_comment,
		:discharge_summary,
		:flow_cyto_remarks,
		:response_comment_day_7,
		:response_comment_day_14,
		:histo_report_results,
		:response_comment,
			:maximum => 65000 )

	test "explicit Factory abstract test" do
		assert_difference('Abstract.count',1) {
			@abstract = Factory(:abstract)
		}
		( not_nil = %w( id created_at updated_at cbc_percent_blasts_unknown ) ).each do |c|
			assert_not_nil @abstract.send(c), "#{c} is nil"
		end
		( Abstract.column_names - not_nil ).each do |c|
			assert_nil @abstract.send(c), "#{c} is not nil"
		end
	end

	test "explicit Factory complete_abstract test" do
		assert_difference('Abstract.count',1) {
			#	this factory randomly sets values, some of which can be nil
			abstract = Factory(:complete_abstract)
		}
	end

	test "should not convert weight if weight_units is null" do
		abstract = Factory(:abstract,:weight_at_diagnosis => 100)
		assert_equal 100, abstract.reload.weight_at_diagnosis
	end

	test "should not convert weight if weight_units is kg" do
		abstract = Factory(:abstract,:weight_at_diagnosis => 100, :weight_units => 'kg')
		assert_equal 100, abstract.reload.weight_at_diagnosis
	end

	test "should convert weight to kg if weight_units is lb" do
		abstract = Factory(:abstract,:weight_at_diagnosis => 100, :weight_units => 'lb')
		abstract.reload
		assert_nil       abstract.weight_units
		assert_not_equal 100,   abstract.weight_at_diagnosis
		assert_in_delta   45.3, abstract.weight_at_diagnosis, 0.1
	end

	test "should not convert height if height_units is null" do
		abstract = Factory(:abstract,:height_at_diagnosis => 100)
		assert_equal 100, abstract.reload.height_at_diagnosis
	end

	test "should not convert height if height_units is cm" do
		abstract = Factory(:abstract,:height_at_diagnosis => 100, :height_units => 'cm')
		assert_equal 100, abstract.reload.height_at_diagnosis
	end

	test "should convert height to cm if height_units is in" do
		abstract = Factory(:abstract,:height_at_diagnosis => 100, :height_units => 'in')
		abstract.reload
		assert_nil       abstract.height_units
		assert_not_equal 100, abstract.height_at_diagnosis
		assert_in_delta  254, abstract.height_at_diagnosis, 0.1
	end

#	test "should return an array of ignorable columns" do
#		abstract = Factory(:abstract)
#		assert_equal abstract.ignorable_columns,
#			["id", "entry_1_by_uid", "entry_2_by_uid", "merged_by_uid",
#				"created_at", "updated_at", "study_subject_id"]
#	end
#
#	test "should return hash of comparable attributes" do
#		abstract = Factory(:abstract)
#		assert abstract.comparable_attributes.is_a?(Hash)
#	end

	test "should return true if abstracts are the same" do
		abstract1 = Factory(:abstract)
		abstract2 = Factory(:abstract)
		assert abstract1.is_the_same_as?(abstract2)
	end

	test "should return false if abstracts are not the same" do
		abstract1 = Factory(:abstract)
		abstract2 = Factory(:abstract, :height_at_diagnosis => 100 )
		assert !abstract1.is_the_same_as?(abstract2)
	end

	test "should return empty hash if abstracts are the same" do
		abstract1 = Factory(:abstract)
		abstract2 = Factory(:abstract)
		assert_equal Hash.new, abstract1.diff(abstract2)
		assert       abstract1.diff(abstract2).empty?
	end

	test "should return hash if abstracts are not the same" do
		abstract1 = Factory(:abstract)
		abstract2 = Factory(:abstract, :height_at_diagnosis => 100 )
		assert !abstract1.diff(abstract2).empty?
		assert  abstract1.diff(abstract2).has_key?('height_at_diagnosis')
	end

	test "should NOT set days since diagnosis fields on create without diagnosed_on" do
		abstract = Factory(:abstract)
		assert_nil abstract.diagnosed_on
		assert_nil abstract.response_day_7_days_since_diagnosis
		assert_nil abstract.response_day_14_days_since_diagnosis
		assert_nil abstract.response_day_28_days_since_diagnosis
	end

	test "should NOT set days since diagnosis fields on create without response_report_on" do
		abstract = Factory(:abstract,
			:diagnosed_on              => ( Date.today - 10 ),
			:response_report_on_day_7  => nil,
			:response_report_on_day_14 => nil,
			:response_report_on_day_28 => nil
		)
		assert_not_nil abstract.diagnosed_on
		assert_nil abstract.response_day_7_days_since_diagnosis
		assert_nil abstract.response_day_14_days_since_diagnosis
		assert_nil abstract.response_day_28_days_since_diagnosis
	end

	test "should set days since diagnosis fields on create with diagnosed_on" do
		today = Date.today
		abstract = Factory(:abstract,
			:diagnosed_on              => ( today - 40 ),
			:response_report_on_day_7  => ( today - 30 ),
			:response_report_on_day_14 => ( today - 20 ),
			:response_report_on_day_28 => ( today - 10 )
		)
		assert_not_nil abstract.diagnosed_on
		assert_not_nil abstract.response_day_7_days_since_diagnosis
		assert_equal 10, abstract.response_day_7_days_since_diagnosis
		assert_not_nil abstract.response_day_14_days_since_diagnosis
		assert_equal 20, abstract.response_day_14_days_since_diagnosis
		assert_not_nil abstract.response_day_28_days_since_diagnosis
		assert_equal 30, abstract.response_day_28_days_since_diagnosis
	end

	test "should NOT set days since treatment_began fields on create" <<
			" without treatment_began_on" do
		abstract = Factory(:abstract)
		assert_nil abstract.treatment_began_on
		assert_nil abstract.response_day_7_days_since_treatment_began
		assert_nil abstract.response_day_14_days_since_treatment_began
		assert_nil abstract.response_day_28_days_since_treatment_began
	end

	test "should NOT set days since treatment_began fields on create" <<
			" without response_report_on" do
		abstract = Factory(:abstract,
			:treatment_began_on        => ( Date.today - 10 ),
			:response_report_on_day_7  => nil,
			:response_report_on_day_14 => nil,
			:response_report_on_day_28 => nil
		)
		assert_not_nil abstract.treatment_began_on
		assert_nil abstract.response_day_7_days_since_treatment_began
		assert_nil abstract.response_day_14_days_since_treatment_began
		assert_nil abstract.response_day_28_days_since_treatment_began
	end

	test "should set days since treatment_began fields on create" <<
			" with treatment_began_on" do
		today = Date.today
		abstract = Factory(:abstract,
			:treatment_began_on        => ( today - 40 ),
			:response_report_on_day_7  => ( today - 30 ),
			:response_report_on_day_14 => ( today - 20 ),
			:response_report_on_day_28 => ( today - 10 )
		)
		assert_not_nil abstract.treatment_began_on
		assert_not_nil abstract.response_day_7_days_since_treatment_began
		assert_equal 10, abstract.response_day_7_days_since_treatment_began
		assert_not_nil abstract.response_day_14_days_since_treatment_began
		assert_equal 20, abstract.response_day_14_days_since_treatment_began
		assert_not_nil abstract.response_day_28_days_since_treatment_began
		assert_equal 30, abstract.response_day_28_days_since_treatment_began
	end

	test "should save a User as entry_1_by" do
		assert_difference('User.count',1) {
		assert_difference('Abstract.count',1) {
			abstract = Factory(:abstract,:entry_1_by => Factory(:user))
			assert abstract.entry_1_by.is_a?(User)
		} }
	end

	test "should save a User as entry_2_by" do
		assert_difference('User.count',1) {
		assert_difference('Abstract.count',1) {
			abstract = Factory(:abstract,:entry_2_by => Factory(:user))
			assert abstract.entry_2_by.is_a?(User)
		} }
	end

	test "should save a User as merged_by" do
		assert_difference('User.count',1) {
		assert_difference('Abstract.count',1) {
			abstract = Factory(:abstract,:merged_by => Factory(:user))
			assert abstract.merged_by.is_a?(User)
		} }
	end

	test "should create first abstract for study_subject with current_user" do
		assert_difference('StudySubject.count',1) {
			@study_subject = create_case_study_subject_with_patid(1234)
			assert_equal '1234', @study_subject.patid
		}
		@current_user = Factory(:user)
		assert_difference('Abstract.count',1) {
			abstract = create_abstract(:current_user => @current_user,
				:study_subject => @study_subject)
			assert_equal abstract.entry_1_by, @current_user
			assert_equal abstract.entry_2_by, @current_user
			assert_equal abstract.study_subject, @study_subject
		}
	end

	test "should create second abstract for study_subject with current_user" do
		assert_difference('StudySubject.count',1) {
			@study_subject = create_case_study_subject_with_patid(1234)
			assert_equal '1234', @study_subject.patid
		}
		@current_user = Factory(:user)
		abstract = create_abstract(:current_user => @current_user,
			:study_subject => @study_subject)
		assert_difference('Abstract.count',1) {
			abstract = create_abstract(:current_user => @current_user,
				:study_subject => @study_subject.reload)
			assert_equal abstract.entry_1_by, @current_user
			assert_equal abstract.entry_2_by, @current_user
			assert_equal abstract.study_subject, @study_subject
		}
	end

	test "should NOT create third abstract for study_subject with current_user " <<
			"without merging flag" do
		assert_difference('StudySubject.count',1) {
			@study_subject = create_case_study_subject_with_patid(1234)
			assert_equal '1234', @study_subject.patid
		}
		@current_user = Factory(:user)
		abstract = create_abstract(:current_user => @current_user,
			:study_subject => @study_subject)
		abstract = create_abstract(:current_user => @current_user,
			:study_subject => @study_subject.reload)
		assert_difference('Abstract.count',0) {
			abstract = create_abstract(:current_user => @current_user,
				:study_subject => @study_subject.reload)
			assert abstract.errors.on(:study_subject_id)
		}
	end

	test "should create third abstract for study_subject with current_user " <<
			"with merging flag" do
		assert_difference('StudySubject.count',1) {
			@study_subject = create_case_study_subject_with_patid(1234)
			assert_equal '1234', @study_subject.patid
		}
		@current_user = Factory(:user)
		abstract = create_abstract(:current_user => @current_user,
			:study_subject => @study_subject)
		abstract = create_abstract(:current_user => @current_user,
			:study_subject => @study_subject.reload)
#	yes, when creating the merged, the other 2 go away
		assert_difference('Abstract.count',-1) {
			abstract = create_abstract(:current_user => @current_user,
				:study_subject => @study_subject.reload, :merging => true)
			assert_equal abstract.merged_by, @current_user
			assert_equal abstract.study_subject, @study_subject
		}
	end

	test "should NOT create merged abstract if study_subject already has one" do
		study_subject = create_case_study_subject_with_patid(1234)
		a1 = create_abstract(:study_subject => study_subject)
		a1.merged_by = Factory(:user)
		a1.save
		assert_not_nil study_subject.reload.merged_abstract
		assert_not_nil a1.reload.merged_by
		assert a1.merged?
		assert_difference('Abstract.count',0) {
			a2 = create_abstract( :study_subject => study_subject, :merging => true)
			assert a2.errors.on(:study_subject_id)
		}
	end

	test "should return abstract sections for class" do
		sections = Abstract.sections
		assert  Abstract.class_variable_defined?("@@sections")
		assert sections.is_a?(Array)
		assert sections.length >= 15
		assert sections.first.is_a?(Hash)
	end

	test "should return abstract fields for class" do
		fields = Abstract.fields
		assert  Abstract.class_variable_defined?("@@fields")
		assert fields.is_a?(Array)
		assert fields.length >= 15
		assert fields.first.is_a?(Hash)
	end

	test "should return abstract fields for instance" do
		fields = Abstract.new.fields
		assert  Abstract.class_variable_defined?("@@fields")
		assert fields.is_a?(Array)
		assert fields.length >= 15
		assert fields.first.is_a?(Hash)
	end

	test "should return abstract db_fields for class" do
		db_fields = Abstract.db_fields
		assert  Abstract.class_variable_defined?("@@fields")
		assert db_fields.is_a?(Array)
		assert db_fields.length >= 15
		assert db_fields.first.is_a?(String)
	end

	test "should return abstract db_fields for instance" do
		db_fields = Abstract.new.db_fields
		assert  Abstract.class_variable_defined?("@@fields")
		assert db_fields.is_a?(Array)
		assert db_fields.length >= 15
		assert db_fields.first.is_a?(String)
	end

	[ :cbc_report_found,
		:cerebrospinal_fluid_report_found,
		:chemo_protocol_report_found,
		:chest_ct_medmass_present,
		:chest_imaging_report_found,
		:cytogen_hospital_fish_done,
		:cytogen_karyotype_done,
		:cytogen_report_found,
		:cytogen_trisomy4,
		:cytogen_trisomy5,
		:cytogen_trisomy10,
		:cytogen_trisomy17,
		:cytogen_trisomy21,
		:cytogen_ucb_fish_done,
		:diagnosis_is_all,
		:diagnosis_is_aml,
		:diagnosis_is_b_all,
		:diagnosis_is_cll,
		:diagnosis_is_cml,
		:diagnosis_is_other,
		:diagnosis_is_t_all,
		:discharge_summary_found,
		:flow_cyto_num_results_available,
		:flow_cyto_report_found,
		:h_and_p_reports_found,
		:hepatomegaly_present,
		:histo_report_found,
		:is_down_syndrome_phenotype,
		:marrow_aspirate_report_found,
		:marrow_biopsy_report_found,
		:mediastinal_mass_present,
		:patient_on_chemo_protocol,
		:ploidy_report_found,
		:received_bone_marrow_aspirate,
		:received_bone_marrow_biopsy,
		:received_cbc,
		:received_chemo_protocol,
		:received_chest_ct,
		:received_chest_xray,
		:received_csf,
		:received_cytogenetics,
		:received_discharge_summary,
		:received_flow_cytometry,
		:received_hla_typing,
		:received_h_and_p,
		:received_other_reports,
		:received_ploidy,
		:received_resp_to_therapy,
		:response_day14or28_flag,
		:response_day30_is_in_remission,
		:response_is_inconclusive_day_7,
		:response_is_inconclusive_day_14,
		:response_is_inconclusive_day_21,
		:response_is_inconclusive_day_28,
		:response_report_found_day_7,
		:response_report_found_day_14,
		:response_report_found_day_28,
		:splenomegaly_present,
		:tdt_often_found_flow_cytometry,
		:tdt_report_found ].each do |field|

		#	Making assumption that 12345 will NEVER be a valid value.
		test "should NOT allow 12345 for #{field}" do
			abstract = Abstract.new(field => 12345)
			abstract.valid?
			assert abstract.errors.on_attr_and_type?(field,:inclusion)
		end

		test "should allow nil for #{field}" do
			abstract = Abstract.new(field => nil)
			assert_nil abstract.send(field)
			abstract.valid?
			assert !abstract.errors.on(field)
		end

		test "should allow all valid YNDK values for #{field}" do
			abstract = Abstract.new
			YNDK.valid_values.each do |value|
				abstract.send("#{field}=", value)
				abstract.valid?
				assert !abstract.errors.on(field)
			end
		end

	end

end


text:
require 'date'
require 'google/apis/core/base_service'
require 'google/apis/core/json_representation'
require 'google/apis/core/hashable'
require 'google/apis/errors'

module Google
  module Apis
    module DigitalassetlinksV1

      class AndroidAppAsset
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class Asset
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class CertificateInfo
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class CheckResponse
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class ListResponse
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class Statement
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class WebAsset
        class Representation < Google::Apis::Core::JsonRepresentation; end

        include Google::Apis::Core::JsonObjectSupport
      end

      class AndroidAppAsset
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
          property :certificate, as: 'certificate', class: Google::Apis::DigitalassetlinksV1::CertificateInfo, decorator: Google::Apis::DigitalassetlinksV1::CertificateInfo::Representation

          property :package_name, as: 'packageName'
        end
      end

      class Asset
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
          property :android_app, as: 'androidApp', class: Google::Apis::DigitalassetlinksV1::AndroidAppAsset, decorator: Google::Apis::DigitalassetlinksV1::AndroidAppAsset::Representation

          property :web, as: 'web', class: Google::Apis::DigitalassetlinksV1::WebAsset, decorator: Google::Apis::DigitalassetlinksV1::WebAsset::Representation

        end
      end

      class CertificateInfo
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
          property :sha256_fingerprint, as: 'sha256Fingerprint'
        end
      end

      class CheckResponse
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
          property :debug_string, as: 'debugString'
          collection :error_code, as: 'errorCode'
          property :linked, as: 'linked'
          property :max_age, as: 'maxAge'
        end
      end

      class ListResponse
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
          property :debug_string, as: 'debugString'
          collection :error_code, as: 'errorCode'
          property :max_age, as: 'maxAge'
          collection :statements, as: 'statements', class: Google::Apis::DigitalassetlinksV1::Statement, decorator: Google::Apis::DigitalassetlinksV1::Statement::Representation

        end
      end

      class Statement
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
          property :relation, as: 'relation'
          property :source, as: 'source', class: Google::Apis::DigitalassetlinksV1::Asset, decorator: Google::Apis::DigitalassetlinksV1::Asset::Representation

          property :target, as: 'target', class: Google::Apis::DigitalassetlinksV1::Asset, decorator: Google::Apis::DigitalassetlinksV1::Asset::Representation

        end
      end

      class WebAsset
        # @private
        class Representation < Google::Apis::Core::JsonRepresentation
          property :site, as: 'site'
        end
      end
    end
  end
end


text:
import Flip from './Flip';

const not = fn => x => !fn(x);
const isDeferred = element =>
  typeof element.defer === 'function' ? element.defer() : element.defer;

class FlipGroup {
  constructor() {
    this.elements = [];
    this.elementsDeferred = [];
  }

  getConcernedElements(defer) {
    if (defer === undefined) {
      return this.elements;
    } else if (defer) {
      return this.elements.filter(isDeferred);
    } else {
      return this.elements.filter(not(isDeferred));
    }
  }

  addElement(element, defer) {
    if (element instanceof Flip) {
      this.elements = [...this.elements, { element, defer }];

      return () => {
        this.elements = this.elements.filter(
          current => current.element !== element
        );
      };
    }
  }

  first({ deferred } = {}) {
    this.getConcernedElements(deferred).forEach(({ element }) =>
      element.first());
  }

  last({ deferred } = {}) {
    this.getConcernedElements(deferred).forEach(({ element }) =>
      element.last());
  }

  invert({ deferred } = {}) {
    return this.getConcernedElements(deferred)
      .map(({ element }) => element.invert())
      .some(hasInverted => hasInverted);
  }

  play() {
    const playPromises = this.getConcernedElements()
      .map(({ element }) => element.play())
      .filter(promise => promise);

    if (playPromises.length === 0) {
      return;
    }
    return Promise.all(playPromises);
  }
}

export default FlipGroup;


text:
FILE(REMOVE_RECURSE
  "../msg_gen"
  "../msg_gen"
  "../src/Human_intention/msg"
  "CMakeFiles/rosbuild_premsgsrvgen"
)

# Per-language clean rules from dependency scanning.
FOREACH(lang)
  INCLUDE(CMakeFiles/rosbuild_premsgsrvgen.dir/cmake_clean_${lang}.cmake OPTIONAL)
ENDFOREACH(lang)


text:
source env/bin/activate
pip2.7 install -r requirements-2.txt
pip3.7 install -r requirements-3.txt

echo "Removing any previous build dir..."
rm -rf build
echo "Removing any previous dist dir..."
rm -rf dist

echo "Building for python 2.7..."
python2.7 setup.py sdist bdist_wheel
echo "\n\n\n"
echo "Building for python 3.7+..."
python3.7 setup.py sdist bdist_wheel
echo "\n\n\n"

echo "Running twine upload..."
twine upload dist/*