text:
/***********************************************************************************************************************************
Test Convert C Types
***********************************************************************************************************************************/
#include "common/stackTrace.h"

/***********************************************************************************************************************************
Test Run
***********************************************************************************************************************************/
static void
testRun(void)
{
    FUNCTION_HARNESS_VOID();

    // *****************************************************************************************************************************
    if (testBegin("cvtBoolToZ()"))
    {
        char buffer[STACK_TRACE_PARAM_MAX];

        TEST_ERROR(cvtBoolToZ(true, buffer, 4), AssertError, "buffer overflow");

        TEST_RESULT_UINT(cvtBoolToZ(true, buffer, STACK_TRACE_PARAM_MAX), 4, "convert true bool to string");
        TEST_RESULT_Z(buffer, "true", "    check buffer");
        TEST_RESULT_UINT(cvtBoolToZ(false, buffer, STACK_TRACE_PARAM_MAX), 5, "convert false bool to string");
        TEST_RESULT_Z(buffer, "false", "    check buffer");
    }

    // *****************************************************************************************************************************
    if (testBegin("cvtCharToZ()"))
    {
        char buffer[STACK_TRACE_PARAM_MAX];

        TEST_ERROR(cvtCharToZ('A', buffer, 1), AssertError, "buffer overflow");

        TEST_RESULT_UINT(cvtCharToZ('C', buffer, STACK_TRACE_PARAM_MAX), 1, "convert char to string");
        TEST_RESULT_Z(buffer, "C", "    check buffer");
    }

    // *****************************************************************************************************************************
    if (testBegin("cvtDoubleToZ() and cvtZToDouble()"))
    {
        char buffer[STACK_TRACE_PARAM_MAX];

        TEST_ERROR(cvtDoubleToZ(999.1234, buffer, 4), AssertError, "buffer overflow");

        TEST_RESULT_UINT(cvtDoubleToZ(999.1234, buffer, STACK_TRACE_PARAM_MAX), 8, "convert double to string");
        TEST_RESULT_Z(buffer, "999.1234", "    check buffer");

        TEST_RESULT_UINT(cvtDoubleToZ(999999999.123456, buffer, STACK_TRACE_PARAM_MAX), 16, "convert double to string");
        TEST_RESULT_Z(buffer, "999999999.123456", "    check buffer");

        TEST_RESULT_UINT(cvtDoubleToZ(999.0, buffer, STACK_TRACE_PARAM_MAX), 3, "convert double to string");
        TEST_RESULT_Z(buffer, "999", "    check buffer");

        TEST_ERROR(cvtZToDouble("AAA"), FormatError, "unable to convert string 'AAA' to double");
        TEST_RESULT_DOUBLE(cvtZToDouble("0"), 0, "convert string to double");
        TEST_RESULT_DOUBLE(cvtZToDouble("123.123"), 123.123, "convert string to double");
        TEST_RESULT_DOUBLE(cvtZToDouble("-999999999.123456"), -999999999.123456, "convert string to double");
    }

    // *****************************************************************************************************************************
    if (testBegin("cvtIntToZ() and cvtZToInt()"))
    {
        char buffer[STACK_TRACE_PARAM_MAX];

        TEST_ERROR(cvtIntToZ(9999, buffer, 4), AssertError, "buffer overflow");

        TEST_RESULT_UINT(cvtIntToZ(1234567890, buffer, STACK_TRACE_PARAM_MAX), 10, "convert int to string");
        TEST_RESULT_Z(buffer, "1234567890", "    check buffer");

        TEST_ERROR(cvtZToInt("FEF"), FormatError, "unable to convert base 10 string 'FEF' to int");
        TEST_ERROR(cvtZToInt("9223372036854775807"), FormatError, "unable to convert base 10 string '9223372036854775807' to int");
        TEST_ERROR(
            cvtZToInt("-9223372036854775807"), FormatError, "unable to convert base 10 string '-9223372036854775807' to int");

        TEST_RESULT_INT(cvtZToIntBase("-FF", 16), -255, "convert string to int");
        TEST_RESULT_INT(cvtZToInt("0"), 0, "convert string to int");
        TEST_RESULT_INT(cvtZToInt("1234567890"), 1234567890, "convert string to int");
        TEST_RESULT_INT(cvtZToInt("-1234567890"), -1234567890, "convert string to int");
    }

    // *****************************************************************************************************************************
    if (testBegin("cvtInt32ToZigZag(), cvtInt32FromZigZag(), cvtInt64ToZigZag(), and cvtInt64FromZigZag()"))
    {
        TEST_TITLE("32-bit zigzag");

        TEST_RESULT_UINT(cvtInt32ToZigZag(-1), 1, "-1 to zigzag");
        TEST_RESULT_UINT(cvtInt32ToZigZag(INT32_MIN), UINT32_MAX, "INT32_MIN to zigzag");
        TEST_RESULT_UINT(cvtInt32ToZigZag(INT32_MAX), UINT32_MAX - 1, "INT32_MAX to zigzag");
        TEST_RESULT_INT(cvtInt32FromZigZag(1), -1, "-1 to zigzag");
        TEST_RESULT_INT(cvtInt32FromZigZag(UINT32_MAX), INT32_MIN, "zigzag to INT32_MIN");
        TEST_RESULT_INT(cvtInt32FromZigZag(UINT32_MAX - 1), INT32_MAX, "zigzag to INT32_MAX");

        TEST_TITLE("64-bit zigzag");

        TEST_RESULT_UINT(cvtInt64ToZigZag(-1), 1, "-1 to zigzag");
        TEST_RESULT_UINT(cvtInt64ToZigZag(INT64_MIN), UINT64_MAX, "INT64_MIN to zigzag");
        TEST_RESULT_UINT(cvtInt64ToZigZag(INT64_MAX), UINT64_MAX - 1, "INT64_MAX to zigzag");
        TEST_RESULT_INT(cvtInt64FromZigZag(1), -1, "-1 to zigzag");
        TEST_RESULT_INT(cvtInt64FromZigZag(UINT64_MAX), INT64_MIN, "zigzag to INT64_MIN");
        TEST_RESULT_INT(cvtInt64FromZigZag(UINT64_MAX - 1), INT64_MAX, "zigzag to INT64_MAX");
    }

    // *****************************************************************************************************************************
    if (testBegin("cvtModeToZ()"))
    {
        char buffer[STACK_TRACE_PARAM_MAX];

        TEST_ERROR(cvtModeToZ(0750, buffer, 4), AssertError, "buffer overflow");

        TEST_RESULT_UINT(cvtModeToZ(0777, buffer, STACK_TRACE_PARAM_MAX), 4, "convert mode to string");
        TEST_RESULT_Z(buffer, "0777", "    check buffer");

        TEST_RESULT_UINT(cvtZToMode("0700"), 0700, "convert string to mode");
    }

    // *****************************************************************************************************************************
    if (testBegin("cvtSizeToZ() and cvtSSizeToZ()"))
    {
        char buffer[STACK_TRACE_PARAM_MAX];

        TEST_ERROR(cvtSizeToZ(9999, buffer, 4), AssertError, "buffer overflow");

        TEST_RESULT_UINT(cvtSizeToZ(4294967295, buffer, STACK_TRACE_PARAM_MAX), 10, "convert size to string");
        TEST_RESULT_Z(buffer, "4294967295", "    check buffer");

        // ------------------------------------------------------------------------------------------------------------------------
        TEST_ERROR(cvtSSizeToZ(-9999, buffer, 4), AssertError, "buffer overflow");

        TEST_RESULT_UINT(cvtSSizeToZ(-9999, buffer, STACK_TRACE_PARAM_MAX), 5, "convert ssize to string");
        TEST_RESULT_Z(buffer, "-9999", "    check buffer");
    }

    // *****************************************************************************************************************************
    if (testBegin("cvtTimeToZ()"))
    {
        char buffer[STACK_TRACE_PARAM_MAX];

        TEST_ERROR(cvtTimeToZ(9999, buffer, 4), AssertError, "buffer overflow");

        TEST_RESULT_UINT(cvtTimeToZ(1573222014, buffer, STACK_TRACE_PARAM_MAX), 10, "convert time to string");
        TEST_RESULT_Z(buffer, "1573222014", "    check buffer");
    }

    // *****************************************************************************************************************************
    if (testBegin("cvtUIntToZ() and cvtZToUInt()"))
    {
        char buffer[STACK_TRACE_PARAM_MAX];

        TEST_ERROR(cvtUIntToZ(9999, buffer, 4), AssertError, "buffer overflow");

        TEST_RESULT_UINT(cvtUIntToZ(4294967295, buffer, STACK_TRACE_PARAM_MAX), 10, "convert unsigned int to string");
        TEST_RESULT_Z(buffer, "4294967295", "    check buffer");

        TEST_ERROR(cvtZToUInt("-1"), FormatError, "unable to convert base 10 string '-1' to unsigned int");
        TEST_ERROR(cvtZToUInt("5000000000"), FormatError, "unable to convert base 10 string '5000000000' to unsigned int");

        TEST_RESULT_UINT(cvtZToUIntBase("FF", 16), 255, "convert string to unsigned int");
        TEST_RESULT_UINT(cvtZToUInt("3333333333"), 3333333333U, "convert string to unsigned int");
    }

    // *****************************************************************************************************************************
    if (testBegin("cvtInt64ToZ() and cvtZToInt64()"))
    {
        char buffer[STACK_TRACE_PARAM_MAX];

        TEST_ERROR(cvtInt64ToZ(9999, buffer, 4), AssertError, "buffer overflow");

        TEST_RESULT_UINT(cvtInt64ToZ(9223372036854775807, buffer, STACK_TRACE_PARAM_MAX), 19, "convert int64 to string");
        TEST_RESULT_Z(buffer, "9223372036854775807", "    check buffer");

        TEST_ERROR(cvtZToInt64("123INV"), FormatError, "unable to convert base 10 string '123INV' to int64");
        TEST_ERROR(cvtZToInt64("FEF"), FormatError, "unable to convert base 10 string 'FEF' to int64");
        TEST_ERROR(cvtZToInt64(""), FormatError, "unable to convert base 10 string '' to int64");
        TEST_ERROR(cvtZToInt64(" 1"), FormatError, "unable to convert base 10 string ' 1' to int64");
        TEST_ERROR(cvtZToInt64("\t1"), FormatError, "unable to convert base 10 string '\t1' to int64");
        TEST_ERROR(cvtZToInt64("1\t"), FormatError, "unable to convert base 10 string '1\t' to int64");
        TEST_ERROR(
            cvtZToInt64("9223372036854775808"), FormatError, "unable to convert base 10 string '9223372036854775808' to int64");

        TEST_RESULT_INT(cvtZToInt64Base("-FF", 16), -255, "convert string to int64");
        TEST_RESULT_INT(cvtZToInt64("0"), 0, "convert string to int64");
        TEST_RESULT_INT(cvtZToInt64("9223372036854775807"), 9223372036854775807, "convert string to int64");
        TEST_RESULT_INT(cvtZToInt64("-9223372036854775807"), -9223372036854775807, "convert string to int64");
    }

    // *****************************************************************************************************************************
    if (testBegin("UInt64ToZ() and cvtZToUInt64()"))
    {
        char buffer[STACK_TRACE_PARAM_MAX];

        TEST_ERROR(cvtUInt64ToZ(9999, buffer, 4), AssertError, "buffer overflow");

        TEST_RESULT_UINT(cvtUInt64ToZ(0xFFFFFFFFFFFFFFFF, buffer, STACK_TRACE_PARAM_MAX), 20, "convert uint64 to string");
        TEST_RESULT_Z(buffer, "18446744073709551615", "    check buffer");

        TEST_ERROR(cvtZToUInt64("FEF"), FormatError, "unable to convert base 10 string 'FEF' to uint64");
        TEST_ERROR(cvtZToUInt64(" 10"), FormatError, "unable to convert base 10 string ' 10' to uint64");
        TEST_ERROR(cvtZToUInt64("10 "), FormatError, "unable to convert base 10 string '10 ' to uint64");
        TEST_ERROR(cvtZToUInt64("-1"), FormatError, "unable to convert base 10 string '-1' to uint64");

        TEST_RESULT_UINT(cvtZToUInt64Base("FF", 16), 255, "convert string to uint64");
        TEST_RESULT_UINT(cvtZToUInt64("18446744073709551615"), 18446744073709551615U, "convert string to uint64");
    }

    FUNCTION_HARNESS_RETURN_VOID();
}


text:
import util
from graphicsUtils import *

class GraphicsGridworldDisplay:

    def __init__(self, gridworld, size=120, speed=1.0):
        self.gridworld = gridworld
        self.size = size
        self.speed = speed

    def start(self):
        setup(self.gridworld, size=self.size)

    def pause(self):
        wait_for_keys()

    def displayValues(self, agent, currentState = None, message = 'Agent Values'):
        values = util.Counter()
        policy = {}
        states = self.gridworld.getStates()
        for state in states:
            values[state] = agent.getValue(state)
            policy[state] = agent.getPolicy(state)
        drawValues(self.gridworld, values, policy, currentState, message)
        sleep(0.05 / self.speed)

    def displayNullValues(self, currentState = None, message = ''):
        values = util.Counter()
        #policy = {}
        states = self.gridworld.getStates()
        for state in states:
            values[state] = 0.0
            #policy[state] = agent.getPolicy(state)
        drawNullValues(self.gridworld, currentState,'')
        # drawValues(self.gridworld, values, policy, currentState, message)
        sleep(0.05 / self.speed)

    def displayQValues(self, agent, currentState = None, message = 'Agent Q-Values'):
        qValues = util.Counter()
        states = self.gridworld.getStates()
        for state in states:
            for action in self.gridworld.getPossibleActions(state):
                qValues[(state, action)] = agent.getQValue(state, action)
        drawQValues(self.gridworld, qValues, currentState, message)
        sleep(0.05 / self.speed)

BACKGROUND_COLOR = formatColor(0,0,0)
EDGE_COLOR = formatColor(1,1,1)
OBSTACLE_COLOR = formatColor(0.5,0.5,0.5)
TEXT_COLOR = formatColor(1,1,1)
MUTED_TEXT_COLOR = formatColor(0.7,0.7,0.7)
LOCATION_COLOR = formatColor(0,0,1)

WINDOW_SIZE = -1
GRID_SIZE = -1
GRID_HEIGHT = -1
MARGIN = -1

def setup(gridworld, title = "Gridworld Display", size = 120):
    global GRID_SIZE, MARGIN, SCREEN_WIDTH, SCREEN_HEIGHT, GRID_HEIGHT
    grid = gridworld.grid
    WINDOW_SIZE = size
    GRID_SIZE = size
    GRID_HEIGHT = grid.height
    MARGIN = GRID_SIZE * 0.75
    screen_width = (grid.width - 1) * GRID_SIZE + MARGIN * 2
    screen_height = (grid.height - 0.5) * GRID_SIZE + MARGIN * 2

    begin_graphics(screen_width,
                   screen_height,
                   BACKGROUND_COLOR, title=title)

def drawNullValues(gridworld, currentState = None, message = ''):
    grid = gridworld.grid
    blank()
    for x in range(grid.width):
        for y in range(grid.height):
            state = (x, y)
            gridType = grid[x][y]
            isExit = (str(gridType) != gridType)
            isCurrent = (currentState == state)
            if gridType == '#':
                drawSquare(x, y, 0, 0, 0, None, None, True, False, isCurrent)
            else:
                drawNullSquare(gridworld.grid, x, y, False, isExit, isCurrent)
    pos = to_screen(((grid.width - 1.0) / 2.0, - 0.8))
    text( pos, TEXT_COLOR, message, "Courier", -32, "bold", "c")

def drawValues(gridworld, values, policy, currentState = None, message = 'State Values'):
    grid = gridworld.grid
    blank()
    valueList = [values[state] for state in gridworld.getStates()] + [0.0]
    minValue = min(valueList)
    maxValue = max(valueList)
    for x in range(grid.width):
        for y in range(grid.height):
            state = (x, y)
            gridType = grid[x][y]
            isExit = (str(gridType) != gridType)
            isCurrent = (currentState == state)
            if gridType == '#':
                drawSquare(x, y, 0, 0, 0, None, None, True, False, isCurrent)
            else:
                value = values[state]
                action = None
                if policy != None and state in policy:
                    action = policy[state]
                    actions = gridworld.getPossibleActions(state)
                if action not in actions and 'exit' in actions:
                    action = 'exit'
                valString = '%.2f' % value
                drawSquare(x, y, value, minValue, maxValue, valString, action, False, isExit, isCurrent)
    pos = to_screen(((grid.width - 1.0) / 2.0, - 0.8))
    text( pos, TEXT_COLOR, message, "Courier", -32, "bold", "c")

def drawQValues(gridworld, qValues, currentState = None, message = 'State-Action Q-Values'):
    grid = gridworld.grid
    blank()
    stateCrossActions = [[(state, action) for action in gridworld.getPossibleActions(state)] for state in gridworld.getStates()]
    qStates = reduce(lambda x,y: x+y, stateCrossActions, [])
    qValueList = [qValues[(state, action)] for state, action in qStates] + [0.0]
    minValue = min(qValueList)
    maxValue = max(qValueList)
    for x in range(grid.width):
        for y in range(grid.height):
            state = (x, y)
            gridType = grid[x][y]
            isExit = (str(gridType) != gridType)
            isCurrent = (currentState == state)
            actions = gridworld.getPossibleActions(state)
            if actions == None or len(actions) == 0:
                actions = [None]
            bestQ = max([qValues[(state, action)] for action in actions])
            bestActions = [action for action in actions if qValues[(state, action)] == bestQ]

            q = util.Counter()
            valStrings = {}
            for action in actions:
                v = qValues[(state, action)]
                q[action] += v
                valStrings[action] = '%.2f' % v
            if gridType == '#':
                drawSquare(x, y, 0, 0, 0, None, None, True, False, isCurrent)
            elif isExit:
                action = 'exit'
                value = q[action]
                valString = '%.2f' % value
                drawSquare(x, y, value, minValue, maxValue, valString, action, False, isExit, isCurrent)
            else:
                drawSquareQ(x, y, q, minValue, maxValue, valStrings, actions, isCurrent)
    pos = to_screen(((grid.width - 1.0) / 2.0, - 0.8))
    text( pos, TEXT_COLOR, message, "Courier", -32, "bold", "c")

def blank():
    clear_screen()

def drawNullSquare(grid,x, y, isObstacle, isTerminal, isCurrent):

    square_color = getColor(0, -1, 1)

    if isObstacle:
        square_color = OBSTACLE_COLOR

    (screen_x, screen_y) = to_screen((x, y))
    square( (screen_x, screen_y),
                   0.5* GRID_SIZE,
                   color = square_color,
                   filled = 1,
                   width = 1)

    square( (screen_x, screen_y),
                   0.5* GRID_SIZE,
                   color = EDGE_COLOR,
                   filled = 0,
                   width = 3)

    if isTerminal and not isObstacle:
        square( (screen_x, screen_y),
                     0.4* GRID_SIZE,
                     color = EDGE_COLOR,
                     filled = 0,
                     width = 2)
        text( (screen_x, screen_y),
               TEXT_COLOR,
               str(grid[x][y]),
               "Courier", -24, "bold", "c")

    text_color = TEXT_COLOR

    if not isObstacle and isCurrent:
        circle( (screen_x, screen_y), 0.1*GRID_SIZE, LOCATION_COLOR, fillColor=LOCATION_COLOR )

    # if not isObstacle:
    #   text( (screen_x, screen_y), text_color, valStr, "Courier", 24, "bold", "c")

def drawSquare(x, y, val, min, max, valStr, action, isObstacle, isTerminal, isCurrent):

    square_color = getColor(val, min, max)

    if isObstacle:
        square_color = OBSTACLE_COLOR

    (screen_x, screen_y) = to_screen((x, y))
    square( (screen_x, screen_y),
                   0.5* GRID_SIZE,
                   color = square_color,
                   filled = 1,
                   width = 1)
    square( (screen_x, screen_y),
                   0.5* GRID_SIZE,
                   color = EDGE_COLOR,
                   filled = 0,
                   width = 3)
    if isTerminal and not isObstacle:
        square( (screen_x, screen_y),
                     0.4* GRID_SIZE,
                     color = EDGE_COLOR,
                     filled = 0,
                     width = 2)

    if action == 'north':
        polygon( [(screen_x, screen_y - 0.45*GRID_SIZE), (screen_x+0.05*GRID_SIZE, screen_y-0.40*GRID_SIZE), (screen_x-0.05*GRID_SIZE, screen_y-0.40*GRID_SIZE)], EDGE_COLOR, filled = 1, smoothed = False)
    if action == 'south':
        polygon( [(screen_x, screen_y + 0.45*GRID_SIZE), (screen_x+0.05*GRID_SIZE, screen_y+0.40*GRID_SIZE), (screen_x-0.05*GRID_SIZE, screen_y+0.40*GRID_SIZE)], EDGE_COLOR, filled = 1, smoothed = False)
    if action == 'west':
        polygon( [(screen_x-0.45*GRID_SIZE, screen_y), (screen_x-0.4*GRID_SIZE, screen_y+0.05*GRID_SIZE), (screen_x-0.4*GRID_SIZE, screen_y-0.05*GRID_SIZE)], EDGE_COLOR, filled = 1, smoothed = False)
    if action == 'east':
        polygon( [(screen_x+0.45*GRID_SIZE, screen_y), (screen_x+0.4*GRID_SIZE, screen_y+0.05*GRID_SIZE), (screen_x+0.4*GRID_SIZE, screen_y-0.05*GRID_SIZE)], EDGE_COLOR, filled = 1, smoothed = False)

    text_color = TEXT_COLOR

    if not isObstacle and isCurrent:
        circle( (screen_x, screen_y), 0.1*GRID_SIZE, outlineColor=LOCATION_COLOR, fillColor=LOCATION_COLOR )

    if not isObstacle:
        text( (screen_x, screen_y), text_color, valStr, "Courier", -30, "bold", "c")

def drawSquareQ(x, y, qVals, minVal, maxVal, valStrs, bestActions, isCurrent):

    (screen_x, screen_y) = to_screen((x, y))

    center = (screen_x, screen_y)
    nw = (screen_x-0.5*GRID_SIZE, screen_y-0.5*GRID_SIZE)
    ne = (screen_x+0.5*GRID_SIZE, screen_y-0.5*GRID_SIZE)
    se = (screen_x+0.5*GRID_SIZE, screen_y+0.5*GRID_SIZE)
    sw = (screen_x-0.5*GRID_SIZE, screen_y+0.5*GRID_SIZE)
    n = (screen_x, screen_y-0.5*GRID_SIZE+5)
    s = (screen_x, screen_y+0.5*GRID_SIZE-5)
    w = (screen_x-0.5*GRID_SIZE+5, screen_y)
    e = (screen_x+0.5*GRID_SIZE-5, screen_y)

    actions = qVals.keys()
    for action in actions:

        wedge_color = getColor(qVals[action], minVal, maxVal)

        if action == 'north':
            polygon( (center, nw, ne), wedge_color, filled = 1, smoothed = False)
            #text(n, text_color, valStr, "Courier", 8, "bold", "n")
        if action == 'south':
            polygon( (center, sw, se), wedge_color, filled = 1, smoothed = False)
            #text(s, text_color, valStr, "Courier", 8, "bold", "s")
        if action == 'east':
            polygon( (center, ne, se), wedge_color, filled = 1, smoothed = False)
            #text(e, text_color, valStr, "Courier", 8, "bold", "e")
        if action == 'west':
            polygon( (center, nw, sw), wedge_color, filled = 1, smoothed = False)
            #text(w, text_color, valStr, "Courier", 8, "bold", "w")

    square( (screen_x, screen_y),
                   0.5* GRID_SIZE,
                   color = EDGE_COLOR,
                   filled = 0,
                   width = 3)
    line(ne, sw, color = EDGE_COLOR)
    line(nw, se, color = EDGE_COLOR)

    if isCurrent:
        circle( (screen_x, screen_y), 0.1*GRID_SIZE, LOCATION_COLOR, fillColor=LOCATION_COLOR )

    for action in actions:
        text_color = TEXT_COLOR
        if qVals[action] < max(qVals.values()): text_color = MUTED_TEXT_COLOR
        valStr = ""
        if action in valStrs:
            valStr = valStrs[action]
        h = -20
        if action == 'north':
            #polygon( (center, nw, ne), wedge_color, filled = 1, smooth = 0)
            text(n, text_color, valStr, "Courier", h, "bold", "n")
        if action == 'south':
            #polygon( (center, sw, se), wedge_color, filled = 1, smooth = 0)
            text(s, text_color, valStr, "Courier", h, "bold", "s")
        if action == 'east':
            #polygon( (center, ne, se), wedge_color, filled = 1, smooth = 0)
            text(e, text_color, valStr, "Courier", h, "bold", "e")
        if action == 'west':
            #polygon( (center, nw, sw), wedge_color, filled = 1, smooth = 0)
            text(w, text_color, valStr, "Courier", h, "bold", "w")

def getColor(val, minVal, max):
    r, g = 0.0, 0.0
    if val < 0 and minVal < 0:
        r = val * 0.65 / minVal
    if val > 0 and max > 0:
        g = val * 0.65 / max
    return formatColor(r,g,0.0)

def square(pos, size, color, filled, width):
    x, y = pos
    dx, dy = size, size
    return polygon([(x - dx, y - dy), (x - dx, y + dy), (x + dx, y + dy), (x + dx, y - dy)], outlineColor=color, fillColor=color, filled=filled, width=width, smoothed=False)

def to_screen(point):
    ( gamex, gamey ) = point
    x = gamex*GRID_SIZE + MARGIN
    y = (GRID_HEIGHT - gamey - 1)*GRID_SIZE + MARGIN
    return ( x, y )

def to_grid(point):
    (x, y) = point
    x = int ((y - MARGIN + GRID_SIZE * 0.5) / GRID_SIZE)
    y = int ((x - MARGIN + GRID_SIZE * 0.5) / GRID_SIZE)
    print point, "-->", (x, y)
    return (x, y)

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
 * Attributes for Text Labels.
 * @package    Google_Api_Ads_AdWords_v201605
 * @subpackage v201605
 */
class DisplayAttribute extends LabelAttribute
{

    const WSDL_NAMESPACE = "https://adwords.google.com/api/adwords/cm/v201605";
    const XSI_TYPE = "DisplayAttribute";

    /**
     * @access public
     * @var string
     */
    public $backgroundColor;

    /**
     * @access public
     * @var string
     */
    public $description;

    /**
     * Gets the namesapce of this class
     * @return string the namespace of this class
     */
    public function getNamespace()
    {
        return self::WSDL_NAMESPACE;
    }

    /**
     * Gets the xsi:type name of this class
     * @return string the xsi:type name of this class
     */
    public function getXsiTypeName()
    {
        return self::XSI_TYPE;
    }

    public function __construct($backgroundColor = null, $description = null, $LabelAttributeType = null)
    {
        parent::__construct();
        $this->backgroundColor = $backgroundColor;
        $this->description = $description;
        $this->LabelAttributeType = $LabelAttributeType;
    }

}


text:
require "mark_opt_in_api/version"

module MarkOptInApi
  require 'httparty'

  class Configuration
    attr_accessor :host, :port

    def initialize
      self.host = 'localhost'
      self.port = 3000
    end
  end

  def self.configuration
    @configuration ||=  Configuration.new
  end

  def self.configure
    yield(configuration) if block_given?
  end

  class Api
    def self.add options = {}
      raise ArgumentError.new('Options should be present') if options.empty?
      response = HTTParty.post("http://#{MarkOptInApi.configuration.host}:#{MarkOptInApi.configuration.port}/marketings", query: { marketing: options })
      puts response
    end

    def self.update id = nil, options = {}
      raise ArgumentError.new('ID and Options should be present') if id.nil? || options.empty?
      response = HTTParty.put("http://#{MarkOptInApi.configuration.host}:#{MarkOptInApi.configuration.port}/marketing/#{id}", query: { marketing: options })
      puts response
    end

    def self.delete id = nil
      raise ArgumentError.new('ID should be present') unless id
      response = HTTParty.delete("http://#{MarkOptInApi.configuration.host}:#{MarkOptInApi.configuration.port}/marketing/#{id}")
      puts response
    end
  end
end


text:
#include "mitkTwoTissueCompartmentFDGModelFactory.h"

#include <mitkImageTimeSelector.h>
#include <mitkImageCast.h>
#include <mitkSimpleBarrierConstraintChecker.h>

mitk::ConstraintCheckerBase::Pointer
mitk::TwoTissueCompartmentFDGModelFactory::CreateDefaultConstraints() const
{
  SimpleBarrierConstraintChecker::Pointer constraints = SimpleBarrierConstraintChecker::New();

  constraints->SetLowerBarrier(ModelType::POSITION_PARAMETER_K1, 0.0);
  constraints->SetLowerBarrier(ModelType::POSITION_PARAMETER_k2, 0, 0);
  constraints->SetLowerBarrier(ModelType::POSITION_PARAMETER_k3, 0, 0);
  constraints->SetLowerBarrier(ModelType::POSITION_PARAMETER_VB, 0, 0);

  constraints->SetUpperBarrier(ModelType::POSITION_PARAMETER_K1, 1.0, 0);
  constraints->SetUpperBarrier(ModelType::POSITION_PARAMETER_k2, 1.0, 0);
  constraints->SetUpperBarrier(ModelType::POSITION_PARAMETER_k3, 1.0, 0);
  constraints->SetUpperBarrier(ModelType::POSITION_PARAMETER_VB, 1, 0);

  return constraints.GetPointer();
};

mitk::ModelParameterizerBase::ParametersType
mitk::TwoTissueCompartmentFDGModelFactory::GetDefaultInitialParameterization() const
{
  return TwoTissueCompartmentFDGModelParameterizer::New()->GetDefaultInitialParameterization();
};

mitk::TwoTissueCompartmentFDGModelFactory::TwoTissueCompartmentFDGModelFactory()
{
};

mitk::TwoTissueCompartmentFDGModelFactory::~TwoTissueCompartmentFDGModelFactory()
{
};


text:
[![NPM
version](https://badge.fury.io/js/lexemic.png)](http://badge.fury.io/js/lexemic)

## Requirements

* Node.js (v0.10.17+)
* npm (v1.3.9+)

## Install

	npm install lexemic -g

## Description

Tools for working with human language data.

## Features

* Sentiment analysis
* Stemming
* Tokenization
* Statistical analysis

## Usage

```
$ lexemic [command] [implementation] [target...]
```
NOTE: The `target` may be an inline string or the path to a text file encoded as UTF-8.

### Sentiment analysis

```
$ lexemic sentiment "I am mad at you." # => {
                                             :score -1,
                                             :comparative -0.25,
                                             :positive {
                                                        :score 0,
                                                        :comparative 0,
                                                        :words ()
                                                       },
                                             :negative {
                                                        :score 1,
                                                        :comparative 0.25,
                                                        :words (mad)
                                                       }
                                             }
```
Sentiment analysis attempts to determine the affective state of the
speaker or the writer. The default implementation returns an
[EDN](https://github.com/edn-format/edn) map of this analysis. The `:score`
represents the number of emotive words in the text while the
`:comparative` rates the occurrence of these words with regards to the
length of the text. The nested values (i.e. those under `:positive` and
`:negative` ) provide a list of matched `:words` and take only into account
their respective affectivity. The top level values incorporate both
affective states – returning negative values for texts with overall negative
affects and positive values for texts with overall positive affects.

### Stemming

```
$ lexemic stem "My education has been educational" # => #{"My"
                                                          "educ"
                                                          "ha"
                                                          "been"}
```
Stemming attempts to reduce inflected words to their stem. This is
useful in reducing your working set of words and expanding possible
search matches. The default implementation uses the porter
algorithm, though you may explicitly specify an implementation; `-p`
and `-porter` for the porter algorithm (standard and gentle) or `-l` and
`-lancaster` for the lancaster algorithm (much more aggressive). This
command returns an [EDN](https://github.com/edn-format/edn) set of the
reduced working set.

### Tokenization

```
$ lexemic tokenize "This is a sample sentence." # => ["This"
                                                      "is"
                                                      "a"
                                                      "sample"
                                                      "sentence"
                                                      "."]
```
Tokenization attempts to break a text into its desired constituent
parts – typically, that is into words. This command returns an
[EDN](https://github.com/edn-format/edn) vector of the result of this
process.

### Statistical analysis

#### Levenshtein distance

```
$ lexemic distance "This is a sentence." "This is a similar sentence." # => 8
```
Levenshtein distance measures the distance between two strings of text, often
two documents. Informally, this distance corresponds to the minimum
number of single-character edits required to change one string into the
other (e.g. in the above example, '8' represents the insertion of 1
space and the 7 letters of the word 'similar'). This command returns an
integer representing the result of this process.

## Issues

If you need help, find a bug, want to request a feature or want to contribute, please
[create an issue](https://github.com/bertrandk/lexemic/issues/new).

## Copyright

Copyright (c) 2013 Bertrand Karerangabo

See `LICENSE.txt` for details.


text:
namespace Google.Cloud.SecurityCenter.Settings.V1Beta1.Snippets
{
    // [START securitycenter_v1beta1_generated_SecurityCenterSettingsService_GetServiceAccount_async]
    using Google.Cloud.SecurityCenter.Settings.V1Beta1;
    using System.Threading.Tasks;

    public sealed partial class GeneratedSecurityCenterSettingsServiceClientSnippets
    {
        /// <summary>Snippet for GetServiceAccountAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task GetServiceAccountRequestObjectAsync()
        {
            // Create client
            SecurityCenterSettingsServiceClient securityCenterSettingsServiceClient = await SecurityCenterSettingsServiceClient.CreateAsync();
            // Initialize request argument(s)
            GetServiceAccountRequest request = new GetServiceAccountRequest
            {
                ServiceAccountName = ServiceAccountName.FromOrganization("[ORGANIZATION]"),
            };
            // Make the request
            ServiceAccount response = await securityCenterSettingsServiceClient.GetServiceAccountAsync(request);
        }
    }
    // [END securitycenter_v1beta1_generated_SecurityCenterSettingsService_GetServiceAccount_async]
}


text:
<?php

namespace phpseclib\File\ASN1\Maps;

use phpseclib\File\ASN1;

/**
 * DigestInfo
 *
 * from https://tools.ietf.org/html/rfc2898#appendix-A.3
 *
 * @package ASN1
 * @author  Jim Wigginton <terrafrost@php.net>
 * @access  public
 */
abstract class DigestInfo
{
    const MAP = [
        'type'     => ASN1::TYPE_SEQUENCE,
        'children' => [
            'digestAlgorithm' => AlgorithmIdentifier::MAP,
            'digest' => ['type' => ASN1::TYPE_OCTET_STRING]
        ]
    ];
}


text:
Rails.application.routes.draw do
  mount Garage::Docs::Engine => '/docs'
  mount Garage::Meta::Engine => '/meta'

  resources :posts do
    collection do
      get :hide
      get :capped
      get :namespaced
    end
  end

  resources :users do
    resources :posts do
      collection do
        get :private
      end
    end

    resources :public_posts, only: :index
  end

  resource :session
  resource :echo
  resource :ping

  get :mine, to: 'public_posts#my'
end


text:
import os
import tempfile

import fixtures

from openstack.common import pastedeploy
from openstack.common import test

class App(object):

    def __init__(self, data):
        self.data = data

class AppWithLocalConf(App):

    def __init__(self, data, foo=None):
        super(AppWithLocalConf, self).__init__(data)
        self.foo = foo

class Filter(object):

    def __init__(self, app, data):
        self.app = app
        self.data = data

class PasteTestCase(test.BaseTestCase):

    def setUp(self):
        super(PasteTestCase, self).setUp()
        self.useFixture(fixtures.NestedTempfile())

    def create_tempfile(self, contents):
        (fd, path) = tempfile.mkstemp()
        try:
            os.write(fd, contents)
        finally:
            os.close(fd)
        return path

    def test_app_factory(self):
        data = 'test_app_factory'

        paste_conf = self.create_tempfile("""[DEFAULT]
[app:myfoo]
paste.app_factory = openstack.common.pastedeploy:app_factory
openstack.app_factory = tests.unit.test_pastedeploy:App
""")

        app = pastedeploy.paste_deploy_app(paste_conf, 'myfoo', data)
        self.assertEqual(app.data, data)

    def test_app_factory_with_local_conf(self):
        data = 'test_app_factory_with_local_conf'

        paste_conf = self.create_tempfile("""[DEFAULT]
[app:myfoo]
paste.app_factory = openstack.common.pastedeploy:app_factory
openstack.app_factory = tests.unit.test_pastedeploy:AppWithLocalConf
foo = bar
""")

        app = pastedeploy.paste_deploy_app(paste_conf, 'myfoo', data)
        self.assertEqual(app.data, data)
        self.assertEqual(app.foo, 'bar')

    def test_filter_factory(self):
        data = 'test_filter_factory'

        paste_conf = self.create_tempfile("""[DEFAULT]
[pipeline:myfoo]
pipeline = myfoofilter myfooapp

[filter:myfoofilter]
paste.filter_factory = openstack.common.pastedeploy:filter_factory
openstack.filter_factory = tests.unit.test_pastedeploy:Filter

[app:myfooapp]
paste.app_factory = openstack.common.pastedeploy:app_factory
openstack.app_factory = tests.unit.test_pastedeploy:App
""")

        app = pastedeploy.paste_deploy_app(paste_conf, 'myfoo', data)
        self.assertEqual(app.data, data)
        self.assertEqual(app.app.data, data)


text:
import itertools

from chainer.cuda import to_gpu, to_cpu
from chainer.functions import convolution_2d

import numpy as np
from sklearn.decomposition import IncrementalPCA

from utils import gpu_enabled

if gpu_enabled():
    try:
        import cupy as xp
    except ImportError:
        import numpy as xp
else:
    import numpy as xp

def steps(image_shape, filter_shape, step_shape):
    """
    Generates feature map coordinates that filters visit

    Parameters
    ----------
    image_shape: tuple of ints
        Image height / width
    filter_shape: tuple of ints
        Filter height / width
    step_shape: tuple of ints
        Step height / width

    Returns
    -------
    ys: Map coordinates along y axis
    xs: Map coordinates along x axis
    """
    h, w = image_shape
    fh, fw = filter_shape
    sh, sw = step_shape

    ys = range(0, h-fh+1, sh)
    xs = range(0, w-fw+1, sw)
    return ys, xs

def components_to_filters(components, n_channels, filter_shape):
    """
    | In PCANet, components of PCA are used as filter weights.
    | This function reshapes PCA components so that
      it can be used as networks filters
    """
    n_filters = components.shape[0]
    return components.reshape(n_filters, n_channels, *filter_shape)

def output_shape(ys, xs):
    return len(ys), len(xs)

class Patches(object):
    def __init__(self, image, filter_shape, step_shape):
        assert(image.ndim == 2)

        # should be either numpy.ndarray or cupy.ndarray
        self.ndarray = type(image)
        self.image = image
        self.filter_shape = filter_shape

        self.ys, self.xs = steps(image.shape[0:2], filter_shape, step_shape)

    @property
    def patches(self):
        """
        Return image patches of shape
        (n_patches, filter_height, filter_width)
        """
        fh, fw = self.filter_shape
        it = list(itertools.product(self.ys, self.xs))
        patches = self.ndarray((len(it), fh, fw), dtype=self.image.dtype)
        for i, (y, x) in enumerate(it):
            patches[i, :, :] = self.image[y:y+fh, x:x+fw]
        return patches

    @property
    def output_shape(self):
        return output_shape(self.ys, self.xs)

def atleast_4d(images):
    """Regard gray-scale images as 1-channel images"""
    assert(np.ndim(images) == 3)
    n, h, w = images.shape
    return images.reshape(n, h, w, 1)

def to_channels_first(images):
    """
    Change image channel order from
    :code:`(n_images, y, x, n_channels)` to
    :code:`(n_images, n_channels, y, x)`
    """
    # images.shape == (n_images, y, x, n_channels)
    images = np.swapaxes(images, 1, 3)
    images = np.swapaxes(images, 2, 3)
    # images.shape == (n_images, n_channels, y, x)
    return images

def image_to_patch_vectors(image, filter_shape, step_shape):
    """
    Parameters
    ----------
    image: np.ndarray
        Image to extract patch vectors
    filter_shape: tuple of ints
        The shape of a filter
    step_shape: tuple of ints
        Step height/width of a filter

    Returns
    -------
    X: np.ndarray
        A set of normalized and flattened patches
    """

    X = Patches(image, filter_shape, step_shape).patches
    # X.shape == (n_patches, filter_height, filter_width)

    X = X.reshape(X.shape[0], -1)  # flatten each patch
    X = X - X.mean(axis=1, keepdims=True)  # Remove mean from each patch.
    return X  # \overline{X}_i in the original paper

def binarize(X):
    """
    Binarize each element of :code:`X`

    .. code::

        X = [1 if X[i] > 0 else 0 for i in range(len(X))]
    """
    X[X > 0] = 1
    X[X <= 0] = 0
    return X

def binary_to_decimal(X):
    """
    | This function takes :code:`X` of shape (n_images, L2, y, x) as an argument.
    | Supporse that :code:`X[k]` (0 <= k < n_images) can be represented as

    .. code-block:: none

        X[k] = [map_k[0], map_k[1], ..., map_k[L2-1]]

    where the shape of each map_k is (y, x).

    Then we calculate

    .. code-block:: none

        a[0] * map_k[0] + a[1] * map_k[1] + ... + a[L2-1] * map_k[L2-1]

    for each :code:`X[k]`, where :math:`a = [2^{L2-1}, 2^{L2-2}, ..., 2^{0}]`

    Therefore, the output shape must be (n_images, y, x)

    Parameters
    ----------
    X: xp.ndarray
        Feature maps
    """
    a = xp.arange(X.shape[1])[::-1]
    a = xp.power(2, a)
    return xp.tensordot(X, a, axes=([1], [0]))

def to_tuple_if_int(value):
    """
    If int is given, duplicate it and return as a 2 element tuple.
    """
    if isinstance(value, int):
        return (value, value)
    return value

class PCANet(object):
    def __init__(self, image_shape,
                 filter_shape_l1, step_shape_l1, n_l1_output,
                 filter_shape_l2, step_shape_l2, n_l2_output,
                 filter_shape_pooling, step_shape_pooling):
        """
        Parameters
        ----------
        image_shape: int or sequence of ints
            Input image shape.
        filter_shape_l1: int or sequence of ints
            The shape of the kernel in the first convolution layer.
            If the value is int, a filter of the square shape is applied.
            If you want to apply a filter of a different aspect ratio, just
            pass a tuple of shape (height, width).
        step_shape_l1: int or sequence of ints
            The shape of kernel step in the first convolution layer.
            If the value is int, a step of the square shape is applied.
            If you want to apply a step of a different aspect ratio, just
            pass a tuple of shape (height, width).
        n_l1_output:
            L1 in the original paper. The number of outputs obtained
            from a set of input images.
        filter_shape_l2: int or sequence of ints
            The shape of the kernel in the second convolution layer.
            If the value is int, a filter of the square shape is applied.
            If you want to apply a filter of a different aspect ratio, just
            pass a tuple of shape (height, width).
        step_shape_l2: int or sequence of ints
            The shape of kernel step in the second convolution layer.
            If the value is int, a step of the square shape is applied.
            If you want to apply a step of a different aspect ratio, just
            pass a tuple of shape (height, width).
        n_l2_output:
            L2 in the original paper. The number of outputs obtained
            from each L1 output.
        filter_shape_pooling: int or sequence of ints
            The shape of the filter in the pooling layer.
        step_shape_pooling: int or sequence of ints
            The shape of the filter step in the pooling layer.
        """

        self.image_shape = to_tuple_if_int(image_shape)

        self.filter_shape_l1 = to_tuple_if_int(filter_shape_l1)
        self.step_shape_l1 = to_tuple_if_int(step_shape_l1)
        self.n_l1_output = n_l1_output

        self.filter_shape_l2 = to_tuple_if_int(filter_shape_l2)
        self.step_shape_l2 = to_tuple_if_int(step_shape_l2)
        self.n_l2_output = n_l2_output

        self.filter_shape_pooling = to_tuple_if_int(filter_shape_pooling)
        self.step_shape_pooling = to_tuple_if_int(step_shape_pooling)
        self.n_bins = None  # TODO make n_bins specifiable

        self.pca_l1 = IncrementalPCA(n_l1_output)
        self.pca_l2 = IncrementalPCA(n_l2_output)

    def histogram(self, binary_images):
        """
        Separate a given image into blocks and calculate a histogram
        in each block.

        Supporse data in a block is in range [0, 3] and the acutual
        values are

        ::

            [0 0 1]
            [2 2 2]
            [2 3 3]

        | If default bins ``[-0.5 0.5 1.5 2.5 3.5]`` applied,
          the histogram will be ``[2 1 4 2]``.
        | If ``n_bins`` is specified, the range of data divided equally.

        | For example, if the data is in range ``[0, 3]`` and ``n_bins = 2``,
        | bins will be ``[-0.5 1.5 3.5]`` and the histogram will be ``[3 6]``.
        """

        k = pow(2, self.n_l2_output)
        if self.n_bins is None:
            self.n_bins = k + 1
        bins = xp.linspace(-0.5, k - 0.5, self.n_bins)

        def bhist(image):
            # calculate Bhist(T) in the original paper
            ps = Patches(
                image,
                self.filter_shape_pooling,
                self.step_shape_pooling).patches

            H = [xp.histogram(p.flatten(), bins)[0] for p in ps]
            return xp.concatenate(H)
        return xp.vstack([bhist(image) for image in binary_images])

    def process_input(self, images):
        assert(np.ndim(images) >= 3)
        assert(images.shape[1:3] == self.image_shape)
        if np.ndim(images) == 3:
            # forcibly convert to multi-channel images
            images = atleast_4d(images)
        images = to_channels_first(images)
        return images

    def fit(self, images):
        """
        Train PCANet

        Parameters
        ----------
        images: np.ndarray
            | Color / grayscale images of shape
            | (n_images, height, width, n_channels) or
            | (n_images, height, width)
        """
        images = self.process_input(images)
        # images.shape == (n_images, n_channels, y, x)

        for image in images:
            X = []
            for channel in image:
                patches = image_to_patch_vectors(
                    channel,
                    self.filter_shape_l1,
                    self.step_shape_l1
                )
                X.append(patches)
            patches = np.hstack(X)
            # patches.shape = (n_patches, n_patches * vector length)
            self.pca_l1.partial_fit(patches)

        filters_l1 = components_to_filters(
            self.pca_l1.components_,
            n_channels=images.shape[1],
            filter_shape=self.filter_shape_l1,
        )

        if gpu_enabled():
            images = to_gpu(images)
            filters_l1 = to_gpu(filters_l1)

        images = convolution_2d(
            images,
            filters_l1,
            stride=self.step_shape_l1
        ).data

        if gpu_enabled():
            images = to_cpu(images)
            filters_l1 = to_cpu(filters_l1)

        # images.shape == (n_images, L1, y, x)
        images = images.reshape(-1, *images.shape[2:4])

        for image in images:
            patches = image_to_patch_vectors(
                image,
                self.filter_shape_l2,
                self.step_shape_l2
            )
            self.pca_l2.partial_fit(patches)
        return self

    def transform(self, images):
        """
        Parameters
        ----------
        images: np.ndarray
            | Color / grayscale images of shape
            | (n_images, height, width, n_channels) or
            | (n_images, height, width)

        Returns
        -------
        X: np.ndarray
            A set of feature vectors of shape (n_images, n_features)
            where :code:`n_features` is determined by the hyperparameters
        """
        images = self.process_input(images)
        # images.shape == (n_images, n_channels, y, x)

        filters_l1 = components_to_filters(
            self.pca_l1.components_,
            n_channels=images.shape[1],
            filter_shape=self.filter_shape_l1,
        )

        filters_l2 = components_to_filters(
            self.pca_l2.components_,
            n_channels=1,
            filter_shape=self.filter_shape_l2
        )

        if gpu_enabled():
            images = to_gpu(images)
            filters_l1 = to_gpu(filters_l1)
            filters_l2 = to_gpu(filters_l2)

        images = convolution_2d(
            images,
            filters_l1,
            stride=self.step_shape_l1
        ).data

        images = xp.swapaxes(images, 0, 1)

        # L1.shape == (L1, n_images, y, x)
        # iterate over each L1 output

        X = []
        for maps in images:
            n_images, h, w = maps.shape
            maps = convolution_2d(
                maps.reshape(n_images, 1, h, w),  # 1 channel images
                filters_l2,
                stride=self.step_shape_l2
            ).data

            # maps.shape == (n_images, L2, y, x) right here
            maps = binarize(maps)
            maps = binary_to_decimal(maps)
            # maps.shape == (n_images, y, x)
            x = self.histogram(maps)

            # x is a set of feature vectors.
            # The shape of x is (n_images, vector length)
            X.append(x)

        # concatenate over L1
        X = xp.hstack(X)

        if gpu_enabled():
            X = to_cpu(X)

        X = X.astype(np.float64)

        # The shape of X is (n_images, L1 * vector length)
        return X

    def validate_structure(self):
        """
        Check that the filter visits all pixels of input images without
        dropping any information.

        Raises
        ------
        ValueError:
            if the network structure does not satisfy the above constraint.
        """
        def is_valid_(input_shape, filter_shape, step_shape):
            ys, xs = steps(input_shape, filter_shape, step_shape)
            fh, fw = filter_shape
            h, w = input_shape
            if ys[-1]+fh != h or xs[-1]+fw != w:
                raise ValueError("Invalid network structure.")
            return output_shape(ys, xs)

        output_shape_l1 = is_valid_(self.image_shape,
                                    self.filter_shape_l1,
                                    self.step_shape_l1)
        output_shape_l2 = is_valid_(output_shape_l1,
                                    self.filter_shape_l2,
                                    self.step_shape_l2)
        is_valid_(
            output_shape_l2,
            self.filter_shape_pooling,
            self.filter_shape_pooling
        )


text:
<!DOCTYPE html>

		<meta charset="utf-8" />
		<title>AngularMongoBootstrap</title>
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<link rel="shortcut icon" href="Assets/favicon.png">

		<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.css">

		<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-theme.min.css">
		<link href="Style/Carousel.css" rel="stylesheet" type="text/css" />
		<link href="Style/index.css" rel="stylesheet" type="text/css" />

			  <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

			  </button>
			  Project name

Home

Pictures

About

				  Dropdown

Home

Pictures

About

Enter a name and address

Add, Update, Delete

Go around on the carousel

Angular Mongo Bootstrap

{{name}}

Since you probably installed this project by pulling it
			from GitHub, it includes a .git folder. You main want
			to remove this folder if you downloaded it into an existing
			Git repository.

View the readme.

		<button data-ng-click="loadData()">Load Data</button>

					<input type='text' ng-model='firstName'>

					<input type='text' ng-model='lastName'>

					<input type='text' ng-model='address' placeholder='address'>

					<input type='text' ng-model='city' placeholder='city'>

					<input type='text' ng-model='state' placeholder='state'>

					<input type='text' ng-model='zip' placeholder='zip'>

					<input type='text' ng-model='phoneHome' placeholder='phoneHome'>

					<input type='text' ng-model='phoneMobile' placeholder='phoneMobile'>

					<input type='text' ng-model='email' placeholder='email'>

					<input id="indexSelection" type='number' ng-change="indexChange()" ng-model='userIndexSelection' min="0" max="{{presidentsLength-1}}">

Rows in DB: {{presidentsLength}}

					<button ng-click='addPresident()'>Add President</button>
					<button ng-click='updateRow()'>Update</button>
					<button ng-click='deleteRow()'>Delete</button>

{{selectedIndex}}

								{{president.firstName}} {{president.lastName}}

Back to top

© 2013 Company, Inc. · Privacy · Terms


text:
package ch.raffael.sangria.dynamic.spec.reflection;

/**
 * @author Raffael Herzog
 */
@Hierarchy({
        DupBar.class, IBar.class, IDup.class,
        DupFoo.class, IFoo.class,
        Object.class
})
public class DupBar extends DupFoo implements IBar, IDup {

}


text:
<?php
/* Configuração default para o Behavior Locale */
// Configure::write('Language.default', 'pt-br');

/* Definição de timezone para usar a classe DateTime */
// date_default_timezone_set('America/Sao_Paulo');

/* Definição de locale para formatar saída de Data, Hora, moedas e etc */
// setlocale(LC_ALL, 'pt_BR.utf-8', 'pt_BR', 'pt-br', 'pt_BR.iso-8859-1', 'portuguese');


text:
using Newtonsoft.Json.Linq;

namespace DevLab.JmesPath.Expressions
{
    public class JmesPathIndexExpression : JmesPathCompoundExpression
    {
        public JmesPathIndexExpression(JmesPathExpression expression, JmesPathExpression specifier)
            : base(expression, specifier)
        {
            System.Diagnostics.Debug.Assert(
                specifier is JmesPathIndex ||
                specifier is JmesPathFilterProjection ||
                specifier is JmesPathFlattenProjection ||
                specifier is JmesPathListWildcardProjection ||
                specifier is JmesPathSliceProjection ||
                false
                );
        }
    }
}


text:
import base64
import peekviewstate
from libs import utils

__author__  = "rich@kyr.us"
__version__ = 1.0
__updated__ = "09/07/2012"
__help__    = "Module for decoding viewstate parameters"
__alias__   = ["vsd"]

def Command(pymyo, name, *args):
    """
    Decodes a viewstate, based on a modified peekviewstate (https://code.google.com/p/peekviewstate)
    """
    for s in args:
        try:
            vs = base64.decodestring(s)
            pymyo.output( peekviewstate.parse(vs)[1] )
        except:
            pymyo.error("Error viewstate decoding %s"%(s) )


text:
import {expect} from "assertions"
import {ColumnDataSource} from "@bokehjs/models/sources/column_data_source"
import {GlyphRenderer} from "@bokehjs/models/renderers/glyph_renderer"
import {Circle} from "@bokehjs/models/glyphs"
import {build_view} from "@bokehjs/core/build_views"
import {Plot} from "@bokehjs/models/plots"

function mkrenderer(glyph_obj: Circle): GlyphRenderer {
  const source = new ColumnDataSource({
    data: {
      x: [10, 20, 30, 40],
      y: [1, 2, 3, 4],
      color: ["red", "green", "red", "green"],
      label: ["foo", "bar", "foo", "bar"],
    },
  })
  return new GlyphRenderer({glyph: glyph_obj, data_source: source})
}

describe("GlyphRendererView", async () => {
  // Basic case with no all glyphs going to their defaults

  const basic_circle = new Circle({fill_color: "red"})
  const glyph_renderer = mkrenderer(basic_circle)
  const grv = await build_view(
    glyph_renderer,
    {parent: await build_view(new Plot())},
  )

  const {glyph, selection_glyph, nonselection_glyph, muted_glyph, decimated_glyph} = grv

  describe("get_reference_point", () => {
    it("should return 0 if no field, value is passed", () => {
      const index = grv.get_reference_point(null)
      expect(index).to.be.equal(0)
    })

    it("should return 0 if field not in column data source", () => {
      const index = grv.get_reference_point("milk", "bar")
      expect(index).to.be.equal(0)
    })

    it("should return correct index if field and value in column data source", () => {
      const index = grv.get_reference_point("label", "bar")
      expect(index).to.be.equal(1)
    })

    it("should return 0 index if field in column data source but value not available", () => {
      const index = grv.get_reference_point("label", "baz")
      expect(index).to.be.equal(0)
    })
  })

  it("should have default selection_glyph equal to main glyph", () => {
    expect(selection_glyph.model.attributes).to.be.equal(glyph.model.attributes)
  })

  it("should have default nonselection_glyph with 0.2 alpha", () => {
    expect((nonselection_glyph.model as Circle).fill_alpha).to.be.equal({value: 0.2})
  })

  it("should have undefined hover_glyph if renderer hover_glyph is null", () => {
    expect(grv.model.hover_glyph).to.be.null
    expect(grv.hover_glyph).to.be.undefined
  })

  it("should have default muted_glyph with 0.2 alpha", () => {
    expect((muted_glyph.model as Circle).fill_alpha).to.be.equal({value: 0.2})
  })

  it("should have default decimated_glyph with 0.3 line alpha and color grey", () => {
    expect((decimated_glyph.model as Circle).line_alpha).to.be.equal({value: 0.3})
    expect((decimated_glyph.model as Circle).line_color).to.be.equal({value: "grey"})
  })

})


text:
const createLogger = require('./browser.js');

describe('createLogger() Browser API', () => {
	it('should be a function.', () => {
		expect(typeof createLogger).toBe('function');
	});

	it('should return an object containing the logger API.', () => {
		const logger = createLogger('foo');

		expect(typeof logger).toBe('object');
		expect(typeof logger.enforceLogging).toBe('function');
		expect(typeof logger.info).toBe('function');
		expect(typeof logger.warn).toBe('function');
		expect(typeof logger.success).toBe('function');
		expect(typeof logger.debug).toBe('function');
		expect(typeof logger.log).toBe('function');
		expect(typeof logger.error).toBe('function');
		expect(typeof logger.fatal).toBe('function');
	});
});


text:
package collins.models.lshw

import play.api.libs.json.Format
import play.api.libs.json.JsObject
import play.api.libs.json.JsSuccess
import play.api.libs.json.JsValue
import play.api.libs.json.Json

import collins.util.ByteStorageUnit

object Disk {

  type Type = Type.Value
  object Type extends Enumeration {
    val Ide = Value("IDE")
    val Scsi = Value("SCSI")
    val Flash = Value("PCIe")
    val CdRom = Value("CD-ROM")
  }

  implicit object DiskFormat extends Format[Disk] {
    override def reads(json: JsValue) = JsSuccess(Disk(
      ByteStorageUnit((json \ "SIZE").as[Long]),
      Disk.Type.withName((json \ "TYPE").as[String]),
      (json \ "DESCRIPTION").as[String],
      (json \ "PRODUCT").as[String],
      (json \ "VENDOR").as[String]))
    override def writes(disk: Disk) = JsObject(Seq(
      "SIZE" -> Json.toJson(disk.size.inBytes),
      "SIZE_S" -> Json.toJson(disk.size.inBytes.toString),
      "SIZE_HUMAN" -> Json.toJson(disk.size.toHuman),
      "TYPE" -> Json.toJson(disk.diskType.toString),
      "DESCRIPTION" -> Json.toJson(disk.description),
      "PRODUCT" -> Json.toJson(disk.product),
      "VENDOR" -> Json.toJson(disk.vendor)))
  }
}

case class Disk(
    size: ByteStorageUnit, diskType: Disk.Type, description: String, product: String, vendor: String) extends LshwAsset {

  import Disk._

  def isIde(): Boolean = diskType == Type.Ide
  def isScsi(): Boolean = diskType == Type.Scsi
  def isFlash(): Boolean = diskType == Type.Flash
  def isCdRom(): Boolean = diskType == Type.CdRom

  override def toJsValue() = Json.toJson(this)
}


text:
'use strict';

var grunt = require('grunt');

exports.couch = ['simple', 'full', 'advanced', 'merge', 'jsonfile', 'jsfile'].reduce(function(tests, name) {
  tests[name]= function(test) {
    test.expect(1);

    var actual = grunt.file.readJSON('tmp/' + name + '.json');
    var expected = grunt.file.readJSON('test/expected/' + name + '.json');
    test.deepEqual(actual, expected, 'should have compiled doc.');

    test.done();
  };

  return tests;
}, {});


text:
package org.camunda.bpm.engine.impl.core.variable.mapping.value;

import org.camunda.bpm.engine.delegate.VariableScope;

/**
 * @author Daniel Meyer
 *
 */
public class NullValueProvider implements ParameterValueProvider {

  public Object getValue(VariableScope variableScope) {
    return null;
  }

  @Override
  public boolean isDynamic() {
    return false;
  }
}


text:
// Copyright (C) 2006 Google Inc.
//
// 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.enterprise.connector.spi;

import com.google.common.base.Charsets;
import com.google.enterprise.connector.common.StringUtils;
import com.google.enterprise.connector.manager.Context;
import com.google.enterprise.connector.spiimpl.BinaryValue;
import com.google.enterprise.connector.spiimpl.BooleanValue;
import com.google.enterprise.connector.util.InputStreamFactory;

import junit.framework.Assert;
import junit.framework.TestCase;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

/**
 * Unit tests for the {@link Value} class.
 */
public class ValueTest extends TestCase {
  @Override
  public void setUp() {
    // RFC 822 is English-only, and ISO 8601 isn't locale-sensitive,
    // so change the locale but expect the same results.
    Locale.setDefault(Locale.FRENCH);
  }

  @Override
  public void tearDown() {
    // Reset the default time zone.
    Value.setFeedTimeZone("");
  }

  public void testCalendarToIso8601() {
    // We're comparing date strings here, so we need a fixed time zone.
    Value.setFeedTimeZone("GMT");

    Calendar c = Calendar.getInstance();
    Date d = new Date(999);
    c.setTime(d);
    String s = Value.calendarToIso8601(c);
    Assert.assertEquals("1970-01-01T00:00:00.999Z", s);
  }

  public void testIso8601ToCalendar() throws ParseException {
    {
      String s = "1970-01-01T00:00:00.999Z";
      Calendar c = Value.iso8601ToCalendar(s);
      Date d = c.getTime();
      long millis = d.getTime();
      Assert.assertEquals(999, millis);
    }
    {
      String s = "1970-01-01T00:00:50Z";
      Calendar c = Value.iso8601ToCalendar(s);
      Date d = c.getTime();
      long millis = d.getTime();
      Assert.assertEquals(50000, millis);
    }
  }

  public void testCalendarToRfc822() {
    // We're comparing date strings here, so we need a fixed time zone.
    Value.setFeedTimeZone("GMT");

    Calendar c = Calendar.getInstance();
    Date d = new Date(999);
    c.setTime(d);
    String s = Value.calendarToRfc822(c);
    Assert.assertEquals("Thu, 01 Jan 1970 00:00:00 GMT", s);
  }

  /**
   * Represents the prefix and suffix of formatted timestamp strings
   * for a specific date in both the RFC 822 and ISO 8601 formats.
   */
  private static class DateFragments {
    public final String rfc822Date;
    public final String rfc822TimeZone;
    public final String iso8601Date;
    public final String iso8601TimeZone;

    public DateFragments(String rfc822Date, String rfc822TimeZone,
        String iso8601Date, String iso8601TimeZone) {
      this.rfc822Date = rfc822Date;
      this.rfc822TimeZone = rfc822TimeZone;
      this.iso8601Date = iso8601Date;
      this.iso8601TimeZone = iso8601TimeZone;
    }
  }

  /** Tests the local time zone. */
  public void testDefaultTimeZone() {
    Value.setFeedTimeZone("");
    Calendar timestamp = Calendar.getInstance();
    // We have to compute the offset in this case, because we do not
    // know the time zone. Due to Daylight Savings Time, which may
    // alter the UTC offset of any given time zone, we need to use the
    // date under test, rather than the current date, to get the right
    // offset. The date used here should match the dates in
    // testTimeZoneOFfset.
    // TODO(jlacey): Find a way to isolate this from test data changes.
    timestamp.set(2000, 11 /* zero-based */, 31);
    int offset = timestamp.get(Calendar.ZONE_OFFSET)
        + timestamp.get(Calendar.DST_OFFSET);
    int minutes = offset / 60 / 1000;
    String timezone = String.format("%+03d%02d", minutes / 60,
        Math.abs(minutes % 60));
    testTimeZoneOffset(timestamp, offset, timezone);
  }

  /**
   * Tests the given time zone.
   *
   * @param offset the offset does not have to match the
   * timezone value, it just needs to have the right sign
   * @param timezone the UTC offset as a timezone string, e.g., "-0800"
   */
  private void testFixedTimeZone(int offset, String timezone) {
    Value.setFeedTimeZone("GMT" + timezone);
    Calendar timestamp = Calendar.getInstance();
    timestamp.setTimeZone(TimeZone.getTimeZone("GMT" + timezone));
    testTimeZoneOffset(timestamp, offset, timezone);
  }

  /** Tests a time zone west of UTC. The details do not matter. */
  public void testWestTimeZone() {
    testFixedTimeZone(-1, "-0500");
  }

  /** Tests a time zone east of UTC. The details do not matter. */
  public void testEastTimeZone() {
    testFixedTimeZone(+1, "+1100");
  }

  /** Tests the UTC time zone. */
  public void testUtcTimeZone() {
    testFixedTimeZone(0, "+0000");
  }

  /**
   * Tests converting a timestamp with the default local time zone,
   * setting the time zone, and converting the same timestamp again.
   *
   * NOTE: We want all of the Value methods to be called in this same
   * test method, because the Java date-time classes do some strange
   * cloning behind the scenes, and we need to make sure that
   * Value.setFeedTimeZone correctly affects all of the SimpleDateFormat
   * instances in the Value class.
   *
   * @param timestamp a calendar with the time zone set as desired
   * @param offset the offset does not have to match the
   * timezone value, it just needs to have the right sign
   * @param timezone the UTC offset as a timezone string, e.g., "-0800"
   */
  private void testTimeZoneOffset(Calendar timestamp, int offset,
      String timezone) {
    timestamp.clear();
    DateFragments local;
    DateFragments other;
    String otherId;
    // The test and local dates here should be less than an hour from
    // midnight, so that the date in the other time zone is different.
    // If the dates used here change, especially across a DST bounday,
    // you need to change the date used in testDefaultTimeZone.
    if (offset < 0) {
      // West of prime meridian.
      timestamp.set(2000, 11 /* zero-based */, 31, 23, 59, 01);
      local = new DateFragments("Sun, 31 Dec 2000", timezone,
          "2000-12-31", timezone);
      other = new DateFragments("Mon, 01 Jan 2001", "GMT", "2001-01-01", "Z");
      otherId = "GMT";
    } else if (offset > 0) {
      // East of prime meridian.
      timestamp.set(2001, 0 /* zero-based */, 1, 00, 00, 59);
      local = new DateFragments("Mon, 01 Jan 2001", timezone,
          "2001-01-01", timezone);
      other = new DateFragments("Sun, 31 Dec 2000", "GMT", "2000-12-31", "Z");
      otherId = "GMT";
    } else {
      // UTC
      timestamp.set(2001, 0 /* zero-based */, 1, 00, 00, 59);
      local = new DateFragments("Mon, 01 Jan 2001", "GMT", "2001-01-01", "Z");
      // Do not use timezone in this case, which is "+0000".
      other = new DateFragments("Sun, 31 Dec 2000", "-0800",
          "2000-12-31", "-0800");
      otherId = "GMT-0800";
    }

    testTimeZoneFragments(timestamp, local);
    Value.setFeedTimeZone(otherId);
    testTimeZoneFragments(timestamp, other);
  }

  /**
   * Calls all three formatting methods in Value and
   * compares the results to the given fragments.
   *
   * @param timestamp a calendar with the time and time zone set as desired
   * @param expected the expected date string fragments
   */
  private void testTimeZoneFragments(Calendar timestamp,
      DateFragments expected) {
    String s;
    s = Value.calendarToRfc822(timestamp);
    assertTrue(s, s.startsWith(expected.rfc822Date));
    assertTrue(s, s.endsWith(expected.rfc822TimeZone));
    s = Value.calendarToIso8601(timestamp);
    assertTrue(s, s.startsWith(expected.iso8601Date));
    assertTrue(s, s.endsWith(expected.iso8601TimeZone));
    s = Value.calendarToFeedXml(timestamp);
    assertEquals(expected.iso8601Date, s);
  }

  private static final String TEST_DIR = "testdata/contextTests/value/";

  /** Tests the default Spring configuration. */
  public void testDefaultConfig() throws Exception {
    testConfig(TEST_DIR + "default.xml", TimeZone.getDefault().getID());
  }

  /**
   * Tests the Spring configuration and an explicit time zone. This
   * test uses an offset, because those are unlikely to be the default
   * time zone, due to Daylight Savings Time. As an added but probably
   * unnecessary protection, we use GMT+0100, which is almost empty
   * during standard time or DST.
   */
  public void testOffsetConfig() throws Exception {
    testConfig(TEST_DIR + "offset.xml", "GMT+01:00");
  }

  private void testConfig(String applicationContext, String expectedId) {
    Context.refresh();
    Context context = Context.getInstance();
    context.setStandaloneContext(applicationContext, null);

    assertEquals(expectedId, Value.getFeedTimeZone());
  }

  private static final String CONTENTS = "Test Content";
  private static final byte[] CONTENTS_BYTES =
      CONTENTS.getBytes(Charsets.UTF_8);

  /** Tests BinaryValue constructors - byte array. */
  public void testBinaryValueByteArray() throws Exception {
    testBinaryValue(Value.getBinaryValue(CONTENTS_BYTES));
  }

  /** Tests BinaryValue constructors - InputStream. */
  public void testBinaryValueInputStream() throws Exception {
    testBinaryValue(Value.getBinaryValue(
        new ByteArrayInputStream(CONTENTS_BYTES)));
  }

  /** Tests BinaryValue constructors - InputStreamFactory. */
  public void testBinaryValueInputStreamFactory() throws Exception {
    testBinaryValue(Value.getBinaryValue(
        new InputStreamFactory() {
          public InputStream getInputStream() {
            return new ByteArrayInputStream(CONTENTS_BYTES);
          }
        }));
  }

  /** Tests BinaryValue constructors - InputStreamFactory. */
  public void testBinaryValueInputStreamFactoryError() throws Exception {
    BinaryValue value = (BinaryValue) Value.getBinaryValue(
        new InputStreamFactory() {
          public InputStream getInputStream() throws IOException {
            throw new IOException("Test Exception");
          }
        });

    try {
      value.getInputStream();
      fail("Expected RepositoryDocumentException, but got none.");
    } catch (RepositoryDocumentException expected) {
      // Expected.
    }
  }

  /** Tests reading a BinaryValue. */
  public void testBinaryValue(Value value) throws Exception {
    assertTrue(value instanceof BinaryValue);
    InputStream is = ((BinaryValue) value).getInputStream();
    assertNotNull(is);
    assertEquals(CONTENTS, StringUtils.streamToStringAndThrow(is));
  }

  /** Asserts that the Value represents a boolean of the expected value. */
  private void assertValueEquals(boolean expected, Value value) {
    assertEquals(value.toString(), BooleanValue.class, value.getClass());
    assertEquals(value.toString(),
        expected, ((BooleanValue) value).toBoolean());
  }

  public void testBooleanValue_f() {
    assertValueEquals(false, Value.getBooleanValue("f"));
  }

  public void testBooleanValue_false() {
    assertValueEquals(false, Value.getBooleanValue("false"));
  }

  public void testBooleanValue_FaLsE() {
    assertValueEquals(false, Value.getBooleanValue("FaLsE"));
  }

  public void testBooleanValue_t() {
    assertValueEquals(true, Value.getBooleanValue("t"));
  }

  public void testBooleanValue_true() {
    assertValueEquals(true, Value.getBooleanValue("true"));
  }

  public void testBooleanValue_TRUE() {
    assertValueEquals(true, Value.getBooleanValue("TRUE"));
  }

  public void testBooleanValue_helloworld() {
    assertValueEquals(true, Value.getBooleanValue("hello, world"));
  }

  public void testBooleanValue_empty() {
    assertValueEquals(true, Value.getBooleanValue(""));
  }

  public void testBooleanValue_null() {
    assertValueEquals(true, Value.getBooleanValue(null));
  }
}


text:
package org.apache.poi.hssf.converter;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormatter;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hwpf.converter.AbstractWordConverter;
import org.apache.poi.hwpf.converter.DefaultFontReplacer;
import org.apache.poi.hwpf.converter.FontReplacer;
import org.apache.poi.hwpf.converter.NumberFormatter;
import org.apache.poi.ss.formula.eval.ErrorEval;
import org.apache.poi.util.Beta;
import org.w3c.dom.Document;

/**
 * Common class for {@link ExcelToFoConverter} and {@link ExcelToHtmlConverter}
 *
 * @author Sergey Vladimirov (vlsergey {at} gmail {dot} com)
 * @see AbstractWordConverter
 */
@Beta
public abstract class AbstractExcelConverter
{
    protected static int getColumnWidth( HSSFSheet sheet, int columnIndex )
    {
        return ExcelToHtmlUtils.getColumnWidthInPx( sheet
                .getColumnWidth( columnIndex ) );
    }

    protected static int getDefaultColumnWidth( HSSFSheet sheet )
    {
        return ExcelToHtmlUtils.getColumnWidthInPx( sheet
                .getDefaultColumnWidth() );
    }

    protected final HSSFDataFormatter _formatter = new HSSFDataFormatter();

    private FontReplacer fontReplacer = new DefaultFontReplacer();

    private boolean outputColumnHeaders = true;

    private boolean outputHiddenColumns = false;

    private boolean outputHiddenRows = false;

    private boolean outputLeadingSpacesAsNonBreaking = true;

    private boolean outputRowNumbers = true;

    /**
     * Generates name for output as column header in case
     * <tt>{@link #isOutputColumnHeaders()} == true</tt>
     *
     * @param columnIndex
     *            0-based column index
     */
    protected String getColumnName( int columnIndex )
    {
        return NumberFormatter.getNumber( columnIndex + 1, 3 );
    }

    protected abstract Document getDocument();

    public FontReplacer getFontReplacer()
    {
        return fontReplacer;
    }

    /**
     * Generates name for output as row number in case
     * <tt>{@link #isOutputRowNumbers()} == true</tt>
     */
    protected String getRowName( HSSFRow row )
    {
        return String.valueOf( row.getRowNum() + 1 );
    }

    public boolean isOutputColumnHeaders()
    {
        return outputColumnHeaders;
    }

    public boolean isOutputHiddenColumns()
    {
        return outputHiddenColumns;
    }

    public boolean isOutputHiddenRows()
    {
        return outputHiddenRows;
    }

    public boolean isOutputLeadingSpacesAsNonBreaking()
    {
        return outputLeadingSpacesAsNonBreaking;
    }

    public boolean isOutputRowNumbers()
    {
        return outputRowNumbers;
    }

    protected boolean isTextEmpty( HSSFCell cell )
    {
        final String value;
        switch ( cell.getCellTypeEnum() )
        {
        case STRING:
            // XXX: enrich
            value = cell.getRichStringCellValue().getString();
            break;
        case FORMULA:
            switch ( cell.getCachedFormulaResultTypeEnum() )
            {
            case STRING:
                HSSFRichTextString str = cell.getRichStringCellValue();
                if ( str == null || str.length() <= 0 )
                    return false;

                value = str.toString();
                break;
            case NUMERIC:
                HSSFCellStyle style = cell.getCellStyle();
                double nval = cell.getNumericCellValue();
                short df = style.getDataFormat();
                String dfs = style.getDataFormatString();
                value = _formatter.formatRawCellContents(nval, df, dfs);
                break;
            case BOOLEAN:
                value = String.valueOf( cell.getBooleanCellValue() );
                break;
            case ERROR:
                value = ErrorEval.getText( cell.getErrorCellValue() );
                break;
            default:
                value = ExcelToHtmlUtils.EMPTY;
                break;
            }
            break;
        case BLANK:
            value = ExcelToHtmlUtils.EMPTY;
            break;
        case NUMERIC:
            value = _formatter.formatCellValue( cell );
            break;
        case BOOLEAN:
            value = String.valueOf( cell.getBooleanCellValue() );
            break;
        case ERROR:
            value = ErrorEval.getText( cell.getErrorCellValue() );
            break;
        default:
            return true;
        }

        return ExcelToHtmlUtils.isEmpty( value );
    }

    public void setFontReplacer( FontReplacer fontReplacer )
    {
        this.fontReplacer = fontReplacer;
    }

    public void setOutputColumnHeaders( boolean outputColumnHeaders )
    {
        this.outputColumnHeaders = outputColumnHeaders;
    }

    public void setOutputHiddenColumns( boolean outputZeroWidthColumns )
    {
        this.outputHiddenColumns = outputZeroWidthColumns;
    }

    public void setOutputHiddenRows( boolean outputZeroHeightRows )
    {
        this.outputHiddenRows = outputZeroHeightRows;
    }

    public void setOutputLeadingSpacesAsNonBreaking(
            boolean outputPrePostSpacesAsNonBreaking )
    {
        this.outputLeadingSpacesAsNonBreaking = outputPrePostSpacesAsNonBreaking;
    }

    public void setOutputRowNumbers( boolean outputRowNumbers )
    {
        this.outputRowNumbers = outputRowNumbers;
    }

}


text:
"""Unit tests for extended_attributes.py."""

import unittest

from .extended_attribute import ExtendedAttribute
from .extended_attribute import ExtendedAttributes

class TestableExtendedAttribute(ExtendedAttribute):
    FORM_NO_ARGS = ExtendedAttribute._FORM_NO_ARGS
    FORM_IDENT = ExtendedAttribute._FORM_IDENT
    FORM_IDENT_LIST = ExtendedAttribute._FORM_IDENT_LIST
    FORM_ARG_LIST = ExtendedAttribute._FORM_ARG_LIST
    FORM_NAMED_ARG_LIST = ExtendedAttribute._FORM_NAMED_ARG_LIST

    def __init__(self, key, values=None, arguments=None, name=None):
        super(TestableExtendedAttribute, self).__init__(
            key=key, values=values, arguments=arguments, name=name)

    @property
    def format(self):
        return self._format

class ExtendedAttributeTest(unittest.TestCase):
    def test_attribute_create(self):
        # NoArgs
        attr = TestableExtendedAttribute(key='Foo')
        self.assertEqual(attr.format, TestableExtendedAttribute.FORM_NO_ARGS)
        self.assertEqual(attr.key, 'Foo')
        self.assertEqual(attr.value, None)
        self.assertEqual(attr.values, ())
        with self.assertRaises(ValueError):
            _ = attr.arguments
        with self.assertRaises(ValueError):
            _ = attr.name

        # Ident
        attr = TestableExtendedAttribute(key='Bar', values='Val')
        self.assertEqual(attr.format, TestableExtendedAttribute.FORM_IDENT)
        self.assertEqual(attr.key, 'Bar')
        self.assertEqual(attr.value, 'Val')
        self.assertEqual(attr.values, ('Val', ))
        with self.assertRaises(ValueError):
            _ = attr.arguments
        with self.assertRaises(ValueError):
            _ = attr.name

        # IdentList
        attr = TestableExtendedAttribute(key='Buz', values=('Val', 'ue'))
        self.assertEqual(attr.format,
                         TestableExtendedAttribute.FORM_IDENT_LIST)
        self.assertEqual(attr.key, 'Buz')
        self.assertEqual(attr.values, ('Val', 'ue'))
        attr = TestableExtendedAttribute(
            key='IdentList', values=['Val', 'ue', 'List'])
        self.assertEqual(attr.values, ('Val', 'ue', 'List'))
        with self.assertRaises(ValueError):
            _ = attr.arguments
        with self.assertRaises(ValueError):
            _ = attr.name

        # ArgList
        attr = TestableExtendedAttribute(
            key='Foo', arguments=(('Left', 'Right'), ('foo', 'bar')))
        self.assertEqual(attr.format, TestableExtendedAttribute.FORM_ARG_LIST)
        self.assertEqual(attr.key, 'Foo')
        with self.assertRaises(ValueError):
            _ = attr.values
        self.assertEqual(attr.arguments, (('Left', 'Right'), ('foo', 'bar')))
        with self.assertRaises(ValueError):
            _ = attr.name

        # NamedArgList
        attr = TestableExtendedAttribute(
            key='Bar', arguments=(('Left', 'Right'), ), name='Buz')
        self.assertEqual(attr.format,
                         TestableExtendedAttribute.FORM_NAMED_ARG_LIST)
        self.assertEqual(attr.key, 'Bar')
        with self.assertRaises(ValueError):
            _ = attr.values
        self.assertEqual(attr.arguments, (('Left', 'Right'), ))
        self.assertEqual(attr.name, 'Buz')

    def test_attributes(self):
        attrs = [
            ExtendedAttribute(key='A', values='val'),
            ExtendedAttribute(key='B'),
            ExtendedAttribute(key='C', values=('Val', 'ue')),
            ExtendedAttribute(key='B', values=('Val', 'ue', 'B'))
        ]
        attributes = ExtendedAttributes(attrs)
        self.assertTrue('A' in attributes)
        self.assertFalse('D' in attributes)
        self.assertEqual(attributes.get('A').value, 'val')
        b_values = attributes.get_list_of('B')
        self.assertEqual(b_values[0].values, ())
        self.assertEqual(b_values[1].values, ('Val', 'ue', 'B'))


text:
[![Build Status](https://travis-ci.org/codecombat/aether.png)](https://travis-ci.org/codecombat/aether)

## Purpose
Aether aims to make it easy for people to learn and write JavaScript and CoffeeScript by helping them catch and fix bugs,
letting them see and more easily understand the execution of their program [(like Bret Victor commanded!)](http://youtu.be/PUv66718DII?t=17m25s),
and giving them tips on how they can improve their code. [CodeCombat](http://codecombat.com/) is behind it.

## Get in touch
You can use the [GitHub issues](https://github.com/codecombat/aether/issues), the [Discourse forum](http://discourse.codecombat.com/), the [HipChat](http://www.hipchat.com/g3plnOKqa), or [email](mailto:nick@codecombat.com) [Nick](http://www.nickwinter.net/).

## What is it?
It's a JavaScript library (written in CoffeeScript) that takes user code as input; does computer-sciencey transpilation things to it with the help of [JSHint](http://jshint.com/), [Esprima](http://esprima.org/), [JS_WALA](https://github.com/wala/JS_WALA), [escodegen](https://github.com/Constellation/escodegen), and [traceur](https://github.com/google/traceur-compiler); and gives you linting, transformation, sandboxing, instrumentation, time-travel debugging, style analysis, autocompletion, and more.

## Devour [aetherjs.com](http://aetherjs.com) for docs, demos, and developer discourse

## License
[The MIT License (MIT)](https://github.com/codecombat/aether/blob/master/LICENSE)

If you'd like to contribute, please [sign the CodeCombat contributor license agreement](http://codecombat.com/cla) so we can accept your pull requests. It is easy.

======

![aether logo](http://i.imgur.com/uf36eRD.jpg)


text:
package com.be_hase.honoumi.controller.argument;

import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.MessageEvent;

import com.be_hase.honoumi.exception.ArgumentResolveException;

public interface ArgumentResolver<T> {
	public T resolveArgument(ChannelHandlerContext ctx, MessageEvent evt) throws ArgumentResolveException;

	public boolean supportedType(Class<?> klass);
}