<commit_before>module.exports = async function (msg) {
    if (!msg.author) return; // Message.author is occasionally undefined. abal plz fix
    if (msg.author.bot) return; // ignore bots
    if (msg.channel instanceof ErisO.PrivateChannel) {
        if (config.reroutePMs) {
            let pm = await this.getDMChannel(config.oid)
            let embedString = msg.embeds.map(a => `\`\`\`\n${this.embedToText(a)}\`\`\`\n`).join("\n")
            let attachmentString = msg.attachments.map(a => a.url).join("\n")
            let embed = {
                author: {
                    name: `${this.getTag(msg.author)} sent a PM to me!`,
                    icon_url: msg.author.avatarURL
                },
                description: `${msg.content}\n${attachmentString}\n${embedString}`
            }
            try {
                await this.createMessage(pm.id, {
                    embed
                })
            } catch (err) {
                console.log(this.embedToText(embed))
            }
        }
        return; // ignore DMs
    }
    if (msg.channel.topic && msg.channel.topic.includes("[tt.bot block]")) return // we ignore the channel when [tt.bot block] is anywhere in the message.
    let server = await db.table("configs").get(msg.guild.id).run();
    msg.guildConfig = server;
    if ((server && msg.content.startsWith(server.prefix)) || msg.content.startsWith(config.prefix)) { // if the content starts with the prefix
        let nameslice = (server && msg.content.startsWith(server.prefix)) ? msg.content.slice(server.prefix.length) : msg.content.slice(config.prefix.length) // we slice it so we can get the command
        let cmdName = nameslice.split(" ")[0]; //  we split the slice output by spaces and choosing the command from the first element
        let args = nameslice.slice(cmdName.length).slice(1); // we determine arguments
        let cmdAlias = cmdAliases[cmdName.toLowerCase()]
        try {
            let cmd = cmds[cmdName.toLowerCase()]; // we load it from object
            if (!cmd) cmd = cmds[cmdAlias]
            if (cmd) {
                console.log(
`Received a command message
    From ${this.getTag(msg.author)} (${msg.author.id})
    Guild ${msg.guild.name} (${msg.guild.id})
    Command ${cmdName}
${args ? `    Arguments ${args}` : ""}
`
                )
                let e = cmd.exec(msg, args); // we execute it
            }
        } catch (err) {
            console.error(err); // if an error is thrown, we log it.
        }
    }
}
module.exports.isEvent = true; // event declaration<commit_msg>pad args correctly<commit_after>module.exports = async function (msg) {
    if (!msg.author) return; // Message.author is occasionally undefined. abal plz fix
    if (msg.author.bot) return; // ignore bots
    if (msg.channel instanceof ErisO.PrivateChannel) {
        if (config.reroutePMs) {
            let pm = await this.getDMChannel(config.oid)
            let embedString = msg.embeds.map(a => `\`\`\`\n${this.embedToText(a)}\`\`\`\n`).join("\n")
            let attachmentString = msg.attachments.map(a => a.url).join("\n")
            let embed = {
                author: {
                    name: `${this.getTag(msg.author)} sent a PM to me!`,
                    icon_url: msg.author.avatarURL
                },
                description: `${msg.content}\n${attachmentString}\n${embedString}`
            }
            try {
                await this.createMessage(pm.id, {
                    embed
                })
            } catch (err) {
                console.log(this.embedToText(embed))
            }
        }
        return; // ignore DMs
    }
    if (msg.channel.topic && msg.channel.topic.includes("[tt.bot block]")) return // we ignore the channel when [tt.bot block] is anywhere in the message.
    let server = await db.table("configs").get(msg.guild.id).run();
    msg.guildConfig = server;
    if ((server && msg.content.startsWith(server.prefix)) || msg.content.startsWith(config.prefix)) { // if the content starts with the prefix
        let nameslice = (server && msg.content.startsWith(server.prefix)) ? msg.content.slice(server.prefix.length) : msg.content.slice(config.prefix.length) // we slice it so we can get the command
        let cmdName = nameslice.split(" ")[0]; //  we split the slice output by spaces and choosing the command from the first element
        let args = nameslice.slice(cmdName.length).slice(1); // we determine arguments
        let cmdAlias = cmdAliases[cmdName.toLowerCase()]
        try {
            let cmd = cmds[cmdName.toLowerCase()]; // we load it from object
            if (!cmd) cmd = cmds[cmdAlias]
            if (cmd) {
                console.log(
`Received a command message
    From        ${this.getTag(msg.author)} (${msg.author.id})
    Guild       ${msg.guild.name} (${msg.guild.id})
    Command     ${cmdName}
${args ? `    Arguments   ${args}` : ""}
`
                )
                let e = cmd.exec(msg, args); // we execute it
            }
        } catch (err) {
            console.error(err); // if an error is thrown, we log it.
        }
    }
}
module.exports.isEvent = true; // event declaration<|endoftext|>


<commit_before>'use strict';
var plugin = [];
plugin.command = []; // extra commands
plugin.commandName = []; // extra commands
plugin.addToHelp = [];
plugin.gamemodeId = [];
plugin.gamemode = [];

plugin.name = "example plugin"; // Name of plugin where it would be listed in
plugin.author = "andrews54757"; // author
plugin.commandName[0] = "tptoplayer";
plugin.description = "An example plugin";
plugin.addToHelp[0] = "tptoplayer : tps to a player";
plugin.command[0] = require("./tptoplayer.js");
plugin.version = '1.0.0';
plugin.compatVersion = ''; // compatable with (todo)
plugin.gamemodeId[0] = 80;
plugin.gamemode[0] = require("./sffa.js");

plugin.init = function (gameServer) {
  // init, Used to do stuff such as overriding things

};
module.exports = plugin;

<commit_msg>Update index.js<commit_after>'use strict';
var plugin = [];
plugin.command = []; // extra commands
plugin.commandName = []; // extra commands
plugin.addToHelp = [];
plugin.gamemodeId = [];
plugin.gamemode = [];

plugin.name = "example plugin"; // Name of plugin where it would be listed in
plugin.author = "andrews54757"; // author
plugin.commandName[0] = "tptoplayer";
plugin.description = "An example plugin";
plugin.addToHelp[0] = "tptoplayer : tps to a player";
plugin.command[0] = require("./tptoplayer.js");
plugin.version = '1.0.0';
plugin.compatVersion = ''; // compatable with (todo)
plugin.gamemodeId[0] = 80;
plugin.gamemode[0] = require("./sffa.js");

plugin.init = function (gameServer, config) {
  this.config = config;
  // init, Used to do stuff such as overriding things

};
module.exports = plugin;

<|endoftext|>


<commit_before>var mouseX = 0, mouseY = 0,
windowHalfX = window.innerWidth / 2,
windowHalfY = window.innerHeight / 2,
SEPARATION = 200,
AMOUNTX = 10,
AMOUNTY = 10,
camera, scene, renderer,earth;
var container = document.createElement('div');
document.body.appendChild(container)

init();
animate();

function init() {

  createPerspectiveCamera()
  createScene()
  createRenderer()
  createAmbientLight()
  createDirectionalLight()
  createEarth()

  document.addEventListener( 'mousemove', onDocumentMouseMove, false );
  document.addEventListener( 'touchstart', onDocumentTouchStart, false );
  document.addEventListener( 'touchmove', onDocumentTouchMove, false );
  window.addEventListener( 'resize', onWindowResize, false );
}

function createRenderer(){
  renderer = new THREE.CanvasRenderer({antialias:true,alpha: true  });
  renderer.setPixelRatio( window.devicePixelRatio );
  renderer.setSize( window.innerWidth, window.innerHeight );
  renderer.setClearColorHex(0x000000, 1.0);//设置
  container.appendChild( renderer.domElement );
}

function createScene(){
  scene = new THREE.Scene();
}

function createPerspectiveCamera(){
  camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 10000 );
  camera.position.z = 100;
}

function createAmbientLight(){
  var ambientLight = new THREE.AmbientLight(0x050505, 1.0, 0);
  ambientLight.position.set( 200, 200, 200 );
  scene.add(ambientLight);
}

function createDirectionalLight(){
  var directionalLight = new THREE.DirectionalLight(0xffffff, 1.0, 0);
  directionalLight.position.set( 200, 200, 200 );
  scene.add(directionalLight);
}

function createEarth(){
  var loader = new THREE.TextureLoader();
  loader.load(
    'textures/land_ocean_ice_cloud_2048.jpg',
    function ( texture ) {
      earth = new THREE.Mesh(
        new THREE.SphereGeometry(20,100,50),
        new THREE.MeshLambertMaterial({
          map: texture,
          //color: 0xffffff,
          overdraw:true}) //材质设定
      );
      earth.position.set(0,0,0);
    },
    function (progress){
      console.log(progress)
    },
    function (err){
      earth = new THREE.Mesh(
        new THREE.SphereGeometry(20,100,50),
        new THREE.MeshLambertMaterial({color: 0xffffff,overdraw:true}) //材质设定
      );
      earth.position.set(0,0,0);
    }
  );

  scene.add(earth);
}

function onWindowResize() {
  windowHalfX = window.innerWidth / 2;
  windowHalfY = window.innerHeight / 2;
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize( window.innerWidth, window.innerHeight );
}

function onDocumentMouseMove(event) {
  mouseX = event.clientX - windowHalfX;
  mouseY = event.clientY - windowHalfY;
}

function onDocumentTouchStart( event ) {
  if ( event.touches.length > 1 ) {
    event.preventDefault();
    mouseX = event.touches[ 0 ].pageX - windowHalfX;
    mouseY = event.touches[ 0 ].pageY - windowHalfY;
  }
}

function onDocumentTouchMove( event ) {
  if ( event.touches.length == 1 ) {
    event.preventDefault();
    mouseX = event.touches[ 0 ].pageX - windowHalfX;
    mouseY = event.touches[ 0 ].pageY - windowHalfY;
  }
}

function animate() {
  requestAnimationFrame( animate );
  render();
}

function render() {
  renderer.clear();

  earth && earth.rotateOnAxis (new THREE.Vector3(0,1,0), 0.01)

  renderer.render( scene, camera );
}
<commit_msg>earth<commit_after>var mouseX = 0, mouseY = 0,
windowHalfX = window.innerWidth / 2,
windowHalfY = window.innerHeight / 2,
SEPARATION = 200,
AMOUNTX = 10,
AMOUNTY = 10,
camera, scene, renderer,earth;
var container = document.createElement('div');
document.body.appendChild(container)

init();
animate();

function init() {

  createPerspectiveCamera()
  createScene()
  createRenderer()
  createAmbientLight()
  createDirectionalLight()
  createEarth()

  document.addEventListener( 'mousemove', onDocumentMouseMove, false );
  document.addEventListener( 'touchstart', onDocumentTouchStart, false );
  document.addEventListener( 'touchmove', onDocumentTouchMove, false );
  window.addEventListener( 'resize', onWindowResize, false );
}

function createRenderer(){
  renderer = new THREE.CanvasRenderer({antialias:true,alpha: true  });
  renderer.setPixelRatio( window.devicePixelRatio );
  renderer.setSize( window.innerWidth, window.innerHeight );
  renderer.setClearColorHex(0x000000, 1.0);//设置
  container.appendChild( renderer.domElement );
}

function createScene(){
  scene = new THREE.Scene();
}

function createPerspectiveCamera(){
  camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 10000 );
  camera.position.z = 100;
}

function createAmbientLight(){
  var ambientLight = new THREE.AmbientLight(0x050505, 1.0, 0);
  ambientLight.position.set( 200, 200, 200 );
  scene.add(ambientLight);
}

function createDirectionalLight(){
  var directionalLight = new THREE.DirectionalLight(0xffffff, 1.0, 0);
  directionalLight.position.set( 200, 200, 200 );
  scene.add(directionalLight);
}

function createEarth(){
  var loader = new THREE.TextureLoader();
  loader.load(
    'textures/land_ocean_ice_cloud_2048.jpg',
    function ( texture ) {
      earth = new THREE.Mesh(
        new THREE.SphereGeometry(20,100,50),
        new THREE.MeshBasicMaterial({
          map: texture,
          //color: 0xffffff,
          overdraw:true}) //材质设定
      );
      earth.position.set(0,0,0);
    },
    function (progress){
      console.log(progress)
    },
    function (err){
      earth = new THREE.Mesh(
        new THREE.SphereGeometry(20,100,50),
        new THREE.MeshLambertMaterial({color: 0xffffff,overdraw:true}) //材质设定
      );
      earth.position.set(0,0,0);
    }
  );

  scene.add(earth);
}

function onWindowResize() {
  windowHalfX = window.innerWidth / 2;
  windowHalfY = window.innerHeight / 2;
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize( window.innerWidth, window.innerHeight );
}

function onDocumentMouseMove(event) {
  mouseX = event.clientX - windowHalfX;
  mouseY = event.clientY - windowHalfY;
}

function onDocumentTouchStart( event ) {
  if ( event.touches.length > 1 ) {
    event.preventDefault();
    mouseX = event.touches[ 0 ].pageX - windowHalfX;
    mouseY = event.touches[ 0 ].pageY - windowHalfY;
  }
}

function onDocumentTouchMove( event ) {
  if ( event.touches.length == 1 ) {
    event.preventDefault();
    mouseX = event.touches[ 0 ].pageX - windowHalfX;
    mouseY = event.touches[ 0 ].pageY - windowHalfY;
  }
}

function animate() {
  requestAnimationFrame( animate );
  render();
}

function render() {
  renderer.clear();

  earth && earth.rotateOnAxis (new THREE.Vector3(0,1,0), 0.01)

  renderer.render( scene, camera );
}
<|endoftext|>


<commit_before>const append = ({ data, type }, list) => {
  if (!data) {
    return list;
  }

  return [
    ...list,
    {
      data,
      type
    }
  ];
};

const prepareDataForListView = articleData => {
  const relatedArticleSliceData = articleData.relatedArticleSlice
    ? { relatedArticleSlice: articleData.relatedArticleSlice }
    : null;
  const commentsData = {
    articleId: articleData.id,
    commentsEnabled: articleData.commentsEnabled,
    url: articleData.url
  };

  const data = articleData.content
    ? [
        ...articleData.content.map((rowData, index) => {
          const item = {
            data: Object.assign({}, rowData),
            index,
            type: "articleBodyRow"
          };
          if (rowData.name === "ad") {
            item.data.attributes = {
              ...item.data.attributes,
              ...{
                contextUrl: articleData.url,
                section: articleData.section
              }
            };
          }
          return item;
        }),
        {
          data: {
            topics: articleData.topics
          },
          type: "topics"
        }
      ]
    : [];

  return append(
    {
      data: { articleId: articleData.id, articleUrl: articleData.url },
      type: "articleExtrasRow"
    },
    append(
      {
        data: commentsData,
        type: "comments"
      },
      append(
        {
          data: relatedArticleSliceData,
          type: "relatedArticleSlice"
        },
        data
      )
    )
  );
};

export const getRegistrationType = () => {
  const user = (global.nuk && global.nuk.user) || {};
  return user && user.registrationType ? user.registrationType : "";
};

export const getSharedStatus = () => {
  const user = (global.nuk && global.nuk.user) || {};
  return user && user.isShared ? "yes" : "no";
};

export const getIsLiveOrBreakingFlag = flags =>
  flags && flags.find(flag => flag === "breaking" || flag === "live");

export default prepareDataForListView;
<commit_msg>updating text case (#2843)<commit_after>const append = ({ data, type }, list) => {
  if (!data) {
    return list;
  }

  return [
    ...list,
    {
      data,
      type
    }
  ];
};

const prepareDataForListView = articleData => {
  const relatedArticleSliceData = articleData.relatedArticleSlice
    ? { relatedArticleSlice: articleData.relatedArticleSlice }
    : null;
  const commentsData = {
    articleId: articleData.id,
    commentsEnabled: articleData.commentsEnabled,
    url: articleData.url
  };

  const data = articleData.content
    ? [
        ...articleData.content.map((rowData, index) => {
          const item = {
            data: Object.assign({}, rowData),
            index,
            type: "articleBodyRow"
          };
          if (rowData.name === "ad") {
            item.data.attributes = {
              ...item.data.attributes,
              ...{
                contextUrl: articleData.url,
                section: articleData.section
              }
            };
          }
          return item;
        }),
        {
          data: {
            topics: articleData.topics
          },
          type: "topics"
        }
      ]
    : [];

  return append(
    {
      data: { articleId: articleData.id, articleUrl: articleData.url },
      type: "articleExtrasRow"
    },
    append(
      {
        data: commentsData,
        type: "comments"
      },
      append(
        {
          data: relatedArticleSliceData,
          type: "relatedArticleSlice"
        },
        data
      )
    )
  );
};

export const getRegistrationType = () => {
  const user = (global.nuk && global.nuk.user) || {};
  return user && user.registrationType ? user.registrationType : "";
};

export const getSharedStatus = () => {
  const user = (global.nuk && global.nuk.user) || {};
  return user && user.isShared ? "yes" : "no";
};

export const getIsLiveOrBreakingFlag = flags =>
  flags && flags.find(flag => flag === "BREAKING" || flag === "LIVE");

export default prepareDataForListView;
<|endoftext|>


<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements.  See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership.  The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License.  You may obtain a copy of the License at
*
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied.  See the License for the
* specific language governing permissions and limitations
* under the License.
*/

var KEY_DELIMITER = '-->';
/**
 * params handler
 * @param {module:echarts/model/SeriesModel} seriesModel
 * @returns {*}
 */
var getAutoCurvenessParams = function (seriesModel) {
    return seriesModel.get('autoCurveness') || null;
};

/**
 * Generate a list of edge curvatures, 20 is the default
 * @param {module:echarts/model/SeriesModel} seriesModel
 * @param {number} appendLength
 * @return  20 => [0, -0.2, 0.2, -0.4, 0.4, -0.6, 0.6, -0.8, 0.8, -1, 1, -1.2, 1.2, -1.4, 1.4, -1.6, 1.6, -1.8, 1.8, -2]
 */
var createCurveness = function (seriesModel, appendLength) {
    var autoCurvenessParmas = getAutoCurvenessParams(seriesModel);
    var length = 20;
    var curvenessList = [];

    // handler the function set
    if (typeof autoCurvenessParmas === 'number') {
        length = autoCurvenessParmas;
    }
    else if (Object.prototype.toString.call(autoCurvenessParmas) === '[object Array]') {
        seriesModel._curvenessList = autoCurvenessParmas;
        return;
    }

    // append length
    if (appendLength > length) {
        length = appendLength;
    }

    // make sure the length is even
    var len = length % 2 ? length + 2 : length + 3;
    curvenessList = [];

    for (var i = 0; i < len; i++) {
        curvenessList.push((i % 2 ? i + 1 : i) / 10 * (i % 2 ? -1 : 1));
    }
    seriesModel._curvenessList = curvenessList;
};

/**
 * Create different cache key data in the positive and negative directions, in order to set the curvature later
 * @param {number|string|module:echarts/data/Graph.Node} n1
 * @param {number|string|module:echarts/data/Graph.Node} n2
 * @param {module:echarts/model/SeriesModel} seriesModel
 * @returns {string} key
 */
var getKeyOfEdges = function (n1, n2, seriesModel) {
    var source = [n1.id, n1.dataIndex].join('.');
    var target = [n2.id, n2.dataIndex].join('.');
    return [seriesModel.uid, source, target].join(KEY_DELIMITER);
};

/**
 * get opposite key
 * @param {string} key
 * @returns {string}
 */
var getOppositeKey = function (key) {
    var keys = key.split(KEY_DELIMITER);
    return [keys[0], keys[2], keys[1]].join(KEY_DELIMITER);
};

/**
 * set edgeMap with key
 * @param {number|string|module:echarts/data/Graph.Node} n1
 * @param {number|string|module:echarts/data/Graph.Node} n2
 * @param {module:echarts/model/SeriesModel} seriesModel
 * @param {number} index
 */
var setEdgeToMap = function (n1, n2, seriesModel, index) {
    var key = getKeyOfEdges(n1, n2, seriesModel);
    var edgeMap = seriesModel._edgeMap;
    var oppositeEdges = edgeMap[getOppositeKey(key)];
    // set direction
    if (edgeMap[key] && !oppositeEdges) {
        edgeMap[key].isForward = true;
    }
    else if (oppositeEdges && edgeMap[key]) {
        oppositeEdges.isForward = true;
        edgeMap[key].isForward = false;
    }

    edgeMap[key] = edgeMap[key] || [];
    edgeMap[key].push(index);
};

/**
 * get edgeMap with key
 * @param edge
 * @param {module:echarts/model/SeriesModel} seriesModel
 */
var getEdgeFromMap = function (edge, seriesModel) {
    var key = getKeyOfEdges(edge.node1, edge.node2, seriesModel);
    return seriesModel._edgeMap[key];
};

/**
 * calculate all cases total length
 * @param edge
 * @param seriesModel
 * @returns {number}
 */
var getTotalLengthBetweenNodes = function (edge, seriesModel) {
    var len = getEdgeMapLengthWithKey(getKeyOfEdges(edge.node1, edge.node2, seriesModel), seriesModel);
    var lenV = getEdgeMapLengthWithKey(getKeyOfEdges(edge.node2, edge.node1, seriesModel), seriesModel);

    return len + lenV;
};

/**
 *
 * @param key
 */
var getEdgeMapLengthWithKey = function (key, seriesModel) {
    var edgeMap = seriesModel._edgeMap;
    return edgeMap[key] ? edgeMap[key].length : 0;
};

/**
 * Count the number of edges between the same two points, used to obtain the curvature table and the parity of the edge
 * @see /graph/GraphSeries.js@getInitialData
 * @param edges
 * @param {module:echarts/model/SeriesModel} seriesModel
 */
export function initCurvenessList(edges, seriesModel) {
    if (!getAutoCurvenessParams(seriesModel)) {
        return;
    }
    // Hang on this object 4 dispose
    seriesModel._curvenessList = seriesModel._curvenessList || [];
    // calc the array of curveness List
    createCurveness(seriesModel);
}

/**
 * create the edgeMap after addEdges
 * @see chart/helper/createGraphFromNodeEdge.js#L52
 * @param {number|string|module:echarts/data/Graph.Node} n1
 * @param {number|string|module:echarts/data/Graph.Node} n2
 * @param {module:echarts/model/SeriesModel} seriesModel
 * @param {number} dataIndex
 */
export function createEdgeMapForCurveness(n1, n2, seriesModel, dataIndex) {
    seriesModel._edgeMap = seriesModel._edgeMap || {};
    setEdgeToMap(n1, n2, seriesModel, dataIndex);
}

/**
 * get curvature for edge
 * @param edge
 * @param {module:echarts/model/SeriesModel} seriesModel
 * @param index
 */
export function getCurvenessForEdge(edge, seriesModel, index, needReverse) {
    const autoCurvenessParams = getAutoCurvenessParams(seriesModel);
    const isArrayParam = Object.prototype.toString.call(autoCurvenessParams) === '[object Array]';
    if (!autoCurvenessParams) {
        return null;
    }

    var edgeArray = getEdgeFromMap(edge, seriesModel);
    if (!edgeArray) {
        return null;
    }

    var edgeIndex = -1;
    for (var i = 0; i < edgeArray.length; i++) {
        if (edgeArray[i] === index) {
            edgeIndex = i;
            break;
        }
    }
    // if totalLen is Longer createCurveness
    var totalLen = getTotalLengthBetweenNodes(edge, seriesModel);
    createCurveness(seriesModel, totalLen);

    edge.lineStyle = edge.lineStyle || {};
    // if is opposite edge, must set curvenss to opposite number
    var curKey = getKeyOfEdges(edge.node1, edge.node2, seriesModel);
    var curvenessList = seriesModel._curvenessList;
    // if pass array no need parity
    var parityCorrection = isArrayParam ? 0 : totalLen % 2 ? 0 : 1;

    if (!edgeArray.isForward) {
        // the opposite edge show outside
        var oppositeKey = getOppositeKey(curKey);
        var len = getEdgeMapLengthWithKey(oppositeKey, seriesModel);
        var resValue = curvenessList[edgeIndex + len + parityCorrection];
        // isNeedReverse, simple, force type need reverse the curveness in the junction of the forword and the opposite
        if (needReverse) {
            // set as array may make the parity by add 1
            if (isArrayParam) {
                return ((len % 2 ? 0 : 1) + parityCorrection) % 2 ? resValue : -resValue;
            }
            else {
                return (len + parityCorrection) % 2 ? resValue : -resValue;
            }
        }
        else {
            return curvenessList[edgeIndex + len + parityCorrection];
        }
    }
    else {
        return curvenessList[edgeIndex];
    }
}
<commit_msg>fix(tree): code rebuild follow the review suggest #2<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements.  See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership.  The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License.  You may obtain a copy of the License at
*
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied.  See the License for the
* specific language governing permissions and limitations
* under the License.
*/

var KEY_DELIMITER = '-->';
/**
 * params handler
 * @param {module:echarts/model/SeriesModel} seriesModel
 * @returns {*}
 */
var getAutoCurvenessParams = function (seriesModel) {
    return seriesModel.get('autoCurveness') || null;
};

/**
 * Generate a list of edge curvatures, 20 is the default
 * @param {module:echarts/model/SeriesModel} seriesModel
 * @param {number} appendLength
 * @return  20 => [0, -0.2, 0.2, -0.4, 0.4, -0.6, 0.6, -0.8, 0.8, -1, 1, -1.2, 1.2, -1.4, 1.4, -1.6, 1.6, -1.8, 1.8, -2]
 */
var createCurveness = function (seriesModel, appendLength) {
    var autoCurvenessParmas = getAutoCurvenessParams(seriesModel);
    var length = 20;
    var curvenessList = [];

    // handler the function set
    if (typeof autoCurvenessParmas === 'number') {
        length = autoCurvenessParmas;
    }
    else if (Object.prototype.toString.call(autoCurvenessParmas) === '[object Array]') {
        seriesModel._curvenessList = autoCurvenessParmas;
        return;
    }

    // append length
    if (appendLength > length) {
        length = appendLength;
    }

    // make sure the length is even
    var len = length % 2 ? length + 2 : length + 3;
    curvenessList = [];

    for (var i = 0; i < len; i++) {
        curvenessList.push((i % 2 ? i + 1 : i) / 10 * (i % 2 ? -1 : 1));
    }
    seriesModel._curvenessList = curvenessList;
};

/**
 * Create different cache key data in the positive and negative directions, in order to set the curvature later
 * @param {number|string|module:echarts/data/Graph.Node} n1
 * @param {number|string|module:echarts/data/Graph.Node} n2
 * @param {module:echarts/model/SeriesModel} seriesModel
 * @returns {string} key
 */
var getKeyOfEdges = function (n1, n2, seriesModel) {
    var source = [n1.id, n1.dataIndex].join('.');
    var target = [n2.id, n2.dataIndex].join('.');
    return [seriesModel.uid, source, target].join(KEY_DELIMITER);
};

/**
 * get opposite key
 * @param {string} key
 * @returns {string}
 */
var getOppositeKey = function (key) {
    var keys = key.split(KEY_DELIMITER);
    return [keys[0], keys[2], keys[1]].join(KEY_DELIMITER);
};

/**
 * set edgeMap with key
 * @param {number|string|module:echarts/data/Graph.Node} n1
 * @param {number|string|module:echarts/data/Graph.Node} n2
 * @param {module:echarts/model/SeriesModel} seriesModel
 * @param {number} index
 */
var setEdgeToMap = function (n1, n2, seriesModel, index) {
    var key = getKeyOfEdges(n1, n2, seriesModel);
    var edgeMap = seriesModel._edgeMap;
    var oppositeEdges = edgeMap[getOppositeKey(key)];
    // set direction
    if (edgeMap[key] && !oppositeEdges) {
        edgeMap[key].isForward = true;
    }
    else if (oppositeEdges && edgeMap[key]) {
        oppositeEdges.isForward = true;
        edgeMap[key].isForward = false;
    }

    edgeMap[key] = edgeMap[key] || [];
    edgeMap[key].push(index);
};

/**
 * get edgeMap with key
 * @param edge
 * @param {module:echarts/model/SeriesModel} seriesModel
 */
var getEdgeFromMap = function (edge, seriesModel) {
    var key = getKeyOfEdges(edge.node1, edge.node2, seriesModel);
    return seriesModel._edgeMap[key];
};

/**
 * calculate all cases total length
 * @param edge
 * @param seriesModel
 * @returns {number}
 */
var getTotalLengthBetweenNodes = function (edge, seriesModel) {
    var len = getEdgeMapLengthWithKey(getKeyOfEdges(edge.node1, edge.node2, seriesModel), seriesModel);
    var lenV = getEdgeMapLengthWithKey(getKeyOfEdges(edge.node2, edge.node1, seriesModel), seriesModel);

    return len + lenV;
};

/**
 *
 * @param key
 */
var getEdgeMapLengthWithKey = function (key, seriesModel) {
    var edgeMap = seriesModel._edgeMap;
    return edgeMap[key] ? edgeMap[key].length : 0;
};

/**
 * Count the number of edges between the same two points, used to obtain the curvature table and the parity of the edge
 * @see /graph/GraphSeries.js@getInitialData
 * @param edges
 * @param {module:echarts/model/SeriesModel} seriesModel
 */
export function initCurvenessList(edges, seriesModel) {
    if (!getAutoCurvenessParams(seriesModel)) {
        return;
    }
    // Hang on this object 4 dispose
    seriesModel._curvenessList = seriesModel._curvenessList || [];
    // calc the array of curveness List
    createCurveness(seriesModel);
}

/**
 * create the edgeMap after addEdges
 * @see chart/helper/createGraphFromNodeEdge.js#L52
 * @param {number|string|module:echarts/data/Graph.Node} n1
 * @param {number|string|module:echarts/data/Graph.Node} n2
 * @param {module:echarts/model/SeriesModel} seriesModel
 * @param {number} dataIndex
 */
export function createEdgeMapForCurveness(n1, n2, seriesModel, dataIndex) {
    seriesModel._edgeMap = seriesModel._edgeMap || {};
    setEdgeToMap(n1, n2, seriesModel, dataIndex);
}

/**
 * get curvature for edge
 * @param edge
 * @param {module:echarts/model/SeriesModel} seriesModel
 * @param index
 */
export function getCurvenessForEdge(edge, seriesModel, index, needReverse) {
    const autoCurvenessParams = getAutoCurvenessParams(seriesModel);
    const isArrayParam = Object.prototype.toString.call(autoCurvenessParams) === '[object Array]';
    if (!autoCurvenessParams) {
        return null;
    }

    var edgeArray = getEdgeFromMap(edge, seriesModel);
    if (!edgeArray) {
        return null;
    }

    var edgeIndex = -1;
    for (var i = 0; i < edgeArray.length; i++) {
        if (edgeArray[i] === index) {
            edgeIndex = i;
            break;
        }
    }
    // if totalLen is Longer createCurveness
    var totalLen = getTotalLengthBetweenNodes(edge, seriesModel);
    createCurveness(seriesModel, totalLen);

    edge.lineStyle = edge.lineStyle || {};
    // if is opposite edge, must set curvenss to opposite number
    var curKey = getKeyOfEdges(edge.node1, edge.node2, seriesModel);
    var curvenessList = seriesModel._curvenessList;
    // if pass array no need parity
    var parityCorrection = isArrayParam ? 0 : totalLen % 2 ? 0 : 1;

    if (!edgeArray.isForward) {
        // the opposite edge show outside
        var oppositeKey = getOppositeKey(curKey);
        var len = getEdgeMapLengthWithKey(oppositeKey, seriesModel);
        var resValue = curvenessList[edgeIndex + len + parityCorrection];
        // isNeedReverse, simple, force type need reverse the curveness in the junction of the forword and the opposite
        if (needReverse) {
            // set as array may make the parity handle with the len of opposite
            if (isArrayParam) {
                if (autoCurvenessParams && autoCurvenessParams[0] === 0) {
                    return (len + parityCorrection) % 2 ? resValue : -resValue;
                }
                else {
                    return ((len % 2 ? 0 : 1) + parityCorrection) % 2 ? resValue : -resValue;
                }
            }
            else {
                return (len + parityCorrection) % 2 ? resValue : -resValue;
            }
        }
        else {
            return curvenessList[edgeIndex + len + parityCorrection];
        }
    }
    else {
        return curvenessList[edgeIndex];
    }
}
<|endoftext|>


<commit_before>/* eslint-disable react/forbid-prop-types */
/* eslint-disable import/prefer-default-export */
/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */

import React, { useCallback } from 'react';
import PropTypes from 'prop-types';
import { View } from 'react-native';

import { recordKeyExtractor, getItemLayout } from './dataTableUtilities/utilities';
import { UIDatabase } from '../database';

import { DataTable, DataTableHeaderRow, DataTableRow } from '../widgets/DataTable';

import { newPageStyles } from '../globalStyles';
import { usePageReducer, useSyncListener } from '../hooks';

import { DataTablePageView, SearchBar } from '../widgets';

import { ItemDetails } from '../widgets/modals/ItemDetails';

const stateInitialiser = () => {
  const backingData = UIDatabase.objects('Item').sorted('name');

  return {
    backingData,
    data: backingData.slice(),
    keyExtractor: recordKeyExtractor,
    dataState: new Map(),
    searchTerm: '',
    filterDataKeys: ['item.name'],
    sortBy: 'itemName',
    isAscending: true,
    selectedRow: null,
  };
};

/**
 * Renders a mSupply mobile page with customer invoice loaded for editing
 *
 * State:
 * Uses a reducer to manage state with `backingData` being a realm results
 * of items to display. `data` is a plain JS array of realm objects. data is
 * hydrated from the `backingData` for displaying in the interface.
 * i.e: When filtering, data is populated from filtered items of `backingData`.
 *
 * dataState is a simple map of objects corresponding to a row being displayed,
 * holding the state of a given row. Each object has the shape :
 * { isSelected, isFocused, isDisabled },
 *
 * @prop {Object} transaction The realm transaction object for this invoice.
 * @prop {Func} runWithLoadingIndicator Callback for displaying a fullscreen spinner.
 * @prop {String} routeName The current route name for the top of the navigation stack.
 */
export const StockPage = ({ routeName }) => {
  const [state, dispatch, instantDebouncedDispatch] = usePageReducer(
    routeName,
    {},
    stateInitialiser
  );

  const {
    data,
    dataState,
    sortBy,
    isAscending,
    selectedRow,
    searchTerm,
    keyExtractor,
    columns,
    PageActions,
  } = state;

  //  Refresh data on retrieving item or itembatch records from sync.
  const refreshCallback = () => dispatch(PageActions.refreshData());
  useSyncListener(refreshCallback, ['Item', 'ItemBatch']);

  const onSelectRow = useCallback(({ id }) => dispatch(PageActions.selectOneRow(id)), []);
  const onDeselectRow = () => dispatch(PageActions.deselectRow(selectedRow.id));
  const onFilterData = value => PageActions.filterData(value);

  const renderRow = useCallback(
    listItem => {
      const { item, index } = listItem;
      const rowKey = keyExtractor(item);
      return (
        <DataTableRow
          rowData={data[index]}
          rowState={dataState.get(rowKey)}
          rowKey={rowKey}
          columns={columns}
          isFinalised={false}
          dispatch={dispatch}
          rowIndex={index}
          onPress={onSelectRow}
        />
      );
    },
    [data, dataState]
  );

  const renderHeader = () => (
    <DataTableHeaderRow
      columns={columns}
      dispatch={instantDebouncedDispatch}
      sortAction={PageActions.sortData}
      isAscending={isAscending}
      sortBy={sortBy}
    />
  );

  const { newPageTopSectionContainer } = newPageStyles;
  return (
    <DataTablePageView>
      <View style={newPageTopSectionContainer}>
        <SearchBar
          onChangeText={onFilterData}
          value={searchTerm}
          onFocusOrBlur={selectedRow && onDeselectRow}
        />
      </View>

      <DataTable
        data={data}
        extraData={dataState}
        renderRow={renderRow}
        renderHeader={renderHeader}
        keyExtractor={keyExtractor}
        getItemLayout={getItemLayout}
        columns={columns}
      />

      <ItemDetails isOpen={!!selectedRow} item={selectedRow} onClose={onDeselectRow} />
    </DataTablePageView>
  );
};

StockPage.propTypes = {
  routeName: PropTypes.string.isRequired,
};
<commit_msg>Add update doc string<commit_after>/* eslint-disable react/forbid-prop-types */
/* eslint-disable import/prefer-default-export */
/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */

import React, { useCallback } from 'react';
import PropTypes from 'prop-types';
import { View } from 'react-native';

import { recordKeyExtractor, getItemLayout } from './dataTableUtilities/utilities';
import { UIDatabase } from '../database';

import { DataTable, DataTableHeaderRow, DataTableRow } from '../widgets/DataTable';

import { newPageStyles } from '../globalStyles';
import { usePageReducer, useSyncListener } from '../hooks';

import { DataTablePageView, SearchBar } from '../widgets';

import { ItemDetails } from '../widgets/modals/ItemDetails';

const stateInitialiser = () => {
  const backingData = UIDatabase.objects('Item').sorted('name');

  return {
    backingData,
    data: backingData.slice(),
    keyExtractor: recordKeyExtractor,
    dataState: new Map(),
    searchTerm: '',
    filterDataKeys: ['item.name'],
    sortBy: 'itemName',
    isAscending: true,
    selectedRow: null,
  };
};

/**
 * Renders a mSupply mobile page with Items and their stock levels.
 *
 * State:
 * Uses a reducer to manage state with `backingData` being a realm results
 * of items to display. `data` is a plain JS array of realm objects. data is
 * hydrated from the `backingData` for displaying in the interface.
 * i.e: When filtering, data is populated from filtered items of `backingData`.
 *
 * dataState is a simple map of objects corresponding to a row being displayed,
 * holding the state of a given row. Each object has the shape :
 * { isSelected, isFocused, isDisabled },
 *
 * @prop {Object} routeName Name of the current route.
 */
export const StockPage = ({ routeName }) => {
  const [state, dispatch, instantDebouncedDispatch] = usePageReducer(
    routeName,
    {},
    stateInitialiser
  );

  const {
    data,
    dataState,
    sortBy,
    isAscending,
    selectedRow,
    searchTerm,
    keyExtractor,
    columns,
    PageActions,
  } = state;

  //  Refresh data on retrieving item or itembatch records from sync.
  const refreshCallback = () => dispatch(PageActions.refreshData());
  useSyncListener(refreshCallback, ['Item', 'ItemBatch']);

  const onSelectRow = useCallback(({ id }) => dispatch(PageActions.selectOneRow(id)), []);
  const onDeselectRow = () => dispatch(PageActions.deselectRow(selectedRow.id));
  const onFilterData = value => PageActions.filterData(value);

  const renderRow = useCallback(
    listItem => {
      const { item, index } = listItem;
      const rowKey = keyExtractor(item);
      return (
        <DataTableRow
          rowData={data[index]}
          rowState={dataState.get(rowKey)}
          rowKey={rowKey}
          columns={columns}
          isFinalised={false}
          dispatch={dispatch}
          rowIndex={index}
          onPress={onSelectRow}
        />
      );
    },
    [data, dataState]
  );

  const renderHeader = () => (
    <DataTableHeaderRow
      columns={columns}
      dispatch={instantDebouncedDispatch}
      sortAction={PageActions.sortData}
      isAscending={isAscending}
      sortBy={sortBy}
    />
  );

  const { newPageTopSectionContainer } = newPageStyles;
  return (
    <DataTablePageView>
      <View style={newPageTopSectionContainer}>
        <SearchBar
          onChangeText={onFilterData}
          value={searchTerm}
          onFocusOrBlur={selectedRow && onDeselectRow}
        />
      </View>

      <DataTable
        data={data}
        extraData={dataState}
        renderRow={renderRow}
        renderHeader={renderHeader}
        keyExtractor={keyExtractor}
        getItemLayout={getItemLayout}
        columns={columns}
      />

      <ItemDetails isOpen={!!selectedRow} item={selectedRow} onClose={onDeselectRow} />
    </DataTablePageView>
  );
};

StockPage.propTypes = {
  routeName: PropTypes.string.isRequired,
};
<|endoftext|>


<commit_before>/**
 * @file moderationLog event
 * @author Sankarsan Kampa (a.k.a k3rn31p4nic)
 * @license MIT
 */

/**
 * @param {Guild} guild The guild where this moderation action was fired
 * @param {User} executor The user who fired this moderation action
 * @param {string} action The moderation action's name
 * @param {User|Channel} target The target on which this action was taken
 * @param {string} reason The reason for the moderation action
 * @param {object} extras An object containing any extra data of the moderation action
 * @returns {void}
 */
module.exports = async (guild, executor, action, target, reason, extras) => {
  try {
    let guildSettings = await guild.client.db.get(`SELECT modLog, modCaseNo FROM guildSettings WHERE guildID=${guild.id}`);
    if (!guildSettings || !guildSettings.modLog) return;

    let modLogChannel = guild.channels.get(guildSettings.modLog);
    if (!modLogChannel) return;

    let modCaseNo = parseInt(guildSettings.modCaseNo), color,
      logData = [
        {
          name: 'User',
          value: `${target}`,
          inline: true
        },
        {
          name: 'User ID',
          value: target.id,
          inline: true
        },
        {
          name: 'Reason',
          value: reason || 'No reason given'
        },
        {
          name: 'Responsible Moderator',
          value: `${executor}`,
          inline: true
        },
        {
          name: 'Moderator ID',
          value: executor.id,
          inline: true
        }
      ];

    switch (action.toLowerCase()) {
      case 'addrole':
        action = guild.client.strings.events(guild.language, 'addRole');
        color = guild.client.colors.GREEN;
        logData.unshift(
          {
            name: 'Role',
            value: extras.role.name
          }
        );
        break;

      case 'ban':
        action = guild.client.strings.events(guild.language, 'guildBanAdd');
        color = guild.client.colors.RED;
        break;

      case 'clear':
        action = guild.client.strings.events(guild.language, 'messageClear');
        color = guild.client.colors.RED;
        logData.splice(0, 3,
          {
            name: 'Channel',
            value: `${target}`,
            inline: true
          },
          {
            name: 'Channel ID',
            value: target.id,
            inline: true
          },
          {
            name: 'Cleared',
            value: extras.cleared
          }
        );
        break;

      case 'deafen':
        action = guild.client.strings.events(guild.language, 'deafAdd');
        color = guild.client.colors.ORANGE;
        break;

      case 'kick':
        action = guild.client.strings.events(guild.language, 'kick');
        color = guild.client.colors.RED;
        break;

      case 'mute':
        action = guild.client.strings.events(guild.language, 'voiceMuteAdd');
        color = guild.client.colors.ORANGE;
        break;

      /*
      case 'nickname':
        action = 'Updated User Nickname';
        color = guild.client.colors.ORANGE;
        logData.push();
        break;
      */

      case 'removeallroles':
        action = guild.client.strings.events(guild.language, 'removeAllRole');
        color = guild.client.colors.RED;
        break;

      case 'removerole':
        action = guild.client.strings.events(guild.language, 'removeRole');
        color = guild.client.colors.RED;
        logData.unshift(
          {
            name: 'Role',
            value: extras.role.name
          }
        );
        break;

      case 'report':
        action = guild.client.strings.events(guild.language, 'userReport');
        color = guild.client.colors.ORANGE;
        logData.splice(logData.length - 2, 2,
          {
            name: 'Reporter',
            value: `${executor}`,
            inline: true
          },
          {
            name: 'Reporter ID',
            value: executor.id,
            inline: true
          }
        );
        break;

      case 'softban':
        action = guild.client.strings.events(guild.language, 'userSoftBan');
        color = guild.client.colors.RED;
        break;

      case 'textmute':
        action = guild.client.strings.events(guild.language, 'textMuteAdd');
        color = guild.client.colors.ORANGE;
        logData.splice(logData.length - 2, 0,
          {
            name: 'Channel',
            value: `${extras.channel}`
          }
        );
        break;

      case 'textunmute':
        action = guild.client.strings.events(guild.language, 'textMuteRemove');
        color = guild.client.colors.GREEN;
        logData.splice(logData.length - 2, 0,
          {
            name: 'Channel',
            value: `${extras.channel}`
          }
        );
        break;

      case 'unban':
        action = guild.client.strings.events(guild.language, 'guildBanRemove');
        color = guild.client.colors.GREEN;
        break;

      case 'undeafen':
        action = guild.client.strings.events(guild.language, 'deafRemove');
        color = guild.client.colors.GREEN;
        break;

      case 'unmute':
        action = guild.client.strings.events(guild.language, 'voiceMuteRemove');
        color = guild.client.colors.GREEN;
        break;

      case 'warn':
        action = guild.client.strings.events(guild.language, 'userWarnAdd');
        color = guild.client.colors.ORANGE;
        break;

      case 'clearWarn':
        action = guild.client.strings.events(guild.language, 'userWarnRemove');
        color = guild.client.colors.GREEN;
        break;

      default:
        return guild.client.log.error(`Moderation logging is not present for ${action} action.`);
    }

    modLogChannel.send({
      embed: {
        color: color,
        title: action,
        fields: logData,
        footer: {
          text: `Case Number: ${modCaseNo}`
        },
        timestamp: new Date()
      }
    }).catch(e => {
      guild.client.log.error(e);
    });

    await guild.client.db.run(`UPDATE guildSettings SET modCaseNo='${modCaseNo + 1}' WHERE guildID=${guild.id}`);
  }
  catch (e) {
    guild.client.log.error(e);
  }
};
<commit_msg>Fix clearwarn not triggering moderationlog<commit_after>/**
 * @file moderationLog event
 * @author Sankarsan Kampa (a.k.a k3rn31p4nic)
 * @license MIT
 */

/**
 * @param {Guild} guild The guild where this moderation action was fired
 * @param {User} executor The user who fired this moderation action
 * @param {string} action The moderation action's name
 * @param {User|Channel} target The target on which this action was taken
 * @param {string} reason The reason for the moderation action
 * @param {object} extras An object containing any extra data of the moderation action
 * @returns {void}
 */
module.exports = async (guild, executor, action, target, reason, extras) => {
  try {
    let guildSettings = await guild.client.db.get(`SELECT modLog, modCaseNo FROM guildSettings WHERE guildID=${guild.id}`);
    if (!guildSettings || !guildSettings.modLog) return;

    let modLogChannel = guild.channels.get(guildSettings.modLog);
    if (!modLogChannel) return;

    let modCaseNo = parseInt(guildSettings.modCaseNo), color,
      logData = [
        {
          name: 'User',
          value: `${target}`,
          inline: true
        },
        {
          name: 'User ID',
          value: target.id,
          inline: true
        },
        {
          name: 'Reason',
          value: reason || 'No reason given'
        },
        {
          name: 'Responsible Moderator',
          value: `${executor}`,
          inline: true
        },
        {
          name: 'Moderator ID',
          value: executor.id,
          inline: true
        }
      ];

    switch (action.toLowerCase()) {
      case 'addrole':
        action = guild.client.strings.events(guild.language, 'addRole');
        color = guild.client.colors.GREEN;
        logData.unshift(
          {
            name: 'Role',
            value: extras.role.name
          }
        );
        break;

      case 'ban':
        action = guild.client.strings.events(guild.language, 'guildBanAdd');
        color = guild.client.colors.RED;
        break;

      case 'clear':
        action = guild.client.strings.events(guild.language, 'messageClear');
        color = guild.client.colors.RED;
        logData.splice(0, 3,
          {
            name: 'Channel',
            value: `${target}`,
            inline: true
          },
          {
            name: 'Channel ID',
            value: target.id,
            inline: true
          },
          {
            name: 'Cleared',
            value: extras.cleared
          }
        );
        break;

      case 'deafen':
        action = guild.client.strings.events(guild.language, 'deafAdd');
        color = guild.client.colors.ORANGE;
        break;

      case 'kick':
        action = guild.client.strings.events(guild.language, 'kick');
        color = guild.client.colors.RED;
        break;

      case 'mute':
        action = guild.client.strings.events(guild.language, 'voiceMuteAdd');
        color = guild.client.colors.ORANGE;
        break;

      /*
      case 'nickname':
        action = 'Updated User Nickname';
        color = guild.client.colors.ORANGE;
        logData.push();
        break;
      */

      case 'removeallroles':
        action = guild.client.strings.events(guild.language, 'removeAllRole');
        color = guild.client.colors.RED;
        break;

      case 'removerole':
        action = guild.client.strings.events(guild.language, 'removeRole');
        color = guild.client.colors.RED;
        logData.unshift(
          {
            name: 'Role',
            value: extras.role.name
          }
        );
        break;

      case 'report':
        action = guild.client.strings.events(guild.language, 'userReport');
        color = guild.client.colors.ORANGE;
        logData.splice(logData.length - 2, 2,
          {
            name: 'Reporter',
            value: `${executor}`,
            inline: true
          },
          {
            name: 'Reporter ID',
            value: executor.id,
            inline: true
          }
        );
        break;

      case 'softban':
        action = guild.client.strings.events(guild.language, 'userSoftBan');
        color = guild.client.colors.RED;
        break;

      case 'textmute':
        action = guild.client.strings.events(guild.language, 'textMuteAdd');
        color = guild.client.colors.ORANGE;
        logData.splice(logData.length - 2, 0,
          {
            name: 'Channel',
            value: `${extras.channel}`
          }
        );
        break;

      case 'textunmute':
        action = guild.client.strings.events(guild.language, 'textMuteRemove');
        color = guild.client.colors.GREEN;
        logData.splice(logData.length - 2, 0,
          {
            name: 'Channel',
            value: `${extras.channel}`
          }
        );
        break;

      case 'unban':
        action = guild.client.strings.events(guild.language, 'guildBanRemove');
        color = guild.client.colors.GREEN;
        break;

      case 'undeafen':
        action = guild.client.strings.events(guild.language, 'deafRemove');
        color = guild.client.colors.GREEN;
        break;

      case 'unmute':
        action = guild.client.strings.events(guild.language, 'voiceMuteRemove');
        color = guild.client.colors.GREEN;
        break;

      case 'warn':
        action = guild.client.strings.events(guild.language, 'userWarnAdd');
        color = guild.client.colors.ORANGE;
        break;

      case 'clearwarn':
        action = guild.client.strings.events(guild.language, 'userWarnRemove');
        color = guild.client.colors.GREEN;
        break;

      default:
        return guild.client.log.error(`Moderation logging is not present for ${action} action.`);
    }

    modLogChannel.send({
      embed: {
        color: color,
        title: action,
        fields: logData,
        footer: {
          text: `Case Number: ${modCaseNo}`
        },
        timestamp: new Date()
      }
    }).catch(e => {
      guild.client.log.error(e);
    });

    await guild.client.db.run(`UPDATE guildSettings SET modCaseNo='${modCaseNo + 1}' WHERE guildID=${guild.id}`);
  }
  catch (e) {
    guild.client.log.error(e);
  }
};
<|endoftext|>


<commit_before>/*"""
===================================
tester.js
===================================
A base JavaScript tester class.
*/
'use strict';

require.config({
    shim: {},
});

define([], function() {
    class Tester {
        /*"""
        Tester
        ============
        Base class for testing applications
        */
        constructor() {
            this.obj = 42;
        };
    };

    return Tester;
});
<commit_msg>testing tester<commit_after>/*"""
===================================
tester.js
===================================
A base JavaScript tester class.
*/
'use strict';

/*require.config({
    shim: {},
});

define([], function() {
    class Tester {
        /*"""
        Tester
        ============
        Base class for testing applications
        */
/*        constructor() {
            this.obj = 42;
        };
    };

    return Tester;
});
*/

class Tester {
    constructor() {
        this.obj = 42;
    };
};
<|endoftext|>


<commit_before>"use strict";

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

/**
 * For this example to run properly you must create an api app at developer.vimeo.com/apps/new and set your callback url to http://localhost:8080/oauth_callback
 *
 */
var vimeo_module = require('../index');
var Vimeo = vimeo_module.Vimeo;
var util_module = require('util');

try {
	var config = require('./config.json');
} catch (error) {
	console.error('ERROR: For this example to run properly you must create an api app at developer.vimeo.com/apps/new and set your callback url to http://localhost:8080/oauth_callback');
	console.error('ERROR: Once you have your app, make a copy of config.json.example named "config.json" and add your client id and client secret');
	return;
}

var http_module = require('http');
var url_module = require('url');

var state_data = {
	state : "unauthorized"
};

// Here we have to build the vimeo library using the client_id and client_secret
// We do not need an access token here because we will generate one
// If we already knew our access token, we can provide it as the third parameter
var lib = new Vimeo(config.client_id, config.client_secret);

// The authorization process requires the user to be redirected back to a webpage, so we can start up a simple http server here
var server = http_module.createServer(function (request, response) {
	var url = url_module.parse(request.url, true);

	// Once the user accepts your app, they will be redirected back to localhost:8080/oauth_callback.
	// If they are not redirected you should check your apps configuration on developer.vimeo.com/apps
	if (url.pathname === '/oauth_callback') {
		if (url.query.state !== 'abcdefg') {
			throw new Error('invalid state');
		}

		if (!url.query.error) {
			// At this state (a request to /oauth_callback without an error parameter)
			// the user has been redirected back to the app and you can exchange the "code" parameter for an access token
			console.info('successful oauth callback request');
			lib.accessToken(url.query.code, 'http://localhost:8080/oauth_callback', function (err, token) {
				if (err) {
					return response.end("error\n" + err);
				}

				if (token.access_token) {
					// At this state the code has been successfully exchanged for an access token
					lib.access_token = token.access_token;
					state_data.user = token.user;
					state_data.state = "authorized";
					response.statusCode = 302;
					response.setHeader('Location', '/');
					response.end();
				} else {
					throw new Error('no access token provided');
				}
			});
		} else {
			// At this state (a request to /oauth_callback with an error parameter)
			// something went wrong when you sent your user to Vimeo.com. The error parameter should tell you more
			console.error('failed oauth callback request');
			console.error(url.query.error);

			response.setHeader('Content-Type', 'text/html');
			response.write('Your command line is currently unauthenticated. Please ');
			response.end('Link with Vimeo
' + JSON.stringify(url.query));
		}

	} else {
		if (state_data.state !== "authorized") {
			// At this state (any request where state_data.state has not been set to "authorized")
			// we do not have an authentication token, so we need to send the user to Vimeo.
			console.info('http request without access token');
			response.setHeader('Content-Type', 'text/html');
			response.write('Your command line is currently unauthenticated. Please ');
			response.end('Link with Vimeo');
		} else {
			// At this state (state_data.state has been set to "authorized" when we retrieved the access token)
			// we can make authenticated api requests
			console.info('http request with access token');
			response.setHeader('Content-Type', 'text/html');
			response.end('Your command line is currently authorized with the user : ' + state_data.user.name + '. You can make api requests via the command line using the "request" function, or upload files using the "upload" function.
 Try "request(\'/me\');"');
		}
	}
});

server.listen(8080, function () {
	console.log('Server started on 8080');
});

var context = require('repl').start({}).context;

/**
 * This will upload the video to the authenticated account.
 *
 * @param  {string} path The path to the video file
 */
context.upload = function (path) {
	lib.streamingUpload(path, function (err, data, status, headers) {
		if (err) {
			console.log('---upload error---');
			console.log('error');
			console.log(err);
			console.log('response body');
			console.log(data);
			console.log('response status');
			console.log(status);
			console.log('response headers');
			console.log(headers);
		} else {
			console.log('---upload success---');
			console.log('response body');
			console.log(data);
			console.log('response status');
			console.log(status);
			console.log('response headers');
			console.log(headers);
		}
	});
};

/**
 * This method lets you make api requests.
 *
 * options.method is a string of the HTTP method for the request (GET, POST, PUT, PATCH, DELETE)
 * options.path is a string of the path portion of a url (eg. /users/dashron)
 * options.query is an object containing all of your request parameters. If GET they will be appended to the url, if POST it will be part of your request body
 * options.headers is an object containing key value pairings of all of the HTTP request headers
 *
 * @param  {Object|String} options If string, it will make a GET request to that url. If an object, you can provide many parameters. See the function description for more.
 */
context.request = function (options) {
	if (typeof options === "string") {
		options = {path : options};
	}

	lib.request(options, function (err, data, status, headers) {
		if (err) {
			console.log('---request error---');
			console.log('status');
			console.log(status);
			console.log('headers');
			console.log(headers);

			console.log('error');
			console.log(util_module.inspect(err));
		} else {
			console.log('---request success---');
			console.log('status');
			console.log(status);
			console.log('headers');
			console.log(headers);

			console.log('response');
			console.log(data);
		}
	});
};
<commit_msg>clean up auth example and make it easier to support<commit_after>"use strict";

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

/**
 * For this example to run properly you must create an api app at developer.vimeo.com/apps/new and set your callback url to http://localhost:8080/oauth_callback
 *
 */
var vimeo_module = require('../index');
var Vimeo = vimeo_module.Vimeo;
var util_module = require('util');

try {
	var config = require('./config.json');
} catch (error) {
	console.error('ERROR: For this example to run properly you must create an api app at developer.vimeo.com/apps/new and set your callback url to http://localhost:8080/oauth_callback');
	console.error('ERROR: Once you have your app, make a copy of config.json.example named "config.json" and add your client id and client secret');
	return;
}

var http_module = require('http');
var url_module = require('url');

var state_data = {
	state : "unauthorized"
};

// Here we have to build the vimeo library using the client_id and client_secret
// We do not need an access token here because we will generate one
// If we already knew our access token, we can provide it as the third parameter
var lib = new Vimeo(config.client_id, config.client_secret);

var scopes = ['public', 'private', 'edit', 'interact'];
var callback_url = 'http://localhost:8080/oauth_callback';

// The authorization process requires the user to be redirected back to a webpage, so we can start up a simple http server here
var server = http_module.createServer(function (request, response) {
	var url = url_module.parse(request.url, true);

	// Once the user accepts your app, they will be redirected back to localhost:8080/oauth_callback.
	// If they are not redirected you should check your apps configuration on developer.vimeo.com/apps
	if (url.pathname === '/oauth_callback') {
		if (url.query.state !== 'abcdefg') {
			throw new Error('invalid state');
		}

		if (!url.query.error) {
			// At this state (a request to /oauth_callback without an error parameter)
			// the user has been redirected back to the app and you can exchange the "code" parameter for an access token
			console.info('successful oauth callback request');
			lib.accessToken(url.query.code, callback_url, function (err, token) {
				if (err) {
					return response.end("error\n" + err);
				}

				if (token.access_token) {
					// At this state the code has been successfully exchanged for an access token
					lib.access_token = token.access_token;
					state_data.user = token.user;
					state_data.state = "authorized";
					response.statusCode = 302;
					response.setHeader('Location', '/');
					response.end();
				} else {
					throw new Error('no access token provided');
				}
			});
		} else {
			// At this state (a request to /oauth_callback with an error parameter)
			// something went wrong when you sent your user to Vimeo.com. The error parameter should tell you more
			console.error('failed oauth callback request');
			console.error(url.query.error);

			response.setHeader('Content-Type', 'text/html');
			response.write('Your command line is currently unauthenticated. Please ');
			response.end('Link with Vimeo
' + JSON.stringify(url.query));
		}

	} else {
		if (state_data.state !== "authorized") {
			// At this state (any request where state_data.state has not been set to "authorized")
			// we do not have an authentication token, so we need to send the user to Vimeo.
			console.info('http request without access token');
			response.setHeader('Content-Type', 'text/html');
			response.write('Your command line is currently unauthenticated. Please ');
			response.end('Link with Vimeo');
		} else {
			// At this state (state_data.state has been set to "authorized" when we retrieved the access token)
			// we can make authenticated api requests
			console.info('http request with access token');
			response.setHeader('Content-Type', 'text/html');
			response.end('Your command line is currently authorized with the user : ' + state_data.user.name + '. You can make api requests via the command line using the "request" function, or upload files using the "upload" function.
 Try "request(\'/me\');"');
		}
	}
});

server.listen(8080, function () {
	console.log('Server started on 8080');
});

var context = require('repl').start({}).context;

/**
 * This will upload the video to the authenticated account.
 *
 * @param  {string} path The path to the video file
 */
context.upload = function (path) {
	lib.streamingUpload(path, function (err, data, status, headers) {
		if (err) {
			console.log('---upload error---');
			console.log('error');
			console.log(err);
			console.log('response body');
			console.log(data);
			console.log('response status');
			console.log(status);
			console.log('response headers');
			console.log(headers);
		} else {
			console.log('---upload success---');
			console.log('response body');
			console.log(data);
			console.log('response status');
			console.log(status);
			console.log('response headers');
			console.log(headers);
		}
	});
};

/**
 * This method lets you make api requests.
 *
 * options.method is a string of the HTTP method for the request (GET, POST, PUT, PATCH, DELETE)
 * options.path is a string of the path portion of a url (eg. /users/dashron)
 * options.query is an object containing all of your request parameters. If GET they will be appended to the url, if POST it will be part of your request body
 * options.headers is an object containing key value pairings of all of the HTTP request headers
 *
 * @param  {Object|String} options If string, it will make a GET request to that url. If an object, you can provide many parameters. See the function description for more.
 */
context.request = function (options) {
	if (typeof options === "string") {
		options = {path : options};
	}

	lib.request(options, function (err, data, status, headers) {
		if (err) {
			console.log('---request error---');
			console.log('status');
			console.log(status);
			console.log('headers');
			console.log(headers);

			console.log('error');
			console.log(util_module.inspect(err));
		} else {
			console.log('---request success---');
			console.log('status');
			console.log(status);
			console.log('headers');
			console.log(headers);

			console.log('response');
			console.log(data);
		}
	});
};
<|endoftext|>


<commit_before>const format_currency = require('../../common_functions/currency_to_symbol').format_currency;
const MBDefaults = require('./mb_defaults').MBDefaults;
const japanese_client = require('../../common_functions/country_base').japanese_client;
const State  = require('../../base/storage').State;
const Client = require('../../base/client').Client;

/*
 * Handles currency display
 *
 * It process 'socket.send({payout_currencies:1})` response
 * and display them
 */
function MBDisplayCurrencies(selected, showClass) {
    'use strict';

    const target = document.getElementById('currency'),
        fragment =  document.createDocumentFragment(),
        currencies = Client.get_value('currencies').split(',');

    if (!target) {
        return;
    }

    while (target && target.firstChild) {
        target.removeChild(target.firstChild);
    }

    if (currencies.length > 1 && !japanese_client()) {
        currencies.forEach(function (currency) {
            const option = document.createElement('option'),
                content = document.createTextNode(currency);

            option.setAttribute('value', currency);
            /* if (selected && selected == key) {
                option.setAttribute('selected', 'selected');
            }*/

            option.appendChild(content);
            fragment.appendChild(option);
        });

        target.appendChild(fragment);
        MBDefaults.set('currency', target.value);
    } else {
        $('#currency').replaceWith('' +
                                    (State.get('is_mb_trading') && japanese_client() ? '✕' : format_currency(currencies[0])) + '');
        MBDefaults.set('currency', currencies[0]);
    }
}

module.exports = {
    MBDisplayCurrencies: MBDisplayCurrencies,
};
<commit_msg>Widen payout width<commit_after>const format_currency = require('../../common_functions/currency_to_symbol').format_currency;
const MBDefaults = require('./mb_defaults').MBDefaults;
const japanese_client = require('../../common_functions/country_base').japanese_client;
const State  = require('../../base/storage').State;
const Client = require('../../base/client').Client;

/*
 * Handles currency display
 *
 * It process 'socket.send({payout_currencies:1})` response
 * and display them
 */
function MBDisplayCurrencies(selected, showClass) {
    'use strict';

    const target = document.getElementById('currency'),
        fragment =  document.createDocumentFragment(),
        currencies = Client.get_value('currencies').split(',');

    if (!target) {
        return;
    }

    while (target && target.firstChild) {
        target.removeChild(target.firstChild);
    }

    if (currencies.length > 1 && !japanese_client()) {
        currencies.forEach(function (currency) {
            const option = document.createElement('option'),
                content = document.createTextNode(currency);

            option.setAttribute('value', currency);
            /* if (selected && selected == key) {
                option.setAttribute('selected', 'selected');
            }*/

            option.appendChild(content);
            fragment.appendChild(option);
        });

        target.appendChild(fragment);
        MBDefaults.set('currency', target.value);
    } else {
        $('#currency').replaceWith('' +
                                    (State.get('is_mb_trading') && japanese_client() ? '✕' : format_currency(currencies[0])) + '');
        if ($('.payout-mult:visible').length === 0) $('#payout').width(40); // wider when there is free space
        MBDefaults.set('currency', currencies[0]);
    }
}

module.exports = {
    MBDisplayCurrencies: MBDisplayCurrencies,
};
<|endoftext|>


<commit_before>define(function(require, exports, module) {
    "use strict";
    main.consumes = [
        "Plugin", "commands", "menus", "ace"
    ];
    main.provides = ["emmet"];
    return main;

    function main(options, imports, register) {
        var Plugin = imports.Plugin;
        var commands = imports.commands;
        var menus = imports.menus;

        var emmetExt = require("ace/ext/emmet");
        emmetExt.setCore("lib/emmet/emmet");
        emmetExt.updateCommands = function() {};

        /***** Initialization *****/

        var plugin = new Plugin("Ajax.org", main.consumes);
        var emit = plugin.getEmitter();

        var loaded = false;
        function load() {
            if (loaded) return false;
            loaded = true;

            var keymap = {
                expand_abbreviation: {mac: "ctrl+alt+e", win: "ctrl+alt+e"},
                match_pair_outward: {}, // {mac: "ctrl+d", win: "ctrl+,"},
                match_pair_inward: {}, // {mac: "ctrl+j", win: "ctrl+shift+0"},
                matching_pair:  {}, // {mac: "ctrl+alt+j", win: "alt+j"},
                next_edit_point:  {}, // "alt+right",
                prev_edit_point:  {}, // "alt+left",
                toggle_comment: {}, // {mac: "command+/", win: "ctrl+/"},
                split_join_tag:  {}, // {mac: "shift+command+'", win: "shift+ctrl+`"},
                remove_tag:  {}, // {mac: "command+'", win: "shift+ctrl+;"},
                evaluate_math_expression:  {mac: "shift+command+y", win: "shift+ctrl+y"},
                increment_number_by_1:  {}, // "ctrl+up",
                decrement_number_by_1:  {}, // "ctrl+down",
                increment_number_by_01:  {}, // "alt+up",
                decrement_number_by_01:  {}, // "alt+down",
                increment_number_by_10:  {}, // {mac: "alt+command+up", win: "shift+alt+up"},
                decrement_number_by_10:  {}, // {mac: "alt+command+down", win: "shift+alt+down"},
                select_next_item: {mac: "shift+command+.", win: "shift+ctrl+."},
                select_previous_item: {mac: "shift+command+,", win: "shift+ctrl+,"},
                reflect_css_value:  {}, // {mac: "shift+command+r", win: "shift+ctrl+r"},

                // encode_decode_data_url:  {}, // {mac: "shift+ctrl+d", win: "ctrl+'"},
                // update_image_size: {mac: "shift+ctrl+i", win: "ctrl+u"},
                // expand_as_you_type: "ctrl+alt+enter",
                // wrap_as_you_type: {mac: "shift+ctrl+g", win: "shift+ctrl+g"},
                expand_abbreviation_with_tab: {mac: "Tab", win: "Tab"},
                wrap_with_abbreviation: {mac: "shift+ctrl+a", win: "shift+ctrl+a"}
            };

            for (var i in keymap) {
                commands.addCommand({
                    name: "emmet_" + i,
                    action: i,
                    group: "emmet",
                    bindKey: keymap[i],
                    exec: emmetExt.runEmmetCommand,
                    isAvailable: isAvailable,
                    findEditor: findEditor
                }, plugin);
            }
        }

        var drawn = false;
        function draw() {
            if (drawn) return;
            drawn = true;

            // TODO add menu items?

            emit("draw");
        }

        /***** Methods *****/

        function show() {
            draw();
        }

        function isAvailable(editor, args, event) {
            if (!editor || !editor.ace) return false;

            // using this instead of editor.type == "ace" to make
            // commands avaliable in editors inheriting from ace
            if (event instanceof KeyboardEvent && (!editor.ace.isFocused()))
                return false;

            return emmetExt.isSupportedMode(editor.ace.session.$modeId);
        }

        function findEditor(editor) {
            if (editor && editor.ace)
                return editor.ace;
            return editor;
        }

        /***** Lifecycle *****/

        plugin.on("load", function() {
            load();
        });
        plugin.on("enable", function() {

        });
        plugin.on("disable", function() {

        });
        plugin.on("unload", function() {
            loaded = false;
            drawn = false;
        });

        /***** Register and define API *****/

        /**
         *
         **/
        plugin.freezePublicAPI({
        });

        register(null, {
            emmet: plugin
        });
    }
});<commit_msg>allow enabling emmet from a mode<commit_after>define(function(require, exports, module) {
    "use strict";
    main.consumes = [
        "Plugin", "commands", "menus", "ace"
    ];
    main.provides = ["emmet"];
    return main;

    function main(options, imports, register) {
        var Plugin = imports.Plugin;
        var commands = imports.commands;
        var menus = imports.menus;

        var emmetExt = require("ace/ext/emmet");
        emmetExt.setCore("lib/emmet/emmet");
        emmetExt.updateCommands = function() {};

        /***** Initialization *****/

        var plugin = new Plugin("Ajax.org", main.consumes);
        var emit = plugin.getEmitter();

        var loaded = false;
        function load() {
            if (loaded) return false;
            loaded = true;

            var keymap = {
                expand_abbreviation: {mac: "ctrl+alt+e", win: "ctrl+alt+e"},
                match_pair_outward: {}, // {mac: "ctrl+d", win: "ctrl+,"},
                match_pair_inward: {}, // {mac: "ctrl+j", win: "ctrl+shift+0"},
                matching_pair:  {}, // {mac: "ctrl+alt+j", win: "alt+j"},
                next_edit_point:  {}, // "alt+right",
                prev_edit_point:  {}, // "alt+left",
                toggle_comment: {}, // {mac: "command+/", win: "ctrl+/"},
                split_join_tag:  {}, // {mac: "shift+command+'", win: "shift+ctrl+`"},
                remove_tag:  {}, // {mac: "command+'", win: "shift+ctrl+;"},
                evaluate_math_expression:  {mac: "shift+command+y", win: "shift+ctrl+y"},
                increment_number_by_1:  {}, // "ctrl+up",
                decrement_number_by_1:  {}, // "ctrl+down",
                increment_number_by_01:  {}, // "alt+up",
                decrement_number_by_01:  {}, // "alt+down",
                increment_number_by_10:  {}, // {mac: "alt+command+up", win: "shift+alt+up"},
                decrement_number_by_10:  {}, // {mac: "alt+command+down", win: "shift+alt+down"},
                select_next_item: {mac: "shift+command+.", win: "shift+ctrl+."},
                select_previous_item: {mac: "shift+command+,", win: "shift+ctrl+,"},
                reflect_css_value:  {}, // {mac: "shift+command+r", win: "shift+ctrl+r"},

                // encode_decode_data_url:  {}, // {mac: "shift+ctrl+d", win: "ctrl+'"},
                // update_image_size: {mac: "shift+ctrl+i", win: "ctrl+u"},
                // expand_as_you_type: "ctrl+alt+enter",
                // wrap_as_you_type: {mac: "shift+ctrl+g", win: "shift+ctrl+g"},
                expand_abbreviation_with_tab: {mac: "Tab", win: "Tab"},
                wrap_with_abbreviation: {mac: "shift+ctrl+a", win: "shift+ctrl+a"}
            };

            for (var i in keymap) {
                commands.addCommand({
                    name: "emmet_" + i,
                    action: i,
                    group: "emmet",
                    bindKey: keymap[i],
                    exec: emmetExt.runEmmetCommand,
                    isAvailable: isAvailable,
                    findEditor: findEditor
                }, plugin);
            }
        }

        var drawn = false;
        function draw() {
            if (drawn) return;
            drawn = true;

            // TODO add menu items?

            emit("draw");
        }

        /***** Methods *****/

        function show() {
            draw();
        }

        function isAvailable(editor, args, event) {
            if (!editor || !editor.ace) return false;

            // using this instead of editor.type == "ace" to make
            // commands avaliable in editors inheriting from ace
            if (event instanceof KeyboardEvent && (!editor.ace.isFocused()))
                return false;

            return emmetExt.isSupportedMode(editor.ace.session.$mode);
        }

        function findEditor(editor) {
            if (editor && editor.ace)
                return editor.ace;
            return editor;
        }

        /***** Lifecycle *****/

        plugin.on("load", function() {
            load();
        });
        plugin.on("enable", function() {

        });
        plugin.on("disable", function() {

        });
        plugin.on("unload", function() {
            loaded = false;
            drawn = false;
        });

        /***** Register and define API *****/

        /**
         *
         **/
        plugin.freezePublicAPI({
        });

        register(null, {
            emmet: plugin
        });
    }
});<|endoftext|>