text:
(function(root, factory) {
  /* ======= Global Moon ======= */
  (typeof module === "object" && module.exports) ? module.exports = factory() : root.Moon = factory();
}(this, function() {
    "use strict";

    /* ======= Global Variables ======= */

    var directives = {};
    var specialDirectives = {};
    var components = {};
    var eventModifiersCode = {
      stop: 'event.stopPropagation();',
      prevent: 'event.preventDefault();',
      ctrl: 'if(!event.ctrlKey) {return;};',
      shift: 'if(!event.shiftKey) {return;};',
      alt: 'if(!event.altKey) {return;};',
      enter: 'if(event.keyCode !== 13) {return;};'
    };
    var id = 0;

    /* ======= Observer ======= */
    /**
     * Makes Computed Properties for an Instance
     * @param {Object} instance
     * @param {Object} computed
     */
    var initComputed = function (instance, computed) {
      var setComputedProperty = function (prop) {
        // Add to Observer Cache
        instance.$observer.cache[prop] = {
          dirty: true,
          getter: computed[prop].get,
          cache: null
        };

        // Create Getters/Setters
        var properties = {
          get: function () {
            return instance.$observer.getComputed(prop);
          }
        };
        if (computed[prop].set) {
          properties.set = function (val) {
            return computed[prop].set.call(instance, val);
          };
        }

        // Add Getters/Setters
        Object.defineProperty(instance.$data, prop, properties);
      };

      // Set All Computed Properties
      for (var propName in computed) {
        setComputedProperty(propName);
      }
    };

    function Observer(instance) {
      this.instance = instance;
      this.cache = {};
    }

    Observer.prototype.getComputed = function (prop) {
      // Check if Changed ("dirty")
      if (this.cache[prop].dirty) {
        // Invoke Getter
        var output = this.cache[prop].getter.call(this.instance);

        // Cache Output
        this.cache[prop].cache = output;

        // Return Output
        return output;
      } else {
        // Clean, return Cached Value
        return this.cache[prop].cache;
      }
    };

    Observer.prototype.notify = function () {
      queueBuild(this.instance);
    };

    /* ======= Global Utilities ======= */

    /**
     * Logs a Message
     * @param {String} msg
     */
    var log = function (msg) {
      if (!Moon.config.silent) console.log(msg);
    };

    /**
     * Throws an Error
     * @param {String} msg
     */
    var error = function (msg) {
      console.error("[Moon] ERR: " + msg);
    };

    /**
     * Adds DOM Updates to Queue
     * @param {Object} instance
     */
    var queueBuild = function (instance) {
      if (!instance.$queued && !instance.$destroyed) {
        instance.$queued = true;
        setTimeout(function () {
          instance.build();
          callHook(instance, 'updated');
          instance.$queued = false;
        }, 0);
      }
    };

    /**
     * Converts attributes into key-value pairs
     * @param {Node} node
     * @return {Object} Key-Value pairs of Attributes
     */
    var extractAttrs = function (node) {
      var attrs = {};
      for (var rawAttrs = node.attributes, i = rawAttrs.length; i--;) {
        attrs[rawAttrs[i].name] = rawAttrs[i].value;
      }
      node.__moon__props__ = attrs;
      return attrs;
    };

    /**
     * Gives Default Metadata for a VNode
     * @return {Object} metadata
     */
    var defaultMetadata = function () {
      return {
        shouldRender: true,
        eventListeners: {}
      };
    };

    /**
     * Escapes a String
     * @param {String} str
     */
    var escapeString = function (str) {
      var NEWLINE_RE = /\n/g;
      var DOUBLE_QUOTE_RE = /"/g;
      var BACKSLASH_RE = /\\/g;
      return str.replace(BACKSLASH_RE, "\\\\").replace(DOUBLE_QUOTE_RE, "\\\"").replace(NEWLINE_RE, "\\n");
    };

    /**
     * Resolves an Object Keypath and Sets it
     * @param {Object} instance
     * @param {Object} obj
     * @param {String} keypath
     * @param {String} val
     * @return {Object} resolved object
     */
    var resolveKeyPath = function (instance, obj, keypath, val) {
      var i;
      keypath.replace(/\[(\w+)\]/g, function (match, index) {
        keypath = keypath.replace(match, '.' + index);
      });
      var path = keypath.split(".");
      for (i = 0; i < path.length - 1; i++) {
        var propName = path[i];
        obj = obj[propName];
      }
      obj[path[i]] = val;
      return obj;
    };

    /**
     * Compiles a Template
     * @param {String} template
     * @param {Boolean} isString
     * @return {String} compiled template
     */
    var compileTemplate = function (template, isString) {
      var TEMPLATE_RE = /{{([A-Za-z0-9_$@]+)([A-Za-z0-9_.()'"+\-*/\s\[\]]+)?}}/gi;
      var compiled = template;
      template.replace(TEMPLATE_RE, function (match, key, modifiers) {
        if (!modifiers) {
          modifiers = '';
        }
        if (isString) {
          compiled = compiled.replace(match, '" + instance.get("' + key + '")' + modifiers + ' + "');
        } else {
          compiled = compiled.replace(match, 'instance.get("' + key + '")' + modifiers);
        }
      });
      return compiled;
    };

    /**
     * Extracts the Slots From Component Children
     * @param {Array} children
     * @return {Object} extracted slots
     */
    var getSlots = function (children) {
      var slots = {};

      // No Children Means No Slots
      if (!children) {
        return slots;
      }

      var defaultSlotName = "default";
      slots[defaultSlotName] = [];

      for (var i = 0; i < children.length; i++) {
        var child = children[i];
        var childProps = child.props.attrs;
        if (childProps.slot) {
          if (!slots[childProps.slot]) {
            slots[childProps.slot] = [child];
          } else {
            slots[childProps.slot].push(child);
          }
          delete childProps.slot;
        } else {
          slots[defaultSlotName].push(child);
        }
      }

      return slots;
    };

    /**
     * Creates a Virtual DOM Node
     * @param {String} type
     * @param {String} val
     * @param {Object} props
     * @param {Array} children
     * @param {Object} meta
     * @return {Object} Virtual DOM Node
     */
    var createElement = function (type, val, props, children, meta) {
      return {
        type: type,
        val: val,
        props: props,
        children: children,
        meta: meta || defaultMetadata()
      };
    };

    /**
     * Creates a Functional Component
     * @param {String} type
     * @param {Object} props
     * @param {Object} meta
     * @param {Array} children
     * @param {Object} functionalComponent
     * @return {Object} Virtual DOM Node
     */
    var createFunctionalComponent = function (type, props, meta, children, functionalComponent) {
      var data = functionalComponent.opts.data || {};
      // Merge data with provided props
      if (functionalComponent.opts.props) {
        for (var i = 0; i < functionalComponent.opts.props.length; i++) {
          var prop = functionalComponent.opts.props[i];
          data[prop] = props.attrs[prop];
        }
      }
      return functionalComponent.opts.render(h, {
        data: data,
        slots: getSlots(children)
      });
    };

    /**
     * Compiles Arguments to a VNode
     * @param {String} tag
     * @param {Object} attrs
     * @param {Object} meta
     * @param {...Object|String} children
     * @return {String} Object usable in Virtual DOM (VNode)
     */
    var h = function (tag, attrs, meta) {
      // Setup Children
      var children = [];
      var childrenLen = arguments.length - 3;
      for (var i = 0; i < childrenLen; i++) {
        var child = arguments[i + 3];
        if (Array.isArray(child)) {
          children = children.concat(child);
        } else if (typeof child === "string" || child === null) {
          children.push(createElement("#text", child || "", { attrs: {} }, [], defaultMetadata()));
        } else {
          children.push(child);
        }
      }
      // It's a Component
      if (components[tag]) {
        // Functional component
        if (components[tag].opts.functional) {
          return createFunctionalComponent(tag, attrs, meta, children, components[tag]);
        } else {
          // Provide the instance to diff engine
          meta.component = components[tag];
        }
      }

      // In the end, we have a VNode structure like:
      // {
      //  type: 'h1', <= nodename
      //  props: {
      //    attrs: {id: 'someId'}, <= regular attributes
      //    dom: {textContent: 'some text content'} <= only for DOM properties added by directives
      //  },
      //  meta: {}, <= metadata used internally
      //  children: [], <= any child nodes or text
      // }

      return createElement(tag, "", attrs, children, meta);
    };

    /**
     * Adds metadata Event Listeners to an Element
     * @param {Object} node
     * @param {Object} vnode
     * @param {Object} instance
     */
    var addEventListeners = function (node, vnode, instance) {
      var eventListeners = vnode.meta.eventListeners;
      for (var type in eventListeners) {
        for (var i = 0; i < eventListeners[type].length; i++) {
          var method = eventListeners[type][i];
          node.addEventListener(type, method);
        }
      }
    };

    /**
     * Creates DOM Node from VNode
     * @param {Object} vnode
     * @param {Object} instance
     * @return {Object} DOM Node
     */
    var createNodeFromVNode = function (vnode, instance) {
      var el;

      if (vnode.type === "#text") {
        // Create textnode
        el = document.createTextNode(vnode.val);
      } else {
        el = vnode.meta.isSVG ? document.createElementNS('http://www.w3.org/2000/svg', vnode.type) : document.createElement(vnode.type);
        // Optimization: VNode only has one child that is text, and create it here
        if (vnode.children.length === 1 && vnode.children[0].type === "#text") {
          el.textContent = vnode.children[0].val;
        } else {
          // Add all children
          for (var i = 0; i < vnode.children.length; i++) {
            var childVNode = vnode.children[i];
            var childNode = createNodeFromVNode(vnode.children[i], instance);
            el.appendChild(childNode);
            // Component detected, mount it here
            if (childVNode.meta.component) {
              createComponentFromVNode(childNode, childVNode, childVNode.meta.component);
            }
          }
        }
        // Add all event listeners
        addEventListeners(el, vnode, instance);
      }
      // Setup Props (With Cache)
      el.__moon__props__ = extend({}, vnode.props.attrs);
      diffProps(el, {}, vnode, vnode.props.attrs);

      // Setup Cached NodeName
      el.__moon__nodeName__ = vnode.type;
      return el;
    };

    /**
     * Mounts a Component To The DOM
     * @param {Object} node
     * @param {Object} vnode
     * @param {Object} component
     * @return {Object} DOM Node
     */
    var createComponentFromVNode = function (node, vnode, component) {
      var componentInstance = new component.CTor();
      // Merge data with provided props
      for (var i = 0; i < componentInstance.$props.length; i++) {
        var prop = componentInstance.$props[i];
        componentInstance.$data[prop] = vnode.props.attrs[prop];
      }
      componentInstance.$slots = getSlots(vnode.children);
      componentInstance.$el = node;
      componentInstance.build();
      callHook(componentInstance, 'mounted');
      return componentInstance.$el;
    };

    /**
     * Diffs Props of Node and a VNode, and apply Changes
     * @param {Object} node
     * @param {Object} nodeProps
     * @param {Object} vnode
     * @param {Object} vnodeProps
     */
    var diffProps = function (node, nodeProps, vnode, vnodeProps) {
      // Get object of all properties being compared
      var allProps = merge(nodeProps, vnodeProps);

      // If node is svg, update with SVG namespace
      var isSVG = node instanceof SVGElement;

      for (var propName in allProps) {
        // If not in VNode or is a Directive, remove it
        if (!vnodeProps.hasOwnProperty(propName) || directives[propName]) {
          // If it is a directive, run the directive
          if (directives[propName]) {
            directives[propName](node, allProps[propName], vnode);
          }
          isSVG ? node.removeAttributeNS(null, propName) : node.removeAttribute(propName);
          delete node.__moon__props__[propName];
        } else if (!nodeProps[propName] || nodeProps[propName] !== vnodeProps[propName]) {
          // It has changed or is not in the node in the first place
          isSVG ? node.setAttributeNS(null, propName, vnodeProps[propName]) : node.setAttribute(propName, vnodeProps[propName]);
          node.__moon__props__[propName] = vnodeProps[propName];
        }
      }

      if (vnode.props.dom) {
        for (var domProp in vnode.props.dom) {
          var domPropValue = vnode.props.dom[domProp];
          if (node[domProp] !== vnode.props.dom[domProp]) {
            node[domProp] = vnode.props.dom[domProp];
          }
        }
      }
    };

    /**
     * Diffs Node and a VNode, and applies Changes
     * @param {Object} node
     * @param {Object} vnode
     * @param {Object} parent
     * @param {Object} instance
     * @return {Object} adjusted node only if it was replaced
     */
    var diff = function (node, vnode, parent, instance) {
      var nodeName;

      if (node) {
        nodeName = node.__moon__nodeName__ || node.nodeName.toLowerCase();
      }

      if (!node && vnode) {
        // No Node, create a node
        var newNode = createNodeFromVNode(vnode, instance);
        parent.appendChild(newNode);
        if (vnode.meta.component) {
          // Detected parent component, build it here (parent node is available)
          createComponentFromVNode(newNode, vnode, vnode.meta.component);
        }
        return newNode;
      } else if (!vnode) {
        // No vnode, remove the node
        parent.removeChild(node);
        if (node.__moon__) {
          // Component was unmounted, destroy it here
          node.__moon__.destroy();
        }
        return null;
      } else if (nodeName !== vnode.type) {
        // Different types, replace it
        var newNode = createNodeFromVNode(vnode, instance);
        parent.replaceChild(newNode, node);
        if (node.__moon__) {
          // Component was unmounted, destroy it here
          node.__moon__.destroy();
        }
        if (vnode.meta.component) {
          // Detected parent component, build it here (parent node is available)
          createComponentFromVNode(newNode, vnode, vnode.meta.component);
        }
        return newNode;
      } else if (vnode.meta.shouldRender && vnode.type === "#text" && nodeName === "#text" && vnode.val !== node.textContent) {
        // Both are textnodes, update the node
        node.textContent = vnode.val;
        return node;
      } else if (vnode && vnode.type !== "#text" && vnode.meta.shouldRender) {

        if (vnode.meta.component) {
          if (!node.__moon__) {
            // Not mounted, create a new instance and mount it here
            createComponentFromVNode(node, vnode, vnode.meta.component);
          } else {
            // Mounted already, need to update
            var componentInstance = node.__moon__;
            var componentChanged = false;
            // Merge any properties that changed
            for (var prop in vnode.props.attrs) {
              if (componentInstance.$data[prop] !== vnode.props.attrs[prop]) {
                componentInstance.$data[prop] = vnode.props.attrs[prop];
                componentChanged = true;
              }
            }
            // If it has children, resolve any new slots
            if (vnode.children) {
              componentInstance.$slots = getSlots(vnode.children);
              componentChanged = true;
            }
            // If any changes were detected, build the component
            if (componentChanged) {
              componentInstance.build();
            }
          }
          // Skip diffing any children
          return node;
        }

        // Children May have Changed

        // Diff props
        var nodeProps = node.__moon__props__ || extractAttrs(node);
        diffProps(node, nodeProps, vnode, vnode.props.attrs);

        // Add initial event listeners (done once)
        if (instance.$initialRender) {
          addEventListeners(node, vnode, instance);
        }

        // Check if innerHTML was changed, don't diff children
        if (vnode.props.dom && vnode.props.dom.innerHTML) {
          return node;
        }

        // Diff Children
        var currentChildNode = node.firstChild;
        // Optimization:
        //  If the vnode contains just one text vnode, create it here
        if (vnode.children.length === 1 && vnode.children[0].type === "#text" && currentChildNode && !currentChildNode.nextSibling && currentChildNode.nodeName === "#text") {
          if (vnode.children[0].val !== currentChildNode.textContent) {
            currentChildNode.textContent = vnode.children[0].val;
          }
        } else {
          // Iterate through all children
          for (var i = 0; i < vnode.children.length || currentChildNode; i++) {
            var next = currentChildNode ? currentChildNode.nextSibling : null;
            diff(currentChildNode, vnode.children[i], node, instance);
            currentChildNode = next;
          }
        }

        return node;
      } else {
        // Nothing Changed
        return node;
      }
    };

    /**
     * Extends an Object with another Object's properties
     * @param {Object} parent
     * @param {Object} child
     * @return {Object} Extended Parent
     */
    var extend = function (parent, child) {
      for (var key in child) {
        parent[key] = child[key];
      }
      return parent;
    };

    /**
     * Merges Two Objects Together
     * @param {Object} parent
     * @param {Object} child
     * @return {Object} Merged Object
     */
    var merge = function (parent, child) {
      var merged = {};
      for (var key in parent) {
        merged[key] = parent[key];
      }
      for (var key in child) {
        merged[key] = child[key];
      }
      return merged;
    };

    /**
     * Calls a Hook
     * @param {Object} instance
     * @param {String} name
     */
    var callHook = function (instance, name) {
      var hook = instance.$hooks[name];
      if (hook) {
        hook.call(instance);
      }
    };

    /**
     * Does No Operation
     */
    var noop = function () {};

    /* ======= Compiler ======= */
    var lex = function (input) {
      var state = {
        input: input,
        current: 0,
        tokens: []
      };
      lexState(state);
      return state.tokens;
    };

    var lexState = function (state) {
      var input = state.input;
      var len = input.length;
      while (state.current < len) {
        // Check if it is text
        if (input.charAt(state.current) !== "<") {
          lexText(state);
          continue;
        }

        // Check if it is a comment
        if (input.substr(state.current, 4) === "<!--") {
          lexComment(state);
          continue;
        }

        // It's a tag
        lexTag(state);
      }
    };

    var lexText = function (state) {
      var input = state.input;
      var len = input.length;
      var endOfText = input.indexOf("<", state.current);
      // Only Text
      if (endOfText === -1) {
        state.tokens.push({
          type: "text",
          value: input.slice(state.current)
        });
        state.current = len;
        return;
      }

      // No Text at All
      if (endOfText === state.current) {
        return;
      }

      // End of Text Found
      state.tokens.push({
        type: "text",
        value: input.slice(state.current, endOfText)
      });
      state.current = endOfText;
    };

    var lexComment = function (state) {
      var input = state.input;
      var len = input.length;
      state.current += 4;
      var endOfComment = input.indexOf("-->", state.current);

      // Only an unclosed comment
      if (endOfComment === -1) {
        state.tokens.push({
          type: "comment",
          value: input.slice(state.current)
        });
        state.current = len;
        return;
      }

      // End of Comment Found
      state.tokens.push({
        type: "comment",
        value: input.slice(state.current, endOfComment)
      });
      state.current = endOfComment + 3;
    };

    var lexTag = function (state) {
      var input = state.input;
      var len = input.length;

      // Lex Starting of Tag
      var isClosingStart = input.charAt(state.current + 1) === "/";
      state.tokens.push({
        type: "tagStart",
        close: isClosingStart
      });
      state.current += isClosingStart ? 2 : 1;

      // Lex type and attributes
      var tagType = lexTagType(state);
      lexAttributes(state);

      // Lex ending tag
      var isClosingEnd = input.charAt(state.current) === "/";
      state.tokens.push({
        type: "tagEnd",
        close: false
      });
      state.current += isClosingEnd ? 2 : 1;
      if (isClosingEnd) {
        state.tokens.push({
          type: "tagStart",
          close: true
        });
        state.tokens.push({
          type: "tag",
          value: tagType
        });
        state.tokens.push({
          type: "attribute",
          value: {}
        });
        state.tokens.push({
          type: "tagEnd",
          close: false
        });
      }
    };

    var lexTagType = function (state) {
      var input = state.input;
      var len = input.length;
      var start = state.current;
      while (start < len) {
        var char = input.charAt(start);
        if (char === "/" || char === ">" || char === " ") {
          start++;
        } else {
          break;
        }
      }

      var end = start;
      while (end < len) {
        var char = input.charAt(end);
        if (char === "/" || char === ">" || char === " ") {
          break;
        } else {
          end++;
        }
      }

      var tagType = input.slice(start, end);
      state.tokens.push({
        type: "tag",
        value: tagType
      });
      state.current = end;
      return tagType;
    };

    var lexAttributes = function (state) {
      var input = state.input;
      var len = input.length;
      var end = state.current;

      var attrs = {};

      var char = input.charAt(end);
      var nextChar = input.charAt(end + 1);

      var incrementChar = function () {
        end++;
        char = input.charAt(end);
        nextChar = input.charAt(end + 1);
      };

      while (end < len) {
        // Reached the end of the tag
        if (char === ">" || char === "/" && nextChar === ">") {
          break;
        }

        // Reached end of an attribute
        if (char === " ") {
          incrementChar();
          continue;
        }

        // Begin obtaining the attribute name
        var attrName = "";
        var noValue = false;
        while (char !== "=" && end < len) {
          // Ensure attribute has a value
          if (char !== " " && char !== ">" || char === "/" && nextChar !== ">") {
            attrName += char;
          } else {
            // Attribute had no value, skip it
            noValue = true;
            break;
          }
          incrementChar();
        }

        if (noValue) {
          attrs[attrName] = "";
          continue;
        }

        var attrValue = {
          meta: {},
          value: ""
        };
        var quoteType = " ";

        // Exit equal sign and setup quote type
        incrementChar();
        if (char === "'" || char === "\"") {
          quoteType = char;
          incrementChar();
        } else {
          attrValue.value += char;
        }

        while ((char !== quoteType && char !== ">" || char === "/" && nextChar !== ">") && end < len) {
          attrValue.value += char;
          incrementChar();
        }

        if (attrName.indexOf(":") !== -1) {
          var attrNames = attrName.split(":");
          attrName = attrNames[0];
          attrValue.meta.arg = attrNames[1];
        }

        attrs[attrName] = attrValue;
        incrementChar();
      }

      state.current = end;
      state.tokens.push({
        type: "attribute",
        value: attrs
      });
    };

    var parse = function (tokens) {
      var root = {
        type: "ROOT",
        children: []
      };

      var state = {
        current: 0,
        tokens: tokens
      };

      while (state.current < tokens.length) {
        var child = walk(state);
        if (child) {
          root.children.push(child);
        }
      }

      return root;
    };

    var HTML_ELEMENTS = ["area", "base", "br", "command", "embed", "hr", "img", "input", "keygen", "link", "meta", "param", "source", "track", "wbr"];
    var SVG_ELEMENTS = ["svg", "animate", "circle", "clippath", "cursor", "defs", "desc", "ellipse", "filter", "font-face", "foreignObject", "g", "glyph", "image", "line", "marker", "mask", "missing-glyph", "path", "pattern", "polygon", "polyline", "rect", "switch", "symbol", "text", "textpath", "tspan", "use", "view"];

    var createParseNode = function (type, props, children) {
      return {
        type: type,
        props: props,
        children: children
      };
    };

    var walk = function (state) {
      var token = state.tokens[state.current];
      var previousToken = state.tokens[state.current - 1];
      var secondToken = state.tokens[state.current + 1];
      var thirdToken = state.tokens[state.current + 2];
      var fourthToken = state.tokens[state.current + 3];

      var increment = function (num) {
        state.current += num === undefined ? 1 : num;
        token = state.tokens[state.current];
        previousToken = state.tokens[state.current - 1];
        secondToken = state.tokens[state.current + 1];
        thirdToken = state.tokens[state.current + 2];
      };

      if (token.type === "text") {
        increment();
        return previousToken.value;
      }

      if (token.type === "comment") {
        increment();
        return;
      }

      // Start of new Tag
      if (token.type === "tagStart" && !token.close && !fourthToken.close) {
        var node = createParseNode(secondToken.value, thirdToken.value, []);
        var tagType = secondToken.value;
        // Exit Start Tag
        increment(4);

        // If it is an svg element, let code generator know
        if (SVG_ELEMENTS.indexOf(node.type) !== -1) {
          node.isSVG = true;
        }

        // If it's self closing, return it here
        if (HTML_ELEMENTS.indexOf(node.type) !== -1) {
          return node;
        }

        var startContentIndex = state.current;
        // Make sure it has content and is closed
        if (token) {
          // Find Closing Tag, and push children recursively
          while (token.type !== "tagStart" || token.type === "tagStart" && !token.close) {
            // Push a parsed child to the current node
            var parsedChildState = walk(state);
            var lastKnown;
            if (parsedChildState) {
              node.children.push(parsedChildState);
            }
            increment(0);
            if (!token) {
              // No token means a tag was left unclosed
              error('The element "' + node.type + '" was left unclosed.');
              break;
            }
          }
          increment();
        }

        return node;
      }

      increment();
      return;
    };

    /**
     * Generates Code for Props
     * @param {Object} vnode
     * @return {String} generated code
     */
    var generateProps = function (vnode) {
      var attrs = vnode.props.attrs;
      var generatedObject = "{attrs: {";

      if (attrs) {
        for (var attr in attrs) {
          if (directives[attr]) {
            vnode.dynamic = true;
          }
          if (specialDirectives[attr]) {
            // Special directive found that generates code after initial generation, push it to its known special directives to run afterGenerate later
            if (specialDirectives[attr].afterGenerate) {
              if (!vnode.specialDirectivesAfter) {
                vnode.specialDirectivesAfter = {};
              }
              vnode.specialDirectivesAfter[attr] = attrs[attr];
            }

            // Invoke any special directives that need to change values before code generation
            if (specialDirectives[attr].beforeGenerate) {
              specialDirectives[attr].beforeGenerate(attrs[attr].value, attrs[attr].meta, vnode);
            }

            // Invoke any special directives that need to change values of props during code generation
            if (specialDirectives[attr].duringPropGenerate) {
              generatedObject += specialDirectives[attr].duringPropGenerate(attrs[attr].value, attrs[attr].meta, vnode);
            }

            // Keep a flag to know to always rerender this
            vnode.dynamic = true;

            // Remove special directive
            delete attrs[attr];
          } else {
            var normalizedProp = JSON.stringify(attrs[attr].value);
            var compiledProp = compileTemplate(normalizedProp, true);
            if (normalizedProp !== compiledProp) {
              vnode.dynamic = true;
            }
            generatedObject += '"' + attr + '": ' + compiledProp + ', ';
          }
        }

        if (Object.keys(attrs).length) {
          generatedObject = generatedObject.slice(0, -2) + "}";
        } else {
          generatedObject += "}";
        }
      }

      var dom = vnode.props.dom;
      if (dom) {
        vnode.dynamic = true;
        generatedObject += ", dom: {";
        for (var domProp in dom) {
          generatedObject += '"' + domProp + '": ' + dom[domProp] + ', ';
        }
        generatedObject = generatedObject.slice(0, -2) + "}";
      }

      // Close the generated object
      generatedObject += "}";
      return generatedObject;
    };

    /**
     * Generates Code for Event Listeners
     * @param {Object} listeners
     * @return {String} generated code
     */
    var generateEventListeners = function (listeners) {
      if (Object.keys(listeners).length === 0) {
        return "{}";
      }
      var generatedObject = "{";

      for (var type in listeners) {
        generatedObject += '"' + type + '": [' + generateArray(listeners[type]) + '], ';
      }

      generatedObject = generatedObject.slice(0, -2) + "}";

      return generatedObject;
    };

    /**
     * Generates Code for Metadata
     * @param {Object} meta
     * @return {String} generated code
     */
    var generateMeta = function (meta) {
      var generatedObject = "{";

      for (var key in meta) {
        if (key === 'eventListeners') {
          generatedObject += '"' + key + '": ' + generateEventListeners(meta[key]) + ', ';
        } else {
          generatedObject += '"' + key + '": ' + meta[key] + ', ';
        }
      }

      generatedObject = generatedObject.slice(0, -2) + "}";

      return generatedObject;
    };

    /**
     * Generates Code for an Array
     * @param {Array} arr
     * @return {String} generated array
     */
    var generateArray = function (arr) {
      var generatedArray = "";

      for (var i = 0; i < arr.length; i++) {
        generatedArray += arr[i] + ', ';
      }

      generatedArray = generatedArray.slice(0, -2);

      return generatedArray;
    };

    /**
     * Creates an "h" Call for a VNode
     * @param {Object} vnode
     * @param {Array} children
     * @return {String} "h" call
     */
    var createCall = function (vnode) {
      var call = 'h("' + vnode.type + '", ';
      call += generateProps(vnode) + ", ";
      // Generate code for children recursively here (in case modified by special directives)
      var children = vnode.children.map(generateEl);
      // Detected static vnode, tell diffing engine to skip it
      if (vnode.children.length === 1 && children.length === 1 && typeof vnode.children[0] === "string" && "\"" + vnode.children[0] + "\"" === children[0] && !vnode.dynamic) {
        vnode.meta.shouldRender = "instance.$initialRender";
      }

      call += generateMeta(vnode.meta);
      call += children.length ? ", " + generateArray(children) : "";
      call += ")";
      return call;
    };

    var generateEl = function (el) {
      var code = "";

      if (typeof el === "string") {
        // Escape newlines and double quotes, and compile the string
        code += '"' + compileTemplate(escapeString(el), true) + '"';
      } else {
        // Recursively generate code for children
        if (!el.meta) {
          el.meta = defaultMetadata();
          if (el.isSVG) {
            el.meta.isSVG = true;
          }
        }
        el.props = {
          attrs: el.props
        };
        var slotNameAttr = el.props.attrs.name;
        var compiledCode = el.type === "slot" ? 'instance.$slots[\'' + (slotNameAttr && slotNameAttr.value || "default") + '\']' : createCall(el);
        if (el.specialDirectivesAfter) {
          // There are special directives that need to change the value after code generation, so
          // run them now
          for (var specialDirectiveAfter in el.specialDirectivesAfter) {
            compiledCode = specialDirectives[specialDirectiveAfter].afterGenerate(el.specialDirectivesAfter[specialDirectiveAfter].value, el.specialDirectivesAfter[specialDirectiveAfter].meta, compiledCode, el);
          }
        }
        code += compiledCode;
      }
      return code;
    };

    var generate = function (ast) {
      // Get root element
      var root = ast.children[0];
      // Begin Code
      var code = "var instance = this; return " + generateEl(root);

      try {
        return new Function("h", code);
      } catch (e) {
        error("Could not create render function");
        return noop;
      }
    };

    var compile = function (template) {
      var tokens = lex(template);
      var ast = parse(tokens);
      return generate(ast);
    };

    function Moon(opts) {
      /* ======= Initial Values ======= */
      this.$opts = opts || {};

      this.$id = id++;

      this.$name = this.$opts.name || "root";
      this.$data = this.$opts.data || {};
      this.$render = this.$opts.render || noop;
      this.$hooks = this.$opts.hooks || {};
      this.$methods = this.$opts.methods || {};
      this.$events = {};
      this.$dom = {};
      this.$observer = new Observer(this);
      this.$destroyed = false;
      this.$initialRender = true;
      this.$queued = false;

      // Setup Computed Properties
      if (this.$opts.computed) {
        initComputed(this, this.$opts.computed);
      }

      /* ======= Initialize 🎉 ======= */
      this.init();
    }

    /* ======= Instance Methods ======= */

    /**
     * Gets Value in Data
     * @param {String} key
     * @return {String} Value of key in data
     */
    Moon.prototype.get = function (key) {
      return this.$data[key];
    };

    /**
     * Sets Value in Data
     * @param {String} key
     * @param {String} val
     */
    Moon.prototype.set = function (key, val) {
      resolveKeyPath(this, this.$data, key, val);
      this.$observer.notify();
    };

    /**
     * Destroys Moon Instance
     */
    Moon.prototype.destroy = function () {
      this.removeEvents();
      this.$el = null;
      this.$destroyed = true;
      callHook(this, 'destroyed');
    };

    /**
     * Calls a method
     * @param {String} method
     */
    Moon.prototype.callMethod = function (method, args) {
      args = args || [];
      this.$methods[method].apply(this, args);
    };

    // Event Emitter, adapted from https://github.com/KingPixil/voke

    /**
     * Attaches an Event Listener
     * @param {String} eventName
     * @param {Function} action
     */
    Moon.prototype.on = function (eventName, action) {
      if (this.$events[eventName]) {
        this.$events[eventName].push(action);
      } else {
        this.$events[eventName] = [action];
      }
    };

    /**
     * Removes an Event Listener
     * @param {String} eventName
     * @param {Function} action
     */
    Moon.prototype.off = function (eventName, action) {
      var index = this.$events[eventName].indexOf(action);
      if (index !== -1) {
        this.$events[eventName].splice(index, 1);
      }
    };

    /**
     * Removes All Event Listeners
     * @param {String} eventName
     * @param {Function} action
     */
    Moon.prototype.removeEvents = function () {
      for (var evt in this.$events) {
        this.$events[evt] = [];
      }
    };

    /**
     * Emits an Event
     * @param {String} eventName
     * @param {Object} meta
     */
    Moon.prototype.emit = function (eventName, meta) {
      meta = meta || {};
      meta.type = eventName;

      if (this.$events["*"]) {
        for (var i = 0; i < this.$events["*"].length; i++) {
          var globalHandler = this.$events["*"][i];
          globalHandler(meta);
        }
      }

      for (var i = 0; i < this.$events[eventName].length; i++) {
        var handler = this.$events[eventName][i];
        handler(meta);
      }
    };

    /**
     * Renders "m-for" Directive Array
     * @param {Array} arr
     * @param {Function} item
     */
    Moon.prototype.renderLoop = function (arr, item) {
      var items = [];
      for (var i = 0; i < arr.length; i++) {
        items.push(item(arr[i], i));
      }
      return items;
    };

    /**
     * Renders a Class in Array/Object Form
     * @param {Array|Object|String} classNames
     * @return {String} renderedClassNames
     */
    Moon.prototype.renderClass = function (classNames) {
      if (typeof classNames === "string") {
        return classNames;
      }
      var renderedClassNames = "";
      if (Array.isArray(classNames)) {
        for (var i = 0; i < classNames.length; i++) {
          renderedClassNames += this.renderClass(classNames[i]) + ' ';
        }
      } else if (typeof classNames === "object") {
        for (var className in classNames) {
          if (classNames[className]) {
            renderedClassNames += className + ' ';
          }
        }
      }
      renderedClassNames = renderedClassNames.slice(0, -1);
      return renderedClassNames;
    };

    /**
     * Mounts Moon Element
     * @param {Object} el
     */
    Moon.prototype.mount = function (el) {
      this.$el = document.querySelector(el);
      this.$destroyed = false;

      if (!this.$el) {
        error("Element " + this.$opts.el + " not found");
      }

      // Sync Element and Moon instance
      this.$el.__moon__ = this;

      // Setup template as provided `template` or outerHTML of the Element
      this.$template = this.$opts.template || this.$el.outerHTML;

      // Setup render Function
      if (this.$render === noop) {
        this.$render = Moon.compile(this.$template);
      }

      // Run First Build
      this.build();
      callHook(this, 'mounted');
    };

    /**
     * Renders Virtual DOM
     * @return Virtual DOM
     */
    Moon.prototype.render = function () {
      return this.$render(h);
    };

    /**
     * Diff then Patches Nodes With Data
     * @param {Object} node
     * @param {Object} vnode
     */
    Moon.prototype.patch = function (node, vnode, parent) {
      var newRootEl = diff(node, vnode, parent, this);
      if (node !== newRootEl) {
        // Root Node Changed, Apply Change in Instance
        this.$el = newRootEl;
        this.$el.__moon__ = this;
      }
      this.$initialRender = false;
    };

    /**
     * Render and Patches the DOM With Data
     */
    Moon.prototype.build = function () {
      this.$dom = this.render();
      this.patch(this.$el, this.$dom, this.$el.parentNode);
    };

    /**
     * Initializes Moon
     */
    Moon.prototype.init = function () {
      log("======= Moon =======");
      callHook(this, 'init');

      if (this.$opts.el) {
        this.mount(this.$opts.el);
      }
    };

    /* ======= Global API ======= */

    /**
     * Configuration of Moon
     */
    Moon.config = {
      silent: typeof console === 'undefined',
      prefix: "m-",
      keyCodes: function (keyCodes) {
        for (var keyCode in keyCodes) {
          eventModifiersCode[keyCode] = 'if(event.keyCode !== ' + keyCodes[keyCode] + ') {return;};';
        }
      }
    };

    /**
     * Version of Moon
     */
    Moon.version = '0.7.0';

    /**
     * Moon Utilities
     */
    Moon.util = {
      noop: noop,
      error: error,
      log: log,
      merge: merge,
      extend: extend
    };

    /**
     * Runs an external Plugin
     * @param {Object} plugin
     */
    Moon.use = function (plugin) {
      plugin.init(Moon);
    };

    /**
     * Compiles HTML to a Render Function
     * @param {String} template
     * @return {Function} render function
     */
    Moon.compile = function (template) {
      return compile(template);
    };

    /**
     * Runs a Task After Update Queue
     * @param {Function} task
     */
    Moon.nextTick = function (task) {
      setTimeout(task, 0);
    };

    /**
     * Creates a Directive
     * @param {String} name
     * @param {Function} action
     */
    Moon.directive = function (name, action) {
      directives[Moon.config.prefix + name] = action;
    };

    /**
     * Creates a Component
     * @param {String} name
     * @param {Function} action
     */
    Moon.component = function (name, opts) {
      var Parent = this;
      opts.name = name;

      function MoonComponent() {
        Moon.call(this, opts);
      }

      MoonComponent.prototype = Object.create(Parent.prototype);
      MoonComponent.prototype.constructor = MoonComponent;

      MoonComponent.prototype.init = function () {
        callHook(this, 'init');
        this.$destroyed = false;
        this.$props = this.$opts.props || [];

        this.$template = this.$opts.template;

        if (this.$render === noop) {
          this.$render = Moon.compile(this.$template);
        }
      };

      components[name] = {
        CTor: MoonComponent,
        opts: opts
      };

      return MoonComponent;
    };

    /* ======= Default Directives ======= */

    specialDirectives[Moon.config.prefix + "if"] = {
      afterGenerate: function (value, meta, code, vnode) {
        return '(' + compileTemplate(value, false) + ') ? ' + code + ' : \'\'';
      }
    };

    specialDirectives[Moon.config.prefix + "for"] = {
      afterGenerate: function (value, meta, code, vnode) {
        var parts = value.split(" in ");
        var aliases = parts[0].split(",");

        var iteratable = compileTemplate(parts[1], false);

        var params = aliases.join(",");

        code.replace(/instance\.get\("([^"]+)"\)/g, function (match, alias) {
          if (aliases.indexOf(alias) !== -1) {
            code = code.replace(new RegExp('instance.get\\("' + alias + '"\\)', "g"), alias);
          }
        });

        return 'instance.renderLoop(' + iteratable + ', function(' + params + ') { return ' + code + '; })';
      }
    };

    specialDirectives[Moon.config.prefix + "on"] = {
      beforeGenerate: function (value, meta, vnode) {

        // Extract modifiers and the event
        var rawModifiers = meta.arg.split(".");
        var eventToCall = rawModifiers[0];
        var params = "event";
        var methodToCall = compileTemplate(value, false);
        var rawParams = methodToCall.split("(");

        if (rawParams.length > 1) {
          methodToCall = rawParams.shift();
          params = rawParams.join("(").slice(0, -1);
        }
        var modifiers = "";

        rawModifiers.shift();

        for (var i = 0; i < rawModifiers.length; i++) {
          modifiers += eventModifiersCode[rawModifiers[i]];
        }

        var code = 'function(event) {' + modifiers + 'instance.callMethod("' + methodToCall + '", [' + params + '])}';
        if (!vnode.meta.eventListeners[eventToCall]) {
          vnode.meta.eventListeners[eventToCall] = [code];
        } else {
          vnode.meta.eventListeners[eventToCall].push(code);
        }
      }
    };

    specialDirectives[Moon.config.prefix + "model"] = {
      beforeGenerate: function (value, meta, vnode) {
        // Compile a string value for the keypath
        var compiledStringValue = compileTemplate(value, true);
        // Setup default event types and dom property to change
        var eventType = "input";
        var valueProp = "value";

        // If input type is checkbox, listen on 'change' and change the 'checked' dom property
        if (vnode.props.attrs.type === "checkbox") {
          eventType = "change";
          valueProp = "checked";
        }

        // Generate event listener code
        var code = 'function(event) {instance.set("' + compiledStringValue + '", event.target.' + valueProp + ')}';

        // Push the listener to it's event listeners
        if (!vnode.meta.eventListeners[eventType]) {
          vnode.meta.eventListeners[eventType] = [code];
        } else {
          vnode.meta.eventListeners[eventType].push(code);
        }

        // Setup a query used to get the value, and set the corresponding dom property
        var getQuery = compileTemplate('{{' + compileTemplate(value, false) + '}}', false);
        if (!vnode.props.dom) {
          vnode.props.dom = {};
        }
        vnode.props.dom[valueProp] = getQuery;
      }
    };

    specialDirectives[Moon.config.prefix + "literal"] = {
      duringPropGenerate: function (value, meta, vnode) {
        var prop = meta.arg;
        // make sure object is treated correctly during code generation
        vnode.props.attrs[prop] = true;

        if (prop === "class") {
          // Classes need to be rendered differently
          return '"class": instance.renderClass(' + compileTemplate(value, false) + '), ';
        }
        return '"' + prop + '": ' + compileTemplate(value, false) + ', ';
      }
    };

    specialDirectives[Moon.config.prefix + "once"] = {
      beforeGenerate: function (value, meta, vnode) {
        vnode.meta.shouldRender = "instance.$initialRender";
      }
    };

    specialDirectives[Moon.config.prefix + "pre"] = {
      beforeGenerate: function (value, meta, vnode) {
        vnode.meta.shouldRender = false;
      }
    };

    specialDirectives[Moon.config.prefix + "html"] = {
      beforeGenerate: function (value, meta, vnode) {
        if (!vnode.props.dom) {
          vnode.props.dom = {};
        }
        vnode.props.dom.innerHTML = '"' + compileTemplate(value, true) + '"';
      }
    };

    specialDirectives[Moon.config.prefix + "text"] = {
      beforeGenerate: function (value, meta, vnode) {
        vnode.children = [value];
      }
    };

    directives[Moon.config.prefix + "show"] = function (el, val, vnode) {
      var evaluated = new Function("return " + val);
      if (!evaluated()) {
        el.style.display = 'none';
      } else {
        el.style.display = 'block';
      }
    };

    directives[Moon.config.prefix + "mask"] = function (el, val, vnode) {};
    return Moon;
}));


text:
<?php

use yupe\components\Mail;

class DbFeedbackSender implements IFeedbackSender
{
    protected $mail;

    protected $module;

    public function __construct(Mail $mail, FeedbackModule $module)
    {
        $this->mail = $mail;

        $this->module = $module;
    }

    public function send(FeedBackForm $form)
    {
        $feedback = new FeedBack;

        $feedback->setAttributes(array(
            'name' => $form->name,
            'email' => $form->email,
            'theme' => $form->theme,
            'text' => $form->text,
            'phone' => $form->phone,
            'type' => $form->type,
        ));

        if ($feedback->save()) {

            if ($this->module->sendConfirmation) {

                return $this->sendConfirmation($form);
            }

            return true;
        }

        return false;
    }

    public function sendConfirmation(FeedBackForm $feedback)
    {
        $emailBody = Yii::app()->controller->renderPartial('feedbackConfirmationEmail', array('model' => $feedback), true);

        $result = $this->mail->send(
            $this->module->notifyEmailFrom,
            $feedback->email,
            Yii::t('FeedbackModule.feedback', 'Your proposition on site "{site}" was received', array('{site}' => Yii::app()->name)),
            $emailBody
        );

        if ($result) {
            Yii::log(
                Yii::t('FeedbackModule.feedback', 'Feedback: Notification for user was sent to email successfully'),
                CLogger::LEVEL_INFO,
                FeedbackModule::$logCategory
            );
        } else {
            Yii::log(
                Yii::t('FeedbackModule.feedback', 'Feedback: can\'t send message'),
                CLogger::LEVEL_INFO,
                FeedbackModule::$logCategory
            );
        }

        return $result;
    }
}

redpajama_set_name: RedPajamaGithub


text:
MailNode::MailNode( )
{
__ENTER_FUNCTION

    m_nPoolIndex = INVALID_INDEX ;

    _WORLD_INFO& WorldInfo = g_Config.m_WorldInfo;
    if(WorldInfo.m_EnableShareMem)
    {
        m_pMailSMU = g_MailSMUPool.NewObj();
        Assert(m_pMailSMU);
        memcpy(&m_Mail,&(m_pMailSMU->m_MailSM),sizeof(m_Mail));
    }
    else
    {
        m_pMailSMU = NULL;
    }

__LEAVE_FUNCTION
}

MailNode::~MailNode( )
{
__ENTER_FUNCTION

__LEAVE_FUNCTION
}

VOID MailNode::CleanUp( )
{
__ENTER_FUNCTION

    m_Mail.CleanUp( ) ;
    if(m_pMailSMU)
    {
            ValidateShareMem();
    }
    m_nPoolIndex = INVALID_INDEX ;
    m_nUserNodePoolIndex = INVALID_INDEX ;

__LEAVE_FUNCTION
}

VOID MailNode::SetMail( const MAIL* pMail )
{
    m_Mail = *pMail ;
    ValidateShareMem();
}

VOID MailNode::ValidateShareMem()
{
    __ENTER_FUNCTION
    if(m_pMailSMU )
    {
        m_pMailSMU->Lock(SM_W_WRITE);
        memcpy(&(m_pMailSMU->m_MailSM),&m_Mail,sizeof(m_Mail));
        m_pMailSMU->UnLock(SM_W_WRITE);
    }
    __LEAVE_FUNCTION

    if(m_pMailSMU)
        m_pMailSMU->UnLock(SM_W_WRITE);
}

/////////////////////////////////////////////////////////////////////////////////
//
UserNode::UserNode( )
{
__ENTER_FUNCTION

    m_nPoolIndex = INVALID_INDEX ;
    m_ChainMail.OutAll() ;
    m_uTickCount = 0 ;
    memset( m_szName, 0, sizeof(CHAR)*MAX_CHARACTER_NAME ) ;

__LEAVE_FUNCTION
}

UserNode::~UserNode( )
{
__ENTER_FUNCTION

__LEAVE_FUNCTION
}

VOID UserNode::CleanUp( )
{
__ENTER_FUNCTION

    m_nPoolIndex = INVALID_INDEX ;
    m_ChainMail.Last() ;
    while( m_ChainMail.GetNum()>0)
    {
        MailNode* pMailNode = (MailNode*)(m_ChainMail.OutChain()) ;
        g_pMailNodePool->DeleteNode( pMailNode ) ;
    };
    m_uTickCount = 0 ;
    memset( m_szName, 0, MAX_CHARACTER_NAME*sizeof(CHAR) ) ;

__LEAVE_FUNCTION
}

INT UserNode::GetMailCount( )//返回此用户的邮件数量
{
__ENTER_FUNCTION

    return (INT)(m_ChainMail.GetNum()) ;

__LEAVE_FUNCTION

    return 0 ;
}

INT UserNode::GetScriptMailCount( )//返回此用户的邮件数量
{
__ENTER_FUNCTION

    return (INT)(m_ChainScriptMail.GetNum()) ;

__LEAVE_FUNCTION

    return 0 ;
}
/////////////////////////////////////////////////////////////////////////////////
//
UserChain::UserChain( )
{
__ENTER_FUNCTION

__LEAVE_FUNCTION
}

UserChain::~UserChain( )
{
__ENTER_FUNCTION

__LEAVE_FUNCTION
}

BOOL UserChain::Init( )
{
__ENTER_FUNCTION

    Assert( m_ChainUser.GetNum()==0 ) ;

    return TRUE ;

__LEAVE_FUNCTION

    return FALSE ;
}

VOID UserChain::CleanUp( )
{
__ENTER_FUNCTION

    m_ChainUser.First() ;
    while( m_ChainUser.GetNum()>0 )
    {
        UserNode* pUserNode = (UserNode*)(m_ChainUser.OutChain()) ;
        pUserNode->CleanUp() ;
    };

__LEAVE_FUNCTION
}

/////////////////////////////////////////////////////////////////////////////////
//
UserHashTable::UserHashTable( )
{
__ENTER_FUNCTION

__LEAVE_FUNCTION
}

UserHashTable::~UserHashTable( )
{
__ENTER_FUNCTION

__LEAVE_FUNCTION
}

BOOL UserHashTable::Init( )
{
__ENTER_FUNCTION

    m_NameTable.InitTable( g_Config.m_ConfigInfo.m_nHashMailUserCount, MAX_CHARACTER_NAME ) ;

    return TRUE ;

__LEAVE_FUNCTION

    return FALSE ;
}

VOID UserHashTable::CleanUp( )
{
__ENTER_FUNCTION

    m_NameTable.CleanUp( ) ;

__LEAVE_FUNCTION
}

BOOL UserHashTable::Add( CHAR* szName, UserNode* pNode )
{
__ENTER_FUNCTION

    m_NameTable.Add( szName, pNode ) ;

    return TRUE ;

__LEAVE_FUNCTION

    return FALSE ;
}

VOID UserHashTable::Del( CHAR* szName )
{
__ENTER_FUNCTION

    m_NameTable.Remove( szName ) ;

__LEAVE_FUNCTION
}

UserNode* UserHashTable::Get( CHAR* szName )
{
__ENTER_FUNCTION

    return (UserNode*)(m_NameTable.Get(szName)) ;

__LEAVE_FUNCTION

    return NULL ;
}


text:
<?php

namespace Utill\MQ\MessageMQ;

/**
 * rabbitMQ message wrapper
 * @author Mustafa Zeynel Dağlı
 */
abstract class abstractMQMessage {

     /**
      * rabbitMQ message properties
      * @var array
      */
     protected $messageProperties = array('delivery_mode' => 2,# make message persistent, so it is not lost if server crashes or quits
                  'content_type' => 'application/json');

     /**
      * rabbitMQ message object
      * @var \PhpAmqpLib\Message\AMQPMessage
      */
    protected $message;

    /**
     * rabbitMQ message body
     * @var string
    */
    protected $messageBody;

    /**
      * creates a new rabbitMQ message body
      * will be overriden in extended classes
      * @var array  $messageBody
      */
     abstract public function setMessageBody($messageBody);

     /**
      * get rabbitMQ message body
      * @return array | object | string
      */
     public function getMesssageBody() {
         return $this->messageBody;
     }

    /**
      * creates a new rabbitMQ message
      * will be overriden in extended classes
      */
     abstract public function setMessage();

     /**
      * get rabbitMQ message object
      * @return \PhpAmqpLib\Message\AMQPMessage | null
      */
     public function getMessage() {
         return$this->message;
     }

     /**
      * creates a new rabbitMQ message properties
      * will be overriden in extended classes
      * @var array  $messageProperties
      */
     abstract public function setMessageProperties(array $messageProperties = array());

     /**
      * get rabbitMQ message properties
      * @return array | null
      */
     public function getMessageProperties() {
         return $this->messageProperties;
     }
}


text:
layout: post
title: Exercism - Hamming
date: 19 Mar 2015
---

Task: Write a program that can calculate the Hamming difference between two DNA strands.

The Hamming distance between two strands of DNA by counting the number of differences between the two. So, for example:
{% highlight text %}
GGACG
GGTCG
{% endhighlight %}

The Hamming distance between these two DNA strands is 1.

The implementation of the code should look like this:

{% highlight ruby %}
Hamming.compute('GGACG', 'GGTCG')
# => 1
{% endhighlight %}

Now for the code writing part. So far I know there needs to be a ``Hamming`` class and that has a function ``compute`` and it expects two strings of the same size.

{% highlight ruby %}
class Hamming
    def self.compute(base, compare)
    end
end
{% endhighlight %}

The first solution that came to mind was to iterate through each character in the ``base`` string and compare the value between the ``base`` string and ``compare`` string. Since both strings are of the same size we only need to iterate through once string. So the algorithm will be of linear time complexity.

Since the index position of base goes from 0 to ``base.length - 1``, it made the most sense to use a Range object. The Range object will look something like ``(0..(base.length - 1))``. From there I just called the ``.each`` method to access the inidivdual characters in the string, adding one to a diff variable whenever the ``base[index]`` does not match ``compare[index]``

The first iteration of the code looks like this:

{% highlight ruby %}
class Hamming
  def self.compute(base, compare)
    diff = 0
    (0..(base.length - 1)).each do |index|
      if base[index] != compare[index]
        diff += 1
      end
    end
    diff
  end
end
{% endhighlight %}

This passes all the test cases supplied by Exercism.io. However, this will still run even if the two arguments are not of the same length. Since Hamming distance is only defined for sequences of equal length I'll want to guarantee that, so I need to raise an exception when ``base.length`` and ``compare.length`` are unequal.

{% highlight ruby %}
class Hamming
  def self.compute(base, compare)
    raise ArgumentError if base.length != compare.length
    diff = 0
    (0..(base.length - 1)).each do |index|
      if base[index] != compare[index]
        diff += 1
      end
    end
    diff
  end
end
{% endhighlight %}

Since none of the pre-made test cases test for this, I added my own.

{% highlight ruby %}
def test_exception_raised_if_different_lengths
    assert_raises ArgumentError do
        Hamming.compare('A', 'AA')
    end
end

{% endhighlight %}

And it passes.


text: Heroku project to serve content directly from S3 include basic authentication


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="?android:attr/listPreferredItemHeight"
    android:padding="6dip"
    android:focusable="false">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="0dip"
        android:layout_weight="1"
        android:layout_height="fill_parent"
        android:focusable="false">
        <TextView
            android:id="@+id/text_entry_phone"
            android:layout_width="fill_parent"
            android:layout_height="0dip"
            android:layout_weight="1"
            android:gravity="center_vertical"
            android:focusable="false"
			android:layout_marginLeft="5sp"
            android:textColor="#8bd7ff"
        />
    </LinearLayout>
        <ImageButton
        android:id="@+id/button_call"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_marginRight="6dip"
        android:src="@android:drawable/sym_action_call"
        android:focusable="false"
        android:background="@null" />
</LinearLayout>


text:
StereoCrossEye::StereoCrossEye()
{
}

bool StereoCrossEye::Init()
{
	ENGINE::StartWindowSystem(MercuryWindow::Dimensions(1280, 480));

	auto window = MercuryWindow::GetCurrentWindow();

	int width = window->CurrentWidth();
	int height = window->CurrentHeight();

	float projection[16];

	//left eye
	m_leftEyeVp.x = m_leftEyeVp.y = 0;
	m_leftEyeVp.width = width / 2;
	m_leftEyeVp.height = height;

	//right eye
	m_rightEyeVp.x = width / 2;
	m_rightEyeVp.y = 0;
	m_rightEyeVp.width = width / 2;
	m_rightEyeVp.height = height;

	double renderWidth = width / 2.0;
	double renderHeight = height;
	Perspective2(60, renderWidth / renderHeight, 0.1f, 100.0f, projection);
	m_projection.load(projection);

	return true;
}

void StereoCrossEye::Render(HgCamera* camera, RenderQueue* queue)
{
	HgCamera left_eye = *camera;
	left_eye.setWorldSpacePosition(ComputeStereoCameraPosition(left_eye, -EYE_DISTANCE * 0.5f));

	HgCamera right_eye = *camera;
	right_eye.setWorldSpacePosition(ComputeStereoCameraPosition(right_eye, EYE_DISTANCE * 0.5f));

	Renderer::Render(m_leftEyeVp, left_eye.toViewMatrix(), m_projection, queue); //eye 1
	Renderer::Render(m_rightEyeVp, right_eye.toViewMatrix(), m_projection, queue); //eye 2
}


text:
from reporter.core import SqlReport, Schedule
from reporter.emailing import RECIPIENT_IT_DWH
from reporter.uhl_reports.civicrm import get_contact_id_search_link

class BioresourceNotInRedcap(SqlReport):
    def __init__(self):
        super().__init__(
            introduction=("The following participants have "
                          "a record in CiviCRM, but do not have "
                          "a record in REDCap"),
            recipients=[RECIPIENT_IT_DWH],
            sql='''

SELECT  CONVERT(VARCHAR(100), bioresource_id) as bioresource_id
FROM    i2b2_app03_bioresource_Data.dbo.LOAD_Civicrm_Bioresource a
WHERE NOT EXISTS (
        SELECT  1
        FROM    i2b2_app03_bioresource_Data.dbo.LOAD_Redcap_Bioresource
        WHERE   bioresource_id = a.bioresource_id
            OR bioresource_id = a.legacy_bioresource_id
    ) AND NOT EXISTS (
        SELECT  1
        FROM    i2b2_app03_bioresource_Data.dbo.LOAD_Redcap_JointBriccs
        WHERE   bioresource_id = a.bioresource_id
    ) AND NOT EXISTS (
        SELECT  1
        FROM    i2b2_app03_bioresource_Data.dbo.LOAD_Civicrm_Interval
        WHERE   bioresource_id = a.bioresource_id
    )
    AND is_excluded = 0
    AND is_failed_to_respond = 0
    AND is_declined = 0
    AND is_recruitment_pending = 0
    AND is_duplicate = 0
    AND is_withdrawn = 0
    AND blank_study_id = 0

                ''',
            schedule=Schedule.never,
        )

    def get_report_line(self, row):
        return '- {}\r\n'.format(
            get_contact_id_search_link(
                row['bioresource_id'],
                row['bioresource_id'],
            )
        )


text:
import { NgModule } from '@angular/core'
import { RouterModule } from '@angular/router'

import { CommonModule } from '@balnc/common'
import { OverviewComponent } from './components/overview/overview.component'
import { ContactComponent } from './components/contact/contact.component'
import { WrapperComponent } from './components/_wrapper/wrapper.component'

import { ContactsService } from './contacts.service'
import { ContactsRoutes } from './contacts.routes'

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild(ContactsRoutes)
  ],
  declarations: [
    WrapperComponent,
    OverviewComponent,
    ContactComponent
  ],
  providers: [
    ContactsService
  ]
})
export class ContactsModule { }


text:
<?php
!isset($this->include_tag_hover_highlight) && $this->include_tag_hover_highlight = false;
!isset($this->include_tag_reverse_aliases) && $this->include_tag_reverse_aliases = false;
?>

<?= $this->t('.title') ?>

    <?php !empty($this->tags['exclude']) && print $this->tag_links($this->tags['exclude'], array('prefix' => '-', 'with_hover_highlight' => 'true', 'with_hover_highlight' => $this->include_tag_hover_highlight)) ?>
    <?php !empty($this->tags['include']) && print $this->tag_links($this->tags['include'], array('with_aliases' => $this->include_tag_reverse_aliases, 'with_hover_highlight' => $this->include_tag_hover_highlight)) ?>
    <?php !empty($this->tags['related']) && print $this->tag_links(Tag::find_related($this->tags['related']), array('with_hover_highlight' => 'true', 'with_hover_highlight' => $this->include_tag_hover_highlight)) ?>


text:
package tafit3.cplibrary;

import java.util.Arrays;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

import static java.util.Arrays.*;
import static java.util.stream.Collectors.*;

public class TestUtils {
    public static <T extends Comparable<T>> Comparator<List<T>> tupleComparator() {
        return (a, b) -> {
            Iterator<T> aIt = a.iterator();
            Iterator<T> bIt = b.iterator();
            while (aIt.hasNext() && bIt.hasNext()) {
                T x = aIt.next();
                T y = bIt.next();
                int res = x.compareTo(y);
                if (res > 0) {
                    return 1;
                } else if(res < 0) {
                    return -1;
                }
            }
            if(aIt.hasNext()) {
                return 1;
            }
            if(bIt.hasNext()) {
                return -1;
            }
            return 0;
        };
    }

    public static final Comparator<List<Integer>> INTEGER_TUPLE_COMPARATOR = tupleComparator();

    public static long newton(long n, long k) {
        return fac(n) / (fac(k)*fac(n-k));
    }

    public static long fac(long x) {
        long res = 1;
        for(long a=1;a<=x;a++) {
            res *= a;
        }
        return res;
    }

    public static List<Integer> convertToList(int[] a) {
        return stream(a).boxed().collect(toList());
    }

    public static void out(Object x) {
        System.out.println(x);
    }

    public static class Holder<T> {
        T object;
    }

    public static String ats(int[] x) {
        return Arrays.toString(x);
    }

    public static String ats(long[] x) {
        return Arrays.toString(x);
    }

    public static String ats(Object[] x) {
        return Arrays.deepToString(x);
    }

    public static long[] int2longArray(int[] a) {
        long[] res = new long[a.length];
        for(int i=0;i<a.length;i++) {
            res[i] = a[i];
        }
        return res;
    }
}


text:
layout: post
type: post
status: publish
tags:
- cd
- distro
- dvd
- fedora
- free
- kubuntu
- latest
- linux
- Non-technical
- request
- ubuntu
meta:
  _wpbitly: http://q.bibhas.in/Ha3NCr
  blogger_author: i Am Bibhashttp://www.blogger.com/profile/14301225485885111453noreply@blogger.com
  _edit_last: "1"
  blogger_blog: iambibhas.blogspot.com
  blogger_permalink: /2009/11/request-or-download-major-linux-distro.html
published: true
permalink: /blog/113/request-or-download-major-linux-distro-cds-absolutely-free/
title: Request or download major Linux distro CDs, absolutely Free.
---

This post is imported from an old blog of mine. But I've updated it. You can check it as a new post. :)

Want Linux Discs? All you need is an internet connection to make the request and/or a postal address. I'm assuming you have the both. :)

 Request CD
https://shipit.ubuntu.com/ (Ubuntu has stopped the Shipit service. You need to download it now.)

Download
http://www.ubuntu.com/getubuntu/download

 Request CD
https://shipit.kubuntu.com/(Same as Ubuntu. No CD, just Download.)

Download
http://www.kubuntu.org/getkubuntu

 Request CD
Its a bit tricky. First go here..
https://fedoraproject.org/freemedia/FreeMedia-form.html

The form is opened at the beginning of each month. If it says that the form is closed for this month, then find your nearest Fedora ambassador from here and mail them. They will surely attend you as soon as possible.

Download
http://fedoraproject.org/get-fedora

 Request CD
https://oscd.sun.com/

Download
http://www.opensolaris.com/get/index.jsp

Most of the distros are not available in postal delivery as it needs much maintenance.. But you can download them always..

Many More Downloadables..

Arch Linux

http://www.archlinux.org/download/

CentOS

http://www.centos.org/modules/tinycontent/index.php?id=15

Debian

http://www.debian.org/distrib/

Linux Mint

http://www.linuxmint.com/download.html

Mandriva

http://www2.mandriva.com/downloads/

OpenSUSE

http://software.opensuse.org/

Slackware

http://www.slackware.com/getslack/

Gentoo Linux

http://www.gentoo.org/main/en/where.xml

This is it for now. Keep checking my blog for more. ^_^


text:
namespace TomP2P.Core.P2P
{
    /// <summary>
    /// The handler that is called when a broadcast message is received.
    /// One way to implement this would be to send it to random peers.
    /// </summary>
    public interface IBroadcastHandler
    {
        /// <summary>
        /// This method is called when a peer receives a broadcast message request.
        /// It is up to the peer to decide what to do with it.
        /// </summary>
        /// <param name="message"></param>
        void Receive(Message.Message message);
    }
}


text:
path: src/branch/main
source: src/cli/main.ts
---

# Command line interface
The easy way. From a command prompt with administrator privileges, install the `coveralls` executable:

``` shell
npm install --global @cedx/coveralls
```

!!! tip
	Consider adding the [`npm install --global`](https://docs.npmjs.com/files/folders) executables directory to your system path.

Then use it to upload your coverage reports:

``` shell
$ coveralls --help

Usage: coveralls [options] <file>

Send a coverage report to the Coveralls service.

Options:

	-h, --help         output usage information
	-v, --version      output the version number
```

For example:

``` shell
coveralls build/lcov.info
```


text:
/*
 * Generated by XDoclet - Do not edit!
 */
package org.dcm4chex.archive.ejb.interfaces;

/**
 * Local home interface for PublishedStudy.
 * @xdoclet-generated at ${TODAY}
 * @copyright The XDoclet Team
 * @author XDoclet
 * @version 2.19.0-SNAPSHOT
 */
public interface PublishedStudyLocalHome
   extends javax.ejb.EJBLocalHome
{
   public static final String COMP_NAME="java:comp/env/ejb/PublishedStudyLocal";
   public static final String JNDI_NAME="ejb/PublishedStudy";

   public org.dcm4chex.archive.ejb.interfaces.PublishedStudyLocal create(org.dcm4chex.archive.ejb.interfaces.StudyLocal study , java.lang.String docUID , java.lang.String docEntryUID , java.lang.String repoUID)
      throws javax.ejb.CreateException;

   public java.util.Collection findByStudyPkAndStatus(long studyPk, int status)
      throws javax.ejb.FinderException;

   public java.util.Collection findByStudyIUID(java.lang.String suid)
      throws javax.ejb.FinderException;

   public java.util.Collection findByStudyIUIDAndStatus(java.lang.String suid, int status)
      throws javax.ejb.FinderException;

   public org.dcm4chex.archive.ejb.interfaces.PublishedStudyLocal findByPrimaryKey(java.lang.Long pk)
      throws javax.ejb.FinderException;

}


text:
function Test()
	-- Test for a clean directory.
	local originalFiles =
	{
		'Jamfile.jam',
		'common/common.jam',
		'common/print.cpp',
		'common/print.h',
		'libA/libA.cpp',
		'libA/libA.jam',
		'project1/project1.cpp',
		'project1/project1.jam',
	}

	local originalDirs =
	{
		'common/',
		'libA/',
		'project1/',
	}

	RunJam{ 'clean' }
	TestDirectories(originalDirs)
	TestFiles(originalFiles)

	if Platform == 'win32' then
		-- First build
		local pattern = [[
*** found 26 target(s)...
*** updating 9 target(s)...
@ C.$(COMPILER).C++ <$(TOOLCHAIN_GRIST):project1>project1.obj
!NEXT!@ C.$(COMPILER).C++ <$(TOOLCHAIN_GRIST):common>print.obj
!NEXT!@ $(C_ARCHIVE) <$(TOOLCHAIN_GRIST):common>common.lib
!NEXT!@ C.$(COMPILER).C++ <$(TOOLCHAIN_GRIST):libA>libA.obj
!NEXT!@ $(C_ARCHIVE) <$(TOOLCHAIN_GRIST):libA>libA.lib
!NEXT!@ $(C_LINK) <$(TOOLCHAIN_GRIST):project1>project1.exe
!NEXT!*** updated 9 target(s)...
]]

		TestPattern(pattern, RunJam())

		local pass1Files =
		{
			'Jamfile.jam',
			'common/common.jam',
			'common/print.cpp',
			'common/print.h',
			'$(TOOLCHAIN_PATH)/common/common/common.release.lib',
			'$(TOOLCHAIN_PATH)/common/common/print.obj',
			'libA/libA.cpp',
			'libA/libA.jam',
			'$(TOOLCHAIN_PATH)/libA/libA/libA.obj',
			'$(TOOLCHAIN_PATH)/libA/libA/libA.release.lib',
			'project1/project1.cpp',
			'project1/project1.jam',
			'$(TOOLCHAIN_PATH)/project1/project1/project1.obj',
			'$(TOOLCHAIN_PATH)/project1/project1/project1.release.exe',
			'?$(TOOLCHAIN_PATH)/project1/project1/project1.release.exe.intermediate.manifest',
			'$(TOOLCHAIN_PATH)/project1/project1/project1.release.pdb',
		}

		local pass1Directories = {
			'common/',
			'libA/',
			'project1/',
			'$(TOOLCHAIN_PATH)/',
			'$(TOOLCHAIN_PATH)/common/common/',
			'$(TOOLCHAIN_PATH)/libA/libA/',
			'$(TOOLCHAIN_PATH)/project1/project1/',
		}

		TestFiles(pass1Files)
		TestDirectories(pass1Directories)

		local pattern2 = [[
*** found 26 target(s)...
]]
		TestPattern(pattern2, RunJam())
	else
		-- First build
		local pattern = [[
*** found 18 target(s)...
*** updating 9 target(s)...
@ C.$(COMPILER).C++ <$(TOOLCHAIN_GRIST):project1>project1.o
@ C.$(COMPILER).C++ <$(TOOLCHAIN_GRIST):common>print.o
@ $(C_ARCHIVE) <$(TOOLCHAIN_GRIST):common>common.a
@ C.$(COMPILER).C++ <$(TOOLCHAIN_GRIST):libA>libA.o
@ $(C_ARCHIVE) <$(TOOLCHAIN_GRIST):libA>libA.a
@ $(C_LINK) <$(TOOLCHAIN_GRIST):project1>project1
*** updated 9 target(s)...
]]

		TestPattern(pattern, RunJam())

		local pass1Directories = {
			'common/',
			'libA/',
			'project1/',
			'$(TOOLCHAIN_PATH)/',
			'$(TOOLCHAIN_PATH)/common/common/',
			'$(TOOLCHAIN_PATH)/libA/libA/',
			'$(TOOLCHAIN_PATH)/project1/project1/',
		}

		local pass1Files =
		{
			'Jamfile.jam',
			'test.lua',
			'common/common.jam',
			'common/print.cpp',
			'common/print.h',
			'$(TOOLCHAIN_PATH)/common/common/common.release.a',
			'$(TOOLCHAIN_PATH)/common/common/print.o',
			'libA/libA.cpp',
			'libA/libA.jam',
			'$(TOOLCHAIN_PATH)/libA/libA/libA.o',
			'$(TOOLCHAIN_PATH)/libA/libA/libA.release.a',
			'project1/project1.cpp',
			'project1/project1.jam',
			'$(TOOLCHAIN_PATH)/project1/project1/project1.o',
			'$(TOOLCHAIN_PATH)/project1/project1/project1.release',
		}

		TestFiles(pass1Files)
		TestDirectories(pass1Directories)

		local pattern2 = [[
*** found 18 target(s)...
]]
		TestPattern(pattern2, RunJam())
	end

	osprocess.sleep(1.0)
	ospath.touch('common/print.h')

	if Platform == 'win32' then
		local pattern3 = [[
*** found 26 target(s)...
*** updating 4 target(s)...
@ C.$(COMPILER).C++ <$(TOOLCHAIN_GRIST):project1>project1.obj
!NEXT!@ C.$(COMPILER).C++ <$(TOOLCHAIN_GRIST):libA>libA.obj
!NEXT!@ $(C_ARCHIVE) <$(TOOLCHAIN_GRIST):libA>libA.lib
!NEXT!@ $(C_LINK) <$(TOOLCHAIN_GRIST):project1>project1.exe
!NEXT!*** updated 4 target(s)...
]]
		TestPattern(pattern3, RunJam())
	else
		local pattern3 = [[
*** found 18 target(s)...
*** updating 4 target(s)...
@ C.$(COMPILER).C++ <$(TOOLCHAIN_GRIST):project1>project1.o
@ C.$(COMPILER).C++ <$(TOOLCHAIN_GRIST):libA>libA.o
@ $(C_ARCHIVE) <$(TOOLCHAIN_GRIST):libA>libA.a
@ $(C_LINK) <$(TOOLCHAIN_GRIST):project1>project1
*** updated 4 target(s)...
]]
		TestPattern(pattern3, RunJam())
	end

	RunJam{ 'clean' }
	TestDirectories(originalDirs)
	TestFiles(originalFiles)
end


text:
package com.hue.translator.sql.formatter;

import java.util.ArrayList;
import java.util.List;

import com.facebook.presto.sql.tree.Expression;
import com.facebook.presto.sql.tree.FrameBound;
import com.facebook.presto.sql.tree.FunctionCall;
import com.facebook.presto.sql.tree.Window;
import com.facebook.presto.sql.tree.WindowFrame;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.vero.common.constant.DBType;

import static com.vero.server.engine.sql.formatter.VeroFunctions.*;

public class VeroRedshiftExpFormatter extends VeroGenExpFormatter
{
    public VeroRedshiftExpFormatter() { _formatterType = DBType.REDSHIFT; }

    public void setSqlFormatter(VeroGenSqlFormatter sqlFormatter) {
        super.setSqlFormatter(sqlFormatter);
    }

    public String formatExpression(Expression expression)
    {
        return new Formatter().process(expression, null);
    }

    public Function<Expression, String> expressionFormatterFunction()
    {
        return new Function<Expression, String>()
        {
            @Override
            public String apply(Expression input)
            {
                return formatExpression(input);
            }
        };
    }

    public class Formatter
            extends VeroGenExpFormatter.Formatter
    {
	private String windowFunctionName = null;

        @Override
        protected String visitFunctionCall(FunctionCall node, Void context)
        {
            StringBuilder builder = new StringBuilder();
            String functionName = getFunctionName(node);

            int numArguments = node.getArguments().size();
            String arguments = joinExpressions(node.getArguments());
            if (node.getArguments().isEmpty() && "count".equalsIgnoreCase(node.getName().getSuffix())) {
                arguments = "*";
            }
            if (node.isDistinct()) {
                arguments = "DISTINCT " + arguments;
            }

            if (functionName.equals("concat")) {
                builder.append(joinExpressions(" || ", node.getArguments()));
            } else if (functionName.equals("sinh")) {
                builder.append(processFuncSinh(this, node));
            } else if (functionName.equals("cosh")) {
                builder.append(processFuncCosh(this, node));
            } else if (functionName.equals("tanh")) {
                builder.append(processFuncTanh(this, node, getFormatterType()));
            } else if (functionName.equals("acosh")) {
                builder.append(processFuncAcosh(this, node));
            } else if (functionName.equals("asinh")) {
                builder.append(processFuncAsinh(this, node));
            } else if (functionName.equals("atanh")) {
                builder.append(processFuncAtanh(this, node));
            } else if (functionName.equals("atan2") && (numArguments==2)) {
                builder.append("atan2").append('(').append(node.getArguments().get(1)).append(", ").append(node.getArguments().get(0)).append(')');
            } else if (functionName.equals("nullifzero")) {
                builder.append("nullif").append('(').append(arguments).append(", 0").append(')');
            } else if (functionName.equals("zeroifnull")) {
                builder.append("coalesce").append('(').append(arguments).append(", 0").append(')');
            } else if (functionName.equals("substr")) {
                if (numArguments==2) {
                    builder.append("substring").append('(').append(node.getArguments().get(0)).append(", ").append(node.getArguments().get(1))
                    .append(", ").append("len").append('(').append(process(node.getArguments().get(0), null)).append(')').append(')');
                } else {
                    builder.append("substring").append('(').append(arguments).append(')');
                }
            } else {
                if (node.getWindow().isPresent()) {
                    //System.out.println("WindowFuncName: " + getFunctionName(node));
                    windowFunctionName = getFunctionName(node);
                }

                // use super
                return super.visitFunctionCall(node, context);
            }

            if (node.getWindow().isPresent()) {
                builder.append(" OVER ").append(visitWindow(node.getWindow().get(), null));
            }

            return builder.toString();
        }

        @Override
        public String visitWindow(Window node, Void context)
        {
            List<String> parts = new ArrayList<>();

            if (!node.getPartitionBy().isEmpty()) {
                parts.add("PARTITION BY " + joinExpressions(node.getPartitionBy()));
            }
            if (!node.getOrderBy().isEmpty()) {
                parts.add("ORDER BY " + formatSortItems(node.getOrderBy()));
            }
            if (node.getFrame().isPresent()) {
                parts.add(process(node.getFrame().get(), null));
            } else {
                if (!windowFunctionName.equalsIgnoreCase("rank")) {
                    if (!node.getOrderBy().isEmpty()) {
            			// Redshift needs to specify frame explicitly if there is order by and the function is not rank()
            			FrameBound fb = new FrameBound(FrameBound.Type.UNBOUNDED_PRECEDING);
            			WindowFrame wf = new WindowFrame(WindowFrame.Type.ROWS, fb, null);
            			parts.add(process(wf, null));
        			}
        		}
            }

            return '(' + Joiner.on(' ').join(parts) + ')';
        }
    }
}


text:
#include <QtDebug>
#include <QNetworkRequest>
#include <QNetworkReply>
#include "qtweetstatusupdate.h"
#include "qtweetstatus.h"
#include "qtweetgeocoord.h"
#include "qtweetconvert.h"
#include "json/qjsondocument.h"
#include "json/qjsonobject.h"

QTweetStatusUpdate::QTweetStatusUpdate(QObject *parent) :
    QTweetNetBase(parent)
{
}

QTweetStatusUpdate::QTweetStatusUpdate(OAuthTwitter *oauthTwitter, QObject *parent) :
        QTweetNetBase(oauthTwitter, parent)
{
}

/**
 *   Posts a tweet
 *   @param status text of the status update
 *   @param inReplyToStatus ID of a existing tweet is in reply to
 *   @param latLong latitude and longitude
 *   @param placeid a place in the world (use reverse geocoding)
 *   @param displayCoordinates whether or not to put a exact coordinates a tweet has been sent from
 */
void QTweetStatusUpdate::post(const QString &status,
                              qint64 inReplyToStatus,
                              const QTweetGeoCoord& latLong,
                              const QString &placeid,
                              bool displayCoordinates,
                              bool trimUser,
                              bool includeEntities)
{
    if (!isAuthenticationEnabled()) {
        qCritical("Needs authentication to be enabled");
        return;
    }

    QUrl url("https://api.twitter.com/1.1/statuses/update.json");

    QUrl urlQuery("https://api.twitter.com/1.1/statuses/update.json");

    urlQuery.addEncodedQueryItem("status", QUrl::toPercentEncoding(status));

    if (inReplyToStatus != 0)
        urlQuery.addQueryItem("in_reply_to_status_id", QString::number(inReplyToStatus));

    if (latLong.isValid()) {
        urlQuery.addQueryItem("lat", QString::number(latLong.latitude()));
        urlQuery.addQueryItem("long", QString::number(latLong.longitude()));
    }

    if (!placeid.isEmpty())
        urlQuery.addQueryItem("place_id", placeid);

    if (displayCoordinates)
        urlQuery.addQueryItem("display_coordinates", "true");

    if (trimUser)
        urlQuery.addQueryItem("trim_user", "true");

    if (includeEntities)
        urlQuery.addQueryItem("include_entities", "true");

    QByteArray oauthHeader = oauthTwitter()->generateAuthorizationHeader(urlQuery, OAuth::POST);
    QNetworkRequest req(url);
    req.setRawHeader(AUTH_HEADER, oauthHeader);
    req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");

    //build status post array
    QByteArray statusPost = urlQuery.toEncoded(QUrl::RemoveScheme | QUrl::RemoveAuthority | QUrl::RemovePath);

    //remove '?'
    statusPost.remove(0, 1);

    QNetworkReply *reply = oauthTwitter()->networkAccessManager()->post(req, statusPost);
    connect(reply, SIGNAL(finished()), this, SLOT(reply()));
}

void QTweetStatusUpdate::parseJsonFinished(const QJsonDocument &jsonDoc)
{
    if (jsonDoc.isObject()) {
        QTweetStatus status = QTweetConvert::jsonObjectToStatus(jsonDoc.object());

        emit postedStatus(status);
    }
}


text:
// Copyright (c) 2003-2014, Jodd Team (jodd.org). All Rights Reserved.

/**
 * Generic DAO.
 */
package jodd.db.oom.dao;


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.applicationinsights.generated;

import com.azure.core.util.Context;
import com.azure.resourcemanager.applicationinsights.models.Kind;
import com.azure.resourcemanager.applicationinsights.models.MyWorkbook;

/** Samples for MyWorkbooks Update. */
public final class MyWorkbooksUpdateSamples {
    /*
     * x-ms-original-file: specification/applicationinsights/resource-manager/Microsoft.Insights/stable/2021-03-08/examples/MyWorkbookUpdate.json
     */
    /**
     * Sample code: WorkbookUpdate.
     *
     * @param manager Entry point to ApplicationInsightsManager.
     */
    public static void workbookUpdate(
        com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager manager) {
        MyWorkbook resource =
            manager
                .myWorkbooks()
                .getByResourceGroupWithResponse(
                    "my-resource-group", "deadb33f-5e0d-4064-8ebb-1a4ed0313eb2", Context.NONE)
                .getValue();
        resource
            .update()
            .withKind(Kind.USER)
            .withDisplayName("Blah Blah Blah")
            .withSerializedData(
                "{\"version\":\"Notebook/1.0\",\"items\":[{\"type\":1,\"content\":\"{\"json\":\"## New workbook\\r"
                    + "\\n"
                    + "---\\r"
                    + "\\n"
                    + "\\r"
                    + "\\n"
                    + "Welcome to your new workbook.  This area will display text formatted as markdown.\\r"
                    + "\\n"
                    + "\\r"
                    + "\\n"
                    + "\\r"
                    + "\\n"
                    + "We've included a basic analytics query to get you started. Use the `Edit` button below each"
                    + " section to configure it or add more"
                    + " sections.\"}\",\"halfWidth\":null,\"conditionalVisibility\":null},{\"type\":3,\"content\":\"{\"version\":\"KqlItem/1.0\",\"query\":\"union"
                    + " withsource=TableName *\\n"
                    + "| summarize Count=count() by TableName\\n"
                    + "| render"
                    + " barchart\",\"showQuery\":false,\"size\":1,\"aggregation\":0,\"showAnnotations\":false}\",\"halfWidth\":null,\"conditionalVisibility\":null}],\"isLocked\":false}")
            .withVersion("ME")
            .withCategory("workbook")
            .withSourceId(
                "/subscriptions/00000000-0000-0000-0000-00000000/resourceGroups/MyGroup/providers/Microsoft.Web/sites/MyTestApp-CodeLens")
            .apply();
    }
}


text:
"""
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.

"""

import os

#Used in subsequent imports from params
from resource_management.libraries.script.script import Script
from resource_management.libraries.functions.default import default
from resource_management.libraries.functions.format import format
from install_params import exclude_packages
from status_params import *

config = Script.get_config()
hadoop_conf_dir = None
hbase_conf_dir = None
hadoop_home = None
try:
  hadoop_conf_dir = os.environ["HADOOP_CONF_DIR"]
  hbase_conf_dir = os.environ["HBASE_CONF_DIR"]
  hadoop_home = os.environ["HADOOP_HOME"]
except:
  pass
#directories & files
dfs_name_dir = config['configurations']['hdfs-site']['dfs.namenode.name.dir']
fs_checkpoint_dir = config['configurations']['hdfs-site']['dfs.namenode.checkpoint.dir']
dfs_data_dir = config['configurations']['hdfs-site']['dfs.datanode.data.dir']
#decomission
hdfs_exclude_file = default("/clusterHostInfo/decom_dn_hosts", [])
exclude_file_path = config['configurations']['hdfs-site']['dfs.hosts.exclude']
include_file_path = default("/configurations/hdfs-site/dfs.hosts", None)
hdfs_include_file = None
manage_include_files = default("/configurations/hdfs-site/manage.include.files", False)
if include_file_path and manage_include_files:
  slave_hosts = default("/clusterHostInfo/slave_hosts", [])
  hdfs_include_file = slave_hosts
update_files_only = default("/commandParams/update_files_only",False)
# HDFS High Availability properties
dfs_ha_enabled = False
dfs_ha_nameservices = default("/configurations/hdfs-site/dfs.internal.nameservices", None)
dfs_ha_namenode_ids = default(format("/configurations/hdfs-site/dfs.ha.namenodes.{dfs_ha_nameservices}"), None)

namenode_id = None
namenode_rpc = None
hostname = config["hostname"]
if dfs_ha_namenode_ids:
  dfs_ha_namemodes_ids_list = dfs_ha_namenode_ids.split(",")
  dfs_ha_namenode_ids_array_len = len(dfs_ha_namemodes_ids_list)
  if dfs_ha_namenode_ids_array_len > 1:
    dfs_ha_enabled = True
if dfs_ha_enabled:
  for nn_id in dfs_ha_namemodes_ids_list:
    nn_host = config['configurations']['hdfs-site'][format('dfs.namenode.rpc-address.{dfs_ha_nameservices}.{nn_id}')]
    if hostname in nn_host:
      namenode_id = nn_id
      namenode_rpc = nn_host

hadoop_user = config["configurations"]["cluster-env"]["hadoop.user.name"]
hdfs_user = hadoop_user

grep_exe = "findstr"

name_node_params = default("/commandParams/namenode", None)

service_map = {
  "datanode" : datanode_win_service_name,
  "journalnode" : journalnode_win_service_name,
  "namenode" : namenode_win_service_name,
  "secondarynamenode" : snamenode_win_service_name,
  "zkfc_slave": zkfc_win_service_name
}


text:
import template from './app.html';

import './app.scss';

class AppController {
  constructor() {
    'ngInject';
  }
}

export default {
  template,
  controller: AppController
};


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Source code</title>
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

001package io.ebean.config;
002
003import java.util.Properties;
004
005public class PropertiesWrapper {
006
007  protected final Properties properties;
008
009  protected final String prefix;
010
011  protected final String serverName;
012
013  private final ClassLoadConfig classLoadConfig;
014
015  /**
016   * Construct with a prefix, serverName and properties.
017   */
018  public PropertiesWrapper(String prefix, String serverName, Properties properties, ClassLoadConfig classLoadConfig) {
019    this.serverName = serverName;
020    this.prefix = prefix;
021    this.properties = properties;
022    this.classLoadConfig = classLoadConfig;
023  }
024
025  /**
026   * Construct without prefix of serverName.
027   */
028  public PropertiesWrapper(Properties properties, ClassLoadConfig classLoadConfig) {
029    this(null, null, properties, classLoadConfig);
030  }
031
032  /**
033   * Return the serverName (optional).
034   */
035  public String getServerName() {
036    return serverName;
037  }
038
039  /**
040   * Get a property with no default value.
041   */
042  public String get(String key) {
043    return get(key, null);
044  }
045
046  /**
047   * Get a property with a default value.
048   * <p>
049   * This performs a search using the prefix and server name (if supplied) to search for the property
050   * value in order based on:
051   * <pre>{@code
052   *   prefix.serverName.key
053   *   prefix.key
054   *   key
055   * }</pre>
056   * </p>
057   */
058  public String get(String key, String defaultValue) {
059
060    String value = null;
061    if (serverName != null && prefix != null) {
062      value = internalGet(prefix + "." + serverName + "." + key);
063    }
064    if (value == null && prefix != null) {
065      value = internalGet(prefix + "." + key);
066    }
067    if (value == null) {
068      value = internalGet(key);
069    }
070    return value == null ? defaultValue : value;
071  }
072
073  private String internalGet(String key) {
074    return properties.getProperty(key);
075  }
076
077  /**
078   * Return a double property value.
079   */
080  public double getDouble(String key, double defaultValue) {
081
082    String value = get(key, String.valueOf(defaultValue));
083    return Double.parseDouble(value);
084  }
085
086  /**
087   * Return an int property value.
088   */
089  public int getInt(String key, int defaultValue) {
090
091    String value = get(key, String.valueOf(defaultValue));
092    return Integer.parseInt(value);
093  }
094
095  /**
096   * Return a long property value.
097   */
098  public long getLong(String key, long defaultValue) {
099
100    String value = get(key, String.valueOf(defaultValue));
101    return Long.parseLong(value);
102  }
103
104  /**
105   * Return a boolean property value.
106   */
107  public boolean getBoolean(String key, boolean defaultValue) {
108
109    String value = get(key, String.valueOf(defaultValue));
110    return Boolean.parseBoolean(value);
111  }
112
113  /**
114   * Return a Enum property value.
115   */
116  public <T extends Enum<T>> T getEnum(Class<T> enumType, String key, T defaultValue) {
117    String level = get(key, null);
118    return (level == null) ? defaultValue : Enum.valueOf(enumType, level.toUpperCase());
119  }
120
121  /**
122   * Return the instance to use (can be null) for the given plugin.
123   *
124   * @param pluginType the type of plugin
125   * @param key        properties key
126   * @param instance   existing instance
127   */
128  public <T> T createInstance(Class<T> pluginType, String key, T instance) {
129
130    if (instance != null) {
131      return instance;
132    }
133    String classname = get(key, null);
134    return createInstance(pluginType, classname);
135  }
136
137  /**
138   * Return the instance to use (can be null) for the given plugin.
139   *
140   * @param pluginType the type of plugin
141   * @param classname  the implementation class as per properties
142   */
143  @SuppressWarnings("unchecked")
144  public <T> T createInstance(Class<T> pluginType, String classname) {
145    return classname == null ? null : (T) classLoadConfig.newInstance(classname);
146  }
147}


text:
import pygame

class Singleton(object):
    _instances = {}

    def __new__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = object.__new__(cls, *args, **kwargs)
        return cls._instances[cls]

# Any class can use this by importing uimgr and getting an instance of the manager.
# I know the singleton stuff is weird, but just call uimgr.UIManager() to get this instance
class UIManager(Singleton):

    # has a position, size, background, border, on/off switch for rendering
    # usually you don't use these (you can though) everything else subclasses it.
    class UIElement(object):
        def __init__(self, rect, bgColor = None, borderColor = None, borderSize = 5):
            self.rect = rect
            self.offset = (0,0)
            self.position = (rect[0], rect[1])
            self.size = (rect[2], rect[3])
            self.bgColor = bgColor
            self.borderColor = borderColor
            self.parent = None # changes when placed in a container
            self.fullLoc = None # updated when parent exists
            self.enabled = True
            self.bSize = borderSize

        def setEnabled(self, state):
            self.enabled = state

        def getFullLocation(self):
            if self.parent is None:
                return self.rect
            else:
                pRect = self.parent.getFullLocation()
                pX = pRect[0]
                pY = pRect[1]

                sX = self.position[0]
                sY = self.position[1]
                sW = self.size[0]
                sH = self.size[1]

                newX = pX + sX
                newY = pY + sY
                return (newX,newY,sW,sH)

        def moveTo(self, position):
            self.rect = (position[0], position[1], self.rect[2], self.rect[3])

        def render(self, surface):
            if self.bgColor is not None:
                pygame.draw.rect(surface, self.bgColor, self.rect)

            if self.borderColor is not None:
                pygame.draw.rect(surface, self.borderColor, self.rect, self.bSize)

    class Image(UIElement):
        def __init__(self, position, spriteSrc, sizeMod = 1, spriteSheet = False, numSprites = 1):
            self.image = pygame.image.load(spriteSrc).convert()
            self.position = position
            self.isSpriteSheet = spriteSheet
            if spriteSheet:
                size = self.image.get_size()
                self.spriteWidth = size[0]/numSprites
                self.spriteHeight = size[1]
                self.spriteNum = 0

            self.setMod(sizeMod)
            super(type(self),self).__init__(self.rect)

        def setMod(self, mod):
            self.mod = mod
            self.scaleImage()
            self.setRect()

        def setRect(self):
            x = self.position[0]
            y = self.position[1]
            size = self.scaledImg.get_size()
            self.rect = (x,y,size[0],size[1])

        def scaleImage(self):
            if self.isSpriteSheet:
                size = (self.spriteWidth, self.spriteHeight)
                sprite = pygame.Surface(size).convert()
                sprite.blit(self.image,(0,0),(self.spriteNum*self.spriteWidth,0,size[0],size[1]))
                self.scaledImg = pygame.transform.scale(sprite,(int(size[0]*self.mod),int(size[1]*self.mod)))
            else:
                size = self.image.get_size()
                self.scaledImg = pygame.transform.scale(self.image,(int(size[0]*self.mod),int(size[1]*self.mod)))
            self.scaledImg.set_colorkey((0,0,0))

        def renderSprite(self, surface, spriteNum, reverse = False):
            self.spriteNum = spriteNum
            self.scaleImage()
            super(type(self),self).render(surface)
            if reverse:
                flipped = pygame.transform.flip(self.scaledImg,True,False) # flip on X axis
                surface.blit(flipped, self.rect)
            else:
                surface.blit(self.scaledImg, self.rect)

        def render(self, surface):
            super(type(self),self).render(surface)
            surface.blit(self.scaledImg, self.rect)

    # Text element
    class Text(UIElement):
        def __init__(self, position, text, color, size):
            self.font = pygame.font.SysFont("arial", size)
            self.text = text
            self.fontSize = size
            self.color = color
            self.position = position

            self.rText = self.preRender() # sets the self.rect attr

            super(type(self),self).__init__((position[0],position[1],self.width,self.height))

        def preRender(self):
            self.width, self.height = self.font.size(self.text)
            renderedText = self.font.render(self.text, 0, self.color)
            return renderedText

        def setText(self, text):
            self.text = text
            self.rText = self.preRender()

        def render(self, surface):
            super(type(self),self).render(surface)
            surface.blit(self.rText, self.rect)

    # Used for grouping things
    class Container(UIElement):
        def __init__(self, rect, bgColor = None, borderColor = None):
            super(type(self),self).__init__(rect,bgColor,borderColor)
            self.children = []

        #Has an optional return value if u want the index ID to get it later.
        def addChild(self, ele):
            self.children.append(ele)
            ele.parent = self
            self.offsetChild(ele)
            return self.children.index(ele)

        def offsetChild(self, ele):
            ele.offset = (self.offset[0]+self.position[0],self.offset[1]+self.position[1])
            ele.rect = (ele.offset[0]+ele.position[0],ele.offset[1]+ele.position[1],ele.size[0],ele.size[1])

            if hasattr(ele, 'children'):
                for i in range (0,len(ele.children)):
                    ele.offsetChild(ele.children[i])

        def child(self, ID):
            return self.children[ID]

        def render(self,surface):
            super(type(self),self).render(surface)
            for i in range(0,len(self.children)):
                self.children[i].render(surface)

#End UIManager