text:
typedef enum {
	RBSVHorizontalCursor=0,		// appears over horizontal dividers
	RBSVVerticalCursor,			// appears over vertical dividers
	RBSV2WayCursor,				// appears over two-way thumbs
	RBSVDragCursor,				// appears while dragging
	RBSVCursorTypeCount
} RBSVCursorType;

@interface RBSplitView : RBSplitSubview {
    // Subclasses normally should use setter methods instead of changing instance variables by assignment.
    // Most getter methods simply return the corresponding instance variable, so with some care, subclasses
    // could reference them directly.
	IBOutlet id delegate;		// The delegate (may be nil).
	NSString* autosaveName;		// This name is used for storing subview proportions in user defaults.
	NSColor* background;		// The color used to paint the view's background (may be nil).
	NSImage* divider;			// The image used for the divider "dimple".
	NSRect* dividers;			// A C array of NSRects, one for each divider.
	CGFloat dividerThickness;	// Actual divider width; should be an integer and at least 1.0.
	BOOL mustAdjust;			// Set internally if the subviews need to be adjusted.
	BOOL mustClearFractions;	// Set internally if fractions should be cleared before adjusting.
	BOOL isHorizontal;			// The divider's orientation; default is vertical.
	BOOL canSaveState;			// Set internally to allow saving subview state.
	BOOL isCoupled;				// If YES, take some parameters from the containing RBSplitView, if any.
	BOOL isAdjusting;			// Set internally while the subviews are being adjusted.
	BOOL isDragging;			// Set internally while in a drag loop.
	BOOL isInScrollView;		// Set internally if directly contained in an NSScrollView.
}

// These class methods get and set the cursor used for each type.
// Pass in nil to reset to the default cursor for that type.
+ (NSCursor*)cursor:(RBSVCursorType)type;
+ (void)setCursor:(RBSVCursorType)type toCursor:(NSCursor*)cursor;

// This class method clears the saved state for a given autosave name from the defaults.
+ (void)removeStateUsingName:(NSString*)name;

// This class method returns the actual key used to store autosave data in the defaults.
+ (NSString*)defaultsKeyForName:(NSString*)name isHorizontal:(BOOL)orientation;

// Sets and gets the autosaveName; this will be the key used to store the subviews' proportions
// in the user defaults. Default is @"", which doesn't save anything. Set flag to YES to set
// unique names for nested subviews. You are responsible for avoiding duplicates.
- (void)setAutosaveName:(NSString*)aString recursively:(BOOL)flag;
- (NSString*)autosaveName;

// Saves the current state of the subviews if there's a valid autosave name set. If the argument
// is YES, it's then also called recursively for nested RBSplitViews. Returns YES if successful.
- (BOOL)saveState:(BOOL)recurse;

// Restores the saved state of the subviews if there's a valid autosave name set. If the argument
// is YES, it's first called recursively for nested RBSplitViews. Returns YES if successful.
// You need to call adjustSubviews after calling this.
- (BOOL)restoreState:(BOOL)recurse;

// Returns a string encoding the current state of all direct subviews. Does not check for nesting.
- (NSString*)stringWithSavedState;

// Readjusts all direct subviews according to the encoded string parameter. The number of subviews
// must match. Returns YES if successful. Does not check for nesting.
- (BOOL)setStateFromString:(NSString*)aString;

// Returns an array with complete state information for the receiver and all subviews, taking
// nesting into account. Don't store this array in a file, as its format might change in the
// future; this is for taking a state snapshot and later restoring it with setStatesFromArray.
- (NSArray*)arrayWithStates;

// Restores the state of the receiver and all subviews. The array must have been produced by a
// previous call to arrayWithStates. Returns YES if successful. This will fail if you have
// added or removed subviews in the meantime!
// You need to call adjustSubviews after calling this.
- (BOOL)setStatesFromArray:(NSArray*)array;

// This is the designated initializer for creating RBSplitViews programmatically.
- (id)initWithFrame:(NSRect)frame;

// This convenience initializer adds any number of subviews and adjusts them proportionally.
- (id)initWithFrame:(NSRect)frame andSubviews:(NSUInteger)count;

// Sets and gets the delegate. (Delegates aren't retained.) See further down for delegate methods.
- (void)setDelegate:(id)anObject;
- (id)delegate;

// Returns a subview which has a certain identifier string, or nil if there's none
- (RBSplitSubview*)subviewWithIdentifier:(NSString*)anIdentifier;

// Returns the subview at a certain position. Returns nil if the position is invalid.
- (RBSplitSubview*)subviewAtPosition:(NSUInteger)position;

// Adds a subview at a certain position.
- (void)addSubview:(NSView*)aView atPosition:(NSUInteger)position;

// Sets and gets the divider thickness, which should be a positive integer or zero.
// Setting the divider image also resets this automatically, so you would call this
// only if you want the divider to be larger or smaller than the image. Zero means that
// the image dimensions will be used.
- (void)setDividerThickness:(CGFloat)thickness;
- (CGFloat)dividerThickness;

// Sets and gets the divider image. The default image can also be set in Interface Builder, so usually
// there's no need to call this. Passing in nil means that the default divider thickness will be zero,
// and no mouse events will be processed, so that the dividers can be moved only programmatically.
- (void)setDivider:(NSImage*)image;
- (NSImage*)divider;

// Sets and gets the view background. The default is nil, meaning no background is
// drawn and the view and its subviews are considered transparent.
- (void)setBackground:(NSColor*)color;
- (NSColor*)background;

// Sets and gets the orientation. This uses the same convention as NSSplitView: vertical means the
// dividers are vertical, but the subviews are in a horizontal row. Sort of counter-intuitive, yes.
- (void)setVertical:(BOOL)flag;
- (BOOL)isVertical;
- (void)setHorizontal:(BOOL)flag;
- (BOOL)isHorizontal;

// Call this to force adjusting the subviews before display. Called automatically if anything
// relevant is changed.
- (void)setMustAdjust;

// Returns YES if there's a pending adjustment.
- (BOOL)mustAdjust;
- (BOOL)isAdjusting;

// Returns YES if we're in a dragging loop.
- (BOOL)isDragging;

// Returns YES if the view is directly contained in an NSScrollView.
- (BOOL)isInScrollView;

// Call this to recalculate all subview dimensions. Normally this is done automatically whenever
// something relevant is changed, so you rarely will need to call this explicitly.
- (void)adjustSubviews;

// This method should be called only from within the splitView:wasResizedFrom:to: delegate method
// to keep some specific subview the same size.
- (void)adjustSubviewsExcepting:(RBSplitSubview*)excepting;

// This method draws dividers. You should never call it directly but you can override it when
// subclassing, if you need custom dividers.
- (void)drawDivider:(NSImage*)anImage inRect:(NSRect)rect betweenView:(RBSplitSubview*)leading andView:(RBSplitSubview*)trailing;

@end

// The following methods are optionally implemented by the delegate.

@protocol RBSplitViewDelegate<NSObject>
@optional

// The delegate can override a subview's ability to collapse by implementing this method.
// Return YES to allow collapsing. If this is implemented, the subviews' built-in
// 'collapsed' flags are ignored.
- (BOOL)splitView:(RBSplitView*)sender canCollapse:(RBSplitSubview*)subview;

// The delegate can alter the divider's appearance by implementing this method.
// Before calling this, the divider is filled with the background, and afterwards
// the divider image is drawn into the returned rect. If imageRect is empty, no
// divider image will be drawn, because there are nested RBSplitViews. Return
// NSZeroRect to suppress the divider image. Return imageRect to use the default
// location for the image, or change its origin to place the image elsewhere.
// You could also draw the divider yourself at this point and return NSZeroRect.
- (NSRect)splitView:(RBSplitView*)sender willDrawDividerInRect:(NSRect)dividerRect betweenView:(RBSplitSubview*)leading andView:(RBSplitSubview*)trailing withProposedRect:(NSRect)imageRect;

// These methods are called after a subview is completely collapsed or expanded. adjustSubviews may or may not
// have been called, however.
- (void)splitView:(RBSplitView*)sender didCollapse:(RBSplitSubview*)subview;
- (void)splitView:(RBSplitView*)sender didExpand:(RBSplitSubview*)subview;

// These methods are called just before and after adjusting subviews.
- (void)willAdjustSubviews:(RBSplitView*)sender;
- (void)didAdjustSubviews:(RBSplitView*)sender;

// This method will be called after a RBSplitView is resized with setFrameSize: but before
// adjustSubviews is called on it.
- (void)splitView:(RBSplitView*)sender wasResizedFrom:(CGFloat)oldDimension to:(CGFloat)newDimension;

// This method will be called when a divider is double-clicked and both leading and trailing
// subviews can be collapsed. Return either of the parameters to collapse that subview, or nil
// to collapse neither. If not implemented, the smaller subview will be collapsed.
- (RBSplitSubview*)splitView:(RBSplitView*)sender collapseLeading:(RBSplitSubview*)leading orTrailing:(RBSplitSubview*)trailing;

// This method will be called when a cursor rect is being set (inside resetCursorRects). The
// proposed rect is passed in. Return the actual rect, or NSZeroRect to suppress cursor setting
// for this divider. This won't be called for two-axis thumbs, however. The rects are in
// sender's local coordinates.
- (NSRect)splitView:(RBSplitView*)sender cursorRect:(NSRect)rect forDivider:(NSUInteger)divider;

// This method will be called whenever a mouse-down event is received in a divider. Return YES to have
// the event handled by the split view, NO if you wish to ignore it or handle it in the delegate.
- (BOOL)splitView:(RBSplitView*)sender shouldHandleEvent:(NSEvent*)theEvent inDivider:(NSUInteger)divider betweenView:(RBSplitSubview*)leading andView:(RBSplitSubview*)trailing;

// This method will be called just before a subview will be collapsed or expanded with animation.
// Return the approximate time the animation should take, or 0.0 to disallow animation.
// If not implemented, it will use the default of 0.2 seconds per 150 pixels.
- (NSTimeInterval)splitView:(RBSplitView*)sender willAnimateSubview:(RBSplitSubview*)subview withDimension:(CGFloat)dimension;

// This method will be called whenever a subview's frame is changed, usually from inside adjustSubviews' final loop.
// You'd normally use this to move some auxiliary view to keep it aligned with the subview.
- (void)splitView:(RBSplitView*)sender changedFrameOfSubview:(RBSplitSubview*)subview from:(NSRect)fromRect to:(NSRect)toRect;

// This method is called whenever the event handlers want to check if some point within the RBSplitSubview
// should act as an alternate drag view. Usually, the delegate will check the point (which is in sender's
// local coordinates) against the frame of one or several auxiliary views, and return a valid divider number.
// Returning NSNotFound means the point is not valid.
- (NSUInteger)splitView:(RBSplitView*)sender dividerForPoint:(NSPoint)point inSubview:(RBSplitSubview*)subview;

// This method is called continuously while a divider is dragged, just before the leading subview is resized.
// Return NO to resize the trailing view by the same amount, YES to resize the containing window by the same amount.
- (BOOL)splitView:(RBSplitView*)sender shouldResizeWindowForDivider:(NSUInteger)divider betweenView:(RBSplitSubview*)leading andView:(RBSplitSubview*)trailing willGrow:(BOOL)grow;

// This method is called by each subview's drawRect: method, just after filling it with the background color but
// before the contained subviews are drawn. Usually you would use this to draw a frame inside the subview.
- (void)splitView:(RBSplitView*)sender willDrawSubview:(RBSplitSubview*)subview inRect:(NSRect)rect;

@end


text:
# MongoDB Interaction

One of the facilities that Grassroots system provides is an API to access a [MongoDB](https://www.mongodb.org/) instance through JSON-based messages. All of the MongoDB messages are accessed using a **mongodb** key.

## Inserting data

The client would send a child **insert** key with a list of child key-value pairs. These can be in a single object if you just want to insert a single document or as an array if you want to insert multiple documents. For example, both of the following requests are valid:

~~~{.json}
{
	"mongodb": {
		"collection": "bands",
		"insert": [{
			"band": "spinal tap",
			"volume": 11,
			"recorded in": "dobly"
		}, {
			"band": "bad news",
			"label": "frilly pink"
		}]
	}
}
~~~

~~~{.json}
{
	"mongodb": {
		"collection": "bands",
		"insert": {
			"band": "spinal tap",
			"volume": 11,
			"recorded in": "dobly"
		}
	}
}
~~~

The response from the Server will be a list of **success** values along with the document ids in the same order as they were specified in the incoming request

~~~{.json}
{
	"mongodb": {
		"response": [{
			"success": true,
			"id": "123456789012345678901234"
		}, {
			"success": false
		}]
	}
}
~~~

## Deleting documents

To delete documents from a collection, a Client would send a list of the queries that would specify which documents to remove.

~~~{.json}
{
	"mongodb": {
		"collection": "bands",
		"delete": [{
			"id": "123456789012345678901234"
		}, {
			"id": "1112223334445556667778889"
		}, {
			"crop": "wheat"
		}]
	}
}
~~~

## Updating documents

Documents that were previously added can be subsequently updated.

redpajama_set_name: RedPajamaGithub


text:
/**
 * Check if a statement has an block (empty or otherwise).
 *
 * @param {Rule|AtRule} statement - postcss rule or at-rule node
 * @return {boolean} True if `statement` has a block (empty or otherwise)
 */
export default function (statement) {
  return (
    statement.nodes !== undefined
  )
}


text:
"""
``graph_tool.draw`` - Graph drawing and layout
----------------------------------------------

Summary
+++++++

Layout algorithms
=================

.. autosummary::
   :nosignatures:

   sfdp_layout
   fruchterman_reingold_layout
   arf_layout
   radial_tree_layout
   random_layout
   get_hierarchy_control_points

Graph drawing
=============

.. autosummary::
   :nosignatures:

   graph_draw
   draw_hierarchy
   graphviz_draw
   prop_to_size

Low-level graph drawing
^^^^^^^^^^^^^^^^^^^^^^^

.. autosummary::
   :nosignatures:

   cairo_draw
   interactive_window
   GraphWidget
   GraphWindow

Contents
++++++++
"""

from __future__ import division, absolute_import, print_function

from .. import GraphView, _check_prop_vector, group_vector_property, \
     ungroup_vector_property, infect_vertex_property, _prop, _get_rng
from .. topology import max_cardinality_matching, max_independent_vertex_set, \
    label_components, pseudo_diameter, shortest_distance
from .. stats import label_parallel_edges
from .. generation import predecessor_tree
import numpy.random
from numpy import sqrt
import sys

from .. dl_import import dl_import
dl_import("from . import libgraph_tool_layout")

__all__ = ["graph_draw", "graphviz_draw", "fruchterman_reingold_layout",
           "arf_layout", "sfdp_layout", "random_layout", "radial_tree_layout",
           "cairo_draw", "prop_to_size", "get_hierarchy_control_points",
           "default_cm"]

def random_layout(g, shape=None, pos=None, dim=2):
    r"""Performs a random layout of the graph.

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph to be used.
    shape : tuple or list (optional, default: ``None``)
        Rectangular shape of the bounding area. The size of this parameter must
        match `dim`, and each element can be either a pair specifying a range,
        or a single value specifying a range starting from zero. If None is
        passed, a square of linear size :math:`\sqrt{N}` is used.
    pos : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
        Vector vertex property maps where the coordinates should be stored.
    dim : int (optional, default: ``2``)
        Number of coordinates per vertex.

    Returns
    -------
    pos : :class:`~graph_tool.PropertyMap`
        A vector-valued vertex property map with the coordinates of the
        vertices.

    Notes
    -----
    This algorithm has complexity :math:`O(V)`.

    Examples
    --------
    .. testcode::
       :hide:

       np.random.seed(42)
       gt.seed_rng(42)

    >>> g = gt.random_graph(100, lambda: (3, 3))
    >>> shape = [[50, 100], [1, 2], 4]
    >>> pos = gt.random_layout(g, shape=shape, dim=3)
    >>> pos[g.vertex(0)].a
    array([ 68.72700594,   1.03142919,   2.56812658])

    """

    if pos == None:
        pos = g.new_vertex_property("vector<double>")
    _check_prop_vector(pos, name="pos")

    pos = ungroup_vector_property(pos, list(range(0, dim)))

    if shape == None:
        shape = [sqrt(g.num_vertices())] * dim

    for i in range(dim):
        if hasattr(shape[i], "__len__"):
            if len(shape[i]) != 2:
                raise ValueError("The elements of 'shape' must have size 2.")
            r = [min(shape[i]), max(shape[i])]
        else:
            r = [min(shape[i], 0), max(shape[i], 0)]
        d = r[1] - r[0]

        # deal with filtering
        p = pos[i].ma
        p[:] = numpy.random.random(len(p)) * d + r[0]

    pos = group_vector_property(pos)
    return pos

def fruchterman_reingold_layout(g, weight=None, a=None, r=1., scale=None,
                                circular=False, grid=True, t_range=None,
                                n_iter=100, pos=None):
    r"""Calculate the Fruchterman-Reingold spring-block layout of the graph.

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph to be used.
    weight : :class:`PropertyMap` (optional, default: ``None``)
        An edge property map with the respective weights.
    a : float (optional, default: :math:`V`)
        Attracting force between adjacent vertices.
    r : float (optional, default: 1.0)
        Repulsive force between vertices.
    scale : float (optional, default: :math:`\sqrt{V}`)
        Total scale of the layout (either square side or radius).
    circular : bool (optional, default: ``False``)
        If ``True``, the layout will have a circular shape. Otherwise the shape
        will be a square.
    grid : bool (optional, default: ``True``)
        If ``True``, the repulsive forces will only act on vertices which are on
        the same site on a grid. Otherwise they will act on all vertex pairs.
    t_range : tuple of floats (optional, default: ``(scale / 10, scale / 1000)``)
        Temperature range used in annealing. The temperature limits the
        displacement at each iteration.
    n_iter : int (optional, default: ``100``)
        Total number of iterations.
    pos : :class:`PropertyMap` (optional, default: ``None``)
        Vector vertex property maps where the coordinates should be stored. If
        provided, this will also be used as the initial position of the
        vertices.

    Returns
    -------
    pos : :class:`~graph_tool.PropertyMap`
        A vector-valued vertex property map with the coordinates of the
        vertices.

    Notes
    -----
    This algorithm is defined in [fruchterman-reingold]_, and has
    complexity :math:`O(\text{n-iter}\times V^2)` if `grid=False` or
    :math:`O(\text{n-iter}\times (V + E))` otherwise.

    Examples
    --------
    .. testcode::
       :hide:

       np.random.seed(42)
       gt.seed_rng(42)

    >>> g = gt.price_network(300)
    >>> pos = gt.fruchterman_reingold_layout(g, n_iter=1000)
    >>> gt.graph_draw(g, pos=pos, output="graph-draw-fr.pdf")
    <...>

    .. testcode::
       :hide:

       gt.graph_draw(g, pos=pos, output="graph-draw-fr.png")

    .. figure:: graph-draw-fr.*
        :align: center

        Fruchterman-Reingold layout of a Price network.

    References
    ----------
    .. [fruchterman-reingold] Fruchterman, Thomas M. J.; Reingold, Edward M.
       "Graph Drawing by Force-Directed Placement". Software - Practice & Experience
       (Wiley) 21 (11): 1129-1164. (1991) :doi:`10.1002/spe.4380211102`
    """

    if pos == None:
        pos = random_layout(g, dim=2)
    _check_prop_vector(pos, name="pos", floating=True)

    if a is None:
        a = float(g.num_vertices())

    if scale is None:
        scale = sqrt(g.num_vertices())

    if t_range is None:
        t_range = (scale / 10, scale / 1000)

    ug = GraphView(g, directed=False)
    libgraph_tool_layout.fruchterman_reingold_layout(ug._Graph__graph,
                                                     _prop("v", g, pos),
                                                     _prop("e", g, weight),
                                                     a, r, not circular, scale,
                                                     grid, t_range[0],
                                                     t_range[1], n_iter)
    return pos

def arf_layout(g, weight=None, d=0.5, a=10, dt=0.001, epsilon=1e-6,
               max_iter=1000, pos=None, dim=2):
    r"""Calculate the ARF spring-block layout of the graph.

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph to be used.
    weight : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
        An edge property map with the respective weights.
    d : float (optional, default: ``0.5``)
        Opposing force between vertices.
    a : float (optional, default: ``10``)
        Attracting force between adjacent vertices.
    dt : float (optional, default: ``0.001``)
        Iteration step size.
    epsilon : float (optional, default: ``1e-6``)
        Convergence criterion.
    max_iter : int (optional, default: ``1000``)
        Maximum number of iterations. If this value is ``0``, it runs until
        convergence.
    pos : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
        Vector vertex property maps where the coordinates should be stored.
    dim : int (optional, default: ``2``)
        Number of coordinates per vertex.

    Returns
    -------
    pos : :class:`~graph_tool.PropertyMap`
        A vector-valued vertex property map with the coordinates of the
        vertices.

    Notes
    -----
    This algorithm is defined in [geipel-self-organization-2007]_, and has
    complexity :math:`O(V^2)`.

    Examples
    --------
    .. testcode::
       :hide:

       np.random.seed(42)
       gt.seed_rng(42)

    >>> g = gt.price_network(300)
    >>> pos = gt.arf_layout(g, max_iter=0)
    >>> gt.graph_draw(g, pos=pos, output="graph-draw-arf.pdf")
    <...>

    .. testcode::
       :hide:

       gt.graph_draw(g, pos=pos, output="graph-draw-arf.png")

    .. figure:: graph-draw-arf.*
        :align: center

        ARF layout of a Price network.

    References
    ----------
    .. [geipel-self-organization-2007] Markus M. Geipel, "Self-Organization
       applied to Dynamic Network Layout", International Journal of Modern
       Physics C vol. 18, no. 10 (2007), pp. 1537-1549,
       :doi:`10.1142/S0129183107011558`, :arxiv:`0704.1748v5`
    .. _arf: http://www.sg.ethz.ch/research/graphlayout
    """

    if pos is None:
        pos = random_layout(g, dim=dim)
    _check_prop_vector(pos, name="pos", floating=True)

    ug = GraphView(g, directed=False)
    libgraph_tool_layout.arf_layout(ug._Graph__graph, _prop("v", g, pos),
                                    _prop("e", g, weight), d, a, dt, max_iter,
                                    epsilon, dim)
    return pos

def _coarse_graph(g, vweight, eweight, mivs=False, groups=None):
    if groups is None:
        if mivs:
            mivs = max_independent_vertex_set(g, high_deg=True)
            u = GraphView(g, vfilt=mivs, directed=False)
            c = label_components(u)[0]
            c.fa += 1
            u = GraphView(g, directed=False)
            infect_vertex_property(u, c,
                                   list(range(1, c.fa.max() + 1)))
            c = g.own_property(c)
        else:
            mivs = None
            m = max_cardinality_matching(GraphView(g, directed=False),
                                         heuristic=True, weight=eweight,
                                         minimize=False)
            u = GraphView(g, efilt=m, directed=False)
            c = label_components(u)[0]
            c = g.own_property(c)
            u = GraphView(g, directed=False)
    else:
        mivs = None
        c = groups
    cg, cc, vcount, ecount = condensation_graph(g, c, vweight, eweight)[:4]
    return cg, cc, vcount, ecount, c, mivs

def _propagate_pos(g, cg, c, cc, cpos, delta, mivs):
    pos = g.new_vertex_property(cpos.value_type())

    if mivs is not None:
        g = GraphView(g, vfilt=mivs)
    libgraph_tool_layout.propagate_pos(g._Graph__graph,
                                       cg._Graph__graph,
                                       _prop("v", g, c),
                                       _prop("v", cg, cc),
                                       _prop("v", g, pos),
                                       _prop("v", cg, cpos),
                                       delta if mivs is None else 0,
                                       _get_rng())

    if mivs is not None:
        g = g.base
        u = GraphView(g, directed=False)
        try:
            libgraph_tool_layout.propagate_pos_mivs(u._Graph__graph,
                                                    _prop("v", u, mivs),
                                                    _prop("v", u, pos),
                                                    delta, _get_rng())
        except ValueError:
            graph_draw(u, mivs, vertex_fillcolor=mivs)
    return pos

def _avg_edge_distance(g, pos):
    libgraph_tool_layout.sanitize_pos(g._Graph__graph, _prop("v", g, pos))
    ad = libgraph_tool_layout.avg_dist(g._Graph__graph, _prop("v", g, pos))
    if numpy.isnan(ad) or ad == 0:
        ad = 1.
    return ad

def coarse_graphs(g, method="hybrid", mivs_thres=0.9, ec_thres=0.75,
                  weighted_coarse=False, eweight=None, vweight=None,
                  groups=None, verbose=False):
    cg = [[g, None, None, None, None, None]]
    if weighted_coarse:
        cg[-1][2], cg[-1][3] = vweight, eweight
    mivs = not (method in ["hybrid", "ec"])
    while True:
        u = _coarse_graph(cg[-1][0], cg[-1][2], cg[-1][3], mivs, groups)
        groups = None
        thres = mivs_thres if mivs else ec_thres
        if u[0].num_vertices() >= thres * cg[-1][0].num_vertices():
            if method == "hybrid" and not mivs:
                mivs = True
            else:
                break
        if u[0].num_vertices() <= 2:
            break
        cg.append(u)
        if verbose:
            print("Coarse level (%s):" % ("MIVS" if mivs else "EC"), end=' ')
            print(len(cg), " num vertices:", end=' ')
            print(u[0].num_vertices())
    cg.reverse()
    Ks = []
    pos = random_layout(cg[0][0], dim=2)
    for i in range(len(cg)):
        if i == 0:
            u = cg[i][0]
            K = _avg_edge_distance(u, pos)
            if K == 0:
                K = 1.
            Ks.append(K)
            continue
        if weighted_coarse:
            gamma = 1.
        else:
            #u = cg[i - 1][0]
            #w = cg[i][0]
            #du = pseudo_diameter(u)[0]
            #dw = pseudo_diameter(w)[0]
            #gamma = du / float(max(dw, du))
            gamma = 0.75
        Ks.append(Ks[-1] * gamma)

    for i in range(len(cg)):
        u, cc, vcount, ecount, c, mivs = cg[i]
        yield u, pos, Ks[i], vcount, ecount

        if verbose:
            print("avg edge distance:", _avg_edge_distance(u, pos))

        if i < len(cg) - 1:
            if verbose:
                print("propagating...", end=' ')
                print(mivs.a.sum() if mivs is not None else "")
            pos = _propagate_pos(cg[i + 1][0], u, c, cc, pos,
                                 Ks[i] / 1000., mivs)

def coarse_graph_stack(g, c, coarse_stack, eweight=None, vweight=None,
                       weighted_coarse=True, verbose=False):
    cg = [[g, c, None, None]]
    if weighted_coarse:
        cg[-1][2], cg[-1][3] = vweight, eweight
    for u in coarse_stack:
        c = u.vp["b"]
        vcount = u.vp["count"]
        ecount = u.ep["count"]
        cg.append((u, c, vcount, ecount))
        if verbose:
            print("Coarse level:", end=' ')
            print(len(cg), " num vertices:", end=' ')
            print(u.num_vertices())
    cg.reverse()
    Ks = []
    pos = random_layout(cg[0][0], dim=2)
    for i in range(len(cg)):
        if i == 0:
            u = cg[i][0]
            K = _avg_edge_distance(u, pos)
            if K == 0:
                K = 1.
            Ks.append(K)
            continue
        if weighted_coarse:
            gamma = 1.
        else:
            #u = cg[i - 1][0]
            #w = cg[i][0]
            #du = pseudo_diameter(u)[0]
            #dw = pseudo_diameter(w)[0]
            #gamma = du / float(max(dw, du))
            gamma = 0.75
        Ks.append(Ks[-1] * gamma)

    for i in range(len(cg)):
        u, c, vcount, ecount = cg[i]
        yield u, pos, Ks[i], vcount, ecount

        if verbose:
            print("avg edge distance:", _avg_edge_distance(u, pos))

        if i < len(cg) - 1:
            if verbose:
                print("propagating...")
            pos = _propagate_pos(cg[i + 1][0], u, c, u.vertex_index.copy("int"),
                                 pos, Ks[i] / 1000., None)

def sfdp_layout(g, vweight=None, eweight=None, pin=None, groups=None, C=0.2,
                K=None, p=2., theta=0.6, max_level=11, gamma=1., mu=0., mu_p=1.,
                init_step=None, cooling_step=0.95, adaptive_cooling=True,
                epsilon=1e-2, max_iter=0, pos=None, multilevel=None,
                coarse_method="hybrid", mivs_thres=0.9, ec_thres=0.75,
                coarse_stack=None, weighted_coarse=False, verbose=False):
    r"""Obtain the SFDP spring-block layout of the graph.

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph to be used.
    vweight : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
        A vertex property map with the respective weights.
    eweight : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
        An edge property map with the respective weights.
    pin : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
        A vertex property map with boolean values, which, if given,
        specify the vertices which will not have their positions modified.
    groups : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
        A vertex property map with group assignments. Vertices belonging to the
        same group will be put close together.
    C : float (optional, default: ``0.2``)
        Relative strength of repulsive forces.
    K : float (optional, default: ``None``)
        Optimal edge length. If not provided, it will be taken to be the average
        edge distance in the initial layout.
    p : float (optional, default: ``2``)
        Repulsive force exponent.
    theta : float (optional, default: ``0.6``)
        Quadtree opening parameter, a.k.a. Barnes-Hut opening criterion.
    max_level : int (optional, default: ``11``)
        Maximum quadtree level.
    gamma : float (optional, default: ``1.0``)
        Strength of the attractive force between connected components, or group
        assignments.
    mu : float (optional, default: ``0.0``)
        Strength of the attractive force between vertices of the same connected
        component, or group assignment.
    mu_p : float (optional, default: ``1.0``)
        Scaling exponent of the attractive force between vertices of the same
        connected component, or group assignment.
    init_step : float (optional, default: ``None``)
        Initial update step. If not provided, it will be chosen automatically.
    cooling_step : float (optional, default: ``0.95``)
        Cooling update step.
    adaptive_cooling : bool (optional, default: ``True``)
        Use an adaptive cooling scheme.
    epsilon : float (optional, default: ``0.01``)
        Relative convergence criterion.
    max_iter : int (optional, default: ``0``)
        Maximum number of iterations. If this value is ``0``, it runs until
        convergence.
    pos : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
        Initial vertex layout. If not provided, it will be randomly chosen.
    multilevel : bool (optional, default: ``None``)
        Use a multilevel layout algorithm. If ``None`` is given, it will be
        activated based on the size of the graph.
    coarse_method : str (optional, default: ``"hybrid"``)
        Coarsening method used if ``multilevel == True``. Allowed methods are
        ``"hybrid"``, ``"mivs"`` and ``"ec"``.
    mivs_thres : float (optional, default: ``0.9``)
        If the relative size of the MIVS coarse graph is above this value, the
        coarsening stops.
    ec_thres : float (optional, default: ``0.75``)
        If the relative size of the EC coarse graph is above this value, the
        coarsening stops.
    weighted_coarse : bool (optional, default: ``False``)
        Use weighted coarse graphs.
    verbose : bool (optional, default: ``False``)
        Provide verbose information.

    Returns
    -------
    pos : :class:`~graph_tool.PropertyMap`
        A vector-valued vertex property map with the coordinates of the
        vertices.

    Notes
    -----
    This algorithm is defined in [hu-multilevel-2005]_, and has
    complexity :math:`O(V\log V)`.

    Examples
    --------
    .. testcode::
       :hide:

       np.random.seed(42)
       gt.seed_rng(42)

    >>> g = gt.price_network(3000)
    >>> pos = gt.sfdp_layout(g)
    >>> gt.graph_draw(g, pos=pos, output="graph-draw-sfdp.pdf")
    <...>

    .. testcode::
       :hide:

       gt.graph_draw(g, pos=pos, output="graph-draw-sfdp.png")

    .. figure:: graph-draw-sfdp.*
        :align: center

        SFDP layout of a Price network.

    References
    ----------
    .. [hu-multilevel-2005] Yifan Hu, "Efficient and High Quality Force-Directed
       Graph", Mathematica Journal, vol. 10, Issue 1, pp. 37-71, (2005)
       http://www.mathematica-journal.com/issue/v10i1/graph_draw.html
    """

    if pos is None:
        pos = random_layout(g, dim=2)
    _check_prop_vector(pos, name="pos", floating=True)

    g = GraphView(g, directed=False)

    if pin is not None:
        if pin.value_type() != "bool":
            raise ValueError("'pin' property must be of type 'bool'.")
    else:
        pin = g.new_vertex_property("bool")

    if K is None:
        K = _avg_edge_distance(g, pos)

    if init_step is None:
        init_step = 2 * max(_avg_edge_distance(g, pos), K)

    if multilevel is None:
        multilevel = g.num_vertices() > 1000

    if multilevel:
        if eweight is not None or vweight is not None:
            weighted_coarse = True
        if coarse_stack is None:
            cgs = coarse_graphs(g, method=coarse_method,
                                mivs_thres=mivs_thres,
                                ec_thres=ec_thres,
                                weighted_coarse=weighted_coarse,
                                eweight=eweight,
                                vweight=vweight,
                                groups=groups,
                                verbose=verbose)
        else:
            cgs = coarse_graph_stack(g, coarse_stack[0], coarse_stack[1],
                                     eweight=eweight, vweight=vweight,
                                     verbose=verbose)
        for count, (u, pos, K, vcount, ecount) in enumerate(cgs):
            if verbose:
                print("Positioning level:", count, u.num_vertices(), end=' ')
                print("with K =", K, "...")
                count += 1
            #graph_draw(u, pos)
            pos = sfdp_layout(u, pos=pos,
                              vweight=vcount if weighted_coarse else None,
                              eweight=ecount if weighted_coarse else None,
                              groups=None if u.num_vertices() < g.num_vertices() else groups,
                              C=C, K=K, p=p,
                              theta=theta, gamma=gamma, mu=mu, mu_p=mu_p,
                              epsilon=epsilon,
                              max_iter=max_iter,
                              cooling_step=cooling_step,
                              adaptive_cooling=False,
                              # init_step=max(2 * K,
                              #               _avg_edge_distance(u, pos)),
                              multilevel=False,
                              verbose=False)
            #graph_draw(u, pos)
        return pos

    if g.num_vertices() <= 1:
        return pos
    if g.num_vertices() == 2:
        vs = [g.vertex(0, False), g.vertex(1, False)]
        pos[vs[0]] = [0, 0]
        pos[vs[1]] = [1, 1]
        return pos
    if g.num_vertices() <= 50:
        max_level = 0
    if groups is None:
        groups = label_components(g)[0]
    elif groups.value_type() != "int32_t":
        raise ValueError("'groups' property must be of type 'int32_t'.")
    libgraph_tool_layout.sanitize_pos(g._Graph__graph, _prop("v", g, pos))
    libgraph_tool_layout.sfdp_layout(g._Graph__graph, _prop("v", g, pos),
                                     _prop("v", g, vweight),
                                     _prop("e", g, eweight),
                                     _prop("v", g, pin),
                                     (C, K, p, gamma, mu, mu_p, _prop("v", g, groups)),
                                     theta, init_step, cooling_step, max_level,
                                     epsilon, max_iter, not adaptive_cooling,
                                     verbose, _get_rng())
    return pos

def radial_tree_layout(g, root, rel_order=None, weighted=False, r=1.):
    r"""Computes a radial layout of the graph according to the minimum spanning
    tree centered at the ``root`` vertex.

    Parameters
    ----------
    g : :class:`~graph_tool.Graph`
        Graph to be used.
    root : :class:`~graph_tool.Vertex` or ``int``
        The root of the radial tree.
    rel_order : :class:`~graph_tool.PropertyMap` (optional, default: ``None``)
        Relative order of the nodes at each respective branch.
    weighted : ``bool`` (optional, default: ``False``)
        If true, the angle between the child branches will be computed according
        to weight of the entire sub-branches.
    r : ``float`` (optional, default: ``1.``)
        Layer spacing.

    Returns
    -------
    pos : :class:`~graph_tool.PropertyMap`
        A vector-valued vertex property map with the coordinates of the
        vertices.

    Notes
    -----
    This algorithm has complexity :math:`O(V + E)`.

    Examples
    --------
    .. testcode::
       :hide:

       np.random.seed(42)
       gt.seed_rng(42)

    >>> g = gt.price_network(1000)
    >>> pos = gt.radial_tree_layout(g, g.vertex(0))
    >>> gt.graph_draw(g, pos=pos, output="graph-draw-radial.pdf")
    <...>

    .. testcode::
       :hide:

       gt.graph_draw(g, pos=pos, output="graph-draw-radial.png")

    .. figure:: graph-draw-radial.*
        :align: center

        Radial tree layout of a Price network.

    """

    levels, pred_map = shortest_distance(GraphView(g, directed=False), root,
                                         pred_map=True)
    t = predecessor_tree(g, pred_map)
    pos = t.new_vertex_property("vector<double>")
    levels = t.own_property(levels)
    if rel_order is None:
        rel_order = g.vertex_index.copy("int")

    libgraph_tool_layout.get_radial(t._Graph__graph,
                                    _prop("v", g, pos),
                                    _prop("v", g, levels),
                                    _prop("v", g, rel_order),
                                    int(root), weighted, r)
    return g.own_property(pos)

def prop_to_size(prop, mi=0, ma=5, log=False, power=0.5):
    r"""Convert property map values to be more useful as a vertex size, or edge
    width. The new values are taken to be

    .. math::

        y = mi + (ma - mi) \left(\frac{x_i - min(x)} {max(x) - min(x)}\right)^\text{power}

    If `log=True`, the natural logarithm of the property values is used instead.

    """
    prop = prop.copy(value_type="double")
    if log:
        vals = numpy.log(prop.fa)
    else:
        vals = prop.fa

    delta = vals.max() - vals.min()
    if delta == 0:
        delta = 1
    prop.fa = mi + (ma - mi) * ((vals - vals.min()) / delta) ** power
    return prop

try:
    from .cairo_draw import graph_draw, cairo_draw, get_hierarchy_control_points, default_cm
except ImportError:
    pass

try:
    from .cairo_draw import GraphWidget, GraphWindow, \
        interactive_window, draw_hierarchy
    __all__ += ["interactive_window", "GraphWidget", "GraphWindow", "draw_hierarchy"]
except ImportError:
    pass

try:
   from .graphviz_draw import graphviz_draw
except ImportError:
   pass

# Bottom imports to avoid circular dependency issues
from .. community import condensation_graph


text:
/* eslint-disable */

const creds = require('../../.sodo/jiracred.json');
const syncrequest = require('sync-request');
const opn = require('opn');

class Jira {
  constructor() {
    this.resources = ['backlog', 'tickets'];
    this.ops = ['add', 'remove', 'onboard', 'offboard', 'summary', 'list', 'usage'];
    this.creds = creds;
    this.authorization = Buffer.from(`${creds.username}:${creds.password}`).toString('base64');
  }

  getConfig() {
    return this.config;
  }

  canProvide(resourceName) {
    if (this.resources.includes(resourceName)) {
      return true;
    }
    return false;
  }

  credentialsExist() {
    return this.creds.username !== undefined && this.creds.password !== undefined;
  }

  // TODO fix this eslint error
  provide(resourceName, sodoRequest) { // eslint-disable-line class-methods-use-this
    const self = this;
    const args = sodoRequest.arguments;
    const uri = args.instance;
    // TODO: Implement
    const provider = {
      uri,
      description: 'A Jira based-backlog',
      projectKey: args.projectKey,
      label: args.label,
      execute: (request) => {
        if (request.command === 'showissue') {
          return provider.showissue(request);
        } else if (request.command === 'addissue') {
          return provider.addissue(request);
        }
        return provider.list();
      },
      addissue: () => {
        const path = `${uri}/secure/CreateIssue!default.jspa`;
        opn(path, { wait: false });
        return {
          success: true,
        };
      },
      showissue: () => {
        if (self.credentialsExist()) {
          const path = `${uri}/rest/api/2/issue/SODO-29`;
          const options = {
            headers: {
              'Content-Type': 'application/json',
              Authorization: `Basic ${self.authorization}`,
            },
          };

          const res = syncrequest('GET', path, options);
          if (res.statusCode >= 200 && res.statusCode < 300) {
            return {
              success: true,
              message: JSON.parse(res.getBody()),
              info: 'Credentials were available',
            };
          }

          return {
            success: false,
            message: {},
            info: 'Credentials were available',
          };
        }

        return {
          success: false,
          message: {},
          info: 'Credentials were not available',
        };
      },
      list: () => {
        if (creds.username !== undefined && creds.password !== undefined) {
          const jql = `project = ${args.projectKey} AND resolution = Unresolved ORDER BY priority DESC, updated DESC`;

          const path = `${uri}/rest/api/2/search`;
          const options = {
            qs: {
              jql,
              maxResults: 3,
            },
            headers: {
              'Content-Type': 'application/json',
              Authorization: `Basic ${self.authorization}`,
            },
          };

          const res = syncrequest('GET', path, options);
          if (res.statusCode >= 200 && res.statusCode < 300) {
            const jiraResponse = JSON.parse(res.getBody());
            const issues = jiraResponse.issues.map((e) => {
              const sodoIssue = {
                issueKey: e.key,
                title: e.fields.summary,
                priority: e.fields.priority.name,
              };
              return sodoIssue;
            });

            return {
              success: true,
              message: {
                type: 'JIRA',
                projectKey: args.projectKey,
                totalOpenIssues: jiraResponse.total,
                issues,
              },
              info: 'Credentials were available',
            };
          }

          return {
            success: false,
            message: {},
            info: 'Credentials were available.',
          };
        }
        return {
          success: true,
          message: {
            type: 'JIRA',
            projectKey: args.projectKey,
          },
          info: 'Credentials were not available',
        };
      },
      getConfig: () => ({
        resource: 'backlog',
        properties: {
          type: 'jira',
          description: 'A Jira based-backlog',
          projectKey: args.projectKey,
        },
      }),
    };

    return provider;
  }
}

module.exports = Jira;