<commit_before>/**
  * @constructor
  * @extends BaseEditor
  */

var DOMMarkupEditor = function()
{
  this.base_init(this);
  this.type = "dom-markup-editor";
  // specific context
  this.context_enter =
  {
    rt_id: '',
    obj_id: '',
    parent_obj_id: '',
    outerHTML: '',
    host_target: ''
  }

  this.context_cur =
  {
    rt_id: '',
    obj_id: '',
    parent_obj_id: '',
    outerHTML: '',
    host_target: ''
  }

  this.edit = function(event, ref_ele)
  {
    var
    ele = ref_ele || event.target,
    rt_id = ele.parentElement.parentElement.getAttribute('rt-id'),
    obj_id = ele.parentElement.getAttribute('ref-id'),
    script = '',
    tag = '',
    prop = '',
    container = ele;

    while( container
            && !/container/.test(container.nodeName)
            && ( container = container.parentElement ) );
    if(container)
    {
      container.firstChild.style.position = 'relative';
      container.firstChild.render(['fade-out']);
      this.context_enter =
      {
        rt_id: rt_id,
        obj_id: obj_id,
        parent_obj_id: dom_data.getParentElement(obj_id),
        outerHTML: '',
        host_target: ''
      };
      this.context_cur = {};
      for( prop in this.context_enter )
      {
        this.context_cur[prop] = this.context_enter[prop];
      }
      script = this["return new Host_updater(target)"];
      tag = tagManager.setCB(this, this.register_host_updater, [rt_id]);
      services['ecmascript-debugger'].eval( tag, rt_id, '', '', script, ['target', obj_id]);
      tag = tagManager.setCB(this, this.handle_get_outer_html, [rt_id, obj_id, ele, event])
      services['ecmascript-debugger'].inspectDOM( tag, obj_id, 'subtree', 'json' );
    }
  }

  this.oninput = function(event)
  {
    var
    script = "",
    state = this.context_cur;

    if( this.textarea_container.parentElement && state.host_target )
    {
      this.set_textarea_dimensions();
      state.outerHTML = this.textarea.value;
      var script = "host_target.outerHTML = '" + encode(state.outerHTML) + "';";
      services['ecmascript-debugger'].eval
      (
        0, state.rt_id, '', '', script, ['host_target', state.host_target]
      );
    }
  }

  this.submit = function()
  {
    // return a valid navigation target or null
    var
    state = this.context_cur,
    nav_target = this.textarea_container.parentElement;

    if(nav_target)
    {
      var tag = tagManager.setCB(this, this.on_exit_edit, [state, nav_target]);
      var script = "host_target.exit_edit()";
      services['ecmascript-debugger'].eval
      (
        tag, state.rt_id, '', '', script, ['host_target', state.host_target]
      );
    }
    return nav_target;
  }

  this.cancel = function()
  {
    // return a valid navigation target or null
    var
    script = "",
    state = this.context_enter,
    nav_target = this.textarea_container.parentElement;

    if( nav_target )
    {
      if(state.outerHTML != this.context_cur.outerHTML)
      {
        var tag = tagManager.setCB(this, this.on_exit_edit, [state, nav_target]);
        var script = "host_target.cancel_edit()";
        services['ecmascript-debugger'].eval
        (
          tag, state.rt_id, '', '', script, ['host_target', state.host_target]
        );
      }
    }
    return nav_target;
  }

  this.nav_next = function()
  {
    var
    val = this.textarea.value,
    start = this.textarea.selectionStart,
    end = this.textarea.selectionEnd,
    indent = '  ';

    this.textarea.value = val.slice(0, start) + indent +  val.slice(end);
    this.textarea.selectionStart = start + indent.length;
    this.textarea.selectionEnd = start + indent.length;
  }

  this.set_textarea_dimensions = function()
  {
    this.textarea.style.height = this.textarea.scrollHeight + 'px';
  }

  this.__is_active = function()
  {
    return this.context_enter && this.context_enter.host_target && true || false;
  }

  // could be the default method?
  this.onclick = function(event)
  {
    event.preventDefault();
    event.stopPropagation();
    if(!this.textarea_container.contains(event.target))
    {
      this.submit(true);
      return false;
    }
    return true;
  }

  // helpers

  this.on_exit_edit = function(xml, state, nav_target)
  {
    if( xml.getNodeData('status') == 'completed' )
    {
      // to remove the textarea_container from the dom
      nav_target.textContent = "";
      this.context_cur = this.context_enter = null;
      dom_data.closeNode(state.parent_obj_id, true);
      dom_data.getChildernFromNode(state.parent_obj_id);
    }
    else
    {
      opera.postError('exit markup edit failed in DOMMarkupEditor');
    }
  };

  var encode = function(str)
  {
    return str.replace(/\u200F\r\n/g, "").replace(/\r\n/g, "\\n").replace(/'/g, "\\'");
  };

  // class on the host side to update the given DOM range
  var Host_updater = function(target)
  {
    var
    range_target = document.createRange(),
    timeout = 0,
    new_str = '',
    enter_node = null,
    update = function(str)
    {
      if( enter_node )
      {
        range_target.deleteContents();
      }
      else
      {
        enter_node = range_target.extractContents();
      };
      var range_source = document.createRange();
      var temp = null;
      if( document.documentElement )
      {
        temp = document.createElement('df-temp-element');
        ( document.body || document.documentElement ).appendChild(temp);
        temp.innerHTML = new_str;
      }
      else
      {
        var new_source = lexer.lex(new_str), tag = new_source[0];

        if(tag)
        {
          var attrs = tag[2], i = 0, attr = null;
          for( ; ( attr = attrs[i] ) && attr[0] != 'xmlns'; i++);
          if( attr )
          {
            attrs.splice(i, 1);
            temp = document.createElementNS(attr[1], tag[1]);
          }
          else
          {
            temp = document.createElement(tag[1]);
          }
          for( i = 0 ; attr = attrs[i]; i++)
          {
            temp.setAttribute(attr[0], attr[1]);
          }
          document.appendChild(temp);
          temp.innerHTML = new_source[1];
        }
      };
      var first = temp.firstChild;
      var last = temp.lastChild;
      if(first)
      {
        if( temp == document.documentElement )
        {
          range_target.selectNode(document.documentElement);
        }
        else
        {
          range_source.selectNodeContents(temp);
          var fragment = range_source.extractContents();
          range_target.insertNode(fragment);
          range_target.setStartBefore(first);
          range_target.setEndAfter(last);
        }
      };
      if(temp.parentElement)
      {
        temp.parentNode.removeChild(temp);
      };
      timeout = 0;
    },
    lexer = new function()
    {
      /* adjusted to get only the first tag */
      const TEXT = 'TEXT', TAG = 'TAG';
      var
      source = '',
      cur = '',
      pos = 0,
      text = function()
      {
        var ret = [], buffer = '', _tag = null;
        while( cur )
        {
          if( cur == '<' )
          {
            cur = source.charAt(pos++);
            if(buffer)
            {
              ret[ret.length] = [TEXT, buffer];
              buffer = '';
            }
            _tag = tag();
            if( !/[!?]/.test(_tag[1].charAt(0)) )
            {
              return [_tag, source.slice(pos)];
            }
            continue;
          }
          buffer += cur;
          cur = source.charAt(pos++);
        }
        return ret;
      },
      tag = function()
      {
        var buffer = '', attrs = [], has_attrs = false;
        while( cur )
        {
          if( cur == '>' )
          {
            cur = source.charAt(pos++);
            return [TAG, buffer, attrs];
          }
          if( cur == ' ' )
          {
            cur = source.charAt(pos++);
            has_attrs = true;
            continue;
          }
          if( has_attrs )
          {
            attrs = attr_key();
            continue;
          }
          buffer += cur;
          cur = source.charAt(pos++);
        }
      },
      attr_key = function()
      {
        var attrs = [], attr_key = '', buffer = '';
        while( cur )
        {
          if( cur == ' ' )
          {
            if(buffer)
            {
              attr_key = buffer;
              buffer = '';
            }
            cur = source.charAt(pos++);
            continue;
          }
          if( cur == '=' )
          {
            if(buffer)
            {
              attr_key = buffer;
              buffer = '';
            }
            cur = source.charAt(pos++);
            attrs[attrs.length] = [attr_key, set_attr_delimiter()];
            attr_key = '';
            continue;
          }
          if( cur == '>' )
          {
            if(buffer)
            {
              attr_key = buffer;
              buffer = '';
            }
            if(attr_key)
            {
              attrs[attrs.length] = [attr_key];
            }
            return attrs;
          }
          buffer += cur;
          cur = source.charAt(pos++);
        }
      },
      set_attr_delimiter = function()
      {
        var delimiter = '';
        while( cur )
        {
          if( cur == ' ' )
          {
            cur = source.charAt(pos++);
            continue;
          }
          if( cur == '\'' || cur == '"' )
          {
            delimiter = cur;
            cur = source.charAt(pos++);
            return attr_value(delimiter);
          }
          return attr_value(' ');
        }
      },
      attr_value = function(delimiter)
      {
        var buffer = '';
        while(cur)
        {
          if( cur == delimiter )
          {
            cur = source.charAt(pos++);
            return buffer;
          }
          if( cur == '>' && delimiter == ' ' )
          {
            return buffer;
          }
          buffer += cur;
          cur = source.charAt(pos++);
        }
      };

      this.lex = function(_source)
      {
        source = _source;
        pos = 0;
        cur = source.charAt(pos++);
        return text();
      }
    };

    range_target.selectNode(target);
    this.__defineSetter__
    (
      "outerHTML",
      function(str)
      {
        new_str = str;
        timeout || ( timeout = setTimeout(update, 100) );
      }
    );
    this.cancel_edit = function()
    {
      timeout && ( timeout = clearTimeout(timeout) );
      if(enter_node)
      {
        range_target.deleteContents();
        range_target.insertNode(enter_node);
      }
      this.exit_edit();
    };
    this.exit_edit = function()
    {
      if( timeout )
      {
        timeout = clearTimeout(timeout);
        update();
      };
      lexer = range_target = timeout = new_str = enter_node = update = null;
    };
  };

  this["return new Host_updater(target)"] =
    "return new (" + Host_updater.toString() + ")(target)";

  this.register_host_updater = function(xml, rt_id)
  {
    var
    status = xml.getNodeData('status'),
    obj_id = xml.getNodeData('object-id');

    if(  status == 'completed' && obj_id )
    {
      this.context_enter.host_target = this.context_cur.host_target = obj_id;
    }
    else
    {
      opera.postError("failed register_host_updater in DOMMarkupEditor");
    }
  }

  // complete the edit call
  this.handle_get_outer_html = function(xml, rt_id, obj_id, ele, event)
  {
    var json = xml.getNodeData('jsondata');
    if( json )
    {
      var
      outerHTML = views['dom'].serializeToOuterHTML(eval('(' + json +')')),
      parent = ele.parentNode,
      parent_parent = parent.parentElement,
      margin = parseInt(parent.style.marginLeft),
      next = null;

      this.context_enter.outerHTML = this.context_cur.outerHTML = outerHTML;
      if( !this.base_style['font-size'] )
      {
        this.get_base_style(ele);
      }
      // this should never be needed
      if( this.textarea_container.parentElement )
      {
        opera.postError("this.textarea_container.parentElement is not null in submit");
      }
      this.textarea.value = outerHTML;
      parent.innerHTML = "";
      parent.appendChild(this.textarea_container);
      while( ( next = parent.nextElementSibling ) && parseInt(next.style.marginLeft) > margin )
      {
        parent_parent.removeChild(next);
      };
      if( next && parseInt(next.style.marginLeft) == margin && /<\//.test(next.textContent) )
      {
        parent_parent.removeChild(next);
      }
      this.set_textarea_dimensions();
      // only for click events
      if( event )
      {
        this.textarea.focus();
      }
      this.textarea.selectionEnd = this.textarea.selectionStart = 0;
    }
    else
    {
      opera.postError("get subtree failed in DOMMarkupEditor handleGetSubtree")
    }
  }
}

DOMMarkupEditor.prototype = BaseEditor;<commit_msg>fix for bug DFL-291, DOM tree cannot be edited when the 'Show DOM in tree view' is enabled.<commit_after>/**
  * @constructor
  * @extends BaseEditor
  */

var DOMMarkupEditor = function()
{
  this.base_init(this);
  this.type = "dom-markup-editor";
  // specific context
  this.context_enter =
  {
    rt_id: '',
    obj_id: '',
    parent_obj_id: '',
    outerHTML: '',
    host_target: ''
  }

  this.context_cur =
  {
    rt_id: '',
    obj_id: '',
    parent_obj_id: '',
    outerHTML: '',
    host_target: ''
  }

  this.edit = function(event, ref_ele)
  {
    var
    ele = ref_ele || event.target,
    rt_id = ele.parentElement.parentElement.getAttribute('rt-id')
      // for DOM tree style
      || ele.parentElement.parentElement.parentElement.getAttribute('rt-id'),
    obj_id = ele.parentElement.getAttribute('ref-id'),
    script = '',
    tag = '',
    prop = '',
    container = ele;

    while( container
            && !/container/.test(container.nodeName)
            && ( container = container.parentElement ) );
    if(container)
    {
      container.firstChild.style.position = 'relative';
      container.firstChild.render(['fade-out']);
      this.context_enter =
      {
        rt_id: rt_id,
        obj_id: obj_id,
        parent_obj_id: dom_data.getParentElement(obj_id),
        outerHTML: '',
        host_target: ''
      };
      this.context_cur = {};
      for( prop in this.context_enter )
      {
        this.context_cur[prop] = this.context_enter[prop];
      }
      script = this["return new Host_updater(target)"];
      tag = tagManager.setCB(this, this.register_host_updater, [rt_id]);
      services['ecmascript-debugger'].eval( tag, rt_id, '', '', script, ['target', obj_id]);
      tag = tagManager.setCB(this, this.handle_get_outer_html, [rt_id, obj_id, ele, event])
      services['ecmascript-debugger'].inspectDOM( tag, obj_id, 'subtree', 'json' );
    }
  }

  this.oninput = function(event)
  {

    var
    script = "",
    state = this.context_cur;

    if( this.textarea_container.parentElement && state.host_target )
    {
      this.set_textarea_dimensions();
      state.outerHTML = this.textarea.value;
      var script = "host_target.outerHTML = '" + encode(state.outerHTML) + "';";
      services['ecmascript-debugger'].eval
      (
        0, state.rt_id, '', '', script, ['host_target', state.host_target]
      );
    }
  }

  this.submit = function()
  {
    // return a valid navigation target or null
    var
    state = this.context_cur,
    nav_target = this.textarea_container.parentElement;

    if(nav_target)
    {
      var tag = tagManager.setCB(this, this.on_exit_edit, [state, nav_target]);
      var script = "host_target.exit_edit()";
      services['ecmascript-debugger'].eval
      (
        tag, state.rt_id, '', '', script, ['host_target', state.host_target]
      );
    }
    return nav_target;
  }

  this.cancel = function()
  {
    // return a valid navigation target or null
    var
    script = "",
    state = this.context_enter,
    nav_target = this.textarea_container.parentElement;

    if( nav_target )
    {
      if(state.outerHTML != this.context_cur.outerHTML)
      {
        var tag = tagManager.setCB(this, this.on_exit_edit, [state, nav_target]);
        var script = "host_target.cancel_edit()";
        services['ecmascript-debugger'].eval
        (
          tag, state.rt_id, '', '', script, ['host_target', state.host_target]
        );
      }
    }
    return nav_target;
  }

  this.nav_next = function()
  {
    var
    val = this.textarea.value,
    start = this.textarea.selectionStart,
    end = this.textarea.selectionEnd,
    indent = '  ';

    this.textarea.value = val.slice(0, start) + indent +  val.slice(end);
    this.textarea.selectionStart = start + indent.length;
    this.textarea.selectionEnd = start + indent.length;
  }

  this.set_textarea_dimensions = function()
  {
    this.textarea.style.height = this.textarea.scrollHeight + 'px';
  }

  this.__is_active = function()
  {
    return this.context_enter && this.context_enter.host_target && true || false;
  }

  // could be the default method?
  this.onclick = function(event)
  {
    event.preventDefault();
    event.stopPropagation();
    if(!this.textarea_container.contains(event.target))
    {
      this.submit(true);
      return false;
    }
    return true;
  }

  // helpers

  this.on_exit_edit = function(xml, state, nav_target)
  {
    if( xml.getNodeData('status') == 'completed' )
    {
      // to remove the textarea_container from the dom
      nav_target.textContent = "";
      this.context_cur = this.context_enter = null;
      dom_data.closeNode(state.parent_obj_id, true);
      dom_data.getChildernFromNode(state.parent_obj_id);
    }
    else
    {
      opera.postError('exit markup edit failed in DOMMarkupEditor');
    }
  };

  var encode = function(str)
  {
    return str.replace(/\u200F\r\n/g, "").replace(/\r\n/g, "\\n").replace(/'/g, "\\'");
  };

  // class on the host side to update the given DOM range
  var Host_updater = function(target)
  {
    var
    range_target = document.createRange(),
    timeout = 0,
    new_str = '',
    enter_node = null,
    update = function(str)
    {
      if( enter_node )
      {
        range_target.deleteContents();
      }
      else
      {
        enter_node = range_target.extractContents();
      };
      var range_source = document.createRange();
      var temp = null;
      if( document.documentElement )
      {
        temp = document.createElement('df-temp-element');
        ( document.body || document.documentElement ).appendChild(temp);
        temp.innerHTML = new_str;
      }
      else
      {
        var new_source = lexer.lex(new_str), tag = new_source[0];

        if(tag)
        {
          var attrs = tag[2], i = 0, attr = null;
          for( ; ( attr = attrs[i] ) && attr[0] != 'xmlns'; i++);
          if( attr )
          {
            attrs.splice(i, 1);
            temp = document.createElementNS(attr[1], tag[1]);
          }
          else
          {
            temp = document.createElement(tag[1]);
          }
          for( i = 0 ; attr = attrs[i]; i++)
          {
            temp.setAttribute(attr[0], attr[1]);
          }
          document.appendChild(temp);
          temp.innerHTML = new_source[1];
        }
      };
      var first = temp.firstChild;
      var last = temp.lastChild;
      if(first)
      {
        if( temp == document.documentElement )
        {
          range_target.selectNode(document.documentElement);
        }
        else
        {
          range_source.selectNodeContents(temp);
          var fragment = range_source.extractContents();
          range_target.insertNode(fragment);
          range_target.setStartBefore(first);
          range_target.setEndAfter(last);
        }
      };
      if(temp.parentElement)
      {
        temp.parentNode.removeChild(temp);
      };
      timeout = 0;
    },
    lexer = new function()
    {
      /* adjusted to get only the first tag */
      const TEXT = 'TEXT', TAG = 'TAG';
      var
      source = '',
      cur = '',
      pos = 0,
      text = function()
      {
        var ret = [], buffer = '', _tag = null;
        while( cur )
        {
          if( cur == '<' )
          {
            cur = source.charAt(pos++);
            if(buffer)
            {
              ret[ret.length] = [TEXT, buffer];
              buffer = '';
            }
            _tag = tag();
            if( !/[!?]/.test(_tag[1].charAt(0)) )
            {
              return [_tag, source.slice(pos)];
            }
            continue;
          }
          buffer += cur;
          cur = source.charAt(pos++);
        }
        return ret;
      },
      tag = function()
      {
        var buffer = '', attrs = [], has_attrs = false;
        while( cur )
        {
          if( cur == '>' )
          {
            cur = source.charAt(pos++);
            return [TAG, buffer, attrs];
          }
          if( cur == ' ' )
          {
            cur = source.charAt(pos++);
            has_attrs = true;
            continue;
          }
          if( has_attrs )
          {
            attrs = attr_key();
            continue;
          }
          buffer += cur;
          cur = source.charAt(pos++);
        }
      },
      attr_key = function()
      {
        var attrs = [], attr_key = '', buffer = '';
        while( cur )
        {
          if( cur == ' ' )
          {
            if(buffer)
            {
              attr_key = buffer;
              buffer = '';
            }
            cur = source.charAt(pos++);
            continue;
          }
          if( cur == '=' )
          {
            if(buffer)
            {
              attr_key = buffer;
              buffer = '';
            }
            cur = source.charAt(pos++);
            attrs[attrs.length] = [attr_key, set_attr_delimiter()];
            attr_key = '';
            continue;
          }
          if( cur == '>' )
          {
            if(buffer)
            {
              attr_key = buffer;
              buffer = '';
            }
            if(attr_key)
            {
              attrs[attrs.length] = [attr_key];
            }
            return attrs;
          }
          buffer += cur;
          cur = source.charAt(pos++);
        }
      },
      set_attr_delimiter = function()
      {
        var delimiter = '';
        while( cur )
        {
          if( cur == ' ' )
          {
            cur = source.charAt(pos++);
            continue;
          }
          if( cur == '\'' || cur == '"' )
          {
            delimiter = cur;
            cur = source.charAt(pos++);
            return attr_value(delimiter);
          }
          return attr_value(' ');
        }
      },
      attr_value = function(delimiter)
      {
        var buffer = '';
        while(cur)
        {
          if( cur == delimiter )
          {
            cur = source.charAt(pos++);
            return buffer;
          }
          if( cur == '>' && delimiter == ' ' )
          {
            return buffer;
          }
          buffer += cur;
          cur = source.charAt(pos++);
        }
      };

      this.lex = function(_source)
      {
        source = _source;
        pos = 0;
        cur = source.charAt(pos++);
        return text();
      }
    };

    range_target.selectNode(target);
    this.__defineSetter__
    (
      "outerHTML",
      function(str)
      {
        new_str = str;
        timeout || ( timeout = setTimeout(update, 100) );
      }
    );
    this.cancel_edit = function()
    {
      timeout && ( timeout = clearTimeout(timeout) );
      if(enter_node)
      {
        range_target.deleteContents();
        range_target.insertNode(enter_node);
      }
      this.exit_edit();
    };
    this.exit_edit = function()
    {
      if( timeout )
      {
        timeout = clearTimeout(timeout);
        update();
      };
      lexer = range_target = timeout = new_str = enter_node = update = null;
    };
  };

  this["return new Host_updater(target)"] =
    "return new (" + Host_updater.toString() + ")(target)";

  this.register_host_updater = function(xml, rt_id)
  {
    var
    status = xml.getNodeData('status'),
    obj_id = xml.getNodeData('object-id');

    if(  status == 'completed' && obj_id )
    {
      this.context_enter.host_target = this.context_cur.host_target = obj_id;
    }
    else
    {
      opera.postError("failed register_host_updater in DOMMarkupEditor");
    }
  }

  // complete the edit call
  this.handle_get_outer_html = function(xml, rt_id, obj_id, ele, event)
  {
    var json = xml.getNodeData('jsondata');
    if( json )
    {
      var
      outerHTML = views['dom'].serializeToOuterHTML(eval('(' + json +')')),
      parent = ele.parentNode,
      parent_parent = parent.parentElement,
      margin = parseInt(parent.style.marginLeft),
      next = null;

      this.context_enter.outerHTML = this.context_cur.outerHTML = outerHTML;
      if( !this.base_style['font-size'] )
      {
        this.get_base_style(ele);
      }
      // this should never be needed
      if( this.textarea_container.parentElement )
      {
        opera.postError("this.textarea_container.parentElement is not null in submit");
      }
      this.textarea.value = outerHTML;
      parent.innerHTML = "";
      parent.appendChild(this.textarea_container);
      while( ( next = parent.nextElementSibling ) && parseInt(next.style.marginLeft) > margin )
      {
        parent_parent.removeChild(next);
      };
      if( next && parseInt(next.style.marginLeft) == margin && /<\//.test(next.textContent) )
      {
        parent_parent.removeChild(next);
      }
      this.set_textarea_dimensions();
      // only for click events
      if( event )
      {
        this.textarea.focus();
      }
      this.textarea.selectionEnd = this.textarea.selectionStart = 0;
    }
    else
    {
      opera.postError("get subtree failed in DOMMarkupEditor handleGetSubtree")
    }
  }
}

DOMMarkupEditor.prototype = BaseEditor;<|endoftext|>


<commit_before>
var test_version = "v3";

function include(filename)
{
    var head = document.getElementsByTagName('head')[0];

    var script = document.createElement('script');
    script.src = filename;
    script.type = 'text/javascript';

    head.appendChild(script)
}

//include('http://mrdoob.github.com/three.js/build/three.min.js');

parent.wl_inst.handleCommandResponse = function(msg, id)
{
	alert("On command response: " + msg);
}

parent.wl_inst.handleCommandError = function(msg, id)
{
	alert("On handleCommandError: " + msg);
}

parent.wl_inst.setTime = function(time)
{
	alert("On set time" + time);
}

parent.wl_inst.startInteraction = function()
{
	alert("OnStartInteraction");
}

parent.wl_inst.end = function()
{
	alert("OnEnd");
}

function gfxinit()
{
}
<commit_msg>[jstest]: Minor changes to test script<commit_after>
var test_version = "v3";

function include(filename)
{
    var head = document.getElementsByTagName('head')[0];

    var script = document.createElement('script');
    script.src = filename;
    script.type = 'text/javascript';

    head.appendChild(script)
}

include('http://mrdoob.github.com/three.js/build/three.min.js');

parent.wl_inst.handleCommandResponse = function(msg, id)
{
	alert("On command response: " + msg);
}

parent.wl_inst.handleCommandError = function(msg, id)
{
	alert("On handleCommandError: " + msg);
}

parent.wl_inst.setTime = function(time)
{
	alert("On set time" + time);
}

parent.wl_inst.startInteraction = function()
{
	alert("OnStartInteraction");
	gfxinit();
}

parent.wl_inst.end = function()
{
	alert("OnEnd");
}

function gfxtest()
{
	alert("Test");
}

function gfxinit()
{
	container = document.createElement('div');
	document.body.appendChild(container);

	camera = new THREE.PesrpectiveCamera( 45, window.innerWidth / window.innertHeight, 1, 10000);
	camera.position.z = 1000;

	scene = new THREE.Scene();

	scene.add(camera);

	renderer = new THREE.CanvasRenderer();
	renderer.setSize(window.innerWidth, window.innerHeight);

	container.appendChild(renderer.domElement);

	stats = new Stats();
	stats.domElement.style.position = 'absolute';
	stats.domElement.style.top = '0px';
	container.appendChild( stats.domElement );
}

function gfxanimate()
{
	requestAnimationFrame(gfxanimate);

	gfxrender();
	stats.update();
}

function gfxrender()
{
	renderer.autoClear = false;
	renderer.clear();

	renderer.render(scene, camera);
}

//@ sourceURL=dynamicScript.js
<|endoftext|>


<commit_before>/*! Copyright (c) 2016, Salesforce.com, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 *
 *      Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 *
 *      Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
 *      documentation and/or other materials provided with the distribution.
 *
 *      Neither the name of Salesforce.com nor the names of its contributors may be used to endorse or promote products derived from this software
 *      without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
'use strict';
/*global angular:false, require:false */

angular.module('argus', [
	// Dependencies
	'ngRoute',
	'ngAnimate',
	'ngStorage',
	'angular-growl',
	'angularUtils.directives.dirPagination',
	'angulartics',
	'ui.bootstrap',
	'ui.bootstrap.datetimepicker',
	'angularScreenfull',
	'argus.urlConfig',
	'argus.config',
	'argus.filters',
	'argus.constants',
	'argus.services',
	'argus.controllers',
	'argus.directives',
	'argus.directives.breadcrumbs',
	'argus.directives.confirm',
	'argus.directives.dashboardResource',
	'argus.directives.controls.dashboard',
	'argus.directives.controls.date',
	'argus.directives.controls.submit',
	'argus.directives.controls.text',
	'argus.directives.controls.select',
	'argus.directives.charts.chart',
	'argus.directives.charts.lineChart',
	'argus.directives.charts.flags',
	'argus.directives.charts.heatmap',
	'argus.directives.charts.metric',
	'argus.directives.charts.option',
	'argus.directives.charts.statusIndicator',
	'argus.directives.charts.table',
	'argus.directives.headerMenu',
	'argus.directives.modals.confirmClick'
]).run(['$http', '$templateCache', function ($http, $templateCache) {
	// template caching
	$http.get('js/templates/breadcrumbs.html', {cache: $templateCache});
	$http.get('js/templates/login.html', {cache: $templateCache});
	$http.get('js/templates/alert-list.html', {cache: $templateCache});
	$http.get('js/templates/alert-detail.html', {cache: $templateCache});
	$http.get('js/templates/dashboard-list.html', {cache: $templateCache});
	$http.get('js/templates/dashboard-detail.html', {cache: $templateCache});
	$http.get('js/templates/viewmetrics.html', {cache: $templateCache});
	$http.get('js/templates/charts/topToolbar.html', {cache: $templateCache});
}]);

// Services
angular.module('argus.services', [
	'argus.services.admin.reinstateuser',
	'argus.services.alerts',
	'argus.services.annotations',
	'argus.services.asyncMetrics',
	'argus.services.auth',
	'argus.services.batches',
	'argus.services.breadcrumbs',
	'argus.services.charts.options',
	'argus.services.charts.rendering',
	'argus.services.charts.tools',
	'argus.services.charts.dataProcessing',
	'argus.services.charts.dateHandler',
	'argus.services.charts.elements',
	'argus.services.dashboard',
	'argus.services.dashboards',
	'argus.services.history',
	'argus.services.inputTracker',
	'argus.services.jobexecutiondetails',
	'argus.services.metrics',
	'argus.services.namespace',
	'argus.services.notifications',
	'argus.services.search',
	'argus.services.storage',
	'argus.services.tags',
	'argus.services.triggers',
	'argus.services.triggersmap',
	'argus.services.utils',
	'argus.services.jsonFlatten',
	'argus.services.tableListService',
	'argus.services.downloadHelper',
	'argus.services.agTableService',
	'argus.services.tokenAuthInterceptor',
	'argus.services.users',
	'argus.services.confirmClick',
	'argus.services.browsing'
]);

// Controllers
angular.module('argus.controllers', [
	'argus.services',
	'argus.controllers.about',
	'argus.controllers.admin',
	'argus.controllers.alerts',
	'argus.controllers.alerts.detail',
	'argus.controllers.batches',
	'argus.controllers.beta',
	'argus.controllers.dashboards',
	'argus.controllers.dashboards.detail',
	'argus.controllers.login',
	'argus.controllers.main',
	'argus.controllers.metricelements',
	'argus.controllers.namespace',
	'argus.controllers.viewelements',
	'argus.controllers.viewMetrics',
	'argus.controllers.metricsBrowsing'
]);

// Directives
angular.module('argus.directives', [
]);

// Filters
angular.module('argus.filters', [
]);

// Argus module
require('./config');
require('./argusConfig');

// utils
require('./utils/constants');
require('./utils/filters');

// controllers
require('./controllers/about');
require('./controllers/admin');
require('./controllers/alerts');
require('./controllers/alertsDetail');
require('./controllers/batches');
require('./controllers/beta');
require('./controllers/dashboards');
require('./controllers/dashboardsDetail');
require('./controllers/login');
require('./controllers/main');
require('./controllers/metricElements');
require('./controllers/namespace');
require('./controllers/viewElements');
require('./controllers/viewMetrics');
require('./controllers/metricsBrowsing');

// services
require('./services/auth');
require('./services/breadcrumbs');
require('./services/controls');
require('./services/dashboard');
require('./services/inputTracker');
require('./services/search');
require('./services/storage');
require('./services/tags');
require('./services/utilService');
require('./services/jsonUnflatten');
require('./services/tableListService');
require('./services/downloadHelper');
require('./services/agTableService');
require('./services/tokenAuthInterceptor');
require('./services/ConfirmClickService');
require('./services/charts/chartOptions');
require('./services/charts/chartRendering');
require('./services/charts/chartTools');
require('./services/charts/dataProcessing');
require('./services/charts/dateHandler');
require('./services/charts/chartElements');

require('./services/factories/alerts');
require('./services/factories/asyncMetrics');
require('./services/factories/annotations');
require('./services/factories/batches');
require('./services/factories/dashboards');
require('./services/factories/history');
require('./services/factories/jobExecutionDetails');
require('./services/factories/metrics');
require('./services/factories/namespace');
require('./services/factories/notifications');
require('./services/factories/reinstateUser');
require('./services/factories/triggers');
require('./services/factories/triggersMap');
require('./services/factories/users');
require('./services/factories/browsing');

// directives
require('./directives/headerMenu');
require('./directives/tableList');
require('./directives/tableTabs');
require('./directives/breadcrumbs');
require('./directives/dashboardResource');
require('./directives/controls/dashboard');
require('./directives/controls/date');
require('./directives/controls/submit');
require('./directives/controls/text');
require('./directives/controls/select');
require('./directives/charts/chart');
require('./directives/charts/lineChart');
require('./directives/charts/flags');
require('./directives/charts/heatmap');
require('./directives/charts/metric');
require('./directives/charts/option');
require('./directives/charts/statusIndicator');
require('./directives/charts/table');
require('./directives/UItools/autoFocus');
require('./directives/UItools/stopEvent');
require('./directives/UItools/ngConfirm');
require('./directives/UItools/ngLoading');
require('./directives/UItools/ngEnter');
require('./directives/modals/confirmClick');

// css
require('../css/main.css');
<commit_msg>fix webpack error. fix deployment.<commit_after>/*! Copyright (c) 2016, Salesforce.com, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 *
 *      Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 *
 *      Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
 *      documentation and/or other materials provided with the distribution.
 *
 *      Neither the name of Salesforce.com nor the names of its contributors may be used to endorse or promote products derived from this software
 *      without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
'use strict';
/*global angular:false, require:false */

angular.module('argus', [
	// Dependencies
	'ngRoute',
	'ngAnimate',
	'ngStorage',
	'angular-growl',
	'angularUtils.directives.dirPagination',
	'angulartics',
	'ui.bootstrap',
	'ui.bootstrap.datetimepicker',
	'angularScreenfull',
	'argus.urlConfig',
	'argus.config',
	'argus.filters',
	'argus.constants',
	'argus.services',
	'argus.controllers',
	'argus.directives',
	'argus.directives.breadcrumbs',
	'argus.directives.confirm',
	'argus.directives.dashboardResource',
	'argus.directives.controls.dashboard',
	'argus.directives.controls.date',
	'argus.directives.controls.submit',
	'argus.directives.controls.text',
	'argus.directives.controls.select',
	'argus.directives.charts.chart',
	'argus.directives.charts.lineChart',
	'argus.directives.charts.flags',
	'argus.directives.charts.heatmap',
	'argus.directives.charts.metric',
	'argus.directives.charts.option',
	'argus.directives.charts.statusIndicator',
	'argus.directives.charts.table',
	'argus.directives.headerMenu',
	'argus.directives.modals.confirmClick'
]).run(['$http', '$templateCache', function ($http, $templateCache) {
	// template caching
	$http.get('js/templates/breadcrumbs.html', {cache: $templateCache});
	$http.get('js/templates/login.html', {cache: $templateCache});
	$http.get('js/templates/alert-list.html', {cache: $templateCache});
	$http.get('js/templates/alert-detail.html', {cache: $templateCache});
	$http.get('js/templates/dashboard-list.html', {cache: $templateCache});
	$http.get('js/templates/dashboard-detail.html', {cache: $templateCache});
	$http.get('js/templates/viewmetrics.html', {cache: $templateCache});
	$http.get('js/templates/charts/topToolbar.html', {cache: $templateCache});
}]);

// Services
angular.module('argus.services', [
	'argus.services.admin.reinstateuser',
	'argus.services.alerts',
	'argus.services.annotations',
	'argus.services.asyncMetrics',
	'argus.services.auth',
	'argus.services.batches',
	'argus.services.breadcrumbs',
	'argus.services.charts.options',
	'argus.services.charts.rendering',
	'argus.services.charts.tools',
	'argus.services.charts.dataProcessing',
	'argus.services.charts.dateHandler',
	'argus.services.charts.elements',
	'argus.services.dashboard',
	'argus.services.dashboards',
	'argus.services.history',
	'argus.services.inputTracker',
	'argus.services.jobexecutiondetails',
	'argus.services.metrics',
	'argus.services.namespace',
	'argus.services.notifications',
	'argus.services.search',
	'argus.services.storage',
	'argus.services.tags',
	'argus.services.triggers',
	'argus.services.triggersmap',
	'argus.services.utils',
	'argus.services.jsonFlatten',
	'argus.services.tableListService',
	'argus.services.downloadHelper',
	'argus.services.agTableService',
	'argus.services.tokenAuthInterceptor',
	'argus.services.users',
	'argus.services.confirmClick',
	'argus.services.browsing'
]);

// Controllers
angular.module('argus.controllers', [
	'argus.services',
	'argus.controllers.about',
	'argus.controllers.admin',
	'argus.controllers.alerts',
	'argus.controllers.alerts.detail',
	'argus.controllers.batches',
	'argus.controllers.beta',
	'argus.controllers.dashboards',
	'argus.controllers.dashboards.detail',
	'argus.controllers.login',
	'argus.controllers.main',
	'argus.controllers.metricelements',
	'argus.controllers.namespace',
	'argus.controllers.viewelements',
	'argus.controllers.viewMetrics',
	'argus.controllers.metricsBrowsing'
]);

// Directives
angular.module('argus.directives', [
]);

// Filters
angular.module('argus.filters', [
]);

// Argus module
require('./config');
require('./argusConfig');

// utils
require('./utils/constants');
require('./utils/filters');

// controllers
require('./controllers/about');
require('./controllers/admin');
require('./controllers/alerts');
require('./controllers/alertsDetail');
require('./controllers/batches');
require('./controllers/betaFeatures');
require('./controllers/dashboards');
require('./controllers/dashboardsDetail');
require('./controllers/login');
require('./controllers/main');
require('./controllers/metricElements');
require('./controllers/namespace');
require('./controllers/viewElements');
require('./controllers/viewMetrics');
require('./controllers/metricsBrowsing');

// services
require('./services/auth');
require('./services/breadcrumbs');
require('./services/controls');
require('./services/dashboard');
require('./services/inputTracker');
require('./services/search');
require('./services/storage');
require('./services/tags');
require('./services/utilService');
require('./services/jsonUnflatten');
require('./services/tableListService');
require('./services/downloadHelper');
require('./services/agTableService');
require('./services/tokenAuthInterceptor');
require('./services/ConfirmClickService');
require('./services/charts/chartOptions');
require('./services/charts/chartRendering');
require('./services/charts/chartTools');
require('./services/charts/dataProcessing');
require('./services/charts/dateHandler');
require('./services/charts/chartElements');

require('./services/factories/alerts');
require('./services/factories/asyncMetrics');
require('./services/factories/annotations');
require('./services/factories/batches');
require('./services/factories/dashboards');
require('./services/factories/history');
require('./services/factories/jobExecutionDetails');
require('./services/factories/metrics');
require('./services/factories/namespace');
require('./services/factories/notifications');
require('./services/factories/reinstateUser');
require('./services/factories/triggers');
require('./services/factories/triggersMap');
require('./services/factories/users');
require('./services/factories/browsing');

// directives
require('./directives/headerMenu');
require('./directives/tableList');
require('./directives/tableTabs');
require('./directives/breadcrumbs');
require('./directives/dashboardResource');
require('./directives/controls/dashboard');
require('./directives/controls/date');
require('./directives/controls/submit');
require('./directives/controls/text');
require('./directives/controls/select');
require('./directives/charts/chart');
require('./directives/charts/lineChart');
require('./directives/charts/flags');
require('./directives/charts/heatmap');
require('./directives/charts/metric');
require('./directives/charts/option');
require('./directives/charts/statusIndicator');
require('./directives/charts/table');
require('./directives/UItools/autoFocus');
require('./directives/UItools/stopEvent');
require('./directives/UItools/ngConfirm');
require('./directives/UItools/ngLoading');
require('./directives/UItools/ngEnter');
require('./directives/modals/confirmClick');

// css
require('../css/main.css');
<|endoftext|>


<commit_before>/**
    @file       application.js
    @brief      Client-side application.

    @author     Oleg Kertanov <okertanov@gmail.com>
    @date       September 2012
    @copyright  Copyright (C) 2012 Oleg Kertanov <okertanov@gmail.com>
    @license    BSD
    @see LICENSE file
*/

/**
    @brief IIFE
    @see https://developer.mozilla.org/en/JavaScript/Reference/Operators/function
*/
(function($, exports)
{

/**
    @brief Strict mode by default
    @see https://developer.mozilla.org/en/JavaScript/Strict_mode
*/
"use strict";

/**
    @fn $(function())
    @brief jQuery-like ready() that re-launches every <script></script> load.
    @see http://api.jquery.com/ready/
    @attention So try to avoid direct code invocation at the top of current namespace
               and here, in DOM's ready handler.
*/
$(function($, exports)
{
    try
    {
        var that = this,
            app = new Luxboard.Application();

        app.Initialize();

        $(window).bind('beforeunload', function(e)
        {
            app.Terminate();
            return undefined;
        });
    }
    catch(e)
    {
        console.log(e, e.toString());
    }
});

/**
    @class exports.Application
    @brief Application
*/
exports.Application = function()
{
    return {
        ctx:
        {
            socket: null
        },
        Initialize: function()
        {
            console.log('Application:', 'Starting...');

            try
            {
                this.InitializeUI(),
                    this.InitializeIO();
            }
            catch(e)
            {
                console.log(e, e.toString());
            }

            return this;
        },
        Terminate: function()
        {
            console.log('Application:', 'Terminating.');

            return this;
        },
        InitializeUI: function()
        {
            // Disable elastic page scrolling
            $(document).bind('touchmove', false);

            // Setup plot
            var options =
            {
                series: { shadowSize: 0 },
                lines:  { show: true    },
                legend: { show: false   },
                points: { show: true    },
                yaxis:  { show: true    },
                xaxis:  { show: true,
                          mode: "time"  },
                grid:   { show: false   }
            };

            var plots =
            [
                {
                    "label": "",
                    "data": []
                },
                {
                    "label": "",
                    "data": []
                }
            ];

            var plot = this.ctx.plot = $.plot($("div.plot"), plots, options);

            return this;
        },
        InitializeIO: function()
        {
            var that = this,
                socket = this.ctx.socket = io.connect();

            socket.on('connect', function()
            {
                console.log('Socket.io connection.');
                $(document).attr("title", $(document).attr("title") + ' - [Connected]');

                socket.on('luxboard.service.ping', function(msg)
                {
                    console.log('Socket.io ping received: ', msg);
                    socket.emit('luxboard.service.ack', msg);
                });

                socket.on('luxboard.service.message', function(msg)
                {
                    console.log('Socket.io service message received: ', msg);
                    socket.emit('luxboard.service.ack', msg);
                });

                socket.on('luxboard.service.ack', function(msg)
                {
                    console.log('Socket.io ack received: ', msg);
                });

                socket.on('disconnect', function()
                {
                    console.log('Socket.io disconnect.');
                });

                socket.on('luxboard.jiraffe.trunk.unresolved', function(msg)
                {
                    console.log('Socket.io luxboard.jiraffe.trunk.unresolved received: ', msg);
                    var num = (isNaN(parseInt(msg)) ? 0 : parseInt(msg));
                    $('#left.issues .counter').text(num);
                });

                socket.on('luxboard.jiraffe.stable.unresolved', function(msg)
                {
                    console.log('Socket.io luxboard.jiraffe.stable.unresolved received: ', msg);
                    var num = (isNaN(parseInt(msg)) ? 0 : parseInt(msg));
                    $('#right.issues .counter').text(num);
                });

                socket.on('luxboard.jiraffe.timeline', function(msg)
                {
                    console.log('Socket.io luxboard.jiraffe.timeline received: ', msg);

                    that.ctx.plot.setData(msg);
                    that.ctx.plot.draw();
                });
            });

            return this;
        }
    };
};

})(jQuery, (typeof exports !== 'undefined' ? exports : this['Luxboard'] = {}));

<commit_msg>drawing gix<commit_after>/**
    @file       application.js
    @brief      Client-side application.

    @author     Oleg Kertanov <okertanov@gmail.com>
    @date       September 2012
    @copyright  Copyright (C) 2012 Oleg Kertanov <okertanov@gmail.com>
    @license    BSD
    @see LICENSE file
*/

/**
    @brief IIFE
    @see https://developer.mozilla.org/en/JavaScript/Reference/Operators/function
*/
(function($, exports)
{

/**
    @brief Strict mode by default
    @see https://developer.mozilla.org/en/JavaScript/Strict_mode
*/
"use strict";

/**
    @fn $(function())
    @brief jQuery-like ready() that re-launches every <script></script> load.
    @see http://api.jquery.com/ready/
    @attention So try to avoid direct code invocation at the top of current namespace
               and here, in DOM's ready handler.
*/
$(function($, exports)
{
    try
    {
        var that = this,
            app = new Luxboard.Application();

        app.Initialize();

        $(window).bind('beforeunload', function(e)
        {
            app.Terminate();
            return undefined;
        });
    }
    catch(e)
    {
        console.log(e, e.toString());
    }
});

/**
    @class exports.Application
    @brief Application
*/
exports.Application = function()
{
    return {
        ctx:
        {
            socket: null
        },
        Initialize: function()
        {
            console.log('Application:', 'Starting...');

            try
            {
                this.InitializeUI(),
                    this.InitializeIO();
            }
            catch(e)
            {
                console.log(e, e.toString());
            }

            return this;
        },
        Terminate: function()
        {
            console.log('Application:', 'Terminating.');

            return this;
        },
        InitializeUI: function()
        {
            // Disable elastic page scrolling
            $(document).bind('touchmove', false);

            // Setup plot
            var options =
            {
                series: { shadowSize: 0 },
                lines:  { show: true    },
                legend: { show: false   },
                points: { show: true    },
                yaxis:  { show: true    },
                xaxis:  { show: true,
                          mode: "time"  },
                grid:   { show: false   }
            };

            var plots =
            [
                {
                    "label": "",
                    "data": []
                },
                {
                    "label": "",
                    "data": []
                }
            ];

            var plot = this.ctx.plot = $.plot($("div.plot"), plots, options);

            return this;
        },
        InitializeIO: function()
        {
            var that = this,
                socket = this.ctx.socket = io.connect();

            socket.on('connect', function()
            {
                console.log('Socket.io connection.');
                $(document).attr("title", $(document).attr("title") + ' - [Connected]');

                socket.on('luxboard.service.ping', function(msg)
                {
                    console.log('Socket.io ping received: ', msg);
                    socket.emit('luxboard.service.ack', msg);
                });

                socket.on('luxboard.service.message', function(msg)
                {
                    console.log('Socket.io service message received: ', msg);
                    socket.emit('luxboard.service.ack', msg);
                });

                socket.on('luxboard.service.ack', function(msg)
                {
                    console.log('Socket.io ack received: ', msg);
                });

                socket.on('disconnect', function()
                {
                    console.log('Socket.io disconnect.');
                });

                socket.on('luxboard.jiraffe.trunk.unresolved', function(msg)
                {
                    console.log('Socket.io luxboard.jiraffe.trunk.unresolved received: ', msg);
                    var num = (isNaN(parseInt(msg)) ? 0 : parseInt(msg));
                    $('#left.issues .counter').text(num);
                });

                socket.on('luxboard.jiraffe.stable.unresolved', function(msg)
                {
                    console.log('Socket.io luxboard.jiraffe.stable.unresolved received: ', msg);
                    var num = (isNaN(parseInt(msg)) ? 0 : parseInt(msg));
                    $('#right.issues .counter').text(num);
                });

                socket.on('luxboard.jiraffe.timeline', function(msg)
                {
                    console.log('Socket.io luxboard.jiraffe.timeline received: ', msg);

                    that.ctx.plot.setData(msg);
                    that.ctx.plot.setupGrid();
                    that.ctx.plot.draw();
                });
            });

            return this;
        }
    };
};

})(jQuery, (typeof exports !== 'undefined' ? exports : this['Luxboard'] = {}));

<|endoftext|>


<commit_before>let express  = require('express');
let router = express.Router();
let events   = require('../../models/events');
let notifies = require('../../models/notifies');
let Crypto = require('crypto');
let project = require('../../models/project');

let md5 = function (input) {
  return Crypto.createHash('md5').update(input.toString(), 'utf8').digest('hex');
};

/**
 *  Lead php debug_backtrace to custom stack format
 *
 * @param {Object[]} debugBacktrace
 * @param {String} debugBacktrace[].function — current function name
 * @param {Number} debugBacktrace[].line — current line number
 * @param {String} debugBacktrace[].file — current file name
 * @param {String} debugBacktrace[].class — current class name, if current function is a class method
 * @param {String} debugBacktrace[].object — current object of a class, if current function is a method
 * @param {String} debugBacktrace[].type — current call type.
 *                                         '->' for class method, '::' for static class method, nothing for a function call
 * @param {*[]} debugBacktrace[].args — list of function arguments
 *
 * @returns {{file: String, func: String, line: Number}[]} formatted stack
 *
 */
let formatDebugBacktrace = function (debugBacktrace) {
  let result = [];

  for (let i = debugBacktrace.length - 1; i >= 0; i--) {
    result[i] = {
      'file': debugBacktrace[i].file,
      'line': debugBacktrace[i].line,
      'trace': debugBacktrace[i].trace
    };

    let args = debugBacktrace[i].args;

    if (args) {
      debugBacktrace[i].function += '(' + args.slice(0, -1).join(', ') + args[args.length - 1] + ')';
    } else {
      debugBacktrace[i].function += '()';
    }

    switch (debugBacktrace[i]['type']) {
      case '::':
        result[i].func = debugBacktrace[i].class + '::' + debugBacktrace[i].function;
        break;
      case '->':
        result[i].func = debugBacktrace[i].object + '->' + debugBacktrace[i].function;
        break;
      default:
        result[i].func = debugBacktrace[i].function;
    }
  }

  return result;
};

let getServerErrors = function (req, res) {
  const tags = {
    1    : 'fatal',    // Error
    2    : 'warnings', // Warning
    4    : 'fatal',    // Parsing Error
    8    : 'notice',   // Notice
    16   : 'fatal',    // Core Error
    32   : 'warnings', // Core Warning
    64   : 'fatal',    // Compile Error
    128  : 'warnings', // Compile Warning
    256  : 'fatal',    // User Error
    512  : 'warnings', // User Warning
    1024 : 'notice',   // User Notice
    2048 : 'notice',   // Strict Error
    4096 : 'fatal',    // Recoverable error
    8192 : 'notice',   // Deprecated
    16384: 'notice',   // User Deprecated
  };

  let request = req.body,
      eventGroupPrehashed = request.error_description,
      server = request.http_params;

  let event = {
    type: 'php',
    tag: tags[request.error_type],
    token: request.access_token,
    groupHash: md5(eventGroupPrehashed),
    message: request.error_description,
    stack: formatDebugBacktrace(request.debug_backtrace),
    time: server.REQUEST_TIME,
    errorLocation: {
      file: request.error_file || '',
      line: request.error_line,
      full: request.error_file + ' -> ' + request.error_line
    },
    params: {
      post: request.POST || [],
      get : request.GET || [],
      headers : request.HEADERS || [],
      cookies : request.COOKIES || []
    },
    location: {
      url: 'http' + (server.HTTPS ? 's' : '') + server.SERVER_NAME + server.REQUEST_URI + '?' + server.QUERY_STRING,
      host: server.SERVER_NAME,
      path: server.REQUEST_URI,
    },
    request: {
      ip: server.REMOTE_ADDR,
      method: server.REQUEST_METHOD,
      referrer: server.HTTP_REFERRER,
    }
  };

  logger.info('Got php error from ' + event.location.host);

  project.getByToken(event.token)
    .then( function (foundProject) {
      if (!foundProject) {
        res.sendStatus(403);
        return;
      }

      return events.add(foundProject._id, event)
        .then(function () {
          return foundProject;
        });
    })
    .then(function (foundProject) {
      if (!foundProject) {
        return;
      }

      notifies.send(foundProject, event);

      res.sendStatus(200);
    })
    .catch( function () {
      res.sendStatus(500);
    });
};

/* GET server errors. */
router.post('/php', getServerErrors);

module.exports = router;
<commit_msg>save some vars<commit_after>let express  = require('express');
let router = express.Router();
let events   = require('../../models/events');
let notifies = require('../../models/notifies');
let Crypto = require('crypto');
let project = require('../../models/project');

let md5 = function (input) {
  return Crypto.createHash('md5').update(input.toString(), 'utf8').digest('hex');
};

/**
 *  Lead php debug_backtrace to custom stack format
 *
 * @param {Object[]} debugBacktrace
 * @param {String} debugBacktrace[].function — current function name
 * @param {Number} debugBacktrace[].line — current line number
 * @param {String} debugBacktrace[].file — current file name
 * @param {String} debugBacktrace[].class — current class name, if current function is a class method
 * @param {String} debugBacktrace[].object — current object of a class, if current function is a method
 * @param {String} debugBacktrace[].type — current call type.
 *                                         '->' for class method, '::' for static class method, nothing for a function call
 * @param {*[]} debugBacktrace[].args — list of function arguments
 *
 * @returns {{file: String, func: String, line: Number}[]} formatted stack
 *
 */
let formatDebugBacktrace = function (debugBacktrace) {
  let result = [];

  for (let i = debugBacktrace.length - 1; i >= 0; i--) {
    result[i] = {
      'file': debugBacktrace[i].file,
      'line': debugBacktrace[i].line,
      'trace': debugBacktrace[i].trace
    };

    let args = debugBacktrace[i].args;

    if (args) {
      debugBacktrace[i].function += '(' + args.slice(0, -1).join(', ') + args[args.length - 1] + ')';
    } else {
      debugBacktrace[i].function += '()';
    }

    switch (debugBacktrace[i]['type']) {
      case '::':
        result[i].func = debugBacktrace[i].class + '::' + debugBacktrace[i].function;
        break;
      case '->':
        result[i].func = debugBacktrace[i].object + '->' + debugBacktrace[i].function;
        break;
      default:
        result[i].func = debugBacktrace[i].function;
    }
  }

  return result;
};

let getServerErrors = function (req, res) {
  const tags = {
    1    : 'fatal',    // Error
    2    : 'warnings', // Warning
    4    : 'fatal',    // Parsing Error
    8    : 'notice',   // Notice
    16   : 'fatal',    // Core Error
    32   : 'warnings', // Core Warning
    64   : 'fatal',    // Compile Error
    128  : 'warnings', // Compile Warning
    256  : 'fatal',    // User Error
    512  : 'warnings', // User Warning
    1024 : 'notice',   // User Notice
    2048 : 'notice',   // Strict Error
    4096 : 'fatal',    // Recoverable error
    8192 : 'notice',   // Deprecated
    16384: 'notice',   // User Deprecated
  };

  let request = req.body,
      eventGroupPrehashed = request.error_description,
      server = request.http_params;

  let event = {
    type: 'php',
    tag: tags[request.error_type],
    token: request.access_token,
    groupHash: md5(eventGroupPrehashed),
    message: request.error_description,
    stack: formatDebugBacktrace(request.debug_backtrace),
    context: request.error_context,
    time: server.REQUEST_TIME,
    errorLocation: {
      file: request.error_file || '',
      line: request.error_line,
      full: request.error_file + ' -> ' + request.error_line
    },
    params: {
      post: request.POST || [],
      get : request.GET || [],
      headers : request.HEADERS || [],
      cookies : request.COOKIES || [],
      http_params : server || []
    },
    location: {
      url: 'http' + (server.HTTPS ? 's' : '') + '://' + server.HTTP_HOST + server.REQUEST_URI,
      host: server.HTTP_HOST ,
      path: server.REQUEST_URI,
    },
    request: {
      ip: server.REMOTE_ADDR,
      method: server.REQUEST_METHOD,
      referrer: server.HTTP_REFERRER,
    }
  };

  logger.info('Got php error from ' + event.location.host);

  project.getByToken(event.token)
    .then( function (foundProject) {
      if (!foundProject) {
        res.sendStatus(403);
        return;
      }

      return events.add(foundProject._id, event)
        .then(function () {
          return foundProject;
        });
    })
    .then(function (foundProject) {
      if (!foundProject) {
        return;
      }

      notifies.send(foundProject, event);

      res.sendStatus(200);
    })
    .catch( function () {
      res.sendStatus(500);
    });
};

/* GET server errors. */
router.post('/php', getServerErrors);

module.exports = router;
<|endoftext|>


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

'use strict';

// MODULES //

var isArrayLikeObject = require( '@stdlib/assert/is-array-like-object' );
var isComplexLike = require( '@stdlib/assert/is-complex-like' );
var real = require( '@stdlib/complex/real' );
var imag = require( '@stdlib/complex/imag' );

// MAIN //

/**
* Returns an array of iterated values.
*
* @private
* @param {Object} it - iterator
* @param {Function} clbk - callback to invoke for each iterated value
* @param {*} thisArg - invocation context
* @returns {(Array|TypeError)} array or an error
*/
function fromIteratorMap( it, clbk, thisArg ) {
	var out;
	var v;
	var i;

	out = [];
	i = 0;
	while ( true ) {
		v = it.next();
		i += 1;
		if ( v.value ) {
			v = clbk.call( thisArg, v.value, i );
			if ( isArrayLikeObject( v ) ) {
				out.push( v[ 0 ], v[ 1 ] );
			} else if ( isComplexLike( v ) ) {
				out.push( real( v ), imag( v ) );
			} else {
				return new TypeError( 'invalid argument. Callback must return either a two-element array containing real and imaginary components or a complex number. Value: `'+v+'`.' );
			}
		}
		if ( v.done ) {
			break;
		}
	}
	return out;
}

// EXPORTS //

module.exports = fromIteratorMap;
<commit_msg>Fix assignment bug and add length check<commit_after>/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*    http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

// MODULES //

var isArrayLikeObject = require( '@stdlib/assert/is-array-like-object' );
var isComplexLike = require( '@stdlib/assert/is-complex-like' );
var real = require( '@stdlib/complex/real' );
var imag = require( '@stdlib/complex/imag' );

// MAIN //

/**
* Returns an array of iterated values.
*
* @private
* @param {Object} it - iterator
* @param {Function} clbk - callback to invoke for each iterated value
* @param {*} thisArg - invocation context
* @returns {(Array|TypeError)} array or an error
*/
function fromIteratorMap( it, clbk, thisArg ) {
	var out;
	var v;
	var z;
	var i;

	out = [];
	i = 0;
	while ( true ) {
		i += 1;
		v = it.next();
		z = v.value;
		if ( z ) {
			z = clbk.call( thisArg, z, i );
			if ( isArrayLikeObject( z ) && z.length >= 2 ) {
				out.push( z[ 0 ], z[ 1 ] );
			} else if ( isComplexLike( z ) ) {
				out.push( real( z ), imag( z ) );
			} else {
				return new TypeError( 'invalid argument. Callback must return either a two-element array containing real and imaginary components or a complex number. Value: `'+z+'`.' );
			}
		}
		if ( v.done ) {
			break;
		}
	}
	return out;
}

// EXPORTS //

module.exports = fromIteratorMap;
<|endoftext|>


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

'use strict';

// MODULES //

var tape = require( 'tape' );
var defineProperty = require( '@stdlib/utils/define-property' );
var isWritableProperty = require( './../lib' );

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.equal( typeof isWritableProperty, 'function', 'export is a function' );
	t.end();
});

tape( 'the function returns `true` if an object property is writable', function test( t ) {
	var bool;
	var obj;

	function Foo() {
		this.bar = 'beep';
		return this;
	}

	obj = {
		'a': 'b'
	};
	bool = isWritableProperty( obj, 'a' );
	t.equal( bool, true, 'returns true' );

	bool = isWritableProperty( [ 1, 2, 3 ], '1' );
	t.equal( bool, true, 'returns true' );

	bool = isWritableProperty( [ 1, 2, 3 ], 1 );
	t.equal( bool, true, 'returns true' );

	bool = isWritableProperty( new Foo(), 'bar' );
	t.equal( bool, true, 'returns true' );

	bool = isWritableProperty( [ 'a' ], 'length' );
	t.equal( bool, true, 'returns true' );

	obj = {};
	defineProperty( obj, 'a', {
		'configurable': false,
		'enumerable': false,
		'writable': true,
		'value': 'b'
	});

	bool = isWritableProperty( obj, 'a' );
	t.equal( bool, true, 'returns true' );

	obj = {};
	defineProperty( obj, 'a', {
		'configurable': false,
		'enumerable': false,
		'set': setter
	});

	bool = isWritableProperty( obj, 'a' );
	t.equal( bool, true, 'returns true' );

	t.end();

	function setter() {
		// No-op...
	}
});

tape( 'the function returns `false` if provided `null` or `undefined` for the first argument', function test( t ) {
	var bool;

	bool = isWritableProperty( null, 'beep' );
	t.equal( bool, false, 'returns false when provided null' );

	bool = isWritableProperty( void 0, 'beep' );
	t.equal( bool, false, 'returns false when provided undefined' );

	t.end();
});

tape( 'the function returns `false` if provided a property argument which does not correspond to a writable property', function test( t ) {
	var bool;
	var obj;

	obj = {
		'a': 'b'
	};

	bool = isWritableProperty( obj, 'c' );
	t.equal( bool, false, 'returns false' );

	t.end();
});

tape( 'the function returns `false` if provided a prototype property', function test( t ) {
	var bool;

	bool = isWritableProperty( {}, 'hasOwnProperty' );
	t.equal( bool, false, 'returns false when provided a prototype property' );

	bool = isWritableProperty( {}, 'toString' );
	t.equal( bool, false, 'returns false' );

	bool = isWritableProperty( {}, 'constructor' );
	t.equal( bool, false, 'returns false' );

	t.end();
});

tape( 'values are coerced to objects', function test( t ) {
	var bool;

	bool = isWritableProperty( 'beep', 'length' );
	t.equal( bool, false, 'returns false' );

	t.end();
});
<commit_msg>Make test message consistent<commit_after>/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*    http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

// MODULES //

var tape = require( 'tape' );
var defineProperty = require( '@stdlib/utils/define-property' );
var isWritableProperty = require( './../lib' );

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.equal( typeof isWritableProperty, 'function', 'export is a function' );
	t.end();
});

tape( 'the function returns `true` if an object property is writable', function test( t ) {
	var bool;
	var obj;

	function Foo() {
		this.bar = 'beep';
		return this;
	}

	obj = {
		'a': 'b'
	};
	bool = isWritableProperty( obj, 'a' );
	t.equal( bool, true, 'returns true' );

	bool = isWritableProperty( [ 1, 2, 3 ], '1' );
	t.equal( bool, true, 'returns true' );

	bool = isWritableProperty( [ 1, 2, 3 ], 1 );
	t.equal( bool, true, 'returns true' );

	bool = isWritableProperty( new Foo(), 'bar' );
	t.equal( bool, true, 'returns true' );

	bool = isWritableProperty( [ 'a' ], 'length' );
	t.equal( bool, true, 'returns true' );

	obj = {};
	defineProperty( obj, 'a', {
		'configurable': false,
		'enumerable': false,
		'writable': true,
		'value': 'b'
	});

	bool = isWritableProperty( obj, 'a' );
	t.equal( bool, true, 'returns true' );

	obj = {};
	defineProperty( obj, 'a', {
		'configurable': false,
		'enumerable': false,
		'set': setter
	});

	bool = isWritableProperty( obj, 'a' );
	t.equal( bool, true, 'returns true' );

	t.end();

	function setter() {
		// No-op...
	}
});

tape( 'the function returns `false` if provided `null` or `undefined` for the first argument', function test( t ) {
	var bool;

	bool = isWritableProperty( null, 'beep' );
	t.equal( bool, false, 'returns false when provided null' );

	bool = isWritableProperty( void 0, 'beep' );
	t.equal( bool, false, 'returns false when provided undefined' );

	t.end();
});

tape( 'the function returns `false` if provided a property argument which does not correspond to a writable property', function test( t ) {
	var bool;
	var obj;

	obj = {
		'a': 'b'
	};

	bool = isWritableProperty( obj, 'c' );
	t.equal( bool, false, 'returns false' );

	t.end();
});

tape( 'the function returns `false` if provided a prototype property', function test( t ) {
	var bool;

	bool = isWritableProperty( {}, 'hasOwnProperty' );
	t.equal( bool, false, 'returns false' );

	bool = isWritableProperty( {}, 'toString' );
	t.equal( bool, false, 'returns false' );

	bool = isWritableProperty( {}, 'constructor' );
	t.equal( bool, false, 'returns false' );

	t.end();
});

tape( 'values are coerced to objects', function test( t ) {
	var bool;

	bool = isWritableProperty( 'beep', 'length' );
	t.equal( bool, false, 'returns false' );

	t.end();
});
<|endoftext|>


<commit_before>var RawFeedService = require('../database/raw_feed.js');
var responseHandler = require('../general_response');

module.exports = function(app, models, io, logger) {

	var me = this;

	me.app = app;
	me.models = models;
	me.io = io;
	me.logger = logger;

	var rawFeedService = new RawFeedService(models, io, logger);

	// Get a list of all rawFeeds
	app.get('/rawfeed/?', function(req, res){
		if(logger.DO_LOG){
			logger.info('Request for list of feeds');
		}

		//params
		rawFeedService.list(req.query, function(err, rawFeeds){
			if(err){
				var errMsg = "Error listing raw feeds";
				me.logger.error("RawFeed: "+err, err);
				responseHandler.send500(res, errMsg);
			} else {
				res.jsonp(rawFeeds);
				res.end();
			}
		});
	});

	// Review
	app.get('/rawfeed/:id([0-9a-f]+)', function(req, res){
		if(0 && logger.DO_LOG){
			logger.info("Request for raw feed " + req.params.id);
		}
		rawFeedService.get(req.params.id, function(err, docs){
			if(err) {
				logger.info("Error getting raw feed "+err);
				responseHandler.send500(res, "Error getting raw feed " + err);
			} else if(docs) {
				res.jsonp(docs);
				res.end();
			} else {
				responseHandler.send404(res);
			}
		});
	});

	// Create
	app.post('/rawfeed/?', function(req, res){
		var data = req.body;

		if(logger.DO_LOG){
			logger.info("Receiving new feed", data);
		}
		rawFeedService.create(req.body, function(err, val, newFeed) {
			if(err){
				logger.error('Error saving raw feed ', err);
				responseHandler.send500(res, 'Error saving raw feed ' + err);
			} else if (!val.valid) {
				logger.info('Invalid raw_feed ' + JSON.stringify(val.errors));
				responseHandler.send500(res, 'Invalid raw feed ' + JSON.stringify(val.errors));
			} else {
				logger.info('Raw feed saved ' + JSON.stringify(newFeed));
				res.json({_id:newFeed._id});
				res.end();
			}
		});
	});

	// Update
	app.post('/rawfeed/:id([0-9a-f]+)', function(req,res){
		if(logger.DO_LOG){
			logger.info("Update feed " + req.params.id, data);
		}
		rawFeedService.update(req.params.id, req.body, function(err, val, updFeed) {
			if(err){
				logger.error('Error updating raw feed', err);
				responseHandler.send500(res, 'Error updating raw feed ' + err);
			} else if (!val.valid) {
				logger.info('Invalid raw feed ' + JSON.stringify(val.errors));
				responseHandler.send500(res, 'Invalid raw feed ' + JSON.stringify(val.errors));
			} else {
				logger.info('Raw feed updated ' + JSON.stringify(updFeed));
				res.json({id:updFeed._id});
				res.end();
			}
		});
	});

	// Delete an individual raw_feed
	app.del('/rawfeed/:id([0-9a-f]+)',function(req, res){
		var id = req.params.id;

		if(logger.DO_LOG){
			logger.info("Deleting raw feed with id: " + id);
		}

		rawFeedService.del({_id:id}, function(err, count){
			res.json({deleted_count: count});
			res.end;
		});
	});

	// Delete all raw_feed entries
	app.del('/rawfeed/',function(req, res){
		if(logger.DO_LOG){
			logger.info("Deleting all raw feed entries");
		}

		rawFeedService.del({}, function(err, count){
			res.json({deleted_count: count});
			res.end;
		});
	});
};<commit_msg>fixing undefined variable data<commit_after>var RawFeedService = require('../database/raw_feed.js');
var responseHandler = require('../general_response');

module.exports = function(app, models, io, logger) {

	var me = this;

	me.app = app;
	me.models = models;
	me.io = io;
	me.logger = logger;

	var rawFeedService = new RawFeedService(models, io, logger);

	// Get a list of all rawFeeds
	app.get('/rawfeed/?', function(req, res){
		if(logger.DO_LOG){
			logger.info('Request for list of feeds');
		}

		//params
		rawFeedService.list(req.query, function(err, rawFeeds){
			if(err){
				var errMsg = "Error listing raw feeds";
				me.logger.error("RawFeed: "+err, err);
				responseHandler.send500(res, errMsg);
			} else {
				res.jsonp(rawFeeds);
				res.end();
			}
		});
	});

	// Review
	app.get('/rawfeed/:id([0-9a-f]+)', function(req, res){
		if(0 && logger.DO_LOG){
			logger.info("Request for raw feed " + req.params.id);
		}
		rawFeedService.get(req.params.id, function(err, docs){
			if(err) {
				logger.info("Error getting raw feed "+err);
				responseHandler.send500(res, "Error getting raw feed " + err);
			} else if(docs) {
				res.jsonp(docs);
				res.end();
			} else {
				responseHandler.send404(res);
			}
		});
	});

	// Create
	app.post('/rawfeed/?', function(req, res){
		if(logger.DO_LOG){
			logger.info("Receiving new feed", req.body);
		}
		rawFeedService.create(req.body, function(err, val, newFeed) {
			if(err){
				logger.error('Error saving raw feed ', err);
				responseHandler.send500(res, 'Error saving raw feed ' + err);
			} else if (!val.valid) {
				logger.info('Invalid raw_feed ' + JSON.stringify(val.errors));
				responseHandler.send500(res, 'Invalid raw feed ' + JSON.stringify(val.errors));
			} else {
				logger.info('Raw feed saved ' + JSON.stringify(newFeed));
				res.json({_id:newFeed._id});
				res.end();
			}
		});
	});

	// Update
	app.post('/rawfeed/:id([0-9a-f]+)', function(req,res){
		if(logger.DO_LOG){
			logger.info("Update feed " + req.params.id, req.body);
		}
		rawFeedService.update(req.params.id, req.body, function(err, val, updFeed) {
			if(err){
				logger.error('Error updating raw feed', err);
				responseHandler.send500(res, 'Error updating raw feed ' + err);
			} else if (!val.valid) {
				logger.info('Invalid raw feed ' + JSON.stringify(val.errors));
				responseHandler.send500(res, 'Invalid raw feed ' + JSON.stringify(val.errors));
			} else {
				logger.info('Raw feed updated ' + JSON.stringify(updFeed));
				res.json({id:updFeed._id});
				res.end();
			}
		});
	});

	// Delete an individual raw_feed
	app.del('/rawfeed/:id([0-9a-f]+)',function(req, res){
		var id = req.params.id;

		if(logger.DO_LOG){
			logger.info("Deleting raw feed with id: " + id);
		}

		rawFeedService.del({_id:id}, function(err, count){
			res.json({deleted_count: count});
			res.end;
		});
	});

	// Delete all raw_feed entries
	app.del('/rawfeed/',function(req, res){
		if(logger.DO_LOG){
			logger.info("Deleting all raw feed entries");
		}

		rawFeedService.del({}, function(err, count){
			res.json({deleted_count: count});
			res.end;
		});
	});
};<|endoftext|>


<commit_before>'use strict'
const file = require('path').join(__dirname, '../package.json')
const {readFileSync, writeFileSync} = require('fs')
const {stdout} = require('process')
const {indent, crlf} = require('./lib/package-json-config.json')
const {parse, stringify} = JSON
const ENCODING = {encoding: 'utf8'}
const jsonobj = parse(readFileSync(file, ENCODING))
const jsonstr = stringify(jsonobj, undefined, indent).split('\n').join(crlf ? '\r\n' : '\n')
writeFileSync(file, jsonstr, ENCODING)
<commit_msg>Log 'Done.'<commit_after>'use strict'
const file = require('path').join(__dirname, '../package.json')
const {readFileSync, writeFileSync} = require('fs')
const {stdout} = require('process')
const {indent, crlf} = require('./lib/package-json-config.json')
const {parse, stringify} = JSON
const ENCODING = {encoding: 'utf8'}
const jsonobj = parse(readFileSync(file, ENCODING))
const jsonstr = stringify(jsonobj, undefined, indent).split('\n').join(crlf ? '\r\n' : '\n')
writeFileSync(file, jsonstr, ENCODING)
stdout.write('Done.\n')
<|endoftext|>


<commit_before>/*
  nr is the prefix for this function space.
*/
function ddg_spice_xkcd(xk) {
  // console.log(xk);

    var img,snippet,link,div;

  // validity check
   if (xk['img'] && xk['alt']) {

       // snippet shown in 0-click
       snippet = d.createElement('span');

       if (nur) img = nur('',xk['alt'],xk['img']);
       if (img) {
	   YAHOO.util.Dom.addClass(img,'cizb');
	   div = d.createElement('div');
	   div.appendChild(img);
	   snippet.appendChild(div);

	   link = d.createElement('a');
	   link.href = '/?q=xkcd ' + (parseInt(xk['num']) - 1)
	   link.appendChild(d.createTextNode('Prev'));
	   snippet.appendChild(link);
	   snippet.appendChild(d.createTextNode('\u00a0 \u00a0'));
       }

       items = new Array();
       items[0] = new Array();
       items[0]['a'] = snippet;

       items[0]['h'] = xk['safe_title'];

       // Source name and url for the More at X link.
       items[0]['s'] = 'XKCD';
       items[0]['u'] = 'http://xkcd.com/' + xk['num'];

       // Force no compression.
       items[0]['f'] = 1;

       // The rendering function is nra.
       nra(items);
   }
}<commit_msg>Class fix to stop xkcd img from getting to big.<commit_after>/*
  nr is the prefix for this function space.
*/
function ddg_spice_xkcd(xk) {
  // console.log(xk);

    var img,snippet,link,div;

  // validity check
   if (xk['img'] && xk['alt']) {

       // snippet shown in 0-click
       snippet = d.createElement('span');

       if (nur) img = nur('',xk['alt'],xk['img']);
       if (img) {
	   YAHOO.util.Dom.addClass(img,'img_zero_click_big');
	   div = d.createElement('div');
	   div.appendChild(img);
	   snippet.appendChild(div);

	   link = d.createElement('a');
	   link.href = '/?q=xkcd ' + (parseInt(xk['num']) - 1)
	   link.appendChild(d.createTextNode('Prev'));
	   snippet.appendChild(link);
	   snippet.appendChild(d.createTextNode('\u00a0 \u00a0'));
       }

       items = new Array();
       items[0] = new Array();
       items[0]['a'] = snippet;

       items[0]['h'] = xk['safe_title'];

       // Source name and url for the More at X link.
       items[0]['s'] = 'XKCD';
       items[0]['u'] = 'http://xkcd.com/' + xk['num'];

       // Force no compression.
       items[0]['f'] = 1;

       // The rendering function is nra.
       nra(items);
   }
}<|endoftext|>


<commit_before>// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

'use strict';

tvcm.require('tracing.test_utils');
tvcm.require('tracing.importer.trace_event_importer');

tvcm.unittest.testSuite('tracing.importer.trace_event_importer_perf_test', function() { // @suppress longLineCheck
  var eventStrings = {};

  function getSynchronous(url) {
    var req = new XMLHttpRequest();
    req.open('GET', url, false);
    req.send(null);
    return req.responseText;
  }

  function getEvents(url) {
    if (url in eventStrings)
      return eventStrings[url];
    eventStrings[url] = getSynchronous(url);
    return eventStrings[url];
  }

  function timedPerfTestWithEvents(name, testFn, initialOptions) {
    if (initialOptions.setUp)
      throw new Error(
          'Per-test setUp not supported. Trivial to fix if needed.');

    var options = {};
    for (var k in initialOptions)
      options[k] = initialOptions[k];
    options.setUp = function() {
      ['/test_data/simple_trace.json', '/test_data/lthi_cats.json'].forEach(
          function warmup(url) {
            getEvents(url);
          });
    };
    timedPerfTest(name, testFn, options);
  }

  var n110100 = [1, 10, 100];
  n110100.forEach(function(val) {
    timedPerfTestWithEvents('simple_trace_' + val, function() {
      var events = getEvents('/test_data/simple_trace.json');
      var m = new tracing.TraceModel();
      m.importTraces([events], false, false);
    }, {iterations: val});
  });

  timedPerfTestWithEvents('lthi_cats_1', function() {
    var events = getEvents('/test_data/lthi_cats.json');
    var m = new tracing.TraceModel();
    m.importTraces([events], false, false);
  }, {iterations: 1});
});
<commit_msg>Fixed lthi_cats_perf_test<commit_after>// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

'use strict';

tvcm.require('tracing.test_utils');
tvcm.require('tracing.importer');

tvcm.unittest.testSuite('tracing.importer.trace_event_importer_perf_test', function() { // @suppress longLineCheck
  var eventStrings = {};

  // @const
  var TEST_NAMES = ['simple_trace', 'lthi_cats'];
  // @const
  var TEST_FILES_PATHS = ['/test_data/simple_trace.json',
                          '/test_data/lthi_cats.json.gz'];

  function getSynchronous(url) {
    var req = new XMLHttpRequest();
    req.open('GET', url, false);
    // Without the mime type specified like this, the file's bytes are not
    // retrieved correctly.
    req.overrideMimeType('text/plain; charset=x-user-defined');
    req.send(null);
    return req.responseText;
  }

  function getEvents(url) {
    if (url in eventStrings)
      return eventStrings[url];
    eventStrings[url] = getSynchronous(url);
    return eventStrings[url];
  }

  function timedPerfTestWithEvents(name, testFn, initialOptions) {
    if (initialOptions.setUp)
      throw new Error(
          'Per-test setUp not supported. Trivial to fix if needed.');

    var options = {};
    for (var k in initialOptions)
      options[k] = initialOptions[k];
    options.setUp = function() {
      TEST_FILES_PATHS.forEach(
          function warmup(url) {
            getEvents(url);
          });
    };
    timedPerfTest(name, testFn, options);
  }

  var n110100 = [1, 10, 100];
  n110100.forEach(function(val) {
    timedPerfTestWithEvents(TEST_NAMES[0] + '_' + val, function() {
      var events = getEvents(TEST_FILES_PATHS[0]);
      var m = new tracing.TraceModel();
      m.importTraces([events], false, false);
    }, {iterations: val});
  });

  timedPerfTestWithEvents(TEST_NAMES[1] + '_1', function() {
    var events = getEvents(TEST_FILES_PATHS[1]);
    var m = new tracing.TraceModel();
    m.importTraces([events], false, false);
  }, {iterations: 1});
});
<|endoftext|>