text:
package com.digits.sdk.android;

import android.net.Uri;

import io.fabric.sdk.android.services.network.HttpMethod;

import com.twitter.sdk.android.core.TwitterAuthConfig;
import com.twitter.sdk.android.core.TwitterAuthToken;
import com.twitter.sdk.android.core.internal.oauth.OAuth1aHeaders;

import java.util.Map;
/**
 * Provides helper methods to generate OAuth Headers for Digits
 **/
public class DigitsOAuthSigning {
    protected static final String VERIFY_CREDENTIALS_URL = DigitsApi.BASE_HOST_URL + "/1" +
            ".1/sdk/account.json";
    protected final TwitterAuthConfig authConfig;
    protected final TwitterAuthToken authToken;
    protected final OAuth1aHeaders oAuth1aHeaders;

    /**
     * Constructs OAuthSigning with TwitterAuthConfig and TwitterAuthToken
     *
     * @param authConfig The auth config.
     * @param authToken The auth token to use to sign the request.
     */
    public DigitsOAuthSigning(TwitterAuthConfig authConfig, TwitterAuthToken authToken) {
        this(authConfig, authToken, new OAuth1aHeaders());
    }

    DigitsOAuthSigning(TwitterAuthConfig authConfig, TwitterAuthToken authToken,
            OAuth1aHeaders oAuth1aHeaders) {
        if (authConfig == null) {
            throw new IllegalArgumentException("authConfig must not be null");
        }
        if (authToken == null) {
            throw new IllegalArgumentException("authToken must not be null");
        }

        this.authConfig = authConfig;
        this.authToken = authToken;
        this.oAuth1aHeaders = oAuth1aHeaders;
    }

    /**
     * Returns OAuth Echo header for <a href="https://api.digits.com/1.1/sdk/account.json
     * endpoint.
     *
     * @return A map of OAuth Echo headers
     */
    public Map<String, String> getOAuthEchoHeadersForVerifyCredentials() {
        return oAuth1aHeaders.getOAuthEchoHeaders(authConfig, authToken, null,
                HttpMethod.GET.name(), VERIFY_CREDENTIALS_URL, null);
    }

    /**
     * Returns OAuth Echo header for <a href="https://api.digits.com/1.1/sdk/account.json
     * endpoint.
     *
     * @param optParams optional custom params to add the request URL. These extra parameters help
     * as a Nonce between the client's session and the Echo header to validate that this header
     * cannot be reused by another client's session.
     * @return A map of OAuth Echo headers
     */
    public Map<String, String> getOAuthEchoHeadersForVerifyCredentials(Map<String, String>
            optParams) {
        return oAuth1aHeaders.getOAuthEchoHeaders(authConfig, authToken, null,
                HttpMethod.GET.name(), createProviderUrlWithQueryParams(optParams), null);
    }

    private String createProviderUrlWithQueryParams(Map<String, String> optParams) {
        if (optParams == null) {
            return VERIFY_CREDENTIALS_URL;
        }
        final Uri.Builder uriHeader = Uri.parse(VERIFY_CREDENTIALS_URL).buildUpon();
        for (String key : optParams.keySet()) {
            uriHeader.appendQueryParameter(key, optParams.get(key));
        }
        return uriHeader.toString();
    }
}


text:
title: "Statistical inference of factors related to need for invasive cardiac surgery"
collection: consulting
permalink: /consulting/cardiac/
date: 2020-04-16
client: "UBC Vancouver Fraser Medical Program"
---

redpajama_set_name: RedPajamaGithub


text:
(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  typeof define === 'function' && define.amd ? define('d3-hierarchy', ['exports'], factory) :
  factory((global.d3_hierarchy = {}));
}(this, function (exports) { 'use strict';

  function bundle() {
    return function(links) {
      var i = -1,
          n = links.length,
          link,
          paths = new Array(n);
      while (++i < n) link = links[i], paths[i] = path(link.source, link.end);
      return paths;
    };
  };

  function path(start, end) {
    var lca = leastCommonAncestor(start, end),
        points = [start];
    while (start !== lca) {
      start = start.parent;
      points.push(start);
    }
    var k = points.length;
    while (end !== lca) {
      points.splice(k, 0, end);
      end = end.parent;
    }
    return points;
  }

  function ancestors(node) {
    var ancestors = [],
        parent = node.parent;
    while (parent != null) {
      ancestors.push(node);
      node = parent;
      parent = parent.parent;
    }
    ancestors.push(node);
    return ancestors;
  }

  function leastCommonAncestor(a, b) {
    if (a === b) return a;
    var aNodes = ancestors(a),
        bNodes = ancestors(b),
        c = null;
    a = aNodes.pop();
    b = bNodes.pop();
    while (a === b) {
      c = a;
      a = aNodes.pop();
      b = bNodes.pop();
    }
    return c;
  }

  // Pre-order traversal.
  function visitBefore(node, callback) {
    var nodes = [node];
    while ((node = nodes.pop()) != null) {
      callback(node);
      if ((children = node.children) && (n = children.length)) {
        var n, children;
        while (--n >= 0) nodes.push(children[n]);
      }
    }
  };

  // Post-order traversal.
  function visitAfter(node, callback) {
    var nodes = [node], nodes2 = [];
    while ((node = nodes.pop()) != null) {
      nodes2.push(node);
      if ((children = node.children) && (n = children.length)) {
        var i = -1, n, children;
        while (++i < n) nodes.push(children[i]);
      }
    }
    while ((node = nodes2.pop()) != null) {
      callback(node);
    }
  };

  function links(nodes) {
    var links = [];
    nodes.forEach(function(parent) {
      if (parent.children) parent.children.forEach(function(child) {
        links.push({source: parent, target: child});
      });
    });
    return links;
  };

  function defaultChildren(d) {
    return d.children;
  }

  function defaultValue(d) {
    return d.value;
  }

  function defaultSort$1(a, b) {
    return b.value - a.value;
  }

  function rebind(layout, hierarchy) {

    layout.sort = function() {
      var x = hierarchy.sort.apply(hierarchy, arguments);
      return x === hierarchy ? layout : x;
    };

    layout.children = function() {
      var x = hierarchy.children.apply(hierarchy, arguments);
      return x === hierarchy ? layout : x;
    };

    layout.value = function() {
      var x = hierarchy.value.apply(hierarchy, arguments);
      return x === hierarchy ? layout : x;
    };

    layout.nodes = layout;
    layout.links = links;

    return layout;
  };

  function hierarchy() {
    var sort = defaultSort$1,
        children = defaultChildren,
        value = defaultValue;

    function hierarchy(root) {
      var stack = [root],
          nodes = [],
          node;

      root.parent = null;
      root.depth = 0;

      while ((node = stack.pop()) != null) {
        nodes.push(node);
        if ((childs = children.call(hierarchy, node, node.depth)) && (n = childs.length)) {
          var n, childs, child;
          while (--n >= 0) {
            stack.push(child = childs[n]);
            child.parent = node;
            child.depth = node.depth + 1;
          }
          if (value) node.value = 0;
          node.children = childs;
        } else {
          if (value) node.value = +value.call(hierarchy, node, node.depth) || 0;
          delete node.children;
        }
      }

      visitAfter(root, function(node) {
        var childs, parent;
        if (sort && (childs = node.children)) childs.sort(sort);
        if (value && (parent = node.parent)) parent.value += node.value;
      });

      return nodes;
    }

    hierarchy.nodes = hierarchy;

    hierarchy.links = links;

    hierarchy.sort = function(x) {
      return arguments.length ? (sort = x, hierarchy) : sort;
    };

    hierarchy.children = function(x) {
      return arguments.length ? (children = x, hierarchy) : children;
    };

    hierarchy.value = function(x) {
      return arguments.length ? (value = x, hierarchy) : value;
    };

    hierarchy.revalue = function(root) {
      if (value) {
        visitBefore(root, function(node) {
          if (node.children) node.value = 0;
        });
        visitAfter(root, function(node) {
          var parent;
          if (!node.children) node.value = +value.call(hierarchy, node, node.depth) || 0;
          if (parent = node.parent) parent.value += node.value;
        });
      }
      return root;
    };

    return hierarchy;
  };

  function defaultSeparation(a, b) {
    return a.parent === b.parent ? 1 : 2;
  };

  // function radialSeparation(a, b) {
  //   return (a.parent === b.parent ? 1 : 2) / a.depth;
  // }

  // This function is used to traverse the left contour of a subtree (or
  // subforest). It returns the successor of v on this contour. This successor is
  // either given by the leftmost child of v or by the thread of v. The function
  // returns null if and only if v is on the highest level of its subtree.
  function nextLeft(v) {
    var children = v.children;
    return children.length ? children[0] : v.t;
  }

  // This function works analogously to nextLeft.
  function nextRight(v) {
    var children = v.children, n;
    return (n = children.length) ? children[n - 1] : v.t;
  }

  // Shifts the current subtree rooted at w+. This is done by increasing
  // prelim(w+) and mod(w+) by shift.
  function moveSubtree(wm, wp, shift) {
    var change = shift / (wp.i - wm.i);
    wp.c -= change;
    wp.s += shift;
    wm.c += change;
    wp.z += shift;
    wp.m += shift;
  }

  // All other shifts, applied to the smaller subtrees between w- and w+, are
  // performed by this function. To prepare the shifts, we have to adjust
  // change(w+), shift(w+), and change(w-).
  function executeShifts(v) {
    var shift = 0,
        change = 0,
        children = v.children,
        i = children.length,
        w;
    while (--i >= 0) {
      w = children[i];
      w.z += shift;
      w.m += shift;
      shift += w.s + (change += w.c);
    }
  }

  // If vi-'s ancestor is a sibling of v, returns vi-'s ancestor. Otherwise,
  // returns the specified (default) ancestor.
  function nextAncestor(vim, v, ancestor) {
    return vim.a.parent === v.parent ? vim.a : ancestor;
  }

  // Node-link tree diagram using the Reingold-Tilford "tidy" algorithm
  function tree() {
    var layout = hierarchy().sort(null).value(null),
        separation = defaultSeparation,
        size = [1, 1], // width, height
        nodeSize = null;

    function tree(d, i) {
      var nodes = layout.call(this, d, i),
          root0 = nodes[0],
          root1 = wrapTree(root0);

      // Compute the layout using Buchheim et al.'s algorithm.
      visitAfter(root1, firstWalk), root1.parent.m = -root1.z;
      visitBefore(root1, secondWalk);

      // If a fixed node size is specified, scale x and y.
      if (nodeSize) visitBefore(root0, sizeNode);

      // If a fixed tree size is specified, scale x and y based on the extent.
      // Compute the left-most, right-most, and depth-most nodes for extents.
      else {
        var left = root0,
            right = root0,
            bottom = root0;
        visitBefore(root0, function(node) {
          if (node.x < left.x) left = node;
          if (node.x > right.x) right = node;
          if (node.depth > bottom.depth) bottom = node;
        });
        var tx = separation(left, right) / 2 - left.x,
            kx = size[0] / (right.x + separation(right, left) / 2 + tx),
            ky = size[1] / (bottom.depth || 1);
        visitBefore(root0, function(node) {
          node.x = (node.x + tx) * kx;
          node.y = node.depth * ky;
        });
      }

      return nodes;
    }

    function wrapTree(root0) {
      var root1 = {A: null, children: [root0]},
          queue = [root1],
          node1;

      while ((node1 = queue.pop()) != null) {
        for (var children = node1.children, child, i = 0, n = children.length; i < n; ++i) {
          queue.push((children[i] = child = {
            _: children[i], // source node
            parent: node1,
            children: (child = children[i].children) && child.slice() || [],
            A: null, // default ancestor
            a: null, // ancestor
            z: 0, // prelim
            m: 0, // mod
            c: 0, // change
            s: 0, // shift
            t: null, // thread
            i: i // number
          }).a = child);
        }
      }

      return root1.children[0];
    }

    // Computes a preliminary x-coordinate for v. Before that, FIRST WALK is
    // applied recursively to the children of v, as well as the function
    // APPORTION. After spacing out the children by calling EXECUTE SHIFTS, the
    // node v is placed to the midpoint of its outermost children.
    function firstWalk(v) {
      var children = v.children,
          siblings = v.parent.children,
          w = v.i ? siblings[v.i - 1] : null;
      if (children.length) {
        executeShifts(v);
        var midpoint = (children[0].z + children[children.length - 1].z) / 2;
        if (w) {
          v.z = w.z + separation(v._, w._);
          v.m = v.z - midpoint;
        } else {
          v.z = midpoint;
        }
      } else if (w) {
        v.z = w.z + separation(v._, w._);
      }
      v.parent.A = apportion(v, w, v.parent.A || siblings[0]);
    }

    // Computes all real x-coordinates by summing up the modifiers recursively.
    function secondWalk(v) {
      v._.x = v.z + v.parent.m;
      v.m += v.parent.m;
    }

    // The core of the algorithm. Here, a new subtree is combined with the
    // previous subtrees. Threads are used to traverse the inside and outside
    // contours of the left and right subtree up to the highest common level. The
    // vertices used for the traversals are vi+, vi-, vo-, and vo+, where the
    // superscript o means outside and i means inside, the subscript - means left
    // subtree and + means right subtree. For summing up the modifiers along the
    // contour, we use respective variables si+, si-, so-, and so+. Whenever two
    // nodes of the inside contours conflict, we compute the left one of the
    // greatest uncommon ancestors using the function ANCESTOR and call MOVE
    // SUBTREE to shift the subtree and prepare the shifts of smaller subtrees.
    // Finally, we add a new thread (if necessary).
    function apportion(v, w, ancestor) {
      if (w) {
        var vip = v,
            vop = v,
            vim = w,
            vom = vip.parent.children[0],
            sip = vip.m,
            sop = vop.m,
            sim = vim.m,
            som = vom.m,
            shift;
        while (vim = nextRight(vim), vip = nextLeft(vip), vim && vip) {
          vom = nextLeft(vom);
          vop = nextRight(vop);
          vop.a = v;
          shift = vim.z + sim - vip.z - sip + separation(vim._, vip._);
          if (shift > 0) {
            moveSubtree(nextAncestor(vim, v, ancestor), v, shift);
            sip += shift;
            sop += shift;
          }
          sim += vim.m;
          sip += vip.m;
          som += vom.m;
          sop += vop.m;
        }
        if (vim && !nextRight(vop)) {
          vop.t = vim;
          vop.m += sim - sop;
        }
        if (vip && !nextLeft(vom)) {
          vom.t = vip;
          vom.m += sip - som;
          ancestor = v;
        }
      }
      return ancestor;
    }

    function sizeNode(node) {
      node.x *= size[0];
      node.y = node.depth * size[1];
    }

    tree.separation = function(x) {
      if (!arguments.length) return separation;
      separation = x;
      return tree;
    };

    tree.size = function(x) {
      if (!arguments.length) return nodeSize ? null : size;
      nodeSize = (size = x) == null ? sizeNode : null;
      return tree;
    };

    tree.nodeSize = function(x) {
      if (!arguments.length) return nodeSize ? size : null;
      nodeSize = (size = x) == null ? null : sizeNode;
      return tree;
    };

    return rebind(tree, layout);
  };

  function meanX(children) {
    return children.reduce(function(x, c) { return x + c.x; }, 0) / children.length;
  }

  function maxY(children) {
    return 1 + children.reduce(function(y, c) { return Math.max(y, c.y); }, 0);
  }

  function leftLeaf(node) {
    var children;
    while ((children = node.children) && children.length) node = children[0];
    return node;
  }

  function rightLeaf(node) {
    var children, n;
    while ((children = node.children) && (n = children.length)) node = children[n - 1];
    return node;
  }

  // Implements a hierarchical layout using the cluster (or dendrogram)
  // algorithm.
  function cluster() {
    var layout = hierarchy().sort(null).value(null),
        separation = defaultSeparation,
        size = [1, 1], // width, height
        nodeSize = false;

    function cluster(d, i) {
      var nodes = layout.call(this, d, i),
          root = nodes[0],
          previousNode,
          x = 0;

      // First walk, computing the initial x & y values.
      visitAfter(root, function(node) {
        var children = node.children;
        if (children && children.length) {
          node.x = meanX(children);
          node.y = maxY(children);
        } else {
          node.x = previousNode ? x += separation(node, previousNode) : 0;
          node.y = 0;
          previousNode = node;
        }
      });

      // Compute the left-most, right-most, and depth-most nodes for extents.
      var left = leftLeaf(root),
          right = rightLeaf(root),
          x0 = left.x - separation(left, right) / 2,
          x1 = right.x + separation(right, left) / 2;

      // Second walk, normalizing x & y to the desired size.
      visitAfter(root, nodeSize ? function(node) {
        node.x = (node.x - root.x) * size[0];
        node.y = (root.y - node.y) * size[1];
      } : function(node) {
        node.x = (node.x - x0) / (x1 - x0) * size[0];
        node.y = (1 - (root.y ? node.y / root.y : 1)) * size[1];
      });

      return nodes;
    }

    cluster.separation = function(x) {
      if (!arguments.length) return separation;
      separation = x;
      return cluster;
    };

    cluster.size = function(x) {
      if (!arguments.length) return nodeSize ? null : size;
      nodeSize = (size = x) == null;
      return cluster;
    };

    cluster.nodeSize = function(x) {
      if (!arguments.length) return nodeSize ? size : null;
      nodeSize = (size = x) != null;
      return cluster;
    };

    return rebind(cluster, layout);
  };

  // Returns the smallest circle that contains the specified circles.
  function enclosingCircle(circles) {
    return enclosingCircleIntersectingCircles(randomizedList(circles), []);
  };

  // Returns a linked list from the specified array in random order.
  function randomizedList(array) {
    var i,
        n = (array = array.slice()).length,
        head = null,
        node = head;

    while (n) {
      var next = {id: array.length - n, value: array[n - 1], next: null};
      if (node) node = node.next = next;
      else node = head = next;
      array[i] = array[--n];
    }

    return {head: head, tail: node};
  }

  // Returns the smallest circle that contains the circles L
  // and intersects the circles B.
  function enclosingCircleIntersectingCircles(L, B) {
    var circle,
        l0 = null,
        l1 = L.head,
        l2,
        p1;

    switch (B.length) {
      case 1: circle = B[0]; break;
      case 2: circle = circleIntersectingTwoCircles(B[0], B[1]); break;
      case 3: circle = circleIntersectingThreeCircles(B[0], B[1], B[2]); break;
    }

    while (l1) {
      p1 = l1.value, l2 = l1.next;
      if (!circle || !circleContainsCircle(circle, p1)) {

        // Temporarily truncate L before l1.
        if (l0) L.tail = l0, l0.next = null;
        else L.head = L.tail = null;

        B.push(p1);
        circle = enclosingCircleIntersectingCircles(L, B); // Note: reorders L!
        B.pop();

        // Move l1 to the front of L and reconnect the truncated list L.
        if (L.head) l1.next = L.head, L.head = l1;
        else l1.next = null, L.head = L.tail = l1;
        l0 = L.tail, l0.next = l2;

      } else {
        l0 = l1;
      }
      l1 = l2;
    }

    L.tail = l0;
    return circle;
  }

  // Returns true if the specified circle1 contains the specified circle2.
  function circleContainsCircle(circle1, circle2) {
    var xc0 = circle1.x - circle2.x,
        yc0 = circle1.y - circle2.y;
    return Math.sqrt(xc0 * xc0 + yc0 * yc0) < circle1.r - circle2.r + 1e-6;
  }

  // Returns the smallest circle that intersects the two specified circles.
  function circleIntersectingTwoCircles(circle1, circle2) {
    var x1 = circle1.x, y1 = circle1.y, r1 = circle1.r,
        x2 = circle2.x, y2 = circle2.y, r2 = circle2.r,
        x12 = x2 - x1, y12 = y2 - y1, r12 = r2 - r1,
        l = Math.sqrt(x12 * x12 + y12 * y12);
    return {
      x: (x1 + x2 + x12 / l * r12) / 2,
      y: (y1 + y2 + y12 / l * r12) / 2,
      r: (l + r1 + r2) / 2
    };
  }

  // Returns the smallest circle that intersects the three specified circles.
  function circleIntersectingThreeCircles(circle1, circle2, circle3) {
    var x1 = circle1.x, y1 = circle1.y, r1 = circle1.r,
        x2 = circle2.x, y2 = circle2.y, r2 = circle2.r,
        x3 = circle3.x, y3 = circle3.y, r3 = circle3.r,
        a2 = 2 * (x1 - x2),
        b2 = 2 * (y1 - y2),
        c2 = 2 * (r2 - r1),
        d2 = x1 * x1 + y1 * y1 - r1 * r1 - x2 * x2 - y2 * y2 + r2 * r2,
        a3 = 2 * (x1 - x3),
        b3 = 2 * (y1 - y3),
        c3 = 2 * (r3 - r1),
        d3 = x1 * x1 + y1 * y1 - r1 * r1 - x3 * x3 - y3 * y3 + r3 * r3,
        ab = a3 * b2 - a2 * b3,
        xa = (b2 * d3 - b3 * d2) / ab - x1,
        xb = (b3 * c2 - b2 * c3) / ab,
        ya = (a3 * d2 - a2 * d3) / ab - y1,
        yb = (a2 * c3 - a3 * c2) / ab,
        A = xb * xb + yb * yb - 1,
        B = 2 * (xa * xb + ya * yb + r1),
        C = xa * xa + ya * ya - r1 * r1,
        r = (-B - Math.sqrt(B * B - 4 * A * C)) / (2 * A);
    return {
      x: xa + xb * r + x1,
      y: ya + yb * r + y1,
      r: r
    };
  }

  function defaultSort(a, b) {
    return a.value - b.value;
  }

  function insert(a, b) {
    var c = a._pack_next;
    a._pack_next = b;
    b._pack_prev = a;
    b._pack_next = c;
    c._pack_prev = b;
  }

  function splice(a, b) {
    a._pack_next = b;
    b._pack_prev = a;
  }

  function intersects(a, b) {
    var dx = b.x - a.x,
        dy = b.y - a.y,
        dr = a.r + b.r;
    return 0.999 * dr * dr > dx * dx + dy * dy; // relative error within epsilon
  }

  function packChildren(node) {
    if (!(nodes = node.children) || !(n = nodes.length)) return;

    var nodes,
        a, b, c, i, j, k, n;

    // Create node links.
    nodes.forEach(link);

    // Create first node.
    a = nodes[0];
    a.x = -a.r;
    a.y = 0;

    // Create second node.
    if (n > 1) {
      b = nodes[1];
      b.x = b.r;
      b.y = 0;

      // Create third node and build chain.
      if (n > 2) {
        c = nodes[2];
        place(a, b, c);
        insert(a, c);
        a._pack_prev = c;
        insert(c, b);
        b = a._pack_next;

        // Now iterate through the rest.
        for (i = 3; i < n; i++) {
          place(a, b, c = nodes[i]);

          // Search for the closest intersection.
          var isect = 0, s1 = 1, s2 = 1;
          for (j = b._pack_next; j !== b; j = j._pack_next, s1++) {
            if (intersects(j, c)) {
              isect = 1;
              break;
            }
          }
          if (isect == 1) {
            for (k = a._pack_prev; k !== j._pack_prev; k = k._pack_prev, s2++) {
              if (intersects(k, c)) {
                break;
              }
            }
          }

          // Update node chain.
          if (isect) {
            if (s1 < s2 || (s1 == s2 && b.r < a.r)) splice(a, b = j);
            else splice(a = k, b);
            i--;
          } else {
            insert(a, c);
            b = c;
          }
        }
      }
    }

    // Re-center the circles and compute the encompassing radius.
    var c = enclosingCircle(nodes);
    for (i = 0; i < n; ++i) {
      a = nodes[i];
      a.x -= c.x;
      a.y -= c.y;
    }
    node.r = c.r;

    // Remove node links.
    nodes.forEach(unlink);
  }

  function link(node) {
    node._pack_next = node._pack_prev = node;
  }

  function unlink(node) {
    delete node._pack_next;
    delete node._pack_prev;
  }

  function transform(node, x, y, k) {
    var children = node.children;
    node.x = x += k * node.x;
    node.y = y += k * node.y;
    node.r *= k;
    if (children) {
      var i = -1, n = children.length;
      while (++i < n) transform(children[i], x, y, k);
    }
  }

  function place(a, b, c) {
    var db = a.r + c.r,
        dx = b.x - a.x,
        dy = b.y - a.y;
    if (db && (dx || dy)) {
      var da = b.r + c.r,
          dc = dx * dx + dy * dy;
      da *= da;
      db *= db;
      var x = 0.5 + (db - da) / (2 * dc),
          y = Math.sqrt(Math.max(0, 2 * da * (db + dc) - (db -= dc) * db - da * da)) / (2 * dc);
      c.x = a.x + x * dx + y * dy;
      c.y = a.y + x * dy - y * dx;
    } else {
      c.x = a.x + db;
      c.y = a.y;
    }
  }

  function pack() {
    var layout = hierarchy().sort(defaultSort),
        padding = 0,
        size = [1, 1],
        radius;

    function pack(d, i) {
      var nodes = layout.call(this, d, i),
          root = nodes[0],
          w = size[0],
          h = size[1],
          r = radius == null ? Math.sqrt : typeof radius === "function" ? radius : function() { return radius; };

      // Recursively compute the layout.
      root.x = root.y = 0;
      visitAfter(root, function(d) { d.r = +r(d.value); });
      visitAfter(root, packChildren);

      // When padding, recompute the layout using scaled padding.
      if (padding) {
        var dr = padding * (radius ? 1 : Math.max(2 * root.r / w, 2 * root.r / h)) / 2;
        visitAfter(root, function(d) { d.r += dr; });
        visitAfter(root, packChildren);
        visitAfter(root, function(d) { d.r -= dr; });
      }

      // Translate and scale the layout to fit the requested size.
      transform(root, w / 2, h / 2, radius ? 1 : 1 / Math.max(2 * root.r / w, 2 * root.r / h));

      return nodes;
    }

    pack.size = function(_) {
      if (!arguments.length) return size.slice();
      size = [+_[0], +_[1]];
      return pack;
    };

    pack.radius = function(_) {
      if (!arguments.length) return radius;
      radius = _ == null || typeof _ === "function" ? _ : +_;
      return pack;
    };

    pack.padding = function(_) {
      if (!arguments.length) return padding;
      padding = +_;
      return pack;
    };

    return rebind(pack, layout);
  };

  // TODO use visit function?
  function depth(node) {
    var c = node.children, d = 0, i, n;
    if (c) for (i = 0, n = c.length; i < n; ++i) d = Math.max(d, depth(c[i]));
    return 1 + d;
  }

  // TODO use visit function?
  function position(node, x, dx, dy) {
    var children = node.children;
    node.x = x;
    node.y = node.depth * dy;
    node.dx = dx;
    node.dy = dy;
    if (children && (n = children.length)) {
      var i = -1,
          n,
          c,
          d;
      dx = node.value ? dx / node.value : 0;
      while (++i < n) {
        position(c = children[i], x, d = c.value * dx, dy);
        x += d;
      }
    }
  }

  function partition() {
    var layout = hierarchy(),
        size = [1, 1]; // width, height

    function partition(d, i) {
      var nodes = layout.call(this, d, i);
      position(nodes[0], 0, size[0], size[1] / depth(nodes[0]));
      return nodes;
    }

    partition.size = function(x) {
      if (!arguments.length) return size.slice();
      size = [+x[0], +x[1]];
      return partition;
    };

    return rebind(partition, layout);
  };

  var phi = (1 + Math.sqrt(5)) / 2; // golden ratio

  function padNone(node) {
    return {x: node.x, y: node.y, dx: node.dx, dy: node.dy};
  }

  function padStandard(node, padding) {
    var x = node.x + padding[3],
        y = node.y + padding[0],
        dx = node.dx - padding[1] - padding[3],
        dy = node.dy - padding[0] - padding[2];
    if (dx < 0) { x += dx / 2; dx = 0; }
    if (dy < 0) { y += dy / 2; dy = 0; }
    return {x: x, y: y, dx: dx, dy: dy};
  }

  var modes = {
    "slice": 1,
    "dice": 1,
    "slice-dice": 1,
    "squarify": 1
  };

  // Squarified Treemaps by Mark Bruls, Kees Huizing, and Jarke J. van Wijk.
  // Modified to support a target aspect ratio by Jeff Heer.
  function treemap() {
    var layout = hierarchy(),
        round = Number,
        size = [1, 1], // width, height
        padding = null,
        pad = padNone,
        sticky = false,
        stickies,
        mode = "squarify",
        ratio = phi;

    function padFunction(node) {
      var p = padding.call(treemap, node, node.depth);
      return p == null
          ? padNone(node)
          : padStandard(node, typeof p === "number" ? [p, p, p, p] : p);
    }

    function padConstant(node) {
      return padStandard(node, padding);
    }

    // Compute the area for each child based on value & scale.
    function scale(children, k) {
      var i = -1,
          n = children.length,
          child,
          area;
      while (++i < n) {
        area = (child = children[i]).value * (k < 0 ? 0 : k);
        child.area = isNaN(area) || area <= 0 ? 0 : area;
      }
    }

    // Recursively arranges the specified node's children into squarified rows.
    function squarify(node) {
      var children = node.children;
      if (children && children.length) {
        var rect = pad(node),
            row = [],
            remaining = children.slice(), // copy-on-write
            child,
            best = Infinity, // the best row score so far
            score, // the current row score
            u = mode === "slice" ? rect.dx
              : mode === "dice" ? rect.dy
              : mode === "slice-dice" ? node.depth & 1 ? rect.dy : rect.dx
              : Math.min(rect.dx, rect.dy), // initial orientation
            n;
        scale(remaining, rect.dx * rect.dy / node.value);
        row.area = 0;
        while ((n = remaining.length) > 0) {
          row.push(child = remaining[n - 1]);
          row.area += child.area;
          if (mode !== "squarify" || (score = worst(row, u)) <= best) { // continue with this orientation
            remaining.pop();
            best = score;
          } else { // abort, and try a different orientation
            row.area -= row.pop().area;
            position(row, u, rect, false);
            u = Math.min(rect.dx, rect.dy);
            row.length = row.area = 0;
            best = Infinity;
          }
        }
        if (row.length) {
          position(row, u, rect, true);
          row.length = row.area = 0;
        }
        children.forEach(squarify);
      }
    }

    // Recursively resizes the specified node's children into existing rows.
    // Preserves the existing layout!
    function stickify(node) {
      var children = node.children;
      if (children && children.length) {
        var rect = pad(node),
            remaining = children.slice(), // copy-on-write
            child,
            row = [];
        scale(remaining, rect.dx * rect.dy / node.value);
        row.area = 0;
        while (child = remaining.pop()) {
          row.push(child);
          row.area += child.area;
          if (child.z != null) {
            position(row, child.z ? rect.dx : rect.dy, rect, !remaining.length);
            row.length = row.area = 0;
          }
        }
        children.forEach(stickify);
      }
    }

    // Computes the score for the specified row, as the worst aspect ratio.
    function worst(row, u) {
      var s = row.area,
          r,
          rmax = 0,
          rmin = Infinity,
          i = -1,
          n = row.length;
      while (++i < n) {
        if (!(r = row[i].area)) continue;
        if (r < rmin) rmin = r;
        if (r > rmax) rmax = r;
      }
      s *= s;
      u *= u;
      return s
          ? Math.max((u * rmax * ratio) / s, s / (u * rmin * ratio))
          : Infinity;
    }

    // Positions the specified row of nodes. Modifies `rect`.
    function position(row, u, rect, flush) {
      var i = -1,
          n = row.length,
          x = rect.x,
          y = rect.y,
          v = u ? round(row.area / u) : 0,
          o;
      if (u == rect.dx) { // horizontal subdivision
        if (flush || v > rect.dy) v = rect.dy; // over+underflow
        while (++i < n) {
          o = row[i];
          o.x = x;
          o.y = y;
          o.dy = v;
          x += o.dx = Math.min(rect.x + rect.dx - x, v ? round(o.area / v) : 0);
        }
        o.z = true;
        o.dx += rect.x + rect.dx - x; // rounding error
        rect.y += v;
        rect.dy -= v;
      } else { // vertical subdivision
        if (flush || v > rect.dx) v = rect.dx; // over+underflow
        while (++i < n) {
          o = row[i];
          o.x = x;
          o.y = y;
          o.dx = v;
          y += o.dy = Math.min(rect.y + rect.dy - y, v ? round(o.area / v) : 0);
        }
        o.z = false;
        o.dy += rect.y + rect.dy - y; // rounding error
        rect.x += v;
        rect.dx -= v;
      }
    }

    function treemap(d) {
      var nodes = stickies || layout(d),
          root = nodes[0];
      root.x = 0;
      root.y = 0;
      root.dx = size[0];
      root.dy = size[1];
      if (stickies) layout.revalue(root);
      scale([root], root.dx * root.dy / root.value);
      (stickies ? stickify : squarify)(root);
      if (sticky) stickies = nodes;
      return nodes;
    }

    treemap.size = function(x) {
      if (!arguments.length) return size.slice();
      size = [+x[0], +x[1]];
      return treemap;
    };

    treemap.padding = function(x) {
      if (!arguments.length) return Array.isArray(padding) ? padding.slice() : padding;
      var t;
      pad = x == null ? (padding = null, padNone)
          : (t = typeof x) === "function" ? (padding = x, padFunction)
          : t === "number" ? (padding = [x, x, x, x], padConstant)
          : (padding = [+x[0], +x[1], +x[2], +x[3]], padConstant);
      return treemap;
    };

    treemap.round = function(x) {
      if (!arguments.length) return round !== Number;
      round = x ? Math.round : Number;
      return treemap;
    };

    treemap.sticky = function(x) {
      if (!arguments.length) return sticky;
      sticky = !!x, stickies = null;
      return treemap;
    };

    treemap.ratio = function(x) {
      if (!arguments.length) return ratio;
      ratio = +x;
      return treemap;
    };

    treemap.mode = function(x) {
      if (!arguments.length) return mode;
      mode = modes.hasOwnProperty(x) ? x + "" : "squarify";
      return treemap;
    };

    return rebind(treemap, layout);
  };

  var version = "0.0.2";

  exports.version = version;
  exports.bundle = bundle;
  exports.cluster = cluster;
  exports.links = links;
  exports.pack = pack;
  exports.partition = partition;
  exports.tree = tree;
  exports.treemap = treemap;

}));


text:
package org.fogbeam.experimental.reasoning.tangential;

import static org.fogbeam.experimental.reasoning.abductive.AbductionConstants1.TDB_DIR;

import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.eclipse.collections.api.set.UnsortedSetIterable;
import org.eclipse.collections.impl.set.mutable.UnifiedSet;
import org.fogbeam.experimental.reasoning.abductive.queries.QueryManifestationsStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PowerSetMain
{
	final static Logger logger = LoggerFactory.getLogger(PowerSetMain.class);

	public static void main(String[] args)
	{

		PowerSetMain main = new PowerSetMain();
		main.run();

		logger.debug( "done" );

	}

	// generate the power-set of our set
	public void run()
	{
		QueryManifestationsStrategy query = new QueryManifestationsStrategy( TDB_DIR + "/trivial" );

		Set<String> manifestations = query.listAll();

		UnifiedSet<String> uSet = new UnifiedSet<String>();
		uSet.addAll(manifestations);

		Set<UnsortedSetIterable<String>> powerSet = uSet.powerSet();

		for( UnsortedSetIterable<String> setInPowerSet : powerSet )
		{
			System.out.print( "{ ");
			setInPowerSet.forEach( (k) -> { System.out.print( StringUtils.substringAfter(k, "#") + " " ); } );
			logger.debug( "}\n" );
		}
	}
}


text:
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>ThunderRTC Demo: Instant Messaging + Rooms </title>
        <link rel="stylesheet" type="text/css" href="/thunderrtc/thunderrtc.css" />

        <link rel="stylesheet" type="text/css" href="css/landing.css" />

        <link rel="stylesheet" type="text/css" href="js/prettify/prettify.css" />

Local Demos

Documentation

Support: Discussion Group

ThunderRTC.com

ThunderRTC Demo: Instant Messaging + Rooms

Note: This is primarily an application
                    developed to test new features going into ThunderRTC Modular (v1.0.x). It's currently not written to be a tutorial,
                    but it does demonstrate how to use various features like presence and room targeted messaging.

The Demo

                    Username: <input type="text" id="userNameField" />
                    Password: <input type="text" id="credentialField" />

                        <button id="connectButton" onclick="connect();">Connect</button>

                    <button onclick="disconnect();">Disconnect from server.</button>

                    Presence:
                    <input type="radio" name="presence" onclick="setPresence('away');"/>away
                    <input type="radio" name="presence" checked onclick="setPresence('chat');"/>chat
                    <input type="radio" name="presence" onclick="setPresence('dnd');"/>dnd
                    <input type="radio" name="presence" onclick="setPresence('xa');"/>xa
                    <input type="text" onkeyup="updatePresenceStatus(this.value);" />

                    Quick Join -

 <button onclick="refreshRoomList();"> Refresh</button>
                    <button onclick="addRoom(null, null, true);">or join </button>
                    <input id="roomToAdd" type="text" size="20" />

                    Optional room parameters<input id="optRoomParms" type="text" size="20"/>

Not connected yet

                        <textarea id="sendMessageText" placeholder="Enter your message here"></textarea>

                        Rooms:

                        Received Messages:

 Adding api fields

                    <input type="text" id="apiroomname" placeholder="room name">
                    <input type="text" id="apifieldname" placeholder="field name">

                    <input size="50" type="text" id="apifieldvalue" placeholder="field value">

                    <button onclick="addApiField()">Add the api field</button>

Getting the list of room occupants

                    <input type="text" id="queryRoom" placeholder="room name">
                    <button onclick="queryRoomNames();">Dump occupant names to console</button>

Fields from server

                    <button onclick="thunderrtc.getFreshIceConfig();" class="postconnection"> Get Fresh ICE configuration</button>

 Name To Id

                        <input id="targetName" type="text" />
                        <button onclick="getIdsOfName();">Fetch ids</button>

Testing the following ThunderRTC Features:

Authentication - If username is provided, it will be available to others to see.

Define Rooms during Authentication - You can join rooms before you press 'Connect'.

Default Rooms - If you join no rooms before you connect, you will join the default room.

Messages to All In Room (targetRoom) - Type a message, then click on a room name to send it to everyone in the same room. When received, the other client will know it was sent to the room at large.

Message to Individual In Room (targetRoom + targetThunderrtcid) - Type a message, then click on another client in a room to send it to just that person. That person will know it was sent directly to them, and that it was sent via a specific room.

Presence - Your presence gets sent to all clients in rooms you share. DND=Do not disturb. XE=Extended Away. The status field can be any string.

Delta Lists - After initial login, the client should only receive changes to who is online.

© 2014 - CosRTC Software Inc., All Rights Reserved.

ThunderRTC source code released under a BSD2 License. See LICENSE file in project folder for details.


text:
package com.linkedin.thirdeye.client.util;

import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.Multimap;
import org.joda.time.DateTime;
import org.joda.time.format.ISODateTimeFormat;
import org.testng.Assert;
import org.testng.annotations.Test;

public class TestSqlUtils {
  @Test
  public void testGetBetweenClause() {
    DateTime start = ISODateTimeFormat.dateTimeParser().parseDateTime("2015-01-01TZ");
    DateTime end = ISODateTimeFormat.dateTimeParser().parseDateTime("2015-01-02TZ");
    String betweenClause = SqlUtils.getBetweenClause(start, end);
    Assert.assertEquals(betweenClause, "time BETWEEN '2015-01-01T00:00:00Z' AND '2015-01-02T00:00:00Z'");
  }

  @Test
  public void testGetDimensionWhereClause() {
    Multimap<String, String> dimensionValues = ImmutableMultimap.of(
        "A", "A1",
        "B", "B1",
        "C", "!");
    String dimensionWhereClause = SqlUtils.getDimensionWhereClause(dimensionValues);
    Assert.assertEquals(dimensionWhereClause, "A = 'A1' AND B = 'B1'");
  }

  @Test
  public void testGetGroupByClause() {
    Multimap<String, String> dimensionValues = ImmutableMultimap.of(
        "A", "A1",
        "B", "B1",
        "C", "!");
    String groupByClause = SqlUtils.getDimensionGroupByClause(dimensionValues);
    Assert.assertEquals(groupByClause, "GROUP BY 'C'");
  }
}


text:
'use strict';

import type {DataID} from 'relay-runtime';

/**
 * @RelayResolver
 * @fieldName client_node(id: ID!)
 * @edgeTo Node
 * @onType User
 */
function client_node(args: {id: string}): DataID {
  return args.id;
}

module.exports = {
  client_node,
};


text:
#import <Foundation/Foundation.h>

@interface PLCrashReportSignalInfo : NSObject {
@private
    /** Signal name */
    NSString *_name;

    /** Signal code */
    NSString *_code;

    /** Fauling instruction or address */
    uint64_t _address;
}

- (id) initWithSignalName: (NSString *) name code: (NSString *) code address: (uint64_t) address;

/**
 * The signal name.
 */
@property(nonatomic, readonly) NSString *name;

/**
 * The signal code.
 */
@property(nonatomic, readonly) NSString *code;

/**
 * The faulting instruction or address.
 */
@property(nonatomic, readonly) uint64_t address;

@end


text:
 * [Project Proposal](docs/proposal.md)
 * [Project Milestone](docs/milestone.md)
 * [Project Final Report](docs/final_report.md)


text:
function Remove-xSPOListContentType {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
        [uri]
        $Url,

        [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
        [string]
        $Title,

        [Parameter(Mandatory, ValueFromPipeline, ValueFromPipelineByPropertyName)]
        [string]
        $Name
    )

    begin {
    }

    process {
        try {
            $SPOClientContext = [Microsoft.SharePoint.Client.ClientContext]::new($Url)
            $SPOClientContext.Credentials = $SPOCredential
            $ListContentTypes = $SPOClientContext.Web.Lists.GetByTitle($Title).ContentTypes
            $SPOClientContext.Load($ListContentTypes)
            $SPOClientContext.ExecuteQuery()
            $SPOClientContext.Dispose()
            for ($i = $ListContentTypes.Count - 1; $i -ge 0; $i--) {
                if ($ListContentTypes[$i].Name -eq $Name) {
                    $ListContentTypes[$i].DeleteObject()
                }
            }
            $SPOClientContext.ExecuteQuery()
            $SPOClientContext.Dispose()
        }
        catch {
            $_.Exception.Message
        }
    }

    end {
    }
}


text:
<!DOCTYPE html>

  <title>Firing Range - Remote Inclusion </title>

        Tests in this page allow an attacker to control the URL of an active
        content being imported in the page.

Full URL

      This class of tests simply takes the URL and uses it as the source of
      the inclusion.

            Remote inclusion - SCRIPT - Parameter

            Remote inclusion - SCRIPT - Hash

            Remote inclusion - OBJECT [Raw] - Parameter

            Remote inclusion - OBJECT [Flash] - Parameter

            Remote inclusion - OBJECT [Raw] - Hash


text:
author: slowe
categories: Information
comments: false
date: 2005-10-06T12:04:41Z
slug: open-source-on-mac-os-x
tags:
- macOS
- OSS
title: Open Source on Mac OS X
url: /2005/10/06/open-source-on-mac-os-x/
wordpress_id: 100
---

Most people automatically equate "open source" with Linux or [Apache](http://www.apache.org/). But there's more to open source than that. There are a wide variety of open source projects that are also targeted at (gasp) [Microsoft Windows](http://www.microsoft.com/windows/) and [Mac OS X](http://www.apple.com/macosx/).

Being a Mac user myself, I was particularly interested in [this article](http://software.newsforge.com/article.pl?sid=05/09/20/166254) recently posted at [NewsForge](http://www.newsforge.com/). Some of the projects listed there were new to me; for example, I had never heard of or used [Vienna](http://www.opencommunity.co.uk/vienna2.html). Given that I don't like brushed metal interfaces (can't stand them) and that I already use a commercial RSS reader, Vienna won't do me much good.

Many of the projects listed there, though, I was familiar with and actually using currently. For example, [Adium X](http://www.adiumx.com/) is my default IM client (I use it to stay connected to MSN, AIM, and Google Talk), [Cyberduck](http://cyberduck.ch/) is my FTP/SFTP client, and [Growl](http://growl.info/) helps keep me informed about what is happening with all the various applications I have running. I've never used [Seashore](http://seashore.sourceforge.net/), but I'll probably have a look at it soon (I've been looking for a good image editor).

[This link](http://www.nothickmanuals.info/doku.php?id=opensourcemac) (also referenced in the NewsForge article) lists an even larger variety of open source Mac applications. Again, some I recognize (and use), a lot that I don't. If you are a Mac user, I encourage you to take another look at some of the many high-quality open source projects available.


text:
import pickle

from huey.exceptions import QueueException

class TaskRegistry(object):
    """
    A simple Registry used to track subclasses of :class:`QueueTask` - the
    purpose of this registry is to allow translation from queue messages to
    task classes, and vice-versa.
    """
    _ignore = ['QueueTask', 'PeriodicQueueTask']

    _registry = {}
    _periodic_tasks = []

    def task_to_string(self, task):
        return '%s' % (task.__name__)

    def register(self, task_class):
        klass_str = self.task_to_string(task_class)
        if klass_str in self._ignore:
            return

        if klass_str not in self._registry:
            self._registry[klass_str] = task_class

            # store an instance in a separate list of periodic tasks
            if hasattr(task_class, 'validate_datetime'):
                self._periodic_tasks.append(task_class())

    def unregister(self, task_class):
        klass_str = self.task_to_string(task_class)

        if klass_str in self._registry:
            del(self._registry[klass_str])

            for task in self._periodic_tasks:
                if isinstance(task, task_class):
                    self._periodic_tasks.remove(task)

    def __contains__(self, klass_str):
        return klass_str in self._registry

    def get_message_for_task(self, task):
        """Convert a task object to a message for storage in the queue"""
        return pickle.dumps((
            task.task_id,
            self.task_to_string(type(task)),
            task.execute_time,
            task.retries,
            task.retry_delay,
            task.get_data(),
        ))

    def get_task_class(self, klass_str):
        klass = self._registry.get(klass_str)

        if not klass:
            raise QueueException('%s not found in TaskRegistry' % klass_str)

        return klass

    def get_task_for_message(self, msg):
        """Convert a message from the queue into a task"""
        # parse out the pieces from the enqueued message
        raw = pickle.loads(msg)
        task_id, klass_str, execute_time, retries, delay, data = raw

        klass = self.get_task_class(klass_str)
        return klass(data, task_id, execute_time, retries, delay)

    def get_periodic_tasks(self):
        return self._periodic_tasks

registry = TaskRegistry()


text:
var gulp = require('gulp')
var log = require('gulp-util').log
var lib = require('./gulpfile.lib.js')
var browserSync = require('browser-sync').create()

var files = {
  js: './index.js',
  jsBndl: '../borgweb/static/bundle.js',
  css: '../borgweb/static/style.css',
  cssBndl: '../borgweb/static/bundle.css'
}
var buildID = 1
var newBuildLog = function () {
  log("Build # " + lib.log (buildID++, 1)
  + " ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") }

gulp.task ('watch', function () {
  newBuildLog(); browserSync.init({ proxy: 'localhost:5000', open: false })
  lib.generateBundle(files.js, files.jsBndl, true)

  gulp.watch([files.js, 'src/**/*.js'], function (ev) {
    if (ev.type == 'changed') {
      newBuildLog()
      log("Changed: " + ev.path)
      var ret = lib.generateBundle(files.js, files.jsBndl)
      setTimeout(function () { browserSync.reload() }, 150) // todo
      return ret
    }
  })
})


text:
//
//  AKHighPassButterworthFilter.h
//  AudioKit
//
//  Auto-generated on 2/19/15.
//  Copyright (c) 2015 Aurelius Prochazka. All rights reserved.
//

#import "AKAudio.h"
#import "AKParameter+Operation.h"

/** A high-pass Butterworth filter.

 These filters are Butterworth second-order IIR filters. They offer an almost flat passband and very good precision and stopband attenuation.
 */

NS_ASSUME_NONNULL_BEGIN
@interface AKHighPassButterworthFilter : AKAudio
/// Instantiates the high pass butterworth filter with all values
/// @param input Input signal to be filtered.
/// @param cutoffFrequency Cutoff frequency for each of the filters. Updated at Control-rate. [Default Value: 500]
- (instancetype)initWithInput:(AKParameter *)input
              cutoffFrequency:(AKParameter *)cutoffFrequency;

/// Instantiates the high pass butterworth filter with default values
/// @param input Input signal to be filtered.
- (instancetype)initWithInput:(AKParameter *)input;

/// Instantiates the high pass butterworth filter with default values
/// @param input Input signal to be filtered.
+ (instancetype)filterWithInput:(AKParameter *)input;

/// Instantiates the high pass butterworth filter with default values
/// @param input Input signal to be filtered.
- (instancetype)initWithPresetDefaultFilterWithInput:(AKParameter *)input;

/// Instantiates the high pass butterworth filter with default values
/// @param input Input signal to be filtered.
+ (instancetype)presetDefaultFilterWithInput:(AKParameter *)input;

/// Instantiates the high pass butterworth filter with a moderate cutoff
/// @param input Input signal to be filtered.
- (instancetype)initWithPresetModerateFilterWithInput:(AKParameter *)input;

/// Instantiates the high pass butterworth filter with a moderate cutoff
/// @param input Input signal to be filtered.
+ (instancetype)presetModerateFilterWithInput:(AKParameter *)input;

/// Instantiates the high pass butterworth filter with an extreme cutoff
/// @param input Input signal to be filtered.
- (instancetype)initWithPresetExtremeFilterWithInput:(AKParameter *)input;

/// Instantiates the high pass butterworth filter with extreme cutoff
/// @param input Input signal to be filtered.
+ (instancetype)presetExtremeFilterWithInput:(AKParameter *)input;

/// Cutoff frequency for each of the filters. [Default Value: 500]
@property (nonatomic) AKParameter *cutoffFrequency;

/// Set an optional cutoff frequency
/// @param cutoffFrequency Cutoff frequency for each of the filters. Updated at Control-rate. [Default Value: 500]
- (void)setOptionalCutoffFrequency:(AKParameter *)cutoffFrequency;

@end
NS_ASSUME_NONNULL_END


text:
import { Controller } from '../src';

@Controller('cats')
export class CatsController {}


text:
package oceanstor

import (
	"encoding/json"
	"errors"
	"fmt"
	"os"
	"strconv"
	"time"

	log "github.com/golang/glog"
	. "github.com/opensds/opensds/contrib/drivers/utils/config"
	model "github.com/opensds/opensds/pkg/model"
	pb "github.com/opensds/opensds/pkg/model/proto"
	"github.com/opensds/opensds/pkg/utils"
	"github.com/opensds/opensds/pkg/utils/config"
	uuid "github.com/satori/go.uuid"
)

func (d *Driver) Setup() error {
	if d.Client != nil {
		return nil
	}

	var err error

	d.InitConf()
	cli, err := newRestCommon(d.Config)
	if err != nil {
		msg := fmt.Sprintf("get new client failed: %v", err)
		log.Error(msg)
		return errors.New(msg)
	}

	d.Client = cli
	log.Info("get oceanstor client successfully")

	return nil
}

func (d *Driver) InitConf() {
	path := config.CONF.OsdsDock.Backends.HuaweiOceanStorFile.ConfigPath
	if path == "" {
		path = DefaultConfPath
	}

	conf := &Config{}
	d.Config = conf
	Parse(conf, path)
}

func (d *Driver) Unset() error {

	if err := d.logout(); err != nil {
		msg := fmt.Sprintf("logout failed: %v", err)
		log.Error(msg)
		return errors.New(msg)
	}

	return nil
}

func (d *Driver) CreateFileShare(opt *pb.CreateFileShareOpts) (*model.FileShareSpec, error) {
	fsName := opt.GetName()
	size := opt.GetSize()
	prf := opt.GetProfile()
	poolID := opt.GetPoolName()
	shareProto := ""

	err := d.parameterCheck(poolID, prf, size, &fsName, &shareProto)
	if err != nil {
		log.Error(err.Error())
		return nil, err
	}

	// create file system
	fs, err := d.createFileSystemIfNotExist(fsName, poolID, size)
	if err != nil {
		msg := fmt.Sprintf("create file system failed: %v", err)
		log.Error(msg)
		return nil, errors.New(msg)
	}

	shareDriver := NewProtocol(shareProto, d.Client)
	// create file share if not exist
	shareID, err := d.createShareIfNotExist(fsName, fs.ID, shareDriver)
	if err != nil {
		return nil, err
	}

	// get location
	location, err := d.getShareLocation(fsName, shareDriver)
	if err != nil {
		msg := fmt.Sprintf("get share location failed: %v", err)
		log.Error(msg)
		return nil, errors.New(msg)
	}

	share := &model.FileShareSpec{
		BaseModel: &model.BaseModel{
			Id: opt.GetId(),
		},
		Name:             opt.GetName(),
		Protocols:        []string{shareProto},
		Description:      opt.GetDescription(),
		Size:             size,
		AvailabilityZone: opt.GetAvailabilityZone(),
		PoolId:           poolID,
		ExportLocations:  location,
		Metadata:         map[string]string{FileShareName: fsName, FileShareID: shareID},
	}
	return share, nil
}

func (d *Driver) parameterCheck(poolID, prf string, size int64, fsName, shareProto *string) error {
	// Parameter check
	if poolID == "" {
		msg := "pool id cannot be empty"
		log.Error(msg)
		return errors.New(msg)
	}

	if *fsName == "" {
		log.Infof("use default file system name %s", defaultFileSystem)
		*fsName = defaultFileSystem
	}

	proto, err := d.GetProtoFromProfile(prf)
	if err != nil {
		return err
	}

	if !checkProtocol(proto) {
		return fmt.Errorf("%s protocol is not supported, support is %s and %s", proto, NFSProto, CIFSProto)
	}

	*shareProto = proto

	if size == 0 {
		return errors.New("size must be greater than 0")
	}

	return nil
}

func (d *Driver) createShareIfNotExist(fsName, fsID string, shareDriver Protocol) (string, error) {
	sharePath := getSharePath(fsName)
	share, err := shareDriver.getShare(fsName)
	if err != nil {
		return "", fmt.Errorf("get share %s failed: %v", sharePath, err)
	}

	if share != nil {
		log.Infof("share %s already exist", sharePath)
		return "", nil
	}

	share, err = shareDriver.createShare(fsName, fsID)
	if err != nil {
		shareDriver.deleteShare(fsName)
		return "", fmt.Errorf("create share %s failed: %v", sharePath, err)
	}

	log.Infof("create share %s successfully", sharePath)
	return shareDriver.getShareID(share), nil
}

func (d *Driver) getShareLocation(fsName string, shareDriver Protocol) ([]string, error) {
	logicalPortList, err := d.getAllLogicalPort()
	if err != nil {
		return nil, err
	}

	location, err := d.getLocationPath(fsName, logicalPortList, shareDriver)
	if err != nil {
		return nil, err
	}

	return location, nil
}

// createFileSystemIfNotExist
func (d *Driver) createFileSystemIfNotExist(fsName, poolID string, size int64) (*FileSystemData, error) {
	fsList, err := d.getFileSystemByName(fsName)
	if err != nil {
		return nil, fmt.Errorf("get filesystem %s by name failed: %v", fsName, err)
	}

	if len(fsList) == 0 {
		fs, err := d.createFileSystem(fsName, poolID, size)
		if err != nil {
			d.DeleteFileSystem(fsName)
			return nil, fmt.Errorf("create file system %s failed, %v", fsName, err)
		}

		err = d.checkFsStatus(fs, poolID)
		if err != nil {
			return nil, err
		}

		log.Infof("create filesystem %s successfully", fsName)
		return fs, nil
	}

	log.Infof("filesystem %s already exist", fsName)
	return &fsList[0], nil
}

func (d *Driver) getLocationPath(sharePath string, logicalPortList []LogicalPortData, shareDriver Protocol) ([]string, error) {
	if len(logicalPortList) == 0 {
		return nil, errors.New("cannot find file share server end logical ip")
	}

	var location []string

	for _, port := range logicalPortList {
		location = append(location, shareDriver.getLocation(sharePath, port.IpAddr))
	}

	return location, nil
}

func (d *Driver) checkFsStatus(fs *FileSystemData, poolID string) error {
	ticker := time.NewTicker(3 * time.Second)
	timeout := time.After(1 * time.Minute)
	var fsStable *FileSystemData
	var err error
	for {
		select {
		case <-ticker.C:
			fsStable, err = d.getFileSystem(fs.ID)
			if err != nil {
				d.DeleteFileSystem(fs.Name)
				return fmt.Errorf("check file system status failed: %v", err)
			}

			if fsStable.HealthStatus == StatusFSHealth && fsStable.RunningStatus == StatusFSRunning {
				return nil
			}

		case <-timeout:
			d.DeleteFileSystem(fs.Name)
			return fmt.Errorf("timeout occured waiting for checking file system status %s or invalid status health:%s, running:%s", fsStable.ID, fsStable.HealthStatus, fsStable.RunningStatus)
		}
	}
}

func (d *Driver) ListPools() ([]*model.StoragePoolSpec, error) {
	var pols []*model.StoragePoolSpec
	sp, err := d.ListStoragePools()
	if err != nil {
		msg := fmt.Sprintf("list pools from storage failed: %v", err)
		log.Error(msg)
		return nil, errors.New(msg)
	}

	c := d.Config
	for _, p := range sp {
		if _, ok := c.Pool[p.Name]; !ok {
			continue
		}
		host, _ := os.Hostname()
		name := fmt.Sprintf("%s:%s:%s", host, d.Endpoint, p.Id)

		userTotalCapacity, _ := strconv.ParseInt(p.UserTotalCapacity, 10, 64)
		userFreeCapacity, _ := strconv.ParseInt(p.UserFreeCapacity, 10, 64)

		pol := &model.StoragePoolSpec{
			BaseModel: &model.BaseModel{
				Id: uuid.NewV5(uuid.NamespaceOID, name).String(),
			},
			Name:             p.Name,
			TotalCapacity:    Sector2Gb(userTotalCapacity),
			FreeCapacity:     Sector2Gb(userFreeCapacity),
			StorageType:      c.Pool[p.Name].StorageType,
			Extras:           c.Pool[p.Name].Extras,
			AvailabilityZone: c.Pool[p.Name].AvailabilityZone,
		}
		if pol.AvailabilityZone == "" {
			pol.AvailabilityZone = defaultAZ
		}
		pols = append(pols, pol)
	}

	if len(pols) == 0 {
		msg := "pools in configuration file not found"
		log.Error(msg)
		return nil, errors.New(msg)
	}

	log.Info("list pools successfully")

	return pols, nil
}

func (d *Driver) getFSInfo(fsName string) (*FileSystemData, error) {
	fsList, err := d.getFileSystemByName(fsName)
	if err != nil {
		return nil, fmt.Errorf("get filesystem %s by name failed: %v", fsName, err)
	}

	if len(fsList) == 0 {
		return nil, fmt.Errorf("filesystem %s does not exist", fsName)
	}

	return &fsList[0], nil
}

func (d *Driver) GetProtoFromProfile(prf string) (string, error) {
	if prf == "" {
		msg := "profile cannot be empty"
		return "", errors.New(msg)
	}

	log.V(5).Infof("file share profile is %s", prf)
	profile := &model.ProfileSpec{}
	err := json.Unmarshal([]byte(prf), profile)
	if err != nil {
		msg := fmt.Sprintf("unmarshal profile failed: %v", err)
		return "", errors.New(msg)
	}

	shareProto := profile.ProvisioningProperties.IOConnectivity.AccessProtocol
	if shareProto == "" {
		msg := "file share protocol cannot be empty"
		return "", errors.New(msg)
	}

	return shareProto, nil
}

func (d *Driver) DeleteFileShare(opt *pb.DeleteFileShareOpts) error {
	shareProto, err := d.GetProtoFromProfile(opt.GetProfile())
	if err != nil {
		log.Error(err.Error())
		return err
	}

	meta := opt.GetMetadata()
	if meta == nil || (meta != nil && meta[FileShareName] == "" && meta[FileShareID] == "") {
		msg := "cannot get file share name and id"
		log.Error(msg)
		return errors.New(msg)
	}

	fsName := meta[FileShareName]
	shareID := meta[FileShareID]

	shareDriver := NewProtocol(shareProto, d.Client)

	sharePath := getSharePath(fsName)
	if err := shareDriver.deleteShare(shareID); err != nil {
		msg := fmt.Sprintf("delete file share %s failed: %v", sharePath, err)
		log.Error(msg)
		return errors.New(msg)
	}

	log.Infof("delete share %s successfully", sharePath)

	if err := d.DeleteFileSystem(fsName); err != nil {
		msg := fmt.Sprintf("delete filesystem %s failed: %v", fsName, err)
		log.Error(msg)
		return errors.New(msg)
	}

	log.Infof("delete file system %s successfully", fsName)

	return nil
}

func (d *Driver) DeleteFileSystem(fsName string) error {
	fs, err := d.getFSInfo(fsName)
	if err != nil {
		return err
	}

	err = d.deleteFS(fs.ID)
	if err != nil {
		return err
	}

	log.Infof("delete filesystem %s successfully", fs.ID)
	return nil
}

func (d *Driver) CreateFileShareSnapshot(opt *pb.CreateFileShareSnapshotOpts) (*model.FileShareSnapshotSpec, error) {
	snapID := opt.GetId()
	if snapID == "" {
		msg := "snapshot id cannot be empty"
		log.Error(msg)
		return nil, errors.New(msg)
	}

	meta := opt.GetMetadata()

	if meta == nil || (meta != nil && meta[FileShareName] == "" && meta[FileShareID] == "") {
		msg := "cannot get file share name and id"
		log.Error(msg)
		return nil, errors.New(msg)
	}

	fsName := meta[FileShareName]

	fs, err := d.getFSInfo(fsName)
	if err != nil {
		msg := fmt.Sprintf("get file system %s failed: %v", fsName, err)
		log.Error(msg)
		return nil, errors.New(msg)
	}

	if fs == nil {
		msg := fmt.Sprintf("%s does not exist", fsName)
		log.Error(msg)
		return nil, errors.New(msg)
	}

	snapName := EncodeName(snapID)

	fsSnapshot, err := d.createSnapshot(fs.ID, snapName)
	if err != nil {
		msg := fmt.Sprintf("create filesystem snapshot failed: %v", err)
		log.Error(msg)
		return nil, errors.New(msg)
	}

	snapSize, _ := strconv.ParseInt(fsSnapshot.Capacity, 10, 64)

	return &model.FileShareSnapshotSpec{
		BaseModel: &model.BaseModel{
			Id: opt.GetId(),
		},
		Name:         snapName,
		Description:  opt.GetDescription(),
		SnapshotSize: snapSize,
		Metadata:     map[string]string{FileShareSnapshotID: fsSnapshot.ID},
	}, nil
}

func (d *Driver) DeleteFileShareSnapshot(opt *pb.DeleteFileShareSnapshotOpts) error {
	meta := opt.GetMetadata()
	if meta == nil || (meta != nil && meta[FileShareSnapshotID] == "") {
		msg := "cannot get file share snapshot id"
		log.Error(msg)
		return errors.New(msg)
	}

	snapID := meta[FileShareSnapshotID]

	err := d.deleteFSSnapshot(snapID)
	if err != nil {
		msg := fmt.Sprintf("delete filesystem snapshot %s failed, %v", snapID, err)
		log.Error(msg)
		return errors.New(msg)
	}

	log.Infof("delete file share snapshot %s successfully", snapID)

	return nil
}

func (d *Driver) getAccessLevel(accessLevels []string, shareProto string) (string, error) {
	var accessLevel string

	if accessLevels == nil || (accessLevels != nil && len(accessLevels) == 0) {
		return "", errors.New("access level cannot be empty")
	}

	supportAccessLevels := []string{AccessLevelRead, AccessLevelWrite}

	if len(accessLevels) > len(supportAccessLevels) {
		return "", errors.New("invalid access level")
	}

	accessLevel = "ro"
	for _, v := range accessLevels {
		if !utils.Contained(v, supportAccessLevels) {
			return "", errors.New("only read only or read write access level are supported")
		}
		if v == AccessLevelWrite {
			accessLevel = "rw"
		}
	}

	shareDriver := NewProtocol(shareProto, d.Client)
	return shareDriver.getAccessLevel(accessLevel), nil
}

func (d *Driver) CreateFileShareAclParamCheck(opt *pb.CreateFileShareAclOpts) (string, string, string, string, error) {
	log.V(5).Infof("create file share access client parameters %#v", opt)
	meta := opt.GetMetadata()

	if meta == nil || (meta != nil && meta[FileShareName] == "" && meta[FileShareID] == "") {
		msg := "cannot get file share name and id"
		log.Error(msg)
		return "", "", "", "", errors.New(msg)
	}

	fsName := meta[FileShareName]
	if fsName == "" {
		return "", "", "", "", errors.New("fileshare name cannot be empty")
	}

	shareProto, err := d.GetProtoFromProfile(opt.Profile)
	if err != nil {
		return "", "", "", "", err
	}

	if !checkProtocol(shareProto) {
		return "", "", "", "", fmt.Errorf("%s protocol is not supported, support is NFS and CIFS", shareProto)
	}

	accessLevels := opt.GetAccessCapability()

	accessLevel, err := d.getAccessLevel(accessLevels, shareProto)
	if err != nil {
		return "", "", "", "", err
	}

	accessType := opt.Type
	if !checkAccessType(accessType) {
		return "", "", "", "", fmt.Errorf("only access type %s and %s are supported", AccessTypeUser, AccessTypeIp)
	}
	if shareProto == CIFSProto && accessType != AccessTypeUser {
		return "", "", "", "", errors.New("only USER access type is allowed for CIFS shares")
	}

	accessTo := opt.GetAccessTo()
	if accessTo == "" {
		return "", "", "", "", errors.New("access client cannot be empty")
	}

	if shareProto == NFSProto {
		if accessType == AccessTypeUser {
			accessTo += "@"
		} else {
			accessTo = "*"
		}
	}

	return fsName, shareProto, accessLevel, accessTo, nil
}

// AllowAccess allow access to the share
func (d *Driver) CreateFileShareAcl(opt *pb.CreateFileShareAclOpts) (*model.FileShareAclSpec, error) {
	shareName, shareProto, accessLevel, accessTo, err := d.CreateFileShareAclParamCheck(opt)
	if err != nil {
		msg := fmt.Sprintf("create fileshare access client failed: %v", err)
		log.Error(msg)
		return nil, errors.New(msg)
	}

	shareDriver := NewProtocol(shareProto, d.Client)

	share, err := shareDriver.getShare(shareName)
	if err != nil {
		log.Error(err.Error())
		return nil, err
	}

	if share == nil {
		return nil, fmt.Errorf("share %s does not exist", shareName)
	}

	shareID := shareDriver.getShareID(share)

	err = d.createAccessIfNotExist(shareID, accessTo, shareProto, accessLevel, shareDriver)
	if err != nil {
		msg := fmt.Sprintf("allow access %s to %s failed %v", accessTo, shareName, err)
		log.Error(msg)
		return nil, errors.New(msg)
	}

	shareAccess := &model.FileShareAclSpec{
		BaseModel: &model.BaseModel{
			Id: opt.Id,
		},
		AccessTo: accessTo,
		Metadata: map[string]string{FileShareName: shareName},
	}

	return shareAccess, nil
}

func (d *Driver) createAccessIfNotExist(shareID, accessTo, shareProto, accessLevel string, shareDriver Protocol) error {
	// Check if access already exists
	accessID, err := d.getAccessFromShare(shareID, accessTo, shareProto)
	if err != nil {
		return err
	}

	if accessID != "" {
		log.Infof("fileshare access %s already exists", accessID)
		return nil
	}

	if _, err := shareDriver.allowAccess(shareID, accessTo, accessLevel); err != nil {
		return err
	}

	log.Infof("create fileshare access successfully")

	return nil
}

func (d *Driver) DeleteFileShareAcl(opt *pb.DeleteFileShareAclOpts) error {
	shareName, shareProto, accessTo, err := d.DeleteFileShareAclParamCheck(opt)
	if err != nil {
		log.Error(err.Error())
		return err
	}

	accessTo = "*"

	shareDriver := NewProtocol(shareProto, d.Client)

	share, err := shareDriver.getShare(shareName)
	if err != nil {
		log.Error(err.Error())
		return err
	}

	if share == nil {
		msg := fmt.Sprintf("share %s does not exist", shareName)
		log.Error(msg)
		return errors.New(msg)
	}

	shareID := shareDriver.getShareID(share)

	accessID, err := d.getAccessFromShare(shareID, accessTo, shareProto)
	if err != nil {
		msg := fmt.Sprintf("get access from share failed: %v", err)
		log.Error(msg)
		return errors.New(msg)
	}

	if accessID == "" {
		msg := fmt.Sprintf("can not get access id from share %s", shareName)
		log.Error(msg)
		return errors.New(msg)
	}

	if err := d.removeAccessFromShare(accessID, shareProto); err != nil {
		msg := fmt.Sprintf("remove access from share failed: %v", err)
		log.Error(msg)
		return errors.New(msg)
	}

	return nil
}

func (d *Driver) DeleteFileShareAclParamCheck(opt *pb.DeleteFileShareAclOpts) (string, string, string, error) {
	meta := opt.GetMetadata()
	if meta == nil || (meta != nil && meta[FileShareName] == "") {
		return "", "", "", errors.New("fileshare name cannot be empty when deleting file share access client")
	}

	fsName := meta[FileShareName]

	shareProto, err := d.GetProtoFromProfile(opt.Profile)
	if err != nil {
		return "", "", "", err
	}

	if !checkProtocol(shareProto) {
		return "", "", "", fmt.Errorf("%s protocol is not supported, support is NFS and CIFS", shareProto)
	}

	accessType := opt.Type
	if !checkAccessType(accessType) {
		return "", "", "", fmt.Errorf("only access type %s and %s are supported", AccessTypeUser, AccessTypeIp)
	}
	if shareProto == CIFSProto && accessType != AccessTypeUser {
		return "", "", "", fmt.Errorf("only USER access type is allowed for CIFS shares")
	}

	accessTo := opt.GetAccessTo()
	if accessTo == "" {
		return "", "", "", errors.New("cannot find access client")
	}

	return fsName, shareProto, accessTo, nil
}


text:
title: Side effects of stubbing console in tests
excerpt: "Avoid stubbing console inside tests as it can have unintentional effects on the out comes."
categories:
    - Javascript
tags:
    - javascript
    - mocking
    - stub
    - sinonjs
author: gyandeeps
---

We all love stubbing objects in unit test as it makes our life easier when writing tests. You can stub objects created by your source code or objects which our environment specific like node or browser. On [ESLint](https://github.com/eslint/eslint) project, we were stubbing `console` object so that we can see a clean output for the test runs. But later on we figured out that if the test has some errors then it will not be displayed by the testing framework on the cmd because we have stubbed the console object completely.

For better understanding of stubbing please reference excellent article by [Elijah Manor](https://twitter.com/elijahmanor) - [Unit Test like a Secret Agent with Sinon.js](http://elijahmanor.com/unit-test-like-a-secret-agent-with-sinon-js/).

Lets run through some scenarios of what happens when you do mock console vs when you don't mock console. We will be using the following libraries[^1] for demonstration purposes:

1. [Mocha](https://mochajs.org/)
1. [Sinon.JS](http://sinonjs.org/)
1. [Chai asserts](http://chaijs.com/api/assert/)
1. [Proxyquire](https://github.com/thlorenz/proxyquire)

## Scenarios {#id}

#### Test pass and console is not mocked {#id}

Without mocking anything, if we run a sample test with all test passing.

```js
var assert = require("chai").assert;
var sinon = require("sinon");

describe("validation", function(){
    it("Expect it to be true", function(){
        assert.isTrue(true);
    });

    it("Expect it to be false", function(){
        assert.isFalse(false);
    });
});
```

The output will be

```sh
$ ./node_modules/.bin/mocha test.js

  validation
    √ Expect it to be true
    √ Expect it to be false

  2 passing (6ms)
```

Everything works as expected and mocha is able to easily display the output for the test.

#### Test fail and console is not mocked {#id}

Without mocking anything, if we run a sample test in which one test has failure.

```js
var assert = require("chai").assert;
var sinon = require("sinon");

describe("validation", function(){
    it("Expect it to be true", function(){
        assert.isTrue(false);
    });

    it("Expect it to be false", function(){
        assert.isFalse(false);
    });
});
```

The output will be

```sh
$ ./node_modules/.bin/mocha test.js

  validation
    1) Expect it to be true
    √ Expect it to be false

  1 passing (8ms)
  1 failing

  1) validation Expect it to be true:
     AssertionError: expected false to be true
      stack trace...
```

Everything works as expected and mocha is able to easily display the output for the test failure and the stack trace for information about the error.

#### Test fail and console is mocked {#id}

We will mock some common methods on `console` object and then the test which has some failures.

```js
var assert = require("chai").assert;
var sinon = require("sinon");

describe("validation", function(){
    beforeEach(function(){
        this.cStub1 = sinon.stub(console, "info");
        this.cStub2 = sinon.stub(console, "log");
        this.cStub3 = sinon.stub(console, "error");
        this.cStub4 = sinon.stub(console, "trace");
    });
    afterEach(function(){
        this.cStub1.restore();
        this.cStub2.restore();
        this.cStub3.restore();
        this.cStub4.restore();
    });

    it("Expect it to be true", function(){
        assert.isTrue(false);
    });

    it("Expect it to be false", function(){
        assert.isFalse(false);
    });
});
```

The output will be

```sh
$ ./node_modules/.bin/mocha test.js

  validation

  1 passing (13ms)
  1 failing

  1) validation Expect it to be true:
     AssertionError: expected false to be true
      stack trace...
```

Everything works as expected and mocha is able to easily display the output for the test failure. But if you see closely the individual test run checks didn't get printed. Now that is because your test stubbed the console object. Since this is very simple example that is why the damage is minimum but it can lead to more bigger issues.

#### Worst scenario {#id}

when you do all the mocking inside the test (inside `it`) and not inside `beforeEach`. Then if a test fails the stub never restores itself.

```js
var assert = require("chai").assert;
var sinon = require("sinon");

describe("validation", function(){
    it("Expect it to be true", function(){
        this.cStub1 = sinon.stub(console, "info");
        this.cStub2 = sinon.stub(console, "log");
        this.cStub3 = sinon.stub(console, "error");
        this.cStub4 = sinon.stub(console, "trace");

        assert.isTrue(false);

        this.cStub1.restore();
        this.cStub2.restore();
        this.cStub3.restore();
        this.cStub4.restore();
    });

    it("Expect it to be false", function(){
        assert.isFalse(false);
    });
});
```

The output will be

```sh
$ ./node_modules/.bin/mocha test.js

  validation
```

Here nothing gets displayed because `console` never got restored to its original state. If you have many tests then this can lead to potential undetected issues. Debugging is a nightmare in this situation.

## Solution {#id}

Best way to tackle such scenarios is to extract the logging logic into its own module and then stub that module inside your tests.

Create `logging.js` module[^2] to be consumed.

```js
module.exports = {
    info: function() {
        console.log.apply(console, Array.prototype.slice.call(arguments));
    },

    error: function() {
        console.error.apply(console, Array.prototype.slice.call(arguments));
    }
};
```

Consume `logging` module created above inside your `app.js` module.

```js
var log = require("./logging.js");

module.exports = {
    sayHi: function(name){
        log.info("Hi " + name);
    }
};
```

So this way when you write unit test for the `app` module you can actually stub `logging` module.

```js
var assert = require("chai").assert;
var sinon = require("sinon");
var proxyquire = require("proxyquire");

proxyquire = proxyquire.noCallThru().noPreserveCache();

describe("validation", function(){
    var log = {
        info: sinon.spy(),
        error: sinon.spy()
    };

    it("Expect it to be true", function(){
        var app = proxyquire("../lib/app", {
            "./logging": log
        });
        app.sayHi("test");
        assert.isTrue(log.info.calledOnce);
    });

    it("Expect it to be false", function(){
        assert.isFalse(false);
    });
});
```

## Conclusion {#id}

Always avoid stubbing `console` as there is always a better way to achieve what you are trying to do. Sometimes stubbing like this may lead to issue where you will not know that there are issues since they all are silently getting ignored.

##### References

[^1]: For list of libraries used please reference the top section of the article.
[^2]: Some of the code examples have been taken from [ESLint](http://eslint.org/) library.


text:
package pieql

// SelectStatement represents a statement for retrieving data.
type SelectStatement struct {
	Fields Fields
	Source string
}

// Fields represents a list of fields.
type Fields []*Field

// Field represents a column to be selected.
type Field struct {
	Name string
}


text:
<!DOCTYPE html>

Authentication Codes

The following authentication codes have been issued to client applications.

                        ID
                        Code
                        Issued to

                        id
                        client id
                        client secret
                        <button:delete href="${'/codes/delete?id=' + code.id}">revoke</button:delete>


text:
package org.apache.cassandra.stress.settings;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.math3.distribution.ExponentialDistribution;
import org.apache.commons.math3.distribution.NormalDistribution;
import org.apache.commons.math3.distribution.UniformRealDistribution;
import org.apache.commons.math3.distribution.WeibullDistribution;
import org.apache.commons.math3.random.JDKRandomGenerator;

import org.apache.cassandra.stress.generate.Distribution;
import org.apache.cassandra.stress.generate.DistributionBoundApache;
import org.apache.cassandra.stress.generate.DistributionFactory;
import org.apache.cassandra.stress.generate.DistributionFixed;
import org.apache.cassandra.stress.generate.DistributionInverted;
import org.apache.cassandra.stress.generate.DistributionOffsetApache;
import org.apache.cassandra.stress.generate.RatioDistribution;
import org.apache.cassandra.stress.generate.RatioDistributionFactory;

/**
 * For selecting a mathematical distribution
 */
public class OptionRatioDistribution extends Option
{

    private static final Pattern FULL = Pattern.compile("(.*)/([0-9]+[KMB]?)", Pattern.CASE_INSENSITIVE);

    final OptionDistribution delegate;
    private double divisor;

    private static final RatioDistribution DEFAULT = new RatioDistribution(new DistributionFixed(1), 1);

    public OptionRatioDistribution(String prefix, String defaultSpec, String description)
    {
        delegate = new OptionDistribution(prefix, defaultSpec, description);
    }

    @Override
    public boolean accept(String param)
    {
        Matcher m = FULL.matcher(param);
        if (!m.matches() || !delegate.accept(m.group(1)))
            return false;
        divisor = OptionDistribution.parseLong(m.group(2));
        return true;
    }

    public static RatioDistributionFactory get(String spec)
    {
        OptionRatioDistribution opt = new OptionRatioDistribution("", "", "");
        if (!opt.accept(spec))
            throw new IllegalArgumentException();
        return opt.get();
    }

    public RatioDistributionFactory get()
    {
        return !delegate.setByUser() ? new DefaultFactory() : new DelegateFactory(delegate.get(), divisor);
    }

    @Override
    public boolean happy()
    {
        return delegate.happy();
    }

    public String longDisplay()
    {
        return delegate.longDisplay();
    }

    @Override
    public List<String> multiLineDisplay()
    {
        return Arrays.asList(
                GroupedOptions.formatMultiLine("EXP(min..max)/divisor", "An exponential ratio distribution over the range [min..max]/divisor"),
                GroupedOptions.formatMultiLine("EXTREME(min..max,shape)/divisor", "An extreme value (Weibull) ratio distribution over the range [min..max]/divisor"),
                GroupedOptions.formatMultiLine("GAUSSIAN(min..max,stdvrng)/divisor", "A gaussian/normal ratio distribution, where mean=(min+max)/2, and stdev is ((mean-min)/stdvrng)/divisor"),
                GroupedOptions.formatMultiLine("GAUSSIAN(min..max,mean,stdev)/divisor", "A gaussian/normal ratio distribution, with explicitly defined mean and stdev"),
                GroupedOptions.formatMultiLine("UNIFORM(min..max)/divisor", "A uniform ratio distribution over the range [min, max]/divisor"),
                GroupedOptions.formatMultiLine("FIXED(val)/divisor", "A fixed ratio distribution, always returning the same value"),
                "Preceding the name with ~ will invert the distribution, e.g. ~exp(1..10)/10 will yield 0.1 least, instead of most, often",
                "Aliases: extr, gauss, normal, norm, weibull"
        );
    }

    boolean setByUser()
    {
        return delegate.setByUser();
    }

    @Override
    public String shortDisplay()
    {
        return delegate.shortDisplay();
    }

    // factories

    private static final class DefaultFactory implements RatioDistributionFactory
    {
        @Override
        public RatioDistribution get()
        {
            return DEFAULT;
        }
    }

    private static final class DelegateFactory implements RatioDistributionFactory
    {
        final DistributionFactory delegate;
        final double divisor;

        private DelegateFactory(DistributionFactory delegate, double divisor)
        {
            this.delegate = delegate;
            this.divisor = divisor;
        }

        @Override
        public RatioDistribution get()
        {
            return new RatioDistribution(delegate.get(), divisor);
        }
    }

    @Override
    public int hashCode()
    {
        return delegate.hashCode();
    }

    @Override
    public boolean equals(Object that)
    {
        return super.equals(that) && ((OptionRatioDistribution) that).delegate.equals(this.delegate);
    }

}


text:
<?php
require '../common/database.php';

session_start();

function returnFalse()
{
	$response = array(
		"success" => false
	);
	echo json_encode($response);
}

$username = $_SESSION['username'];
$userid = $_SESSION['userid'];
$game_id = $_POST['game_id'];

$conn = getConnection();
$query = "UPDATE games set master_user = $userid where id = $game_id";
$update = mysqli_query($conn, $query);
if(!$update){
    returnFalse();
    $conn->close();
    exit;
}else{
    $response = array(
        "success" => true
    );
    echo json_encode($response);
    $conn->close();
    exit;
}
?>


text:
/**
 *
 */
// package com.beenos.lib;

import java.util.UUID;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

/**
 * インストール毎にユニークなIDを返す
 *
 * @see http://bit.ly/1kDHp8G
 * @see http://bit.ly/1kDHlWA
 */
public class UIID {
	private static String uiid = null;
	private static final String PREFERENCE_KEY = "beenos.UIID";

	/**
	 *
	 */
	public synchronized static String id(Context context)
	{
		if (uiid != null) {
			return uiid;
		}

		SharedPreferences prefs = context.getSharedPreferences(PREFERENCE_KEY, Context.MODE_PRIVATE);
		uiid = prefs.getString(PREFERENCE_KEY, null);
		if (uiid == null) {
			uiid = UUID.randomUUID().toString();
			Editor editor = prefs.edit();
			editor.putString(PREFERENCE_KEY, uiid);
			editor.commit();
		}

		return uiid;
	}
}


text:
    <button class="btn btn-success" style="margin-bottom:10px" ng-show="isAllSetUp">Créer un événément</button>

    <input type="text" style="margin-bottom:10px" placeholder="Rechercher" search ng-show="(allEvents.length > 0 || allPastEvents.length > 0) && isAllSetUp">

 0">Évènements à venir

 0">

        Nom
        Début
        Fin
        J'y vais
        Peut-être
        J'y vais pas
        Commentaires

         {{ event.name }}
         {{ event.dateStart | date:'yyyy-MM-dd HH:mm' }}
         {{ event.dateEnd | date:'yyyy-MM-dd HH:mm' }}
         {{ event.nbParticipant }}
         {{ event.nbMaybe }}
         {{ event.nbNotgoing }}
         {{ event.nbComments }}

Il n'y a aucun événément à venir, créez en un :)

Customise d'abord ta page association avant de créer un event :)

 0">Évènements passés

 0 && isAllSetUp">

        Nom
        Début
        Fin
        J'y vais
        Peut-être
        J'y vais pas
        Commentaires

         {{ event.name }}
         {{ event.dateStart | date:'yyyy-MM-dd HH:mm' }}
         {{ event.dateEnd | date:'yyyy-MM-dd HH:mm' }}
         {{ event.nbParticipant }}
         {{ event.nbMaybe }}
         {{ event.nbNotgoing }}
         {{ event.nbComments }}


text:
{% extends 'templates/nhs_transaction_layout.html' %}

{% block content %}

   <link rel="stylesheet" href="/public/stylesheets/pagination.css">
   <link rel="stylesheet" id="font-awesome-css" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" type="text/css" media="screen">

Get help with health costs

1. Overview

2. Children and young people

3. Pensioners

4. Getting benefits or tax credits

5. Employed or self employed

6. Pregnant or had a baby recently

7. Long term illness

Help for people with a long term medical condition

          People with certain medical conditions may give free NHS prescriptions.

Diabetes

Where treatment is not by diet alone

Cancer and are undergoing treatment

Including treatment for the effects of cancer or the effects of cancer treatment.

Epilepsy
Which needs anti-epileptic drugs (AEDs)

A continuing physical disability

Which means you cannot go out without the help of another person

You need a continuous surgical dressing or an appliance

Like a tracheotomy or need to use a stoma

An underactive thyroid (hypothyroidism)

Which needs hormone replacement

If you have a illness that is not listed or you unsure about the name of your condition, check with your doctor, who can advice you about free prescriptions.

Help me work out if I can get help with health costs

                      Previous
                      Help for people who get benefits or tax credits

                      Next Help for people who are pregnant or had a baby in the last 12 months

{% endblock %}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>gao.zone.study</groupId>
	<artifactId>gao.zone.study</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>pom</packaging>

	<dependencies>

		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j13</artifactId>
			<version>1.0.1</version>
		</dependency>

		<!-- apache commons -->
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-io</artifactId>
			<version>1.3.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.3.2</version>
		</dependency>

		<!-- test -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
			<scope>test</scope>
		</dependency>
	</dependencies>
	<modules>
		<module>gao.zone.study.akka</module>
		<module>gao.zone.study.java8.lambdas</module>
	</modules>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>


text:
package main

import (
	"bufio"
	"errors"
	"log"
	"os"
	"strings"
	"time"

	"github.com/cilium/ebpf"
	"github.com/cilium/ebpf/link"
	"github.com/cilium/ebpf/rlimit"
)

// $BPF_CLANG and $BPF_CFLAGS are set by the Makefile.
//go:generate go run github.com/cilium/ebpf/cmd/bpf2go -cc $BPF_CLANG -cflags $BPF_CFLAGS bpf cgroup_skb.c -- -I../headers

func main() {
	// Allow the current process to lock memory for eBPF resources.
	if err := rlimit.RemoveMemlock(); err != nil {
		log.Fatal(err)
	}

	// Load pre-compiled programs and maps into the kernel.
	objs := bpfObjects{}
	if err := loadBpfObjects(&objs, nil); err != nil {
		log.Fatalf("loading objects: %v", err)
	}
	defer objs.Close()

	// Get the first-mounted cgroupv2 path.
	cgroupPath, err := detectCgroupPath()
	if err != nil {
		log.Fatal(err)
	}

	// Link the count_egress_packets program to the cgroup.
	l, err := link.AttachCgroup(link.CgroupOptions{
		Path:    cgroupPath,
		Attach:  ebpf.AttachCGroupInetEgress,
		Program: objs.CountEgressPackets,
	})
	if err != nil {
		log.Fatal(err)
	}
	defer l.Close()

	log.Println("Counting packets...")

	// Read loop reporting the total amount of times the kernel
	// function was entered, once per second.
	ticker := time.NewTicker(1 * time.Second)
	defer ticker.Stop()

	for range ticker.C {
		var value uint64
		if err := objs.PktCount.Lookup(uint32(0), &value); err != nil {
			log.Fatalf("reading map: %v", err)
		}
		log.Printf("number of packets: %d\n", value)
	}
}

// detectCgroupPath returns the first-found mount point of type cgroup2
// and stores it in the cgroupPath global variable.
func detectCgroupPath() (string, error) {
	f, err := os.Open("/proc/mounts")
	if err != nil {
		return "", err
	}
	defer f.Close()

	scanner := bufio.NewScanner(f)
	for scanner.Scan() {
		// example fields: cgroup2 /sys/fs/cgroup/unified cgroup2 rw,nosuid,nodev,noexec,relatime 0 0
		fields := strings.Split(scanner.Text(), " ")
		if len(fields) >= 3 && fields[2] == "cgroup2" {
			return fields[1], nil
		}
	}

	return "", errors.New("cgroup2 not mounted")
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Thelidium limitatum f. myriocarpoides Servít

### Remarks
null


text:
require 'nagios-herald/messages/base'
require 'mail'

module NagiosHerald
  class Message
    class Pager < Message

      attr_accessor :subject
      attr_accessor :text

      # Public: Initializes a new Message::Pager object.
      #
      # recipients - A list of recipients for this message.
      # options - The options hash from Executor.
      # FIXME: Is that ^^ necessary now with Config.config available?
      #
      # Returns a new Message::Pager object.
      def initialize(recipients, options = {})
        @replyto     = options[:replyto]
        @subject     = ""
        @text        = ""
        super(recipients, options)
      end

      # Public: Generates the text portion of the content hash.
      #
      # Returns the full text portion of the content hash.
      def curate_text
        notification_type = get_nagios_var('NAGIOS_NOTIFICATIONTYPE')
        if notification_type.eql?('ACKNOWLEDGEMENT')
          @text += self.content[:short_text][:ack_info] unless self.content[:short_text][:ack_info].empty?
        else
          [:state_info, :additional_info, :additional_details].each do |info|
            @text += self.content[:short_text][info] unless self.content[:short_text][info].empty?
          end
        end
      end

      # Public: Prints the subject and text content to the terminal.
      # Useful for debugging.
      #
      # Returns nothing.
      def print
        puts @subject
        puts @text
      end

      # Public: Sends the pager message.
      #
      # Returns nothing.
      def build_message
        @subject = self.content[:short_subject]
        curate_text

        mail = Mail.new({
          :from    => @replyto,
          :to      => @recipients,
          :subject => @subject,
          :body    => @text
        })

        if @no_send
          self.print
          return
        end

        return mail
      end

      def send
        mail = self.build_message
        mail.deliver! unless mail.nil?
      end

    end
  end
end


text:
Developer Guide
===============

This guide provides instructions (mostly as links) on how to build the repo and implement improvements. It will expand over time.

Building the repository
=======================

The CoreFX repo can be built from a regular, non-admin command prompt. The build produces multiple managed binaries that make up the CoreFX libraries and the accompanying tests. The repo can be built for the following platforms, using the provided instructions.

| Chip  | Windows | Linux | OS X |
| :---- | :-----: | :---: | :--: |
| x64   | ●| ◒| ◒ |
| x86   | ◯| ◯| ◯|
| ARM32 | ◯ | ◯| ◯ |
|       | [Instructions](windows-instructions.md) | [Instructions](linux-instructions.md) | |

The CoreFX build and test suite is a work in progress, as are the [building and testing instructions](README.md). The .NET Core team and the community are improving Linux and OS X support on a daily basis are and adding more tests for all platforms. See [CoreFX Issues](https://github.com/dotnet/corefx/issues) to find out about specific work items or report issues.


text:
<ion-view title="Friends">
  <ion-nav-buttons side="right">
    <button class="button" ng-click="logout()" ng-if=" !nodeWebkit ">

    </button>

  </ion-nav-buttons>
  <ion-content class="has-header" has-bouncing="true">
    <ion-list>

        <input type="text" placeholder="Search" search-by-key post="postFriends" reset="resetFriends" items="friends">

        Profile

      <ion-item class="item item-avatar" ng-click="gotoAccount()">

{{loginUser.userName}}

{{loginUser.message}}

      </ion-item>

Friends({{friendCount}})

    	<ion-item ng-repeat="friend in friends" class="item-remove-animate item-avatar item-icon-right" type="item-text-wrap" ng-click='gotoChat("{{friend.user_id}}")' >

{{friend.user_name}}

{{friend.message}}

        <ion-option-button class="button-assertive" ng-click='removeFriend("{{friend.user_id}}", $index)'>
          Remove
        </ion-option-button>
      </ion-item>
    </ion-list>
  </ion-content>
  <button class="button button-yellow icon ion-person-add button-add" ng-click="openUserModal()"></button>
</ion-view>


text:
package flow

import (
	"github.com/google/gopacket"
	"github.com/google/gopacket/layers"
)

// Create a layer type, should be unique and high, so it doesn't conflict,
// giving it a name and a decoder to use.
var LayerTypeInGRE = gopacket.RegisterLayerType(55555, gopacket.LayerTypeMetadata{Name: "LayerTypeInGRE", Decoder: gopacket.DecodeFunc(decodeInGRELayer)})

// Try to find if the next layer is IPv4, or IPv6. If it fails, it considers it is Ethernet.
var LayerTypeInMplsEthOrIp = gopacket.RegisterLayerType(55556, gopacket.LayerTypeMetadata{Name: "LayerTypeInMplsEthOrIp", Decoder: gopacket.DecodeFunc(decodeInMplsEthOrIpLayer)})

type InGRELayer struct {
	StrangeHeader []byte
	payload       []byte
}

func (m InGRELayer) LayerType() gopacket.LayerType {
	return LayerTypeInGRE
}

func (m InGRELayer) LayerContents() []byte {
	return m.StrangeHeader
}

func (m InGRELayer) LayerPayload() []byte {
	return m.payload
}

// Try to decode data as IP4 or IP6. If data starts by 4 or 6,
// ipPrefix is set to true to indicate it seems to be an IP header,
// and a decoding failure would be reported in error.
func ipDecoderFromRawData(data []byte, p gopacket.PacketBuilder) (ipPrefix bool, e error) {
	switch (data[0] >> 4) & 0xf {
	case 4:
		ip4 := &layers.IPv4{}
		err := ip4.DecodeFromBytes(data, p)
		p.AddLayer(ip4)

		// Only the first call to this function is kept by
		// gopacket. So, this works even if this layer is not
		// the network layer (in case of encapsulation).
		p.SetNetworkLayer(ip4)
		if err != nil {
			return true, err
		}
		return true, p.NextDecoder(ip4.NextLayerType())
	case 6:
		ip6 := &layers.IPv6{}
		err := ip6.DecodeFromBytes(data, p)
		p.AddLayer(ip6)
		p.SetNetworkLayer(ip6)
		if err != nil {
			return true, err
		}
		return true, p.NextDecoder(ip6.NextLayerType())
	default:
		return false, nil
	}
}

func decodeInGRELayer(data []byte, p gopacket.PacketBuilder) error {
	if ipPrefix, err := ipDecoderFromRawData(data, p); ipPrefix {
		return err
	} else {
		packet := gopacket.NewPacket(data, layers.LayerTypeARP, gopacket.Lazy)
		layer := packet.Layer(layers.LayerTypeARP)
		p.AddLayer(layer)
		return nil
	}
}

func decodeInMplsEthOrIpLayer(data []byte, p gopacket.PacketBuilder) error {
	if ipPrefix, err := ipDecoderFromRawData(data, p); ipPrefix && err == nil {
		return nil
	} else {
		// If IPv4 or IPv6 fails, we fallback to Ethernet
		eth := &layers.Ethernet{}
		err := eth.DecodeFromBytes(data, p)
		p.AddLayer(eth)
		if err != nil {
			return err
		}
		return p.NextDecoder(eth.NextLayerType())
	}
}

func init() {
	// By default, gopacket tries to decode IPv4 or IPv6 in the
	// MPLS next layer and fails otherwise. Instead, we also tries
	// to decode it as Ethernet.
	layers.MPLSPayloadDecoder = LayerTypeInMplsEthOrIp
}


text:
module RubySL
  module Profiler
    VERSION = "2.0.1"
  end
end


text:
namespace sf {
namespace core {
namespace context {

  class Daemon;
  typedef std::shared_ptr<Daemon> DaemonRef;

  //! Daemon specific context.
  class Daemon {
   protected:
    static DaemonRef _instance;

   public:
    static DaemonRef instance();
    static void destroy();

   protected:
    bool _exiting;
    int  exit_code;
    bool forced_exit;

    sf::core::utility::SubProcessRef manager;
    sf::core::utility::SubProcessRef spawner;

    Daemon();

   public:
    ~Daemon();

    int  exitCode();
    void exiting(int code);

    void shutdown();
    void shutdownForced();
    bool terminating();
    bool terminatingForced();

    void clearManager();
    void clearSpawner();

    void setManager(sf::core::utility::SubProcessRef manager);
    void setSpawner(sf::core::utility::SubProcessRef spawner);

    pid_t managerPid();
    pid_t spawnerPid();

    sf::core::model::EventDrainRef managerDrain();
    sf::core::model::EventDrainRef spawnerDrain();
  };

}  // namespace context
}  // namespace core
}  // namespace sf

#endif  // CORE_CONTEXT_DAEMON_H_