text:
<?php

namespace CgmConfigAdmin\Form;

use ZfcBase\Form\ProvidesEventsForm;
use CgmConfigAdmin\Model\ConfigGroup;
use CgmConfigAdmin\Model\ConfigOption;
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputProviderInterface;
use Zend\Form\Element\Csrf as CsrfElement;
use Zend\Form\Element\Button as ButtonElement;
use Zend\Validator\Explode as ExplodeValidator;
use Zend\Validator\InArray as InArrayValidator;
use Zend\Validator\ValidatorPluginManager;

class ConfigOptionsForm extends ProvidesEventsForm
{
    // Maps config option types to elements
    protected static $elementMappings = array(
        'color'         => 'Zend\Form\Element\Color',
        'date'          => 'Zend\Form\Element\Date',
        'datetimelocal' => 'Zend\Form\Element\DateTimeLocal',
        'email'         => 'Zend\Form\Element\Email',
        'month'         => 'Zend\Form\Element\Month',
        'multicheckbox' => 'Zend\Form\Element\MultiCheckbox',
        'number'        => 'Zend\Form\Element\Number',
        'password'      => 'Zend\Form\Element\Password',
        'radio'         => 'Zend\Form\Element\Radio',
        'range'         => 'Zend\Form\Element\Range',
        'select'        => 'Zend\Form\Element\Select',
        'text'          => 'Zend\Form\Element\Text',
        'textarea'      => 'Zend\Form\Element\Textarea',
        'time'          => 'Zend\Form\Element\Time',
        'url'           => 'Zend\Form\Element\Url',
        'week'          => 'Zend\Form\Element\Week',
    );

    /**
     * @var ValidatorPluginManager
     */
    protected $validatorPluginManager;

    /**
     * @param  array            $groups  Optional array of ConfigGroups
     * @param  null|int|string  $name    Optional name for the form
     * @param  array            $options Optional array of options
     */
    public function __construct(array $groups = array(), $name = null, array $options = array())
    {
        $isPreviewEnabled = true;
        if (isset($options['preview_enabled'])) {
            $isPreviewEnabled = $options['preview_enabled'];
            unset($options['preview_enabled']);
        }

        parent::__construct($name, $options);
        $this->filter = new InputFilter();

        $this->setAttribute('class', 'form-horizontal');

        if (!empty($groups)) {
            $this->addConfigGroups($groups);
        }

        $this->addActionButtons($isPreviewEnabled);

        $csrf = new CsrfElement('csrf');
        $csrf->setCsrfValidatorOptions(array('timeout' => null));
        $this->add($csrf);
    }

    /**
     * @param  boolean $enabled
     * @return ConfigOptionsForm
     */
    public function setIsPreviewEnabled($enabled)
    {
        return $this->addActionButtons($enabled);
    }

    /**
     * @param  boolean $isPreviewEnabled
     * @return ConfigOptionsForm
     */
    public function addActionButtons($isPreviewEnabled = true)
    {
        $this->remove('reset');
        $this->remove('preview');
        $this->remove('save');

        if ($isPreviewEnabled) {
            $resetBtn = new ButtonElement('reset');
            $resetBtn
                ->setLabel('Reset')
                ->setAttribute('type', 'submit')
                ->setValue('1');
            $this->add($resetBtn);

            $previewBtn = new ButtonElement('preview');
            $previewBtn
                ->setLabel('Preview')
                ->setAttribute('type', 'submit')
                ->setValue('1');
            $this->add($previewBtn);
        }

        $saveBtn = new ButtonElement('save');
        $saveBtn
            ->setLabel('Save')
            ->setAttribute('type', 'submit')
            ->setValue('1');
        $this->add($saveBtn);

        return $this;
    }

    /**
     * @param  array $groups
     * @return ConfigOptionsForm
     */
    public function addConfigGroups(array $groups)
    {
        // Add fieldsets for all defined groups
        usort($groups, function ($a, $b) {
            return strnatcasecmp($a->getSort(), $b->getSort());
        });
        foreach ($groups as $groupId => $configGroup) {
            $this->add($this->createConfigGroupElementSpec($configGroup));
            $this->filter->add(
                $this->createConfigGroupInputFilterSpec($configGroup),
                $configGroup->getId()
            );
        }
        return $this;
    }

    /**
     * @return int
     */
    public function getNumFieldsets()
    {
        return count($this->fieldsets);
    }

    /**
     * Create a form element spec from a ConfigGroup
     *
     * @return array
     */
    protected function createConfigGroupElementSpec(ConfigGroup $configGroup)
    {
        $elementSpec = array();

        $elementSpec['type'] = 'Zend\Form\Fieldset';
        $elementSpec['name'] = $configGroup->getId();
        $elementSpec['options']['label'] = $configGroup->getLabel();

        foreach ($configGroup->getConfigOptions() as $id => $configOption) {
            $elementSpec['elements'][]['spec'] = $this->createConfigOptionElementSpec($configOption);
        }

        return $elementSpec;
    }

    /**
     * Create a form element spec from a ConfigOption
     *
     * @return array
     */
    protected function createConfigOptionElementSpec(ConfigOption $configOption)
    {
        $configOption->prepare();
        $elementSpec = array();

        $type = $configOption->getInputType();
        $elementSpec['type'] = (array_key_exists($type, self::$elementMappings))
            ? self::$elementMappings[$type] : $type;

        $elementSpec['name']             = $configOption->getId();
        $elementSpec['options']['label'] = $configOption->getLabel();

        // Value
        if (null !== ($value = $configOption->getValue())) {
            $elementSpec['attributes']['value'] = $value;
        }

        // Value Options
        if (null !== ($valueOptions = $configOption->getValueOptions())) {
            $elementSpec['options']['value_options'] = $valueOptions;
        }

        return $elementSpec;
    }

    /**
     * Create an input filter spec from a ConfigGroup
     *
     * @param  ConfigGroup $configGroup
     * @return array
     */
    protected function createConfigGroupInputFilterSpec(ConfigGroup $configGroup)
    {
        $inputFilters = array(
            'type' => 'Zend\InputFilter\InputFilter',
        );

        foreach ($configGroup->getConfigOptions() as $id => $configOption) {
            $inputFilters[$id] = $this->createConfigOptionInputFilterSpec(
                $configOption, $configGroup->getId()
            );
        }
        return $inputFilters;
    }

    /**
     * Create an input filter spec from a ConfigOption
     *
     * @param  ConfigOption $configOption
     * @return array
     */
    protected function createConfigOptionInputFilterSpec(ConfigOption $configOption, $groupId)
    {
        $element = $this->get($groupId)->get($configOption->getId());
        if ($element instanceof InputProviderInterface) {
            $inputSpec = $element->getInputSpecification();
        } else {
            $inputSpec = array();
            $inputSpec['name'] = $configOption->getId();
        }

        $inputSpec['required']    = $configOption->getRequired();
        $inputSpec['allow_empty'] = ! $configOption->getRequired();

        return $inputSpec;
    }

    /**
     * @return ValidatorPluginManager
     */
    public function getValidatorPluginManager()
    {
        if (!isset($this->validatorPluginManager)) {
            $this->setValidatorPluginManager(new ValidatorPluginManager());
        }
        return $this->validatorPluginManager;
    }

    /**
     * @param  ValidatorPluginManager $manager
     * @return ConfigOptionsForm
     */
    public function setValidatorPluginManager(ValidatorPluginManager $manager)
    {
        $this->validatorPluginManager = $manager;
        return $this;
    }

    /**
     * @static
     * @param array $mappings
     */
    public static function setElementMappings(array $mappings)
    {
        self::$elementMappings = $mappings;
    }

    /**
     * @static
     * @return array
     */
    public static function getElementMappings()
    {
        return self::$elementMappings;
    }
}


text:
title: Projects
permalink: "/projects/"
layout: nosidebar
---

redpajama_set_name: RedPajamaGithub


text:
type MongoID = number;

// MONGO ENTRY =============================================================================

interface Notebook {
  user: MongoID;                        // Reference to the User document
  lab: MongoID;                         // Reference to the Lab document
  completion: number;                   // % of questions answered, in range (0, 1)
  timestamps: number[];                 // Anti-cheating mechanism: every save point
  values: [{[row: string]: any}];       // Stored values, organized by section
}


text:
package org.midao.jdbc.examples.derby;

import org.midao.jdbc.core.MjdbcFactory;
import org.midao.jdbc.core.exception.MjdbcRuntimeException;
import org.midao.jdbc.core.handlers.input.named.MapInputHandler;
import org.midao.jdbc.core.handlers.output.RowCountOutputHandler;
import org.midao.jdbc.core.handlers.output.lazy.BeanLazyScrollUpdateOutputHandler;
import org.midao.jdbc.core.handlers.output.lazy.MapLazyScrollUpdateOutputHandler;
import org.midao.jdbc.core.service.QueryRunnerService;
import org.midao.jdbc.examples.Student;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 */
public class QueryOutputLazyScrollUpdateHandlerExample {
    public static void main(String[] args) throws SQLException {
        Connection conn = DerbyParameters.createConnection();

        QueryRunnerService runner = MjdbcFactory.getQueryRunner(conn);
        runner.setTransactionManualMode(true);

        try {
            runner.update("CREATE TABLE students ("
                    + "id INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),"
                    + "name VARCHAR(24) NOT NULL,"
                    + "address VARCHAR(1024)," + "CONSTRAINT primary_key PRIMARY KEY (id))");

            Map<String, Object> insertValues = null;

            for (int i = 0; i < 3; i++) {
                insertValues = new HashMap<String, Object>();
                insertValues.put("studentName", "Someone");

                MapInputHandler input = new MapInputHandler("INSERT INTO students (name) VALUES (:studentName)", insertValues);

                runner.update(input, new RowCountOutputHandler<Integer>());
                runner.commit();
            }

            MapInputHandler input = new MapInputHandler("SELECT * FROM students", null);

            MapLazyScrollUpdateOutputHandler lazyMapList = runner.query(input, new MapLazyScrollUpdateOutputHandler());

            BeanLazyScrollUpdateOutputHandler<Student> lazyBeanList = runner.query(input, new BeanLazyScrollUpdateOutputHandler<Student>(Student.class));

            int lazyMapListSize = 0;
            int lazeBeanListSize = 0;

            while (lazyMapList.hasNext() == true) {
                if (lazyMapList.getNext() != null) lazyMapListSize++;
            }

            // going to very beginning
            lazyMapList.moveRelative(-3);
            if (lazyMapList.hasPrev() == true ||
                    (Integer) lazyMapList.getCurrent().get("id") != 1) {

                throw new MjdbcRuntimeException("This never happened before, embarrassing.");
            }

            while (lazyBeanList.hasNext() == true) {
                if (lazyBeanList.getNext() != null) lazeBeanListSize++;
            }

            // going to very beginning
            lazyBeanList.moveRelative(-3);
            if (lazyBeanList.hasPrev() == true || lazyBeanList.getCurrent().getId() != 1) {

                throw new MjdbcRuntimeException("This never happened before, embarrassing.");
            }

            lazyMapList.close();
            lazyBeanList.close();

            System.out.println(String.format("Lazy loaded maps: %d and beans: %d", lazyMapListSize, lazeBeanListSize));
        } catch (SQLException ex) {
            ex.printStackTrace();
        } finally {
            runner.update("DROP TABLE students");
            runner.commit();
        }
    }
}


text:
"""
Module providing facilities for handling struct-like data.
"""

import abc
import struct
import warnings
from collections import defaultdict
from collections.abc import Iterable, Mapping

from pcapng import strictness as strictness
from pcapng._compat import namedtuple
from pcapng.exceptions import (
    BadMagic,
    CorruptedFile,
    PcapngLoadError,
    StreamEmpty,
    TruncatedFile,
)
from pcapng.flags import FlagBool, FlagEnum, FlagField, FlagUInt, FlagWord
from pcapng.utils import (
    pack_euiaddr,
    pack_ipv4,
    pack_ipv6,
    pack_macaddr,
    unpack_euiaddr,
    unpack_ipv4,
    unpack_ipv6,
    unpack_macaddr,
)

SECTION_HEADER_MAGIC = 0x0A0D0D0A
BYTE_ORDER_MAGIC = 0x1A2B3C4D
BYTE_ORDER_MAGIC_INVERSE = 0x4D3C2B1A

# Anything greater and we cannot safely read
# todo: add support for this!
CURRENT_SUPPORTED_VERSION = (1, 0)

INT_FORMATS = {8: "b", 16: "h", 32: "i", 64: "q"}

# Type name constants, to keep a list and prevent typos
TYPE_BYTES = "bytes"
TYPE_STRING = "string"
TYPE_IPV4 = "ipv4"
TYPE_IPV4_MASK = "ipv4+mask"
TYPE_IPV6 = "ipv6"
TYPE_IPV6_PREFIX = "ipv6+prefix"
TYPE_MACADDR = "macaddr"
TYPE_EUIADDR = "euiaddr"
TYPE_TYPE_BYTES = "type+bytes"
TYPE_EPBFLAGS = "epb_flags"
TYPE_OPT_CUSTOM_STR = "opt_custom_str"
TYPE_OPT_CUSTOM_BYTES = "opt_custom_bytes"

TYPE_U8 = "u8"  # Unsigned integer, 8 bits
TYPE_U16 = "u16"
TYPE_U32 = "u32"
TYPE_U64 = "u64"
TYPE_I8 = "i8"  # Signed integer, 8 bits
TYPE_I16 = "i16"
TYPE_I32 = "i32"
TYPE_I64 = "i64"

_numeric_types = {
    TYPE_U8: "B",
    TYPE_I8: "b",
    TYPE_U16: "H",
    TYPE_I16: "h",
    TYPE_U32: "I",
    TYPE_I32: "i",
    TYPE_U64: "Q",
    TYPE_I64: "q",
}

NRB_RECORD_END = 0
NRB_RECORD_IPv4 = 1
NRB_RECORD_IPv6 = 2

def read_int(stream, size, signed=False, endianness="="):
    """
    Read (and decode) an integer number from a binary stream.

    :param stream: an object providing a ``read()`` method
    :param size: the size, in bits, of the number to be read.
        Supported sizes are: 8, 16, 32 and 64 bits.
    :param signed: Whether a signed or unsigned number is required.
        Defaults to ``False`` (unsigned int).
    :param endianness: specify the endianness to use to decode the number,
        in the same format used by Python :py:mod:`struct` module.
        Defaults to '=' (native endianness). '!' means "network" endianness
        (big endian), '<' little endian, '>' big endian.
    :return: the read integer number
    """
    fmt = INT_FORMATS.get(size)
    fmt = fmt.lower() if signed else fmt.upper()
    assert endianness in "<>!="
    fmt = endianness + fmt
    size_bytes = size // 8
    data = read_bytes(stream, size_bytes)
    return struct.unpack(fmt, data)[0]

def write_int(number, stream, size, signed=False, endianness="="):
    """
    Write (and encode) an integer number to a binary stream.

    :param number: the integer number to write
    :param stream: an object providing a ``write()`` method
    :param size: the size, in bits, of the number to be written.
        Supported sizes are: 8, 16, 32 and 64 bits.
    :param signed: Whether a signed or unsigned number is required.
        Defaults to ``False`` (unsigned int).
    :param endianness: specify the endianness to use to encode the number,
        in the same format used by Python :py:mod:`struct` module.
        Defaults to '=' (native endianness). '!' means "network" endianness
        (big endian), '<' little endian, '>' big endian.

    """
    fmt = INT_FORMATS.get(size)
    fmt = fmt.lower() if signed else fmt.upper()
    assert endianness in "<>!="
    fmt = endianness + fmt
    write_bytes(stream, struct.pack(fmt, number))

def read_section_header(stream):
    """
    Read a section header block from a stream.

    .. note::
        The byte order magic will be removed from the returned data
        This is ok as we don't need it anymore once we determined
        the correct endianness of the section.

    :returns: a dict containing the ``'endianness'`` and ``'data'`` keys
        that will be used to construct a :py:mod:`~pcapng.blocks.SectionHeader`
        instance.
    """

    # Read the length as raw bytes, then keep for later (since we
    # don't know the section endianness yet, we cannot parse this)
    blk_len_raw = read_bytes(stream, 4)

    # Read the "byte order magic" and see which endianness reports
    # it correctly (should be 0x1a2b3c4d)
    byte_order_magic = read_int(stream, 32, False, ">")  # Default BIG
    if byte_order_magic == BYTE_ORDER_MAGIC:
        endianness = ">"  # BIG
    else:
        if byte_order_magic != BYTE_ORDER_MAGIC_INVERSE:
            # We got an invalid number..
            raise BadMagic(
                "Wrong byte order magic: got 0x{0:08X}, expected "
                "0x{1:08X} or 0x{2:08X}".format(
                    byte_order_magic, BYTE_ORDER_MAGIC, BYTE_ORDER_MAGIC_INVERSE
                )
            )
        endianness = "<"  # LITTLE

    # Now we can safely decode the block length from the bytes we read earlier
    blk_len = struct.unpack(endianness + "I", blk_len_raw)[0]

    # ..and we then just want to read the appropriate amount of raw data.
    # Exclude: magic, len, bom, len (16 bytes)
    payload_size = blk_len - (4 + 4 + 4 + 4)
    block_data = read_bytes_padded(stream, payload_size)

    # Double-check lenght at block end
    blk_len2 = read_int(stream, 32, False, endianness)
    if blk_len != blk_len2:
        raise CorruptedFile(
            "Mismatching block lengths: {0} and {1}".format(blk_len, blk_len2)
        )

    return {
        "endianness": endianness,
        "data": block_data,
    }

def read_block_data(stream, endianness):
    """
    Read block data from a stream.

    Each "block" is in the form:

    - 32bit integer indicating the size (including header and size)
    - block payload (the above-specified number of bytes minus 12)
    - 32bit integer indicating the size (again)

    :param stream: the stream from which to read data
    :param endianness: Endianness marker, one of '<', '>', '!', '='.
    """

    block_length = read_int(stream, 32, signed=False, endianness=endianness)
    payload_length = block_length - 12  # bytes
    block_data = read_bytes_padded(stream, payload_length)
    block_length2 = read_int(stream, 32, signed=False, endianness=endianness)
    if block_length != block_length2:
        raise CorruptedFile(
            "Mismatching block lengths: {0} and {1}".format(block_length, block_length2)
        )
    return block_data

def read_bytes(stream, size):
    """
    Read the given amount of raw bytes from a stream.

    :param stream: the stream from which to read data
    :param size: the size to read, in bytes
    :returns: the read data
    :raises: :py:exc:`~pcapng.exceptions.StreamEmpty` if zero bytes were read
    :raises: :py:exc:`~pcapng.exceptions.TruncatedFile` if 0 < bytes < size
        were read
    """

    if size == 0:
        return b""

    data = stream.read(size)
    if len(data) == 0:
        raise StreamEmpty("Zero bytes read from stream")
    if len(data) < size:
        raise TruncatedFile(
            "Trying to read {0} bytes, only got {1}".format(size, len(data))
        )
    return data

def write_bytes(stream, data):
    """
    Write the given amount of raw bytes to a stream.

    :param stream: the stream into which to write data
    :param data: the data to write
    """
    stream.write(data)

def read_bytes_padded(stream, size, pad_block_size=4):
    """
    Read the given amount of bytes from a stream, plus read and discard
    any necessary extra byte to align up to the pad_block_size-sized
    next block.

    :param stream: the stream from which to read data
    :param size: the size to read, in bytes
    :returns: the read data
    :raises: :py:exc:`~pcapng.exceptions.StreamEmpty` if zero bytes were read
    :raises: :py:exc:`~pcapng.exceptions.TruncatedFile` if 0 < bytes < size
        were read
    """

    if stream.tell() % pad_block_size != 0:
        raise RuntimeError("Stream is misaligned!")

    data = read_bytes(stream, size)
    padding = (pad_block_size - (size % pad_block_size)) % pad_block_size
    if padding > 0:
        read_bytes(stream, padding)
    return data

def write_bytes_padded(stream, data, pad_block_size=4):
    """
    Read the given amount of bytes from a stream, plus read and discard
    any necessary extra byte to align up to the pad_block_size-sized
    next block.

    :param stream: the stream from which to read data
    :param size: the size to read, in bytes
    :returns: the read data
    :raises: :py:exc:`~pcapng.exceptions.StreamEmpty` if zero bytes were read
    :raises: :py:exc:`~pcapng.exceptions.TruncatedFile` if 0 < bytes < size
        were read
    """

    write_bytes(stream, data)
    padding = (pad_block_size - (len(data) % pad_block_size)) % pad_block_size
    if padding > 0:
        write_bytes(stream, bytes([0] * padding))

class StructField(object):
    """Abstract base class for struct fields"""

    __metaclass__ = abc.ABCMeta
    __slots__ = []

    @abc.abstractmethod
    def load(self, stream, endianness, seen=None):
        pass

    def __repr__(self):
        return "{0}()".format(self.__class__.__name__)

    def __unicode__(self):
        return self.__repr__().encode("UTF-8")

    def encode_finish(self, stream, endianness):
        pass

class RawBytes(StructField):
    """
    Field containing a fixed-width amount of raw bytes

    :param size: field size, in bytes
    """

    __slots__ = ["size"]

    def __init__(self, size):
        self.size = size  # in bytes!

    def load(self, stream, endianness=None, seen=None):
        return read_bytes_padded(stream, self.size)

    def encode(self, value, stream, endianness=None):
        write_bytes_padded(stream, value)

    def __repr__(self):
        return "{0}(size={1!r})".format(self.__class__.__name__, self.size)

class IntField(StructField):
    """
    Field containing an integer number.

    :param size: number size, in bits. Currently supported
        are 8, 16, 32 and 64-bit integers
    :param signed: whether the number is a signed or unsigned
        integer. Defaults to False (unsigned)
    """

    __slots__ = ["size", "signed"]

    def __init__(self, size, signed=False):
        self.size = size  # in bits!
        self.signed = signed

    def load(self, stream, endianness, seen=None):
        number = read_int(stream, self.size, signed=self.signed, endianness=endianness)
        return number

    def encode(self, number, stream, endianness):
        if not isinstance(number, int):
            raise TypeError("'{}' is not numeric".format(number))
        write_int(number, stream, self.size, signed=self.signed, endianness=endianness)

    def __repr__(self):
        return "{0}(size={1!r}, signed={2!r})".format(
            self.__class__.__name__, self.size, self.signed
        )

class OptionsField(StructField):
    """
    Field containing some options.

    :param options_schema:
        Same as the ``schema`` parameter to :py:class:`Options` class
        constructor.
    """

    __slots__ = ["options_schema"]

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

    def load(self, stream, endianness, seen=None):
        options = read_options(stream, endianness)
        return Options(schema=self.options_schema, data=options, endianness=endianness)

    def encode(self, options, stream, endianness):
        write_options(stream, options)

    def __repr__(self):
        return "{0}({1!r})".format(self.__class__.__name__, self.options_schema)

class PacketBytes(StructField):
    """
    Field containing some "packet data", used in the Packet
    and EnhancedPacket blocks.

    The packet data is composed of three fields (returned in a tuple):

    - captured len (uint32)
    - packet len (uint32)
    - packet data (captured_len-sized binary data)
    """

    __slots__ = ["dependency"]

    def __init__(self, len_field):
        self.dependency = len_field

    def load(self, stream, endianness, seen=[]):
        try:
            length = seen[self.dependency]
        except TypeError:
            raise PcapngLoadError(
                "PacketBytes dependent on field '{0}' which wasn't passed".format(
                    self.dependency
                )
            )
        except KeyError:
            raise PcapngLoadError(
                "PacketBytes dependent on field '{0}' which was never found".format(
                    self.dependency
                )
            )
        return read_bytes_padded(stream, length)

    def encode(self, packet, stream, endianness=None):
        if not packet:
            raise ValueError("Packet invalid")
        write_bytes_padded(stream, packet)

class ListField(StructField):
    """
    A list field is a variable amount of fields of some other type.
    Used for packets containing multiple "items", such as
    :py:class:`~pcapng.blocks.NameResolution`.

    It will keep loading data using a subfield until a
    :py:exc:`~pcapng.exceptions.StreamEmpty` excaption is raised, indicating
    we reached the end of data (note that a sub-field might even "simulate"
    a stream end once it reaches some end marker in the file).

    Values are returned in a list.

    :param subfield: a :py:class:`StructField` sub-class instance to be
        used to read values from the stream.
    """

    __slots__ = ["subfield"]

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

    def load(self, stream, endianness, seen=None):
        return list(self._iter_load(stream, endianness))

    def _iter_load(self, stream, endianness):
        while True:
            try:
                yield self.subfield.load(stream, endianness)
            except StreamEmpty:
                return

    def encode(self, list_data, stream, endianness):
        for rec in list_data:
            self.subfield.encode(rec, stream, endianness)
        self.subfield.encode_finish(stream, endianness)

    def __repr__(self):
        return "{0}({1!r})".format(self.__class__.__name__, self.subfield)

class NameResolutionRecordField(StructField):
    """
    A name resolution record field contains an item of data used in
    the :py:class:`~pcapng.blocks.NameResolution` block.

    it is composed of three fields:

    - record type (uint16)
    - record length (uint16)
    - payload

    Accepted types are:

    - ``0x00`` - end marker
    - ``0x01`` - ipv4 address resolution
    - ``0x02`` - ipv6 address resolution

    In both cases, the payload is composed of a valid address in the
    selected IP version, followed by null-separated/terminated domain names.
    """

    __slots__ = []

    def load(self, stream, endianness, seen=None):
        record_type = read_int(stream, 16, False, endianness)
        record_length = read_int(stream, 16, False, endianness)

        if record_type == NRB_RECORD_END:
            raise StreamEmpty("End marker reached")

        data = read_bytes_padded(stream, record_length)

        if record_type == NRB_RECORD_IPv4:
            return {
                "type": record_type,
                "address": unpack_ipv4(data[:4]),
                "names": [x.decode() for x in data[4:].split(b"\x00") if x != b""],
            }

        if record_type == NRB_RECORD_IPv6:
            return {
                "type": record_type,
                "address": unpack_ipv6(data[:16]),
                "names": [x.decode() for x in data[16:].split(b"\x00") if x != b""],
            }

        return {"type": record_type, "raw": data}

    def encode(self, d, stream, endianness):
        if d["type"] == NRB_RECORD_END:
            # Don't let the user add records of this type.
            # We take care of it in `encode_finish()` below
            return

        write_int(d["type"], stream, 16, endianness=endianness)
        if d["type"] == NRB_RECORD_IPv4:
            raw = pack_ipv4(d["address"])
            raw += (b"\x00".join([s.encode() for s in d["names"]])) + b"\x00"
            write_int(len(raw), stream, 16, endianness=endianness)
            write_bytes_padded(stream, raw)
        elif d["type"] == NRB_RECORD_IPv6:
            raw = pack_ipv6(d["address"])
            raw += (b"\x00".join([s.encode() for s in d["names"]])) + b"\x00"
            write_int(len(raw), stream, 16, endianness=endianness)
            write_bytes_padded(stream, raw)
        else:
            write_int(len(d["raw"]), stream, 16, endianness=endianness)
            write_bytes_padded(stream, d["raw"])

    def encode_finish(self, stream, endianness):
        write_int(NRB_RECORD_END, stream, 16, endianness=endianness)
        write_int(0, stream, 16, endianness=endianness)

def read_options(stream, endianness):
    """
    Read "options" from an "options block" in a stream, until a
    ``StreamEmpty`` exception is caught, or an end marker is reached.

    Each option is composed by:

    - option_code (uint16)
    - value_length (uint16)
    - value (value_length-sized binary data)

    The end marker is simply an option with code ``0x0000`` and no payload
    """

    def _iter_read_options(stream, endianness):
        while True:
            try:
                option_code = read_int(stream, 16, False, endianness)
                option_length = read_int(stream, 16, False, endianness)

                if option_code == 0:  # End of options
                    return

                payload = read_bytes_padded(stream, option_length)
                yield option_code, payload

            except StreamEmpty:
                return

    return list(_iter_read_options(stream, endianness))

def write_options(stream, options):
    """
    Each option is composed by:

    - option_code (uint16)
    - value_length (uint16)
    - value (value_length-sized binary data)

    The end marker is simply an option with code ``0x0000``, length 0,
    and no payload
    """

    if not options:
        # Options are optional; if there are none we don't need opt_endofopt
        return

    for key in options:
        code = options._field_names[key]
        values = options.get_all_raw(key)
        if len(values) > 1 and not options.schema[code].multiple:
            strictness.problem(
                "writing repeated option {} '{}' not permitted by pcapng spec".format(
                    code, options._get_name_alias(code)
                )
            )
            if strictness.should_fix():
                values = values[:1]
        for value in values:
            write_int(code, stream, 16, False, options.endianness)
            write_int(len(value), stream, 16, False, options.endianness)
            write_bytes_padded(stream, value)
    # Write the end marker
    write_int(0, stream, 32, False, options.endianness)

class EPBFlags(FlagWord):
    """Class representing the epb_flags option on an EPB"""

    __slots__ = []

    def __init__(self, val=0):
        super(EPBFlags, self).__init__(
            [
                FlagField("inout", FlagEnum, 2, ("NA", "inbound", "outbound")),
                FlagField(
                    "casttype",
                    FlagEnum,
                    3,
                    ("NA", "unicast", "multicast", "broadcast", "promiscuous"),
                ),
                FlagField("fcslen", FlagUInt, 4),
                FlagField("reserved", FlagUInt, 7),
                FlagField("err_16", FlagBool),
                FlagField("err_17", FlagBool),
                FlagField("err_18", FlagBool),
                FlagField("err_19", FlagBool),
                FlagField("err_20", FlagBool),
                FlagField("err_21", FlagBool),
                FlagField("err_22", FlagBool),
                FlagField("err_23", FlagBool),
                FlagField("err_crc", FlagBool),
                FlagField("err_long", FlagBool),
                FlagField("err_short", FlagBool),
                FlagField("err_frame_gap", FlagBool),
                FlagField("err_frame_align", FlagBool),
                FlagField("err_frame_delim", FlagBool),
                FlagField("err_preamble", FlagBool),
                FlagField("err_symbol", FlagBool),
            ],
            nbits=32,
            initial=val,
        )

# Class representing a single option schema for Options.
# require code and name; by default, empty ftype, forbid multiples
Option = namedtuple(
    "Option", ("code", "name", "ftype", "multiple"), defaults=(None, False)
)

class Options(Mapping):
    """
    Wrapper object used to easily access the contents of an "options"
    field.

    Fields can be accessed either by numerical id or by name (if one was
    specified in the schema).

    .. note::

        When iterating the object (or calling :py:meth:`keys` /
        :py:meth:`iterkeys` / :py:meth:`viewkeys`) string keys will be
        returned if possible in place of numeric keys.  (The purpose of this
        is to achieve better readability, for example, when converting
        to a dictionary).

    :param schema:
        Definition of the known options: a list of Option objects.

        The following value types are currently supported:

        - ``string``: convert value to a unicode string, using utf-8 encoding
        - ``{u,i}{8,16,32,64}``: (un)signed integer of the specified length
        - ``ipv4``: a single ipv4 address [4 bytes]
        - ``ipv4+mask``: an ipv4 address followed by a netmask [8 bytes]
        - ``ipv6``: a single ipv6 address [16 bytes]
        - ``ipv6+prefix``: an ipv6 address followed by prefix length [17 bytes]
        - ``macaddr``: a mac address [6 bytes]
        - ``euiaddr``: a eui address [8 bytes]
        - ``epb_flags``: 32-bit bitmask as per pcapng spec section 4.3.1
        - ``type+bytes``: field where the first byte is a type, and
          the remainder is bytes
        - ``opt_custom_str`` and ``opt_custom_bytes``: 4 bytes of Private
          Enterprise Number, followed by str or bytes (see pcapng spec,
          section 3.5.1)

    :param data:
        Initial data for the options. A dict of ``code: value`` items.
        Items with the same code may be repeated; only the first one will be
        accessible using subscript ``options[code]``; the others can be
        accessed using :py:meth:`get_all` and related methods

    :param endianness:
        The current endianness of the section these options came from.
        Required in order to load numeric fields.
    """

    __slots__ = [
        "schema",
        "_field_names",
        "data",
        "endianness",
    ]

    def __init__(self, schema, data, endianness):
        self.schema = {}  # Schema of option fields: {<code>: Option(...)}
        self._field_names = {}  # Map names to codes
        self.data = defaultdict(list)  # option data, with numeric option IDs as keys
        self.endianness = endianness  # one of '<>!='

        # This is the default schema, common to all objects
        for item in [
            Option(0, "opt_endofopt"),
            Option(1, "opt_comment", TYPE_STRING, multiple=True),
            # The spec calls all these next options ``opt_custom`` --
            # I've renamed them here so they can be told apart
            Option(2988, "custom_str_safe", TYPE_OPT_CUSTOM_STR, multiple=True),
            Option(2989, "custom_bytes_safe", TYPE_OPT_CUSTOM_BYTES, multiple=True),
            Option(19372, "custom_str", TYPE_OPT_CUSTOM_STR, multiple=True),
            Option(19373, "custom_bytes", TYPE_OPT_CUSTOM_BYTES, multiple=True),
        ] + list(schema):
            if not isinstance(item, Option):
                raise TypeError("expected option, got '{}'".format(item))
            self.schema[item.code] = item
        self._field_names = {x.name: x.code for x in self.schema.values()}

        # Update raw data with current values
        self._update_data(data)

    # -------------------- Nice interface :) --------------------

    def __eq__(self, other):
        return self.data == other.data

    def __getitem__(self, name):
        code = self._resolve_name(name)
        if code not in self.data:
            # The defaultdict would create an empty entry if we just let this slide.
            # `tests/test_structs.py` expects a KeyError to be raised here instead.
            raise KeyError(name)
        return self.data[code][0]

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

    def __iter__(self):
        for key in self.data:
            yield self._get_name_alias(key)

    def __setitem__(self, name, value):
        # This also gets called for ``block.options[name] += value``
        # as if ``block.options[name] = block.options[name] + value``
        # which means that, if value is a string, each character gets added
        # separately. Workaround: wrap the string in [ ], or use ``add()``
        code = self._resolve_name(name)
        if isinstance(value, Iterable) and not isinstance(
            value, (str, bytes, bytearray)
        ):
            # We're being assigned a list/iterable, use its values for our list
            self.data[code] = list(value)
            self._check_multiples(code)
        else:
            # We're being assigned a single value, store as a one-item list
            self.data[code] = [value]

    def __delitem__(self, name):
        code = self._resolve_name(name)
        del self.data[code]

    def get_all(self, name):
        """Get all values for the given option"""
        code = self._resolve_name(name)
        return self.data[code]

    def get_raw(self, name):
        """Get raw value for the given option"""
        code = self._resolve_name(name)
        return self._encode_value(self.data[code][0], self.schema[code].ftype)

    def get_all_raw(self, name):
        """Get all raw values for the given option"""
        code = self._resolve_name(name)
        return [self._encode_value(x, self.schema[code].ftype) for x in self.data[code]]

    def iter_all_items(self):
        """
        Similar to :py:meth:`iteritems` but will yield a list of values
        as the second tuple field.
        """
        for key in self:
            yield key, self.get_all(key)

    def add(self, name, value):
        """Add a value to the given-named option"""
        code = self._resolve_name(name)
        self.data[code].append(value)
        self._check_multiples(code)

    def __repr__(self):
        args = dict(self.iter_all_items())
        name = self.__class__.__name__
        return "{0}({1!r})".format(name, args)

    # -------------------- Internal methods --------------------

    def _update_data(self, data):
        if data is None:
            return

        for code, value in data:
            self.data[code].append(self._decode(code, value))
            if len(self.data[code]) > 1 and not self.schema[code].multiple:
                try:
                    name = "{} '{}'".format(code, self.schema[code].name)
                except KeyError:
                    name = "{} (unknown)".format(code)
                # This code gets called when reading a file. We don't want
                # to potentially abort in this case, just warn
                strictness.warn(
                    "repeated option {} not permitted by pcapng spec".format(name)
                )

    def _check_multiples(self, code):
        """Check if a non-repeatable option is repeated"""
        if len(self.data[code]) > 1 and not self.schema[code].multiple:
            strictness.problem(
                "repeated option {} '{}' not permitted by pcapng spec".format(
                    code, self._get_name_alias(code)
                )
            )
            if strictness.should_fix():
                self.data[code] = self.data[code][:1]

    def _resolve_name(self, name):
        code = self._field_names.get(name, name)
        if code == 0:
            # opt_endofopt is special and should never be touched by the user
            raise KeyError(name)
        return code

    def _get_name_alias(self, code):
        if code in self.schema:
            return self.schema[code].name
        return code

    def _decode(self, code, value):
        code = self._resolve_name(code)
        if code in self.schema:
            return self._decode_value(value, self.schema[code].ftype)
        return value

    def _decode_all(self, code, values):
        code = self._resolve_name(code)
        if code in self.schema:
            return [
                self._decode_value(value, self.schema[code].ftype) for value in values
            ]
        return values

    def _decode_value(self, value, ftype):
        assert isinstance(value, (bytes, bytearray))

        if ftype is None:
            warnings.warn(
                DeprecationWarning(
                    'Field type should not be "None". Please explicitly '
                    "use TYPE_BYTES instead."
                )
            )
            return value

        if ftype == TYPE_BYTES:
            return value

        if hasattr(ftype, "__call__"):
            return ftype(value, self.endianness)

        if ftype == TYPE_STRING:
            return value.decode("utf-8")

        if ftype in ("str", "unicode"):
            warnings.warn(
                DeprecationWarning(
                    'The "{ftype}" field type is deprecated. Please use "string" '
                    "(TYPE_STRING) instead.".format(ftype=ftype)
                )
            )
            return value.decode("utf-8")

        if ftype in _numeric_types:
            fmt = self.endianness + _numeric_types[ftype]
            return struct.unpack(fmt, value)[0]

        if ftype == TYPE_IPV4:
            return unpack_ipv4(value)

        if ftype == TYPE_IPV4_MASK:
            return unpack_ipv4(value[:4]), unpack_ipv4(value[4:8])

        if ftype == TYPE_IPV6:
            return unpack_ipv6(value)

        if ftype == TYPE_IPV6_PREFIX:
            return (
                unpack_ipv6(value[:16]),
                struct.unpack(self.endianness + "B", value[16]),
            )

        if ftype == TYPE_MACADDR:
            return unpack_macaddr(value)

        if ftype == TYPE_EUIADDR:
            return unpack_euiaddr(value)

        if ftype == TYPE_TYPE_BYTES:
            return (value[0], value[1:])

        if ftype == TYPE_EPBFLAGS:
            fmt = self.endianness + _numeric_types[TYPE_U32]
            flg = struct.unpack(fmt, value)[0]
            return EPBFlags(flg)

        if ftype == TYPE_OPT_CUSTOM_STR:
            fmt = self.endianness + _numeric_types[TYPE_U32]
            return (struct.unpack(fmt, value[0:4])[0], value[4:].decode("utf-8"))

        if ftype == TYPE_OPT_CUSTOM_BYTES:
            fmt = self.endianness + _numeric_types[TYPE_U32]
            return (struct.unpack(fmt, value[0:4])[0], value[4:])

        raise ValueError("Unsupported field type: {0}".format(ftype))

    def _encode_value(self, value, ftype):

        if ftype is None:
            warnings.warn(
                DeprecationWarning(
                    'Field type should not be "None". Please explicitly '
                    "use TYPE_BYTES instead."
                )
            )
            assert isinstance(value, (bytes, bytearray))
            return value

        if ftype == TYPE_BYTES:
            assert isinstance(value, (bytes, bytearray))
            return value

        if hasattr(ftype, "__call__"):
            # TODO figure out how callable options work
            return ftype(value, self.endianness)

        if ftype == TYPE_STRING:
            return value.encode("utf-8")

        if ftype in ("str", "unicode"):
            warnings.warn(
                DeprecationWarning(
                    'The "{ftype}" field type is deprecated. Please use "string" '
                    "(TYPE_STRING) instead.".format(ftype=ftype)
                )
            )
            return value.encode("utf-8")

        if ftype in _numeric_types:
            fmt = self.endianness + _numeric_types[ftype]
            return struct.pack(fmt, value)

        if ftype == TYPE_IPV4:
            return pack_ipv4(value)

        if ftype == TYPE_IPV4_MASK:
            return pack_ipv4(value[0]) + pack_ipv4(value[1])

        if ftype == TYPE_IPV6:
            return pack_ipv6(value)

        if ftype == TYPE_IPV6_PREFIX:
            return pack_ipv6(value[0]) + value[1]

        if ftype == TYPE_MACADDR:
            return pack_macaddr(value)

        if ftype == TYPE_EUIADDR:
            return pack_euiaddr(value)

        if ftype == TYPE_TYPE_BYTES:
            return struct.pack("B", value[0]) + value[1]

        if ftype == TYPE_EPBFLAGS:
            fmt = self.endianness + _numeric_types[TYPE_U32]
            return struct.pack(fmt, int(value))

        if ftype == TYPE_OPT_CUSTOM_STR:
            fmt = self.endianness + _numeric_types[TYPE_U32]
            return struct.pack(fmt, value[0]) + value[1].encode("utf-8")

        if ftype == TYPE_OPT_CUSTOM_BYTES:
            fmt = self.endianness + _numeric_types[TYPE_U32]
            return struct.pack(fmt, value[0]) + value[1]

        raise ValueError("Unsupported field type: {0}".format(ftype))

def struct_decode(schema, stream, endianness="="):
    """
    Decode structured data from a stream, following a schema.

    :param schema:
        a list of three tuples: ``(name, field, default)``, where ``name`` is a
        string representing the attribute name, and ``field`` is an instance of
        a :py:class:`StructField` sub-class, providing a ``.load()`` method to
        be called on the stream to get the field value. ``default`` is used
        when manually instantiating a block, but is ignored here.

    :param stream:
        a file-like object, providing a ``.read()`` method, from which data
        will be read.

    :param endianness:
        endianness specifier, as accepted by Python struct module
        (one of ``<>!=``, defaults to ``=``).

    :return:
        a dictionary mapping the field names to decoded data
    """

    decoded = {}
    for name, field, default in schema:
        decoded[name] = field.load(stream, endianness=endianness, seen=decoded)
    return decoded

def block_decode(block, stream):
    return struct_decode(block.schema, stream, block.section.endianness)

def struct_encode(schema, obj, outstream, endianness="="):
    """
    Encode structured data to a stream.
    """
    for name, field, default in schema:
        field.encode(getattr(obj, name), outstream, endianness=endianness)


text:
package org.kie.workbench.common.stunner.core.graph.util;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Stream;

import org.kie.workbench.common.stunner.core.graph.Edge;
import org.kie.workbench.common.stunner.core.graph.Element;
import org.kie.workbench.common.stunner.core.graph.Graph;
import org.kie.workbench.common.stunner.core.graph.Node;
import org.kie.workbench.common.stunner.core.graph.content.definition.Definition;
import org.kie.workbench.common.stunner.core.graph.content.relationship.Child;
import org.kie.workbench.common.stunner.core.graph.content.view.View;
import org.kie.workbench.common.stunner.core.graph.processing.traverse.content.AbstractChildrenTraverseCallback;
import org.kie.workbench.common.stunner.core.graph.processing.traverse.content.ChildrenTraverseProcessor;

import static org.kie.workbench.common.stunner.core.graph.util.GraphUtils.getDockParent;
import static org.kie.workbench.common.stunner.core.graph.util.GraphUtils.getDockedNodes;
import static org.kie.workbench.common.stunner.core.graph.util.GraphUtils.isDockedNode;

public class SafeDeleteNodeProcessor {

    public interface Callback {

        void deleteCandidateConnector(final Edge<? extends View<?>, Node> edge);

        boolean deleteConnector(final Edge<? extends View<?>, Node> edge);

        void removeChild(final Element<?> parent,
                         final Node<?, Edge> candidate);

        void removeDock(final Node<?, Edge> parent,
                        final Node<?, Edge> candidate);

        void deleteCandidateNode(final Node<?, Edge> node);

        boolean deleteNode(final Node<?, Edge> node);

        default void moveChildToCanvasRoot(final Element<?> canvas, final Node<?, Edge> node) {
            // Nothing
        }
    }

    private final Set<String> processedConnectors = new HashSet<>();
    private final Node<Definition<?>, Edge> candidate;
    private final Graph graph;
    private final ChildrenTraverseProcessor childrenTraverseProcessor;
    private final boolean keepChildren;

    public SafeDeleteNodeProcessor(final ChildrenTraverseProcessor childrenTraverseProcessor,
                                   final Graph graph,
                                   final Node<Definition<?>, Edge> candidate) {
        this(childrenTraverseProcessor, graph, candidate, false);
    }

    public SafeDeleteNodeProcessor(final ChildrenTraverseProcessor childrenTraverseProcessor,
                                   final Graph graph,
                                   final Node<Definition<?>, Edge> candidate,
                                   final boolean keepChildren) {
        this.childrenTraverseProcessor = childrenTraverseProcessor;
        this.graph = graph;
        this.candidate = candidate;
        this.keepChildren = keepChildren;
    }

    @SuppressWarnings("unchecked")
    public void run(final Callback callback) {
        final Deque<Node<View, Edge>> nodes = createNodesDequeue();
        processedConnectors.clear();

        if (!keepChildren) {
            deleteChildren(callback, nodes);
        }

        // Process candidate's delete.
        processNode(candidate,
                    callback,
                    true);
    }

    Deque<Node<View, Edge>> createNodesDequeue() {
        return new ArrayDeque();
    }

    protected void deleteChildren(final Callback callback,
                                  final Deque<Node<View, Edge>> nodes) {
        childrenTraverseProcessor
                .setRootUUID(candidate.getUUID())
                .traverse(graph,
                          new AbstractChildrenTraverseCallback<Node<View, Edge>, Edge<Child, Node>>() {

                              @Override
                              public void startNodeTraversal(final Node<View, Edge> node) {
                                  super.startNodeTraversal(node);
                                  if (isDockedNode(node)) {
                                      //docked nodes will be handled on the #processNode
                                      return;
                                  }
                                  nodes.add(node);
                              }

                              @Override
                              public boolean startNodeTraversal(final List<Node<View, Edge>> parents,
                                                                final Node<View, Edge> node) {
                                  super.startNodeTraversal(parents,
                                                           node);
                                  if (isDockedNode(node)) {
                                      //docked nodes will be handled on the #processNode
                                      return true;
                                  }
                                  nodes.add(node);
                                  return true;
                              }
                          });

        // Process delete for children nodes
        nodes.descendingIterator().forEachRemaining(node -> processNode(node,
                                                                        callback,
                                                                        false));
    }

    @SuppressWarnings("unchecked")
    void processNode(final Node<?, Edge> node,
                     final Callback callback,
                     final boolean isTheCandidate) {
        //processing recursively docked nodes relative to the current node
        getDockedNodes(node).forEach(docked -> processNode(docked, callback, false));

        getDockParent(node).ifPresent(parent -> callback.removeDock(parent, node));

        Stream.concat(node.getOutEdges().stream(),
                      node.getInEdges().stream())
                .filter(e -> e.getContent() instanceof View)
                .forEach(e -> deleteConnector(callback,
                                              e,
                                              isTheCandidate));
        node.getInEdges().stream()
                .filter(e -> e.getContent() instanceof Child)
                .forEach(e -> callback.removeChild(e.getSourceNode(),
                                                   node));
        if (isTheCandidate) {
            callback.deleteCandidateNode(node);
        } else {
            callback.deleteNode(node);
        }
    }

    private void deleteConnector(final Callback callback,
                                 final Edge<? extends View<?>, Node> edge,
                                 final boolean isTheCandidate) {
        if (!processedConnectors.contains(edge.getUUID())) {
            if (isTheCandidate) {
                callback.deleteCandidateConnector(edge);
            } else {
                callback.deleteConnector(edge);
            }
            processedConnectors.add(edge.getUUID());
        }
    }
}


text:
package dcraft.ctp.stream;

import io.netty.buffer.ByteBuf;

import java.io.IOException;

import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;

import dcraft.ctp.f.FileDescriptor;
import dcraft.hub.Hub;
import dcraft.io.CyclingByteBufferOutputStream;
import dcraft.lang.op.OperationContext;
import dcraft.script.StackEntry;
import dcraft.util.FileUtil;
import dcraft.util.StringUtil;
import dcraft.xml.XElement;

public class TarStream extends BaseStream implements IStreamUp {
    protected CyclingByteBufferOutputStream bstream = null;
    protected TarArchiveOutputStream tstream = null;
    protected boolean archiveopenflag = false;
    protected boolean finalflag = false;
    protected String nameHint = null;
    protected String lastpath = null;

    public TarStream() {
    }

    public TarStream withNameHint(String v) {
    	this.nameHint = v;
    	return this;
    }

	@Override
	public void init(StackEntry stack, XElement el) {
		this.nameHint = stack.stringFromElement(el, "NameHint");
	}

	@Override
    public void close() {
		//System.out.println("Tar killed");	// TODO

    	if (this.tstream != null)
			try {
				this.tstream.close();
			}
    		catch (IOException x) {
			}

    	this.bstream = null;
    	this.tstream = null;

    	super.close();
    }

	// make sure we don't return without first releasing the file reference content
	@Override
	public ReturnOption handle(FileSlice slice) {
    	if (slice == FileSlice.FINAL) {
    		if (this.tstream == null)
        		return this.downstream.handle(slice);

    		this.finalflag = true;
    	}

    	// I don't think tar cares about folder entries at this stage - tar is for file content only
    	// folder scanning is upstream in the FileSourceStream and partners
    	// TODO try with ending / to file name
    	if ((slice.file != null) && slice.file.isFolder())
    		return ReturnOption.CONTINUE;

    	// init if not set for this round of processing
    	if (this.tstream == null) {
    		this.bstream = new CyclingByteBufferOutputStream();
            this.tstream = new TarArchiveOutputStream(this.bstream);
            this.tstream.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
    	}

    	ByteBuf in = slice.data;
        ByteBuf out = null;

        // always allow for a header (512) and/or footer (1024) in addition to content
        int sizeEstimate = (in != null) ? in.readableBytes() + 2048 : 2048;
        out = Hub.instance.getBufferAllocator().heapBuffer(sizeEstimate);

        this.bstream.installBuffer(out);

        // TODO if there is no output available to send and not EOF then just request more,
        // no need to send a message that is empty and not EOF

        FileDescriptor blk = new FileDescriptor();

        FileSlice sliceout = FileSlice.allocate(blk, out, 0, false);

		if (StringUtil.isNotEmpty(this.lastpath)) {
			blk.setPath(this.lastpath);
		}
		else {
			if (StringUtil.isNotEmpty(this.nameHint))
				this.lastpath = "/" + this.nameHint + ".tar";
			else if ((slice.file != null) && slice.file.hasPath())
				this.lastpath = "/" + (StringUtil.isNotEmpty(this.nameHint) ? this.nameHint : slice.file.path().getFileName()) + ".tar";
			else
				this.lastpath = "/" + FileUtil.randomFilename() + ".tar";

			blk.setPath(this.lastpath);
		}

		blk.setModTime(System.currentTimeMillis());

    	if ((slice.file != null) && !this.archiveopenflag && !this.finalflag) {
    		TarArchiveEntry tentry = new TarArchiveEntry(slice.file.getPath().toString().substring(1), true);
    		tentry.setSize(slice.file.getSize());
    		tentry.setModTime(slice.file.getModTime());

    		try {
				this.tstream.putArchiveEntry(tentry);
			}
    		catch (IOException x) {
    			if (in != null)
    				in.release();

				out.release();
				OperationContext.get().getTaskRun().kill("Problem writing tar entry: " + x);
				return ReturnOption.DONE;
			}

    		this.archiveopenflag = true;
    	}

    	if (in != null)
			try {
				this.tstream.write(in.array(), in.arrayOffset(), in.writerIndex());
			}
			catch (IOException x) {
				in.release();
				out.release();
				OperationContext.get().getTaskRun().kill("Problem writing tar body: " + x);
				return ReturnOption.DONE;
			}

        if (slice.isEof()) {
        	try {
		        this.tstream.closeArchiveEntry();
			}
			catch (IOException x) {
    			if (in != null)
    				in.release();

				out.release();
				OperationContext.get().getTaskRun().kill("Problem closing tar entry: " + x);
				return ReturnOption.DONE;
			}

    		this.archiveopenflag = false;
        }

        if (in != null)
        	in.release();

    	if (slice == FileSlice.FINAL) {
    		sliceout.setEof(true);

        	try {
		        this.tstream.close();
			}
			catch (IOException x) {
				//in.release();
				out.release();
				OperationContext.get().getTaskRun().kill("Problem closing tar stream: " + x);
				return ReturnOption.DONE;
			}

    		this.tstream = null;
    		this.bstream = null;
    	}
    	else
    		this.bstream.uninstallBuffer();		// we are done with out forever, don't reference it

		System.out.println("tar sending: " + out.readableBytes());

		ReturnOption v = this.downstream.handle(sliceout);

       	if (!this.finalflag)
       		return v;

       	if (v == ReturnOption.CONTINUE)
    		return this.downstream.handle(FileSlice.FINAL);

       	return ReturnOption.DONE;
    }

    @Override
    public void read() {
    	if (this.finalflag) {
    		this.downstream.handle(FileSlice.FINAL);
    		return;
    	}

    	this.upstream.read();
    }
}


text:
package pv.com.pvcloudgo.vc.adapter;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;

import pv.com.pvcloudgo.R;
import pv.com.pvcloudgo.vc.view.ui.fragment.dummy.DummyContent.DummyItem;
import pv.com.pvcloudgo.vc.view.ui.fragment.interf.OnItemClickListener;

/**
 * {@link RecyclerView.Adapter} that can display a {@link DummyItem} and makes a call to the
 */
public class OMYOListRecyclerViewAdapter extends RecyclerView.Adapter<OMYOListRecyclerViewAdapter.ViewHolder> {

    private final List<DummyItem> mValues;
    private final OnItemClickListener mListener;

    public OMYOListRecyclerViewAdapter(List<DummyItem> items, OnItemClickListener listener) {
        mValues = items;
        mListener = listener;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_omyo_list, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
        holder.mItem = mValues.get(position);

        holder.mView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != mListener) {
                    // Notify the active callbacks interface (the activity, if the
                    // fragment is attached to one) that an item has been selected.
                    mListener.onItemClick(holder.getAdapterPosition());
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return mValues.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        public final View mView;
        public DummyItem mItem;

        public ViewHolder(View view) {
            super(view);
            mView = view;
        }

    }
}


text:
<!--
# license: Licensed to the Apache Software Foundation (ASF) under one
#         or more contributor license agreements.  See the NOTICE file
#         distributed with this work for additional information
#         regarding copyright ownership.  The ASF licenses this file
#         to you under the Apache License, Version 2.0 (the
#         "License"); you may not use this file except in compliance
#         with the License.  You may obtain a copy of the License at
#
#           http://www.apache.org/licenses/LICENSE-2.0
#
#         Unless required by applicable law or agreed to in writing,
#         software distributed under the License is distributed on an
#         "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
#         KIND, either express or implied.  See the License for the
#         specific language governing permissions and limitations
#         under the License.
-->

# cordova-plugin-legacy-whitelist

このプラグインは、コルドバ 4.0 のコルドバ 3.6 ホワイト リスト ポリシーを実装します。 安全な代わりに、コルドバ プラグインのホワイト リストを使用してください。

サポートされている: - cordova-android@4.0.0 - cordova-ios@4.0.0

## 使用法:

コルドバの以前のバージョンと同じように、 `<access>`タグを使用します。


text:
from .mg import MG
from flask import jsonify, request

class LineChart(MG):
    """Wrapper for MetricsGraphics Line plot.

        https://github.com/mozilla/metrics-graphics/wiki/Chart-Types
        The user must supply a Figure object. When a route_func
        is supplied, the dataframe and other options are ignored
        in favor of the endpoint function.

        Args:
            df (dataframe): input data.
            figure (mg.Figure): metricsgraphics figure object.
            x (str): name of the column corresponding to the x-axis.
            y (list(str)): name of the columns corresponding to the y-axis.
            title (str): title of the figure.
            description (str): description of the figure.
            init_params (dict): parameters used to initialize the figure.
            timeseries (bool): inidicates whether the plot is a timeseries.
            route_func (function): endpoint function.

    """
    def __init__(self, df, figure, x, y, title="Line Chart",
        description="Line Chart", init_params={}, timeseries=False,
        route_func=None):

        self.plot_opts = {
            "title": title,
            "description": description,
            "target": "#"+figure.chart_id,
            "x_accessor": "x",
            "y_accessor": "y",
            "init_params": init_params
        }
        for k, v in list(figure.get().items()):
            self.plot_opts[k] = v

        if not route_func:
            def get_data():
                args = {}
                for c in init_params:
                    if request.args.get(c):
                        args[c] = request.args[c]
                    else:
                        args[c] = init_params[c]
                return jsonify(LineChart.to_json(
                        self.apply_filters(df, args),
                        x,
                        y,
                        timeseries=timeseries
                    ))
            route_func = get_data

        super(LineChart, self).__init__(figure.chart_id, figure.url, self.plot_opts, route_func)

    @staticmethod
    def to_json(df, x, y, timeseries=False):
        """Format output for json response."""
        values = {k: [] for k in y}
        for i, row in df.iterrows():
            for yy in y:
                values[yy].append({
                    "x": row[x],
                    "y": row[yy]
                    })
        return {"result":  [values[k] for k in y], "date": timeseries}


text:
package com.wut.model.message;

import com.wut.model.map.MessageData;

public class WarningMessage extends MessageData { //

	public WarningMessage(int id, String name, String desc) {
		super(id, name, desc);
	}

}


text:
int ExitOnFail=1;
int DisplayFailMessage=1;

void FailMessage(char *msg)
{
  if(DisplayFailMessage)
     {
       fprintf(stderr,msg);
       fflush(stderr);
     }

   if(ExitOnFail)
      exit(0);
}

int I2CWrapperOpen(int BUS, int SlaveAddress)
    {
	  int handle;
	  char I2C_dev[256];

	  if(BUS < 0) return -1;
	  if(BUS > 1) return -1;

	  sprintf(I2C_dev,"/dev/i2c-%d", BUS);

	  handle = open(I2C_dev, O_RDWR);
	  if(handle < 0)
	   {
	     FailMessage("Failed to open the i2c bus \n");
	    return -1;
	   }
	  if(I2CWrapperSlaveAddress(handle,SlaveAddress) < 0)
	   {
	      close(handle);
		  return -2;
	   }
	   return handle;
	}

////////////////////////////////////   I2CWrapperSlaveAddress
//
//    Specify which Slave device you want to talk to
//
//     inputs,
//
//     handle:   IO handle
//     SlaveAddress:
//
//    Return integer
//
//    0  ok
//    < 0 error
//

int I2CWrapperSlaveAddress(int handle, int SlaveAddress)
    {
       if(SlaveAddress < 3) return -1;
       if(SlaveAddress > 0x77)return -1;

	   if (ioctl(handle, I2C_SLAVE, SlaveAddress) < 0)
	    {
               FailMessage("Failed to acquire bus access and/or talk to slave.\n");
		return -1;
		}
        return 0; // ok
    }

////////////////////////////////////   I2CWrapperReadBlock
//
//    Read N byte from the I2C (maximum of 31 bytes possible)
//
//     inputs,
//
//     handle:   IO handle
//     cmd:  Specify which is the device command (more or less the device function or register)
//     size:     Number of bytes to read
//     array:    the pointer array
//
//    Return integer
//
//    number of byte reed.
//    < 0 error
//
int I2CWrapperReadBlock(int handle, unsigned char cmd, unsigned char  size,  void * array)
{
struct i2c_smbus_ioctl_data  blk;
union i2c_smbus_data i2cdata;

  blk.read_write=1;
  blk.command=cmd;
  blk.size= I2C_SMBUS_I2C_BLOCK_DATA;
  blk.data=&i2cdata;
  i2cdata.block[0]=size;

  if(ioctl(handle,I2C_SMBUS,&blk)<0){
    FailMessage("Unable to Read  I2C data\n");
    return -1;
    }

 memcpy(array,&i2cdata.block[1],size);
 return   i2cdata.block[0];
}

////////////////////////////////////   I2CWrapperReadByte
//
//    Read 1 byte  from the I2C
//
//     inputs,
//
//     handle:   IO handle
//     cmd:  Specify which is the device command (more or less the device function or register)
//
//    Return  byte data (in int),  if <0 error
//
//    Check I2CWrapperErrorFlag for error
//
int  I2CWrapperReadByte(int handle, unsigned char cmd)
{
  struct i2c_smbus_ioctl_data  blk;
  union i2c_smbus_data i2cdata;

  blk.read_write=1;
  blk.command=cmd;
  blk.size=I2C_SMBUS_BYTE_DATA;
  blk.data=&i2cdata;

  if(ioctl(handle,I2C_SMBUS,&blk)<0){
    FailMessage("Unable to Read  I2C data\n");
    return -1;
    }
  return   ((int) i2cdata.byte);
}

////////////////////////////////////   I2CWrapperWriteByte
//
//    Write 1 byte  to the I2C device
//
//     inputs,
//
//     handle:   IO handle
//     cmd:  Specify which is the device command (more or less the device function or register)
//     value:    byte value
//    Return   number of byte written if <0 error
//
//    Check I2CWrapperErrorFlag for error
//
int I2CWrapperWriteByte(int handle,unsigned char cmd, unsigned char value)
{
 struct i2c_smbus_ioctl_data  blk;
 union i2c_smbus_data i2cdata;

 i2cdata.byte=value;
 blk.read_write=0;
 blk.command=cmd;
 blk.size=I2C_SMBUS_BYTE_DATA;
 blk.data= &i2cdata;

  if(ioctl(handle,I2C_SMBUS,&blk)<0){
    FailMessage("Unable to write I2C byte data\n");
    return -1;
    }
 return 1;
}

////////////////////////////////////   I2CWrapperReadWord
//
//    Read 2 bytes  from the I2C
//
//     inputs,
//
//     handle:   IO handle
//     cmd:  Specify which is the device command (more or less the device function or register)
//
//    Return  word data  in ( short long format), if < 0 error
//
//    Check I2CWrapperErrorFlag for error
//
int   I2CWrapperReadWord(int handle, unsigned char cmd)
{
 struct i2c_smbus_ioctl_data  blk;
 union i2c_smbus_data i2cdata;

 blk.read_write=1;
 blk.command=cmd;
 blk.size=I2C_SMBUS_WORD_DATA;
 blk.data=&i2cdata;

 if(ioctl(handle,I2C_SMBUS,&blk)<0){
    FailMessage("Unable to Read  I2C data\n");
    return -1;
    }
 return  (int) i2cdata.word;
}

////////////////////////////////////   I2CWrapperWriteWord
//
//    Write 2 bytes  to the I2C device
//
//     inputs,
//
//     handle:   IO handle
//     cmd:  Specify which is the device command (more or less the device function or register)
//     value:    byte value
//    Return   number of byte written if <0 error
//
//    Check I2CWrapperErrorFlag for error
//
int I2CWrapperWriteWord(int handle,unsigned char cmd, unsigned short value)
{
 struct i2c_smbus_ioctl_data  blk;
  union i2c_smbus_data i2cdata;

  i2cdata.word=value;
  blk.read_write=0;
  blk.command=cmd;
  blk.size=I2C_SMBUS_WORD_DATA;
  blk.data= &i2cdata;

  if(ioctl(handle,I2C_SMBUS,&blk)<0){
    FailMessage("Unable to write I2C data\n");
    return -1;
    }
 return 2;
}


text:
.class public final Landroid/widget/ActivityChooserModel$HistoricalRecord;
.super Ljava/lang/Object;
.source "ActivityChooserModel.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/widget/ActivityChooserModel;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x19
    name = "HistoricalRecord"
.end annotation

# instance fields
.field public final activity:Landroid/content/ComponentName;

.field public final time:J

.field public final weight:F

# direct methods
.method public constructor <init>(Landroid/content/ComponentName;JF)V
    .locals 0
    .parameter "activityName"
    .parameter "time"
    .parameter "weight"

    .prologue
    .line 886
    invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V

    .line 887
    iput-object p1, p0, Landroid/widget/ActivityChooserModel$HistoricalRecord;->activity:Landroid/content/ComponentName;

    .line 888
    iput-wide p2, p0, Landroid/widget/ActivityChooserModel$HistoricalRecord;->time:J

    .line 889
    iput p4, p0, Landroid/widget/ActivityChooserModel$HistoricalRecord;->weight:F

    .line 890
    return-void
.end method

.method public constructor <init>(Ljava/lang/String;JF)V
    .locals 1
    .parameter "activityName"
    .parameter "time"
    .parameter "weight"

    .prologue
    .line 876
    invoke-static {p1}, Landroid/content/ComponentName;->unflattenFromString(Ljava/lang/String;)Landroid/content/ComponentName;

    move-result-object v0

    invoke-direct {p0, v0, p2, p3, p4}, Landroid/widget/ActivityChooserModel$HistoricalRecord;-><init>(Landroid/content/ComponentName;JF)V

    .line 877
    return-void
.end method

# virtual methods
.method public equals(Ljava/lang/Object;)Z
    .locals 7
    .parameter "obj"

    .prologue
    const/4 v1, 0x1

    const/4 v2, 0x0

    .line 904
    if-ne p0, p1, :cond_1

    .line 927
    :cond_0
    :goto_0
    return v1

    .line 907
    :cond_1
    if-nez p1, :cond_2

    move v1, v2

    .line 908
    goto :goto_0

    .line 910
    :cond_2
    invoke-virtual {p0}, Ljava/lang/Object;->getClass()Ljava/lang/Class;

    move-result-object v3

    invoke-virtual {p1}, Ljava/lang/Object;->getClass()Ljava/lang/Class;

    move-result-object v4

    if-eq v3, v4, :cond_3

    move v1, v2

    .line 911
    goto :goto_0

    :cond_3
    move-object v0, p1

    .line 913
    check-cast v0, Landroid/widget/ActivityChooserModel$HistoricalRecord;

    .line 914
    .local v0, other:Landroid/widget/ActivityChooserModel$HistoricalRecord;
    iget-object v3, p0, Landroid/widget/ActivityChooserModel$HistoricalRecord;->activity:Landroid/content/ComponentName;

    if-nez v3, :cond_4

    .line 915
    iget-object v3, v0, Landroid/widget/ActivityChooserModel$HistoricalRecord;->activity:Landroid/content/ComponentName;

    if-eqz v3, :cond_5

    move v1, v2

    .line 916
    goto :goto_0

    .line 918
    :cond_4
    iget-object v3, p0, Landroid/widget/ActivityChooserModel$HistoricalRecord;->activity:Landroid/content/ComponentName;

    iget-object v4, v0, Landroid/widget/ActivityChooserModel$HistoricalRecord;->activity:Landroid/content/ComponentName;

    invoke-virtual {v3, v4}, Landroid/content/ComponentName;->equals(Ljava/lang/Object;)Z

    move-result v3

    if-nez v3, :cond_5

    move v1, v2

    .line 919
    goto :goto_0

    .line 921
    :cond_5
    iget-wide v3, p0, Landroid/widget/ActivityChooserModel$HistoricalRecord;->time:J

    iget-wide v5, v0, Landroid/widget/ActivityChooserModel$HistoricalRecord;->time:J

    cmp-long v3, v3, v5

    if-eqz v3, :cond_6

    move v1, v2

    .line 922
    goto :goto_0

    .line 924
    :cond_6
    iget v3, p0, Landroid/widget/ActivityChooserModel$HistoricalRecord;->weight:F

    invoke-static {v3}, Ljava/lang/Float;->floatToIntBits(F)I

    move-result v3

    iget v4, v0, Landroid/widget/ActivityChooserModel$HistoricalRecord;->weight:F

    invoke-static {v4}, Ljava/lang/Float;->floatToIntBits(F)I

    move-result v4

    if-eq v3, v4, :cond_0

    move v1, v2

    .line 925
    goto :goto_0
.end method

.method public hashCode()I
    .locals 8

    .prologue
    .line 894
    const/16 v0, 0x1f

    .line 895
    .local v0, prime:I
    const/4 v1, 0x1

    .line 896
    .local v1, result:I
    iget-object v2, p0, Landroid/widget/ActivityChooserModel$HistoricalRecord;->activity:Landroid/content/ComponentName;

    if-nez v2, :cond_0

    const/4 v2, 0x0

    :goto_0
    add-int/lit8 v1, v2, 0x1f

    .line 897
    mul-int/lit8 v2, v1, 0x1f

    iget-wide v3, p0, Landroid/widget/ActivityChooserModel$HistoricalRecord;->time:J

    iget-wide v5, p0, Landroid/widget/ActivityChooserModel$HistoricalRecord;->time:J

    const/16 v7, 0x20

    ushr-long/2addr v5, v7

    xor-long/2addr v3, v5

    long-to-int v3, v3

    add-int v1, v2, v3

    .line 898
    mul-int/lit8 v2, v1, 0x1f

    iget v3, p0, Landroid/widget/ActivityChooserModel$HistoricalRecord;->weight:F

    invoke-static {v3}, Ljava/lang/Float;->floatToIntBits(F)I

    move-result v3

    add-int v1, v2, v3

    .line 899
    return v1

    .line 896
    :cond_0
    iget-object v2, p0, Landroid/widget/ActivityChooserModel$HistoricalRecord;->activity:Landroid/content/ComponentName;

    invoke-virtual {v2}, Landroid/content/ComponentName;->hashCode()I

    move-result v2

    goto :goto_0
.end method

.method public toString()Ljava/lang/String;
    .locals 5

    .prologue
    .line 932
    new-instance v0, Ljava/lang/StringBuilder;

    invoke-direct {v0}, Ljava/lang/StringBuilder;-><init>()V

    .line 933
    .local v0, builder:Ljava/lang/StringBuilder;
    const-string v1, "["

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    .line 934
    const-string v1, "; activity:"

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    iget-object v2, p0, Landroid/widget/ActivityChooserModel$HistoricalRecord;->activity:Landroid/content/ComponentName;

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    .line 935
    const-string v1, "; time:"

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    iget-wide v2, p0, Landroid/widget/ActivityChooserModel$HistoricalRecord;->time:J

    invoke-virtual {v1, v2, v3}, Ljava/lang/StringBuilder;->append(J)Ljava/lang/StringBuilder;

    .line 936
    const-string v1, "; weight:"

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    new-instance v2, Ljava/math/BigDecimal;

    iget v3, p0, Landroid/widget/ActivityChooserModel$HistoricalRecord;->weight:F

    float-to-double v3, v3

    invoke-direct {v2, v3, v4}, Ljava/math/BigDecimal;-><init>(D)V

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    .line 937
    const-string v1, "]"

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    .line 938
    invoke-virtual {v0}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v1

    return-object v1
.end method


text:
import * as actions from './actions';

export default {
  [actions.setMobileOpened]: (state, action) => ({ ...state, mobileOpened: action.payload }),
  [actions.setSearchOpened]: (state, action) => ({ ...state, searchOpened: action.payload }),
  [actions.setSearchTerm]: (state, action) => ({ ...state, searchTerm: action.payload }),
};


text:
namespace led {

  void setup();
  void turnOn(uint8_t ledNumber);
  void turnOff(uint8_t ledNumber);
  void shiftOut();
}

#endif


text:
import React, { useEffect, useState } from 'react';
import Popover, { PopoverProps } from '@uiw/react-popover';
import Input, { InputProps } from '@uiw/react-input';
import Button from '@uiw/react-button';
import { IProps } from '@uiw/utils';
import formatter from '@uiw/formatter';
import { TimePickerTime, TimePickerTimeProps } from './Time';
import './style/index.less';

export * from './Panel';
export * from './Time';

export interface TimePickerProps<T>
  extends IProps,
    Omit<InputProps<T>, 'onChange' | 'value'> {
  value?: Date;
  format?: string;
  popoverProps?: PopoverProps;
  disabledHours?: TimePickerTimeProps['disabledHours'];
  precision?: TimePickerTimeProps['precision'];
  disabledMinutes?: TimePickerTimeProps['disabledMinutes'];
  disabledSeconds?: TimePickerTimeProps['disabledSeconds'];
  hideDisabled?: TimePickerTimeProps['hideDisabled'];
  allowClear?: boolean;
  disabled?: boolean;
  onChange?: (
    dataStr?: string,
    date?: Date | '',
    type?: TimePickerTimeProps['type'],
    num?: number,
    disableds?: number[],
  ) => void;
}

export default function TimePicker<T>(props: TimePickerProps<T>) {
  const {
    prefixCls = 'w-timepicker',
    className,
    disabled,
    value,
    format = 'HH:mm:ss',
    popoverProps,
    allowClear = true,
    onChange,
    disabledHours,
    disabledMinutes,
    disabledSeconds,
    hideDisabled,
    precision,
    ...inputProps
  } = props;
  const [date, setDate] = useState(props.value);
  useEffect(() => setDate(props.value), [props.value]);
  const timeProps = {
    disabledHours,
    disabledMinutes,
    disabledSeconds,
    hideDisabled,
    precision,
  };
  const inputValue = date ? formatter(format, date) : '';
  const datePickerTime = date || new Date();
  const _props: InputProps<T> = { ...inputProps, value: inputValue };
  if (allowClear && inputValue !== '' && !!inputValue) {
    _props.addonAfter = (
      <Button
        className={`${prefixCls}-close-btn`}
        icon="close"
        disabled={props.disabled}
        onClick={() => {
          setDate(undefined);
          onChange && onChange();
        }}
        size={props.size}
        basic
        type="light"
      />
    );
  }
  return (
    <Popover
      trigger="focus"
      placement="bottomLeft"
      autoAdjustOverflow
      visibleArrow={false}
      {...popoverProps}
      content={
        <TimePickerTime
          className={`${prefixCls}-popover`}
          {...timeProps}
          date={datePickerTime}
          onSelected={(type, num, disableds, currentDate) => {
            setDate(new Date(currentDate!));
            const dataStr = currentDate ? formatter(format, currentDate) : '';
            onChange && onChange(dataStr, currentDate, type, num, disableds);
          }}
        />
      }
    >
      <Input
        placeholder="请选择时间"
        readOnly
        disabled={disabled}
        {..._props}
        className={[`${prefixCls}-input`, className]
          .filter(Boolean)
          .join(' ')
          .trim()}
      />
    </Popover>
  );
}


text:
//
//  UIView+Frame.h
//  BuDeJie
//
//  Created by kun on 16/8/22.
//  Copyright © 2016年 kun. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface UIView (Frame)
@property (nonatomic, assign) CGFloat fkl_width;
@property (nonatomic, assign) CGFloat fkl_height;
@property (nonatomic, assign) CGPoint fkl_center;
@property (nonatomic, assign) CGFloat fkl_x;
@property (nonatomic, assign) CGFloat fkl_y;
@property (nonatomic, assign) CGFloat fkl_centerX;
@property (nonatomic, assign) CGFloat fkl_centerY;

/** 根据类名创建由 xib 生成的 View */
+ (instancetype)fkl_viewFromXib;
@end


text:
"""
A label command (sub-command) for the Organice management command.
"""
from django.utils.translation import ugettext as _

class BootstrapCommandMixin(object):

    def bootstrap_command(self):
        """
        Initialize Organice = initdb, initauth, initcms, initblog
        """
        self.handle_label('initdb')
        self.handle_label('initauth')
        self.handle_label('initcms')
        self.handle_label('initblog')

        self.log(_('Have an organiced day!'))


text:
package org.apache.spark.shuffle.api.metadata;

import java.util.Optional;

import org.apache.spark.annotation.Private;

/**
 * :: Private ::
 *
 * Represents the result of writing map outputs for a shuffle map task.
 *

 * Partition lengths represents the length of each block written in the map task. This can
 * be used for downstream readers to allocate resources, such as in-memory buffers.
 *

 * Map output writers can choose to attach arbitrary metadata tags to register with a
 * shuffle output tracker (a module that is currently yet to be built in a future
 * iteration of the shuffle storage APIs).
 */
@Private
public final class MapOutputCommitMessage {

  private final long[] partitionLengths;
  private final Optional<MapOutputMetadata> mapOutputMetadata;

  private MapOutputCommitMessage(
      long[] partitionLengths, Optional<MapOutputMetadata> mapOutputMetadata) {
    this.partitionLengths = partitionLengths;
    this.mapOutputMetadata = mapOutputMetadata;
  }

  public static MapOutputCommitMessage of(long[] partitionLengths) {
    return new MapOutputCommitMessage(partitionLengths, Optional.empty());
  }

  public static MapOutputCommitMessage of(
      long[] partitionLengths, MapOutputMetadata mapOutputMetadata) {
    return new MapOutputCommitMessage(partitionLengths, Optional.of(mapOutputMetadata));
  }

  public long[] getPartitionLengths() {
    return partitionLengths;
  }

  public Optional<MapOutputMetadata> getMapOutputMetadata() {
    return mapOutputMetadata;
  }
}


text:
filename: /packages/material-ui/src/Grow/Grow.js
---

# Grow API

The API documentation of the Grow React component. Learn more about the props and the CSS customization points.

## Import

```js
import Grow from '@material-ui/core/Grow';
// or
import { Grow } from '@material-ui/core';
```

You can learn more about the difference by [reading this guide](/guides/minimizing-bundle-size/).

The Grow transition is used by the [Tooltip](/components/tooltips/) and
[Popover](/components/popover/) components.
It uses [react-transition-group](https://github.com/reactjs/react-transition-group) internally.

## Props

| Name | Type | Default | Description |
|:-----|:-----|:--------|:------------|
| children | element |  | A single child content element. |
| in | bool |  | If `true`, show the component; triggers the enter or exit animation. |
| timeout | number
| { enter?: number, exit?: number }
| 'auto' | 'auto' | The duration for the transition, in milliseconds. You may specify a single timeout for all transitions, or individually with an object.
Set to 'auto' to automatically calculate transition time based on height. |

The `ref` is forwarded to the root element.

Any other props supplied will be provided to the root element ([Transition](https://reactcommunity.org/react-transition-group/transition/#Transition-props)).

## Inheritance

The props of the [Transition](https://reactcommunity.org/react-transition-group/transition/#Transition-props) component, from react-transition-group, are also available.
You can take advantage of this behavior to [target nested components](/guides/api/#spread).

## Demos

- [Popover](/components/popover/)
- [Transitions](/components/transitions/)