<commit_before>function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.projectId = $("#projectHeader").data('value');

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);
    gvm.projectDescription = ko.observable("Description");

    gvm.firstNameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("firstNameTableTitle");}, gvm);
    gvm.lastNameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("lastNameTableTitle");}, gvm);
    gvm.actionTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ActionTableTitle");}, gvm);

    gvm.scoreTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("scoreTableTitle")});
    gvm.filesTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("filesTableTitle")});

    gvm.searchStudent = ko.observable("");

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + gvm.projectId, function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
            gvm.projectDescription(data[0].description);
        });
    };

    gvm.getStudentListBis = function() {
        $.getJSON('/api/project/' + gvm.projectId + '/students', function(data) {
            data.forEach(function(element){
                viewModel.addTableData(element.id, element.firstname, element.lastname, element.mail, element.assessCount);
            });
        });
    };

    gvm.getStudentList = function() {
        $.getJSON('/api/project/' + gvm.projectId + '/students/', function(data) {
            $.each(data, function(i, item) {

                $.getJSON('/api/project/' + gvm.projectid  + '/student/' + item.id + '/assessed', function(data)
                {
                    viewModel.users.removeAll();
                    data.forEach(function(element)
                    {
                        viewModel.users.push(element.firstname + " " + element.lastname);
                    });

                    viewModel.addTableData(item.id, item.firstname, item.lastname, item.mail, viewModel.users().length);
                });
            });
        });
    };

    gvm.users = ko.observableArray([]);

    gvm.assassedUsers = ko.observableArray([]);

    gvm.tabledata = ko.observableArray([]);

    gvm.tempTableData = ko.observableArray([]);

    // Add data to the table
    gvm.addTableData = function(id, firstname, lastname, email, countAssessed) {
        // Push data
        var data = countAssessed;
        var tblOject = {tid: id, tfirstname: firstname, tlastname: lastname, tScoreTableBtn: gvm.scoreTableTitle, tFilesTableBtn: gvm.filesTableTitle, tpid: gvm.projectId, email: email, tcountAssessed: data};
        gvm.tabledata.push(tblOject);
    };

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    };

    /*gvm.getAllData = function() {
        $.getJSON('/api/project/getAllData/' + $("#projectHeader").data('value'), function(data) {
            console.log(data);
        });
    }*/
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getStudentListBis();
    //viewModel.getStudentList();

    $("#searchField").bind("keypress", {}, keypressInBox);

}

function keypressInBox(e) {
    var code = (e.keyCode ? e.keyCode : e.which);
    if (code == 13) { //Enter keycode
        $("#searchField").blur();
        getStudentByName();

    }
};

function createPDF(id,name,lastname,email, projectheader, projectdescription)
{
    /*$.getJSON('/api/finalscore/' + viewModel.projectId + '/' + id, function (data) {
        makePDF(id,name,lastname,email,projectheader,projectdescription,data);
        //console.log(data);
    });*/

    $.ajax({
        url: '/api/finalscore/' + viewModel.projectId + '/' + id,
        type: "GET",
        dataType: 'json',
        success: function(data) {
            makePDF(id,name,lastname,email,projectheader,projectdescription,data);
        },
        error: function()
        {
            alert("Please make sure points are given!");
        }
    });
}

function getStudentByName(){

    if(viewModel.tempTableData().length == 0) {
        viewModel.tempTableData(viewModel.tabledata.slice(0));
    }

    viewModel.tabledata([]);

    viewModel.tempTableData().forEach(function(item, element){
        var fullname = item.tfirstname + " " + item.tlastname;
        var fullnameReverse = item.tlastname + " " + item.tfirstname;

        if (item.tfirstname.toLowerCase().contains(viewModel.searchStudent().toLowerCase()) || item.tlastname.toLowerCase().contains(viewModel.searchStudent().toLowerCase()) || fullname.toLowerCase().contains(viewModel.searchStudent().toLowerCase()) || fullnameReverse.toLowerCase().contains(viewModel.searchStudent().toLowerCase())){
            viewModel.tabledata.push(item);
        }
    });
}

function showFullList()
{
    viewModel.searchStudent = ko.observable("");
    getStudentByName();
}

function getData(id)
{
    $.getJSON('/api/project/' + viewModel.projectId  + '/student/' + id + '/assessed', function(data)
    {
        viewModel.users.removeAll();
        data.forEach(function(element)
        {
            viewModel.users.push(element.firstname + " " + element.lastname);
        });
    });

    return viewModel.users();
}

function getNrOfAssessing(){
    $.getJSON('/api/project/nrOfAssessing/' + viewModel.projectId , function(data)
    {
        console.log(data);

        data.foreach(function(item)
        {
           console.log(item[0]);

        });
    });
}

function getDataCount(projectid, id)
{
    $.getJSON('/api/project/' + projectid  + '/student/' + id + '/assessed', function(data)
    {
        viewModel.users.removeAll();
        data.forEach(function(element)
        {
            viewModel.users.push(element.firstname + " " + element.lastname);
        });

        return viewModel.users().length;
    });
}<commit_msg>nr of assessing color balls<commit_after>function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.projectId = $("#projectHeader").data('value');

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);
    gvm.projectDescription = ko.observable("Description");

    gvm.firstNameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("firstNameTableTitle");}, gvm);
    gvm.lastNameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("lastNameTableTitle");}, gvm);
    gvm.actionTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ActionTableTitle");}, gvm);

    gvm.scoreTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("scoreTableTitle")});
    gvm.filesTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("filesTableTitle")});

    gvm.searchStudent = ko.observable("");

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + gvm.projectId, function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
            gvm.projectDescription(data[0].description);
        });
    };

    gvm.getStudentListBis = function() {
        $.getJSON('/api/project/' + gvm.projectId + '/students', function(data) {
            data.forEach(function(element){
                viewModel.addTableData(element.id, element.firstname, element.lastname, element.mail, element.assessCount);
            });
        });
    };

    gvm.getStudentList = function() {
        $.getJSON('/api/project/' + gvm.projectId + '/students/', function(data) {
            $.each(data, function(i, item) {

                $.getJSON('/api/project/' + gvm.projectid  + '/student/' + item.id + '/assessed', function(data)
                {
                    viewModel.users.removeAll();
                    data.forEach(function(element)
                    {
                        viewModel.users.push(element.firstname + " " + element.lastname);
                    });

                    viewModel.addTableData(item.id, item.firstname, item.lastname, item.mail, viewModel.users().length);
                });
            });
        });
    };

    gvm.users = ko.observableArray([]);

    gvm.assassedUsers = ko.observableArray([]);

    gvm.tabledata = ko.observableArray([]);

    gvm.tempTableData = ko.observableArray([]);

    // Add data to the table
    gvm.addTableData = function(id, firstname, lastname, email, countAssessed) {
        // Push data
        var data = countAssessed;
        var tblOject = {tid: id, tfirstname: firstname, tlastname: lastname, tScoreTableBtn: gvm.scoreTableTitle, tFilesTableBtn: gvm.filesTableTitle, tpid: gvm.projectId, email: email, tcountAssessed: data};
        gvm.tabledata.push(tblOject);
    };

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    };

    /*gvm.getAllData = function() {
        $.getJSON('/api/project/getAllData/' + $("#projectHeader").data('value'), function(data) {
            console.log(data);
        });
    }*/
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getStudentListBis();
    //viewModel.getStudentList();

    $("#searchField").bind("keypress", {}, keypressInBox);

}

function keypressInBox(e) {
    var code = (e.keyCode ? e.keyCode : e.which);
    if (code == 13) { //Enter keycode
        $("#searchField").blur();
        getStudentByName();

    }
};

function createPDF(id,name,lastname,email, projectheader, projectdescription)
{
    /*$.getJSON('/api/finalscore/' + viewModel.projectId + '/' + id, function (data) {
        makePDF(id,name,lastname,email,projectheader,projectdescription,data);
        //console.log(data);
    });*/

    $.ajax({
        url: '/api/finalscore/' + viewModel.projectId + '/' + id,
        type: "GET",
        dataType: 'json',
        success: function(data) {
            makePDF(id,name,lastname,email,projectheader,projectdescription,data);
        },
        error: function()
        {
            alert("Please make sure points are given!");
        }
    });
}

function getStudentByName(){

    if(viewModel.tempTableData().length == 0) {
        viewModel.tempTableData(viewModel.tabledata.slice(0));
    }

    viewModel.tabledata([]);

    viewModel.tempTableData().forEach(function(item, element){
        var fullname = item.tfirstname + " " + item.tlastname;
        var fullnameReverse = item.tlastname + " " + item.tfirstname;

        if (item.tfirstname.toLowerCase().contains(viewModel.searchStudent().toLowerCase()) || item.tlastname.toLowerCase().contains(viewModel.searchStudent().toLowerCase()) || fullname.toLowerCase().contains(viewModel.searchStudent().toLowerCase()) || fullnameReverse.toLowerCase().contains(viewModel.searchStudent().toLowerCase())){
            viewModel.tabledata.push(item);
        }
    });
}

function showFullList()
{
    viewModel.searchStudent = ko.observable("");
    getStudentByName();
}

function getData(id)
{
    $.getJSON('/api/project/' + viewModel.projectId  + '/student/' + id + '/assessed', function(data)
    {
        viewModel.users.removeAll();
        data.forEach(function(element)
        {
            viewModel.users.push(element.firstname + " " + element.lastname);
        });
    });

    return viewModel.users();
}

function getNrOfAssessing(){
    $.getJSON('/api/project/nrOfAssessing/' + viewModel.projectId , function(data)
    {
        console.log(data);

        data.forEach(function(item)
        {
           console.log(item.nrOfAssessing);

        });
    });
}

function getDataCount(projectid, id)
{
    $.getJSON('/api/project/' + projectid  + '/student/' + id + '/assessed', function(data)
    {
        viewModel.users.removeAll();
        data.forEach(function(element)
        {
            viewModel.users.push(element.firstname + " " + element.lastname);
        });

        return viewModel.users().length;
    });
}<|endoftext|>


<commit_before>var axios = require('axios');
import { CheckReponse } from './responses';
import { AGO_URL, AGO_RiverBasins, AGO_CatalogingUnits, AGO_HUCS, Data_FeatureID } from './actionConstants';

//set base URL for axios
axios.defaults.baseURL = AGO_URL;

const CHART_DATA_OUT_FIELDS = 'geography_level%2Cgeography_label';
const CHART_DATA_ORDER_BY_FIELDS = 'geography_level';

//AGO query to get list of geography levels available
function AGO_GeographyLevels(){

  const query_URL = '/RDRBP/FeatureServer/' + Data_FeatureID + '/query' +
                    '?where=id<>%27%27&objectIds=' +
                    '&time=&resultType=none' +
                    '&outFields=' + CHART_DATA_OUT_FIELDS +
                    '&returnIdsOnly=false' +
                    '&returnCountOnly=false' +
                    '&returnDistinctValues=true' +
                    '&orderByFields=' + CHART_DATA_ORDER_BY_FIELDS +
                    '&groupByFieldsForStatistics=' +
                    '&outStatistics=' +
                    '&resultOffset=' +
                    '&resultRecordCount='
                    +'&f=pgeojson' +
                    '&token='

  return axios.get(query_URL);

};

//get the current level of geog for a geography level to use in ago api
//  example this gets all the hucs for a Cataloging unit
function getCurrentLevel(geogLevel){
  switch (geogLevel) {
    case 'River Basins':
      return 1;
      break;
    case 'Cataloging Units':
      return 2;
      break;
    case 'HUC12':
      return 3;
      break;
    default:
      return 99;
    }
}

//get the next level of geog for a geography level to use in ago api
//  example this gets all the hucs for a Cataloging unit
function getNextLevel(geogLevel){
  switch (geogLevel) {
    case 'River Basins':
      return 2;
      break;
    case 'Cataloging Units':
      return 3;
      break;
    case 'HUC12':
      return 99;
      break;
    default:
      return 99;
    }
}

//only needs this untill I change the data feed have named generically?
// or maybe control via yaml file....
function get_AGOGeographyLabel(geogLevel){
  switch (geogLevel) {
    case 'River Basins':
      return 'huc_6';
      break;
    case 'Cataloging Units':
      return 'huc_8';
      break;
    case 'HUC12':
      return 'huc_12';
      break;
    default:
      return 'huc_12';
    }
}
//updates the a geography level filter
//  determined by changed menuitem value
//  or when the user clicks on huc in map (not done yet)
function update_activeGeographyFilter( state, active_level, filter_value ){

  //convert the active layer name to the AGO generic name
  // need to do check of active layer
  const nextLevel = getNextLevel(active_level)
  const currentLevel = getCurrentLevel(active_level)
  const geography_levels = state.geography_levels.geography_levels
  const menuLists = state.menuLists.lists;

  //console.log(menuLists)

  //instatiate variables
  let GList = [];
  let filtered_menu_list  = []

  //loop the geography levels
  geography_levels.map(function(level) {

     //get the label, level,for the geography_level
     let geography_label = level['geography_label'];
     let geography_level = level['geography_level'];
     let active = level['active'];
     let filter = level['filter'];
     let current_id = level['current_id'];

     //set current id for current geography_level from the menu pulldown
     if (currentLevel === geography_level ){
       current_id = filter_value;
     }

     //if the geography_level is lower than the current level reset the current_id
     if (currentLevel < geography_level ){
       current_id = '';
     }

     //set the filter value for lower level geographies
     if (geography_level >= nextLevel){
       filter = filter_value;

     }

     console.log('test')

     let filteredList = [];
     //get a filtered menu list
     const l = menuLists.map(menuList => {

       const menuName = get_AGOGeographyLabel(menuList.name);
      //  console.log('menu name: ' + menuName)
      //  console.log('geography label: ' + geography_label)
      let filteredMenuList = [];

       if( menuName ===  geography_label){
         menuList.lists.map(list => {

           const checkedValue = list.id.substring(0, filter_value.length)
           if (checkedValue === filter_value){
             filteredMenuList.push(list)
           }

         })
         return filteredMenuList
         console.log('afer return')
       }
       return filteredMenuList
                console.log('afer if')
      //  if( menuName ===  geography_label){
      //
      //    menuList.lists.map(list => {
      //      const checkedValue = list.id.substring(0, filter_value.length)
      //
      //      if (checkedValue === filter_value){
      //         filteredList.push(list)
      //      }
      //
      //    })
      //    //console.log(filteredList)
      //    return filteredList
      //  }
      // //  if (filteredList.length > 0){
      //    console.log('here')
      //    console.log(filteredList)
      //    console.log(filteredList.length)
      //    console.log('here')
      //    //return filteredList
      // //  }
     })

    //  console.log('test')
    //  console.log(filtered_menu_list)
    //  console.log('test')
    console.log(l)
    console.log('test')

     //create new geography_level object
     let thisGeographyList = {geography_level, geography_label, active, filter, current_id, filtered_menu_list};

     //add the geography_level object to new state array
     GList.push(thisGeographyList)
   })

  return GList;

}

//updates the which geograpy level is active_level
//  determined by which menu item the user clicks or
//  or when the user clicks on huc in map (not done yet)
function update_activeGeographyLevel( state, active_level ){

  //convert the active layer name to the AGO generic name
  // need to do check of active layer
  const label = get_AGOGeographyLabel(active_level);
  const geography_levels = state.geography_levels.geography_levels;

  //instatiate variables
  let GList = [];
  let active = false;
  // let filter = '';

  //loop the geography levels
  geography_levels.map(function(level) {

     //get the label, level,for the geography_level
     let geography_label = level['geography_label'];
     let geography_level = level['geography_level'];
     let filter = level['filter'];
     let current_id = level['current_id'];
     let filtered_menu_list  = []

     //check of the labels matches the new active layer label
     //  is so set active to true.
     //  otherwise false
     if (level['geography_label'] === label){
       active = true;
     } else {
       active = false;
     }

     //create new geography_level object
     let thisGeographyList = {geography_level, geography_label, active, filter, current_id, filtered_menu_list};

     //add the geography_level object to new state array
     GList.push(thisGeographyList)
   })

  return GList;

}

// change filter for geography level
export function change_geographyLevelFilter(filter_value, active_level) {
  return (dispatch, getState) => {

    const state = getState()

    //create new geography_level state object
    const newLevels = update_activeGeographyFilter( state, active_level, filter_value );

    //send the new geography level data on
    dispatch(geography_levels('CHANGE_FILTER_GEOGRAPHY_LEVEL',newLevels))

  }
}

// change active geography level
export function change_geographyLevelActive(active_level) {
  return (dispatch, getState) => {

    const state = getState()

    //create new geography_level state object
    const newLevels = update_activeGeographyLevel( state, active_level );

    //send the new geography level data on
    dispatch(geography_levels('CHANGE_ACTIVE_GEOGRAPHY_LEVEL',newLevels))

  }
}

export function get_GeographyLevels(){
  return dispatch => {
      AGO_GeographyLevels()
        .then(function test(response){

          //check repsonses for errors
          let theGeographyLevels = CheckReponse(response,'AGO_API_ERROR');

          //instatiate variables and default values
          let GList = [];
          let active = false;
          let filter = '';
          let current_id = '';
          let filtered_menu_list  = [];

          //loop the geography_levels and build the geography_level state obect
          theGeographyLevels.features.map(function(features) {

             //get values for label and level   //instatiate variables
             let geography_label = features.properties.geography_label;
             let geography_level = features.properties.geography_level;

             //create new geography_level state object
             let thisGeographyList = {geography_level, geography_label, active , filter, current_id, filtered_menu_list};

             //add the geography_level object to new state array
             GList.push(thisGeographyList)
           })

          //send the geography level data on
          dispatch(geography_levels('GET_GEOGRAPHY_LEVELS',GList))
        })
        .catch(error => { console.log('request failed', error); });
  }
}

//new geography_levels object to pass to reducer
function geography_levels(type,data) {
  return {
    type: type,
    geography_levels: data,
    receivedAt: Date.now()
  }
}
<commit_msg>filtered menus<commit_after>var axios = require('axios');
import { CheckReponse } from './responses';
import { AGO_URL, AGO_RiverBasins, AGO_CatalogingUnits, AGO_HUCS, Data_FeatureID } from './actionConstants';

//set base URL for axios
axios.defaults.baseURL = AGO_URL;

const CHART_DATA_OUT_FIELDS = 'geography_level%2Cgeography_label';
const CHART_DATA_ORDER_BY_FIELDS = 'geography_level';

//AGO query to get list of geography levels available
function AGO_GeographyLevels(){

  const query_URL = '/RDRBP/FeatureServer/' + Data_FeatureID + '/query' +
                    '?where=id<>%27%27&objectIds=' +
                    '&time=&resultType=none' +
                    '&outFields=' + CHART_DATA_OUT_FIELDS +
                    '&returnIdsOnly=false' +
                    '&returnCountOnly=false' +
                    '&returnDistinctValues=true' +
                    '&orderByFields=' + CHART_DATA_ORDER_BY_FIELDS +
                    '&groupByFieldsForStatistics=' +
                    '&outStatistics=' +
                    '&resultOffset=' +
                    '&resultRecordCount='
                    +'&f=pgeojson' +
                    '&token='

  return axios.get(query_URL);

};

//get the current level of geog for a geography level to use in ago api
//  example this gets all the hucs for a Cataloging unit
function getCurrentLevel(geogLevel){
  switch (geogLevel) {
    case 'River Basins':
      return 1;
      break;
    case 'Cataloging Units':
      return 2;
      break;
    case 'HUC12':
      return 3;
      break;
    default:
      return 99;
    }
}

//get the next level of geog for a geography level to use in ago api
//  example this gets all the hucs for a Cataloging unit
function getNextLevel(geogLevel){
  switch (geogLevel) {
    case 'River Basins':
      return 2;
      break;
    case 'Cataloging Units':
      return 3;
      break;
    case 'HUC12':
      return 99;
      break;
    default:
      return 99;
    }
}

//only needs this untill I change the data feed have named generically?
// or maybe control via yaml file....
function get_AGOGeographyLabel(geogLevel){
  switch (geogLevel) {
    case 'River Basins':
      return 'huc_6';
      break;
    case 'Cataloging Units':
      return 'huc_8';
      break;
    case 'HUC12':
      return 'huc_12';
      break;
    default:
      return 'huc_12';
    }
}
//updates the a geography level filter
//  determined by changed menuitem value
//  or when the user clicks on huc in map (not done yet)
function update_activeGeographyFilter( state, active_level, filter_value ){

  //convert the active layer name to the AGO generic name
  // need to do check of active layer
  const nextLevel = getNextLevel(active_level)
  const currentLevel = getCurrentLevel(active_level)
  const geography_levels = state.geography_levels.geography_levels
  const menuLists = state.menuLists.lists;

  //console.log(menuLists)

  //instatiate variables
  let GList = [];

  //loop the geography levels
  geography_levels.map(function(level) {

    let filtered_menu_list  = []

     //get the label, level,for the geography_level
     let geography_label = level['geography_label'];
     let geography_level = level['geography_level'];
     let active = level['active'];
     let filter = level['filter'];
     let current_id = level['current_id'];

     //set current id for current geography_level from the menu pulldown
     if (currentLevel === geography_level ){
       current_id = filter_value;
     }

     //if the geography_level is lower than the current level reset the current_id
     if (currentLevel < geography_level ){
       current_id = '';
     }

     //set the filter value for lower level geographies
     if (geography_level >= nextLevel){
       filter = filter_value;
     }

     //get the menuLists for the geography_level
     const menuList = menuLists[geography_level-1].lists

     console.log(geography_level)

     //only filter when there is a filter value
     //  otherwise get the entire menu
     if (filter.length > 0 ){

       //filter the menuLists for the geography_level by the filter value
       menuList.map(listItem => {
         const checkedValue = listItem.id.toString().substring(0, filter.length)
         if (filter_value === checkedValue){
           filtered_menu_list.push(listItem)
         }
       })
     } else {
        //no filter get entire menu
        filtered_menu_list = menuList
     }

    //  console.log(JSON.stringify(filtered_menu_list))
    //  console.log(geography_level)
     //console.log(filtered_menu_list)
     //create new geography_level object
     let thisGeographyList = {geography_level, geography_label, active, filter, current_id, filtered_menu_list};

     //add the geography_level object to new state array
     GList.push(thisGeographyList)
   })

  return GList;

}

//updates the which geograpy level is active_level
//  determined by which menu item the user clicks or
//  or when the user clicks on huc in map (not done yet)
function update_activeGeographyLevel( state, active_level ){

  //convert the active layer name to the AGO generic name
  // need to do check of active layer
  const label = get_AGOGeographyLabel(active_level);
  const geography_levels = state.geography_levels.geography_levels;

  //instatiate variables
  let GList = [];
  let active = false;
  // let filter = '';

  //loop the geography levels
  geography_levels.map(function(level) {

     //get the label, level,for the geography_level
     let geography_label = level['geography_label'];
     let geography_level = level['geography_level'];
     let filter = level['filter'];
     let current_id = level['current_id'];
     let filtered_menu_list  = level['filtered_menu_list'];

     //check of the labels matches the new active layer label
     //  is so set active to true.
     //  otherwise false
     if (level['geography_label'] === label){
       active = true;
     } else {
       active = false;
     }

     //create new geography_level object
     let thisGeographyList = {geography_level, geography_label, active, filter, current_id, filtered_menu_list};

     //add the geography_level object to new state array
     GList.push(thisGeographyList)
   })

  return GList;

}

// change filter for geography level
export function change_geographyLevelFilter(filter_value, active_level) {
  return (dispatch, getState) => {

    const state = getState()

    //create new geography_level state object
    const newLevels = update_activeGeographyFilter( state, active_level, filter_value );

    //send the new geography level data on
    dispatch(geography_levels('CHANGE_FILTER_GEOGRAPHY_LEVEL',newLevels))

  }
}

// change active geography level
export function change_geographyLevelActive(active_level) {
  return (dispatch, getState) => {

    const state = getState()

    //create new geography_level state object
    const newLevels = update_activeGeographyLevel( state, active_level );

    //send the new geography level data on
    dispatch(geography_levels('CHANGE_ACTIVE_GEOGRAPHY_LEVEL',newLevels))

  }
}

export function get_GeographyLevels(){
  return dispatch => {
      AGO_GeographyLevels()
        .then(function test(response){

          //check repsonses for errors
          let theGeographyLevels = CheckReponse(response,'AGO_API_ERROR');

          //instatiate variables and default values
          let GList = [];
          let active = false;
          let filter = '';
          let current_id = '';
          let filtered_menu_list  = [];

          //loop the geography_levels and build the geography_level state obect
          theGeographyLevels.features.map(function(features) {

             //get values for label and level   //instatiate variables
             let geography_label = features.properties.geography_label;
             let geography_level = features.properties.geography_level;

             //create new geography_level state object
             let thisGeographyList = {geography_level, geography_label, active , filter, current_id, filtered_menu_list};

             //add the geography_level object to new state array
             GList.push(thisGeographyList)
           })

          //send the geography level data on
          dispatch(geography_levels('GET_GEOGRAPHY_LEVELS',GList))
        })
        .catch(error => { console.log('request failed', error); });
  }
}

//new geography_levels object to pass to reducer
function geography_levels(type,data) {
  return {
    type: type,
    geography_levels: data,
    receivedAt: Date.now()
  }
}
<|endoftext|>


<commit_before>import * as dom from './dom/index.js'
import { swalClasses } from '../utils/classes.js'

// Fix iOS scrolling http://stackoverflow.com/q/39626302

/* istanbul ignore next */
export const iOSfix = () => {
  const iOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream
  if (iOS && !dom.hasClass(document.body, swalClasses.iosfix)) {
    const offset = document.body.scrollTop
    document.body.style.top = (offset * -1) + 'px'
    dom.addClass(document.body, swalClasses.iosfix)
    lockBodyScroll()
  }
}

const lockBodyScroll = () => { // #1246
  const container = dom.getContainer()
  let preventTouchMove
  container.ontouchstart = (e) => {
    preventTouchMove =
      e.target === container ||
      (
        !dom.isScrollable(container) &&
        e.target.tagName !== 'INPUT' // #1603
      )
  }
  container.ontouchmove = (e) => {
    if (preventTouchMove) {
      e.preventDefault()
      e.stopPropagation()
    }
  }
}

/* istanbul ignore next */
export const undoIOSfix = () => {
  if (dom.hasClass(document.body, swalClasses.iosfix)) {
    const offset = parseInt(document.body.style.top, 10)
    dom.removeClass(document.body, swalClasses.iosfix)
    document.body.style.top = ''
    document.body.scrollTop = (offset * -1)
  }
}
<commit_msg>fix: iOS/iPadOS 13 detection (#1789)<commit_after>import * as dom from './dom/index.js'
import { swalClasses } from '../utils/classes.js'

// Fix iOS scrolling http://stackoverflow.com/q/39626302

/* istanbul ignore next */
export const iOSfix = () => {
  const iOS = (/iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream) || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1)
  if (iOS && !dom.hasClass(document.body, swalClasses.iosfix)) {
    const offset = document.body.scrollTop
    document.body.style.top = (offset * -1) + 'px'
    dom.addClass(document.body, swalClasses.iosfix)
    lockBodyScroll()
  }
}

const lockBodyScroll = () => { // #1246
  const container = dom.getContainer()
  let preventTouchMove
  container.ontouchstart = (e) => {
    preventTouchMove =
      e.target === container ||
      (
        !dom.isScrollable(container) &&
        e.target.tagName !== 'INPUT' // #1603
      )
  }
  container.ontouchmove = (e) => {
    if (preventTouchMove) {
      e.preventDefault()
      e.stopPropagation()
    }
  }
}

/* istanbul ignore next */
export const undoIOSfix = () => {
  if (dom.hasClass(document.body, swalClasses.iosfix)) {
    const offset = parseInt(document.body.style.top, 10)
    dom.removeClass(document.body, swalClasses.iosfix)
    document.body.style.top = ''
    document.body.scrollTop = (offset * -1)
  }
}
<|endoftext|>


<commit_before>function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);

    gvm.firstNameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("firstNameTableTitle");}, gvm);
    gvm.lastNameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("lastNameTableTitle");}, gvm);
    gvm.actionTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ActionTableTitle");}, gvm);

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + $("#projectHeader").data('value'), function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
        });
    };

    gvm.getStudentList = function() {
        console.log("hallo");
        $.getJSON('/api/project/' + $("#projectHeader").data('value') + '/students', function(data) {
            console.log(data);
            $.each(data, function(i, item) {
                console.log(item);
                viewModel.addTableData(item.id, item.firstname, item.lastname);
            });
        });
    };

    gvm.tabledata = ko.observableArray([]);

    // Add data to the table
    gvm.addTableData = function(id, firstname, lastname) {
        // Push data
        var tblOject = {tid: id, tfirstname: firstname, tlastname: lastname};
        gvm.tabledata.push(tblOject);
    };

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    };

    /*gvm.getAllData = function() {
        $.getJSON('/api/project/getAllData/' + $("#projectHeader").data('value'), function(data) {
            console.log(data);
        });
    }*/
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getStudentList();
}<commit_msg>studentist for assessing project<commit_after>function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);

    gvm.firstNameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("firstNameTableTitle");}, gvm);
    gvm.lastNameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("lastNameTableTitle");}, gvm);
    gvm.actionTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ActionTableTitle");}, gvm);

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + $("#projectHeader").data('value'), function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
        });
    };

    gvm.getStudentList = function() {
        $.getJSON('/api/project/' + $("#projectHeader").data('value') + '/students', function(data) {
            $.each(data, function(i, item) {
                console.log(item);
                viewModel.addTableData(item.id, item.firstname, item.lastname);
            });
        });
    };

    gvm.tabledata = ko.observableArray([]);

    // Add data to the table
    gvm.addTableData = function(id, firstname, lastname) {
        // Push data
        var tblOject = {tid: id, tfirstname: firstname, tlastname: lastname};
        gvm.tabledata.push(tblOject);
    };

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    };

    /*gvm.getAllData = function() {
        $.getJSON('/api/project/getAllData/' + $("#projectHeader").data('value'), function(data) {
            console.log(data);
        });
    }*/
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getStudentList();
}<|endoftext|>


<commit_before>/* eslint no-console: 0 */

var chalk = require('chalk');

const colors = {
  debug: 'gray',
  error: 'yellow',
  stdout: 'green',
  stderr: 'red',
  stdin: 'blue',
  sendosc: 'cyan',
  rcvosc: 'magenta'
};

/**
 * usage:
 *
 * log = new Logger(true, true);
 *
 * log.dbug('a message');
 * log.err('oh no');
 * log.stdin('command that I sent')
 * log.stdout('output from server')
 * log.stderr('error from server')
 *
 */

export default class Logger {

  /**
   * @param {winston.Logger|undefined} log - optional external winston Logger or compatible API
   */
  constructor(debug, echo, log) {
    this.debug = debug;
    this.echo = echo;
    this.colorize = typeof log === 'undefined';
    this.log = log || console;
    this.browser = typeof window !== 'undefined';
  }

  dbug(text) {
    if (this.debug) {
      this.print('debug  ', text, colors.debug);
    }
  }

  err(text) {
    this.print('error  ', text, colors.error);
  }

  stdin(text) {
    if (this.echo) {
      this.print('stdin  ', text, colors.stdin);
    }
  }

  stdout(text) {
    if (this.echo) {
      this.print('stdout ', text, colors.stdout);
    }
  }

  stderr(text) {
    if (this.echo) {
      this.print('stderr ', text, colors.stderr);
    }
  }

  sendosc(text) {
    if (this.echo) {
      this.print('sendosc', text, colors.sendosc);
    }
  }

  rcvosc(text) {
    if (this.echo) {
      this.print('rcvosc ', text, colors.rcvosc);
    }
  }

  print(label, text, color) {
    if (this.browser) {
      console.log('%c' + label, 'font-size: 10px; color:' + color, text);
    } else {
      // terminal
      if (typeof text !== 'string') {
        text = JSON.stringify(text, undefined, 2);
      }
      var
        lines = text.split('\n'),
        clean = [label + ': ' + lines[0]],
        rest = lines.slice(1)
          .filter((s) => s.length > 0)
          .map((s) => '           ' + s);
      clean = clean.concat(rest).join('\n');
      if (this.colorize) {
        clean = chalk[color](clean);
      }

      switch (label.trim()) {
        case 'debug':
        case 'stdin':
        case 'sendosc':
        case 'rcvosc':
          this.log.debug(clean);
          break;
        case 'stderr':
        case 'error':
          this.log.error(clean);
          break;
        default:
          this.log.info(clean);
      }
    }
  }
}
<commit_msg>fix: default node logger does not have .debug, use .info instead<commit_after>/* eslint no-console: 0 */

var chalk = require('chalk');

const colors = {
  debug: 'gray',
  error: 'yellow',
  stdout: 'green',
  stderr: 'red',
  stdin: 'blue',
  sendosc: 'cyan',
  rcvosc: 'magenta'
};

/**
 * usage:
 *
 * log = new Logger(true, true);
 *
 * log.dbug('a message');
 * log.err('oh no');
 * log.stdin('command that I sent')
 * log.stdout('output from server')
 * log.stderr('error from server')
 *
 */

export default class Logger {

  /**
   * @param {winston.Logger|undefined} log - optional external winston Logger or compatible API
   */
  constructor(debug, echo, log) {
    this.debug = debug;
    this.echo = echo;
    this.colorize = typeof log === 'undefined';
    this.log = log || console;
    this.browser = typeof window !== 'undefined';
  }

  dbug(text) {
    if (this.debug) {
      this.print('debug  ', text, colors.debug);
    }
  }

  err(text) {
    this.print('error  ', text, colors.error);
  }

  stdin(text) {
    if (this.echo) {
      this.print('stdin  ', text, colors.stdin);
    }
  }

  stdout(text) {
    if (this.echo) {
      this.print('stdout ', text, colors.stdout);
    }
  }

  stderr(text) {
    if (this.echo) {
      this.print('stderr ', text, colors.stderr);
    }
  }

  sendosc(text) {
    if (this.echo) {
      this.print('sendosc', text, colors.sendosc);
    }
  }

  rcvosc(text) {
    if (this.echo) {
      this.print('rcvosc ', text, colors.rcvosc);
    }
  }

  print(label, text, color) {
    if (this.browser) {
      console.log('%c' + label, 'font-size: 10px; color:' + color, text);
    } else {
      // terminal
      if (typeof text !== 'string') {
        text = JSON.stringify(text, undefined, 2);
      }
      var
        lines = text.split('\n'),
        clean = [label + ': ' + lines[0]],
        rest = lines.slice(1)
          .filter((s) => s.length > 0)
          .map((s) => '           ' + s);
      clean = clean.concat(rest).join('\n');
      if (this.colorize) {
        clean = chalk[color](clean);
      }

      switch (label.trim()) {
        case 'debug':
        case 'stdin':
        case 'sendosc':
        case 'rcvosc':
          this.log.info(clean);
          break;
        case 'stderr':
        case 'error':
          this.log.error(clean);
          break;
        default:
          this.log.info(clean);
      }
    }
  }
}
<|endoftext|>


<commit_before>'use strict';

module.exports = function(app) {
  app.factory('GameService', ['$rootScope', '$route', '$http', 'ResultService', 'UserService', 'StatsService', function($rs, $route, $http, resultService, userService, statsService) {

    const newGame = function(gameData) {
      return new Promise((resolve, reject) => {
        createGameAndResults(gameData)
          .then((newGameData) => {
            updateGameAndUsers(newGameData.gameId, newGameData.results)
              .then(resolve)
              .catch(reject);
          })
          .catch(reject);
      });
    };

    const createGameAndResults = function(gameData) {
      return new Promise((resolve, reject) => {
        create(gameData)
          .then((newGame) => {
            resultService.create(newGame._id, gameData.players)
              .then((results) => {
                let newGameData = {
                  gameId: newGame._id,
                  results: results,
                };
                resolve(newGameData);
              })
              .catch(reject);
          })
          .catch(reject);
      });
    };

    const updateGameAndUsers = function(gameId, resultsArray) {
      return new Promise((resolve, reject) => {
        let resultIds = [];
        let userIds = [];
        let gameUpdateData = {};
        let userUpdateData = {};

        resultIds = resultsArray.map((result) => {
          return result._id;
        });

        userIds = resultsArray.map((result) => {
          return result.playerId;
        })

        gameUpdateData.gameId = gameId;
        gameUpdateData.updateOptions = {
          $addToSet: { results: { $each: resultIds }},
        };

        userUpdateData.usersIds = userIds;
        userUpdateData.updateOptions = {
          $addToSet: { gameIds: gameId },
        };

        //TODO: refactor to mitigate callback hell.
        update(gameUpdateData)
          .then(() => {
            userService.updateManyById(userUpdateData)
              .then(() => {
                statsService.updateManyByDocOrUserId(resultsArray)
                  .then(() => {
                    resolve();
                    $route.reload();
                  })
                  .catch(reject);
              })
              .catch(reject);
          })
          .catch(reject);
      });
    };

    const create = function(gameData) {
      return new Promise((resolve, reject) => {
        $http.post(`${$rs.baseUrl}/games/create`, gameData)
          .then((newGame) => {
            resolve(newGame.data);
          })
          .catch((err) => {
            console.log(err);
            reject(err);
          });
      });
    };

    const update = function(updateData) {
      return new Promise((resolve, reject) => {
        $http.post(`${$rs.baseUrl}/games/update`, updateData)
          .then((newData) => {
            resolve(newData.data);
          })
          .catch(reject);
      });
    };

    this.getByPublicId = function(gameId) {
      return new Promise((resolve, reject) => {
        $http.get($rs.baseUrl + '/games/' + gameId)
          .then((game) => {
            resolve(game.data);
          })
          .catch(reject);
      });
    };

    this.getAllByPublicId = function(publicIdArray) {
      return new Promise((resolve, reject) => {
        let publicIdData = {
          publicIdArray: publicIdArray,
        };
        $http.post($rs.baseUrl + '/games/all', publicIdData)
          .then((games) => {
            resolve(games.data);
          })
          .catch(() => {
            alert('error getting games');
            reject();
          });
      });
    };

    return {
      create: create,
      newGame: newGame,
    }
  }]);
};
<commit_msg>Add getAllById method.<commit_after>'use strict';

module.exports = function(app) {
  app.factory('GameService', ['$rootScope', '$route', '$http', 'ResultService', 'UserService', 'StatsService', function($rs, $route, $http, resultService, userService, statsService) {

    const data = {
      allGames: {},
    };

    const newGame = function(gameData) {
      return new Promise((resolve, reject) => {
        createGameAndResults(gameData)
          .then((newGameData) => {
            updateGameAndUsers(newGameData.gameId, newGameData.results)
              .then(resolve)
              .catch(reject);
          })
          .catch(reject);
      });
    };

    const createGameAndResults = function(gameData) {
      return new Promise((resolve, reject) => {
        create(gameData)
          .then((newGame) => {
            resultService.create(newGame._id, gameData.players)
              .then((results) => {
                let newGameData = {
                  gameId: newGame._id,
                  results: results,
                };
                resolve(newGameData);
              })
              .catch(reject);
          })
          .catch(reject);
      });
    };

    const updateGameAndUsers = function(gameId, resultsArray) {
      return new Promise((resolve, reject) => {
        let resultIds = [];
        let userIds = [];
        let gameUpdateData = {};
        let userUpdateData = {};

        resultIds = resultsArray.map((result) => {
          return result._id;
        });

        userIds = resultsArray.map((result) => {
          return result.playerId;
        })

        gameUpdateData.gameId = gameId;
        gameUpdateData.updateOptions = {
          $addToSet: { results: { $each: resultIds }},
        };

        userUpdateData.usersIds = userIds;
        userUpdateData.updateOptions = {
          $addToSet: { gameIds: gameId },
        };

        //TODO: refactor to mitigate callback hell.
        update(gameUpdateData)
          .then(() => {
            userService.updateManyById(userUpdateData)
              .then(() => {
                statsService.updateManyByDocOrUserId(resultsArray)
                  .then(() => {
                    resolve();
                    $route.reload();
                  })
                  .catch(reject);
              })
              .catch(reject);
          })
          .catch(reject);
      });
    };

    const create = function(gameData) {
      return new Promise((resolve, reject) => {
        $http.post(`${$rs.baseUrl}/games/create`, gameData)
          .then((newGame) => {
            resolve(newGame.data);
          })
          .catch((err) => {
            console.log(err);
            reject(err);
          });
      });
    };

    const getAllById = function(gameIds) {
      return new Promise((resolve, reject) => {
        let gameIdData = {
          gameIds: gameIds,
        };
        $http.post(`${$rs.baseUrl}/games/all`, gameIdData)
        .then((games) => {
          games = games.data;
          data.allGames.games = games;
          resolve();
        })
        .catch(() => {
          alert('error getting games');
          reject();
        });
      });
    };

    const update = function(updateData) {
      return new Promise((resolve, reject) => {
        $http.post(`${$rs.baseUrl}/games/update`, updateData)
          .then((newData) => {
            resolve(newData.data);
          })
          .catch(reject);
      });
    };

    this.getByPublicId = function(gameId) {
      return new Promise((resolve, reject) => {
        $http.get($rs.baseUrl + '/games/' + gameId)
          .then((game) => {
            resolve(game.data);
          })
          .catch(reject);
      });
    };

    return {
      create: create,
      getAllById: getAllById,
      newGame: newGame,
      data: data,
    }
  }]);
};
<|endoftext|>


<commit_before>/* ===========================================================
 * bootstrap-modalmanager.js v2.2.0
 * ===========================================================
 * Copyright 2012 Jordan Schroter.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ========================================================== */

!function ($) {

	"use strict"; // jshint ;_;

	/* MODAL MANAGER CLASS DEFINITION
	* ====================== */

	var ModalManager = function (element, options) {
		this.init(element, options);
	};

	ModalManager.prototype = {

		constructor: ModalManager,

		init: function (element, options) {
			this.$element = $(element);
			this.options = $.extend({}, $.fn.modalmanager.defaults, this.$element.data(), typeof options == 'object' && options);
			this.stack = [];
			this.backdropCount = 0;

			if (this.options.resize) {
				var resizeTimeout,
					that = this;

				$(window).on('resize.modal', function(){
					resizeTimeout && clearTimeout(resizeTimeout);
					resizeTimeout = setTimeout(function(){
						for (var i = 0; i < that.stack.length; i++){
							that.stack[i].isShown && that.stack[i].layout();
						}
					}, 10);
				});
			}
		},

		createModal: function (element, options) {
			$(element).modal($.extend({ manager: this }, options));
		},

		appendModal: function (modal) {
			this.stack.push(modal);

			var that = this;

			modal.$element.on('show.modalmanager', targetIsSelf(function (e) {

				var showModal = function(){
					modal.isShown = true;

					var transition = $.support.transition && modal.$element.hasClass('fade');

					that.$element
						.toggleClass('modal-open', that.hasOpenModal())
						.toggleClass('page-overflow', $(window).height() < that.$element.height());

					modal.$parent = modal.$element.parent();

					modal.$container = that.createContainer(modal);

					modal.$element.appendTo(modal.$container);

					that.backdrop(modal, function () {

						modal.$element.show();

						if (transition) {
							//modal.$element[0].style.display = 'run-in';
							modal.$element[0].offsetWidth;
							//modal.$element.one($.support.transition.end, function () { modal.$element[0].style.display = 'block' });
						}

						modal.layout();

						modal.$element
							.addClass('in')
							.attr('aria-hidden', false);

						var complete = function () {
							that.setFocus();
							modal.$element.trigger('shown');
						};

						transition ?
							modal.$element.one($.support.transition.end, complete) :
							complete();
					});
				};

				modal.options.replace ?
					that.replace(showModal) :
					showModal();
			}));

			modal.$element.on('hidden.modalmanager', targetIsSelf(function (e) {

				that.backdrop(modal);

				if (modal.$backdrop){
					$.support.transition && modal.$element.hasClass('fade') ?
						modal.$backdrop.one($.support.transition.end, function () { that.destroyModal(modal) }) :
						that.destroyModal(modal);
				} else {
					that.destroyModal(modal);
				}

			}));

			modal.$element.on('destroy.modalmanager', targetIsSelf(function (e) {
				that.removeModal(modal);
			}));

		},

		destroyModal: function (modal) {

			modal.destroy();

			var hasOpenModal = this.hasOpenModal();

			this.$element.toggleClass('modal-open', hasOpenModal);

			if (!hasOpenModal){
				this.$element.removeClass('page-overflow');
			}

			this.removeContainer(modal);

			this.setFocus();
		},

		getOpenModals: function () {
			var openModals = [];
			for (var i = 0; i < this.stack.length; i++){
				if (this.stack[i].isShown) openModals.push(this.stack[i]);
			}

			return openModals;
		},

		hasOpenModal: function () {
			return this.getOpenModals().length > 0;
		},

		setFocus: function () {
			var topModal;

			for (var i = 0; i < this.stack.length; i++){
				if (this.stack[i].isShown) topModal = this.stack[i];
			}

			if (!topModal) return;

			topModal.focus();

		},

		removeModal: function (modal) {
			modal.$element.off('.modalmanager');
			if (modal.$backdrop) this.removeBackdrop(modal);
			this.stack.splice(this.getIndexOfModal(modal), 1);
		},

		getModalAt: function (index) {
			return this.stack[index];
		},

		getIndexOfModal: function (modal) {
			for (var i = 0; i < this.stack.length; i++){
				if (modal === this.stack[i]) return i;
			}
		},

		replace: function (callback) {
			var topModal;

			for (var i = 0; i < this.stack.length; i++){
				if (this.stack[i].isShown) topModal = this.stack[i];
			}

			if (topModal) {
				this.$backdropHandle = topModal.$backdrop;
				topModal.$backdrop = null;

				callback && topModal.$element.one('hidden',
					targetIsSelf( $.proxy(callback, this) ));

				topModal.hide();
			} else if (callback) {
				callback();
			}
		},

		removeBackdrop: function (modal) {
			modal.$backdrop.remove();
			modal.$backdrop = null;
		},

		createBackdrop: function (animate, tmpl) {
			var $backdrop;

			if (!this.$backdropHandle) {
				$backdrop = $(tmpl)
					.addClass(animate)
					.appendTo(this.$element);
			} else {
				$backdrop = this.$backdropHandle;
				$backdrop.off('.modalmanager');
				this.$backdropHandle = null;
				this.isLoading && this.removeSpinner();
			}

			return $backdrop;
		},

		removeContainer: function (modal) {
			modal.$container.remove();
			modal.$container = null;
		},

		createContainer: function (modal) {
			var $container;

			$container = $('
')
				.css('z-index', getzIndex('modal', this.getOpenModals().length))
				.appendTo(this.$element);

			if (modal && modal.options.backdrop != 'static') {
				$container.on('click.modal', targetIsSelf(function (e) {
					modal.hide();
				}));
			} else if (modal) {
				$container.on('click.modal', targetIsSelf(function (e) {
					modal.attention();
				}));
			}

			return $container;

		},

		backdrop: function (modal, callback) {
			var animate = modal.$element.hasClass('fade') ? 'fade' : '',
				showBackdrop = modal.options.backdrop &&
					this.backdropCount < this.options.backdropLimit;

			if (modal.isShown && showBackdrop) {
				var doAnimate = $.support.transition && animate && !this.$backdropHandle;

				modal.$backdrop = this.createBackdrop(animate, modal.options.backdropTemplate);

				modal.$backdrop.css('z-index', getzIndex( 'backdrop', this.getOpenModals().length ));

				if (doAnimate) modal.$backdrop[0].offsetWidth; // force reflow

				modal.$backdrop.addClass('in');

				this.backdropCount += 1;

				doAnimate ?
					modal.$backdrop.one($.support.transition.end, callback) :
					callback();

			} else if (!modal.isShown && modal.$backdrop) {
				modal.$backdrop.removeClass('in');

				this.backdropCount -= 1;

				var that = this;

				$.support.transition && modal.$element.hasClass('fade')?
					modal.$backdrop.one($.support.transition.end, function () { that.removeBackdrop(modal) }) :
					that.removeBackdrop(modal);

			} else if (callback) {
				callback();
			}
		},

		removeSpinner: function(){
			this.$spinner && this.$spinner.remove();
			this.$spinner = null;
			this.isLoading = false;
		},

		removeLoading: function () {
			this.$backdropHandle && this.$backdropHandle.remove();
			this.$backdropHandle = null;
			this.removeSpinner();
		},

		loading: function (callback) {
			callback = callback || function () { };

			this.$element
				.toggleClass('modal-open', !this.isLoading || this.hasOpenModal())
				.toggleClass('page-overflow', $(window).height() < this.$element.height());

			if (!this.isLoading) {

				this.$backdropHandle = this.createBackdrop('fade', this.options.backdropTemplate);

				this.$backdropHandle[0].offsetWidth; // force reflow

				var openModals = this.getOpenModals();

				this.$backdropHandle
					.css('z-index', getzIndex('backdrop', openModals.length + 1))
					.addClass('in');

				var $spinner = $(this.options.spinner)
					.css('z-index', getzIndex('modal', openModals.length + 1))
					.appendTo(this.$element)
					.addClass('in');

				this.$spinner = $(this.createContainer())
					.append($spinner)
					.on('click.modalmanager', $.proxy(this.loading, this));

				this.isLoading = true;

				$.support.transition ?
					this.$backdropHandle.one($.support.transition.end, callback) :
					callback();

			} else if (this.isLoading && this.$backdropHandle) {
				this.$backdropHandle.removeClass('in');

				var that = this;
				$.support.transition ?
					this.$backdropHandle.one($.support.transition.end, function () { that.removeLoading() }) :
					that.removeLoading();

			} else if (callback) {
				callback(this.isLoading);
			}
		}
	};

	/* PRIVATE METHODS
	* ======================= */

	// computes and caches the zindexes
	var getzIndex = (function () {
		var zIndexFactor,
			baseIndex = {};

		return function (type, pos) {

			if (typeof zIndexFactor === 'undefined'){
				var $baseModal = $('
').appendTo('body'),
					$baseBackdrop = $('
').appendTo('body');

				baseIndex['modal'] = +$baseModal.css('z-index');
				baseIndex['backdrop'] = +$baseBackdrop.css('z-index');
				zIndexFactor = baseIndex['modal'] - baseIndex['backdrop'];

				$baseModal.remove();
				$baseBackdrop.remove();
				$baseBackdrop = $baseModal = null;
			}

			return baseIndex[type] + (zIndexFactor * pos);

		}
	}());

	// make sure the event target is the modal itself in order to prevent
	// other components such as tabsfrom triggering the modal manager.
	// if Boostsrap namespaced events, this would not be needed.
	function targetIsSelf(callback){
		return function (e) {
			if (this === e.target){
				return callback.apply(this, arguments);
			}
		}
	}

	/* MODAL MANAGER PLUGIN DEFINITION
	* ======================= */

	$.fn.modalmanager = function (option, args) {
		return this.each(function () {
			var $this = $(this),
				data = $this.data('modalmanager');

			if (!data) $this.data('modalmanager', (data = new ModalManager(this, option)));
			if (typeof option === 'string') data[option].apply(data, [].concat(args))
		})
	};

	$.fn.modalmanager.defaults = {
		backdropLimit: 999,
		resize: true,
		spinner: '

',
		backdropTemplate: '
'
	};

	$.fn.modalmanager.Constructor = ModalManager

}(jQuery);
<commit_msg>trigger a relayout due to firebox's buggy transition end<commit_after>/* ===========================================================
 * bootstrap-modalmanager.js v2.2.0
 * ===========================================================
 * Copyright 2012 Jordan Schroter.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ========================================================== */

!function ($) {

	"use strict"; // jshint ;_;

	/* MODAL MANAGER CLASS DEFINITION
	* ====================== */

	var ModalManager = function (element, options) {
		this.init(element, options);
	};

	ModalManager.prototype = {

		constructor: ModalManager,

		init: function (element, options) {
			this.$element = $(element);
			this.options = $.extend({}, $.fn.modalmanager.defaults, this.$element.data(), typeof options == 'object' && options);
			this.stack = [];
			this.backdropCount = 0;

			if (this.options.resize) {
				var resizeTimeout,
					that = this;

				$(window).on('resize.modal', function(){
					resizeTimeout && clearTimeout(resizeTimeout);
					resizeTimeout = setTimeout(function(){
						for (var i = 0; i < that.stack.length; i++){
							that.stack[i].isShown && that.stack[i].layout();
						}
					}, 10);
				});
			}
		},

		createModal: function (element, options) {
			$(element).modal($.extend({ manager: this }, options));
		},

		appendModal: function (modal) {
			this.stack.push(modal);

			var that = this;

			modal.$element.on('show.modalmanager', targetIsSelf(function (e) {

				var showModal = function(){
					modal.isShown = true;

					var transition = $.support.transition && modal.$element.hasClass('fade');

					that.$element
						.toggleClass('modal-open', that.hasOpenModal())
						.toggleClass('page-overflow', $(window).height() < that.$element.height());

					modal.$parent = modal.$element.parent();

					modal.$container = that.createContainer(modal);

					modal.$element.appendTo(modal.$container);

					that.backdrop(modal, function () {
						modal.$element.show();

						if (transition) {
							//modal.$element[0].style.display = 'run-in';
							modal.$element[0].offsetWidth;
							//modal.$element.one($.support.transition.end, function () { modal.$element[0].style.display = 'block' });
						}

						modal.layout();

						modal.$element
							.addClass('in')
							.attr('aria-hidden', false);

						var complete = function () {
							that.setFocus();
							modal.$element.trigger('shown');
						};

						transition ?
							modal.$element.one($.support.transition.end, complete) :
							complete();
					});
				};

				modal.options.replace ?
					that.replace(showModal) :
					showModal();
			}));

			modal.$element.on('hidden.modalmanager', targetIsSelf(function (e) {

				that.backdrop(modal);
				if (modal.$backdrop){
					var transition = $.support.transition && modal.$element.hasClass('fade');

					// trigger a relayout due to firebox's buggy transition end event
					if (transition) { modal.$element[0].offsetWidth; }

					$.support.transition && modal.$element.hasClass('fade') ?
						modal.$backdrop.one($.support.transition.end, function () { that.destroyModal(modal) }) :
						that.destroyModal(modal);
				} else {
					that.destroyModal(modal);
				}

			}));

			modal.$element.on('destroy.modalmanager', targetIsSelf(function (e) {
				that.removeModal(modal);
			}));

		},

		destroyModal: function (modal) {
			modal.destroy();

			var hasOpenModal = this.hasOpenModal();

			this.$element.toggleClass('modal-open', hasOpenModal);

			if (!hasOpenModal){
				this.$element.removeClass('page-overflow');
			}

			this.removeContainer(modal);

			this.setFocus();
		},

		getOpenModals: function () {
			var openModals = [];
			for (var i = 0; i < this.stack.length; i++){
				if (this.stack[i].isShown) openModals.push(this.stack[i]);
			}

			return openModals;
		},

		hasOpenModal: function () {
			return this.getOpenModals().length > 0;
		},

		setFocus: function () {
			var topModal;

			for (var i = 0; i < this.stack.length; i++){
				if (this.stack[i].isShown) topModal = this.stack[i];
			}

			if (!topModal) return;

			topModal.focus();

		},

		removeModal: function (modal) {
			modal.$element.off('.modalmanager');
			if (modal.$backdrop) this.removeBackdrop(modal);
			this.stack.splice(this.getIndexOfModal(modal), 1);
		},

		getModalAt: function (index) {
			return this.stack[index];
		},

		getIndexOfModal: function (modal) {
			for (var i = 0; i < this.stack.length; i++){
				if (modal === this.stack[i]) return i;
			}
		},

		replace: function (callback) {
			var topModal;

			for (var i = 0; i < this.stack.length; i++){
				if (this.stack[i].isShown) topModal = this.stack[i];
			}

			if (topModal) {
				this.$backdropHandle = topModal.$backdrop;
				topModal.$backdrop = null;

				callback && topModal.$element.one('hidden',
					targetIsSelf( $.proxy(callback, this) ));

				topModal.hide();
			} else if (callback) {
				callback();
			}
		},

		removeBackdrop: function (modal) {
			modal.$backdrop.remove();
			modal.$backdrop = null;
		},

		createBackdrop: function (animate, tmpl) {
			var $backdrop;

			if (!this.$backdropHandle) {
				$backdrop = $(tmpl)
					.addClass(animate)
					.appendTo(this.$element);
			} else {
				$backdrop = this.$backdropHandle;
				$backdrop.off('.modalmanager');
				this.$backdropHandle = null;
				this.isLoading && this.removeSpinner();
			}

			return $backdrop;
		},

		removeContainer: function (modal) {
			modal.$container.remove();
			modal.$container = null;
		},

		createContainer: function (modal) {
			var $container;

			$container = $('
')
				.css('z-index', getzIndex('modal', this.getOpenModals().length))
				.appendTo(this.$element);

			if (modal && modal.options.backdrop != 'static') {
				$container.on('click.modal', targetIsSelf(function (e) {
					modal.hide();
				}));
			} else if (modal) {
				$container.on('click.modal', targetIsSelf(function (e) {
					modal.attention();
				}));
			}

			return $container;

		},

		backdrop: function (modal, callback) {
			var animate = modal.$element.hasClass('fade') ? 'fade' : '',
				showBackdrop = modal.options.backdrop &&
					this.backdropCount < this.options.backdropLimit;

			if (modal.isShown && showBackdrop) {
				var doAnimate = $.support.transition && animate && !this.$backdropHandle;

				modal.$backdrop = this.createBackdrop(animate, modal.options.backdropTemplate);

				modal.$backdrop.css('z-index', getzIndex( 'backdrop', this.getOpenModals().length ));

				if (doAnimate) modal.$backdrop[0].offsetWidth; // force reflow

				modal.$backdrop.addClass('in');

				this.backdropCount += 1;

				doAnimate ?
					modal.$backdrop.one($.support.transition.end, callback) :
					callback();

			} else if (!modal.isShown && modal.$backdrop) {
				modal.$backdrop.removeClass('in');

				this.backdropCount -= 1;

				var that = this;

				$.support.transition && modal.$element.hasClass('fade')?
					modal.$backdrop.one($.support.transition.end, function () { that.removeBackdrop(modal) }) :
					that.removeBackdrop(modal);

			} else if (callback) {
				callback();
			}
		},

		removeSpinner: function(){
			this.$spinner && this.$spinner.remove();
			this.$spinner = null;
			this.isLoading = false;
		},

		removeLoading: function () {
			this.$backdropHandle && this.$backdropHandle.remove();
			this.$backdropHandle = null;
			this.removeSpinner();
		},

		loading: function (callback) {
			callback = callback || function () { };

			this.$element
				.toggleClass('modal-open', !this.isLoading || this.hasOpenModal())
				.toggleClass('page-overflow', $(window).height() < this.$element.height());

			if (!this.isLoading) {

				this.$backdropHandle = this.createBackdrop('fade', this.options.backdropTemplate);

				this.$backdropHandle[0].offsetWidth; // force reflow

				var openModals = this.getOpenModals();

				this.$backdropHandle
					.css('z-index', getzIndex('backdrop', openModals.length + 1))
					.addClass('in');

				var $spinner = $(this.options.spinner)
					.css('z-index', getzIndex('modal', openModals.length + 1))
					.appendTo(this.$element)
					.addClass('in');

				this.$spinner = $(this.createContainer())
					.append($spinner)
					.on('click.modalmanager', $.proxy(this.loading, this));

				this.isLoading = true;

				$.support.transition ?
					this.$backdropHandle.one($.support.transition.end, callback) :
					callback();

			} else if (this.isLoading && this.$backdropHandle) {
				this.$backdropHandle.removeClass('in');

				var that = this;
				$.support.transition ?
					this.$backdropHandle.one($.support.transition.end, function () { that.removeLoading() }) :
					that.removeLoading();

			} else if (callback) {
				callback(this.isLoading);
			}
		}
	};

	/* PRIVATE METHODS
	* ======================= */

	// computes and caches the zindexes
	var getzIndex = (function () {
		var zIndexFactor,
			baseIndex = {};

		return function (type, pos) {

			if (typeof zIndexFactor === 'undefined'){
				var $baseModal = $('
').appendTo('body'),
					$baseBackdrop = $('
').appendTo('body');

				baseIndex['modal'] = +$baseModal.css('z-index');
				baseIndex['backdrop'] = +$baseBackdrop.css('z-index');
				zIndexFactor = baseIndex['modal'] - baseIndex['backdrop'];

				$baseModal.remove();
				$baseBackdrop.remove();
				$baseBackdrop = $baseModal = null;
			}

			return baseIndex[type] + (zIndexFactor * pos);

		}
	}());

	// make sure the event target is the modal itself in order to prevent
	// other components such as tabsfrom triggering the modal manager.
	// if Boostsrap namespaced events, this would not be needed.
	function targetIsSelf(callback){
		return function (e) {
			if (this === e.target){
				return callback.apply(this, arguments);
			}
		}
	}

	/* MODAL MANAGER PLUGIN DEFINITION
	* ======================= */

	$.fn.modalmanager = function (option, args) {
		return this.each(function () {
			var $this = $(this),
				data = $this.data('modalmanager');

			if (!data) $this.data('modalmanager', (data = new ModalManager(this, option)));
			if (typeof option === 'string') data[option].apply(data, [].concat(args))
		})
	};

	$.fn.modalmanager.defaults = {
		backdropLimit: 999,
		resize: true,
		spinner: '

',
		backdropTemplate: '
'
	};

	$.fn.modalmanager.Constructor = ModalManager

}(jQuery);
<|endoftext|>


<commit_before>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';

class advertisement_discovery extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text style={styles.instructions}>
          To get started, edit index.android.js
        </Text>
        <Text style={styles.instructions}>
          Double tap R on your keyboard to reload,{'\n'}
          Shake or press menu button for dev menu
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

AppRegistry.registerComponent('advertisement_discovery', () => advertisement_discovery);
<commit_msg>add index.android.js<commit_after>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';

import noble from 'react-native-ble';

class advertisement_discovery extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text style={styles.instructions}>
          To get started, edit index.android.js
        </Text>
        <Text style={styles.instructions}>
          Double tap R on your keyboard to reload,{'\n'}
          Shake or press menu button for dev menu
        </Text>
      </View>
    );
  }

  componentWillMount() {
    noble.on('stateChange', this._onStateChange);
    noble.on('discover', this._onDiscover);
  }

  _onStateChange(state) {
    if (state === 'poweredOn') {
      noble.startScanning();
    } else {
      noble.stopScanning();
    }
  }

  _onDiscover(peripheral) {
    console.log('peripheral discovered (' + peripheral.id +
                ' with address <' + peripheral.address +  ', ' + peripheral.addressType + '>,' +
                ' connectable ' + peripheral.connectable + ',' +
                ' RSSI ' + peripheral.rssi + ':');
    console.log('\thello my local name is:');
    console.log('\t\t' + peripheral.advertisement.localName);
    console.log('\tcan I interest you in any of the following advertised services:');
    console.log('\t\t' + JSON.stringify(peripheral.advertisement.serviceUuids));

    var serviceData = peripheral.advertisement.serviceData;
    if (serviceData && serviceData.length) {
      console.log('\there is my service data:');
      for (var i in serviceData) {
        console.log('\t\t' + JSON.stringify(serviceData[i].uuid) + ': ' + JSON.stringify(serviceData[i].data.toString('hex')));
      }
    }
    if (peripheral.advertisement.manufacturerData) {
      console.log('\there is my manufacturer data:');
      console.log('\t\t' + JSON.stringify(peripheral.advertisement.manufacturerData.toString('hex')));
    }
    if (peripheral.advertisement.txPowerLevel !== undefined) {
      console.log('\tmy TX power level is:');
      console.log('\t\t' + peripheral.advertisement.txPowerLevel);
    }

    console.log();
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

AppRegistry.registerComponent('advertisement_discovery', () => advertisement_discovery);
<|endoftext|>


<commit_before>import $ from 'jquery';

import { wrap } from '@girder/core/utilities/PluginUtils';
import { restRequest } from '@girder/core/rest';
import AccessWidget from '@girder/core/views/widgets/AccessWidget';
import HierarchyWidget from '@girder/core/views/widgets/HierarchyWidget';

import AnnotationModel from '../models/AnnotationModel';

wrap(HierarchyWidget, 'initialize', function (initialize, settings) {
    initialize.call(this, settings);

    this.folderListView.on('g:folderClicked', () => {
        ownAnnotation(this, this.parentModel.id);
    });
});

wrap(HierarchyWidget, 'render', function (render) {
    render.call(this);

    if (this.parentModel.get('_modelType') === 'folder') {
        ownAnnotation(this, this.parentModel.id);
    }
});

function ownAnnotation(root, folderId) {
    restRequest({
        type: 'GET',
        url: 'annotation/folder/' + folderId + '/present',
        data: {
            recurse: true
        }
    }).done((ownsAnnot) => {
        if (ownsAnnot) {
            addAccessControl(root);
        }
    });
}

function addAccessControl(root) {
    if (root.$('.g-edit-annotation-access').length === 0) {
        if (root.$('.g-folder-actions-menu > .divider').length > 0) {
            root.$('.g-folder-actions-menu > .divider').before(
                '
' +
                    '' +
                        '' +
                        'Annotation access control' +
                    '' +
                '
'
            );
        } else {
            root.$('.g-folder-actions-menu > .dropdown-header').after(
                '
' +
                    '' +
                        '' +
                        'Annotation access control' +
                    '' +
                '
' +
                '
'
            );
        }
        root.events['click .g-edit-annotation-access'] = editAnnotAccess;
        root.delegateEvents();
    }
}

function editAnnotAccess() {
    restRequest({
        type: 'GET',
        url: 'annotation/folder/' + this.parentModel.get('_id'),
        data: {
            recurse: true,
            limit: 1
        }
    }).done((resp) => {
        const model = new AnnotationModel(resp[0]);
        model.get('annotation').name = 'Your Annotations';
        model.save = () => {};
        model.updateAccess = (settings) => {
            const access = {
                access: model.get('access'),
                public: model.get('public'),
                publicFlags: model.get('publicFlags')
            };
            const defaultUpdateModel = new AnnotationModel();
            defaultUpdateModel.id = this.parentModel.get('_id');
            defaultUpdateModel.altUrl = 'annotation/folder';
            defaultUpdateModel.set(access);
            defaultUpdateModel.updateAccess(settings);
            model.trigger('g:accessListSaved');
        };
        model.fetchAccess(true)
            .done(() => {
                new AccessWidget({// eslint-disable-line no-new
                    el: $('#g-dialog-container'),
                    modelType: 'annotation',
                    model,
                    hideRecurseOption: false,
                    parentView: this
                });
            });
    });
}

export default HierarchyWidget;
<commit_msg>Remove unnecessary `HierarchyWidget` wrapper<commit_after>import $ from 'jquery';

import { wrap } from '@girder/core/utilities/PluginUtils';
import { restRequest } from '@girder/core/rest';
import AccessWidget from '@girder/core/views/widgets/AccessWidget';
import HierarchyWidget from '@girder/core/views/widgets/HierarchyWidget';

import AnnotationModel from '../models/AnnotationModel';

wrap(HierarchyWidget, 'render', function (render) {
    render.call(this);

    if (this.parentModel.get('_modelType') === 'folder') {
        ownAnnotation(this, this.parentModel.id);
    }
});

function ownAnnotation(root, folderId) {
    restRequest({
        type: 'GET',
        url: 'annotation/folder/' + folderId + '/present',
        data: {
            recurse: true
        }
    }).done((ownsAnnot) => {
        if (ownsAnnot) {
            addAccessControl(root);
        }
    });
}

function addAccessControl(root) {
    if (root.$('.g-edit-annotation-access').length === 0) {
        if (root.$('.g-folder-actions-menu > .divider').length > 0) {
            root.$('.g-folder-actions-menu > .divider').before(
                '
' +
                    '' +
                        '' +
                        'Annotation access control' +
                    '' +
                '
'
            );
        } else {
            root.$('.g-folder-actions-menu > .dropdown-header').after(
                '
' +
                    '' +
                        '' +
                        'Annotation access control' +
                    '' +
                '
' +
                '
'
            );
        }
        root.events['click .g-edit-annotation-access'] = editAnnotAccess;
        root.delegateEvents();
    }
}

function editAnnotAccess() {
    restRequest({
        type: 'GET',
        url: 'annotation/folder/' + this.parentModel.get('_id'),
        data: {
            recurse: true,
            limit: 1
        }
    }).done((resp) => {
        const model = new AnnotationModel(resp[0]);
        model.get('annotation').name = 'Your Annotations';
        model.save = () => {};
        model.updateAccess = (settings) => {
            const access = {
                access: model.get('access'),
                public: model.get('public'),
                publicFlags: model.get('publicFlags')
            };
            const defaultUpdateModel = new AnnotationModel();
            defaultUpdateModel.id = this.parentModel.get('_id');
            defaultUpdateModel.altUrl = 'annotation/folder';
            defaultUpdateModel.set(access);
            defaultUpdateModel.updateAccess(settings);
            model.trigger('g:accessListSaved');
        };
        model.fetchAccess(true)
            .done(() => {
                new AccessWidget({// eslint-disable-line no-new
                    el: $('#g-dialog-container'),
                    modelType: 'annotation',
                    model,
                    hideRecurseOption: false,
                    parentView: this
                });
            });
    });
}

export default HierarchyWidget;
<|endoftext|>


<commit_before>// Copyright 2013-2017, University of Colorado Boulder

/**
 * Reset All button, typically used to reset everything ('reset all') on a Screen.
 * Extends ResetButton, adding things that are specific to 'reset all'.
 *
 * @author John Blanco
 * @author Chris Malley (PixelZoom, Inc.)
 */
define( function( require ) {
  'use strict';

  // modules
  var DerivedProperty = require( 'AXON/DerivedProperty' );
  var DerivedPropertyIO = require( 'AXON/DerivedPropertyIO' );
  var inherit = require( 'PHET_CORE/inherit' );
  var PhetColorScheme = require( 'SCENERY_PHET/PhetColorScheme' );
  var ResetButton = require( 'SCENERY_PHET/buttons/ResetButton' );
  var sceneryPhet = require( 'SCENERY_PHET/sceneryPhet' );
  var SceneryPhetA11yStrings = require( 'SCENERY_PHET/SceneryPhetA11yStrings' );
  var Shape = require( 'KITE/Shape' );
  var Tandem = require( 'TANDEM/Tandem' );
  var Utterance = require( 'SCENERY_PHET/accessibility/Utterance' );
  var utteranceQueue = require( 'SCENERY_PHET/accessibility/utteranceQueue' );

  // ifphetio
  var BooleanIO = require( 'ifphetio!PHET_IO/types/BooleanIO' );

  // constants
  var RESET_ALL_BUTTON_RADIUS = 24; // derived from the image files that were originally used for this button

  // strings
  var resetAllButtonNameString = require( 'string!SCENERY_PHET/ResetAllButton.name' );

  // a11y strings - not translatable
  var resetAllAlertString = SceneryPhetA11yStrings.resetAllAlertString.value;

  /**
   * @param {Object} [options]
   * @constructor
   */
  function ResetAllButton( options ) {

    options = _.extend( {
      radius: RESET_ALL_BUTTON_RADIUS,
      baseColor: PhetColorScheme.RESET_ALL_BUTTON_BASE_COLOR,
      arrowColor: 'white',
      tandem: Tandem.required,

      phetioDocumentation: 'The orange, round button that can be used to restore the initial state',

      // a11y
      innerContent: resetAllButtonNameString
    }, options );

    ResetButton.call( this, options );

    this.focusHighlight = new Shape().circle( 0, 0, options.radius + 5 );

    // @private - Mirrored property of `buttonModel.isFiringProperty`, but is phet-io instrumented.
    this.isFiringProperty = new DerivedProperty( [ this.buttonModel.isFiringProperty ], function( a ) { return a; }, {
      tandem: options.tandem.createTandem( 'isFiringProperty' ),
      phetioDocumentation: 'Temporarily becomes true while the Reset All button is firing.  Commonly used to disable audio effects during reset.',
      phetioType: DerivedPropertyIO( BooleanIO ),
      phetioState: false // this is a transient property based on user interaction, should not be stored in the state
    } );

    // a11y - when reset all button is fired, disable alerts so that there isn't an excessive stream of alerts
    // while many Properties are reset. When callbacks are ended for reset all, enable alerts again and announce an
    // alert that everything was reset.
    this.isFiringProperty.lazyLink( function( isFiring ) {
      utteranceQueue.enabled = !isFiring;

      !isFiring && utteranceQueue.addToBack( new Utterance( resetAllAlertString, {
        typeId: 'resetAllButtonAlert'
      } ) );
    } );
  }

  sceneryPhet.register( 'ResetAllButton', ResetAllButton );

  return inherit( ResetButton, ResetAllButton, {

    /**
     * Make eligible for garbage collection.
     * @public
     */
    dispose: function() {

      this.isFiringProperty.dispose();

      ResetButton.prototype.dispose.call( this );
    }
  } );
} );
<commit_msg>typeId -> uniqueGroupId, see #405<commit_after>// Copyright 2013-2017, University of Colorado Boulder

/**
 * Reset All button, typically used to reset everything ('reset all') on a Screen.
 * Extends ResetButton, adding things that are specific to 'reset all'.
 *
 * @author John Blanco
 * @author Chris Malley (PixelZoom, Inc.)
 */
define( function( require ) {
  'use strict';

  // modules
  var DerivedProperty = require( 'AXON/DerivedProperty' );
  var DerivedPropertyIO = require( 'AXON/DerivedPropertyIO' );
  var inherit = require( 'PHET_CORE/inherit' );
  var PhetColorScheme = require( 'SCENERY_PHET/PhetColorScheme' );
  var ResetButton = require( 'SCENERY_PHET/buttons/ResetButton' );
  var sceneryPhet = require( 'SCENERY_PHET/sceneryPhet' );
  var SceneryPhetA11yStrings = require( 'SCENERY_PHET/SceneryPhetA11yStrings' );
  var Shape = require( 'KITE/Shape' );
  var Tandem = require( 'TANDEM/Tandem' );
  var Utterance = require( 'SCENERY_PHET/accessibility/Utterance' );
  var utteranceQueue = require( 'SCENERY_PHET/accessibility/utteranceQueue' );

  // ifphetio
  var BooleanIO = require( 'ifphetio!PHET_IO/types/BooleanIO' );

  // constants
  var RESET_ALL_BUTTON_RADIUS = 24; // derived from the image files that were originally used for this button

  // strings
  var resetAllButtonNameString = require( 'string!SCENERY_PHET/ResetAllButton.name' );

  // a11y strings - not translatable
  var resetAllAlertString = SceneryPhetA11yStrings.resetAllAlertString.value;

  /**
   * @param {Object} [options]
   * @constructor
   */
  function ResetAllButton( options ) {

    options = _.extend( {
      radius: RESET_ALL_BUTTON_RADIUS,
      baseColor: PhetColorScheme.RESET_ALL_BUTTON_BASE_COLOR,
      arrowColor: 'white',
      tandem: Tandem.required,

      phetioDocumentation: 'The orange, round button that can be used to restore the initial state',

      // a11y
      innerContent: resetAllButtonNameString
    }, options );

    ResetButton.call( this, options );

    this.focusHighlight = new Shape().circle( 0, 0, options.radius + 5 );

    // @private - Mirrored property of `buttonModel.isFiringProperty`, but is phet-io instrumented.
    this.isFiringProperty = new DerivedProperty( [ this.buttonModel.isFiringProperty ], function( a ) { return a; }, {
      tandem: options.tandem.createTandem( 'isFiringProperty' ),
      phetioDocumentation: 'Temporarily becomes true while the Reset All button is firing.  Commonly used to disable audio effects during reset.',
      phetioType: DerivedPropertyIO( BooleanIO ),
      phetioState: false // this is a transient property based on user interaction, should not be stored in the state
    } );

    // a11y - when reset all button is fired, disable alerts so that there isn't an excessive stream of alerts
    // while many Properties are reset. When callbacks are ended for reset all, enable alerts again and announce an
    // alert that everything was reset.
    this.isFiringProperty.lazyLink( function( isFiring ) {
      utteranceQueue.enabled = !isFiring;

      !isFiring && utteranceQueue.addToBack( new Utterance( resetAllAlertString, {
        uniqueGroupId: 'resetAllButtonAlert'
      } ) );
    } );
  }

  sceneryPhet.register( 'ResetAllButton', ResetAllButton );

  return inherit( ResetButton, ResetAllButton, {

    /**
     * Make eligible for garbage collection.
     * @public
     */
    dispose: function() {

      this.isFiringProperty.dispose();

      ResetButton.prototype.dispose.call( this );
    }
  } );
} );
<|endoftext|>


<commit_before>// Per request from FAS Service Team 11/12/20, "Import Content" should be
// modified as follows:
//
// 1. Adds a notification advising faculty to exclude Calendar Events when
//    copying a course, since events will include old Zoom URLs that don't work.
// 2. Automatically sets the default option to "Select specific content" instead
//    of "All content" when copying a canvas course.
//
(function() {
    "use strict";

    function show_import_notification() {
        var content = document.querySelector("#content");
        var notification = document.createElement("div");
        notification.className = "ic-notification ic-notification--alert";
        notification.innerHTML =
            '
' +
                '' +
                'alert' +
            '
' +
            '
' +
                'Attention Spring 2020 Courses: ' +
                'Use "Select specific content" to exclude Calendar Events when copying from previous courses. Events will include old Zoom links that will not work in your new course. Learn how to exclude these items when importing your course content.' +
            '
';
        content.insertBefore(notification, content.firstChild);
    }

    function update_selective_import_value() {
        var radio = document.querySelector("#migrationConverterContainer input[type=radio][name=selective_import][value=true]");
        if(!radio) {
            return;
        }
        if(!radio.dataset.initialized) {
            radio.dataset.initialized = "yes";
            radio.checked = true;
            radio.click(); // simulating a click because the form validator doesn't recognize it as checked
        }
    }

    function watch_for_changes(el, callback) {
        if(!el) {
            return;
        }
        if (window.MutationObserver) {
            var observer = new MutationObserver(callback);
            observer.observe(el, {
                attributes: false,
                childList: true,
                subtree: true
            })
        }
        return observer;
    }

    if (/^\/courses\/\d+\/content_migrations/.test(window.location.pathname)) {
        show_import_notification();
        watch_for_changes(document.querySelector("#migrationConverterContainer"), function(mutationsList, observer) {
            update_selective_import_value();
        });
    }

})();
<commit_msg>Updated text on Course Import Content page for Fall 2021.<commit_after>// Per request from FAS Service Team 11/12/20, "Import Content" should be
// modified as follows:
//
// 1. Adds a notification advising faculty to exclude Calendar Events when
//    copying a course, since events will include old Zoom URLs that don't work.
// 2. Automatically sets the default option to "Select specific content" instead
//    of "All content" when copying a canvas course.
//
(function() {
    "use strict";

    function show_import_notification() {
        var content = document.querySelector("#content");
        var notification = document.createElement("div");
        notification.className = "ic-notification ic-notification--alert";
        notification.innerHTML =
            '
' +
                '' +
                'alert' +
            '
' +
            '
' +
                'Attention: Use "Select specific content" to exclude Calendar Events when copying from previous courses. Events will include old Zoom links that will not work in your new course. Learn how to exclude these items when importing your course content.' +
            '
';
        content.insertBefore(notification, content.firstChild);
    }

    function update_selective_import_value() {
        var radio = document.querySelector("#migrationConverterContainer input[type=radio][name=selective_import][value=true]");
        if(!radio) {
            return;
        }
        if(!radio.dataset.initialized) {
            radio.dataset.initialized = "yes";
            radio.checked = true;
            radio.click(); // simulating a click because the form validator doesn't recognize it as checked
        }
    }

    function watch_for_changes(el, callback) {
        if(!el) {
            return;
        }
        if (window.MutationObserver) {
            var observer = new MutationObserver(callback);
            observer.observe(el, {
                attributes: false,
                childList: true,
                subtree: true
            })
        }
        return observer;
    }

    if (/^\/courses\/\d+\/content_migrations/.test(window.location.pathname)) {
        show_import_notification();
        watch_for_changes(document.querySelector("#migrationConverterContainer"), function(mutationsList, observer) {
            update_selective_import_value();
        });
    }

})();
<|endoftext|>


<commit_before>// Copyright 2021, University of Colorado Boulder

/**
 * Auto-generated from modulify, DO NOT manually modify.
 */

import getStringModule from '../../chipper/js/getStringModule.js';
import fractionMatcher from './fractionMatcher.js';

const fractionMatcherStrings = getStringModule( 'FRACTION_MATCHER' );

fractionMatcher.register( 'fractionMatcherStrings', fractionMatcherStrings );

export default fractionMatcherStrings;
<commit_msg>update copyright dates from daily grunt work<commit_after>// Copyright 2020-2021, University of Colorado Boulder

/**
 * Auto-generated from modulify, DO NOT manually modify.
 */

import getStringModule from '../../chipper/js/getStringModule.js';
import fractionMatcher from './fractionMatcher.js';

const fractionMatcherStrings = getStringModule( 'FRACTION_MATCHER' );

fractionMatcher.register( 'fractionMatcherStrings', fractionMatcherStrings );

export default fractionMatcherStrings;
<|endoftext|>