text:
import ply.lex as lex
import AST
import json, os, re, sys

import bsvpreprocess
import globalv
import cppgen, bsvgen

scripthome = os.path.dirname(os.path.abspath(__file__))
noisyFlag=True
parseDebugFlag=False
parseTrace=False

tokens = (
    'AMPER',
    'AMPERAMPER',
    'AMPERAMPERAMPER',
    'APOSTROPHE',
    'BANG',
    'BAR',
    'BARBAR',
    'BUILTINVAR',
    'CARET',
    'COLON',
    'COLONCOLON',
    'COMMA',
    'DOT',
    'EQEQ',
    'EQUAL',
    'GEQ',
    'GREATER',
    'GREATERGREATER',
    'HASH',
    'LARROW',
    'LBRACE',
    'LBRACKET',
    'LEQ',
    'LESS',
    'LESSLESS',
    'LPAREN',
    'LPARENSTAR',
    'MINUS',
    'NEQ',
    'NUM',
    'PERCENT',
    'PLUS',
    'QUESTION',
    'RBRACE',
    'RBRACKET',
    'RPAREN',
    'RPARENSTAR',
    'SEMICOLON',
    'SLASH',
    'STAR',
    'STARSTAR',
    'STR',
    'TILDE',
    'TILDEAMPER',
    'TILDEBAR',
    'TILDECARET',
    'VAR'
)

reserved = {
    'action': 'TOKACTION',
    'Action': 'TOKUACTION',
    'actionvalue': 'TOKACTIONVALUE',
    'BDPI': 'TOKBDPI',
    'begin': 'TOKBEGIN',
    'BVI': 'TOKBVI',
    'C': 'TOKC',
    'case': 'TOKCASE',
    'CF': 'TOKCF',
    'clocked_by': 'TOKCLOCKED_BY',
    'default': 'TOKDEFAULT',
    'default_clock': 'TOKDEFAULT_CLOCK',
    'default_reset': 'TOKDEFAULT_RESET',
    '`define': 'TOKTICKDEFINE',
    'dependencies': 'TOKDEPENDENCIES',
    'deriving': 'TOKDERIVING',
    'determines': 'TOKDETERMINES',
    'else': 'TOKELSE',
    'enable': 'TOKENABLE',
    'end': 'TOKEND',
    'endaction': 'TOKENDACTION',
    'endactionvalue': 'TOKENDACTIONVALUE',
    'endcase': 'TOKENDCASE',
    'endfunction': 'TOKENDFUNCTION',
    'endinstance': 'TOKENDINSTANCE',
    'endinterface': 'TOKENDINTERFACE',
    'endmethod': 'TOKENDMETHOD',
    'endmodule': 'TOKENDMODULE',
    'endpackage': 'TOKENDPACKAGE',
    'endpar': 'TOKENDPAR',
    'endrule': 'TOKENDRULE',
    'endrules': 'TOKENDRULES',
    'endseq': 'TOKENDSEQ',
    'endtypeclass': 'TOKENDTYPECLASS',
    'enum': 'TOKENUM',
    'export': 'TOKEXPORT',
    'for': 'TOKFOR',
    'function': 'TOKFUNCTION',
    'if': 'TOKIF',
    'import': 'TOKIMPORT',
#    'in': 'TOKIN',
    'input_clock': 'TOKINPUT_CLOCK',
    'input_reset': 'TOKINPUT_RESET',
    'instance': 'TOKINSTANCE',
    'interface': 'TOKINTERFACE',
    'let': 'TOKLET',
    'match': 'TOKMATCH',
    'matches': 'TOKMATCHES',
    'method': 'TOKMETHOD',
    'module': 'TOKMODULE',
    'no_reset': 'TOKNO_RESET',
    'numeric': 'TOKNUMERIC',
    'output_clock': 'TOKOUTPUT_CLOCK',
    'output_reset': 'TOKOUTPUT_RESET',
    'package': 'TOKPACKAGE',
    'par': 'TOKPAR',
    'port': 'TOKPORT',
    'parameter': 'TOKPARAMETER',
    'port': 'TOKPORT',
    'provisos': 'TOKPROVISOS',
    'ready': 'TOKREADY',
    'reset_by': 'TOKRESET_BY',
    'return': 'TOKRETURN',
    'rule': 'TOKRULE',
    'rules': 'TOKRULES',
    'SB': 'TOKSB',
    'SBR': 'TOKSBR',
    'schedule': 'TOKSCHEDULE',
    'seq': 'TOKSEQ',
    '_when_': 'TOKWHEN',
    'Stmt' : 'TOKSTMT',
    'struct': 'TOKSTRUCT',
    'tagged': 'TOKTAGGED',
    'type': 'TOKTYPE',
    'typeclass': 'TOKTYPECLASS',
    'typedef': 'TOKTYPEDEF',
    'union': 'TOKUNION',
    'while': 'TOKWHILE',
}

for tok in reserved.values():
    tokens = tokens + (tok,)

t_AMPER = r'&'
t_AMPERAMPER = r'&&'
t_AMPERAMPERAMPER = r'&&&'
t_APOSTROPHE = r'\''
t_BANG = r'!'
t_BAR = r'\|'
t_BARBAR = r'\|\|'
t_CARET = r'\^'
t_COLON = r':'
t_COLONCOLON = r'::'
t_COMMA = r','
t_DOT = r'[\.]'
t_EQEQ = r'=='
t_EQUAL = r'='
t_GEQ = r'>='
t_GREATER = r'>'
t_GREATERGREATER = r'>>'
t_HASH = r'\#'
t_LARROW = r'<-'
t_LBRACE = r'{'
t_LBRACKET = r'\['
t_LEQ = r'<='
t_LESS = r'<'
t_LESSLESS = r'<<'
t_LPAREN = r'\('
t_LPARENSTAR = r'\(\*'
t_MINUS = r'[-]'
t_NEQ = r'!='
t_NUM = r'(([0-9]+\'?[bdh\.]?[0-9a-zA-Z?]*)|(\'[bdh\.]?[0-9a-zA-Z?]+))'
t_PERCENT = r'%'
t_PLUS = r'\+'
t_QUESTION = r'\?'
t_RBRACE = r'}'
t_RBRACKET = r'\]'
t_RPAREN = r'\)'
t_RPARENSTAR = r'\*\)'
t_SEMICOLON = r';'
t_SLASH = r'/'
t_STAR = r'\*'
t_STARSTAR = r'\*\*'
t_STR = r'"[^\"]*"'
t_TILDE = r'~'
t_TILDEAMPER = r'~\&'
t_TILDEBAR = r'~\|'
t_TILDECARET = r'~^'

t_ignore = ' \t\f'

def t_error(t):
    print "Illegal character '%s' in file '%s'" % (t.value[0], globalfilename)
    t.lexer.skip(1)

def p_error(errtoken):
    if hasattr(errtoken, 'lineno'):
        sys.stderr.write("%s:%d: Syntax error, token=%s\n" % (globalfilename, errtoken.lineno, errtoken.type))
    else:
        sys.stderr.write("%s: Syntax error, token=%s\n" % (globalfilename, errtoken))
    return None

def t_VAR(t):
    r'`?([a-zA-Z_][$a-zA-Z0-9_]*)|(\\[-+*/|^&][*]?)'
    t.type = reserved.get(t.value,'VAR')
    return t

t_BUILTINVAR = r'\$[a-zA-Z_][a-zA-Z0-9_]*'

def t_newline(t):
    r'\n+'
    t.lexer.lineno += len(t.value)

def t_COMMENT(t):
    r'//.*'
    pass

def t_MCOMMENT(t):
    r'/\*(.|\n)*?\*/'
    #print t.value, t.value.count('\n'), t.lineno
    t.lineno += t.value.count('\n')

import ply.yacc as yacc

def p_goal(p):
    'goal : package '
    p[0] = p[1]

def p_typeParams(p):
    '''typeParams :
                  | type
                  | typeParams COMMA type'''
    if len(p) == 2:
        p[0] = [p[1]]
    elif len(p) == 4:
        p[0] = p[1] + [p[3]]
    else:
        p[0] = []

def p_type(p):
    '''type : VAR
            | VAR COLONCOLON VAR
            | NUM
            | TOKUACTION
            | VAR HASH LPAREN typeParams RPAREN
            | VAR COLONCOLON VAR HASH LPAREN typeParams RPAREN'''
    if len(p) == 2:
        p[0] = AST.Type(p[1], [])
    elif len(p) == 4:
        p[0] = p[3]
    elif len(p) == 8:
        p[0] = AST.Type(p[3], p[6])
    else:
        p[0] = AST.Type(p[1], p[4])

def p_expressions(p):
    '''expressions : expression
                   |
                   | expressions COMMA expression'''

precedence = (
    ('left', 'STAR', 'SLASH', 'PERCENT'),
    ('left', 'PLUS', 'MINUS'),
    ('left', 'GREATERGREATER', 'LESSLESS'),
    ('left', 'LEQ', 'GEQ', 'LESS', 'GREATER'),
    ('left', 'EQEQ', 'NEQ'),
    ('left', 'AMPER'),
    ('left', 'CARET'),
    ('left', 'TILDECARET'),
    ('left', 'BAR'),
    ('left', 'AMPERAMPER'),
    ('left', 'BARBAR'),
    ('left', 'AMPERAMPERAMPER')
)

def p_colonVar(p):
    '''colonVar :
                | COLON VAR'''

def p_expression(p):
    '''expression : caseExpr
                  | binaryExpression'''
    p[0] = p[1]

def p_caseExprItem(p):
    '''caseExprItem : pattern COLON expression SEMICOLON'''

def p_caseExprItems(p):
    '''caseExprItems :
                 | caseExprItems caseExprItem'''

def p_defaultExprItem(p):
    '''defaultExprItem :
                   | TOKDEFAULT expression SEMICOLON
                   | TOKDEFAULT COLON expression SEMICOLON'''

def p_caseExpr(p):
    '''caseExpr : TOKCASE LPAREN expression RPAREN caseExprItems defaultExprItem TOKENDCASE
                | TOKCASE LPAREN expression RPAREN TOKMATCHES caseExprItems defaultExprItem TOKENDCASE'''

def p_binaryExpression(p):
    '''binaryExpression : unaryExpression
                        | binaryExpression AMPERAMPERAMPER binaryExpression
                        | binaryExpression MINUS binaryExpression
                        | binaryExpression PLUS binaryExpression
                        | binaryExpression STAR binaryExpression
                        | binaryExpression STARSTAR binaryExpression
                        | binaryExpression APOSTROPHE binaryExpression
                        | binaryExpression SLASH binaryExpression
                        | binaryExpression CARET binaryExpression
                        | binaryExpression LESS binaryExpression
                        | binaryExpression GREATER binaryExpression
                        | binaryExpression GEQ binaryExpression
                        | binaryExpression LESSLESS binaryExpression
                        | binaryExpression LEQ binaryExpression
                        | binaryExpression GREATERGREATER binaryExpression
                        | binaryExpression EQEQ binaryExpression
                        | binaryExpression NEQ binaryExpression
                        | binaryExpression AMPER binaryExpression
                        | binaryExpression AMPERAMPER binaryExpression
                        | binaryExpression BAR binaryExpression
                        | binaryExpression BARBAR binaryExpression
                        | binaryExpression PERCENT binaryExpression'''
    p[0] = p[1]

def p_unaryExpression(p):
    '''unaryExpression : term
                       | PLUS term
                       | MINUS term
                       | BANG term
                       | TILDE term
                       | AMPER term
                       | TILDEAMPER term
                       | BAR term
                       | TILDEBAR term
                       | CARET term
                       | TILDECARET term
                       | TOKACTION colonVar expressionStmts TOKENDACTION colonVar
                       | TOKACTIONVALUE colonVar expressionStmts TOKENDACTIONVALUE colonVar
                       '''
    p[0] = p[1]

def p_term(p):
    '''term : type
            | type LBRACKET expression RBRACKET
            | type LBRACKET expression COLON expression RBRACKET
            | STR
            | QUESTION
            | term QUESTION expression
            | term QUESTION expression COLON expression
            | LPAREN expression RPAREN
            | TOKINTERFACE VAR interfaceHashParams SEMICOLON expressionStmts TOKENDINTERFACE colonVar
            | TOKINTERFACE VAR COLONCOLON VAR interfaceHashParams SEMICOLON expressionStmts TOKENDINTERFACE colonVar
            | TOKINTERFACE VAR expressionStmts TOKENDINTERFACE colonVar
            | TOKINTERFACE VAR COLONCOLON VAR expressionStmts TOKENDINTERFACE colonVar
            | BUILTINVAR
            | TOKCLOCKED_BY expression
            | TOKRESET_BY expression
            | TOKTAGGED VAR
            | TOKTAGGED VAR expression
            | TOKTAGGED VAR LBRACE structInits RBRACE
            | term LBRACE structInits RBRACE
            | term TOKMATCHES pattern
            | LBRACE expressions RBRACE
            | term DOT VAR
            | term LBRACKET expression RBRACKET DOT term
            | term LBRACKET expression RBRACKET
            | term LBRACKET expression COLON expression RBRACKET
            | term LPAREN params RPAREN DOT term
            | term LPAREN params RPAREN'''
    if len(p) > 2 and type(p[1]) == str:
        p[0] = p[2]
    else:
        p[0] = p[1]

def p_structInits(p):
    '''structInits :
                   | structInits COMMA VAR COLON expression
                   | structInits COMMA VAR COLON DOT VAR
                   | VAR COLON expression
                   | VAR COLON DOT VAR'''

def p_structPatternElements(p):
    '''structPatternElements : VAR COLON pattern
                             | structPatternElements COMMA VAR COLON pattern '''

def p_pattern(p):
    '''pattern : TOKTAGGED VAR
               | TOKTAGGED VAR DOT VAR
               | TOKTAGGED VAR LBRACE structPatternElements RBRACE
               | LBRACE patterns RBRACE
               | DOT VAR
               | DOT STAR
               | NUM'''

def p_patterns(p):
    '''patterns : pattern
                | patterns COMMA pattern'''

def p_importDecl(p):
    'importDecl : TOKIMPORT VAR COLONCOLON STAR SEMICOLON'
    if not p[2] in globalimports:
        globalimports.append(p[2])
    p[0] = p[2]

def p_importDecls(p):
    '''importDecls :
                   | importDecls importDecl'''

def p_exportDecl(p):
    '''exportDecl : TOKEXPORT VAR LPAREN DOT DOT RPAREN SEMICOLON
                  | TOKEXPORT VAR SEMICOLON
                  | TOKEXPORT VAR COLONCOLON STAR SEMICOLON'''
    p[0] = p[2]

def p_exportDecls(p):
    '''exportDecls :
                   | exportDecls exportDecl'''

def p_interfaceFormalParam(p):
    '''interfaceFormalParam : TOKTYPE VAR
                            | VAR interfaceHashParams
                            | NUM
                            | TOKNUMERIC TOKTYPE VAR'''
    if len(p) == 2:
        p[0] = p[1]
    elif len(p) == 3:
        p[0] = p[2]
    else:
        p[0] = p[3]

def p_interfaceFormalParams(p):
    '''interfaceFormalParams : interfaceFormalParam
                             | interfaceFormalParams COMMA interfaceFormalParam'''
    if len(p) == 2:
        p[0] = [p[1]]
    else:
        p[0] = p[1] + [p[3]]

def p_interfaceHashParams(p):
    '''interfaceHashParams :
                           | HASH LPAREN interfaceFormalParams RPAREN'''
    if len(p) == 5:
        p[0] = p[3]
    else:
        p[0] = []

def p_instanceAttributes(p):
    '''instanceAttributes :
                          | instanceAttributes LPARENSTAR attrSpecs RPARENSTAR'''

def p_subinterfaceDecl(p):
    '''subinterfaceDecl : instanceAttributes TOKINTERFACE type VAR SEMICOLON
                        | type VAR SEMICOLON'''
    if len(p) == 6:
        name = p[4]
        t = p[3]
    elif len(p) == 5:
        name = p[3]
        t = p[2]
    else:
        name = p[2]
        t = p[1]
    p[0] = AST.Interface(t.name, t.params, [], name, globalfilename)

def p_parenthesizedFormalParams(p):
    '''parenthesizedFormalParams :
                                 |  LPAREN RPAREN
                                 |  LPAREN moduleFormalParams RPAREN'''
    if len(p) < 4:
        p[0] = []
    else:
        p[0] = p[2]

def p_methodDecl(p):
    '''methodDecl : TOKMETHOD type VAR parenthesizedFormalParams SEMICOLON'''
    p[0] = AST.Method(p[3], p[2], p[4])

def p_interfaceStmt(p):
    '''interfaceStmt : subinterfaceDecl
                     | methodDecl '''
    p[0] = p[1]

def p_interfaceStmts(p):
    '''interfaceStmts :
                      | interfaceStmts interfaceStmt'''
    if len(p) == 3:
        p[0] = p[1] + [p[2]]
    else:
        p[0] = []

def p_interfaceDecl(p):
    '''interfaceDecl : instanceAttributes TOKINTERFACE VAR interfaceHashParams SEMICOLON interfaceStmts TOKENDINTERFACE colonVar'''
    interface = AST.Interface(p[3], p[4], p[6], None, globalfilename)
    p[0] = interface

# the token '[' signifies an array type
def p_arrayDecl(p):
    '''arrayDecl : type VAR LBRACKET NUM RBRACKET'''
    arr_t = AST.Type(p[3],p[1])
    p[0] = AST.Variable(p[2], arr_t, None)

def p_varDecl(p):
    '''varDecl : arrayDecl
               | type VAR'''
    if len(p)==3:
        p[0] = AST.Variable(p[2], p[1], None)
    else:
        p[0] = p[1]

def p_params(p):
    '''params : expressions
              | TOKSEQ fsmStmts TOKENDSEQ'''

def p_lvalue(p):
    '''lvalue : VAR
              | LPAREN lvalue RPAREN
              | lvalue DOT VAR
              | TOKACTION fsmStmts TOKENDACTION
              | lvalue LBRACKET expression RBRACKET
              | lvalue LBRACKET expression COLON expression RBRACKET
              | TOKMATCH pattern'''

def p_varAssign1(p):
    '''varAssign1 : TOKLET VAR EQUAL expression
                  | TOKLET VAR LARROW expression'''
    p[0] = AST.Variable(p[2], None, p[4])

def p_varAssign2(p):
    '''varAssign2 : type VAR EQUAL expression
                  | type VAR LBRACKET expression RBRACKET EQUAL expression
                  | type VAR LBRACKET expression RBRACKET LBRACKET NUM RBRACKET EQUAL expression
                  | type VAR LARROW expression'''
    p[0] = AST.Variable(p[2], p[1], p[4])

def p_varAssign3(p):
    '''varAssign3 : lvalue EQUAL expression
                  | lvalue LEQ expression
                  | lvalue LARROW expression'''
    p[0] = AST.Variable(p[2], p[1], None)

def p_varAssign(p):
    '''varAssign : varAssign1
                 | varAssign2
                 | varAssign3'''

def p_ruleCond(p):
    '''ruleCond : LPAREN expression RPAREN'''

def p_implicitCond(p):
    '''implicitCond :
                    | TOKIF LPAREN expression RPAREN'''

def p_rule(p):
    '''rule : TOKRULE VAR implicitCond SEMICOLON expressionStmts TOKENDRULE colonVar
            | TOKRULE VAR ruleCond implicitCond SEMICOLON expressionStmts TOKENDRULE colonVar'''

def p_ifStmt(p):
    '''ifStmt : TOKIF LPAREN expression RPAREN fsmStmt
              | TOKIF LPAREN expression RPAREN fsmStmt TOKELSE fsmStmt'''

def p_caseItem(p):
    '''caseItem : expressions COLON expressionStmt'''

def p_caseItems(p):
    '''caseItems :
                 | caseItems caseItem'''

def p_defaultItem(p):
    '''defaultItem :
                   | TOKDEFAULT expressionStmt
                   | TOKDEFAULT COLON expressionStmt'''

def p_caseStmt(p):
    '''caseStmt : TOKCASE LPAREN expression RPAREN caseItems defaultItem TOKENDCASE
                | TOKCASE LPAREN expression RPAREN TOKMATCHES caseItems defaultItem TOKENDCASE'''

def p_forStmt(p):
    '''forStmt : TOKFOR LPAREN varAssign SEMICOLON expression SEMICOLON varAssign RPAREN fsmStmt'''

def p_whenStmt(p):
    '''whenStmt : TOKWHEN LPAREN expression RPAREN LPAREN expression RPAREN SEMICOLON'''

def p_beginStmt(p):
    '''beginStmt : TOKBEGIN expressionStmts TOKEND'''

def p_expressionStmt(p):
    '''expressionStmt : TOKRETURN expression SEMICOLON
                      | fsmStmtDef
                      | whenStmt
                      | lvalue SEMICOLON
                      | lvalue LPAREN params RPAREN DOT expression SEMICOLON
                      | lvalue LPAREN params RPAREN SEMICOLON
                      | BUILTINVAR LPAREN expressions RPAREN SEMICOLON
                      | varAssign SEMICOLON
                      | varDecl SEMICOLON
                      | beginStmt
                      | ifStmt
                      | caseStmt
                      | forStmt
                      | interfaceDef
                      | functionDef
                      | methodDef
                      | moduleDef
                      | TOKACTION colonVar expressionStmts TOKENDACTION colonVar
                      | TOKACTIONVALUE colonVar expressionStmts TOKENDACTIONVALUE colonVar
                      | typeDef
                      | instanceAttributes rule
                      | TOKACTION fsmStmts TOKENDACTION
                      '''
    if parseTrace:
        print 'ENDSTATEMENT', [pitem for pitem in p]

def p_expressionStmts(p):
    '''expressionStmts : expressionStmts expressionStmt
                       | '''

def p_provisos(p):
    '''provisos :
                | TOKPROVISOS LPAREN typeParams RPAREN'''
    if len(p) == 5:
        p[0] = p[3]
    else:
        p[0] = []

def p_endFunction(p):
    '''endFunction : TOKENDFUNCTION colonVar'''

def p_functionBody(p):
    '''functionBody : SEMICOLON expressionStmts endFunction'''

def p_functionValue(p):
    '''functionValue : EQUAL expression SEMICOLON'''

def p_functionFormal(p):
    '''functionFormal : type VAR
                      | VAR'''

def p_functionFormals(p):
    '''functionFormals :
                       | functionFormal
                       | functionFormals COMMA functionFormal '''
def p_fsmStmt(p):
    '''fsmStmt : TOKSEQ fsmStmts TOKENDSEQ
               | TOKPAR fsmStmts TOKENDPAR
               | TOKWHILE ruleCond fsmStmt
               | expressionStmt'''

def p_fsmStmts(p):
    '''fsmStmts : fsmStmt fsmStmts
                | fsmStmt'''

def p_fsmStmtDef(p):
    '''fsmStmtDef : TOKSTMT VAR EQUAL fsmStmts SEMICOLON'''

def p_functionDef(p):
    '''functionDef : instanceAttributes TOKFUNCTION type VAR LPAREN functionFormals RPAREN provisos functionBody
                   | instanceAttributes TOKFUNCTION      VAR LPAREN functionFormals RPAREN provisos functionBody
                   | instanceAttributes TOKFUNCTION type VAR LPAREN functionFormals RPAREN provisos functionValue
                   | instanceAttributes TOKFUNCTION      VAR LPAREN functionFormals RPAREN provisos functionValue
                   '''
    if len(p) == 9:
        # no type
        p[0] = AST.Function(p[3], None, p[5])
    else:
        p[0] = AST.Function(p[4], p[3], p[6])

def p_methodDef(p):
    '''methodDef : TOKMETHOD type VAR LPAREN functionFormals RPAREN implicitCond SEMICOLON methodBody
                 | TOKMETHOD type VAR implicitCond SEMICOLON methodBody
                 | TOKMETHOD type VAR EQUAL expression SEMICOLON
                 | TOKMETHOD type VAR LPAREN functionFormals RPAREN EQUAL expression SEMICOLON
                 | TOKMETHOD VAR LPAREN functionFormals RPAREN EQUAL expression SEMICOLON
                 | TOKMETHOD VAR EQUAL expression SEMICOLON'''
    returnType = p[2]
    name = p[3]
    params = []
    p[0] = AST.Method(name, returnType, params)

def p_methodBody(p):
    '''methodBody : expressionStmts endMethod
                  | endMethod'''

def p_endMethod(p):
    '''endMethod : TOKENDMETHOD colonVar'''

def p_unionMember(p):
    '''unionMember : type VAR SEMICOLON
                   | subStruct VAR SEMICOLON
                   | subUnion VAR SEMICOLON'''

def p_subStruct(p):
    '''subStruct : TOKSTRUCT LBRACE structMembers RBRACE'''

def p_structMembers(p):
    '''structMembers :
                     | structMember
                     | structMembers structMember'''
    if len(p) == 1:
        p[0] = []
    elif len(p) == 2:
        p[0] = [p[1]]
    elif len(p) == 3:
        p[0] = p[1] + [p[2]]

def p_structMember(p):
    '''structMember : type VAR SEMICOLON
                    | subUnion VAR SEMICOLON'''
    p[0] = AST.StructMember(p[1], p[2])

def p_subUnion(p):
    '''subUnion : TOKUNION TOKTAGGED LBRACE unionMembers RBRACE'''

def p_unionMembers(p):
    '''unionMembers : unionMember
                    | unionMembers unionMember'''

def p_taggedUnionDef(p):
    '''taggedUnionDef : TOKUNION TOKTAGGED LBRACE unionMembers RBRACE'''

def p_structDef(p):
    '''structDef : TOKSTRUCT LBRACE structMembers RBRACE'''
    p[0] = AST.Struct(p[3])

def p_enumRange(p):
    '''enumRange :
                 | LBRACKET NUM RBRACKET
                 | LBRACKET NUM COLON NUM RBRACKET'''

def p_enumElement(p):
    '''enumElement : VAR enumRange
                   | VAR enumRange EQUAL NUM'''
    if len(p) == 3:
        p[0] = [p[1], None]
    else:
        p[0] = [p[1], p[4]]

def p_enumElements(p):
    '''enumElements : enumElement
                    | enumElements COMMA enumElement'''
    if len(p) == 2:
        p[0] = [p[1]]
    else:
        p[0] = p[1] + [p[3]]

def p_enumDef(p):
    '''enumDef : TOKENUM LBRACE enumElements RBRACE'''
    p[0] = AST.Enum(p[3])

def p_vardot(p):
    '''vardot : VAR
            | vardot DOT VAR'''
    if len(p) == 2:
        p[0] = p[1]
    else:
        p[0] = p[3]

def p_vars(p):
    '''vars : vardot
            | vars COMMA vardot'''
    if len(p) == 2:
        p[0] = [p[1]]
    else:
        p[0] = p[1] + [p[3]]

def p_deriving(p):
    '''deriving :
                | TOKDERIVING LPAREN vars RPAREN'''
    if len(p) == 5:
        p[0] = p[3]
    else:
        p[0] = []

def p_macroDef(p):
    '''macroDef : TOKTICKDEFINE VAR expression'''

def p_typeDefBody(p):
    '''typeDefBody : taggedUnionDef
                   | structDef
                   | enumDef
                   | type'''
    p[0] = p[1]

def p_typeDef(p):
    '''typeDef : TOKTYPEDEF typeDefBody VAR deriving SEMICOLON
               | TOKTYPEDEF typeDefBody VAR interfaceHashParams deriving SEMICOLON'''
    if len(p) == 6:
        p[0] = AST.TypeDef(p[2], p[3], [])
    else:
        p[0] = AST.TypeDef(p[2], p[3], p[4])

def p_interfaceDef(p):
    '''interfaceDef : TOKINTERFACE type VAR SEMICOLON expressionStmts TOKENDINTERFACE colonVar
                    | TOKINTERFACE type VAR EQUAL expression SEMICOLON
                    | TOKINTERFACE VAR EQUAL expression SEMICOLON'''
    if parseTrace:
        print 'ENDINTERFACE', [pitem for pitem in p]

def p_formalParam(p):
    '''formalParam : type VAR'''
    param = AST.Param(p[2], p[1])
    p[0] = param

def p_moduleFormalParams(p):
    '''moduleFormalParams : formalParam
                          | TOKFUNCTION type VAR parenthesizedFormalParams
                          | moduleFormalParams COMMA formalParam
                          |'''
    if len(p) == 1:
        p[0] = []
    elif len(p) == 2:
        p[0] = [p[1]]
    elif len(p) == 5:
        p[0] = p[2]
    elif len(p) == 4:
        p[0] = p[1] + [p[3]]

def p_moduleFormalArg(p):
    '''moduleFormalArg : instanceAttributes type
                       | instanceAttributes type VAR'''

def p_moduleFormalArgs(p):
    '''moduleFormalArgs :
                        | moduleFormalArg
                        | moduleFormalArgs COMMA moduleFormalArg'''
    if len(p) == 2:
        p[0] = [p[1]]
    else:
        p[0] = p[1] + [p[3]]

def p_moduleParamsArgs(p):
    '''moduleParamsArgs :
                        | HASH LPAREN moduleFormalParams RPAREN
                        | HASH LPAREN moduleFormalParams RPAREN LPAREN moduleFormalArgs RPAREN
                        | LPAREN moduleFormalArgs RPAREN'''
    if len(p) == 8:
        p[0] = [ p[3], p[6] ]
    elif len(p) == 5:
        p[0] = [ p[3], None ]
    else:
        p[0] = [ None, p[2] ]

def p_attrSpec(p):
    '''attrSpec : VAR
                | VAR EQUAL expression'''

def p_attrSpecs(p):
    '''attrSpecs : attrSpec
                 | attrSpecs COMMA attrSpec'''

def p_moduleContext(p):
    '''moduleContext :
                     | LBRACKET VAR RBRACKET'''
    if len(p) > 2:
        p[0] = p[2]

def p_moduleDefHeader(p):
    '''moduleDefHeader : instanceAttributes TOKMODULE moduleContext VAR moduleParamsArgs provisos SEMICOLON'''
    p[0] = [p[3], p[4], p[5][0], p[5][1], p[6]]

def p_moduleDef(p):
    '''moduleDef : moduleDefHeader expressionStmts TOKENDMODULE colonVar'''
    if parseTrace:
        print 'ENDMODULE', [pitem for pitem in p]
    p[0] = AST.Module(p[1][0], p[1][1], p[1][2], p[1][3], p[1][4], p[2])

def p_importBviDef(p):
    '''importBviDef : TOKIMPORT STR VAR EQUAL bviModuleDef
            | TOKIMPORT STR TOKFUNCTION TOKUACTION VAR LPAREN functionFormals RPAREN SEMICOLON'''
    p[0] = p[5]
    if len(p) > 6:
        p[0] = AST.Module(None, p[5], None, None, None, None)

def p_bviModuleDef(p):
    '''bviModuleDef : instanceAttributes TOKMODULE moduleContext VAR moduleParamsArgs provisos SEMICOLON bviExpressionStmts TOKENDMODULE colonVar'''
    p[0] = AST.Module(p[3], p[4], p[5][0], p[5][1], p[6], p[8])

def p_bviExpressionStmts(p):
    '''bviExpressionStmts : bviExpressionStmts bviExpressionStmt
                          | bviExpressionStmt '''

def p_bviExpressionStmt(p):
    '''bviExpressionStmt : TOKRETURN expression SEMICOLON
                         | fsmStmtDef
                         | whenStmt
                         | lvalue SEMICOLON
                         | lvalue LPAREN expressions RPAREN SEMICOLON
                         | BUILTINVAR LPAREN expressions RPAREN SEMICOLON
                         | varAssign SEMICOLON
                         | varDecl SEMICOLON
                         | beginStmt
                         | ifStmt
                         | caseStmt
                         | forStmt
                         | bviInterfaceDef
                         | functionDef
                         | bviMethodDef
                         | moduleDef
                         | TOKACTION colonVar expressionStmts TOKENDACTION colonVar
                         | typeDef
                         | instanceAttributes rule
                         | TOKSEQ fsmStmts TOKENDSEQ
                         | TOKPORT VAR EQUAL expression SEMICOLON
                         | TOKPARAMETER VAR EQUAL expression SEMICOLON
                         | TOKDEFAULT_CLOCK VAR LPAREN RPAREN SEMICOLON
                         | TOKDEFAULT_CLOCK VAR LPAREN VAR RPAREN SEMICOLON
                         | TOKDEFAULT_RESET VAR LPAREN RPAREN SEMICOLON
                         | TOKDEFAULT_RESET TOKNO_RESET SEMICOLON
                         | TOKDEFAULT_RESET VAR LPAREN VAR RPAREN SEMICOLON
                         | TOKINPUT_CLOCK VAR LPAREN VAR RPAREN EQUAL expression SEMICOLON
                         | TOKINPUT_RESET VAR LPAREN VAR RPAREN EQUAL expression SEMICOLON
                         | TOKINPUT_RESET VAR LPAREN RPAREN EQUAL expression SEMICOLON
                         | TOKOUTPUT_CLOCK VAR LPAREN VAR RPAREN SEMICOLON
                         | TOKOUTPUT_RESET VAR LPAREN VAR RPAREN SEMICOLON
                         | TOKSCHEDULE LPAREN vars RPAREN schedOp LPAREN vars RPAREN SEMICOLON'''

def p_schedOp(p):
    '''schedOp : TOKCF
               | TOKC
               | TOKSB
               | TOKSBR'''

def p_bviInterfaceDef(p):
    '''bviInterfaceDef : TOKINTERFACE type VAR SEMICOLON bviExpressionStmts TOKENDINTERFACE colonVar
                       | TOKINTERFACE type VAR EQUAL expression SEMICOLON
                       | TOKINTERFACE VAR EQUAL expression SEMICOLON'''

def p_bviMethodAttributes(p):
    '''bviMethodAttributes :
                           | bviMethodAttributes bviMethodAttribute'''
def p_bviMethodAttribute(p):
    '''bviMethodAttribute :
                          | TOKENABLE LPAREN instanceAttributes VAR RPAREN
                          | TOKCLOCKED_BY LPAREN instanceAttributes VAR RPAREN
                          | TOKRESET_BY LPAREN instanceAttributes VAR RPAREN'''

def p_bviMethodDef(p):
    '''bviMethodDef : TOKMETHOD VAR LPAREN VAR RPAREN bviMethodAttributes SEMICOLON
                    | TOKMETHOD VAR VAR LPAREN RPAREN bviMethodAttributes SEMICOLON'''

def p_instanceDeclStmt(p):
    '''instanceDeclStmt : varAssign SEMICOLON
                        | functionDef
                        | moduleDef'''
    p[0] = p[1]

def p_instanceDeclStmts(p):
    '''instanceDeclStmts :
                         | instanceDeclStmt
                         | instanceDeclStmts instanceDeclStmt'''

def p_instanceDecl(p):
    '''instanceDecl : TOKINSTANCE VAR HASH LPAREN typeParams RPAREN provisos SEMICOLON instanceDeclStmts TOKENDINSTANCE'''
    p[0] = AST.TypeclassInstance(p[2], p[5], p[7], p[9])

def p_typeClassDeclStmts(p):
    '''typeClassDeclStmts :
                          | moduleDefHeader'''

def p_typeClassDecl(p):
    '''typeClassDecl : TOKTYPECLASS VAR HASH LPAREN interfaceFormalParams RPAREN provisos SEMICOLON typeClassDeclStmts TOKENDTYPECLASS'''
    p[0] = AST.Typeclass(p[2])

globalimports = []
globalfilename = None

def p_packageStmt(p):
    '''packageStmt : interfaceDecl
                   | typeClassDecl
                   | functionDef
                   | instanceDecl
                   | varDecl SEMICOLON
                   | varAssign SEMICOLON
                   | moduleDef
                   | macroDef
                   | typeDef
                   | importBviDef'''
    globalv.add_new(p[1])

def p_packageStmts(p):
    '''packageStmts :
                    | packageStmts packageStmt exportDecls'''

def p_beginPackage(p):
    '''beginPackage :
                    | TOKPACKAGE VAR SEMICOLON'''

def p_endPackage(p):
    '''endPackage :
                  | TOKENDPACKAGE colonVar'''

def p_package(p):
    '''package : beginPackage exportDecls importDecls packageStmts exportDecls endPackage'''
    p[0] = p[4]

def syntax_parse(argdata, inputfilename, bsvdefines, bsvpath):
    global globalfilename
    globalfilename = inputfilename
    data = bsvpreprocess.preprocess(inputfilename, argdata + '\n', bsvdefines, bsvpath)
    lexer = lex.lex(errorlog=lex.NullLogger())
    parserdir=scripthome+'/syntax'
    if not os.path.isdir(parserdir):
        os.makedirs(parserdir)
    if not (parserdir in sys.path):
        sys.path.append(parserdir)
    parser = yacc.yacc(optimize=1,errorlog=yacc.NullLogger(),outputdir=parserdir,debugfile=parserdir+'/parser.out')
    if noisyFlag:
        print 'Parsing:', inputfilename
    if parseDebugFlag:
        return parser.parse(data,debug=1)
    return  parser.parse(data)

def generate_bsvcpp(filelist, project_dir, bsvdefines, interfaces, bsvpath):
    for inputfile in filelist:
        syntax_parse(open(inputfile).read(), inputfile, bsvdefines, bsvpath)
    ## code generation pass
    ilist = []
    for i in interfaces:
        ifc = globalv.globalvars.get(i)
        if not ifc:
            print 'Connectal: Unable to locate the interface:', i
            for keys in globalv.globalvars:
                print '    ', keys
            sys.exit(1)
        ifc = ifc.instantiate(dict(zip(ifc.params, ifc.params)))
        ilist.append(ifc)
        for ditem in ifc.decls:
            for pitem in ditem.params:
                thisType = pitem.type
                p = globalv.globalvars.get(thisType.name)
                if p and thisType.params and p.params:
                    myName = '%sL_%s_P' % (thisType.name, '_'.join([t.name for t in thisType.params if t]))
                    pitem.oldtype = pitem.type
                    pitem.type = AST.Type(myName, [])
                    if not globalv.globalvars.get(myName):
                        globalv.add_new(AST.TypeDef(p.tdtype.instantiate(dict(zip(p.params, thisType.params))), myName, []))
    jsondata = AST.serialize_json(ilist, globalimports, bsvdefines)
    if project_dir:
        cppgen.generate_cpp(project_dir, noisyFlag, jsondata)
        bsvgen.generate_bsv(project_dir, noisyFlag, False, jsondata)

if __name__=='__main__':
    if len(sys.argv) == 1:
        parserdir=scripthome+'/syntax'
        sys.path.append(parserdir)
        if not os.path.isdir(parserdir):
            os.makedirs(parserdir)
        parser = yacc.yacc(outputdir=parserdir,debugfile=parserdir+'/parser.out')
        import parsetab
        sys.exit(0)
    ifitems = []
    t = os.environ.get('INTERFACES')
    if t:
        t = t.split()
        for item in t:
            if item not in ifitems:
                ifitems.append(item)
    deflist = []
    t = os.environ.get('BSVDEFINES_LIST')
    if t:
        deflist = t.split()
    noisyFlag = os.environ.get('D') == '1'
    if os.environ.get('D'):
        parseDebugFlag=True
    if noisyFlag:
        parseTrace=True
    project_dir =  os.environ.get('DTOP')
    tmp = os.environ.get('PROTODEBUG')
    if tmp:
        print 'JSONNN', tmp
        j2file = open(tmp).read()
        jsondata = json.loads(j2file)
        cppgen.generate_cpp(project_dir, noisyFlag, jsondata)
        bsvgen.generate_bsv(project_dir, noisyFlag, True, jsondata)
    else:
        bsvpath = os.environ.get('BSVPATH', []).split(':')
        generate_bsvcpp(sys.argv[1:], project_dir, deflist, ifitems, bsvpath)


text:
<?php

namespace Kamui\Resources;

use Kamui\API;
use Kamui\BaseResource;

class Collections extends BaseResource
{
    public function __construct(API $api)
    {
        parent::__construct($api);
    }

    public function get($collection)
    {
        $id = $this->api->getCollectionID($collection);
        if (!$id)
            return false;

        return $this->api->sendGet("collections/{$id}");
    }

    public function items($collection, $all = false)
    {
        $id = $this->api->getCollectionID($collection);
        if (!$id)
            return false;

        $args = array(
            'include_all_items' => (bool) $all,
        );

        return $this->api->sendGet("collections/{$id}/items", $args);
    }

    public function create($channel, $args = array())
    {
        $id = $this->api->getUserID($channel);
        if (!$id || !is_string($title))
            return false;

        $this->api->scope = 'collections_edit';
        return $this->api->sendPostJson("channels/{$id}/collections", $args, array(), true);
    }

    public function update($collection, $args = array())
    {
        $id = $this->api->getCollectionID($collection);
        if (!$id || !is_string($title))
            return false;

        $this->api->scope = 'collections_edit';
        return $this->api->sendPutJson("collections/{$id}", $args, array(), true);
    }

    public function delete($collection, $item = null)
    {
        $collection_id = $this->api->getCollectionID($collection);
        if (!$collection_id)
            return false;

        if (is_null($item)) {
            return $this->sendDelete("collections/{$collection_id}", array(), true);
        }

        $item_id = $this->api->getCollectionItemID($item);
        if (!$item_id)
            return false;

        $this->api->scope = 'collections_edit';
        return $this->sendDelete("collections/{$collection_id}/items/{$video_id}", array(), true);
    }

    public function add($collection, $item, $type = null)
    {
        $collection_id = $this->api->getCollectionID($collection);
        $item_id = $this->api->getCollectionItemID($item);
        if (!$collection_id || !$item_id)
            return false;

        if (is_null($type)) {
            $type = $this->api->getCollectionItemType($item);
        }

        $data = array(
            'id'    => $item_id,
            'type'  => $type,
        );

        $this->api->scope = 'collections_edit';
        return $this->sendPostJson("collections/{$collection_id}/items", $data, array(), true);
    }

    public function move($collection, $item, $position)
    {
        $collection_id = $this->api->getCollectionID($collection);
        $item_id = $this->api->getCollectionItemID($item);
        if (!$collection_id || !$item_id || !is_numeric($position))
            return false;

        $data = array(
            'position'  => intval($position),
        );

        $this->api->scope = 'collections_edit';
        $this->sendPutJson("collections/{$collection_id}/items/{$item_id}", $data, array(), true);
    }

    public function thumbnail($collection, $item)
    {
        $collection_id = $this->api->getCollectionID($collection);
        $item_id = $this->api->getCollectionItemID($item);
        if (!$collection_id || !$item_id)
            return false;

        $data = array(
            'item_id'   => $item_id,
        );

        $this->api->scope = 'collections_edit';
        return $this->sendPutJson("collections/{$collection_id}/thumbnail", $data, array(), true);
    }
}

redpajama_set_name: RedPajamaGithub


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package trypComponents;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import trypResources.ActionCodes;
import trypResources.Tools;

/**
 *
 * @author amnesia
 */
public class GradientPanel extends JPanel implements ActionListener, ChangeListener, FocusListener
{
    JSlider[] sliders;
    JTextField[] fields;
    JButton JB_Make, JB_SelectStart, JB_SelectEnd;

    int min, max;

    public GradientPanel(ActionListener A)
    {
        this.setLayout(new GridBagLayout());

        GridBagConstraints c = new GridBagConstraints();

        c.fill=GridBagConstraints.BOTH;
        c.weightx=0.5;
        c.weighty=0;
        c.gridwidth=1;
        c.gridheight=1;
        c.ipadx=0;

        min=0;
        max=0;

        sliders = new JSlider[2];
        fields = new JTextField[2];

        sliders[0] = new JSlider(0,0,0);
        sliders[0].addChangeListener(this);

        sliders[1] = new JSlider(0,0,0);
        sliders[1].addChangeListener(this);

        fields[0] = new JTextField("10");
        fields[0].addFocusListener(this);
        fields[0].addActionListener(this);
        fields[0].setMinimumSize(new Dimension(80, 20));

        fields[1] = new JTextField("10");
        fields[1].addFocusListener(this);
        fields[1].addActionListener(this);

        JB_Make = new JButton("Make Gradient");
        JB_Make.addActionListener(A);

        JB_SelectStart = new JButton("Select Start");
        JB_SelectStart.addActionListener(A);

        JB_SelectEnd = new JButton("Select End");
        JB_SelectEnd.addActionListener(A);

        c.gridx=0;
        c.gridy=0;
        this.add(JB_SelectStart,c);

        c.gridx=2;
        c.gridy=0;
        c.gridheight=2;
        this.add(JB_Make,c);

        c.gridheight=1;

        c.gridx=4;
        c.gridy=0;
        this.add(JB_SelectEnd,c);

        c.gridx=1;
        c.gridy=0;
        c.ipadx=30;
        this.add(fields[0],c);

        c.gridx=3;
        c.gridy=0;
        c.weightx=1;
        this.add(fields[1],c);

        c.gridx=0;
        c.gridy=1;
        c.gridwidth=2;
        this.add(sliders[0],c);

        c.gridx=3;
        c.gridy=1;
        this.add(sliders[1],c);

        setAllEnabled(true);
    }

    public void setAllEnabled(boolean state)
    {
        sliders[0].setEnabled(state);
        sliders[1].setEnabled(state);
        fields[0].setEnabled(state);
        fields[1].setEnabled(state);
        JB_Make.setEnabled(state);
        JB_SelectStart.setEnabled(state);
        JB_SelectEnd.setEnabled(state);
    }

    public void setMax(int max)
    {
        this.max=max;

        for(int i=0;i<=1;i++)
        {
            fields[i].setText("0");
            sliders[i].setValue(0);
            sliders[i].setMaximum(max);
        }
    }

    public void updateFields()
    {
        if(sliders[0].getValue()>=sliders[1].getValue())
        {
            if(sliders[0].getValueIsAdjusting())
            {
                sliders[1].setValue(sliders[0].getValue());
            }
            else sliders[0].setValue(sliders[1].getValue());
        }
        fields[0].setText(""+sliders[0].getValue());
        fields[1].setText(""+sliders[1].getValue());
    }

    public int parseField(JTextField JT)
    {
        try
        {
            return Integer.parseInt(JT.getText());
        }
        catch(Exception e)
        {
        }
        return -1;
    }

    public void parseFields()
    {
        int[] toCheck = new int[2];
        toCheck[0]=parseField(fields[0]);
        toCheck[1]=parseField(fields[1]);

        for(int i=0; i<=1; i++)
        {
            if(toCheck[i]==-1)
            {
                fields[i].setText("" + sliders[i].getValue());
            }
            else if(toCheck[i] <=0)
            {
                fields[i].setText("0");
                sliders[i].setValue(0);
            }
            else if(toCheck[i]>=max)
            {
                fields[i].setText(""+max);
                sliders[i].setValue(max);
            }
            else
            {
                sliders[i].setValue(toCheck[i]);
            }
        }
        updateFields();
    }

    @Override
    public void stateChanged(ChangeEvent e)
    {
        updateFields();
    }

    @Override
    public void focusGained(FocusEvent e)
    {
        parseFields();
    }

    @Override
    public void focusLost(FocusEvent e)
    {
        parseFields();
    }

    @Override
    public void actionPerformed(ActionEvent e)
    {
        parseFields();
    }

    public int checkActions(Object toCheck)
    {
        Tools.p("Action Triggered");
        if(toCheck == JB_SelectStart)
        {
            return ActionCodes.CODE_GRADIENTPANEL_SELECTSTART;
        }
        else if(toCheck == JB_SelectEnd)
        {
            Tools.p("Selected End");
            return ActionCodes.CODE_GRADIENTPANEL_SELECTEND;
        }
        else if(toCheck == JB_Make)
        {

            return ActionCodes.CODE_GRADIENTPANEL_MAKE;
        }
        return ActionCodes.NULLCODE;
    }

    public void setStart(int val)
    {
        if(val>sliders[1].getValue())
        {
            sliders[1].setValue(val);
        }
        sliders[0].setValue(val);

        updateFields();
    }

    public void setEnd(int val)
    {
        if(val<sliders[0].getValue())
        {
            sliders[0].setValue(val);
        }
        sliders[1].setValue(val);

        updateFields();
    }

    public int getStart()
    {
        return sliders[0].getValue();
    }

    public int getEnd()
    {
        return sliders[1].getValue();
    }
}


text:
kitbox is a computer school project in 3rd bachelor in ECAM Brussels. The goal is to create a software to build
a cupboard.
The client build block with elements in catalog.

# Members
- Mathieu David, [azerupi](https://github.com/azerupi)
- William De Decker, [WilliamHdd](https://github.com/WilliamHdd)
- Saïkou Barry, [bluebeel](https://github.com/bluebeel)
- Momo Guy Donatien, [momodonatien](https://github.com/momodonatien)
- Jonathan Petit, [JonathanPetit](https://github.com/JonathanPetit)


text:
<?php

namespace Negko\QrBundle\Exception;

use InvalidArgumentException as BaseInvalidArgumentException;

class InvalidArgumentException extends BaseInvalidArgumentException implements Exception
{
}


text:
package iso20022

// Provides the settlement details.
type Settlement1 struct {

	// Total amount to be settled.
	SettlementAmount *AmountAndDirection27 `xml:"SttlmAmt"`

	// Place where settlement of the securities takes place.
	Depository *PartyIdentification34Choice `xml:"Dpstry,omitempty"`
}

func (s *Settlement1) AddSettlementAmount() *AmountAndDirection27 {
	s.SettlementAmount = new(AmountAndDirection27)
	return s.SettlementAmount
}

func (s *Settlement1) AddDepository() *PartyIdentification34Choice {
	s.Depository = new(PartyIdentification34Choice)
	return s.Depository
}


text:
#ifndef BLEAUDIOENCODER_AAC_HPP
#define BLEAUDIOENCODER_AAC_HPP

#include <QByteArray>

#include "faac.h"
#include "BleAudioEncoderAbstract.hpp"

class BleAudioEncoder_AAC : public BleAudioEncoderAbstract
{
public:
    BleAudioEncoder_AAC();

    virtual bool init(int samplerate, int channel, int bitrate);
    virtual void fini();
    virtual bool encode(const QByteArray &data, QByteArray &output);\
    virtual int getFrameSize();
    virtual float getFrameDuration();

    QByteArray getHeader();

public:
    //int sample_rate;
    int m_nFrameSize;
    int m_channels;

    unsigned long m_samplesInputSize;
    unsigned long m_maxOutputSize;

    faacEncHandle   m_faacHandle;
    int*            m_pInBuf;
    unsigned char *m_outputBuffer;
    QByteArray m_header;
};

#endif // BLEAUDIOENCODER_AAC_HPP


text:
package hooks

import (
	"fmt"
	"os"
	"os/exec"

	"github.com/apex/log"
	"github.com/jpillora/archive"

	"github.com/apex/apex/function"
)

func init() {
	function.RegisterPlugin("hooks", &Plugin{})
}

// HookError represents a failed hook command.
type HookError struct {
	Hook    string
	Command string
	Output  string
}

// Error string.
func (e *HookError) Error() string {
	return fmt.Sprintf("%s hook: %s", e.Hook, e.Output)
}

// Plugin implementation.
type Plugin struct{}

// Build runs the "build" hook commands.
func (p *Plugin) Build(fn *function.Function, zip *archive.Archive) error {
	return p.run("build", fn.Hooks.Build, fn)
}

// Clean runs the "clean" hook commands.
func (p *Plugin) Clean(fn *function.Function) error {
	return p.run("clean", fn.Hooks.Clean, fn)
}

// Deploy runs the "deploy" hook commands.
func (p *Plugin) Deploy(fn *function.Function) error {
	return p.run("deploy", fn.Hooks.Deploy, fn)
}

// run a hook command.
func (p *Plugin) run(hook, command string, fn *function.Function) error {
	if command == "" {
		return nil
	}

	fn.Log.WithFields(log.Fields{
		"hook":    hook,
		"command": command,
	}).Debug("hook")

	cmd := exec.Command("sh", "-c", command)
	cmd.Env = os.Environ()
	cmd.Dir = fn.Path

	b, err := cmd.CombinedOutput()
	if err != nil {
		return &HookError{
			Hook:    hook,
			Command: command,
			Output:  string(b),
		}
	}

	return nil
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace NPascalCoin.API.Objects {

	/// <summary>
	/// Embedded JSON object describing node protocol support
	/// </summary>
	public class NetProtocol : PascalCoinDTO {

		/// <summary>
		/// Net protocol version
		/// </summary>
		[JsonProperty("ver")]
		public uint Version { get; set; }

		/// <summary>
		/// Net protocol available
		/// </summary>
		[JsonProperty("ver_a")]
		public uint AvailableVersion { get; set; }
	}

}


text:
class UtilLinux < Formula
  desc "Collection of Linux utilities"
  homepage "https://github.com/karelzak/util-linux"
  url "https://www.kernel.org/pub/linux/utils/util-linux/v2.34/util-linux-2.34.tar.xz"
  sha256 "743f9d0c7252b6db246b659c1e1ce0bd45d8d4508b4dfa427bbb4a3e9b9f62b5"

  bottle do
    cellar :any
    rebuild 1
    sha256 "ad4962d8ce56d784085cf53e2f3add3432a3905285acf05a23fcc2e5e40cf5a8" => :catalina
    sha256 "483548a881703f1e4645c40a9779758ff2da0db1dc521b4ce7321d86c723669d" => :mojave
    sha256 "f02d33204d3ff42112ab972d1fa93f84a7676bcc28f208eac41172db4f7416e7" => :high_sierra
  end

  keg_only "macOS provides the uuid.h header"

  def install
    system "./configure", "--disable-dependency-tracking",
                          "--disable-silent-rules",
                          "--prefix=#{prefix}",
                          "--disable-ipcs",  # does not build on macOS
                          "--disable-ipcrm", # does not build on macOS
                          "--disable-wall",  # already comes with macOS
                          "--enable-libuuid" # conflicts with ossp-uuid

    system "make", "install"

    # Remove binaries already shipped by macOS
    %w[cal col colcrt colrm getopt hexdump logger nologin look mesg more renice rev ul whereis].each do |prog|
      rm_f bin/prog
      rm_f sbin/prog
      rm_f man1/"#{prog}.1"
      rm_f man8/"#{prog}.8"
      rm_f share/"bash-completion/completions/#{prog}"
    end

    # install completions only for installed programs
    Pathname.glob("bash-completion/*") do |prog|
      if (bin/prog.basename).exist? || (sbin/prog.basename).exist?
        bash_completion.install prog
      end
    end
  end

  test do
    stat  = File.stat "/usr"
    owner = Etc.getpwuid(stat.uid).name
    group = Etc.getgrgid(stat.gid).name

    flags = ["x", "w", "r"] * 3
    perms = flags.each_with_index.reduce("") do |sum, (flag, index)|
      sum.insert 0, ((stat.mode & (2 ** index)).zero? ? "-" : flag)
    end

    out = shell_output("#{bin}/namei -lx /usr").split("\n").last.split(" ")
    assert_equal ["d#{perms}", owner, group, "usr"], out
  end
end


text:
namespace blink {

void DeprecatedPaintLayerPainter::paint(GraphicsContext* context, const LayoutRect& damageRect, const GlobalPaintFlags globalPaintFlags, LayoutObject* paintingRoot, PaintLayerFlags paintFlags)
{
    DeprecatedPaintLayerPaintingInfo paintingInfo(&m_paintLayer, LayoutRect(enclosingIntRect(damageRect)), globalPaintFlags, LayoutSize(), paintingRoot);
    if (shouldPaintLayerInSoftwareMode(globalPaintFlags, paintFlags))
        paintLayer(context, paintingInfo, paintFlags);
}

static ShouldRespectOverflowClip shouldRespectOverflowClip(PaintLayerFlags paintFlags, const LayoutObject* layoutObject)
{
    return (paintFlags & PaintLayerPaintingOverflowContents || (paintFlags & PaintLayerPaintingChildClippingMaskPhase && layoutObject->hasClipPath())) ? IgnoreOverflowClip : RespectOverflowClip;
}

void DeprecatedPaintLayerPainter::paintLayer(GraphicsContext* context, const DeprecatedPaintLayerPaintingInfo& paintingInfo, PaintLayerFlags paintFlags)
{
    // https://code.google.com/p/chromium/issues/detail?id=343772
    DisableCompositingQueryAsserts disabler;

    if (m_paintLayer.compositingState() != NotComposited) {
        if (paintingInfo.globalPaintFlags() & GlobalPaintFlattenCompositingLayers) {
            // FIXME: ok, but what about GlobalPaintFlattenCompositingLayers? That's for printing and drag-image.
            // FIXME: why isn't the code here global, as opposed to being set on each paintLayer() call?
            paintFlags |= PaintLayerUncachedClipRects;
        }
    }

    // Non self-painting leaf layers don't need to be painted as their layoutObject() should properly paint itself.
    if (!m_paintLayer.isSelfPaintingLayer() && !m_paintLayer.hasSelfPaintingLayerDescendant())
        return;

    // If this layer is totally invisible then there is nothing to paint.
    if (!m_paintLayer.layoutObject()->opacity())
        return;

    if (m_paintLayer.paintsWithTransparency(paintingInfo.globalPaintFlags()))
        paintFlags |= PaintLayerHaveTransparency;

    LayerFixedPositionRecorder fixedPositionRecorder(*context, *m_paintLayer.layoutObject());

    // PaintLayerAppliedTransform is used in LayoutReplica, to avoid applying the transform twice.
    if (m_paintLayer.paintsWithTransform(paintingInfo.globalPaintFlags()) && !(paintFlags & PaintLayerAppliedTransform)) {
        paintLayerWithTransform(context, paintingInfo, paintFlags);
        return;
    }

    paintLayerContentsAndReflection(context, paintingInfo, paintFlags);
}

void DeprecatedPaintLayerPainter::paintLayerContentsAndReflection(GraphicsContext* context, const DeprecatedPaintLayerPaintingInfo& paintingInfo, PaintLayerFlags paintFlags, FragmentPolicy fragmentPolicy)
{
    ASSERT(m_paintLayer.isSelfPaintingLayer() || m_paintLayer.hasSelfPaintingLayerDescendant());

    PaintLayerFlags localPaintFlags = paintFlags & ~(PaintLayerAppliedTransform);

    // Paint the reflection first if we have one.
    if (m_paintLayer.reflectionInfo()) {
        ScopeRecorder scopeRecorder(*context);
        m_paintLayer.reflectionInfo()->paint(context, paintingInfo, localPaintFlags | PaintLayerPaintingReflection);
    }

    localPaintFlags |= PaintLayerPaintingCompositingAllPhases;
    paintLayerContents(context, paintingInfo, localPaintFlags, fragmentPolicy);
}

class ClipPathHelper {
public:
    ClipPathHelper(GraphicsContext* context, const DeprecatedPaintLayer& paintLayer, const DeprecatedPaintLayerPaintingInfo& paintingInfo, LayoutRect& rootRelativeBounds, bool& rootRelativeBoundsComputed,
        const LayoutPoint& offsetFromRoot, PaintLayerFlags paintFlags)
        : m_resourceClipper(0), m_paintLayer(paintLayer), m_context(context)
    {
        const ComputedStyle& style = paintLayer.layoutObject()->styleRef();

        // Clip-path, like border radius, must not be applied to the contents of a composited-scrolling container.
        // It must, however, still be applied to the mask layer, so that the compositor can properly mask the
        // scrolling contents and scrollbars.
        if (!paintLayer.layoutObject()->hasClipPath() || (paintLayer.needsCompositedScrolling() && !(paintFlags & PaintLayerPaintingChildClippingMaskPhase)))
            return;

        m_clipperState = SVGClipPainter::ClipperNotApplied;

        ASSERT(style.clipPath());
        if (style.clipPath()->type() == ClipPathOperation::SHAPE) {
            ShapeClipPathOperation* clipPath = toShapeClipPathOperation(style.clipPath());
            if (clipPath->isValid()) {
                if (!rootRelativeBoundsComputed) {
                    rootRelativeBounds = paintLayer.physicalBoundingBoxIncludingReflectionAndStackingChildren(paintingInfo.rootLayer, offsetFromRoot);
                    rootRelativeBoundsComputed = true;
                }
                m_clipPathRecorder.emplace(*context, *paintLayer.layoutObject(), clipPath->path(rootRelativeBounds));
            }
        } else if (style.clipPath()->type() == ClipPathOperation::REFERENCE) {
            ReferenceClipPathOperation* referenceClipPathOperation = toReferenceClipPathOperation(style.clipPath());
            Document& document = paintLayer.layoutObject()->document();
            // FIXME: It doesn't work with forward or external SVG references (https://bugs.webkit.org/show_bug.cgi?id=90405)
            Element* element = document.getElementById(referenceClipPathOperation->fragment());
            if (isSVGClipPathElement(element) && element->layoutObject()) {
                if (!rootRelativeBoundsComputed) {
                    rootRelativeBounds = paintLayer.physicalBoundingBoxIncludingReflectionAndStackingChildren(paintingInfo.rootLayer, offsetFromRoot);
                    rootRelativeBoundsComputed = true;
                }

                m_resourceClipper = toLayoutSVGResourceClipper(toLayoutSVGResourceContainer(element->layoutObject()));
                if (!SVGClipPainter(*m_resourceClipper).applyClippingToContext(*paintLayer.layoutObject(), rootRelativeBounds,
                    paintingInfo.paintDirtyRect, context, m_clipperState)) {
                    // No need to post-apply the clipper if this failed.
                    m_resourceClipper = 0;
                }
            }
        }
    }

    ~ClipPathHelper()
    {
        if (m_resourceClipper)
            SVGClipPainter(*m_resourceClipper).postApplyStatefulResource(*m_paintLayer.layoutObject(), m_context, m_clipperState);
    }
private:
    LayoutSVGResourceClipper* m_resourceClipper;
    Optional<ClipPathRecorder> m_clipPathRecorder;
    SVGClipPainter::ClipperState m_clipperState;
    const DeprecatedPaintLayer& m_paintLayer;
    GraphicsContext* m_context;
};

void DeprecatedPaintLayerPainter::paintLayerContents(GraphicsContext* context, const DeprecatedPaintLayerPaintingInfo& paintingInfo, PaintLayerFlags paintFlags, FragmentPolicy fragmentPolicy)
{
    ASSERT(m_paintLayer.isSelfPaintingLayer() || m_paintLayer.hasSelfPaintingLayerDescendant());
    ASSERT(!(paintFlags & PaintLayerAppliedTransform));

    bool isSelfPaintingLayer = m_paintLayer.isSelfPaintingLayer();
    bool isPaintingOverlayScrollbars = paintFlags & PaintLayerPaintingOverlayScrollbars;
    bool isPaintingScrollingContent = paintFlags & PaintLayerPaintingCompositingScrollingPhase;
    bool isPaintingCompositedForeground = paintFlags & PaintLayerPaintingCompositingForegroundPhase;
    bool isPaintingCompositedBackground = paintFlags & PaintLayerPaintingCompositingBackgroundPhase;
    bool isPaintingOverflowContents = paintFlags & PaintLayerPaintingOverflowContents;
    // Outline always needs to be painted even if we have no visible content. Also,
    // the outline is painted in the background phase during composited scrolling.
    // If it were painted in the foreground phase, it would move with the scrolled
    // content. When not composited scrolling, the outline is painted in the
    // foreground phase. Since scrolled contents are moved by paint invalidation in this
    // case, the outline won't get 'dragged along'.
    bool shouldPaintOutline = isSelfPaintingLayer && !isPaintingOverlayScrollbars
        && ((isPaintingScrollingContent && isPaintingCompositedBackground)
        || (!isPaintingScrollingContent && isPaintingCompositedForeground));
    bool shouldPaintContent = m_paintLayer.hasVisibleContent() && isSelfPaintingLayer && !isPaintingOverlayScrollbars;

    if (paintFlags & PaintLayerPaintingRootBackgroundOnly && !m_paintLayer.layoutObject()->isLayoutView() && !m_paintLayer.layoutObject()->isDocumentElement())
        return;

    // Ensure our lists are up-to-date.
    m_paintLayer.stackingNode()->updateLayerListsIfNeeded();

    LayoutPoint offsetFromRoot;
    m_paintLayer.convertToLayerCoords(paintingInfo.rootLayer, offsetFromRoot);

    if (m_paintLayer.compositingState() == PaintsIntoOwnBacking)
        offsetFromRoot.move(m_paintLayer.subpixelAccumulation());
    else
        offsetFromRoot.move(paintingInfo.subPixelAccumulation);

    LayoutRect rootRelativeBounds;
    bool rootRelativeBoundsComputed = false;

    // These helpers output clip and compositing operations using a RAII pattern. Stack-allocated-varibles are destructed in the reverse order of construction,
    // so they are nested properly.
    ClipPathHelper clipPathHelper(context, m_paintLayer, paintingInfo, rootRelativeBounds, rootRelativeBoundsComputed, offsetFromRoot, paintFlags);

    Optional<LayerClipRecorder> clipRecorder;
    Optional<CompositingRecorder> compositingRecorder;
    // Blending operations must be performed only with the nearest ancestor stacking context.
    // Note that there is no need to composite if we're painting the root.
    // FIXME: this should be unified further into DeprecatedPaintLayer::paintsWithTransparency().
    bool shouldCompositeForBlendMode = (!m_paintLayer.layoutObject()->isDocumentElement() || m_paintLayer.layoutObject()->isSVGRoot()) && m_paintLayer.stackingNode()->isStackingContext() && m_paintLayer.hasNonIsolatedDescendantWithBlendMode();
    if (shouldCompositeForBlendMode || m_paintLayer.paintsWithTransparency(paintingInfo.globalPaintFlags())) {
        clipRecorder.emplace(*context, *m_paintLayer.layoutObject(), DisplayItem::TransparencyClip,
            m_paintLayer.paintingExtent(paintingInfo.rootLayer, paintingInfo.paintDirtyRect, paintingInfo.subPixelAccumulation, paintingInfo.globalPaintFlags()),
            &paintingInfo, LayoutPoint(), paintFlags);

        compositingRecorder.emplace(*context, *m_paintLayer.layoutObject(),
            WebCoreCompositeToSkiaComposite(CompositeSourceOver, m_paintLayer.layoutObject()->style()->blendMode()),
            m_paintLayer.layoutObject()->opacity());
    }

    DeprecatedPaintLayerPaintingInfo localPaintingInfo(paintingInfo);

    DeprecatedPaintLayerFragments layerFragments;
    if (shouldPaintContent || shouldPaintOutline || isPaintingOverlayScrollbars) {
        // Collect the fragments. This will compute the clip rectangles and paint offsets for each layer fragment.
        ClipRectsCacheSlot cacheSlot = (paintFlags & PaintLayerUncachedClipRects) ? UncachedClipRects : PaintingClipRects;
        ShouldRespectOverflowClip respectOverflowClip = shouldRespectOverflowClip(paintFlags, m_paintLayer.layoutObject());
        if (fragmentPolicy == ForceSingleFragment)
            m_paintLayer.appendSingleFragmentIgnoringPagination(layerFragments, localPaintingInfo.rootLayer, localPaintingInfo.paintDirtyRect, cacheSlot, IgnoreOverlayScrollbarSize, respectOverflowClip, &offsetFromRoot, localPaintingInfo.subPixelAccumulation);
        else
            m_paintLayer.collectFragments(layerFragments, localPaintingInfo.rootLayer, localPaintingInfo.paintDirtyRect, cacheSlot, IgnoreOverlayScrollbarSize, respectOverflowClip, &offsetFromRoot, localPaintingInfo.subPixelAccumulation);
        if (shouldPaintContent)
            shouldPaintContent = atLeastOneFragmentIntersectsDamageRect(layerFragments, localPaintingInfo, paintFlags, offsetFromRoot);
    }

    bool selectionOnly = localPaintingInfo.globalPaintFlags() & GlobalPaintSelectionOnly;
    // If this layer's layoutObject is a child of the paintingRoot, we paint unconditionally, which
    // is done by passing a nil paintingRoot down to our layoutObject (as if no paintingRoot was ever set).
    // Else, our layout tree may or may not contain the painting root, so we pass that root along
    // so it will be tested against as we descend through the layoutObjects.
    LayoutObject* paintingRootForLayoutObject = 0;
    if (localPaintingInfo.paintingRoot && !m_paintLayer.layoutObject()->isDescendantOf(localPaintingInfo.paintingRoot))
        paintingRootForLayoutObject = localPaintingInfo.paintingRoot;

    { // Begin block for the lifetime of any filter.
        FilterPainter filterPainter(m_paintLayer, context, offsetFromRoot, layerFragments.isEmpty() ? ClipRect() : layerFragments[0].backgroundRect, localPaintingInfo, paintFlags,
            rootRelativeBounds, rootRelativeBoundsComputed);

        bool shouldPaintBackground = isPaintingCompositedBackground && shouldPaintContent && !selectionOnly;
        bool shouldPaintNegZOrderList = (isPaintingScrollingContent && isPaintingOverflowContents) || (!isPaintingScrollingContent && isPaintingCompositedBackground);
        bool shouldPaintOwnContents = isPaintingCompositedForeground && shouldPaintContent;
        bool shouldPaintNormalFlowAndPosZOrderLists = isPaintingCompositedForeground;
        bool shouldPaintOverlayScrollbars = isPaintingOverlayScrollbars;

        if (shouldPaintBackground) {
            paintBackgroundForFragments(layerFragments, context, paintingInfo.paintDirtyRect,
                localPaintingInfo, paintingRootForLayoutObject, paintFlags);
        }

        if (shouldPaintNegZOrderList)
            paintChildren(NegativeZOrderChildren, context, paintingInfo, paintFlags);

        if (shouldPaintOwnContents) {
            paintForegroundForFragments(layerFragments, context, paintingInfo.paintDirtyRect,
                localPaintingInfo, paintingRootForLayoutObject, selectionOnly, paintFlags);
        }

        if (shouldPaintOutline)
            paintOutlineForFragments(layerFragments, context, localPaintingInfo, paintingRootForLayoutObject, paintFlags);

        if (shouldPaintNormalFlowAndPosZOrderLists)
            paintChildren(NormalFlowChildren | PositiveZOrderChildren, context, paintingInfo, paintFlags);

        if (shouldPaintOverlayScrollbars)
            paintOverflowControlsForFragments(layerFragments, context, localPaintingInfo, paintFlags);
    } // FilterPainter block

    bool shouldPaintMask = (paintFlags & PaintLayerPaintingCompositingMaskPhase) && shouldPaintContent && m_paintLayer.layoutObject()->hasMask() && !selectionOnly;
    bool shouldPaintClippingMask = (paintFlags & PaintLayerPaintingChildClippingMaskPhase) && shouldPaintContent && !selectionOnly;

    if (shouldPaintMask)
        paintMaskForFragments(layerFragments, context, localPaintingInfo, paintingRootForLayoutObject, paintFlags);
    if (shouldPaintClippingMask) {
        // Paint the border radius mask for the fragments.
        paintChildClippingMaskForFragments(layerFragments, context, localPaintingInfo, paintingRootForLayoutObject, paintFlags);
    }
}

bool DeprecatedPaintLayerPainter::needsToClip(const DeprecatedPaintLayerPaintingInfo& localPaintingInfo, const ClipRect& clipRect)
{
    return clipRect.rect() != localPaintingInfo.paintDirtyRect || clipRect.hasRadius();
}

bool DeprecatedPaintLayerPainter::atLeastOneFragmentIntersectsDamageRect(DeprecatedPaintLayerFragments& fragments, const DeprecatedPaintLayerPaintingInfo& localPaintingInfo, PaintLayerFlags localPaintFlags, const LayoutPoint& offsetFromRoot)
{
    if (m_paintLayer.enclosingPaginationLayer())
        return true; // The fragments created have already been found to intersect with the damage rect.

    if (&m_paintLayer == localPaintingInfo.rootLayer && (localPaintFlags & PaintLayerPaintingOverflowContents))
        return true;

    for (DeprecatedPaintLayerFragment& fragment: fragments) {
        LayoutPoint newOffsetFromRoot = offsetFromRoot + fragment.paginationOffset;
        // Note that this really only works reliably on the first fragment. If the layer has visible
        // overflow and a subsequent fragment doesn't intersect with the border box of the layer
        // (i.e. only contains an overflow portion of the layer), intersection will fail. The reason
        // for this is that fragment.layerBounds is set to the border box, not the bounding box, of
        // the layer.
        if (m_paintLayer.intersectsDamageRect(fragment.layerBounds, fragment.backgroundRect.rect(), localPaintingInfo.rootLayer, &newOffsetFromRoot))
            return true;
    }
    return false;
}

void DeprecatedPaintLayerPainter::paintLayerWithTransform(GraphicsContext* context, const DeprecatedPaintLayerPaintingInfo& paintingInfo, PaintLayerFlags paintFlags)
{
    TransformationMatrix layerTransform = m_paintLayer.renderableTransform(paintingInfo.globalPaintFlags());
    // If the transform can't be inverted, then don't paint anything.
    if (!layerTransform.isInvertible())
        return;

    // FIXME: We should make sure that we don't walk past paintingInfo.rootLayer here.
    // m_paintLayer may be the "root", and then we should avoid looking at its parent.
    DeprecatedPaintLayer* parentLayer = m_paintLayer.parent();

    ClipRect ancestorBackgroundClipRect;
    if (parentLayer) {
        // Calculate the clip rectangle that the ancestors establish.
        ClipRectsContext clipRectsContext(paintingInfo.rootLayer, (paintFlags & PaintLayerUncachedClipRects) ? UncachedClipRects : PaintingClipRects, IgnoreOverlayScrollbarSize);
        if (shouldRespectOverflowClip(paintFlags, m_paintLayer.layoutObject()) == IgnoreOverflowClip)
            clipRectsContext.setIgnoreOverflowClip();
        ancestorBackgroundClipRect = m_paintLayer.clipper().backgroundClipRect(clipRectsContext);
    }

    DeprecatedPaintLayer* paginationLayer = m_paintLayer.enclosingPaginationLayer();
    DeprecatedPaintLayerFragments fragments;
    if (paginationLayer) {
        // FIXME: This is a mess. Look closely at this code and the code in Layer and fix any
        // issues in it & refactor to make it obvious from code structure what it does and that it's
        // correct.
        ClipRectsCacheSlot cacheSlot = (paintFlags & PaintLayerUncachedClipRects) ? UncachedClipRects : PaintingClipRects;
        ShouldRespectOverflowClip respectOverflowClip = shouldRespectOverflowClip(paintFlags, m_paintLayer.layoutObject());
        // Calculate the transformed bounding box in the current coordinate space, to figure out
        // which fragmentainers (e.g. columns) we need to visit.
        LayoutRect transformedExtent = DeprecatedPaintLayer::transparencyClipBox(&m_paintLayer, paginationLayer, DeprecatedPaintLayer::PaintingTransparencyClipBox, DeprecatedPaintLayer::RootOfTransparencyClipBox, paintingInfo.subPixelAccumulation, paintingInfo.globalPaintFlags());
        // FIXME: we don't check if paginationLayer is within paintingInfo.rootLayer here.
        paginationLayer->collectFragments(fragments, paintingInfo.rootLayer, paintingInfo.paintDirtyRect, cacheSlot, IgnoreOverlayScrollbarSize, respectOverflowClip, 0, paintingInfo.subPixelAccumulation, &transformedExtent);
    } else {
        // We don't need to collect any fragments in the regular way here. We have already
        // calculated a clip rectangle for the ancestry if it was needed, and clipping this
        // layer is something that can be done further down the path, when the transform has
        // been applied.
        DeprecatedPaintLayerFragment fragment;
        fragment.backgroundRect = paintingInfo.paintDirtyRect;
        fragments.append(fragment);
    }

    bool needsScope = fragments.size() > 1;
    for (const auto& fragment : fragments) {
        Optional<ScopeRecorder> scopeRecorder;
        if (needsScope)
            scopeRecorder.emplace(*context);
        Optional<LayerClipRecorder> clipRecorder;
        if (parentLayer) {
            ClipRect clipRectForFragment(ancestorBackgroundClipRect);
            clipRectForFragment.moveBy(fragment.paginationOffset);
            clipRectForFragment.intersect(fragment.backgroundRect);
            if (clipRectForFragment.isEmpty())
                continue;
            if (needsToClip(paintingInfo, clipRectForFragment))
                clipRecorder.emplace(*context, *parentLayer->layoutObject(), DisplayItem::ClipLayerParent, clipRectForFragment, &paintingInfo, fragment.paginationOffset, paintFlags);
        }

        paintFragmentByApplyingTransform(context, paintingInfo, paintFlags, fragment.paginationOffset);
    }
}

void DeprecatedPaintLayerPainter::paintFragmentByApplyingTransform(GraphicsContext* context, const DeprecatedPaintLayerPaintingInfo& paintingInfo, PaintLayerFlags paintFlags, const LayoutPoint& fragmentTranslation)
{
    // This involves subtracting out the position of the layer in our current coordinate space, but preserving
    // the accumulated error for sub-pixel layout.
    LayoutPoint delta;
    m_paintLayer.convertToLayerCoords(paintingInfo.rootLayer, delta);
    delta.moveBy(fragmentTranslation);
    TransformationMatrix transform(m_paintLayer.renderableTransform(paintingInfo.globalPaintFlags()));
    IntPoint roundedDelta = roundedIntPoint(delta);
    transform.translateRight(roundedDelta.x(), roundedDelta.y());
    LayoutSize adjustedSubPixelAccumulation = paintingInfo.subPixelAccumulation + (delta - roundedDelta);

    Transform3DRecorder transform3DRecorder(*context, *m_paintLayer.layoutObject(), DisplayItem::Transform3DElementTransform, transform);

    // Now do a paint with the root layer shifted to be us.
    DeprecatedPaintLayerPaintingInfo transformedPaintingInfo(&m_paintLayer, LayoutRect(enclosingIntRect(transform.inverse().mapRect(paintingInfo.paintDirtyRect))), paintingInfo.globalPaintFlags(),
        adjustedSubPixelAccumulation, paintingInfo.paintingRoot);
    paintLayerContentsAndReflection(context, transformedPaintingInfo, paintFlags, ForceSingleFragment);
}

void DeprecatedPaintLayerPainter::paintChildren(unsigned childrenToVisit, GraphicsContext* context, const DeprecatedPaintLayerPaintingInfo& paintingInfo, PaintLayerFlags paintFlags)
{
    if (!m_paintLayer.hasSelfPaintingLayerDescendant())
        return;

#if ENABLE(ASSERT)
    LayerListMutationDetector mutationChecker(m_paintLayer.stackingNode());
#endif

    IntSize scrollOffsetAccumulation = paintingInfo.scrollOffsetAccumulation;
    if (m_paintLayer.layoutObject()->hasOverflowClip())
        scrollOffsetAccumulation += m_paintLayer.layoutBox()->scrolledContentOffset();

    DeprecatedPaintLayerStackingNodeIterator iterator(*m_paintLayer.stackingNode(), childrenToVisit);
    while (DeprecatedPaintLayerStackingNode* child = iterator.next()) {
        DeprecatedPaintLayerPainter childPainter(*child->layer());
        // If this Layer should paint into its own backing or a grouped backing, that will be done via CompositedDeprecatedPaintLayerMapping::paintContents()
        // and CompositedDeprecatedPaintLayerMapping::doPaintTask().
        if (!childPainter.shouldPaintLayerInSoftwareMode(paintingInfo.globalPaintFlags(), paintFlags))
            continue;

        DeprecatedPaintLayerPaintingInfo childPaintingInfo = paintingInfo;
        childPaintingInfo.scrollOffsetAccumulation = scrollOffsetAccumulation;
        // Rare case: accumulate scroll offset of non-stacking-context ancestors up to m_paintLayer.
        for (DeprecatedPaintLayer* parentLayer = child->layer()->parent(); parentLayer != &m_paintLayer; parentLayer = parentLayer->parent()) {
            if (parentLayer->layoutObject()->hasOverflowClip())
                childPaintingInfo.scrollOffsetAccumulation += parentLayer->layoutBox()->scrolledContentOffset();
        }

        childPainter.paintLayer(context, childPaintingInfo, paintFlags);
    }
}

// FIXME: inline this.
static bool paintForFixedRootBackground(const DeprecatedPaintLayer* layer, PaintLayerFlags paintFlags)
{
    return layer->layoutObject()->isDocumentElement() && (paintFlags & PaintLayerPaintingRootBackgroundOnly);
}

bool DeprecatedPaintLayerPainter::shouldPaintLayerInSoftwareMode(const GlobalPaintFlags globalPaintFlags, PaintLayerFlags paintFlags)
{
    DisableCompositingQueryAsserts disabler;

    return m_paintLayer.compositingState() == NotComposited
        || (globalPaintFlags & GlobalPaintFlattenCompositingLayers)
        || ((paintFlags & PaintLayerPaintingReflection) && !m_paintLayer.has3DTransform())
        || paintForFixedRootBackground(&m_paintLayer, paintFlags);
}

void DeprecatedPaintLayerPainter::paintOverflowControlsForFragments(const DeprecatedPaintLayerFragments& layerFragments, GraphicsContext* context, const DeprecatedPaintLayerPaintingInfo& localPaintingInfo, PaintLayerFlags paintFlags)
{
    bool needsScope = layerFragments.size() > 1;
    for (auto& fragment : layerFragments) {
        Optional<ScopeRecorder> scopeRecorder;
        if (needsScope)
            scopeRecorder.emplace(*context);

        Optional<LayerClipRecorder> clipRecorder;

        if (needsToClip(localPaintingInfo, fragment.backgroundRect))
            clipRecorder.emplace(*context, *m_paintLayer.layoutObject(), DisplayItem::ClipLayerOverflowControls, fragment.backgroundRect, &localPaintingInfo, fragment.paginationOffset, paintFlags);
        if (DeprecatedPaintLayerScrollableArea* scrollableArea = m_paintLayer.scrollableArea())
            ScrollableAreaPainter(*scrollableArea).paintOverflowControls(context, roundedIntPoint(toPoint(fragment.layerBounds.location() - m_paintLayer.layoutBoxLocation())), pixelSnappedIntRect(fragment.backgroundRect.rect()), true);
    }
}

void DeprecatedPaintLayerPainter::paintFragmentWithPhase(PaintPhase phase, const DeprecatedPaintLayerFragment& fragment, GraphicsContext* context, const ClipRect& clipRect, const DeprecatedPaintLayerPaintingInfo& paintingInfo, LayoutObject* paintingRootForLayoutObject, PaintLayerFlags paintFlags, ClipState clipState)
{
    ASSERT(m_paintLayer.isSelfPaintingLayer());

    Optional<LayerClipRecorder> clipRecorder;
    if (clipState != HasClipped && paintingInfo.clipToDirtyRect && needsToClip(paintingInfo, clipRect)) {
        DisplayItem::Type clipType = DisplayItem::paintPhaseToClipLayerFragmentType(phase);
        LayerClipRecorder::BorderRadiusClippingRule clippingRule;
        switch (phase) {
        case PaintPhaseBlockBackground: // Background painting will handle clipping to self.
        case PaintPhaseSelfOutline:
        case PaintPhaseMask: // Mask painting will handle clipping to self.
            clippingRule = LayerClipRecorder::DoNotIncludeSelfForBorderRadius;
            break;
        default:
            clippingRule = LayerClipRecorder::IncludeSelfForBorderRadius;
            break;
        }

        clipRecorder.emplace(*context, *m_paintLayer.layoutObject(), clipType, clipRect, &paintingInfo, fragment.paginationOffset, paintFlags, clippingRule);
    }

    PaintInfo paintInfo(context, pixelSnappedIntRect(clipRect.rect()), phase, paintingInfo.globalPaintFlags(), paintFlags, paintingRootForLayoutObject, 0, paintingInfo.rootLayer->layoutObject());
    Optional<ScrollRecorder> scrollRecorder;
    LayoutPoint paintOffset = toPoint(fragment.layerBounds.location() - m_paintLayer.layoutBoxLocation());
    if (!paintingInfo.scrollOffsetAccumulation.isZero()) {
        // As a descendant of the root layer, m_paintLayer's painting is not controlled by the ScrollRecorders
        // created by BlockPainter of the ancestor layers up to the root layer, so we need to issue ScrollRecorder
        // for this layer seperately, with the scroll offset accumulated from the root layer to the parent of this
        // layer, to get the same result as ScrollRecorder in BlockPainter.
        paintOffset += paintingInfo.scrollOffsetAccumulation;
        paintInfo.rect.move(paintingInfo.scrollOffsetAccumulation);
        scrollRecorder.emplace(*paintInfo.context, *m_paintLayer.layoutObject(), paintInfo.phase, paintingInfo.scrollOffsetAccumulation);
    }
    m_paintLayer.layoutObject()->paint(paintInfo, paintOffset);
}

void DeprecatedPaintLayerPainter::paintBackgroundForFragments(const DeprecatedPaintLayerFragments& layerFragments, GraphicsContext* context,
    const LayoutRect& transparencyPaintDirtyRect, const DeprecatedPaintLayerPaintingInfo& localPaintingInfo,
    LayoutObject* paintingRootForLayoutObject, PaintLayerFlags paintFlags)
{
    bool needsScope = layerFragments.size() > 1;
    for (auto& fragment : layerFragments) {
        Optional<ScopeRecorder> scopeRecorder;
        if (needsScope)
            scopeRecorder.emplace(*context);
        paintFragmentWithPhase(PaintPhaseBlockBackground, fragment, context, fragment.backgroundRect, localPaintingInfo, paintingRootForLayoutObject, paintFlags, HasNotClipped);
    }
}

void DeprecatedPaintLayerPainter::paintForegroundForFragments(const DeprecatedPaintLayerFragments& layerFragments, GraphicsContext* context,
    const LayoutRect& transparencyPaintDirtyRect, const DeprecatedPaintLayerPaintingInfo& localPaintingInfo,
    LayoutObject* paintingRootForLayoutObject, bool selectionOnly, PaintLayerFlags paintFlags)
{
    // Optimize clipping for the single fragment case.
    bool shouldClip = localPaintingInfo.clipToDirtyRect && layerFragments.size() == 1 && !layerFragments[0].foregroundRect.isEmpty();
    ClipState clipState = HasNotClipped;
    Optional<LayerClipRecorder> clipRecorder;
    if (shouldClip && needsToClip(localPaintingInfo, layerFragments[0].foregroundRect)) {
        clipRecorder.emplace(*context, *m_paintLayer.layoutObject(), DisplayItem::ClipLayerForeground, layerFragments[0].foregroundRect, &localPaintingInfo, layerFragments[0].paginationOffset, paintFlags);
        clipState = HasClipped;
    }

    // We have to loop through every fragment multiple times, since we have to issue paint invalidations in each specific phase in order for
    // interleaving of the fragments to work properly.
    paintForegroundForFragmentsWithPhase(selectionOnly ? PaintPhaseSelection : PaintPhaseChildBlockBackgrounds, layerFragments,
        context, localPaintingInfo, paintingRootForLayoutObject, paintFlags, clipState);

    if (!selectionOnly) {
        paintForegroundForFragmentsWithPhase(PaintPhaseFloat, layerFragments, context, localPaintingInfo, paintingRootForLayoutObject, paintFlags, clipState);
        paintForegroundForFragmentsWithPhase(PaintPhaseForeground, layerFragments, context, localPaintingInfo, paintingRootForLayoutObject, paintFlags, clipState);
        paintForegroundForFragmentsWithPhase(PaintPhaseChildOutlines, layerFragments, context, localPaintingInfo, paintingRootForLayoutObject, paintFlags, clipState);
    }
}

void DeprecatedPaintLayerPainter::paintForegroundForFragmentsWithPhase(PaintPhase phase, const DeprecatedPaintLayerFragments& layerFragments, GraphicsContext* context,
    const DeprecatedPaintLayerPaintingInfo& localPaintingInfo, LayoutObject* paintingRootForLayoutObject, PaintLayerFlags paintFlags, ClipState clipState)
{
    bool needsScope = layerFragments.size() > 1;
    for (auto& fragment : layerFragments) {
        if (!fragment.foregroundRect.isEmpty()) {
            Optional<ScopeRecorder> scopeRecorder;
            if (needsScope)
                scopeRecorder.emplace(*context);
            paintFragmentWithPhase(phase, fragment, context, fragment.foregroundRect, localPaintingInfo, paintingRootForLayoutObject, paintFlags, clipState);
        }
    }
}

void DeprecatedPaintLayerPainter::paintOutlineForFragments(const DeprecatedPaintLayerFragments& layerFragments, GraphicsContext* context, const DeprecatedPaintLayerPaintingInfo& localPaintingInfo,
    LayoutObject* paintingRootForLayoutObject, PaintLayerFlags paintFlags)
{
    bool needsScope = layerFragments.size() > 1;
    for (auto& fragment : layerFragments) {
        if (!fragment.outlineRect.isEmpty()) {
            Optional<ScopeRecorder> scopeRecorder;
            if (needsScope)
                scopeRecorder.emplace(*context);
            paintFragmentWithPhase(PaintPhaseSelfOutline, fragment, context, fragment.outlineRect, localPaintingInfo, paintingRootForLayoutObject, paintFlags, HasNotClipped);
        }
    }
}

void DeprecatedPaintLayerPainter::paintMaskForFragments(const DeprecatedPaintLayerFragments& layerFragments, GraphicsContext* context, const DeprecatedPaintLayerPaintingInfo& localPaintingInfo,
    LayoutObject* paintingRootForLayoutObject, PaintLayerFlags paintFlags)
{
    bool needsScope = layerFragments.size() > 1;
    for (auto& fragment : layerFragments) {
        Optional<ScopeRecorder> scopeRecorder;
        if (needsScope)
            scopeRecorder.emplace(*context);
        paintFragmentWithPhase(PaintPhaseMask, fragment, context, fragment.backgroundRect, localPaintingInfo, paintingRootForLayoutObject, paintFlags, HasNotClipped);
    }
}

void DeprecatedPaintLayerPainter::paintChildClippingMaskForFragments(const DeprecatedPaintLayerFragments& layerFragments, GraphicsContext* context, const DeprecatedPaintLayerPaintingInfo& localPaintingInfo,
    LayoutObject* paintingRootForLayoutObject, PaintLayerFlags paintFlags)
{
    bool needsScope = layerFragments.size() > 1;
    for (auto& fragment: layerFragments) {
        Optional<ScopeRecorder> scopeRecorder;
        if (needsScope)
            scopeRecorder.emplace(*context);
        paintFragmentWithPhase(PaintPhaseClippingMask, fragment, context, fragment.foregroundRect, localPaintingInfo, paintingRootForLayoutObject, paintFlags, HasNotClipped);
    }
}

void DeprecatedPaintLayerPainter::paintOverlayScrollbars(GraphicsContext* context, const LayoutRect& damageRect, const GlobalPaintFlags paintFlags, LayoutObject* paintingRoot)
{
    if (!m_paintLayer.containsDirtyOverlayScrollbars())
        return;

    DeprecatedPaintLayerPaintingInfo paintingInfo(&m_paintLayer, LayoutRect(enclosingIntRect(damageRect)), paintFlags, LayoutSize(), paintingRoot);
    paintLayer(context, paintingInfo, PaintLayerPaintingOverlayScrollbars);

    m_paintLayer.setContainsDirtyOverlayScrollbars(false);
}

} // namespace blink


text:
main(void){
    //inicializamos la variable que tomara el valor de cada caracter del arreglo;
    int c;

   // recorremos el string y lo imprimimos;
    while( (c=getchar()) != EOF){
        putchar(c);
    }
}


text:
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Globalization;

namespace System.Waf.Foundation
{
    ///
    /// This class provides an implementation for the <see cref="IDataErrorInfo"/> interface which uses the
    /// validation classes found in the <see cref="System.ComponentModel.DataAnnotations"/> namespace.
    ///
    public sealed class DataErrorInfoSupport : IDataErrorInfo
    {
        private readonly object instance;

        /// Initializes a new instance of the <see cref="DataErrorInfoSupport"/> class.
        /// <param name="instance">The instance.</param>
        /// <exception cref="ArgumentNullException">instance must not be <c>null</c>.</exception>
        public DataErrorInfoSupport(object instance)
        {
            this.instance = instance ?? throw new ArgumentNullException(nameof(instance));
        }

        /// Gets an error message indicating what is wrong with this object.
        /// <returns>An error message indicating what is wrong with this object. The default is an empty string ("").</returns>
        public string Error => this[""];

        /// Gets the error message for the property with the given name.
        /// <param name="memberName">The name of the property whose error message to get.</param>
        /// <returns>The error message for the property. The default is an empty string ("").</returns>
        public string this[string? memberName]
        {
            get
            {
                var validationResults = new List<ValidationResult>();
                if (string.IsNullOrEmpty(memberName))
                {
                    Validator.TryValidateObject(instance, new ValidationContext(instance, null, null), validationResults, true);
                }
                else
                {
                    PropertyDescriptor property = TypeDescriptor.GetProperties(instance)[memberName];
                    if (property == null)
                    {
                        throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
                            "The specified member {0} was not found on the instance {1}", memberName, instance.GetType()));
                    }
                    Validator.TryValidateProperty(property.GetValue(instance),
                        new ValidationContext(instance, null, null) { MemberName = memberName }, validationResults);
                }
                return string.Join(Environment.NewLine, validationResults.Select(x => x.ErrorMessage));
            }
        }
    }
}


text:
warning: 'This file is auto generated by `npm run web:inject`, do not edit by hand'
examples:
  - Math.ceil(sin(8723321.4) * 10000000)
estarget: es5
returns:
  - '-9834330'
dependencies: []
authors:
  original by:
    - 'Onno Marsman (https://twitter.com/onnomarsman)'
notes: []
type: function
layout: function
title: PHP's sin in JavaScript
description: >-
  Here's what our current JavaScript equivalent to PHP's sin looks like.
function: sin
category: math
language: php
permalink: php/math/sin/
alias:
  - /functions/php/sin/
  - /functions/math/sin/
  - /php/sin/
  - /functions/sin/
---
{% codeblock lang:javascript %}module.exports = function sin (arg) {
  //  discuss at: https://locutus.io/php/sin/
  // original by: Onno Marsman (https://twitter.com/onnomarsman)
  //   example 1: Math.ceil(sin(8723321.4) * 10000000)
  //   returns 1: -9834330

  return Math.sin(arg)
}
{% endcodeblock %}


text:
<?php

declare(strict_types=1);

namespace Kerox\Messenger\Event;

use Kerox\Messenger\Model\Callback\Payment;

final class PaymentEvent extends AbstractEvent
{
    public const NAME = 'payment';

    /**
     * @var int
     */
    protected $timestamp;

    /**
     * @var \Kerox\Messenger\Model\Callback\Payment
     */
    protected $payment;

    /**
     * PaymentEvent constructor.
     */
    public function __construct(string $senderId, string $recipientId, int $timestamp, Payment $payment)
    {
        parent::__construct($senderId, $recipientId);

        $this->timestamp = $timestamp;
        $this->payment = $payment;
    }

    public function getTimestamp(): int
    {
        return $this->timestamp;
    }

    public function getPayment(): Payment
    {
        return $this->payment;
    }

    public function getName(): string
    {
        return self::NAME;
    }

    /**
     * @return \Kerox\Messenger\Event\PaymentEvent
     */
    public static function create(array $payload): self
    {
        $senderId = $payload['sender']['id'];
        $recipientId = $payload['recipient']['id'];
        $timestamp = $payload['timestamp'];
        $payment = Payment::create($payload['payment']);

        return new self($senderId, $recipientId, $timestamp, $payment);
    }
}


text:
import sbt._
import sbt.Keys._
import scala.util.matching.Regex
import scala.util.matching.Regex.Match

// adapted from http://stackoverflow.com/questions/16934488/how-to-link-classes-from-jdk-into-scaladoc-generated-doc
object ScaladocSettings {
  private[this] val externalJavadocMap = Map(
    //"owlapi" -> "http://owlcs.github.io/owlapi/apidocs_4_0_2/index.html"
  )

  /*
   * The rt.jar file is located in the path stored in the sun.boot.class.path system property.
   * See the Oracle documentation at http://docs.oracle.com/javase/6/docs/technotes/tools/findingclasses.html.
   */
  private[this] val rtJar: String = System.getProperty("sun.boot.class.path").split(java.io.File.pathSeparator).collectFirst {
    case str: String if str.endsWith(java.io.File.separator + "rt.jar") => str
  }.get // fail hard if not found

  private[this] val javaApiUrl: String = "http://docs.oracle.com/javase/8/docs/api/index.html"

  private[this] val allExternalJavadocLinks: Seq[String] = javaApiUrl +: externalJavadocMap.values.toSeq

  private[this] def javadocLinkRegex(javadocURL: String): Regex = ("""\"(\Q""" + javadocURL + """\E)#([^"]*)\"""").r

  private[this] def hasJavadocLink(f: File): Boolean = allExternalJavadocLinks exists {
    javadocURL: String =>
      (javadocLinkRegex(javadocURL) findFirstIn IO.read(f)).nonEmpty
  }

  private[this] val fixJavaLinks: Match => String = m =>
    m.group(1) + "?" + m.group(2).replace(".", "/") + ".html"

  private[this] val mapJavaLink = { target: File =>
    (target ** "*.html").get.filter(hasJavadocLink).foreach { f =>
      //println(s"Fixing $f.")
      val newContent: String = allExternalJavadocLinks.foldLeft(IO.read(f)) {
        case (oldContent: String, javadocURL: String) =>
          javadocLinkRegex(javadocURL).replaceAllIn(oldContent, fixJavaLinks)
      }
      IO.write(f, newContent)
    }
    target
  }

  /* You can print the classpath with `show compile:fullClasspath` in the SBT REPL.
   * From that list you can find the name of the jar for the managed dependency.
   */
  lazy val scaladocSettings = Seq(
    apiMappings ++= {
      // Lookup the path to jar from the classpath
      val classpath = (fullClasspath in Compile).value
      def findJar(nameBeginsWith: String): File = {
        classpath.find { attributed: Attributed[File] => (attributed.data ** s"$nameBeginsWith*.jar").get.nonEmpty }.get.data // fail hard if not found
      }
      // Define external documentation paths
      (externalJavadocMap map {
        case (name, javadocURL) => findJar(name) -> url(javadocURL)
      }) + (file(rtJar) -> url(javaApiUrl))
    },
    // Override the task to fix the links to JavaDoc
    doc in Compile <<= (doc in Compile) map mapJavaLink,
    doc in Test <<= (doc in Test) map mapJavaLink
  )
}