<commit_before>import { Map } from 'immutable';
import {
  EditorState,
  RichUtils,
  DefaultDraftBlockRenderMap,
  DefaultDraftInlineStyle,
  CompositeDecorator,
  Modifier,
  AtomicBlockUtils,
  SelectionState,
  convertFromRaw,
} from 'draft-js';
import {
  INIT,
  SET_REF,
  UPDATE_EDITOR_STATE,
  UPDATE_EDITOR_STATE_FROM_RAW,
  UPDATE_READ_ONLY,
  TOGGLE_BLOCK,
  TOGGLE_STYLE,
  APPLY_BLOCK,
  REMOVE_ENTITY,
  APPLY_ENTITY,
  INSERT_ENTITY,
  INSERT_ATOMIC_BLOCK,
  REMOVE_BLOCK,
  UPDATE_ENTITY_DATA,
} from '../constants/ActionTypes';
import isEntityActive from '../utils/isEntityActive';

let getBlockRenderMap = (customBlockMap) => {
  let customBlockRenderMap = Map(Object
    .keys(customBlockMap)
    .reduce((map, blockName) => {
      map[blockName] = {
        element: 'div',
      };
      return map;
    }, {
      // 'paragraph': {
      //   element: 'div',
      // },
      'unstyled': {
        element: 'div',
      },
      'atomic': {
        element: 'div',
      },
    }));
  let mergedRenderMap = DefaultDraftBlockRenderMap
    .merge(customBlockRenderMap);

  return mergedRenderMap;
};

let getActiveMap = ({
  editorState, blockNames, styleNames, decoratorNames,
}) => {
  let selectionState = editorState.getSelection();
  let currentBlockType = editorState
    .getCurrentContent()
    .getBlockForKey(selectionState.getStartKey())
    .getType();
  let currentStyleNames = editorState.getCurrentInlineStyle();
  let blockActiveMap = blockNames
    .reduce((map, blockName) => {
      map[blockName] = (
        blockName === currentBlockType
      );
      return map;
    }, {});
  let styleActiveMap = styleNames
    .reduce((map, styleName) => {
      map[styleName] = currentStyleNames.has(styleName);
      return map;
    }, {});
  let entityActiveMap = decoratorNames
    .reduce((map, decoratorName) => {
      map[decoratorName] = isEntityActive(editorState, decoratorName);
      return map;
    }, {});

  return {
    ...blockActiveMap,
    ...styleActiveMap,
    ...entityActiveMap,
  };
};

let initialEditorState = {};
let editorReducer = (state = initialEditorState, action) => {
  switch (action.type) {
    case INIT: {
      let { config } = action;
      let {
        customStyleMap,
        customBlockMap,
        entityMap,
        decoratorMap,
        renderMap,
      } = config;
      let defaultStyleNames = Object.keys(DefaultDraftInlineStyle);
      let styleNames = [
        ...defaultStyleNames,
        ...Object.keys(customStyleMap || []),
      ];
      let defaultBlockNames = (
        DefaultDraftBlockRenderMap.keySeq().toArray()
      );

      let editorState = (
        action.editorState ||
        EditorState.createEmpty()
      );
      let blockRenderMap = getBlockRenderMap(customBlockMap);
      let blockRendererFn = (contentBlock) => {
        let name = contentBlock.getType();

        return customBlockMap[name];
      };
      let blockNames = (
        blockRenderMap.keySeq().toArray()
      );
      let entityNames = Object.keys(entityMap);
      let decoratorNames = Object.keys(decoratorMap);
      let decorators = (
        decoratorNames.map(decoratorName => decoratorMap[decoratorName])
      );

      editorState = EditorState.set(editorState, {
        decorator: new CompositeDecorator(decorators),
      });
      return {
        // private redux-draft props
        _instance: null,
        _initialized: true,

        // public redux-draft props
        name: action.editorName,
        config,
        defaultStyleNames,
        styleNames,
        defaultBlockNames,
        blockNames,
        entityNames,
        decoratorNames,
        decorators,
        activeMap: getActiveMap({
          editorState,
          blockNames,
          styleNames,
          decoratorNames,
        }),
        renderMap,

        // draft props
        editorState,
        customStyleMap,
        blockRenderMap,
        blockRendererFn,
        readOnly: false,
      };
    }

    case SET_REF: {
      return {
        ...state,
        _instance: action.editorInstance,
      };
    }

    case UPDATE_EDITOR_STATE: {
      let {
        blockNames,
        styleNames,
        decoratorNames,
      } = state;
      let { editorState } = action;

      return {
        ...state,
        editorState,
        activeMap: getActiveMap({
          editorState,
          blockNames,
          styleNames,
          decoratorNames,
        }),
      };
    }

    case UPDATE_EDITOR_STATE_FROM_RAW: {
      let {
        blockNames,
        styleNames,
        decoratorNames,
        decorators,
      } = state;
      let { rawContent } = action;
      let contentState = convertFromRaw(rawContent);
      let editorState = EditorState.createWithContent(
        contentState,
        new CompositeDecorator(decorators)
      );

      return {
        ...state,
        editorState,
        activeMap: getActiveMap({
          editorState,
          blockNames,
          styleNames,
          decoratorNames,
        }),
      };
    }

    case UPDATE_READ_ONLY: {
      return {
        ...state,
        readOnly: action.readOnly,
      };
    }

    case TOGGLE_BLOCK: {
      let {
        blockNames,
        styleNames,
        decoratorNames,
      } = state;
      let editorState = RichUtils.toggleBlockType(
        state.editorState,
        action.blockName
      );

      return {
        ...state,
        editorState,
        activeMap: getActiveMap({
          editorState,
          blockNames,
          styleNames,
          decoratorNames,
        }),
      };
    }

    case TOGGLE_STYLE: {
      let {
        blockNames,
        styleNames,
        decoratorNames,
      } = state;
      let editorState = RichUtils.toggleInlineStyle(
        state.editorState,
        action.styleName
      );

      return {
        ...state,
        editorState,
        activeMap: getActiveMap({
          editorState,
          blockNames,
          styleNames,
          decoratorNames,
        }),
      };
    }

    case APPLY_BLOCK: {
      let {
        editorState,
        blockNames,
        styleNames,
        decoratorNames,
      } = state;
      let contentState = editorState.getCurrentContent();
      let selectionState = editorState.getSelection();
      let setBlock = Modifier.setBlockType(
        contentState,
        selectionState,
        action.blockName,
      );

      contentState = EditorState.push(
        editorState,
        setBlock,
        'change-block-type'
      );
      editorState = EditorState.forceSelection(
        contentState, setBlock.getSelectionAfter()
      );
      return {
        ...state,
        editorState,
        activeMap: getActiveMap({
          editorState,
          blockNames,
          styleNames,
          decoratorNames,
        }),
      };
    }

    case REMOVE_ENTITY: {
      let {
        editorState,
        blockNames,
        styleNames,
        decoratorNames,
      } = state;
      let selectionState = editorState.getSelection();
      let contentState = editorState.getCurrentContent();
      let contentStateWithoutEntity = Modifier.applyEntity(
        contentState,
        selectionState,
        null
      );
      editorState = EditorState.push(
        editorState,
        contentStateWithoutEntity,
        'apply-entity'
      );

      return {
        ...state,
        editorState,
        activeMap: getActiveMap({
          editorState,
          blockNames,
          styleNames,
          decoratorNames,
        }),
      };
    }

    case APPLY_ENTITY: {
      let {
        editorState,
        blockNames,
        styleNames,
        decoratorNames,
      } = state;
      let selectionState = editorState.getSelection();
      let contentState = editorState.getCurrentContent();

      let contentStateWithNewEntity = contentState.createEntity(
        action.entityName,
        action.mutability,
        action.data
      );
      let entityKey = contentStateWithNewEntity.getLastCreatedEntityKey();
      let contentStateWithEntity = Modifier.applyEntity(
        contentStateWithNewEntity,
        selectionState,
        entityKey
      );
      editorState = EditorState.push(
        editorState,
        contentStateWithEntity,
        'apply-entity'
      );

      return {
        ...state,
        editorState,
        activeMap: getActiveMap({
          editorState,
          blockNames,
          styleNames,
          decoratorNames,
        }),
      };
    }

    case INSERT_ENTITY: {
      let {
        editorState,
        blockNames,
        styleNames,
        decoratorNames,
      } = state;
      let selectionState = editorState.getSelection();
      let contentState = editorState.getCurrentContent();

      let contentStateWithNewEntity = contentState.createEntity(
        action.entityName,
        action.mutability,
        action.data
      );
      let entityKey = contentStateWithNewEntity.getLastCreatedEntityKey();

      let firstBlank = Modifier.insertText(
        contentState,
        selectionState,
        ' ',
        null,
        null
      );
      let withEntity = Modifier.insertText(
        firstBlank,
        selectionState,
        action.text,
        null,
        entityKey
      );
      let withBlank = Modifier.insertText(
        withEntity,
        selectionState,
        ' ',
        null,
        null,
      );

      editorState = EditorState.push(
        editorState,
        withBlank,
        'insert-text'
      );

      return {
        ...state,
        editorState,
        activeMap: getActiveMap({
          editorState,
          blockNames,
          styleNames,
          decoratorNames,
        }),
      };
    }

    case INSERT_ATOMIC_BLOCK: {
      let {
        editorState,
        blockNames,
        styleNames,
        decoratorNames,
      } = state;
      let contentState = editorState.getCurrentContent();
      let contentStateWithNewEntity = contentState.createEntity(
        action.entityName,
        action.mutability,
        action.data
      );
      let entityKey = contentStateWithNewEntity.getLastCreatedEntityKey();

      editorState = EditorState.set(
        editorState,
        {currentContent: contentStateWithNewEntity},
      );
      editorState = AtomicBlockUtils.insertAtomicBlock(
        editorState,
        entityKey,
        action.text
      );
      return {
        ...state,
        editorState,
        activeMap: getActiveMap({
          editorState,
          blockNames,
          styleNames,
          decoratorNames,
        }),
      };
    }

    case REMOVE_BLOCK: {
      let { editorState } = state;
      let contentState = editorState.getCurrentContent();
      let block = contentState.getBlockForKey(action.blockKey);
      let targetRange = new SelectionState({
        anchorKey: action.blockKey,
        anchorOffset: 0,
        focusKey: action.blockKey,
        focusOffset: block.getLength(),
      });
      let withoutBlock = Modifier.removeRange(
        contentState,
        targetRange,
        'backward'
      );
      let resetBlock = Modifier.setBlockType(
        withoutBlock,
        withoutBlock.getSelectionAfter(),
        'unstyled',
      );

      contentState = EditorState.push(editorState, resetBlock, 'remove-range');
      editorState = EditorState.forceSelection(
        contentState, resetBlock.getSelectionAfter()
      );
      return {
        ...state,
        editorState,
      };
    }

    case UPDATE_ENTITY_DATA: {
      let { editorState, decorators } = state;
      let contentState = editorState.getCurrentContent();
      contentState = contentState.mergeEntityData(
        action.entityKey,
        action.data
      );
      editorState = EditorState.createWithContent(
        contentState,
        new CompositeDecorator(decorators)
      );

      return {
        ...state,
        editorState,
      };
    }
  }
};

let initialState = {};

export default (state = initialState, action) => {
  let { editorName } = action;

  if (editorName) {
    return {
      ...state,
      [editorName]: editorReducer(state[editorName], action),
    };
  } else {
    return state;
  }
};
<commit_msg>Fix default value bug<commit_after>import { Map } from 'immutable';
import {
  EditorState,
  RichUtils,
  DefaultDraftBlockRenderMap,
  DefaultDraftInlineStyle,
  CompositeDecorator,
  Modifier,
  AtomicBlockUtils,
  SelectionState,
  convertFromRaw,
} from 'draft-js';
import {
  INIT,
  SET_REF,
  UPDATE_EDITOR_STATE,
  UPDATE_EDITOR_STATE_FROM_RAW,
  UPDATE_READ_ONLY,
  TOGGLE_BLOCK,
  TOGGLE_STYLE,
  APPLY_BLOCK,
  REMOVE_ENTITY,
  APPLY_ENTITY,
  INSERT_ENTITY,
  INSERT_ATOMIC_BLOCK,
  REMOVE_BLOCK,
  UPDATE_ENTITY_DATA,
} from '../constants/ActionTypes';
import isEntityActive from '../utils/isEntityActive';

let getBlockRenderMap = (customBlockMap) => {
  let customBlockRenderMap = Map(Object
    .keys(customBlockMap)
    .reduce((map, blockName) => {
      map[blockName] = {
        element: 'div',
      };
      return map;
    }, {
      // 'paragraph': {
      //   element: 'div',
      // },
      'unstyled': {
        element: 'div',
      },
      'atomic': {
        element: 'div',
      },
    }));
  let mergedRenderMap = DefaultDraftBlockRenderMap
    .merge(customBlockRenderMap);

  return mergedRenderMap;
};

let getActiveMap = ({
  editorState, blockNames, styleNames, decoratorNames,
}) => {
  let selectionState = editorState.getSelection();
  let currentBlockType = editorState
    .getCurrentContent()
    .getBlockForKey(selectionState.getStartKey())
    .getType();
  let currentStyleNames = editorState.getCurrentInlineStyle();
  let blockActiveMap = blockNames
    .reduce((map, blockName) => {
      map[blockName] = (
        blockName === currentBlockType
      );
      return map;
    }, {});
  let styleActiveMap = styleNames
    .reduce((map, styleName) => {
      map[styleName] = currentStyleNames.has(styleName);
      return map;
    }, {});
  let entityActiveMap = decoratorNames
    .reduce((map, decoratorName) => {
      map[decoratorName] = isEntityActive(editorState, decoratorName);
      return map;
    }, {});

  return {
    ...blockActiveMap,
    ...styleActiveMap,
    ...entityActiveMap,
  };
};

let initialEditorState = {};
let editorReducer = (state = initialEditorState, action) => {
  switch (action.type) {
    case INIT: {
      let { config } = action;
      let {
        customStyleMap = {},
        customBlockMap = {},
        entityMap = {},
        decoratorMap = {},
        renderMap = {},
      } = config;
      let defaultStyleNames = Object.keys(DefaultDraftInlineStyle);
      let styleNames = [
        ...defaultStyleNames,
        ...Object.keys(customStyleMap || []),
      ];
      let defaultBlockNames = (
        DefaultDraftBlockRenderMap.keySeq().toArray()
      );

      let editorState = (
        action.editorState ||
        EditorState.createEmpty()
      );
      let blockRenderMap = getBlockRenderMap(customBlockMap);
      let blockRendererFn = (contentBlock) => {
        let name = contentBlock.getType();

        return customBlockMap[name];
      };
      let blockNames = (
        blockRenderMap.keySeq().toArray()
      );
      let entityNames = Object.keys(entityMap);
      let decoratorNames = Object.keys(decoratorMap);
      let decorators = (
        decoratorNames.map(decoratorName => decoratorMap[decoratorName])
      );

      editorState = EditorState.set(editorState, {
        decorator: new CompositeDecorator(decorators),
      });
      return {
        // private redux-draft props
        _instance: null,
        _initialized: true,

        // public redux-draft props
        name: action.editorName,
        config,
        defaultStyleNames,
        styleNames,
        defaultBlockNames,
        blockNames,
        entityNames,
        decoratorNames,
        decorators,
        activeMap: getActiveMap({
          editorState,
          blockNames,
          styleNames,
          decoratorNames,
        }),
        renderMap,

        // draft props
        editorState,
        customStyleMap,
        blockRenderMap,
        blockRendererFn,
        readOnly: false,
      };
    }

    case SET_REF: {
      return {
        ...state,
        _instance: action.editorInstance,
      };
    }

    case UPDATE_EDITOR_STATE: {
      let {
        blockNames,
        styleNames,
        decoratorNames,
      } = state;
      let { editorState } = action;

      return {
        ...state,
        editorState,
        activeMap: getActiveMap({
          editorState,
          blockNames,
          styleNames,
          decoratorNames,
        }),
      };
    }

    case UPDATE_EDITOR_STATE_FROM_RAW: {
      let {
        blockNames,
        styleNames,
        decoratorNames,
        decorators,
      } = state;
      let { rawContent } = action;
      let contentState = convertFromRaw(rawContent);
      let editorState = EditorState.createWithContent(
        contentState,
        new CompositeDecorator(decorators)
      );

      return {
        ...state,
        editorState,
        activeMap: getActiveMap({
          editorState,
          blockNames,
          styleNames,
          decoratorNames,
        }),
      };
    }

    case UPDATE_READ_ONLY: {
      return {
        ...state,
        readOnly: action.readOnly,
      };
    }

    case TOGGLE_BLOCK: {
      let {
        blockNames,
        styleNames,
        decoratorNames,
      } = state;
      let editorState = RichUtils.toggleBlockType(
        state.editorState,
        action.blockName
      );

      return {
        ...state,
        editorState,
        activeMap: getActiveMap({
          editorState,
          blockNames,
          styleNames,
          decoratorNames,
        }),
      };
    }

    case TOGGLE_STYLE: {
      let {
        blockNames,
        styleNames,
        decoratorNames,
      } = state;
      let editorState = RichUtils.toggleInlineStyle(
        state.editorState,
        action.styleName
      );

      return {
        ...state,
        editorState,
        activeMap: getActiveMap({
          editorState,
          blockNames,
          styleNames,
          decoratorNames,
        }),
      };
    }

    case APPLY_BLOCK: {
      let {
        editorState,
        blockNames,
        styleNames,
        decoratorNames,
      } = state;
      let contentState = editorState.getCurrentContent();
      let selectionState = editorState.getSelection();
      let setBlock = Modifier.setBlockType(
        contentState,
        selectionState,
        action.blockName,
      );

      contentState = EditorState.push(
        editorState,
        setBlock,
        'change-block-type'
      );
      editorState = EditorState.forceSelection(
        contentState, setBlock.getSelectionAfter()
      );
      return {
        ...state,
        editorState,
        activeMap: getActiveMap({
          editorState,
          blockNames,
          styleNames,
          decoratorNames,
        }),
      };
    }

    case REMOVE_ENTITY: {
      let {
        editorState,
        blockNames,
        styleNames,
        decoratorNames,
      } = state;
      let selectionState = editorState.getSelection();
      let contentState = editorState.getCurrentContent();
      let contentStateWithoutEntity = Modifier.applyEntity(
        contentState,
        selectionState,
        null
      );
      editorState = EditorState.push(
        editorState,
        contentStateWithoutEntity,
        'apply-entity'
      );

      return {
        ...state,
        editorState,
        activeMap: getActiveMap({
          editorState,
          blockNames,
          styleNames,
          decoratorNames,
        }),
      };
    }

    case APPLY_ENTITY: {
      let {
        editorState,
        blockNames,
        styleNames,
        decoratorNames,
      } = state;
      let selectionState = editorState.getSelection();
      let contentState = editorState.getCurrentContent();

      let contentStateWithNewEntity = contentState.createEntity(
        action.entityName,
        action.mutability,
        action.data
      );
      let entityKey = contentStateWithNewEntity.getLastCreatedEntityKey();
      let contentStateWithEntity = Modifier.applyEntity(
        contentStateWithNewEntity,
        selectionState,
        entityKey
      );
      editorState = EditorState.push(
        editorState,
        contentStateWithEntity,
        'apply-entity'
      );

      return {
        ...state,
        editorState,
        activeMap: getActiveMap({
          editorState,
          blockNames,
          styleNames,
          decoratorNames,
        }),
      };
    }

    case INSERT_ENTITY: {
      let {
        editorState,
        blockNames,
        styleNames,
        decoratorNames,
      } = state;
      let selectionState = editorState.getSelection();
      let contentState = editorState.getCurrentContent();

      let contentStateWithNewEntity = contentState.createEntity(
        action.entityName,
        action.mutability,
        action.data
      );
      let entityKey = contentStateWithNewEntity.getLastCreatedEntityKey();

      let firstBlank = Modifier.insertText(
        contentState,
        selectionState,
        ' ',
        null,
        null
      );
      let withEntity = Modifier.insertText(
        firstBlank,
        selectionState,
        action.text,
        null,
        entityKey
      );
      let withBlank = Modifier.insertText(
        withEntity,
        selectionState,
        ' ',
        null,
        null,
      );

      editorState = EditorState.push(
        editorState,
        withBlank,
        'insert-text'
      );

      return {
        ...state,
        editorState,
        activeMap: getActiveMap({
          editorState,
          blockNames,
          styleNames,
          decoratorNames,
        }),
      };
    }

    case INSERT_ATOMIC_BLOCK: {
      let {
        editorState,
        blockNames,
        styleNames,
        decoratorNames,
      } = state;
      let contentState = editorState.getCurrentContent();
      let contentStateWithNewEntity = contentState.createEntity(
        action.entityName,
        action.mutability,
        action.data
      );
      let entityKey = contentStateWithNewEntity.getLastCreatedEntityKey();

      editorState = EditorState.set(
        editorState,
        {currentContent: contentStateWithNewEntity},
      );
      editorState = AtomicBlockUtils.insertAtomicBlock(
        editorState,
        entityKey,
        action.text
      );
      return {
        ...state,
        editorState,
        activeMap: getActiveMap({
          editorState,
          blockNames,
          styleNames,
          decoratorNames,
        }),
      };
    }

    case REMOVE_BLOCK: {
      let { editorState } = state;
      let contentState = editorState.getCurrentContent();
      let block = contentState.getBlockForKey(action.blockKey);
      let targetRange = new SelectionState({
        anchorKey: action.blockKey,
        anchorOffset: 0,
        focusKey: action.blockKey,
        focusOffset: block.getLength(),
      });
      let withoutBlock = Modifier.removeRange(
        contentState,
        targetRange,
        'backward'
      );
      let resetBlock = Modifier.setBlockType(
        withoutBlock,
        withoutBlock.getSelectionAfter(),
        'unstyled',
      );

      contentState = EditorState.push(editorState, resetBlock, 'remove-range');
      editorState = EditorState.forceSelection(
        contentState, resetBlock.getSelectionAfter()
      );
      return {
        ...state,
        editorState,
      };
    }

    case UPDATE_ENTITY_DATA: {
      let { editorState, decorators } = state;
      let contentState = editorState.getCurrentContent();
      contentState = contentState.mergeEntityData(
        action.entityKey,
        action.data
      );
      editorState = EditorState.createWithContent(
        contentState,
        new CompositeDecorator(decorators)
      );

      return {
        ...state,
        editorState,
      };
    }
  }
};

let initialState = {};

export default (state = initialState, action) => {
  let { editorName } = action;

  if (editorName) {
    return {
      ...state,
      [editorName]: editorReducer(state[editorName], action),
    };
  } else {
    return state;
  }
};
<|endoftext|>


<commit_before>var $Q, $, Globalize, _, Backbone, Highcharts, L;
(function() {
  var environment = 'dev', // 'dev' (development) or 'pr' (production)
  getCulture = function () {
    var defaultLanguage = 'en',
      availableLanguages = ['es', 'en'],
      clientLanguage = (window.navigator) ? window.navigator.language.split('-')[0] : defaultLanguage,
      selectedLanguage = (availableLanguages.indexOf(clientLanguage) !== -1) ? clientLanguage : defaultLanguage;
    document.getElementsByTagName('html')[0].lang = selectedLanguage;
    return selectedLanguage;
  };

  $Q = {
    appName: 'Borrasca',
    appTitle: 'Borrasca-Next - ',
    version: (environment === 'pr') ? '2.2.1.0' : Date.now(),
    servicePath: (document.URL.indexOf( 'http://' ) === -1 && document.URL.indexOf( 'https://' ) === -1) ? 'http://borrasca-next.digitalpapyrus.es/' : '',
    server: (window.location.port === '9000') ? 'node' : 'php', // 'node' or 'php'
    waitOnInitialize: 40,
    culture: getCulture(),
    compressed: false,
    legacy: true,
    geolocation: null,
    templatesReady: false,
    jsLibs: {
      route: (!this.compressed) ? 'libs/': 'libs/min/',
      versions: {
        jquery: (this.legacy) ? '1.10.2' : '2.0.3',
        underscore: '1.5.1',
        lodash: '2.1.0',
        backbone: '1.0.0',
        requireText: '2.0.7',
        requireAsync: '0.1.1',
        highcharts: '3.0.2',
        bootstrap: '3.0.0',
        jquery_sliceSlide: '4.0',
        leaflet: '0.6.4'
      },
      equivalent: {
        underscore: 'lodash' // 'lodash' or 'underscore'
      }
    },
    templates: {
      route: '../tmpl/',
      routeCultures: '../cultures/'
    },
    images: {
      route: 'img'
    },
    piwik: {
      enabled: false,
      ready: false,
      url: null,
      id: '2'
    },
    views: {},
    removableViews: ['detail', 'nowAndHere']
  };

  $Q.alternateCulture = ($Q.culture === 'es') ? 'sp' : $Q.culture;

  $Q.services = {
    main: ($Q.server === 'php') ? $Q.servicePath + 'services/main.php?lang=' + $Q.alternateCulture + '&geolocation=' : $Q.servicePath + '?lang=' + $Q.alternateCulture + '&geolocation=',
    search: ($Q.server === 'php') ? $Q.servicePath + 'services/search.php?location_name=' : $Q.servicePath + '?location_name=',
    detail: ($Q.server === 'php') ? $Q.servicePath + 'services/detail.php?lang=' + $Q.alternateCulture + '&location_name=' : $Q.servicePath + '?detail=true&lang=' + $Q.alternateCulture + '&location_name=',
    xml: ($Q.server === 'php') ? $Q.servicePath + 'services/xml.php?location_id=' : $Q.servicePath + '?xml='
  }

  require.config({
    paths: {
      text: 'libs/require.text-' + $Q.jsLibs.versions.requireText,
      async: 'libs/require.async-' + $Q.jsLibs.versions.requireAsync,
      'jquery': $Q.jsLibs.route + 'jquery-' + $Q.jsLibs.versions.jquery,
      'globalize': 'libs/globalize',
      'globalize_culture': $Q.templates.routeCultures + 'globalize/globalize.culture.' + $Q.culture,
      'underscore': ($Q.jsLibs.equivalent.underscore === 'lodash') ? $Q.jsLibs.route + 'lodash.underscore-' + $Q.jsLibs.versions.lodash : $Q.jsLibs.route + 'underscore-' + $Q.jsLibs.versions.underscore,
      'backbone': $Q.jsLibs.route + 'backbone-' + $Q.jsLibs.versions.backbone,
      'highcharts': $Q.jsLibs.route + 'highcharts-' + $Q.jsLibs.versions.highcharts,
      'bootstrap': $Q.jsLibs.route + 'bootstrap-' + $Q.jsLibs.versions.bootstrap,
      'jquery_sliceSlide': $Q.jsLibs.route + 'slice-slide/jquery.sliceslide-' + $Q.jsLibs.versions.jquery_sliceSlide,
      'leaflet': $Q.jsLibs.route + 'leaflet-' + $Q.jsLibs.versions.leaflet,
      'mixins': 'br.mixins',
      'br_ui': 'br.ui',
      'br_utils': 'br.utils',
      'br_routes': 'br.routes',
      'br_extend_view': 'br.extendView',
      'mvc_main': 'mvc/main.mvc',
      'mvc_search': 'mvc/search.mvc',
      'mvc_bookmarks': 'mvc/bookmarks.mvc',
      'mvc_nowAndHere': 'mvc/nowAndHere.mvc',
      'mvc_detail': 'mvc/detail.mvc'
    },
    shim: {
      'underscore': {
        deps: [],
        exports: '_'
      },
      'backbone': {
        deps: ['jquery', 'underscore'],
        exports: 'Backbone'
      },
      'highcharts': {
        deps: ['jquery'],
        exports: 'Highcharts'
      },
      'globalize': {
        deps: ['jquery'],
        exports: 'Globalize'
      },
      'globalize_culture': {
        deps: ['globalize']
      },
      'bootstrap': {
        deps: ['jquery']
      },
      'jquery_sliceSlide': {
        deps: ['jquery', 'underscore']
      },
      'leaflet': {
        exports: 'L'
      },
      'mixins': {
        deps: ['jquery', 'underscore']
      },
      'br_ui': {
        deps: ['jquery', 'underscore']
      },
      'br_utils': {
        deps: ['jquery', 'underscore']
      },
      'br_routes': {
        deps: ['backbone']
      },
      'br_extend_view': {
        deps: ['br_utils', 'br_routes', 'globalize', 'mixins', 'br_ui', 'bootstrap']
      },
      'mvc_main': {
        deps: ['br_extend_view']
      },
      'mvc_search': {
        deps: ['mvc_main']
      },
      'mvc_bookmarks': {
        deps: ['mvc_main']
      },
      'mvc_nowAndHere': {
        deps: ['mvc_main']
      },
      'mvc_detail': {
        deps: ['mvc_main', 'leaflet']
      }
    },
    waitSeconds: 40,
    urlArgs: $Q.version
  });

  $Q.resourcesJs = [
    'jquery',
    'globalize',
    'underscore',
    'backbone',
    'highcharts',
    'leaflet',
    'jquery_sliceSlide',
    'globalize_culture',
    'mixins',
    'br_ui',
    'br_utils',
    'br_routes',
    'br_extend_view',
    'mvc_main',
    'mvc_search',
    'mvc_bookmarks',
    'mvc_nowAndHere',
    'mvc_detail',
    'br.app.aemet'
  ];
  $Q.resourcesText = [
    'text!' + $Q.templates.routeCultures + 'text_' + $Q.culture + '.html',
    'text!' + $Q.templates.route + 'mixin_tmpl_loading.html',
    'text!' + $Q.templates.route + 'mixin_tmpl_messages_error.html',
    'text!' + $Q.templates.route + 'mixin_tmpl_map_layers.html',
    'text!' + $Q.templates.route + 'mixin_tmpl_current_weather.html',
    'text!' + $Q.templates.route + 'mixin_tmpl_buttons_refresh.html',
    'text!' + $Q.templates.route + 'tmpl_main.html',
    'text!' + $Q.templates.route + 'tmpl_search.html',
    'text!' + $Q.templates.route + 'tmpl_bookmarks.html',
    'text!' + $Q.templates.route + 'tmpl_now_and_here.html',
    'text!' + $Q.templates.route + 'tmpl_detail.html'
  ];

  $Q.initialize = function () {
    $Q.utils.getGeolocation();
    $(document).on('geolocated', function () {
      $Q.app_router = new $Q.AppRouter();
      $Q.views.mainView = new $Q.MainView();
      Backbone.history.start();
    });
  }

  define($Q.resourcesJs.concat($Q.resourcesText), function () {
    var templates = '',
      l = arguments.length,
      i;
    $ = arguments[0];
    Globalize = arguments[1];
    _ = arguments[2];
    Backbone = arguments[3];
    Highcharts = arguments[4];
    L = arguments[5];
    for (i = 5; i < l; i += 1) {
      if (typeof arguments[i] === 'string') {
        templates += arguments[i];
      }
    }

    Globalize.culture($Q.culture);
    $('title').text($Q.appTitle + $Q.version);

    $Q.supported = {
      html5: {
        storage: _.support_html5_storage()
      }
    };
    if ($Q.supported.html5.storage) {
      if (_.isEmpty(localStorage.getItem('appData'))) {
        localStorage.setItem('appData', JSON.stringify({locations: [], locationsName: []}));
      }
    }

    $.when($('#templates-area').append(templates)).then(function () {
      $Q.templatesReady = true;
      if ($Q.piwik.enabled) {
        require(['async!' + $Q.utils.piwikStats.getScriptUrl() +'!callback']);
        var piwikIntervalCount = 0,
          piwikInterval = setInterval(function () {
            $Q.piwik.ready = _.isObject(Piwik);
            if (piwikIntervalCount > 80 || $Q.piwik.ready) {
              $Q.utils.piwikStats.start();
              $Q.utils.piwikStats.trackPageView(window.location.hash);
              $Q.initialize();
              clearInterval(piwikInterval);
            }
            piwikIntervalCount += 1;
          }, 500);
      } else {
        $Q.initialize();
      }
    });
  });

}());
<commit_msg>language selection refactor<commit_after>var $Q, $, Globalize, _, Backbone, Highcharts, L;
(function() {
  var environment = 'dev', // 'dev' (development) or 'pr' (production)
    defaultLanguage = 'en',
    getNavigatorLanguage = function () {
      var language = defaultLanguage;
      if (window.navigator) {
        language = (window.navigator.language || window.navigator.userLanguage).split('-')[0]
      }
      return language;
    },
    getCulture = function () {
      var availableLanguages = ['es', 'en'],
        clientLanguage = getNavigatorLanguage(),
        selectedLanguage = (availableLanguages.indexOf(clientLanguage) !== -1) ? clientLanguage : defaultLanguage;
      document.getElementsByTagName('html')[0].lang = selectedLanguage;
      return selectedLanguage;
    };

  $Q = {
    appName: 'Borrasca',
    appTitle: 'Borrasca-Next - ',
    version: (environment === 'pr') ? '2.2.1.0' : Date.now(),
    servicePath: (document.URL.indexOf( 'http://' ) === -1 && document.URL.indexOf( 'https://' ) === -1) ? 'http://borrasca-next.digitalpapyrus.es/' : '',
    server: (window.location.port === '9000') ? 'node' : 'php', // 'node' or 'php'
    waitOnInitialize: 40,
    culture: getCulture(),
    compressed: false,
    legacy: true,
    geolocation: null,
    templatesReady: false,
    jsLibs: {
      route: (!this.compressed) ? 'libs/': 'libs/min/',
      versions: {
        jquery: (this.legacy) ? '1.10.2' : '2.0.3',
        underscore: '1.5.1',
        lodash: '2.1.0',
        backbone: '1.0.0',
        requireText: '2.0.7',
        requireAsync: '0.1.1',
        highcharts: '3.0.2',
        bootstrap: '3.0.0',
        jquery_sliceSlide: '4.0',
        leaflet: '0.6.4'
      },
      equivalent: {
        underscore: 'lodash' // 'lodash' or 'underscore'
      }
    },
    templates: {
      route: '../tmpl/',
      routeCultures: '../cultures/'
    },
    images: {
      route: 'img'
    },
    piwik: {
      enabled: false,
      ready: false,
      url: null,
      id: '2'
    },
    views: {},
    removableViews: ['detail', 'nowAndHere']
  };

  $Q.alternateCulture = ($Q.culture === 'es') ? 'sp' : $Q.culture;

  $Q.services = {
    main: ($Q.server === 'php') ? $Q.servicePath + 'services/main.php?lang=' + $Q.alternateCulture + '&geolocation=' : $Q.servicePath + '?lang=' + $Q.alternateCulture + '&geolocation=',
    search: ($Q.server === 'php') ? $Q.servicePath + 'services/search.php?location_name=' : $Q.servicePath + '?location_name=',
    detail: ($Q.server === 'php') ? $Q.servicePath + 'services/detail.php?lang=' + $Q.alternateCulture + '&location_name=' : $Q.servicePath + '?detail=true&lang=' + $Q.alternateCulture + '&location_name=',
    xml: ($Q.server === 'php') ? $Q.servicePath + 'services/xml.php?location_id=' : $Q.servicePath + '?xml='
  }

  require.config({
    paths: {
      text: 'libs/require.text-' + $Q.jsLibs.versions.requireText,
      async: 'libs/require.async-' + $Q.jsLibs.versions.requireAsync,
      'jquery': $Q.jsLibs.route + 'jquery-' + $Q.jsLibs.versions.jquery,
      'globalize': 'libs/globalize',
      'globalize_culture': $Q.templates.routeCultures + 'globalize/globalize.culture.' + $Q.culture,
      'underscore': ($Q.jsLibs.equivalent.underscore === 'lodash') ? $Q.jsLibs.route + 'lodash.underscore-' + $Q.jsLibs.versions.lodash : $Q.jsLibs.route + 'underscore-' + $Q.jsLibs.versions.underscore,
      'backbone': $Q.jsLibs.route + 'backbone-' + $Q.jsLibs.versions.backbone,
      'highcharts': $Q.jsLibs.route + 'highcharts-' + $Q.jsLibs.versions.highcharts,
      'bootstrap': $Q.jsLibs.route + 'bootstrap-' + $Q.jsLibs.versions.bootstrap,
      'jquery_sliceSlide': $Q.jsLibs.route + 'slice-slide/jquery.sliceslide-' + $Q.jsLibs.versions.jquery_sliceSlide,
      'leaflet': $Q.jsLibs.route + 'leaflet-' + $Q.jsLibs.versions.leaflet,
      'mixins': 'br.mixins',
      'br_ui': 'br.ui',
      'br_utils': 'br.utils',
      'br_routes': 'br.routes',
      'br_extend_view': 'br.extendView',
      'mvc_main': 'mvc/main.mvc',
      'mvc_search': 'mvc/search.mvc',
      'mvc_bookmarks': 'mvc/bookmarks.mvc',
      'mvc_nowAndHere': 'mvc/nowAndHere.mvc',
      'mvc_detail': 'mvc/detail.mvc'
    },
    shim: {
      'underscore': {
        deps: [],
        exports: '_'
      },
      'backbone': {
        deps: ['jquery', 'underscore'],
        exports: 'Backbone'
      },
      'highcharts': {
        deps: ['jquery'],
        exports: 'Highcharts'
      },
      'globalize': {
        deps: ['jquery'],
        exports: 'Globalize'
      },
      'globalize_culture': {
        deps: ['globalize']
      },
      'bootstrap': {
        deps: ['jquery']
      },
      'jquery_sliceSlide': {
        deps: ['jquery', 'underscore']
      },
      'leaflet': {
        exports: 'L'
      },
      'mixins': {
        deps: ['jquery', 'underscore']
      },
      'br_ui': {
        deps: ['jquery', 'underscore']
      },
      'br_utils': {
        deps: ['jquery', 'underscore']
      },
      'br_routes': {
        deps: ['backbone']
      },
      'br_extend_view': {
        deps: ['br_utils', 'br_routes', 'globalize', 'mixins', 'br_ui', 'bootstrap']
      },
      'mvc_main': {
        deps: ['br_extend_view']
      },
      'mvc_search': {
        deps: ['mvc_main']
      },
      'mvc_bookmarks': {
        deps: ['mvc_main']
      },
      'mvc_nowAndHere': {
        deps: ['mvc_main']
      },
      'mvc_detail': {
        deps: ['mvc_main', 'leaflet']
      }
    },
    waitSeconds: 40,
    urlArgs: $Q.version
  });

  $Q.resourcesJs = [
    'jquery',
    'globalize',
    'underscore',
    'backbone',
    'highcharts',
    'leaflet',
    'jquery_sliceSlide',
    'globalize_culture',
    'mixins',
    'br_ui',
    'br_utils',
    'br_routes',
    'br_extend_view',
    'mvc_main',
    'mvc_search',
    'mvc_bookmarks',
    'mvc_nowAndHere',
    'mvc_detail',
    'br.app.aemet'
  ];
  $Q.resourcesText = [
    'text!' + $Q.templates.routeCultures + 'text_' + $Q.culture + '.html',
    'text!' + $Q.templates.route + 'mixin_tmpl_loading.html',
    'text!' + $Q.templates.route + 'mixin_tmpl_messages_error.html',
    'text!' + $Q.templates.route + 'mixin_tmpl_map_layers.html',
    'text!' + $Q.templates.route + 'mixin_tmpl_current_weather.html',
    'text!' + $Q.templates.route + 'mixin_tmpl_buttons_refresh.html',
    'text!' + $Q.templates.route + 'tmpl_main.html',
    'text!' + $Q.templates.route + 'tmpl_search.html',
    'text!' + $Q.templates.route + 'tmpl_bookmarks.html',
    'text!' + $Q.templates.route + 'tmpl_now_and_here.html',
    'text!' + $Q.templates.route + 'tmpl_detail.html'
  ];

  $Q.initialize = function () {
    $Q.utils.getGeolocation();
    $(document).on('geolocated', function () {
      $Q.app_router = new $Q.AppRouter();
      $Q.views.mainView = new $Q.MainView();
      Backbone.history.start();
    });
  }

  define($Q.resourcesJs.concat($Q.resourcesText), function () {
    var templates = '',
      l = arguments.length,
      i;
    $ = arguments[0];
    Globalize = arguments[1];
    _ = arguments[2];
    Backbone = arguments[3];
    Highcharts = arguments[4];
    L = arguments[5];
    for (i = 5; i < l; i += 1) {
      if (typeof arguments[i] === 'string') {
        templates += arguments[i];
      }
    }

    Globalize.culture($Q.culture);
    $('title').text($Q.appTitle + $Q.version);

    $Q.supported = {
      html5: {
        storage: _.support_html5_storage()
      }
    };
    if ($Q.supported.html5.storage) {
      if (_.isEmpty(localStorage.getItem('appData'))) {
        localStorage.setItem('appData', JSON.stringify({locations: [], locationsName: []}));
      }
    }

    $.when($('#templates-area').append(templates)).then(function () {
      $Q.templatesReady = true;
      if ($Q.piwik.enabled) {
        require(['async!' + $Q.utils.piwikStats.getScriptUrl() +'!callback']);
        var piwikIntervalCount = 0,
          piwikInterval = setInterval(function () {
            $Q.piwik.ready = _.isObject(Piwik);
            if (piwikIntervalCount > 80 || $Q.piwik.ready) {
              $Q.utils.piwikStats.start();
              $Q.utils.piwikStats.trackPageView(window.location.hash);
              $Q.initialize();
              clearInterval(piwikInterval);
            }
            piwikIntervalCount += 1;
          }, 500);
      } else {
        $Q.initialize();
      }
    });
  });

}());
<|endoftext|>


<commit_before><commit_msg>combine reducers in index.js<commit_after>import projects from './projects'
import { combineReducers } from 'redux'

export default combineReducers({projects})
<|endoftext|>


<commit_before>import * as fs from 'fs';

import {
  CHANGE_FILENAME,
  DONE_SAVING,
  EXIT,
  KILL_KERNEL,
  MOVE_CELL,
  NEW_CELL_AFTER,
  NEW_KERNEL,
  READ_NOTEBOOK,
  SET_SELECTED,
  START_SAVING,
  UPDATE_CELL_EXECUTION_COUNT,
  UPDATE_CELL_OUTPUTS,
  UPDATE_CELL_SOURCE,
  ERROR_KERNEL_NOT_CONNECTED,
} from '../actions/constants';

import {
  loadNotebook,
  updateExecutionCount,
  moveCell,
  newCellAfter,
  updateSource,
  updateOutputs,
} from './document';

export const reducers = {};

reducers[READ_NOTEBOOK] = loadNotebook;
reducers[UPDATE_CELL_EXECUTION_COUNT] = updateExecutionCount;
reducers[NEW_CELL_AFTER] = newCellAfter;
reducers[UPDATE_CELL_SOURCE] = updateSource;
reducers[UPDATE_CELL_OUTPUTS] = updateOutputs;
reducers[MOVE_CELL] = moveCell;

reducers[SET_SELECTED] = function setSelected(state, action) {
  const selected = action.additive ?
      state.selected.concat(action.ids) :
      action.ids;
  return Object.assign({}, state, {
    selected,
  });
};

function cleanupKernel(state) {
  if (state.channels) {
    state.channels.shell.complete();
    state.channels.iopub.complete();
    state.channels.stdin.complete();
    state.channels = null;
  }
  if (state.spawn) {
    state.spawn.kill();
    state.spawn = null;
  }
  if (state.connectionFile) {
    fs.unlink(state.connectionFile);
    state.connectionFile = null;
  }

  delete state.channels;
  delete state.spawn;
  delete state.connectionFile;
  return state;
}

reducers[NEW_KERNEL] = function newKernel(state, action) {
  const { channels, connectionFile, spawn } = action;

  // cleanup old kernels first
  cleanupKernel();

  state.channels = channels;
  state.connectionFile = connectionFile;
  state.spawn = spawn;
  return state;
};

reducers[EXIT] = function exit(state) {
  return cleanupKernel(state);
};

reducers[KILL_KERNEL] = cleanupKernel;

reducers[START_SAVING] = function startSaving(state) {
  return Object.assign({}, state, { isSaving: true });
};

reducers[ERROR_KERNEL_NOT_CONNECTED] = function alertKernelNotConnected() {
  alert('Error: We\'re not connected to a runtime!'); // eslint-disable-line no-alert
};

reducers[DONE_SAVING] = function doneSaving(state) {
  return Object.assign({}, state, { isSaving: false });
};

reducers[CHANGE_FILENAME] = function changeFilename(state, action) {
  const { filename } = action;
  if(!filename) {
    return state;
  }
  return Object.assign({}, state, { filename });
};
<commit_msg>Pass state in for kernel cleanup.<commit_after>import * as fs from 'fs';

import {
  CHANGE_FILENAME,
  DONE_SAVING,
  EXIT,
  KILL_KERNEL,
  MOVE_CELL,
  NEW_CELL_AFTER,
  NEW_KERNEL,
  READ_NOTEBOOK,
  SET_SELECTED,
  START_SAVING,
  UPDATE_CELL_EXECUTION_COUNT,
  UPDATE_CELL_OUTPUTS,
  UPDATE_CELL_SOURCE,
  ERROR_KERNEL_NOT_CONNECTED,
} from '../actions/constants';

import {
  loadNotebook,
  updateExecutionCount,
  moveCell,
  newCellAfter,
  updateSource,
  updateOutputs,
} from './document';

export const reducers = {};

reducers[READ_NOTEBOOK] = loadNotebook;
reducers[UPDATE_CELL_EXECUTION_COUNT] = updateExecutionCount;
reducers[NEW_CELL_AFTER] = newCellAfter;
reducers[UPDATE_CELL_SOURCE] = updateSource;
reducers[UPDATE_CELL_OUTPUTS] = updateOutputs;
reducers[MOVE_CELL] = moveCell;

reducers[SET_SELECTED] = function setSelected(state, action) {
  const selected = action.additive ?
      state.selected.concat(action.ids) :
      action.ids;
  return Object.assign({}, state, {
    selected,
  });
};

function cleanupKernel(state) {
  if (state.channels) {
    state.channels.shell.complete();
    state.channels.iopub.complete();
    state.channels.stdin.complete();
    state.channels = null;
  }
  if (state.spawn) {
    state.spawn.kill();
    state.spawn = null;
  }
  if (state.connectionFile) {
    fs.unlink(state.connectionFile);
    state.connectionFile = null;
  }

  delete state.channels;
  delete state.spawn;
  delete state.connectionFile;
  return state;
}

reducers[NEW_KERNEL] = function newKernel(state, action) {
  const { channels, connectionFile, spawn } = action;

  // cleanup old kernels first
  state = cleanupKernel(state);

  state.channels = channels;
  state.connectionFile = connectionFile;
  state.spawn = spawn;
  return state;
};

reducers[EXIT] = function exit(state) {
  return cleanupKernel(state);
};

reducers[KILL_KERNEL] = cleanupKernel;

reducers[START_SAVING] = function startSaving(state) {
  return Object.assign({}, state, { isSaving: true });
};

reducers[ERROR_KERNEL_NOT_CONNECTED] = function alertKernelNotConnected() {
  alert('Error: We\'re not connected to a runtime!'); // eslint-disable-line no-alert
};

reducers[DONE_SAVING] = function doneSaving(state) {
  return Object.assign({}, state, { isSaving: false });
};

reducers[CHANGE_FILENAME] = function changeFilename(state, action) {
  const { filename } = action;
  if(!filename) {
    return state;
  }
  return Object.assign({}, state, { filename });
};
<|endoftext|>


<commit_before>let stage = new createjs.Stage('game-stage');
let hello = new createjs.Text('Hello world', '55px Arial', '#000');
hello.textAlign = 'center';
hello.textBaseline = 'center';
hello.x = stage.canvas.width / 2;
hello.y = stage.canvas.height / 2;
stage.addChild(hello);
stage.update();
<commit_msg>make app obj<commit_after>const app = {
  init() {
    this.stage = new createjs.Stage('game-stage');
    this.createHello();
    this.stage.update();
  },
  createHello() {
    this.hello = new createjs.Text('Hello world', '55px Arial', '#000');
    this.hello.textAlign = 'center';
    this.hello.textBaseline = 'center';
    this.hello.x = this.stage.canvas.width / 2;
    this.hello.y = this.stage.canvas.height / 2;
    this.stage.addChild(this.hello);
  },
};

app.init();
<|endoftext|>


<commit_before>/* @flow */
/**
 *  Copyright (c) 2015, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 */

type GraphiQLData = {
  query: ?string,
  variables: ?{[name: string]: mixed},
  operationName: ?string,
  result?: mixed
};

// Current latest version of GraphiQL.
const GRAPHIQL_VERSION = '0.9.1';

// Ensures string values are safe to be used within a <script> tag.
function safeSerialize(data) {
  return data ? JSON.stringify(data).replace(/\//g, '\\/') : 'undefined';
}

/**
 * When express-graphql receives a request which does not Accept JSON, but does
 * Accept HTML, it may present GraphiQL, the in-browser GraphQL explorer IDE.
 *
 * When shown, it will be pre-populated with the result of having executed the
 * requested query.
 */
export function renderGraphiQL(data: GraphiQLData): string {
  const queryString = data.query;
  const variablesString =
    data.variables ? JSON.stringify(data.variables, null, 2) : null;
  const resultString =
    data.result ? JSON.stringify(data.result, null, 2) : null;
  const operationName = data.operationName;

  /* eslint-disable max-len */
  return `<!--
The request to this GraphQL server provided the header "Accept: text/html"
and as a result has been presented GraphiQL - an in-browser IDE for
exploring GraphQL.

If you wish to receive JSON, provide the header "Accept: application/json" or
add "&raw" to the end of the URL within a browser.
-->
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title>GraphiQL</title>
  <meta name="robots" content="noindex" />
  <style>
    html, body {
      height: 100%;
      margin: 0;
      overflow: hidden;
      width: 100%;
    }
  </style>
  <link href="//cdn.jsdelivr.net/graphiql/${GRAPHIQL_VERSION}/graphiql.css" rel="stylesheet" />
  <script src="//cdn.jsdelivr.net/fetch/0.9.0/fetch.min.js"></script>
  <script src="//cdn.jsdelivr.net/react/15.4.2/react.min.js"></script>
  <script src="//cdn.jsdelivr.net/react/15.4.2/react-dom.min.js"></script>
  <script src="//cdn.jsdelivr.net/graphiql/${GRAPHIQL_VERSION}/graphiql.min.js"></script>
</head>
<body>
  <script>
    // Collect the URL parameters
    var parameters = {};
    window.location.search.substr(1).split('&').forEach(function (entry) {
      var eq = entry.indexOf('=');
      if (eq >= 0) {
        parameters[decodeURIComponent(entry.slice(0, eq))] =
          decodeURIComponent(entry.slice(eq + 1));
      }
    });

    // Produce a Location query string from a parameter object.
    function locationQuery(params) {
      return '?' + Object.keys(params).map(function (key) {
        return encodeURIComponent(key) + '=' +
          encodeURIComponent(params[key]);
      }).join('&');
    }

    // Derive a fetch URL from the current URL, sans the GraphQL parameters.
    var graphqlParamNames = {
      query: true,
      variables: true,
      operationName: true
    };

    var otherParams = {};
    for (var k in parameters) {
      if (parameters.hasOwnProperty(k) && graphqlParamNames[k] !== true) {
        otherParams[k] = parameters[k];
      }
    }
    var fetchURL = locationQuery(otherParams);

    // Defines a GraphQL fetcher using the fetch API.
    function graphQLFetcher(graphQLParams) {
      return fetch(fetchURL, {
        method: 'post',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(graphQLParams),
        credentials: 'include',
      }).then(function (response) {
        return response.text();
      }).then(function (responseBody) {
        try {
          return JSON.parse(responseBody);
        } catch (error) {
          return responseBody;
        }
      });
    }

    // When the query and variables string is edited, update the URL bar so
    // that it can be easily shared.
    function onEditQuery(newQuery) {
      parameters.query = newQuery;
      updateURL();
    }

    function onEditVariables(newVariables) {
      parameters.variables = newVariables;
      updateURL();
    }

    function onEditOperationName(newOperationName) {
      parameters.operationName = newOperationName;
      updateURL();
    }

    function updateURL() {
      history.replaceState(null, null, locationQuery(parameters));
    }

    // Render <GraphiQL /> into the body.
    ReactDOM.render(
      React.createElement(GraphiQL, {
        fetcher: graphQLFetcher,
        onEditQuery: onEditQuery,
        onEditVariables: onEditVariables,
        onEditOperationName: onEditOperationName,
        query: ${safeSerialize(queryString)},
        response: ${safeSerialize(resultString)},
        variables: ${safeSerialize(variablesString)},
        operationName: ${safeSerialize(operationName)},
      }),
      document.body
    );
  </script>
</body>
</html>`;
}
<commit_msg>Update graphiql version<commit_after>/* @flow */
/**
 *  Copyright (c) 2015, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 */

type GraphiQLData = {
  query: ?string,
  variables: ?{[name: string]: mixed},
  operationName: ?string,
  result?: mixed
};

// Current latest version of GraphiQL.
const GRAPHIQL_VERSION = '0.9.3';

// Ensures string values are safe to be used within a <script> tag.
function safeSerialize(data) {
  return data ? JSON.stringify(data).replace(/\//g, '\\/') : 'undefined';
}

/**
 * When express-graphql receives a request which does not Accept JSON, but does
 * Accept HTML, it may present GraphiQL, the in-browser GraphQL explorer IDE.
 *
 * When shown, it will be pre-populated with the result of having executed the
 * requested query.
 */
export function renderGraphiQL(data: GraphiQLData): string {
  const queryString = data.query;
  const variablesString =
    data.variables ? JSON.stringify(data.variables, null, 2) : null;
  const resultString =
    data.result ? JSON.stringify(data.result, null, 2) : null;
  const operationName = data.operationName;

  /* eslint-disable max-len */
  return `<!--
The request to this GraphQL server provided the header "Accept: text/html"
and as a result has been presented GraphiQL - an in-browser IDE for
exploring GraphQL.

If you wish to receive JSON, provide the header "Accept: application/json" or
add "&raw" to the end of the URL within a browser.
-->
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title>GraphiQL</title>
  <meta name="robots" content="noindex" />
  <style>
    html, body {
      height: 100%;
      margin: 0;
      overflow: hidden;
      width: 100%;
    }
  </style>
  <link href="//cdn.jsdelivr.net/graphiql/${GRAPHIQL_VERSION}/graphiql.css" rel="stylesheet" />
  <script src="//cdn.jsdelivr.net/fetch/0.9.0/fetch.min.js"></script>
  <script src="//cdn.jsdelivr.net/react/15.4.2/react.min.js"></script>
  <script src="//cdn.jsdelivr.net/react/15.4.2/react-dom.min.js"></script>
  <script src="//cdn.jsdelivr.net/graphiql/${GRAPHIQL_VERSION}/graphiql.min.js"></script>
</head>
<body>
  <script>
    // Collect the URL parameters
    var parameters = {};
    window.location.search.substr(1).split('&').forEach(function (entry) {
      var eq = entry.indexOf('=');
      if (eq >= 0) {
        parameters[decodeURIComponent(entry.slice(0, eq))] =
          decodeURIComponent(entry.slice(eq + 1));
      }
    });

    // Produce a Location query string from a parameter object.
    function locationQuery(params) {
      return '?' + Object.keys(params).map(function (key) {
        return encodeURIComponent(key) + '=' +
          encodeURIComponent(params[key]);
      }).join('&');
    }

    // Derive a fetch URL from the current URL, sans the GraphQL parameters.
    var graphqlParamNames = {
      query: true,
      variables: true,
      operationName: true
    };

    var otherParams = {};
    for (var k in parameters) {
      if (parameters.hasOwnProperty(k) && graphqlParamNames[k] !== true) {
        otherParams[k] = parameters[k];
      }
    }
    var fetchURL = locationQuery(otherParams);

    // Defines a GraphQL fetcher using the fetch API.
    function graphQLFetcher(graphQLParams) {
      return fetch(fetchURL, {
        method: 'post',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(graphQLParams),
        credentials: 'include',
      }).then(function (response) {
        return response.text();
      }).then(function (responseBody) {
        try {
          return JSON.parse(responseBody);
        } catch (error) {
          return responseBody;
        }
      });
    }

    // When the query and variables string is edited, update the URL bar so
    // that it can be easily shared.
    function onEditQuery(newQuery) {
      parameters.query = newQuery;
      updateURL();
    }

    function onEditVariables(newVariables) {
      parameters.variables = newVariables;
      updateURL();
    }

    function onEditOperationName(newOperationName) {
      parameters.operationName = newOperationName;
      updateURL();
    }

    function updateURL() {
      history.replaceState(null, null, locationQuery(parameters));
    }

    // Render <GraphiQL /> into the body.
    ReactDOM.render(
      React.createElement(GraphiQL, {
        fetcher: graphQLFetcher,
        onEditQuery: onEditQuery,
        onEditVariables: onEditVariables,
        onEditOperationName: onEditOperationName,
        query: ${safeSerialize(queryString)},
        response: ${safeSerialize(resultString)},
        variables: ${safeSerialize(variablesString)},
        operationName: ${safeSerialize(operationName)},
      }),
      document.body
    );
  </script>
</body>
</html>`;
}
<|endoftext|>


<commit_before>/*
 * Copyright 2013, All Rights Reserved.
 *
 * Code licensed under the BSD License:
 * https://github.com/node-gh/gh/blob/master/LICENSE.md
 *
 * @author Zeno Rocha <zno.rocha@gmail.com>
 * @author Eduardo Lundgren <edu@rdo.io>
 */

'use strict';

// -- Requires -------------------------------------------------------------------------------------

var async = require('async'),
    base = require('../base'),
    hooks = require('../hooks'),
    logger = require('../logger'),
    openUrl = require('open'),
    config = base.getConfig();

// -- Constructor ----------------------------------------------------------------------------------

function Issue(options) {
    this.options = options;

    if (!options.repo && !options.all) {
        logger.error('You must specify a Git repository to run this command');
    }
}

// -- Constants ------------------------------------------------------------------------------------

Issue.DETAILS = {
    alias: 'is',
    description: 'Provides a set of util commands to work with Issues.',
    iterative: 'number',
    commands: [
        'browser',
        'close',
        'comment',
        'list',
        'new',
        'open'
    ],
    options: {
        'all': Boolean,
        'assignee': String,
        'browser': Boolean,
        'close': Boolean,
        'comment': String,
        'detailed': Boolean,
        'label': String,
        'list': Boolean,
        'message': String,
        'milestone': Number,
        'new': Boolean,
        'number': [String, Array],
        'open': Boolean,
        'remote': String,
        'repo': String,
        'state': ['open', 'closed'],
        'title': String,
        'user': String
    },
    shorthands: {
        'a': ['--all'],
        'A': ['--assignee'],
        'B': ['--browser'],
        'C': ['--close'],
        'c': ['--comment'],
        'd': ['--detailed'],
        'L': ['--label'],
        'l': ['--list'],
        'm': ['--message'],
        'M': ['--milestone'],
        'N': ['--new'],
        'n': ['--number'],
        'o': ['--open'],
        'r': ['--repo'],
        'S': ['--state'],
        't': ['--title'],
        'u': ['--user']
    },
    payload: function(payload, options) {
        if (payload[0]) {
            options.new = true;
            options.title = options.title || payload[0];
            options.message = options.message || payload[1];
        }
        else {
            options.list = true;
        }
    }
};

Issue.STATE_CLOSED = 'closed';
Issue.STATE_OPEN = 'open';

// -- Commands -------------------------------------------------------------------------------------

Issue.prototype.run = function() {
    var instance = this,
        options = instance.options;

    options.state = options.state || Issue.STATE_OPEN;

    if (options.browser) {
        instance.browser(options.user, options.repo, options.number);
    }

    if (options.close) {
        hooks.invoke('issue.close', instance, function(afterHooksCallback) {
            options.state = Issue.STATE_CLOSED;

            logger.logTemplate(
                '{{prefix}} [info] Closing issue {{greenBright "#" options.number}} on {{greenBright options.user "/" options.repo}}', {
                    options: options
                });

            instance.close(function(err) {
                logger.defaultCallback(
                    err, null, logger.compileTemplate('{{issueLink}}', {
                        options: options
                    }));

                afterHooksCallback();
            });
        });
    }

    if (options.comment) {
        logger.logTemplate(
            '{{prefix}} [info] Adding comment on issue {{greenBright "#" options.number}}', {
                options: options
            });

        instance.comment(function(err) {
            logger.defaultCallback(
                err, null, logger.compileTemplate('{{issueLink}}', {
                    options: options
                }));
        });
    }

    if (options.list) {
        if (options.all) {
            logger.logTemplate(
                '{{prefix}} [info] Listing {{greenBright options.state}} issues for {{greenBright options.user}}', {
                    options: options
                });

            instance.listFromAllRepositories(function(err) {
                logger.defaultCallback(err, null, false);
            });
        }
        else {
            logger.logTemplate(
                '{{prefix}} [info] Listing {{greenBright options.state}} issues on {{greenBright options.user "/" options.repo}}', {
                    options: options
                });

            instance.list(options.user, options.repo, function(err) {
                logger.defaultCallback(err, null, false);
            });
        }
    }

    if (options.new) {
        hooks.invoke('issue.new', instance, function(afterHooksCallback) {
            logger.logTemplate(
                '{{prefix}} [info] Creating a new issue on {{greenBright options.user "/" options.repo}}', {
                    options: options
                });

            instance.new(function(err, issue) {
                if (issue) {
                    options.number = issue.number;
                }

                logger.defaultCallback(
                    err, null, logger.compileTemplate('{{issueLink}}', {
                        options: options
                    }));

                afterHooksCallback();
            });
        });
    }

    if (options.open) {
        hooks.invoke('issue.open', instance, function(afterHooksCallback) {
            logger.logTemplate(
                '{{prefix}} [info] Opening issue {{greenBright "#" options.number}} on {{greenBright options.user "/" options.repo}}', {
                    options: options
                });

            instance.open(function(err) {
                logger.defaultCallback(
                    err, null, logger.compileTemplate('{{issueLink}}', {
                        options: options
                    }));

                afterHooksCallback();
            });
        });
    }

};

Issue.prototype.browser = function(user, repo, number) {
    openUrl('https://github.com/' + user + '/' + repo + '/issues/' + number);
};

Issue.prototype.close = function(opt_callback) {
    var instance = this;

    instance.getIssue_(function(err, issue) {
        if (err) {
            opt_callback && opt_callback(err);
        }
        else {
            instance.editIssue_(issue.title, Issue.STATE_CLOSED, opt_callback);
        }
    });
};

Issue.prototype.comment = function(opt_callback) {
    var instance = this,
        options = instance.options,
        payload;

    options.comment = logger.applyReplacements(options.comment) + config.signature;

    payload = {
        body: options.comment,
        number: options.number,
        repo: options.repo,
        user: options.user
    };

    base.github.issues.createComment(payload, opt_callback);
};

Issue.prototype.editIssue_ = function(title, state, opt_callback) {
    var instance = this,
        options = instance.options,
        payload;

    payload = {
        number: options.number,
        assignee: options.assignee,
        milestone: options.milestone,
        repo: options.repo,
        state: state,
        title: title,
        user: options.user
    };

    if (typeof options.label == 'string') {
        payload.label = options.label.split(',');
    }

    base.github.issues.edit(payload, opt_callback);
};

Issue.prototype.getIssue_ = function(opt_callback) {
    var instance = this,
        options = instance.options,
        payload;

    payload = {
        number: options.number,
        repo: options.repo,
        user: options.user
    };

    base.github.issues.getRepoIssue(payload, opt_callback);
};

Issue.prototype.list = function(user, repo, opt_callback) {
    var instance = this,
        options = instance.options,
        operations,
        payload;

    options.label = options.label || '';
    options.milestone = options.milestone || 'none';

    payload = {
        labels: options.label,
        milestone: options.milestone,
        repo: repo,
        state: options.state,
        user: user
    };

    if (options.assignee) {
        payload.assignee = options.assignee;
    }

    operations = [

        function(callback) {
            base.github.issues.repoIssues(payload, callback);
        }
    ];

    if (options.milestone === 'none') {
        operations.push(function(callback) {
            payload.milestone = '*';
            base.github.issues.repoIssues(payload, callback);
        });
    }

    async.parallel(operations, function(err, results) {
        if (err && !options.all) {
            logger.error(logger.getErrorMessage(err));
        }

        var issues = [];

        if (options.number) {
            results.forEach(function(result) {
                if (!result) {
                    return;
                }

                result.forEach(function(issue) {
                    if (options.number == issue.number) {
                        issues.push(issue);
                    }
                });
            });
        } else {
            results.forEach(function(result) {
                if (result) {
                    issues = issues.concat(result);
                }
            });
        }

        issues.sort(function(a, b) {
            return a.number > b.number ? -1 : 1;
        });

        if (issues && issues.length > 0) {
            logger.logTemplateFile('issue.handlebars', {
                detailed: options.detailed,
                issues: issues,
                repo: repo,
                user: user
            });

            opt_callback && opt_callback(err);
        }
    });
};

Issue.prototype.listFromAllRepositories = function(opt_callback) {
    var instance = this,
        options = instance.options,
        payload;

    payload = {
        type: 'all',
        user: options.user
    };

    base.github.repos.getAll(payload, function(err, repositories) {
        if (err) {
            opt_callback && opt_callback(err);
        }
        else {
            repositories.forEach(function(repository) {
                instance.list(repository.owner.login, repository.name, opt_callback);
            });
        }
    });
};

Issue.prototype.new = function(opt_callback) {
    var instance = this,
        options = instance.options,
        payload;

    if (options.message) {
        options.message = logger.applyReplacements(options.message);
    }

    if (options.label) {
        options.label = options.label.split(',');
    }
    else {
        options.label = [];
    }

    payload = {
        assignee: options.assignee,
        body: options.message,
        repo: options.repo,
        title: options.title,
        user: options.user,
        labels: options.label
    };

    base.github.issues.create(payload, opt_callback);
};

Issue.prototype.open = function(opt_callback) {
    var instance = this;

    instance.getIssue_(function(err, issue) {
        if (err) {
            opt_callback && opt_callback(err);
        }
        else {
            instance.editIssue_(issue.title, Issue.STATE_OPEN, opt_callback);
        }
    });
};

exports.Impl = Issue;
<commit_msg>github api expect "labels" instead of "label"<commit_after>/*
 * Copyright 2013, All Rights Reserved.
 *
 * Code licensed under the BSD License:
 * https://github.com/node-gh/gh/blob/master/LICENSE.md
 *
 * @author Zeno Rocha <zno.rocha@gmail.com>
 * @author Eduardo Lundgren <edu@rdo.io>
 */

'use strict';

// -- Requires -------------------------------------------------------------------------------------

var async = require('async'),
    base = require('../base'),
    hooks = require('../hooks'),
    logger = require('../logger'),
    openUrl = require('open'),
    config = base.getConfig();

// -- Constructor ----------------------------------------------------------------------------------

function Issue(options) {
    this.options = options;

    if (!options.repo && !options.all) {
        logger.error('You must specify a Git repository to run this command');
    }
}

// -- Constants ------------------------------------------------------------------------------------

Issue.DETAILS = {
    alias: 'is',
    description: 'Provides a set of util commands to work with Issues.',
    iterative: 'number',
    commands: [
        'browser',
        'close',
        'comment',
        'list',
        'new',
        'open'
    ],
    options: {
        'all': Boolean,
        'assignee': String,
        'browser': Boolean,
        'close': Boolean,
        'comment': String,
        'detailed': Boolean,
        'label': String,
        'list': Boolean,
        'message': String,
        'milestone': Number,
        'new': Boolean,
        'number': [String, Array],
        'open': Boolean,
        'remote': String,
        'repo': String,
        'state': ['open', 'closed'],
        'title': String,
        'user': String
    },
    shorthands: {
        'a': ['--all'],
        'A': ['--assignee'],
        'B': ['--browser'],
        'C': ['--close'],
        'c': ['--comment'],
        'd': ['--detailed'],
        'L': ['--label'],
        'l': ['--list'],
        'm': ['--message'],
        'M': ['--milestone'],
        'N': ['--new'],
        'n': ['--number'],
        'o': ['--open'],
        'r': ['--repo'],
        'S': ['--state'],
        't': ['--title'],
        'u': ['--user']
    },
    payload: function(payload, options) {
        if (payload[0]) {
            options.new = true;
            options.title = options.title || payload[0];
            options.message = options.message || payload[1];
        }
        else {
            options.list = true;
        }
    }
};

Issue.STATE_CLOSED = 'closed';
Issue.STATE_OPEN = 'open';

// -- Commands -------------------------------------------------------------------------------------

Issue.prototype.run = function() {
    var instance = this,
        options = instance.options;

    options.state = options.state || Issue.STATE_OPEN;

    if (options.browser) {
        instance.browser(options.user, options.repo, options.number);
    }

    if (options.close) {
        hooks.invoke('issue.close', instance, function(afterHooksCallback) {
            options.state = Issue.STATE_CLOSED;

            logger.logTemplate(
                '{{prefix}} [info] Closing issue {{greenBright "#" options.number}} on {{greenBright options.user "/" options.repo}}', {
                    options: options
                });

            instance.close(function(err) {
                logger.defaultCallback(
                    err, null, logger.compileTemplate('{{issueLink}}', {
                        options: options
                    }));

                afterHooksCallback();
            });
        });
    }

    if (options.comment) {
        logger.logTemplate(
            '{{prefix}} [info] Adding comment on issue {{greenBright "#" options.number}}', {
                options: options
            });

        instance.comment(function(err) {
            logger.defaultCallback(
                err, null, logger.compileTemplate('{{issueLink}}', {
                    options: options
                }));
        });
    }

    if (options.list) {
        if (options.all) {
            logger.logTemplate(
                '{{prefix}} [info] Listing {{greenBright options.state}} issues for {{greenBright options.user}}', {
                    options: options
                });

            instance.listFromAllRepositories(function(err) {
                logger.defaultCallback(err, null, false);
            });
        }
        else {
            logger.logTemplate(
                '{{prefix}} [info] Listing {{greenBright options.state}} issues on {{greenBright options.user "/" options.repo}}', {
                    options: options
                });

            instance.list(options.user, options.repo, function(err) {
                logger.defaultCallback(err, null, false);
            });
        }
    }

    if (options.new) {
        hooks.invoke('issue.new', instance, function(afterHooksCallback) {
            logger.logTemplate(
                '{{prefix}} [info] Creating a new issue on {{greenBright options.user "/" options.repo}}', {
                    options: options
                });

            instance.new(function(err, issue) {
                if (issue) {
                    options.number = issue.number;
                }

                logger.defaultCallback(
                    err, null, logger.compileTemplate('{{issueLink}}', {
                        options: options
                    }));

                afterHooksCallback();
            });
        });
    }

    if (options.open) {
        hooks.invoke('issue.open', instance, function(afterHooksCallback) {
            logger.logTemplate(
                '{{prefix}} [info] Opening issue {{greenBright "#" options.number}} on {{greenBright options.user "/" options.repo}}', {
                    options: options
                });

            instance.open(function(err) {
                logger.defaultCallback(
                    err, null, logger.compileTemplate('{{issueLink}}', {
                        options: options
                    }));

                afterHooksCallback();
            });
        });
    }

};

Issue.prototype.browser = function(user, repo, number) {
    openUrl('https://github.com/' + user + '/' + repo + '/issues/' + number);
};

Issue.prototype.close = function(opt_callback) {
    var instance = this;

    instance.getIssue_(function(err, issue) {
        if (err) {
            opt_callback && opt_callback(err);
        }
        else {
            instance.editIssue_(issue.title, Issue.STATE_CLOSED, opt_callback);
        }
    });
};

Issue.prototype.comment = function(opt_callback) {
    var instance = this,
        options = instance.options,
        payload;

    options.comment = logger.applyReplacements(options.comment) + config.signature;

    payload = {
        body: options.comment,
        number: options.number,
        repo: options.repo,
        user: options.user
    };

    base.github.issues.createComment(payload, opt_callback);
};

Issue.prototype.editIssue_ = function(title, state, opt_callback) {
    var instance = this,
        options = instance.options,
        payload;

    payload = {
        number: options.number,
        assignee: options.assignee,
        milestone: options.milestone,
        repo: options.repo,
        state: state,
        title: title,
        user: options.user
    };

    if (typeof options.label == 'string') {
        payload.labels = options.label.split(',');
    }

    base.github.issues.edit(payload, opt_callback);
};

Issue.prototype.getIssue_ = function(opt_callback) {
    var instance = this,
        options = instance.options,
        payload;

    payload = {
        number: options.number,
        repo: options.repo,
        user: options.user
    };

    base.github.issues.getRepoIssue(payload, opt_callback);
};

Issue.prototype.list = function(user, repo, opt_callback) {
    var instance = this,
        options = instance.options,
        operations,
        payload;

    options.label = options.label || '';
    options.milestone = options.milestone || 'none';

    payload = {
        labels: options.label,
        milestone: options.milestone,
        repo: repo,
        state: options.state,
        user: user
    };

    if (options.assignee) {
        payload.assignee = options.assignee;
    }

    operations = [

        function(callback) {
            base.github.issues.repoIssues(payload, callback);
        }
    ];

    if (options.milestone === 'none') {
        operations.push(function(callback) {
            payload.milestone = '*';
            base.github.issues.repoIssues(payload, callback);
        });
    }

    async.parallel(operations, function(err, results) {
        if (err && !options.all) {
            logger.error(logger.getErrorMessage(err));
        }

        var issues = [];

        if (options.number) {
            results.forEach(function(result) {
                if (!result) {
                    return;
                }

                result.forEach(function(issue) {
                    if (options.number == issue.number) {
                        issues.push(issue);
                    }
                });
            });
        } else {
            results.forEach(function(result) {
                if (result) {
                    issues = issues.concat(result);
                }
            });
        }

        issues.sort(function(a, b) {
            return a.number > b.number ? -1 : 1;
        });

        if (issues && issues.length > 0) {
            logger.logTemplateFile('issue.handlebars', {
                detailed: options.detailed,
                issues: issues,
                repo: repo,
                user: user
            });

            opt_callback && opt_callback(err);
        }
    });
};

Issue.prototype.listFromAllRepositories = function(opt_callback) {
    var instance = this,
        options = instance.options,
        payload;

    payload = {
        type: 'all',
        user: options.user
    };

    base.github.repos.getAll(payload, function(err, repositories) {
        if (err) {
            opt_callback && opt_callback(err);
        }
        else {
            repositories.forEach(function(repository) {
                instance.list(repository.owner.login, repository.name, opt_callback);
            });
        }
    });
};

Issue.prototype.new = function(opt_callback) {
    var instance = this,
        options = instance.options,
        payload;

    if (options.message) {
        options.message = logger.applyReplacements(options.message);
    }

    if (options.label) {
        options.label = options.label.split(',');
    }
    else {
        options.label = [];
    }

    payload = {
        assignee: options.assignee,
        body: options.message,
        repo: options.repo,
        title: options.title,
        user: options.user,
        labels: options.label
    };

    base.github.issues.create(payload, opt_callback);
};

Issue.prototype.open = function(opt_callback) {
    var instance = this;

    instance.getIssue_(function(err, issue) {
        if (err) {
            opt_callback && opt_callback(err);
        }
        else {
            instance.editIssue_(issue.title, Issue.STATE_OPEN, opt_callback);
        }
    });
};

exports.Impl = Issue;
<|endoftext|>


<commit_before>'use strict';
exports.info = {
  desc: 'Lookup RB6 Siege Stats / Top Operators for PC.',
  usage: '<name> [pc, xbl, psn]',
  aliases: [],
};

const request = require('superagent');
const moment = require('moment');

// Scrape RB6 Siege stats to show in Discord
exports.run = (client, msg, params = []) => new Promise((resolve, reject) => {
  if (!params[0]) params[0] = 'annemunition';
  const name = params[0];
  let platform = params[1].toLowerCase() || 'uplay';
  if (platform === 'pc') platform = 'uplay';
  if (platform !== 'uplay' && platform !== 'xbl' && platform !== 'psn') {
    msg.channel.send(`**${platform}** is not a known platform. **pc** (default), **xbl**, or **psn**`);
    return;
  }
  msg.channel.send(`Looking up **${platform}** RB6 Siege stats for **${name}**. Please wait...`)
    .then(m => {
      fetch(`https://public-ubiservices.ubi.com/v2/profiles?nameOnPlatform=${name}&platformType=${platform}`, client)
        .then(result => {
          if (result.body.profiles.length === 0) {
            m.delete();
            msg.channel.send(`No ${platform} stats found for **${name}**.`);
            return;
          }
          const userId = result.body.profiles[0].userId;
          const userName = result.body.profiles[0].nameOnPlatform;
          const stats = [
            'casualpvp_timeplayed',
            'rankedpvp_timeplayed',
            'operatorpvp_timeplayed',
          ];
          Promise.all([
            /* eslint-disable max-len */
            fetch(`https://public-ubiservices.ubi.com/v1/spaces/5172a557-50b5-4665-b7db-e3f2e8c5041d/sandboxes/OSBOR_PC_LNCH_A/playerstats2/statistics?populations=${userId}&statistics=${stats.join(',')}`, client),
            fetch(`https://public-ubiservices.ubi.com/v1/spaces/5172a557-50b5-4665-b7db-e3f2e8c5041d/sandboxes/OSBOR_PC_LNCH_A/r6karma/players?board_id=pvp_ranked&profile_ids=${userId}&region_id=ncsa&season_id=-1`, client),
            fetch(`https://public-ubiservices.ubi.com/v1/spaces/5172a557-50b5-4665-b7db-e3f2e8c5041d/sandboxes/OSBOR_PC_LNCH_A/r6playerprofile/playerprofile/progressions?profile_ids=${userId}`, client),
            /* eslint-enable max-len */
          ])
            .then(results => {
              const data = results[0].body.results[userId];
              const rankedData = results[1].body.players[userId];
              const profileData = results[2].body.player_profiles[0];
              const opTimePlayed = [];
              for (const key in data) {
                if (data.hasOwnProperty(key)) {
                  if (key.startsWith('operatorpvp_timeplayed')) {
                    const op = key.replace('operatorpvp_timeplayed', '').replace('infinite', '');
                    opTimePlayed.push({ name: resolveOperator(op) || op, time: data[key] });
                  }
                }
              }
              const statistics = {
                name: userName,
                id: userId,
                platform,
                level: profileData.level,
                mmr: rankedData.mmr.toFixed(0),
                max_mmr: rankedData.max_mmr.toFixed(0),
                rank: resolveRank(rankedData.rank),
                avatar: `https://ubisoft-avatars.akamaized.net/${userId}/default_146_146.png` +
                `?appId=39baebad-39e5-4552-8c25-2c9b919064e2`,
                casualTime: formatTime(data['casualpvp_timeplayed:infinite']),
                rankedTime: formatTime(data['rankedpvp_timeplayed:infinite']),
                rb6Uri: `https://game-rainbow6.ubi.com/en-us/${platform}/player-statistics/${userId}/multiplayer`,
                operators: opTimePlayed.sort((a, b) => b.time - a.time).slice(0, 6),
              };
              // Post results to Discord
              m.delete().catch(client.logger.error);
              const embed = new client.Discord.RichEmbed()
                .setDescription(buildStringToPost(statistics))
                .setThumbnail(statistics.avatar);
              msg.channel.send({ embed }).then(resolve).catch(reject);
            })
            .catch(err => {
              client.logger.error(err);
              m.delete().catch(client.logger.error);
              msg.reply(`Error looking up **${platform}** stats for **${name}**.`);
            });
        })
        .catch(err => {
          client.logger.error(err);
          m.delete().catch(client.logger.error);
          msg.reply(`Error looking up **${platform}** stats for **${name}**.`);
        });
    })
    .catch(reject);
});

function fetch(uri) {
  return new Promise((resolve, reject) => {
    request
      .get(uri)
      .type('json')
      .set('Ubi-AppId', '39baebad-39e5-4552-8c25-2c9b919064e2')
      /* eslint-disable max-len */
      .set('Authorization', 'Ubi_v1 t=ew0KICAidmVyIjogIjEiLA0KICAiYWlkIjogIjM5YmFlYmFkLTM5ZTUtNDU1Mi04YzI1LTJjOWI5MTkwNjRlMiIsDQogICJlbnYiOiAiUHJvZCIsDQogICJzaWQiOiAiYmU2MTk1YzItOTAwMC00NmI2LTkzZmItZGI0YTVmYzNjMjIyIiwNCiAgInR5cCI6ICJKV0UiLA0KICAiZW5jIjogIkExMjhDQkMiLA0KICAiaXYiOiAiWFJhQU5ZT0F2ZlBUMWVmb2lVaFZiQSIsDQogICJpbnQiOiAiSFMyNTYiDQp9.qAolPxOJu7-Yc0uBQZLj6q_PgUMdgAatu2ymrE9DoSvMQ5rIc3GewdJgZPEyr-qEIzHcyK5RkwJdMV53GlPbJQIDsJKQPWQaLGbW8CUP25FfbwDLRjaXNMcSe6q9gHzorlsyglI1GQHYTp3IYMmMHvD7HDImi2SVirRY919CEACgD4EeBsox3GwhwRY_npOiop5wbePFTa4okOf_hiCopvNf2ZbDtdCF9V5ooDxE1QRxui5grS5BQoOWRc97_yTCFO1A9SY6zTfu6JEM45ecIncjnF2F4KfdG03iFuFIv0moxk5tGWvWUbun-2gaDEDri9YIy70XzBs8xFm33eulKhCT_dC5A0DeXD7Om2rr3j8znSo5YBpXDtCivEdJ1ZTrKBYx61NeAL68pJAsD5wh5TTbE2J1Dtwsvf3RB2PkKKCFy405tpn4p8MARVT6hCIZ-S6WX0gAwpJwXXQka7GZNn-tkWa5TM6oBrtEKycsk3Z7oBdRKxEAoN7o2HJs2SX5BJxrwgiRr3OoeLvj9zP-ETLEEHffhAYhE45OzVWMwba-S-UYk-p3xW3DUG9sMR5OhwXUcwclTyjbmY1DSfDUD6GW1hGjWEOw9sEj4gIoGtvA3qYjmpdojY2CMQYZhILFEm5NjhyGRYD8Dd2lMq8LlksTKzLzyuWW4B0YEx56gVlcr2x49ci_hvh3gaazvj4wSKVjpnmdUljT-oIDQeL-3MQKcDudzheJGz_cbRG8_sm2XLQ5zSjJg1vvXAB2kyHc46TS8TGaMphAYKCs5VDgMISMWdm0IYxRslGKkD4qhAxA7QQ4hRfEXH3HgV76_WXcuudNUTj538C1qM29FGcwRQr5HrvgU3zYXHlczqonEQFrGZjtY_I_S2WMkQK1qmOXlguRUt0xhq5PuuEFW3vOaRZwAZ9yd2uf-UzMuscfQyeDaUORv_CCNDjPUH0QnTxZ83_AzsvTJzKrd4zgS0LtMBmspOY4oC2wkHNWfAN20IPdrRBI1iYP0KZCqoUFH0ZI7XLd5M48SovVnnpTEjkF1JOegVIrDOjBEZ4pdwFmDUzW5GWeRBBhcSCyl1mvpounOXFp3PcI7QCPZ4DU_CblqhZ3smOfU0-Yg4f5fmSJAHE_g1CdFZhTL_yJ872GPLb5uzJlMhEYKaWRzJ1XiUzPMm5aAkkjbX4YiuujZ3lepDHvoZqX7hoqzWNjd4bkn65vwRAg5Ndz6WzBncRb5LUDrmEpvn0W9Nr3Pd8JAIVxftNmKsYWypL2ZM5X20z4W79VrjJqmZSF4f7DxlISLIioytiw7o5c8IYxqPAkD8I2eYhd8RbQBdhzf-6B-pWTgo7lmxxgcXuq6t-0kX1bbLJCLGoSK2HbUR9jfRKJHZVr_6GA7Su_w0jju6V5LW3lLB0u-MpfrbwbtN3ACYNcPCfCUg.xbpxYIFU9KLFvLaK5xVLr_vLbB1PDoBORO-f9wrWfjM')
      /* eslint-enable max-len */
      .end((err, res) => {
        if (err) return reject(err);
        return resolve(res);
      });
  });
}

function formatTime(seconds) {
  const t = moment.duration(seconds, 'seconds');
  const hours = t.asHours().toFixed(0);
  if (hours > 1) return `${hours} hour${hours === 1 ? '' : 's'}`;
  const minutes = t.asMinutes().toFixed(0);
  return `${minutes} minute${minutes === 1 ? '' : 's'}`;
}

function buildStringToPost(stats) {
  let str = `RB6 Siege Statistics - ${stats.name}:\n\n`;
  if (stats.casualTime) str += `Casual: ${stats.casualTime} played - Level: ${stats.level}\n`;
  if (stats.rankedTime) {
    str += `Ranked: ${stats.rankedTime} played - Rank: '${stats.rank}'\n`;
    str += `MMR: ${stats.mmr} - Max: ${stats.max_mmr}\n`;
  }
  str += '\nTop Operators =>\n';
  stats.operators.forEach(op => {
    const padName = padString(op.name, 9);
    const timePlayed = padTime(op.time);
    str += `${(stats.operators.indexOf(op) + 1)}: ${padName} - ${timePlayed}\n`;
  });
  str = `\`\`\`qml\n${str}\`\`\`[Rainbow 6 Siege Stats](${stats.rb6Uri})`;
  return str;
}

function padTime(str) {
  if (typeof str === 'number') str = formatTime(str);
  let i = str.split(' ')[0].split('').length;
  for (i; i < 3; i++) {
    str = ` ${str}`;
  }
  return str;
}

function padString(str, p) {
  if (p < str.length) {
    return str;
  }
  const a = str.split('');
  for (let i = str.length; i <= p; i++) {
    a[i] = ' ';
  }
  return a.join('');
}

const opCodes = {
  ':2:1:': 'Smoke',
  ':3:1:': 'Mute',
  ':4:1:': 'Sledge',
  ':5:1:': 'Thatcher',
  ':2:2:': 'Castle',
  ':3:2:': 'Ash',
  ':4:2:': 'Pulse',
  ':5:2:': 'Thermite',
  ':2:3:': 'Doc',
  ':3:3:': 'Rook',
  ':4:3:': 'Twitch',
  ':5:3:': 'Montagne',
  ':2:4:': 'Glaz',
  ':3:4:': 'Fuze',
  ':4:4:': 'Kapkan',
  ':5:4:': 'Tachanka',
  ':2:5:': 'Blitz',
  ':3:5:': 'IQ',
  ':4:5:': 'Jager',
  ':5:5:': 'Bandit',
  ':2:6:': 'Buck',
  ':3:6:': 'Frost',
  ':2:7:': 'Blackbeard',
  ':3:7:': 'Valkyrie',
  ':2:8:': 'Capitao',
  ':3:8:': 'Caveira',
  ':2:9:': 'Hibana',
  ':3:9:': 'Echo',
  ':2:A:': 'Jackal',
  ':3:A:': 'Mira',
};

function resolveOperator(code) {
  return opCodes[code];
}

const rankNames = [
  'COPPER IV',
  'COPPER III',
  'COPPER II',
  'COPPER I',
  'BRONZE IV',
  'BRONZE III',
  'BRONZE II',
  'BRONZE I',
  'SILVER IV',
  'SILVER III',
  'SILVER II',
  'SILVER I',
  'GOLD IV',
  'GOLD III',
  'GOLD II',
  'GOLD I',
  'PLATINUM III',
  'PLATINUM II',
  'PLATINUM I',
  'DIAMOND',
];

function resolveRank(num) {
  return rankNames[num - 1];
}
<commit_msg>fix error<commit_after>'use strict';
exports.info = {
  desc: 'Lookup RB6 Siege Stats / Top Operators for PC.',
  usage: '<name> [pc, xbl, psn]',
  aliases: [],
};

const request = require('superagent');
const moment = require('moment');

// Scrape RB6 Siege stats to show in Discord
exports.run = (client, msg, params = []) => new Promise((resolve, reject) => {
  if (!params[0]) params[0] = 'annemunition';
  const name = params[0];
  let platform = params[1] ? params[1].toLowerCase() : 'uplay';
  if (platform === 'pc') platform = 'uplay';
  if (platform !== 'uplay' && platform !== 'xbl' && platform !== 'psn') {
    msg.channel.send(`**${platform}** is not a known platform. **pc** (default), **xbl**, or **psn**`);
    return;
  }
  msg.channel.send(`Looking up **${platform}** RB6 Siege stats for **${name}**. Please wait...`)
    .then(m => {
      fetch(`https://public-ubiservices.ubi.com/v2/profiles?nameOnPlatform=${name}&platformType=${platform}`, client)
        .then(result => {
          if (result.body.profiles.length === 0) {
            m.delete();
            msg.channel.send(`No ${platform} stats found for **${name}**.`);
            return;
          }
          const userId = result.body.profiles[0].userId;
          const userName = result.body.profiles[0].nameOnPlatform;
          const stats = [
            'casualpvp_timeplayed',
            'rankedpvp_timeplayed',
            'operatorpvp_timeplayed',
          ];
          Promise.all([
            /* eslint-disable max-len */
            fetch(`https://public-ubiservices.ubi.com/v1/spaces/5172a557-50b5-4665-b7db-e3f2e8c5041d/sandboxes/OSBOR_PC_LNCH_A/playerstats2/statistics?populations=${userId}&statistics=${stats.join(',')}`, client),
            fetch(`https://public-ubiservices.ubi.com/v1/spaces/5172a557-50b5-4665-b7db-e3f2e8c5041d/sandboxes/OSBOR_PC_LNCH_A/r6karma/players?board_id=pvp_ranked&profile_ids=${userId}&region_id=ncsa&season_id=-1`, client),
            fetch(`https://public-ubiservices.ubi.com/v1/spaces/5172a557-50b5-4665-b7db-e3f2e8c5041d/sandboxes/OSBOR_PC_LNCH_A/r6playerprofile/playerprofile/progressions?profile_ids=${userId}`, client),
            /* eslint-enable max-len */
          ])
            .then(results => {
              const data = results[0].body.results[userId];
              const rankedData = results[1].body.players[userId];
              const profileData = results[2].body.player_profiles[0];
              const opTimePlayed = [];
              for (const key in data) {
                if (data.hasOwnProperty(key)) {
                  if (key.startsWith('operatorpvp_timeplayed')) {
                    const op = key.replace('operatorpvp_timeplayed', '').replace('infinite', '');
                    opTimePlayed.push({ name: resolveOperator(op) || op, time: data[key] });
                  }
                }
              }
              const statistics = {
                name: userName,
                id: userId,
                platform,
                level: profileData.level,
                mmr: rankedData.mmr.toFixed(0),
                max_mmr: rankedData.max_mmr.toFixed(0),
                rank: resolveRank(rankedData.rank),
                avatar: `https://ubisoft-avatars.akamaized.net/${userId}/default_146_146.png` +
                `?appId=39baebad-39e5-4552-8c25-2c9b919064e2`,
                casualTime: formatTime(data['casualpvp_timeplayed:infinite']),
                rankedTime: formatTime(data['rankedpvp_timeplayed:infinite']),
                rb6Uri: `https://game-rainbow6.ubi.com/en-us/${platform}/player-statistics/${userId}/multiplayer`,
                operators: opTimePlayed.sort((a, b) => b.time - a.time).slice(0, 6),
              };
              // Post results to Discord
              m.delete().catch(client.logger.error);
              const embed = new client.Discord.RichEmbed()
                .setDescription(buildStringToPost(statistics))
                .setThumbnail(statistics.avatar);
              msg.channel.send({ embed }).then(resolve).catch(reject);
            })
            .catch(err => {
              client.logger.error(err);
              m.delete().catch(client.logger.error);
              msg.reply(`Error looking up **${platform}** stats for **${name}**.`);
            });
        })
        .catch(err => {
          client.logger.error(err);
          m.delete().catch(client.logger.error);
          msg.reply(`Error looking up **${platform}** stats for **${name}**.`);
        });
    })
    .catch(reject);
});

function fetch(uri) {
  return new Promise((resolve, reject) => {
    request
      .get(uri)
      .type('json')
      .set('Ubi-AppId', '39baebad-39e5-4552-8c25-2c9b919064e2')
      /* eslint-disable max-len */
      .set('Authorization', 'Ubi_v1 t=ew0KICAidmVyIjogIjEiLA0KICAiYWlkIjogIjM5YmFlYmFkLTM5ZTUtNDU1Mi04YzI1LTJjOWI5MTkwNjRlMiIsDQogICJlbnYiOiAiUHJvZCIsDQogICJzaWQiOiAiYmU2MTk1YzItOTAwMC00NmI2LTkzZmItZGI0YTVmYzNjMjIyIiwNCiAgInR5cCI6ICJKV0UiLA0KICAiZW5jIjogIkExMjhDQkMiLA0KICAiaXYiOiAiWFJhQU5ZT0F2ZlBUMWVmb2lVaFZiQSIsDQogICJpbnQiOiAiSFMyNTYiDQp9.qAolPxOJu7-Yc0uBQZLj6q_PgUMdgAatu2ymrE9DoSvMQ5rIc3GewdJgZPEyr-qEIzHcyK5RkwJdMV53GlPbJQIDsJKQPWQaLGbW8CUP25FfbwDLRjaXNMcSe6q9gHzorlsyglI1GQHYTp3IYMmMHvD7HDImi2SVirRY919CEACgD4EeBsox3GwhwRY_npOiop5wbePFTa4okOf_hiCopvNf2ZbDtdCF9V5ooDxE1QRxui5grS5BQoOWRc97_yTCFO1A9SY6zTfu6JEM45ecIncjnF2F4KfdG03iFuFIv0moxk5tGWvWUbun-2gaDEDri9YIy70XzBs8xFm33eulKhCT_dC5A0DeXD7Om2rr3j8znSo5YBpXDtCivEdJ1ZTrKBYx61NeAL68pJAsD5wh5TTbE2J1Dtwsvf3RB2PkKKCFy405tpn4p8MARVT6hCIZ-S6WX0gAwpJwXXQka7GZNn-tkWa5TM6oBrtEKycsk3Z7oBdRKxEAoN7o2HJs2SX5BJxrwgiRr3OoeLvj9zP-ETLEEHffhAYhE45OzVWMwba-S-UYk-p3xW3DUG9sMR5OhwXUcwclTyjbmY1DSfDUD6GW1hGjWEOw9sEj4gIoGtvA3qYjmpdojY2CMQYZhILFEm5NjhyGRYD8Dd2lMq8LlksTKzLzyuWW4B0YEx56gVlcr2x49ci_hvh3gaazvj4wSKVjpnmdUljT-oIDQeL-3MQKcDudzheJGz_cbRG8_sm2XLQ5zSjJg1vvXAB2kyHc46TS8TGaMphAYKCs5VDgMISMWdm0IYxRslGKkD4qhAxA7QQ4hRfEXH3HgV76_WXcuudNUTj538C1qM29FGcwRQr5HrvgU3zYXHlczqonEQFrGZjtY_I_S2WMkQK1qmOXlguRUt0xhq5PuuEFW3vOaRZwAZ9yd2uf-UzMuscfQyeDaUORv_CCNDjPUH0QnTxZ83_AzsvTJzKrd4zgS0LtMBmspOY4oC2wkHNWfAN20IPdrRBI1iYP0KZCqoUFH0ZI7XLd5M48SovVnnpTEjkF1JOegVIrDOjBEZ4pdwFmDUzW5GWeRBBhcSCyl1mvpounOXFp3PcI7QCPZ4DU_CblqhZ3smOfU0-Yg4f5fmSJAHE_g1CdFZhTL_yJ872GPLb5uzJlMhEYKaWRzJ1XiUzPMm5aAkkjbX4YiuujZ3lepDHvoZqX7hoqzWNjd4bkn65vwRAg5Ndz6WzBncRb5LUDrmEpvn0W9Nr3Pd8JAIVxftNmKsYWypL2ZM5X20z4W79VrjJqmZSF4f7DxlISLIioytiw7o5c8IYxqPAkD8I2eYhd8RbQBdhzf-6B-pWTgo7lmxxgcXuq6t-0kX1bbLJCLGoSK2HbUR9jfRKJHZVr_6GA7Su_w0jju6V5LW3lLB0u-MpfrbwbtN3ACYNcPCfCUg.xbpxYIFU9KLFvLaK5xVLr_vLbB1PDoBORO-f9wrWfjM')
      /* eslint-enable max-len */
      .end((err, res) => {
        if (err) return reject(err);
        return resolve(res);
      });
  });
}

function formatTime(seconds) {
  const t = moment.duration(seconds, 'seconds');
  const hours = t.asHours().toFixed(0);
  if (hours > 1) return `${hours} hour${hours === 1 ? '' : 's'}`;
  const minutes = t.asMinutes().toFixed(0);
  return `${minutes} minute${minutes === 1 ? '' : 's'}`;
}

function buildStringToPost(stats) {
  let str = `RB6 Siege Statistics - ${stats.name}:\n\n`;
  if (stats.casualTime) str += `Casual: ${stats.casualTime} played - Level: ${stats.level}\n`;
  if (stats.rankedTime) {
    str += `Ranked: ${stats.rankedTime} played - Rank: '${stats.rank}'\n`;
    str += `MMR: ${stats.mmr} - Max: ${stats.max_mmr}\n`;
  }
  str += '\nTop Operators =>\n';
  stats.operators.forEach(op => {
    const padName = padString(op.name, 9);
    const timePlayed = padTime(op.time);
    str += `${(stats.operators.indexOf(op) + 1)}: ${padName} - ${timePlayed}\n`;
  });
  str = `\`\`\`qml\n${str}\`\`\`[Rainbow 6 Siege Stats](${stats.rb6Uri})`;
  return str;
}

function padTime(str) {
  if (typeof str === 'number') str = formatTime(str);
  let i = str.split(' ')[0].split('').length;
  for (i; i < 3; i++) {
    str = ` ${str}`;
  }
  return str;
}

function padString(str, p) {
  if (p < str.length) {
    return str;
  }
  const a = str.split('');
  for (let i = str.length; i <= p; i++) {
    a[i] = ' ';
  }
  return a.join('');
}

const opCodes = {
  ':2:1:': 'Smoke',
  ':3:1:': 'Mute',
  ':4:1:': 'Sledge',
  ':5:1:': 'Thatcher',
  ':2:2:': 'Castle',
  ':3:2:': 'Ash',
  ':4:2:': 'Pulse',
  ':5:2:': 'Thermite',
  ':2:3:': 'Doc',
  ':3:3:': 'Rook',
  ':4:3:': 'Twitch',
  ':5:3:': 'Montagne',
  ':2:4:': 'Glaz',
  ':3:4:': 'Fuze',
  ':4:4:': 'Kapkan',
  ':5:4:': 'Tachanka',
  ':2:5:': 'Blitz',
  ':3:5:': 'IQ',
  ':4:5:': 'Jager',
  ':5:5:': 'Bandit',
  ':2:6:': 'Buck',
  ':3:6:': 'Frost',
  ':2:7:': 'Blackbeard',
  ':3:7:': 'Valkyrie',
  ':2:8:': 'Capitao',
  ':3:8:': 'Caveira',
  ':2:9:': 'Hibana',
  ':3:9:': 'Echo',
  ':2:A:': 'Jackal',
  ':3:A:': 'Mira',
};

function resolveOperator(code) {
  return opCodes[code];
}

const rankNames = [
  'COPPER IV',
  'COPPER III',
  'COPPER II',
  'COPPER I',
  'BRONZE IV',
  'BRONZE III',
  'BRONZE II',
  'BRONZE I',
  'SILVER IV',
  'SILVER III',
  'SILVER II',
  'SILVER I',
  'GOLD IV',
  'GOLD III',
  'GOLD II',
  'GOLD I',
  'PLATINUM III',
  'PLATINUM II',
  'PLATINUM I',
  'DIAMOND',
];

function resolveRank(num) {
  return rankNames[num - 1];
}
<|endoftext|>