text:
(function() {
  var __slice = [].slice;
  var _types = typeof require !== 'undefined' ? require('ottypes') : window.ottypes;
  var _type = _types['http://sharejs.org/types/JSONv0'];

  // Helpers

  function depath(path) {
    if (path.length === 1 && path[0].constructor === Array) {
      return path[0];
    } else {
      return path;
    }
  }

  function traverse(snapshot, path) {
    var key = 'data';
    var elem = { data: snapshot };

    for (var i = 0; i < path.length; i++) {
      elem = elem[key];
      key = path[i];
      if (typeof elem === 'undefined') {
        throw new Error('bad path');
      }
    }

    return {
      elem: elem,
      key: key
    };
  }

  function pathEquals(p1, p2) {
    if (p1.length !== p2.length) {
      return false;
    }
    for (var i = 0; i < p1.length; ++i) {
      if (p1[i] !== p2[i]) {
        return false;
      }
    }
    return true;
  }

  function containsPath(p1, p2) {
    if (p1.length < p2.length) return false;
    return pathEquals( p1.slice(0,p2.length), p2);
  }

  // does nothing, used as a default callback
  function nullFunction() {}

  // given a path represented as an array or a number, normalize to an array
  // whole numbers are converted to integers.
  function normalizePath(path) {
    if (path instanceof Array) {
      return path;
    }
    if (typeof(path) == "number") {
      return [path];
    }
    // if (typeof(path) == "string") {
    //   path = path.split(".");
    //   var out = [];
    //   for (var i=0; i<path.length; i++) {
    //     var part = path[i];
    //     if (String(parseInt(part, 10)) == part) {
    //       out.push(parseInt(part, 10));
    //     } else {
    //       out.push(part);
    //     }
    //   }
    //   return out;
    // }
  }

  // helper for creating functions with the method signature func([path],arg1,arg2,...,[cb])
  // populates an array of arguments with a default path and callback
  function normalizeArgs(obj, args, func, requiredArgsCount){
    args = Array.prototype.slice.call(args);
    var path_prefix = obj.path || [];

    if (func.length > 1 && typeof args[args.length-1] !== 'function') {
      args.push(nullFunction);
    }

    if (args.length < (requiredArgsCount || func.length)) {
      args.unshift(path_prefix);
    } else {
      args[0] = path_prefix.concat(normalizePath(args[0]));
    }

    return func.apply(obj,args);
  }

  // SubDoc
  // this object is returned from context.createContextAt()

  var SubDoc = function(context, path) {
    this.context = context;
    this.path = path || [];
  };

  SubDoc.prototype._updatePath = function(op){
    console.log("UPDATEPATH", op);
    for (var i = 0; i < op.length; i++) {
      var c = op[i];
      if(c.lm !== undefined && containsPath(this.path,c.p)){
        var new_path_prefix = c.p.slice(0,c.p.length-1);
        new_path_prefix.push(c.lm);
        this.path = new_path_prefix.concat(this.path.slice(new_path_prefix.length));
      }
    }
  };

  SubDoc.prototype.createContextAt = function() {
    var path = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
    return this.context.createContextAt(this.path.concat(depath(path)));
  };

  SubDoc.prototype.get = function(path) {
    return normalizeArgs(this, arguments, function(path){
      return this.context.get(path);
    });
  };

  SubDoc.prototype.set = function(path, value, cb) {
    return normalizeArgs(this, arguments, function(path, value, cb){
      return this.context.set(path, value, cb);
    });
  };

  SubDoc.prototype.insert = function(path, value, cb) {
    return normalizeArgs(this, arguments, function(path, value, cb){
      return this.context.insert(path, value, cb);
    });
  };

  SubDoc.prototype.remove = function(path, len, cb) {
    return normalizeArgs(this, arguments, function(path, len, cb) {
      return this.context.remove(path, len, cb);
    }, 2);
  };

  SubDoc.prototype.push = function(path, value, cb) {
    return normalizeArgs(this, arguments, function(path, value, cb) {
        var _ref = traverse(this.context.getSnapshot(), path);
        var len = _ref.elem[_ref.key].length;
        path.push(len);
      return this.context.insert(path, value, cb);
    });
  };

  SubDoc.prototype.move = function(path, from, to, cb) {
    return normalizeArgs(this, arguments, function(path, from, to, cb) {
      console.log("sd MOVE");
      return this.context.move(path, from, to, cb);
    });
  };

  SubDoc.prototype.add = function(path, amount, cb) {
    return normalizeArgs(this, arguments, function(path, amount, cb) {
      return this.context.add(path, amount, cb);
    });
  };

  SubDoc.prototype.on = function(event, cb) {
    return this.context.addListener(this.path, event, cb);
  };

  SubDoc.prototype.removeListener = function(l) {
    return this.context.removeListener(l);
  };

  SubDoc.prototype.getLength = function(path) {
    return normalizeArgs(this, arguments, function(path) {
      return this.context.getLength(path);
    });
  };

  // DEPRECATED
  SubDoc.prototype.getText = function(path) {
    return normalizeArgs(this, arguments, function(path) {
      return this.context.getText(path);
    });
  };

  // DEPRECATED
  SubDoc.prototype.deleteText = function(path, pos, length, cb) {
    return normalizeArgs(this, arguments, function(path, pos, length, cb) {
      return this.context.deleteText(path, length, pos, cb);
    });
  };

  SubDoc.prototype.destroy = function() {
    this.context._removeSubDoc(this);
  };

  // JSON API methods
  // these methods are mixed in to the context return from doc.createContext()

  _type.api = {

    provides: {
      json: true
    },

    _fixComponentPaths: function(c) {
      if (!this._listeners) {
        return;
      }
      if (c.na !== undefined || c.si !== undefined || c.sd !== undefined) {
        return;
      }

      var to_remove = [];
      var _ref = this._listeners;

      for (var i = 0; i < _ref.length; i++) {
        var l = _ref[i];
        var dummy = {
          p: l.path,
          na: 0
        };
        var xformed = _type.transformComponent([], dummy, c, 'left');
        if (xformed.length === 0) {
          to_remove.push(i);
        } else if (xformed.length === 1) {
          l.path = xformed[0].p;
        } else {
          throw new Error("Bad assumption in json-api: xforming an 'na' op will always result in 0 or 1 components.");
        }
      }

      to_remove.sort(function(a, b) {
        return b - a;
      });

      var _results = [];
      for (var j = 0; j < to_remove.length; j++) {
        i = to_remove[j];
        _results.push(this._listeners.splice(i, 1));
      }

      return _results;
    },

    _fixPaths: function(op) {
      var _results = [];
      for (var i = 0; i < op.length; i++) {
        var c = op[i];
        _results.push(this._fixComponentPaths(c));
      }
      return _results;
    },

    _submit: function(op, callback) {
      this._fixPaths(op);
      return this.submitOp(op, callback);
    },

    _addSubDoc: function(subdoc){
      this._subdocs || (this._subdocs = []);
      this._subdocs.push(subdoc);
    },

    _removeSubDoc: function(subdoc){
      this._subdocs || (this._subdocs = []);
      for(var i = 0; i < this._subdocs.length; i++){
        if(this._subdocs[i] === subdoc) this._subdocs.splice(i,1);
        return;
      }
    },

    _updateSubdocPaths: function(op){
      this._subdocs || (this._subdocs = []);
      for(var i = 0; i < this._subdocs.length; i++){
        this._subdocs[i]._updatePath(op);
      }
    },

    createContextAt: function() {
      var path = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
      var subdoc =  new SubDoc(this, depath(path));
      this._addSubDoc(subdoc);
      return subdoc;
    },

    get: function(path) {
      if (!path) return this.getSnapshot();
      return normalizeArgs(this,arguments,function(path){
        var _ref = traverse(this.getSnapshot(), path);
        return _ref.elem[_ref.key];
      });
    },

    set: function(path, value, cb) {
      return normalizeArgs(this, arguments, function(path, value, cb) {
        var _ref = traverse(this.getSnapshot(), path);
        var elem = _ref.elem;
        var key = _ref.key;
        var op = {
          p: path
        };

        if (elem.constructor === Array) {
          op.li = value;
          if (typeof elem[key] !== 'undefined') {
            op.ld = elem[key];
          }
        } else if (typeof elem === 'object') {
          op.oi = value;
          if (typeof elem[key] !== 'undefined') {
            op.od = elem[key];
          }
        } else {
          throw new Error('bad path');
        }

        return this._submit([op], cb);
      });
    },

    remove: function(path, len, cb) {
      return normalizeArgs(this, arguments, function(path, len, cb) {
        if (!cb && len instanceof Function) {
          cb = len;
          len = null;
        }
        // if there is no len argument, then we are removing a single item from either a list or a hash
        var _ref, elem, op, key;
        if (len === null || len === undefined) {
          _ref = traverse(this.getSnapshot(), path);
          elem = _ref.elem;
          key = _ref.key;
          op = {
            p: path
          };

          if (typeof elem[key] === 'undefined') {
            throw new Error('no element at that path');
          }

          if (elem.constructor === Array) {
            op.ld = elem[key];
          } else if (typeof elem === 'object') {
            op.od = elem[key];
          } else {
            throw new Error('bad path');
          }
          return this._submit([op], cb);
        } else {
          var pos;
          pos = path.pop();
          _ref = traverse(this.getSnapshot(), path);
          elem = _ref.elem;
          key = _ref.key;
          if (typeof elem[key] === 'string') {
            op = {
              p: path.concat(pos),
              sd: _ref.elem[_ref.key].slice(pos, pos + len)
            };
            return this._submit([op], cb);
          } else if (elem[key].constructor === Array) {
            var ops = [];
            for (var i=pos; i<pos+len; i++) {
              ops.push({
                p: path.concat(pos),
                ld: elem[key][i]
              });
            }
            return this._submit(ops, cb);
          } else {
            throw new Error('element at path does not support range');
          }
        }
      }, 2);
    },

    insert: function(path, value, cb) {
      return normalizeArgs(this, arguments, function(path, value, cb) {
        var pos = path.pop();
        var _ref = traverse(this.getSnapshot(), path);
        var elem = _ref.elem;
        var key = _ref.key;
        var op = {
          p: path.concat(pos)
        };

        if (elem[key].constructor === Array) {
          op.li = value;
        } else if (typeof elem[key] === 'string') {
          op.si = value;
        }
        return this._submit([op], cb);
      });
    },

    move: function(path, from, to, cb) {
      return normalizeArgs(this, arguments, function(path, from, to, cb) {
        var self = this;
        var op = [
          {
            p: path.concat(from),
            lm: to
          }
        ];

        return this._submit(op, function(){
          self._updateSubdocPaths(op);
          if(cb) cb.apply(cb, arguments);
        });
      });
    },

    push: function(path, value, cb) {
      return normalizeArgs(this, arguments, function(path, value, cb) {
        var _ref = traverse(this.getSnapshot(), path);
        var len = _ref.elem[_ref.key].length;
        path.push(len);
        return this.insert(path, value, cb);
      });
    },

    add: function(path, amount, cb) {
      return normalizeArgs(this, arguments, function(path, value, cb) {
        var op = [
          {
            p: path,
            na: amount
          }
        ];
        return this._submit(op, cb);
      });
    },

    getLength: function(path) {
        return normalizeArgs(this, arguments, function(path) {
          return this.get(path).length;
        });
    },

    getText: function(path) {
      return normalizeArgs(this, arguments, function(path) {
        console.warn("Deprecated. Use `get()` instead");
        return this.get(path);
      });
    },

    deleteText: function(path, length, pos, cb) {
      return normalizeArgs(this, arguments, function(path, length, pos, cb) {
        console.warn("Deprecated. Use `remove(path, length, cb)` instead");
        var _ref = traverse(this.getSnapshot(), path);
        var op = [
          {
            p: path.concat(pos),
            sd: _ref.elem[_ref.key].slice(pos, pos + length)
          }
        ];

        return this._submit(op, cb);
      });
    },

    addListener: function(path, event, cb) {
      return normalizeArgs(this, arguments, function(path, value, cb) {
        var listener = {
          path: path,
          event: event,
          cb: cb
        };
        this._listeners || (this._listeners = []);
        this._listeners.push(listener);
        return listener;
      });
    },

    removeListener: function(listener) {
      if (!this._listeners) {
        return;
      }
      var i = this._listeners.indexOf(listener);
      if (i < 0) {
        return false;
      }
      this._listeners.splice(i, 1);
      return true;
    },

    _onOp: function(op) {
      for (var i = 0; i < op.length; i++) {
        var c = op[i];
        this._fixComponentPaths(c);

        if(c.lm !== undefined) {
          this._updateSubdocPaths([c]);
        }

        var match_path = c.na === undefined ? c.p.slice(0, c.p.length - 1) : c.p;

        for (var l = 0; l < this._listeners.length; l++) {
          var listener = this._listeners[l];
          var cb = listener.cb;

          if (pathEquals(listener.path, match_path)) {
            switch (listener.event) {
              case 'insert':
                if (c.li !== undefined && c.ld === undefined) {
                  cb(c.p[c.p.length - 1], c.li);
                } else if (c.oi !== undefined && c.od === undefined) {
                  cb(c.p[c.p.length - 1], c.oi);
                } else if (c.si !== undefined) {
                  cb(c.p[c.p.length - 1], c.si);
                }
                break;
              case 'delete':
                if (c.li === undefined && c.ld !== undefined) {
                  cb(c.p[c.p.length - 1], c.ld);
                } else if (c.oi === undefined && c.od !== undefined) {
                  cb(c.p[c.p.length - 1], c.od);
                } else if (c.sd !== undefined) {
                  cb(c.p[c.p.length - 1], c.sd);
                }
                break;
              case 'replace':
                if (c.li !== undefined && c.ld !== undefined) {
                  cb(c.p[c.p.length - 1], c.ld, c.li);
                } else if (c.oi !== undefined && c.od !== undefined) {
                  cb(c.p[c.p.length - 1], c.od, c.oi);
                }
                break;
              case 'move':
                if (c.lm !== undefined) {
                  cb(c.p[c.p.length - 1], c.lm);
                }
                break;
              case 'add':
                if (c.na !== undefined) {
                  cb(c.na);
                }
            }
          }

          if (_type.canOpAffectPath(c, listener.path) && listener.event === 'child op') {
            var child_path = c.p.slice(listener.path.length);
            cb(child_path, c);
          }
        }
      }
    }
  };

}).call(this);


text:
require 'spec_helper'
require 'stats'

describe Array, "that is empty" do
  before do
    @empty = Array.new
  end

  it "should have a sum of nil" do
    @empty.sum.should be_nil
  end

  it "should have a mean of nil" do
    @empty.mean.should be_nil
  end

  it "should have a median of nil" do
    @empty.median.should be_nil
  end

  it "should have stdev nil" do
    @empty.stdev.should be_nil
  end

  it "should have lower quartile nil" do
    @empty.lower_quartile.should be_nil
  end

  it "should have upper quartile nil" do
    @empty.upper_quartile.should be_nil
  end
end

describe Array, "of all zeros" do
  before do
    @zeros = Array.new(10, 0)
  end

  it "should have a sum of zero" do
    @zeros.sum.should == 0
  end

  it "should have a mean of 0" do
    @zeros.mean.should == 0
  end

  it "should have a median of 0" do
    @zeros.median.should == 0
  end

  it "should have a lower quartile of 0" do
    @zeros.lower_quartile.should == 0
  end

  it "should have an upper quartile of 0" do
    @zeros.upper_quartile.should == 0
  end
end

describe Array, "of 1..9" do
  before do
    @test = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    @test_shuffled = @test.shuffle
  end

  it "should have a sum of 45" do
    @test.sum.should == 45
    @test_shuffled.sum.should == 45
  end

  it "should have a mean of 5" do
    @test.mean.should == 5
    @test_shuffled.mean.should == 5
  end

  it "should have a median of 5" do
    @test.median.should == 5
    @test_shuffled.median.should == 5
  end

  it "should have a lower quartile of 2.5" do
    @test.lower_quartile.should == 2.5
    @test_shuffled.lower_quartile.should == 2.5
  end

  it "should have an upper quartile of 7.5" do
    @test.upper_quartile.should == 7.5
    @test_shuffled.upper_quartile.should == 7.5
  end
end

describe Array, "of 1..10" do
  before do
    @test = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    @test_shuffled = @test.shuffle
  end

  it "should have a sum of 55" do
    @test.sum.should == 55
    @test_shuffled.sum.should == 55
  end

  it "should have a mean of 5.5" do
    @test.mean.should == 5.5
    @test_shuffled.mean.should == 5.5
  end

  it "should have a median of 5.5" do
    @test.median.should == 5.5
    @test_shuffled.median.should == 5.5
  end

  it "should have a lower quartile of 3" do
    @test.lower_quartile.should == 3
    @test_shuffled.lower_quartile.should == 3
  end

  it "should have an upper quartile of 8" do
    @test.upper_quartile.should == 8
    @test_shuffled.upper_quartile.should == 8
  end
end

redpajama_set_name: RedPajamaGithub


text:
template <int8_t port>
class AnalogWrite {
  private:
    int16_t currentValue;
  public:
    void setup() {
      pinMode(port, OUTPUT);
      currentValue = 0;
    }
    int16_t write(int16_t v) {
      currentValue = v;
      analogWrite(port, currentValue);
      return currentValue;
    }
    int16_t value() const {
      return currentValue;
    }
};


text:
import { Permission, User } from '../app/entities';
import { dataSource  } from '../db';

export async function main() {
  await dataSource.initialize();

  const user = new User();
  user.email = 'john@foalts.org';
  await user.setPassword('password');

  const user2 = new User();
  user2.email = 'mary@foalts.org';
  await user2.setPassword('password2');

  const permission = new Permission();
  permission.name = 'Admin permission';
  permission.codeName = 'admin';

  user.userPermissions = [ permission ];

  console.log(await permission.save());
  console.log(await user.save());
  console.log(await user2.save());
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MafiaBotV2.Util;

namespace MafiaBotV2.MafiaGame.Commands
{
    class DeadlineCommand : ICommand
    {
        #region ICommand Members

        public string Name {
            get { return "deadline"; }
        }

        public bool AllowedInPublic {
            get { return true; }
        }

        MafiaGame game;

        public object Parent {
            get { return game; }
        }

        public DeadlineCommand(MafiaGame game) {
            this.game = game;
        }

        public string Execute(MafiaBotV2.Network.NetUser from, MafiaBotV2.Network.NetObject source, string[] args) {
            if(args.Length == 0) {
                return "Syntax: ##deadline <seconds>";
            }

            if(from != game.Creator) {
                return "Only the creator can set deadlines.";
            }

            DateTime executionTime = DateTime.Now.AddSeconds(Int32.Parse(args[0]));
            game.SetDeadline(executionTime);
            return null;
        }

        #endregion
    }
}


text:
@interface HomeViewController ()
@end

@implementation HomeViewController

#pragma mark - Init
- (instancetype)init
{
   NSString* className = NSStringFromClass([self class]);
   if (self = [super initWithNibName:className bundle:nil])
   {
   }
   return self;
}

#pragma mark - Class Methods
+ (instancetype)controller
{
   return [[HomeViewController alloc] init];
}

@end


text:
package com.samaxes.javax.rs.validation;

import java.io.IOException;
import java.net.URL;
import java.util.Collection;
import java.util.Collections;
import java.util.logging.Logger;

import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.json.JsonValue;
import javax.json.stream.JsonGenerator;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.glassfish.jersey.jsonp.JsonProcessingFeature;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.junit.InSequence;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.ArchivePaths;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.formatter.Formatters;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(Arquillian.class)
public class PersonsIT {

    private static final Logger LOGGER = Logger.getLogger(PersonsIT.class.getName());

    @Deployment
    public static WebArchive createDeployment() throws IOException {
        final WebArchive war = ShrinkWrap.create(WebArchive.class, "jaxrs-beanvalidation-javaee7.war")
                .addPackage("com.samaxes.javax.rs.validation")
                .addAsWebInfResource(EmptyAsset.INSTANCE, ArchivePaths.create("beans.xml"));

        LOGGER.info(war.toString(Formatters.VERBOSE));

        return war;
    }

    @Test
    @RunAsClient
    @InSequence(10)
    public void shouldReturnAllPersons(@ArquillianResource URL baseURL) {
        Client client = ClientBuilder.newBuilder()
                .register(JsonProcessingFeature.class)
                .property(JsonGenerator.PRETTY_PRINTING, true)
                .build();
        Response response = client.target(baseURL + "r/persons")
                .request(MediaType.APPLICATION_JSON)
                .get();
        response.bufferEntity();

        logResponse("shouldReturnAllPersons", response, JsonArray.class);
        Assert.assertEquals(Collections.emptyList(), response.readEntity(new GenericType<Collection<Person>>() {}));
    }

    @Test
    @RunAsClient
    @InSequence(20)
    public void shouldReturnAValidationErrorWhenGettingAPerson(@ArquillianResource URL baseURL) {
        Client client = ClientBuilder.newBuilder()
                .register(JsonProcessingFeature.class)
                .property(JsonGenerator.PRETTY_PRINTING, true)
                .build();
        Response response = client.target(baseURL + "r/persons/{id}")
                .resolveTemplate("id", "test")
                .request(MediaType.APPLICATION_JSON)
                .header("Accept-Language", "en")
                .get();
        response.bufferEntity();

        logResponse("shouldReturnAValidationErrorWhenGettingAPerson", response, JsonObject.class);
        Assert.assertEquals(HttpServletResponse.SC_BAD_REQUEST, response.getStatus());
    }

    @Test
    @RunAsClient
    @InSequence(30)
    public void shouldReturnAnEmptyPerson(@ArquillianResource URL baseURL) {
        Client client = ClientBuilder.newBuilder()
                .register(JsonProcessingFeature.class)
                .property(JsonGenerator.PRETTY_PRINTING, true)
                .build();
        Response response = client.target(baseURL + "r/persons/{id}")
                .resolveTemplate("id", "10")
                .request(MediaType.APPLICATION_JSON)
                .get();
        response.bufferEntity();

        logResponse("shouldReturnAnEmptyPerson", response, JsonObject.class);
        Assert.assertEquals(null, response.readEntity(Person.class));
    }

    @Test
    @RunAsClient
    @InSequence(40)
    public void shouldReturnAValidationErrorWhenCreatingAPerson(@ArquillianResource URL baseURL) {
        Form form = new Form();

        Client client = ClientBuilder.newBuilder()
                .register(JsonProcessingFeature.class)
                .property(JsonGenerator.PRETTY_PRINTING, true)
                .build();
        Response response = client.target(baseURL + "r/persons/create")
                .request(MediaType.APPLICATION_JSON)
                .header("Accept-Language", "pt")
                .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED));
        response.bufferEntity();

        logResponse("shouldReturnAValidationErrorWhenCreatingAPerson", response, JsonObject.class);
        Assert.assertEquals(HttpServletResponse.SC_BAD_REQUEST, response.getStatus());
    }

    @Test
    @RunAsClient
    @InSequence(50)
    public void shouldReturnACreatedPerson(@ArquillianResource URL baseURL) {
        Person person = new Person();
        person.setId(20);
        person.setName("sam");
        Form form = new Form();
        form.param("id", String.valueOf(person.getId()));
        form.param("name", person.getName());

        Client client = ClientBuilder.newBuilder()
                .register(JsonProcessingFeature.class)
                .property(JsonGenerator.PRETTY_PRINTING, true)
                .build();
        Response response = client.target(baseURL + "r/persons/create")
                .request(MediaType.APPLICATION_JSON)
                .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED));
        response.bufferEntity();

        logResponse("shouldReturnACreatedPerson", response, JsonObject.class);
        Assert.assertEquals(person, response.readEntity(Person.class));
    }

    private void logResponse(String method, Response response, Class<? extends JsonValue> type) {
        StringBuilder builder = new StringBuilder(method).append("\n");
        builder.append("Response: ").append(response).append("\n");
        builder.append("Entity: ");
        if (MediaType.APPLICATION_JSON_TYPE.equals(response.getMediaType())) {
            builder.append(response.readEntity(type));
        }
        builder.append("\n");
        LOGGER.info(builder.toString());
    }
}


text:
package gov.nih.nci.cagrid.cananolab.service.globus;

import gov.nih.nci.cagrid.cananolab.service.CaNanoLabServiceImpl;

import java.rmi.RemoteException;

/**
 * DO NOT EDIT:  This class is autogenerated!
 *
 * This class implements each method in the portType of the service.  Each method call represented
 * in the port type will be then mapped into the unwrapped implementation which the user provides
 * in the CaNanoLabServiceImpl class.  This class handles the boxing and unboxing of each method call
 * so that it can be correclty mapped in the unboxed interface that the developer has designed and
 * has implemented.  Authorization callbacks are automatically made for each method based
 * on each methods authorization requirements.
 *
 * @created by Introduce Toolkit version 1.3
 *
 */
public class CaNanoLabServiceProviderImpl{

	CaNanoLabServiceImpl impl;

	public CaNanoLabServiceProviderImpl() throws RemoteException {
		impl = new CaNanoLabServiceImpl();
	}

    public gov.nih.nci.cagrid.cananolab.stubs.GetFindingsByCharacterizationIdResponse getFindingsByCharacterizationId(gov.nih.nci.cagrid.cananolab.stubs.GetFindingsByCharacterizationIdRequest params) throws RemoteException {
    gov.nih.nci.cagrid.cananolab.stubs.GetFindingsByCharacterizationIdResponse boxedResult = new gov.nih.nci.cagrid.cananolab.stubs.GetFindingsByCharacterizationIdResponse();
    boxedResult.setFinding(impl.getFindingsByCharacterizationId(params.getCharId()));
    return boxedResult;
  }

    public gov.nih.nci.cagrid.cananolab.stubs.GetExperimentConfigsByCharacterizationIdResponse getExperimentConfigsByCharacterizationId(gov.nih.nci.cagrid.cananolab.stubs.GetExperimentConfigsByCharacterizationIdRequest params) throws RemoteException {
    gov.nih.nci.cagrid.cananolab.stubs.GetExperimentConfigsByCharacterizationIdResponse boxedResult = new gov.nih.nci.cagrid.cananolab.stubs.GetExperimentConfigsByCharacterizationIdResponse();
    boxedResult.setExperimentConfig(impl.getExperimentConfigsByCharacterizationId(params.getCharId()));
    return boxedResult;
  }

    public gov.nih.nci.cagrid.cananolab.stubs.GetKeywordsBySampleIdResponse getKeywordsBySampleId(gov.nih.nci.cagrid.cananolab.stubs.GetKeywordsBySampleIdRequest params) throws RemoteException {
    gov.nih.nci.cagrid.cananolab.stubs.GetKeywordsBySampleIdResponse boxedResult = new gov.nih.nci.cagrid.cananolab.stubs.GetKeywordsBySampleIdResponse();
    boxedResult.setKeyword(impl.getKeywordsBySampleId(params.getSampleId()));
    return boxedResult;
  }

    public gov.nih.nci.cagrid.cananolab.stubs.GetFilesByCompositionInfoIdResponse getFilesByCompositionInfoId(gov.nih.nci.cagrid.cananolab.stubs.GetFilesByCompositionInfoIdRequest params) throws RemoteException {
    gov.nih.nci.cagrid.cananolab.stubs.GetFilesByCompositionInfoIdResponse boxedResult = new gov.nih.nci.cagrid.cananolab.stubs.GetFilesByCompositionInfoIdResponse();
    boxedResult.setFile(impl.getFilesByCompositionInfoId(params.getId(),params.getClassName()));
    return boxedResult;
  }

    public gov.nih.nci.cagrid.cananolab.stubs.GetProtocolByCharacterizationIdResponse getProtocolByCharacterizationId(gov.nih.nci.cagrid.cananolab.stubs.GetProtocolByCharacterizationIdRequest params) throws RemoteException {
    gov.nih.nci.cagrid.cananolab.stubs.GetProtocolByCharacterizationIdResponse boxedResult = new gov.nih.nci.cagrid.cananolab.stubs.GetProtocolByCharacterizationIdResponse();
    boxedResult.setProtocol(impl.getProtocolByCharacterizationId(params.getCharId()));
    return boxedResult;
  }

    public gov.nih.nci.cagrid.cananolab.stubs.GetSampleIdsResponse getSampleIds(gov.nih.nci.cagrid.cananolab.stubs.GetSampleIdsRequest params) throws RemoteException {
    gov.nih.nci.cagrid.cananolab.stubs.GetSampleIdsResponse boxedResult = new gov.nih.nci.cagrid.cananolab.stubs.GetSampleIdsResponse();
    boxedResult.setResponse(impl.getSampleIds(params.getSampleName(), params.getSamplePointOfContact(),params.getNanomaterialEntityClassNames(),params.getFunctionalizingEntityClassNames(),params.getFunctionClassNames(),params.getCharacterizationClassNames(),params.getWords()));
    return boxedResult;
  }

    public gov.nih.nci.cagrid.cananolab.stubs.GetPublicationIdsByResponse getPublicationIdsBy(gov.nih.nci.cagrid.cananolab.stubs.GetPublicationIdsByRequest params) throws RemoteException {
    gov.nih.nci.cagrid.cananolab.stubs.GetPublicationIdsByResponse boxedResult = new gov.nih.nci.cagrid.cananolab.stubs.GetPublicationIdsByResponse();
    boxedResult.setResponse(impl.getPublicationIdsBy(params.getPublicationTitle(),params.getPublicationCategory(),params.getSampleName(),params.getResearchAreas(),params.getKeywords(),params.getPubMedId(),params.getDigitalObjectId(),params.getAuthors(),params.getNanomaterialEntityClassNames(),params.getFunctionalizingEntityClassNames(),params.getFunctionClassNames()));
    return boxedResult;
  }

    public gov.nih.nci.cagrid.cananolab.stubs.GetOtherPointOfContactsBySampleIdResponse getOtherPointOfContactsBySampleId(gov.nih.nci.cagrid.cananolab.stubs.GetOtherPointOfContactsBySampleIdRequest params) throws RemoteException {
    gov.nih.nci.cagrid.cananolab.stubs.GetOtherPointOfContactsBySampleIdResponse boxedResult = new gov.nih.nci.cagrid.cananolab.stubs.GetOtherPointOfContactsBySampleIdResponse();
    boxedResult.setPointOfContact(impl.getOtherPointOfContactsBySampleId(params.getSampleId()));
    return boxedResult;
  }

    public gov.nih.nci.cagrid.cananolab.stubs.GetSampleNamesByPublicationIdResponse getSampleNamesByPublicationId(gov.nih.nci.cagrid.cananolab.stubs.GetSampleNamesByPublicationIdRequest params) throws RemoteException {
    gov.nih.nci.cagrid.cananolab.stubs.GetSampleNamesByPublicationIdResponse boxedResult = new gov.nih.nci.cagrid.cananolab.stubs.GetSampleNamesByPublicationIdResponse();
    boxedResult.setResponse(impl.getSampleNamesByPublicationId(params.getPublicationId()));
    return boxedResult;
  }

    public gov.nih.nci.cagrid.cananolab.stubs.GetPublicationsBySampleIdResponse getPublicationsBySampleId(gov.nih.nci.cagrid.cananolab.stubs.GetPublicationsBySampleIdRequest params) throws RemoteException {
    gov.nih.nci.cagrid.cananolab.stubs.GetPublicationsBySampleIdResponse boxedResult = new gov.nih.nci.cagrid.cananolab.stubs.GetPublicationsBySampleIdResponse();
    boxedResult.setPublication(impl.getPublicationsBySampleId(params.getSampleId()));
    return boxedResult;
  }

    public gov.nih.nci.cagrid.cananolab.stubs.GetPrimaryPointOfContactBySampleIdResponse getPrimaryPointOfContactBySampleId(gov.nih.nci.cagrid.cananolab.stubs.GetPrimaryPointOfContactBySampleIdRequest params) throws RemoteException {
    gov.nih.nci.cagrid.cananolab.stubs.GetPrimaryPointOfContactBySampleIdResponse boxedResult = new gov.nih.nci.cagrid.cananolab.stubs.GetPrimaryPointOfContactBySampleIdResponse();
    boxedResult.setPointOfContact(impl.getPrimaryPointOfContactBySampleId(params.getSampleId()));
    return boxedResult;
  }

    public gov.nih.nci.cagrid.cananolab.stubs.GetSampleViewStrsResponse getSampleViewStrs(gov.nih.nci.cagrid.cananolab.stubs.GetSampleViewStrsRequest params) throws RemoteException {
    gov.nih.nci.cagrid.cananolab.stubs.GetSampleViewStrsResponse boxedResult = new gov.nih.nci.cagrid.cananolab.stubs.GetSampleViewStrsResponse();
    boxedResult.setResponse(impl.getSampleViewStrs(params.getSampleName()));
    return boxedResult;
  }
    public gov.nih.nci.cagrid.cananolab.stubs.GetFileByProtocolIdResponse getFileByProtocolId(gov.nih.nci.cagrid.cananolab.stubs.GetFileByProtocolIdRequest params) throws RemoteException {
        gov.nih.nci.cagrid.cananolab.stubs.GetFileByProtocolIdResponse boxedResult = new gov.nih.nci.cagrid.cananolab.stubs.GetFileByProtocolIdResponse();
        boxedResult.setFile(impl.getFileByProtocolId(params.getProtocolId()));
        return boxedResult;
  }
}


text:
mkdir "$(pwd)/local"
export TEST_DIR="$(pwd)/local"

echo -e "\nRUNNING TEST\n"

node "$rootdir/bin/veendor.js" install -vvv --debug

cd "$(pwd)/local"
tar -xf 1722dc5c5ee28cf0bcdc5ac1da82e0608b655f88.tar.gz

if [[ ! -f "node_modules/deep-object-diff/package.json" ]]; then
    echo "gitPush failed; node_modules/deep-object-diff/package.json is not there"
    exit 1;
fi


text:
import asyncio
import logging
import traceback
from enum import Enum
from json.decoder import JSONDecodeError
from typing import List, Union, Callable

import requests

from config import HOME_LINK
from .json_model import AnnotatedJson
from .parser import Parser as HtmlParser, Tag

logger = logging.getLogger('issue')

class QueueTask(AnnotatedJson):
    id: int
    responsible_name: str
    has_issue_access: str
    issue_url: str
    responsible_url: str
    status_name: str
    student_name: str
    student_url: str
    task_title: str

    @staticmethod
    def _extract_id(data, field_name):
        return data['DT_RowData'].get(field_name)

    def __eq__(self, other):
        return self.id == other.id

class Comment(object):
    author: str = ''
    author_href: str = ''
    text: str = ''
    files: List[str] = None

class IssueParser(HtmlParser):
    task: str = None
    comments: List[Comment] = None
    current_comment: Comment = None
    token: str = None
    mark: [int, int] = None

    _mark_found = None

    def on_feed(self):
        self.task = ''
        self.comments = []
        self._mark_found = False

    def on_starttag(self, t: Tag):
        if (t.attrs.get('name') == 'csrfmiddlewaretoken'
                and self._tags_stack[-2].attrs.get('id') == 'status_form'):
            self.token = t.attrs['value']

        if t.name == 'li' and 'history' in self._classes:
            self.current_comment = Comment()
            self.current_comment.files = []

    def on_data(self, t: Tag, data: str):
        in_problem = ('problem-statement' in self._classes
                      and 'modal' not in self._classes)
        in_header = 'header' in self._classes

        comment = self.current_comment

        comment_classes = ('contest-response-comment',
                           'issue-page-comment')

        if in_problem and not in_header:
            data = ' '.join(data.split())
            if 'tex-monospace' in t.classes:
                data = "```\n" + data + "\n```\n"
            elif t.name == 'a':
                data = ' [{}]({})'.format(data, t.attrs.get('href', ''))
            else:
                data = ' ' + data

            self.task += data
        elif (t.name == 'a'
              and 'card-link' in t.classes
              and 'user_img' not in self._classes
              and comment is not None):
            comment.author_href = t.attrs.get('href')
            comment.author = data
        elif comment is not None:
            if any(c in self._classes for c in comment_classes):
                comment.text += data
            elif t.name == 'a' and 'files' in self._classes:
                comment.files.append(t.attrs['href'])
        elif t.name == 'a' and data == 'Оценка':
            self._mark_found = True
        elif self._mark_found and 'accordion2-result' in t.classes:
            self.mark = list(map(float, data.split('из')))

    def on_endtag(self, t: Tag):
        if self.current_comment is not None and t.name == 'li':
            self.comments.append(self.current_comment)
            self.current_comment = None
        elif self._mark_found and t.name == 'div' and 'card' in t.classes:
            self._mark_found = False

def get_check_queue(sid: str, n: int = 5):
    url = '{}/course/ajax_get_queue?' \
          'draw=2&start.py=0&length={}&lang=ru&timezone=Asia%2FVladivostok&' \
          'course_id=34&' \
          'filter=status_field%3D3'.format(HOME_LINK, n)

    with requests.Session() as s:
        data = s.get(url, cookies={'sessionid': sid})

    try:
        j = data.json()
    except JSONDecodeError as e:
        return []

    return j['data']

def get_issue(sid: str, issue_id: int) -> [str, List[Comment], str]:
    url = HOME_LINK + '/issue/' + str(issue_id)

    print('--> Start download issue id', issue_id)
    r = requests.get(url, cookies={'sessionid': sid})

    parser = IssueParser()
    parser.feed(r.text)
    parser.close()
    print('<-- Finished download issue id', issue_id)

    return parser.task, parser.comments, parser.token, parser.mark

loop = asyncio.get_event_loop()

def get_issue_async(sid: str, issue_id: int):
    try:
        return loop.run_in_executor(None, get_issue, sid, issue_id)
        # return get_issue(sid, issue_id)
    except:
        logger.error(traceback.format_exc())

class VerdictType(Enum):
    status = 'status', 'status_form'
    mark = 'mark', 'mark_form'

Verdict = Union[int, float]

def issue_send_verdict(sid: str, token: str, issue_id: int,
                       comment: str,
                       verdict_type: VerdictType,
                       verdict: Verdict,
                       on_finish: Callable):
    verdict_key, form_name = verdict_type.value
    form_data = dict(csrfmiddlewaretoken=token,
                     comment_verdict=comment,
                     form_name=form_name)
    form_data[verdict_key] = verdict

    if verdict_type == VerdictType.mark:
        form_data['Accepted'] = ''

    try:
        url = '{}/issue/{}'.format(HOME_LINK, issue_id)
        r = requests.post(url,
                          data=form_data,
                          cookies={'sessionid': sid,
                                   'csrftoken': token})
        logger.debug(r.text)
    except Exception as e:
        logger.log(logging.ERROR,
                   'request send failed. '
                   'id: {} session: {} token: {} comment: {} '
                   'verdict: {}'.format(issue_id, sid, token,
                                        comment, verdict))
    else:
        logger.info('verdict sent. '
                     'id: {}, status: {}'.format(issue_id, r.status_code))

        on_finish(r.status_code)


text:
Article 704
----
Elles revivent si les choses sont rétablies de manière qu'on puisse en user ; à
moins qu'il ne se soit déjà écoulé un espace de temps suffisant pour faire
présumer l'extinction de la servitude, ainsi qu'il est dit à l'article 707.


text:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();
            $table->string('title');
            $table->string('slug'); // slug as URL str_slug()
            $table->text('body');
            $table->dateTime('published_at')->nullable(); // if null post is a draft
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}


text:
(function (window, angular, undefined) {
    'use strict';

    angular.module('admin.dashboard', []);

})(window, window.angular);


text:
require_relative '../../spec_helper'
require_relative 'fixtures/classes'
require_relative 'shared/enumerable_enumeratorized'

describe "Enumerable#group_by" do
  it "returns a hash with values grouped according to the block" do
    e = EnumerableSpecs::Numerous.new("foo", "bar", "baz")
    h = e.group_by { |word| word[0..0].to_sym }
    h.should == { f: ["foo"], b: ["bar", "baz"]}
  end

  it "returns an empty hash for empty enumerables" do
    EnumerableSpecs::Empty.new.group_by { |x| x}.should == {}
  end

  it "returns a hash without default_proc" do
    e = EnumerableSpecs::Numerous.new("foo", "bar", "baz")
    h = e.group_by { |word| word[0..0].to_sym }
    h[:some].should be_nil
    h.default_proc.should be_nil
    h.default.should be_nil
  end

  it "returns an Enumerator if called without a block" do
    EnumerableSpecs::Numerous.new.group_by.should be_an_instance_of(Enumerator)
  end

  it "gathers whole arrays as elements when each yields multiple" do
    e = EnumerableSpecs::YieldsMulti.new
    h = e.group_by { |i| i }
    h.should == { [1, 2] => [[1, 2]],
                  [6, 7, 8, 9] => [[6, 7, 8, 9]],
                  [3, 4, 5] => [[3, 4, 5]] }
  end

  it "returns a tainted hash if self is tainted" do
    EnumerableSpecs::Empty.new.taint.group_by {}.tainted?.should be_true
  end

  it "returns an untrusted hash if self is untrusted" do
    EnumerableSpecs::Empty.new.untrust.group_by {}.untrusted?.should be_true
  end

  it_behaves_like :enumerable_enumeratorized_with_origin_size, :group_by
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FluentAssertions;
using Mandrill.Model;
using Xunit;
using Mandrill;

namespace Tests
{
    [Trait("Category", "subaccounts")]
    [Collection("subaccounts")]
    public class Subaccounts : IntegrationTest
    {
        HashSet<string> _added = new HashSet<string>();

        public override void Dispose()
        {
            foreach (var id in _added)
            {
                var result = Api.Subaccounts.DeleteAsync(id).GetAwaiter().GetResult();
            }
            base.Dispose();
        }

        [Trait("Category", "subaccounts/add.json")]
        public class Add : Subaccounts
        {
            [Fact]
            public async Task Can_add_subaccount()
            {
                var id = Guid.NewGuid().ToString("N");
                var notes = "created by test at " + DateTime.UtcNow.ToString("s");
                var result = await Api.Subaccounts.AddAsync(id, name: "test", notes: notes, customQuota: null);
                result.Id.Should().Be(id);
                _added.Add(result.Id);
            }
        }

        [Trait("Category", "subaccounts/list.json")]
        public class List : Subaccounts
        {
            [Fact]
            public async Task Can_list_subaccount()
            {
                var results = await Api.Subaccounts.ListAsync(q:null);
                results.Count.Should().BeGreaterOrEqualTo(0);
            }
            [Fact]
            public async Task Can_filter_subaccount()
            {
                var results = await Api.Subaccounts.ListAsync(q: Guid.NewGuid().ToString("N"));
                results.Count.Should().Be(0);
            }
        }

        [Trait("Category", "subaccounts/update.json")]
        public class Update : Subaccounts
        {
            [Fact]
            public async Task Can_update_subaccount()
            {
                var id = Guid.NewGuid().ToString("N");
                var notes = "created by test at " + DateTime.UtcNow.ToString("s");
                await Api.Subaccounts.AddAsync(id, name: "test", notes: notes, customQuota: null);

                var result = await Api.Subaccounts.UpdateAsync(id, name: "test", notes: "update", customQuota: 5000);
                result.CustomQuota.Should().Be(5000);
                _added.Add(result.Id);
            }

        }

        [Trait("Category", "subaccounts/pause.json")]
        public class Pause : Subaccounts
        {
            [Fact]
            public async Task Can_pause_subaccount()
            {
                var id = Guid.NewGuid().ToString("N");
                var notes = "created by test at " + DateTime.UtcNow.ToString("s");
                await Api.Subaccounts.AddAsync(id, name: "test", notes: notes, customQuota: null);

                var result = await Api.Subaccounts.PauseAsync(id);
                result.Status.Should().Be(MandrillSubaccountStatus.Paused);
                _added.Add(result.Id);
            }

        }

        [Trait("Category", "subaccounts/resume.json")]
        public class Resume : Subaccounts
        {
            [Fact]
            public async Task Can_resume_subaccount()
            {
                var id = Guid.NewGuid().ToString("N");
                var notes = "created by test at " + DateTime.UtcNow.ToString("s");
                await Api.Subaccounts.AddAsync(id, name: "test", notes: notes, customQuota: null);

                var result = await Api.Subaccounts.PauseAsync(id);
                result.Status.Should().Be(MandrillSubaccountStatus.Paused);

                result = await Api.Subaccounts.ResumeAsync(id);
                result.Status.Should().Be(MandrillSubaccountStatus.Active);
                _added.Add(result.Id);
            }

        }

        [Trait("Category", "subaccounts/delete.json")]
        public class Delete : Subaccounts
        {
            [Fact]
            public async Task Can_delete_subaccount()
            {
                var id = Guid.NewGuid().ToString("N");
                var notes = "created by test at " + DateTime.UtcNow.ToString("s");
                await Api.Subaccounts.AddAsync(id, name: "test", notes: notes, customQuota: null);

                var result = await Api.Subaccounts.DeleteAsync(id);
                result.Id.Should().Be(id);
            }

        }

        [Trait("Category", "subaccounts/info.json")]
        public class Info : Subaccounts
        {
            [Fact]
            public async Task Can_get_info_subaccount()
            {
                var id = Guid.NewGuid().ToString("N");
                var notes = "created by test at " + DateTime.UtcNow.ToString("s");
                await Api.Subaccounts.AddAsync(id, name: "test", notes: notes, customQuota: null);

                var result = await Api.Subaccounts.InfoAsync(id);
                result.Id.Should().Be(id);
                result.Last30Days.Clicks.Should().Be(0);
                result.FirstSentAt.Should().Be((DateTime?) null);

                _added.Add(result.Id);

            }

        }
    }
}


text:
/**
 * @fileoverview
 * @author Francois-Xavier Aeberhard <fx@red-agent.com>
 */
YUI.add('wegas-layout-list', function(Y) {
    "use strict";

    var BOUNDINGBOX = 'boundingBox',
        CONTENTBOX = 'contentBox',
        List;

    /**
     * @name Y.Wegas.List
     * @extends Y.Widget
     * @borrows Y.WidgetParent, Y.WidgetChild, Y.Wegas.Editable, Y.Wegas.Parent
     * @class class to serialize widgets
     * @constructor
     * @description class to serialize widgets
     */
    List = Y.Base.create("wegas-list", Y.Widget, [Y.WidgetParent, Y.WidgetChild, Y.Wegas.Editable, Y.Wegas.Parent], {
        /** @lends Y.Wegas.List# */

        // *** Private fields *** //
        // -

        // ** Lifecycle Methods ** /
        /**
         * @function
         * @private
         * @description set class of the contentbox (vertical or horizontal)
         * add class with "clear:both" style after the contentbox.
         */
        syncUI: function() {
            var cb = this.get(CONTENTBOX);

            if (this.get('direction') === 'vertical') {
                cb.addClass(this.getClassName('vertical'));
                cb.removeClass(this.getClassName('horizontal'));
            } else {
                cb.addClass(this.getClassName('horizontal'));
                cb.removeClass(this.getClassName('vertical'));
            }
            this.get(BOUNDINGBOX).append('

');
        },
        getEditorLabel: function() {
            return Y.Wegas.Helper.stripHtml(this.get("name"));
        }
    }, {
        /** @lends Y.Wegas.List */
        EDITORNAME: "Folder",
        CSS_PREFIX: "wegas-list",
        /**
         * @field
         * @static
         * @description
         *
Attributes

         *

         *
defaultChildType: default value for children. Transient.

         *
children: list of widget. Transient.

         *
direction: string-helper to add class and set style of the
         *     list (vertical or horizontal). Vertical by default

         *

         */
        ATTRS: {
            direction: {
                value: 'vertical',
                type: "string",
                choices: [{
                        value: 'vertical'
                    }, {
                        value: 'horizontal'
                    }]
            },
            name: {
                value: "folder",
                type: "string"
            }

            /**
             * Prevent widgetchild selection to be propagated through the hierarchy
             */
            //selected: {
            //    value: 2,
            //    readonly: true
            //}
        }

    });
    Y.Wegas.List = List;

});


text:
Manage multiple SQlite file example project.

同じxcdatamodeldからできた複数のSQliteファイルを扱って、切り替えることができるかを試すサンプルです。

## Usage

You add SQlite file to ``document`` dir.

via iTunes File Sharing or [sidir](https://github.com/paulsamuels/sidir "sidir") etc...

## License

MIT


text: docker build -t airhacks/java:8 java8/


text:
package org.apache.sling.event.impl.support;

/**
 * Sub package matcher - the topic must be in the same package or a sub package.
 */
public class SubPackagesTopicMatcher implements TopicMatcher {

    private final String packageName;

    public SubPackagesTopicMatcher(final String name) {
        // remove last char and maybe a trailing slash
        int lastPos = name.length() - 1;
        if ( lastPos > 0 && name.charAt(lastPos - 1) == '/' ) {
            this.packageName = name.substring(0, lastPos);
        } else {
            this.packageName = name.substring(0, lastPos) + '/';
        }
    }

    /**
     * @see org.apache.sling.event.impl.support.TopicMatcher#match(java.lang.String)
     */
    @Override
    public String match(final String topic) {
        final int pos = topic.lastIndexOf('/');
        return pos > -1 && topic.substring(0, pos + 1).startsWith(this.packageName) ? topic.substring(this.packageName.length()) : null;
    }

    @Override
    public String toString() {
        return "SubPackageMatcher [packageName=" + packageName + "]";
    }
}


text:
ThinkingSphinx::Index.define :book, :with => :active_record, :delta => ThinkingSphinx::Deltas::DelayedDelta do
  indexes title, author
end if ThinkingSphinx::Index.respond_to?(:define)


text:
layout: default
title: Home
---

We're building a community

                    Software Niagara is a grassroots initiative to build a stronger
                    software community and startup culture in Niagara.

                    Be a part of it!

{% for post in site.categories.slides %}

{{ post.title }}

            {{ post.content }}

{% endfor %}


text:
var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  //生产环境
  res.render('index', { title: 'ZDM\'s website' });
  //dev 环境
  //res.render('index-dev', { title: 'ZDM\'s website' });
});

module.exports = router;


text:
package de.gishmo.gwt.example.domain.services.client.dto;

import de.gishmo.gwt.example.domain.dto.shared.model.Person;
import de.gishmo.gwt.example.domain.dto.shared.search.PersonSearch;
import de.gishmo.gwt.example.domain.dto.shared.transport.response.PersonGetResponse;
import de.gishmo.gwt.example.domain.dto.shared.transport.response.PersonInsertResponse;
import de.gishmo.gwt.example.domain.dto.shared.transport.response.PersonSearchResponse;
import de.gishmo.gwt.example.domain.dto.shared.transport.response.PersonUpdateResponse;
import org.fusesource.restygwt.client.MethodCallback;
import org.fusesource.restygwt.client.Options;
import org.fusesource.restygwt.client.RestService;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;

/**
 * der PersonService als RestyGWT-Service mit JAX-RS-Annotationen
 */
@Path("/Person")
public interface PersonService
  extends RestService {

  @GET
  @Path("/get/{id}")
  void get(@PathParam("id") String id,
           MethodCallback<PersonGetResponse> callback);

  @POST
  @Path("/search")
  void search(PersonSearch search,
              MethodCallback<PersonSearchResponse> callback);

  @POST
  @Path("/insert")
  void insert(Person person,
              MethodCallback<PersonInsertResponse> callback);

  @POST
  @Options(timeout = 5000, expect = {200,
                                     201})
  @Path("/update")
  void update(Person person,
              MethodCallback<PersonUpdateResponse> callback);

}


text:
package org.gradle.nativebinaries.internal.prebuilt;

import org.gradle.api.Action;
import org.gradle.api.internal.AbstractNamedDomainObjectContainer;
import org.gradle.api.internal.file.FileResolver;
import org.gradle.internal.reflect.Instantiator;
import org.gradle.nativebinaries.PrebuiltLibraries;
import org.gradle.nativebinaries.PrebuiltLibrary;

public class DefaultPrebuiltLibraries extends AbstractNamedDomainObjectContainer<PrebuiltLibrary> implements PrebuiltLibraries {
    private final FileResolver fileResolver;
    private final Action<PrebuiltLibrary> libraryInitializer;
    private String name;

    public DefaultPrebuiltLibraries(String name, Instantiator instantiator, FileResolver fileResolver, Action<PrebuiltLibrary> libraryInitializer) {
        super(PrebuiltLibrary.class, instantiator);
        this.name = name;
        this.fileResolver = fileResolver;
        this.libraryInitializer = libraryInitializer;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    protected PrebuiltLibrary doCreate(String name) {
        return getInstantiator().newInstance(DefaultPrebuiltLibrary.class, name, fileResolver);
    }

    public PrebuiltLibrary resolveLibrary(String name) {
        PrebuiltLibrary library = findByName(name);
        if (library != null && library.getBinaries().isEmpty()) {
            libraryInitializer.execute(library);
        }
        return library;
    }

}


text:
using namespace hum;

Clock::Clock()
{
    m_time_point = std::chrono::high_resolution_clock::now();
}

Clock::~Clock()
{}

Time Clock::getTime() const
{
    auto elapsed = std::chrono::high_resolution_clock::now() - m_time_point;
    return Time::nanoseconds(std::chrono::duration_cast<std::chrono::nanoseconds>(elapsed).count());
}

Time Clock::reset()
{
    auto new_point = std::chrono::high_resolution_clock::now();
    auto elapsed = new_point - m_time_point;
    Time t = Time::nanoseconds(std::chrono::duration_cast<std::chrono::nanoseconds>(elapsed).count());
    m_time_point = new_point;
    return t;
}


text:
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ash/display/privacy_screen_controller.h"
#include "ash/public/cpp/ash_pref_names.h"
#include "ash/session/session_controller_impl.h"
#include "ash/shell.h"
#include "ash/test/ash_test_base.h"
#include "components/prefs/pref_service.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "ui/display/fake/fake_display_snapshot.h"
#include "ui/display/manager/display_change_observer.h"
#include "ui/display/manager/display_manager.h"
#include "ui/display/manager/test/action_logger_util.h"
#include "ui/display/manager/test/test_native_display_delegate.h"
#include "ui/display/types/display_constants.h"

namespace ash {

namespace {

constexpr char kUser1Email[] = "user1@privacyscreen";
constexpr char kUser2Email[] = "user2@privacyscreen";
constexpr gfx::Size kDisplaySize{1024, 768};

class MockObserver : public PrivacyScreenController::Observer {
 public:
  MockObserver() {}
  ~MockObserver() override = default;

  MOCK_METHOD(void, OnPrivacyScreenSettingChanged, (bool enabled), (override));
};

class PrivacyScreenControllerTest : public NoSessionAshTestBase {
 public:
  PrivacyScreenControllerTest()
      : logger_(std::make_unique<display::test::ActionLogger>()) {}
  ~PrivacyScreenControllerTest() override = default;

  PrivacyScreenControllerTest(const PrivacyScreenControllerTest&) = delete;
  PrivacyScreenControllerTest& operator=(const PrivacyScreenControllerTest&) =
      delete;

  PrivacyScreenController* controller() {
    return Shell::Get()->privacy_screen_controller();
  }

  PrefService* user1_pref_service() const {
    return Shell::Get()->session_controller()->GetUserPrefServiceForUser(
        AccountId::FromUserEmail(kUser1Email));
  }

  void SetUp() override {
    NoSessionAshTestBase::SetUp();

    // Create user 1 session and simulate its login.
    SimulateUserLogin(kUser1Email);

    // Create user 2 session.
    GetSessionControllerClient()->AddUserSession(kUser2Email);

    native_display_delegate_ =
        new display::test::TestNativeDisplayDelegate(logger_.get());
    display_manager()->configurator()->SetDelegateForTesting(
        std::unique_ptr<display::NativeDisplayDelegate>(
            native_display_delegate_));
    display_change_observer_ =
        std::make_unique<display::DisplayChangeObserver>(display_manager());
    test_api_ = std::make_unique<display::DisplayConfigurator::TestApi>(
        display_manager()->configurator());

    controller()->AddObserver(observer());
  }

  struct TestSnapshotParams {
    int64_t id;
    bool is_internal_display;
    bool supports_privacy_screen;
  };

  void TearDown() override {
    // DisplayChangeObserver access DeviceDataManager in its destructor, so
    // destroy it first.
    display_change_observer_ = nullptr;
    controller()->RemoveObserver(observer());
    AshTestBase::TearDown();
  }

  void SwitchActiveUser(const std::string& email) {
    GetSessionControllerClient()->SwitchActiveUser(
        AccountId::FromUserEmail(email));
  }

  // Builds displays snapshots into |owned_snapshots_| and update the display
  // configurator and display manager with it.
  void BuildAndUpdateDisplaySnapshots(
      const std::vector<TestSnapshotParams>& snapshot_params) {
    owned_snapshots_.clear();
    std::vector<display::DisplaySnapshot*> outputs;

    for (const auto& param : snapshot_params) {
      owned_snapshots_.emplace_back(
          display::FakeDisplaySnapshot::Builder()
              .SetId(param.id)
              .SetNativeMode(kDisplaySize)
              .SetCurrentMode(kDisplaySize)
              .SetType(param.is_internal_display
                           ? display::DISPLAY_CONNECTION_TYPE_INTERNAL
                           : display::DISPLAY_CONNECTION_TYPE_HDMI)
              .SetPrivacyScreen(param.supports_privacy_screen
                                    ? display::kDisabled
                                    : display::kNotSupported)
              .Build());
      outputs.push_back(owned_snapshots_.back().get());
    }

    native_display_delegate_->set_outputs(outputs);
    display_manager()->configurator()->OnConfigurationChanged();
    display_manager()->configurator()->ForceInitialConfigure();
    EXPECT_TRUE(test_api_->TriggerConfigureTimeout());
    display_change_observer_->OnDisplayModeChanged(outputs);
  }

  MockObserver* observer() { return &observer_; }

 private:
  std::unique_ptr<display::test::ActionLogger> logger_;
  display::test::TestNativeDisplayDelegate*
      native_display_delegate_;  // Not owned.
  std::unique_ptr<display::DisplayChangeObserver> display_change_observer_;
  std::unique_ptr<display::DisplayConfigurator::TestApi> test_api_;
  std::vector<std::unique_ptr<display::DisplaySnapshot>> owned_snapshots_;
  ::testing::NiceMock<MockObserver> observer_;
};

// Test that user prefs do not get mixed up between user changes on a device
// with a single supporting display.
TEST_F(PrivacyScreenControllerTest, TestEnableAndDisable) {
  // Create a single internal display that supports privacy screen.
  BuildAndUpdateDisplaySnapshots({{
      /*id=*/123u,
      /*is_internal_display=*/true,
      /*supports_privacy_screen=*/true,
  }});
  EXPECT_EQ(1u, display_manager()->GetNumDisplays());
  ASSERT_TRUE(controller()->IsSupported());

  // Enable for user 1, and switch to user 2. User 2 should have it disabled.
  controller()->SetEnabled(true);
  // Switching accounts shouldn't trigger observers.
  ::testing::Mock::VerifyAndClear(observer());
  EXPECT_CALL(*observer(), OnPrivacyScreenSettingChanged).Times(0);
  EXPECT_TRUE(controller()->GetEnabled());
  SwitchActiveUser(kUser2Email);
  EXPECT_FALSE(controller()->GetEnabled());

  // Switch back to user 1, expect it to be enabled.
  SwitchActiveUser(kUser1Email);
  EXPECT_TRUE(controller()->GetEnabled());
}

// Tests that updates of the Privacy Screen user prefs from outside the
// PrivacyScreenController (such as Settings UI) are observed and applied.
TEST_F(PrivacyScreenControllerTest, TestOutsidePrefsUpdates) {
  BuildAndUpdateDisplaySnapshots({{
      /*id=*/123u,
      /*is_internal_display=*/true,
      /*supports_privacy_screen=*/true,
  }});
  EXPECT_EQ(1u, display_manager()->GetNumDisplays());
  ASSERT_TRUE(controller()->IsSupported());

  EXPECT_CALL(*observer(), OnPrivacyScreenSettingChanged(true));
  EXPECT_FALSE(controller()->GetEnabled());
  user1_pref_service()->SetBoolean(prefs::kDisplayPrivacyScreenEnabled, true);
  EXPECT_TRUE(controller()->GetEnabled());

  EXPECT_CALL(*observer(), OnPrivacyScreenSettingChanged(false));
  user1_pref_service()->SetBoolean(prefs::kDisplayPrivacyScreenEnabled, false);
  EXPECT_FALSE(controller()->GetEnabled());
}

TEST_F(PrivacyScreenControllerTest, NotSupportedOnSingleInternalDisplay) {
  BuildAndUpdateDisplaySnapshots({{
      /*id=*/123u,
      /*is_internal_display=*/true,
      /*supports_privacy_screen=*/false,
  }});
  EXPECT_EQ(1u, display_manager()->GetNumDisplays());
  ASSERT_FALSE(controller()->IsSupported());

  EXPECT_FALSE(controller()->GetEnabled());
}

TEST_F(PrivacyScreenControllerTest,
       SupportedOnInternalDisplayWithMultipleExternalDisplays) {
  BuildAndUpdateDisplaySnapshots({{
                                      /*id=*/1234u,
                                      /*is_internal_display=*/true,
                                      /*supports_privacy_screen=*/true,
                                  },
                                  {
                                      /*id=*/2341u,
                                      /*is_internal_display=*/false,
                                      /*supports_privacy_screen=*/false,
                                  },
                                  {
                                      /*id=*/3412u,
                                      /*is_internal_display=*/false,
                                      /*supports_privacy_screen=*/false,
                                  },
                                  {
                                      /*id=*/4123u,
                                      /*is_internal_display=*/false,
                                      /*supports_privacy_screen=*/false,
                                  }});
  EXPECT_EQ(4u, display_manager()->GetNumDisplays());
  ASSERT_TRUE(controller()->IsSupported());

  controller()->SetEnabled(true);
  EXPECT_TRUE(controller()->GetEnabled());
}

TEST_F(PrivacyScreenControllerTest,
       NotSupportedOnInternalDisplayWithMultipleExternalDisplays) {
  BuildAndUpdateDisplaySnapshots({{
                                      /*id=*/1234u,
                                      /*is_internal_display=*/true,
                                      /*supports_privacy_screen=*/false,
                                  },
                                  {
                                      /*id=*/2341u,
                                      /*is_internal_display=*/false,
                                      /*supports_privacy_screen=*/false,
                                  },
                                  {
                                      /*id=*/3412u,
                                      /*is_internal_display=*/false,
                                      /*supports_privacy_screen=*/false,
                                  },
                                  {
                                      /*id=*/4123u,
                                      /*is_internal_display=*/false,
                                      /*supports_privacy_screen=*/false,
                                  }});
  EXPECT_EQ(4u, display_manager()->GetNumDisplays());
  ASSERT_FALSE(controller()->IsSupported());

  EXPECT_FALSE(controller()->GetEnabled());
}

TEST_F(PrivacyScreenControllerTest,
       NotSupportedOnMultipleSupportingExternalDisplays) {
  BuildAndUpdateDisplaySnapshots({{
                                      /*id=*/1234u,
                                      /*is_internal_display=*/false,
                                      /*supports_privacy_screen=*/false,
                                  },
                                  {
                                      /*id=*/2341u,
                                      /*is_internal_display=*/false,
                                      /*supports_privacy_screen=*/true,
                                  },
                                  {
                                      /*id=*/3412u,
                                      /*is_internal_display=*/false,
                                      /*supports_privacy_screen=*/true,
                                  },
                                  {
                                      /*id=*/4123u,
                                      /*is_internal_display=*/false,
                                      /*supports_privacy_screen=*/true,
                                  }});
  EXPECT_EQ(4u, display_manager()->GetNumDisplays());
  ASSERT_FALSE(controller()->IsSupported());

  EXPECT_FALSE(controller()->GetEnabled());
}

}  // namespace

}  // namespace ash


text:
#ifndef __INCLUDE_PIPELINE_COMMON_FE_H__
#define __INCLUDE_PIPELINE_COMMON_FE_H__

#include <rte_common.h>
#include <rte_cycles.h>
#include <rte_malloc.h>
#include <cmdline_parse.h>

#include "pipeline_common_be.h"
#include "pipeline.h"
#include "app.h"

#ifndef MSG_TIMEOUT_DEFAULT
#define MSG_TIMEOUT_DEFAULT                      1000
#endif

static inline struct app_pipeline_data *
app_pipeline_data(struct app_params *app, uint32_t id)
{
	struct app_pipeline_params *params;

	APP_PARAM_FIND_BY_ID(app->pipeline_params, "PIPELINE", id, params);
	if (params == NULL)
		return NULL;

	return &app->pipeline_data[params - app->pipeline_params];
}

static inline void *
app_pipeline_data_fe(struct app_params *app, uint32_t id)
{
	struct app_pipeline_data *pipeline_data;

	pipeline_data = app_pipeline_data(app, id);
	if (pipeline_data == NULL)
		return NULL;

	return pipeline_data->fe;
}

static inline struct rte_ring *
app_pipeline_msgq_in_get(struct app_params *app,
	uint32_t pipeline_id)
{
	struct app_msgq_params *p;

	APP_PARAM_FIND_BY_ID(app->msgq_params,
		"MSGQ-REQ-PIPELINE",
		pipeline_id,
		p);
	if (p == NULL)
		return NULL;

	return app->msgq[p - app->msgq_params];
}

static inline struct rte_ring *
app_pipeline_msgq_out_get(struct app_params *app,
	uint32_t pipeline_id)
{
	struct app_msgq_params *p;

	APP_PARAM_FIND_BY_ID(app->msgq_params,
		"MSGQ-RSP-PIPELINE",
		pipeline_id,
		p);
	if (p == NULL)
		return NULL;

	return app->msgq[p - app->msgq_params];
}

static inline void *
app_msg_alloc(__rte_unused struct app_params *app)
{
	return rte_malloc(NULL, 2048, RTE_CACHE_LINE_SIZE);
}

static inline void
app_msg_free(__rte_unused struct app_params *app,
	void *msg)
{
	rte_free(msg);
}

static inline void
app_msg_send(struct app_params *app,
	uint32_t pipeline_id,
	void *msg)
{
	struct rte_ring *r = app_pipeline_msgq_in_get(app, pipeline_id);
	int status;

	do {
		status = rte_ring_sp_enqueue(r, msg);
	} while (status == -ENOBUFS);
}

static inline void *
app_msg_recv(struct app_params *app,
	uint32_t pipeline_id)
{
	struct rte_ring *r = app_pipeline_msgq_out_get(app, pipeline_id);
	void *msg;
	int status = rte_ring_sc_dequeue(r, &msg);

	if (status != 0)
		return NULL;

	return msg;
}

static inline void *
app_msg_send_recv(struct app_params *app,
	uint32_t pipeline_id,
	void *msg,
	uint32_t timeout_ms)
{
	struct rte_ring *r_req = app_pipeline_msgq_in_get(app, pipeline_id);
	struct rte_ring *r_rsp = app_pipeline_msgq_out_get(app, pipeline_id);
	uint64_t hz = rte_get_tsc_hz();
	void *msg_recv;
	uint64_t deadline;
	int status;

	/* send */
	do {
		status = rte_ring_sp_enqueue(r_req, (void *) msg);
	} while (status == -ENOBUFS);

	/* recv */
	deadline = (timeout_ms) ?
		(rte_rdtsc() + ((hz * timeout_ms) / 1000)) :
		UINT64_MAX;

	do {
		if (rte_rdtsc() > deadline)
			return NULL;

		status = rte_ring_sc_dequeue(r_rsp, &msg_recv);
	} while (status != 0);

	return msg_recv;
}

int
app_pipeline_ping(struct app_params *app,
	uint32_t pipeline_id);

int
app_pipeline_stats_port_in(struct app_params *app,
	uint32_t pipeline_id,
	uint32_t port_id,
	struct rte_pipeline_port_in_stats *stats);

int
app_pipeline_stats_port_out(struct app_params *app,
	uint32_t pipeline_id,
	uint32_t port_id,
	struct rte_pipeline_port_out_stats *stats);

int
app_pipeline_stats_table(struct app_params *app,
	uint32_t pipeline_id,
	uint32_t table_id,
	struct rte_pipeline_table_stats *stats);

int
app_pipeline_port_in_enable(struct app_params *app,
	uint32_t pipeline_id,
	uint32_t port_id);

int
app_pipeline_port_in_disable(struct app_params *app,
	uint32_t pipeline_id,
	uint32_t port_id);

int
app_link_config(struct app_params *app,
	uint32_t link_id,
	uint32_t ip,
	uint32_t depth);

int
app_link_up(struct app_params *app,
	uint32_t link_id);

int
app_link_down(struct app_params *app,
	uint32_t link_id);

int
app_pipeline_common_cmd_push(struct app_params *app);

#endif


text:
@implementation DFClassDefinition

- (BOOL)isSubclassOf:(DFClassDefinition*)parent {
    BOOL isId = [parent.name isEqualToString:@"id"];

    // Make sure that we implement all same protocols as parent
    __block NSMutableDictionary* searchProtocols = [NSMutableDictionary dictionaryWithDictionary:parent.protocols];
    [searchProtocols removeObjectsForKeys:self.protocols.allKeys];

    DFClassDefinition* def = self;
    while ((def = def.superclassDef)) {
        [searchProtocols removeObjectsForKeys:def.protocols.allKeys];

        if (def == parent || isId) {
            // Found all protocols?
            if (![searchProtocols count]) {
                return YES;
            }
        }
    }
    return NO;
}

@end


text:
/*

         ###
#  #  #########     _______ _     _  ______ _     _
##  ######## @ ##   |______ |     | |  ____ |     |
##################  |       |_____| |_____| |_____|
##  #############      f  r  a  m  e  w  o  r  k
#  #  #########
         ###

(c) 2015 - 2018 FUGU framework project

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.

*/

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace Fugu.Localization.Tool
{
    public class ExtractorOptions
    {
        public Dictionary<String, Regex[]> Patterns { get; set; }
        public Boolean Flat { get; set; }
    }
}


text:
using System;
using System.ComponentModel;
using Elasticsearch.Net;
using Newtonsoft.Json;

namespace Nest
{
	[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
	public interface IRequest
	{
		HttpMethod HttpMethod { get; }

		RouteValues RouteValues { get; }
	}

	public interface IRequest<TParameters> : IRequest
		where TParameters : IRequestParameters, new()
	{
		/// <summary>
		/// Used to describe request parameters that are not part of the body. e.g. query string, connection configuration overrides, etc.
		/// </summary>
		TParameters RequestParameters { get; set; }
	}

	/// <summary>
	/// A request that has an untyped document property
	/// </summary>
	public interface IUntypedDocumentRequest : IRequest
	{
		/// <summary>
		/// The untyped document
		/// </summary>
		object UntypedDocument { get; }
	}

	public abstract class RequestBase<TParameters> : IRequest<TParameters>
		where TParameters : IRequestParameters, new()
	{
		[JsonIgnore]
		protected IRequest<TParameters> RequestState => this;

		protected RequestBase() { }
		protected RequestBase(Func<RouteValues, RouteValues> pathSelector)
		{
			pathSelector(RequestState.RouteValues);
		}

		protected virtual HttpMethod HttpMethod => RequestState.RequestParameters.DefaultHttpMethod;

		[JsonIgnore]
		HttpMethod IRequest.HttpMethod => this.HttpMethod;

		[JsonIgnore]
		RouteValues IRequest.RouteValues { get; } = new RouteValues();

		[JsonIgnore]
		TParameters IRequest<TParameters>.RequestParameters { get; set; } = new TParameters();

		protected TOut Q<TOut>(string name) => RequestState.RequestParameters.GetQueryStringValue<TOut>(name);

		protected void Q(string name, object value) => RequestState.RequestParameters.AddQueryStringValue(name, value);

	}

	public abstract class PlainRequestBase<TParameters> : RequestBase<TParameters>
		where TParameters : IRequestParameters, new()
	{
		protected PlainRequestBase() { }
		protected PlainRequestBase(Func<RouteValues, RouteValues> pathSelector) : base(pathSelector) { }

		/// <summary>
		/// Specify settings for this request alone, handy if you need a custom timeout or want to bypass sniffing, retries
		/// </summary>
		public IRequestConfiguration RequestConfiguration
		{
			get { return RequestState.RequestParameters.RequestConfiguration;  }
			set { RequestState.RequestParameters.RequestConfiguration = value; }
		}
	}

	public abstract class RequestDescriptorBase<TDescriptor, TParameters, TInterface> : RequestBase<TParameters>, IDescriptor
		where TDescriptor : RequestDescriptorBase<TDescriptor, TParameters, TInterface>, TInterface
		where TParameters : FluentRequestParameters<TParameters>, new()
	{
		private readonly TDescriptor _descriptor;

		protected RequestDescriptorBase() { _descriptor = (TDescriptor)this; }
		protected RequestDescriptorBase(Func<RouteValues, RouteValues> pathSelector) : base(pathSelector) { _descriptor = (TDescriptor)this;  }

		protected TInterface Self => _descriptor;
		protected IRequestConfiguration RequestConfig => ((IRequestParameters)RequestState.RequestParameters).RequestConfiguration;

		protected TDescriptor Assign(Action<TInterface> assign) => Fluent.Assign(_descriptor, assign);

		protected TDescriptor AssignParam(Action<TParameters> assigner)
		{
			assigner?.Invoke(this.RequestState.RequestParameters);
			return _descriptor;
		}

		/// <summary>
		/// Specify settings for this request alone, handy if you need a custom timeout or want to bypass sniffing, retries
		/// </summary>
		public TDescriptor RequestConfiguration(Func<RequestConfigurationDescriptor, IRequestConfiguration> configurationSelector)
		{
			RequestState.RequestParameters.RequestConfiguration(configurationSelector);
			return _descriptor;
		}

		/// <summary>
		/// Hides the <see cref="Equals"/> method.
		/// </summary>
		[Browsable(false)]
		[EditorBrowsable(EditorBrowsableState.Never)]
		public override bool Equals(object obj) => base.Equals(obj);

		/// <summary>
		/// Hides the <see cref="GetHashCode"/> method.
		/// </summary>
		[Browsable(false)]
		[EditorBrowsable(EditorBrowsableState.Never)]
		public override int GetHashCode() => base.GetHashCode();

		/// <summary>
		/// Hides the <see cref="ToString"/> method.
		/// </summary>
		[Browsable(false)]
		[EditorBrowsable(EditorBrowsableState.Never)]
		public override string ToString() => base.ToString();
	}
}


text:
package com.twosigma.beakerx.chart.serializer;

import com.twosigma.beakerx.util.SerializerUtil;
import com.twosigma.beakerx.chart.Color;
import com.twosigma.beakerx.chart.xychart.NanoPlot;
import com.twosigma.beakerx.chart.xychart.plotitem.ConstantLine;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;

import java.io.IOException;

public class ConstantLineSerializer extends JsonSerializer<ConstantLine> {

  public static final String TYPE = "type";

  @Override
  public void serialize(ConstantLine constantLine, JsonGenerator jgen, SerializerProvider sp)
    throws IOException, JsonProcessingException {

    jgen.writeStartObject();

    boolean isNanoPlot = NanoPlot.isNanoPlotClass(constantLine.getPlotType());
    jgen.writeObjectField(TYPE, SerializerUtil.getTypeName(constantLine));
    jgen.writeObjectField("x", isNanoPlot ? processLargeNumber(constantLine.getX()) : constantLine.getX());
    jgen.writeObjectField("y", constantLine.getY());
    jgen.writeObjectField("visible", constantLine.getVisible());
    jgen.writeObjectField("yAxis", constantLine.getYAxis());
    jgen.writeObjectField("showLabel", constantLine.getShowLabel());
    if (constantLine.getWidth() != null) {
      jgen.writeObjectField("width", constantLine.getWidth());
    }
    if (constantLine.getStyle() != null) {
      jgen.writeObjectField("style", constantLine.getStyle().toString());
    }
    if (constantLine.getColor() instanceof Color) {
      jgen.writeObjectField("color", constantLine.getColor());
    }

    jgen.writeEndObject();
  }

  private String processLargeNumber(Number largeNumber){
    return largeNumber != null ? largeNumber.toString() : "";
  }

}


text:
 Creates a <FieldRef> node for ViewFields clause

**Namespace:** [OfficeDevPnP.Core.Utilities](OfficeDevPnP.Core.Utilities.md)
**Assembly:** OfficeDevPnP.Core.dll
## Syntax
```C#
public static string FieldRef(String fieldName)
```
### Parameters
#### fieldName
  Type: System.String
  Name of the field

### Return Value
Type: string
Returns FieldRef string to be used in CAML queries

## See also
- [CAML](OfficeDevPnP.Core.Utilities.CAML.md)
- [OfficeDevPnP.Core.Utilities](OfficeDevPnP.Core.Utilities.md)


text:
<?php

error_reporting(E_ALL | E_STRICT);

// Required for testing logging of sessionID in pattern layout
session_start();

date_default_timezone_set('Europe/London');

// Define a temp dir where tests may write to
$tmpDir = dirname(__FILE__) . '/../../../target/temp/phpunit';
if (!is_dir($tmpDir)) {
	mkdir($tmpDir, 0777, true);
}
define('PHPUNIT_TEMP_DIR', realpath($tmpDir));

// Make the path to the configurations dir for easier access
$confDir = dirname(__FILE__) . '/../resources/configs';
define('PHPUNIT_CONFIG_DIR', realpath($confDir));

require dirname(__FILE__) . '/../../main/php/Logger.php';
require dirname(__FILE__) . DIRECTORY_SEPARATOR . 'LoggerTestHelper.php';


text: module.exports = require('i18n-context')('ember_super_field', require.resolve('../locales'));


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Rhabdospora ramealis var. macrospora K.R. Appel & Laubert

### Remarks
null


text:
package Kirby::Comicvine;

use strict;
use warnings;

use Mojo::UserAgent;
use Mojo::Util qw/url_escape/;
use Mojo::JSON;
use Data::Dumper;

sub new {
    my $self = shift;
    my %args = @_;
    my %defaults = (
        api     => '',
        url     => 'http://api.comicvine.com',
    );
    my %object = (%defaults, %args);

    $object{'ua'} = Mojo::UserAgent->new();
    $object{'req'} = "$object{'url'}/?api_key=$object{'api'}";
    return bless \%object, $self;
}

sub search {
    my $self = shift;
    my $json = Mojo::JSON->new();
    my %args = @_;
    my %defaults = (
        query => '',
        # blank query seems acceptable to the API
        filter => ["issue", "volume"],
        # searching for issue and volume seems like a sane default
    );
    my %object = (%defaults, %args);

    my $req = "$self{'req'}&query=".url_escape($object{'query'});
    $req .="&resources=".join(',', $object{'filter'});
    $req .= "&format=json";

    my $res = $self{'ua'}->get($req)->res->body;
    print Dumper \$res;
    return $json->decode($res);
}

1;


text:
#if __OBJC__
#  import <Foundation/Foundation.h>
#endif

/**
 * Make global functions usable in C++
 */
#if defined(__cplusplus)
#define ABI11_0_0RCT_EXTERN extern "C" __attribute__((visibility("default")))
#else
#define ABI11_0_0RCT_EXTERN extern __attribute__((visibility("default")))
#endif

/**
 * The ABI11_0_0RCT_DEBUG macro can be used to exclude error checking and logging code
 * from release builds to improve performance and reduce binary size.
 */
#ifndef ABI11_0_0RCT_DEBUG
#if DEBUG
#define ABI11_0_0RCT_DEBUG 1
#else
#define ABI11_0_0RCT_DEBUG 0
#endif
#endif

/**
 * The ABI11_0_0RCT_DEV macro can be used to enable or disable development tools
 * such as the debug executors, dev menu, red box, etc.
 */
#ifndef ABI11_0_0RCT_DEV
#if DEBUG
#define ABI11_0_0RCT_DEV 1
#else
#define ABI11_0_0RCT_DEV 0
#endif
#endif

#if ABI11_0_0RCT_DEV
#define ABI11_0_0RCT_IF_DEV(...) __VA_ARGS__
#else
#define ABI11_0_0RCT_IF_DEV(...)
#endif

#ifndef ABI11_0_0RCT_PROFILE
#define ABI11_0_0RCT_PROFILE ABI11_0_0RCT_DEV
#endif

/**
 * By default, only raise an NSAssertion in debug mode
 * (custom assert functions will still be called).
 */
#ifndef ABI11_0_0RCT_NSASSERT
#define ABI11_0_0RCT_NSASSERT ABI11_0_0RCT_DEBUG
#endif

/**
 * Concat two literals. Supports macro expansions,
 * e.g. ABI11_0_0RCT_CONCAT(foo, __FILE__).
 */
#define ABI11_0_0RCT_CONCAT2(A, B) A ## B
#define ABI11_0_0RCT_CONCAT(A, B) ABI11_0_0RCT_CONCAT2(A, B)

/**
 * Throw an assertion for unimplemented methods.
 */
#define ABI11_0_0RCT_NOT_IMPLEMENTED(method) \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Wmissing-method-return-type\"") \
_Pragma("clang diagnostic ignored \"-Wunused-parameter\"") \
ABI11_0_0RCT_EXTERN NSException *_ABI11_0_0RCTNotImplementedException(SEL, Class); \
method NS_UNAVAILABLE { @throw _ABI11_0_0RCTNotImplementedException(_cmd, [self class]); } \
_Pragma("clang diagnostic pop")

  #define ABI11_0_0EX_REMOVE_VERSION(string) (([string hasPrefix:@"ABI11_0_0"]) ? [string stringByReplacingCharactersInRange:(NSRange){0,@"ABI11_0_0".length} withString:@""] : string)


text:
namespace Owin.Scim.Configuration
{
    using System;

    using DryIoc;

    using NContext.EventHandling;

    public class DryIocActivationProvider : IActivationProvider
    {
        private readonly IContainer _Container;

        public DryIocActivationProvider(IContainer container)
        {
            _Container = container;
        }

        public IHandleEvent<TEvent> CreateInstance<TEvent>(Type handler)
        {
            return _Container.Resolve(handler) as IHandleEvent<TEvent>;
        }
    }
}


text:
#region References

using System;
using System.Runtime.InteropServices;

#endregion

namespace TestR.Internal.Inputs
{
	/// <summary>
	/// The KEYBDINPUT structure contains information about a simulated keyboard event.  (see: http://msdn.microsoft.com/en-us/library/ms646271(VS.85).aspx)
	/// </summary>
	/// <remarks>
	/// Windows 2000/XP: INPUT_KEYBOARD supports nonkeyboard-input methods—such as handwriting recognition or voice recognition—as if it were text input by using the KEYEVENTF_UNICODE flag. If KEYEVENTF_UNICODE is specified, SendInput sends a WM_KEYDOWN or WM_KEYUP message to the foreground thread's message queue with wParam equal to VK_PACKET. Once GetMessage or PeekMessage obtains this message, passing the message to TranslateMessage posts a WM_CHAR message with the Unicode character originally specified by wScan. This Unicode character will automatically be converted to the appropriate ANSI value if it is posted to an ANSI window.
	/// Windows 2000/XP: Set the KEYEVENTF_SCANCODE flag to define keyboard input in terms of the scan code. This is useful to simulate a physical keystroke regardless of which keyboard is currently being used. The virtual key value of a key may alter depending on the current keyboard layout or what other keys were pressed, but the scan code will always be the same.
	/// </remarks>
	[StructLayout(LayoutKind.Sequential)]
	public struct KeyboardInput
	{
		/// <summary>
		/// Specifies a virtual-key code. The code must be a value in the range 1 to 254. If the dwFlags member specifies KEYEVENTF_UNICODE, wVk must be 0.
		/// </summary>
		public ushort KeyCode;

		/// <summary>
		/// Specifies a hardware scan code for the key. If dwFlags specifies KEYEVENTF_UNICODE, wScan specifies a Unicode character which is to be sent to the foreground application.
		/// </summary>
		public ushort Scan;

		/// <summary>
		/// Specifies various aspects of a keystroke. This member can be certain combinations of the following values.
		/// KEYEVENTF_EXTENDEDKEY - If specified, the scan code was preceded by a prefix byte that has the value 0xE0 (224).
		/// KEYEVENTF_KEYUP - If specified, the key is being released. If not specified, the key is being pressed.
		/// KEYEVENTF_SCANCODE - If specified, wScan identifies the key and wVk is ignored.
		/// KEYEVENTF_UNICODE - Windows 2000/XP: If specified, the system synthesizes a VK_PACKET keystroke. The wVk parameter must be zero. This flag can only be combined with the KEYEVENTF_KEYUP flag. For more information, see the Remarks section.
		/// </summary>
		public uint Flags;

		/// <summary>
		/// Time stamp for the event, in milliseconds. If this parameter is zero, the system will provide its own time stamp.
		/// </summary>
		public uint Time;

		/// <summary>
		/// Specifies an additional value associated with the keystroke. Use the GetMessageExtraInfo function to obtain this information.
		/// </summary>
		public IntPtr ExtraInfo;
	}
}


text:
/*-------------------------------------------------------------------------
 *
 * nodeAppendOnlyscan.c
 *	  Support routines for sequential scans of append-only relations.
 *
 * Portions Copyright (c) 2008, greenplum inc
 * Portions Copyright (c) 1996-2006, PostgreSQL Global Development Group
 * Portions Copyright (c) 1994, Regents of the University of California
 *
 *-------------------------------------------------------------------------
 */
/*
 * INTERFACE ROUTINES
 *		ExecAppendOnlyScan				sequentially scans a relation.
 *		ExecAppendOnlyNext				retrieve next tuple in sequential order.
 *		ExecInitAppendOnlyScan			creates and initializes a seqscan node.
 *		ExecEndAppendOnlyScan			releases any storage allocated.
 *		ExecAppendOnlyReScan			rescans the relation
 */
#include "postgres.h"

#include "access/heapam.h"
#include "cdb/cdbappendonlyam.h"
#include "cdb/cdbvars.h"
#include "executor/execdebug.h"
#include "executor/nodeAppendOnlyscan.h"

#include "parser/parsetree.h"

static TupleTableSlot *AppendOnlyNext(AppendOnlyScanState *node);

/*
 * Open/Close underlying AO table.
 * Open/Close means resource acquisition and release.
 */
static void OpenAOScanRelation(AppendOnlyScanState *node);
static void CloseAOScanRelation(AppendOnlyScanState *node);

static void
initGpmonPktForAppendOnlyScan(Plan *planNode, gpmon_packet_t *gpmon_pkt, EState *estate);

/* ----------------------------------------------------------------
 *						Scan Support
 * ----------------------------------------------------------------
 */
/* ----------------------------------------------------------------
 *		SeqNext
 *
 *		This is a workhorse for ExecSeqScan
 * ----------------------------------------------------------------
 */
static TupleTableSlot *
AppendOnlyNext(AppendOnlyScanState *node)
{
	AppendOnlyScanDesc scandesc;
	Index		scanrelid;
	EState	   *estate;
	ScanDirection direction;
	TupleTableSlot *slot;

	Assert((node->ss.scan_state & SCAN_SCAN) != 0);
	/*
	 * get information from the estate and scan state
	 */
	estate = node->ss.ps.state;
	scandesc = node->aos_ScanDesc;
	scanrelid = ((AppendOnlyScan *) node->ss.ps.plan)->scan.scanrelid;
	direction = estate->es_direction;
	slot = node->ss.ss_ScanTupleSlot;

	/*
	 * put the next tuple from the access methods in our tuple slot
	 */
	appendonly_getnext(scandesc, direction, slot);

	return slot;
}

/* ----------------------------------------------------------------
 *		ExecAppendOnlyScan(node)
 *
 *		Scans the relation sequentially and returns the next qualifying
 *		tuple.
 *		It calls the ExecScan() routine and passes it the access method
 *		which retrieve tuples sequentially.
 *
 */

TupleTableSlot *
ExecAppendOnlyScan(AppendOnlyScanState *node)
{
	/*
	 * use AppendOnlyNext as access method
	 */
	TupleTableSlot *slot;

	if((node->ss.scan_state & SCAN_SCAN) == 0)
		OpenAOScanRelation(node);

	slot = ExecScan((ScanState *) node, (ExecScanAccessMtd) AppendOnlyNext);
     	if (!TupIsNull(slot))
        {
     		Gpmon_M_Incr_Rows_Out(GpmonPktFromAppOnlyScanState(node));
                CheckSendPlanStateGpmonPkt(&node->ss.ps);
        }

	Assert((node->ss.scan_state & SCAN_MARKPOS) == 0);
	if(TupIsNull(slot))
		CloseAOScanRelation(node);

	return slot;
}

/* ----------------------------------------------------------------
 *		ExecInitAppendOnlyScan
 * ----------------------------------------------------------------
 */
AppendOnlyScanState *
ExecInitAppendOnlyScan(AppendOnlyScan *node, EState *estate, int eflags)
{
	AppendOnlyScanState	*appendonlystate;
	Relation			currentRelation;

	Assert(outerPlan(node) == NULL);
	Assert(innerPlan(node) == NULL);

	/*
	 * create state structure
	 */
	appendonlystate = makeNode(AppendOnlyScanState);
	appendonlystate->ss.ps.plan = (Plan *) node;
	appendonlystate->ss.ps.state = estate;

	/*
	 * Miscellaneous initialization
	 *
	 * create expression context for node
	 */
	ExecAssignExprContext(estate, &appendonlystate->ss.ps);

	/*
	 * initialize child expressions
	 */
	appendonlystate->ss.ps.targetlist = (List *)
		ExecInitExpr((Expr *) node->scan.plan.targetlist,
					 (PlanState *) appendonlystate);
	appendonlystate->ss.ps.qual = (List *)
		ExecInitExpr((Expr *) node->scan.plan.qual,
					 (PlanState *) appendonlystate);

#define AOSCAN_NSLOTS 2

	/*
	 * tuple table initialization
	 */
	ExecInitResultTupleSlot(estate, &appendonlystate->ss.ps);
	ExecInitScanTupleSlot(estate, &appendonlystate->ss);

	/*
	 * get the relation object id from the relid'th entry in the range table
	 * and open that relation.
	 */
	currentRelation = ExecOpenScanRelation(estate, node->scan.scanrelid);
	appendonlystate->ss.ss_currentRelation = currentRelation;
	ExecAssignScanType(&appendonlystate->ss, RelationGetDescr(currentRelation));

	/*
	 * Initialize result tuple type and projection info.
	 */
	ExecAssignResultTypeFromTL(&appendonlystate->ss.ps);
	ExecAssignScanProjectionInfo(&appendonlystate->ss);

	initGpmonPktForAppendOnlyScan((Plan *)node, &appendonlystate->ss.ps.gpmon_pkt, estate);

	return appendonlystate;
}

/*
 * Open/Close underlying relation for AO Scan.
 *
 * Open/Close means resource allocation/release.  Here, it is file descriptors
 * and the buffers in the aos_ScanDesc.
 *
 * See nodeSeqscan.c as well.
 */
static void OpenAOScanRelation(AppendOnlyScanState *node)
{
	Assert(node->ss.scan_state == SCAN_INIT || node->ss.scan_state == SCAN_DONE);
	Assert(!node->aos_ScanDesc);

	node->aos_ScanDesc = appendonly_beginscan(
			node->ss.ss_currentRelation,
			node->ss.ps.state->es_snapshot,
			0, NULL);
	node->ss.scan_state = SCAN_SCAN;
}

static void CloseAOScanRelation(AppendOnlyScanState *node)
{
	Assert((node->ss.scan_state & SCAN_SCAN) != 0);
	appendonly_endscan(node->aos_ScanDesc);
	node->aos_ScanDesc = NULL;
	node->ss.scan_state = SCAN_INIT;
}

int
ExecCountSlotsAppendOnlyScan(AppendOnlyScan *node)
{
	return ExecCountSlotsNode(outerPlan(node)) +
		ExecCountSlotsNode(innerPlan(node)) +
		AOSCAN_NSLOTS;
}

/* ----------------------------------------------------------------
 *		ExecEndAppendOnlyScan
 *
 *		frees any storage allocated through C routines.
 * ----------------------------------------------------------------
 */
void
ExecEndAppendOnlyScan(AppendOnlyScanState *node)
{
	Relation			relation;
	AppendOnlyScanDesc	scanDesc;

	/*
	 * get information from node
	 */
	relation = node->ss.ss_currentRelation;
	scanDesc = node->aos_ScanDesc;

	/*
	 * Free the exprcontext
	 */
	ExecFreeExprContext(&node->ss.ps);

	/*
	 * clean out the tuple table
	 */
	ExecClearTuple(node->ss.ps.ps_ResultTupleSlot);
	ExecClearTuple(node->ss.ss_ScanTupleSlot);

	ExecEagerFreeAppendOnlyScan(node);

	/*
	 * close the heap relation.
	 */
	ExecCloseScanRelation(relation);

	EndPlanStateGpmonPkt(&node->ss.ps);
}

/* ----------------------------------------------------------------
 *						Join Support
 * ----------------------------------------------------------------
 */

/* ----------------------------------------------------------------
 *		ExecAppendOnlyReScan
 *
 *		Rescans the relation.
 * ----------------------------------------------------------------
 */
void
ExecAppendOnlyReScan(AppendOnlyScanState *node, ExprContext *exprCtxt)
{
	EState				*estate;
	Index				scanrelid;
	AppendOnlyScanDesc	scan;

	estate = node->ss.ps.state;
	scanrelid = ((AppendOnlyScan *) node->ss.ps.plan)->scan.scanrelid;

	/* If this is re-scanning of PlanQual ... */
	if (estate->es_evTuple != NULL &&
		estate->es_evTuple[scanrelid - 1] != NULL)
	{
		estate->es_evTupleNull[scanrelid - 1] = false;
		return;
	}

	if((node->ss.scan_state & SCAN_SCAN) == 0)
		OpenAOScanRelation(node);

	scan = node->aos_ScanDesc;

	appendonly_rescan(scan,			/* scan desc */
					  NULL);		/* new scan keys */

	Gpmon_M_Incr(GpmonPktFromAppOnlyScanState(node), GPMON_APPONLYSCAN_RESCAN);
	CheckSendPlanStateGpmonPkt(&node->ss.ps);
}

static void
initGpmonPktForAppendOnlyScan(Plan *planNode, gpmon_packet_t *gpmon_pkt, EState *estate)
{
	Assert(planNode != NULL && gpmon_pkt != NULL && IsA(planNode, AppendOnlyScan));

	{
		RangeTblEntry *rte = rt_fetch(((AppendOnlyScan *)planNode)->scan.scanrelid,
									  estate->es_range_table);
		char schema_rel_name[SCAN_REL_NAME_BUF_SIZE] = {0};

		Assert(GPMON_APPONLYSCAN_TOTAL <= (int)GPMON_QEXEC_M_COUNT);
		InitPlanNodeGpmonPkt(planNode, gpmon_pkt, estate, PMNT_AppendOnlyScan,
							 (int64)planNode->plan_rows,
							 GetScanRelNameGpmon(rte->relid, schema_rel_name));
	}
}

void
ExecEagerFreeAppendOnlyScan(AppendOnlyScanState *node)
{
	if((node->ss.scan_state & SCAN_SCAN) != 0)
		CloseAOScanRelation(node);
}


text:
Create a Brain object which handles the actual process of fetching a reply.

## async reply (string user, string msg[, scope])

Fetch a reply for the user. This returns a Promise that may be awaited on.

## async _getReply (string user, string msg, string context, int step, scope)

The internal reply method. DO NOT CALL THIS DIRECTLY.

* user, msg and scope are the same as reply()
* context = "normal" or "begin"
* step = the recursion depth
* scope = the call scope for object macros

## string formatMessage (string msg)

Format a user's message for safe processing.

## async triggerRegexp (string user, string trigger)

Prepares a trigger for the regular expression engine.

## string processTags (string user, string msg, string reply, string[] stars, string[] botstars, int step, scope)

Process tags in a reply element.

## string substitute (string msg, string type)

Run substitutions against a message. `type` is either "sub" or "person" for
the type of substitution to run.


text:
from sqlalchemy import MetaData, Table
from migrate import ForeignKeyConstraint

from nova import log as logging

meta = MetaData()

def upgrade(migrate_engine):
    # Upgrade operations go here. Don't create your own engine;
    # bind migrate_engine to your metadata
    meta.bind = migrate_engine
    dialect = migrate_engine.url.get_dialect().name
    if dialect.startswith('sqlite'):
        return

    instances = Table('instances', meta, autoload=True)
    vifs = Table('virtual_interfaces', meta, autoload=True)

    try:
        fkey_name = list(vifs.c.instance_id.foreign_keys)[0].constraint.name
        ForeignKeyConstraint(columns=[vifs.c.instance_id],
                             refcolumns=[instances.c.id],
                             name=fkey_name).drop()

    except Exception:
        logging.error(_("foreign key constraint couldn't be removed"))
        raise

def downgrade(migrate_engine):
    # Operations to reverse the above upgrade go here.
    meta.bind = migrate_engine
    dialect = migrate_engine.url.get_dialect().name
    if dialect.startswith('sqlite'):
        return

    instances = Table('instances', meta, autoload=True)
    vifs = Table('virtual_interfaces', meta, autoload=True)

    try:
        ForeignKeyConstraint(columns=[vifs.c.instance_id],
                             refcolumns=[instances.c.id]).create()
    except Exception:
        logging.error(_("foreign key constraint couldn't be added"))
        raise