<commit_before>/**
 *
 * SugarCRM Community Edition is a customer relationship management program developed by
 * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
 *
 * SuiteCRM is an extension to SugarCRM Community Edition developed by SalesAgility Ltd.
 * Copyright (C) 2011 - 2018 SalesAgility Ltd.
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License version 3 as published by the
 * Free Software Foundation with the addition of the following permission added
 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License along with
 * this program; if not, see http://www.gnu.org/licenses or write to the Free
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301 USA.
 *
 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
 *
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU Affero General Public License version 3.
 *
 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
 * these Appropriate Legal Notices must retain the display of the "Powered by
 * SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not
 * reasonably feasible for technical reasons, the Appropriate Legal Notices must
 * display the words "Powered by SugarCRM" and "Supercharged by SuiteCRM".
 */

if(!SUGAR.Emails) {
  SUGAR.Emails = {};
}

/**
 * @param {string} moduleName
 * @param {string} actionUrl
 * @param {function} successCallback
 * @param {function} errorCallback (optional)
 * @param {string} loadingTitle (optional)
 * @param {string} errorMessage (optional)
 */
SUGAR.Emails.handleSelectedListViewItems =  function(
  moduleName,
  actionUrl,
  successCallback,
  errorCallback,
  loadingTitle,
  errorMessage
) {

  if(typeof loadingTitle === 'undefined') {
    loadingTitle = SUGAR.language.translate('Emails', 'LBL_LOADING');
  }

  if(typeof errorMessage === 'undefined') {
    errorMessage = 'Error at selected emails handling.';
  }

  var mb = messageBox({backdrop: false});
  mb.setTitle(loadingTitle);
  mb.setBody('

');
  mb.hideFooter();
  mb.show();
  mb.on('cancel', function() {
    "use strict";
    mb.remove();
  });

  var query = JSON.parse($('[name=MassUpdate] [name=current_query_by_page]').val());
  var url = 'index.php?module=' + moduleName + '&action=' + actionUrl;

  var postOpts = {
    "inbound_email_record": query.inbound_email_record,
    "folders_id": query.folders_id,
    "folder": query.folder,
    "uid[]": []
  };

  if(document.MassUpdate.select_entire_list &&
    document.MassUpdate.select_entire_list.value == 1) {
    // Import all emails from mail box
    postOpts.all = true;
  } else {
    postOpts.all = false;
    // import only selected emails from inbox
    $('.listview-checkbox').each(function(i,v) {
      if($(v).is(':checked')) {
        postOpts['uid[]'].push(query.email_uids[i]);
      }
    });
  }

  $.post( url, postOpts).done(function (data) {
    var jsonData = JSON.parse(data);
    mb.hide();
    if(jsonData.response) {
      successCallback(jsonData);
    } else {
      if(errorCallback) {
        errorCallback(jsonData);
      } else {
        console.error(errorMessage + ' Please check the logs for details.');
      }
    }
  }).error(function (data) {
    mb.hide();
    console.error(data);
  });
};

$(document).ready(function () {

  var query = JSON.parse($('[name=current_query_by_page]').val());
  var jQueryBtnEmailsCurrentFolder = $('.btn-emails-current-folder');

  if(typeof query.folder === 'undefined' ||  query.folder === '') {
    jQueryBtnEmailsCurrentFolder.remove();
  } else if(query.folder === null) {
    jQueryBtnEmailsCurrentFolder.html('');
  } else {
    jQueryBtnEmailsCurrentFolder.text(query.folder);
  }

});<commit_msg>Fix sub-folders folder name<commit_after>/**
 *
 * SugarCRM Community Edition is a customer relationship management program developed by
 * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
 *
 * SuiteCRM is an extension to SugarCRM Community Edition developed by SalesAgility Ltd.
 * Copyright (C) 2011 - 2018 SalesAgility Ltd.
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License version 3 as published by the
 * Free Software Foundation with the addition of the following permission added
 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License along with
 * this program; if not, see http://www.gnu.org/licenses or write to the Free
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301 USA.
 *
 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
 *
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU Affero General Public License version 3.
 *
 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
 * these Appropriate Legal Notices must retain the display of the "Powered by
 * SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not
 * reasonably feasible for technical reasons, the Appropriate Legal Notices must
 * display the words "Powered by SugarCRM" and "Supercharged by SuiteCRM".
 */

if(!SUGAR.Emails) {
  SUGAR.Emails = {};
}

/**
 * @param {string} moduleName
 * @param {string} actionUrl
 * @param {function} successCallback
 * @param {function} errorCallback (optional)
 * @param {string} loadingTitle (optional)
 * @param {string} errorMessage (optional)
 */
SUGAR.Emails.handleSelectedListViewItems =  function(
  moduleName,
  actionUrl,
  successCallback,
  errorCallback,
  loadingTitle,
  errorMessage
) {

  if(typeof loadingTitle === 'undefined') {
    loadingTitle = SUGAR.language.translate('Emails', 'LBL_LOADING');
  }

  if(typeof errorMessage === 'undefined') {
    errorMessage = 'Error at selected emails handling.';
  }

  var mb = messageBox({backdrop: false});
  mb.setTitle(loadingTitle);
  mb.setBody('

');
  mb.hideFooter();
  mb.show();
  mb.on('cancel', function() {
    "use strict";
    mb.remove();
  });

  var query = JSON.parse($('[name=MassUpdate] [name=current_query_by_page]').val());
  var url = 'index.php?module=' + moduleName + '&action=' + actionUrl;

  var postOpts = {
    "inbound_email_record": query.inbound_email_record,
    "folders_id": query.folders_id,
    "folder": query.folder,
    "uid[]": []
  };

  if(document.MassUpdate.select_entire_list &&
    document.MassUpdate.select_entire_list.value == 1) {
    // Import all emails from mail box
    postOpts.all = true;
  } else {
    postOpts.all = false;
    // import only selected emails from inbox
    $('.listview-checkbox').each(function(i,v) {
      if($(v).is(':checked')) {
        postOpts['uid[]'].push(query.email_uids[i]);
      }
    });
  }

  $.post( url, postOpts).done(function (data) {
    var jsonData = JSON.parse(data);
    mb.hide();
    if(jsonData.response) {
      successCallback(jsonData);
    } else {
      if(errorCallback) {
        errorCallback(jsonData);
      } else {
        console.error(errorMessage + ' Please check the logs for details.');
      }
    }
  }).error(function (data) {
    mb.hide();
    console.error(data);
  });
};

$(document).ready(function () {

  $.ajax({
    type: "GET",
    cache: false,
    url: 'index.php?module=Emails&action=GetFolders'
  }).done(function (data) {
    let query = JSON.parse($('[name=current_query_by_page]').val());
    let jQueryBtnEmailsCurrentFolder = $('.btn-emails-current-folder');
    let response = JSON.parse(data);
    let responses = response.response;

    if(typeof query.folder === 'undefined' ||  query.folder === '') {
      jQueryBtnEmailsCurrentFolder.remove();
    } else if(query.folder === null) {
      jQueryBtnEmailsCurrentFolder.html('');
    }

    for (let i = 0; i < (responses.length); i++) {

      if (responses[i].id === query.folders_id) {
        jQueryBtnEmailsCurrentFolder.text(responses[(i)].text);
      } else if (responses[i].id === query.inbound_email_record) {
        let regExp = /\(([^)]+)\)/;
        let match = regExp.exec(responses[(i)].text);
        jQueryBtnEmailsCurrentFolder.text(query.folder + ' ' + match[0]);
      }
    }
  });
});<|endoftext|>


<commit_before>'use strict';

// CONSTANTS

const WEEKDAYS = [
  '星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六',
];
const DRINKS = [
  '水', '茶', '红茶', '绿茶', '咖啡', '奶茶', '可乐', '鲜奶', '豆奶', '果汁',
  '果味汽水', '苏打水', '运动饮料', '酸奶', '酒',
];
const DIRECTIONS = [
  '北方', '东方', '南方', '西方', '东北方', '东南方', '西南方', '西北方',
];
const GODDESS_SYMBOL = '★★★★★☆☆☆☆☆';
const VARIABLES = [
 'jieguo', 'huodong', 'pay', 'expire', 'zhangdan', 'every', 'free',
 'i1', 'a', 'virtual', 'ad', 'spider', 'mima', 'pass', 'ui',
];
const TOOLS = [
  'Eclipse写程序', 'MSOffice写文档', '记事本写程序',
  'Windows8', 'Linux', 'MacOS', 'IE', 'Android设备', 'iOS设备',
];

function tool() {
  return TOOLS[random(12) % TOOLS.length];
}

function variable() {
  return VARIABLES[random(11) % VARIABLES.length];
}

function linesCount() {
  return random(12) % 247 + 30;
}

function asActivityName(name) {
  return name
    .replace('%t', tool())
    .replace('%v', variable())
    .replace('%l', linesCount());
}

const ACTIVITES = [];
function defActivity(name, reasonGood, reasonBad, forWeekend) {
  const activity = {name, reasonGood, reasonBad, forWeekend};
  ACTIVITES.push(activity);

  activity.asGood = () => {
    return {
      name: asActivityName(name),
      reason: reasonGood,
    };
  };
  activity.asBad = () => {
    return {
      name: asActivityName(name),
      reason: reasonBad,
    };
  };

  return activity;
}
defActivity('写单元测试', '写单元测试将减少出错', '写单元测试会降低你的开发效率', false);
defActivity('洗澡', '你几天没洗澡了？', '会把设计方面的灵感洗掉', true);
defActivity('锻炼一下身体', '', '能量没消耗多少，吃得却更多', true);
defActivity('抽烟', '抽烟有利于提神，增加思维敏捷', '除非你活够了，死得早点没关系', true);
defActivity('白天上线', '今天白天上线是安全得', '可能导致灾难性后果', false);
defActivity('重构', '代码质量得到提高', '你很有可能会陷入泥潭', false);
defActivity('使用%t', '你看起来更有品味', '别人会觉得你在装逼', false);
defActivity('跳槽', '该放手时就放手', '鉴于当前的经济形式，你的下一份工作未必比现在强', false);
defActivity('招人', '你面前这位有成为牛人的潜质', '这人会写程序吗？', false);
defActivity('面试', '面试官今天心情很好', '面试官不爽，会拿你出气', false);
defActivity('提交辞职申请', '公司找到了一个比你更能干更便宜的家伙，巴不得你赶快滚蛋', '鉴于当前的经济形势，你的下一份工作未必比现在强', false);
defActivity('申请加薪', '老板今天心情很好', '公司正在考虑裁员', false);
defActivity('晚上加班', '晚上是程序员精神最好的时候', '', true);
defActivity('在妹子面前吹牛', '改善你矮穷挫的形象', '会被识破', true);
defActivity('撸管', '避免缓冲区溢出', '强撸灰飞烟灭', true);
defActivity('浏览成人网站', '重拾对生活的信心', '你会心神不宁', true);
defActivity('命名变量%v', '', '', false);
defActivity('写超过%l行的方法', '你的代码组织的很好，长一点没关系', '你的代码将混乱不堪，你自己都看不懂', false);
defActivity('提交代码', '遇到冲突的几率是最低的', '你遇到的一大堆冲突让你觉得自己是不是时间穿越了', false);
defActivity('代码复审', '发现重要问题的几率大大增加', '你什么问题都发现不了，白白浪费时间', false);
defActivity('开会', '写代码之余放松一下打个盹，有益健康', '小心被扣屎盆子背黑锅', false);
defActivity('打DOTA', '你将如有神助', '你会被虐得很惨', true);
defActivity('晚上上线', '晚上是程序员精神最好的时候', '你白天已经筋疲力尽了', false);
defActivity('修复BUG', '你今天对BUG的嗅觉大大提高', '新产生的BUG将比修复的更多', false);
defActivity('设计评审', '设计评审会议将变成头脑风暴', '人人筋疲力尽，评审就这么过了', false);
defActivity('需求评审', '', '', false);
defActivity('上微博', '今天发生的事不能错过', '今天的微博充满负能量', true);
defActivity('上AB站', '还需要理由吗？', '满屏兄贵亮瞎你的眼', true);
defActivity('玩FlappyBird', '今天破纪录的几率很高', '除非你想玩到把手机砸了', true);

function merge(...things) {
  const o = {};

  for (let thing of things) {
    for (let k in thing) {
      o[k] = thing[k];
    }
  }

  return o;
}

function today() {
  const date = new Date();

  return {
    year: date.getYear() + 1900,
    month: date.getMonth(),
    day: date.getDate(),
    dayOfWeek: WEEKDAYS[date.getDay()],
  };
}

function todaySeed() {
  const date = today();
  return date.year * 1000 + date.month * 100 + date.day;
}

function random(seed) {
  const modulo = 11117;

  let n = todaySeed() % modulo;
  for (let i = 0; i < seed + 100; i++) n = n * n % modulo;
  return n;
}

function pickItems(items, requiredCount) {
  let picked = items.slice();
  for (let removedCount = 0;
       removedCount < items.length - requiredCount;
       removedCount++) {
    const toRemove = random(removedCount) % picked.length;
    picked = picked.slice(0, toRemove).concat(picked.slice(toRemove + 1));
  }

  return picked;
}

function activites() {
  const isWeekend = ['星期六', '星期日'].indexOf(today().dayOfWeek) !== -1;
  let availableActivites = ACTIVITES;
  if (isWeekend) {
    availableActivites = availableActivites.filter((i) => i.forWeekend);
  }

  const goodActivitesCount = random(98) % 3 + 2;
  const badActivitesCount = random(87) % 3 + 2;
  const pickedActivites = pickItems(
    availableActivites,
    goodActivitesCount + badActivitesCount
  );

  const goodActivites = pickedActivites
    .slice(0, goodActivitesCount)
    .map((i) => i.asGood());
  const badActivites = pickedActivites
    .slice(goodActivitesCount + 1)
    .map((i) => i.asBad());

  return {activites: {good: goodActivites, bad: badActivites}};
}

function drinkings() {
  return {drinkings: pickItems(DRINKS, 2)};
}

function directions() {
  return {directions: DIRECTIONS[random(2) % DIRECTIONS.length]};
}

function goddess() {
  const maxLevel = GODDESS_SYMBOL.length / 2;
  const level = random(maxLevel + 1) % maxLevel;
  return {
    godddess: {
      level,
      symbol: GODDESS_SYMBOL.slice(maxLevel - level, maxLevel * 2 - level),
    },
  };
}

function huangli() {
  return merge(
    today(),
    activites(),
    drinkings(),
    directions(),
    goddess()
  );
};

module.exports = {
  random,

  huangli,
  today,
  activites,
  drinkings,
  directions,
  goddess,
};
<commit_msg>fix: typo.<commit_after>'use strict';

// CONSTANTS

const WEEKDAYS = [
  '星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六',
];
const DRINKS = [
  '水', '茶', '红茶', '绿茶', '咖啡', '奶茶', '可乐', '鲜奶', '豆奶', '果汁',
  '果味汽水', '苏打水', '运动饮料', '酸奶', '酒',
];
const DIRECTIONS = [
  '北方', '东方', '南方', '西方', '东北方', '东南方', '西南方', '西北方',
];
const GODDESS_SYMBOL = '★★★★★☆☆☆☆☆';
const VARIABLES = [
 'jieguo', 'huodong', 'pay', 'expire', 'zhangdan', 'every', 'free',
 'i1', 'a', 'virtual', 'ad', 'spider', 'mima', 'pass', 'ui',
];
const TOOLS = [
  'Eclipse写程序', 'MSOffice写文档', '记事本写程序',
  'Windows8', 'Linux', 'MacOS', 'IE', 'Android设备', 'iOS设备',
];

function tool() {
  return TOOLS[random(12) % TOOLS.length];
}

function variable() {
  return VARIABLES[random(11) % VARIABLES.length];
}

function linesCount() {
  return random(12) % 247 + 30;
}

function asActivityName(name) {
  return name
    .replace('%t', tool())
    .replace('%v', variable())
    .replace('%l', linesCount());
}

const ACTIVITES = [];
function defActivity(name, reasonGood, reasonBad, forWeekend) {
  const activity = {name, reasonGood, reasonBad, forWeekend};
  ACTIVITES.push(activity);

  activity.asGood = () => {
    return {
      name: asActivityName(name),
      reason: reasonGood,
    };
  };
  activity.asBad = () => {
    return {
      name: asActivityName(name),
      reason: reasonBad,
    };
  };

  return activity;
}
defActivity('写单元测试', '写单元测试将减少出错', '写单元测试会降低你的开发效率', false);
defActivity('洗澡', '你几天没洗澡了？', '会把设计方面的灵感洗掉', true);
defActivity('锻炼一下身体', '', '能量没消耗多少，吃得却更多', true);
defActivity('抽烟', '抽烟有利于提神，增加思维敏捷', '除非你活够了，死得早点没关系', true);
defActivity('白天上线', '今天白天上线是安全得', '可能导致灾难性后果', false);
defActivity('重构', '代码质量得到提高', '你很有可能会陷入泥潭', false);
defActivity('使用%t', '你看起来更有品味', '别人会觉得你在装逼', false);
defActivity('跳槽', '该放手时就放手', '鉴于当前的经济形式，你的下一份工作未必比现在强', false);
defActivity('招人', '你面前这位有成为牛人的潜质', '这人会写程序吗？', false);
defActivity('面试', '面试官今天心情很好', '面试官不爽，会拿你出气', false);
defActivity('提交辞职申请', '公司找到了一个比你更能干更便宜的家伙，巴不得你赶快滚蛋', '鉴于当前的经济形势，你的下一份工作未必比现在强', false);
defActivity('申请加薪', '老板今天心情很好', '公司正在考虑裁员', false);
defActivity('晚上加班', '晚上是程序员精神最好的时候', '', true);
defActivity('在妹子面前吹牛', '改善你矮穷挫的形象', '会被识破', true);
defActivity('撸管', '避免缓冲区溢出', '强撸灰飞烟灭', true);
defActivity('浏览成人网站', '重拾对生活的信心', '你会心神不宁', true);
defActivity('命名变量%v', '', '', false);
defActivity('写超过%l行的方法', '你的代码组织的很好，长一点没关系', '你的代码将混乱不堪，你自己都看不懂', false);
defActivity('提交代码', '遇到冲突的几率是最低的', '你遇到的一大堆冲突让你觉得自己是不是时间穿越了', false);
defActivity('代码复审', '发现重要问题的几率大大增加', '你什么问题都发现不了，白白浪费时间', false);
defActivity('开会', '写代码之余放松一下打个盹，有益健康', '小心被扣屎盆子背黑锅', false);
defActivity('打DOTA', '你将如有神助', '你会被虐得很惨', true);
defActivity('晚上上线', '晚上是程序员精神最好的时候', '你白天已经筋疲力尽了', false);
defActivity('修复BUG', '你今天对BUG的嗅觉大大提高', '新产生的BUG将比修复的更多', false);
defActivity('设计评审', '设计评审会议将变成头脑风暴', '人人筋疲力尽，评审就这么过了', false);
defActivity('需求评审', '', '', false);
defActivity('上微博', '今天发生的事不能错过', '今天的微博充满负能量', true);
defActivity('上AB站', '还需要理由吗？', '满屏兄贵亮瞎你的眼', true);
defActivity('玩FlappyBird', '今天破纪录的几率很高', '除非你想玩到把手机砸了', true);

function merge(...things) {
  const o = {};

  for (let thing of things) {
    for (let k in thing) {
      o[k] = thing[k];
    }
  }

  return o;
}

function today() {
  const date = new Date();

  return {
    year: date.getYear() + 1900,
    month: date.getMonth(),
    day: date.getDate(),
    dayOfWeek: WEEKDAYS[date.getDay()],
  };
}

function todaySeed() {
  const date = today();
  return date.year * 1000 + date.month * 100 + date.day;
}

function random(seed) {
  const modulo = 11117;

  let n = todaySeed() % modulo;
  for (let i = 0; i < seed + 100; i++) n = n * n % modulo;
  return n;
}

function pickItems(items, requiredCount) {
  let picked = items.slice();
  for (let removedCount = 0;
       removedCount < items.length - requiredCount;
       removedCount++) {
    const toRemove = random(removedCount) % picked.length;
    picked = picked.slice(0, toRemove).concat(picked.slice(toRemove + 1));
  }

  return picked;
}

function activites() {
  const isWeekend = ['星期六', '星期日'].indexOf(today().dayOfWeek) !== -1;
  let availableActivites = ACTIVITES;
  if (isWeekend) {
    availableActivites = availableActivites.filter((i) => i.forWeekend);
  }

  const goodActivitesCount = random(98) % 3 + 2;
  const badActivitesCount = random(87) % 3 + 2;
  const pickedActivites = pickItems(
    availableActivites,
    goodActivitesCount + badActivitesCount
  );

  const goodActivites = pickedActivites
    .slice(0, goodActivitesCount)
    .map((i) => i.asGood());
  const badActivites = pickedActivites
    .slice(goodActivitesCount + 1)
    .map((i) => i.asBad());

  return {activites: {good: goodActivites, bad: badActivites}};
}

function drinkings() {
  return {drinkings: pickItems(DRINKS, 2)};
}

function directions() {
  return {directions: DIRECTIONS[random(2) % DIRECTIONS.length]};
}

function goddess() {
  const maxLevel = GODDESS_SYMBOL.length / 2;
  const level = random(maxLevel + 1) % maxLevel;
  return {
    goddess: {
      level,
      symbol: GODDESS_SYMBOL.slice(maxLevel - level, maxLevel * 2 - level),
    },
  };
}

function huangli() {
  return merge(
    today(),
    activites(),
    drinkings(),
    directions(),
    goddess()
  );
};

module.exports = {
  random,

  huangli,
  today,
  activites,
  drinkings,
  directions,
  goddess,
};
<|endoftext|>


<commit_before>module.exports= {
    greetMsg: 'Hi! I am PMKB Bot. I can retrieve information about clinical cancer interpretations from my database.',
    disclaimerMsg: 'PMKB Bot is currently in Beta. By using this bot, you assume full responsibility for all risks. The Englander Institute for Precision Medicine makes no guarantee of the comprehensiveness, reliability or accuracy of the information on this website and the IPM assumes no responsibility for errors in the information associated with this web site. Healthcare providers and patients must integrate all clinical and laboratory findings as well as information from a variety of sources before deciding on appropriate clinical care options.',
    gettingStartedMsg: 'Type your query to get started. You can also check some examples of what you can do by clicking below.',
    exitMsg: 'Thank you for using PMKB. Enjoy your day :)',
    errorMsg: "I'm sorry, I didn't quite get that. Could you please repeat your query making sure to include a gene name, variant, tissue type, or tumor type? If unsure type 'help'",
    whoAmI: "I am the PMKB Bot."
    exBrca1: "Tell me more about BRCA1.",
    exVariant: "What do you know about BRAF V600E?",
    exComplex: "Give me interpretations for EGFR in lung cancer.",
    exTumor: "What do you know about Acute Myeloid Leukemia?",
    Examples: `Here are some examples: ${exVariant}, ${exComplex}, ${exTumor}`
}
<commit_msg>missing comma in prompts<commit_after>module.exports= {
    greetMsg: 'Hi! I am PMKB Bot. I can retrieve information about clinical cancer interpretations from my database.',
    disclaimerMsg: 'PMKB Bot is currently in Beta. By using this bot, you assume full responsibility for all risks. The Englander Institute for Precision Medicine makes no guarantee of the comprehensiveness, reliability or accuracy of the information on this website and the IPM assumes no responsibility for errors in the information associated with this web site. Healthcare providers and patients must integrate all clinical and laboratory findings as well as information from a variety of sources before deciding on appropriate clinical care options.',
    gettingStartedMsg: 'Type your query to get started. You can also check some examples of what you can do by clicking below.',
    exitMsg: 'Thank you for using PMKB. Enjoy your day :)',
    errorMsg: "I'm sorry, I didn't quite get that. Could you please repeat your query making sure to include a gene name, variant, tissue type, or tumor type? If unsure type 'help'",
    whoAmI: "I am the PMKB Bot.",
    exBrca1: "Tell me more about BRCA1.",
    exVariant: "What do you know about BRAF V600E?",
    exComplex: "Give me interpretations for EGFR in lung cancer.",
    exTumor: "What do you know about Acute Myeloid Leukemia?",
    Examples: `Here are some examples: ${exVariant}, ${exComplex}, ${exTumor}`
}
<|endoftext|>


<commit_before>/**
* Adds cue points support
*/
( function( mw, $ ) { "use strict";

mw.KCuePoints = function( embedPlayer ){
	return this.init( embedPlayer );
};
mw.KCuePoints.prototype = {

	// The bind postfix:
	bindPostfix: '.kCuePoints',
	midCuePointsArray: [],
	liveCuePointsIntervalId: null,

	init: function( embedPlayer ){
		var _this = this;
		// Remove any old bindings:
		this.destroy();
		// Setup player ref:
		this.embedPlayer = embedPlayer;

		// Process cue points
		embedPlayer.bindHelper('KalturaSupport_CuePointsReady' + this.bindPostfix, function() {
			_this.processCuePoints();
			// Add player bindings:
			_this.addPlayerBindings();
			//Set live cuepoint polling
			if (mw.getConfig("EmbedPlayer.LiveCuepoints")){
				_this.requestLiveCuepoints();
			}
		});
	},
	destroy: function(){
		if (this.liveCuePointsIntervalId) {
			clearInterval( this.liveCuePointsIntervalId );
			this.liveCuePointsIntervalId = null;
		}
		$( this.embedPlayer ).unbind( this.bindPostfix );
	},
	/*
	 * Trigger Pre/Post cue points and create Mid cue points array
	 */
	processCuePoints: function() {
		var _this = this;
		var cuePoints = this.getCuePoints();
		this.requestThumbAsset(cuePoints, function(){
			_this.embedPlayer.triggerHelper( 'KalturaSupport_ThumbCuePointsReady' );
		});
		// Create new array with midrolls only
		var newCuePointsArray = [];
		$.each( cuePoints, function( idx, cuePoint ){
			if( _this.getVideoAdType( cuePoint ) == 'pre' || _this.getVideoAdType( cuePoint ) == 'post' ) {
				_this.triggerCuePoint( cuePoint );
			} else {
				// Midroll
				if (cuePoint.cuePointType != "eventCuePoint.Event") {
					newCuePointsArray.push( cuePoint );
				}
			}
		});

		this.midCuePointsArray = newCuePointsArray;
	},
	requestThumbAsset: function(cuePoints, callback){
		var _this = this;
		var requestArray = [];
		var responseArray = [];
		var requestCuePoints = cuePoints || this.getCuePoints();
		var thumbCuePoint = $.grep(requestCuePoints, function(cuePoint){
			return (cuePoint.cuePointType == 'thumbCuePoint.Thumb');
		});

		//Create request data only for cuepoints that have assetId
		$.each(thumbCuePoint, function(index, item) {
			requestArray.push(
				{
					'service': 'thumbAsset',
					'action': 'getUrl',
					'id': item.assetId
				}
			);
			responseArray[index] = item;
		});

		if (requestArray.length){
			// do the api request
			this.getKalturaClient().doRequest( requestArray, function ( data ) {
				// Validate result
				$.each(data, function(index, res) {
					if ( !_this.isValidResult( res ) ) {
						data[index] = null;
					}
				});
				$.each(thumbCuePoint, function(index, item){
					item.thumbnailUrl = data[index];
				});
				if (callback){
					callback();
				}
			} );
		} else {
			if (callback){
				callback();
			}
		}
	},
	requestLiveCuepoints: function(){
		var _this = this;

		// Create associative cuepoint array to enable comparing new cuepoints vs existing ones
		var cuePoints = this.getCuePoints();
		this.associativeCuePoints = {};
		$.each( cuePoints, function ( index, cuePoint ) {
			_this.associativeCuePoints[cuePoint.id] = cuePoint;
		} );

		//Start live cuepoint pulling
		this.liveCuePointsIntervalId = setInterval(function(){
			var entryId = _this.embedPlayer.kentryid;
			var lastUpdatedAt = _this.getLastUpdateTime() + 1;
			_this.getKalturaClient().doRequest({
					'service': 'cuepoint_cuepoint',
					'action': 'list',
					'filter:entryIdEqual': entryId,
					'filter:objectType':'KalturaCuePointFilter',
					'filter:cuePointTypeEqual':	'thumbCuePoint.Thumb',
					'filter:updatedAtGreaterThanOrEqual' : lastUpdatedAt
				},
				function( data ){
					// if an error pop out:
					if( !data || data.code ){
						// todo: add error handling
						mw.log("Error:: KCuePoints could not retrieve live cuepoints");
						return ;
					}
					_this.updateCuePoints( data.objects );
					_this.embedPlayer.triggerHelper( 'KalturaSupport_CuePointsUpdated', [data.totalCount] );
				}
			);
		}, mw.getConfig("EmbedPlayer.LiveCuepointsRequestInterval") || 10000);
	},
	updateCuePoints: function( rawCuePoints ){
		if (rawCuePoints.length > 0) {
			var _this = this;

			var associativeRawCuePoints = {};
			$.each( rawCuePoints, function ( index, cuePoint ) {
				associativeRawCuePoints[cuePoint.id] = cuePoint;
			} );

			var updatedCuePoints = [];
			//Only add new cuepoints or existing cuepoints which have a newer updateAt value
			$.each( associativeRawCuePoints, function ( index, rawCuePoint ) {
				if ( (!_this.associativeCuePoints[index]) ||
					 ( _this.associativeCuePoints[index] &&
					   _this.associativeCuePoints[index].updatedAt < rawCuePoint.updatedAt ) ) {
					_this.associativeCuePoints[index] = rawCuePoint;
					updatedCuePoints.push( rawCuePoint );
				}
			} );

			if ( updatedCuePoints.length > 0 ) {
				var cuePoints = this.getCuePoints();
				//update cuepoints
				$.merge(cuePoints, updatedCuePoints);
				//update midpoint cuepoints
				$.merge(this.midCuePointsArray, updatedCuePoints);
				//Request thumb asset only for new cuepoints
				this.requestThumbAsset(updatedCuePoints, function(){
					_this.embedPlayer.triggerHelper( 'KalturaSupport_ThumbCuePointsUpdated', [updatedCuePoints] );
				});
				// sort the cuePoitns by startTime:
				this.midCuePointsArray.sort( function ( a, b ) {
					return a.startTime - b.startTime;
				} );
			}
		}
	},
	getLastUpdateTime: function(){
		var cuePoints = this.getCuePoints();
		var lastUpdateTime= -1;
		$.each(cuePoints, function(key, cuePoint){
			if (lastUpdateTime < cuePoint.updatedAt){
				lastUpdateTime = cuePoint.updatedAt;
			}
		});
		return lastUpdateTime;
	},
	getKalturaClient: function() {
		if( ! this.kClient ) {
			this.kClient = mw.kApiGetPartnerClient( this.embedPlayer.kwidgetid );
		}
		return this.kClient;
	},
	isValidResult: function( data ){
		// Check if we got error
		if( !data
			||
			( data.code && data.message )
			){
			return false;
		}
		return true;
	},
	/**
	 * Adds player cue point bindings
	 */
	addPlayerBindings: function(){
		var _this = this;
		// Get first cue point
		var currentCuePoint = this.getNextCuePoint(0);
		var embedPlayer = this.embedPlayer;

		// Don't add any bindings if no cuePoint exists )
		if( !currentCuePoint ){
			return ;
		}

		// Destroy on changeMedia
		$( embedPlayer ).bind( 'onChangeMedia' + this.bindPostfix, function(){
			_this.destroy();
		});

		// Bind to monitorEvent to trigger the cue points events and update he nextCuePoint
		$( embedPlayer ).bind(
				"monitorEvent" + this.bindPostfix +
				" seeked" + this.bindPostfix +
				" onplay" + this.bindPostfix +
				" KalturaSupport_ThumbCuePointsUpdated" + this.bindPostfix,
			function() {
				var currentTime = embedPlayer.currentTime * 1000;
				// Check if the currentCuePoint exists
				if( currentCuePoint && currentTime > currentCuePoint.startTime && embedPlayer._propagateEvents ){
					// Make a copy of the cue point to be triggered.
					// Sometimes the trigger can result in monitorEvent being called and an
					// infinite loop ( ie ad network error, no ad received, and restore player calling monitor() )
					var cuePointToBeTriggered = $.extend( {}, currentCuePoint);
					// Trigger the cue point
					_this.triggerCuePoint( cuePointToBeTriggered );
				}
				// Update the current Cue Point to the "next" cue point
				currentCuePoint = _this.getNextCuePoint( currentTime );
			}
		);
	},
	getEndTime: function(){
		return this.embedPlayer.evaluate('{mediaProxy.entry.msDuration}');
	},
	getCuePoints: function(){
		if( ! this.embedPlayer.rawCuePoints || ! this.embedPlayer.rawCuePoints.length ){
			return [];
		}
		return this.embedPlayer.rawCuePoints;
	},
	/**
	* Returns the next cuePoint object for requested time
	* @param {Number} time Time in milliseconds
	*/
	getNextCuePoint: function( time ){
		if (!isNaN(time) && time >= 0) {
			var cuePoints = this.midCuePointsArray;
			// Start looking for the cue point via time, return first match:
			for ( var i = 0; i < cuePoints.length; i++ ) {
				if ( cuePoints[i].startTime >= time ) {
					return cuePoints[i];
				}
			}
		}
		// No cue point found in range return false:
		return false;
	},
	/**
	 * Triggers the given cue point
	 * @param (Object) Cue Point object
	 **/
	triggerCuePoint: function( rawCuePoint ) {
		/**
		 *  We need different events for each cue point type
		 */
		var eventName;
		/*
		 * Evaluate cuePoint sourceURL strings ( used for VAST property substitutions )
		 */
		rawCuePoint.sourceUrl = this.embedPlayer.evaluate( rawCuePoint.sourceUrl );

		/*
		 * The cue point object is wrapped with another object that has context property.
		 * We used that property so that the different plugins will know the context of the ad
		 * In case the cue point is not a adOpportunity their will be no context
		 *
		 * This matches the KDP implementation
		 * */
		var cuePointWrapper = {
			'cuePoint' : rawCuePoint
		};
		if( rawCuePoint.cuePointType == 'codeCuePoint.Code' || rawCuePoint.cuePointType == 'thumbCuePoint.Thumb' ) {
			// Code type cue point ( make it easier for people grepping the code base for an event )
			eventName = 'KalturaSupport_CuePointReached';
		} else if( rawCuePoint.cuePointType == 'adCuePoint.Ad' ) {
			// Ad type cue point
			eventName = 'KalturaSupport_AdOpportunity';
			cuePointWrapper.context = this.getVideoAdType( rawCuePoint );
		} else {
			// Ignore all others cue points types
			return ;
		}
		mw.log('mw.KCuePoints :: Trigger event: ' + eventName + ' - ' + rawCuePoint.cuePointType + ' at: ' + rawCuePoint.startTime );
		$( this.embedPlayer ).trigger(  eventName, cuePointWrapper );
		// TOOD "midSequenceComplete"
	},

	// Get Ad Type from Cue Point
	getVideoAdType: function( rawCuePoint ) {
		if( rawCuePoint.startTime === 0 ) {
			return 'pre';
		} else if( rawCuePoint.startTime == this.getEndTime() ) {
			return 'post';
		} else {
			return 'mid';
		}
		mw.log("Error:: KCuePoints could not determine adType");
	},
	/**
	 * Accept a cuePoint wrapper
	 * @param cuePointWrapper
	 * @return
	 */
	getAdSlotType: function( cuePointWrapper ) {
		if( cuePointWrapper.cuePoint.adType == 1 ) {
			return this.getVideoAdType( cuePointWrapper.cuePoint ) + 'roll';
		} else {
			return 'overlay';
		}
	},
	getRawAdSlotType: function( rawCuePoint ){
		if( rawCuePoint.adType == 1 ) {
			return this.getVideoAdType( rawCuePoint ) + 'roll';
		} else {
			return 'overlay';
		}
	},

	// Returns the number of CuePoints by type
	// @filter(optional) - string | one of: 'preroll', 'midroll', 'postroll', 'overlay'
	getCuePointsCount: function( filter ) {
		var _this = this;
		var cuePoints = this.getCuePoints();

		// No cue points, return zero
		if( !cuePoints )
			return 0;

		// No filter, return all cue points
		if( !filter )
			return  cuePoints.length;

		var totalResults = {
			'preroll': 0,
			'midroll': 0,
			'postroll': 0,
			'overlay': 0
		};

		$.each(cuePoints, function( idx, rawCuePoint) {
			totalResults[ _this.getRawAdSlotType( rawCuePoint ) ]++;
		});

		// return count by filter
		if( filter && totalResults[ filter ] ) {
			return totalResults[ filter ];
		}
		// anything else, return zero
		return 0;
	}
};

} )( window.mw, window.jQuery );<commit_msg>FEC-2201 #comment Fix wrong cuepoint trigger on seek #time 4h<commit_after>/**
* Adds cue points support
*/
( function( mw, $ ) { "use strict";

mw.KCuePoints = function( embedPlayer ){
	return this.init( embedPlayer );
};
mw.KCuePoints.prototype = {

	// The bind postfix:
	bindPostfix: '.kCuePoints',
	midCuePointsArray: [],
	liveCuePointsIntervalId: null,

	init: function( embedPlayer ){
		var _this = this;
		// Remove any old bindings:
		this.destroy();
		// Setup player ref:
		this.embedPlayer = embedPlayer;

		// Process cue points
		embedPlayer.bindHelper('KalturaSupport_CuePointsReady' + this.bindPostfix, function() {
			_this.processCuePoints();
			// Add player bindings:
			_this.addPlayerBindings();
			//Set live cuepoint polling
			if (mw.getConfig("EmbedPlayer.LiveCuepoints")){
				_this.requestLiveCuepoints();
			}
		});
	},
	destroy: function(){
		if (this.liveCuePointsIntervalId) {
			clearInterval( this.liveCuePointsIntervalId );
			this.liveCuePointsIntervalId = null;
		}
		$( this.embedPlayer ).unbind( this.bindPostfix );
	},
	/*
	 * Trigger Pre/Post cue points and create Mid cue points array
	 */
	processCuePoints: function() {
		var _this = this;
		var cuePoints = this.getCuePoints();
		this.requestThumbAsset(cuePoints, function(){
			_this.embedPlayer.triggerHelper( 'KalturaSupport_ThumbCuePointsReady' );
		});
		// Create new array with midrolls only
		var newCuePointsArray = [];
		$.each( cuePoints, function( idx, cuePoint ){
			if( _this.getVideoAdType( cuePoint ) == 'pre' || _this.getVideoAdType( cuePoint ) == 'post' ) {
				_this.triggerCuePoint( cuePoint );
			} else {
				// Midroll
				if (cuePoint.cuePointType != "eventCuePoint.Event") {
					newCuePointsArray.push( cuePoint );
				}
			}
		});

		this.midCuePointsArray = newCuePointsArray;
	},
	requestThumbAsset: function(cuePoints, callback){
		var _this = this;
		var requestArray = [];
		var responseArray = [];
		var requestCuePoints = cuePoints || this.getCuePoints();
		var thumbCuePoint = $.grep(requestCuePoints, function(cuePoint){
			return (cuePoint.cuePointType == 'thumbCuePoint.Thumb');
		});

		//Create request data only for cuepoints that have assetId
		$.each(thumbCuePoint, function(index, item) {
			requestArray.push(
				{
					'service': 'thumbAsset',
					'action': 'getUrl',
					'id': item.assetId
				}
			);
			responseArray[index] = item;
		});

		if (requestArray.length){
			// do the api request
			this.getKalturaClient().doRequest( requestArray, function ( data ) {
				// Validate result
				$.each(data, function(index, res) {
					if ( !_this.isValidResult( res ) ) {
						data[index] = null;
					}
				});
				$.each(thumbCuePoint, function(index, item){
					item.thumbnailUrl = data[index];
				});
				if (callback){
					callback();
				}
			} );
		} else {
			if (callback){
				callback();
			}
		}
	},
	requestLiveCuepoints: function(){
		var _this = this;

		// Create associative cuepoint array to enable comparing new cuepoints vs existing ones
		var cuePoints = this.getCuePoints();
		this.associativeCuePoints = {};
		$.each( cuePoints, function ( index, cuePoint ) {
			_this.associativeCuePoints[cuePoint.id] = cuePoint;
		} );

		//Start live cuepoint pulling
		this.liveCuePointsIntervalId = setInterval(function(){
			var entryId = _this.embedPlayer.kentryid;
			var lastUpdatedAt = _this.getLastUpdateTime() + 1;
			_this.getKalturaClient().doRequest({
					'service': 'cuepoint_cuepoint',
					'action': 'list',
					'filter:entryIdEqual': entryId,
					'filter:objectType':'KalturaCuePointFilter',
					'filter:cuePointTypeEqual':	'thumbCuePoint.Thumb',
					'filter:updatedAtGreaterThanOrEqual' : lastUpdatedAt
				},
				function( data ){
					// if an error pop out:
					if( !data || data.code ){
						// todo: add error handling
						mw.log("Error:: KCuePoints could not retrieve live cuepoints");
						return ;
					}
					_this.updateCuePoints( data.objects );
					_this.embedPlayer.triggerHelper( 'KalturaSupport_CuePointsUpdated', [data.totalCount] );
				}
			);
		}, mw.getConfig("EmbedPlayer.LiveCuepointsRequestInterval") || 10000);
	},
	updateCuePoints: function( rawCuePoints ){
		if (rawCuePoints.length > 0) {
			var _this = this;

			var associativeRawCuePoints = {};
			$.each( rawCuePoints, function ( index, cuePoint ) {
				associativeRawCuePoints[cuePoint.id] = cuePoint;
			} );

			var updatedCuePoints = [];
			//Only add new cuepoints or existing cuepoints which have a newer updateAt value
			$.each( associativeRawCuePoints, function ( index, rawCuePoint ) {
				if ( (!_this.associativeCuePoints[index]) ||
					 ( _this.associativeCuePoints[index] &&
					   _this.associativeCuePoints[index].updatedAt < rawCuePoint.updatedAt ) ) {
					_this.associativeCuePoints[index] = rawCuePoint;
					updatedCuePoints.push( rawCuePoint );
				}
			} );

			if ( updatedCuePoints.length > 0 ) {
				var cuePoints = this.getCuePoints();
				//update cuepoints
				$.merge(cuePoints, updatedCuePoints);
				//update midpoint cuepoints
				$.merge(this.midCuePointsArray, updatedCuePoints);
				//Request thumb asset only for new cuepoints
				this.requestThumbAsset(updatedCuePoints, function(){
					_this.embedPlayer.triggerHelper( 'KalturaSupport_ThumbCuePointsUpdated', [updatedCuePoints] );
				});
				// sort the cuePoitns by startTime:
				this.midCuePointsArray.sort( function ( a, b ) {
					return a.startTime - b.startTime;
				} );
			}
		}
	},
	getLastUpdateTime: function(){
		var cuePoints = this.getCuePoints();
		var lastUpdateTime= -1;
		$.each(cuePoints, function(key, cuePoint){
			if (lastUpdateTime < cuePoint.updatedAt){
				lastUpdateTime = cuePoint.updatedAt;
			}
		});
		return lastUpdateTime;
	},
	getKalturaClient: function() {
		if( ! this.kClient ) {
			this.kClient = mw.kApiGetPartnerClient( this.embedPlayer.kwidgetid );
		}
		return this.kClient;
	},
	isValidResult: function( data ){
		// Check if we got error
		if( !data
			||
			( data.code && data.message )
			){
			return false;
		}
		return true;
	},
	/**
	 * Adds player cue point bindings
	 */
	addPlayerBindings: function(){
		var _this = this;
		// Get first cue point
		var currentCuePoint = this.getNextCuePoint(0);
		var embedPlayer = this.embedPlayer;

		// Don't add any bindings if no cuePoint exists )
		if( !currentCuePoint ){
			return ;
		}

		// Destroy on changeMedia
		$( embedPlayer ).bind( 'onChangeMedia' + this.bindPostfix, function(){
			_this.destroy();
		});

		// Bind to monitorEvent to trigger the cue points events and update he nextCuePoint
		$( embedPlayer ).bind(
				"monitorEvent" + this.bindPostfix +
				" seeked" + this.bindPostfix +
				" onplay" + this.bindPostfix +
				" KalturaSupport_ThumbCuePointsUpdated" + this.bindPostfix,
			function(e) {
				var currentTime = embedPlayer.currentTime * 1000;
				//In case of seeked the current cuepoint needs to be updated to new seek time before
				if ( e.type == "seeked"){
					currentCuePoint = _this.getNextCuePoint( currentTime );
				}
				// Check if the currentCuePoint exists
				if( currentCuePoint && currentTime > currentCuePoint.startTime && embedPlayer._propagateEvents ){
					// Make a copy of the cue point to be triggered.
					// Sometimes the trigger can result in monitorEvent being called and an
					// infinite loop ( ie ad network error, no ad received, and restore player calling monitor() )
					var cuePointToBeTriggered = $.extend( {}, currentCuePoint);
					// Trigger the cue point
					_this.triggerCuePoint( cuePointToBeTriggered );
				}
				// Update the current Cue Point to the "next" cue point
				currentCuePoint = _this.getNextCuePoint( currentTime );
			}
		);
	},
	getEndTime: function(){
		return this.embedPlayer.evaluate('{mediaProxy.entry.msDuration}');
	},
	getCuePoints: function(){
		if( ! this.embedPlayer.rawCuePoints || ! this.embedPlayer.rawCuePoints.length ){
			return [];
		}
		return this.embedPlayer.rawCuePoints;
	},
	/**
	* Returns the next cuePoint object for requested time
	* @param {Number} time Time in milliseconds
	*/
	getNextCuePoint: function( time ){
		if (!isNaN(time) && time >= 0) {
			var cuePoints = this.midCuePointsArray;
			// Start looking for the cue point via time, return first match:
			for ( var i = 0; i < cuePoints.length; i++ ) {
				if ( cuePoints[i].startTime >= time ) {
					return cuePoints[i];
				}
			}
		}
		// No cue point found in range return false:
		return false;
	},
	/**
	 * Triggers the given cue point
	 * @param (Object) Cue Point object
	 **/
	triggerCuePoint: function( rawCuePoint ) {
		/**
		 *  We need different events for each cue point type
		 */
		var eventName;
		/*
		 * Evaluate cuePoint sourceURL strings ( used for VAST property substitutions )
		 */
		rawCuePoint.sourceUrl = this.embedPlayer.evaluate( rawCuePoint.sourceUrl );

		/*
		 * The cue point object is wrapped with another object that has context property.
		 * We used that property so that the different plugins will know the context of the ad
		 * In case the cue point is not a adOpportunity their will be no context
		 *
		 * This matches the KDP implementation
		 * */
		var cuePointWrapper = {
			'cuePoint' : rawCuePoint
		};
		if( rawCuePoint.cuePointType == 'codeCuePoint.Code' || rawCuePoint.cuePointType == 'thumbCuePoint.Thumb' ) {
			// Code type cue point ( make it easier for people grepping the code base for an event )
			eventName = 'KalturaSupport_CuePointReached';
		} else if( rawCuePoint.cuePointType == 'adCuePoint.Ad' ) {
			// Ad type cue point
			eventName = 'KalturaSupport_AdOpportunity';
			cuePointWrapper.context = this.getVideoAdType( rawCuePoint );
		} else {
			// Ignore all others cue points types
			return ;
		}
		mw.log('mw.KCuePoints :: Trigger event: ' + eventName + ' - ' + rawCuePoint.cuePointType + ' at: ' + rawCuePoint.startTime );
		$( this.embedPlayer ).trigger(  eventName, cuePointWrapper );
		// TOOD "midSequenceComplete"
	},

	// Get Ad Type from Cue Point
	getVideoAdType: function( rawCuePoint ) {
		if( rawCuePoint.startTime === 0 ) {
			return 'pre';
		} else if( rawCuePoint.startTime == this.getEndTime() ) {
			return 'post';
		} else {
			return 'mid';
		}
		mw.log("Error:: KCuePoints could not determine adType");
	},
	/**
	 * Accept a cuePoint wrapper
	 * @param cuePointWrapper
	 * @return
	 */
	getAdSlotType: function( cuePointWrapper ) {
		if( cuePointWrapper.cuePoint.adType == 1 ) {
			return this.getVideoAdType( cuePointWrapper.cuePoint ) + 'roll';
		} else {
			return 'overlay';
		}
	},
	getRawAdSlotType: function( rawCuePoint ){
		if( rawCuePoint.adType == 1 ) {
			return this.getVideoAdType( rawCuePoint ) + 'roll';
		} else {
			return 'overlay';
		}
	},

	// Returns the number of CuePoints by type
	// @filter(optional) - string | one of: 'preroll', 'midroll', 'postroll', 'overlay'
	getCuePointsCount: function( filter ) {
		var _this = this;
		var cuePoints = this.getCuePoints();

		// No cue points, return zero
		if( !cuePoints )
			return 0;

		// No filter, return all cue points
		if( !filter )
			return  cuePoints.length;

		var totalResults = {
			'preroll': 0,
			'midroll': 0,
			'postroll': 0,
			'overlay': 0
		};

		$.each(cuePoints, function( idx, rawCuePoint) {
			totalResults[ _this.getRawAdSlotType( rawCuePoint ) ]++;
		});

		// return count by filter
		if( filter && totalResults[ filter ] ) {
			return totalResults[ filter ];
		}
		// anything else, return zero
		return 0;
	}
};

} )( window.mw, window.jQuery );<|endoftext|>


<commit_before>
const ytdl = require('ytdl-core');

const queues = {};

module.exports = {
    play: (message, config, _, url) => {
        enqueue(message, url)
            .then(() => {
                const voiceConn = message.guild.voiceConnection;

                if (voiceConn) {
                    return false;
                }

                const vc = message.member.voiceChannel;

                if (!vc) {
                    return message.reply('Join a voice channel before using the command.');
                }

                return vc.join()
                    .then(dispatch.bind(
                            null,
                            message,
                            queues[message.guild.id].shift().url,
                            config,
                        ));
            })
            .catch(console.error);
    },

    stop: (message) => {
        const voiceConn = message.guild.voiceConnection;
        if (voiceConn) {
            return new Promise((resolve, reject) => {
                message.channel.send('Interrupting song...')
                    .then((_message) => {
                        const dispatcher = voiceConn.dispatcher;
                        dispatcher.end();
                        resolve(_message);
                    })
                    .catch(reject);
            });
        }
        return message.channel.send('Stop what?');
    },

    pleasestop: (message) => {
        module.exports.clearqueue(message)
            .then(module.exports.stop);
    },

    clearqueue: message => (
        new Promise((resolve, reject) => {
            message.channel.send('Queue cleared.').then((_message) => {
                queues[message.guild.id] = [];
                resolve(_message);
            }).catch(reject);
        })
    ),

    queue: (message) => {
        const q = queues[message.guild.id] || [];
        if (q.length === 0) {
            message.channel.send('Queue is empty');
        } else {
            const cb = '```';
            const qStr = q.map(elem => (
                `${elem.title} - Requested by ${elem.requester}`
            )).join('\n');
            message.channel.send(`${cb}${qStr}${cb}`);
        }
    },

    volumeshift: (message, config, _, n) => {
        n = Number(n);
        n = !isNaN(n) ? (n / 50) : 0;
        const voiceConn = message.guild.voiceConnection;
        if (voiceConn) {
            const dispatcher = voiceConn.dispatcher;
            const oldVol = dispatcher.volume;
            const newVol = Math.max(0,
                Math.min(2,
                    clean(dispatcher.volume + n),
                ),
            );

            dispatcher.setVolume(newVol);
            message.channel.send(`Volume shifted by ${clean(newVol - oldVol) * 50}%. It is now ${clean(dispatcher.volume) * 50}%.`);
        }

        function clean(_n) {
            return Math.round(_n * 10) / 10;
        }
    },
};

function dispatch(message, url, config, connection) {
    const stream = ytdl(url, {
        filter: 'audioonly',
    });
    const dispatcher = connection.playStream(
        stream,
        { passes: config.music.passes },
    );
    dispatcher.setVolume(config.music.volume);
    dispatcher.on('end', () => {
        if (queues[message.guild.id].length > 0) {
            setTimeout(() => {
                dispatch(
                        message,
                        queues[message.guild.id].shift().url,
                        config,
                        connection,
                    );
            }, 500);
        } else {
            message.channel.send('Queue is now empty.').then(() => {
                connection.channel.leave();
            });
        }
    });
    message.channel.send(`Playing song at url:\n${url}`);
}

function enqueue(message, url) {
    queues[message.guild.id] = queues[message.guild.id] || [];

    return new Promise((resolve, reject) => {
        ytdl.getInfo(url, (e, info) => {
            if (e) {
                message.channel.send('Invalid YouTube URL.');
                reject(e);
            } else {
                queues[message.guild.id].push({
                    'url': url,
                    'title': info.title,
                    requester: message.author,
                });
                message.channel.send(`Enqueued **${info.title}**.`);
                resolve();
            }
        });
    });
}
<commit_msg>Add volume command and empty url handling for enqueue<commit_after>
const ytdl = require('ytdl-core');

const queues = {};

module.exports = {
    play: (message, config, _, url) => {
        enqueue(message, url)
            .then(() => {
                const voiceConn = message.guild.voiceConnection;

                if (voiceConn) {
                    return false;
                }

                const vc = message.member.voiceChannel;

                if (!vc) {
                    return message.reply('Join a voice channel before using the command.');
                }

                return vc.join()
                    .then(dispatch.bind(
                            null,
                            message,
                            queues[message.guild.id].shift().url,
                            config,
                        ));
            })
            .catch(console.error);
    },

    stop: (message) => {
        const voiceConn = message.guild.voiceConnection;
        if (voiceConn) {
            return new Promise((resolve, reject) => {
                message.channel.send('Interrupting song...')
                    .then((_message) => {
                        const dispatcher = voiceConn.dispatcher;
                        dispatcher.end();
                        resolve(_message);
                    })
                    .catch(reject);
            });
        }
        return message.channel.send('Stop what?');
    },

    pleasestop: (message) => {
        module.exports.clearqueue(message)
            .then(module.exports.stop);
    },

    clearqueue: message => (
        new Promise((resolve, reject) => {
            message.channel.send('Queue cleared.').then((_message) => {
                queues[message.guild.id] = [];
                resolve(_message);
            }).catch(reject);
        })
    ),

    queue: (message) => {
        const q = queues[message.guild.id] || [];
        if (q.length === 0) {
            message.channel.send('Queue is empty');
        } else {
            const cb = '```';
            const qStr = q.map(elem => (
                `${elem.title} - Requested by ${elem.requester}`
            )).join('\n');
            message.channel.send(`${cb}${qStr}${cb}`);
        }
    },

    volume: (message) => {
        const voiceConn = message.guild.voiceConnection;
        if (voiceConn) {
            const dispatcher = voiceConn.dispatcher;
            message.channel.send(`Volume is at ${dispatcher.volume}%.`);
        } else {
            message.channel.send('Volume can only be shown when playing music.');
        }
    },

    volumeshift: (message, config, _, n) => {
        n = Number(n);
        n = !isNaN(n) ? (n / 50) : 0;
        const voiceConn = message.guild.voiceConnection;
        if (voiceConn) {
            const dispatcher = voiceConn.dispatcher;
            const oldVol = dispatcher.volume;
            const newVol = Math.max(0,
                Math.min(2,
                    clean(dispatcher.volume + n),
                ),
            );

            dispatcher.setVolume(newVol);
            message.channel.send(`Volume shifted by ${clean(newVol - oldVol) * 50}%. It is now ${clean(dispatcher.volume) * 50}%.`);
        } else {
            message.channel.send('Volume can only be shifted when playing music.');
        }

        function clean(_n) {
            return Math.round(_n * 10) / 10;
        }
    },
};

function dispatch(message, url, config, connection) {
    const stream = ytdl(url, {
        filter: 'audioonly',
    });
    const dispatcher = connection.playStream(
        stream,
        { passes: config.music.passes },
    );
    dispatcher.setVolume(config.music.volume);
    dispatcher.on('end', () => {
        if (queues[message.guild.id].length > 0) {
            setTimeout(() => {
                dispatch(
                        message,
                        queues[message.guild.id].shift().url,
                        config,
                        connection,
                    );
            }, 500);
        } else {
            message.channel.send('Queue is now empty.').then(() => {
                connection.channel.leave();
            });
        }
    });
    message.channel.send(`Playing song at url:\n${url}`);
}

function enqueue(message, url = '') {
    queues[message.guild.id] = queues[message.guild.id] || [];

    return new Promise((resolve, reject) => {
        ytdl.getInfo(url, (e, info) => {
            if (e) {
                message.channel.send('Invalid YouTube URL.');
                reject(e);
            } else {
                queues[message.guild.id].push({
                    'url': url,
                    'title': info.title,
                    requester: message.author,
                });
                message.channel.send(`Enqueued **${info.title}**.`);
                resolve();
            }
        });
    });
}
<|endoftext|>


<commit_before>/**
 * Created by suparngupta on 11/16/13.
 */

/**
 * Module dependencies.
 */

var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var socket = require("socket.io");
var app = express();
var phone1;

var response;
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
    app.use(express.errorHandler());
}

app.get('/', function(req, res, next){
    res.redirect('/index2.html');
});
app.get('/users', user.list);

app.get('/contacts', function(req, res, next){
    response = res;
    var Contacts= {};
    Contacts.details=[
        {name: 'Suparn',    phn: '12345',     email:'some@getonsip.com' },
        {name: 'Rajendra',  phn: '34567',     email:''    },
        {name: 'Kim',       phn: '56789',     email:'KoreaKim@sip.com'    } ,
        {name: 'Aditya',    phn: '78901',     email:'adthakkar@sip.com'    }
        // and so on
    ];

    // TODO get the contacts from the phone and then send the JSON response to the browser.

    phone1.emit('contact_req');
    //res.json(Contacts);
});

app.get('/messages', function(req, res, next){

    // TODO send request to phone to get all the messages.
});

app.post('/send/sms', function(req, res, next){

    // TODO send the request to phone to send the sms
    res.json(req.body);
});
var server = require('http').createServer(app);
server.listen(3000);
var io = socket.listen(server);

io.sockets.on('connection', function (socket) {
    phone1 = socket;
    console.log("connection");
    socket.on('message', function(message){
        console.log(message);
        socket.send(message);

        socket.emit("contact_req", {'data': 'yahoo'});
        socket.emit('sms_req', {data: 'yahoo'});
        socket.emit('send_sms_req', JSON.stringify({number: '15555215556', message: "I am also!"}));
    });

    //socket.emit('news', { hello: 'world' });
    socket.on('my other event', function (data) {
        console.log(data);
    });

    socket.on('contact_res', function(message){
        console.log(message);
        console.log("Received the contacts list");
        socket.send("Received the contacts");
        response.json(message);
    });
    socket.on('sms_res', function(message){
        console.log("Received the smses");
        console.log(message);
        socket.send('Received the smses');
    });

    socket.on('send_sms_res', function(message){
        console.log("Send SMS response received");
        console.log(message);
    });

});
<commit_msg>Removed the events.<commit_after>/**
 * Created by suparngupta on 11/16/13.
 */

/**
 * Module dependencies.
 */

var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var socket = require("socket.io");
var app = express();
var phone1;

var response;
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
    app.use(express.errorHandler());
}

app.get('/', function(req, res, next){
    res.redirect('/index2.html');
});
app.get('/users', user.list);

app.get('/contacts', function(req, res, next){
    response = res;
    var Contacts= {};
    Contacts.details=[
        {name: 'Suparn',    phn: '12345',     email:'some@getonsip.com' },
        {name: 'Rajendra',  phn: '34567',     email:''    },
        {name: 'Kim',       phn: '56789',     email:'KoreaKim@sip.com'    } ,
        {name: 'Aditya',    phn: '78901',     email:'adthakkar@sip.com'    }
        // and so on
    ];

    // TODO get the contacts from the phone and then send the JSON response to the browser.

    phone1.emit('contact_req');
    res.json(Contacts);
});

app.get('/messages', function(req, res, next){

    // TODO send request to phone to get all the messages.
});

app.post('/send/sms', function(req, res, next){

    // TODO send the request to phone to send the sms
    res.json(req.body);
});
var server = require('http').createServer(app);
server.listen(3000);
var io = socket.listen(server);

io.sockets.on('connection', function (socket) {
    phone1 = socket;
    console.log("connection");
    socket.on('message', function(message){
        console.log(message);
        socket.send(message);

//        socket.emit("contact_req", {'data': 'yahoo'});
//        socket.emit('sms_req', {data: 'yahoo'});
//        socket.emit('send_sms_req', JSON.stringify({number: '15555215556', message: "I am also!"}));
    });

    //socket.emit('news', { hello: 'world' });
    socket.on('my other event', function (data) {
        console.log(data);
    });

    socket.on('contact_res', function(message){
        console.log(message);
        console.log("Received the contacts list");
        socket.send("Received the contacts");
        response.json(message);
    });
    socket.on('sms_res', function(message){
        console.log("Received the smses");
        console.log(message);
        socket.send('Received the smses');
    });

    socket.on('send_sms_res', function(message){
        console.log("Send SMS response received");
        console.log(message);
    });

});
<|endoftext|>


<commit_before>function editRelated (collectionId, data, templateData, field, idField) {
  var list = templateData[field];
  if (idField === 'article') {
    var dataTemplate = {list: list, idField: idField, idPlural: 'articles'};
  } else if (idField === 'bulletin') {
    var dataTemplate = {list: list, idField: idField, idPlural: 'bulletins'};
  } else if (idField === 'dataset') {
    var dataTemplate = {list: list, idField: idField, idPlural: 'datasets'};
  } else if (idField === 'document') {
    var dataTemplate = {list: list, idField: idField, idPlural: 'documents'};
  } else if (idField === 'methodology') {
    var dataTemplate = {list: list, idField: idField, idPlural: 'methodologies'};
  } else {
    var dataTemplate = {list: list, idField: idField};
  }
  var html = templates.editorRelated(dataTemplate);
  $('#'+ idField).replaceWith(html);

  initialiseRelated(collectionId, data, templateData, field, idField);
}

function refreshRelated(collectionId, data, templateData, field, idField) {
  var list = templateData[field];
  if (idField === 'article') {
    var dataTemplate = {list: list, idField: idField, idPlural: 'articles'};
  } else if (idField === 'bulletin') {
    var dataTemplate = {list: list, idField: idField, idPlural: 'bulletins'};
  } else if (idField === 'dataset') {
    var dataTemplate = {list: list, idField: idField, idPlural: 'datasets'};
  } else if (idField === 'document') {
    var dataTemplate = {list: list, idField: idField, idPlural: 'documents'};
  } else if (idField === 'methodology') {
    var dataTemplate = {list: list, idField: idField, idPlural: 'methodologies'};
  } else {
    var dataTemplate = {list: list, idField: idField};
  }
  var html = templates.editorRelated(dataTemplate);
  $('#sortable-'+ idField).replaceWith($(html).find('#sortable-'+ idField));
  initialiseRelated(collectionId, data, templateData, field, idField);
}

function initialiseRelated(collectionId, data, templateData, field, idField) {
  // Load
  if (!data[field] || data[field].length === 0) {
    editRelated['lastIndex' + field] = 0;
  } else {
    $(data[field]).each(function (index, value) {
      editRelated['lastIndex' + field] = index + 1;

      // Delete
      $('#' + idField + '-delete_' + index).click(function () {
        var result = confirm("Are you sure you want to delete this link?");
        if (result === true) {
          var position = $(".workspace-edit").scrollTop();
          Florence.globalVars.pagePos = position;
          $(this).parent().remove();
          data[field].splice(index, 1);
          templateData[field].splice(index, 1);
          postContent(collectionId, data.uri, JSON.stringify(data),
            success = function (response) {
              Florence.Editor.isDirty = false;
              refreshPreview(data.uri);
              refreshRelated(collectionId, data, templateData, field, idField)
            },
            error = function (response) {
              if (response.status === 400) {
                alert("Cannot edit this file. It is already part of another collection.");
              }
              else if (response.status === 401) {
                alert("You are not authorised to update content.");
              }
              else {
                handleApiError(response);
              }
            }
          );
        }
      });
    });
  }

  //Add
  $('#add-' + idField).off().one('click', function () {
    var position = $(".workspace-edit").scrollTop();
    Florence.globalVars.pagePos = position;
    var iframeEvent = document.getElementById('iframe').contentWindow;
    iframeEvent.removeEventListener('click', Florence.Handler, true);
    createWorkspace(data.uri, collectionId, '', true);

    $('#sortable-' + idField).append(
      '
' +
      '  <textarea id="' + idField + '-uri_' + editRelated['lastIndex' + field] + '" placeholder="Go to the related data and click Get"></textarea>' +
      '  <button class="btn-page-get" id="' + idField + '-get_' + editRelated['lastIndex' + field] + '">Get</button>' +
      '  <button class="btn-page-cancel" id="' + idField + '-cancel_' + editRelated['lastIndex' + field] + '">Cancel</button>' +
      '
').trigger('create');

    $('#' + idField + '-cancel_' + editRelated['lastIndex' + field]).one('click', function () {
      createWorkspace(data.uri, collectionId, 'edit');
    });

    $('#' + idField + '-get_' + editRelated['lastIndex' + field]).one('click', function () {
      var pastedUrl = $('#' + idField + '-uri_'+editRelated['lastIndex' + field]).val();
      if (pastedUrl) {
        checkPathParsed(pastedUrl);
        var dataUrlData = pastedUrl + "/data";
      } else {
        var dataUrl = getPathNameTrimLast();
        checkPathParsed(dataUrl);
        var dataUrlData = dataUrl + "/data";
      }

      $.ajax({
        url: dataUrlData,
        dataType: 'json',
        crossDomain: true,
        success: function (result) {
          if ((field === 'relatedBulletins' || field === 'statsBulletins') && result.type === 'bulletin') {
            if (!data[field]) {
              data[field] = [];
            }
          }

          else if (field === 'relatedArticles' && result.type === 'article') {
            if (!data[field]) {
              data[field] = [];
            }
          }

          else if ((field === 'relatedDocuments') && (result.type === 'article' || result.type === 'bulletin' || result.type === 'compendium_landing_page')) {
            if (!data[field]) {
              data[field] = [];
            }
          }

          else if ((field === 'relatedDatasets' || field === 'datasets') && (result.type === 'dataset' || result.type === 'reference_tables')) {
            if (!data[field]) {
              data[field] = [];
            }
          }

          else if ((field === 'items') && (result.type === 'timeseries')) {
            if (!data[field]) {
              data[field] = [];
            }
          }

          else if ((field === 'relatedData') && (result.type === 'timeseries' || result.type === 'dataset' || result.type === 'reference_tables')) {
            if (!data[field]) {
              data[field] = [];
            }
          }

          else if (field === 'relatedMethodology' && result.type === 'static_methodology') {
            if (!data[field]) {
              data[field] = [];
            }
          }

          else {
            alert("This is not a valid document");
            return;
          }

          data[field].push({uri: result.uri});
          saveRelated(collectionId, data.uri, data, field, idField);

        },
        error: function () {
          console.log('No page data returned');
        }
      });
    });
  });

  function sortable() {
    $('#sortable-' + idField).sortable();
  }
  sortable();
}
<commit_msg>Refactored to use return value of checkPathParsed function.<commit_after>function editRelated (collectionId, data, templateData, field, idField) {
  var list = templateData[field];
  var dataTemplate = createRelatedTemplate(idField, list);
  var html = templates.editorRelated(dataTemplate);
  $('#'+ idField).replaceWith(html);
  initialiseRelated(collectionId, data, templateData, field, idField);
}

function refreshRelated(collectionId, data, templateData, field, idField) {
  var list = templateData[field];
  var dataTemplate = createRelatedTemplate(idField, list);
  var html = templates.editorRelated(dataTemplate);
  $('#sortable-'+ idField).replaceWith($(html).find('#sortable-'+ idField));
  initialiseRelated(collectionId, data, templateData, field, idField);
}

function createRelatedTemplate(idField, list) {
  var dataTemplate;
  if (idField === 'article') {
    dataTemplate = {list: list, idField: idField, idPlural: 'articles'};
  } else if (idField === 'bulletin') {
    dataTemplate = {list: list, idField: idField, idPlural: 'bulletins'};
  } else if (idField === 'dataset') {
    dataTemplate = {list: list, idField: idField, idPlural: 'datasets'};
  } else if (idField === 'document') {
    dataTemplate = {list: list, idField: idField, idPlural: 'documents'};
  } else if (idField === 'methodology') {
    dataTemplate = {list: list, idField: idField, idPlural: 'methodologies'};
  } else {
    dataTemplate = {list: list, idField: idField};
  }
  return dataTemplate;
}

function initialiseRelated(collectionId, data, templateData, field, idField) {
  // Load
  if (!data[field] || data[field].length === 0) {
    editRelated['lastIndex' + field] = 0;
  } else {
    $(data[field]).each(function (index, value) {
      editRelated['lastIndex' + field] = index + 1;

      // Delete
      $('#' + idField + '-delete_' + index).click(function () {
        var result = confirm("Are you sure you want to delete this link?");
        if (result === true) {
          var position = $(".workspace-edit").scrollTop();
          Florence.globalVars.pagePos = position;
          $(this).parent().remove();
          data[field].splice(index, 1);
          templateData[field].splice(index, 1);
          postContent(collectionId, data.uri, JSON.stringify(data),
            success = function (response) {
              Florence.Editor.isDirty = false;
              refreshPreview(data.uri);
              refreshRelated(collectionId, data, templateData, field, idField)
            },
            error = function (response) {
              if (response.status === 400) {
                alert("Cannot edit this file. It is already part of another collection.");
              }
              else if (response.status === 401) {
                alert("You are not authorised to update content.");
              }
              else {
                handleApiError(response);
              }
            }
          );
        }
      });
    });
  }

  //Add
  $('#add-' + idField).off().one('click', function () {
    var position = $(".workspace-edit").scrollTop();
    Florence.globalVars.pagePos = position;
    var iframeEvent = document.getElementById('iframe').contentWindow;
    iframeEvent.removeEventListener('click', Florence.Handler, true);
    createWorkspace(data.uri, collectionId, '', true);

    $('#sortable-' + idField).append(
      '
' +
      '  <textarea id="' + idField + '-uri_' + editRelated['lastIndex' + field] + '" placeholder="Go to the related data and click Get"></textarea>' +
      '  <button class="btn-page-get" id="' + idField + '-get_' + editRelated['lastIndex' + field] + '">Get</button>' +
      '  <button class="btn-page-cancel" id="' + idField + '-cancel_' + editRelated['lastIndex' + field] + '">Cancel</button>' +
      '
').trigger('create');

    $('#' + idField + '-cancel_' + editRelated['lastIndex' + field]).one('click', function () {
      createWorkspace(data.uri, collectionId, 'edit');
    });

    $('#' + idField + '-get_' + editRelated['lastIndex' + field]).one('click', function () {
      var baseUrl = $('#' + idField + '-uri_'+editRelated['lastIndex' + field]).val();
      if (!baseUrl) {
        baseUrl = getPathNameTrimLast();
      }
      baseUrl = checkPathParsed(baseUrl);
      var dataUrlData = baseUrl + "/data";

      $.ajax({
        url: dataUrlData,
        dataType: 'json',
        crossDomain: true,
        success: function (result) {
          if ((field === 'relatedBulletins' || field === 'statsBulletins') && result.type === 'bulletin') {
            if (!data[field]) {
              data[field] = [];
            }
          }

          else if (field === 'relatedArticles' && result.type === 'article') {
            if (!data[field]) {
              data[field] = [];
            }
          }

          else if ((field === 'relatedDocuments') && (result.type === 'article' || result.type === 'bulletin' || result.type === 'compendium_landing_page')) {
            if (!data[field]) {
              data[field] = [];
            }
          }

          else if ((field === 'relatedDatasets' || field === 'datasets') && (result.type === 'dataset' || result.type === 'reference_tables')) {
            if (!data[field]) {
              data[field] = [];
            }
          }

          else if ((field === 'items') && (result.type === 'timeseries')) {
            if (!data[field]) {
              data[field] = [];
            }
          }

          else if ((field === 'relatedData') && (result.type === 'timeseries' || result.type === 'dataset' || result.type === 'reference_tables')) {
            if (!data[field]) {
              data[field] = [];
            }
          }

          else if (field === 'relatedMethodology' && result.type === 'static_methodology') {
            if (!data[field]) {
              data[field] = [];
            }
          }

          else {
            alert("This is not a valid document");
            return;
          }

          data[field].push({uri: baseUrl});
          saveRelated(collectionId, data.uri, data, field, idField);

        },
        error: function () {
          console.log('No page data returned');
        }
      });
    });
  });

  function sortable() {
    $('#sortable-' + idField).sortable();
  }
  sortable();
}
<|endoftext|>


<commit_before>(function(){

NewsArticleView = Backbone.View.extend({
	tagName: 'li',

	className: 'feedpost',

	events: {
		"click .markRead": function() { this.model.set("unread", false); },
		"click .markUnread": function() { this.model.set("unread", true); },
		"click a": function() { this.model.set("unread", false); },
	},

	template: Mustache.compile($('#news-article-template').html()),

	initialize: function() {
    	this.listenTo(this.model, "change", this.render);
  	},

  	render: function() {
  		var self = this;
  		var feedObj = NewsFeeds.find(function(x) { return x.id == self.model.get("article").feedId; });
  		var newView = $.extend(true, this.model.attributes, {
  			feed: feedObj.get("feed"),
  			feedObj: feedObj
  		});

  		// Format date in a friendlier manner.
  		newView.article.pubDate = new Date(newView.article.pubDate).toLocaleString();
  		this.$el.html(this.template(newView));
  		if (this.model.get("unread") == true)
  		{
  			var selfModel = this.model;
  			this.$el.addClass("unread");
  			this.$(".markRead").removeClass("hide-element");
  			this.$(".markUnread").addClass("hide-element");
  			/*this.$el.waypoint(function() {
  				selfModel.set("unread", false);
  			}, {
  				offset: function() {
    				return -$(this).height();
  				}
  			});*/
  		}
  		else
  		{
	  		this.$el.removeClass("unread");
	  		this.$(".markRead").addClass("hide-element");
  			this.$(".markUnread").removeClass("hide-element");
  		}

  		// Make all <a> links in feed open a new window.
  		this.$("a").each(function(i) {
  			if (this.href) {
  				this.target = "_blank";
  			}
  		});

  		return this;
  	}
});

}).call(this);<commit_msg>fixed security issue that allowed <script> tags in. oops.<commit_after>(function(){

NewsArticleView = Backbone.View.extend({
	tagName: 'li',

	className: 'feedpost',

	events: {
		"click .markRead": function() { this.model.set("unread", false); },
		"click .markUnread": function() { this.model.set("unread", true); },
		"click a": function() { this.model.set("unread", false); },
	},

	template: Mustache.compile($('#news-article-template').html()),

	initialize: function() {
    	this.listenTo(this.model, "change", this.render);
  	},

  	render: function() {
  		var self = this;
  		var feedObj = NewsFeeds.find(function(x) { return x.id == self.model.get("article").feedId; });
  		var newView = $.extend(true, this.model.attributes, {
  			feed: feedObj.get("feed"),
  			feedObj: feedObj
  		});

  		// Format date in a friendlier manner.
  		newView.article.pubDate = new Date(newView.article.pubDate).toLocaleString();
  		this.$el.html($.parseHTML(this.template(newView)));
  		if (this.model.get("unread") == true)
  		{
  			var selfModel = this.model;
  			this.$el.addClass("unread");
  			this.$(".markRead").removeClass("hide-element");
  			this.$(".markUnread").addClass("hide-element");
  			/*this.$el.waypoint(function() {
  				selfModel.set("unread", false);
  			}, {
  				offset: function() {
    				return -$(this).height();
  				}
  			});*/
  		}
  		else
  		{
	  		this.$el.removeClass("unread");
	  		this.$(".markRead").addClass("hide-element");
  			this.$(".markUnread").removeClass("hide-element");
  		}

  		// Make all <a> links in feed open a new window.
  		this.$("a").each(function(i) {
  			if (this.href) {
  				this.target = "_blank";
  			}
  		});

  		return this;
  	}
});

}).call(this);
<|endoftext|>


<commit_before>import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import { userType } from '@/modules/users/client/users.prop-types';
import ManifestoText from './ManifestoText.component.js';
import Tooltip from '@/modules/core/client/components/Tooltip.js';
import BoardCredits from '@/modules/core/client/components/BoardCredits.js';
import { Trans, useTranslation } from 'react-i18next';
import classnames from 'classnames';
import Board from '@/modules/core/client/components/Board.js';
import { getRouteParams } from '@/modules/core/client/services/angular-compat';
import { getCircleBackgroundStyle } from '@/modules/tribes/client/utils';
import * as tribesAPI from '@/modules/tribes/client/api/tribes.api';

const api = {
  tribes: tribesAPI,
};

export default function Home({ user, isNativeMobileApp, photoCredits }) {
  const { t } = useTranslation('pages');
  const { tribe: tribeRoute } = getRouteParams();

  // TODO get header height instead of magic number 56
  // const headerHeight = angular.element('#tr-header').height() || 0; // code of the original angular controller
  const headerHeight = 56;

  const boardHeight =
    window.innerWidth <= 480 && window.innerHeight < 700
      ? 400
      : window.innerHeight - headerHeight + 14;

  const boards =
    tribeRoute &&
    ['hitchhikers', 'dumpster-divers', 'punks'].indexOf(tribeRoute) > -1
      ? // Photos for these 3 circles
        [
          'rainbowpeople',
          'hitchroad',
          'desertgirl',
          'hitchgirl1',
          'hitchgirl2',
          'hitchtruck',
        ]
      : [
          'woman-bridge',
          'rainbowpeople',
          'hitchroad',
          'hitchgirl1',
          'wavewatching',
          'sahara-backpacker',
          'hitchtruck',
        ];

  const [tribes, setTribes] = useState([]);

  useEffect(() => {
    async function fetchData() {
      const tribes = await api.tribes.read({ limit: 3 });
      const tribeIsLoaded = tribes.some(t => t.slug === tribeRoute);

      if (tribeRoute && !tribeIsLoaded) {
        const extraTribe = await api.tribes.get(tribeRoute);

        if (extraTribe && extraTribe._id) {
          tribes.unshift(extraTribe);
        }
      }
      setTribes(tribes);
    }
    fetchData();
  }, []);

  return (
    <>
      {!user && (
        // TODO apply tr-boards-ignore-small attribute here and implement functionality in the Board.js controller
        <Board
          className="board-primary container home-intro"
          names={boards}
          style={{
            height: boardHeight,
          }}
        >

Trustroots

{t("Travellers' community")}

                    {t('Sharing, hosting and getting people together.')}

                    {t('Join Trustroots now')}

                  {!isNativeMobileApp && (

                        {t('Play Store')}

                        {t('App Store')}

                  )}

              {/* .row */}

        </Board>
      )}

      {/* How does it work */}

{t('How does it work?')}

                {t(
                  `Have a look! Travel anywhere and easily find great people who want to
                meet you as well. See where other travellers are and help each other
                out, whether through welcoming them to your home, sharing your stories
                or becoming friends.`,
                )}

                {/* @TODO remove ns (issue #1368) */}
                <Trans t={t} ns="pages">
                  Trustroots is over 50,000 members{' '}
                  strong!
                </Trans>

      {/* Share */}

                {t('Share the beautiful you with the world.')}

                {t(`Put yourself in the shoes of others: what would you like to know about
                your travel buddies? What should they know about you?`)}

                {t('Be genuine yourself.')}

      {/* Tribes */}
      {tribes.length > 0 && (

{t('Circles')}

                    {t(`Joining circles helps you find likeminded Trustroots members and
                  tells others what you're interested in.`)}

                      {t('More circles')}

                {tribes.slice(0, 3).map(tribe => (
                  <a
                    key={tribe._id}
                    href={`/circles/${tribe.slug}`}
                    className="img-circle tribe-xs tribe-image"
                    style={getCircleBackgroundStyle(tribe, '520x520')}
                  >
                    {!tribe.image && {tribe.label.charAt(0)}}

                ))}

              {tribes.slice(0, 3).map((tribe, index, items) => (
                <div
                  key={tribe._id}
                  className={classnames('col-sm-3', 'hidden-xs', {
                    'col-sm-pull-3': index < items.length - 1,
                  })}
                >

                    <a href={`/circles/${tribe.slug}`} className="tribe-link">

{tribe.label}

              ))}

      )}

      {/* Manifesto */}
      <Board
        className="board-primary board-inset"
        names="mountainforest"
        id="manifesto"
      >

              <ManifestoText></ManifestoText>
              {!user && (

                    {t('Join Trustroots')}

              )}

      </Board>

      {/* Footer */}
      <Board
        className="board-primary board-inset home-footer"
        names="bokeh"
        ignoreBackgroundOnSmallScreen
      >

{t('Foundation')}

                {t(`Owned and operated by Trustroots Foundation, a non-profit registered
                in the United Kingdom since March 2015.`)}

                  {t('Learn more')}

{t('Team')}

                {/* @TODO remove ns (issue #1368) */}
                <Trans t={t} ns="pages">
                  Trustroots is being built by a small team of activists who
                  felt that the world of sharing is being taken over by
                  corporations trying to monetize people's willingness to
                  help each other. Same team brought you also{' '}
                  Hitchwiki,{' '}
                  Trashwiki and{' '}
                  Nomadwiki.
                </Trans>

                  {t('Meet the team')}

{t('Free and open source')}

                {t(`We think it's a shame that former non profits have been sold to
                venture capital. We've been running other notable free and open
                projects for a decade now and we hope our deeds so far speak for us.`)}

                  {t('For developers')}

                  {t('FAQ')}

                  {t('Blog')}

                  {t('Shop')}

                  {t('Volunteering')}

                  {t('Media')}

                  {t('Contact & support')}

            {!isNativeMobileApp && (

                  {t('Play Store')}

                  {t('App Store')}

            )}

                <Tooltip id="facebook-tooltip" tooltip="Facebook">

                </Tooltip>

                <Tooltip id="facebook-tooltip" tooltip="Twitter">

                </Tooltip>

                <Tooltip id="instagram-tooltip" tooltip="Instagram">

                </Tooltip>

                <Tooltip id="github-tooltip" tooltip="GitHub">

                </Tooltip>

            <BoardCredits photoCredits={photoCredits} />

          {/* .row */}

        {/* /.container */}
      </Board>
    </>
  );
}

Home.propTypes = {
  user: userType,
  isNativeMobileApp: PropTypes.bool,
  photoCredits: PropTypes.object,
};
<commit_msg>Fix: circle images on homepage (#1933)<commit_after>import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import { userType } from '@/modules/users/client/users.prop-types';
import ManifestoText from './ManifestoText.component.js';
import Tooltip from '@/modules/core/client/components/Tooltip.js';
import BoardCredits from '@/modules/core/client/components/BoardCredits.js';
import { Trans, useTranslation } from 'react-i18next';
import classnames from 'classnames';
import Board from '@/modules/core/client/components/Board.js';
import { getRouteParams } from '@/modules/core/client/services/angular-compat';
import { getCircleBackgroundStyle } from '@/modules/tribes/client/utils';
import * as tribesAPI from '@/modules/tribes/client/api/tribes.api';

const api = {
  tribes: tribesAPI,
};

export default function Home({ user, isNativeMobileApp, photoCredits }) {
  const { t } = useTranslation('pages');
  const { tribe: tribeRoute } = getRouteParams();

  // TODO get header height instead of magic number 56
  // const headerHeight = angular.element('#tr-header').height() || 0; // code of the original angular controller
  const headerHeight = 56;

  const boardHeight =
    window.innerWidth <= 480 && window.innerHeight < 700
      ? 400
      : window.innerHeight - headerHeight + 14;

  const boards =
    tribeRoute &&
    ['hitchhikers', 'dumpster-divers', 'punks'].indexOf(tribeRoute) > -1
      ? // Photos for these 3 circles
        [
          'rainbowpeople',
          'hitchroad',
          'desertgirl',
          'hitchgirl1',
          'hitchgirl2',
          'hitchtruck',
        ]
      : [
          'woman-bridge',
          'rainbowpeople',
          'hitchroad',
          'hitchgirl1',
          'wavewatching',
          'sahara-backpacker',
          'hitchtruck',
        ];

  const [tribes, setTribes] = useState([]);

  useEffect(() => {
    async function fetchData() {
      const tribes = await api.tribes.read({ limit: 3 });
      const tribeIsLoaded = tribes.some(t => t.slug === tribeRoute);

      if (tribeRoute && !tribeIsLoaded) {
        const extraTribe = await api.tribes.get(tribeRoute);

        if (extraTribe && extraTribe._id) {
          tribes.unshift(extraTribe);
        }
      }
      setTribes(tribes);
    }
    fetchData();
  }, []);

  return (
    <>
      {!user && (
        // TODO apply tr-boards-ignore-small attribute here and implement functionality in the Board.js controller
        <Board
          className="board-primary container home-intro"
          names={boards}
          style={{
            height: boardHeight,
          }}
        >

Trustroots

{t("Travellers' community")}

                    {t('Sharing, hosting and getting people together.')}

                    {t('Join Trustroots now')}

                  {!isNativeMobileApp && (

                        {t('Play Store')}

                        {t('App Store')}

                  )}

              {/* .row */}

        </Board>
      )}

      {/* How does it work */}

{t('How does it work?')}

                {t(
                  `Have a look! Travel anywhere and easily find great people who want to
                meet you as well. See where other travellers are and help each other
                out, whether through welcoming them to your home, sharing your stories
                or becoming friends.`,
                )}

                {/* @TODO remove ns (issue #1368) */}
                <Trans t={t} ns="pages">
                  Trustroots is over 50,000 members{' '}
                  strong!
                </Trans>

      {/* Share */}

                {t('Share the beautiful you with the world.')}

                {t(`Put yourself in the shoes of others: what would you like to know about
                your travel buddies? What should they know about you?`)}

                {t('Be genuine yourself.')}

      {/* Tribes */}
      {tribes.length > 0 && (

{t('Circles')}

                    {t(`Joining circles helps you find likeminded Trustroots members and
                  tells others what you're interested in.`)}

                      {t('More circles')}

                {tribes.slice(0, 3).map(tribe => (
                  <a
                    key={tribe._id}
                    href={`/circles/${tribe.slug}`}
                    className="img-circle tribe-xs tribe-image"
                    style={getCircleBackgroundStyle(tribe, '742x496')}
                  >
                    {!tribe.image && {tribe.label.charAt(0)}}

                ))}

              {tribes.slice(0, 3).map((tribe, index, items) => (
                <div
                  key={tribe._id}
                  className={classnames('col-sm-3', 'hidden-xs', {
                    'col-sm-pull-3': index < items.length - 1,
                  })}
                >

                    <a href={`/circles/${tribe.slug}`} className="tribe-link">

{tribe.label}

              ))}

      )}

      {/* Manifesto */}
      <Board
        className="board-primary board-inset"
        names="mountainforest"
        id="manifesto"
      >

              <ManifestoText></ManifestoText>
              {!user && (

                    {t('Join Trustroots')}

              )}

      </Board>

      {/* Footer */}
      <Board
        className="board-primary board-inset home-footer"
        names="bokeh"
        ignoreBackgroundOnSmallScreen
      >

{t('Foundation')}

                {t(`Owned and operated by Trustroots Foundation, a non-profit registered
                in the United Kingdom since March 2015.`)}

                  {t('Learn more')}

{t('Team')}

                {/* @TODO remove ns (issue #1368) */}
                <Trans t={t} ns="pages">
                  Trustroots is being built by a small team of activists who
                  felt that the world of sharing is being taken over by
                  corporations trying to monetize people's willingness to
                  help each other. Same team brought you also{' '}
                  Hitchwiki,{' '}
                  Trashwiki and{' '}
                  Nomadwiki.
                </Trans>

                  {t('Meet the team')}

{t('Free and open source')}

                {t(`We think it's a shame that former non profits have been sold to
                venture capital. We've been running other notable free and open
                projects for a decade now and we hope our deeds so far speak for us.`)}

                  {t('For developers')}

                  {t('FAQ')}

                  {t('Blog')}

                  {t('Shop')}

                  {t('Volunteering')}

                  {t('Media')}

                  {t('Contact & support')}

            {!isNativeMobileApp && (

                  {t('Play Store')}

                  {t('App Store')}

            )}

                <Tooltip id="facebook-tooltip" tooltip="Facebook">

                </Tooltip>

                <Tooltip id="facebook-tooltip" tooltip="Twitter">

                </Tooltip>

                <Tooltip id="instagram-tooltip" tooltip="Instagram">

                </Tooltip>

                <Tooltip id="github-tooltip" tooltip="GitHub">

                </Tooltip>

            <BoardCredits photoCredits={photoCredits} />

          {/* .row */}

        {/* /.container */}
      </Board>
    </>
  );
}

Home.propTypes = {
  user: userType,
  isNativeMobileApp: PropTypes.bool,
  photoCredits: PropTypes.object,
};
<|endoftext|>


<commit_before>angular
    .module('ngSharepoint.Users')
    .factory('RestSPUser', function($q, $spLoader) {
        var RestSPUser = function(accountName) {
            this.accountName = accountName;
        };
        RestSPUser.prototype.load = function() {
            var user = this;
            var endpoint = '_api/SP.UserProfiles.PeopleManager/getPropertiesFor(@account)?@account=\'' + user.accountName + '\'';
            return $q(function(resolve, reject) {
                $spLoader({
                    method: 'GET',
                    url: endpoint
                }).then(function(response) {
                    var data = {};
                    data.displayName = response.d.DisplayName;
                    data.email = response.d.Email;
                    data.picture = response.d.PictureUrl;
                    data.title = response.d.Title;
                    data.personalUrl = response.d.PersonalUrl;
                    data.userUrl = response.d.UserUrl;
                    resolve(data);
                }, reject);
            });
        };
        return (RestSPUser);
    });<commit_msg>Keep lines short<commit_after>angular
    .module('ngSharepoint.Users')
    .factory('RestSPUser', function($q, $spLoader) {
        var RestSPUser = function(accountName) {
            this.accountName = accountName;
        };
        RestSPUser.prototype.load = function() {
            var user = this;
            var endpoint = '_api/SP.UserProfiles.PeopleManager/getPropertiesFor(@account)' +
                '?@account=\'' + user.accountName + '\'';
            return $q(function(resolve, reject) {
                $spLoader({
                    method: 'GET',
                    url: endpoint
                }).then(function(response) {
                    var data = {};
                    data.displayName = response.d.DisplayName;
                    data.email = response.d.Email;
                    data.picture = response.d.PictureUrl;
                    data.title = response.d.Title;
                    data.personalUrl = response.d.PersonalUrl;
                    data.userUrl = response.d.UserUrl;
                    resolve(data);
                }, reject);
            });
        };
        return (RestSPUser);
    });<|endoftext|>