<commit_before>import Ember from 'ember';
import DS from 'ember-data';
import ValidationError from 'ilios/mixins/validation-error';
import EmberValidations from 'ember-validations';

const { Component, computed, inject, RSVP, isEmpty, isPresent } = Ember;
const { service } = inject;
const { PromiseArray } = DS;

export default Component.extend(EmberValidations, ValidationError, {
  init() {
    this._super(...arguments);
  },
  store: service(),
  i18n: service(),
  currentUser: service(),
  flashMessages: service(),
  classNames: ['form-container', 'detail-view', 'new-myreport', 'mesh-manager'],
  title: null,
  currentSchool: null,
  currentSubject: 'course',
  currentPrepositionalObject: null,
  currentPrepositionalObjectId: null,

  validations: {
    title : {
      length: {maximum: 240, allowBlank: true, messages: { tooLong: "myreport.errors.titleTooLong" }}
    }
  },

  subjectList: computed('i18n.locale', function(){
    let list = [
      {value: 'course', label: this.get('i18n').t('general.courses')},
      {value: 'session', label: this.get('i18n').t('general.sessions')},
      {value: 'program', label: this.get('i18n').t('general.programs')},
      {value: 'program year', label: this.get('i18n').t('general.programYears')},
      {value: 'instructor', label: this.get('i18n').t('general.instructors')},
      {value: 'instructor group', label: this.get('i18n').t('general.instructorGroups')},
      {value: 'learning material', label: this.get('i18n').t('general.learningMaterials')},
      {value: 'competency', label: this.get('i18n').t('general.competencies')},
      {value: 'mesh term', label: this.get('i18n').t('general.meshTerms')},
      {value: 'session type', label: this.get('i18n').t('general.sessionTypes')},
    ];

    return list;
  }),
  prepositionalObjectList: computed('i18n.locale', 'currentSubject', function(){
    let list = [
      {value: 'course', label: this.get('i18n').t('general.course'), subjects: ['session', 'program', 'program year', 'instructor', 'instructor group', 'learning material', 'competency', 'mesh term', 'session type']},
      {value: 'session', label: this.get('i18n').t('general.session'), subjects: ['course', 'program', 'program year', 'instructor', 'instructor group', 'learning material', 'competency', 'mesh term']},
      {value: 'program', label: this.get('i18n').t('general.program'), subjects: ['course', 'session', 'session type']},
      {value: 'instructor', label: this.get('i18n').t('general.instructor'), subjects: ['course', 'session', 'instructor group', 'learning material', 'session type']},
      {value: 'instructor group', label: this.get('i18n').t('general.instructorGroup'), subjects: ['course', 'session', 'instructor', 'learning material', 'session type']},
      {value: 'learning material', label: this.get('i18n').t('general.learningMaterial'), subjects: ['course', 'session', 'instructor', 'instructor group', 'mesh term', 'session type']},
      {value: 'competency', label: this.get('i18n').t('general.competency'), subjects: ['course', 'session', 'session type']},
      {value: 'mesh term', label: this.get('i18n').t('general.meshTerm'), subjects: ['course', 'session', 'learning material', 'session type']},
      {value: 'session type', label: this.get('i18n').t('general.sessionType'), subjects: ['session', 'instructor', 'instructor group', 'learning material', 'competency', 'mesh term']},
    ];

    const subject = this.get('currentSubject');

    return list.filter(item =>item.subjects.contains(subject));
  }),
  prepositionalObjectIdList: computed('currentPrepositionalObject', 'currentSchool', function(){
    const type = this.get('currentPrepositionalObject');

    let defer = RSVP.defer();
    if(isEmpty(type) || type === 'instructor'){
      defer.resolve([]);
      return PromiseArray.create({
        promise: defer.promise
      });
    }

    let model = type.dasherize();
    const store = this.get('store');
    const school = this.get('currentSchool');
    let query = {
      limit: 1000,
      filters: {}
    };
    if(isPresent(school)){
      let schoolScopedModels = [
        'session',
        'course',
        'program',
        'session-type',
        'instructor-group',
        'competency',
      ];
      if(schoolScopedModels.contains(model)){
        query.filters.school = this.get('currentSchool').get('id');
      }
    }

    store.query(model, query).then(objects => {
      let label = type === 'mesh term'?'name':'title';
      let values = objects.map(object => {
        return {
          value: object.get('id'),
          label: object.get(label)
        };
      }).sortBy('label');

      defer.resolve(values);
    });
    return PromiseArray.create({
      promise: defer.promise
    });
  }),
  currentSubjectLabel: computed('currentSubject', 'subjectList.[]', function(){
    const currentSubjectValue = this.get('currentSubject');
    let currentSubject = this.get('subjectList').find(subject => {
      return subject.value === currentSubjectValue;
    });

    return currentSubject.label;
  }),
  selectedUser: computed('currentPrepositionalObject', 'currentPrepositionalObjectId', function(){
    if(
      this.get('currentPrepositionalObject') === 'instructor' &&
      this.get('currentPrepositionalObjectId')
    ){
      return this.get('store').peekRecord('user', this.get('currentPrepositionalObjectId'));
    } else {
      return null;
    }
  }),
  selectedMeshTerm: computed('currentPrepositionalObject', 'currentPrepositionalObjectId', function(){
    if(
      this.get('currentPrepositionalObject') === 'mesh term' &&
      this.get('currentPrepositionalObjectId')
    ){
      return this.get('store').peekRecord('mesh-descriptor', this.get('currentPrepositionalObjectId'));
    } else {
      return null;
    }
  }),
  schoolList: computed('currentUser.schools.[]',function(){
    let defer = RSVP.defer();
    this.get('currentUser').get('model').then(user => {
      if(isEmpty(user)){
        defer.resolve([]);
      } else {
        user.get('schools').then(schools => {
          defer.resolve(schools.sortBy('title'));
        });
      }
    });
    return PromiseArray.create({
      promise: defer.promise
    });
  }),
  actions: {
    changeSchool(schoolId){
      let school = this.get('schoolList').find(school =>  school.get('id') === schoolId);
      this.set('currentSchool', school);
    },
    changeSubject(subject){
      this.set('currentSubject', subject);
      this.set('currentPrepositionalObject', null);
      this.set('currentPrepositionalObjectId', null);
    },
    changePrepositionalObject(object){
      this.set('currentPrepositionalObject', object);
      this.set('currentPrepositionalObjectId', null);
      this.get('prepositionalObjectIdList').then(list => {
        if(!this.get('currentPrepositionalObjectId')){
          let first = list.get('firstObject');
          if(first){
            this.set('currentPrepositionalObjectId', first.value);
          }
        }
      });
    },
    changePrepositionalObjectId(id){
      this.set('currentPrepositionalObjectId', id);
    },
    chooseInstructor(user){
      this.set('currentPrepositionalObjectId', user.get('id'));
    },
    chooseMeshTerm(term){
      this.set('currentPrepositionalObjectId', term.get('id'));
    },
    closeEditor(){
      this.sendAction('close');
    },
    save(){
      this.validate().then(() => {
        const flashMessages = this.get('flashMessages');
        const store = this.get('store');
        const subject = this.get('currentSubject');
        let object = this.get('currentPrepositionalObject');
        if (isPresent(subject) && isEmpty(object)) {
          if (subject === 'instructor') {
            flashMessages.alert('dashboard.reportMissingObjectForInstructor');
            return;
          }
          if (subject === 'mesh term') {
            flashMessages.alert('dashboard.reportMissingObjectForMeshTerm');
            return;
          }
        }
        if (
            object && !this.get('currentPrepositionalObjectId')
        ) {
          if (object === 'instructor') {
            flashMessages.alert('dashboard.reportMissingInstructor');
          }
          if (object === 'mesh term') {
            flashMessages.alert('dashboard.reportMissingMeshTerm');
          }
          return;
        }
        this.get('currentUser.model').then(user => {

          let title = this.get('title');
          let subject = this.get('currentSubject');
          let prepositionalObject = this.get('currentPrepositionalObject');
          let prepositionalObjectTableRowId = this.get('currentPrepositionalObjectId');
          let school = this.get('currentSchool');
          let report = store.createRecord('report', {
            title,
            user,
            subject,
            prepositionalObject,
            prepositionalObjectTableRowId,
            school
          });
          report.save().then(() => {
            this.sendAction('close');
          });
        });
      }).catch(() => {
        const keys = Ember.keys(this.get('errors'));
        keys.forEach((key) => {
          this.get('flashMessages').alert(this.get('errors.' + key));
        });
      });
    }
  }
});
<commit_msg>fixed report builder for school-scoped session assoc.<commit_after>import Ember from 'ember';
import DS from 'ember-data';
import ValidationError from 'ilios/mixins/validation-error';
import EmberValidations from 'ember-validations';

const { Component, computed, inject, RSVP, isEmpty, isPresent } = Ember;
const { service } = inject;
const { PromiseArray } = DS;

export default Component.extend(EmberValidations, ValidationError, {
  init() {
    this._super(...arguments);
  },
  store: service(),
  i18n: service(),
  currentUser: service(),
  flashMessages: service(),
  classNames: ['form-container', 'detail-view', 'new-myreport', 'mesh-manager'],
  title: null,
  currentSchool: null,
  currentSubject: 'course',
  currentPrepositionalObject: null,
  currentPrepositionalObjectId: null,

  validations: {
    title : {
      length: {maximum: 240, allowBlank: true, messages: { tooLong: "myreport.errors.titleTooLong" }}
    }
  },

  subjectList: computed('i18n.locale', function(){
    let list = [
      {value: 'course', label: this.get('i18n').t('general.courses')},
      {value: 'session', label: this.get('i18n').t('general.sessions')},
      {value: 'program', label: this.get('i18n').t('general.programs')},
      {value: 'program year', label: this.get('i18n').t('general.programYears')},
      {value: 'instructor', label: this.get('i18n').t('general.instructors')},
      {value: 'instructor group', label: this.get('i18n').t('general.instructorGroups')},
      {value: 'learning material', label: this.get('i18n').t('general.learningMaterials')},
      {value: 'competency', label: this.get('i18n').t('general.competencies')},
      {value: 'mesh term', label: this.get('i18n').t('general.meshTerms')},
      {value: 'session type', label: this.get('i18n').t('general.sessionTypes')},
    ];

    return list;
  }),
  prepositionalObjectList: computed('i18n.locale', 'currentSubject', function(){
    let list = [
      {value: 'course', label: this.get('i18n').t('general.course'), subjects: ['session', 'program', 'program year', 'instructor', 'instructor group', 'learning material', 'competency', 'mesh term', 'session type']},
      {value: 'session', label: this.get('i18n').t('general.session'), subjects: ['course', 'program', 'program year', 'instructor', 'instructor group', 'learning material', 'competency', 'mesh term']},
      {value: 'program', label: this.get('i18n').t('general.program'), subjects: ['course', 'session', 'session type']},
      {value: 'instructor', label: this.get('i18n').t('general.instructor'), subjects: ['course', 'session', 'instructor group', 'learning material', 'session type']},
      {value: 'instructor group', label: this.get('i18n').t('general.instructorGroup'), subjects: ['course', 'session', 'instructor', 'learning material', 'session type']},
      {value: 'learning material', label: this.get('i18n').t('general.learningMaterial'), subjects: ['course', 'session', 'instructor', 'instructor group', 'mesh term', 'session type']},
      {value: 'competency', label: this.get('i18n').t('general.competency'), subjects: ['course', 'session', 'session type']},
      {value: 'mesh term', label: this.get('i18n').t('general.meshTerm'), subjects: ['course', 'session', 'learning material', 'session type']},
      {value: 'session type', label: this.get('i18n').t('general.sessionType'), subjects: ['session', 'instructor', 'instructor group', 'learning material', 'competency', 'mesh term']},
    ];

    const subject = this.get('currentSubject');

    return list.filter(item =>item.subjects.contains(subject));
  }),
  prepositionalObjectIdList: computed('currentPrepositionalObject', 'currentSchool', function(){
    const type = this.get('currentPrepositionalObject');

    let defer = RSVP.defer();
    if(isEmpty(type) || type === 'instructor'){
      defer.resolve([]);
      return PromiseArray.create({
        promise: defer.promise
      });
    }

    let model = type.dasherize();
    const store = this.get('store');
    const school = this.get('currentSchool');
    let query = {
      limit: 1000,
      filters: {}
    };
    if(isPresent(school)){
      let schoolScopedModels = [
        'session',
        'course',
        'program',
        'session-type',
        'instructor-group',
        'competency',
      ];
      if(schoolScopedModels.contains(model)) {
        if ('session' === model) {
          query.filters.schools = [this.get('currentSchool').get('id')];
        } else {
          query.filters.school = this.get('currentSchool').get('id');
        }
      }
    }

    store.query(model, query).then(objects => {
      let label = type === 'mesh term'?'name':'title';
      let values = objects.map(object => {
        return {
          value: object.get('id'),
          label: object.get(label)
        };
      }).sortBy('label');

      defer.resolve(values);
    });
    return PromiseArray.create({
      promise: defer.promise
    });
  }),
  currentSubjectLabel: computed('currentSubject', 'subjectList.[]', function(){
    const currentSubjectValue = this.get('currentSubject');
    let currentSubject = this.get('subjectList').find(subject => {
      return subject.value === currentSubjectValue;
    });

    return currentSubject.label;
  }),
  selectedUser: computed('currentPrepositionalObject', 'currentPrepositionalObjectId', function(){
    if(
      this.get('currentPrepositionalObject') === 'instructor' &&
      this.get('currentPrepositionalObjectId')
    ){
      return this.get('store').peekRecord('user', this.get('currentPrepositionalObjectId'));
    } else {
      return null;
    }
  }),
  selectedMeshTerm: computed('currentPrepositionalObject', 'currentPrepositionalObjectId', function(){
    if(
      this.get('currentPrepositionalObject') === 'mesh term' &&
      this.get('currentPrepositionalObjectId')
    ){
      return this.get('store').peekRecord('mesh-descriptor', this.get('currentPrepositionalObjectId'));
    } else {
      return null;
    }
  }),
  schoolList: computed('currentUser.schools.[]',function(){
    let defer = RSVP.defer();
    this.get('currentUser').get('model').then(user => {
      if(isEmpty(user)){
        defer.resolve([]);
      } else {
        user.get('schools').then(schools => {
          defer.resolve(schools.sortBy('title'));
        });
      }
    });
    return PromiseArray.create({
      promise: defer.promise
    });
  }),
  actions: {
    changeSchool(schoolId){
      let school = this.get('schoolList').find(school =>  school.get('id') === schoolId);
      this.set('currentSchool', school);
    },
    changeSubject(subject){
      this.set('currentSubject', subject);
      this.set('currentPrepositionalObject', null);
      this.set('currentPrepositionalObjectId', null);
    },
    changePrepositionalObject(object){
      this.set('currentPrepositionalObject', object);
      this.set('currentPrepositionalObjectId', null);
      this.get('prepositionalObjectIdList').then(list => {
        if(!this.get('currentPrepositionalObjectId')){
          let first = list.get('firstObject');
          if(first){
            this.set('currentPrepositionalObjectId', first.value);
          }
        }
      });
    },
    changePrepositionalObjectId(id){
      this.set('currentPrepositionalObjectId', id);
    },
    chooseInstructor(user){
      this.set('currentPrepositionalObjectId', user.get('id'));
    },
    chooseMeshTerm(term){
      this.set('currentPrepositionalObjectId', term.get('id'));
    },
    closeEditor(){
      this.sendAction('close');
    },
    save(){
      this.validate().then(() => {
        const flashMessages = this.get('flashMessages');
        const store = this.get('store');
        const subject = this.get('currentSubject');
        let object = this.get('currentPrepositionalObject');
        if (isPresent(subject) && isEmpty(object)) {
          if (subject === 'instructor') {
            flashMessages.alert('dashboard.reportMissingObjectForInstructor');
            return;
          }
          if (subject === 'mesh term') {
            flashMessages.alert('dashboard.reportMissingObjectForMeshTerm');
            return;
          }
        }
        if (
            object && !this.get('currentPrepositionalObjectId')
        ) {
          if (object === 'instructor') {
            flashMessages.alert('dashboard.reportMissingInstructor');
          }
          if (object === 'mesh term') {
            flashMessages.alert('dashboard.reportMissingMeshTerm');
          }
          return;
        }
        this.get('currentUser.model').then(user => {

          let title = this.get('title');
          let subject = this.get('currentSubject');
          let prepositionalObject = this.get('currentPrepositionalObject');
          let prepositionalObjectTableRowId = this.get('currentPrepositionalObjectId');
          let school = this.get('currentSchool');
          let report = store.createRecord('report', {
            title,
            user,
            subject,
            prepositionalObject,
            prepositionalObjectTableRowId,
            school
          });
          report.save().then(() => {
            this.sendAction('close');
          });
        });
      }).catch(() => {
        const keys = Ember.keys(this.get('errors'));
        keys.forEach((key) => {
          this.get('flashMessages').alert(this.get('errors.' + key));
        });
      });
    }
  }
});
<|endoftext|>


<commit_before>'use strict';

angular.module('iMLApp.interactive-learning.interactive-learning-service', [])

  .factory('Util', function() {
    return {
      randomBetween: function(min, max) {
        var ret = Math.random() * max;
        while(ret + min > max)
          ret = Math.random() * max;
        return ret + min;
      },
      shuffle: function(a) {
        for (let i = a.length; i; i--) {
          let j = Math.floor(Math.random() * i);
          [a[i - 1], a[j]] = [a[j], a[i - 1]];
        }
        return a;
      },
      generateRandomNumbers: function(max, nrOfNumbers) {
        var r = [];
        var m = max;
        for(let i = 0; i < nrOfNumbers-1; i++) {
          r[i] = this.randomBetween(0, m);
          m -= r[i];
        }
        r[nrOfNumbers-1] = m;
        return this.shuffle(r);
      }
    };
  })

  .factory('ILService', function (Util, $resource, $q, anonymizationConfig) {
    //use $resource later for retrieval from webservice

    let dataResource = $resource('assets/testdata/marital-status-k2.json');
    let data = dataResource.query();

    console.log("AnonymizationJS:");
    console.dir($A);

    console.log("GraphiniusJS:");
    console.dir($G);

    let basename = "assets/00_sample_data_UI_prototype";
    let filename_originalData = "original_data_500_rows.csv";

    let TARGETS = [
      "target_education-num",
      "target_marital-status",
      "target_income"
    ];

    let csvIn = new $A.IO.CSVIN($A.config.adults);
    //console.log("CSV Reader: ");
    //console.log(csvIn);

    let url = basename + "/" + filename_originalData;
    let output = basename + "/output";

    //console.log("config:");
    //console.dir(config);

    // Specify Generalization hierarchy files
    let gen_base = 'assets/genHierarchies/',
      workclass_file = gen_base + 'workclassGH.json',
      sex_file = gen_base + 'sexGH.json',
      race_file = gen_base + 'raceGH.json',
      marital_file = gen_base + 'marital-statusGH.json',
      nat_country_file = gen_base + 'native-countryGH.json',
      relationship_file = gen_base + 'relationshipGH.json',
      occupation_file = gen_base + 'occupationGH.json',
      income_file = gen_base + 'incomeGH.json';

    return {
      getTestdata: function (callback) {
        let TestdataResource = $resource('assets/testdata/testdatarecords.json');
        TestdataResource.get(callback);
      },
      getMaritalStatusK2: function () {
        return data.$promise;
      },

      createSan: function(config, gen_base) {
        let san = new $A.algorithms.Sangreea("testus", config);
        console.log("SaNGreeA Algorithm:");
        console.log(san);

        // Inspect the internal graph => should be empty
        console.log("Graph Stats BEFORE Instantiation:");
        console.log(san._graph.getStats());

        // Uff, this feels like 2012 at the latest....
        $.ajaxSetup({
          async: false
        });

        // Load Generalization hierarchies
        [workclass_file, nat_country_file, sex_file, race_file, marital_file,
          relationship_file, occupation_file, income_file].forEach( function(file) {
          var json = $.getJSON(file).responseText;
          //console.log(json);
          let strgh = new $A.genHierarchy.Category(json);
          san.setCatHierarchy(strgh._name, strgh);
        });

        return san;
      },

      getWeightsArray: function(custom_weights) {

        let weights = [];
        weights.push(custom_weights.range['age']);
        weights.push(0.0); //space for education-num
        weights.push(custom_weights.range['hours-per-week']);
        weights.push(custom_weights.categorical['workclass']);
        weights.push(custom_weights.categorical['native-country']);
        weights.push(custom_weights.categorical['sex']);
        weights.push(custom_weights.categorical['race']);
        weights.push(custom_weights.categorical['relationship']);
        weights.push(custom_weights.categorical['occupation']);
        weights.push(custom_weights.categorical['income']);
        weights.push(custom_weights.categorical['marital-status']);

        return weights;
      },

      /**
       * Retrieves the data records from original csv that have not been anonymized
       */
      getNotAnonymizedRecords: function () {
        let deferred = $q.defer();

        csvIn.readCSVFromURL(url, function(csv) {
          let records = [];
          let headers = csv[0].split(", ");
          let anonymizedRecordsCount = config.NR_DRAWS;

          for (let recordIdx = 1; recordIdx <= (500-anonymizedRecordsCount); recordIdx++) {
            let record = csv[anonymizedRecordsCount + recordIdx].split(", ");
            records[recordIdx-1] = {};
            for (let i = 0; i < headers.length; i++) {
              records[recordIdx-1][headers[i]] = record[i];
            }
          }

          //TODO: order records / data point randomly

          //console.log("nodes: ", records);

          deferred.resolve(records);
        });

        return deferred.promise;
      },

      /**
       *
       */
      calculateRandomClusters: function(nrOfAdditionalDraws, fixedIndex, k) {

        // get global config data of config.js
        let config = anonymizationConfig;
        config.NR_DRAWS = nrOfAdditionalDraws + 1;
        config.K_FACTOR = k;

        let san = this.createSan(config, gen_base);
        let deferred = $q.defer();

        // Remotely read the original data and anonymize
        csvIn.readCSVFromURL(url, function(csv) {

          let randNrs = [];
          while(randNrs.length < nrOfAdditionalDraws){
              let randomnumber = Math.ceil(Math.random()*csv.length);
              if(randNrs.indexOf(randomnumber) > -1 || randomnumber === fixedIndex || randomnumber === 0) continue;
              randNrs[randNrs.length] = randomnumber;
          }

          let shortCSV = [];

          shortCSV.push(csv[0]);
          shortCSV.push(csv[fixedIndex]);
          for(let a in randNrs)
            shortCSV.push(csv[randNrs[a]]);

          console.log("shortCSV", shortCSV);
          san.instantiateGraph(shortCSV, false );
          // Inspect the internal graph again => should be populated now
          //console.log("Graph Stats AFTER Instantiation:");
          //console.log(san._graph.getStats());

          // let's run the whole anonymization inside the browser
          san.anonymizeGraph();

          // let's take a look at the clusters
          //console.log("Clusteres:");
          //console.dir(san._clusters);

          deferred.resolve([san._clusters, anonymizationConfig.GEN_WEIGHT_VECTORS.equal_weights]);
        });

        return deferred.promise;
      },

      getCase: function(nrOfDraws, k) {

        let deferred = $q.defer();

        /*
            generate two random clusters
            cluster1[0] and cluster2[0] is the header.. age, ...
            cluster1[1] and cluster2[1]is the fixed element (element in the middle)
            cluster1[2-20] and cluster2[2-20] are random elements of the 500element csv file
         */
        let promise_randomWeightClusters1 = this.calculateRandomClusters(nrOfDraws - 1, 1, k);
        let promise_randomWeightClusters2 = this.calculateRandomClusters(nrOfDraws - 1, 1, k);

        $q.all([promise_randomWeightClusters1, promise_randomWeightClusters2]).then(function (values) {

          let clusters1 = values[0][0];
          let weights1 = values[0][1];
          let clusters2 = values[1][0];
          let weights2 = values[1][1];

          //
          var cluster_obj ={};
          cluster_obj.cluster1 = clusters1[0];
          cluster_obj.cluster2 = clusters2[0];
          cluster_obj.dataPoint = clusters1[0].nodes[0];
          if(JSON.stringify(cluster_obj.cluster1.nodes[0]) !== JSON.stringify(cluster_obj.cluster2.nodes[0]))
            alert("fail");

          cluster_obj.cluster1.weights = weights1;
          cluster_obj.cluster2.weights = weights2;

          deferred.resolve([cluster_obj.dataPoint, cluster_obj.cluster1, cluster_obj.cluster2]);

        }, function(reason) {              //error
          console.log("ILCTrl " + "[error] retrieving of anonymized clusters and centers failed: ", reason);
        });

        return deferred.promise;
      },

      getCases: function(nrOfCases, nrOfDraws, k) {
        let deferred = $q.defer();

        let cases;
        let promises = [];

        for (let i = 0; i < nrOfCases; i++) {
          let promise = this.getCase(nrOfDraws, k);
          promises.push(promise);
        }

        $q.all(promises).then(function(data) {
          cases = data;
          deferred.resolve(cases);
          console.log("cases ", cases);
        });

        return deferred.promise;
      },

      getAnonymizedRecords: function () {
        let san = this.createSan(config, gen_base);

        let deferred = $q.defer();

        // Remotely read the original data and anonymize
        csvIn.readCSVFromURL(url, function(csv) {
          //console.log("File URL ANON: " + url);
          //console.log("File length ANON in total rows:");
          //console.log(csv.length);
          //console.log("Headers:");
          //console.log(csv[0]);
          //console.log(csv[1]);

          san.instantiateGraph(csv, false );
          // Inspect the internal graph again => should be populated now
          console.log("Graph Stats AFTER Instantiation:");
          console.log(san._graph.getStats());

          // let's run the whole anonymization inside the browser
          san.anonymizeGraph();

          // let's take a look at the clusters
          console.log("Clusteres:");
          console.dir(san._clusters);

          sampleCostCalculation(san);
          deferred.resolve(san._clusters);
        });

        //san.outputAnonymizedCSV(output);

        function sampleCostCalculation(san) {
          // Compute costs between some Cluster and some node
          let cluster = selectRandomCluster(san._clusters);
          let node = san._graph.getRandomNode();

          function selectRandomCluster(clusters) {
            return clusters[Math.floor(Math.random()*clusters.length)];
          }

          console.log("\n Computing cost of generalization between cluster and node:");
          console.log(cluster);
          console.log(node);
          console.log("Cost: " + san.calculateGIL(cluster, node));
        }

        return deferred.promise;
      }
    }
  });
<commit_msg>added random fixed index calculation commit message ENDE<commit_after>'use strict';

angular.module('iMLApp.interactive-learning.interactive-learning-service', [])

  .factory('Util', function() {
    return {
      fixedIndex: -1,
      randomBetween: function(min, max) {
        var ret = Math.random() * max;
        while(ret + min > max)
          ret = Math.random() * max;
        return ret + min;
      },
      shuffle: function(a) {
        for (let i = a.length; i; i--) {
          let j = Math.floor(Math.random() * i);
          [a[i - 1], a[j]] = [a[j], a[i - 1]];
        }
        return a;
      },
      generateRandomNumbers: function(max, nrOfNumbers) {
        var r = [];
        var m = max;
        for(let i = 0; i < nrOfNumbers-1; i++) {
          r[i] = this.randomBetween(0, m);
          m -= r[i];
        }
        r[nrOfNumbers-1] = m;
        return this.shuffle(r);
      }
    };
  })

  .factory('ILService', function (Util, $resource, $q, anonymizationConfig) {
    //use $resource later for retrieval from webservice

    let dataResource = $resource('assets/testdata/marital-status-k2.json');
    let data = dataResource.query();

    console.log("AnonymizationJS:");
    console.dir($A);

    console.log("GraphiniusJS:");
    console.dir($G);

    let basename = "assets/00_sample_data_UI_prototype";
    let filename_originalData = "original_data_500_rows.csv";

    let TARGETS = [
      "target_education-num",
      "target_marital-status",
      "target_income"
    ];

    let csvIn = new $A.IO.CSVIN($A.config.adults);
    //console.log("CSV Reader: ");
    //console.log(csvIn);

    let url = basename + "/" + filename_originalData;
    let output = basename + "/output";

    //console.log("config:");
    //console.dir(config);

    // Specify Generalization hierarchy files
    let gen_base = 'assets/genHierarchies/',
      workclass_file = gen_base + 'workclassGH.json',
      sex_file = gen_base + 'sexGH.json',
      race_file = gen_base + 'raceGH.json',
      marital_file = gen_base + 'marital-statusGH.json',
      nat_country_file = gen_base + 'native-countryGH.json',
      relationship_file = gen_base + 'relationshipGH.json',
      occupation_file = gen_base + 'occupationGH.json',
      income_file = gen_base + 'incomeGH.json';

    return {
      getTestdata: function (callback) {
        let TestdataResource = $resource('assets/testdata/testdatarecords.json');
        TestdataResource.get(callback);
      },
      getMaritalStatusK2: function () {
        return data.$promise;
      },

      createSan: function(config, gen_base) {
        let san = new $A.algorithms.Sangreea("testus", config);
        console.log("SaNGreeA Algorithm:");
        console.log(san);

        // Inspect the internal graph => should be empty
        console.log("Graph Stats BEFORE Instantiation:");
        console.log(san._graph.getStats());

        // Uff, this feels like 2012 at the latest....
        $.ajaxSetup({
          async: false
        });

        // Load Generalization hierarchies
        [workclass_file, nat_country_file, sex_file, race_file, marital_file,
          relationship_file, occupation_file, income_file].forEach( function(file) {
          var json = $.getJSON(file).responseText;
          //console.log(json);
          let strgh = new $A.genHierarchy.Category(json);
          san.setCatHierarchy(strgh._name, strgh);
        });

        return san;
      },

      getWeightsArray: function(custom_weights) {

        let weights = [];
        weights.push(custom_weights.range['age']);
        weights.push(0.0); //space for education-num
        weights.push(custom_weights.range['hours-per-week']);
        weights.push(custom_weights.categorical['workclass']);
        weights.push(custom_weights.categorical['native-country']);
        weights.push(custom_weights.categorical['sex']);
        weights.push(custom_weights.categorical['race']);
        weights.push(custom_weights.categorical['relationship']);
        weights.push(custom_weights.categorical['occupation']);
        weights.push(custom_weights.categorical['income']);
        weights.push(custom_weights.categorical['marital-status']);

        return weights;
      },

      /**
       * Retrieves the data records from original csv that have not been anonymized
       */
      getNotAnonymizedRecords: function () {
        let deferred = $q.defer();

        csvIn.readCSVFromURL(url, function(csv) {
          let records = [];
          let headers = csv[0].split(", ");
          let anonymizedRecordsCount = config.NR_DRAWS;

          for (let recordIdx = 1; recordIdx <= (500-anonymizedRecordsCount); recordIdx++) {
            let record = csv[anonymizedRecordsCount + recordIdx].split(", ");
            records[recordIdx-1] = {};
            for (let i = 0; i < headers.length; i++) {
              records[recordIdx-1][headers[i]] = record[i];
            }
          }

          //TODO: order records / data point randomly

          //console.log("nodes: ", records);

          deferred.resolve(records);
        });

        return deferred.promise;
      },

      /**
       *
       */
      calculateRandomClusters: function(nrOfAdditionalDraws, k) {

        // get global config data of config.js
        let config = anonymizationConfig;
        config.NR_DRAWS = nrOfAdditionalDraws + 1;
        config.K_FACTOR = k;

        let san = this.createSan(config, gen_base);
        let deferred = $q.defer();

        // Remotely read the original data and anonymize
        csvIn.readCSVFromURL(url, function(csv) {

          // generate a random fixed index
          if(Util.fixedIndex === -1)
            Util.fixedIndex = Math.ceil(Math.random()*csv.length);

          let randNrs = [];
          while(randNrs.length < nrOfAdditionalDraws){
              let randomnumber = Math.ceil(Math.random()*csv.length);
              if(randNrs.indexOf(randomnumber) > -1 || randomnumber === Util.fixedIndex || randomnumber === 0) continue;
              randNrs[randNrs.length] = randomnumber;
          }

          let shortCSV = [];

          shortCSV.push(csv[0]);
          shortCSV.push(csv[Util.fixedIndex]);
          for(let a in randNrs)
            shortCSV.push(csv[randNrs[a]]);

          console.log("shortCSV", shortCSV);
          san.instantiateGraph(shortCSV, false );
          // Inspect the internal graph again => should be populated now
          //console.log("Graph Stats AFTER Instantiation:");
          //console.log(san._graph.getStats());

          // let's run the whole anonymization inside the browser
          san.anonymizeGraph();

          // let's take a look at the clusters
          //console.log("Clusteres:");
          //console.dir(san._clusters);

          deferred.resolve([san._clusters, anonymizationConfig.GEN_WEIGHT_VECTORS.equal_weights]);
        });

        return deferred.promise;
      },

      getCase: function(nrOfDraws, k) {

        let deferred = $q.defer();

        /*
            generate two random clusters
            cluster1[0] and cluster2[0] is the header.. age, ...
            cluster1[1] and cluster2[1]is the fixed element (element in the middle)
            cluster1[2-20] and cluster2[2-20] are random elements of the 500element csv file
         */

        // generate the random data point sample index (used for both clusters)
        Util.fixedIndex = -1;
        let promise_randomWeightClusters1 = this.calculateRandomClusters(nrOfDraws - 1, k);
        console.log(Util.fixedIndex)
        let promise_randomWeightClusters2 = this.calculateRandomClusters(nrOfDraws - 1, k);
        Util.fixedIndex = -1;

        $q.all([promise_randomWeightClusters1, promise_randomWeightClusters2]).then(function (values) {

          let clusters1 = values[0][0];
          let weights1 = values[0][1];
          let clusters2 = values[1][0];
          let weights2 = values[1][1];

          //
          let cluster_obj ={};
          cluster_obj.cluster1 = clusters1[0];
          cluster_obj.cluster2 = clusters2[0];
          cluster_obj.dataPoint = clusters1[0].nodes[0];
          if(JSON.stringify(cluster_obj.cluster1.nodes[0]) !== JSON.stringify(cluster_obj.cluster2.nodes[0]))
            alert("fail");

          cluster_obj.cluster1.weights = weights1;
          cluster_obj.cluster2.weights = weights2;

          deferred.resolve([cluster_obj.dataPoint, cluster_obj.cluster1, cluster_obj.cluster2]);

        }, function(reason) {              //error
          console.log("ILCTrl " + "[error] retrieving of anonymized clusters and centers failed: ", reason);
        });

        return deferred.promise;
      },

      getCases: function(nrOfCases, nrOfDraws, k) {
        let deferred = $q.defer();

        let cases;
        let promises = [];

        for (let i = 0; i < nrOfCases; i++) {
          let promise = this.getCase(nrOfDraws, k);
          promises.push(promise);
        }

        $q.all(promises).then(function(data) {
          cases = data;
          deferred.resolve(cases);
          console.log("cases ", cases);
        });

        return deferred.promise;
      },

      getAnonymizedRecords: function () {
        let san = this.createSan(config, gen_base);

        let deferred = $q.defer();

        // Remotely read the original data and anonymize
        csvIn.readCSVFromURL(url, function(csv) {
          //console.log("File URL ANON: " + url);
          //console.log("File length ANON in total rows:");
          //console.log(csv.length);
          //console.log("Headers:");
          //console.log(csv[0]);
          //console.log(csv[1]);

          san.instantiateGraph(csv, false );
          // Inspect the internal graph again => should be populated now
          console.log("Graph Stats AFTER Instantiation:");
          console.log(san._graph.getStats());

          // let's run the whole anonymization inside the browser
          san.anonymizeGraph();

          // let's take a look at the clusters
          console.log("Clusteres:");
          console.dir(san._clusters);

          sampleCostCalculation(san);
          deferred.resolve(san._clusters);
        });

        //san.outputAnonymizedCSV(output);

        function sampleCostCalculation(san) {
          // Compute costs between some Cluster and some node
          let cluster = selectRandomCluster(san._clusters);
          let node = san._graph.getRandomNode();

          function selectRandomCluster(clusters) {
            return clusters[Math.floor(Math.random()*clusters.length)];
          }

          console.log("\n Computing cost of generalization between cluster and node:");
          console.log(cluster);
          console.log(node);
          console.log("Cost: " + san.calculateGIL(cluster, node));
        }

        return deferred.promise;
      }
    }
  });
<|endoftext|>


<commit_before>
class Foo {
  constructor() {
    return '*/*';
  }

  method1 () {
    return '*/*';
  }
}

class Bar extends foo {
  constructor() {
    return '*/*';
  }

  method1 () {
    return '*/*';
  }

  method2 () {
    return '*/*';
  }
}

var Foobar = class {
  constructor () {
    return '*/*';
  }

  method1 () {
    return '*/*';
  }
}
<commit_msg>Update class test case for property initiazier<commit_after>
class Foo {
  constructor() {
    return '*/*';
  }

  method1 () {
    return '*/*';
  }
}

class Bar extends foo {
  constructor() {
    return '*/*';
  }

  method1 () {
    return '*/*';
  }

  method2 () {
    return '*/*';
  }
}

var foo = foo.bar ? `${zzz}` : `${xd}` ;
var Foobar = {
  foo: foo.bar ? `${zzz}` : `${xd}` ;
}
var Foobar = class {
  foo = foo.bar ? `${zzz}` : `${xd}` ;
  constructor () {
    return '*/*';
  }

  method1 () {
    return '*/*';
  }
}
<|endoftext|>


<commit_before>/* eslint-disable */

import React from 'react';
import { keyBy, map } from 'lodash';
import RogueClient from '../../utilities/RogueClient';
import { extractPostsFromSignups, extractSignupsFromPosts } from '../../helpers';

const reviewComponent = (Component, data) => {
  return class extends React.Component {
    constructor(props) {
      super(props);

      this.state = {
        loading: true,
      };

      this.api = new RogueClient(window.location.origin, {
        headers: { 'Authorization' : `Bearer ${window.AUTH}`}
      });
      this.updatePost = this.updatePost.bind(this);
      this.updateTag = this.updateTag.bind(this);
      this.updateQuantity = this.updateQuantity.bind(this);
      this.showHistory = this.showHistory.bind(this);
      this.hideHistory = this.hideHistory.bind(this);
      this.deletePost = this.deletePost.bind(this);
      this.setNewPosts = this.setNewPosts.bind(this);
      this.rotate = this.rotate.bind(this);
    }

    // Loads initial posts into state.
    componentDidMount() {
      // Require initial_posts and campaign parameters.
      if (data.initial_posts && data.campaign) {
        this.getPostsByStatus(data.initial_posts, data.campaign.id);
      } else {
        // @TODO - handle error better.
        console.log("Error: need to know the initial posts to load and the campaign.");
      }
    }

    // Make API call to GET api/v3/posts to get posts by filtered status.
    getPostsByStatus(status, campaignId) {
      this.api.getPosts({
        filter: {
          status: status,
          campaign_id: campaignId,
        },
        include: ['signup','siblings'],
      }).then(json => this.setState({
        campaign: data.campaign,
        posts: keyBy(json.data, 'id'),
        postIds: map(json.data, 'id'),
        signups: extractSignupsFromPosts(keyBy(json.data, 'id')),
        filter: status,
        // postTotals: json.meta.pagination.total,
        displayHistoryModal: null,
        historyModalId: null,
        loading: false,
        nextPage: json.meta.cursor.next,
        prevPage: json.meta.cursor.prev,
      }));
    }

    setNewPosts(apiResponse) {
      const posts = keyBy(apiResponse.data, 'id');
      this.setState({
        campaign: data.campaign,
        posts: posts,
        postIds: map(apiResponse.data, 'id'),
        signups: extractSignupsFromPosts(posts),
        // postTotals: apiResponse.meta.pagination.total,
        displayHistoryModal: null,
        historyModalId: null,
        loading: false,
        nextPage: apiResponse.meta.cursor.next,
        prevPage: apiResponse.meta.cursor.prev,
      });
    }

    // Open the history modal of the given post
    showHistory(postId, event, signupId) {
      event.preventDefault();

      this.api.getEvents({
        filter: {
          signup_id: signupId,
        }
      }).then((result) => {
        this.setState((previousState) => {
          const newState = {...previousState};

          newState.displayHistoryModal = true;
          newState.historyModalId = postId;
          newState.signupEvents = Object.values(result.data);
          return newState;
        });
      });
    }

    // Close the open history modal
    hideHistory(event) {
      if (event) {
        event.preventDefault();
      }

      this.setState({
        displayHistoryModal: false,
        historyModalId: null,
      });
    }

    // Updates a post status.
    updatePost(postId, fields) {
      fields.post_id = postId;

      let request = this.api.postReview(fields);

      return request.then((result) => {
        this.setState((previousState) => {
          const newState = {...previousState};
          newState.posts[postId].status = fields.status;

          return newState;
        });
      });
    }

    // Tag a post.
    updateTag(postId, tag) {
      const fields = {
        post_id: postId,
        tag_name: tag,
      };

      let response = this.api.post('tags', fields);

      return response.then((result) => {
        this.setState((previousState) => {
          const newState = {...previousState};
          const user = newState.posts[postId].user;
          const signup = newState.posts[postId].signup.data;

          // Merge existing post with the newly updated values from API.
          newState.posts[postId] = {
            ...newState.posts[postId],
            ...result['data']
          };

          return newState;
        });
      });
    }

    // Update a post's quantity.
    updateQuantity(post, newQuantity) {
      // Field to send to /api/v3/posts/:post_id
      const field = {
        quantity: parseInt(newQuantity),
      };

      // Make API request to Rogue to update the quantity on the backend
      let request = this.api.patch(`api/v3/posts/${post['id']}`, field);

      request.then((result) => {
        // Update the state
        this.setState((previousState) => {
          const newState = {...previousState};
          newState.posts[post['id']].quantity = result.data['quantity'];

          return newState;
        });
      });

      // Close the modal
      this.hideHistory();
    }

    // Delete a post.
    deletePost(postId, event) {
      event.preventDefault();
      const confirmed = confirm('🚨🔥🚨Are you sure you want to delete this?🚨🔥🚨');

      if (confirmed) {
        // Make API request to Rogue to update the quantity on the backend
        let response = this.api.delete('posts/'.concat(postId));

        response.then((result) => {
          // Update the state
          this.setState((previousState) => {
            var newState = {...previousState};

            // Remove the deleted post from the state
            delete(newState.posts[postId]);

            // Remove the postId from the state.
            const postIdIndex = newState.postIds.indexOf(postId);

            if (postIdIndex > -1) {
              newState.postIds.splice(postIdIndex, 1);
            }

            // Return the new state
            return newState;
          });
        });
      }
    }

    // Rotate a Post Image.
    rotate(postId) {
      const post = this.state.posts[postId];

      let response = this.api.post(`images/${postId}?rotate=90`);

      return response.then((json) => {
        this.setState((prevState) => {
          const newState = {...prevState};
          // Add a cache-busting string to the end of the image url
          // so that it changes and triggers a re-render.
          newState.posts[postId].media.original_image_url = json.original_image_url + '?time=' + Date.now();

          return newState;
        });
      });
    }

    render() {
      const methods = {
        updatePost: this.updatePost,
        updateTag: this.updateTag,
        updateQuantity: this.updateQuantity,
        showHistory: this.showHistory,
        hideHistory: this.hideHistory,
        deletePost: this.deletePost,
        setNewPosts: this.setNewPosts,
        rotate: this.rotate,
      };

      // Pass in the state from this HoC to trigger rendering down the DOM
      // Also pass in methods bound to this instance.
      // Also pass in original data pass to the HoC in case other components still need it down the line.
      return <Component {...this.state} {...methods} {...data} />;
    }
  }
}

export default reviewComponent;

<commit_msg>removes commented out lines<commit_after>/* eslint-disable */

import React from 'react';
import { keyBy, map } from 'lodash';
import RogueClient from '../../utilities/RogueClient';
import { extractPostsFromSignups, extractSignupsFromPosts } from '../../helpers';

const reviewComponent = (Component, data) => {
  return class extends React.Component {
    constructor(props) {
      super(props);

      this.state = {
        loading: true,
      };

      this.api = new RogueClient(window.location.origin, {
        headers: { 'Authorization' : `Bearer ${window.AUTH}`}
      });
      this.updatePost = this.updatePost.bind(this);
      this.updateTag = this.updateTag.bind(this);
      this.updateQuantity = this.updateQuantity.bind(this);
      this.showHistory = this.showHistory.bind(this);
      this.hideHistory = this.hideHistory.bind(this);
      this.deletePost = this.deletePost.bind(this);
      this.setNewPosts = this.setNewPosts.bind(this);
      this.rotate = this.rotate.bind(this);
    }

    // Loads initial posts into state.
    componentDidMount() {
      // Require initial_posts and campaign parameters.
      if (data.initial_posts && data.campaign) {
        this.getPostsByStatus(data.initial_posts, data.campaign.id);
      } else {
        // @TODO - handle error better.
        console.log("Error: need to know the initial posts to load and the campaign.");
      }
    }

    // Make API call to GET api/v3/posts to get posts by filtered status.
    getPostsByStatus(status, campaignId) {
      this.api.getPosts({
        filter: {
          status: status,
          campaign_id: campaignId,
        },
        include: ['signup','siblings'],
      }).then(json => this.setState({
        campaign: data.campaign,
        posts: keyBy(json.data, 'id'),
        postIds: map(json.data, 'id'),
        signups: extractSignupsFromPosts(keyBy(json.data, 'id')),
        filter: status,
        displayHistoryModal: null,
        historyModalId: null,
        loading: false,
        nextPage: json.meta.cursor.next,
        prevPage: json.meta.cursor.prev,
      }));
    }

    setNewPosts(apiResponse) {
      const posts = keyBy(apiResponse.data, 'id');
      this.setState({
        campaign: data.campaign,
        posts: posts,
        postIds: map(apiResponse.data, 'id'),
        signups: extractSignupsFromPosts(posts),
        displayHistoryModal: null,
        historyModalId: null,
        loading: false,
        nextPage: apiResponse.meta.cursor.next,
        prevPage: apiResponse.meta.cursor.prev,
      });
    }

    // Open the history modal of the given post
    showHistory(postId, event, signupId) {
      event.preventDefault();

      this.api.getEvents({
        filter: {
          signup_id: signupId,
        }
      }).then((result) => {
        this.setState((previousState) => {
          const newState = {...previousState};

          newState.displayHistoryModal = true;
          newState.historyModalId = postId;
          newState.signupEvents = Object.values(result.data);
          return newState;
        });
      });
    }

    // Close the open history modal
    hideHistory(event) {
      if (event) {
        event.preventDefault();
      }

      this.setState({
        displayHistoryModal: false,
        historyModalId: null,
      });
    }

    // Updates a post status.
    updatePost(postId, fields) {
      fields.post_id = postId;

      let request = this.api.postReview(fields);

      return request.then((result) => {
        this.setState((previousState) => {
          const newState = {...previousState};
          newState.posts[postId].status = fields.status;

          return newState;
        });
      });
    }

    // Tag a post.
    updateTag(postId, tag) {
      const fields = {
        post_id: postId,
        tag_name: tag,
      };

      let response = this.api.post('tags', fields);

      return response.then((result) => {
        this.setState((previousState) => {
          const newState = {...previousState};
          const user = newState.posts[postId].user;
          const signup = newState.posts[postId].signup.data;

          // Merge existing post with the newly updated values from API.
          newState.posts[postId] = {
            ...newState.posts[postId],
            ...result['data']
          };

          return newState;
        });
      });
    }

    // Update a post's quantity.
    updateQuantity(post, newQuantity) {
      // Field to send to /api/v3/posts/:post_id
      const field = {
        quantity: parseInt(newQuantity),
      };

      // Make API request to Rogue to update the quantity on the backend
      let request = this.api.patch(`api/v3/posts/${post['id']}`, field);

      request.then((result) => {
        // Update the state
        this.setState((previousState) => {
          const newState = {...previousState};
          newState.posts[post['id']].quantity = result.data['quantity'];

          return newState;
        });
      });

      // Close the modal
      this.hideHistory();
    }

    // Delete a post.
    deletePost(postId, event) {
      event.preventDefault();
      const confirmed = confirm('🚨🔥🚨Are you sure you want to delete this?🚨🔥🚨');

      if (confirmed) {
        // Make API request to Rogue to update the quantity on the backend
        let response = this.api.delete('posts/'.concat(postId));

        response.then((result) => {
          // Update the state
          this.setState((previousState) => {
            var newState = {...previousState};

            // Remove the deleted post from the state
            delete(newState.posts[postId]);

            // Remove the postId from the state.
            const postIdIndex = newState.postIds.indexOf(postId);

            if (postIdIndex > -1) {
              newState.postIds.splice(postIdIndex, 1);
            }

            // Return the new state
            return newState;
          });
        });
      }
    }

    // Rotate a Post Image.
    rotate(postId) {
      const post = this.state.posts[postId];

      let response = this.api.post(`images/${postId}?rotate=90`);

      return response.then((json) => {
        this.setState((prevState) => {
          const newState = {...prevState};
          // Add a cache-busting string to the end of the image url
          // so that it changes and triggers a re-render.
          newState.posts[postId].media.original_image_url = json.original_image_url + '?time=' + Date.now();

          return newState;
        });
      });
    }

    render() {
      const methods = {
        updatePost: this.updatePost,
        updateTag: this.updateTag,
        updateQuantity: this.updateQuantity,
        showHistory: this.showHistory,
        hideHistory: this.hideHistory,
        deletePost: this.deletePost,
        setNewPosts: this.setNewPosts,
        rotate: this.rotate,
      };

      // Pass in the state from this HoC to trigger rendering down the DOM
      // Also pass in methods bound to this instance.
      // Also pass in original data pass to the HoC in case other components still need it down the line.
      return <Component {...this.state} {...methods} {...data} />;
    }
  }
}

export default reviewComponent;

<|endoftext|>


<commit_before>var gulp = require('gulp');
var metascriptPipe = require('gulp-metascript');
var headerPipe = require('gulp-header');
var chmod = require('gulp-chmod');
var clean = require('gulp-clean');

gulp.task('metascript', ['clean'], function () {
  return gulp.src('Sources/**/*.js')
    .pipe(metascriptPipe())
    .pipe(headerPipe("/* It is auto-generated file. Do not modify it. */\n"))
    .pipe(chmod({ write: false }))
    .on('error', logError)
    .pipe(gulp.dest('../Libraries/'));
});

gulp.task('clean', function () {
  return gulp.src('../Libraries', { read: false })
    .pipe(clean({ force: true }));
});

gulp.task('build-Debug', ['metascript']);
gulp.task('build-Release', ['metascript']);

/*Helpers*/
function logError(error) {
  console.error(error.message);
  process.exit(1);
}
<commit_msg>Translated scripts should contain BOM at the beginning.<commit_after>var gulp = require('gulp');
var metascriptPipe = require('gulp-metascript');
var headerPipe = require('gulp-header');
var chmod = require('gulp-chmod');
var clean = require('gulp-clean');

gulp.task('metascript', ['clean'], function () {
  return gulp.src('Sources/**/*.js')
    .pipe(metascriptPipe())
    .pipe(headerPipe("\uFEFF/* It is auto-generated file. Do not modify it. */\n"))
    .pipe(chmod({ write: false }))
    .on('error', logError)
    .pipe(gulp.dest('../Libraries/'));
});

gulp.task('clean', function () {
  return gulp.src('../Libraries', { read: false })
    .pipe(clean({ force: true }));
});

gulp.task('build-Debug', ['metascript']);
gulp.task('build-Release', ['metascript']);

/*Helpers*/
function logError(error) {
  console.error(error.message);
  process.exit(1);
}
<|endoftext|>


<commit_before>/*
 *     (C) Copyright 2012-2013 Universidad Politécnica de Madrid
 *
 *     This file is part of Wirecloud Platform.
 *
 *     Wirecloud Platform is free software: you can redistribute it and/or
 *     modify it under the terms of the GNU Affero General Public License as
 *     published by the Free Software Foundation, either version 3 of the
 *     License, or (at your option) any later version.
 *
 *     Wirecloud is distributed in the hope that it will be useful, but WITHOUT
 *     ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 *     FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
 *     License for more details.
 *
 *     You should have received a copy of the GNU Affero General Public License
 *     along with Wirecloud Platform.  If not, see
 *     <http://www.gnu.org/licenses/>.
 *
 */

/*global EzWebExt, Wirecloud*/

Wirecloud.location = {
    'domain': document.location.protocol + '//' + document.location.host,
    'protocol': document.location.protocol.substr(0, document.location.protocol.length - 1),
    'host': document.location.host
};

(function () {

    "use strict";

    var setRequestHeaders = function setRequestHeaders() {
        var headers, name;

        headers = EzWebExt.merge({
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
        }, this.options.requestHeaders);

        if (!('Content-Type' in headers) && this.options.contentType != null) {
            headers['Content-Type'] = this.options.contentType;
            if (this.options.encoding != null) {
                headers['Content-Type'] += '; charset=' + this.options.encoding;
            }
        }

        for (name in headers) {
            this.transport.setRequestHeader(name, headers[name]);
        }
    };

    var onReadyStateChange = function onReadyStateChange() {
        if (this.transport.readyState == 4) {

            var response = new Response(this);

            try {
                if (('on' + response.status) in this.options) {
                    this.options['on' + response.status](response);
                } else if (this.options.onSuccess && (response.status >= 200 && response.status < 300)) {
                    this.options.onSuccess(response);
                } else if (this.options.onFailure) {
                    this.options.onFailure(response);
                }
            } catch (e) {
            }

            if (this.options.onComplete) {
                try {
                    this.options.onComplete();
                } catch (e) {}
            }
        }
    };

    var Response = function Response(request) {
        Object.defineProperties(this, {
            'request': {value: request},
            'transport': {value: request.transport},
            'status': {value: request.transport.status},
            'statusText': {value: request.transport.statusText},
            'response': {value: request.transport.response},
            'responseText': {value: request.transport.responseText}
        });
    };

    Response.prototype.getHeader = function getHeader(name) {
        try {
            return this.transport.getResponseHeader(name);
        } catch (e) { return null; }
    };

    Response.prototype.getAllResponseHeaders = function getAllResponseHeaders() {
        return this.transport.getAllResponseHeaders();
    };

    var toQueryString = function toQueryString(parameters) {
        var key, query = '';

        if (typeof parameters === 'string') {
            return parameters;
        }

        for (key in parameters) {
            query += '&' + encodeURIComponent(key) + '=' + encodeURIComponent(parameters[key]);
        }

        return query.substr(1);
    };

    var Request = function Request(url, options) {
        this.url = url;
        this.options = EzWebExt.merge({
            method:       'POST',
            asynchronous: true,
            responseType: null,
            contentType:  null,
            encoding:     null,
            postBody:     null
        }, options);

        if (this.options.onSuccess != null && typeof this.options.onSuccess !== 'function') {
            throw new TypeError('Invalid onSuccess callback');
        }
        if (this.options.onFailure != null && typeof this.options.onFailure !== 'function') {
            throw new TypeError('Invalid onFailure callback');
        }
        this.method = this.options.method.toUpperCase();

        if (this.options.parameters != null && (typeof this.options.parameters === 'string' || typeof this.options.parameters === 'object')) {
            if (['PUT', 'POST'].indexOf(this.method) !== -1 && this.options.postBody == null) {
                this.postBody = toQueryString(this.options.parameters);
                if (this.options.contentType == null) {
                    this.options.contentType = 'application/x-www-form-urlencoded';
                }
                if (this.options.encoding == null) {
                    this.options.encoding = 'UTF-8';
                }
            } else if (this.method === 'GET') {
                if (this.url.indexOf('?') !== -1) {
                    this.url += '&' + toQueryString(this.options.parameters);
                }  else {
                    this.url += '?' + toQueryString(this.options.parameters);
                }
            }
        }

        this.transport = new XMLHttpRequest();
        this.transport.open(this.options.method, this.url, this.options.asynchronous);
        if (this.options.responseType) {
            this.transport.responseType = this.options.responseType;
        }
        this.transport.addEventListener('readystatechange', onReadyStateChange.bind(this), true);
        setRequestHeaders.call(this);
        this.transport.send(this.options.postBody);
    };

    var io = {};

    io.buildProxyURL = function buildProxyURL(url, options) {
        var final_url, protocolEnd, link, forceProxy, hostStart, pathStart, protocol,
            host, rest;

        forceProxy = options != null && !!options.forceProxy;

        if (url.length > 4 && url.indexOf('www.') === 0) {
            url = 'http://' + url;
        }

        protocol = Wirecloud.location.protocol;
        host = Wirecloud.location.host;

        protocolEnd = url.indexOf('://');
        if (protocolEnd !== -1) {
            hostStart = protocolEnd + 3;
            pathStart = url.indexOf('/', hostStart);
            if (pathStart === -1) {
                pathStart = url.length;
            }

            protocol = url.substr(0, protocolEnd);
            host = url.substr(hostStart, pathStart - hostStart);
            rest = url.substring(pathStart);
            final_url = url;
        } else {
            if (url.charAt(0) === '/') {
                rest = url;
            } else {
                rest = '/' + url;
            }

            if (!forceProxy) {
                final_url = Wirecloud.location.domain + rest;
            }
        }

        if (forceProxy || protocol !== Wirecloud.location.protocol || host !== Wirecloud.location.host) {
            final_url = Wirecloud.location.domain +
                Wirecloud.URLs.PROXY.evaluate({protocol: protocol, domain: host, path: rest});
        }

        return final_url;
    };

    io.makeRequest = function makeRequest(url, options) {
        var handlerRegExp, key;

        if (options != null && options.context != null) {
            handlerRegExp = new RegExp(/^on(?:Create|Complete|Exception|Failure|Interactive|Loaded|Loading|Success|Uninitialized|\d{3})$/);
            for (key in options) {
                if (handlerRegExp.test(key) && typeof options[key] === 'function') {
                    options[key] = options[key].bind(options.context);
                }
            }
        }

        return new Request(Wirecloud.io.buildProxyURL(url, options), options);
    };

    Wirecloud.io = io;

})();
<commit_msg>Add supportAccessControl option<commit_after>/*
 *     (C) Copyright 2012-2013 Universidad Politécnica de Madrid
 *
 *     This file is part of Wirecloud Platform.
 *
 *     Wirecloud Platform is free software: you can redistribute it and/or
 *     modify it under the terms of the GNU Affero General Public License as
 *     published by the Free Software Foundation, either version 3 of the
 *     License, or (at your option) any later version.
 *
 *     Wirecloud is distributed in the hope that it will be useful, but WITHOUT
 *     ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 *     FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
 *     License for more details.
 *
 *     You should have received a copy of the GNU Affero General Public License
 *     along with Wirecloud Platform.  If not, see
 *     <http://www.gnu.org/licenses/>.
 *
 */

/*global EzWebExt, Wirecloud*/

Wirecloud.location = {
    'domain': document.location.protocol + '//' + document.location.host,
    'protocol': document.location.protocol.substr(0, document.location.protocol.length - 1),
    'host': document.location.host
};

(function () {

    "use strict";

    var setRequestHeaders = function setRequestHeaders() {
        var headers, name;

        headers = EzWebExt.merge({
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
        }, this.options.requestHeaders);

        if (!('Content-Type' in headers) && this.options.contentType != null) {
            headers['Content-Type'] = this.options.contentType;
            if (this.options.encoding != null) {
                headers['Content-Type'] += '; charset=' + this.options.encoding;
            }
        }

        for (name in headers) {
            this.transport.setRequestHeader(name, headers[name]);
        }
    };

    var onReadyStateChange = function onReadyStateChange() {
        if (this.transport.readyState == 4) {

            var response = new Response(this);

            try {
                if (('on' + response.status) in this.options) {
                    this.options['on' + response.status](response);
                } else if (this.options.onSuccess && (response.status >= 200 && response.status < 300)) {
                    this.options.onSuccess(response);
                } else if (this.options.onFailure) {
                    this.options.onFailure(response);
                }
            } catch (e) {
            }

            if (this.options.onComplete) {
                try {
                    this.options.onComplete();
                } catch (e) {}
            }
        }
    };

    var Response = function Response(request) {
        Object.defineProperties(this, {
            'request': {value: request},
            'transport': {value: request.transport},
            'status': {value: request.transport.status},
            'statusText': {value: request.transport.statusText},
            'response': {value: request.transport.response},
            'responseText': {value: request.transport.responseText}
        });
    };

    Response.prototype.getHeader = function getHeader(name) {
        try {
            return this.transport.getResponseHeader(name);
        } catch (e) { return null; }
    };

    Response.prototype.getAllResponseHeaders = function getAllResponseHeaders() {
        return this.transport.getAllResponseHeaders();
    };

    var toQueryString = function toQueryString(parameters) {
        var key, query = '';

        if (typeof parameters === 'string') {
            return parameters;
        }

        for (key in parameters) {
            query += '&' + encodeURIComponent(key) + '=' + encodeURIComponent(parameters[key]);
        }

        return query.substr(1);
    };

    var Request = function Request(url, options) {
        this.url = url;
        this.options = EzWebExt.merge({
            method:       'POST',
            asynchronous: true,
            responseType: null,
            contentType:  null,
            encoding:     null,
            postBody:     null
        }, options);

        if (this.options.onSuccess != null && typeof this.options.onSuccess !== 'function') {
            throw new TypeError('Invalid onSuccess callback');
        }
        if (this.options.onFailure != null && typeof this.options.onFailure !== 'function') {
            throw new TypeError('Invalid onFailure callback');
        }
        this.method = this.options.method.toUpperCase();

        if (this.options.parameters != null && (typeof this.options.parameters === 'string' || typeof this.options.parameters === 'object')) {
            if (['PUT', 'POST'].indexOf(this.method) !== -1 && this.options.postBody == null) {
                this.postBody = toQueryString(this.options.parameters);
                if (this.options.contentType == null) {
                    this.options.contentType = 'application/x-www-form-urlencoded';
                }
                if (this.options.encoding == null) {
                    this.options.encoding = 'UTF-8';
                }
            } else if (this.method === 'GET') {
                if (this.url.indexOf('?') !== -1) {
                    this.url += '&' + toQueryString(this.options.parameters);
                }  else {
                    this.url += '?' + toQueryString(this.options.parameters);
                }
            }
        }

        this.transport = new XMLHttpRequest();
        this.transport.open(this.options.method, this.url, this.options.asynchronous);
        if (this.options.responseType) {
            this.transport.responseType = this.options.responseType;
        }
        this.transport.addEventListener('readystatechange', onReadyStateChange.bind(this), true);
        setRequestHeaders.call(this);
        this.transport.send(this.options.postBody);
    };

    var io = {};

    io.buildProxyURL = function buildProxyURL(url, options) {
        var final_url, protocolEnd, link, forceProxy, hostStart, pathStart, protocol,
            host, rest;

        forceProxy = options != null && !!options.forceProxy;

        if (url.length > 4 && url.indexOf('www.') === 0) {
            url = 'http://' + url;
        }

        protocol = Wirecloud.location.protocol;
        host = Wirecloud.location.host;

        protocolEnd = url.indexOf('://');
        if (protocolEnd !== -1) {
            hostStart = protocolEnd + 3;
            pathStart = url.indexOf('/', hostStart);
            if (pathStart === -1) {
                pathStart = url.length;
            }

            protocol = url.substr(0, protocolEnd);
            host = url.substr(hostStart, pathStart - hostStart);
            rest = url.substring(pathStart);
            final_url = url;
        } else {
            if (url.charAt(0) === '/') {
                rest = url;
            } else {
                rest = '/' + url;
            }

            if (!forceProxy) {
                final_url = Wirecloud.location.domain + rest;
            }
        }

        if (forceProxy || (options.supportsAccessControl !== true && (protocol !== Wirecloud.location.protocol || host !== Wirecloud.location.host))) {
            final_url = Wirecloud.location.domain +
                Wirecloud.URLs.PROXY.evaluate({protocol: protocol, domain: host, path: rest});
        }

        return final_url;
    };

    io.makeRequest = function makeRequest(url, options) {
        var handlerRegExp, key;

        if (options != null && options.context != null) {
            handlerRegExp = new RegExp(/^on(?:Create|Complete|Exception|Failure|Interactive|Loaded|Loading|Success|Uninitialized|\d{3})$/);
            for (key in options) {
                if (handlerRegExp.test(key) && typeof options[key] === 'function') {
                    options[key] = options[key].bind(options.context);
                }
            }
        }

        return new Request(Wirecloud.io.buildProxyURL(url, options), options);
    };

    Wirecloud.io = io;

})();
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import { BackAndroid, View, TouchableOpacity, NavigationExperimental, StyleSheet } from 'react-native';
import { connect } from 'react-redux';

import { navigatePush, navigatePop } from '../redux/modules/routing';
import Articles from './Articles';
import Article from './Article';
import Settings from '../components/Settings';
import { IconSetting } from '../assets/svg';

const {
  CardStack: NavigationCardStack,
  Header: NavigationHeader,
} = NavigationExperimental;

class AppContainer extends React.Component {
  constructor(props) {
    super(props);
    this._renderHeader = this._renderHeader.bind(this);
    this._renderScene = this._renderScene.bind(this);
  }

  componentWillMount() {
    BackAndroid.addEventListener('hardwareBackPress', this.handleBackButton.bind(this));
  }

  handleBackButton() {
    if (this.props.navigationState.index) {
      this.props.handleNavigateBack();
      return true;
    }
    return false;
  }

  _renderScene({ scene }) {
    const { route } = scene;
    const componentsMapping = {
      Articles,
      Article,
      Settings
    };

    const toRender = componentsMapping[route.key] || null;
    // make all the Views' marginTop equals header height
    return (
      <View style={{ flex: 1, marginTop: NavigationExperimental.Header.HEIGHT }}>
      {React.createElement(toRender, { route })}
      </View>
    );
  }

  _renderHeader(sceneProps) {
    const { handleNavigateBack, pushRoute } = this.props;

    return (
      <NavigationHeader
        {...sceneProps}

        onNavigateBack={handleNavigateBack}
        renderRightComponent={props => {
          return (
            <TouchableOpacity
              style={[styles.center, { padding: 10 }]}
              onPress={() => { pushRoute({ key: 'Settings' }); }}
            >
              <IconSetting />
            </TouchableOpacity>
            );
        }}

        renderTitleComponent={props => {
          const route = props.scene.route;
          const title =  route.key === 'Articles' ? 'DEMO' : 'NEWS';
          return <NavigationHeader.Title>{title}</NavigationHeader.Title>;
        }}
      />
    );
  }

  render() {
    const { navigationState, handleNavigateBack } = this.props;

    return (
      // Redux is handling the reduction of our state for us. We grab the navigationState
      // we have in our Redux store and pass it directly to the <NavigationTransitioner />.
      <NavigationCardStack
        navigationState={navigationState}
        style={styles.outerContainer}
        onNavigateBack={handleNavigateBack}
        renderScene={this._renderScene}
        renderOverlay={this._renderHeader}
      />
    );
  }

}

AppContainer.propTypes = {
  navigationState: PropTypes.object,
  pushRoute: PropTypes.func.isRequired,
  handleNavigateBack: PropTypes.func.isRequired
};

const styles = StyleSheet.create({
  outerContainer: {
    flex: 1
  },
  container: {
    flex: 1
  },
  center: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  }
});

export default connect(
  state => ({
    navigationState: state.routing
  }),
  dispatch => ({
    handleNavigateBack: (action) => {
      dispatch(navigatePop());
    },
    pushRoute: (action) => {
      dispatch(navigatePush(action));
    }
  })
)(AppContainer);
<commit_msg>remove react-native-svg, try to upgrade react-native to v0.30.0 first<commit_after>import React, { PropTypes } from 'react';
import { BackAndroid, View, TouchableOpacity, NavigationExperimental, StyleSheet } from 'react-native';
import { connect } from 'react-redux';

import { navigatePush, navigatePop } from '../redux/modules/routing';
import Articles from './Articles';
import Article from './Article';
import Settings from '../components/Settings';

const {
  CardStack: NavigationCardStack,
  Header: NavigationHeader,
} = NavigationExperimental;

class AppContainer extends React.Component {
  constructor(props) {
    super(props);
    this._renderHeader = this._renderHeader.bind(this);
    this._renderScene = this._renderScene.bind(this);
  }

  componentWillMount() {
    BackAndroid.addEventListener('hardwareBackPress', this.handleBackButton.bind(this));
  }

  handleBackButton() {
    if (this.props.navigationState.index) {
      this.props.handleNavigateBack();
      return true;
    }
    return false;
  }

  _renderScene({ scene }) {
    const { route } = scene;
    const componentsMapping = {
      Articles,
      Article,
      Settings
    };

    const toRender = componentsMapping[route.key] || null;
    // make all the Views' marginTop equals header height
    return (
      <View style={{ flex: 1, marginTop: NavigationExperimental.Header.HEIGHT }}>
      {React.createElement(toRender, { route })}
      </View>
    );
  }

  _renderHeader(sceneProps) {
    const { handleNavigateBack, pushRoute } = this.props;

    return (
      <NavigationHeader
        {...sceneProps}

        onNavigateBack={handleNavigateBack}

        renderTitleComponent={props => {
          const route = props.scene.route;
          const title =  route.key === 'Articles' ? 'DEMO' : 'NEWS';
          return <NavigationHeader.Title>{title}</NavigationHeader.Title>;
        }}
      />
    );
  }

  render() {
    const { navigationState, handleNavigateBack } = this.props;

    return (
      // Redux is handling the reduction of our state for us. We grab the navigationState
      // we have in our Redux store and pass it directly to the <NavigationTransitioner />.
      <NavigationCardStack
        navigationState={navigationState}
        style={styles.outerContainer}
        onNavigateBack={handleNavigateBack}
        renderScene={this._renderScene}
        renderOverlay={this._renderHeader}
      />
    );
  }

}

AppContainer.propTypes = {
  navigationState: PropTypes.object,
  pushRoute: PropTypes.func.isRequired,
  handleNavigateBack: PropTypes.func.isRequired
};

const styles = StyleSheet.create({
  outerContainer: {
    flex: 1
  },
  container: {
    flex: 1
  },
  center: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  }
});

export default connect(
  state => ({
    navigationState: state.routing
  }),
  dispatch => ({
    handleNavigateBack: (action) => {
      dispatch(navigatePop());
    },
    pushRoute: (action) => {
      dispatch(navigatePush(action));
    }
  })
)(AppContainer);
<|endoftext|>


<commit_before>'use strict';

angular.module('iMLApp.interactive-learning.interactive-learning-service', [])

  .factory('ILService', function ($resource) {
    //use $resource later for retrieval from webservice

    let dataResource = $resource('assets/testdata/marital-status-k2.json');
    let data = dataResource.query();

    return {
      getTestdata: function (callback) {
        let TestdataResource = $resource('assets/testdata/testdatarecords.json');
        TestdataResource.get(callback);
      },
      getMaritalStatusK2: function () {
        return data.$promise;
      },
      getAnonymizationRecords: function () {

        console.log("AnonymizationJS:");
        console.dir($A);

        console.log("GraphiniusJS:");
        console.dir($G);

        let basename = "assets/00_sample_data_UI_prototype";

        let TARGETS = [
          "target_education-num",
          "target_marital-status",
          "target_income"
        ];

        let filename = "original_data_500_rows.csv";
        let anonym_file = "adults_anonymized_k3_equal.csv";

        let csvIn = new $A.IO.CSVIN($A.config.adults);
        console.log("CSV Reader: ");
        console.log(csvIn);

        let url = basename + "/" + TARGETS[0] + "/" + filename;

        // Instantiate a SaNGreeA object
        // NOTE: The config should be instantiated by the User Interface,
        // the internal $A.config... was only for testing!
        let config = $A.config.adults;

        // of course we can overwrite the settings locally
        config.NR_DRAWS = 500; // max for this file...
        config.K_FACTOR = 7;

        let san = new $A.algorithms.Sangreea("testus", config);
        console.log("SaNGreeA Algorithm:");
        console.log(san);

        // Inspect the internal graph => should be empty
        console.log("Graph Stats BEFORE Instantiation:");
        console.log(san._graph.getStats());

        // Specify Generalization hierarchy files
        let gen_base = 'assets/genHierarchies/',
          workclass_file = gen_base + 'workclassGH.json',
          sex_file = gen_base + 'sexGH.json',
          race_file = gen_base + 'raceGH.json',
          marital_file = gen_base + 'marital-statusGH.json',
          nat_country_file = gen_base + 'native-countryGH.json',
          relationship_file = gen_base + 'relationshipGH.json',
          occupation_file = gen_base + 'occupationGH.json',
          income_file = gen_base + 'incomeGH.json';

        // Uff, this feels like 2012 at the latest....
        $.ajaxSetup({
          async: false
        });

        // Load Generalization hierarchies

        // Remotely read the original data and anonymize
        csvIn.readCSVFromURL(url, function(csv) {
          console.log("File URL ANON: " + url);
          console.log("File length ANON in total rows:");
          console.log(csv.length);
          console.log("Headers:")
          console.log(csv[0]);
          console.log(csv[1]);

          san.instantiateGraph(csv, false );
          // Inspect the internal graph again => should be populated now
          console.log("Graph Stats AFTER Instantiation:");
          console.log(san._graph.getStats());

          // let's run the whole anonymization inside the browser
          san.anonymizeGraph();

          // let's take a look at the clusters
          console.dir(san._clusters);

          sampleCostCalculation(san);
        });

        function sampleCostCalculation(san) {
          // Compute costs between some Cluster and some node
          let cluster = selectRandomCluster(san._clusters);
          let node = san._graph.getRandomNode();

          function selectRandomCluster(clusters) {
            return clusters[Math.floor(Math.random()*clusters.length)];
          }

          console.log("\n Computing cost of generalization between cluster and node:");
          console.log(cluster);
          console.log(node);
          console.log("Cost: " + san.calculateGIL(cluster, node));
        }

      }
    }
  });
<commit_msg>DEV: incl generalization hierarchies<commit_after>'use strict';

angular.module('iMLApp.interactive-learning.interactive-learning-service', [])

  .factory('ILService', function ($resource) {
    //use $resource later for retrieval from webservice

    let dataResource = $resource('assets/testdata/marital-status-k2.json');
    let data = dataResource.query();

    return {
      getTestdata: function (callback) {
        let TestdataResource = $resource('assets/testdata/testdatarecords.json');
        TestdataResource.get(callback);
      },
      getMaritalStatusK2: function () {
        return data.$promise;
      },
      getAnonymizationRecords: function () {

        console.log("AnonymizationJS:");
        console.dir($A);

        console.log("GraphiniusJS:");
        console.dir($G);

        let basename = "assets/00_sample_data_UI_prototype";

        let TARGETS = [
          "target_education-num",
          "target_marital-status",
          "target_income"
        ];

        let filename = "original_data_500_rows.csv";
        let anonym_file = "adults_anonymized_k3_equal.csv";

        let csvIn = new $A.IO.CSVIN($A.config.adults);
        console.log("CSV Reader: ");
        console.log(csvIn);

        let url = basename + "/" + TARGETS[0] + "/" + filename;

        // Instantiate a SaNGreeA object
        // NOTE: The config should be instantiated by the User Interface,
        // the internal $A.config... was only for testing!
        let config = $A.config.adults;

        // of course we can overwrite the settings locally
        config.NR_DRAWS = 500; // max for this file...
        config.K_FACTOR = 7;

        let san = new $A.algorithms.Sangreea("testus", config);
        console.log("SaNGreeA Algorithm:");
        console.log(san);

        // Inspect the internal graph => should be empty
        console.log("Graph Stats BEFORE Instantiation:");
        console.log(san._graph.getStats());

        // Specify Generalization hierarchy files
        let gen_base = 'assets/genHierarchies/',
          workclass_file = gen_base + 'workclassGH.json',
          sex_file = gen_base + 'sexGH.json',
          race_file = gen_base + 'raceGH.json',
          marital_file = gen_base + 'marital-statusGH.json',
          nat_country_file = gen_base + 'native-countryGH.json',
          relationship_file = gen_base + 'relationshipGH.json',
          occupation_file = gen_base + 'occupationGH.json',
          income_file = gen_base + 'incomeGH.json';

        // Uff, this feels like 2012 at the latest....
        $.ajaxSetup({
          async: false
        });

        // Load Generalization hierarchies
        [workclass_file, nat_country_file, sex_file, race_file, marital_file,
          relationship_file, occupation_file, income_file].forEach( function(file) {
          var json = $.getJSON(file).responseText;
          console.log(json);
          let strgh = new $A.genHierarchy.Category(json);
          san.setCatHierarchy(strgh._name, strgh);
        });

        // Remotely read the original data and anonymize
        csvIn.readCSVFromURL(url, function(csv) {
          console.log("File URL ANON: " + url);
          console.log("File length ANON in total rows:");
          console.log(csv.length);
          console.log("Headers:")
          console.log(csv[0]);
          console.log(csv[1]);

          san.instantiateGraph(csv, false );
          // Inspect the internal graph again => should be populated now
          console.log("Graph Stats AFTER Instantiation:");
          console.log(san._graph.getStats());

          // let's run the whole anonymization inside the browser
          san.anonymizeGraph();

          // let's take a look at the clusters
          console.log("Clusteres:");
          console.dir(san._clusters);

          sampleCostCalculation(san);
        });

        function sampleCostCalculation(san) {
          // Compute costs between some Cluster and some node
          let cluster = selectRandomCluster(san._clusters);
          let node = san._graph.getRandomNode();

          function selectRandomCluster(clusters) {
            return clusters[Math.floor(Math.random()*clusters.length)];
          }

          console.log("\n Computing cost of generalization between cluster and node:");
          console.log(cluster);
          console.log(node);
          console.log("Cost: " + san.calculateGIL(cluster, node));
        }

      }
    }
  });
<|endoftext|>


<commit_before>/**
 * Author: CReich
 * Company: Rainbow Unicorn
 * Date: 29.02.2016
 * Created: 18:47
 **/
(function(window){

    AnimationController.prototype.constructor = AnimationController;
    AnimationController.prototype = {
        val0 : '',
        val1 : ''
    };

    var ref, center, $animationWrap, $animation, $pRed, $pBlue, $applyBorder, $applyBorderBlue, $logoText, $millionText, $apply, timeline,
        $applyBlue, $applyTextWhite, $applyTextBlack;
    function AnimationController(){
        ref = this;

        Logger.useDefaults();
        //Logger.setLevel(Logger.OFF);

        center = "1000 400";

    };

    AnimationController.prototype.init = function(){

        $animationWrap = $('.svg-animation-wrap');

        ref.load();
    };

    AnimationController.prototype.load = function(){
        var preload = [];
        $('.svg-element').each(function(){
            var job = {};
            job.url = $(this).attr('data-src');
            job.type = $(this).prop('nodeName');
            job.$elem = $(this);
            preload.push(job);
        });
        ref.loadBatch(preload);
    };

    AnimationController.prototype.loadBatch = function(preload){
        var promises = [];
        for (var i = 0; i < preload.length; i++) {
            (function(job, promise) {

                Logger.log("job.type == " + job.type);

                job.$elem[0].addEventListener('load', function() {

                    Logger.log("OBJECT loaded: " + job.url);

                    promise.resolve();
                }, true);
                job.$elem.attr('data',job.url);

            })(preload[i], promises[i] = $.Deferred());
        }
        $.when.apply($, promises).done(function() {
            ref.onBatchLoaded();
        });
    };

    AnimationController.prototype.onBatchLoaded = function(){

        //set references

        var animSVG = document.getElementById("ptf-svg");
        if(animSVG) var svgDoc = animSVG.contentDocument;

        Logger.log("svgDoc -> " + svgDoc);

        $animation = $(svgDoc.getElementById("animation"));

        $pRed = $('#red',$animation);
        $pBlue = $('#blue',$animation);
        $logoText = $('#logo-text',$animation);
        $millionText = $('#million-text',$animation);
        $apply = $('#apply',$animation);
        $applyBlue = $('#apply-blue',$animation);
        $applyBorder = $('#apply-border',$animation);
        $applyBorderBlue = $('#apply-border-blue',$animation);
        $applyTextWhite = $('#text-white',$animation);
        $applyTextBlack = $('#text-black',$animation);

        timeline = new TimelineMax({delay:0, onComplete:ref.animationFinished})
            .set([$pRed, $pBlue, $logoText, $millionText, $apply, $applyBlue, $applyBorderBlue, $applyTextWhite],{opacity:0})
            .set($pBlue,{svgOrigin:center, scale:0})
            .set($pRed,{svgOrigin:center, x:'-15%', y:'-3%'})
            .set($animationWrap,{className:'-=ptf-hidden', opacity:1})
            .to($pBlue, 1, {scale: 1, opacity:1, ease:Back.easeOut},'start')
            .to($pRed, 1, {opacity:1, x:'0%', y:'0%', ease:Sine.easeInOut},'start+=0.5')
            .set($logoText,{y:'10%'})
            .to($logoText,0.75,{delay:1.5, opacity:1, y:'0%'}, 'go')
            .to($pRed,0.75,{delay:1, opacity:0}, 'go')
            .set($millionText,{x:'500%',opacity:1})
            .to([$pRed,$pBlue,$logoText],0.75,{delay:2.5, x:'-500%'}, 'slide')
            .to($millionText,0.75,{delay:2.5, x:'0%'}, 'slide')
            .to($millionText,1,{delay:2.5, x:'-300%'},'slideOut')
            .set($apply,{svgOrigin:center, scale:0},'slideOut+=2.75')
            .set($applyBlue,{scaleX:0,opacity:1},'slideOut+=2.75')
            .to($apply,1,{opacity:1, scale:1, ease:Back.easeOut},'slideOut+=2.75')
            .to($applyTextWhite,0.1,{opacity:1},'changeColorIn')
            .to($applyTextBlack,0.1,{opacity:0},'changeColorIn')
            .set($applyBorder,{opacity:0})
            .set($applyBorderBlue,{opacity:1})
            .to($applyBlue,0.25,{scaleX:1, ease:Sine.easeIn})
            .to($applyBlue,0.25,{delay:1.5, scaleX:0, ease:Sine.easeOut},'changeColorOut')
            .to($applyTextWhite,0.1,{delay:1.5, opacity:0},'changeColorOut')
            .to($applyTextBlack,0.1,{delay:1.5, opacity:1},'changeColorOut')
            .set($applyBorder,{opacity:1})
            .set($applyBorderBlue,{opacity:0})
            .to($apply,0.5,{delay:1, opacity:1, scale:0, ease:Back.easeIn})

    };

    AnimationController.prototype.animationFinished = function(){
        Logger.log("animationFinished");
        timeline.play(0);
    };

    window.AnimationController = AnimationController;

}(window));
<commit_msg>fixed ptf teaser cache/reload bug<commit_after>/**
 * Author: CReich
 * Company: Rainbow Unicorn
 * Date: 29.02.2016
 * Created: 18:47
 **/
(function(window){

    AnimationController.prototype.constructor = AnimationController;
    AnimationController.prototype = {
        val0 : '',
        val1 : ''
    };

    var ref, center, $animationWrap, $animation, $pRed, $pBlue, $applyBorder, $applyBorderBlue, $logoText, $millionText, $apply, timeline,
        $applyBlue, $applyTextWhite, $applyTextBlack, initialized;
    function AnimationController(){
        ref = this;

        Logger.useDefaults();
        Logger.setLevel(Logger.OFF);

        center = "1000 400";

    };

    AnimationController.prototype.init = function(){

        $animationWrap = $('.svg-animation-wrap');

        ref.load();
    };

    AnimationController.prototype.load = function(){

        var preload = [];
        $('.svg-element').each(function(){
            var job = {};
            job.url = $(this).attr('data-src');
            job.type = $(this).prop('nodeName');
            job.$elem = $(this);
            preload.push(job);
        });
        ref.loadBatch(preload);

    };

    AnimationController.prototype.loadBatch = function(preload){
        var promises = [];
        for (var i = 0; i < preload.length; i++) {
            (function(job, promise) {

                Logger.log("job.type == " + job.type);

                job.$elem[0].addEventListener('load', function() {

                    promise.resolve();
                    ref.onBatchLoaded();
                }, true);
                job.$elem.each(function() {
                    if(this.complete) $(this).load();
                });
                job.$elem.attr('data',job.url);

            })(preload[i], promises[i] = $.Deferred());
        }

    };

    AnimationController.prototype.onBatchLoaded = function(){

        Logger.log("onBatchLoaded");

        //set references
        initialized = true;

        var animSVG = document.getElementById("ptf-svg");
        if(animSVG) var svgDoc = animSVG.contentDocument;

        $animation = $(svgDoc.getElementById("animation"));

        $pRed = $('#red',$animation);
        $pBlue = $('#blue',$animation);
        $logoText = $('#logo-text',$animation);
        $millionText = $('#million-text',$animation);
        $apply = $('#apply',$animation);
        $applyBlue = $('#apply-blue',$animation);
        $applyBorder = $('#apply-border',$animation);
        $applyBorderBlue = $('#apply-border-blue',$animation);
        $applyTextWhite = $('#text-white',$animation);
        $applyTextBlack = $('#text-black',$animation);

        timeline = new TimelineMax({delay:0, paused:true, onComplete:ref.animationFinished})
            .set([$pRed, $pBlue, $logoText, $millionText, $apply, $applyBlue, $applyBorderBlue, $applyTextWhite],{opacity:0})
            .set($pBlue,{svgOrigin:center, scale:0})
            .set($pRed,{svgOrigin:center, x:'-15%', y:'-3%'})
            .set($animationWrap,{className:'-=ptf-hidden', opacity:1})
            .to($pBlue, 1, {scale: 1, opacity:1, ease:Back.easeOut},'start')
            .to($pRed, 1, {opacity:1, x:'0%', y:'0%', ease:Sine.easeInOut},'start+=0.5')
            .set($logoText,{y:'10%'})
            .to($logoText,0.75,{delay:1.5, opacity:1, y:'0%'}, 'go')
            .to($pRed,0.75,{delay:1, opacity:0}, 'go')
            .set($millionText,{x:'500%',opacity:1})
            .to([$pRed,$pBlue,$logoText],0.75,{delay:2.5, x:'-500%'}, 'slide')
            .to($millionText,0.75,{delay:2.5, x:'0%'}, 'slide')
            .to($millionText,1,{delay:2.5, x:'-300%'},'slideOut')
            .set($apply,{svgOrigin:center, scale:0},'slideOut+=2.75')
            .set($applyBlue,{scaleX:0,opacity:1},'slideOut+=2.75')
            .to($apply,1,{opacity:1, scale:1, ease:Back.easeOut},'slideOut+=2.75')
            .to($applyTextWhite,0.1,{opacity:1},'changeColorIn')
            .to($applyTextBlack,0.1,{opacity:0},'changeColorIn')
            .set($applyBorder,{opacity:0})
            .set($applyBorderBlue,{opacity:1})
            .to($applyBlue,0.25,{scaleX:1, ease:Sine.easeIn})
            .to($applyBlue,0.25,{delay:1.5, scaleX:0, ease:Sine.easeOut},'changeColorOut')
            .to($applyTextWhite,0.1,{delay:1.5, opacity:0},'changeColorOut')
            .to($applyTextBlack,0.1,{delay:1.5, opacity:1},'changeColorOut')
            .set($applyBorder,{opacity:1})
            .set($applyBorderBlue,{opacity:0})
            .to($apply,0.5,{delay:1, opacity:1, scale:0, ease:Back.easeIn})
        timeline.play(0);

    };

    AnimationController.prototype.animationFinished = function(){
        Logger.log("animationFinished");
        timeline.play(0);
    };

    window.AnimationController = AnimationController;

}(window));
<|endoftext|>