text:
/* jshint browser: true */
/* jshint unused: false */
/* global arangoHelper, _, frontendConfig, slicePath, icon, Joi, wheelnav, document, sigma, Backbone, templateEngine, $, window*/
(function () {
  'use strict';

  window.GraphViewer2 = Backbone.View.extend({
    el: '#content',

    remove: function () {
      this.$el.empty().off(); /* off to unbind the events */
      this.stopListening();
      return this;
    },

    template: templateEngine.createTemplate('graphViewer2.ejs'),

    initialize: function (options) {
      var self = this;

      if (options.id) {
        // dynamically set id if available
        this.setElement(options.id);
        this.graphData = options.data;
        this.aqlMode = true;
      }

      this.name = options.name;
      this.userConfig = options.userConfig;
      this.documentStore = options.documentStore;
      this.initSigma();

      if (this.name !== undefined) {
        this.collection.fetch({
          cache: false,
          success: function (data) {
            self.model = self.collection.findWhere({_key: options.name}).toJSON();
          }
        });
      }
    },

    colors: {
      hotaru: ['#364C4A', '#497C7F', '#92C5C0', '#858168', '#CCBCA5'],
      random1: ['#292F36', '#4ECDC4', '#F7FFF7', '#DD6363', '#FFE66D']
    },

    activeNodes: [],
    selectedNodes: {},

    aqlMode: false,

    events: {
      'click #downloadPNG': 'downloadSVG',
      'click #reloadGraph': 'reloadGraph',
      'click #settingsMenu': 'toggleSettings',
      'click #noGraphToggle': 'toggleSettings',
      'click #toggleForce': 'toggleLayout',
      'click #selectNodes': 'toggleLasso'
    },

    cursorX: 0,
    cursorY: 0,

    layouting: false,

    model: null,

    viewStates: {
      captureMode: false
    },

    graphConfig: null,
    graphSettings: null,

    initSigma: function () {
      // init sigma
      try {
        sigma.classes.graph.addMethod('neighbors', function (nodeId) {
          var k;
          var neighbors = {};
          var index = this.allNeighborsIndex[nodeId] || {};

          for (k in index) {
            neighbors[k] = this.nodesIndex[k];
          }
          return neighbors;
        });

        sigma.classes.graph.addMethod('getNodeEdges', function (nodeId) {
          var edges = this.edges();
          var edgesToReturn = [];

          _.each(edges, function (edge) {
            if (edge.source === nodeId || edge.target === nodeId) {
              edgesToReturn.push(edge.id);
            }
          });
          return edgesToReturn;
        });

        sigma.classes.graph.addMethod('getNodeEdgesCount', function (id) {
          return this.allNeighborsCount[id];
        });
      } catch (ignore) {}
    },

    downloadSVG: function () {
      var size = parseInt($('#graph-container').width(), 10);
      sigma.plugins.image(this.currentGraph, this.currentGraph.renderers[0], {
        download: true,
        size: size,
        background: 'white',
        zoom: true
      });
    },

    resize: function () {
      // adjust container widht + height
      $('#graph-container').width($('.centralContent').width());
      $('#graph-container').height($('.centralRow').height() - 150);
    },

    toggleSettings: function () {
      this.graphSettingsView.toggle();
    },

    render: function (toFocus) {
      this.$el.html(this.template.render({}));

      // render navigation
      $('#subNavigationBar .breadcrumb').html(
        'Graph: ' + this.name
      );

      this.resize();
      this.fetchGraph(toFocus);
    },

    renderAQL: function (data) {
      this.$el.html(this.template.render({}));

      // remove not needed elements
      this.$el.find('.headerBar').remove();

      // set graph box height
      var height = $('.centralRow').height() - 250;
      this.$el.find('#graph-container').css('height', height);

      // render
      this.graphData.modified = this.parseData(this.graphData.original, this.graphData.graphInfo);
      this.renderGraph(this.graphData.modified, null, true);
    },

    parseData: function (data, type) {
      var vertices = {}; var edges = {};
      var returnObj = {
        nodes: [],
        edges: [],
        settings: {}
      };

      if (type === 'object') {
        _.each(data, function (obj) {
          if (obj.edges && obj.vertices) {
            _.each(obj.edges, function (edge) {
              if (edge !== null) {
                edges[edge._id] = {
                  id: edge._id,
                  source: edge._from,
                  // label: edge._key,
                  color: '#cccccc',
                  target: edge._to
                };
              }
            });

            _.each(obj.vertices, function (node) {
              vertices[node._id] = {
                id: node._id,
                label: node._key,
                // size: 0.3,
                color: '#2ecc71',
                x: Math.random(),
                y: Math.random()
              };
            });
          }
        });

        _.each(vertices, function (node) {
          returnObj.nodes.push(node);
        });

        _.each(edges, function (edge) {
          returnObj.edges.push(edge);
        });
      } else if (type === 'array') {
        _.each(data, function (edge) {
          vertices[edge._from] = null;
          vertices[edge._to] = null;

          returnObj.edges.push({
            id: edge._id,
            source: edge._from,
            // label: edge._key,
            color: '#cccccc',
            target: edge._to
          });
        });

        _.each(vertices, function (val, key) {
          returnObj.nodes.push({
            id: key,
            label: key,
            size: 0.3,
            color: '#2ecc71',
            x: Math.random(),
            y: Math.random()
          });
        });
      }

      return returnObj;
    },

    rerender: function () {
      this.fetchGraph();
    },

    fetchGraph: function (toFocus) {
      var self = this;
      // arangoHelper.buildGraphSubNav(self.name, 'Content');
      $(this.el).append(
        '
' +
        '' +
        'Fetching graph data. Please wait ...

' +
        'If it`s taking too much time to draw the graph, please navigate to: ' +
        'Graphs View
Click the settings icon and reset the display settings.' +
        'It is possible that the graph is too big to be handled by the browser.
'
      );

      var continueFetchGraph = function () {
        var ajaxData = {};
        if (this.graphConfig) {
          ajaxData = _.clone(this.graphConfig);

          // remove not needed params
          delete ajaxData.layout;
          delete ajaxData.edgeType;
          delete ajaxData.renderer;
        }

        if (self.tmpStartNode) {
          if (self.graphConfig) {
            if (self.graphConfig.nodeStart.length === 0) {
              ajaxData.nodeStart = self.tmpStartNode;
            }
          } else {
            ajaxData.nodeStart = self.tmpStartNode;
          }
        }

        this.setupSigma();

        self.fetchStarted = new Date();
        $.ajax({
          type: 'GET',
          url: arangoHelper.databaseUrl('/_admin/aardvark/graph/' + encodeURIComponent(this.name)),
          contentType: 'application/json',
          data: ajaxData,
          success: function (data) {
            if (data.empty === true) {
              self.renderGraph(data, toFocus);
            } else {
              if (data.settings) {
                if (data.settings.startVertex && self.graphConfig.startNode === undefined) {
                  if (self.tmpStartNode === undefined) {
                    self.tmpStartNode = data.settings.startVertex._id;
                  }
                }
              }

              self.fetchFinished = new Date();
              self.calcStart = self.fetchFinished;
              $('#calcText').html('Server response took ' + Math.abs(self.fetchFinished.getTime() - self.fetchStarted.getTime()) + ' ms. Initializing graph engine. Please wait ... ');
              // arangoHelper.buildGraphSubNav(self.name, 'Content');
              window.setTimeout(function () {
                self.renderGraph(data, toFocus);
              }, 50);
            }
          },
          error: function (e) {
            try {
              arangoHelper.arangoError('Graph', e.responseJSON.exception);

              var found = e.responseJSON.exception.search('1205');
              if (found !== -1) {
                var string = 'Starting point: ' + self.graphConfig.nodeStart + ' is invalid';
                $('#calculatingGraph').html(
                  '
Stopped.

' +
                  string +
                  '. Please choose a different start node.
'
                );
              } else {
                $('#calculatingGraph').html('Failed to fetch graph information.');
              }
            } catch (ignore) {}
          }
        });
      }.bind(this);

      // load graph configuration
      this.getGraphSettings(continueFetchGraph);
    },

    setupSigma: function () {
      if (this.graphConfig) {
        if (this.graphConfig.edgeLabel) {
          // Initialize package:
          sigma.utils.pkg('sigma.settings');

          var settings = {
            defaultEdgeLabelColor: '#000',
            defaultEdgeLabelActiveColor: '#000',
            defaultEdgeLabelSize: 12,
            edgeLabelSize: 'fixed',
            edgeLabelThreshold: 1,
            edgeLabelSizePowRatio: 1
          };

          // Export the previously designed settings:
          sigma.settings = sigma.utils.extend(sigma.settings || {}, settings);

          // Override default settings:
          sigma.settings.drawEdgeLabels = true;
        }
      }
    },

    contextState: {
      createEdge: false,
      _from: false,
      _to: false,
      fromX: false,
      fromY: false
    },

    clearOldContextMenu: function (states) {
      var self = this;

      // clear dom
      $('#nodeContextMenu').remove();
      var string = '

';
      $('#graph-container').append(string);

      // clear state
      if (states) {
        _.each(this.contextState, function (val, key) {
          self.contextState[key] = false;
        });
      }

      // clear events
      var c = document.getElementsByClassName('sigma-mouse')[0];
      c.removeEventListener('mousemove', self.drawLine.bind(this), false);

      // clear info div
    },

    trackCursorPosition: function (e) {
      this.cursorX = e.x;
      this.cursorY = e.y;
    },

    deleteNode: function (e, id) {
      var self = this;
      var documentKey;
      var collectionId;
      var documentId;

      if (id) {
        documentKey = id;
      } else {
        documentKey = $('#delete-node-attr-id').text();
      }
      collectionId = documentKey.split('/')[0];
      documentId = documentKey.split('/')[1];

      if ($('#delete-node-edges-attr').val() === 'yes') {
        $.ajax({
          cache: false,
          type: 'DELETE',
          contentType: 'application/json',
          url: arangoHelper.databaseUrl(
            '/_api/gharial/' + encodeURIComponent(self.name) + '/vertex/' + encodeURIComponent(documentKey.split('/')[0]) + '/' + encodeURIComponent(documentKey.split('/')[1])
          ),
          success: function (data) {
            self.currentGraph.graph.dropNode(documentKey);
            self.currentGraph.refresh();
          },
          error: function () {
            arangoHelper.arangoError('Graph', 'Could not delete node.');
          }
        });
      } else {
        var callback = function (error) {
          if (!error) {
            self.currentGraph.graph.dropNode(documentKey);

            // rerender graph
            self.currentGraph.refresh();
          } else {
            arangoHelper.arangoError('Graph', 'Could not delete node.');
          }
        };

        this.documentStore.deleteDocument(collectionId, documentId, callback);
      }
      window.modalView.hide();
    },

    deleteNodes: function () {
      var self = this;

      try {
        var arr = JSON.parse($('#delete-nodes-arr-id').text());
        _.each(arr, function (id) {
          self.deleteNode(null, id);
        });
      } catch (ignore) {
      }
    },

    deleteNodesModal: function () {
      var nodeIds = [];

      _.each(this.selectedNodes, function (id) {
        nodeIds.push(id);
      });

      if (nodeIds.length === 0) {
        arangoHelper.arangoNotification('Graph', 'No nodes selected.');
        return;
      }

      var buttons = []; var tableContent = [];

      tableContent.push(
        window.modalView.createReadOnlyEntry('delete-nodes-arr-id', 'Really delete nodes', JSON.stringify(nodeIds))
      );

      buttons.push(
        window.modalView.createDeleteButton('Delete', this.deleteNodes.bind(this))
      );

      window.modalView.show(
        'modalTable.ejs',
        'Delete nodes',
        buttons,
        tableContent
      );
    },

    deleteNodeModal: function (nodeId) {
      var buttons = []; var tableContent = [];

      tableContent.push(
        window.modalView.createReadOnlyEntry('delete-node-attr-id', 'Really delete node', nodeId)
      );

      tableContent.push(
        window.modalView.createSelectEntry(
          'delete-node-edges-attr',
          'Also delete edges?',
          undefined,
          undefined,
          [
            {
              value: 'yes',
              label: 'Yes'
            },
            {
              value: 'no',
              label: 'No'
            }
          ]
        )
      );

      buttons.push(
        window.modalView.createDeleteButton('Delete', this.deleteNode.bind(this))
      );

      window.modalView.show(
        'modalTable.ejs',
        'Delete node',
        buttons,
        tableContent
      );
    },

    addNode: function () {
      var self = this;

      var x = self.addNodeX / 100;
      var y = self.addNodeY / 100;

      var collectionId = $('.modal-body #new-node-collection-attr').val();
      var key = $('.modal-body #new-node-key-attr').last().val();

      var callback = function (error, id, msg) {
        if (error) {
          arangoHelper.arangoError('Could not create node', msg.errorMessage);
        } else {
          $('#emptyGraph').remove();
          self.currentGraph.graph.addNode({
            id: id,
            label: id.split('/')[1] || '',
            size: self.graphConfig.nodeSize || Math.random(),
            color: self.graphConfig.nodeColor || '#2ecc71',
            x: x,
            y: y
          });

          window.modalView.hide();
          // rerender graph
          self.currentGraph.refresh();
        }
      };

      if (key !== '' || key !== undefined) {
        this.documentStore.createTypeDocument(collectionId, key, callback);
      } else {
        this.documentStore.createTypeDocument(collectionId, null, callback);
      }
    },

    deleteEdgeModal: function (edgeId) {
      var buttons = []; var tableContent = [];

      tableContent.push(
        window.modalView.createReadOnlyEntry('delete-edge-attr-id', 'Really delete edge', edgeId)
      );

      buttons.push(
        window.modalView.createDeleteButton('Delete', this.deleteEdge.bind(this))
      );

      window.modalView.show(
        'modalTable.ejs',
        'Delete edge',
        buttons,
        tableContent
      );
    },

    deleteEdge: function () {
      var self = this;
      var documentKey = $('#delete-edge-attr-id').text();
      var collectionId = documentKey.split('/')[0];
      var documentId = documentKey.split('/')[1];

      var callback = function (error) {
        if (!error) {
          self.currentGraph.graph.dropEdge(documentKey);

          // rerender graph
          self.currentGraph.refresh();
        } else {
          arangoHelper.arangoError('Graph', 'Could not delete edge.');
        }
      };

      this.documentStore.deleteDocument(collectionId, documentId, callback);
      window.modalView.hide();
    },

    addNodeModal: function () {
      if (this.graphSettings.vertexCollections !== 0) {
        var buttons = []; var tableContent = []; var collections = [];

        _.each(this.graphSettings.vertexCollections, function (val) {
          collections.push({
            label: val.name,
            value: val.id
          });
        });

        tableContent.push(
          window.modalView.createTextEntry(
            'new-node-key-attr',
            '_key',
            undefined,
            'The nodes unique key(optional attribute, leave empty for autogenerated key',
            'is optional: leave empty for autogenerated key',
            false,
            [
              {
                rule: Joi.string().allow('').optional(),
                msg: ''
              }
            ]
          )
        );

        tableContent.push(
          window.modalView.createSelectEntry(
            'new-node-collection-attr',
            'Collection',
            undefined,
            'Please select the destination for the new node.',
            collections
          )
        );

        buttons.push(
          window.modalView.createSuccessButton('Create', this.addNode.bind(this))
        );

        window.modalView.show(
          'modalTable.ejs',
          'Create node',
          buttons,
          tableContent
        );
      } else {
        arangoHelper.arangoError('Graph', 'No valid vertex collections found.');
      }
    },

    addEdge: function () {
      var self = this;
      var from = self.contextState._from;
      var to = self.contextState._to;

      var collectionName;
      if ($('.modal-body #new-edge-collection-attr').val() === '') {
        collectionName = $('.modal-body #new-edge-collection-attr').text();
      } else {
        collectionName = $('.modal-body #new-edge-collection-attr').val();
      }
      var key = $('.modal-body #new-edge-key-attr').last().val();

      var callback = function (error, data, msg) {
        if (!error) {
          // success
          if (self.graphConfig.edgeEditable === 'true') {
            self.currentGraph.graph.addEdge({
              source: from,
              size: 1,
              target: to,
              id: data._id,
              color: self.graphConfig.edgeColor
            });
          } else {
            self.currentGraph.graph.addEdge({
              source: from,
              target: to,
              id: data._id,
              color: self.graphConfig.edgeColor
            });
          }

          // rerender graph
          if (self.graphConfig) {
            if (self.graphConfig.edgeType === 'curve') {
              sigma.canvas.edges.autoCurve(self.currentGraph);
            }
          }
          self.currentGraph.refresh();
        } else {
          arangoHelper.arangoError('Could not create edge', msg.errorMessage);
        }

        // then clear states
        self.clearOldContextMenu(true);
        window.modalView.hide();
      };

      if (key !== '' || key !== undefined) {
        this.documentStore.createTypeEdge(collectionName, from, to, key, callback);
      } else {
        this.documentStore.createTypeEdge(collectionName, from, to, null, callback);
      }
    },

    addEdgeModal: function (edgeDefinitions) {
      if (edgeDefinitions !== 0) {
        var buttons = []; var tableContent = [];

        tableContent.push(
          window.modalView.createTextEntry(
            'new-edge-key-attr',
            '_key',
            undefined,
            'The edges unique key(optional attribute, leave empty for autogenerated key',
            'is optional: leave empty for autogenerated key',
            false,
            [
              {
                rule: Joi.string().allow('').optional(),
                msg: ''
              }
            ]
          )
        );

        if (edgeDefinitions.length > 1) {
          var collections = [];

          _.each(edgeDefinitions, function (val) {
            collections.push({
              label: val,
              value: val
            });
          });

          tableContent.push(
            window.modalView.createSelectEntry(
              'new-edge-collection-attr',
              'Edge collection',
              undefined,
              'Please select the destination for the new edge.',
              collections
            )
          );
        } else {
          tableContent.push(
            window.modalView.createReadOnlyEntry(
              'new-edge-collection-attr',
              'Edge collection',
              edgeDefinitions[0],
              'The edges collection to be used.'
            )
          );
        }

        buttons.push(
          window.modalView.createSuccessButton('Create', this.addEdge.bind(this))
        );

        window.modalView.show(
          'modalTable.ejs',
          'Create edge',
          buttons,
          tableContent
        );
      } else {
        arangoHelper.arangoError('Graph', 'No valid edge definitions found.');
      }
    },

    updateColors: function (nodes, edges, ncolor, ecolor) {
      var combinedName = window.App.currentDB.toJSON().name + '_' + this.name;
      var self = this;

      this.userConfig.fetch({
        success: function (data) {
          if (nodes === true) {
            self.graphConfig = data.toJSON().graphs[combinedName];
            self.currentGraph.graph.nodes().forEach(function (n) {
              n.color = ncolor;
            });
          }

          if (edges === true) {
            self.currentGraph.graph.edges().forEach(function (e) {
              e.color = ecolor;
            });
          }

          self.currentGraph.refresh();
        }
      });
    },

    // right click nodes context menu
    createNodesContextMenu: function (e) {
      var self = this;

      // if right click
      if (e.which === 3) {
        var x = e.clientX - 50;
        var y = e.clientY - 50;
        this.clearOldContextMenu();

        var generateMenu = function (e) {
          var Wheelnav = wheelnav;

          var wheel = new Wheelnav('nodeContextMenu');
          wheel.maxPercent = 1.0;
          wheel.wheelRadius = 50;
          wheel.clockwise = false;
          wheel.colors = self.colors.hotaru;
          wheel.multiSelect = true;
          wheel.clickModeRotate = false;
          wheel.slicePathFunction = slicePath().DonutSlice;
          if (self.viewStates.captureMode) {
            wheel.createWheel([icon.plus, icon.trash]);
          } else {
            wheel.createWheel([icon.trash, icon.arrowleft2]);
          }

          wheel.navItems[0].selected = false;
          wheel.navItems[0].hovered = false;
          // add menu events

          // function 0: remove all selectedNodes
          wheel.navItems[0].navigateFunction = function (e) {
            self.clearOldContextMenu();
            self.deleteNodesModal();
          };

          // function 1: clear contextmenu
          wheel.navItems[1].navigateFunction = function (e) {
            self.clearOldContextMenu();
          };

          // deselect active default entry
          wheel.navItems[0].selected = false;
          wheel.navItems[0].hovered = false;
        };

        $('#nodeContextMenu').css('position', 'fixed');
        $('#nodeContextMenu').css('left', x);
        $('#nodeContextMenu').css('top', y);
        $('#nodeContextMenu').width(100);
        $('#nodeContextMenu').height(100);

        generateMenu(e);
      } else {
        self.clearOldContextMenu();
      }
    },

    // right click background context menu
    createContextMenu: function (e) {
      var self = this;
      var x = self.cursorX - 50;
      var y = self.cursorY - 50;
      this.clearOldContextMenu();

      var generateMenu = function (e) {
        var Wheelnav = wheelnav;

        var wheel = new Wheelnav('nodeContextMenu');
        wheel.maxPercent = 1.0;
        wheel.wheelRadius = 50;
        wheel.clockwise = false;
        wheel.colors = self.colors.hotaru;
        wheel.multiSelect = true;
        wheel.clickModeRotate = false;
        wheel.slicePathFunction = slicePath().DonutSlice;
        wheel.createWheel([icon.plus, icon.arrowleft2]);

        // add menu events
        wheel.navItems[0].selected = false;
        wheel.navItems[0].hovered = false;

        // function 0: add node
        wheel.navItems[0].navigateFunction = function (e) {
          self.clearOldContextMenu();
          self.addNodeModal();
        };

        // function 1: exit
        wheel.navItems[1].navigateFunction = function (e) {
          self.clearOldContextMenu();
        };

        // deselect active default entry
        wheel.navItems[0].selected = false;
        wheel.navItems[0].hovered = false;
      };

      $('#nodeContextMenu').css('position', 'fixed');
      $('#nodeContextMenu').css('left', x);
      $('#nodeContextMenu').css('top', y);
      $('#nodeContextMenu').width(100);
      $('#nodeContextMenu').height(100);

      generateMenu(e);
    },

    // right click edge context menu
    createEdgeContextMenu: function (edgeId, e) {
      var self = this;
      var x = this.cursorX - 165;
      var y = this.cursorY - 120;

      this.clearOldContextMenu();

      var generateMenu = function (e, edgeId) {
        var hotaru = ['#364C4A', '#497C7F', '#92C5C0', '#858168', '#CCBCA5'];

        var Wheelnav = wheelnav;

        var wheel = new Wheelnav('nodeContextMenu');
        wheel.maxPercent = 1.0;
        wheel.wheelRadius = 50;
        wheel.clockwise = false;
        wheel.colors = hotaru;
        wheel.multiSelect = true;
        wheel.clickModeRotate = false;
        wheel.slicePathFunction = slicePath().DonutSlice;
        wheel.createWheel([icon.edit, icon.trash]);

        // add menu events
        wheel.navItems[0].selected = false;
        wheel.navItems[0].hovered = false;

        // function 0: edit
        wheel.navItems[0].navigateFunction = function (e) {
          self.clearOldContextMenu();
          self.editEdge(edgeId);
        };

        // function 1: delete
        wheel.navItems[1].navigateFunction = function (e) {
          self.clearOldContextMenu();
          self.deleteEdgeModal(edgeId);
        };

        // deselect active default entry
        wheel.navItems[0].selected = false;
        wheel.navItems[0].hovered = false;
      };

      $('#nodeContextMenu').css('left', x + 115);
      $('#nodeContextMenu').css('top', y + 72);
      $('#nodeContextMenu').width(100);
      $('#nodeContextMenu').height(100);

      generateMenu(e, edgeId);
    },

    // right click node context menu
    createNodeContextMenu: function (nodeId, e) {
      var self = this;
      var x; var y; var size;

      // case canvas
      _.each(e.data.node, function (val, key) {
        if (key.substr(0, 8) === 'renderer' && key.charAt(key.length - 1) === 'x') {
          x = val;
        }
        if (key.substr(0, 8) === 'renderer' && key.charAt(key.length - 1) === 'y') {
          y = val;
        }
        if (key.substr(0, 8) === 'renderer' && key.charAt(key.length - 1) === 'e') {
          size = val;
        }
      });

      if (x === undefined && y === undefined) {
        // case webgl
        _.each(e.data.node, function (val, key) {
          if (key.substr(0, 8) === 'read_cam' && key.charAt(key.length - 1) === 'x') {
            x = val + $('#graph-container').width() / 2;
          }
          if (key.substr(0, 8) === 'read_cam' && key.charAt(key.length - 1) === 'y') {
            y = val + $('#graph-container').height() / 2;
          }
        });
      }

      var radius = size * 2.5;

      if (radius < 75) {
        radius = 75;
      }

      this.clearOldContextMenu();
      var generateMenu = function (e, nodeId) {
        var hotaru = ['#364C4A', '#497C7F', '#92C5C0', '#858168', '#CCBCA5'];

        var Wheelnav = wheelnav;

        var wheel = new Wheelnav('nodeContextMenu');
        wheel.maxPercent = 1.0;
        wheel.wheelRadius = radius;
        wheel.clockwise = false;
        wheel.colors = hotaru;
        wheel.multiSelect = false;
        wheel.clickModeRotate = false;
        wheel.sliceHoverAttr = {stroke: '#fff', 'stroke-width': 2};
        wheel.slicePathFunction = slicePath().DonutSlice;
        wheel.createWheel([icon.edit, icon.trash, icon.flag, icon.connect, icon.expand]);

        window.setTimeout(function () {
          // add menu events

          // function 0: edit
          wheel.navItems[0].navigateFunction = function (e) {
            self.clearOldContextMenu();
            self.editNode(nodeId);
          };

          // function 1: delete
          wheel.navItems[1].navigateFunction = function (e) {
            self.clearOldContextMenu();
            self.deleteNodeModal(nodeId);
          };

          // function 2: mark as start node
          wheel.navItems[2].navigateFunction = function (e) {
            self.clearOldContextMenu();
            self.setStartNode(nodeId);
          };

          // function 3: create edge
          wheel.navItems[3].navigateFunction = function (e) {
            self.contextState.createEdge = true;
            self.contextState._from = nodeId;
            self.contextState.fromX = x;
            self.contextState.fromY = y;

            var c = document.getElementsByClassName('sigma-mouse')[0];
            c.addEventListener('mousemove', self.drawLine.bind(this), false);

            self.clearOldContextMenu();
          };

          // function 4: mark as start node
          wheel.navItems[4].navigateFunction = function (e) {
            self.clearOldContextMenu();
            self.expandNode(nodeId);
          };

          // on hover
          /* TODO
          wheel.navItems[0].navSlice.mouseover(function (a) {
            $(a.target).css('opacity', '1');
          });
          wheel.navItems[0].navSlice.mouseout(function (a) {
            $(a.target).css('opacity', '0.8');
          });
          */

          // deselect active default entry
          wheel.navItems[0].selected = false;
          wheel.navItems[0].hovered = false;
        }, 300);
      };

      var offset = $('#graph-container').offset();
      $('#nodeContextMenu').width(radius * 2);
      $('#nodeContextMenu').height(radius * 2);
      // $('#nodeContextMenu').css('left', e.data.captor.clientX - radius);
      // $('#nodeContextMenu').css('top', e.data.captor.clientY - radius);
      // $('#nodeContextMenu').css('left', x + 150 + 15 - radius);
      // $('#nodeContextMenu').css('top', y + 60 + 42 + 15 - radius);
      $('#nodeContextMenu').css('left', x + offset.left - radius);
      $('#nodeContextMenu').css('top', y + offset.top - radius);

      generateMenu(e, nodeId);
    },

    clearMouseCanvas: function () {
      var c = document.getElementsByClassName('sigma-mouse')[0];
      var ctx = c.getContext('2d');
      ctx.clearRect(0, 0, $(c).width(), $(c).height());
    },

    expandNode: function (id) {
      var self = this;
      var ajaxData = {};

      if (this.graphConfig) {
        ajaxData = _.clone(this.graphConfig);

        // remove not needed params
        delete ajaxData.layout;
        delete ajaxData.edgeType;
        delete ajaxData.renderer;
      }

      ajaxData.query = 'FOR v, e, p IN 1..1 ANY "' + id + '" GRAPH "' + self.name + '" RETURN p';

      $.ajax({
        type: 'GET',
        url: arangoHelper.databaseUrl('/_admin/aardvark/graph/' + encodeURIComponent(this.name)),
        contentType: 'application/json',
        data: ajaxData,
        success: function (data) {
          self.checkExpand(data, id);
        },
        error: function (e) {
          arangoHelper.arangoError('Graph', 'Could not expand node: ' + id + '.');
        }
      });
    },

    checkExpand: function (data, origin) {
      var self = this;
      var newNodes = data.nodes;
      var newEdges = data.edges;
      var existingNodes = this.currentGraph.graph.nodes();

      var found;
      var newNodeCounter = 0;
      var newEdgeCounter = 0;

      _.each(newNodes, function (newNode) {
        found = false;
        _.each(existingNodes, function (existingNode) {
          if (found === false) {
            if (newNode.id === existingNode.id) {
              if (existingNode.id === origin) {
                existingNode.label = existingNode.label + ' (expanded)';
              }
              found = true;
            } else {
              found = false;
            }
          }
        });

        if (found === false) {
          newNode.originalColor = newNode.color;
          self.currentGraph.graph.addNode(newNode);
          newNodeCounter++;

          _.each(newEdges, function (edge) {
            if (edge.source === newNode.id || edge.target === newNode.id) {
              edge.originalColor = edge.color;
              self.currentGraph.graph.addEdge(edge);
              newEdgeCounter++;
            }
          });
        }
      });

      $('#nodesCount').text(parseInt($('#nodesCount').text()) + newNodeCounter);
      $('#edgesCount').text(parseInt($('#edgesCount').text()) + newEdgeCounter);

      // rerender graph
      if (newNodeCounter > 0 || newEdgeCounter > 0) {
        if (self.algorithm === 'force') {
          self.startLayout(true, origin);
        } else if (self.algorithm === 'fruchtermann') {
          sigma.layouts.fruchtermanReingold.start(self.currentGraph);
          self.currentGraph.refresh();
          // self.cameraToNode(origin);
        } else if (self.algorithm === 'noverlap') {
          self.startLayout(true, origin); // tmp bugfix, rerender with noverlap currently not possible
          // self.currentGraph.startNoverlap();
        }
      }
    },

    /*
    cameraToNode: function (node) {
      var self = this;
      console.log(node);

      self.currentGraph.cameras[0].goTo({
        x: node['read_cam0:x'],
        y: node['read_cam0:y']
      });
      /*
      sigma.misc.animation.camera(
        self.currentGraph.camera,
        {
          x: node[self.currentGraph.camera.readPrefix + 'x'],
          y: node[self.currentGraph.camera.readPrefix + 'y'],
          ratio: 1
        },
        {duration: self.currentGraph.settings('animationsTime') || 300}
      );
    },
    */

    drawLine: function (e) {
      var context = window.App.graphViewer2.contextState;

      if (context.createEdge) {
        var fromX = context.fromX;
        var fromY = context.fromY;
        var toX = e.offsetX;
        var toY = e.offsetY;

        var c = document.getElementsByClassName('sigma-mouse')[0];
        var ctx = c.getContext('2d');
        ctx.clearRect(0, 0, $(c).width(), $(c).height());
        ctx.beginPath();
        ctx.moveTo(fromX, fromY);
        ctx.lineTo(toX, toY);
        ctx.strokeStyle = this.newEdgeColor;
        ctx.stroke();
      }
    },

    getGraphSettings: function (callback) {
      var self = this;
      var combinedName = frontendConfig.db + '_' + this.name;

      this.userConfig.fetch({
        success: function (data) {
          self.graphConfig = data.toJSON().graphs[combinedName];

          // init settings view
          if (self.graphSettingsView) {
            self.graphSettingsView.remove();
          }
          self.graphSettingsView = new window.GraphSettingsView({
            name: self.name,
            userConfig: self.userConfig,
            saveCallback: self.render
          });
          self.graphSettingsView.render();

          if (callback) {
            callback(self.graphConfig);
          }
        }
      });
    },

    setStartNode: function (id) {
      this.graphConfig.nodeStart = id;
      this.graphSettingsView.saveGraphSettings(undefined, undefined, id);
    },

    editNode: function (id) {
      var callback = function () {};
      arangoHelper.openDocEditor(id, 'doc', callback);
    },

    editEdge: function (id) {
      var callback = function () {};
      arangoHelper.openDocEditor(id, 'edge', callback);
    },

    reloadGraph: function () {
      Backbone.history.loadUrl(Backbone.history.fragment);
    },

    getEdgeDefinitionCollections: function (fromCollection, toCollection) {
      var array = [];

      _.each(this.model.edgeDefinitions, function (edgeDefinition) {
        _.each(edgeDefinition.from, function (from) {
          if (from === fromCollection) {
            _.each(edgeDefinition.to, function (to) {
              if (to === toCollection) {
                array.push(edgeDefinition.collection);
              }
            });
          }
        });
      });

      return array;
    },

    initializeGraph: function (sigmaInstance, graph) {
      var self = this;
      // sigmaInstance.graph.read(graph);
      sigmaInstance.refresh();

      this.Sigma.plugins.Lasso = sigma.plugins.lasso;

      var lasso = new this.Sigma.plugins.Lasso(sigmaInstance, sigmaInstance.renderers[0], {
        'strokeStyle': 'black',
        'lineWidth': 1,
        'fillWhileDrawing': true,
        'fillStyle': 'rgba(41, 41, 41, 0.2)',
        'cursor': 'crosshair'
      });

      // Listen for selectedNodes event
      lasso.bind('selectedNodes', function (event) {
        // Do something with the selected nodes
        var nodes = event.data;

        if (nodes.length === 0) {
          self.selectedNodes = [];
        } else {
          _.each(nodes, function (val, key) {
            self.selectedNodes[key] = val.id;
          });
        }

        self.activeNodes = nodes;
        sigmaInstance.refresh();
      });

      return lasso;
    },

    renderGraph: function (graph, toFocus, aqlMode) {
      var self = this;

      this.graphSettings = graph.settings;

      if (graph.edges) {
        if (graph.nodes) {
          if (graph.nodes.length === 0 && graph.edges.length === 0) {
            graph.nodes.push({
              id: graph.settings.startVertex._id,
              label: graph.settings.startVertex._key,
              size: 10,
              color: '#2ecc71',
              x: Math.random(),
              y: Math.random()
            });
          }

          var style = 'position: absolute; left: 25px; bottom: 45px;';
          if (this.aqlMode) {
            style = 'position: absolute; left: 30px; margin-top: -37px;';
          }

          $(this.el).append(
            '
' +
              '' + graph.nodes.length + ' nodes' +
                '' + graph.edges.length + ' edges' +
                  '
'
          );
        }
      }
      this.Sigma = sigma;

      // defaults
      var algorithm = 'force';
      var renderer = 'canvas';

      if (this.graphConfig) {
        if (this.graphConfig.layout) {
          algorithm = this.graphConfig.layout;
        }

        if (this.graphConfig.renderer) {
          renderer = this.graphConfig.renderer;

          if (renderer === 'canvas') {
            self.isEditable = true;
          }
        }
      }

      // sigmajs graph settings
      var settings = {
        scalingMode: 'inside',
        borderSize: 3,
        defaultNodeBorderColor: '#8c8c8c',
        doubleClickEnabled: false,
        minNodeSize: 5,
        labelThreshold: 15,
        maxNodeSize: 15,
        batchEdgesDrawing: true,
        minEdgeSize: 10,
        maxEdgeSize: 20,
        enableEdgeHovering: true,
        edgeHoverColor: '#8c8c8c',
        defaultEdgeHoverColor: '#8c8c8c',
        defaultEdgeType: 'arrow',
        edgeHoverSizeRatio: 2,
        edgeHoverExtremities: true,
        nodesPowRatio: 0.5,
        // edgesPowRatio: 1.5,
        // lasso settings
        autoRescale: true,
        mouseEnabled: true,
        touchEnabled: true,
        font: 'Roboto'
      };

      // halo settings
      settings.nodeHaloColor = '#FF7A7A';
      settings.nodeHaloStroke = false;
      settings.nodeHaloStrokeColor = '#000';
      settings.nodeHaloStrokeWidth = 0.5;
      settings.nodeHaloSize = 15;
      settings.nodeHaloClustering = false;
      settings.nodeHaloClusteringMaxRadius = 1000;
      settings.edgeHaloColor = '#fff';
      settings.edgeHaloSize = 10;
      settings.drawHalo = true;

      if (renderer === 'canvas') {
        settings.autoCurveSortByDirection = true;
      }

      // adjust display settings for big graphs
      if (graph.nodes) {
        if (graph.nodes.length > 250) {
          settings.hideEdgesOnMove = true;
        }
      }

      if (this.graphConfig) {
        if (this.graphConfig.edgeType) {
          settings.defaultEdgeType = this.graphConfig.edgeType;

          if (this.graphConfig.edgeType === 'arrow') {
            settings.minArrowSize = 7;
          }
        }
      }

      if (aqlMode) {
        // aql editor settings
        renderer = 'webgl';

        if (graph.nodes.length < 500) {
          algorithm = 'fruchtermann';
        } else {
          settings.scalingMode = 'outside';
        }

        settings.drawEdgeLabels = false;
        settings.minNodeSize = 2;
        settings.maxNodeSize = 8;
      }

      // adjust display settings for webgl renderer
      if (renderer === 'webgl') {
        settings.enableEdgeHovering = false;
      }

      // create sigma graph
      var s = new this.Sigma({
        graph: graph,
        container: 'graph-container',
        renderer: {
          container: document.getElementById('graph-container'),
          type: renderer
        },
        settings: settings
      });
      this.currentGraph = s;

      if (!this.aqlMode) {
        sigma.plugins.fullScreen({
          container: 'graph-container',
          btnId: 'graph-fullscreen-btn'
        });
      }

      s.graph.nodes().forEach(function (n) {
        n.originalColor = n.color;
      });
      s.graph.edges().forEach(function (e) {
        e.originalColor = e.color;
      });

      if (algorithm === 'noverlap') {
        var noverlapListener = s.configNoverlap({
          nodeMargin: 0.1,
          scaleNodes: 1.05,
          gridSize: 75,
          easing: 'quadraticInOut', // animation transition function
          duration: 1500 // animation duration
        });

        noverlapListener.bind('start stop interpolate', function (e) {
          if (e.type === 'start') {
          }
          if (e.type === 'interpolate') {
          }
        });
      } else if (algorithm === 'fruchtermann') {
        var frListener = sigma.layouts.fruchtermanReingold.configure(s, {
          iterations: 100,
          easing: 'quadraticInOut',
          duration: 1500
        });

        frListener.bind('start stop interpolate', function (e) {});
      }

      // for canvas renderer allow graph editing
      if (!self.aqlMode) {
        var showAttributes = function (e, node) {
          $('.nodeInfoDiv').remove();

          if (self.contextState.createEdge === false) {
            if (window.location.hash.indexOf('graph') > -1) {
              var callback = function (error, data) {
                if (!error) {
                  var attributes = '';
                  attributes += 'ID ' + data._id + '';
                  if (Object.keys(data).length > 3) {
                    attributes += 'KEYS ';
                  }
                  _.each(data, function (value, key) {
                    if (key !== '_key' && key !== '_id' && key !== '_rev' && key !== '_from' && key !== '_to') {
                      attributes += '' + key + '';
                    }
                  });
                  var string = '
' + attributes + '
';

                  $(self.el).append(string);
                }
              };

              if (node) {
                self.documentStore.getDocument(e.data.node.id.split('/')[0], e.data.node.id.split('/')[1], callback);
              } else {
                self.documentStore.getDocument(e.data.edge.id.split('/')[0], e.data.edge.id.split('/')[1], callback);
              }
            }
          }
        };

        s.bind('rightClickStage', function (e) {
          self.addNodeX = e.data.captor.x;
          self.addNodeY = e.data.captor.y;
          self.createContextMenu(e);
          self.clearMouseCanvas();
        });

        s.bind('rightClickNode', function (e) {
          var nodeId = e.data.node.id;
          self.createNodeContextMenu(nodeId, e);
        });

        s.bind('clickNode', function (e) {
          if (self.contextState.createEdge === true) {
            // create the edge
            self.contextState._to = e.data.node.id;
            var fromCollection = self.contextState._from.split('/')[0];
            var toCollection = self.contextState._to.split('/')[0];

            // validate edgeDefinitions
            var foundEdgeDefinitions = self.getEdgeDefinitionCollections(fromCollection, toCollection);
            self.addEdgeModal(foundEdgeDefinitions, self.contextState._from, self.contextState._to);
          } else {
            if (!self.dragging) {
              // halo on active nodes:
              if (renderer === 'canvas') {
                self.currentGraph.renderers[0].halo({
                  nodes: self.currentGraph.graph.nodes(),
                  nodeHaloColor: '#DF0101',
                  nodeHaloSize: 100
                });
              }

              showAttributes(e, true);
              self.activeNodes = [e.data.node];

              if (renderer === 'canvas') {
                s.renderers[0].halo({
                  nodes: [e.data.node]
                });
              }
            }
          }
        });

        s.bind('clickStage', function () {
          self.clearOldContextMenu(true);
          self.clearMouseCanvas();
          s.renderers[0].halo({
            nodes: self.activeNodes
          });
        });
      }

      s.bind('doubleClickStage', function () {
        self.activeNodes = [];

        s.graph.nodes().forEach(function (n) {
          n.color = n.originalColor;
        });

        s.graph.edges().forEach(function (e) {
          e.color = e.originalColor;
        });

        $('.nodeInfoDiv').remove();
        s.refresh();
      });

      if (renderer === 'canvas') {
        // render parallel edges
        if (this.graphConfig) {
          if (this.graphConfig.edgeType === 'curve') {
            sigma.canvas.edges.autoCurve(s);
          }
        }

        s.bind('overNode', function (e) {
          if (self.contextState.createEdge === true) {
            self.newEdgeColor = '#ff0000';
          } else {
            self.newEdgeColor = '#000000';
          }
        });

        s.bind('clickEdge', function (e) {
          showAttributes(e, false);
        });

        s.bind('doubleClickNode', function (e) {
          var nodeId = e.data.node.id;
          var toKeep = s.graph.neighbors(nodeId);
          toKeep[nodeId] = e.data.node;

          s.graph.nodes().forEach(function (n) {
            if (toKeep[n.id]) {
              n.color = n.originalColor;
            } else {
              n.color = '#eee';
            }
          });

          s.graph.edges().forEach(function (e) {
            if (toKeep[e.source] && toKeep[e.target]) {
              e.color = 'rgb(64, 74, 83)';
            } else {
              e.color = '#eee';
            }
          });

          s.refresh();
        });
        s.renderers[0].bind('render', function (e) {
          s.renderers[0].halo({
            nodes: self.activeNodes
          });
        });

        if (!this.aqlMode) {
          s.bind('rightClickNode', function (e) {
            var nodeId = e.data.node.id;
            self.createNodeContextMenu(nodeId, e);
          });
        }

        if (this.graphConfig) {
          if (this.graphConfig.edgeEditable) {
            s.bind('rightClickEdge', function (e) {
              var edgeId = e.data.edge.id;
              self.createEdgeContextMenu(edgeId, e);
            });
          }
        }
      }

      // store in view
      self.algorithm = algorithm;

      // Initialize the dragNodes plugin:
      if (algorithm === 'noverlap') {
        s.startNoverlap();
        // allow draggin nodes
      } else if (algorithm === 'force') {
        // add buttons for start/stopping calculation
        var style2 = 'color: rgb(64, 74, 83); cursor: pointer; position: absolute; right: 30px; bottom: 40px;';

        if (self.aqlMode) {
          style2 = 'color: rgb(64, 74, 83); cursor: pointer; position: absolute; right: 30px; margin-top: -30px;';
        }

        $(this.el).append(
          '
' +
            ' Stop layout' +
          '
'
        );
        self.startLayout();

        // suggestion rendering time
        var duration = graph.nodes.length;

        if (aqlMode) {
          if (duration < 250) {
            duration = 250;
          }
        } else {
          if (duration <= 250) {
            duration = 500;
          }
        }

        window.setTimeout(function () {
          self.stopLayout();
        }, duration);
      } else if (algorithm === 'fruchtermann') {
        // Start the Fruchterman-Reingold algorithm:
        sigma.layouts.fruchtermanReingold.start(s);
      }
      var dragListener = sigma.plugins.dragNodes(s, s.renderers[0]);

      dragListener.bind('drag', function (event) {
        self.dragging = true;
      });
      dragListener.bind('drop', function (event) {
        window.setTimeout(function () {
          self.dragging = false;
        }, 400);
      });

      // add listener to keep track of cursor position
      var c = document.getElementsByClassName('sigma-mouse')[0];
      c.addEventListener('mousemove', self.trackCursorPosition.bind(this), false);

      // focus last input box if available
      if (toFocus) {
        $('#' + toFocus).focus();
        $('#graphSettingsContent').animate({
          scrollTop: $('#' + toFocus).offset().top
        }, 2000);
      }

      var enableLasso = function () {
        self.graphLasso = self.initializeGraph(s, graph);
        self.graphLasso.activate();
        self.graphLasso.deactivate();
      };

      // init graph lasso
      if (this.graphConfig) {
        if (this.graphConfig.renderer === 'canvas') {
          enableLasso();
        } else {
          $('#selectNodes').parent().hide();
        }
      } else {
        if (renderer === 'canvas') {
          enableLasso();
        } else {
          $('#selectNodes').parent().hide();
        }
      }

      if (self.graphLasso) {
        // add lasso event
        // Toggle lasso activation on Alt + l
        window.App.listenerFunctions['graphViewer'] = this.keyUpFunction.bind(this);
      }
      // clear up info div
      $('#calculatingGraph').fadeOut('slow');

      if (!aqlMode) {
        if (self.graphConfig) {
          if (self.graphConfig.nodeSizeByEdges === 'false') {
            // make nodes a bit bigger
            // var maxNodeSize = s.settings('maxNodeSize');
            // var factor = 1;
            // var length = s.graph.nodes().length;

            /*
            factor = 0.35;
            maxNodeSize = maxNodeSize * factor;
            s.settings('maxNodeSize', maxNodeSize);
            s.refresh({});
           */
          }
        }
      }

      self.calcFinished = new Date();
      // console.log('Client side calculation took ' + Math.abs(self.calcFinished.getTime() - self.calcStart.getTime()) + ' ms');
      if (graph.empty === true) {
        $('.sigma-background').before('The graph is empty. Please right-click to add a node.');
      }
    },

    keyUpFunction: function (event) {
      var self = this;
      switch (event.keyCode) {
        case 76:
          if (event.altKey) {
            self.toggleLasso();
          }
          break;
      }
    },

    toggleLayout: function () {
      if (this.layouting) {
        this.stopLayout();
      } else {
        this.startLayout();
      }
    },

    toggleLasso: function () {
      if (this.graphLasso.isActive) {
        // remove event
        var c = document.getElementsByClassName('sigma-lasso')[0];
        c.removeEventListener('mouseup', this.createNodesContextMenu.bind(this), false);

        $('#selectNodes').removeClass('activated');
        this.graphLasso.deactivate();

        // clear selected nodes state
        this.selectedNodes = {};
        this.activeNodes = [];
        this.currentGraph.refresh();
      } else {
        $('#selectNodes').addClass('activated');
        this.graphLasso.activate();

        // add event
        var x = document.getElementsByClassName('sigma-lasso')[0];
        x.addEventListener('mouseup', this.createNodesContextMenu.bind(this), false);
      }
    },

    startLayout: function (kill, origin) {
      var self = this;
      this.currentGraph.settings('drawLabels', false);
      this.currentGraph.settings('drawEdgeLabels', false);

      if (kill === true) {
        this.currentGraph.killForceAtlas2();

        window.setTimeout(function () {
          self.stopLayout();

          if (origin) {
            self.currentGraph.refresh();
            // self.cameraToNode(origin);
          }
        }, 500);
      }

      $('#toggleForce .fa').removeClass('fa-play').addClass('fa-pause');
      $('#toggleForce span').html('Stop layout');
      this.layouting = true;
      if (this.aqlMode) {
        this.currentGraph.startForceAtlas2({
          worker: true,
          edgeWeightInfluence: 2
        });
      } else {
        this.currentGraph.startForceAtlas2({
          worker: true
        });
      }
      // sigma.plugins.dragNodes(this.currentGraph, this.currentGraph.renderers[0]);
    },

    stopLayout: function () {
      $('#toggleForce .fa').removeClass('fa-pause').addClass('fa-play');
      $('#toggleForce span').html('Start layout');
      this.layouting = false;
      this.currentGraph.stopForceAtlas2();
      sigma.plugins.dragNodes(this.currentGraph, this.currentGraph.renderers[0]);
      this.currentGraph.settings('drawLabels', true);
      this.currentGraph.settings('drawEdgeLabels', true);
      this.currentGraph.refresh({ skipIndexation: true });
    }

  });
}());


text:
package store

import (
	"fmt"
)

import (
	"github.com/gorilla/sessions"
)

/* ================================================================================
 * redis store interface
 * qq group: 582452342
 * email   : 2091938785@qq.com
 * author  : 美丽的地球啊 - mliu
 * ================================================================================ */
type (
	IRedisStore interface {
		IStore
		Options(CookieOption)
	}

	RedisOption struct {
		Host     string
		Port     int
		Password string
		Prefix   string
		Db       int
	}

	redisStore struct {
		*RedisStoreImpl
	}
)

/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 * Session会话Cookie存储
 * ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
func NewRedisStore(ip string, port int, password, prefixKey string, encryptKey []byte, dbIndex int) IRedisStore {
	host := fmt.Sprintf("%s:%d", ip, port)
	redisStoreImpl, err := NewRedisStoreImpl("tcp", host, password, encryptKey, 10, dbIndex)
	if err != nil {
		panic(fmt.Sprintf("connect redis error: %v", err))
	}

	if len(prefixKey) > 0 {
		redisStoreImpl.SetPrefix(prefixKey)
	}

	return &redisStore{redisStoreImpl}
}

/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 * 设置Redis存储选项
 * ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
func (s *redisStore) Options(cookie CookieOption) {
	s.RedisStoreImpl.Options = &sessions.Options{
		Path:     cookie.Path,
		Domain:   cookie.Domain,
		MaxAge:   cookie.MaxAge,
		Secure:   cookie.IsSecure,
		HttpOnly: cookie.IsHttpOnly,
	}

	s.SetMaxAge(cookie.MaxAge)
}

redpajama_set_name: RedPajamaGithub


text:
#include "twoDDisplay.h"

using namespace nxtKitInterpreter::robotModel::twoD::parts;
using namespace kitBase::robotModel;

Display::Display(DeviceInfo const &info
		, PortInfo const &port
		, twoDModel::engine::TwoDModelEngineInterface &engine)
	: robotModel::parts::NxtDisplay(info, port)
	, mEngine(engine)
{
	mEngine.display()->setPainter(this);
}

void Display::drawPixel(int x, int y)
{
	mPoints << QPoint(x, y);
	mEngine.display()->repaintDisplay();
}

void Display::drawLine(int x1, int y1, int x2, int y2)
{
	mLines << QLine(x1, y1, x2, y2);
	mEngine.display()->repaintDisplay();
}

void Display::drawRect(int x, int y, int width, int height)
{
	mRects << QRect(x, y, width, height);
	mEngine.display()->repaintDisplay();
}

void Display::drawCircle(int x, int y, int radius)
{
	mCircles << QRect(x - radius, y - radius, 2 * radius, 2 * radius);
	mEngine.display()->repaintDisplay();
}

void Display::printText(int x, int y, QString const &text)
{
	mStringPlaces << QPoint(x, y);
	mStrings << text;
	mEngine.display()->repaintDisplay();
}

void Display::clearScreen()
{
	mPoints.clear();
	mLines.clear();
	mRects.clear();
	mCircles.clear();
	mStrings.clear();
	mStringPlaces.clear();
	mEngine.display()->repaintDisplay();
}

void Display::paint(QPainter *painter)
{
	/// @todo ZOMG.
	qreal const pixWidth = static_cast<qreal>(mEngine.display()->displayWidth()) / nxtDisplayWidth;
	qreal const pixHeight = static_cast<qreal>(mEngine.display()->displayHeight()) / nxtDisplayHeight;

	QPen pen;
	QFont font;
	font.setPixelSize(pixHeight * textPixelHeight);

	painter->setBrush(QBrush(Qt::black, Qt::SolidPattern));
	foreach (QPoint const &point, mPoints) {
		painter->drawRect(point.x() * pixWidth, point.y() * pixHeight, pixWidth, pixHeight);
	}

	pen.setWidth((pixWidth + pixHeight) / 2);
	painter->setPen(pen);
	painter->setBrush(QBrush(Qt::black, Qt::NoBrush));
	painter->setFont(font);

	foreach (QLine const &line, mLines) {
		painter->drawLine(line.x1() * pixWidth, line.y1() * pixHeight, line.x2() * pixWidth, line.y2() * pixHeight);
	}

	foreach (QRect const &circle, mCircles) {
		painter->drawEllipse(circle.x() * pixWidth, circle.y() * pixHeight, circle.width() * pixWidth, circle.height() * pixHeight);
	}

	foreach (QRect const &rect, mRects) {
		painter->drawRect(rect.x() * pixWidth, rect.y() * pixHeight, rect.width() * pixWidth, rect.height() * pixHeight);
	}

	QListIterator<QString> strings(mStrings);
	QListIterator<QPoint> strPlaces(mStringPlaces);
	while (strings.hasNext() && strPlaces.hasNext()) {
		QString const str = strings.next();
		QPoint const place = strPlaces.next();
		painter->drawText(place.x() * pixWidth * nxtDisplayWidth / textPixelWidth
				, place.y() * pixHeight * nxtDisplayHeight / textPixelHeight, str);
	}
}

void Display::clear()
{
	clearScreen();
}


text:
/**
 * Additional stylesheet for IE 8.
 * There is no LESS version of this. It's only function is to overwrite the normal styles.css with styles that make IE8 look not broken.
 * Images specially for this stylesheet will be placed in ./img/ie/
 */

/* Prevent ie-browser message from creating a vertical scrollbar */
html {
	overflow-y: hidden;
}

/* Remove sprites and replace with un-sprited graphics */

header #nav-logo {
	background: transparent url('../img/ie/banner.png') center 0 no-repeat;
}

#vendor-info .vendor-title h1:before {
	background: transparent url('../img/ie/truck-icon.png') no-repeat;
}

#vendor-info .vendor-entries .vendor-entry .vendor-image {
	background: transparent url('../img/ie/vendor-icon.png') no-repeat;
}

/* Remove custom list icons from popup menus */

#vendors ul, #calendar ul {
	list-style: square;
	margin-left: 20px;
}

#vendors li, #calendar li {
	background-image: none !important;
	padding-left: 0;
}

/* Hide pi - svg is not supported, and neither is GitHub */
#pi {
	display: none;
}

/* Typicons icon content requires single colon before selector */
.typcn-location-arrow-outline:before {
	content: '\e092';
	font-size: 18px;
	margin-left: 1px;
}

/* Hide leaflet attribution - not an ideal solution, but there is a display bug because :last-of-type selector doesn't work  */
.leaflet-container .leaflet-control-attribution {
	display: none;
}

/* Note: IE8 does not support media queries, so no need to fix responsive screen styles */


text:
<?xml version="1.0" encoding="UTF-8"?>

<!--
   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to You under the Apache License, Version 2.0
   (the "License"); you may not use this file except in compliance with
   the License.  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd ">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.apache.jackrabbit</groupId>
    <artifactId>oak-parent</artifactId>
    <version>1.45-SNAPSHOT</version>
    <relativePath>../oak-parent/pom.xml</relativePath>
  </parent>

  <artifactId>oak-core</artifactId>
  <name>Oak Core</name>
  <packaging>bundle</packaging>

  <properties>
    <!-- enable execution of jacoco and set minimal line coverage -->
    <skip.coverage>false</skip.coverage>
      <minimum.line.coverage>0.77</minimum.line.coverage>
      <minimum.branch.coverage>0.70</minimum.branch.coverage>
  </properties>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.felix</groupId>
        <artifactId>maven-bundle-plugin</artifactId>
        <configuration>
          <instructions>
            <Import-Package>
              <!-- OAK-7182 -->${guava.osgi.import},
              com.codahale.metrics*;version="[3.1, 4)";resolution:=optional,
              *
            </Import-Package>
            <Export-Package>
              org.apache.jackrabbit.oak,
              org.apache.jackrabbit.oak.namepath.impl,
              org.apache.jackrabbit.oak.plugins.commit,
              org.apache.jackrabbit.oak.plugins.identifier,
              org.apache.jackrabbit.oak.plugins.index,
              org.apache.jackrabbit.oak.plugins.index.aggregate,
              org.apache.jackrabbit.oak.plugins.index.cursor,
              org.apache.jackrabbit.oak.plugins.index.fulltext,
              org.apache.jackrabbit.oak.plugins.index.importer,
              org.apache.jackrabbit.oak.plugins.index.property,
              org.apache.jackrabbit.oak.plugins.index.property.strategy,
              org.apache.jackrabbit.oak.plugins.index.reference,
              org.apache.jackrabbit.oak.plugins.lock,
              org.apache.jackrabbit.oak.plugins.migration,
              org.apache.jackrabbit.oak.plugins.migration.report,
              org.apache.jackrabbit.oak.plugins.name,
              org.apache.jackrabbit.oak.plugins.nodetype,
              org.apache.jackrabbit.oak.plugins.nodetype.write,
              org.apache.jackrabbit.oak.plugins.observation,
              org.apache.jackrabbit.oak.plugins.observation.filter,
              org.apache.jackrabbit.oak.plugins.tree.factories,
              org.apache.jackrabbit.oak.plugins.version,
                org.apache.jackrabbit.oak.plugins.metric.util
            </Export-Package>
            <Jaas-ModuleClass>
              org.apache.jackrabbit.oak.spi.security.authentication.GuestLoginModule,
              org.apache.jackrabbit.oak.security.authentication.user.LoginModuleImpl,
              org.apache.jackrabbit.oak.security.authentication.token.TokenLoginModule
            </Jaas-ModuleClass>
            <DynamicImport-Package>
              org.apache.felix.jaas.boot
            </DynamicImport-Package>
          </instructions>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-failsafe-plugin</artifactId>
        <configuration>
          <systemPropertyVariables>
            <java.util.logging.config.file>
              src/test/resources/logging.properties
            </java.util.logging.config.file>
          </systemPropertyVariables>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.rat</groupId>
        <artifactId>apache-rat-plugin</artifactId>
        <configuration>
          <excludes>
            <exclude>**/test.json</exclude>
          </excludes>
        </configuration>
      </plugin>
        <plugin>
            <groupId>org.jacoco</groupId>
            <artifactId>jacoco-maven-plugin</artifactId>
            <executions>
                <execution>
                    <id>pre-unit-test</id>
                    <goals>
                        <goal>prepare-agent</goal>
                    </goals>
                    <configuration>
                        <skip>${skip.coverage}</skip>
                        <destFile>${project.build.directory}/coverage-reports/jacoco-ut.exec</destFile>
                        <propertyName>test.opts.coverage</propertyName>
                    </configuration>
                </execution>
                <execution>
                    <id>post-unit-test</id>
                    <phase>test</phase>
                    <goals>
                        <goal>report</goal>
                    </goals>
                    <configuration>
                        <skip>${skip.coverage}</skip>
                        <dataFile>${project.build.directory}/coverage-reports/jacoco-ut.exec</dataFile>
                        <outputDirectory>${project.reporting.outputDirectory}/jacoco-ut</outputDirectory>
                    </configuration>
                </execution>
                <execution>
                    <id>default-check</id>
                    <goals>
                        <goal>check</goal>
                    </goals>
                    <configuration>
                        <dataFile>${project.build.directory}/coverage-reports/jacoco-ut.exec</dataFile>
                        <rules>
                            <rule>
                                <element>BUNDLE</element>
                                <limits>
                                    <limit>
                                        <counter>LINE</counter>
                                        <value>COVEREDRATIO</value>
                                        <minimum>${minimum.line.coverage}</minimum>
                                    </limit>
                                    <limit>
                                        <counter>BRANCH</counter>
                                        <value>COVEREDRATIO</value>
                                        <minimum>${minimum.branch.coverage}</minimum>
                                    </limit>
                                </limits>
                            </rule>
                            <rule>
                                <element>PACKAGE</element>
                                <includes>
                                    <include>org.apache.jackrabbit.oak.security.authentication</include>
                                    <include>org.apache.jackrabbit.oak.security.authentication.monitor</include>
                                    <include>org.apache.jackrabbit.oak.security.authentication.user</include>
                                    <include>org.apache.jackrabbit.oak.security.authorization</include>
                                    <include>org.apache.jackrabbit.oak.security.authorization.monitor</include>
                                    <include>org.apache.jackrabbit.oak.security.internal</include>
                                    <include>org.apache.jackrabbit.oak.security.principal</include>
                                    <include>org.apache.jackrabbit.oak.security.privilege</include>
                                    <include>org.apache.jackrabbit.oak.security.user.autosave</include>
                                    <include>org.apache.jackrabbit.oak.security.user.monitor</include>
                                    <include>org.apache.jackrabbit.oak.security.user.query</include>
                                    <include>org.apache.jackrabbit.oak.security.user.whiteboard</include>
                                </includes>
                                <excludes>
                                    <exclude>*Test</exclude>
                                </excludes>
                                <limits>
                                    <limit>
                                        <counter>BRANCH</counter>
                                        <value>COVEREDRATIO</value>
                                        <minimum>1.0</minimum>
                                    </limit>
                                </limits>
                            </rule>
                            <rule>
                                <element>PACKAGE</element>
                                <includes>
                                    <include>org.apache.jackrabbit.oak.security.authentication.token</include>
                                    <include>org.apache.jackrabbit.oak.security.authorization.accesscontrol</include>
                                    <include>org.apache.jackrabbit.oak.security.authorization.composite</include>
                                    <include>org.apache.jackrabbit.oak.security.authorization.permission</include>
                                    <include>org.apache.jackrabbit.oak.security.authorization.restriction</include>
                                    <include>org.apache.jackrabbit.oak.security.user</include>
                                </includes>
                                <excludes>
                                    <exclude>*Test</exclude>
                                </excludes>
                                <limits>
                                    <limit>
                                        <counter>BRANCH</counter>
                                        <value>COVEREDRATIO</value>
                                        <minimum>0.99</minimum>
                                    </limit>
                                </limits>
                            </rule>
                        </rules>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
  </build>

  <dependencies>
    <!-- Optional OSGi dependencies, used only when running within OSGi -->
    <dependency>
      <groupId>org.osgi</groupId>
      <artifactId>org.osgi.core</artifactId>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.osgi</groupId>
      <artifactId>org.osgi.compendium</artifactId>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.osgi</groupId>
      <artifactId>org.osgi.annotation</artifactId>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.osgi</groupId>
      <artifactId>org.osgi.service.component.annotations</artifactId>
    </dependency>
    <dependency>
      <groupId>org.osgi</groupId>
      <artifactId>org.osgi.service.metatype.annotations</artifactId>
   </dependency>

    <!-- Dependencies to other Oak components -->
    <dependency>
      <groupId>org.apache.jackrabbit</groupId>
      <artifactId>oak-jackrabbit-api</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.jackrabbit</groupId>
      <artifactId>oak-api</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.jackrabbit</groupId>
      <artifactId>oak-core-spi</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.jackrabbit</groupId>
      <artifactId>oak-query-spi</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.jackrabbit</groupId>
      <artifactId>oak-security-spi</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.jackrabbit</groupId>
      <artifactId>oak-commons</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.jackrabbit</groupId>
      <artifactId>oak-commons</artifactId>
      <version>${project.version}</version>
      <type>test-jar</type>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.jackrabbit</groupId>
      <artifactId>oak-blob-plugins</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.jackrabbit</groupId>
      <artifactId>oak-store-spi</artifactId>
      <version>${project.version}</version>
    </dependency>
    <!-- General utility libraries -->
    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
    </dependency>
    <dependency>
      <groupId>io.dropwizard.metrics</groupId>
      <artifactId>metrics-core</artifactId>
      <optional>true</optional>
    </dependency>

    <!-- JCR and Jackrabbit dependencies -->
    <dependency>
      <groupId>javax.jcr</groupId>
      <artifactId>jcr</artifactId>
      <version>2.0</version>
    </dependency>
    <dependency>
      <groupId>org.apache.jackrabbit</groupId>
      <artifactId>jackrabbit-jcr-commons</artifactId>
      <version>${jackrabbit.version}</version>
    </dependency>

    <!-- Logging -->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
    </dependency>

    <dependency>
      <groupId>org.apache.felix</groupId>
      <artifactId>org.apache.felix.inventory</artifactId>
      <version>1.0.4</version>
      <optional>true</optional>
    </dependency>

    <!-- Nullability annotations -->
    <dependency>
      <groupId>org.jetbrains</groupId>
      <artifactId>annotations</artifactId>
    </dependency>

    <!-- Test Dependencies -->
    <dependency>
      <groupId>org.hamcrest</groupId>
      <artifactId>hamcrest-all</artifactId>
      <version>1.3</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-core</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.easymock</groupId>
      <artifactId>easymock</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>jul-to-slf4j</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-classic</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.jackrabbit</groupId>
      <artifactId>oak-blob-plugins</artifactId>
      <version>${project.version}</version>
      <classifier>tests</classifier>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.sling</groupId>
      <artifactId>org.apache.sling.testing.osgi-mock</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.googlecode.json-simple</groupId>
      <artifactId>json-simple</artifactId>
      <version>1.1.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>


text:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:orientation="vertical">
    <LinearLayout android:layout_height="wrap_content"
                  android:layout_width="fill_parent"
                  android:padding="7dip"
                  android:paddingLeft="2dip"
                  android:orientation="vertical">
    <TextView android:id="@+id/jconnect.droid.viewfeedback.contents"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="@style/jconnect.droid.style.main_font" />
    <TextView android:id="@+id/jconnect.droid.viewfeedback.date"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="@style/jconnect.droid.style.secondary_font" />
    </LinearLayout>
    <LinearLayout android:layout_height="wrap_content"
                  android:layout_width="match_parent"
                  style="@style/jconnect.droid.style.padded_divider_container">
        <View style="@style/jconnect.droid.style.light_divider" />
    </LinearLayout>

</LinearLayout>


text:
package org.apache.isis.viewer.restfulobjects.server.mappers;

import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;

import org.jmock.auto.Mock;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;

import org.apache.isis.core.unittestsupport.jmocking.JUnitRuleMockery2;
import org.apache.isis.viewer.restfulobjects.applib.JsonRepresentation;
import org.apache.isis.viewer.restfulobjects.applib.client.RestfulResponse.HttpStatusCode;
import org.apache.isis.viewer.restfulobjects.applib.util.JsonMapper;
import org.apache.isis.viewer.restfulobjects.rendering.RestfulObjectsApplicationException;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat;

public class RestfulObjectsApplicationExceptionMapperTest {

    private ExceptionMapperForRestfulObjectsApplication exceptionMapper;

    @Rule
    public JUnitRuleMockery2 context = JUnitRuleMockery2.createFor(JUnitRuleMockery2.Mode.INTERFACES_AND_CLASSES);

    @Mock
    HttpHeaders mockHttpHeaders = context.mock(HttpHeaders.class);

    @Before
    public void setUp() throws Exception {
        exceptionMapper = new ExceptionMapperForRestfulObjectsApplication();
        exceptionMapper.httpHeaders = mockHttpHeaders;
    }

    @Test
    public void simpleNoMessage() throws Exception {

        // given
        context.allowing(mockHttpHeaders);

        final HttpStatusCode status = HttpStatusCode.BAD_REQUEST;
        final RestfulObjectsApplicationException ex = RestfulObjectsApplicationException.create(status);

        // when
        final Response response = exceptionMapper.toResponse(ex);

        // then
        assertThat(HttpStatusCode.lookup(response.getStatus()), is(status));
        assertThat(response.getMetadata().get("Warning"), is(nullValue()));

        // and then
        final String entity = (String) response.getEntity();
        assertThat(entity, is(not(nullValue())));
    }

    @Test
    public void entity_withMessage() throws Exception {

        // givens
        context.allowing(mockHttpHeaders);
        final RestfulObjectsApplicationException ex = RestfulObjectsApplicationException.createWithMessage(HttpStatusCode.BAD_REQUEST, "foobar");

        // when
        final Response response = exceptionMapper.toResponse(ex);

        // then
        assertThat((String) response.getMetadata().get("Warning").get(0), is("199 RestfulObjects " + ex.getMessage()));

        // and then
        final String entity = (String) response.getEntity();
        assertThat(entity, is(not(nullValue())));
    }

    @Test
    public void entity_forException() throws Exception {

        // given
        context.allowing(mockHttpHeaders);
        final Exception exception = new Exception("barfoo");
        final RestfulObjectsApplicationException ex = RestfulObjectsApplicationException.createWithCauseAndMessage(HttpStatusCode.BAD_REQUEST, exception, "foobar");

        // when
        final Response response = exceptionMapper.toResponse(ex);
        final String entity = (String) response.getEntity();
        assertThat(entity, is(not(nullValue())));
        final JsonRepresentation jsonRepr = JsonMapper.instance().read(entity, JsonRepresentation.class);

        // then
        assertThat((String) response.getMetadata().get("Warning").get(0), is("199 RestfulObjects foobar"));
        assertThat(jsonRepr.getString("message"), is("foobar"));
        final JsonRepresentation causedByRepr = jsonRepr.getRepresentation("causedBy");
        assertThat(causedByRepr, is(nullValue()));
    }

    @Test
    public void entity_forExceptionWithCause() throws Exception {

        // given
        context.allowing(mockHttpHeaders);
        final Exception rootCause = new Exception("bozfoz");
        final Exception cause = new Exception("barfoo", rootCause);
        final RestfulObjectsApplicationException ex = RestfulObjectsApplicationException.createWithCauseAndMessage(HttpStatusCode.BAD_REQUEST, cause, "foobar");

        // when
        final Response response = exceptionMapper.toResponse(ex);
        final String entity = (String) response.getEntity();
        assertThat(entity, is(not(nullValue())));
        final JsonRepresentation jsonRepr = JsonMapper.instance().read(entity, JsonRepresentation.class);

        // then
        assertThat((String) response.getMetadata().get("Warning").get(0), is("199 RestfulObjects foobar"));
        assertThat(jsonRepr.getString("message"), is("foobar"));
        final JsonRepresentation detail = jsonRepr.getRepresentation("detail");
        assertThat(detail, is(not(nullValue())));
        assertThat(detail.getString("message"), is("foobar"));
        final JsonRepresentation causedBy = detail.getRepresentation("causedBy");
        assertThat(causedBy, is(not(nullValue())));
        assertThat(causedBy.getString("message"), is(cause.getMessage()));
    }

}


text:
'use strict';
// import "babel-polyfill";
// $ cd es6

console.log(`\nEXAMPLE ONE: Protecting Objects: Freezing	************************************\n`);

// Freezing prevents any changes to an object (makes it immutable)
// You can not: add new props, delete, change props, define new properties

const appInfo = {

    company: 'White Knight Software, Inc.',
    version: '1.3.5',
    buildId: '0a995448-ead4-4a8b-b050-9c9083279ea2',
    // this function only accesses properties, so it won't be // affected by freezing
    copyright() {

        return `© ${new Date().getFullYear()}, ${this.company}`;

    },

};

Object.freeze(appInfo);
console.log(`IsFrozen :: ${Object.isFrozen(appInfo)}`); // true

console.log(`\nEXAMPLE TWO: Protecting Objects: Sealing  ************************************\n`);

// Sealing an object prevents the addition of new properties,
// or the reconfiguration or removal of existing properties
// You can not add new props, delete props, define properties.

class Logger {

    constructor(name) {

        this.name = name;
        this.log = [];

    }
    add(entry) {

        this.log.push({

            log: entry,
            timestamp: Date.now(),

        });
    }
}

const log = new Logger("Captain's Log");
Object.seal(log);

console.log(`isSealed :: ${Object.isSealed(log)}`); // isSealed :: true

log.name = "Captain's Boring Log";
log.add("Another boring day at sea....");
log.name = 'test';

console.log(`name :: ${log.name} \t log :: ${JSON.stringify(log.log)}`); // isSealed :: true

// name :: test      log :: [{"log":"Another boring day at sea....","timestamp":1467241003468}]

console.log(`\nEXAMPLE THREE: Protecting Objects: preventExtensions  ************************************\n`);

// You can not add new props.

const log2 = new Logger("First Mate's Log");
Object.preventExtensions(log2);

console.log(`isExtensible :: ${Object.isExtensible(log2)}`); // isExtensible :: false

log2.name = "First Mate's Boring Log";
log2.add("Another boring day at sea....");

log2.name = 'test';
delete log2.name;

// now you can not add name, it has been removed and object is not Extensible

Object.defineProperty(log2, 'log', { enumerable: false });

console.log(`name :: ${log2.name} \t log :: ${JSON.stringify(log2.log)}`);

// name :: undefined     log :: [{"log":"Another boring day at sea....","timestamp":1467241547733}]


text:
chrome.test.runTests([
  function saveFile() {
    chrome.fileSystem.chooseFile({type: 'saveFile'}, chrome.test.callbackFail(
        'User cancelled', function(entry) {}));
  }
]);


text:
package org.mustbe.consulo.unity3d.module;

import org.mustbe.consulo.RequiredReadAction;
import com.intellij.ide.macro.Macro;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.project.Project;

/**
 * @author VISTALL
 * @since 17.11.14
 */
public class UnityFileNameMacro extends Macro
{
	@Override
	public String getName()
	{
		return "UnityFileName";
	}

	@Override
	public String getDescription()
	{
		return "Unity File Name";
	}

	@Override
	@RequiredReadAction
	public String expand(DataContext dataContext)
	{
		final Project project = LangDataKeys.PROJECT.getData(dataContext);
		if(project == null)
		{
			return null;
		}
		Unity3dRootModuleExtension rootModuleExtension = Unity3dModuleExtensionUtil.getRootModuleExtension(project);
		if(rootModuleExtension != null)
		{
			return rootModuleExtension.getFileName();
		}
		return null;
	}
}


text:
from django.shortcuts import redirect
from django.template.response import TemplateResponse

from ..utils import (
    get_checkout_context, get_taxes_for_checkout,
    update_shipping_address_in_anonymous_checkout,
    update_shipping_address_in_checkout)

def anonymous_user_shipping_address_view(request, checkout):
    """Display the shipping step for a user who is not logged in."""
    user_form, address_form, updated = (
        update_shipping_address_in_anonymous_checkout(
            checkout, request.POST or None, request.country))

    if updated:
        return redirect('checkout:shipping-method')

    taxes = get_taxes_for_checkout(checkout, request.taxes)
    ctx = get_checkout_context(checkout, request.discounts, taxes)
    ctx.update({
        'address_form': address_form,
        'user_form': user_form})
    return TemplateResponse(request, 'checkout/shipping_address.html', ctx)

def user_shipping_address_view(request, checkout):
    """Display the shipping step for a logged in user.

    In addition to entering a new address the user has an option of selecting
    one of the existing entries from their address book.
    """
    checkout.email = request.user.email
    checkout.save(update_fields=['email'])
    user_addresses = checkout.user.addresses.all()

    addresses_form, address_form, updated = update_shipping_address_in_checkout(
        checkout, user_addresses, request.POST or None, request.country)

    if updated:
        return redirect('checkout:shipping-method')

    taxes = get_taxes_for_checkout(checkout, request.taxes)
    ctx = get_checkout_context(checkout, request.discounts, taxes)
    ctx.update({
        'additional_addresses': user_addresses,
        'address_form': address_form,
        'user_form': addresses_form})
    return TemplateResponse(request, 'checkout/shipping_address.html', ctx)


text:
(function() {
    "use strict";
    window.Suricate = window.Suricate || {};

    Suricate.WidgetsContainer = function(container) {
        this.container = container;
    };

    /*
     * Public
     */

    // Is widget present on the page ?
    Suricate.WidgetsContainer.prototype.isWidgetPresent = function(id) {
        return this.getWidgetContainer(id).length > 0;
    };

    // Get the DOM element associated to widget with id
    Suricate.WidgetsContainer.prototype.getWidgetContainer = function(id) {
        return this.container.find("[data-widget-id='" + id + "']");
    };
}());


text:
package org.tendiwa.inflectible;

import com.google.common.collect.ImmutableMap;
import java.util.Map;
import java.util.stream.Collectors;
import org.tenidwa.collections.utils.Rethrowing;

/**
 * {@link Templatuary} defined by a map from template identifiers to templates.
 * @author Georgy Vlasov (suseika@tendiwa.org)
 * @version $Id$
 * @since 0.1.0
 */
public final class BasicTemplatuary implements Templatuary {
    /**
     * Map from template identifiers to templates.
     */
    private final transient ImmutableMap<TemplateName, Template> templates;

    /**
     * Ctor.
     * @param map Map from template identifiers to templates.
     */
    public BasicTemplatuary(final ImmutableMap<TemplateName, Template> map) {
        this.templates = map;
    }

    @Override
    public Template template(final TemplateName name) throws Exception {
        final Template template = this.templates.get(name);
        if (template == null) {
            throw new MissingTemplateException(name);
        }
        return template;
    }

    @Override
    public boolean hasTemplate(final TemplateName name) throws Exception {
        return this.stringMap().containsKey(name.string());
    }

    // To be refactored in #47
    /**
     * Cretes map from string template names to their templates.
     * @return Map from string template names to their templates
     * @throws Exception If could not create the map
     */
    private Map<String, Template> stringMap() throws Exception {
        return this.templates
            .keySet()
            .stream()
            .collect(
                Collectors.toMap(
                    Rethrowing.rethrowFunction(TemplateName::string),
                    this.templates::get
                )
            );
    }
}