text:
from __future__ import print_function

"""Tool for packing multiple DTB/DTBO files into a single image"""

import argparse
import fnmatch
import os
import struct
import zlib
from array import array
from collections import namedtuple
from sys import stdout

class CompressionFormat(object):
    """Enum representing DT compression format for a DT entry.
    """
    NO_COMPRESSION = 0x00
    ZLIB_COMPRESSION = 0x01
    GZIP_COMPRESSION = 0x02

class DtEntry(object):
    """Provides individual DT image file arguments to be added to a DTBO.

    Attributes:
        REQUIRED_KEYS_V0: 'keys' needed to be present in the dictionary passed to instantiate
            an object of this class when a DTBO header of version 0 is used.
        REQUIRED_KEYS_V1: 'keys' needed to be present in the dictionary passed to instantiate
            an object of this class when a DTBO header of version 1 is used.
        COMPRESSION_FORMAT_MASK: Mask to retrieve compression info for DT entry from flags field
            when a DTBO header of version 1 is used.
    """
    COMPRESSION_FORMAT_MASK = 0x0f
    REQUIRED_KEYS_V0 = ('dt_file', 'dt_size', 'dt_offset', 'id', 'rev',
                     'custom0', 'custom1', 'custom2', 'custom3')
    REQUIRED_KEYS_V1 = ('dt_file', 'dt_size', 'dt_offset', 'id', 'rev',
                     'flags', 'custom0', 'custom1', 'custom2')

    @staticmethod
    def __get_number_or_prop(arg):
        """Converts string to integer or reads the property from DT image.

        Args:
            arg: String containing the argument provided on the command line.

        Returns:
            An integer property read from DT file or argument string
            converted to integer
        """

        if not arg or arg[0] == '+' or arg[0] == '-':
            raise ValueError('Invalid argument passed to DTImage')
        if arg[0] == '/':
            # TODO(b/XXX): Use pylibfdt to get property value from DT
            raise ValueError('Invalid argument passed to DTImage')
        else:
            base = 10
            if arg.startswith('0x') or arg.startswith('0X'):
                base = 16
            elif arg.startswith('0'):
                base = 8
            return int(arg, base)

    def __init__(self, **kwargs):
        """Constructor for DtEntry object.

        Initializes attributes from dictionary object that contains
        values keyed with names equivalent to the class's attributes.

        Args:
            kwargs: Dictionary object containing values to instantiate
                class members with. Expected keys in dictionary are from
                the tuple (_REQUIRED_KEYS)
        """

        self.__version = kwargs['version']
        required_keys = None
        if self.__version == 0:
            required_keys = self.REQUIRED_KEYS_V0
        elif self.__version == 1:
            required_keys = self.REQUIRED_KEYS_V1

        missing_keys = set(required_keys) - set(kwargs)
        if missing_keys:
            raise ValueError('Missing keys in DtEntry constructor: %r' %
                             sorted(missing_keys))

        self.__dt_file = kwargs['dt_file']
        self.__dt_offset = kwargs['dt_offset']
        self.__dt_size = kwargs['dt_size']
        self.__id = self.__get_number_or_prop(kwargs['id'])
        self.__rev = self.__get_number_or_prop(kwargs['rev'])
        if self.__version == 1:
            self.__flags = self.__get_number_or_prop(kwargs['flags'])
        self.__custom0 = self.__get_number_or_prop(kwargs['custom0'])
        self.__custom1 = self.__get_number_or_prop(kwargs['custom1'])
        self.__custom2 = self.__get_number_or_prop(kwargs['custom2'])
        if self.__version == 0:
            self.__custom3 = self.__get_number_or_prop(kwargs['custom3'])

    def __str__(self):
        sb = []
        sb.append('{key:>20} = {value:d}'.format(key='dt_size',
                                                 value=self.__dt_size))
        sb.append('{key:>20} = {value:d}'.format(key='dt_offset',
                                                 value=self.__dt_offset))
        sb.append('{key:>20} = {value:08x}'.format(key='id',
                                                   value=self.__id))
        sb.append('{key:>20} = {value:08x}'.format(key='rev',
                                                   value=self.__rev))
        if self.__version == 1:
            sb.append('{key:>20} = {value:08x}'.format(key='flags',
                                                       value=self.__flags))
        sb.append('{key:>20} = {value:08x}'.format(key='custom[0]',
                                                   value=self.__custom0))
        sb.append('{key:>20} = {value:08x}'.format(key='custom[1]',
                                                   value=self.__custom1))
        sb.append('{key:>20} = {value:08x}'.format(key='custom[2]',
                                                   value=self.__custom2))
        if self.__version == 0:
            sb.append('{key:>20} = {value:08x}'.format(key='custom[3]',
                                                       value=self.__custom3))
        return '\n'.join(sb)

    def compression_info(self):
        """CompressionFormat: compression format for DT image file.

           Args:
                version: Version of DTBO header, compression is only
                         supported from version 1.
        """
        if self.__version == 0:
            return CompressionFormat.NO_COMPRESSION
        return self.flags & self.COMPRESSION_FORMAT_MASK

    @property
    def dt_file(self):
        """file: File handle to the DT image file."""
        return self.__dt_file

    @property
    def size(self):
        """int: size in bytes of the DT image file."""
        return self.__dt_size

    @size.setter
    def size(self, value):
        self.__dt_size = value

    @property
    def dt_offset(self):
        """int: offset in DTBO file for this DT image."""
        return self.__dt_offset

    @dt_offset.setter
    def dt_offset(self, value):
        self.__dt_offset = value

    @property
    def image_id(self):
        """int: DT entry _id for this DT image."""
        return self.__id

    @property
    def rev(self):
        """int: DT entry _rev for this DT image."""
        return self.__rev

    @property
    def flags(self):
        """int: DT entry _flags for this DT image."""
        return self.__flags

    @property
    def custom0(self):
        """int: DT entry _custom0 for this DT image."""
        return self.__custom0

    @property
    def custom1(self):
        """int: DT entry _custom1 for this DT image."""
        return self.__custom1

    @property
    def custom2(self):
        """int: DT entry custom2 for this DT image."""
        return self.__custom2

    @property
    def custom3(self):
        """int: DT entry custom3 for this DT image."""
        return self.__custom3

class Dtbo(object):
    """
    Provides parser, reader, writer for dumping and creating Device Tree Blob
    Overlay (DTBO) images.

    Attributes:
        _DTBO_MAGIC: Device tree table header magic.
        _ACPIO_MAGIC: Advanced Configuration and Power Interface table header
                      magic.
        _DT_TABLE_HEADER_SIZE: Size of Device tree table header.
        _DT_TABLE_HEADER_INTS: Number of integers in DT table header.
        _DT_ENTRY_HEADER_SIZE: Size of Device tree entry header within a DTBO.
        _DT_ENTRY_HEADER_INTS: Number of integers in DT entry header.
        _GZIP_COMPRESSION_WBITS: Argument 'wbits' for gzip compression
        _ZLIB_DECOMPRESSION_WBITS: Argument 'wbits' for zlib/gzip compression
    """

    _DTBO_MAGIC = 0xd7b7ab1e
    _ACPIO_MAGIC = 0x41435049
    _DT_TABLE_HEADER_SIZE = struct.calcsize('>8I')
    _DT_TABLE_HEADER_INTS = 8
    _DT_ENTRY_HEADER_SIZE = struct.calcsize('>8I')
    _DT_ENTRY_HEADER_INTS = 8
    _GZIP_COMPRESSION_WBITS = 31
    _ZLIB_DECOMPRESSION_WBITS = 47

    def _update_dt_table_header(self):
        """Converts header entries into binary data for DTBO header.

        Packs the current Device tree table header attribute values in
        metadata buffer.
        """
        struct.pack_into('>8I', self.__metadata, 0, self.magic,
                         self.total_size, self.header_size,
                         self.dt_entry_size, self.dt_entry_count,
                         self.dt_entries_offset, self.page_size,
                         self.version)

    def _update_dt_entry_header(self, dt_entry, metadata_offset):
        """Converts each DT entry header entry into binary data for DTBO file.

        Packs the current device tree table entry attribute into
        metadata buffer as device tree entry header.

        Args:
            dt_entry: DtEntry object for the header to be packed.
            metadata_offset: Offset into metadata buffer to begin writing.
            dtbo_offset: Offset where the DT image file for this dt_entry can
                be found in the resulting DTBO image.
        """
        if self.version == 0:
            struct.pack_into('>8I', self.__metadata, metadata_offset, dt_entry.size,
                             dt_entry.dt_offset, dt_entry.image_id, dt_entry.rev,
                             dt_entry.custom0, dt_entry.custom1, dt_entry.custom2,
                             dt_entry.custom3)
        elif self.version == 1:
            struct.pack_into('>8I', self.__metadata, metadata_offset, dt_entry.size,
                             dt_entry.dt_offset, dt_entry.image_id, dt_entry.rev,
                             dt_entry.flags, dt_entry.custom0, dt_entry.custom1,
                             dt_entry.custom2)

    def _update_metadata(self):
        """Updates the DTBO metadata.

        Initialize the internal metadata buffer and fill it with all Device
        Tree table entries and update the DTBO header.
        """

        self.__metadata = array('b', b' ' * self.__metadata_size)
        metadata_offset = self.header_size
        for dt_entry in self.__dt_entries:
            self._update_dt_entry_header(dt_entry, metadata_offset)
            metadata_offset += self.dt_entry_size
        self._update_dt_table_header()

    def _read_dtbo_header(self, buf):
        """Reads DTBO file header into metadata buffer.

        Unpack and read the DTBO table header from given buffer. The
        buffer size must exactly be equal to _DT_TABLE_HEADER_SIZE.

        Args:
            buf: Bytebuffer read directly from the file of size
                _DT_TABLE_HEADER_SIZE.
        """
        (self.magic, self.total_size, self.header_size,
         self.dt_entry_size, self.dt_entry_count, self.dt_entries_offset,
         self.page_size, self.version) = struct.unpack_from('>8I', buf, 0)

        # verify the header
        if self.magic != self._DTBO_MAGIC and self.magic != self._ACPIO_MAGIC:
            raise ValueError('Invalid magic number 0x%x in DTBO/ACPIO file' %
                             (self.magic))

        if self.header_size != self._DT_TABLE_HEADER_SIZE:
            raise ValueError('Invalid header size (%d) in DTBO/ACPIO file' %
                             (self.header_size))

        if self.dt_entry_size != self._DT_ENTRY_HEADER_SIZE:
            raise ValueError('Invalid DT entry header size (%d) in DTBO/ACPIO file' %
                             (self.dt_entry_size))

    def _read_dt_entries_from_metadata(self):
        """Reads individual DT entry headers from metadata buffer.

        Unpack and read the DTBO DT entry headers from the internal buffer.
        The buffer size must exactly be equal to _DT_TABLE_HEADER_SIZE +
        (_DT_ENTRY_HEADER_SIZE * dt_entry_count). The method raises exception
        if DT entries have already been set for this object.
        """

        if self.__dt_entries:
            raise ValueError('DTBO DT entries can be added only once')

        offset = self.dt_entries_offset // 4
        params = {}
        params['version'] = self.version
        params['dt_file'] = None
        for i in range(0, self.dt_entry_count):
            dt_table_entry = self.__metadata[offset:offset + self._DT_ENTRY_HEADER_INTS]
            params['dt_size'] = dt_table_entry[0]
            params['dt_offset'] = dt_table_entry[1]
            for j in range(2, self._DT_ENTRY_HEADER_INTS):
                required_keys = None
                if self.version == 0:
                    required_keys = DtEntry.REQUIRED_KEYS_V0
                elif self.version == 1:
                    required_keys = DtEntry.REQUIRED_KEYS_V1
                params[required_keys[j + 1]] = str(dt_table_entry[j])
            dt_entry = DtEntry(**params)
            self.__dt_entries.append(dt_entry)
            offset += self._DT_ENTRY_HEADER_INTS

    def _read_dtbo_image(self):
        """Parse the input file and instantiate this object."""

        # First check if we have enough to read the header
        file_size = os.fstat(self.__file.fileno()).st_size
        if file_size < self._DT_TABLE_HEADER_SIZE:
            raise ValueError('Invalid DTBO file')

        self.__file.seek(0)
        buf = self.__file.read(self._DT_TABLE_HEADER_SIZE)
        self._read_dtbo_header(buf)

        self.__metadata_size = (self.header_size +
                                self.dt_entry_count * self.dt_entry_size)
        if file_size < self.__metadata_size:
            raise ValueError('Invalid or truncated DTBO file of size %d expected %d' %
                             file_size, self.__metadata_size)

        num_ints = (self._DT_TABLE_HEADER_INTS +
                    self.dt_entry_count * self._DT_ENTRY_HEADER_INTS)
        if self.dt_entries_offset > self._DT_TABLE_HEADER_SIZE:
            num_ints += (self.dt_entries_offset - self._DT_TABLE_HEADER_SIZE) / 4
        format_str = '>' + str(num_ints) + 'I'
        self.__file.seek(0)
        self.__metadata = struct.unpack(format_str,
                                        self.__file.read(self.__metadata_size))
        self._read_dt_entries_from_metadata()

    def _find_dt_entry_with_same_file(self, dt_entry):
        """Finds DT Entry that has identical backing DT file.

        Args:
            dt_entry: DtEntry object whose 'dtfile' we find for existence in the
                current 'dt_entries'.
        Returns:
            If a match by file path is found, the corresponding DtEntry object
            from internal list is returned. If not, 'None' is returned.
        """

        dt_entry_path = os.path.realpath(dt_entry.dt_file.name)
        for entry in self.__dt_entries:
            entry_path = os.path.realpath(entry.dt_file.name)
            if entry_path == dt_entry_path:
                return entry
        return None

    def __init__(self, file_handle, dt_type='dtb', page_size=None, version=0):
        """Constructor for Dtbo Object

        Args:
            file_handle: The Dtbo File handle corresponding to this object.
                The file handle can be used to write to (in case of 'create')
                or read from (in case of 'dump')
        """

        self.__file = file_handle
        self.__dt_entries = []
        self.__metadata = None
        self.__metadata_size = 0

        # if page_size is given, assume the object is being instantiated to
        # create a DTBO file
        if page_size:
            if dt_type == 'acpi':
                self.magic = self._ACPIO_MAGIC
            else:
                self.magic = self._DTBO_MAGIC
            self.total_size = self._DT_TABLE_HEADER_SIZE
            self.header_size = self._DT_TABLE_HEADER_SIZE
            self.dt_entry_size = self._DT_ENTRY_HEADER_SIZE
            self.dt_entry_count = 0
            self.dt_entries_offset = self._DT_TABLE_HEADER_SIZE
            self.page_size = page_size
            self.version = version
            self.__metadata_size = self._DT_TABLE_HEADER_SIZE
        else:
            self._read_dtbo_image()

    def __str__(self):
        sb = []
        sb.append('dt_table_header:')
        _keys = ('magic', 'total_size', 'header_size', 'dt_entry_size',
                 'dt_entry_count', 'dt_entries_offset', 'page_size', 'version')
        for key in _keys:
            if key == 'magic':
                sb.append('{key:>20} = {value:08x}'.format(key=key,
                                                           value=self.__dict__[key]))
            else:
                sb.append('{key:>20} = {value:d}'.format(key=key,
                                                         value=self.__dict__[key]))
        count = 0
        for dt_entry in self.__dt_entries:
            sb.append('dt_table_entry[{0:d}]:'.format(count))
            sb.append(str(dt_entry))
            count = count + 1
        return '\n'.join(sb)

    @property
    def dt_entries(self):
        """Returns a list of DtEntry objects found in DTBO file."""
        return self.__dt_entries

    def compress_dt_entry(self, compression_format, dt_entry_file):
        """Compresses a DT entry.

        Args:
            compression_format: Compression format for DT Entry
            dt_entry_file: File handle to read DT entry from.

        Returns:
            Compressed DT entry and its length.

        Raises:
            ValueError if unrecognized compression format is found.
        """
        compress_zlib = zlib.compressobj()  #  zlib
        compress_gzip = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION,
                                         zlib.DEFLATED, self._GZIP_COMPRESSION_WBITS)  #  gzip
        compression_obj_dict = {
            CompressionFormat.NO_COMPRESSION: None,
            CompressionFormat.ZLIB_COMPRESSION: compress_zlib,
            CompressionFormat.GZIP_COMPRESSION: compress_gzip,
        }

        if compression_format not in compression_obj_dict:
            ValueError("Bad compression format %d" % compression_format)

        if compression_format is CompressionFormat.NO_COMPRESSION:
            dt_entry = dt_entry_file.read()
        else:
            compression_object = compression_obj_dict[compression_format]
            dt_entry_file.seek(0)
            dt_entry = compression_object.compress(dt_entry_file.read())
            dt_entry += compression_object.flush()
        return dt_entry, len(dt_entry)

    def add_dt_entries(self, dt_entries):
        """Adds DT image files to the DTBO object.

        Adds a list of Dtentry Objects to the DTBO image. The changes are not
        committed to the output file until commit() is called.

        Args:
            dt_entries: List of DtEntry object to be added.

        Returns:
            A buffer containing all DT entries.

        Raises:
            ValueError: if the list of DT entries is empty or if a list of DT entries
                has already been added to the DTBO.
        """
        if not dt_entries:
            raise ValueError('Attempted to add empty list of DT entries')

        if self.__dt_entries:
            raise ValueError('DTBO DT entries can be added only once')

        dt_entry_count = len(dt_entries)
        dt_offset = (self.header_size +
                     dt_entry_count * self.dt_entry_size)

        dt_entry_buf = b""
        for dt_entry in dt_entries:
            if not isinstance(dt_entry, DtEntry):
                raise ValueError('Adding invalid DT entry object to DTBO')
            entry = self._find_dt_entry_with_same_file(dt_entry)
            dt_entry_compression_info = dt_entry.compression_info()
            if entry and (entry.compression_info() == dt_entry_compression_info):
                dt_entry.dt_offset = entry.dt_offset
                dt_entry.size = entry.size
            else:
                dt_entry.dt_offset = dt_offset
                compressed_entry, dt_entry.size = self.compress_dt_entry(dt_entry_compression_info,
                                                                         dt_entry.dt_file)
                dt_entry_buf += compressed_entry
                dt_offset += dt_entry.size
                self.total_size += dt_entry.size
            self.__dt_entries.append(dt_entry)
            self.dt_entry_count += 1
            self.__metadata_size += self.dt_entry_size
            self.total_size += self.dt_entry_size

        return dt_entry_buf

    def extract_dt_file(self, idx, fout, decompress):
        """Extract DT Image files embedded in the DTBO file.

        Extracts Device Tree blob image file at given index into a file handle.

        Args:
            idx: Index of the DT entry in the DTBO file.
            fout: File handle where the DTB at index idx to be extracted into.
            decompress: If a DT entry is compressed, decompress it before writing
                it to the file handle.

        Raises:
            ValueError: if invalid DT entry index or compression format is detected.
        """
        if idx > self.dt_entry_count:
            raise ValueError('Invalid index %d of DtEntry' % idx)

        size = self.dt_entries[idx].size
        offset = self.dt_entries[idx].dt_offset
        self.__file.seek(offset, 0)
        fout.seek(0)
        compression_format = self.dt_entries[idx].compression_info()
        if decompress and compression_format:
            if (compression_format == CompressionFormat.ZLIB_COMPRESSION or
                compression_format == CompressionFormat.GZIP_COMPRESSION):
                fout.write(zlib.decompress(self.__file.read(size), self._ZLIB_DECOMPRESSION_WBITS))
            else:
                raise ValueError("Unknown compression format detected")
        else:
            fout.write(self.__file.read(size))

    def commit(self, dt_entry_buf):
        """Write out staged changes to the DTBO object to create a DTBO file.

        Writes a fully instantiated Dtbo Object into the output file using the
        file handle present in '_file'. No checks are performed on the object
        except for existence of output file handle on the object before writing
        out the file.

        Args:
            dt_entry_buf: Buffer containing all DT entries.
        """
        if not self.__file:
            raise ValueError('No file given to write to.')

        if not self.__dt_entries:
            raise ValueError('No DT image files to embed into DTBO image given.')

        self._update_metadata()

        self.__file.seek(0)
        self.__file.write(self.__metadata)
        self.__file.write(dt_entry_buf)
        self.__file.flush()

def parse_dt_entry(global_args, arglist):
    """Parse arguments for single DT entry file.

    Parses command line arguments for single DT image file while
    creating a Device tree blob overlay (DTBO).

    Args:
        global_args: Dtbo object containing global default values
            for DtEntry attributes.
        arglist: Command line argument list for this DtEntry.

    Returns:
        A Namespace object containing all values to instantiate DtEntry object.
    """

    parser = argparse.ArgumentParser(add_help=False)
    parser.add_argument('dt_file', nargs='?',
                        type=argparse.FileType('rb'),
                        default=None)
    parser.add_argument('--id', type=str, dest='id', action='store',
                        default=global_args.global_id)
    parser.add_argument('--rev', type=str, dest='rev',
                        action='store', default=global_args.global_rev)
    parser.add_argument('--flags', type=str, dest='flags',
                        action='store',
                        default=global_args.global_flags)
    parser.add_argument('--custom0', type=str, dest='custom0',
                        action='store',
                        default=global_args.global_custom0)
    parser.add_argument('--custom1', type=str, dest='custom1',
                        action='store',
                        default=global_args.global_custom1)
    parser.add_argument('--custom2', type=str, dest='custom2',
                        action='store',
                        default=global_args.global_custom2)
    parser.add_argument('--custom3', type=str, dest='custom3',
                        action='store',
                        default=global_args.global_custom3)
    return parser.parse_args(arglist)

def parse_dt_entries(global_args, arg_list):
    """Parse all DT entries from command line.

    Parse all DT image files and their corresponding attribute from
    command line

    Args:
        global_args: Argument containing default global values for _id,
            _rev and customX.
        arg_list: The remainder of the command line after global options
            DTBO creation have been parsed.

    Returns:
        A List of DtEntry objects created after parsing the command line
        given in argument.
    """
    dt_entries = []
    img_file_idx = []
    idx = 0
    # find all positional arguments (i.e. DT image file paths)
    for arg in arg_list:
        if not arg.startswith("--"):
            img_file_idx.append(idx)
        idx = idx + 1

    if not img_file_idx:
        raise ValueError('Input DT images must be provided')

    total_images = len(img_file_idx)
    for idx in range(total_images):
        start_idx = img_file_idx[idx]
        if idx == total_images - 1:
            argv = arg_list[start_idx:]
        else:
            end_idx = img_file_idx[idx + 1]
            argv = arg_list[start_idx:end_idx]
        args = parse_dt_entry(global_args, argv)
        params = vars(args)
        params['version'] = global_args.version
        params['dt_offset'] = 0
        params['dt_size'] = os.fstat(params['dt_file'].fileno()).st_size
        dt_entries.append(DtEntry(**params))

    return dt_entries

def parse_config_option(line, is_global, dt_keys, global_key_types):
    """Parses a single line from the configuration file.

    Args:
        line: String containing the key=value line from the file.
        is_global: Boolean indicating if we should parse global or DT entry
            specific option.
        dt_keys: Tuple containing all valid DT entry and global option strings
            in configuration file.
        global_key_types: A dict of global options and their corresponding types. It
            contains all exclusive valid global option strings in configuration
            file that are not repeated in dt entry options.

    Returns:
        Returns a tuple for parsed key and value for the option. Also, checks
        the key to make sure its valid.
    """

    if line.find('=') == -1:
        raise ValueError('Invalid line (%s) in configuration file' % line)

    key, value = (x.strip() for x in line.split('='))
    if is_global and key in global_key_types:
        if global_key_types[key] is int:
            value = int(value)
    elif key not in dt_keys:
        raise ValueError('Invalid option (%s) in configuration file' % key)

    return key, value

def parse_config_file(fin, dt_keys, global_key_types):
    """Parses the configuration file for creating DTBO image.

    Args:
        fin: File handle for configuration file
        is_global: Boolean indicating if we should parse global or DT entry
            specific option.
        dt_keys: Tuple containing all valid DT entry and global option strings
            in configuration file.
        global_key_types: A dict of global options and their corresponding types. It
            contains all exclusive valid global option strings in configuration
            file that are not repeated in dt entry options.

    Returns:
        global_args, dt_args: Tuple of a dictionary with global arguments
        and a list of dictionaries for all DT entry specific arguments the
        following format.
            global_args:
                {'id' : <value>, 'rev' : <value> ...}
            dt_args:
                [{'filename' : 'dt_file_name', 'id' : <value>,
                 'rev' : <value> ...},
                 {'filename' : 'dt_file_name2', 'id' : <value2>,
                  'rev' : <value2> ...}, ...
                ]
    """

    # set all global defaults
    global_args = dict((k, '0') for k in dt_keys)
    global_args['dt_type'] = 'dtb'
    global_args['page_size'] = 2048
    global_args['version'] = 0

    dt_args = []
    found_dt_entry = False
    count = -1
    for line in fin:
        line = line.rstrip()
        if line.lstrip().startswith('#'):
            continue
        comment_idx = line.find('#')
        line = line if comment_idx == -1 else line[0:comment_idx]
        if not line or line.isspace():
            continue
        if line.startswith((' ', '\t')) and not found_dt_entry:
            # This is a global argument
            key, value = parse_config_option(line, True, dt_keys, global_key_types)
            global_args[key] = value
        elif line.find('=') != -1:
            key, value = parse_config_option(line, False, dt_keys, global_key_types)
            dt_args[-1][key] = value
        else:
            found_dt_entry = True
            count += 1
            dt_args.append({})
            dt_args[-1]['filename'] = line.strip()
    return global_args, dt_args

def parse_create_args(arg_list):
    """Parse command line arguments for 'create' sub-command.

    Args:
        arg_list: All command line arguments except the outfile file name.

    Returns:
        The list of remainder of the command line arguments after parsing
        for 'create'.
    """

    image_arg_index = 0
    for arg in arg_list:
        if not arg.startswith("--"):
            break
        image_arg_index = image_arg_index + 1

    argv = arg_list[0:image_arg_index]
    remainder = arg_list[image_arg_index:]
    parser = argparse.ArgumentParser(prog='create', add_help=False)
    parser.add_argument('--dt_type', type=str, dest='dt_type',
                        action='store', default='dtb')
    parser.add_argument('--page_size', type=int, dest='page_size',
                        action='store', default=2048)
    parser.add_argument('--version', type=int, dest='version',
                        action='store', default=0)
    parser.add_argument('--id', type=str, dest='global_id',
                        action='store', default='0')
    parser.add_argument('--rev', type=str, dest='global_rev',
                        action='store', default='0')
    parser.add_argument('--flags', type=str, dest='global_flags',
                        action='store', default='0')
    parser.add_argument('--custom0', type=str, dest='global_custom0',
                        action='store', default='0')
    parser.add_argument('--custom1', type=str, dest='global_custom1',
                        action='store', default='0')
    parser.add_argument('--custom2', type=str, dest='global_custom2',
                        action='store', default='0')
    parser.add_argument('--custom3', type=str, dest='global_custom3',
                        action='store', default='0')
    args = parser.parse_args(argv)
    return args, remainder

def parse_dump_cmd_args(arglist):
    """Parse command line arguments for 'dump' sub-command.

    Args:
        arglist: List of all command line arguments including the outfile
            file name if exists.

    Returns:
        A namespace object of parsed arguments.
    """

    parser = argparse.ArgumentParser(prog='dump')
    parser.add_argument('--output', '-o', nargs='?',
                        type=argparse.FileType('w'),
                        dest='outfile',
                        default=stdout)
    parser.add_argument('--dtb', '-b', nargs='?', type=str,
                        dest='dtfilename')
    parser.add_argument('--decompress', action='store_true', dest='decompress')
    return parser.parse_args(arglist)

def parse_config_create_cmd_args(arglist):
    """Parse command line arguments for 'cfg_create subcommand.

    Args:
        arglist: A list of all command line arguments including the
            mandatory input configuration file name.

    Returns:
        A Namespace object of parsed arguments.
    """
    parser = argparse.ArgumentParser(prog='cfg_create')
    parser.add_argument('conf_file', nargs='?',
                        type=argparse.FileType('r'),
                        default=None)
    cwd = os.getcwd()
    parser.add_argument('--dtb-dir', '-d', nargs='?', type=str,
                        dest='dtbdir', default=cwd)
    return parser.parse_args(arglist)

def create_dtbo_image(fout, argv):
    """Create Device Tree Blob Overlay image using provided arguments.

    Args:
        fout: Output file handle to write to.
        argv: list of command line arguments.
    """

    global_args, remainder = parse_create_args(argv)
    if not remainder:
        raise ValueError('List of dtimages to add to DTBO not provided')
    dt_entries = parse_dt_entries(global_args, remainder)
    dtbo = Dtbo(fout, global_args.dt_type, global_args.page_size, global_args.version)
    dt_entry_buf = dtbo.add_dt_entries(dt_entries)
    dtbo.commit(dt_entry_buf)
    fout.close()

def dump_dtbo_image(fin, argv):
    """Dump DTBO file.

    Dump Device Tree Blob Overlay metadata as output and the device
    tree image files embedded in the DTBO image into file(s) provided
    as arguments

    Args:
        fin: Input DTBO image files.
        argv: list of command line arguments.
    """
    dtbo = Dtbo(fin)
    args = parse_dump_cmd_args(argv)
    if args.dtfilename:
        num_entries = len(dtbo.dt_entries)
        for idx in range(0, num_entries):
            with open(args.dtfilename + '.{:d}'.format(idx), 'wb') as fout:
                dtbo.extract_dt_file(idx, fout, args.decompress)
    args.outfile.write(str(dtbo) + '\n')
    args.outfile.close()

def create_dtbo_image_from_config(fout, argv):
    """Create DTBO file from a configuration file.

    Args:
        fout: Output file handle to write to.
        argv: list of command line arguments.
    """
    args = parse_config_create_cmd_args(argv)
    if not args.conf_file:
        raise ValueError('Configuration file must be provided')

    _DT_KEYS = ('id', 'rev', 'flags', 'custom0', 'custom1', 'custom2', 'custom3')
    _GLOBAL_KEY_TYPES = {'dt_type': str, 'page_size': int, 'version': int}

    global_args, dt_args = parse_config_file(args.conf_file,
                                             _DT_KEYS, _GLOBAL_KEY_TYPES)
    version = global_args['version']

    params = {}
    params['version'] = version
    dt_entries = []
    for dt_arg in dt_args:
        filepath = dt_arg['filename']
        if not os.path.isabs(filepath):
            for root, dirnames, filenames in os.walk(args.dtbdir):
                for filename in fnmatch.filter(filenames, os.path.basename(filepath)):
                    filepath = os.path.join(root, filename)
        params['dt_file'] = open(filepath, 'rb')
        params['dt_offset'] = 0
        params['dt_size'] = os.fstat(params['dt_file'].fileno()).st_size
        for key in _DT_KEYS:
            if key not in dt_arg:
                params[key] = global_args[key]
            else:
                params[key] = dt_arg[key]
        dt_entries.append(DtEntry(**params))

    # Create and write DTBO file
    dtbo = Dtbo(fout, global_args['dt_type'], global_args['page_size'], version)
    dt_entry_buf = dtbo.add_dt_entries(dt_entries)
    dtbo.commit(dt_entry_buf)
    fout.close()

def print_default_usage(progname):
    """Prints program's default help string.

    Args:
        progname: This program's name.
    """
    sb = []
    sb.append('  ' + progname + ' help all')
    sb.append('  ' + progname + ' help <command>\n')
    sb.append('    commands:')
    sb.append('      help, dump, create, cfg_create')
    print('\n'.join(sb))

def print_dump_usage(progname):
    """Prints usage for 'dump' sub-command.

    Args:
        progname: This program's name.
    """
    sb = []
    sb.append('  ' + progname + ' dump <image_file> (<option>...)\n')
    sb.append('    options:')
    sb.append('      -o, --output <filename>  Output file name.')
    sb.append('                               Default is output to stdout.')
    sb.append('      -b, --dtb <filename>     Dump dtb/dtbo files from image.')
    sb.append('                               Will output to <filename>.0, <filename>.1, etc.')
    print('\n'.join(sb))

def print_create_usage(progname):
    """Prints usage for 'create' subcommand.

    Args:
        progname: This program's name.
    """
    sb = []
    sb.append('  ' + progname + ' create <image_file> (<global_option>...) (<dtb_file> (<entry_option>...) ...)\n')
    sb.append('    global_options:')
    sb.append('      --dt_type=<type>         Device Tree Type (dtb|acpi). Default: dtb')
    sb.append('      --page_size=<number>     Page size. Default: 2048')
    sb.append('      --version=<number>       DTBO/ACPIO version. Default: 0')
    sb.append('      --id=<number>       The default value to set property id in dt_table_entry. Default: 0')
    sb.append('      --rev=<number>')
    sb.append('      --flags=<number>')
    sb.append('      --custom0=<number>')
    sb.append('      --custom1=<number>')
    sb.append('      --custom2=<number>\n')
    sb.append('      --custom3=<number>\n')

    sb.append('      The value could be a number or a DT node path.')
    sb.append('      <number> could be a 32-bits digit or hex value, ex. 68000, 0x6800.')
    sb.append('      <path> format is <full_node_path>:<property_name>, ex. /board/:id,')
    sb.append('      will read the value in given FTB file with the path.')
    print('\n'.join(sb))

def print_cfg_create_usage(progname):
    """Prints usage for 'cfg_create' sub-command.

    Args:
        progname: This program's name.
    """
    sb = []
    sb.append('  ' + progname + ' cfg_create <image_file> <config_file> (<option>...)\n')
    sb.append('    options:')
    sb.append('      -d, --dtb-dir <dir>      The path to load dtb files.')
    sb.append('                               Default is load from the current path.')
    print('\n'.join(sb))

def print_usage(cmd, _):
    """Prints usage for this program.

    Args:
        cmd: The string sub-command for which help (usage) is requested.
    """
    prog_name = os.path.basename(__file__)
    if not cmd:
        print_default_usage(prog_name)
        return

    HelpCommand = namedtuple('HelpCommand', 'help_cmd, help_func')
    help_commands = (HelpCommand('dump', print_dump_usage),
                     HelpCommand('create', print_create_usage),
                     HelpCommand('cfg_create', print_cfg_create_usage),
                     )

    if cmd == 'all':
        print_default_usage(prog_name)

    for help_cmd, help_func in help_commands:
        if cmd == 'all' or cmd == help_cmd:
            help_func(prog_name)
            if cmd != 'all':
                return

    print('Unsupported help command: %s' % cmd, end='\n\n')
    print_default_usage(prog_name)
    return

def main():
    """Main entry point for mkdtboimg."""

    parser = argparse.ArgumentParser(prog='mkdtboimg.py')

    subparser = parser.add_subparsers(title='subcommand',
                                      description='Valid subcommands')

    create_parser = subparser.add_parser('create', add_help=False)
    create_parser.add_argument('argfile', nargs='?',
                               action='store', help='Output File',
                               type=argparse.FileType('wb'))
    create_parser.set_defaults(func=create_dtbo_image)

    config_parser = subparser.add_parser('cfg_create', add_help=False)
    config_parser.add_argument('argfile', nargs='?',
                               action='store',
                               type=argparse.FileType('wb'))
    config_parser.set_defaults(func=create_dtbo_image_from_config)

    dump_parser = subparser.add_parser('dump', add_help=False)
    dump_parser.add_argument('argfile', nargs='?',
                             action='store',
                             type=argparse.FileType('rb'))
    dump_parser.set_defaults(func=dump_dtbo_image)

    help_parser = subparser.add_parser('help', add_help=False)
    help_parser.add_argument('argfile', nargs='?', action='store')
    help_parser.set_defaults(func=print_usage)

    (subcmd, subcmd_args) = parser.parse_known_args()
    subcmd.func(subcmd.argfile, subcmd_args)

if __name__ == '__main__':
    main()


text:
import {FlatUser} from '../vo/flat-user.vo';

export class CommonUtil {
  public static getMonthsLong = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August',
    'September', 'October', 'November', 'December' ];

  public static isEmptyObject( object ) {
    // We could use Object.keys, but this is more efficient
    for (const key in object) {
      if (object.hasOwnProperty(key)) {
        return false;
      }
    }
    return true;
  }

  public static getMonthWiseInfo( period, coll ): Array<any> {
    let arr = [];
    coll.forEach(( data ) => {
      if (data.period === period) {
        //console.log(' Here is the Obj  ', data.period);
        arr.push(data);
      }
    });
    return arr;
  }

  public static prepareFlatUsersObject( owners, tenants ): any {
    let obj: any = {};
    obj.flatUsers = [];
    let tenantFound: boolean;
    let flatUser: FlatUser = new FlatUser();
    owners.forEach(( owner ) => {
      tenantFound = false;
      flatUser = owner;
      flatUser.fullName = owner.firstName + ' ' + owner.lastName;
      tenants.forEach(( tenant ) => {
        if (owner._id === tenant._id) {
          tenantFound = true;
          flatUser.tenant = tenant;
          flatUser.tenant.fullName = tenant.firstName + ' ' + tenant.lastName;
          obj.flatUsers.push(flatUser);
        }
      });
      if (!tenantFound) {
        obj.flatUsers.push(flatUser);
      }
    });
    return obj;
  }

  public static convertImageToBase64String( type: string, image ): string {
    let base64String = btoa(image);
    return 'data:' + `${type}` + ';base64,' + base64String;
  }
}

redpajama_set_name: RedPajamaGithub


text:
var is = require('../index');

var StringOrRegExp = [is.STRING, is.REGEXP];

var thing1 = /mischief/;

console.log(is(thing1).a.String); //false
console.log(is(thing1).not.a.Number); //true
console.log(is(thing1).an.Array); //false
console.log(is(thing1).a.RegExp); //true
console.log(is(thing1).a(StringOrRegExp)); //true
console.log(is(thing1).a.Primitive); //false
console.log(is(thing1).a.CoreObject); //true
console.log(is(thing1).not.a.JsonBasicType); //true
console.log(is(thing1).a.BuiltinType); //true

var thing2 = "mayhem";

console.log(is(thing2).a.String); //true
console.log(is(thing2).not.a.Number); //true
console.log(is(thing2).an.Array); //false
console.log(is(thing2).a.RegExp); //false
console.log(is(thing2).a(StringOrRegExp)); //true
console.log(is(thing2).a.Primitive); //true
console.log(is(thing2).a.CoreObject); //true
console.log(is(thing2).not.a.JsonBasicType); //false
console.log(is(thing2).a.BuiltinType); //true

var myType = is.ARRAY;

console.log(myType.is.a.String); //false
console.log(myType.is.not.a.Number); //true
console.log(myType.is.an.Array); //true
console.log(myType.is.a.RegExp); //false
console.log(myType.is.a(StringOrRegExp)); //false
console.log(myType.is.a.Primitive); //false
console.log(myType.is.a.CoreObject); //true
console.log(myType.is.not.a.JsonBasicType); //false
console.log(myType.is.a.BuiltinType); //true


text:
<?php

require_once $_SERVER['SYMFONY_SRC'].'/Symfony/Component/ClassLoader/UniversalClassLoader.php';

$loader = new Symfony\Component\ClassLoader\UniversalClassLoader();
$loader->registerNamespace('Symfony', $_SERVER['SYMFONY_SRC']);
$loader->registerNamespace('Zend', $_SERVER['ZEND_LIB']);
$loader->register();

spl_autoload_register(function($class)
{
    if (0 === strpos($class, 'OpenSky\\Bundle\\GraphiteBundle\\')) {
        $path = implode('/', array_slice(explode('\\', $class), 3)).'.php';
        require_once __DIR__.'/../'.$path;
        return true;
    }
});


text:
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// The following code is copyright Julien Couvreur.
// See http://blog.monstuff.com/archives/000280.html
var FlashHelper_version = 1;

/**************************************** FlashHelper ***************************************************/

var FlashHelper = new Object();
FlashHelper.height = 1; //100;
FlashHelper.width = 1; //100;

FlashHelper.shouldWaitForFlash = function() {
  // todo: should return 3 values: installed, notInstalled, silentInstall

}

FlashHelper.isFlashInstalled = function() {
  var ret;

  if (typeof(this.isFlashInstalledMemo) != "undefined") { return this.isFlashInstalledMemo; }

  if (typeof(ActiveXObject) != "undefined") {
    try {
      var ieObj = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
        } catch (e) { }
        ret = (ieObj != null);
  } else {
    var plugin = navigator.mimeTypes["application/x-shockwave-flash"];
    ret = (plugin != null) && (plugin.enabledPlugin != null);
  }

  this.isFlashInstalledMemo = ret;

  return ret;
}

FlashHelper.getFlash = function() {
  //var flash = (navigator.appName.indexOf ("Microsoft") !=-1)?window["storage"]:document["storage"];
  return FlashHelper.flash4AjaxTag; // $("storage");
}

FlashHelper.checkFlash = function() {
  // confirm that the Flash Storage is running

  try {
    return (this.getFlash().ping() == "pong");
  }
  catch (e) { return false; }
}

FlashHelper.writeFlash = function(fxBaseUrl) {
  var swfName = fxBaseUrl + "/Flash4AJAX.swf";

  var makeParam = function(name,value) {
    var param = document.createElement('param');
    param.setAttribute('name',name);
    param.setAttribute('value',value);
    return param;
  };

  var movie = makeParam('movie',swfName);
  var quality = makeParam('quality','high');
  var swliveconnect = makeParam('swliveconnect','true');

  var link = document.createElement('a');
  link.setAttribute('href','http://www.macromedia.com/software/flashplayer/');
  link.appendChild(document.createTextNode('here'));

  var notice = document.createElement('p');
  notice.appendChild(document.createTextNode('You need Flash for this.  Get the latest version from '));
  notice.appendChild(link);
  notice.appendChild(document.createTextNode('.'));

  var obj = document.createElement('object');
  if (window.ActiveXObject && !FlashHelper.isFlashInstalled()) {
    obj.setAttribute('classid','clsid:D27CDB6E-AE6D-11cf-96B8-444553540000');
    obj.setAttribute('codebase',
      'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,5,0,0');
    obj.setAttribute('height',this.height);
    obj.setAttribute('width',this.width);
    obj.appendChild(movie);
    obj.appendChild(quality);
    obj.appendChild(swliveconnect);
  }
  else {
    obj.setAttribute('data',swfName);
    obj.setAttribute('type','application/x-shockwave-flash');
    obj.setAttribute('height',this.height);
    obj.setAttribute('width',this.width);
    obj.appendChild(movie);
    obj.appendChild(quality);
    obj.appendChild(swliveconnect);
    obj.appendChild(makeParam('pluginurl','http://www.macromedia.com/go/getflashplayer'));
    obj.appendChild(makeParam('pluginspage','http://www.macromedia.com/go/getflashplayer'));
    obj.appendChild(notice);
  }

  document.body.appendChild(obj);

  FlashHelper.flash4AjaxTag = obj;
}

FlashHelper.addLoadEvent = function(func) {
  var oldonload = window.onload;

  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

FlashHelper.load = function() {
  if (typeof(FlashHelper.onload) != "function") { return; }

  if (FlashHelper.isFlashInstalled()) {
    // if we expect Flash to work, wait for both flash and the document to be loaded
    var finishedLoading = this.flashLoaded && this.documentLoaded;
    if (!finishedLoading) { return; }
  }
  // todo: cancel timer

  var fs = FlashHelper.getFlash();

  if ((!FlashHelper.isFlashInstalled() || this.flashLoaded) && fs) {
    if (FlashHelper.checkFlash()) {
      callAppOnLoad(fs);
    } else {
      callAppOnLoad(null);
    }
  } else {
    callAppOnLoad(null);
  }

  function callAppOnLoad(fs) {
    if (FlashHelper.onloadCalled) { return; } // todo: figure out why this case gets hit
    FlashHelper.onloadCalled = true;
    FlashHelper.onload(fs);
  }
}

function storageOnLoad() {
  //alert("storageOnLoad");
  FlashHelper.flashLoaded = true;
  FlashHelper.load();
}

function storageOnError() {
  //alert("storageOnError");
  FlashHelper.flashLoaded = true;
  FlashHelper.load();
}

FlashHelper.init = function() {
  this.flashLoaded = false;
  this.documentLoaded = false;

  // attach to the window.onload event
  this.addLoadEvent(onload);

  function onload() {
    //alert("Flash window.onload");
    if (FlashHelper.isFlashInstalled()) {
      // todo: set a timer
      //setTimeout(storageOnError, 60000);
    }

    FlashHelper.documentLoaded = true;
    FlashHelper.load();
  }
}

FlashHelper.init();

/**************************************** CallbackManager ***************************************************/

var CallbackManager = new Object();
CallbackManager.callbacks = new Array();

// assigns and returns a unique callback name for the input callback
CallbackManager.registerCallback = function(callback) {
  // todo: could be improved (look for the first available spot in the callbacks table, if necessary, expand it)
  var length = this.callbacks.push(selfDeleteCallback);
  var callbackID = length - 1;

  return "CallbackManager.callbacks[" + callbackID + "]";

  function selfDeleteCallback(obj) {
    delete CallbackManager.callbacks[callbackID];
    setTimeout(function() { callback(obj); }, 0);
    return;
  }
}

/**************************************** FlashXmlHttpRequest ***************************************************/

var FlashXMLHttpRequest = function() {

  return function() {
    var self = this;
    var _method, _url, _contentType = null;
    var _headers = new Array();

    // responseXML
    // status

    this.open = function(method, url, async, user, password) {
      _method = method;
      _url = url;
    }
    this.send = function(body) {
      var fs = FlashHelper.getFlash();

      function callback(varName) {
        var response = FlashHelper.getFlash().GetVariable(varName);
        self.responseText = response;

        if (self.onload) {
          self.onload();
        }
      }

      fs.XmlHttp(_url, CallbackManager.registerCallback(callback), _method, body, _contentType, _headers);
    }

    this.setRequestHeader = function(header, value) {
      if (header.toLowerCase() == "Content-Type".toLowerCase()) {
        _contentType = value;
        return;
      }

      _headers.push(header);
      _headers.push(value);
    }

    this.getRequestHeader = function() {
    }
    this.getResponseHeader = function(a) { alert("not supported"); }
    this.getAllResponseHeaders = function() { alert("not supported"); }
    this.abort = function() { alert("not supported"); }
    this.addEventListener = function(a, b, c) { alert("not supported"); }
    this.dispatchEvent = function(e) { alert("not supported"); }
    this.openRequest = function(a, b, c, d, e) { this.open(a, b, c, d, e); }
    this.overrideMimeType = function(e) { alert("not supported"); }
    this.removeEventListener = function(a, b, c) { alert("not supported"); }

    /*
    xmlhttp.setRequestHeader(
    'Content-Type',
    'application/x-www-form-urlencoded; charset=UTF-8'
    );
    */
  };
}();

var initFlapjaxForeignWSO = function(fxBaseUrl) {
  FlashHelper.onload = function() { };
  FlashHelper.writeFlash(fxBaseUrl);
}


text:
iD.modes.Save = function(context) {
    var ui = iD.ui.Commit(context)
        .on('cancel', cancel)
        .on('save', save);

    function cancel() {
        context.enter(iD.modes.Browse(context));
    }

    function save(e) {
        var loading = iD.ui.Loading(context)
            .message(t('save.uploading'))
            .blocking(true);

        context.container()
            .call(loading);

        context.connection().putChangeset(
            context.history().changes(iD.actions.DiscardTags(context.history().difference())),
            e.comment,
            context.history().imageryUsed(),
            function(err, changeset_id) {
                loading.close();
                if (err) {
                    var confirm = iD.ui.confirm(context.container());
                    confirm
                        .select('.modal-section.header')
                        .append('h3')
                        .text(t('save.error'));
                    confirm
                        .select('.modal-section.message-text')
                        .append('p')
                        .text(err.responseText || t('save.unknown_error_details'));
                } else {
                    context.flush();
                    success(e, changeset_id);
                }
            });
    }

    function success(e, changeset_id) {
        context.enter(iD.modes.Browse(context)
            .sidebar(iD.ui.Success(context)
                .changeset({
                    id: changeset_id,
                    comment: e.comment
                })
                .on('cancel', function(ui) {
                    context.ui().sidebar.hide(ui);
                })));
    }

    var mode = {
        id: 'save'
    };

    var behaviors = [
        iD.behavior.Hover(context),
        iD.behavior.Select(context),
        iD.behavior.Lasso(context),
        iD.modes.DragNode(context).behavior];

    mode.enter = function() {
        behaviors.forEach(function(behavior) {
            context.install(behavior);
        });

        context.connection().authenticate(function() {
            context.ui().sidebar.show(ui);
        });
    };

    mode.exit = function() {
        behaviors.forEach(function(behavior) {
            context.uninstall(behavior);
        });

        context.ui().sidebar.hide(ui);
    };

    return mode;
};


text:
use std::cell::Cell;

trait Anything<'a> {
    type AssocType: 'static;
}

fn with_signature<'a, T, F>(cell: Cell<&'a ()>, t: T, op: F)
where
    F: FnOnce(Cell<&'a ()>, T),
{
    op(cell, t)
}

fn require<'a, 'b, T>(_cell: Cell<&'a ()>, _t: T)
where
    T: Anything<'b>,
    T::AssocType: 'a,
{
}

#[rustc_regions]
fn no_relationships_late<'a, 'b, T>(cell: Cell<&'a ()>, t: T)
where
    T: Anything<'b>,
{
    with_signature(cell, t, |cell, t| require(cell, t));
}

#[rustc_regions]
fn no_relationships_early<'a, 'b, T>(cell: Cell<&'a ()>, t: T)
where
    T: Anything<'b>,
    'a: 'a,
{
    with_signature(cell, t, |cell, t| require(cell, t));
}

#[rustc_regions]
fn projection_outlives<'a, 'b, T>(cell: Cell<&'a ()>, t: T)
where
    T: Anything<'b>,
    T::AssocType: 'a,
{
    // This error is unfortunate. This code ought to type-check: we
    // are projecting `<T as Anything<'b>>::AssocType`, and we know
    // that this outlives `'a` because of the where-clause. However,
    // the way the region checker works, we don't register this
    // outlives obligation, and hence we get an error: this is because
    // what we see is a projection like `<T as
    // Anything<'?0>>::AssocType`, and we don't yet know if `?0` will
    // equal `'b` or not, so we ignore the where-clause. Obviously we
    // can do better here with a more involved verification step.

    with_signature(cell, t, |cell, t| require(cell, t));
}

#[rustc_regions]
fn elements_outlive<'a, 'b, T>(cell: Cell<&'a ()>, t: T)
where
    T: Anything<'b>,
    'b: 'a,
{
    with_signature(cell, t, |cell, t| require(cell, t));
}

#[rustc_regions]
fn one_region<'a, T>(cell: Cell<&'a ()>, t: T)
where
    T: Anything<'a>,
{
    // Note that in this case the closure still propagates an external
    // requirement between two variables in its signature, but the
    // creator maps both those two region variables to `'a` on its
    // side.
    with_signature(cell, t, |cell, t| require(cell, t));
}

fn main() {}


text:
[![Build Status](https://travis-ci.org/iuravic/duktig-core.svg?branch=master)](https://travis-ci.org/iuravic/duktig-core) [![Coverage Status](https://coveralls.io/repos/github/iuravic/duktig-core/badge.svg?branch=master)](https://coveralls.io/github/iuravic/duktig-core?branch=master)

# duktig-core

This is the core package for the Duktig micro MVC web framework.

A full skeleton web project using the Duktig framework is featured in the [`duktig-skeleton-web-app`](https://github.com/iuravic/duktig-skeleton-web-app) package, which uses this core package and implements all its dependencies.

# Table of contents
- [About](#about)
    - [duktig-skeleton-web-app package](#duktig-skeleton-web-app-package)
    - [Purpose](#purpose)
    - [Standards](#standards)
    - [Features](#features)
- [Package design](#package-design)
- [Core services](#core-services)
- [Requirements](#requirements)
- [Dependency injection](#dependency-injection)
    - [Container](#container)
    - [Dependency resolution](#dependency-resolution)
    - [Lazy-loading](#lazy-loading)
- [Framework components](#framework-components)
    - [Routing](#routing)
    - [Controllers](#controllers)
    - [Middleware](#middleware)
    - [Templating](#templating)
    - [Events](#events)
    - [Error handling](#error-handling)
- [Configuration](#configuration)
- [Testing](#testing)

# About

Duktig is a light weight MVC micro web framework written for PHP 7.1. It was primarily created as an educational project, but it is also fully tested and feasible for production use. It implements the MVC pattern and features an IoC container, events system, and uses HTTP middleware.

## `duktig-skeleton-web-app` package

The [`duktig-skeleton-web-app`](https://github.com/iuravic/duktig-skeleton-web-app) package is a full-featured project which is based on the `duktig-core` package. It can be used as a starting point for developing your own Duktig framework application since it readily implements all the necessary dependencies based on popular open-source projects and packages.

## Purpose

Duktig framework's goal is to deliver a flexible yet powerful framework for creating web applications
by using the most feasible and up-to-date features and practices.

By learning from some of the most popular PHP web frameworks today ([Aura](http://auraphp.com/), [Silex](https://silex.sensiolabs.org/), [Slim](https://www.slimframework.com/), [Stack](http://stackphp.com/), [Yii2](https://github.com/yiisoft/yii2/), [Lumen](https://lumen.laravel.com/), [Symfony](https://symfony.com/), [Laravel](https://laravel.com/), [Bullet](http://bulletphp.com/), [Proton](https://github.com/alexbilbie/Proton)), Duktig's core architecture relies on modern principles and standards.

## Standards

- [PSR](http://www.php-fig.org) compliant
  - PSR-2 coding, and PSR-4 autoloading standards
  - interfaces: PSR-3 logger, PSR-7 HTTP message, PSR-11 container, PSR-15 HTTP middlewares, PSR-17 HTTP factories
- decoupled package design
- powered by popular open source projects and libraries
- TDD developed, unit, integration, and functionally tested

## Features

- MVC pattern
- IoC and DI container
- HTTP middleware
- event system
- lazy loading

# Package design

Most of Duktig's core services are decoupled from the core package and packaged into their own modules. This kind of approach provides high flexibility and a good package design. Using interface injection, the object graph is naturally composed during the execution.

# Core services

The [`duktig-core`](https://github.com/iuravic/duktig-core) implements several of its own core services, while leaving out the implementation of most others to external projects:
- [configuration service](https://github.com/iuravic/duktig-core/blob/master/src/Core/Config/Config.php),
- [exception handler](https://github.com/iuravic/duktig-core/blob/master/src/Core/Exception/Handler/Handler.php),
- [response sender](https://github.com/iuravic/duktig-core/blob/master/src/Core/Http/ResponseSender.php),

These core services are registered in core's [`'Config/services.php'`](https://github.com/iuravic/duktig-core/blob/master/src/Config/services.php) file. If needed they can be overridden and replaced by your own configuration. This is achieved by using the `'skipCoreServices'` config parameter, in which case they must be specified by your own configuration.

`duktig-core` uses the [Auryn DI container](https://github.com/rdlowrey/auryn) out-of-the-box, or rather the adapter package [`duktig-auryn-adapter`](https://github.com/iuravic/duktig-auryn-adapter) which simply adapts its API to Duktig's [specification](https://github.com/iuravic/duktig-core/blob/master/src/Core/DI/ContainerInterface.php).
The container can be changed to your own choice.

# Requirements

The `duktig-core` package defines and uses a number of interfaces which need to be implemented by resolvable services at runtime. The [`duktig-skeleton-web-app`](https://github.com/iuravic/duktig-skeleton-web-app) demonstrates how this is done in a real case, and is a recommended starting point for writing your own Duktig framework application. Briefly put, to implement these requirements, an application (for example the `duktig-skeleton-web-app`) first includes all the required packages as [composer dependencies](https://github.com/iuravic/duktig-skeleton-web-app/blob/master/composer.json) and then [registers them as services](https://github.com/iuravic/duktig-skeleton-web-app/blob/master/src/Config/services.php).

Once implemented, the application has access to the implementations of the following interfaces:
- `Interop\Http\Factory\ServerRequestFactoryInterface` and `Interop\Http\Factory\ResponseFactoryInterface` - HTTP message factories
- `Interop\Http\ServerMiddleware\DelegateInterface` - HTTP middleware dispatcher service
- [`Duktig\Core\Event\Dispatcher\EventDispatcherInterface`](https://github.com/iuravic/duktig-core/blob/master/src/Core/Event/Dispatcher/EventDispatcherInterface.php) - event dispatcher
- [`Duktig\Core\View\RendererInterface`](https://github.com/iuravic/duktig-core/blob/master/src/Core/View/RendererInterface.php) - template renderer
- [`Duktig\Core\Route\Router\RouterInterface`](https://github.com/iuravic/duktig-core/blob/master/src/Core/Route/Router/RouterInterface.php) - router service
- `Psr\Log\LoggerInterface` - logger service

# Dependency injection

## Container

The DI container must implement the [`Duktig\Core\DI\ContainerInterface`](https://github.com/iuravic/duktig-core/blob/master/src/Core/DI/ContainerInterface.php). This interface is an extension of the `Psr\Container\ContainerInterface` with a several methods of its own. The dependency resolution in Duktig is based on constructor arguments injection which is the central feature the container must implement.

By default, Duktig uses the [Auryn container](https://github.com/rdlowrey/auryn) out-of-the-box, or rather the [`duktig-auryn-adapter`](https://github.com/iuravic/duktig-auryn-adapter) package which adapts to the defined interface. This is defined in the `dutig-core` [configuration](https://github.com/iuravic/duktig-core/tree/master/src/Config). The container can however be changed to any PSR-11 container which additionally implements the `Duktig\Core\DI\ContainerInterface`.

### ContainerFactory

The container itself is instantiated and configured by the [`Duktig\Core\DI\ContainerFactory`](https://github.com/iuravic/duktig-core/blob/master/src/Core/DI/ContainerFactory.php). If the custom container class has any constructor parameters, the `ContainerFactory` will try to resolve and inject them by using the `ReflectionClass`.

The `ContainerFactory` then configures the container, by running it through the service configurators. The services are configured in your app's `services.php` config file.

## Dependency resolution

As with other standard PHP DI containers, the constructor parameter type hinting is used to provide dependency injection. The following entities in the framework are resolved by the container:

- services
- controllers
- closure-type route handlers
- middlewares
- event listeners

These entities will have their constructor parameters resolved and injected at runtime. Any dependency can be injected in this way, either if it was previously defined with the container as a service, or even if it is automatically provisioned, which of course depends on if the container of your choice supports the automatic provisioning feature (the Auryn DI container does).

## Lazy-loading

The framework itself takes advantage of the lazy-loading optimization and delays the object creation in several cases, therefore improving performance. Ie. the controller resolution happens only when the end of the middleware stack is reached, and not sooner. Lazy-loading is naturally related to the container's `make()` method implementation. Therefore, if the container of your choice uses lazy-loading (which the Auryn DI container does), it will also be applied throughout the framework work flow.

# Framework components

## Routing

`duktig-core` defines its routing in terms of several entities. It uses a router which has the job to match the current request to the appropriate route. It also uses a route provider service which provides a simple API for fetching and identifying available routes.

### Router

Duktig's router is featured as a standalone service. The router must implement the [`Duktig\Core\Route\Router\RouterInterface`](https://github.com/iuravic/duktig-core/blob/master/src/Core/Route/Router/RouterInterface.php). This interface defines only one mandatory method `match` which matches the `Psr\Http\Message\ServerRequestInterface` object to a [`Duktig\Core\Route\Router\RouterMatch`](https://github.com/iuravic/duktig-core/blob/master/src/Core/Route/Router/RouterMatch.php) object. The `RouterMatch` is nothing more than a value object which represents the matched route; it holds the route which was matched and its parameters.

### Route

`Duktig\Core\Route\Route` is the Duktig's route model. Its form was heavily influenced by the [Symfony Route's](https://github.com/symfony/routing) route model, as it is one of the most feature-rich and popular route representations in the open-source community.

### RouteProvider

`Duktig\Core\Route\RouteProvider` is a service which provides access to the routes. It accesses the routes' configuration from the configuration services, and converts it to the `Route` objects, exposing them in a way of a several user-friendly API methods.

### Route handlers

A route can have two different kinds of resolvers:

- the first is a classical controller with an action method, where the controller extends the `BaseController` class exposing access to the request and some essential components,
- the second is a closure type handler, which is given directly in route configuration.

Both types of route handlers must return a `ResponseInterface` type object. For a closure type handler, it is recommended to use the `Interop\Http\Factory\ResponseFactoryInterface` to create a response instance, while a controller will already have the response prepared for use via the `BaseController` parent class.

Both types of handlers are dynamically resolved by the container, and have their constructor arguments dependencies injected upon creation.

## Controllers

Controllers are assigned to routes and are in charge of generating a response. Alternatively, instead of defining special controller classes, a simpler [closure-type route handlers](https://github.com/iuravic/duktig-skeleton-web-app/blob/master/README.md#routes-1) can be used.

### `BaseController`
All controller classes should extend the base `Duktig\Core\Controller\BaseController` in order to get access to the application context, including the properties:
- `$request` - the PSR-7 request object
- `$response` - - a "fresh" PSR-7 response object
- `$queryParams` - parsed URI parameters
- `$renderer` - template rendering service
- `$config` - configuration service

`BaseController` also provides methods for quicker manipulation of the response object and its rendering.

### Route parameters

Route parameters are passed to the controller as the action method's parameters. Ie. if a route uses one string parameter `$param`, and assigns it to the `exampleAction` method, the parameter will be available to the action method in this way:

```php
public function exampleAction(string $param) : ResponseInterface;
```

### Return type

Every controller or route handler must return a PSR-7 response object. The `$response` property is available for use within controller that extend the main `BaseController` class, which is internally generated by a PSR-17 `$responseFactory` service.

### Dependency injection

Controllers will have their constructor parameters resolved and injected at runtime. Controllers, among other entities, are by default not given the access to the container, as this is widely considered as the service locator anti-pattern. However, no special restriction is imposed on this approach neither, and could easily be implemented. This practice is, however, strongly discouraged.

It may be quite needless to point this out specifically, but, naturally, when your controller defines it's own dependencies, it must also pay respect to its parent's dependencies as well, ie.:

```php
<?php
namespace MyProject\Controller;

use Duktig\Core\Controller\BaseController;
use Interop\Http\Factory\ResponseFactoryInterface;
use Duktig\Core\View\RendererInterface;
use Duktig\Core\Config\ConfigInterface;
use MyProject\Service\CustomService;

class IndexController extends BaseController
{
    private $customService;

    public function __construct(
        CustomService $customService,
        ResponseFactoryInterface $responseFactory,
        RendererInterface $renderer,
        ConfigInterface $config
    )
    {
        parent::__construct($responseFactory, $renderer, $config);
        $this->customService = $customService;
    }
}
```

### Lazy loading

The controller is resolved and instantiated only at the point when it is reached by the command chain. The special `ControllerResponder` middleware is used to resolve and execute the controller, and return its response to the application.

## Middleware

Duktig uses the "single-pass" HTTP middleware which corresponds to the [PSR-15](http://www.php-fig.org/psr/) specification. It implies the implementation of the `Psr\Http\ServerMiddleware\MiddlewareInterface` and the method with the following signature:

```php
public function process(ServerRequestInterface $request, DelegateInterface $delegate);
```

Likewise the middleware dispatching system must implement the `Psr\Http\ServerMiddleware\DelegateInterface` with the following method:

```php
public function process(ServerRequestInterface $request);
```

Duktig leaves out the implementation of the middleware dispatching system from its core functionality, and delegates it to an external package.

### Application and route middleware

Two kinds of middlewares are used in Duktig:

- application middleware - global for the whole application, it is run on each request,
- route middleware - variable, can be assigned to a specific route.

### ControllerResponder

The ControllerResponder is a special middleware which lies at the end of the middleware stack. It resolves the route handler, calls it, and returns its response back to the middleware stack. Since it is used as a "responder" from the route handler's perspective, hence its name.

### The middleware stack

The full middleware stack which the request traverses consists of:
- application middleware
- route middleware
- the `ControllerResponder` middleware

### Dependency injection

All middlewares are instantiated by the container, therefore will have their constructor dependencies injected.

## Templating

The template rendering service is defined by the [`Duktig\Core\View\RendererInterface`](https://github.com/iuravic/duktig-core/blob/master/src/Core/View/RendererInterface.php). It provides a simple API necessary to use the templating.

## Events

### Event dispatcher

The event dispatcher is defined by the [`Duktig\Core\Event\Dispatcher\EventDispatcherInterface`](https://github.com/iuravic/duktig-core/blob/master/src/Core/Event/Dispatcher/EventDispatcherInterface.php). It implies that a container is provided to the dispatcher, which is then used to resolve the listeners. Therefore the event listeners will have their dependencies injected and be lazy-loaded when their events are dispatched.

### Event

Events in Duktig are simply value objects which contain the contextual information for the listeners to act upon. It is also correct to say that an event is just a value object with a unique name.

Two different event types can be used in Duktig.

#### Event as its separate class

An event can be created as its own class, which must extend the `Duktig\Core\Event\EventAbstract` class.

In this case, its name can but does not have to be specifically provided (as the constructor parameter), and a default event's name will be its fully qualified class name without the prefix backslash. Ie. for an event class `MyProject\Event\CustomEvent`, its default name will be `'MyProject\Event\CustomEvent'`.

Here is a simple example of firing an event which is defined in its own separate class. Let us assume the `UserEvent` takes the parameter `$user` as the constructor parameter. Dispatching this event is as simple as:

```php
$event = new \DemoApp\Event\UserEvent($user);
$eventDispatcher->dispatch($event);
```

#### Simple event

In the case of a simplest event which is represented only by its unique name, and does not need to hold any other information for the listener's handler to use, instead of writing a separate class for the event, the existing `Duktig\Core\Event\EventSimple` class can be used to instantiate an event on-the-fly.

In this case, a unique event name must be given to the constructor. Since the `EventSimple` can be used to instantiate different events, each of those events is held responsible for their own unique naming.

The simple event can be dispatched by instantiating the `EventSimple` object on the fly, ie:

```php
$eventDispatcher->dispatch(new \Duktig\Core\Event\EventSimple('theEventName'));
```

### Listeners

The event listener may either be provided as resolvable class/service name or as a simple closure.

In the first case, in which the listener is a separate class, it must implement the [`Duktig\Core\Event\ListenerInterface`](https://github.com/iuravic/duktig-core/blob/master/src/Core/Event/ListenerInterface.php). When the event is dispatched, the listener is be resolved by the container and have all its constructor dependencies injected.

In case the listener is given as a simple closure, it is not resolved by the container, so no dependencies will be injected. The closure-type listener expect only one optional argument, the event:

```php
function($event) { /* ... */ }
```

### Core events

The framework dispatches its core events throughout the points of interest in the application flow. The full list of Duktig's core events is found in the `duktig-core`'s [`events.php`](https://github.com/iuravic/duktig-core/blob/master/src/Config/events.php) file. Some core events are only defined by their unique names (ie. `'duktig.core.app.afterConfiguring'`), while others are created as separate classes.

## Error handling

Duktig uses its own error and exception handler which implements the [`Duktig\Core\Exception\Handler\HandlerInterface`](https://github.com/iuravic/duktig-core/blob/master/src/Core/Exception/Handler/HandlerInterface.php). Its basic tasks are to register the error handling throughout the application, to convert a `\Throwable` into a response, and to report the occurence of such an error.

It takes in cosideration the PHP 7 error and exception handling mechanisms. From the PHP 7 version, both the `\Error` and the `\Exception` classes implement the `\Throwable` interface. Instead of halting script execution, some fatal errors and recoverable errors now throw exceptions. Also, an uncaught exception will continue to produce a fatal error, and in this same way an `\Error` exception thrown from an uncaught fatal error still produces a fatal error.

In production environment, exceptions and errors are rendered through default or custom error templates. Handler prioritizes the templates by their locations and names. It searches for the most specific template it can find for the given throwable, while first trying to locate the template in the application custom template path, and if none are found it uses the default templates from the `duktig-core` package. It searches and renders an error template in following steps:
- if an `HttpException` is thrown, it searches for the template with the error code for its name,
- if no such template is found, as well as for all other exception types, it looks for a template
 with name equal to the exception class name,
- finally, it searches for a generic error template.

The renderer service is itself given the location of the templates, both for the custom templates within the application dir, and the default templates whithin the framework core dir. In this way it first looks for custom, and then for default templates.

# Configuration

The configuration specifics are described within the [`duktig-skeleton-web-app`](https://github.com/iuravic/duktig-skeleton-web-app) project where it is seen in action. The skeleton application takes the `duktig-core` and provides it with all its dependencies, employing it into the full Duktig environment.

# Testing

The `duktig-core` and all the the other [packages](https://github.com/iuravic/duktig-skeleton-web-app/blob/master/README.md#dependencies) implemented by the `duktig-skeleton-web-app` are fully tested using PHPUnit and Mockery.

A special [`Duktig\Test\AppTesting`](https://github.com/iuravic/duktig-core/blob/master/tests/AppTesting.php) class is available for the testing environment. It extends access to the container and to the response object. It can be used to easily mock services, and to gain direct access to the response.


text:
// <copyright file="TemplateOutliningTagger.cs" company="Oleg Sych">
//  Copyright © Oleg Sych. All Rights Reserved.
// </copyright>

namespace T4Toolbox.VisualStudio.Editor
{
    using System.Diagnostics.CodeAnalysis;
    using System.IO;
    using System.Linq;
    using System.Text;
    using Microsoft.VisualStudio.Text;
    using Microsoft.VisualStudio.Text.Tagging;
    using T4Toolbox.TemplateAnalysis;

    internal sealed class TemplateOutliningTagger : TemplateTagger<OutliningRegionTag>
    {
        public TemplateOutliningTagger(ITextBuffer buffer) : base(buffer)
        {
            this.UpdateTagSpans(this.Analyzer.CurrentAnalysis);
        }

        [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Justification = "This is an internal method, called by base class.")]
        protected override void CreateTagSpans(TemplateAnalysis analysis)
        {
            // If text buffer contains recognizable template
            Template template = analysis.Template;
            if (template != null)
            {
                ITextSnapshot snapshot = analysis.TextSnapshot;
                string text = snapshot.GetText();
                foreach (CodeBlock codeBlock in template.ChildNodes().OfType<CodeBlock>())
                {
                    ITrackingSpan trackingSpan = snapshot.CreateTrackingSpan(codeBlock.Span, SpanTrackingMode.EdgeNegative);

                    string collapsedForm = GetCollapsedForm(codeBlock, text);
                    string collapsedHintForm = GetCollapsedHintForm(codeBlock, text);
                    var tag = new OutliningRegionTag(collapsedForm, collapsedHintForm);

                    this.CreateTagSpan(trackingSpan, tag);
                }
            }
        }

        private static string GetCollapsedForm(CodeBlock codeBlock, string template)
        {
            var text = new StringBuilder();
            text.Append(codeBlock.Start.GetText(template));
            text.Append("...");
            text.Append(codeBlock.End.GetText(template));
            return text.ToString();
        }

        private static string GetCollapsedHintForm(CodeBlock codeBlock, string template)
        {
            var text = new StringBuilder();

            using (var reader = new StringReader(codeBlock.GetText(template)))
            {
                for (int i = 0; i < 10; i++)
                {
                    string line = reader.ReadLine();
                    if (line == null)
                    {
                        return text.ToString();
                    }

                    // Append new line manually to avoid unnecessary \r\n at the end
                    if (i > 0)
                    {
                        text.AppendLine();
                    }

                    text.Append(line);
                }

                text.AppendLine();
                text.Append("...");
            }

            return text.ToString();
        }
    }
}


text:
<!DOCTYPE html>

	<title>angular-cache Demo</title>
	<meta name="viewport" content="width=device-width, initial-scale=1.0">

	<link href="bootstrap.min.css" rel="stylesheet">
	<link href="github.css" rel="stylesheet">

			angular-cache Demo

					Back to docs

AngularCache

				<button class="btn btn-primary btn-large" data-ng-click="add()" style="margin-left: 20px;">
					Add item to all caches
				</button>

				<button class="btn btn-warning navbar-btn btn-large" data-ng-click="reset()"
						style="margin-left: 20px;">
					Reset all
				</button>

			method

					{{info.id}}
					<button class="btn btn-primary btn-small" data-ng-hide="editingDefaultCache"
							data-ng-click="editDefaultCache()">Edit
					</button>
					<button class="btn btn-success btn-small" data-ng-show="editingDefaultCache"
							data-ng-click="saveDefaultCache()">Save
					</button>
					<button class="btn btn-danger btn-small" data-ng-show="editingDefaultCache"
							data-ng-click="cancelDefaultCache()">Cancel
					</button>

{{info.id}}

			info().id
			"{{info.id}}"

			info().capacity

				<input type="text" data-ng-if="$first && editingDefaultCache" placeholder="Enter capacity"
					   data-ng-model="defaultCacheOptions.capacity">
				{{info.capacity}}

			info().size
			{{info.size}}

			info().maxAge

				<input type="text" data-ng-if="$first && editingDefaultCache" placeholder="Enter maxAge (ms)"
					   data-ng-model="defaultCacheOptions.maxAge">
				{{info.maxAge | milliseconds}}

			info().aggressiveDelete

				<input type="text" data-ng-if="$first && editingDefaultCache"
					   placeholder="Enter aggressiveDelete (true || false)"
					   data-ng-model="defaultCacheOptions.aggressiveDelete">
				{{info.aggressiveDelete}}

			info().storageMode

				<input type="text" data-ng-if="$first && editingDefaultCache"
					   placeholder="Enter aggressiveDelete (true || false)"
					   data-ng-model="defaultCacheOptions.storageMode">
				"default"
				"{{info.storageMode}}"

			info().cacheFlushInterval

				<input type="text" data-ng-if="$first && editingDefaultCache"
					   placeholder="Enter cacheFlushInterval (ms)"
					   data-ng-model="defaultCacheOptions.cacheFlushInterval">
				{{info.cacheFlushInterval | milliseconds}}

				get("<input type="text" data-ng-model="selectedKey" data-ng-change="get()"
							style="width: 40px;"/>")

				{{selectedValues[index]}}

			keySet()

			keys()

$angularCacheFactory

				method
				output

				info()

				keySet()


text:
Reports if statements that can be simplified to a single assignment,
return, or assert statement.

Example:

  if (foo()) {
    return true;
  } else {
    return false;
  }

After the quick-fix is applied:

  return foo();

Configure the inspection:

Use the Ignore chained 'if' statements  option if want to hide a warning for chained if statements.

For example, in the following code the warning will be hidden, but the quick-fix will still be available:

  if (condition1) return true;
  if (condition2) return false;
  return true;

Note that replacing if (isTrue()) assert false; with assert isTrue(); may change the program semantics
  when asserts are disabled if condition has side effects.
  Use the Ignore 'if' statements with trivial 'assert' option if you want to hide a warning for if statements
  containing only assert statement in their bodies.


text:
package com.kind.samples.netty.telnet;

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * Handles a client-side channel.
 */
@Sharable
public class TelnetClientHandler extends SimpleChannelInboundHandler<String> {

    protected void messageReceived(ChannelHandlerContext ctx, String msg) {
        System.err.println(msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg)
            throws Exception {
        // TODO Auto-generated method stub

    }
}


text:
<?php

namespace Feeld\Display;

/**
 * Generated by PHPUnit_SkeletonGenerator on 2016-01-24 at 16:35:41.
 */
class NoDisplayTest extends \PHPUnit_Framework_TestCase {

    /**
     * @var NoDisplay
     */
    protected $object;

    /**
     * Sets up the fixture, for example, opens a network connection.
     * This method is called before a test is executed.
     */
    protected function setUp() {
        $this->object = new NoDisplay;
    }

    /**
     * Tears down the fixture, for example, closes a network connection.
     * This method is called after a test is executed.
     */
    protected function tearDown() {

    }

    /**
     * @covers Feeld\Display\NoDisplay::__toString
     * @covers Feeld\Display\NoDisplay::informAboutStructure
     */
    public function test__toString() {
        $this->assertEmpty((string)$this->object);
        $this->assertEmpty($this->object->__toString());
        $this->object->informAboutStructure(new \Feeld\Field\Select(new \Feeld\DataType\URL()));
        $this->assertEmpty((string)$this->object);
        $this->assertEmpty($this->object->__toString());
    }
}


text:
({
    callGlobalMethodInComponentWithDefaultAccess: function(component, event, helper){
    	component.find("componentWithDefaultAccess").globalMethod();
    },

    callPublicMethodInComponentWithDefaultAccess: function(component, event, helper){
    	component.find("componentWithDefaultAccess").publicMethod();
    },

    callPrivateMethodInComponentWithDefaultAccess: function(component, event, helper){
    	component.find("componentWithDefaultAccess").privateMethod();
    },

    setGlobalAttributeInComponentWithDefaultAccess: function(component, event, helper){
    	component.find("componentWithDefaultAccess").set("v.globalAttribute", "new global");
    },

    setPublicAttributeInComponentWithDefaultAccess: function(component, event, helper){
    	component.find("componentWithDefaultAccess").set("v.publicAttribute", "new public");
    },

    setPrivateAttributeInComponentWithDefaultAccess: function(component, event, helper){
    	component.find("componentWithDefaultAccess").set("v.privateAttribute", "new private");
    },
})


text:
using System;
using System.IO;

public class GeometryDumper {
	public static void DumpFigure(Figure figure, SurfaceProperties surfaceProperties, DirectoryInfo figureDestDir) {
		var refinementDirectory = figureDestDir.Subdirectory("refinement");

		GeometryDumper dumper = new GeometryDumper(figure, surfaceProperties, refinementDirectory);
		dumper.DumpRefinement();
	}

	private readonly Figure figure;
	private readonly SurfaceProperties surfaceProperties;
	private readonly DirectoryInfo refinementDirectory;

	private GeometryDumper(Figure figure, SurfaceProperties surfaceProperties, DirectoryInfo refinementDirectory) {
		this.figure = figure;
		this.surfaceProperties = surfaceProperties;
		this.refinementDirectory = refinementDirectory;
	}

	private void DumpControl() {
		var targetDirectory = refinementDirectory.Subdirectory("control");
		if (targetDirectory.Exists) {
			return;
		}

		targetDirectory.Create();
		targetDirectory.File("surface-map.array").WriteArray(figure.Geometry.SurfaceMap);
	}

	private void DumpRefinementLevel(int level) {
		var targetDirectory = refinementDirectory.Subdirectory("level-" + level);
		if (targetDirectory.Exists) {
			return;
		}

		Console.WriteLine("Dumping refined geometry level {0}...", level);

		MultisurfaceQuadTopology topology = figure.Geometry.AsTopology();

		var refinementResult = topology.Refine(level);

		targetDirectory.Create();
		SubdivisionMeshPersistance.Save(targetDirectory, refinementResult.Mesh);
		targetDirectory.File("control-face-map.array").WriteArray(refinementResult.ControlFaceMap);
	}

	private void DumpRefinement() {
		DumpControl();

		DumpRefinementLevel(0);

		if (surfaceProperties.SubdivisionLevel != 0) {
			DumpRefinementLevel(surfaceProperties.SubdivisionLevel);
		}
    }
}


text:
from __future__ import unicode_literals

from django.db import models, migrations
from decimal import Decimal

class Migration(migrations.Migration):

    dependencies = [
        ('core', '0051_generalledgeraccount_balance_updated_at'),
    ]

    operations = [
        migrations.AddField(
            model_name='generalledgerentry',
            name='ledger_balance_increment',
            field=models.DecimalField(default=Decimal('0'), max_digits=18, decimal_places=2),
        ),
        migrations.AddField(
            model_name='generalledgerentry',
            name='meta',
            field=models.TextField(null=True, editable=False),
        ),
        migrations.AddField(
            model_name='generalledgerentry',
            name='notes',
            field=models.TextField(null=True, editable=False),
        ),
    ]


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/action_change_username" android:title="@string/action_change_username" />
</menu>


text:
package org.apache.tika.eval.tokens;

import java.util.Arrays;

import org.apache.commons.math3.stat.descriptive.SummaryStatistics;

public class TokenStatistics {

    private final int totalTokens;
    private final int totalUniqueTokens;
    private final TokenIntPair[] topN;
    private final double entropy;
    private final SummaryStatistics summaryStatistics;

    public TokenStatistics(int totalUniqueTokens, int totalTokens,
                           TokenIntPair[] topN,
                           double entropy, SummaryStatistics summaryStatistics) {
        this.totalUniqueTokens = totalUniqueTokens;
        this.totalTokens = totalTokens;
        this.topN = topN;
        this.entropy = entropy;
        this.summaryStatistics = summaryStatistics;
    }

    public int getTotalTokens() {

        return totalTokens;
    }

    public int getTotalUniqueTokens() {
        return totalUniqueTokens;
    }

    public TokenIntPair[] getTopN() {
        return topN;
    }

    public double getEntropy() {
        return entropy;
    }

    public SummaryStatistics getSummaryStatistics() {
        return summaryStatistics;
    }

    @Override
    public String toString() {
        return "TokenStatistics{" +
                "totalTokens=" + totalTokens +
                ", totalUniqueTokens=" + totalUniqueTokens +
                ", topN=" + Arrays.toString(topN) +
                ", entropy=" + entropy +
                ", summaryStatistics=" + summaryStatistics +
                '}';
    }

    @Override
    public boolean equals(Object o) {

        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        TokenStatistics that = (TokenStatistics) o;

        if (totalTokens != that.totalTokens) return false;
        if (totalUniqueTokens != that.totalUniqueTokens) return false;
        if (!doubleEquals(that.entropy, entropy)) return false;
        // Probably incorrect - comparing Object[] arrays with Arrays.equals
        if (!Arrays.equals(topN, that.topN)) return false;

        SummaryStatistics thatS = ((TokenStatistics) o).summaryStatistics;
        if (summaryStatistics.getN() != thatS.getN()) return false;

        //if both have n==0, don't bother with the stats
        if (summaryStatistics.getN() ==0L) return true;
        //TODO: consider adding others...
        if (!doubleEquals(summaryStatistics.getGeometricMean(), thatS.getGeometricMean())) return false;
        if (!doubleEquals(summaryStatistics.getMax(), thatS.getMax())) return false;
        if (!doubleEquals(summaryStatistics.getMean(), thatS.getMean())) return false;
        if (!doubleEquals(summaryStatistics.getMin(), thatS.getMin())) return false;
        if (!doubleEquals(summaryStatistics.getSum(), thatS.getSum())) return false;
        if (!doubleEquals(summaryStatistics.getStandardDeviation(), thatS.getStandardDeviation())) return false;
        return true;
    }

    @Override
    public int hashCode() {
        int result;
        long temp;
        result = (int) (totalTokens ^ (totalTokens >>> 32));
        result = 31 * result + (int) (totalUniqueTokens ^ (totalUniqueTokens >>> 32));
        result = 31 * result + Arrays.hashCode(topN);
        temp = Double.doubleToLongBits(entropy);
        result = 31 * result + (int) (temp ^ (temp >>> 32));
        result = 31 * result + summaryStatistics.hashCode();
        return result;
    }

    private static boolean doubleEquals(double a, double b) {
        return doubleEquals(a, b, 0.000000000001d);
    }

    private static boolean doubleEquals(double a, double b, double epsilon) {
        return a == b ? true : Math.abs(a - b) < epsilon;
    }

}


text:
from numpy import pi
import pp
from pp.components import taper
from pp.components import bend_circular
from pp.components import waveguide
from pp.routing.manhattan import round_corners
from pp.config import WG_EXPANDED_WIDTH, TAPER_LENGTH
from pp.component import Component
from typing import Callable

@pp.autoname
def delay_snake(
    total_length: float = 160000.0,
    L0: float = 2350.0,
    n: int = 5,
    taper: Callable = taper,
    bend_factory: Callable = bend_circular,
    bend_radius: float = 10.0,
    straight_factory: Callable = waveguide,
    wg_width: float = 0.5,
) -> Component:
    """ Snake input facing west
    Snake output facing east

    Args:
        total_length:
        L0:
        n: number of loops
        taper:
        bend_factory
        bend_radius
        straight_factory
        wg_width

    .. code::

       | L0 |    L2        |

            ->-------------|
                           | pi * radius
       |-------------------|
       |
       |------------------->

       |        DL         |

    .. plot::
      :include-source:

      import pp

      c = pp.c.delay_snake(L0=5, total_length=1600, n=2)
      pp.plotgds(c)

    """
    epsilon = 0.1
    R = bend_radius
    bend90 = bend_factory(radius=R, width=wg_width)
    DL = (total_length + L0 - n * (pi * R + epsilon)) / (2 * n + 1)
    L2 = DL - L0
    assert (
        L2 > 0
    ), "Snake is too short: either reduce L0, increase the total length,\
    or decrease n"

    y = 0
    path = [(0, y), (L2, y)]
    for i in range(n):
        y -= 2 * R + epsilon
        path += [(L2, y), (-L0, y)]
        y -= 2 * R + epsilon
        path += [(-L0, y), (L2, y)]

    path = [(round(_x, 3), round(_y, 3)) for _x, _y in path]

    component = pp.Component()
    if taper:
        if callable(taper):
            _taper = taper(
                width1=wg_width, width2=WG_EXPANDED_WIDTH, length=TAPER_LENGTH
            )
        else:
            _taper = taper
    snake = round_corners(path, bend90, straight_factory, taper=_taper)
    component.add(snake)
    component.ports = snake.ports

    pp.port.auto_rename_ports(component)
    return component

if __name__ == "__main__":
    c = delay_snake()
    pp.show(c)


text:
<link rel="import" href="components/core-toolbar/core-toolbar.html">
<link rel="import" href="components/core-selector/core-selector.html">
<link rel="import" href="components/paper-icon-button/paper-icon-button.html">
<link rel="import" href="components/paper-fab/paper-fab.html">
<link rel="import" href="components/core-icons/image-icons.html">

<link rel="import" href="templates/fieldquest-question-single-select-item.html">
<link rel="import" href="templates/fieldquest-question-single-select-item-autocomplete.html">
<link rel="import" href="templates/fieldquest-question-date-picker.html">
<link rel="import" href="templates/fieldquest-question-multi-dropdown.html">

<link rel="import" href="templates/fieldquest-question-image-picker.html">
<link rel="import" href="templates/fieldquest-question-multiline-input.html">
<link rel="import" href="templates/fieldquest-question-geolocator.html">

<link rel="import" href="fieldquest-status-bar.html">

<polymer-element name="fieldquest-questions" attributes="allAnswers survey answers avatar wide" vertical layout>
<template>

  <link rel="stylesheet" href="fieldquest-questions.css">

      <core-toolbar class="theme-bg" hero-id="punch-bottom" hero?="{{parentElement.selected !== 'empty'}}">

{{question.question}}

      </core-toolbar>

        <core-selector id="questionViews" notap selected="{{question.type}}" cross-fade-delayed on-question-answered="{{questionAnswered}}" on-question-next="{{questionDone}}" on-core-select="{{selectionChangeComplete}}">

            <fieldquest-question-single-select-item name="single-select-item"></fieldquest-question-single-select-item>
            <fieldquest-question-single-select-item-autocomplete name="single-select-item-autocomplete"></fieldquest-question-single-select-item-autocomplete>
            <fieldquest-question-date-picker name="date-picker"></fieldquest-question-date-picker>
            <fieldquest-question-multi-dropdown name="multi-dropdown"></fieldquest-question-multi-dropdown>

            <fieldquest-question-image-picker name="image-picker"></fieldquest-question-image-picker>
            <fieldquest-question-multiline-input name="multiline-input"></fieldquest-question-multiline-input>
            <fieldquest-question-geolocator name="geolocator" wide="{{wide}}"></fieldquest-question-geolocator>
        </core-selector>

      <paper-fab class="check-button-back {{ {show: !firstQuestion} | tokenList }}" icon="image:navigate-before" on-tap="{{questionPrev}}"></paper-fab>
      <paper-fab class="check-button {{ {hide: lastQuestion} | tokenList }}" icon="image:navigate-next" on-tap="{{questionDone}}"></paper-fab>

    <fieldquest-status-bar class="{{ {wide: wide} | tokenList }}" answers="{{answers}}" survey="{{survey}}" index="{{index}}" wide="{{wide}}" actionIcon="done" slide-up?="{{parentElement.selected === 'questions'}}" on-do-action="{{surveyDone}}"></fieldquest-status-bar>
</template>

</polymer-element>