text:
"""
This script defines the metadata schema that is consumed by all of the other scripts. It contains
the following main parts:
 - Declaration of pre-existing types (enums, primitives)
 - Types that encapsulate the schema definition (MemberDef, RecordDef). These are consumed by
   some scripts, but some others consume the schema definition directly (they were not updated
   to consume the encapsulating class instances).
 - Introduced enum definitions (attribute name: enumSchema)
 -
"""

import os
import sys

if __name__ == '__main__':
    #Dynamically append current script path to PYTHONPATH
    sys.path.append(os.path.dirname(sys.argv[0]))

# from BaseGen import classinit
from copy import copy
from CsCommonGen2 import *
from odict import odict

#==========================================================================================================
enumTypes = odict(sorted([
    ('AssemblyFlags', 'uint'),
    ('AssemblyHashAlgorithm', 'uint'),
    ('CallingConventions', 'ushort'), # System.Reflection.CallingConventions
    ('EventAttributes', 'ushort'),
    ('FieldAttributes', 'ushort'),
    ('FixedArgumentAttributes', 'byte'),
    ('GenericParameterAttributes', 'ushort'),
    ('GenericParameterKind', 'byte'),
    ('MethodAttributes', 'ushort'),
    ('MethodImplAttributes', 'ushort'),
    ('MethodSemanticsAttributes', 'ushort'),
    ('NamedArgumentMemberKind', 'byte'),
    ('ParameterAttributes', 'ushort'),
    ('PInvokeAttributes', 'ushort'),
    ('PropertyAttributes', 'ushort'),
    ('TypeAttributes', 'uint'),
]))

#==========================================================================================================
primitiveTypes = odict(sorted([(
    ('bool', 'Boolean'),
    ('char', 'Char'),
    ('string', 'String'),
    ('byte', 'Byte'),
    ('sbyte', 'SByte'),
    ('short', 'Int16'),
    ('ushort', 'UInt16'),
    ('int', 'Int32'),
    ('uint', 'UInt32'),
    ('long', 'Int64'),
    ('ulong', 'UInt64'),
    ('float', 'Single'),
    ('double', 'Double'))]))

#==========================================================================================================
class RecordDefFlags(Flags):
    """
    Defines the set of flags that may be applied to a schema record definition.
    """
    @classmethod
    def __clsinit__(cls):
        cls.AddFlag('Enum')             # Indicates that the record is actually an enum.
        cls.AddFlag('Flags')            # Indicates that [Flags] should be applied to enum definition.
        cls.AddFlag('CustomCompare')    # Indicates a specific set of members have been flagged for use in
                                        # implementing equality functionality; else all members are used.
        cls.AddFlag('ReentrantEquals')  # The generated Equals method is potentially reentrant on the same instance
                                        # and should have a fast exit path to protect from infinite recursion.
classinit(RecordDefFlags)

#==========================================================================================================
class MemberDefFlags(Flags):
    """
    Defines the set of flags that may be applied to the member definition of a schema record.
    """
    @classmethod
    def __clsinit__(cls):
        cls.AddFlag('Map')              # => Dictionary<string, RecordType> for MetadataWriter
                                        # => List<RecordType> for MetadataReader
        cls.AddFlag('List')             # => List<RecordType>
        cls.AddFlag('Array')            # => RecordType[]
        cls.AddMask('Collection', 'Map', 'List', 'Array')
        cls.AddMask('Sequence', 'List', 'Array')
        cls.AddFlag('RecordRef')        # => RecordTypeHandle
        cls.AddMask('Ref', 'RecordRef')
        cls.AddFlag('Child')            # Member instance is logically defined and owned by record;
                                        # otherwise instance may be shared (such as a TypeRef).
        cls.AddFlag('Name')             # May be used as the member's simple name for diagnostics.
        cls.AddFlag('NotPersisted')     # Indicates member is not written to or read from metadata.
        cls.AddFlag('Compare')          # Indicates member should be used for equality functionality.
        cls.AddFlag('EnumerateForHashCode') # Indicates that the collection is safe to be enumerated in GetHashCode
                                            # without causing reentrancy
classinit(MemberDefFlags)

#==========================================================================================================
class MemberDef(object):
    """
    Encapsulates definition of member in schema record definition.
    """
    def __init__(self, name, typeName = None, flags = MemberDefFlags(0), comment = None, **kv):
        self.name = name
        self.typeName = typeName
        self.flags = MemberDefFlags(int(flags))
        self.comment = comment
        # Add additional (name,value) argument pairs as attributes on this instance.
        for k,v in kv.iteritems():
            setattr(self, k, v)

    def __cmp__(self, other):
        return cmp(self.name, other.name)

#==========================================================================================================
class RecordDef(object):
    """
    Encapsulates definition of schema record.
    """
    def __init__(self, name, baseTypeName = None, flags = RecordDefFlags(0), members = [], comment = None, **kv):
        self.name = name
        self.baseTypeName = baseTypeName
        self.flags = RecordDefFlags(int(flags))
        self.comment = comment
        self.members = list()
        for member in members:
            self.members.append(MemberDef(**member))
        # Add additional (name,value) argument pairs as attributes on this instance.
        for k,v in kv.iteritems():
            setattr(self, k, v)

    def __str__(self):
        return self.name

    def __cmp__(self, other):
        return cmp(self.name, other.name)

#=== Defined Enums ========================================================================================
# Defined as a list of dictionaries of (name, value) pairs. These enums supplement those defined by
# System.Reflection.Primitives.

__enumSchema = [
    # AssemblyFlags - as defined in ECMA
    {   'name': 'AssemblyFlags',
        'baseTypeName': 'uint',
        'flags': RecordDefFlags.Enum | RecordDefFlags.Flags,
        'members': [
            { 'name': 'PublicKey', 'value': 0x0001, 'comment': 'The assembly reference holds the full (unhashed) public key.' },
            { 'name': 'Retargetable', 'value': 0x0100, 'comment': 'The implementation of this assembly used at runtime is not expected to match the version seen at compile time.' },
            { 'name': 'DisableJITcompileOptimizer', 'value': 0x4000, 'comment': 'Reserved.' },
            { 'name': 'EnableJITcompileTracking', 'value': 0x8000, 'comment': 'Reserved.' },
        ],
    },
    # AssemblyHashAlgorithm - as defined in ECMA
    {   'name': 'AssemblyHashAlgorithm',
        'baseTypeName': 'uint',
        'flags': RecordDefFlags.Enum,
        'members': [
            { 'name': 'None', 'value': 0x0000 },
            { 'name': 'Reserved', 'value': 0x8003 },
            { 'name': 'SHA1', 'value': 0x8004 },
        ],
    },
    # FixedArgumentAttributes - used to indicate if an argument for a custom attribute instantiation
    # should be boxed.
    {   'name': 'FixedArgumentAttributes',
        'baseTypeName': 'byte',
        'flags': RecordDefFlags.Enum | RecordDefFlags.Flags,
        'members': [
            { 'name': 'None', 'value': 0 },
            { 'name': 'Boxed', 'comment': 'Values should be boxed as Object' },
        ],
    },
    # NamedArgumentMemberKind - used to disambiguate the referenced members of the named
    # arguments to a custom attribute instance.
    {   'name': 'NamedArgumentMemberKind',
        'baseTypeName': 'byte',
        'flags': RecordDefFlags.Enum,
        'members': [
            { 'name': 'Property', 'comment': 'Specifies the name of a property' },
            { 'name': 'Field',    'comment': 'Specifies the name of a field' },
        ]
    },
    # GenericParameterKind - used to distinguish between generic type and generic method type parameters.
    {   'name': 'GenericParameterKind',
        'baseTypeName': 'byte',
        'flags': RecordDefFlags.Enum,
        'members': [
            { 'name': 'GenericTypeParameter', 'comment': 'Represents a type parameter for a generic type.' },
            { 'name': 'GenericMethodParameter', 'comment': 'Represents a type parameter from a generic method.' },
        ]
    },
]

# Create a list of RecordDef instances based on the contents of __enumSchema
enumSchema = [RecordDef(**enumDef) for enumDef in __enumSchema]

#=== Record schema definition =============================================================================

#--- ConstantXXXValue, ConstantXXXArray, and corresponding Handle types -----------------------------------
# Creates a set of record schema definitions (see format description in 'Metadata records' section below)
# that represent contant primitive type values. Adds concept of constant managed reference, which
# must always have a null value (thus the use of the NotPersisted flag).
__constantValueTypes = sorted([fName for (csName, fName) in primitiveTypes.iteritems()] + ['Reference', 'Handle'])
__constantValueRecordSchema = [('Constant' + fName + 'Value', None, RecordDefFlags(0), [('Value', csName, MemberDefFlags(0))]) \
    for (csName, fName) in primitiveTypes.iteritems()] + \
    [('ConstantReferenceValue', None, RecordDefFlags(0), [('Value', 'Object', MemberDefFlags.NotPersisted)])]

# Creates a set of record schema definitions (see format description in 'Metadata records' section below)
# that represent contant arrays primitive type values. Adds concept of a constant array of handle values (currently used to store
# an array TypeDefOrRefOrSpec handles corresponding to System.Type arguments to the instantiation of a custom attribute, or to store
# custom initialized object[] arrays in custom attributes).
__constantValueArrayTypes = sorted([fName + 'Array' for (csName, fName) in primitiveTypes.iteritems()] + ['HandleArray'])
__constantArrayRecordSchema = [('Constant' + fName + 'Array', None, RecordDefFlags(0), [('Value', csName, MemberDefFlags.Array)]) \
    for (csName, fName) in primitiveTypes.iteritems()] + \
    [('ConstantHandleArray', None, RecordDefFlags(0), [('Value', 'Handle', MemberDefFlags.RecordRef | MemberDefFlags.List)])]

# Combines constant value and array schema record definitions
__constantRecordSchema = sorted(__constantValueRecordSchema + __constantArrayRecordSchema, key = lambda x: x[0])

#--- Common tuple definitions -----------------------------------------------------------------------------
EnumConstantValue = ('ConstantByteValue', 'ConstantSByteValue', 'ConstantInt16Value', 'ConstantUInt16Value', 'ConstantInt32Value', 'ConstantUInt32Value', 'ConstantInt64Value', 'ConstantUInt64Value')
TypeDefOrRef = ('TypeDefinition', 'TypeReference')
TypeDefOrRefOrSpec = TypeDefOrRef + ('TypeSpecification',)
TypeSig = ('TypeInstantiationSignature', 'SZArraySignature', 'ArraySignature', 'PointerSignature', 'ByReferenceSignature', 'TypeVariableSignature', 'MethodTypeVariableSignature')
TypeDefOrRefOrSpecOrConstant = TypeDefOrRefOrSpec + tuple(ct[0] for ct in __constantRecordSchema)
MethodDefOrRef = ('QualifiedMethod', 'MemberReference')

#--- Metadata records -------------------------------------------------------------------------------------
# The record schema is defined as a list of tuples, one for each record type.
# Record tuple format: (name, base type (not currently used), flags, [members])
# Member tuple format: (name, type, flags)
# These are largely based on the definitions in ECMA335.

__recordSchema = [
    ('TypeDefinition', None, RecordDefFlags.CustomCompare, [
        ('Flags', 'TypeAttributes', MemberDefFlags(0)),
        ('BaseType', TypeDefOrRefOrSpec, MemberDefFlags.RecordRef),
        ('NamespaceDefinition', 'NamespaceDefinition', MemberDefFlags.RecordRef | MemberDefFlags.Compare),
        ('Name', 'ConstantStringValue', MemberDefFlags.RecordRef | MemberDefFlags.Child | MemberDefFlags.Compare),
        ('Size', 'uint', MemberDefFlags(0)),
        ('PackingSize', 'ushort', MemberDefFlags(0)),
        ('EnclosingType', 'TypeDefinition', MemberDefFlags.RecordRef | MemberDefFlags.Compare),
        ('NestedTypes', 'TypeDefinition', MemberDefFlags.List | MemberDefFlags.RecordRef | MemberDefFlags.Child),
        ('Methods', 'Method', MemberDefFlags.List | MemberDefFlags.RecordRef | MemberDefFlags.Child),
        ('Fields', 'Field', MemberDefFlags.Map | MemberDefFlags.RecordRef | MemberDefFlags.Child),
        ('Properties', 'Property', MemberDefFlags.Map | MemberDefFlags.RecordRef | MemberDefFlags.Child),
        ('Events', 'Event', MemberDefFlags.Map | MemberDefFlags.RecordRef | MemberDefFlags.Child),
        ('GenericParameters', 'GenericParameter', MemberDefFlags.List | MemberDefFlags.RecordRef | MemberDefFlags.Child),
        ('Interfaces', TypeDefOrRefOrSpec, MemberDefFlags.List | MemberDefFlags.RecordRef),
        ('MethodImpls', 'MethodImpl', MemberDefFlags.List | MemberDefFlags.RecordRef | MemberDefFlags.Child),
        ('CustomAttributes', 'CustomAttribute', MemberDefFlags.List | MemberDefFlags.RecordRef | MemberDefFlags.Child),
        ]),
    ('TypeReference', None, RecordDefFlags(0), [
        ('ParentNamespaceOrType', ('NamespaceReference', 'TypeReference'), MemberDefFlags.RecordRef),
        ('TypeName', 'ConstantStringValue', MemberDefFlags.RecordRef | MemberDefFlags.Child | MemberDefFlags.Name),
        ('CustomAttributes', 'CustomAttribute', MemberDefFlags.List | MemberDefFlags.RecordRef | MemberDefFlags.Child),
        ]),
    ('TypeSpecification', None, RecordDefFlags(0), [
        ('Signature', TypeDefOrRef + TypeSig, MemberDefFlags.RecordRef | MemberDefFlags.Child),
        ('CustomAttributes', 'CustomAttribute', MemberDefFlags.List | MemberDefFlags.RecordRef | MemberDefFlags.Child),
        ]),
    ('ScopeDefinition', None, RecordDefFlags.CustomCompare, [
        ('Flags', 'AssemblyFlags', MemberDefFlags.Compare),
        ('Name', 'ConstantStringValue', MemberDefFlags.RecordRef | MemberDefFlags.Child | MemberDefFlags.Compare),
        ('HashAlgorithm', 'AssemblyHashAlgorithm', MemberDefFlags.Compare),
        ('MajorVersion', 'ushort', MemberDefFlags.Compare),
        ('MinorVersion', 'ushort', MemberDefFlags.Compare),
        ('BuildNumber', 'ushort', MemberDefFlags.Compare),
        ('RevisionNumber', 'ushort', MemberDefFlags.Compare),
        ('PublicKey', 'byte', MemberDefFlags.Array | MemberDefFlags.Compare),
        ('Culture', 'ConstantStringValue', MemberDefFlags.RecordRef | MemberDefFlags.Child | MemberDefFlags.Compare),
        ('RootNamespaceDefinition', 'NamespaceDefinition', MemberDefFlags.RecordRef | MemberDefFlags.Child),
        ('CustomAttributes', 'CustomAttribute', MemberDefFlags.List | MemberDefFlags.RecordRef | MemberDefFlags.Child),
        ]),
    ('ScopeReference', None, RecordDefFlags(0), [
        ('Flags', 'AssemblyFlags', MemberDefFlags(0)),
        ('Name', 'ConstantStringValue', MemberDefFlags.RecordRef | MemberDefFlags.Child),
        ('MajorVersion', 'ushort', MemberDefFlags(0)),
        ('MinorVersion', 'ushort', MemberDefFlags(0)),
        ('BuildNumber', 'ushort', MemberDefFlags(0)),
        ('RevisionNumber', 'ushort', MemberDefFlags(0)),
        ('PublicKeyOrToken', 'byte', MemberDefFlags.Array),
        ('Culture', 'ConstantStringValue', MemberDefFlags.RecordRef | MemberDefFlags.Child),
        ('CustomAttributes', 'CustomAttribute', MemberDefFlags.List | MemberDefFlags.RecordRef | MemberDefFlags.Child),
        ]),
    ('NamespaceDefinition', None, RecordDefFlags.CustomCompare, [
        ('ParentScopeOrNamespace', ('NamespaceDefinition', 'ScopeDefinition'), MemberDefFlags.RecordRef | MemberDefFlags.Compare),
        ('Name', 'ConstantStringValue', MemberDefFlags.RecordRef | MemberDefFlags.Child | MemberDefFlags.Compare),
        ('TypeDefinitions', 'TypeDefinition', MemberDefFlags.Map | MemberDefFlags.RecordRef | MemberDefFlags.Child),
        ('TypeForwarders', 'TypeForwarder', MemberDefFlags.Map | MemberDefFlags.RecordRef | MemberDefFlags.Child),
        ('NamespaceDefinitions', 'NamespaceDefinition', MemberDefFlags.Map | MemberDefFlags.RecordRef | MemberDefFlags.Child),
        ]),
    ('NamespaceReference', None, RecordDefFlags(0), [
        ('ParentScopeOrNamespace', ('NamespaceReference', 'ScopeReference'), MemberDefFlags.RecordRef),
        ('Name', 'ConstantStringValue', MemberDefFlags.RecordRef | MemberDefFlags.Child),
        ]),
    ('Method', None, RecordDefFlags(0), [
        ('Flags', 'MethodAttributes', MemberDefFlags(0)),
        ('ImplFlags', 'MethodImplAttributes', MemberDefFlags(0)),
        ('Name', 'ConstantStringValue', MemberDefFlags.RecordRef | MemberDefFlags.Child),
        ('Signature', 'MethodSignature', MemberDefFlags.RecordRef | MemberDefFlags.Child ),
        ('Parameters', 'Parameter', MemberDefFlags.List | MemberDefFlags.RecordRef | MemberDefFlags.Child | MemberDefFlags.EnumerateForHashCode),
        ('GenericParameters', 'GenericParameter', MemberDefFlags.List | MemberDefFlags.RecordRef | MemberDefFlags.Child | MemberDefFlags.EnumerateForHashCode),
        ('CustomAttributes', 'CustomAttribute', MemberDefFlags.List | MemberDefFlags.RecordRef | MemberDefFlags.Child),
        ]),
    ('QualifiedMethod', None, RecordDefFlags(0), [
        ('Method', 'Method', MemberDefFlags.RecordRef),
        ('EnclosingType', 'TypeDefinition', MemberDefFlags.RecordRef),
    ]),
    ('MethodInstantiation', None, RecordDefFlags(0), [
        ('Method', MethodDefOrRef, MemberDefFlags.RecordRef),
        ('GenericTypeArguments', TypeDefOrRefOrSpec, MemberDefFlags.List | MemberDefFlags.RecordRef),
        ('CustomAttributes', 'CustomAttribute', MemberDefFlags.List | MemberDefFlags.RecordRef | MemberDefFlags.Child),
        ]),
    ('MemberReference', None, RecordDefFlags(0), [
        ('Parent', TypeDefOrRefOrSpec, MemberDefFlags.RecordRef),
        ('Name', 'ConstantStringValue', MemberDefFlags.RecordRef | MemberDefFlags.Child),
        ('Signature', ('MethodSignature', 'FieldSignature'), MemberDefFlags.RecordRef | MemberDefFlags.Child),
        ('CustomAttributes', 'CustomAttribute', MemberDefFlags.List | MemberDefFlags.RecordRef | MemberDefFlags.Child),
        ]),
    ('Field', None, RecordDefFlags(0), [
        ('Flags', 'FieldAttributes', MemberDefFlags(0)),
        ('Name', 'ConstantStringValue', MemberDefFlags.RecordRef | MemberDefFlags.Child),
        ('Signature', 'FieldSignature', MemberDefFlags.RecordRef | MemberDefFlags.Child),
        ('DefaultValue', TypeDefOrRefOrSpecOrConstant, MemberDefFlags.RecordRef),
        ('Offset', 'uint', MemberDefFlags(0)),
        ('CustomAttributes', 'CustomAttribute', MemberDefFlags.List | MemberDefFlags.RecordRef | MemberDefFlags.Child | MemberDefFlags.EnumerateForHashCode),
        ]),
    ('Property', None, RecordDefFlags(0), [
        ('Flags', 'PropertyAttributes', MemberDefFlags(0)),
        ('Name', 'ConstantStringValue', MemberDefFlags.RecordRef | MemberDefFlags.Child),
        ('Signature', 'PropertySignature', MemberDefFlags.RecordRef | MemberDefFlags.Child),
        ('MethodSemantics', 'MethodSemantics', MemberDefFlags.List | MemberDefFlags.RecordRef | MemberDefFlags.Child | MemberDefFlags.EnumerateForHashCode),
        ('DefaultValue', TypeDefOrRefOrSpecOrConstant, MemberDefFlags.RecordRef),
        ('CustomAttributes', 'CustomAttribute', MemberDefFlags.List | MemberDefFlags.RecordRef | MemberDefFlags.Child | MemberDefFlags.EnumerateForHashCode),
        ]),
    ('Event', None, RecordDefFlags(0), [
        ('Flags', 'EventAttributes', MemberDefFlags(0)),
        ('Name', 'ConstantStringValue', MemberDefFlags.RecordRef | MemberDefFlags.Child),
        ('Type', TypeDefOrRefOrSpec, MemberDefFlags.RecordRef),
        ('MethodSemantics', 'MethodSemantics', MemberDefFlags.List | MemberDefFlags.RecordRef | MemberDefFlags.Child | MemberDefFlags.EnumerateForHashCode),
        ('CustomAttributes', 'CustomAttribute', MemberDefFlags.List | MemberDefFlags.RecordRef | MemberDefFlags.Child | MemberDefFlags.EnumerateForHashCode),
        ]),
    ('CustomAttribute', None, RecordDefFlags.ReentrantEquals, [
        ('Constructor', MethodDefOrRef, MemberDefFlags.RecordRef),
        ('FixedArguments', 'FixedArgument', MemberDefFlags.List | MemberDefFlags.RecordRef | MemberDefFlags.Child | MemberDefFlags.EnumerateForHashCode),
        ('NamedArguments', 'NamedArgument', MemberDefFlags.List | MemberDefFlags.RecordRef | MemberDefFlags.Child | MemberDefFlags.EnumerateForHashCode),
        ]),
    ('FixedArgument', None, RecordDefFlags(0), [
        ('Flags', 'FixedArgumentAttributes', MemberDefFlags(0)),
        ('Type', TypeDefOrRefOrSpec, MemberDefFlags.RecordRef),
        ('Value', TypeDefOrRefOrSpecOrConstant, MemberDefFlags.RecordRef),
        ]),
    ('NamedArgument', None, RecordDefFlags(0), [
        ('Flags', 'NamedArgumentMemberKind', MemberDefFlags(0)),
        ('Name', 'ConstantStringValue', MemberDefFlags.RecordRef | MemberDefFlags.Child),
        ('Value', 'FixedArgument', MemberDefFlags.RecordRef | MemberDefFlags.Child),
        ]),
    ('ConstantBoxedEnumValue', None, RecordDefFlags(0), [
        ('Value', EnumConstantValue, MemberDefFlags.RecordRef | MemberDefFlags.Child),
        ('Type', TypeDefOrRef, MemberDefFlags.RecordRef)
        ]),
    ('GenericParameter', None, RecordDefFlags(0), [
        ('Number', 'ushort', MemberDefFlags(0)),
        ('Flags', 'GenericParameterAttributes', MemberDefFlags(0)),
        ('Kind', 'GenericParameterKind', MemberDefFlags(0)),
        ('Name', 'ConstantStringValue', MemberDefFlags.RecordRef | MemberDefFlags.Child),
        ('Constraints', TypeDefOrRefOrSpec, MemberDefFlags.List | MemberDefFlags.RecordRef | MemberDefFlags.EnumerateForHashCode),
        ('CustomAttributes', 'CustomAttribute', MemberDefFlags.List | MemberDefFlags.RecordRef | MemberDefFlags.Child),
        ]),
    ('MethodImpl', None, RecordDefFlags(0), [
        ('MethodBody', MethodDefOrRef, MemberDefFlags.RecordRef),
        ('MethodDeclaration', MethodDefOrRef, MemberDefFlags.RecordRef),
        ]),
    ('Parameter', None, RecordDefFlags(0), [
        ('Flags', 'ParameterAttributes', MemberDefFlags(0)),
        ('Sequence', 'ushort', MemberDefFlags(0)),
        ('Name', 'ConstantStringValue', MemberDefFlags.RecordRef | MemberDefFlags.Child),
        ('DefaultValue', TypeDefOrRefOrSpecOrConstant, MemberDefFlags.RecordRef),
        ('CustomAttributes', 'CustomAttribute', MemberDefFlags.List | MemberDefFlags.RecordRef | MemberDefFlags.Child),
        ]),
    ('MethodSemantics', None, RecordDefFlags(0), [
        ('Attributes', 'MethodSemanticsAttributes', MemberDefFlags(0)),
        ('Method', 'Method', MemberDefFlags.RecordRef),
        ]),
    ('TypeInstantiationSignature', None, RecordDefFlags(0), [
        ('GenericType', TypeDefOrRefOrSpec, MemberDefFlags.RecordRef),
        ('GenericTypeArguments', TypeDefOrRefOrSpec, MemberDefFlags.List | MemberDefFlags.RecordRef),
        ]),
    ('SZArraySignature', None, RecordDefFlags(0), [
        ('ElementType', TypeDefOrRefOrSpec, MemberDefFlags.RecordRef),
        ]),
    ('ArraySignature', None, RecordDefFlags(0), [
        ('ElementType', TypeDefOrRefOrSpec, MemberDefFlags.RecordRef),
        ('Rank', 'int', MemberDefFlags(0)),
        ('Sizes', 'int', MemberDefFlags.Array),
        ('LowerBounds', 'int', MemberDefFlags.Array),
        ]),
    ('ByReferenceSignature', None, RecordDefFlags(0), [
        ('Type', TypeDefOrRefOrSpec, MemberDefFlags.RecordRef),
        ]),
    ('PointerSignature', None, RecordDefFlags(0), [
        ('Type', TypeDefOrRefOrSpec, MemberDefFlags.RecordRef),
        ]),
    ('TypeVariableSignature', None, RecordDefFlags(0), [
        ('Number', 'int', MemberDefFlags(0)),
        ]),
    ('MethodTypeVariableSignature', None, RecordDefFlags(0), [
        ('Number', 'int', MemberDefFlags(0)),
        ]),
    ('FieldSignature', None, RecordDefFlags(0), [
        ('Type', TypeDefOrRefOrSpec, MemberDefFlags.RecordRef),
        ('CustomModifiers', 'CustomModifier', MemberDefFlags.List | MemberDefFlags.RecordRef),
        ]),
    ('PropertySignature', None, RecordDefFlags(0), [
        ('CallingConvention', 'CallingConventions', MemberDefFlags(0)),
        ('CustomModifiers', 'CustomModifier', MemberDefFlags.List | MemberDefFlags.RecordRef),
        ('Type', TypeDefOrRefOrSpec, MemberDefFlags.RecordRef),
        ('Parameters', 'ParameterTypeSignature', MemberDefFlags.List | MemberDefFlags.RecordRef | MemberDefFlags.EnumerateForHashCode),
        ]),
    ('MethodSignature', None, RecordDefFlags(0), [
        ('CallingConvention', 'CallingConventions', MemberDefFlags(0)),
        ('GenericParameterCount', 'int', MemberDefFlags(0)),
        ('ReturnType', 'ReturnTypeSignature', MemberDefFlags.RecordRef),
        ('Parameters', 'ParameterTypeSignature', MemberDefFlags.List | MemberDefFlags.RecordRef | MemberDefFlags.EnumerateForHashCode),
        ('VarArgParameters', 'ParameterTypeSignature', MemberDefFlags.List | MemberDefFlags.RecordRef | MemberDefFlags.EnumerateForHashCode),
        ]),
    ('ReturnTypeSignature', None, RecordDefFlags(0), [
        ('CustomModifiers', 'CustomModifier', MemberDefFlags.List | MemberDefFlags.RecordRef),
        ('Type', TypeDefOrRefOrSpec, MemberDefFlags.RecordRef),
        ]),
    ('ParameterTypeSignature', None, RecordDefFlags(0), [
        ('CustomModifiers', 'CustomModifier', MemberDefFlags.List | MemberDefFlags.RecordRef),
        ('Type', TypeDefOrRefOrSpec, MemberDefFlags.RecordRef),
        ]),
    ('TypeForwarder', None, RecordDefFlags(0), [
        ('Scope', 'ScopeReference', MemberDefFlags.RecordRef),
        ('Name', 'ConstantStringValue', MemberDefFlags.RecordRef | MemberDefFlags.Child | MemberDefFlags.Name),
        ('NestedTypes', 'TypeForwarder', MemberDefFlags.List | MemberDefFlags.RecordRef | MemberDefFlags.Child),
        ('CustomAttributes', 'CustomAttribute', MemberDefFlags.List | MemberDefFlags.RecordRef | MemberDefFlags.Child),
        ]),
    ('CustomModifier', None, RecordDefFlags(0), [
        ('IsOptional', 'bool', MemberDefFlags(0)),
        ('Type', TypeDefOrRefOrSpec, MemberDefFlags.RecordRef),
        ]),
    # ConstantXXXValue provided in __constantRecordSchema and appened to end of this list.
] + __constantRecordSchema

# Ordered dictionary of schema records (as defined above)
recordSchema = odict([(rName, rMembers) for rName, rBase, rFlags, rMembers in __recordSchema])

# Ordered dictionary of RecordDef instances
recordDefs = odict([(rName, RecordDef(rName, rBase, rFlags,
                                        [ { 'name': mName, 'typeName': mType, 'flags': mFlags } for mName,mType,mFlags in rMembers])) for rName, rBase, rFlags, rMembers in __recordSchema])

# Used to enable some custom actions for string records.
stringRecordTypes = set(['ConstantStringValue'])

# Contains a list of records with corresponding Handle types (currently all of them).
handleSchema = [n for n in recordSchema.iterkeys()]

# Print out some diagnostic info if script is directly invoked.
if __name__ == '__main__':
    print '\nRecordFlags flag values:'
    for n,v in RecordDefFlags.iterflags():
        print '    {} : 0x{:x}'.format(n,v)

    print '\nRecordFlags mask values:'
    for n,v in RecordDefFlags.itermasks():
        print '    {} : 0x{:x}'.format(n,v)

    print '\nRecordMemberFlags flag values:'
    for n,v in MemberDefFlags.iterflags():
        print '    {} : 0x{:x}'.format(n,v)

    print '\nRecordMemberFlags mask values:'
    for n,v in MemberDefFlags.itermasks():
        print '    {} : 0x{:x}'.format(n,v)

    print '\nRecords:'
    for k in recordSchema.iterkeys():
        print '    ' + k

    print '\nHandles:'
    for k in handleSchema:
        print '    ' + k


text: create sequence film_film_id_seq;

redpajama_set_name: RedPajamaGithub


text:
<?php include 'header.php';?>

Edit thành phố

                                <?php
						if (isset($error) && !is_array($error)) {
							echo '

							  Error:
							  '.html_entity_decode($error).'

';
						}
						if (isset($error) && is_array($error)) {
							for ($i = 0; $i < count($error); $i++) {

								echo '

							  Error:
							  '.$error[$i]['message'].'

';
							}
						}
						//success
						if (isset($message)) {
							echo '

							  Message:
							  '.$message.'

';
						}
						?>

                                    <form id="demo-form2" data-parsley-validate="" class="form-horizontal form-label-left" novalidate="" method="post" action="<?php echo _ADMIN_URL_;?>edit/<?php echo $id.'/'.$table;?>">

                                            Tên thành phố *

                                                <input type="text" id="thanhpho" required="required" name="name" class="form-control col-md-7 col-xs-12" data-parsley-id="3358"
                                                <?php if(isset($value))echo' value="'.$value.'"';?>>

                                                <a href="<?php echo _ADMIN_URL_;?>list/thanhpho" class="btn btn-primary">Cancel
                                                <button type="submit" class="btn btn-success">Update</button>

                                    </form>

<?php include 'footer.php';?>


text:
{% extends "base.html" %}
{% load i18n cms_tags menu_tags placeholder_tags get_placeholder_tag %}
{% block content %}
{% get_placeholder article.top as top %}
{% get_placeholder article.bottom as bottom %}
{% get_placeholder article.meta as meta %}
{% get_placeholder article.media as media %}

{% if top %}

        {{ top }}

{% endif %}

{{ article.title }}

        {% if meta %}

            {{ meta }}

        {% endif %}
        {{ article.body|safe|linebreaks }}
        {% if media %}

            {{ media }}

        {% endif %}

        {% placeholder article.aside or %}
        {% with article.index.article_set.all|slice:":10" as articles and article.index.page as page %}
        {% include "articles/_latest.html" %}
        {% endwith %}
        {% endplaceholder %}

{% if bottom %}

        {{ bottom }}

{% endif %}

{% endblock %}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
J. B. A. P. M. de Lamarck, Encycl. 2:531. 1788

#### Original name
null

### Remarks
null


text:
package mist

import "strings"

// XError is an extended error interface.
type XError interface {
	error                           // Error() returns an error string
	Details() string                // returns details in a string (e.g. an error trace)
	AddVar(n string, v interface{}) // attaches a variable to the extended error
	Vars() []struct {               // returns the attached variables
		Name  string
		Value interface{}
	}
}

// Mistake stores extended error information.
type mistake struct {
	error   string
	details string
	vars    []struct {
		Name  string
		Value interface{}
	}
}

// New returns an extended error using the given text strings.
// First string is error message, others are details.
func New(err string, dets ...string) error {
	if err == "" {
		return nil
	}
	if len(dets) == 0 {
		return &mistake{error: err}
	}
	return &mistake{error: err, details: strings.Join(dets, "")}
}

// AddVar adds a Variable to the extended error.
func (m *mistake) AddVar(n string, v interface{}) {
	m.vars = append(
		m.vars,
		struct {
			Name  string
			Value interface{}
		}{
			Name: n,
			Value: v,
		},
	)
}

// Error returns the error string,
// thus implementing the built-in error interface.
func (m *mistake) Error() string {
	return m.error
}

// Details returns the details string.
func (m *mistake) Details() string {
	return m.details
}

// Vars returns the Variables attached to the extended error.
func (m *mistake) Vars() []struct {
	Name  string
	Value interface{}
} {
	return m.vars
}

// ----------

// Prepend adds a prefix and ":" to the details of the extended error,
// and returns true.
func Prepend(pre string, errp *error) bool {
	if *errp == nil { // no error occured
		return false
	}
	xerr, ok := (*errp).(XError)
	if ok {
		*errp = XError(&mistake{
			error:   xerr.Error(),
			details: pre + ":" + xerr.Details(),
			vars:    xerr.Vars(),
		})
	} else {
		*errp = XError(&mistake{
			error:   (*errp).Error(),
			details: pre,
		})
	}
	return true
}

// Append adds ";" and a suffix to the details of the extended error,
// and returns true.
func Append(suf string, errp *error) bool {
	if *errp == nil { // no error occured
		return false
	}
	xerr, ok := (*errp).(XError)
	if ok {
		*errp = XError(&mistake{
			error:   xerr.Error(),
			details: xerr.Details() + ";" + suf,
			vars:    xerr.Vars(),
		})
	} else {
		*errp = XError(&mistake{
			error:   (*errp).Error(),
			details: suf,
		})
	}
	return true
}


text:
#include <aws/devicefarm/model/Project.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace DeviceFarm
{
namespace Model
{

Project::Project() :
    m_arnHasBeenSet(false),
    m_nameHasBeenSet(false),
    m_defaultJobTimeoutMinutes(0),
    m_defaultJobTimeoutMinutesHasBeenSet(false),
    m_createdHasBeenSet(false),
    m_vpcConfigHasBeenSet(false)
{
}

Project::Project(JsonView jsonValue) :
    m_arnHasBeenSet(false),
    m_nameHasBeenSet(false),
    m_defaultJobTimeoutMinutes(0),
    m_defaultJobTimeoutMinutesHasBeenSet(false),
    m_createdHasBeenSet(false),
    m_vpcConfigHasBeenSet(false)
{
  *this = jsonValue;
}

Project& Project::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("arn"))
  {
    m_arn = jsonValue.GetString("arn");

    m_arnHasBeenSet = true;
  }

  if(jsonValue.ValueExists("name"))
  {
    m_name = jsonValue.GetString("name");

    m_nameHasBeenSet = true;
  }

  if(jsonValue.ValueExists("defaultJobTimeoutMinutes"))
  {
    m_defaultJobTimeoutMinutes = jsonValue.GetInteger("defaultJobTimeoutMinutes");

    m_defaultJobTimeoutMinutesHasBeenSet = true;
  }

  if(jsonValue.ValueExists("created"))
  {
    m_created = jsonValue.GetDouble("created");

    m_createdHasBeenSet = true;
  }

  if(jsonValue.ValueExists("vpcConfig"))
  {
    m_vpcConfig = jsonValue.GetObject("vpcConfig");

    m_vpcConfigHasBeenSet = true;
  }

  return *this;
}

JsonValue Project::Jsonize() const
{
  JsonValue payload;

  if(m_arnHasBeenSet)
  {
   payload.WithString("arn", m_arn);

  }

  if(m_nameHasBeenSet)
  {
   payload.WithString("name", m_name);

  }

  if(m_defaultJobTimeoutMinutesHasBeenSet)
  {
   payload.WithInteger("defaultJobTimeoutMinutes", m_defaultJobTimeoutMinutes);

  }

  if(m_createdHasBeenSet)
  {
   payload.WithDouble("created", m_created.SecondsWithMSPrecision());
  }

  if(m_vpcConfigHasBeenSet)
  {
   payload.WithObject("vpcConfig", m_vpcConfig.Jsonize());

  }

  return payload;
}

} // namespace Model
} // namespace DeviceFarm
} // namespace Aws


text:
\chapter{Error, Warning, and Informational Messages}\label{ch:errors}

Several error, warning, and informational messages will be printed by
\aprepro{} if certain conditions are encountered during the parsing of an
input file. The messages are of the form:

\begin{apinp}
Aprepro:  Type:  Message  (file,  line  line\#)
\end{apinp}

Where \cmd{Type} is \cmd{ERROR} for an error message, \cmd{WARN} for a
warning message, or \cmd{INFO} for an informational message; \cmd{Message}
is an explanation of the problem, \cmd{file} is the filename being processed
at the time of the message, and \cmd{line\#} is the number of the line
within that file. Error messages are always output, Warning messages
are output by default and can be turned off by using the \cmd{-W} or
\cmd{--warning} command option, and Informational messages are turned off by
default and can be turned on by using the \cmd{-M} or \cmd{--message} command
option. (See Chapter~ref{ch:execution}.)

\section{Error Messages}

\begin{description}
\item[Aprepro:  ERROR:  parse  error  (file,  line  line\#)]
An unrecognized or ill-formed expression has been entered. Parsing of
the file continues following this expression.

\item[Aprepro: ERROR: Can't open 'file': No such file or directory] The file specified
in the include command cannot be found or does not exist. Aprepro will terminate
processing following this error message.

\item[Aprepro: ERROR: Can't open 'file': Permission denied] The file specified in the
include or output command could not be opened due to insufficient permission.
Aprepro will terminate processing following this error message.

\item[Aprepro: ERROR: Improperly Nested ifdef/ifndef statements (file, line line\#)]
An invalid ifdef/ifndef block has been detected. Typically this is caused by an
extra endif or else statement.

\item[Aprepro:  ERROR:    Zero  divisor  (file,  line  line\#)]    An expression tried
to divide by zero. The expression is given the value of the dividend and parsing continues.

\item[Aprepro: ERROR: Invalid units system type. Valid types are: 'si', 'cgs', 'cgs-ev', 'shock', 'swap', 'ft-lbf-s', 'ft-lbm-s', 'in-lbf-s']
The units system specified in the command could not be found. This
is most likely due to a misspelling of the units system name.

\item[Aprepro: ERROR: function (file, line line\#) DOMAIN error: Argument out of domain]
The arithmetic function function has been passed an invalid
argument. For example, the above error would be printed for each of
the expressions:
\begin{apinp}
\{sqrt(-1.0)\}  \{log(0.0)\}  \{asin(1.1)\}
\end{apinp}

since the arguments are out of the valid domain for the function. The
value returned by the function following an error is
system-dependent. See the function's man page on your system for more
information.

\end{description}

\section{Warning Messages}

\begin{description}
\item[Aprepro:  WARN:  Undefined  variable  'variable'  (file,  line  line\#)]
A variable is used in an expression before it has been defined. The variable is
set equal to zero or the null string (\texttt{"}\texttt{"}) and parsing continues.

\item[Aprepro:  WARN:  Variable  'variable'  redefined  (file,  line  line\#)]
A previously defined variable is being set equal to a new value.

\item[Aprepro: (IMMUTABLE) Variable 'variable' is immutable and cannot be modified (file, line line\#)]
The value of a variable that was created as an immutable variable was
modified. No value will be returned by the expression. See page~\pageref{immutable} and
page~\ref{immutable_block} for a description of immutable variables.
\end{description}

\section{Informational Messages}

\begin{description}
\item[Aprepro: INFO: Included File: 'filename' (file, line line\#)] The file filename
is being included at line line\# of file file. This message will also be printed
during the execution of a loop block since temporary files are used to implement
the looping function, and during the execution of the units conversion and material
database access routines.
\end{description}


text:
Creating a local apt server
===========================

- `What are some benefits of doing it this way?`_
- `Pick a server`_
- `Configure a throw away build server`_
- `Configure the local APT server`_
- `Make your hosts aware`_
- `Use your shiny new package`_

Certain roles such as Ruby and Golang offer an ability to use a backported
version of the package so it's more up to date. The backports are built off of
Debian Jessie without having to actually use the testing apt source.

What are some benefits of doing it this way?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

A lot of other roles will compile from source  but that's time demanding and
error prone. A backported version of Ruby 2.1.x will apt install in about 5
seconds once you setup your local APT server once.

    Compile it once into a proper package and use it as many times as you want.

It also future proofs your role because you wouldn't have to change anything
once Jessie is officially released. From the role's point of view it's just
installing an apt package using Ansible's ``apt`` module. It does not care where
the apt server is located.

Pick a server
^^^^^^^^^^^^^

The first step is to decide where you want this server. It doesn't need to be
literally local to your workstation. It's local in the context of it not being
an official APT server to the world.

Popular options could be your Ansible controller inside of a container or a
micro-size instance on the cloud depending on your requirements for availability.

Configure a throw away build server
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

You could use your apt server but it's best to use a temporary host. I would
just spin up a container.

In this example we're going to build Ruby 2.1.x. You will have to do this if
you plan to use GitLab so it's a good idea to learn!

::

  # inventory/hosts

  [debops_ruby]
  yourbuildserver

::

  # inventory/host_vars/yourbuildserver.yml

  ruby_version: 'backport'

That tells the `Ruby role <https://github.com/debops/ansible-ruby>`_ to use
the `Backporter role <https://github.com/debops/ansible-backporter>`_ as a
dependency and that will kick off the entire build process for you.

**Then run:**

``debops -l yourbuildserver``

Expect it to take 5 to 15 minutes depending on how fast your server is. You only
need to do this once.

Where are the packages
``````````````````````

Good question, they have been transferred to your Ansible controller in the
``secret/reprepro/includedeb/wheezy-backports/`` directory.

At this point you can delete your build server.

Configure the local APT server
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Next up, we need to tell our server that it is an APT server.

::

  # inventory/host_vars/youraptserver.yml

  apt: 'youraptserver.{{ ansible_domain }}'

You must use your apt server's fully qualified domain name. Run ``hostname -f`` on
the server to check its fully qualified domain name.

**We're just about done**, now you need to transfer the packages to your apt server:

``debops -l youraptserver -t apt``

Make your hosts aware
^^^^^^^^^^^^^^^^^^^^^

The last step is to make your hosts aware of the server.

Below I'm just assuming you want to make it aware to all of your containers and
you have your containers inside of a ``[containers]`` group.

::

    # inventory/group_vars/containers.yml

    apt: 'youraptserver.{{ ansible_domain }}'

**Then run:**

``debops -l containers``

Use your shiny new package
^^^^^^^^^^^^^^^^^^^^^^^^^^

Well, this part is easy. Just use the Ruby role on any host that is aware of
your local apt server and it will install Ruby 2.1.x in about 5 seconds.

You do not need to set ``ruby_version: 'backport'`` on the hosts themselves. It
will just use the default setting which is the apt package and now since your
local apt server is setup and your host is aware, it will use the new backported
version.


text:
from cx_Freeze import setup, Executable
import os
from os.path import dirname, join
import subprocess
import sys

from app.util import autoversioning
from app.util.process_utils import is_windows

buildOptions = {
    'excludes': [],
    'append_script_to_exe': False,
    'build_exe': 'dist',
    'compressed': True,
    'copy_dependent_files': True,
    'create_shared_zip': True,
    'include_in_shared_zip': True,
    'include_files': [
        ('bin/git_askpass.sh', 'bin/git_askpass.sh'),
        ('bin/git_ssh.sh', 'bin/git_ssh.sh'),
        ('conf/default_clusterrunner.conf', 'conf/default_clusterrunner.conf'),
    ],
    'optimize': 1,  # This should not be set to 2 because that removes docstrings needed for command line help.
}

base = 'Console'

executable_name = 'clusterrunner.exe' if is_windows() else 'clusterrunner'
executables = [
    Executable('main.py', base=base, targetName=executable_name)
]

if sys.platform.startswith('linux'):
    # Fixes compatibility between rhel and ubuntu
    bin_includes = ['/usr/lib64/libssl.so.10', '/usr/lib64/libcrypto.so.10']
    file_exists = [os.path.isfile(filename) for filename in bin_includes]

    if all(file_exists):
        buildOptions['bin_includes'] = bin_includes

version = autoversioning.get_version()
autoversioning.write_package_version_file(version)

setup(name='ClusterRunner',
      version=version,
      description='',
      options=dict(build_exe=buildOptions),
      executables=executables)

autoversioning.restore_original_package_version_file()

if sys.platform == 'darwin':
    # Fix a cx_freeze issue on mac.
    # (See similar fix at https://bitbucket.org/iep-project/iep/commits/1e845c0f35)
    abs_python_path = None
    clusterrunner_path = join(dirname(__file__), 'dist', executable_name)

    # Get the Python reference in clusterrunner
    otool_proc = subprocess.Popen(('otool', '-L', clusterrunner_path), stdout=subprocess.PIPE)
    clusterrunner_libs = otool_proc.stdout.readlines()
    for lib in clusterrunner_libs[1:]:
        lib = lib.decode().strip()
        lib_filename, _ = lib.split(maxsplit=1)
        if lib_filename.endswith('/Python'):
            abs_python_path = lib_filename

    # Replace the absolute path reference in clusterrunner with a relative path
    if abs_python_path:
        rel_python_path = '@executable_path/Python'
        print('Replacing reference: "{}" -> "{}"'.format(abs_python_path, rel_python_path))
        subproc_args = ['install_name_tool', '-change', abs_python_path, rel_python_path, clusterrunner_path]
        subprocess.Popen(subproc_args)


text:
#include "stdafx.h"
#include "sample3.h"

#include "MainFrm.h"
#include "sample3Doc.h"
#include "sample3View.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CSample3App

BEGIN_MESSAGE_MAP(CSample3App, CWinApp)
	//{{AFX_MSG_MAP(CSample3App)
	ON_COMMAND(ID_APP_ABOUT, OnAppAbout)
		// NOTE - the ClassWizard will add and remove mapping macros here.
		//    DO NOT EDIT what you see in these blocks of generated code!
	//}}AFX_MSG_MAP
	// Standard file based document commands
	ON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew)
	ON_COMMAND(ID_FILE_OPEN, CWinApp::OnFileOpen)
	// Standard print setup command
	ON_COMMAND(ID_FILE_PRINT_SETUP, CWinApp::OnFilePrintSetup)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CSample3App construction

CSample3App::CSample3App()
{
	// TODO: add construction code here,
	// Place all significant initialization in InitInstance
}

/////////////////////////////////////////////////////////////////////////////
// The one and only CSample3App object

CSample3App theApp;

/////////////////////////////////////////////////////////////////////////////
// CSample3App initialization

BOOL CSample3App::InitInstance()
{
	AfxEnableControlContainer();

	// Standard initialization
	// If you are not using these features and wish to reduce the size
	//  of your final executable, you should remove from the following
	//  the specific initialization routines you do not need.

#ifdef _AFXDLL
	Enable3dControls();			// Call this when using MFC in a shared DLL
#else
	Enable3dControlsStatic();	// Call this when linking to MFC statically
#endif

	// Change the registry key under which our settings are stored.
	// You should modify this string to be something appropriate
	// such as the name of your company or organization.
	SetRegistryKey(_T("Local AppWizard-Generated Applications"));

	LoadStdProfileSettings();  // Load standard INI file options (including MRU)

	// Register the application's document templates.  Document templates
	//  serve as the connection between documents, frame windows and views.

	CSingleDocTemplate* pDocTemplate;
	pDocTemplate = new CSingleDocTemplate(
		IDR_MAINFRAME,
		RUNTIME_CLASS(CSample3Doc),
		RUNTIME_CLASS(CMainFrame),       // main SDI frame window
		RUNTIME_CLASS(CSample3View));
	AddDocTemplate(pDocTemplate);

	// Parse command line for standard shell commands, DDE, file open
	CCommandLineInfo cmdInfo;
	ParseCommandLine(cmdInfo);

	// Dispatch commands specified on the command line
	if (!ProcessShellCommand(cmdInfo))
		return FALSE;

	// The one and only window has been initialized, so show and update it.
	m_pMainWnd->ShowWindow(SW_SHOW);
	m_pMainWnd->UpdateWindow();

	return TRUE;
}

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
		// No message handlers
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// No message handlers
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

// App command to run the dialog
void CSample3App::OnAppAbout()
{
	CAboutDlg aboutDlg;
	aboutDlg.DoModal();
}

/////////////////////////////////////////////////////////////////////////////
// CSample3App commands

BOOL CSample3App::OnIdle(LONG lCount)
{
	// We ignore lCount for ease of instruction

	// Get the MainFrame....
	CFrameWnd *pFrame = (CFrameWnd *)AfxGetApp()->m_pMainWnd;

	// ...and the current document...
	CSample3Doc *pDoc = ((pFrame) ? (CSample3Doc *)pFrame->GetActiveDocument() : NULL);
	ASSERT(pDoc->IsKindOf(RUNTIME_CLASS(CSample3Doc)));

	// ...and if it exists....
	if (pDoc)
	{
		//... and there is a browser ...
		if (pDoc->browser)
			//... and we should render a frame ...
			if (pDoc->browser->Tick())
				//... then render a frame
				pDoc->UpdateAllViews(NULL);
	}

	return CWinApp::OnIdle(lCount);
}


text:
currentType = '';
function changeValueType( value )
{
	var saveSettingsInput = jQuery("#savesettings");
	var addMoreButton = jQuery("#addmore");
	hideAll();
    if ( value == 'bulksms' ) {
    	showById( "bulksmsFields" );
    } else if ( value == 'clickatell' ) {
    	showById( "clickatellFields" );
    } else if ( value == "smpp_gw"){
    	showById( "smppFields" );
    } else {
	    showById( "genericHTTPFields" );
	}

	if (value === "http") {
		saveSettingsInput.prop("type","button");
		saveSettingsInput.attr("onclick","saveSettings()");
		addMoreButton.show();
	} else {
		saveSettingsInput.prop("type","submit");
		saveSettingsInput.removeAttr("onclick");
		addMoreButton.hide();
	}
	currentType = value;
}

function hideAll()
{
	 hideById( "bulksmsFields" );
	 hideById( "clickatellFields" );
	 hideById( "genericHTTPFields" );
}

function getValidationRulesGateway()
{
	var rules = {};
	if ( currentType == 'bulksms' ) {
		rules = {
			'bulksmsFields input[id=name]' : { 'required' : true },
			'bulksmsFields input[id=username]' : { 'required' : true },
			'bulksmsFields input[id=urlTemplate]' : { 'required' : true },
			'bulksmsFields input[id=password]' : { 'required' : true }
		};
	} else if ( currentType == 'clickatell' ) {
		rules = {
			'clickatellFields input[id=name]' : { 'required' : true },
			'clickatellFields input[id=username]' : { 'required' : true },
			'clickatellFields input[id=password]' : { 'required' : true },
			'clickatellFields input[id=urlTemplate]' : { 'required' : true },
			'clickatellFields input[id=authToken]' : { 'required' : true },
			'clickatellFields input[id=apiId]' : { 'required' : true }
		};
	} else {
		rules = {
			'genericHTTPFields input[id=urlTemplate]' : { 'required' : true }
		};
	}

	return rules;
}

function getValidationRulesUpdateClient()
{
	var rules = {
		"version" : {
			"required" : true,
			"digits" : true
		}
	};
	return rules;
}

function saveGatewayConfig()
{

	if ( currentType == 'bulksms' )
	{
		var username = getFieldValue( 'bulksmsFields input[id=username]' );
		var password = getFieldValue( 'bulksmsFields input[id=password]' );
		var URL = getFieldValue( 'bulksmsFields input[id=urlTemplate]' );
		if ( username == "" || password == "" || URL == "")
		{
			showErrorMessage( i18n_required_data_error );
		}
		else
		{
			lockScreen();
			jQuery.postJSON( "saveBulkSMSConfig.action", {
				gatewayType: getFieldValue( 'gatewayType' ),
				name: getFieldValue( 'bulksmsFields input[id=name]' ),
				username: getFieldValue( 'bulksmsFields input[id=username]' ),
				password: getFieldValue( 'bulksmsFields input[id=password]' ),
				urlTemplate: getFieldValue( 'bulksmsFields input[id=urlTemplate]' ),
				urlTemplateForBatchSms: getFieldValue( 'bulksmsFields input[id=urlTemplateForBatchSms]' ),
				region: getFieldValue( 'bulksmsFields select[id=region]' )
			}, function ( json ) {
				unLockScreen();
				showMessage( json );
			} );
		}
	}
	else if ( currentType == 'clickatell' )
	{
		var username = getFieldValue( 'clickatellFields input[id=username]' );
		var password = getFieldValue( 'clickatellFields input[id=password]' );
		var URL = getFieldValue( 'clickatellFields input[id=urlTemplate]' );
		if ( username == "" || password == "" || URL == "")
		{
			showErrorMessage( i18n_required_data_error );
		}
		else
		{
			lockScreen();
			jQuery.postJSON( "saveClickatellConfig.action", {
				gatewayType: getFieldValue( 'gatewayType' ),
				name: getFieldValue( 'clickatellFields input[id=name]' ),
				username: getFieldValue( 'clickatellFields input[id=username]' ),
				password: getFieldValue( 'clickatellFields input[id=password]' ),
				apiId: getFieldValue( 'clickatellFields input[id=apiId]' ),
				urlTemplate: getFieldValue( 'clickatellFields input[id=urlTemplate]' ),
				authToken: getFieldValue( 'clickatellFields input[id=authToken]' )
			}, function ( json ) {
				unLockScreen();
				showMessage( json );
			} );
		}
	}
	else
	{
		var usernameParameter = getFieldValue( 'genericHTTPFields input[id=usernameParameter]' );
		var passwordParameter = getFieldValue( 'genericHTTPFields input[id=passwordParameter]' );
		var username = getFieldValue( 'genericHTTPFields input[id=username]' );
		var password = getFieldValue( 'genericHTTPFields input[id=password]' );

		var messageParameter = getFieldValue( 'genericHTTPFields input[id=messageParameter]' );
		var recipientParameter = getFieldValue( 'genericHTTPFields input[id=recipientParameter]' );

		var URL = getFieldValue( 'genericHTTPFields input[id=urlTemplate]' );

		if( usernameParameter == "" || passwordParameter == "" || URL == "" ||  username == "" || password == "")
		{
			showErrorMessage( i18n_required_data_error );
		}
		else
		{
			lockScreen();
			jQuery.postJSON( "saveHTTPConfig.action", {
				gatewayType: getFieldValue( 'gatewayType' ),
				name: getFieldValue( 'genericHTTPFields input[id=name]' ),

				usernameParameter: getFieldValue( 'genericHTTPFields input[id=usernameParameter]' ),
				username: getFieldValue( 'genericHTTPFields input[id=username]' ),

				passwordParameter: getFieldValue( 'genericHTTPFields input[id=passwordParameter]' ),
				password: getFieldValue( 'genericHTTPFields input[id=password]' ),

				messageParameter: getFieldValue( 'genericHTTPFields input[id=messageParameter]' ),
				recipientParameter: getFieldValue( 'genericHTTPFields input[id=recipientParameter]' ),

				urlTemplate: getFieldValue( 'genericHTTPFields input[id=urlTemplate]' )
			}, function ( json ) {
				unLockScreen();
				showMessage( json );
			} );
		}
	}
}

function showMessage( json )
{
	if ( json.response == "success" ) {
		showSuccessMessage( i18n_add_update_success );
	} else {
		showErrorMessage( json.message, 7000 );
	}
}

function removeItem( itemId, itemName, confirmation, action, success )
{
    var result = window.confirm( confirmation + "\n\n" + itemName );

    if ( result )
    {
		lockScreen();
    	$.postJSON(
    	    action,
    	    {
    	        "id": itemId
    	    },
    	    function( json )
    	    {
    	    	if ( json.response == "success" )
    	    	{
					jQuery( "tr#tr" + itemId ).remove();

					jQuery( "table.listTable tbody tr" ).removeClass( "listRow listAlternateRow" );
	                jQuery( "table.listTable tbody tr:odd" ).addClass( "listAlternateRow" );
	                jQuery( "table.listTable tbody tr:even" ).addClass( "listRow" );
					jQuery( "table.listTable tbody" ).trigger("update");

					if ( success && typeof( success) == "function" )
					{
						success.call();
					}
					unLockScreen();
					showSuccessMessage( i18n_delete_success );
					refreshIndex( itemId );
    	    	}
    	    	else if ( json.response == "error" )
    	    	{
					unLockScreen();
					showWarningMessage( json.message );
    	    	}
    	    }
    	);
    }
}

function generateaddKeyValueParamForm()
{
	var rowId = jQuery('.trNewParam').length + 1;
	var rowName = '\'#trNewParam'+rowId;
	var contend = '
'
		+	'<input id="name' + rowId + '" name="name' + rowId + '" style="width:9em" type="text" onblur="checkDuplicatedKeyName(this.value,' + rowId + ') " placeholder="' + i18_new_key + '" />:	'
		+	'<input id="value' + rowId + '" name="value' + rowId + '" type="text" style="width: 10em" placeholder="' + i18_value + '"/>'
		+   	'<input type="radio" name="inputType'+rowId+'" value="text" onclick="updateInputType(' + rowId + ',\'text\')" checked>'+i18_text+'</input>'
		+   	'<input type="radio" name="inputType'+rowId+'" value="classified" onclick="updateInputType(' + rowId + ',\'classified\')" style="margin-left: 1em" >'+i18_password+'</input>'
		+   	'<input type="checkbox" name="headerType'+rowId+'" style="margin-left: 1em">'+i18_header+'</input>'
		+   	'<input style="margin-left: 3em" type="button" value="remove" onclick="removeNewParamForm(' + rowId + ')"/>	'
		+ '
';
	jQuery('#genericHTTPFields').append(contend);
}

function removeNewParamForm( rowId )
{
	jQuery('#trNewParam'+rowId).remove();
}
function removeOldParamForm( rowId )
{
	jQuery('#trOldParam'+rowId).remove();
}

function updateInputType( rowId, type )
{
	jQuery('#value'+rowId).prop('type', type);
}

function saveSettings ()
{
	var url = "../api/gateways/generichttp";
	var httpFields = jQuery('#genericHTTPFields');
	var data = {
		name: httpFields.find("#name")[0].value,
		messageParameter: httpFields.find("#messageParameter")[0].value,
		recipientParameter: httpFields.find("#recipientParameter")[0].value,
		urlTemplate: httpFields.find("#urlTemplate")[0].value
	};

	var newParams = getHttpKeyValueParamsAddedByTheUser(httpFields);

	if ( data.urltemplate == "" ) {
		showErrorMessage(i18n_required_data_error);
	} else {

		if (newParams) {
			data['parameters'] = newParams;
		}

		jQuery.ajax({
			url: url,
			type: 'POST',
			dataType: 'json',
			data: JSON.stringify(data),
			contentType: "application/json"

		}).done(function (response) {
			console.log(response);
			showSuccessMessage(i18n_add_update_success);
		}).fail(function (error) {
			console.log(error);
			showErrorMessage("Error - status:"+error.status+" message:"+error.statusText);
		});
	}
}

function validateParameters(data)
{
	if (data.key =="" || data.value =="")
	{
		return false;
	}
	else
	{
		return true;
	}
}

function getHttpKeyValueParamsAddedByTheUser(allFields)
{
	var newParamName, newParamValue;
	var newParamsCount = jQuery('.trNewParam').length;
	var oldParamsCount = jQuery('.trOldParam').length;

	var parameters = [];

	for (var rowIndex = 1; rowIndex <= newParamsCount; rowIndex++) {
		var object = {};
		newParamName = allFields.find('#trNewParam'+rowIndex).find('#name'+rowIndex)[0].value;
		newParamValue = allFields.find('#trNewParam'+rowIndex).find('#value'+rowIndex)[0].value;
		newParamType = $('input[name=inputType'+rowIndex+']:checked').val();
		newHeaderType = $('input[name=headerType'+rowIndex+']').is(":checked");

		object.key=newParamName;
		object.value=newParamValue;

		if(newParamType == 'classified')
		{
			object.classified=true;
		}
		else
		{
			object.classified=false;
		}

		if( newHeaderType == true )
		{
			object.header=true;
		}
		else
		{
			object.header=false;
		}

		if(validateParameters(object))
		{
			parameters.push(object);
		}
	}

	for (var rowIndex = 1; rowIndex <= oldParamsCount; rowIndex++) {
		var object = {};
		oldParamName = allFields.find('#trOldParam'+rowIndex).find('#oldVName'+rowIndex)[0].value;
		oldParamValue = allFields.find('#trOldParam'+rowIndex).find('#oldValue'+rowIndex)[0].value;
		oldParamType = allFields.find('#trOldParam'+rowIndex).find('#oldHidden'+rowIndex)[0].value;

		object.key=oldParamName;
		object.value=oldParamValue;
		object.classified=oldParamType;
		parameters.push(object);
	}
	if (Object.keys(parameters).length === 0) {
		return null;
	}
	return parameters;
}


text:
package v1

import (
	"testing"
	"time"

	fuzz "github.com/google/gofuzz"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"

	"k8s.io/heapster/metrics/api/v1/types"
	"k8s.io/heapster/metrics/core"
	metricsink "k8s.io/heapster/metrics/sinks/metric"
)

func TestApiFactory(t *testing.T) {
	metricSink := metricsink.MetricSink{}
	api := NewApi(false, &metricSink, nil, false)
	as := assert.New(t)
	for _, metric := range core.StandardMetrics {
		val, exists := api.gkeMetrics[metric.Name]
		as.True(exists)
		as.Equal(val, metric.MetricDescriptor)
	}
	for _, metric := range core.LabeledMetrics {
		val, exists := api.gkeMetrics[metric.Name]
		as.True(exists)
		as.Equal(val, metric.MetricDescriptor)
	}

	for _, metric := range core.LabeledMetrics {
		val, exists := api.gkeMetrics[metric.Name]
		as.True(exists)
		as.Equal(val, metric.MetricDescriptor)
	}
	labels := append(core.CommonLabels(), core.ContainerLabels()...)
	labels = append(labels, core.PodLabels()...)
	for _, label := range labels {
		val, exists := api.gkeLabels[label.Key]
		as.True(exists)
		as.Equal(val, label)
	}
}

func TestFuzzInput(t *testing.T) {
	api := NewApi(false, nil, nil, false)
	data := []*core.DataBatch{}
	fuzz.New().NilChance(0).Fuzz(&data)
	_ = api.processMetricsRequest(data)
}

func generateMetricSet(objectType string, labels []core.LabelDescriptor) *core.MetricSet {
	ms := &core.MetricSet{
		CollectionStartTime: time.Now().Add(-time.Hour),
		ScrapeTime:          time.Now(),
		Labels:              make(map[string]string),
		MetricValues:        make(map[string]core.MetricValue),
		LabeledMetrics:      make([]core.LabeledMetric, len(labels)),
	}
	// Add all necessary labels
	for _, label := range labels {
		ms.Labels[label.Key] = "test-value"
	}
	ms.Labels[core.LabelMetricSetType.Key] = objectType
	// Add all standard metrics
	for _, metric := range core.StandardMetrics {
		ms.MetricValues[metric.Name] = core.MetricValue{
			MetricType: core.MetricCumulative,
			ValueType:  core.ValueInt64,
			IntValue:   -1,
		}
	}
	// Add all labeled metrics
	for _, metric := range core.LabeledMetrics {
		lm := core.LabeledMetric{
			Name: metric.Name,
			MetricValue: core.MetricValue{
				MetricType: core.MetricCumulative,
				ValueType:  core.ValueInt64,
				IntValue:   -1,
			},
			Labels: make(map[string]string),
		}
		for _, label := range core.MetricLabels() {
			lm.Labels[label.Key] = "test-value"
		}
		ms.LabeledMetrics = append(ms.LabeledMetrics, lm)
	}
	return ms
}

func generateDataBatch() ([]*core.DataBatch, []core.LabelDescriptor) {
	dataBatch := []*core.DataBatch{
		{
			Timestamp:  time.Now(),
			MetricSets: map[string]*core.MetricSet{},
		},
		{
			Timestamp:  time.Now().Add(-time.Minute),
			MetricSets: map[string]*core.MetricSet{},
		},
	}
	labels := append(core.CommonLabels(), core.ContainerLabels()...)
	labels = append(labels, core.PodLabels()...)
	for _, entry := range dataBatch {
		// Add a pod, container, node, systemcontainer
		entry.MetricSets[core.MetricSetTypePod] = generateMetricSet(core.MetricSetTypePod, labels)
		entry.MetricSets[core.MetricSetTypeNode] = generateMetricSet(core.MetricSetTypeNode, labels)
		entry.MetricSets[core.MetricSetTypePodContainer] = generateMetricSet(core.MetricSetTypePodContainer, labels)
		entry.MetricSets[core.MetricSetTypeSystemContainer] = generateMetricSet(core.MetricSetTypeSystemContainer, labels)
	}
	return dataBatch, labels
}

func generateMetricSink() *metricsink.MetricSink {
	batches, _ := generateDataBatch()
	metricSink := &metricsink.MetricSink{}
	for _, batch := range batches {
		metricSink.ExportData(batch)
	}
	return metricSink
}

func TestDisabledExportTrue(t *testing.T) {
	metricSink := generateMetricSink()
	api := NewApi(false, metricSink, nil, true)
	ts := api.getMetricsResponse()
	assert.Equal(t, make([]*types.Timeseries, 0), ts, "Should get 0 timeseries, %v found", len(ts))
}

func TestDisabledExportFalse(t *testing.T) {
	metricSink := generateMetricSink()
	api := NewApi(false, metricSink, nil, false)
	ts := api.getMetricsResponse()
	assert.Equal(t, 4, len(ts), "Should get 4 timeseries, %v found", len(ts))
}

func TestRealInput(t *testing.T) {
	api := NewApi(false, nil, nil, false)
	dataBatch, labels := generateDataBatch()
	ts := api.processMetricsRequest(dataBatch)
	type expectation struct {
		count       int
		extraLabels bool
	}
	expectedMetrics := make(map[string]*expectation)
	for _, metric := range core.StandardMetrics {
		expectedMetrics[metric.Name] = &expectation{
			count:       4,
			extraLabels: false,
		}
	}
	for _, metric := range core.LabeledMetrics {
		expectedMetrics[metric.Name] = &expectation{
			count:       4,
			extraLabels: true,
		}
	}
	as := assert.New(t)
	for _, elem := range ts {
		// validate labels
		for _, label := range labels {
			val, exists := elem.Labels[label.Key]
			as.True(exists, "%q label does not exist", label.Key)
			if label.Key == core.LabelMetricSetType.Key {
				continue
			}
			if label.Key == core.LabelContainerName.Key && val != "machine" && val != "/pod" {
				as.Equal(val, "test-value", "%q label's value is %q, expected 'test-value'", label.Key, val)
			}
		}
		for mname, points := range elem.Metrics {
			ex := expectedMetrics[mname]
			require.NotNil(t, ex)
			as.NotEqual(ex, 0)
			ex.count--
			for _, point := range points {
				as.Equal(point.Value, int64(-1))
				if !ex.extraLabels {
					continue
				}
				as.Equal(len(core.MetricLabels()), len(point.Labels))
				for _, label := range core.MetricLabels() {
					val, exists := point.Labels[label.Key]
					as.True(exists, "expected label %q to be found - %+v", label.Key, point.Labels)
					as.Equal(val, "test-value")
				}
			}
		}

	}
}


text:
package org.apache.bookkeeper.proto;

import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import io.netty.channel.Channel;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.apache.bookkeeper.bookie.Bookie;
import org.apache.bookkeeper.stats.OpStatsLogger;
import org.junit.Before;
import org.junit.Test;

/**
 * Unit test {@link GetBookieInfoProcessorV3}.
 */
public class GetBookieInfoProcessorV3Test {

    private Channel channel;
    private BookieRequestProcessor requestProcessor;
    private Bookie bookie;
    private RequestStats requestStats;
    private OpStatsLogger getBookieInfoStats;
    private OpStatsLogger channelWriteStats;
    private OpStatsLogger getBookieInfoRequestStats;

    @Before
    public void setup() {
        getBookieInfoStats = mock(OpStatsLogger.class);
        channelWriteStats = mock(OpStatsLogger.class);
        getBookieInfoRequestStats = mock(OpStatsLogger.class);
        requestStats = mock(RequestStats.class);
        requestProcessor = mock(BookieRequestProcessor.class);
        bookie = mock(Bookie.class);
        when(requestProcessor.getBookie()).thenReturn(bookie);
        channel = mock(Channel.class);
        when(channel.isOpen()).thenReturn(true);
        when(channel.isActive()).thenReturn(true);
        when(requestProcessor.getRequestStats()).thenReturn(requestStats);
        when(requestProcessor.getRequestStats().getGetBookieInfoStats())
                .thenReturn(getBookieInfoStats);
        when(requestProcessor.getRequestStats().getChannelWriteStats())
                .thenReturn(channelWriteStats);
        when(requestProcessor.getRequestStats().getGetBookieInfoRequestStats())
                .thenReturn(getBookieInfoRequestStats);
    }

    @Test
    public void testGetBookieInfoProcessorStats() throws IOException {
        final BookkeeperProtocol.BKPacketHeader.Builder headerBuilder =
                BookkeeperProtocol.BKPacketHeader.newBuilder()
                .setVersion(BookkeeperProtocol.ProtocolVersion.VERSION_THREE)
                .setOperation(BookkeeperProtocol.OperationType.GET_BOOKIE_INFO)
                .setTxnId(0);

        final BookkeeperProtocol.GetBookieInfoRequest.Builder getBookieInfoBuilder =
                BookkeeperProtocol.GetBookieInfoRequest.newBuilder()
                        .setRequested(BookkeeperProtocol.GetBookieInfoRequest.Flags.FREE_DISK_SPACE_VALUE);

        final BookkeeperProtocol.Request getBookieInfoRequest = BookkeeperProtocol.Request.newBuilder()
                .setHeader(headerBuilder)
                .setGetBookieInfoRequest(getBookieInfoBuilder)
                .build();

        GetBookieInfoProcessorV3 getBookieInfo = new GetBookieInfoProcessorV3(
                getBookieInfoRequest, channel, requestProcessor);
        getBookieInfo.run();

        // get BookieInfo succeeded.
        verify(getBookieInfoStats, times(1))
                .registerSuccessfulEvent(anyLong(), eq(TimeUnit.NANOSECONDS));

        // get BookieInfo failed.
        when(requestProcessor.getBookie().getTotalFreeSpace()).thenThrow(new IOException("test for failed."));
        getBookieInfo.run();
        verify(getBookieInfoStats, times(1))
                .registerFailedEvent(anyLong(), eq(TimeUnit.NANOSECONDS));
    }
}


text:
// Copyright (c) 2022, WNProject Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// clang-format off

#include "StyleSheetNodeSelectorFirstChild.h"
#include "../../Include/Rocket/Core/ElementText.h"
#include "../../Include/Rocket/Core/StyleSheetKeywords.h"
#include "precompiled.h"

namespace Rocket {
namespace Core {

StyleSheetNodeSelectorFirstChild::StyleSheetNodeSelectorFirstChild() {}

StyleSheetNodeSelectorFirstChild::~StyleSheetNodeSelectorFirstChild() {}

// Returns true if the element is the first DOM child in its parent.
bool StyleSheetNodeSelectorFirstChild::IsApplicable(const Element* element,
    int ROCKET_UNUSED_PARAMETER(a), int ROCKET_UNUSED_PARAMETER(b)) {
  Element* parent = element->GetParentNode();
  if (parent == NULL)
    return false;

  int child_index = 0;
  while (child_index < parent->GetNumChildren()) {
    // If this child (the first non-text child) is our element, then the
    // selector succeeds.
    Element* child = parent->GetChild(child_index);
    if (child == element)
      return true;

    // If this child is not a text element, then the selector fails; this
    // element is non-trivial.
    if (rocket_dynamic_cast<ElementText*>(child) == NULL &&
        child->GetDisplay() != DISPLAY_NONE)
      return false;

    // Otherwise, skip over the text element to find the last non-trivial
    // element.
    child_index++;
  }

  return false;
}
}  // namespace Core
}  // namespace Rocket


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta http-equiv="Content-Style-Type" content="text/css" />
  <meta name="generator" content="pandoc" />
  <title>Corona Docs: Plugins > tapfortap > setAppWallListener</title>
  <meta name="revised" content="01-Jul-2013" />
  <meta name="description" content="Whether you're new to Corona or want to take your app to the next level, we've got a wealth of resources for you including extensive documentation, API reference, sample code, and videos.  Plugins > tapfortap > setAppWallListener" />

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

SDK APIs

Enterprise APIs

Plugins

Guides

Tutorials

Corona Resources ▹

  <form action="http://www.google.com/cse" id="cse-search-box">
  <input type="hidden" name="cx" value="009283852522218786394:g40gqt2m6rq" />
  <input type="hidden" name="ie" value="UTF-8" />
  <input type="text" name="q" id="q" autocomplete="off" size="40" style="width:150px;float:left" />
  <input type="submit" name="sa" value="Search" style="float:right; font-size: 13px;" />
  </form>

tapfortap.setAppWallListener(function)

Overview

Syntax

Listener Function (required)

App Wall Listener Function

Examples

Ξ  ▸  Plugins  ▸  tapfortap  ▸  setAppWallListener

tapfortap.setAppWallListener(function)

Type
function

Library
tapfortap.*

Return value
None

Revision
Current Public Release (2013.2076)

Keywords
event, ad, fullscreen, tapfortap

Sample code

See also
tapfortap.prepareAppWall(), tapfortap.showAppWall(), tapfortap.appWallIsReady()

Overview

Sets the app wall's listener. This function will be called the when the appWall fires and event.

Syntax

local function appWallListener(event)
    ...
end

tapfortap.setAppWallListener(appWallListener)

Listener Function (required)

function. The function that will handle the event fired by the appWall. See "App Wall Listener Function" below for more details.

App Wall Listener Function

The listener function must accept a table as a argument. This table has the following keys:

name: The name of the libray passing the event. This will always be tapfortap.

event: The name of the event. Possible events include:

onReceiveAd: Fired when a new ad was received.

onShow: Fired when the ad was shown.

onDismiss: Fired when the ad was dismissed.

onFailToReceiveAd: Fired when the ad failed to download. This event populates the message key with the failure reason.

message: Any extra data that the event passes along. Only the onFailToReceiveAd event uses the message key to send along the failure reason.

Examples

-- Create a listener function
local function appWallListener(event)
    print(event.name, "appWallListener " .. event.event .. " " .. event.message)
end

local tft = require "tapfortap"
tapfortap.initialize("My Tap for Tap API key")

-- Set the app wall listener to to function above
tapfortap.setAppWallListener(appWallListener)
tapfortap.showAppWall()

© 2013 Corona Labs Inc. All Rights Reserved. (Last updated: 01-Jul-2013)

Help us help you! Give us feedback on this page:

Love it

Like it, but...

Hate it


text:
<!--
        Copyright (C) 2012 DataStax Inc.

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.datastax.cassandra</groupId>
    <artifactId>cassandra-driver-parent</artifactId>
    <version>1.0.5-SNAPSHOT</version>
  </parent>
  <artifactId>cassandra-driver-core</artifactId>
  <packaging>bundle</packaging>
  <name>DataStax Java Driver for Apache Cassandra - Core</name>
  <description>A driver for Apache Cassandra 1.2+ that works exclusively with the Cassandra Query Language version 3 (CQL3) and Cassandra's binary protocol.</description>
  <url>https://github.com/datastax/java-driver</url>

  <dependencies>
    <dependency>
      <groupId>io.netty</groupId>
      <artifactId>netty</artifactId>
      <version>3.7.0.Final</version>
    </dependency>

    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
      <version>14.0.1</version>
    </dependency>

    <dependency>
      <groupId>org.apache.cassandra</groupId>
      <artifactId>cassandra-thrift</artifactId>
      <version>${cassandra-dependency.version}</version>
    </dependency>

    <dependency>
      <groupId>org.apache.thrift</groupId>
      <artifactId>libthrift</artifactId>
      <!-- Leave at 0.7.0 for Cassandra compatibility -->
      <version>0.7.0</version>
      <exclusions>
        <exclusion>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-api</artifactId>
        </exclusion>
      </exclusions>
    </dependency>

    <dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-core-asl</artifactId>
      <!-- Leave at 1.9.2 for Cassandra compatibility -->
      <version>1.9.2</version>
    </dependency>

    <dependency>
      <groupId>com.yammer.metrics</groupId>
      <artifactId>metrics-core</artifactId>
      <version>2.2.0</version>
    </dependency>

    <dependency>
      <groupId>org.testng</groupId>
      <artifactId>testng</artifactId>
      <version>6.8.1</version>
      <scope>test</scope>
    </dependency>

  </dependencies>

  <profiles>
    <profile>
      <id>default</id>
      <properties>
        <env>default</env>
      </properties>
      <activation>
        <activeByDefault>true</activeByDefault>
      </activation>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.14</version>
            <configuration>
              <groups>unit</groups>
              <useFile>false</useFile>
              <systemPropertyVariables>
                <cassandra.version>${cassandra.version}</cassandra.version>
                <ipprefix>${ipprefix}</ipprefix>
              </systemPropertyVariables>
            </configuration>
          </plugin>
          <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
              <compilerArgument>-Xlint:all</compilerArgument>
              <showWarnings>true</showWarnings>
              <showDeprecation>true</showDeprecation>
            </configuration>
          </plugin>
        </plugins>
      </build>
    </profile>

    <profile>
      <id>short</id>
      <properties>
        <env>default</env>
      </properties>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.14</version>
            <configuration>
              <groups>unit,short</groups>
              <useFile>false</useFile>
              <systemPropertyVariables>
                <cassandra.version>${cassandra.version}</cassandra.version>
                <ipprefix>${ipprefix}</ipprefix>
              </systemPropertyVariables>
            </configuration>
          </plugin>
        </plugins>
      </build>
    </profile>

    <profile>
      <id>long</id>
      <properties>
        <env>default</env>
      </properties>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.14</version>
            <configuration>
              <groups>unit,short,long</groups>
              <useFile>false</useFile>
              <systemPropertyVariables>
                <cassandra.version>${cassandra.version}</cassandra.version>
                <ipprefix>${ipprefix}</ipprefix>
              </systemPropertyVariables>
            </configuration>
          </plugin>
        </plugins>
      </build>
    </profile>

    <profile>
      <id>duration</id>
      <properties>
        <env>default</env>
      </properties>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.14</version>
            <configuration>
              <groups>unit,short,long,duration</groups>
              <useFile>false</useFile>
              <systemPropertyVariables>
                <cassandra.version>${cassandra.version}</cassandra.version>
                <ipprefix>${ipprefix}</ipprefix>
              </systemPropertyVariables>
            </configuration>
          </plugin>
        </plugins>
      </build>
    </profile>

    <profile>
      <id>doc</id>
      <properties>
        <env>default</env>
      </properties>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.14</version>
            <configuration>
              <groups>unit,doc</groups>
              <useFile>false</useFile>
              <systemPropertyVariables>
                <cassandra.version>${cassandra.version}</cassandra.version>
                <ipprefix>${ipprefix}</ipprefix>
              </systemPropertyVariables>
            </configuration>
          </plugin>
        </plugins>
      </build>
    </profile>
  </profiles>

  <licenses>
    <license>
      <name>Apache 2</name>
      <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
      <distribution>repo</distribution>
      <comments>Apache License Version 2.0</comments>
    </license>
  </licenses>

  <scm>
    <connection>scm:git:git@github.com:datastax/java-driver.git</connection>
    <developerConnection>scm:git:git@github.com:datastax/java-driver.git</developerConnection>
    <url>https://github.com/datastax/java-driver</url>
  </scm>

  <developers>
    <developer>
      <name>Various</name>
      <organization>DataStax</organization>
    </developer>
  </developers>

</project>


text:
import sys,string,os
sys.path.insert(1, os.path.join(sys.path[0], '..')) ### import parent dir dependencies

import numpy as np
import numpy.polynomial.polynomial as poly
import matplotlib
import matplotlib.pyplot as plt

def disp(hgvfile):
    lab={}
    me=[]
    std=[]
    for line in open(hgvfile,'rU').xreadlines():
        data = line.rstrip()
        t = string.split(data,'\t')
        me.append(float(t[2]))
        std.append(float(t[1]))

    me=np.asarray(me)
    std=np.asarray(std)
    coefs = poly.polyfit(me, std, 2)
    ffit = poly.Polynomial(coefs)
    print len(ffit(me))
    np.savetxt("fitted.txt",ffit(me),delimiter="\t")
    fig1 = plt.figure()
    ax1 = fig1.add_subplot(111)
    ax1.scatter(me, std, facecolors='None')
    ax1.plot(me, ffit(me))
    plt.show()

disp("/Users/meenakshi/Documents/altanalyze-master/hgv_0.1.txt")


text:
require 'spec_helper'

describe Raven::Event do
  before do
    Raven::Context.clear!
  end

  context 'a fully implemented event' do
    let(:hash) do
      Raven::Event.new({
        :message => 'test',
        :level => 'warning',
        :logger => 'foo',
        :tags => {
          'foo' => 'bar'
        },
        :extra => {
          'my_custom_variable' => 'value'
        },
        :server_name => 'foo.local',
        :release => '721e41770371db95eee98ca2707686226b993eda',
      }).to_hash
    end

    it 'has message' do
      expect(hash[:message]).to eq('test')
    end

    it 'has level' do
      expect(hash[:level]).to eq(30)
    end

    it 'has logger' do
      expect(hash[:logger]).to eq('foo')
    end

    it 'has server name' do
      expect(hash[:server_name]).to eq('foo.local')
    end

    it 'has release' do
      expect(hash[:release]).to eq('721e41770371db95eee98ca2707686226b993eda')
    end

    it 'has tag data' do
      expect(hash[:tags]).to eq({
        'foo' => 'bar'
      })
    end

    it 'has extra data' do
      expect(hash[:extra]).to eq({
        'my_custom_variable' => 'value'
      })
    end

    it 'has platform' do
      expect(hash[:platform]).to eq('ruby')
    end
  end

  context 'user context specified' do
    let(:hash) do
      Raven.user_context({
        'id' => 'hello',
      })

      Raven::Event.new({
        :level => 'warning',
        :logger => 'foo',
        :tags => {
          'foo' => 'bar'
        },
        :extra => {
          'my_custom_variable' => 'value'
        },
        :server_name => 'foo.local',
      }).to_hash
    end

    it "adds user data" do
      expect(hash[:user]).to eq({
        'id' => 'hello',
      })
    end
  end

  context 'tags context specified' do
    let(:hash) do
      Raven.tags_context({
        'key' => 'value',
      })

      Raven::Event.new({
        :level => 'warning',
        :logger => 'foo',
        :tags => {
          'foo' => 'bar'
        },
        :extra => {
          'my_custom_variable' => 'value'
        },
        :server_name => 'foo.local',
      }).to_hash
    end

    it "merges tags data" do
      expect(hash[:tags]).to eq({
        'key' => 'value',
        'foo' => 'bar',
      })
    end
  end

  context 'extra context specified' do
    let(:hash) do
      Raven.extra_context({
        'key' => 'value',
      })

      Raven::Event.new({
        :level => 'warning',
        :logger => 'foo',
        :tags => {
          'foo' => 'bar'
        },
        :extra => {
          'my_custom_variable' => 'value'
        },
        :server_name => 'foo.local',
      }).to_hash
    end

    it "merges extra data" do
      expect(hash[:extra]).to eq({
        'key' => 'value',
        'my_custom_variable' => 'value',
      })
    end
  end

  context 'rack context specified' do
    require 'stringio'

    let(:hash) do
      Raven.rack_context({
        'REQUEST_METHOD' => 'POST',
        'QUERY_STRING' => 'biz=baz',
        'HTTP_HOST' => 'localhost',
        'SERVER_NAME' => 'localhost',
        'SERVER_PORT' => '80',
        'PATH_INFO' => '/lol',
        'rack.url_scheme' => 'http',
        'rack.input' => StringIO.new('foo=bar'),
      })

      Raven::Event.new({
        :level => 'warning',
        :logger => 'foo',
        :tags => {
          'foo' => 'bar'
        },
        :extra => {
          'my_custom_variable' => 'value'
        },
        :server_name => 'foo.local',
      }).to_hash
    end

    it "adds http data" do
      expect(hash[:request]).to eq({
        :data => { 'foo' => 'bar' },
        :env => { 'SERVER_NAME' => 'localhost', 'SERVER_PORT' => '80' },
        :headers => { 'Host' => 'localhost' },
        :method => 'POST',
        :query_string => 'biz=baz',
        :url => 'http://localhost/lol',
        :cookies => nil
      })
    end
  end

  context 'configuration tags specified' do
    let(:hash) do
      config = Raven::Configuration.new
      config.tags = { 'key' => 'value' }

      Raven::Event.new(
        :level => 'warning',
        :logger => 'foo',
        :tags => {
          'foo' => 'bar'
        },
        :server_name => 'foo.local',
        :configuration => config
      ).to_hash
    end

    it 'merges tags data' do
      expect(hash[:tags]).to eq({
        'key' => 'value',
        'foo' => 'bar'
      })
    end
  end

  context 'configuration tags unspecified' do
    it 'should not persist tags between unrelated events' do
      config = Raven::Configuration.new

      Raven::Event.new(
        :level => 'warning',
        :logger => 'foo',
        :tags => {
          'foo' => 'bar'
        },
        :server_name => 'foo.local',
        :configuration => config
      )

      hash = Raven::Event.new(
        :level => 'warning',
        :logger => 'foo',
        :server_name => 'foo.local',
        :configuration => config
      ).to_hash

      expect(hash[:tags]).to eq({})
    end
  end

  context 'tags hierarchy respected' do
    let(:hash) do
      config = Raven::Configuration.new
      config.tags = {
          'configuration_context_event_key' => 'configuration_value',
          'configuration_context_key' => 'configuration_value',
          'configuration_event_key' => 'configuration_value',
          'configuration_key' => 'configuration_value',
      }

      Raven.tags_context({
        'configuration_context_event_key' => 'context_value',
        'configuration_context_key' => 'context_value',
        'context_event_key' => 'context_value',
        'context_key' => 'context_value',
      })

      Raven::Event.new(
        :level => 'warning',
        :logger => 'foo',
        :tags => {
          'configuration_context_event_key' => 'event_value',
          'configuration_event_key' => 'event_value',
          'context_event_key' => 'event_value',
          'event_key' => 'event_value',
        },
        :server_name => 'foo.local',
        :configuration => config
      ).to_hash
    end

    it 'merges tags data' do
      expect(hash[:tags]).to eq({
        'configuration_context_event_key' => 'event_value',
        'configuration_context_key' => 'context_value',
        'configuration_event_key' => 'event_value',
        'context_event_key' => 'event_value',
        'configuration_key' => 'configuration_value',
        'context_key' => 'context_value',
        'event_key' => 'event_value',
      })
    end
  end

  context 'merging user context' do
    before do
      Raven.user_context({
        'context_event_key' => 'context_value',
        'context_key' => 'context_value',
      })
    end

    let(:hash) do
      Raven::Event.new({
        :user => {
          'context_event_key' => 'event_value',
          'event_key' => 'event_value',
        },
      }).to_hash
    end

    it 'prioritizes event context over request context' do
      expect(hash[:user]).to eq({
        'context_event_key' => 'event_value',
        'context_key' => 'context_value',
        'event_key' => 'event_value',
      })
    end
  end

  context 'merging extra context' do
    before do
      Raven.extra_context({
        'context_event_key' => 'context_value',
        'context_key' => 'context_value',
      })
    end

    let(:hash) do
      Raven::Event.new({
        :extra => {
          'context_event_key' => 'event_value',
          'event_key' => 'event_value',
        },
      }).to_hash
    end

    it 'prioritizes event context over request context' do
      expect(hash[:extra]).to eq({
        'context_event_key' => 'event_value',
        'context_key' => 'context_value',
        'event_key' => 'event_value',
      })
    end
  end

  describe '.initialize' do
    it 'should not touch the env object for an ignored environment' do
      Raven.configure do |config|
        config.current_environment = 'test'
      end
      Raven.rack_context({})
      expect { Raven::Event.new }.not_to raise_error
    end
  end

  describe '.capture_message' do
    let(:message) { 'This is a message' }
    let(:hash) { Raven::Event.capture_message(message).to_hash }

    context 'for a Message' do
      it 'returns an event' do
        expect(Raven::Event.capture_message(message)).to be_a(Raven::Event)
      end

      it "sets the message to the value passed" do
        expect(hash[:message]).to eq(message)
      end

      it 'has level ERROR' do
        expect(hash[:level]).to eq(40)
      end

      it 'accepts an options hash' do
        expect(Raven::Event.capture_message(message, :logger => 'logger').logger).to eq('logger')
      end

      it 'accepts a stacktrace' do
        backtrace = ["/path/to/some/file:22:in `function_name'",
          "/some/other/path:1412:in `other_function'"]
        evt = Raven::Event.capture_message(message, :backtrace => backtrace)
        expect(evt[:stacktrace]).to be_a(Raven::StacktraceInterface)

        frames = evt[:stacktrace].to_hash[:frames]
        expect(frames.length).to eq(2)
        expect(frames[0][:lineno]).to eq(1412)
        expect(frames[0][:function]).to eq('other_function')
        expect(frames[0][:filename]).to eq('/some/other/path')

        expect(frames[1][:lineno]).to eq(22)
        expect(frames[1][:function]).to eq('function_name')
        expect(frames[1][:filename]).to eq('/path/to/some/file')
      end
    end
  end

  describe '.capture_exception' do
    let(:message) { 'This is a message' }
    let(:exception) { Exception.new(message) }
    let(:hash) { Raven::Event.capture_exception(exception).to_hash }

    context 'for an Exception' do
      it 'returns an event' do
        expect(Raven::Event.capture_exception(exception)).to be_a(Raven::Event)
      end

      it "sets the message to the exception's message and type" do
        expect(hash[:message]).to eq("Exception: #{message}")
      end

      # sentry uses python's logging values; 40 is the value of logging.ERROR
      it 'has level ERROR' do
        expect(hash[:level]).to eq(40)
      end

      it 'uses the exception class name as the exception type' do
        expect(hash[:exception][:values][0][:type]).to eq('Exception')
      end

      it 'uses the exception message as the exception value' do
        expect(hash[:exception][:values][0][:value]).to eq(message)
      end

      it 'does not belong to a module' do
        expect(hash[:exception][:values][0][:module]).to eq('')
      end
    end

    context 'for a nested exception type' do
      module Raven::Test
        class Exception < Exception; end
      end
      let(:exception) { Raven::Test::Exception.new(message) }

      it 'sends the module name as part of the exception info' do
        expect(hash[:exception][:values][0][:module]).to eq('Raven::Test')
      end
    end

    context 'for a Raven::Error' do
      let(:exception) { Raven::Error.new }
      it 'does not create an event' do
        expect(Raven::Event.capture_exception(exception)).to be_nil
      end
    end

    context 'for an excluded exception type' do
      module Raven::Test
        class BaseExc < Exception; end
        class SubExc < BaseExc; end
      end

      it 'returns nil for a string match' do
        config = Raven::Configuration.new
        config.excluded_exceptions << 'Raven::Test::BaseExc'
        expect(Raven::Event.capture_exception(Raven::Test::BaseExc.new,
                                       :configuration => config)).to be_nil
      end

      it 'returns nil for a class match' do
        config = Raven::Configuration.new
        config.excluded_exceptions << Raven::Test::BaseExc

        expect(Raven::Event.capture_exception(Raven::Test::SubExc.new,
                                       :configuration => config)).to be_nil
      end
    end

    # Only check causes when they're supported
    if Exception.new.respond_to? :cause
      context 'when the exception has a cause' do
        let(:exception) { build_exception_with_cause }

        it 'captures the cause' do
          expect(hash[:exception][:values].length).to eq(2)
        end
      end

      context 'when the exception has nested causes' do
        let(:exception) { build_exception_with_two_causes }

        it 'captures nested causes' do
          expect(hash[:exception][:values].length).to eq(3)
        end
      end
    end

    context 'when the exception has a recursive cause' do
      let(:exception) { build_exception_with_recursive_cause }

      it 'should handle it gracefully' do
        expect(hash[:exception][:values].length).to eq(2)
      end
    end

    if RUBY_PLATFORM == "java"
      context 'when running under jRuby' do
        let(:exception) do
          begin
            raise java.lang.OutOfMemoryError.new("A Java error")
          rescue Exception => e
            return e
          end
        end

        it 'should have a backtrace' do
          frames = hash[:exception][:values][0][:stacktrace][:frames]
          expect(frames.length).not_to eq(0)
        end
      end
    end

    context 'when the exception has a backtrace' do
      let(:exception) do
        e = Exception.new(message)
        allow(e).to receive(:backtrace).and_return [
          "/path/to/some/file:22:in `function_name'",
          "/some/other/path:1412:in `other_function'"
        ]
        e
      end

      it 'parses the backtrace' do
        frames = hash[:exception][:values][0][:stacktrace][:frames]
        expect(frames.length).to eq(2)
        expect(frames[0][:lineno]).to eq(1412)
        expect(frames[0][:function]).to eq('other_function')
        expect(frames[0][:filename]).to eq('/some/other/path')

        expect(frames[1][:lineno]).to eq(22)
        expect(frames[1][:function]).to eq('function_name')
        expect(frames[1][:filename]).to eq('/path/to/some/file')
      end

      context 'with internal backtrace' do
        let(:exception) do
          e = Exception.new(message)
          allow(e).to receive(:backtrace).and_return(["<internal:prelude>:10:in `synchronize'"])
          e
        end

        it 'marks filename and in_app correctly' do
          frames = hash[:exception][:values][0][:stacktrace][:frames]
          expect(frames[0][:lineno]).to eq(10)
          expect(frames[0][:function]).to eq("synchronize")
          expect(frames[0][:filename]).to eq("<internal:prelude>")
        end
      end

      it "sets the culprit" do
        expect(hash[:culprit]).to eq("/path/to/some/file in function_name at line 22")
      end

      context 'when a path in the stack trace is on the load path' do
        before do
          $LOAD_PATH << '/some'
        end

        after do
          $LOAD_PATH.delete('/some')
        end

        it 'strips prefixes in the load path from frame filenames' do
          frames = hash[:exception][:values][0][:stacktrace][:frames]
          expect(frames[0][:filename]).to eq('other/path')
        end
      end
    end

    it 'accepts an options hash' do
      expect(Raven::Event.capture_exception(exception, :logger => 'logger').logger).to eq('logger')
    end

    it 'uses an annotation if one exists' do
      Raven.annotate_exception(exception, :logger => 'logger')
      expect(Raven::Event.capture_exception(exception).logger).to eq('logger')
    end

    it 'accepts a checksum' do
      expect(Raven::Event.capture_exception(exception, :checksum => 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa').checksum).to eq('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
    end

    it 'accepts a release' do
      expect(Raven::Event.capture_exception(exception, :release => '1.0').release).to eq('1.0')
    end

    it 'accepts a fingerprint' do
      expect(Raven::Event.capture_exception(exception, :fingerprint => ['{{ default }}', 'foo']).fingerprint).to eq(['{{ default }}', 'foo'])
    end

    it 'accepts a logger' do
      expect(Raven::Event.capture_exception(exception, :logger => 'root').logger).to eq('root')
    end
  end
end


text:
package pl.matisoft.soy.ajax.auth;

/**
 * Created with IntelliJ IDEA.
 * User: mati
 * Date: 12/10/2013
 * Time: 23:38
 *
 * AuthManager is an interface, which is responsible for controlling which templates are allowed to be compiled
 * to JavaScript
 */
public interface AuthManager {

    boolean isAllowed(String url);

}