<commit_before>/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * 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.
 */

foam.CLASS({
  package: 'foam.java',
  name: 'JavaClass',

  properties: [
    {
      class: 'String',
      name: 'name'
    },
    {
      class: 'String',
      name: 'package'
    },
    {
      class: 'String',
      name: 'id',
      expression: function(name, package) {
        return package + '.' + name;
      }
    },
    {
      class: 'Boolean',
      name: 'abstract',
      value: false
    },
    {
      class: 'String',
      name: 'extends',
      value: 'foam.core.FObject'
    },
    {
      class: 'StringArray',
      name: 'imports'
    },
    {
      class: 'StringArray',
      name: 'implements',
      adapt: function(o, v) {
        if ( foam.String.is(v) ) return [v];
        return v;
      }
    },
    {
      class: 'String',
      name: 'code'
    }
  ],

  methods: [
    function fromClass(cls) {
      this.package = cls.model_.package;
      this.name = cls.model_.name;
      this.extends = cls.model_.extends;
      this.implements = cls.getAxiomsByClass(foam.core.Implements).map(function(a) {
        return a.path;
      });
      this.abstract = cls.model_.abstract;

      var axioms = cls.getAxioms();
      for ( var i = 0 ; i < axioms.length ; i++ ) {
        var axiom = axioms[i];
        if ( axiom.axiomClassInfo ) this.code += axiom.axiomClassInfo(null, cls, this);
      }

      for ( var i = 0 ; i < axioms.length ; i++ ) {
        var axiom = axioms[i];
        if ( axiom.axiomJavaSource ) this.code += axiom.axiomJavaSource(null, cls, this);
      }
    }
  ],

  templates: [
    {
      name: 'toJavaSource',
      template: function() {/*// GENERATED CODE.  DO NOT MODIFY BY HAND.
<% if ( this.package ) { %>package <%= this.pacakge %>;
<% }
%>public <%= this.abstract ? 'abstract ' : '' %> class <%= this.name %><%
  if ( this.extends ) { %> extends <%= this.extends %><%
  }
  if ( this.implements.length > 0 ) { %> implements <%
    for ( var i = 0 ; i < this.implements.length ; i++ ) {
      %><%= this.implements[i] %><%
      if ( i != this.implements.length - 1 ) { %>, <% }
    }
  }
%> {
<%= this.code %>
}
    */}
    }
  ]
});

foam.CLASS({
  package: 'foam.java',
  name: 'Skeleton',
  properties: [
    {
      class: 'Class2',
      name: 'of'
    },
    {
      name: 'name',
      expression: function(of) {
        return this.of$cls.name + 'Skeleton';
      }
    },
    {
      name: 'package',
      expression: function(of) {
        return this.of$cls.package;
      }
    },
    {
      name: 'id',
      expression: function(name, package) {
        return package + '.' + name;
      }
    }
  ],
  templates: [
    {
      name: 'code',
      template: function() {/*
package <%= this.package %>;

import foam.core.X;

public class <%= this.name %> implements foam.box.Box {
  private X x_;
  public X getX() { return x_; }

  public <%= this.name %>(X x) {
    x_ = x;
  }

  private <%= this.of %> delegate_;
  public <%= this.of %> getDelegate() { return delegate_; }
  public <%= this.name %> setDelegate(<%= this.of %> delegate) {
    delegate_ = delegate;
    return this;
  }

  public void send(foam.box.Message message) {
    if ( ! ( message instanceof foam.box.RPCMessage) ) {
      // TODO error to errorBox
      return;
    }

    foam.box.RPCMessage rpc = (foam.box.RPCMessage)message;

    switch ( rpc.getName() ) {<%
  var methods = this.of$cls.getAxiomsByClass(foam.core.Method);
  for ( var i = 0 ; i < methods.length ; i++ ) {
    var m = methods[i]; %>
      case "<%= m.name %>":
        getDelegate().<%= m.name %>(<%
    for ( var j = 0 ; j < m.args.length ; j++ ) {
      %>(<%= m.args[j].javaType %>)rpc.getArgs()[<%= i %>]<%
      if ( j != m.args.length - 1 ) { %>, <% }
    }
    %>);
        break;
    <%
  }%>
      default: throw new RuntimeException("No such method found \\"" + rpc.getName() + "\\"");
    }
  }
}
  */}
    }
  ]
});

foam.LIB({
  name: 'foam.AbstractClass',
  methods: [
    function javaSource() {
      return foam.java.JavaUtil.create().javaSource(this);
    }
  ]
});

foam.CLASS({
  refines: 'foam.core.AbstractMethod',

  properties: [
    {
      class: 'String',
      name: 'javaCode'
    },
    {
      class: 'String',
      name: 'javaReturns'
    }
  ],

  methods: [
    function createChildMethod_(child) {
      var m = child.clone();
      m.returns = this.returns;
      m.args = this.args;
      m.javaReturns = this.javaReturns;
      m.sourceCls_ = child.sourceCls_;
      return m;
    }
  ],

  templates: [
    {
      name: 'axiomJavaInterfaceSource',
      template: function() {/*
  public <%= this.javaReturns || 'void' %> <%= this.name %>(<%
for ( var i = 0 ; this.args && i < this.args.length ; i++ ) {
  var arg = this.args[i];
  %><%= arg.javaType || 'Object' %> <%= arg.name %><%
  if ( i != this.args.length - 1 ) { %>, <% }
}
%>);
*/}
    },
    {
      name: 'axiomJavaSource',
      template: function() {/*<% if ( ! this.javaCode ) { return opt_outputter || ''; } %>
  public <%= this.javaReturns || 'void' %> <%= this.name %>(<%
for ( var i = 0 ; this.args && i < this.args.length ; i++ ) {
  var arg = this.args[i];
  %><%= arg.javaType || 'Object' %> <%= arg.name %><%
  if ( i != this.args.length - 1 ) { %>, <% }
}
%>) {
  <%= this.javaCode %>
  }
*/}
    }
  ]
});

foam.CLASS({
  refines: 'foam.core.Import',
  templates: [
    {
      name: 'axiomJavaSource',
      template: function() {/*
  public Object get<%= foam.String.capitalize(this.name) %>() {
    return getX().get("<%= this.key %>");
  }
*/}
     }
  ]
});

foam.CLASS({
  refines: 'foam.core.FObject',
  methods: [
    {
      name: 'toString',
      javaReturns: 'String',
      code: foam.core.FObject.prototype.toString
    }
  ]
});

foam.CLASS({
  refines: 'foam.core.Interface',
  templates: [
    {
      name: 'javaSource',
      template: function() {/*
// GENERATED CODE
package <%= this.package %>;

public interface <%= this.name %><% if ( this.extends ) { %><%= this.extends %><% } %> {
<%
  for ( var i = 0 ; i < this.axioms_.length ; i++ ) {
    var axiom = this.axioms_[i];
    if ( axiom.axiomJavaInterfaceSource ) axiom.axiomJavaInterfaceSource(output, this);
  }
%>
}
*/}
    }
  ]
});

foam.CLASS({
  refines: 'foam.core.Property',
  properties: [
    {
      class: 'String',
      name: 'javaType'
    },
    {
      class: 'String',
      name: 'javaJsonParser'
    },
    {
      class: 'String',
      name: 'javaToJSON'
    }
  ],

  templates: [
    {
      name: 'axiomJavaInterfaceSource',
      template: function() {/*<% var cls = arguments[1] %>
  public <%= this.javaType %> get<%= foam.String.capitalize(this.name) %>();
  public <%= cls.name %> set<%= foam.String.capitalize(this.name) %>(<%= this.javaType %> val);
*/}
    },
    {
      name: 'axiomJavaSource',
      template: function() {/*<% var cls = arguments[1]; if ( this.javaType ) { %>
private <%= this.javaType %> <%= this.name %>;

public <%= this.javaType %> get<%= foam.String.capitalize(this.name) %>() {
  return <%= this.name %>;
}

public <%= cls.name %> set<%= foam.String.capitalize(this.name) %>(<%= this.javaType %> val) {
  <%= this.name %> = val;
  return this;
}
<% } %>*/}
    },
    {
      name: 'axiomClassInfo',
      template: function() {/*<% var cls = arguments[1]; %>
  .addProperty(
    new AbstractPropertyInfo() {
      @Override
      public String getName() { return "<%= this.name %>"; }

      @Override
      public Object get(Object obj) {
        return ((<%= cls.name %>)obj).get<%= foam.String.capitalize(this.name) %>();
      }

      @Override
      public void set(Object obj, Object value) {<%
// TODO(adamvy): There should be a more polymorphic way of doing this.
// or we shouldn't support Array properties and use Lists instead.
if ( foam.core.FObjectArray.isInstance(this) ) { %>
        Object[] src = (Object[])value;
        <%= this.javaType %> a = new <%= this.of %>[src.length];
        System.arraycopy(src, 0, a, 0, src.length);
        ((<%= cls.name %>)obj).set<%= foam.String.capitalize(this.name) %>(a);
<% } else { %>
        ((<%= cls.name %>)obj).set<%= foam.String.capitalize(this.name) %>((<%= this.javaType %>)value);
<% } %>
      }

<% if ( this.javaOutputJSON ) { %>
      @Override
      public void toJSON(foam.lib.json.Outputter outputter, StringBuilder out, Object value) {
<%= this.javaToJSON %>
      }
<% } %>

      @Override
      public Parser jsonParser() {
        return new <%= this.javaJsonParser %>();
      }})
*/}
    }
  ]
});

foam.CLASS({
  refines: 'foam.core.String',
  properties: [
    {
      class: 'String',
      name: 'javaType',
      value: 'String'
    },
    ['javaJsonParser', 'foam.lib.json.StringParser']
  ]
});

foam.CLASS({
  refines: 'foam.core.Int',
  properties: [
    ['javaType', 'int'],
    ['javaJsonParser', 'foam.lib.json.IntParser']
  ]
});

foam.CLASS({
  refines: 'foam.core.Array',
  properties: [
    ['javaType', 'Object[]'],
    ['javaJsonParser', 'foam.lib.json.ArrayParser']
  ]
});

foam.CLASS({
  refines: 'foam.core.FObjectProperty',
  properties: [
    {
      name: 'javaType',
      expression: function(of) {
        return of ? of : 'foam.core.FObject';
      }
    },
    ['javaJsonParser', 'foam.lib.json.FObjectParser']
  ]
});

foam.CLASS({
  refines: 'foam.core.FObjectArray',
  properties: [
    {
      name: 'javaType',
      expression: function(of) {
        return of + '[]'
      }
    },
    {
      name: 'javaJsonParser',
      value: 'foam.lib.json.FObjectArrayParser'
    }
  ]
});

foam.CLASS({
  package: 'foam.java',
  name: 'JavaUtil',

  axioms: [
    foam.pattern.Singleton.create()
  ],

  templates: [
    {
      name: 'classInfo',
      template: function(cls) {/*<% var cls = arguments[1]; %>
new ClassInfo()
  .setId("<%= cls.id %>")
  <%
  var a = cls.getAxioms();
  for ( var i = 0 ; i < a.length ; i++ ) {
    if ( ! a[i].axiomClassInfo ) continue;
    a[i].axiomClassInfo(output, cls);
%>
  <%
  }
%>;*/}
    },
    {
      name: 'javaSource',
      template: function(cls) {/*<% var cls = arguments[1];
%>// GENERATED CODE
// adamvy@google.com
package <%= cls.package %>;

import foam.core.*;

import foam.lib.parse.*;
import foam.lib.json.*;

public <%= cls.model_.abstract ? 'abstract ' : '' %>class <%= cls.name %> extends <%= cls.model_.extends %><%
  var interfaces = cls.getAxiomsByClass(foam.core.Implements);
  if ( interfaces.length > 0 ) { %> implements <% }
  for ( var i = 0 ; i < interfaces.length ; i++ ) {
    var intf = interfaces[i];
    %><%= intf.path %><%
    if ( i < interfaces.length - 1 ) { %>,<% }
    %> <%
  }
%> {
  private static ClassInfo classInfo_ = <% this.classInfo(output, cls) %>

  public ClassInfo getClassInfo() {
    return classInfo_;
  }

  public static ClassInfo getOwnClassInfo() {
    return classInfo_;
  }

  public <%= cls.name %>(X x) { super(x); }

<%
  var a = cls.getAxioms();

for ( var i = 0 ; i < a.length; i++ ) {
if ( ! a[i].axiomJavaSource ) continue;
%>
  <% a[i].axiomJavaSource(output, cls); %>
<%
}

%>
}
*/}
    }
  ]
});
<commit_msg>Add replies to Java Skeletons<commit_after>/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * 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.
 */

foam.CLASS({
  package: 'foam.java',
  name: 'JavaClass',

  properties: [
    {
      class: 'String',
      name: 'name'
    },
    {
      class: 'String',
      name: 'package'
    },
    {
      class: 'String',
      name: 'id',
      expression: function(name, package) {
        return package + '.' + name;
      }
    },
    {
      class: 'Boolean',
      name: 'abstract',
      value: false
    },
    {
      class: 'String',
      name: 'extends',
      value: 'foam.core.FObject'
    },
    {
      class: 'StringArray',
      name: 'imports'
    },
    {
      class: 'StringArray',
      name: 'implements',
      adapt: function(o, v) {
        if ( foam.String.is(v) ) return [v];
        return v;
      }
    },
    {
      class: 'String',
      name: 'code'
    }
  ],

  methods: [
    function fromClass(cls) {
      this.package = cls.model_.package;
      this.name = cls.model_.name;
      this.extends = cls.model_.extends;
      this.implements = cls.getAxiomsByClass(foam.core.Implements).map(function(a) {
        return a.path;
      });
      this.abstract = cls.model_.abstract;

      var axioms = cls.getAxioms();
      for ( var i = 0 ; i < axioms.length ; i++ ) {
        var axiom = axioms[i];
        if ( axiom.axiomClassInfo ) this.code += axiom.axiomClassInfo(null, cls, this);
      }

      for ( var i = 0 ; i < axioms.length ; i++ ) {
        var axiom = axioms[i];
        if ( axiom.axiomJavaSource ) this.code += axiom.axiomJavaSource(null, cls, this);
      }
    }
  ],

  templates: [
    {
      name: 'toJavaSource',
      template: function() {/*// GENERATED CODE.  DO NOT MODIFY BY HAND.
<% if ( this.package ) { %>package <%= this.pacakge %>;
<% }
%>public <%= this.abstract ? 'abstract ' : '' %> class <%= this.name %><%
  if ( this.extends ) { %> extends <%= this.extends %><%
  }
  if ( this.implements.length > 0 ) { %> implements <%
    for ( var i = 0 ; i < this.implements.length ; i++ ) {
      %><%= this.implements[i] %><%
      if ( i != this.implements.length - 1 ) { %>, <% }
    }
  }
%> {
<%= this.code %>
}
    */}
    }
  ]
});

foam.CLASS({
  package: 'foam.java',
  name: 'Skeleton',
  properties: [
    {
      class: 'Class2',
      name: 'of'
    },
    {
      name: 'name',
      expression: function(of) {
        return this.of$cls.name + 'Skeleton';
      }
    },
    {
      name: 'package',
      expression: function(of) {
        return this.of$cls.package;
      }
    },
    {
      name: 'id',
      expression: function(name, package) {
        return package + '.' + name;
      }
    }
  ],
  templates: [
    {
      name: 'code',
      template: function() {/*
package <%= this.package %>;

import foam.core.X;

public class <%= this.name %> implements foam.box.Box {
  private X x_;
  public X getX() { return x_; }

  public <%= this.name %>(X x) {
    x_ = x;
  }

  private <%= this.of %> delegate_;
  public <%= this.of %> getDelegate() { return delegate_; }
  public <%= this.name %> setDelegate(<%= this.of %> delegate) {
    delegate_ = delegate;
    return this;
  }

  public void send(foam.box.Message message) {
    if ( ! ( message instanceof foam.box.RPCMessage) ) {
      // TODO error to errorBox
      return;
    }

    foam.box.RPCMessage rpc = (foam.box.RPCMessage)message;
    foam.box.Box replyBox = message.getReplyBox();
    Object result = null;

    switch ( rpc.getName() ) {<%
  var methods = this.of$cls.getAxiomsByClass(foam.core.Method);
  for ( var i = 0 ; i < methods.length ; i++ ) {
    var m = methods[i]; %>
      case "<%= m.name %>":
        <% if ( m.javaReturns && m.javaReturns !== 'void' ) { %>result = <% } %>getDelegate().<%= m.name %>(<%
    for ( var j = 0 ; j < m.args.length ; j++ ) {
      %>(<%= m.args[j].javaType %>)rpc.getArgs()[<%= j %>]<%
      if ( j != m.args.length - 1 ) { %>, <% }
    }
    %>);
        break;
    <%
  }%>
      default: throw new RuntimeException("No such method found \\"" + rpc.getName() + "\\"");
    }

    if ( replyBox != null ) {
      foam.box.RPCReturnMessage reply = (foam.box.RPCReturnMessage)getX().create(foam.box.RPCReturnMessage.class);
      reply.setData(result);

      replyBox.send(reply);
    }
  }
}
  */}
    }
  ]
});

foam.LIB({
  name: 'foam.AbstractClass',
  methods: [
    function javaSource() {
      return foam.java.JavaUtil.create().javaSource(this);
    }
  ]
});

foam.CLASS({
  refines: 'foam.core.AbstractMethod',

  properties: [
    {
      class: 'String',
      name: 'javaCode'
    },
    {
      class: 'String',
      name: 'javaReturns'
    }
  ],

  methods: [
    function createChildMethod_(child) {
      var m = child.clone();
      m.returns = this.returns;
      m.args = this.args;
      m.javaReturns = this.javaReturns;
      m.sourceCls_ = child.sourceCls_;
      return m;
    }
  ],

  templates: [
    {
      name: 'axiomJavaInterfaceSource',
      template: function() {/*
  public <%= this.javaReturns || 'void' %> <%= this.name %>(<%
for ( var i = 0 ; this.args && i < this.args.length ; i++ ) {
  var arg = this.args[i];
  %><%= arg.javaType || 'Object' %> <%= arg.name %><%
  if ( i != this.args.length - 1 ) { %>, <% }
}
%>);
*/}
    },
    {
      name: 'axiomJavaSource',
      template: function() {/*<% if ( ! this.javaCode ) { return opt_outputter || ''; } %>
  public <%= this.javaReturns || 'void' %> <%= this.name %>(<%
for ( var i = 0 ; this.args && i < this.args.length ; i++ ) {
  var arg = this.args[i];
  %><%= arg.javaType || 'Object' %> <%= arg.name %><%
  if ( i != this.args.length - 1 ) { %>, <% }
}
%>) {
  <%= this.javaCode %>
  }
*/}
    }
  ]
});

foam.CLASS({
  refines: 'foam.core.Import',
  templates: [
    {
      name: 'axiomJavaSource',
      template: function() {/*
  public Object get<%= foam.String.capitalize(this.name) %>() {
    return getX().get("<%= this.key %>");
  }
*/}
     }
  ]
});

foam.CLASS({
  refines: 'foam.core.FObject',
  methods: [
    {
      name: 'toString',
      javaReturns: 'String',
      code: foam.core.FObject.prototype.toString
    }
  ]
});

foam.CLASS({
  refines: 'foam.core.Interface',
  templates: [
    {
      name: 'javaSource',
      template: function() {/*
// GENERATED CODE
package <%= this.package %>;

public interface <%= this.name %><% if ( this.extends ) { %><%= this.extends %><% } %> {
<%
  for ( var i = 0 ; i < this.axioms_.length ; i++ ) {
    var axiom = this.axioms_[i];
    if ( axiom.axiomJavaInterfaceSource ) axiom.axiomJavaInterfaceSource(output, this);
  }
%>
}
*/}
    }
  ]
});

foam.CLASS({
  refines: 'foam.core.Property',
  properties: [
    {
      class: 'String',
      name: 'javaType'
    },
    {
      class: 'String',
      name: 'javaJsonParser'
    },
    {
      class: 'String',
      name: 'javaToJSON'
    }
  ],

  templates: [
    {
      name: 'axiomJavaInterfaceSource',
      template: function() {/*<% var cls = arguments[1] %>
  public <%= this.javaType %> get<%= foam.String.capitalize(this.name) %>();
  public <%= cls.name %> set<%= foam.String.capitalize(this.name) %>(<%= this.javaType %> val);
*/}
    },
    {
      name: 'axiomJavaSource',
      template: function() {/*<% var cls = arguments[1]; if ( this.javaType ) { %>
private <%= this.javaType %> <%= this.name %>;

public <%= this.javaType %> get<%= foam.String.capitalize(this.name) %>() {
  return <%= this.name %>;
}

public <%= cls.name %> set<%= foam.String.capitalize(this.name) %>(<%= this.javaType %> val) {
  <%= this.name %> = val;
  return this;
}
<% } %>*/}
    },
    {
      name: 'axiomClassInfo',
      template: function() {/*<% var cls = arguments[1]; %>
  .addProperty(
    new AbstractPropertyInfo() {
      @Override
      public String getName() { return "<%= this.name %>"; }

      @Override
      public Object get(Object obj) {
        return ((<%= cls.name %>)obj).get<%= foam.String.capitalize(this.name) %>();
      }

      @Override
      public void set(Object obj, Object value) {<%
// TODO(adamvy): There should be a more polymorphic way of doing this.
// or we shouldn't support Array properties and use Lists instead.
if ( foam.core.FObjectArray.isInstance(this) ) { %>
        Object[] src = (Object[])value;
        <%= this.javaType %> a = new <%= this.of %>[src.length];
        System.arraycopy(src, 0, a, 0, src.length);
        ((<%= cls.name %>)obj).set<%= foam.String.capitalize(this.name) %>(a);
<% } else { %>
        ((<%= cls.name %>)obj).set<%= foam.String.capitalize(this.name) %>((<%= this.javaType %>)value);
<% } %>
      }

<% if ( this.javaOutputJSON ) { %>
      @Override
      public void toJSON(foam.lib.json.Outputter outputter, StringBuilder out, Object value) {
<%= this.javaToJSON %>
      }
<% } %>

      @Override
      public Parser jsonParser() {
        return new <%= this.javaJsonParser %>();
      }})
*/}
    }
  ]
});

foam.CLASS({
  refines: 'foam.core.String',
  properties: [
    {
      class: 'String',
      name: 'javaType',
      value: 'String'
    },
    ['javaJsonParser', 'foam.lib.json.StringParser']
  ]
});

foam.CLASS({
  refines: 'foam.core.Int',
  properties: [
    ['javaType', 'int'],
    ['javaJsonParser', 'foam.lib.json.IntParser']
  ]
});

foam.CLASS({
  refines: 'foam.core.Array',
  properties: [
    ['javaType', 'Object[]'],
    ['javaJsonParser', 'foam.lib.json.ArrayParser']
  ]
});

foam.CLASS({
  refines: 'foam.core.FObjectProperty',
  properties: [
    {
      name: 'javaType',
      expression: function(of) {
        return of ? of : 'foam.core.FObject';
      }
    },
    ['javaJsonParser', 'foam.lib.json.FObjectParser']
  ]
});

foam.CLASS({
  refines: 'foam.core.FObjectArray',
  properties: [
    {
      name: 'javaType',
      expression: function(of) {
        return of + '[]'
      }
    },
    {
      name: 'javaJsonParser',
      value: 'foam.lib.json.FObjectArrayParser'
    }
  ]
});

foam.CLASS({
  package: 'foam.java',
  name: 'JavaUtil',

  axioms: [
    foam.pattern.Singleton.create()
  ],

  templates: [
    {
      name: 'classInfo',
      template: function(cls) {/*<% var cls = arguments[1]; %>
new ClassInfo()
  .setId("<%= cls.id %>")
  <%
  var a = cls.getAxioms();
  for ( var i = 0 ; i < a.length ; i++ ) {
    if ( ! a[i].axiomClassInfo ) continue;
    a[i].axiomClassInfo(output, cls);
%>
  <%
  }
%>;*/}
    },
    {
      name: 'javaSource',
      template: function(cls) {/*<% var cls = arguments[1];
%>// GENERATED CODE
// adamvy@google.com
package <%= cls.package %>;

import foam.core.*;

import foam.lib.parse.*;
import foam.lib.json.*;

public <%= cls.model_.abstract ? 'abstract ' : '' %>class <%= cls.name %> extends <%= cls.model_.extends %><%
  var interfaces = cls.getAxiomsByClass(foam.core.Implements);
  if ( interfaces.length > 0 ) { %> implements <% }
  for ( var i = 0 ; i < interfaces.length ; i++ ) {
    var intf = interfaces[i];
    %><%= intf.path %><%
    if ( i < interfaces.length - 1 ) { %>,<% }
    %> <%
  }
%> {
  private static ClassInfo classInfo_ = <% this.classInfo(output, cls) %>

  public ClassInfo getClassInfo() {
    return classInfo_;
  }

  public static ClassInfo getOwnClassInfo() {
    return classInfo_;
  }

  public <%= cls.name %>(X x) { super(x); }

<%
  var a = cls.getAxioms();

for ( var i = 0 ; i < a.length; i++ ) {
if ( ! a[i].axiomJavaSource ) continue;
%>
  <% a[i].axiomJavaSource(output, cls); %>
<%
}

%>
}
*/}
    }
  ]
});
<|endoftext|>


<commit_before>//>>excludeStart("exclude", pragmas.exclude);
define([ "shoestring" ], function(){
//>>excludeEnd("exclude");

  /**
	 * Checks the current set of elements against the selector, if one matches return `true`.
	 *
	 * @param {string} selector The selector to check.
	 * @return {boolean}
	 * @this {shoestring}
	 */
	shoestring.fn.is = function( selector ){
		var ret = false, self = this, children = [], parents;

		parents = this.parent();

		if( !parents.length ){
			parents = shoestring( document );
		}

		// assume a dom element
		if( typeof selector !== "string" ){
			children = [selector];

			return _checkElements(this, [selector]);
		}

		parents.each(function( i, e ) {
			var j = 0, children;

//>>includeStart("development", pragmas.development);
				try {
//>>includeEnd("development");
					children = e.querySelectorAll( selector );
//>>includeStart("development", pragmas.development);
				} catch( e ) {
					shoestring.error( 'queryselector', selector );
				}
//>>includeEnd("development");

			ret = _checkElements(self, children);
		});

		return ret;
	};

	function _checkElements(needles, haystack){
		var ret = false;

		needles.each(function() {
			var j = 0;

			while( j < haystack.length ){
				if( this == haystack[j] ){
					ret = true;
				}

				j++;
			}
		});

		return ret;
	}

//>>excludeStart("exclude", pragmas.exclude);
});
//>>excludeEnd("exclude");
<commit_msg>useless assignment<commit_after>//>>excludeStart("exclude", pragmas.exclude);
define([ "shoestring" ], function(){
//>>excludeEnd("exclude");

  /**
	 * Checks the current set of elements against the selector, if one matches return `true`.
	 *
	 * @param {string} selector The selector to check.
	 * @return {boolean}
	 * @this {shoestring}
	 */
	shoestring.fn.is = function( selector ){
		var ret = false, self = this, children = [], parents;

		parents = this.parent();

		if( !parents.length ){
			parents = shoestring( document );
		}

		// assume a dom element
		if( typeof selector !== "string" ){
			return _checkElements(this, [selector]);
		}

		parents.each(function( i, e ) {
			var j = 0, children;

//>>includeStart("development", pragmas.development);
				try {
//>>includeEnd("development");
					children = e.querySelectorAll( selector );
//>>includeStart("development", pragmas.development);
				} catch( e ) {
					shoestring.error( 'queryselector', selector );
				}
//>>includeEnd("development");

			ret = _checkElements(self, children);
		});

		return ret;
	};

	function _checkElements(needles, haystack){
		var ret = false;

		needles.each(function() {
			var j = 0;

			while( j < haystack.length ){
				if( this == haystack[j] ){
					ret = true;
				}

				j++;
			}
		});

		return ret;
	}

//>>excludeStart("exclude", pragmas.exclude);
});
//>>excludeEnd("exclude");
<|endoftext|>


<commit_before>/**
 * @license
 * Visual Blocks Editor
 *
 * Copyright 2016 Massachusetts Institute of Technology
 * All rights reserved.
 *
 * 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';

goog.provide('Blockly.Blocks.motion');

goog.require('Blockly.Blocks');
goog.require('Blockly.Colours');
goog.require('Blockly.constants');

Blockly.Blocks['motion_movesteps'] = {
  /**
   * Block to move steps.
   * @this Blockly.Block
   */
  init: function() {
    this.jsonInit({
      "message0": "move %1 steps",
      "args0": [
        {
          "type": "input_value",
          "name": "STEPS"
        }
      ],
      "inputsInline": true,
      "previousStatement": null,
      "nextStatement": null,
      "category": Blockly.Categories.motion,
      "colour": Blockly.Colours.motion.primary,
      "colourSecondary": Blockly.Colours.motion.secondary,
      "colourTertiary": Blockly.Colours.motion.tertiary
    });
  }
};

Blockly.Blocks['motion_turnright'] = {
  /**
   * Block to turn right.
   * @this Blockly.Block
   */
  init: function() {
    this.jsonInit({
      "message0": "turn %1 %2 degrees",
      "args0": [
        {
          "type": "field_image",
          "src": Blockly.mainWorkspace.options.pathToMedia + "/turnright_arrow.png",
          "width": 16,
          "height": 16
        },
        {
          "type": "input_value",
          "name": "DEGREES"
        }
      ],
      "inputsInline": true,
      "previousStatement": null,
      "nextStatement": null,
      "category": Blockly.Categories.motion,
      "colour": Blockly.Colours.motion.primary,
      "colourSecondary": Blockly.Colours.motion.secondary,
      "colourTertiary": Blockly.Colours.motion.tertiary
    });
  }
};

Blockly.Blocks['motion_turnleft'] = {
  /**
   * Block to turn left.
   * @this Blockly.Block
   */
  init: function() {
    this.jsonInit({
      "message0": "turn %1 %2 degrees",
      "args0": [
        {
          "type": "field_image",
          "src": Blockly.mainWorkspace.options.pathToMedia + "/turnleft_arrow.png",
          "width": 16,
          "height": 16
        },
        {
          "type": "input_value",
          "name": "DEGREES"
        }
      ],
      "inputsInline": true,
      "previousStatement": null,
      "nextStatement": null,
      "category": Blockly.Categories.motion,
      "colour": Blockly.Colours.motion.primary,
      "colourSecondary": Blockly.Colours.motion.secondary,
      "colourTertiary": Blockly.Colours.motion.tertiary
    });
  }
};

Blockly.Blocks['motion_pointindirection'] = {
  /**
   * Block to point in direction.
   * @this Blockly.Block
   */
  init: function() {
    this.jsonInit({
      "message0": "point in direction %1",
      "args0": [
        {
          "type": "input_value",
          "name": "DIRECTION"
        }
      ],
      "inputsInline": true,
      "previousStatement": null,
      "nextStatement": null,
      "category": Blockly.Categories.motion,
      "colour": Blockly.Colours.motion.primary,
      "colourSecondary": Blockly.Colours.motion.secondary,
      "colourTertiary": Blockly.Colours.motion.tertiary
    });
  }
};

Blockly.Blocks['motion_pointtowards_menu'] = {
  /**
   * Point towards drop-down menu.
   * @this Blockly.Block
   */
  init: function() {
    this.jsonInit(
      {
        "message0": "%1",
        "args0": [
          {
            "type": "field_dropdown",
            "name": "TOWARDS",
            "options": [
              ['mouse-pointer', '_mouse_']
            ]
          }
        ],
        "inputsInline": true,
        "output": "String",
        "colour": Blockly.Colours.motion.secondary,
        "colourSecondary": Blockly.Colours.motion.secondary,
        "colourTertiary": Blockly.Colours.motion.tertiary,
        "outputShape": Blockly.OUTPUT_SHAPE_ROUND
      });
  }
};

Blockly.Blocks['motion_pointtowards'] = {
  /**
   * Block to point in direction.
   * @this Blockly.Block
   */
  init: function() {
    this.jsonInit({
      "message0": "point towards %1",
      "args0": [
        {
          "type": "input_value",
          "name": "TOWARDS"
        }
      ],
      "inputsInline": true,
      "previousStatement": null,
      "nextStatement": null,
      "category": Blockly.Categories.motion,
      "colour": Blockly.Colours.motion.primary,
      "colourSecondary": Blockly.Colours.motion.secondary,
      "colourTertiary": Blockly.Colours.motion.tertiary
    });
  }
};

Blockly.Blocks['motion_goto_menu'] = {
  /**
   * Go to drop-down menu.
   * @this Blockly.Block
   */
  init: function() {
    this.jsonInit(
      {
        "message0": "%1",
        "args0": [
          {
            "type": "field_dropdown",
            "name": "TO",
            "options": [
              ['mouse-pointer', '_mouse_'],
              ['random position', '_random_']
            ]
          }
        ],
        "inputsInline": true,
        "output": "String",
        "colour": Blockly.Colours.motion.secondary,
        "colourSecondary": Blockly.Colours.motion.secondary,
        "colourTertiary": Blockly.Colours.motion.tertiary,
        "outputShape": Blockly.OUTPUT_SHAPE_ROUND
      });
  }
};

Blockly.Blocks['motion_gotoxy'] = {
  /**
   * Block to go to X, Y.
   * @this Blockly.Block
   */
  init: function() {
    this.jsonInit({
      "message0": "go to x: %1 y: %2",
      "args0": [
        {
          "type": "input_value",
          "name": "X"
        },
        {
          "type": "input_value",
          "name": "Y"
        }
      ],
      "inputsInline": true,
      "previousStatement": null,
      "nextStatement": null,
      "category": Blockly.Categories.motion,
      "colour": Blockly.Colours.motion.primary,
      "colourSecondary": Blockly.Colours.motion.secondary,
      "colourTertiary": Blockly.Colours.motion.tertiary
    });
  }
};

Blockly.Blocks['motion_goto'] = {
  /**
   * Block to go to a menu item.
   * @this Blockly.Block
   */
  init: function() {
    this.jsonInit({
      "message0": "go to %1",
      "args0": [
        {
          "type": "input_value",
          "name": "TO"
        }
      ],
      "inputsInline": true,
      "previousStatement": null,
      "nextStatement": null,
      "category": Blockly.Categories.motion,
      "colour": Blockly.Colours.motion.primary,
      "colourSecondary": Blockly.Colours.motion.secondary,
      "colourTertiary": Blockly.Colours.motion.tertiary
    });
  }
};

Blockly.Blocks['motion_glidesecstoxy'] = {
  /**
   * Block to glide for a specified time.
   * @this Blockly.Block
   */
  init: function() {
    this.jsonInit({
      "message0": "glide %1 secs to x: %2 y: %3",
      "args0": [
        {
          "type": "input_value",
          "name": "SECS"
        },
        {
          "type": "input_value",
          "name": "X"
        },
        {
          "type": "input_value",
          "name": "Y"
        }
      ],
      "inputsInline": true,
      "previousStatement": null,
      "nextStatement": null,
      "category": Blockly.Categories.motion,
      "colour": Blockly.Colours.motion.primary,
      "colourSecondary": Blockly.Colours.motion.secondary,
      "colourTertiary": Blockly.Colours.motion.tertiary
    });
  }
};

Blockly.Blocks['motion_changexby'] = {
  /**
   * Block to change X.
   * @this Blockly.Block
   */
  init: function() {
    this.jsonInit({
      "message0": "change x by %1",
      "args0": [
        {
          "type": "input_value",
          "name": "DX"
        }
      ],
      "inputsInline": true,
      "previousStatement": null,
      "nextStatement": null,
      "category": Blockly.Categories.motion,
      "colour": Blockly.Colours.motion.primary,
      "colourSecondary": Blockly.Colours.motion.secondary,
      "colourTertiary": Blockly.Colours.motion.tertiary
    });
  }
};

Blockly.Blocks['motion_setx'] = {
  /**
   * Block to set X.
   * @this Blockly.Block
   */
  init: function() {
    this.jsonInit({
      "message0": "set x to %1",
      "args0": [
        {
          "type": "input_value",
          "name": "X"
        }
      ],
      "inputsInline": true,
      "previousStatement": null,
      "nextStatement": null,
      "category": Blockly.Categories.motion,
      "colour": Blockly.Colours.motion.primary,
      "colourSecondary": Blockly.Colours.motion.secondary,
      "colourTertiary": Blockly.Colours.motion.tertiary
    });
  }
};

Blockly.Blocks['motion_changeyby'] = {
  /**
   * Block to change Y.
   * @this Blockly.Block
   */
  init: function() {
    this.jsonInit({
      "message0": "change y by %1",
      "args0": [
        {
          "type": "input_value",
          "name": "DY"
        }
      ],
      "inputsInline": true,
      "previousStatement": null,
      "nextStatement": null,
      "category": Blockly.Categories.motion,
      "colour": Blockly.Colours.motion.primary,
      "colourSecondary": Blockly.Colours.motion.secondary,
      "colourTertiary": Blockly.Colours.motion.tertiary
    });
  }
};

Blockly.Blocks['motion_sety'] = {
  /**
   * Block to set Y.
   * @this Blockly.Block
   */
  init: function() {
    this.jsonInit({
      "message0": "set y to %1",
      "args0": [
        {
          "type": "input_value",
          "name": "Y"
        }
      ],
      "inputsInline": true,
      "previousStatement": null,
      "nextStatement": null,
      "category": Blockly.Categories.motion,
      "colour": Blockly.Colours.motion.primary,
      "colourSecondary": Blockly.Colours.motion.secondary,
      "colourTertiary": Blockly.Colours.motion.tertiary
    });
  }
};

Blockly.Blocks['motion_ifonedgebounce'] = {
  /**
   * Block to bounce on edge.
   * @this Blockly.Block
   */
  init: function() {
    this.jsonInit({
      "message0": "if on edge, bounce",
      "previousStatement": null,
      "nextStatement": null,
      "category": Blockly.Categories.motion,
      "colour": Blockly.Colours.motion.primary,
      "colourSecondary": Blockly.Colours.motion.secondary,
      "colourTertiary": Blockly.Colours.motion.tertiary
    });
  }
};

Blockly.Blocks['motion_setrotationstyle_menu'] = {
  /**
   * Rotation style drop-down menu.
   * @this Blockly.Block
   */
  init: function() {
    this.jsonInit(
      {
        "message0": "%1",
        "args0": [
          {
            "type": "field_dropdown",
            "name": "STYLE",
            "options": [
              ['left-right', 'LEFT-RIGHT'],
              ['don\'t rotate', 'NONE'],
              ['all around', 'ALL']
            ]
          }
        ],
        "inputsInline": true,
        "output": "String",
        "colour": Blockly.Colours.motion.secondary,
        "colourSecondary": Blockly.Colours.motion.secondary,
        "colourTertiary": Blockly.Colours.motion.tertiary,
        "outputShape": Blockly.OUTPUT_SHAPE_ROUND
      });
  }
};

Blockly.Blocks['motion_setrotationstyle'] = {
  /**
   * Block to set rotation style.
   * @this Blockly.Block
   */
  init: function() {
    this.jsonInit({
      "message0": "set rotation style %1",
      "args0": [
        {
          "type": "input_value",
          "name": "STYLE"
        }
      ],
      "previousStatement": null,
      "nextStatement": null,
      "category": Blockly.Categories.motion,
      "colour": Blockly.Colours.motion.primary,
      "colourSecondary": Blockly.Colours.motion.secondary,
      "colourTertiary": Blockly.Colours.motion.tertiary
    });
  }
};

Blockly.Blocks['motion_xposition'] = {
  /**
   * Block to report X.
   * @this Blockly.Block
   */
  init: function() {
    this.jsonInit({
      "message0": "x position",
      "output": "Number",
      "outputShape": Blockly.OUTPUT_SHAPE_ROUND,
      "category": Blockly.Categories.motion,
      "colour": Blockly.Colours.motion.primary,
      "colourSecondary": Blockly.Colours.motion.secondary,
      "colourTertiary": Blockly.Colours.motion.tertiary,
      "checkboxInFlyout": true
    });
  }
};

Blockly.Blocks['motion_yposition'] = {
  /**
   * Block to report Y.
   * @this Blockly.Block
   */
  init: function() {
    this.jsonInit({
      "message0": "y position",
      "output": "Number",
      "outputShape": Blockly.OUTPUT_SHAPE_ROUND,
      "category": Blockly.Categories.motion,
      "colour": Blockly.Colours.motion.primary,
      "colourSecondary": Blockly.Colours.motion.secondary,
      "colourTertiary": Blockly.Colours.motion.tertiary,
      "checkboxInFlyout": true
    });
  }
};

Blockly.Blocks['motion_direction'] = {
  /**
   * Block to report direction.
   * @this Blockly.Block
   */
  init: function() {
    this.jsonInit({
      "message0": "direction",
      "output": "Number",
      "outputShape": Blockly.OUTPUT_SHAPE_ROUND,
      "category": Blockly.Categories.motion,
      "colour": Blockly.Colours.motion.primary,
      "colourSecondary": Blockly.Colours.motion.secondary,
      "colourTertiary": Blockly.Colours.motion.tertiary,
      "checkboxInFlyout": true
    });
  }
};
<commit_msg>Update rotation-style block to match VM and Scratch 2.0<commit_after>/**
 * @license
 * Visual Blocks Editor
 *
 * Copyright 2016 Massachusetts Institute of Technology
 * All rights reserved.
 *
 * 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';

goog.provide('Blockly.Blocks.motion');

goog.require('Blockly.Blocks');
goog.require('Blockly.Colours');
goog.require('Blockly.constants');

Blockly.Blocks['motion_movesteps'] = {
  /**
   * Block to move steps.
   * @this Blockly.Block
   */
  init: function() {
    this.jsonInit({
      "message0": "move %1 steps",
      "args0": [
        {
          "type": "input_value",
          "name": "STEPS"
        }
      ],
      "inputsInline": true,
      "previousStatement": null,
      "nextStatement": null,
      "category": Blockly.Categories.motion,
      "colour": Blockly.Colours.motion.primary,
      "colourSecondary": Blockly.Colours.motion.secondary,
      "colourTertiary": Blockly.Colours.motion.tertiary
    });
  }
};

Blockly.Blocks['motion_turnright'] = {
  /**
   * Block to turn right.
   * @this Blockly.Block
   */
  init: function() {
    this.jsonInit({
      "message0": "turn %1 %2 degrees",
      "args0": [
        {
          "type": "field_image",
          "src": Blockly.mainWorkspace.options.pathToMedia + "/turnright_arrow.png",
          "width": 16,
          "height": 16
        },
        {
          "type": "input_value",
          "name": "DEGREES"
        }
      ],
      "inputsInline": true,
      "previousStatement": null,
      "nextStatement": null,
      "category": Blockly.Categories.motion,
      "colour": Blockly.Colours.motion.primary,
      "colourSecondary": Blockly.Colours.motion.secondary,
      "colourTertiary": Blockly.Colours.motion.tertiary
    });
  }
};

Blockly.Blocks['motion_turnleft'] = {
  /**
   * Block to turn left.
   * @this Blockly.Block
   */
  init: function() {
    this.jsonInit({
      "message0": "turn %1 %2 degrees",
      "args0": [
        {
          "type": "field_image",
          "src": Blockly.mainWorkspace.options.pathToMedia + "/turnleft_arrow.png",
          "width": 16,
          "height": 16
        },
        {
          "type": "input_value",
          "name": "DEGREES"
        }
      ],
      "inputsInline": true,
      "previousStatement": null,
      "nextStatement": null,
      "category": Blockly.Categories.motion,
      "colour": Blockly.Colours.motion.primary,
      "colourSecondary": Blockly.Colours.motion.secondary,
      "colourTertiary": Blockly.Colours.motion.tertiary
    });
  }
};

Blockly.Blocks['motion_pointindirection'] = {
  /**
   * Block to point in direction.
   * @this Blockly.Block
   */
  init: function() {
    this.jsonInit({
      "message0": "point in direction %1",
      "args0": [
        {
          "type": "input_value",
          "name": "DIRECTION"
        }
      ],
      "inputsInline": true,
      "previousStatement": null,
      "nextStatement": null,
      "category": Blockly.Categories.motion,
      "colour": Blockly.Colours.motion.primary,
      "colourSecondary": Blockly.Colours.motion.secondary,
      "colourTertiary": Blockly.Colours.motion.tertiary
    });
  }
};

Blockly.Blocks['motion_pointtowards_menu'] = {
  /**
   * Point towards drop-down menu.
   * @this Blockly.Block
   */
  init: function() {
    this.jsonInit(
      {
        "message0": "%1",
        "args0": [
          {
            "type": "field_dropdown",
            "name": "TOWARDS",
            "options": [
              ['mouse-pointer', '_mouse_']
            ]
          }
        ],
        "inputsInline": true,
        "output": "String",
        "colour": Blockly.Colours.motion.secondary,
        "colourSecondary": Blockly.Colours.motion.secondary,
        "colourTertiary": Blockly.Colours.motion.tertiary,
        "outputShape": Blockly.OUTPUT_SHAPE_ROUND
      });
  }
};

Blockly.Blocks['motion_pointtowards'] = {
  /**
   * Block to point in direction.
   * @this Blockly.Block
   */
  init: function() {
    this.jsonInit({
      "message0": "point towards %1",
      "args0": [
        {
          "type": "input_value",
          "name": "TOWARDS"
        }
      ],
      "inputsInline": true,
      "previousStatement": null,
      "nextStatement": null,
      "category": Blockly.Categories.motion,
      "colour": Blockly.Colours.motion.primary,
      "colourSecondary": Blockly.Colours.motion.secondary,
      "colourTertiary": Blockly.Colours.motion.tertiary
    });
  }
};

Blockly.Blocks['motion_goto_menu'] = {
  /**
   * Go to drop-down menu.
   * @this Blockly.Block
   */
  init: function() {
    this.jsonInit(
      {
        "message0": "%1",
        "args0": [
          {
            "type": "field_dropdown",
            "name": "TO",
            "options": [
              ['mouse-pointer', '_mouse_'],
              ['random position', '_random_']
            ]
          }
        ],
        "inputsInline": true,
        "output": "String",
        "colour": Blockly.Colours.motion.secondary,
        "colourSecondary": Blockly.Colours.motion.secondary,
        "colourTertiary": Blockly.Colours.motion.tertiary,
        "outputShape": Blockly.OUTPUT_SHAPE_ROUND
      });
  }
};

Blockly.Blocks['motion_gotoxy'] = {
  /**
   * Block to go to X, Y.
   * @this Blockly.Block
   */
  init: function() {
    this.jsonInit({
      "message0": "go to x: %1 y: %2",
      "args0": [
        {
          "type": "input_value",
          "name": "X"
        },
        {
          "type": "input_value",
          "name": "Y"
        }
      ],
      "inputsInline": true,
      "previousStatement": null,
      "nextStatement": null,
      "category": Blockly.Categories.motion,
      "colour": Blockly.Colours.motion.primary,
      "colourSecondary": Blockly.Colours.motion.secondary,
      "colourTertiary": Blockly.Colours.motion.tertiary
    });
  }
};

Blockly.Blocks['motion_goto'] = {
  /**
   * Block to go to a menu item.
   * @this Blockly.Block
   */
  init: function() {
    this.jsonInit({
      "message0": "go to %1",
      "args0": [
        {
          "type": "input_value",
          "name": "TO"
        }
      ],
      "inputsInline": true,
      "previousStatement": null,
      "nextStatement": null,
      "category": Blockly.Categories.motion,
      "colour": Blockly.Colours.motion.primary,
      "colourSecondary": Blockly.Colours.motion.secondary,
      "colourTertiary": Blockly.Colours.motion.tertiary
    });
  }
};

Blockly.Blocks['motion_glidesecstoxy'] = {
  /**
   * Block to glide for a specified time.
   * @this Blockly.Block
   */
  init: function() {
    this.jsonInit({
      "message0": "glide %1 secs to x: %2 y: %3",
      "args0": [
        {
          "type": "input_value",
          "name": "SECS"
        },
        {
          "type": "input_value",
          "name": "X"
        },
        {
          "type": "input_value",
          "name": "Y"
        }
      ],
      "inputsInline": true,
      "previousStatement": null,
      "nextStatement": null,
      "category": Blockly.Categories.motion,
      "colour": Blockly.Colours.motion.primary,
      "colourSecondary": Blockly.Colours.motion.secondary,
      "colourTertiary": Blockly.Colours.motion.tertiary
    });
  }
};

Blockly.Blocks['motion_changexby'] = {
  /**
   * Block to change X.
   * @this Blockly.Block
   */
  init: function() {
    this.jsonInit({
      "message0": "change x by %1",
      "args0": [
        {
          "type": "input_value",
          "name": "DX"
        }
      ],
      "inputsInline": true,
      "previousStatement": null,
      "nextStatement": null,
      "category": Blockly.Categories.motion,
      "colour": Blockly.Colours.motion.primary,
      "colourSecondary": Blockly.Colours.motion.secondary,
      "colourTertiary": Blockly.Colours.motion.tertiary
    });
  }
};

Blockly.Blocks['motion_setx'] = {
  /**
   * Block to set X.
   * @this Blockly.Block
   */
  init: function() {
    this.jsonInit({
      "message0": "set x to %1",
      "args0": [
        {
          "type": "input_value",
          "name": "X"
        }
      ],
      "inputsInline": true,
      "previousStatement": null,
      "nextStatement": null,
      "category": Blockly.Categories.motion,
      "colour": Blockly.Colours.motion.primary,
      "colourSecondary": Blockly.Colours.motion.secondary,
      "colourTertiary": Blockly.Colours.motion.tertiary
    });
  }
};

Blockly.Blocks['motion_changeyby'] = {
  /**
   * Block to change Y.
   * @this Blockly.Block
   */
  init: function() {
    this.jsonInit({
      "message0": "change y by %1",
      "args0": [
        {
          "type": "input_value",
          "name": "DY"
        }
      ],
      "inputsInline": true,
      "previousStatement": null,
      "nextStatement": null,
      "category": Blockly.Categories.motion,
      "colour": Blockly.Colours.motion.primary,
      "colourSecondary": Blockly.Colours.motion.secondary,
      "colourTertiary": Blockly.Colours.motion.tertiary
    });
  }
};

Blockly.Blocks['motion_sety'] = {
  /**
   * Block to set Y.
   * @this Blockly.Block
   */
  init: function() {
    this.jsonInit({
      "message0": "set y to %1",
      "args0": [
        {
          "type": "input_value",
          "name": "Y"
        }
      ],
      "inputsInline": true,
      "previousStatement": null,
      "nextStatement": null,
      "category": Blockly.Categories.motion,
      "colour": Blockly.Colours.motion.primary,
      "colourSecondary": Blockly.Colours.motion.secondary,
      "colourTertiary": Blockly.Colours.motion.tertiary
    });
  }
};

Blockly.Blocks['motion_ifonedgebounce'] = {
  /**
   * Block to bounce on edge.
   * @this Blockly.Block
   */
  init: function() {
    this.jsonInit({
      "message0": "if on edge, bounce",
      "previousStatement": null,
      "nextStatement": null,
      "category": Blockly.Categories.motion,
      "colour": Blockly.Colours.motion.primary,
      "colourSecondary": Blockly.Colours.motion.secondary,
      "colourTertiary": Blockly.Colours.motion.tertiary
    });
  }
};

Blockly.Blocks['motion_setrotationstyle_menu'] = {
  /**
   * Rotation style drop-down menu.
   * @this Blockly.Block
   */
  init: function() {
    this.jsonInit(
      {
        "message0": "%1",
        "args0": [
          {
            "type": "field_dropdown",
            "name": "STYLE",
            "options": [
              ['left-right', 'left-right'],
              ['don\'t rotate', 'don\'t rotate'],
              ['all around', 'all around']
            ]
          }
        ],
        "inputsInline": true,
        "output": "String",
        "colour": Blockly.Colours.motion.secondary,
        "colourSecondary": Blockly.Colours.motion.secondary,
        "colourTertiary": Blockly.Colours.motion.tertiary,
        "outputShape": Blockly.OUTPUT_SHAPE_ROUND
      });
  }
};

Blockly.Blocks['motion_setrotationstyle'] = {
  /**
   * Block to set rotation style.
   * @this Blockly.Block
   */
  init: function() {
    this.jsonInit({
      "message0": "set rotation style %1",
      "args0": [
        {
          "type": "input_value",
          "name": "STYLE"
        }
      ],
      "previousStatement": null,
      "nextStatement": null,
      "category": Blockly.Categories.motion,
      "colour": Blockly.Colours.motion.primary,
      "colourSecondary": Blockly.Colours.motion.secondary,
      "colourTertiary": Blockly.Colours.motion.tertiary
    });
  }
};

Blockly.Blocks['motion_xposition'] = {
  /**
   * Block to report X.
   * @this Blockly.Block
   */
  init: function() {
    this.jsonInit({
      "message0": "x position",
      "output": "Number",
      "outputShape": Blockly.OUTPUT_SHAPE_ROUND,
      "category": Blockly.Categories.motion,
      "colour": Blockly.Colours.motion.primary,
      "colourSecondary": Blockly.Colours.motion.secondary,
      "colourTertiary": Blockly.Colours.motion.tertiary,
      "checkboxInFlyout": true
    });
  }
};

Blockly.Blocks['motion_yposition'] = {
  /**
   * Block to report Y.
   * @this Blockly.Block
   */
  init: function() {
    this.jsonInit({
      "message0": "y position",
      "output": "Number",
      "outputShape": Blockly.OUTPUT_SHAPE_ROUND,
      "category": Blockly.Categories.motion,
      "colour": Blockly.Colours.motion.primary,
      "colourSecondary": Blockly.Colours.motion.secondary,
      "colourTertiary": Blockly.Colours.motion.tertiary,
      "checkboxInFlyout": true
    });
  }
};

Blockly.Blocks['motion_direction'] = {
  /**
   * Block to report direction.
   * @this Blockly.Block
   */
  init: function() {
    this.jsonInit({
      "message0": "direction",
      "output": "Number",
      "outputShape": Blockly.OUTPUT_SHAPE_ROUND,
      "category": Blockly.Categories.motion,
      "colour": Blockly.Colours.motion.primary,
      "colourSecondary": Blockly.Colours.motion.secondary,
      "colourTertiary": Blockly.Colours.motion.tertiary,
      "checkboxInFlyout": true
    });
  }
};
<|endoftext|>


<commit_before>'use strict';

function escapeNonWords(s) {
    return s.replace(/[_\W]+/g, "-");
}

var socket = io();
var plots = {}; // Map of sensor -> chart
var rawlist = {};

//Variables used for the canvas.
var x_pos = 0;
var y_pos = 0;
var blocksize = 20;
var ball_size = 6;
var offset = ball_size/2; //Moves the ball object into center
//TODO: Find a dynamic offset value, maybe derive from c.height & c.width
var c, ctx, blocksize, ball;

setInterval(function() {
    for (var m in plots) {
        var plot = plots[m];
        if (typeof plot.redraw === "undefined") {
            continue
        }
        plot.redraw();
    }
}, 500);

socket.on('data', function(pkt){
    if ((~pkt.name.indexOf("GX") || ~pkt.name.indexOf("GY")) && "GX" in plots) {
        update_g_plot(pkt);	//Update the g-force plot
    } else if (pkt.name in plots) {
        // Update the plot
        var shift = plots[pkt.name].series[0].data.length > 400;
        plots[pkt.name].series[0].addPoint(pkt.value, false, shift);
        $('#' + escapeNonWords(name) + '-val').text(pkt.value.toFixed(2));
    } else {
        // Element does not exists, create it
        if (~pkt.name.indexOf("GX") || ~pkt.name.indexOf("GY")){
            create_g_plot();
        } else {
            //Element is a standard line plot
            //create_line_plot(pkt);
            if ($('#' + escapeNonWords(pkt.name) + '-val').length > 0) {
                $('#' + escapeNonWords(pkt.name) + '-val').text(pkt.value.toFixed(2));
            } else {
                $('#rawlist').append(
                    '
' +
                    ''+pkt.name+'	'+
                    ''+pkt.value.toFixed(2) +'	'+
                    '
'
                    );
                rawlist[pkt.name] = pkt;
            }
        }
    }
    $(function() {
        $("#plots").sortable();
        $("#plots").disableSelection();
    });
});

function is_in_circle(x) {
    x = x/4;                            //Only every 4th is a new pixel
    var y = Math.floor(x/ball_size);    //New line for every ball_size pixels
    x = x%ball_size;
    var dist_center = Math.sqrt(Math.pow(ball_size/2 - x, 2) + Math.pow(ball_size/2 - y, 2)); //Euclidian distance to center
    if (dist_center >= ball_size/2.5) {
        return false;
    } else {
        return true;
    }
}

function update_g_plot(packet){
	if (~packet.name.indexOf("GX")) {
        x_pos = packet.value;
    } else {
    //GY-event is usually sent directly after GX-event
    //so we do not update at both events
        y_pos = packet.value;
        ctx.clearRect(0,0,c.width,c.height);                                                //Clear the canvas
        ctx.stroke();                                                                       //Apply grid colors again
        ctx.putImageData(ball, c.width/2 + x_pos*blocksize - offset, c.height/2 + y_pos*blocksize - offset);  //Place ball object
    }
}

function create_g_plot() {
	//Element is a G-force graph - only make on GX event.
	//GX, GY is a html5 canvas element
	$('#plots').append('<canvas class="ui-state-default" id="GX"/>');
	c = document.getElementById("GX");
	ctx = c.getContext("2d");
	ctx.strokeStyle = "lightgrey";
	plots["GX"] = ctx; //Store canvas context in plots so it can be used out of scope.

	//Make the grid
	for (var i = 0; i < c.width/2; i+=blocksize) {
	    ctx.moveTo(c.width/2 + i, 0)
	    ctx.lineTo(c.width/2 + i, c.height)
	    ctx.moveTo(c.width/2 - i, 0)
	    ctx.lineTo(c.width/2 - i, c.height)
	};
	for (var i = 0; i < c.height/2; i+=blocksize) {
	    ctx.moveTo(0, c.height/2 + i)
	    ctx.lineTo(c.width, c.height/2 + i)
	    ctx.moveTo(0, c.height/2 - i)
	    ctx.lineTo(c.width, c.height/2 - i)
	};
	//Make the x and y axis more pronounced.
    ctx.moveTo(c.width/2, 0);
    ctx.lineTo(c.width/2, c.height);
    ctx.moveTo(0, c.height/2);
    ctx.lineTo(c.width, c.height/2);

	//Making a plot indicator object
	ball = ctx.createImageData(ball_size, ball_size); //Height = width => square

	//Paint it royal purple
	for (var i = 0; i < ball.data.length; i+=4) {
	    if (is_in_circle(i)) {
	        ball.data[i] = 120;     //Red 0-255
	        ball.data[i+1] = 81;     //Blue
	        ball.data[i+2] = 169;     //Green
	        ball.data[i+3] = 255;   //Alpha - transparancy
	    } else {
	        ball.data[i] = 0;       //Red
	        ball.data[i+1] = 0;     //Blue
	        ball.data[i+2] = 0;     //Green
	        ball.data[i+3] = 0;     //Alpha - transparancy
	    }
	};
	//Apply our lines onto ctx.
	ctx.stroke();
	ctx.putImageData(ball, c.width/2 - offset, c.height/2 - offset);
}

function create_line_plot(name, value) {
    //No graph exists, create it
    if ($('#' + escapeNonWords(name) + '-graph').length == 0) {
        $('#plots').append('
');
       	//$('#rawlist').append('
<input type="checkbox" class="ui-state-default" id="' + escapeNonWords(packet.name) + '">' + _.escape(packet.name) + '
');
        //$("#rawlist").append('
' + packet.name + ": " + Math.floor(packet.value) + '
');
        plots[name] = new Highcharts.Chart({
            chart: {
                renderTo: escapeNonWords(name)+'-graph',
                defaultSeriesType: 'spline',
                valueDecimals: 2,
                animation: false,
            },
            title: {
                text: _.escape(name),
            },
            xAxis: {
                labels: {
                    format: '{value:.2f}',
                },
            },
            yAxis: {
                title: {
                    text: 'Value',
                },
                labels: {
                    format: '{value:.2f}'
                },
            },
            plotOptions: {
                series: {
                    enableMouseTracking: false,
                    animation: false,
                    marker : {
                        enabled: false
                    }
                },
            },
            series: [{
                name: _.escape(name),
                data: [value],
            }],
        });
    } else {  //ELement already exists, so we delete it
        plots[name].destroy();
        $('#'+ escapeNonWords(name) + '-graph').remove();
        delete plots[name];
    }
}
<commit_msg>Rawlist always updates value if it contains the proper data package<commit_after>'use strict';

function escapeNonWords(s) {
    return s.replace(/[_\W]+/g, "-");
}

var socket = io();
var plots = {}; // Map of sensor -> chart
var rawlist = {};

//Variables used for the canvas.
var x_pos = 0;
var y_pos = 0;
var blocksize = 20;
var ball_size = 6;
var offset = ball_size/2; //Moves the ball object into center
//TODO: Find a dynamic offset value, maybe derive from c.height & c.width
var c, ctx, blocksize, ball;

setInterval(function() {
    for (var m in plots) {
        var plot = plots[m];
        if (typeof plot.redraw === "undefined") {
            continue
        }
        plot.redraw();
    }
}, 500);

socket.on('data', function(pkt){
	if (pkt.name in rawlist) {
		document.getElementById(escapeNonWords(pkt.name) + '-val').innerHTML = pkt.value.toFixed(2);
	};
    if ((~pkt.name.indexOf("GX") || ~pkt.name.indexOf("GY")) && "GX" in plots) {
        update_g_plot(pkt);	//Update the g-force plot
    } else if (pkt.name in plots) {
        // Update the plot
        var shift = plots[pkt.name].series[0].data.length > 400;
        plots[pkt.name].series[0].addPoint(pkt.value, false, shift);
        $('#' + escapeNonWords(name) + '-val').text(pkt.value.toFixed(2));
    } else {
        // Element does not exists, create it
        if (~pkt.name.indexOf("GX") || ~pkt.name.indexOf("GY")){
            create_g_plot();
        } else {
            //Element is a standard line plot
            //create_line_plot(pkt);
            if ($('#' + escapeNonWords(pkt.name) + '-val').length > 0) {
                $('#' + escapeNonWords(pkt.name) + '-val').text(pkt.value.toFixed(2));
            } else {
                $('#rawlist').append(
                    '
' +
                    ''+pkt.name+'	'+
                    ''+pkt.value.toFixed(2) +'	'+
                    '
'
                    );
                rawlist[pkt.name] = pkt;
            }
        }
    }
    $(function() {
        $("#plots").sortable();
        $("#plots").disableSelection();
    });
});

function is_in_circle(x) {
    x = x/4;                            //Only every 4th is a new pixel
    var y = Math.floor(x/ball_size);    //New line for every ball_size pixels
    x = x%ball_size;
    var dist_center = Math.sqrt(Math.pow(ball_size/2 - x, 2) + Math.pow(ball_size/2 - y, 2)); //Euclidian distance to center
    if (dist_center >= ball_size/2.5) {
        return false;
    } else {
        return true;
    }
}

function update_g_plot(packet){
	if (~packet.name.indexOf("GX")) {
        x_pos = packet.value;
    } else {
    //GY-event is usually sent directly after GX-event
    //so we do not update at both events
        y_pos = packet.value;
        ctx.clearRect(0,0,c.width,c.height);                                                //Clear the canvas
        ctx.stroke();                                                                       //Apply grid colors again
        ctx.putImageData(ball, c.width/2 + x_pos*blocksize - offset, c.height/2 + y_pos*blocksize - offset);  //Place ball object
    }
}

function create_g_plot() {
	//Element is a G-force graph - only make on GX event.
	//GX, GY is a html5 canvas element
	$('#plots').append('<canvas class="ui-state-default" id="GX"/>');
	c = document.getElementById("GX");
	ctx = c.getContext("2d");
	ctx.strokeStyle = "lightgrey";
	plots["GX"] = ctx; //Store canvas context in plots so it can be used out of scope.

	//Make the grid
	for (var i = 0; i < c.width/2; i+=blocksize) {
	    ctx.moveTo(c.width/2 + i, 0)
	    ctx.lineTo(c.width/2 + i, c.height)
	    ctx.moveTo(c.width/2 - i, 0)
	    ctx.lineTo(c.width/2 - i, c.height)
	};
	for (var i = 0; i < c.height/2; i+=blocksize) {
	    ctx.moveTo(0, c.height/2 + i)
	    ctx.lineTo(c.width, c.height/2 + i)
	    ctx.moveTo(0, c.height/2 - i)
	    ctx.lineTo(c.width, c.height/2 - i)
	};
	//Make the x and y axis more pronounced.
    ctx.moveTo(c.width/2, 0);
    ctx.lineTo(c.width/2, c.height);
    ctx.moveTo(0, c.height/2);
    ctx.lineTo(c.width, c.height/2);

	//Making a plot indicator object
	ball = ctx.createImageData(ball_size, ball_size); //Height = width => square

	//Paint it royal purple
	for (var i = 0; i < ball.data.length; i+=4) {
	    if (is_in_circle(i)) {
	        ball.data[i] = 120;     //Red 0-255
	        ball.data[i+1] = 81;     //Blue
	        ball.data[i+2] = 169;     //Green
	        ball.data[i+3] = 255;   //Alpha - transparancy
	    } else {
	        ball.data[i] = 0;       //Red
	        ball.data[i+1] = 0;     //Blue
	        ball.data[i+2] = 0;     //Green
	        ball.data[i+3] = 0;     //Alpha - transparancy
	    }
	};
	//Apply our lines onto ctx.
	ctx.stroke();
	ctx.putImageData(ball, c.width/2 - offset, c.height/2 - offset);
}

function create_line_plot(name, value) {
    //No graph exists, create it
    if ($('#' + escapeNonWords(name) + '-graph').length == 0) {
        $('#plots').append('
');
        plots[name] = new Highcharts.Chart({
            chart: {
                renderTo: escapeNonWords(name)+'-graph',
                defaultSeriesType: 'spline',
                valueDecimals: 2,
                animation: false,
            },
            title: {
                text: _.escape(name),
            },
            xAxis: {
                labels: {
                    format: '{value:.2f}',
                },
            },
            yAxis: {
                title: {
                    text: 'Value',
                },
                labels: {
                    format: '{value:.2f}'
                },
            },
            plotOptions: {
                series: {
                    enableMouseTracking: false,
                    animation: false,
                    marker : {
                        enabled: false
                    }
                },
            },
            series: [{
                name: _.escape(name),
                data: [value],
            }],
        });
    } else {  //ELement already exists, so we delete it
        plots[name].destroy();
        $('#'+ escapeNonWords(name) + '-graph').remove();
        delete plots[name];
    }
}
<|endoftext|>


<commit_before>module.exports = function(sails) {

	/**
	 * Module dependencies.
	 */

	var interpret	= require('./interpreter/interpret')(sails),
		getVerb		= require('./interpreter/getVerb'),
		_			= require('lodash');

	/**
	 * Fired after a socket is connected
	 */

	return function onConnect (socket) {
		sails.log.verbose('A socket.io client ('+ socket.id + ') connected successfully!');

		// Legacy support of `message`
		mapRoute('message');

		// Verb support
		mapRoute('get');
		mapRoute('post');
		mapRoute('put');
		mapRoute('delete');

		// Configurable custom onConnect logic here
		// (default: do nothing)
		if (sails.config.sockets.onConnect) {
			sails.session.fromSocket(socket, function sessionReady (err, session) {

				// If an error occurred loading the session, log what happened
				if (err) {
					sails.log.error(err);
					return;
				}

				// But continue on to run event handler either way
				sails.config.sockets.onConnect(session, socket);

			});
		}

		// Configurable custom onConnect logic here
		// (default: do nothing)
		if (sails.config.sockets.onDisconnect) {
			socket.on('disconnect', function onSocketDisconnect () {
				sails.session.fromSocket(socket, function sessionReady (err, session) {

					// If an error occurred loading the session, log what happened
					if (err) {
						sails.log.error(err);
						return;
					}

					// But continue on to run event handler either way
					sails.config.sockets.onDisconnect(session, socket);
				});
		    });
		}

		// Map a socket message to the router
		function mapRoute (messageName) {
			socket.on(messageName, function (socketReq, callback) {

				sails.log.verbose('Routing message over socket: ', socketReq);

				callback = callback || function noCallback(body, status) {
					sails.log.error('No callback specified!');
				};

				var verb = getVerb(socketReq, messageName);

				// Translate socket.io message to an Express-looking request
				interpret(socketReq, callback, socket, verb, function requestBuilt (err, request) {

					// If interpretation fails, log the error and do nothing
					if (err) {
						sails.log.error(err);
						return;
					}

					// Route socket.io request
					sails.emit('router:request', request.req, request.res);
				});

			});
		}
	};

};
<commit_msg>Whitespace.<commit_after>module.exports = function(sails) {

	/**
	 * Module dependencies.
	 */

	var interpret	= require('./interpreter/interpret')(sails),
		getVerb		= require('./interpreter/getVerb'),
		_			= require('lodash');

	/**
	 * Fired after a socket is connected
	 */

	return function onConnect (socket) {
		sails.log.verbose('A socket.io client ('+ socket.id + ') connected successfully!');

		// Legacy support of `message`
		mapRoute('message');

		// Verb support
		mapRoute('get');
		mapRoute('post');
		mapRoute('put');
		mapRoute('delete');

		// Configurable custom onConnect logic here
		// (default: do nothing)
		if (sails.config.sockets.onConnect) {
			sails.session.fromSocket(socket, function sessionReady (err, session) {

				// If an error occurred loading the session, log what happened
				if (err) {
					sails.log.error(err);
					return;
				}

				// But continue on to run event handler either way
				sails.config.sockets.onConnect(session, socket);

			});
		}

		// Configurable custom onConnect logic here
		// (default: do nothing)
		if (sails.config.sockets.onDisconnect) {
			socket.on('disconnect', function onSocketDisconnect () {
				sails.session.fromSocket(socket, function sessionReady (err, session) {

					// If an error occurred loading the session, log what happened
					if (err) {
						sails.log.error(err);
						return;
					}

					// But continue on to run event handler either way
					sails.config.sockets.onDisconnect(session, socket);
				});
		  });
		}

		// Map a socket message to the router
		function mapRoute (messageName) {
			socket.on(messageName, function (socketReq, callback) {

				sails.log.verbose('Routing message over socket: ', socketReq);

				callback = callback || function noCallback(body, status) {
					sails.log.error('No callback specified!');
				};

				var verb = getVerb(socketReq, messageName);

				// Translate socket.io message to an Express-looking request
				interpret(socketReq, callback, socket, verb, function requestBuilt (err, request) {

					// If interpretation fails, log the error and do nothing
					if (err) {
						sails.log.error(err);
						return;
					}

					// Route socket.io request
					sails.emit('router:request', request.req, request.res);
				});

			});
		}
	};

};
<|endoftext|>


<commit_before>const {Subject} = require('rxjs')
const {first, takeUntil} = require('rxjs/operators')
const log = require('sepalLog')()

const errorCodes = {
    'system': 500,
    'notfound': 404,
    'default': 400
}

const errorCode = type =>
    errorCodes[type] || 500

const logError = error =>
    log.error(
        error.cause && error.cause.stack
            ? error.cause.stack
            : error
    )

const handleError = (ctx, error) => {
    logError(error)
    ctx.status = errorCode(error.type)
    ctx.body = error.type
        ? {
            code: error.key,
            data: error.data,
            // cause: error.cause
        }
        : 'other error'
}

const handleSuccess = (ctx, value) =>
    ctx.body = value

const renderStream = async (ctx, body$) => {
    try {
        handleSuccess(ctx, await body$.toPromise())
    } catch (error) {
        handleError(ctx, error)
    }
}

const handleHttp = async ctx => {
    const close$ = new Subject()
    ctx.req.on('close', () => close$.next())
    const body$ = ctx.result$.pipe(
        first(),
        takeUntil(close$)
    )
    await renderStream(ctx, body$)
}

const handleWebsocket = async ctx => {
    const ws = await ctx.ws()
    const close$ = new Subject()

    ws.on('close', () => {
        close$.next()
        ws.terminate()
    })

    ws.on('message', message =>
        ctx.args$.next(message)
    )

    ctx.result$.pipe(
        takeUntil(close$)
    ).subscribe(
        result => {
            result.value && ws.send(result.value)
        },
        // [TODO] handle error
    )
}

const stream = func => {
    return ctx => {
        ctx.args$ = new Subject()
        ctx.result$ = func(ctx)
    }
}

const resolve = async (ctx, next) => {
    await next()
    if (ctx.result$) {
        ctx.ws
            ? await handleWebsocket(ctx)
            : await handleHttp(ctx)
    }
}

module.exports = {resolve, stream}
<commit_msg>Fixed unwrapping of websocket stream.<commit_after>const {Subject} = require('rxjs')
const {first, takeUntil} = require('rxjs/operators')
const log = require('sepalLog')()

const errorCodes = {
    'system': 500,
    'notfound': 404,
    'default': 400
}

const errorCode = type =>
    errorCodes[type] || 500

const logError = error =>
    log.error(
        error.cause && error.cause.stack
            ? error.cause.stack
            : error
    )

const handleError = (ctx, error) => {
    logError(error)
    ctx.status = errorCode(error.type)
    ctx.body = error.type
        ? {
            code: error.key,
            data: error.data,
            // cause: error.cause
        }
        : 'other error'
}

const handleSuccess = (ctx, value) =>
    ctx.body = value

const renderStream = async (ctx, body$) => {
    try {
        handleSuccess(ctx, await body$.toPromise())
    } catch (error) {
        handleError(ctx, error)
    }
}

const handleHttp = async ctx => {
    const close$ = new Subject()
    ctx.req.on('close', () => close$.next())
    const body$ = ctx.result$.pipe(
        first(),
        takeUntil(close$)
    )
    await renderStream(ctx, body$)
}

const handleWebsocket = async ctx => {
    const ws = await ctx.ws()
    const close$ = new Subject()

    ws.on('close', () => {
        close$.next()
        ws.terminate()
    })

    ws.on('message', message =>
        ctx.args$.next(message)
    )

    ctx.result$.pipe(
        takeUntil(close$)
    ).subscribe({
        next: value => ws.send(value),
        error: error => ws.error(error)
    })
}

const stream = func => {
    return ctx => {
        ctx.args$ = new Subject()
        ctx.result$ = func(ctx)
    }
}

const resolve = async (ctx, next) => {
    await next()
    if (ctx.result$) {
        ctx.ws
            ? await handleWebsocket(ctx)
            : await handleHttp(ctx)
    }
}

module.exports = {resolve, stream}
<|endoftext|>


<commit_before><commit_msg>Set the cacheHit property on req.ext<commit_after><|endoftext|>


<commit_before>const EventResponse = require('../EventResponse');

class Issue extends EventResponse {
  constructor(...args) {
    super(...args, {
      description: 'This event gets fired when a new issue is created or an existing issue was updated/closed/reopened',
    });
  }

  embed(data) {
    let issue = data.object_attributes;
    return {
      color: 0xE9642D,
      title: `Opened issue #${issue.iid}: \`${issue.title}\``,
      description: `${issue.description}`,
    };
  }

  text(data) {
    const actor = data.user.username;
    const issue = data.object_attributes;
    return [
      `**${actor}** opened issue **#${issue.iid}**`,
      `        ${issue.title}`,
      `<${issue.url}>`,
    ].join('\n');
  }
}

module.exports = Issue;
<commit_msg>GitLab Events: Fixed issue/open - text didnt have icon and used username instead of name<commit_after>const EventResponse = require('../EventResponse');

class Issue extends EventResponse {
  constructor(...args) {
    super(...args, {
      description: 'This event gets fired when a new issue is created or an existing issue was updated/closed/reopened',
    });
  }

  embed(data) {
    let issue = data.object_attributes;
    return {
      color: 0xE9642D,
      title: `Opened issue #${issue.iid}: \`${issue.title}\``,
      description: `${issue.description}`,
    };
  }

  text(data) {
    const actor = data.user.name;
    const issue = data.object_attributes;
    return [
      `🛠  **${actor}** opened issue **#${issue.iid}**`,
      `        ${issue.title}`,
      `<${issue.url}>`,
    ].join('\n');
  }
}

module.exports = Issue;
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import PropTypes from 'prop-types'

import { connect } from 'react-redux'
import { Link } from 'react-router-dom'

import { fetchSosModelRuns, fetchSosModels,  fetchSectorModels,  fetchScenarios, fetchNarratives } from '../../actions/actions.js'
import { createSosModelRun, createSosModel, createSectorModel, createScenario, createNarrative } from '../../actions/actions.js'
import { deleteSosModelRun, deleteSosModel, deleteSectorModel, deleteScenario, deleteNarrative } from '../../actions/actions.js'

import Popup from '../../components/ConfigForm/General/Popup.js'
import ProjectOverviewItem from '../../components/ConfigForm/ProjectOverview/ProjectOverviewItem.js'

class ProjectOverview extends Component {
    constructor() {
        super()

        this.state = {
            createPopupIsOpen: false,
            createPopupHeader: 'none',
            createPopupType: 'none',
            deletePopupIsOpen: false,
            deletePopupHeader: 'none',
            deletePopupType: 'none'
        }

        this.closeCreatePopup = this.closeCreatePopup.bind(this)
        this.openCreatePopup = this.openCreatePopup.bind(this)
        this.createPopupSubmit = this.createPopupSubmit.bind(this)

        this.closeDeletePopup = this.closeDeletePopup.bind(this)
        this.openDeletePopup = this.openDeletePopup.bind(this)
        this.deletePopupSubmit = this.deletePopupSubmit.bind(this)

        this.handleInputChange = this.handleInputChange.bind(this)
        this.handleProjectSave = this.handleProjectSave.bind(this)
        this.handleCancel = this.handleCancel.bind(this)
    }

    componentWillMount () {
        const { dispatch } = this.props
        dispatch(fetchSosModelRuns())
        dispatch(fetchSosModels())
        dispatch(fetchSectorModels())
        dispatch(fetchScenarios())
        dispatch(fetchNarratives())
    }

    handleInputChange(event) {

        const target = event.target
        const value = target.type === 'checkbox' ? target.checked : target.value
        const name = target.name

        this.setState({
            [name]: value
        })
    }

    openCreatePopup(event) {

        this.setState({
            createPopupIsOpen: true,
            createPopupHeader: event.target.value,
            createPopupType: event.target.name
        })
    }

    createPopupSubmit() {

        const {createPopupType, createPopupName} = this.state
        const { dispatch } = this.props

        this.closeCreatePopup(createPopupType)

        switch(createPopupType) {
        case 'createSosModelRun':
            dispatch(createSosModelRun(createPopupName))
            dispatch(fetchSosModelRuns())
            break
        case 'createSosModel':
            dispatch(createSosModel(createPopupName))
            dispatch(fetchSosModels())
            break
        case 'createSectorModel':
            dispatch(createSectorModel(createPopupName))
            dispatch(fetchSectorModels())
            break
        case 'createScenario':
            dispatch(createScenario(createPopupName))
            dispatch(fetchScenarios())
            break
        case 'createNarrative':
            dispatch(createNarrative(createPopupName))
            dispatch(fetchNarratives())
            break
        }
    }

    closeCreatePopup() {
        this.setState({createPopupIsOpen: false})
    }

    openDeletePopup(event) {
        this.setState({
            deletePopupIsOpen: true,
            deletePopupHeader: event.target.value,
            deletePopupType: event.target.name
        })
    }

    deletePopupSubmit() {

        const {deletePopupType, deletePopupHeader} = this.state
        const { dispatch } = this.props

        this.closeDeletePopup(deletePopupType)

        switch(deletePopupType) {
        case 'deleteSosModelRun':
            dispatch(deleteSosModelRun(deletePopupHeader))
            dispatch(fetchSosModelRuns())
            break
        case 'deleteSosModel':
            dispatch(deleteSosModel(deletePopupHeader))
            dispatch(fetchSosModels())
            break
        case 'deleteSectorModel':
            dispatch(deleteSectorModel(deletePopupHeader))
            dispatch(fetchSectorModels())
            break
        case 'deleteScenario':
            dispatch(deleteScenario(deletePopupHeader))
            dispatch(fetchScenarios())
            break
        case 'deleteNarrative':
            dispatch(deleteNarrative(deletePopupHeader))
            dispatch(fetchNarratives())
            break
        }
    }

    closeDeletePopup() {
        this.setState({deletePopupIsOpen: false})
    }

    render () {
        const { sos_model_runs, sos_models, sector_models, scenarios, narratives, isFetching } = this.props

        return (

                    Loading...

                    Error

                            Project information

                                Name

                                    <input className="form-control" type="text" defaultValue="NISMOD v2.0"/>

                            Model Runs

                            <ProjectOverviewItem itemname="SosModelRun" items={sos_model_runs} itemLink="/configure/sos-model-run/" onDelete={this.openDeletePopup} />
                            <input className="btn btn-secondary btn-lg btn-block" name="createSosModelRun" type="button" value="Create a new Model Run" onClick={this.openCreatePopup}/>

                            System-of-Systems Models

                            <ProjectOverviewItem itemname="SosModel" items={sos_models} itemLink="/configure/sos-models/" onDelete={this.openDeletePopup} />
                            <input className="btn btn-secondary btn-lg btn-block" name="createSosModel" type="button" value="Create a new System-of-Systems Model" onClick={this.openCreatePopup}/>

                            Simulation Model

                            <ProjectOverviewItem itemname="SectorModel" items={sector_models} itemLink="/configure/sector-models/" onDelete={this.openDeletePopup} />
                            <input className="btn btn-secondary btn-lg btn-block" name="createSectorModel" type="button" value="Create a new Simulation Model" onClick={this.openCreatePopup}/>

                            Scenarios

                            <ProjectOverviewItem itemname="Scenario" items={scenarios} itemLink="/configure/scenarios/" onDelete={this.openDeletePopup} />
                            <input className="btn btn-secondary btn-lg btn-block" name="createScenario" type="button" value="Create a new Scenario" onClick={this.openCreatePopup}/>

                            Narratives

                            <ProjectOverviewItem itemname="Narrative" items={narratives} itemLink="/configure/narratives/" onDelete={this.openDeletePopup} />
                            <input className="btn btn-secondary btn-lg btn-block" name="createNarrative" type="button" value="Create a new Narrative" onClick={this.openCreatePopup}/>

                    {/* Popup for Create */}
                    <Popup onRequestOpen={this.state.createPopupIsOpen}>
                        <form onSubmit={(e) => {e.preventDefault(); e.stopPropagation(); this.createPopupSubmit()}}>

 this.subtitle = subtitle}>{this.state.createPopupHeader}

                                Name

                                    <input className="form-control" name="createPopupName" type="text" onChange={this.handleInputChange} required/>

                            <input className="btn btn-secondary btn-lg btn-block" type="submit" value="Create"/>
                            <input className="btn btn-secondary btn-lg btn-block" type="button" value="Cancel" onClick={this.closeCreatePopup}/>
                        </form>
                    </Popup>

                    {/* Popup for Delete */}
                    <Popup onRequestOpen={this.state.deletePopupIsOpen}>
                        <form onSubmit={(e) => {e.preventDefault(); e.stopPropagation(); this.deletePopupSubmit()}}>

 this.subtitle = subtitle}>Confirm delete

                            Are you sure you would like to delete {this.state.deletePopupHeader}?

                            <input className="btn btn-secondary btn-lg btn-block" type="submit" value="Delete"/>
                            <input className="btn btn-secondary btn-lg btn-block" type="button" value="Cancel" onClick={this.closeDeletePopup}/>
                        </form>
                    </Popup>

        )
    }
}

ProjectOverview.propTypes = {
    sos_model_runs: PropTypes.array.isRequired,
    sos_models: PropTypes.array.isRequired,
    sector_models: PropTypes.array.isRequired,
    scenarios: PropTypes.array.isRequired,
    narratives: PropTypes.array.isRequired,
    isFetching: PropTypes.bool.isRequired,
    dispatch: PropTypes.func.isRequired
}

function mapStateToProps(state) {
    const { sos_model_runs, sos_models, sector_models, scenarios, narratives } = state

    return {
        sos_model_runs: sos_model_runs.items,
        sos_models: sos_models.items,
        sector_models: sector_models.items,
        scenarios: scenarios.items,
        narratives: narratives.items,
        isFetching: false
    }
}

export default connect(mapStateToProps)(ProjectOverview)
<commit_msg>Remove Project Save handles<commit_after>import React, { Component } from 'react'
import PropTypes from 'prop-types'

import { connect } from 'react-redux'
import { Link } from 'react-router-dom'

import { fetchSosModelRuns, fetchSosModels,  fetchSectorModels,  fetchScenarios, fetchNarratives } from '../../actions/actions.js'
import { createSosModelRun, createSosModel, createSectorModel, createScenario, createNarrative } from '../../actions/actions.js'
import { deleteSosModelRun, deleteSosModel, deleteSectorModel, deleteScenario, deleteNarrative } from '../../actions/actions.js'

import Popup from '../../components/ConfigForm/General/Popup.js'
import ProjectOverviewItem from '../../components/ConfigForm/ProjectOverview/ProjectOverviewItem.js'

class ProjectOverview extends Component {
    constructor() {
        super()

        this.state = {
            createPopupIsOpen: false,
            createPopupHeader: 'none',
            createPopupType: 'none',
            deletePopupIsOpen: false,
            deletePopupHeader: 'none',
            deletePopupType: 'none'
        }

        this.closeCreatePopup = this.closeCreatePopup.bind(this)
        this.openCreatePopup = this.openCreatePopup.bind(this)
        this.createPopupSubmit = this.createPopupSubmit.bind(this)

        this.closeDeletePopup = this.closeDeletePopup.bind(this)
        this.openDeletePopup = this.openDeletePopup.bind(this)
        this.deletePopupSubmit = this.deletePopupSubmit.bind(this)

        this.handleInputChange = this.handleInputChange.bind(this)
    }

    componentWillMount () {
        const { dispatch } = this.props
        dispatch(fetchSosModelRuns())
        dispatch(fetchSosModels())
        dispatch(fetchSectorModels())
        dispatch(fetchScenarios())
        dispatch(fetchNarratives())
    }

    handleInputChange(event) {

        const target = event.target
        const value = target.type === 'checkbox' ? target.checked : target.value
        const name = target.name

        this.setState({
            [name]: value
        })
    }

    openCreatePopup(event) {

        this.setState({
            createPopupIsOpen: true,
            createPopupHeader: event.target.value,
            createPopupType: event.target.name
        })
    }

    createPopupSubmit() {

        const {createPopupType, createPopupName} = this.state
        const { dispatch } = this.props

        this.closeCreatePopup(createPopupType)

        switch(createPopupType) {
        case 'createSosModelRun':
            dispatch(createSosModelRun(createPopupName))
            dispatch(fetchSosModelRuns())
            break
        case 'createSosModel':
            dispatch(createSosModel(createPopupName))
            dispatch(fetchSosModels())
            break
        case 'createSectorModel':
            dispatch(createSectorModel(createPopupName))
            dispatch(fetchSectorModels())
            break
        case 'createScenario':
            dispatch(createScenario(createPopupName))
            dispatch(fetchScenarios())
            break
        case 'createNarrative':
            dispatch(createNarrative(createPopupName))
            dispatch(fetchNarratives())
            break
        }
    }

    closeCreatePopup() {
        this.setState({createPopupIsOpen: false})
    }

    openDeletePopup(event) {
        this.setState({
            deletePopupIsOpen: true,
            deletePopupHeader: event.target.value,
            deletePopupType: event.target.name
        })
    }

    deletePopupSubmit() {

        const {deletePopupType, deletePopupHeader} = this.state
        const { dispatch } = this.props

        this.closeDeletePopup(deletePopupType)

        switch(deletePopupType) {
        case 'deleteSosModelRun':
            dispatch(deleteSosModelRun(deletePopupHeader))
            dispatch(fetchSosModelRuns())
            break
        case 'deleteSosModel':
            dispatch(deleteSosModel(deletePopupHeader))
            dispatch(fetchSosModels())
            break
        case 'deleteSectorModel':
            dispatch(deleteSectorModel(deletePopupHeader))
            dispatch(fetchSectorModels())
            break
        case 'deleteScenario':
            dispatch(deleteScenario(deletePopupHeader))
            dispatch(fetchScenarios())
            break
        case 'deleteNarrative':
            dispatch(deleteNarrative(deletePopupHeader))
            dispatch(fetchNarratives())
            break
        }
    }

    closeDeletePopup() {
        this.setState({deletePopupIsOpen: false})
    }

    render () {
        const { sos_model_runs, sos_models, sector_models, scenarios, narratives, isFetching } = this.props

        return (

                    Loading...

                    Error

                            Project information

                                Name

                                    <input className="form-control" type="text" defaultValue="NISMOD v2.0"/>

                            Model Runs

                            <ProjectOverviewItem itemname="SosModelRun" items={sos_model_runs} itemLink="/configure/sos-model-run/" onDelete={this.openDeletePopup} />
                            <input className="btn btn-secondary btn-lg btn-block" name="createSosModelRun" type="button" value="Create a new Model Run" onClick={this.openCreatePopup}/>

                            System-of-Systems Models

                            <ProjectOverviewItem itemname="SosModel" items={sos_models} itemLink="/configure/sos-models/" onDelete={this.openDeletePopup} />
                            <input className="btn btn-secondary btn-lg btn-block" name="createSosModel" type="button" value="Create a new System-of-Systems Model" onClick={this.openCreatePopup}/>

                            Simulation Model

                            <ProjectOverviewItem itemname="SectorModel" items={sector_models} itemLink="/configure/sector-models/" onDelete={this.openDeletePopup} />
                            <input className="btn btn-secondary btn-lg btn-block" name="createSectorModel" type="button" value="Create a new Simulation Model" onClick={this.openCreatePopup}/>

                            Scenarios

                            <ProjectOverviewItem itemname="Scenario" items={scenarios} itemLink="/configure/scenarios/" onDelete={this.openDeletePopup} />
                            <input className="btn btn-secondary btn-lg btn-block" name="createScenario" type="button" value="Create a new Scenario" onClick={this.openCreatePopup}/>

                            Narratives

                            <ProjectOverviewItem itemname="Narrative" items={narratives} itemLink="/configure/narratives/" onDelete={this.openDeletePopup} />
                            <input className="btn btn-secondary btn-lg btn-block" name="createNarrative" type="button" value="Create a new Narrative" onClick={this.openCreatePopup}/>

                    {/* Popup for Create */}
                    <Popup onRequestOpen={this.state.createPopupIsOpen}>
                        <form onSubmit={(e) => {e.preventDefault(); e.stopPropagation(); this.createPopupSubmit()}}>

 this.subtitle = subtitle}>{this.state.createPopupHeader}

                                Name

                                    <input className="form-control" name="createPopupName" type="text" onChange={this.handleInputChange} required/>

                            <input className="btn btn-secondary btn-lg btn-block" type="submit" value="Create"/>
                            <input className="btn btn-secondary btn-lg btn-block" type="button" value="Cancel" onClick={this.closeCreatePopup}/>
                        </form>
                    </Popup>

                    {/* Popup for Delete */}
                    <Popup onRequestOpen={this.state.deletePopupIsOpen}>
                        <form onSubmit={(e) => {e.preventDefault(); e.stopPropagation(); this.deletePopupSubmit()}}>

 this.subtitle = subtitle}>Confirm delete

                            Are you sure you would like to delete {this.state.deletePopupHeader}?

                            <input className="btn btn-secondary btn-lg btn-block" type="submit" value="Delete"/>
                            <input className="btn btn-secondary btn-lg btn-block" type="button" value="Cancel" onClick={this.closeDeletePopup}/>
                        </form>
                    </Popup>

        )
    }
}

ProjectOverview.propTypes = {
    sos_model_runs: PropTypes.array.isRequired,
    sos_models: PropTypes.array.isRequired,
    sector_models: PropTypes.array.isRequired,
    scenarios: PropTypes.array.isRequired,
    narratives: PropTypes.array.isRequired,
    isFetching: PropTypes.bool.isRequired,
    dispatch: PropTypes.func.isRequired
}

function mapStateToProps(state) {
    const { sos_model_runs, sos_models, sector_models, scenarios, narratives } = state

    return {
        sos_model_runs: sos_model_runs.items,
        sos_models: sos_models.items,
        sector_models: sector_models.items,
        scenarios: scenarios.items,
        narratives: narratives.items,
        isFetching: false
    }
}

export default connect(mapStateToProps)(ProjectOverview)
<|endoftext|>