text:
@interface HeaderView () <UITextFieldDelegate>
@property (nonatomic,strong) UITextField *tfL;
@property (nonatomic,strong) UITextField *tfG;
@end

@implementation HeaderView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {

        self.tfL = [[UITextField alloc] initWithFrame:CGRectMake(18, 20, ScreenWidth - 36, 20)];
        self.tfL.placeholder = @"add lmz";
        self.tfL.font = [UIFont systemFontOfSize:15];
//        self.tfL.textAlignment = NSTextAlignmentCenter;
        self.tfL.returnKeyType = UIReturnKeyDone;
        self.tfL.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
        self.tfL.delegate = self;
        self.tfL.tag = 1000;
        [self addSubview:self.tfL];

        self.tfG = [[UITextField alloc] initWithFrame:CGRectMake(18, 60, ScreenWidth - 36, 20)];
        self.tfG.placeholder = @"add gyh";
        self.tfG.font = [UIFont systemFontOfSize:15];
        //        self.tfL.textAlignment = NSTextAlignmentCenter;
        self.tfG.returnKeyType = UIReturnKeyDone;
        self.tfG.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
        self.tfG.delegate = self;
        self.tfG.tag = 1001;
        [self addSubview:self.tfG];

    }
    return self;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField.tag == 1000) {
        if (![textField.text isEqualToString:@""]) {
            if (![self isOnlyHasNumberAndPointWithString:textField.text]) {
                [self showAlertMessage:@"别瞎填"];
            } else {
                if (self.lResultBlock) {
                    self.lResultBlock(textField.text);
                }
            }
        }
        self.tfL.text = @"";
        [self.tfL resignFirstResponder];
    } else {
        if (![textField.text isEqualToString:@""]) {
            if (![self isOnlyHasNumberAndPointWithString:textField.text]) {
                [self showAlertMessage:@"别瞎填"];
            } else {
                if (self.gResultBlock) {
                    self.gResultBlock(textField.text);
                }
            }
        }
        self.tfG.text = @"";
        [self.tfG resignFirstResponder];
    }
    return YES;
}

//判断是否只包含数字和小数点
- (BOOL)isOnlyHasNumberAndPointWithString:(NSString *)str {
    NSCharacterSet *set = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789."] invertedSet];
    NSString *filter = [[str componentsSeparatedByCharactersInSet:set] componentsJoinedByString:@""];
    return [str isEqualToString:filter];
}

- (void)showAlertMessage:(NSString *)msg {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:msg message:nil delegate:nil cancelButtonTitle:@"好" otherButtonTitles:nil];
    [alert show];
}

@end


text:
from algo.algorithm import Algorithm
from utils.convert import Convert

class ListSource(Algorithm):

    def __init__(self, value):
        super().__init__()
        self._list = Convert.to_list(value)

    def update(self, data):
        if self._list:
            self._output = self._list[0]
            self._list = self._list[1:]
        else:
            self._output = None

redpajama_set_name: RedPajamaGithub


text:
package events

import (
	"bytes"
	"encoding/json"
	"errors"
)

const (
	PushEvent string = "push"
)

var (
	InvalidEventErr = errors.New("Invalid event")

	exists = struct{}{}

	validEvents = map[string]struct{}{
		PushEvent: exists,
	}
)

func IsValidEvent(event string) bool {
	_, ok := validEvents[event]
	return ok
}

// The payload type.
type Payload interface {
	// The event the payload is for.
	//
	// This will be included in the marshalled payload.
	GetEvent() string

	// The repository name this payload is for.
	//
	// This will be included in the marshalled payload.
	GetRepository() string

	// Extra content to be included in the payload.
	//
	// This returns a tuple of `(fieldName, fieldContents)`.
	//
	// The contents must be `json.Marshal`-able.
	GetContent() (string, interface{})
}

// Marshal a payload into a JSON blob.
func MarshalPayload(p Payload) ([]byte, error) {
	buffer := bytes.NewBufferString("{\n")

	b, err := json.Marshal(p.GetEvent())
	if err != nil {
		return nil, err
	}

	buffer.WriteString("\t\"event\": ")
	buffer.Write(b)
	buffer.WriteString(",\n")

	b, err = json.Marshal(p.GetRepository())
	if err != nil {
		return nil, err
	}

	buffer.WriteString("\t\"repository\": ")
	buffer.Write(b)

	fieldName, content := p.GetContent()
	if fieldName != "" {
		buffer.WriteString(",\n")

		b, err = json.Marshal(fieldName)
		if err != nil {
			return nil, err
		}

		buffer.WriteString("\t")
		buffer.Write(b)
		buffer.WriteString(": ")

		b, err = json.MarshalIndent(content, "\t", "\t")
		if err != nil {
			return nil, err
		}

		buffer.Write(b)
	}

	buffer.WriteString("\n}\n")

	return buffer.Bytes(), nil
}


text:
<?php
//the following connection is for azure
  $servername = "eu-cdbr-azure-west-d.cloudapp.net";
  $username = "b3ecadc66c8aa5";
  $password = "fda61879";
  $dbname = "socialmediadb";

//$servername = "localhost";
//$username = "assignment";
//$password = "assignment";
//$dbname = "social_media";

  // Create connection
  $conn = new mysqli($servername, $username, $password, $dbname);
  // Check connection
  if ($conn->connect_error) {
      die("Connection failed: " . $conn->connect_error);
  }

?>


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<title>MultiselectJS — extras.org</title>

<meta  http-equiv="Content-Type" content="text/html;charset=utf-8" />
<meta  name="generator" content="Org-mode" />
<meta  name="author" content="Jaakko Järvi" />

MultiselectJS — extras.org

Table of Contents

1. Introduction

1.1. Points, lines, and rectangles

1.2. Drawing anchors, cursors, and rubber bands on Canvas

1 Introduction

This file contains definitions that are used in the examples, demos, and tutorials.
Two files are generated: rectangle.js and drawing.hs.
The latter depends on the former, and imports it with require.

1.1 Points, lines, and rectangles

  // public functions of the Rectangle module
  module.exports = {
    rect: rect,
    point: point,
    midPoint: midPoint,
    getOffsetRect: getOffsetRect,
    getOffsetRects: getOffsetRects,
    pointInRect: pointInRect,
    pointInRects: pointInRects,
    findRectOfPoint: findRectOfPoint,
    pointToRect: pointToRect,
    union: union,
    intersect: intersect,
    intersectWithAny: intersectWithAny,
    width: width,
    height: height,
    lineIntersect: lineIntersect,
    lineRectIntersect: lineRectIntersect,
    distance: distance,
    distanceSquared: distanceSquared,
    distanceToRectSquared: distanceToRectSquared,
    isPointBelowRect: isPointBelowRect,
    isPointAboveRect: isPointAboveRect,
    isPointLeftOfRect: isPointLeftOfRect,
    isPointRightOfRect: isPointRightOfRect,
    within: within
  };

  function within(x, b, e) {
    return x >= Math.min(b, e) && x <= Math.max(b, e);
  }

  function relativeToParent(pRect, eRect) {
    return {
      left: eRect.left - pRect.left,
      top: eRect.top - pRect.top,
      right: eRect.right - pRect.left,
      bottom: eRect.bottom - pRect.top
    }
  }

  function getOffsetRects(parent, elem) {
    var parentBox = parent.getBoundingClientRect();
    var boxes = elem.getClientRects();
    var res = $.map(boxes, function (box) { return relativeToParent(parentBox, box); });
    return res;
  }

  function getOffsetRect(parent, elem) {
    // return elem's bounding box in relation to paren's top left corner
    var parentBox = parent.getBoundingClientRect();
    var box = elem.getBoundingClientRect();

    return {
      left: box.left - parentBox.left,
      top: box.top - parentBox.top,
      right: box.right - parentBox.left,
      bottom: box.bottom - parentBox.top
    }
  }

  function rect(p1, p2) {
    return {
      left: Math.min(p1.x, p2.x),
      top: Math.min(p1.y, p2.y),
      right: Math.max(p1.x, p2.x),
      bottom: Math.max(p1.y, p2.y)
    };
  }

  function point(x, y) {
    return { x: x, y: y };
  }

  function midPoint (r) {
    return { x: (r.left + r.right)/2,
             y: (r.top + r.bottom)/2 };
  }

  function pointInRect (p, r) {
    return p.x >= r.left && p.x <= r.right
      && p.y >= r.top && p.y <= r.bottom;
  }

  function pointInRects (p, rs) {
    for (var i = 0; i < rs.length; ++i)
      if (pointInRect(p, rs[i])) return true;
    return false;
  }

  function findRectOfPoint (p, rs) {
    for (var i = 0; i < rs.length; ++i)
      if (pointInRect(p, rs[i])) return rs[i];
    return undefined;
  }

  function isPointBelowRect(p, r) {
    return p.y >= r.bottom;
  }

  function isPointAboveRect(p, r) {
    return p.y <= r.top;
  }

  function isPointLeftOfRect(p, r) {
    return p.x <= r.left;
  }

  function isPointRightOfRect(p, r) {
    return p.x >= r.right;
  }

  // a zero width, zero hight rectangle at point
  function pointToRect (point) {
    return { left: point.x, top: point.y,
             right: point.x, bottom: point.y };
  }

  function distance (p1, p2) {
    return Math.sqrt(distanceSquared(p1, p2));
  }

  function distanceSquared (p1, p2) {
    var dx = p2.x - p1.x;
    var dy = p2.y - p1.y;
    return (dx * dx) + (dy * dy);
  }

  function distanceToRectSquared (p, r) {
    var cand = Math.min(
      distanceSquared(p, {x: r.left, y: r.top}),
      distanceSquared(p, {x: r.left, y: r.bottom}),
      distanceSquared(p, {x: r.right, y: r.top}),
      distanceSquared(p, {x: r.right, y: r.bottom})
    );
    if (p.x > r.left && p.x < r.right)
      return Math.min(cand, Math.abs(p.y - r.top), Math.abs(p.y - r.bottom));
    if (p.y > r.top && p.y < r.bottom)
      return Math.min(cand, Math.abs(p.x - r.left), Math.abs(p.x - r.right));
    return cand;
  }

  // the smallest rectangle that includes r1 and r2
  function union (r1, r2) {
    var left = Math.min(r1.left, r2.left);
    var top = Math.min(r1.top, r2.top);
    var right = Math.max(r1.right, r2.right);
    var bottom = Math.max(r1.bottom, r2.bottom);
    return {
      left: left,
      top: top,
      right: right,
      bottom: bottom
    };
  }

  function width (r) { return r.right - r.left; }
  function height (r) { return r.bottom - r.top; }

  // do r1 and r2 intersect?
  // two zero-width and heigth rectangles do
  // not intersect, even if they are the same point
  // FIXME: this is not quite the right behavior
  function intersect (r1, r2) {
    return r1.left < r2.right
      && r1.right > r2.left
      && r1.top < r2.bottom
      && r1.bottom > r2.top;
  };

  function intersectWithAny (r, rs) {
    for (var i = 0; i < rs.length; ++i)
      if (intersect(r, rs[i])) return true;
    return false;
  }

  /* PORTED FROM:

   * lines_intersect:  AUTHOR: Mukesh Prasad
   *
   *   This function computes whether two line segments,
   *   respectively joining the input points (x1,y1) -- (x2,y2)
   *   and the input points (x3,y3) -- (x4,y4) intersect.
   *   If the lines intersect, the output variables x, y are
   *   set to coordinates of the point of intersection.
   *
   *   All values are in integers.  The returned value is rounded
   *   to the nearest integer point.
   *
   *   If non-integral grid points are relevant, the function
   *   can easily be transformed by substituting floating point
   *   calculations instead of integer calculations.
   *
   *   Entry
   *        x1, y1,  x2, y2   Coordinates of endpoints of one segment.
   *        x3, y3,  x4, y4   Coordinates of endpoints of other segment.
   *
   *   Exit
   *        x, y              Coordinates of intersection point.
   *
   *   The value returned by the function is one of:
   *
   *        DONT_INTERSECT    0
   *        DO_INTERSECT      1
   *        COLLINEAR         2
   *
   * Error conditions:
   *
   *     Depending upon the possible ranges, and particularly on 16-bit
   *     computers, care should be taken to protect from overflow.
   *
   *     In the following code, 'long' values have been used for this
   *     purpose, instead of 'int'.
   *
   */

  function sameSigns(a, b) { return a >= 0 && b >= 0 || a < 0 && b < 0; }

  function lineIntersect( p1,   /* First line segment */
                          p2,
                          p3,   /* Second line segment */
                          p4,
                          p5    /* Output value:
                                 * point of intersection */
                        )
  {

    const DONT_INTERSECT = 0;
    const DO_INTERSECT = 1;
    const COLLINEAR = 2;

    var a1, a2, b1, b2, c1, c2; /* Coefficients of line eqns. */
    var r1, r2, r3, r4;         /* 'Sign' values */
    var denom, offset, num;     /* Intermediate values */

    /* Compute a1, b1, c1, where line joining points 1 and 2
     * is "a1 x  +  b1 y  +  c1  =  0".
     */

    a1 = p2.y - p1.y;
    b1 = p1.x - p2.x;
    c1 = p2.x * p1.y - p1.x * p2.y;

    /* Compute r3 and r4.
     */

    r3 = a1 * p3.x + b1 * p3.y + c1;
    r4 = a1 * p4.x + b1 * p4.y + c1;

    /* Check signs of r3 and r4.  If both point 3 and point 4 lie on
     * same side of line 1, the line segments do not intersect.
     */

    if ( r3 != 0 &&
         r4 != 0 &&
         sameSigns( r3, r4 ))
      return ( DONT_INTERSECT );

    /* Compute a2, b2, c2 */

    a2 = p4.y - p3.y;
    b2 = p3.x - p4.x;
    c2 = p4.x * p3.y - p3.x * p4.y;

    /* Compute r1 and r2 */

    r1 = a2 * p1.x + b2 * p1.y + c2;
    r2 = a2 * p2.x + b2 * p2.y + c2;

    /* Check signs of r1 and r2.  If both point 1 and point 2 lie
     * on same side of second line segment, the line segments do
     * not intersect.
     */

    if ( r1 !== 0 &&
         r2 !== 0 &&
         sameSigns( r1, r2 ))
      return ( DONT_INTERSECT );

    /* Line segments intersect: compute intersection point.
     */

    denom = a1 * b2 - a2 * b1;
    if ( denom === 0 )
      return ( COLLINEAR );
    offset = denom < 0 ? - denom / 2 : denom / 2;

    /* The denom/2 is to get rounding instead of truncating.  It
     * is added or subtracted to the numerator, depending upon the
     * sign of the numerator.
     */

    num = b1 * c2 - b2 * c1;
    p5.x = ( num < 0 ? num - offset : num + offset ) / denom;

    num = a2 * c1 - a1 * c2;
    p5.y = ( num < 0 ? num - offset : num + offset ) / denom;

    return DO_INTERSECT;
  } /* lines_intersect */

  function lineRectIntersect(p1, p2, r) {
    if (!intersect(rect(p1, p2), r)) return false; // if bounding boxes do not overlap, cannot intersect
    var p = {};
    if (lineIntersect(p1, p2, { x: r.left, y: r.top }, { x: r.left, y: r.bottom }, p) !== 0) return true;
    if (lineIntersect(p1, p2, { x: r.left, y: r.top }, { x: r.right, y: r.top }, p) !== 0) return true;
    if (lineIntersect(p1, p2, { x: r.right, y: r.bottom }, { x: r.right, y: r.top }, p) !== 0) return true;
    if (lineIntersect(p1, p2, { x: r.right, y: r.bottom }, { x: r.left, y: r.bottom }, p) !== 0) return true;
    return pointInRect(p1, r) || pointInRect(p2, r);
  }

1.2 Drawing anchors, cursors, and rubber bands on Canvas

var Rect = require("./rectangle");

function createBaseCanvas (parent) {
  var canvas = document.createElement("canvas");
  var rect = parent.getBoundingClientRect();
  canvas.style.position = 'absolute';
  canvas.width=Rect.width(rect);
  canvas.height=Rect.height(rect);
  canvas.style.zIndex = 0;
  canvas.style.overflow = 'hidden';
  parent.insertBefore(canvas, parent.firstChild);
  return canvas;
}

// Create n canvases on top of the baseCanvas, insert them into
// the DOM, and push them into layerArray, and return layerArray.
// The zIndex
// is consequtive, up from baseCanvas's zIndex.  New canvases have
// no border or background.
function createLayers (baseCanvas, n, layers) {
  var z = baseCanvas.style.zIndex || 0;
  layers = layers || [];
  for (var i = 0; i < n; ++i) {
    var canvas = baseCanvas.cloneNode(true);
    canvas.style.position = 'absolute';
    canvas.style.top = baseCanvas.style.top;
    canvas.style.left = baseCanvas.style.left;
    canvas.style.zIndex = z + 1 + i;
    canvas.style.background = null;
    layers.push(canvas);
    baseCanvas.parentNode.insertBefore(canvas, baseCanvas);
  }
  return layers;
};

//////////////////////
// Cursor    canvas //
//////////////////////

exports.CursorCanvas = function (parent) {

  this.baseCanvas = createBaseCanvas(parent);
  this.layers = createLayers(this.baseCanvas, 3, []);
  // construct 3 layers, one each for activeEnd, anchor, rubber

//  this.eventCanvas = this.layers[this.layers.length-1];
  // last layer captures mouse events

  this.rubberCtx = this.layers[0].getContext('2d');
  this.anchorCtx = this.layers[1].getContext('2d');
  this.cursorCtx = this.layers[2].getContext('2d');

  this.anchorCtx.strokeStyle = 'blue';
  this.anchorCtx.lineWidth = 1;

  this.cursorCtx.strokeStyle = 'deeppink';
  this.cursorCtx.lineWidth = 1;

  this.rubberCtx.strokeStyle = 'darkgreen';
  this.rubberCtx.lineWidth = 2;
  if (this.rubberCtx.setLineDash)
    this.rubberCtx.setLineDash([6,3]); // Not in all browsers
}

exports.CursorCanvas.prototype.resize = function (w, h) {
  for (var i = 0; i < this.layers.length; ++i) {
    this.layers[i].width = w;
    this.layers[i].height = h;
  }
};

exports.CursorCanvas.prototype.clear = function (ctx) {
  ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
}

//////////////////////////////////////////////////////
// Helper functions for drawing shapes on a context //
//////////////////////////////////////////////////////

// pre: objects in path have members x and y
exports.drawPath = function (ctx, path) {
  if (path.length < 2) return;
  ctx.beginPath();
  ctx.moveTo(path[0].x, path[0].y);
  for (var i=1; i<path.length; ++i) ctx.lineTo(path[i].x, path[i].y);
  ctx.stroke();
}

// pre: r is a rect
exports.drawBox = function (ctx, r) {
  ctx.strokeRect(r.left, r.top, Rect.width(r), Rect.height(r));

}

exports.drawLine = function (ctx, p1, p2) {
  ctx.beginPath();
  ctx.moveTo(p1.x, p1.y);
  ctx.lineTo(p2.x, p2.y);
  ctx.stroke();
}

exports.drawCircle = function (ctx, point) {
  ctx.beginPath();
  ctx.arc(point.x, point.y, 4, 0, Math.PI*2, true);
  ctx.stroke();
}

exports.drawSmallCircle = function (ctx, point) {
  ctx.beginPath();
  ctx.arc(point.x, point.y, 2, 0, Math.PI*2, true);
  ctx.stroke();
}


text:
{-# LANGUAGE Trustworthy #-}

-- |
-- Module      : Codec.Dvorak
-- Description : Dvorak encoding for Haskell.
-- Copyright   : (c) Kyle Van Berendonck, 2014
-- License     : BSD3
-- Maintainer  : kvanberendonck@gmail.com
-- Stability   : experimental
-- Portability : portable
--
-- This module exposes all the API for this package.
module Codec.Dvorak
    ( toDvorakChar
    , toDvorak
    , fromDvorakChar
    , fromDvorak
    ) where

import           Data.Tuple
import qualified Data.Map.Strict as Map

toTable :: Map.Map Char Char
toTable = Map.fromList $ zip
  "-=qwertyuiop[]asdfghjkl;'zxcvbnm,./_+QWERTYUIOP{}ASDFGHJKL:\"ZXCVBNM<>?"
  "[]',.pyfgcrl/=aoeuidhtns-;qjkxbmwvz{}\"<>PYFGCRL?+AOEUIDHTNS_:QJKXBMWVZ"

fromTable :: Map.Map Char Char
fromTable = Map.fromList . map swap . Map.assocs $ toTable

-- | Encodes a single given 'Char' to its dvorak encoded equivalent.
toDvorakChar :: Char -> Char
toDvorakChar c = case Map.lookup c toTable of
  Just x  -> x
  Nothing -> c
{-# INLINABLE toDvorakChar #-}

-- | Encodes a string to its dvorak encoded equivalent using 'toDvorakChar'. Analagous to:
--
-- @
--    toDvorak = map toDvorakChar
-- @
toDvorak :: String -> String
toDvorak = map toDvorakChar
{-# INLINE toDvorak #-}

-- | Decodes a single given 'Char' from its dvorak encoded equivalent.
fromDvorakChar :: Char -> Char
fromDvorakChar c = case Map.lookup c fromTable of
  Just x  -> x
  Nothing -> c
{-# INLINABLE fromDvorakChar #-}

-- | Decodes a string from its dvorak encoded equivalent using 'fromDvorakChar'. Analagous to:
--
-- @
--    fromDvorak = map fromDvorakChar
-- @
fromDvorak :: String -> String
fromDvorak = map fromDvorakChar
{-# INLINE fromDvorak #-}


text:
namespace OmniXaml.Wpf
{
    using System;
    using System.Reflection;
    using System.Windows;

    public static class Extensions
    {
        public static DependencyProperty GetDependencyProperty(this Type type, string name)
        {
            var dpPropName = name + "Property";
            FieldInfo fieldInfo = type.GetField(dpPropName, BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);
            return (DependencyProperty)fieldInfo?.GetValue(null);
        }
    }
}


text:
@interface FontTableViewCell : AXTableViewCell

@end


text:
Example of using websockets to provide communications between a Jupyter
Notebook and a C application. This was not an exercise in making all the right
decisions, but more about getting something working to prove a concept. Any
advice/criticism from internet land is welcome to learn from though. This was
all tested on Linux (Ubuntu Wiley) only to date. YMMV.

Interesting topics in this example:
* WebSockets comms from a Jupyter notebook to some websocket server
* Those same websocket comms being directed to a C application via a Unix
  socket
* (To come) Wrapping of C structs (used by the C app) for use in Python (using
  Cython), and using those structs as the interface of the Unix socket.
* A "server" (really a server/client) handling both websockets and unix sockets
  at the same time.
* Having the data returned from the C app to the WebSocket client (in the
  notebook) update a display element (currently a Matplotlib figure).
* (Eventually) Custom ipywidgets for use in the notebook.

*This doc is being updated.* Especially the dependencies until requirements.txt
Files are maintained. If problems are found, please drop a line.

### General Dependencies
* [Anaconda](https://www.continuum.io/why-anaconda) - Both the client_side and
  server_side have separate Python3 (3.5) environments with different
  dependencies. Anaconda is used to manage the environments.
* IPython - Installed with Anaconda and absolutely required for all the Python
  things

### General TODO
* Better documentation (README and code...especially code)
* Clean up coroutines vs callbacks on the Python side (go with coroutines)
* Better encapsulation where warranted on the Python side.
* look at Jupyter server extensions
 * for our web socket handler (says REST handler needed in the Jupyter docs,
   but the websocket class extends from request handler, which is what is
   needed. Can we do this since it's a client too?)
 * for the socket client from the c side? can this be combined with the
   websocket handler? Can we even do this since it's a client?

## C Driver (c_driver) Specifics
C application for acting as a Unix socket server, sending/receiving data from
a websocket server (acting as a client of this application).

### c_driver Dependencies
* gcc

### C Driver Usage
* Build the driver.
 * cd to the c_driver directory
 * run `gcc driver.c -o driver`
 * ignore warnings for now
* run the driver with `./driver`. This should be started before the
  server_side/server_main.py is.

### C Driver TODO:
* Rather than echoing what's received, do something with it.
* Print diagnostics.
* Include dummy header files (to show struct usage between driver and
  server_side)
* Investigate an ipywidget for a console to run this from (so everything can
  be in a notebook environment).

## Websocket Server (server_side) Specifics
This side has a websocket server that communicates with a C application over
native Unix sockets, using (eventually) C structs wrapped for Python (using
Cython) as the interface. Messages come to this server from websocket clients,
then go to the C app, and data comes from the C app to be sent over the
websocket back to the clients.

### server_side Dependencies
When stable, this application will include a requirements.txt file. For now,
this list will be manually kept up to date.
* tornado
* pep8
* ipython
* cython

### server_side Usage
* Make the environment (assuming Anaconda is installed and on the path)
`conda create --name websocket_dirver_server python=3 tornado pep8`
* Activate the environment:
`source activate websocket_driver_server`
* Install new packages (as needed...should be documented here already)
`conda install --name websocket_driver_server [packages]` or (in the activated
environment)`pip install [packages]`
* Run websocket the server (needs its own process) from the server_side dir
`python server_main.py`
* NOTE: this should be a jupyter notebook of it's own soon.

### server_side TODO:
* make able to send/receive custom message dicts from the clients
* get structs working with c driver over sockets
 * implement a way to for websocket clients to register message types of
   interest (very low priority)
* make a notebook for the server (with the kernel pointed to the conda env for
  the server). [That process is here](http://ipython.readthedocs.org/en/stable/install/kernel_install.html)

## Websocket Client and Jupyter Notebook (client_side) Specifics
Test websocket client interacting with a Jupyter notebook. This side has as
a websocket client that sits in a jupyter notebook. Data from the notebook is
sent to the server, and data comes from the server to display on the notebook
(and update a graphical display element).

### client_side Dependencies
* tornado
* jupyter
* notebook
* pep8

### client_side Usage
* Make the environment (assuming Anaconda is installed and on the path)
`conda create --name websocket_ui_client python=3 tornado jupyter notebook pep8`
* Activate the environment
`source activate websocket_ui_client`
* Install new packages (as needed...should be documented here already)
`conda install --name websocket_ui_client [packages]` or `pip install [packages]`
* Run notebook server (blocking) `jupyter notebook --port [port_num]`
* Load the notebook 'WebsocketClient Sandbox'
* Have fun. Run the cells in order. Hopefully I'll have time to document things
  in the notebook better soon.

### client_side TODO:
* make able to send/receive custom messages (to be used server_side for filling
  in C struct wrappers)
* customizable ports (really, customizable many things)
* jupyter config values (python path, etc)

### client_side Notes:
* There's a test client (blocking) from the client_side dir:
 `python client_main.py`


text:
@extends('app')

@section('content')

@endsection


text:
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin Core developers
// Copyright (c) 2014-2017 The Sscoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "chainparams.h"
#include "consensus/merkle.h"

#include "tinyformat.h"
#include "util.h"
#include "utilstrencodings.h"

#include <assert.h>

#include <boost/assign/list_of.hpp>

#include "chainparamsseeds.h"

static CBlock CreateGenesisBlock(const char* pszTimestamp, const CScript& genesisOutputScript, uint32_t nTime, uint32_t nNonce, uint32_t nBits, int32_t nVersion, const CAmount& genesisReward)
{
    CMutableTransaction txNew;
    txNew.nVersion = 1;
    txNew.vin.resize(1);
    txNew.vout.resize(1);
    txNew.vin[0].scriptSig = CScript() << 486604799 << CScriptNum(4) << std::vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
    txNew.vout[0].nValue = genesisReward;
    txNew.vout[0].scriptPubKey = genesisOutputScript;

    CBlock genesis;
    genesis.nTime    = nTime;
    genesis.nBits    = nBits;
    genesis.nNonce   = nNonce;
    genesis.nVersion = nVersion;
    genesis.vtx.push_back(txNew);
    genesis.hashPrevBlock.SetNull();
    genesis.hashMerkleRoot = BlockMerkleRoot(genesis);
    return genesis;
}

/**
 * Build the genesis block. Note that the output of its generation
 * transaction cannot be spent since it did not originally exist in the
 * database.
 *
 * CBlock(hash=00000ffd590b14, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=e0028e, nTime=1390095618, nBits=1e0ffff0, nNonce=28917698, vtx=1)
 *   CTransaction(hash=e0028e, ver=1, vin.size=1, vout.size=1, nLockTime=0)
 *     CTxIn(COutPoint(000000, -1), coinbase 04ffff001d01044c5957697265642030392f4a616e2f3230313420546865204772616e64204578706572696d656e7420476f6573204c6976653a204f76657273746f636b2e636f6d204973204e6f7720416363657074696e6720426974636f696e73)
 *     CTxOut(nValue=50.00000000, scriptPubKey=0xA9037BAC7050C479B121CF)
 *   vMerkleTree: e0028e
 */
static CBlock CreateGenesisBlock(uint32_t nTime, uint32_t nNonce, uint32_t nBits, int32_t nVersion, const CAmount& genesisReward)
{
    const char* pszTimestamp = "start 18/08/2017 12/00";
    const CScript genesisOutputScript = CScript() << ParseHex("043bc92229a57041284ed5eda2b0304019ce37b84d1f7d95b0655f66ab57692c4f3b4f2c1eecc48d8c2ab37aed92f24753e3d6f3b8b94dc9b861a2d513f20292fb") << OP_CHECKSIG;
    return CreateGenesisBlock(pszTimestamp, genesisOutputScript, nTime, nNonce, nBits, nVersion, genesisReward);
}

/**
 * Main network
 */
/**
 * What makes a good checkpoint block?
 * + Is surrounded by blocks with reasonable timestamps
 *   (no blocks before with a timestamp after, none after with
 *    timestamp before)
 * + Contains no strange transactions
 */

class CMainParams : public CChainParams {
public:
    CMainParams() {
        strNetworkID = "main";
        consensus.nSubsidyHalvingInterval = 210240; // Note: actual number of blocks per calendar year with DGW v3 is ~200700 (for example 449750 - 249050)
        consensus.nMasternodePaymentsStartBlock = 100000; // not true, but it's ok as long as it's less then nMasternodePaymentsIncreaseBlock
        consensus.nMasternodePaymentsIncreaseBlock = 158000; // actual historical value
        consensus.nMasternodePaymentsIncreasePeriod = 576*30; // 17280 - actual historical value
        consensus.nInstantSendKeepLock = 24;
        consensus.nBudgetPaymentsStartBlock = 328008; // actual historical value
        consensus.nBudgetPaymentsCycleBlocks = 16616; // ~(60*24*30)/2.6, actual number of blocks per month is 200700 / 12 = 16725
        consensus.nBudgetPaymentsWindowBlocks = 100;
        consensus.nBudgetProposalEstablishingTime = 60*60*24;
        consensus.nSuperblockStartBlock = 614820; // The block at which 12.1 goes live (end of final 12.0 budget cycle)
        consensus.nSuperblockCycle = 16616; // ~(60*24*30)/2.6, actual number of blocks per month is 200700 / 12 = 16725
        consensus.nGovernanceMinQuorum = 10;
        consensus.nGovernanceFilterElements = 20000;
        consensus.nMasternodeMinimumConfirmations = 15;
        consensus.nMajorityEnforceBlockUpgrade = 750;
        consensus.nMajorityRejectBlockOutdated = 950;
        consensus.nMajorityWindow = 1000;
        consensus.BIP34Height = 227931;
        consensus.BIP34Hash = uint256S("0x000000000000024b89b42a942fe0d9fea3bb44ab7bd1b19115dd6a759c0808b8");
        consensus.powLimit = uint256S("00000fffff000000000000000000000000000000000000000000000000000000");
        consensus.nPowTargetTimespan = 24 * 60 * 60; // Sscoin: 1 day
        consensus.nPowTargetSpacing = 2.5 * 60; // Sscoin: 2.5 minutes
        consensus.fPowAllowMinDifficultyBlocks = false;
        consensus.fPowNoRetargeting = false;
        consensus.nRuleChangeActivationThreshold = 1916; // 95% of 2016
        consensus.nMinerConfirmationWindow = 2016; // nPowTargetTimespan / nPowTargetSpacing
        consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28;
        consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 1199145601; // January 1, 2008
        consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 1230767999; // December 31, 2008

        // Deployment of BIP68, BIP112, and BIP113.
        consensus.vDeployments[Consensus::DEPLOYMENT_CSV].bit = 0;
        consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 1486252800; // Feb 5th, 2017
        consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = 1517788800; // Feb 5th, 2018

        /**
         * The message start string is designed to be unlikely to occur in normal data.
         * The characters are rarely used upper ASCII, not valid as UTF-8, and produce
         * a large 32-bit integer with any alignment.
         */
        pchMessageStart[0] = 0xbf;
        pchMessageStart[1] = 0x0c;
        pchMessageStart[2] = 0x6b;
        pchMessageStart[3] = 0xbd;
        vAlertPubKey = ParseHex("04a9412131728544c723317aee94346bb3cdecdda2190044818394b95967d3086a0cd2521bc341e111977d6e88fc543ab18f352e85d1b19c76a4051e75b4a58889");
        nDefaultPort = 7111;
        nMaxTipAge = 6 * 60 * 60; // ~144 blocks behind -> 2 x fork detection time, was 24 * 60 * 60 in bitcoin
        nPruneAfterHeight = 100000;

        genesis = CreateGenesisBlock(1503046800, 329261, 0x1e0ffff0, 1, 50 * COIN);
        consensus.hashGenesisBlock = genesis.GetHash();
        assert(consensus.hashGenesisBlock == uint256S("0x0000094337a8cf67ff467ff4856e577bc22946aeeaaaa93001ca5c1e5e9f7842"));
        assert(genesis.hashMerkleRoot == uint256S("0x5b3ba85195aaa0ecefab9084a8576eaaf65ebf2c87c0dcdfa06c9f32b47ed58f"));

        vSeeds.clear();

        // Sscoin addresses start with 'X'
        base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,76);
        // Sscoin script addresses start with '7'
        base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,16);
        // Sscoin private keys start with '7' or 'X'
        base58Prefixes[SECRET_KEY] =     std::vector<unsigned char>(1,204);
        // Sscoin BIP32 pubkeys start with 'xpub' (Bitcoin defaults)
        base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x88)(0xB2)(0x1E).convert_to_container<std::vector<unsigned char> >();
        // Sscoin BIP32 prvkeys start with 'xprv' (Bitcoin defaults)
        base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x88)(0xAD)(0xE4).convert_to_container<std::vector<unsigned char> >();
        // Sscoin BIP44 coin type is '5'
        base58Prefixes[EXT_COIN_TYPE]  = boost::assign::list_of(0x80)(0x00)(0x00)(0x05).convert_to_container<std::vector<unsigned char> >();

        vFixedSeeds = std::vector<SeedSpec6>(pnSeed6_main, pnSeed6_main + ARRAYLEN(pnSeed6_main));

        fMiningRequiresPeers = true;
        fDefaultConsistencyChecks = false;
        fRequireStandard = true;
        fMineBlocksOnDemand = false;
        fTestnetToBeDeprecatedFieldRPC = false;

        nPoolMaxTransactions = 3;
        nFulfilledRequestExpireTime = 60*60; // fulfilled requests expire in 1 hour
        strSporkPubKey = "04ad3f9f12f1e215200c3dceaf2c88f43566b0cfafaacbaa94551cc632d29db081cb66f33c64e9a380b873bd359bfe8befc44c0a0fa0e6fb256799165991a9bfe4";
        strMasternodePaymentsPubKey = "04ad3f9f12f1e215200c3dceaf2c88f43566b0cfafaacbaa94551cc632d29db081cb66f33c64e9a380b873bd359bfe8befc44c0a0fa0e6fb256799165991a9bfe4";

        checkpointData = (CCheckpointData) {
            boost::assign::map_list_of
            (  0, uint256S("0x0000094337a8cf67ff467ff4856e577bc22946aeeaaaa93001ca5c1e5e9f7842")),
            1503046800, // * UNIX timestamp of last checkpoint block
            0,    // * total number of transactions between genesis and last checkpoint
                        //   (the tx=... number in the SetBestChain debug.log lines)
            2800        // * estimated number of transactions per day after checkpoint
        };
    }
};
static CMainParams mainParams;

/**
 * Testnet (v3)
 */
class CTestNetParams : public CChainParams {
public:
    CTestNetParams() {
        strNetworkID = "test";
        consensus.nSubsidyHalvingInterval = 210240;
        consensus.nMasternodePaymentsStartBlock = 10000; // not true, but it's ok as long as it's less then nMasternodePaymentsIncreaseBlock
        consensus.nMasternodePaymentsIncreaseBlock = 46000;
        consensus.nMasternodePaymentsIncreasePeriod = 576;
        consensus.nInstantSendKeepLock = 6;
        consensus.nBudgetPaymentsStartBlock = 60000;
        consensus.nBudgetPaymentsCycleBlocks = 50;
        consensus.nBudgetPaymentsWindowBlocks = 10;
        consensus.nBudgetProposalEstablishingTime = 60*20;
        consensus.nSuperblockStartBlock = 61000; // NOTE: Should satisfy nSuperblockStartBlock > nBudgetPeymentsStartBlock
        consensus.nSuperblockCycle = 24; // Superblocks can be issued hourly on testnet
        consensus.nGovernanceMinQuorum = 1;
        consensus.nGovernanceFilterElements = 500;
        consensus.nMasternodeMinimumConfirmations = 1;
        consensus.nMajorityEnforceBlockUpgrade = 51;
        consensus.nMajorityRejectBlockOutdated = 75;
        consensus.nMajorityWindow = 100;
        consensus.BIP34Height = 21111;
        consensus.BIP34Hash = uint256S("0x0000000023b3a96d3484e5abb3755c413e7d41500f8e2a5c3f0dd01299cd8ef8");
        consensus.powLimit = uint256S("00000fffff000000000000000000000000000000000000000000000000000000");
        consensus.nPowTargetTimespan = 24 * 60 * 60; // Sscoin: 1 day
        consensus.nPowTargetSpacing = 2.5 * 60; // Sscoin: 2.5 minutes
        consensus.fPowAllowMinDifficultyBlocks = true;
        consensus.fPowNoRetargeting = false;
        consensus.nRuleChangeActivationThreshold = 1512; // 75% for testchains
        consensus.nMinerConfirmationWindow = 2016; // nPowTargetTimespan / nPowTargetSpacing
        consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28;
        consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 1199145601; // January 1, 2008
        consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 1230767999; // December 31, 2008

        // Deployment of BIP68, BIP112, and BIP113.
        consensus.vDeployments[Consensus::DEPLOYMENT_CSV].bit = 0;
        consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 1456790400; // March 1st, 2016
        consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = 1493596800; // May 1st, 2017

        pchMessageStart[0] = 0xce;
        pchMessageStart[1] = 0xe2;
        pchMessageStart[2] = 0xca;
        pchMessageStart[3] = 0xff;
        vAlertPubKey = ParseHex("0450450078e04fa341280efb9c0fcb7bfed6f85a4f2a946c5ab17ca1b61e3e46ec16b5285127d4fcfa7bc11eae7824ae39a6a48e9bb60985655d48121b51e61403");
        nDefaultPort = 17111;
        nMaxTipAge = 0x7fffffff; // allow mining on top of old blocks for testnet
        nPruneAfterHeight = 1000;

        genesis = CreateGenesisBlock(1503046801, 3536659, 0x1e0ffff0, 1, 50 * COIN);
        consensus.hashGenesisBlock = genesis.GetHash();
        assert(consensus.hashGenesisBlock == uint256S("0x00000c953002154315ed7f5ea280137b9dae361dfbb714fa840899e313b7894a"));
        assert(genesis.hashMerkleRoot == uint256S("0x5b3ba85195aaa0ecefab9084a8576eaaf65ebf2c87c0dcdfa06c9f32b47ed58f"));

        vFixedSeeds.clear();
        vSeeds.clear();

        // Testnet Sscoin addresses start with 'y'
        base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,140);
        // Testnet Sscoin script addresses start with '8' or '9'
        base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,19);
        // Testnet private keys start with '9' or 'c' (Bitcoin defaults)
        base58Prefixes[SECRET_KEY] =     std::vector<unsigned char>(1,239);
        // Testnet Sscoin BIP32 pubkeys start with 'tpub' (Bitcoin defaults)
        base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x35)(0x87)(0xCF).convert_to_container<std::vector<unsigned char> >();
        // Testnet Sscoin BIP32 prvkeys start with 'tprv' (Bitcoin defaults)
        base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x35)(0x83)(0x94).convert_to_container<std::vector<unsigned char> >();
        // Testnet Sscoin BIP44 coin type is '1' (All coin's testnet default)
        base58Prefixes[EXT_COIN_TYPE]  = boost::assign::list_of(0x80)(0x00)(0x00)(0x01).convert_to_container<std::vector<unsigned char> >();

        vFixedSeeds = std::vector<SeedSpec6>(pnSeed6_test, pnSeed6_test + ARRAYLEN(pnSeed6_test));

        fMiningRequiresPeers = true;
        fDefaultConsistencyChecks = false;
        fRequireStandard = false;
        fMineBlocksOnDemand = false;
        fTestnetToBeDeprecatedFieldRPC = true;

        nPoolMaxTransactions = 3;
        nFulfilledRequestExpireTime = 5*60; // fulfilled requests expire in 5 minutes
        strSporkPubKey = "043cb5f727d103e9bfc6ec600ef2f62cbc0fdc1aebe53c65d34d016d9c45b05b89c284cb38f6307d90b06da3ce54335c692c3251457109c50e232a24bb7898c4ea";
        strMasternodePaymentsPubKey = "043cb5f727d103e9bfc6ec600ef2f62cbc0fdc1aebe53c65d34d016d9c45b05b89c284cb38f6307d90b06da3ce54335c692c3251457109c50e232a24bb7898c4ea";

        checkpointData = (CCheckpointData) {
            boost::assign::map_list_of
            (    0, uint256S("0x00000c953002154315ed7f5ea280137b9dae361dfbb714fa840899e313b7894a")),

            1503046801, // * UNIX timestamp of last checkpoint block
            0,     // * total number of transactions between genesis and last checkpoint
                        //   (the tx=... number in the SetBestChain debug.log lines)
            500         // * estimated number of transactions per day after checkpoint
        };

    }
};
static CTestNetParams testNetParams;

/**
 * Regression test
 */
class CRegTestParams : public CChainParams {
public:
    CRegTestParams() {
        strNetworkID = "regtest";
        consensus.nSubsidyHalvingInterval = 150;
        consensus.nMasternodePaymentsStartBlock = 240;
        consensus.nMasternodePaymentsIncreaseBlock = 350;
        consensus.nMasternodePaymentsIncreasePeriod = 10;
        consensus.nInstantSendKeepLock = 6;
        consensus.nBudgetPaymentsStartBlock = 1000;
        consensus.nBudgetPaymentsCycleBlocks = 50;
        consensus.nBudgetPaymentsWindowBlocks = 10;
        consensus.nBudgetProposalEstablishingTime = 60*20;
        consensus.nSuperblockStartBlock = 1500;
        consensus.nSuperblockCycle = 10;
        consensus.nGovernanceMinQuorum = 1;
        consensus.nGovernanceFilterElements = 100;
        consensus.nMasternodeMinimumConfirmations = 1;
        consensus.nMajorityEnforceBlockUpgrade = 750;
        consensus.nMajorityRejectBlockOutdated = 950;
        consensus.nMajorityWindow = 1000;
        consensus.BIP34Height = -1; // BIP34 has not necessarily activated on regtest
        consensus.BIP34Hash = uint256();
        consensus.powLimit = uint256S("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
        consensus.nPowTargetTimespan = 24 * 60 * 60; // Sscoin: 1 day
        consensus.nPowTargetSpacing = 2.5 * 60; // Sscoin: 2.5 minutes
        consensus.fPowAllowMinDifficultyBlocks = true;
        consensus.fPowNoRetargeting = true;
        consensus.nRuleChangeActivationThreshold = 108; // 75% for testchains
        consensus.nMinerConfirmationWindow = 144; // Faster than normal for regtest (144 instead of 2016)
        consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28;
        consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 0;
        consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 999999999999ULL;
        consensus.vDeployments[Consensus::DEPLOYMENT_CSV].bit = 0;
        consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 0;
        consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = 999999999999ULL;

        pchMessageStart[0] = 0xfc;
        pchMessageStart[1] = 0xc1;
        pchMessageStart[2] = 0xb7;
        pchMessageStart[3] = 0xdc;
        nMaxTipAge = 6 * 60 * 60; // ~144 blocks behind -> 2 x fork detection time, was 24 * 60 * 60 in bitcoin
        nDefaultPort = 17222;
        nPruneAfterHeight = 1000;

        genesis = CreateGenesisBlock(1503046802, 3, 0x207fffff, 1, 50 * COIN);
        consensus.hashGenesisBlock = genesis.GetHash();
        assert(consensus.hashGenesisBlock == uint256S("0x4be88cc4370ea64a80dfe91d492f04c2df1886b3c7164fd2e27d379bc6341dde"));
        assert(genesis.hashMerkleRoot == uint256S("0x5b3ba85195aaa0ecefab9084a8576eaaf65ebf2c87c0dcdfa06c9f32b47ed58f"));

        vFixedSeeds.clear(); //! Regtest mode doesn't have any fixed seeds.
        vSeeds.clear();  //! Regtest mode doesn't have any DNS seeds.

        fMiningRequiresPeers = false;
        fDefaultConsistencyChecks = true;
        fRequireStandard = false;
        fMineBlocksOnDemand = true;
        fTestnetToBeDeprecatedFieldRPC = false;

        nFulfilledRequestExpireTime = 5*60; // fulfilled requests expire in 5 minutes

        checkpointData = (CCheckpointData){
            boost::assign::map_list_of
            ( 0, uint256S("0x4be88cc4370ea64a80dfe91d492f04c2df1886b3c7164fd2e27d379bc6341dde")),
            0,
            0,
            0
        };
        // Regtest Sscoin addresses start with 'y'
        base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,140);
        // Regtest Sscoin script addresses start with '8' or '9'
        base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,19);
        // Regtest private keys start with '9' or 'c' (Bitcoin defaults)
        base58Prefixes[SECRET_KEY] =     std::vector<unsigned char>(1,239);
        // Regtest Sscoin BIP32 pubkeys start with 'tpub' (Bitcoin defaults)
        base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x35)(0x87)(0xCF).convert_to_container<std::vector<unsigned char> >();
        // Regtest Sscoin BIP32 prvkeys start with 'tprv' (Bitcoin defaults)
        base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x35)(0x83)(0x94).convert_to_container<std::vector<unsigned char> >();
        // Regtest Sscoin BIP44 coin type is '1' (All coin's testnet default)
        base58Prefixes[EXT_COIN_TYPE]  = boost::assign::list_of(0x80)(0x00)(0x00)(0x01).convert_to_container<std::vector<unsigned char> >();
   }
};
static CRegTestParams regTestParams;

static CChainParams *pCurrentParams = 0;

const CChainParams &Params() {
    assert(pCurrentParams);
    return *pCurrentParams;
}

CChainParams& Params(const std::string& chain)
{
    if (chain == CBaseChainParams::MAIN)
            return mainParams;
    else if (chain == CBaseChainParams::TESTNET)
            return testNetParams;
    else if (chain == CBaseChainParams::REGTEST)
            return regTestParams;
    else
        throw std::runtime_error(strprintf("%s: Unknown chain %s.", __func__, chain));
}

void SelectParams(const std::string& network)
{
    SelectBaseParams(network);
    pCurrentParams = &Params(network);
}


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

package com.google.firebase.encoders.proto;

import com.google.firebase.encoders.annotations.ExtraProperty;

/**
 * Protocol buffer field configuration that propagates into {@link
 * com.google.firebase.encoders.FieldDescriptor}s
 */
@ExtraProperty
public @interface Protobuf {
  /** Field tag */
  int tag();

  /** Specifies numeric field encoding. */
  IntEncoding intEncoding() default IntEncoding.DEFAULT;

  enum IntEncoding {
    DEFAULT,
    SIGNED,
    FIXED
  }
}


text:
from collections.abc import MutableMapping

class OpenStruct(MutableMapping):
    """OpenStruct, the flexible data structure."""
    def __init__(self, clone=None, dict_convert=False, **kwargs):
        super(OpenStruct, self).__init__()

        if isinstance(clone, OpenStruct):
            kwargs.update(**clone.__dict__)
        elif isinstance(clone, dict):
            kwargs.update(**clone)
        elif clone is not None:
            raise TypeError('Type to be cloned is not supported.')

        for key, value in kwargs.items():
            self.__dict__[key] = self._convert(value, dict_convert)

    @classmethod
    def _convert(cls, value, dict_convert=False):
        if dict_convert and isinstance(value, dict):
            return cls(**value)
        elif isinstance(value, (list, tuple)):
            dictionaries = []
            for item in value:
                dictionaries.append(cls._convert(item, dict_convert))

            if isinstance(value, tuple):
                dictionaries = tuple(dictionaries)

            return dictionaries
        elif isinstance(value, OpenStruct):
            return value.__class__(**value)
        else:
            return value

    def iteritems(self):
        try:
            return self.__dict__.iteritems()
        except AttributeError:
            return self.__dict__.items()

    def items(self):
        return self.__dict__.items()

    def keys(self):
        return self.__dict__.keys()

    def __iter__(self):
        return self.__dict__.__iter__()

    def __setitem__(self, key, value):
        self.__setattr__(key, value)

    def __getitem__(self, key):
        return self.__getattr__(key)

    def __getstate__(self):
        return self.__dict__

    def __setstate__(self, d):
        self.__dict__.update(d)

    def __delitem__(self, key):
        self.__dict__.__delitem__(key)

    def __getattr__(self, key):
        if self.__dict__.get(key) is None:
            self.__dict__[key] = self.__class__()

        return self.__dict__[key]

    def __setattr__(self, key, value):
        self.__dict__[key] = value

    def __delattr__(self, key):
        self.__dict__.pop(key, None)

    def __repr__(self):
        return str(self.__dict__)

    def __cmp__(self, rhs):
        raise TypeError('unorderable types')

    def __lt__(self, rhs):
        raise TypeError('unorderable types')

    def __gt__(self, rhs):
        raise TypeError('unorderable types')

    def __le__(self, rhs):
        raise TypeError('unorderable types')

    def __ge__(self, rhs):
        raise TypeError('unorderable types')

    def __eq__(self, rhs):
        if hasattr(rhs, '__dict__'):
            return self.__dict__ == rhs.__dict__

        return self.__dict__ == rhs

    def __ne__(self, rhs):
        return not self.__eq__(rhs)

    def __len__(self):
        return len(self.__dict__)


text:
"""
Calendar
========

This plugin provides one command, ``weeknum``, which simply echoes the current
week number in the channel.

Options
-------

- None
"""
from datetime import date
from lala.util import msg, command

@command
def weeknum(user, channel, text):
    """Echoes the current week number."""
    d = date.today()
    year, weeknum, weekday = d.isocalendar()
    msg(channel, "It's week #%i of the year %i." % (weeknum, year))


text:
import os
import unittest
from tidypage import Document

HTMLS = os.path.join(os.path.dirname(__file__), 'htmls')

class TestContentOnly(unittest.TestCase):
    def test_content_parser(self):
        html = open(os.path.join(HTMLS, "aleyna-tilki-basrol-oynamaya-hazirlaniyor.html")).read()
        doc = Document(html, True, "http://www.test.com/test.html")
        doc.content()


text:
package edu.sjsu.cmpe273.lab2;

import io.grpc.ChannelImpl;
import edu.sjsu.cmpe273.lab2.PollRequest;
import edu.sjsu.cmpe273.lab2.PollResponse;
import edu.sjsu.cmpe273.lab2.PollServiceGrpc;
import io.grpc.transport.netty.NegotiationType;
import io.grpc.transport.netty.NettyChannelBuilder;

import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * A simple client that requests a greeting from the {@link PollServer}.
 */
public class PollClient {
    private static final Logger logger = Logger.getLogger(PollClient.class.getName());

    private final ChannelImpl channel;
    private final PollServiceGrpc.PollServiceBlockingStub bs;

    public PollClient(String host, int port) {
        channel =
                NettyChannelBuilder.forAddress(host, port).negotiationType(NegotiationType.PLAINTEXT)
                        .build();

        bs = PollServiceGrpc.newBlockingStub(channel);
    }

    public void shutdown() throws InterruptedException {
        channel.shutdown().awaitTerminated(5, TimeUnit.SECONDS);
    }

    public void createPoll(String moderatorId, String question, String startedAt, String expiredAt, String[] choice) {
        try {
            logger.info("sending message");

            PollRequest a = PollRequest.newBuilder()
                    .setExpiredAt(expiredAt)
                    .setQuestion(question)
                    .setStartedAt(startedAt)
                    .addChoice(choice[0])
                    .addChoice(choice[1])
                    .setModeratorId(moderatorId)
                    .build();

            PollResponse poll_response = bs.createPoll(a);
            logger.info("-------------------------------------------------------");
            logger.info("-----------Client Here---------------------------------");
            logger.info("-------------------------------------------------------");
            logger.info("Created a new poll with id = " + poll_response.getId());
            logger.info("-------------------------------------------------------");
            logger.info("sent");
        } catch (RuntimeException e) {
            logger.log(Level.WARNING, "RPC failed", e);
            return;
        }

    }

    public static void main(String[] args) throws Exception {
        PollClient client = new PollClient("localhost", 8980);
        try {
      /* Access a service running on the local machine on port 50051 */
            String moderatorId = "12";
            String question = "What type of smartphone do you have?";
            String startedAt = "2015-03-18T13:00:00.000Z";
            String expiredAt = "2015-03-19T13:00:00.000Z";
            String[] choice = new String[]{"Android", "iPhone"};

            client.createPoll(moderatorId, question, startedAt, expiredAt, choice);

        } finally {
            client.shutdown();
        }
    }
}


text:
import re

import numpy as np
import scipy.sparse
import pytest

from sklearn.datasets import load_digits, load_iris

from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score

from sklearn.utils._testing import assert_almost_equal
from sklearn.utils._testing import assert_array_equal
from sklearn.utils._testing import assert_array_almost_equal
from sklearn.utils._testing import ignore_warnings

from sklearn.naive_bayes import GaussianNB, BernoulliNB
from sklearn.naive_bayes import MultinomialNB, ComplementNB
from sklearn.naive_bayes import CategoricalNB

DISCRETE_NAIVE_BAYES_CLASSES = [
    BernoulliNB, CategoricalNB, ComplementNB, MultinomialNB]
ALL_NAIVE_BAYES_CLASSES = DISCRETE_NAIVE_BAYES_CLASSES + [GaussianNB]

# Data is just 6 separable points in the plane
X = np.array([[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]])
y = np.array([1, 1, 1, 2, 2, 2])

# A bit more random tests
rng = np.random.RandomState(0)
X1 = rng.normal(size=(10, 3))
y1 = (rng.normal(size=(10)) > 0).astype(int)

# Data is 6 random integer points in a 100 dimensional space classified to
# three classes.
X2 = rng.randint(5, size=(6, 100))
y2 = np.array([1, 1, 2, 2, 3, 3])

def test_gnb():
    # Gaussian Naive Bayes classification.
    # This checks that GaussianNB implements fit and predict and returns
    # correct values for a simple toy dataset.

    clf = GaussianNB()
    y_pred = clf.fit(X, y).predict(X)
    assert_array_equal(y_pred, y)

    y_pred_proba = clf.predict_proba(X)
    y_pred_log_proba = clf.predict_log_proba(X)
    assert_array_almost_equal(np.log(y_pred_proba), y_pred_log_proba, 8)

    # Test whether label mismatch between target y and classes raises
    # an Error
    # FIXME Remove this test once the more general partial_fit tests are merged
    with pytest.raises(
        ValueError,
        match="The target label.* in y do not exist in the initial classes"
    ):
        GaussianNB().partial_fit(X, y, classes=[0, 1])

# TODO remove in 1.2 once sigma_ attribute is removed (GH #18842)
def test_gnb_var():
    clf = GaussianNB()
    clf.fit(X, y)

    with pytest.warns(FutureWarning, match="Attribute sigma_ was deprecated"):
        assert_array_equal(clf.sigma_, clf.var_)

def test_gnb_prior():
    # Test whether class priors are properly set.
    clf = GaussianNB().fit(X, y)
    assert_array_almost_equal(np.array([3, 3]) / 6.0,
                              clf.class_prior_, 8)
    clf = GaussianNB().fit(X1, y1)
    # Check that the class priors sum to 1
    assert_array_almost_equal(clf.class_prior_.sum(), 1)

def test_gnb_sample_weight():
    """Test whether sample weights are properly used in GNB. """
    # Sample weights all being 1 should not change results
    sw = np.ones(6)
    clf = GaussianNB().fit(X, y)
    clf_sw = GaussianNB().fit(X, y, sw)

    assert_array_almost_equal(clf.theta_, clf_sw.theta_)
    assert_array_almost_equal(clf.var_, clf_sw.var_)

    # Fitting twice with half sample-weights should result
    # in same result as fitting once with full weights
    sw = rng.rand(y.shape[0])
    clf1 = GaussianNB().fit(X, y, sample_weight=sw)
    clf2 = GaussianNB().partial_fit(X, y, classes=[1, 2], sample_weight=sw / 2)
    clf2.partial_fit(X, y, sample_weight=sw / 2)

    assert_array_almost_equal(clf1.theta_, clf2.theta_)
    assert_array_almost_equal(clf1.var_, clf2.var_)

    # Check that duplicate entries and correspondingly increased sample
    # weights yield the same result
    ind = rng.randint(0, X.shape[0], 20)
    sample_weight = np.bincount(ind, minlength=X.shape[0])

    clf_dupl = GaussianNB().fit(X[ind], y[ind])
    clf_sw = GaussianNB().fit(X, y, sample_weight)

    assert_array_almost_equal(clf_dupl.theta_, clf_sw.theta_)
    assert_array_almost_equal(clf_dupl.var_, clf_sw.var_)

def test_gnb_neg_priors():
    """Test whether an error is raised in case of negative priors"""
    clf = GaussianNB(priors=np.array([-1., 2.]))

    msg = 'Priors must be non-negative'
    with pytest.raises(ValueError, match=msg):
        clf.fit(X, y)

def test_gnb_priors():
    """Test whether the class prior override is properly used"""
    clf = GaussianNB(priors=np.array([0.3, 0.7])).fit(X, y)
    assert_array_almost_equal(clf.predict_proba([[-0.1, -0.1]]),
                              np.array([[0.825303662161683,
                                         0.174696337838317]]), 8)
    assert_array_almost_equal(clf.class_prior_, np.array([0.3, 0.7]))

def test_gnb_priors_sum_isclose():
    # test whether the class prior sum is properly tested"""
    X = np.array([[-1, -1], [-2, -1], [-3, -2], [-4, -5], [-5, -4],
                  [1, 1], [2, 1], [3, 2], [4, 4], [5, 5]])
    priors = np.array([0.08, 0.14, 0.03, 0.16, 0.11, 0.16, 0.07, 0.14,
                       0.11, 0.0])
    Y = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
    clf = GaussianNB(priors=priors)
    # smoke test for issue #9633
    clf.fit(X, Y)

def test_gnb_wrong_nb_priors():
    """ Test whether an error is raised if the number of prior is different
    from the number of class"""
    clf = GaussianNB(priors=np.array([.25, .25, .25, .25]))

    msg = 'Number of priors must match number of classes'
    with pytest.raises(ValueError, match=msg):
        clf.fit(X, y)

def test_gnb_prior_greater_one():
    """Test if an error is raised if the sum of prior greater than one"""
    clf = GaussianNB(priors=np.array([2., 1.]))

    msg = 'The sum of the priors should be 1'
    with pytest.raises(ValueError, match=msg):
        clf.fit(X, y)

def test_gnb_prior_large_bias():
    """Test if good prediction when class prior favor largely one class"""
    clf = GaussianNB(priors=np.array([0.01, 0.99]))
    clf.fit(X, y)
    assert clf.predict([[-0.1, -0.1]]) == np.array([2])

def test_gnb_check_update_with_no_data():
    """ Test when the partial fit is called without any data"""
    # Create an empty array
    prev_points = 100
    mean = 0.
    var = 1.
    x_empty = np.empty((0, X.shape[1]))
    tmean, tvar = GaussianNB._update_mean_variance(prev_points, mean,
                                                   var, x_empty)
    assert tmean == mean
    assert tvar == var

def test_gnb_partial_fit():
    clf = GaussianNB().fit(X, y)
    clf_pf = GaussianNB().partial_fit(X, y, np.unique(y))
    assert_array_almost_equal(clf.theta_, clf_pf.theta_)
    assert_array_almost_equal(clf.var_, clf_pf.var_)
    assert_array_almost_equal(clf.class_prior_, clf_pf.class_prior_)

    clf_pf2 = GaussianNB().partial_fit(X[0::2, :], y[0::2], np.unique(y))
    clf_pf2.partial_fit(X[1::2], y[1::2])
    assert_array_almost_equal(clf.theta_, clf_pf2.theta_)
    assert_array_almost_equal(clf.var_, clf_pf2.var_)
    assert_array_almost_equal(clf.class_prior_, clf_pf2.class_prior_)

def test_gnb_naive_bayes_scale_invariance():
    # Scaling the data should not change the prediction results
    iris = load_iris()
    X, y = iris.data, iris.target
    labels = [GaussianNB().fit(f * X, y).predict(f * X)
              for f in [1E-10, 1, 1E10]]
    assert_array_equal(labels[0], labels[1])
    assert_array_equal(labels[1], labels[2])

# TODO: Remove in version 1.1
@pytest.mark.parametrize('DiscreteNaiveBayes', DISCRETE_NAIVE_BAYES_CLASSES)
def test_discretenb_deprecated_coef_intercept(DiscreteNaiveBayes):
    est = DiscreteNaiveBayes().fit(X2, y2)

    for att in ["coef_", "intercept_"]:
        with pytest.warns(FutureWarning):
            hasattr(est, att)

@pytest.mark.parametrize('DiscreteNaiveBayes', DISCRETE_NAIVE_BAYES_CLASSES)
def test_discretenb_prior(DiscreteNaiveBayes):
    # Test whether class priors are properly set.
    clf = DiscreteNaiveBayes().fit(X2, y2)
    assert_array_almost_equal(np.log(np.array([2, 2, 2]) / 6.0),
                              clf.class_log_prior_, 8)

@pytest.mark.parametrize('DiscreteNaiveBayes', DISCRETE_NAIVE_BAYES_CLASSES)
def test_discretenb_partial_fit(DiscreteNaiveBayes):
    clf1 = DiscreteNaiveBayes()
    clf1.fit([[0, 1], [1, 0], [1, 1]], [0, 1, 1])

    clf2 = DiscreteNaiveBayes()
    clf2.partial_fit([[0, 1], [1, 0], [1, 1]], [0, 1, 1], classes=[0, 1])
    assert_array_equal(clf1.class_count_, clf2.class_count_)
    if DiscreteNaiveBayes is CategoricalNB:
        for i in range(len(clf1.category_count_)):
            assert_array_equal(clf1.category_count_[i],
                               clf2.category_count_[i])
    else:
        assert_array_equal(clf1.feature_count_, clf2.feature_count_)

    clf3 = DiscreteNaiveBayes()
    # all categories have to appear in the first partial fit
    clf3.partial_fit([[0, 1]], [0], classes=[0, 1])
    clf3.partial_fit([[1, 0]], [1])
    clf3.partial_fit([[1, 1]], [1])
    assert_array_equal(clf1.class_count_, clf3.class_count_)
    if DiscreteNaiveBayes is CategoricalNB:
        # the categories for each feature of CategoricalNB are mapped to an
        # index chronologically with each call of partial fit and therefore
        # the category_count matrices cannot be compared for equality
        for i in range(len(clf1.category_count_)):
            assert_array_equal(clf1.category_count_[i].shape,
                               clf3.category_count_[i].shape)
            assert_array_equal(np.sum(clf1.category_count_[i], axis=1),
                               np.sum(clf3.category_count_[i], axis=1))

        # assert category 0 occurs 1x in the first class and 0x in the 2nd
        # class
        assert_array_equal(clf1.category_count_[0][0], np.array([1, 0]))
        # assert category 1 occurs 0x in the first class and 2x in the 2nd
        # class
        assert_array_equal(clf1.category_count_[0][1], np.array([0, 2]))

        # assert category 0 occurs 0x in the first class and 1x in the 2nd
        # class
        assert_array_equal(clf1.category_count_[1][0], np.array([0, 1]))
        # assert category 1 occurs 1x in the first class and 1x in the 2nd
        # class
        assert_array_equal(clf1.category_count_[1][1], np.array([1, 1]))
    else:
        assert_array_equal(clf1.feature_count_, clf3.feature_count_)

@pytest.mark.parametrize('NaiveBayes', ALL_NAIVE_BAYES_CLASSES)
def test_NB_partial_fit_no_first_classes(NaiveBayes):
    # classes is required for first call to partial fit
    with pytest.raises(
        ValueError,
        match="classes must be passed on the first call to partial_fit."
    ):
        NaiveBayes().partial_fit(X2, y2)

    # check consistency of consecutive classes values
    clf = NaiveBayes()
    clf.partial_fit(X2, y2, classes=np.unique(y2))
    with pytest.raises(
        ValueError,
        match="is not the same as on last call to partial_fit"
    ):
        clf.partial_fit(X2, y2, classes=np.arange(42))

# TODO: Remove in version 1.1
@ignore_warnings(category=FutureWarning)
def test_discretenb_predict_proba():
    # Test discrete NB classes' probability scores

    # The 100s below distinguish Bernoulli from multinomial.
    # FIXME: write a test to show this.
    X_bernoulli = [[1, 100, 0], [0, 1, 0], [0, 100, 1]]
    X_multinomial = [[0, 1], [1, 3], [4, 0]]

    # test binary case (1-d output)
    y = [0, 0, 2]  # 2 is regression test for binary case, 02e673
    for DiscreteNaiveBayes, X in zip([BernoulliNB, MultinomialNB],
                                     [X_bernoulli, X_multinomial]):
        clf = DiscreteNaiveBayes().fit(X, y)
        assert clf.predict(X[-1:]) == 2
        assert clf.predict_proba([X[0]]).shape == (1, 2)
        assert_array_almost_equal(clf.predict_proba(X[:2]).sum(axis=1),
                                  np.array([1., 1.]), 6)

    # test multiclass case (2-d output, must sum to one)
    y = [0, 1, 2]
    for DiscreteNaiveBayes, X in zip([BernoulliNB, MultinomialNB],
                                     [X_bernoulli, X_multinomial]):
        clf = DiscreteNaiveBayes().fit(X, y)
        assert clf.predict_proba(X[0:1]).shape == (1, 3)
        assert clf.predict_proba(X[:2]).shape == (2, 3)
        assert_almost_equal(np.sum(clf.predict_proba([X[1]])), 1)
        assert_almost_equal(np.sum(clf.predict_proba([X[-1]])), 1)
        assert_almost_equal(np.sum(np.exp(clf.class_log_prior_)), 1)
        assert_almost_equal(np.sum(np.exp(clf.intercept_)), 1)

@pytest.mark.parametrize('DiscreteNaiveBayes', DISCRETE_NAIVE_BAYES_CLASSES)
def test_discretenb_uniform_prior(DiscreteNaiveBayes):
    # Test whether discrete NB classes fit a uniform prior
    # when fit_prior=False and class_prior=None

    clf = DiscreteNaiveBayes()
    clf.set_params(fit_prior=False)
    clf.fit([[0], [0], [1]], [0, 0, 1])
    prior = np.exp(clf.class_log_prior_)
    assert_array_almost_equal(prior, np.array([.5, .5]))

@pytest.mark.parametrize('DiscreteNaiveBayes', DISCRETE_NAIVE_BAYES_CLASSES)
def test_discretenb_provide_prior(DiscreteNaiveBayes):
    # Test whether discrete NB classes use provided prior

    clf = DiscreteNaiveBayes(class_prior=[0.5, 0.5])
    clf.fit([[0], [0], [1]], [0, 0, 1])
    prior = np.exp(clf.class_log_prior_)
    assert_array_almost_equal(prior, np.array([.5, .5]))

    # Inconsistent number of classes with prior
    msg = 'Number of priors must match number of classes'
    with pytest.raises(ValueError, match=msg):
        clf.fit([[0], [1], [2]], [0, 1, 2])

    msg = 'is not the same as on last call to partial_fit'
    with pytest.raises(ValueError, match=msg):
        clf.partial_fit([[0], [1]], [0, 1], classes=[0, 1, 1])

@pytest.mark.parametrize('DiscreteNaiveBayes', DISCRETE_NAIVE_BAYES_CLASSES)
def test_discretenb_provide_prior_with_partial_fit(DiscreteNaiveBayes):
    # Test whether discrete NB classes use provided prior
    # when using partial_fit

    iris = load_iris()
    iris_data1, iris_data2, iris_target1, iris_target2 = train_test_split(
        iris.data, iris.target, test_size=0.4, random_state=415)

    for prior in [None, [0.3, 0.3, 0.4]]:
        clf_full = DiscreteNaiveBayes(class_prior=prior)
        clf_full.fit(iris.data, iris.target)
        clf_partial = DiscreteNaiveBayes(class_prior=prior)
        clf_partial.partial_fit(iris_data1, iris_target1,
                                classes=[0, 1, 2])
        clf_partial.partial_fit(iris_data2, iris_target2)
        assert_array_almost_equal(clf_full.class_log_prior_,
                                  clf_partial.class_log_prior_)

@pytest.mark.parametrize('DiscreteNaiveBayes', DISCRETE_NAIVE_BAYES_CLASSES)
def test_discretenb_sample_weight_multiclass(DiscreteNaiveBayes):
    # check shape consistency for number of samples at fit time
    X = [
        [0, 0, 1],
        [0, 1, 1],
        [0, 1, 1],
        [1, 0, 0],
    ]
    y = [0, 0, 1, 2]
    sample_weight = np.array([1, 1, 2, 2], dtype=np.float64)
    sample_weight /= sample_weight.sum()
    clf = DiscreteNaiveBayes().fit(X, y, sample_weight=sample_weight)
    assert_array_equal(clf.predict(X), [0, 1, 1, 2])

    # Check sample weight using the partial_fit method
    clf = DiscreteNaiveBayes()
    clf.partial_fit(X[:2], y[:2], classes=[0, 1, 2],
                    sample_weight=sample_weight[:2])
    clf.partial_fit(X[2:3], y[2:3], sample_weight=sample_weight[2:3])
    clf.partial_fit(X[3:], y[3:], sample_weight=sample_weight[3:])
    assert_array_equal(clf.predict(X), [0, 1, 1, 2])

# TODO: Remove in version 1.1
@ignore_warnings(category=FutureWarning)
@pytest.mark.parametrize('DiscreteNaiveBayes', [BernoulliNB, ComplementNB,
                                                MultinomialNB])
def test_discretenb_coef_intercept_shape(DiscreteNaiveBayes):
    # coef_ and intercept_ should have shapes as in other linear models.
    # Non-regression test for issue #2127.
    X = [[1, 0, 0], [1, 1, 1]]
    y = [1, 2]  # binary classification
    clf = DiscreteNaiveBayes()

    clf.fit(X, y)
    assert clf.coef_.shape == (1, 3)
    assert clf.intercept_.shape == (1,)

@pytest.mark.parametrize('DiscreteNaiveBayes', DISCRETE_NAIVE_BAYES_CLASSES)
@pytest.mark.parametrize('use_partial_fit', [False, True])
@pytest.mark.parametrize('train_on_single_class_y', [False, True])
def test_discretenb_degenerate_one_class_case(
        DiscreteNaiveBayes,
        use_partial_fit,
        train_on_single_class_y,
):
    # Most array attributes of a discrete naive Bayes classifier should have a
    # first-axis length equal to the number of classes. Exceptions include:
    # ComplementNB.feature_all_, CategoricalNB.n_categories_.
    # Confirm that this is the case for binary problems and the degenerate
    # case of a single class in the training set, when fitting with `fit` or
    # `partial_fit`.
    # Non-regression test for handling degenerate one-class case:
    # https://github.com/scikit-learn/scikit-learn/issues/18974

    X = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
    y = [1, 1, 2]
    if train_on_single_class_y:
        X = X[:-1]
        y = y[:-1]
    classes = sorted(list(set(y)))
    num_classes = len(classes)

    clf = DiscreteNaiveBayes()
    if use_partial_fit:
        clf.partial_fit(X, y, classes=classes)
    else:
        clf.fit(X, y)
    assert clf.predict(X[:1]) == y[0]

    # Check that attributes have expected first-axis lengths
    attribute_names = [
        'classes_',
        'class_count_',
        'class_log_prior_',
        'feature_count_',
        'feature_log_prob_',
    ]
    for attribute_name in attribute_names:
        attribute = getattr(clf, attribute_name, None)
        if attribute is None:
            # CategoricalNB has no feature_count_ attribute
            continue
        if isinstance(attribute, np.ndarray):
            assert attribute.shape[0] == num_classes
        else:
            # CategoricalNB.feature_log_prob_ is a list of arrays
            for element in attribute:
                assert element.shape[0] == num_classes

@pytest.mark.parametrize('kind', ('dense', 'sparse'))
def test_mnnb(kind):
    # Test Multinomial Naive Bayes classification.
    # This checks that MultinomialNB implements fit and predict and returns
    # correct values for a simple toy dataset.

    if kind == 'dense':
        X = X2
    elif kind == 'sparse':
        X = scipy.sparse.csr_matrix(X2)

    # Check the ability to predict the learning set.
    clf = MultinomialNB()

    msg = 'Negative values in data passed to'
    with pytest.raises(ValueError, match=msg):
        clf.fit(-X, y2)
    y_pred = clf.fit(X, y2).predict(X)

    assert_array_equal(y_pred, y2)

    # Verify that np.log(clf.predict_proba(X)) gives the same results as
    # clf.predict_log_proba(X)
    y_pred_proba = clf.predict_proba(X)
    y_pred_log_proba = clf.predict_log_proba(X)
    assert_array_almost_equal(np.log(y_pred_proba), y_pred_log_proba, 8)

    # Check that incremental fitting yields the same results
    clf2 = MultinomialNB()
    clf2.partial_fit(X[:2], y2[:2], classes=np.unique(y2))
    clf2.partial_fit(X[2:5], y2[2:5])
    clf2.partial_fit(X[5:], y2[5:])

    y_pred2 = clf2.predict(X)
    assert_array_equal(y_pred2, y2)

    y_pred_proba2 = clf2.predict_proba(X)
    y_pred_log_proba2 = clf2.predict_log_proba(X)
    assert_array_almost_equal(np.log(y_pred_proba2), y_pred_log_proba2, 8)
    assert_array_almost_equal(y_pred_proba2, y_pred_proba)
    assert_array_almost_equal(y_pred_log_proba2, y_pred_log_proba)

    # Partial fit on the whole data at once should be the same as fit too
    clf3 = MultinomialNB()
    clf3.partial_fit(X, y2, classes=np.unique(y2))

    y_pred3 = clf3.predict(X)
    assert_array_equal(y_pred3, y2)
    y_pred_proba3 = clf3.predict_proba(X)
    y_pred_log_proba3 = clf3.predict_log_proba(X)
    assert_array_almost_equal(np.log(y_pred_proba3), y_pred_log_proba3, 8)
    assert_array_almost_equal(y_pred_proba3, y_pred_proba)
    assert_array_almost_equal(y_pred_log_proba3, y_pred_log_proba)

def test_mnb_prior_unobserved_targets():
    # test smoothing of prior for yet unobserved targets

    # Create toy training data
    X = np.array([[0, 1], [1, 0]])
    y = np.array([0, 1])

    clf = MultinomialNB()

    with pytest.warns(None) as record:
        clf.partial_fit(X, y, classes=[0, 1, 2])
    assert len(record) == 0

    assert clf.predict([[0, 1]]) == 0
    assert clf.predict([[1, 0]]) == 1
    assert clf.predict([[1, 1]]) == 0

    # add a training example with previously unobserved class
    with pytest.warns(None) as record:
        clf.partial_fit([[1, 1]], [2])
    assert len(record) == 0

    assert clf.predict([[0, 1]]) == 0
    assert clf.predict([[1, 0]]) == 1
    assert clf.predict([[1, 1]]) == 2

# TODO: Remove in version 1.1
@ignore_warnings(category=FutureWarning)
def test_mnb_sample_weight():
    clf = MultinomialNB()
    clf.fit([[1, 2], [1, 2], [1, 0]],
            [0, 0, 1],
            sample_weight=[1, 1, 4])
    assert_array_equal(clf.predict([[1, 0]]), [1])
    positive_prior = np.exp(clf.intercept_[0])
    assert_array_almost_equal([1 - positive_prior, positive_prior],
                              [1 / 3., 2 / 3.])

def test_bnb():
    # Tests that BernoulliNB when alpha=1.0 gives the same values as
    # those given for the toy example in Manning, Raghavan, and
    # Schuetze's "Introduction to Information Retrieval" book:
    # https://nlp.stanford.edu/IR-book/html/htmledition/the-bernoulli-model-1.html

    # Training data points are:
    # Chinese Beijing Chinese (class: China)
    # Chinese Chinese Shanghai (class: China)
    # Chinese Macao (class: China)
    # Tokyo Japan Chinese (class: Japan)

    # Features are Beijing, Chinese, Japan, Macao, Shanghai, and Tokyo
    X = np.array([[1, 1, 0, 0, 0, 0],
                  [0, 1, 0, 0, 1, 0],
                  [0, 1, 0, 1, 0, 0],
                  [0, 1, 1, 0, 0, 1]])

    # Classes are China (0), Japan (1)
    Y = np.array([0, 0, 0, 1])

    # Fit BernoulliBN w/ alpha = 1.0
    clf = BernoulliNB(alpha=1.0)
    clf.fit(X, Y)

    # Check the class prior is correct
    class_prior = np.array([0.75, 0.25])
    assert_array_almost_equal(np.exp(clf.class_log_prior_), class_prior)

    # Check the feature probabilities are correct
    feature_prob = np.array([[0.4, 0.8, 0.2, 0.4, 0.4, 0.2],
                             [1 / 3.0, 2 / 3.0, 2 / 3.0, 1 / 3.0, 1 / 3.0,
                              2 / 3.0]])
    assert_array_almost_equal(np.exp(clf.feature_log_prob_), feature_prob)

    # Testing data point is:
    # Chinese Chinese Chinese Tokyo Japan
    X_test = np.array([[0, 1, 1, 0, 0, 1]])

    # Check the predictive probabilities are correct
    unnorm_predict_proba = np.array([[0.005183999999999999,
                                      0.02194787379972565]])
    predict_proba = unnorm_predict_proba / np.sum(unnorm_predict_proba)
    assert_array_almost_equal(clf.predict_proba(X_test), predict_proba)

def test_bnb_feature_log_prob():
    # Test for issue #4268.
    # Tests that the feature log prob value computed by BernoulliNB when
    # alpha=1.0 is equal to the expression given in Manning, Raghavan,
    # and Schuetze's "Introduction to Information Retrieval" book:
    # http://nlp.stanford.edu/IR-book/html/htmledition/the-bernoulli-model-1.html

    X = np.array([[0, 0, 0], [1, 1, 0], [0, 1, 0], [1, 0, 1], [0, 1, 0]])
    Y = np.array([0, 0, 1, 2, 2])

    # Fit Bernoulli NB w/ alpha = 1.0
    clf = BernoulliNB(alpha=1.0)
    clf.fit(X, Y)

    # Manually form the (log) numerator and denominator that
    # constitute P(feature presence | class)
    num = np.log(clf.feature_count_ + 1.0)
    denom = np.tile(np.log(clf.class_count_ + 2.0), (X.shape[1], 1)).T

    # Check manual estimate matches
    assert_array_almost_equal(clf.feature_log_prob_, (num - denom))

def test_cnb():
    # Tests ComplementNB when alpha=1.0 for the toy example in Manning,
    # Raghavan, and Schuetze's "Introduction to Information Retrieval" book:
    # https://nlp.stanford.edu/IR-book/html/htmledition/the-bernoulli-model-1.html

    # Training data points are:
    # Chinese Beijing Chinese (class: China)
    # Chinese Chinese Shanghai (class: China)
    # Chinese Macao (class: China)
    # Tokyo Japan Chinese (class: Japan)

    # Features are Beijing, Chinese, Japan, Macao, Shanghai, and Tokyo.
    X = np.array([[1, 1, 0, 0, 0, 0],
                  [0, 1, 0, 0, 1, 0],
                  [0, 1, 0, 1, 0, 0],
                  [0, 1, 1, 0, 0, 1]])

    # Classes are China (0), Japan (1).
    Y = np.array([0, 0, 0, 1])

    # Check that weights are correct. See steps 4-6 in Table 4 of
    # Rennie et al. (2003).
    theta = np.array([
        [
            (0 + 1) / (3 + 6),
            (1 + 1) / (3 + 6),
            (1 + 1) / (3 + 6),
            (0 + 1) / (3 + 6),
            (0 + 1) / (3 + 6),
            (1 + 1) / (3 + 6)
        ],
        [
            (1 + 1) / (6 + 6),
            (3 + 1) / (6 + 6),
            (0 + 1) / (6 + 6),
            (1 + 1) / (6 + 6),
            (1 + 1) / (6 + 6),
            (0 + 1) / (6 + 6)
        ]])

    weights = np.zeros(theta.shape)
    normed_weights = np.zeros(theta.shape)
    for i in range(2):
        weights[i] = -np.log(theta[i])
        normed_weights[i] = weights[i] / weights[i].sum()

    # Verify inputs are nonnegative.
    clf = ComplementNB(alpha=1.0)

    msg = re.escape('Negative values in data passed to ComplementNB (input X)')
    with pytest.raises(ValueError, match=msg):
        clf.fit(-X, Y)

    clf.fit(X, Y)

    # Check that counts/weights are correct.
    feature_count = np.array([[1, 3, 0, 1, 1, 0], [0, 1, 1, 0, 0, 1]])
    assert_array_equal(clf.feature_count_, feature_count)
    class_count = np.array([3, 1])
    assert_array_equal(clf.class_count_, class_count)
    feature_all = np.array([1, 4, 1, 1, 1, 1])
    assert_array_equal(clf.feature_all_, feature_all)
    assert_array_almost_equal(clf.feature_log_prob_, weights)

    clf = ComplementNB(alpha=1.0, norm=True)
    clf.fit(X, Y)
    assert_array_almost_equal(clf.feature_log_prob_, normed_weights)

def test_categoricalnb():
    # Check the ability to predict the training set.
    clf = CategoricalNB()
    y_pred = clf.fit(X2, y2).predict(X2)
    assert_array_equal(y_pred, y2)

    X3 = np.array([[1, 4], [2, 5]])
    y3 = np.array([1, 2])
    clf = CategoricalNB(alpha=1, fit_prior=False)

    clf.fit(X3, y3)
    assert_array_equal(clf.n_categories_, np.array([3, 6]))

    # Check error is raised for X with negative entries
    X = np.array([[0, -1]])
    y = np.array([1])
    error_msg = re.escape(
        "Negative values in data passed to CategoricalNB (input X)"
    )
    with pytest.raises(ValueError, match=error_msg):
        clf.predict(X)
    with pytest.raises(ValueError, match=error_msg):
        clf.fit(X, y)

    # Test alpha
    X3_test = np.array([[2, 5]])
    # alpha=1 increases the count of all categories by one so the final
    # probability for each category is not 50/50 but 1/3 to 2/3
    bayes_numerator = np.array([[1/3*1/3, 2/3*2/3]])
    bayes_denominator = bayes_numerator.sum()
    assert_array_almost_equal(clf.predict_proba(X3_test),
                              bayes_numerator / bayes_denominator)

    # Assert category_count has counted all features
    assert len(clf.category_count_) == X3.shape[1]

    # Check sample_weight
    X = np.array([[0, 0], [0, 1], [0, 0], [1, 1]])
    y = np.array([1, 1, 2, 2])
    clf = CategoricalNB(alpha=1, fit_prior=False)
    clf.fit(X, y)
    assert_array_equal(clf.predict(np.array([[0, 0]])), np.array([1]))
    assert_array_equal(clf.n_categories_, np.array([2, 2]))

    for factor in [1., 0.3, 5, 0.0001]:
        X = np.array([[0, 0], [0, 1], [0, 0], [1, 1]])
        y = np.array([1, 1, 2, 2])
        sample_weight = np.array([1, 1, 10, 0.1]) * factor
        clf = CategoricalNB(alpha=1, fit_prior=False)
        clf.fit(X, y, sample_weight=sample_weight)
        assert_array_equal(clf.predict(np.array([[0, 0]])), np.array([2]))
        assert_array_equal(clf.n_categories_, np.array([2, 2]))

@pytest.mark.parametrize(
    "min_categories, exp_X1_count, exp_X2_count, new_X, exp_n_categories_",
    [
        # check min_categories with int > observed categories
        (3, np.array([[2, 0, 0], [1, 1, 0]]), np.array([[1, 1, 0], [1, 1, 0]]),
         np.array([[0, 2]]), np.array([3, 3]),
         ),
        # check with list input
        ([3, 4], np.array([[2, 0, 0], [1, 1, 0]]),
         np.array([[1, 1, 0, 0], [1, 1, 0, 0]]), np.array([[0, 3]]),
         np.array([3, 4]),
         ),
        # check min_categories with min less than actual
        ([1, np.array([[2, 0], [1, 1]]), np.array([[1, 1], [1, 1]]),
          np.array([[0, 1]]), np.array([2, 2])]
         ),
    ]
)
def test_categoricalnb_with_min_categories(min_categories, exp_X1_count,
                                           exp_X2_count, new_X,
                                           exp_n_categories_):
    X_n_categories = np.array([[0, 0], [0, 1], [0, 0], [1, 1]])
    y_n_categories = np.array([1, 1, 2, 2])
    expected_prediction = np.array([1])

    clf = CategoricalNB(alpha=1, fit_prior=False,
                        min_categories=min_categories)
    clf.fit(X_n_categories, y_n_categories)
    X1_count, X2_count = clf.category_count_
    assert_array_equal(X1_count, exp_X1_count)
    assert_array_equal(X2_count, exp_X2_count)
    predictions = clf.predict(new_X)
    assert_array_equal(predictions, expected_prediction)
    assert_array_equal(clf.n_categories_, exp_n_categories_)

@pytest.mark.parametrize(
    "min_categories, error_msg",
    [
        ('bad_arg', "'min_categories' should have integral"),
        ([[3, 2], [2, 4]], "'min_categories' should have shape"),
        (1., "'min_categories' should have integral"),
     ]
)
def test_categoricalnb_min_categories_errors(min_categories, error_msg):

    X = np.array([[0, 0], [0, 1], [0, 0], [1, 1]])
    y = np.array([1, 1, 2, 2])

    clf = CategoricalNB(alpha=1, fit_prior=False,
                        min_categories=min_categories)
    with pytest.raises(ValueError, match=error_msg):
        clf.fit(X, y)

def test_alpha():
    # Setting alpha=0 should not output nan results when p(x_i|y_j)=0 is a case
    X = np.array([[1, 0], [1, 1]])
    y = np.array([0, 1])
    nb = BernoulliNB(alpha=0.)
    msg = (
        "alpha too small will result in numeric errors,"
        " setting alpha = 1.0e-10"
    )
    with pytest.warns(UserWarning, match=msg):
        nb.partial_fit(X, y, classes=[0, 1])
    with pytest.warns(UserWarning, match=msg):
        nb.fit(X, y)
    prob = np.array([[1, 0], [0, 1]])
    assert_array_almost_equal(nb.predict_proba(X), prob)

    nb = MultinomialNB(alpha=0.)
    with pytest.warns(UserWarning, match=msg):
        nb.partial_fit(X, y, classes=[0, 1])
    with pytest.warns(UserWarning, match=msg):
        nb.fit(X, y)
    prob = np.array([[2. / 3, 1. / 3], [0, 1]])
    assert_array_almost_equal(nb.predict_proba(X), prob)

    nb = CategoricalNB(alpha=0.)
    with pytest.warns(UserWarning, match=msg):
        nb.fit(X, y)
    prob = np.array([[1., 0.], [0., 1.]])
    assert_array_almost_equal(nb.predict_proba(X), prob)

    # Test sparse X
    X = scipy.sparse.csr_matrix(X)
    nb = BernoulliNB(alpha=0.)
    with pytest.warns(UserWarning, match=msg):
        nb.fit(X, y)
    prob = np.array([[1, 0], [0, 1]])
    assert_array_almost_equal(nb.predict_proba(X), prob)

    nb = MultinomialNB(alpha=0.)
    with pytest.warns(UserWarning, match=msg):
        nb.fit(X, y)
    prob = np.array([[2. / 3, 1. / 3], [0, 1]])
    assert_array_almost_equal(nb.predict_proba(X), prob)

    # Test for alpha < 0
    X = np.array([[1, 0], [1, 1]])
    y = np.array([0, 1])
    expected_msg = re.escape(
        'Smoothing parameter alpha = -1.0e-01. alpha should be > 0.'
    )
    b_nb = BernoulliNB(alpha=-0.1)
    m_nb = MultinomialNB(alpha=-0.1)
    c_nb = CategoricalNB(alpha=-0.1)
    with pytest.raises(ValueError, match=expected_msg):
        b_nb.fit(X, y)
    with pytest.raises(ValueError, match=expected_msg):
        m_nb.fit(X, y)
    with pytest.raises(ValueError, match=expected_msg):
        c_nb.fit(X, y)

    b_nb = BernoulliNB(alpha=-0.1)
    m_nb = MultinomialNB(alpha=-0.1)
    with pytest.raises(ValueError, match=expected_msg):
        b_nb.partial_fit(X, y, classes=[0, 1])
    with pytest.raises(ValueError, match=expected_msg):
        m_nb.partial_fit(X, y, classes=[0, 1])

def test_alpha_vector():
    X = np.array([[1, 0], [1, 1]])
    y = np.array([0, 1])

    # Setting alpha=np.array with same length
    # as number of features should be fine
    alpha = np.array([1, 2])
    nb = MultinomialNB(alpha=alpha)
    nb.partial_fit(X, y, classes=[0, 1])

    # Test feature probabilities uses pseudo-counts (alpha)
    feature_prob = np.array([[1 / 2, 1 / 2], [2 / 5, 3 / 5]])
    assert_array_almost_equal(nb.feature_log_prob_, np.log(feature_prob))

    # Test predictions
    prob = np.array([[5 / 9, 4 / 9], [25 / 49, 24 / 49]])
    assert_array_almost_equal(nb.predict_proba(X), prob)

    # Test alpha non-negative
    alpha = np.array([1., -0.1])
    m_nb = MultinomialNB(alpha=alpha)
    expected_msg = (
        'Smoothing parameter alpha = -1.0e-01. alpha should be > 0.'
    )
    with pytest.raises(ValueError, match=expected_msg):
        m_nb.fit(X, y)

    # Test that too small pseudo-counts are replaced
    ALPHA_MIN = 1e-10
    alpha = np.array([ALPHA_MIN / 2, 0.5])
    m_nb = MultinomialNB(alpha=alpha)
    m_nb.partial_fit(X, y, classes=[0, 1])
    assert_array_almost_equal(m_nb._check_alpha(),
                              [ALPHA_MIN, 0.5],
                              decimal=12)

    # Test correct dimensions
    alpha = np.array([1., 2., 3.])
    m_nb = MultinomialNB(alpha=alpha)
    expected_msg = re.escape(
        'alpha should be a scalar or a numpy array with shape [n_features]'
    )
    with pytest.raises(ValueError, match=expected_msg):
        m_nb.fit(X, y)

def test_check_accuracy_on_digits():
    # Non regression test to make sure that any further refactoring / optim
    # of the NB models do not harm the performance on a slightly non-linearly
    # separable dataset
    X, y = load_digits(return_X_y=True)
    binary_3v8 = np.logical_or(y == 3, y == 8)
    X_3v8, y_3v8 = X[binary_3v8], y[binary_3v8]

    # Multinomial NB
    scores = cross_val_score(MultinomialNB(alpha=10), X, y, cv=10)
    assert scores.mean() > 0.86

    scores = cross_val_score(MultinomialNB(alpha=10), X_3v8, y_3v8, cv=10)
    assert scores.mean() > 0.94

    # Bernoulli NB
    scores = cross_val_score(BernoulliNB(alpha=10), X > 4, y, cv=10)
    assert scores.mean() > 0.83

    scores = cross_val_score(BernoulliNB(alpha=10), X_3v8 > 4, y_3v8, cv=10)
    assert scores.mean() > 0.92

    # Gaussian NB
    scores = cross_val_score(GaussianNB(), X, y, cv=10)
    assert scores.mean() > 0.77

    scores = cross_val_score(GaussianNB(var_smoothing=0.1), X, y, cv=10)
    assert scores.mean() > 0.89

    scores = cross_val_score(GaussianNB(), X_3v8, y_3v8, cv=10)
    assert scores.mean() > 0.86

# FIXME: remove in 1.2
@pytest.mark.parametrize("Estimator", DISCRETE_NAIVE_BAYES_CLASSES)
def test_n_features_deprecation(Estimator):
    # Check that we raise the proper deprecation warning if accessing
    # `n_features_`.
    X = np.array([[1, 2], [3, 4]])
    y = np.array([1, 0])
    est = Estimator().fit(X, y)

    with pytest.warns(FutureWarning, match="n_features_ was deprecated"):
        est.n_features_


text:
package org.apache.pulsar.common.policies.data;

import static org.apache.pulsar.common.policies.data.PoliciesUtil.defaultBundle;
import lombok.EqualsAndHashCode;
import lombok.ToString;

/**
 * Local policies.
 */
@ToString
@EqualsAndHashCode
public class LocalPolicies {

    public final BundlesData bundles;
    // bookie affinity group for bookie-isolation
    public final BookieAffinityGroupData bookieAffinityGroup;
    // namespace anti-affinity-group
    public final String namespaceAntiAffinityGroup;

    public LocalPolicies() {
        bundles = defaultBundle();
        bookieAffinityGroup = null;
        namespaceAntiAffinityGroup = null;
    }

    public LocalPolicies(BundlesData data,
                         BookieAffinityGroupData bookieAffinityGroup,
                         String namespaceAntiAffinityGroup) {
        bundles = data;
        this.bookieAffinityGroup = bookieAffinityGroup;
        this.namespaceAntiAffinityGroup = namespaceAntiAffinityGroup;
    }

}


text:
{-# LANGUAGE OverloadedStrings #-}
module Main where

import Happstack.Lite (serve, dir)
import Control.Monad (msum)
import Routes (routes)
import Static (static)

main :: IO ()
main = serve Nothing $ msum
    [ dir "/static" static
    , routes
    ]


text:
/* Boten board configuration */

#ifndef __CROS_EC_BOARD_H
#define __CROS_EC_BOARD_H

/* Select Baseboard features */
#define VARIANT_DEDEDE_EC_IT8320
#include "baseboard.h"

/* Battery */
#define CONFIG_BATTERY_FUEL_GAUGE
#define CONFIG_BATTERY_V2
#define CONFIG_BATTERY_COUNT 1
#define CONFIG_HOSTCMD_BATTERY_V2

/* BC 1.2 */
#define CONFIG_BC12_DETECT_PI3USB9201

/* Charger */
#define CONFIG_CHARGE_RAMP_HW
#define CONFIG_CHARGER_RAA489000
#define PD_MAX_VOLTAGE_MV 20000
#define CONFIG_CHARGER_SENSE_RESISTOR_AC 10
#define CONFIG_CHARGER_SENSE_RESISTOR 10
#define CONFIG_OCPC_DEF_RBATT_MOHMS               \
	22 /* R_DS(on) 11.6mOhm + 10mOhm sns rstr \
	    */
#undef CONFIG_USB_PD_TCPC_LPM_EXIT_DEBOUNCE
#define CONFIG_USB_PD_TCPC_LPM_EXIT_DEBOUNCE (100 * MSEC)
/*
 * b/147463641: The charger IC seems to overdraw ~4%, therefore we
 * reduce our target accordingly.
 */
#define CONFIG_CHARGER_INPUT_CURRENT_DERATE_PCT 4

/* DAC for PSYS */
#define CONFIG_DAC

/* LED */
#define CONFIG_LED_ONOFF_STATES

/* PWM */
#define CONFIG_PWM

/* Sensors */
#define CONFIG_ACCEL_LIS2DWL /* Lid accel */
#define CONFIG_ACCELGYRO_LSM6DSM /* Base accel */
#define CONFIG_ACCEL_LSM6DSM_INT_EVENT \
	TASK_EVENT_MOTION_SENSOR_INTERRUPT(BASE_ACCEL)
/* Sensors without hardware FIFO are in forced mode */
#define CONFIG_ACCEL_FORCE_MODE_MASK BIT(LID_ACCEL)

/* Enable sensor fifo, must also define the _SIZE and _THRES */
#define CONFIG_ACCEL_FIFO
/* Power of 2 - Too large of a fifo causes too much timestamp jitter */
#define CONFIG_ACCEL_FIFO_SIZE 256
#define CONFIG_ACCEL_FIFO_THRES (CONFIG_ACCEL_FIFO_SIZE / 3)

#define CONFIG_LID_ANGLE
#define CONFIG_LID_ANGLE_UPDATE
#define CONFIG_LID_ANGLE_SENSOR_BASE BASE_ACCEL
#define CONFIG_LID_ANGLE_SENSOR_LID LID_ACCEL

#define CONFIG_TABLET_MODE
#define CONFIG_TABLET_MODE_SWITCH
#define CONFIG_GMR_TABLET_MODE

/* TCPC */
#define CONFIG_USB_PD_PORT_MAX_COUNT 1
#define CONFIG_USB_PD_TCPM_RAA489000

/* USB defines specific to external TCPCs */
#define CONFIG_USB_PD_DUAL_ROLE_AUTO_TOGGLE
#define CONFIG_USB_PD_VBUS_DETECT_TCPC
#define CONFIG_USB_PD_DISCHARGE_TCPC
#define CONFIG_USB_PD_TCPC_LOW_POWER

/* EC console commands */
#define CONFIG_CMD_TCPC_DUMP
#define CONFIG_CMD_ACCELS
#define CONFIG_CMD_ACCEL_INFO

/* Variant references the TCPCs to determine Vbus sourcing */
#define CONFIG_USB_PD_5V_EN_CUSTOM

/* Thermistors */
#define CONFIG_TEMP_SENSOR
#define CONFIG_THERMISTOR
#define CONFIG_STEINHART_HART_3V3_51K1_47K_4050B

/* USB Mux */
#define CONFIG_USB_MUX_IT5205

/* USB Type A Features */
#define USB_PORT_COUNT 1
#define CONFIG_USB_PORT_POWER_DUMB

#define CONFIG_DYNAMIC_MOTION_SENSOR_COUNT
#define CONFIG_BUTTONS_RUNTIME_CONFIG

#ifndef __ASSEMBLER__

#include "gpio_signal.h"
#include "registers.h"

enum pwm_channel {
	PWM_CH_KBLIGHT,
	PWM_CH_LED_RED,
	PWM_CH_LED_GREEN,
	PWM_CH_LED_WHITE,
	PWM_CH_COUNT,
};

/* Motion sensors */
enum sensor_id { LID_ACCEL, BASE_ACCEL, BASE_GYRO, SENSOR_COUNT };

/* ADC channels */
enum adc_channel {
	ADC_VSNS_PP3300_A, /* ADC0 */
	ADC_TEMP_SENSOR_1, /* ADC2 */
	ADC_TEMP_SENSOR_2, /* ADC3 */
	ADC_CH_COUNT
};

enum temp_sensor_id { TEMP_SENSOR_1, TEMP_SENSOR_2, TEMP_SENSOR_COUNT };

/* List of possible batteries */
enum battery_type {
	BATTERY_SMP,
	BATTERY_LGC,
	BATTERY_SUNWODA,
	BATTERY_TYPE_COUNT,
};

void pen_detect_interrupt(enum gpio_signal s);

#endif /* !__ASSEMBLER__ */

#endif /* __CROS_EC_BOARD_H */