text:
import numpy as np
from openpnm.utils import PrintableList

__all__ = [
    'ParserMixin',
    'LabelMixin',
]

class ParserMixin:

    def _parse_indices(self, indices):
        r"""
        This private method accepts a list of pores or throats and returns a
        properly structured Numpy array of indices.

        Parameters
        ----------
        indices : int or array_like
            This argument can accept numerous different data types including
            boolean masks, integers and arrays.

        Returns
        -------
        A Numpy array of indices.

        Notes
        -----
        This method should only be called by the method that is actually using
        the locations, to avoid calling it multiple times.

        """
        if indices is None:
            indices = np.array([], ndmin=1, dtype=int)
        locs = np.array(indices, ndmin=1)
        # If boolean array, convert to indices
        if locs.dtype == bool:
            if np.size(locs) == self.Np:
                locs = self.Ps[locs]
            elif np.size(locs) == self.Nt:
                locs = self.Ts[locs]
            else:
                raise Exception('Mask of locations must be either '
                                + 'Np nor Nt long')
        locs = locs.astype(dtype=int)
        return locs

    def _parse_element(self, element, single=False):
        r"""
        This private method is used to parse the keyword \'element\' in many
        of the above methods.

        Parameters
        ----------
        element : str or List[str]
            The element argument to check.  If is None is recieved, then a list
            containing both \'pore\' and \'throat\' is returned.
        single : bool (default is False)
            When set to True only a single element is allowed and it will also
            return a string containing the element.

        Returns
        -------
        When ``single`` is ``False`` (default) a list containing the element(s)
        is returned.  When ``single`` is ``True`` a bare string containing the
        element is returned.

        """
        if element is None:
            element = ['pore', 'throat']
        # Convert element to a list for subsequent processing
        if isinstance(element, str):
            element = [element]
        # Convert 'pore.prop' and 'throat.prop' into just 'pore' and 'throat'
        element = [item.split('.', 1)[0] for item in element]
        # Make sure all are lowercase
        element = [item.lower() for item in element]
        # Deal with an plurals
        element = [item.rsplit('s', maxsplit=1)[0] for item in element]
        for item in element:
            if item not in ['pore', 'throat']:
                raise Exception('All keys must start with either pore or throat')
        # Remove duplicates if any
        _ = [element.remove(L) for L in element if element.count(L) > 1]
        if single:
            if len(element) > 1:
                raise Exception('Both elements recieved when single element '
                                + 'allowed')
            element = element[0]
        return element

    def _parse_labels(self, labels, element):
        r"""
        This private method is used for converting \'labels\' to a proper
        format, including dealing with wildcards (\*).

        Parameters
        ----------
        labels : str or List[str]
            The label or list of labels to be parsed. Note that the \* can be
            used as a wildcard.

        Returns
        -------
        A list of label strings, with all wildcard matches included if
        applicable.

        """
        if labels is None:
            raise Exception('Labels cannot be None')
        if isinstance(labels, str):
            labels = [labels]
        # Parse the labels list
        parsed_labels = []
        for label in labels:
            # Remove element from label, if present
            if element in label:
                label = label.split('.', 1)[-1]
            # Deal with wildcards
            if '*' in label:
                Ls = [L.split('.', 1)[-1] for L in self.labels(element=element)]
                if label.startswith('*'):
                    temp = [L for L in Ls if L.endswith(label.strip('*'))]
                if label.endswith('*'):
                    temp = [L for L in Ls if L.startswith(label.strip('*'))]
                temp = [element+'.'+L for L in temp]
            elif element+'.'+label in self.keys():
                temp = [element+'.'+label]
            else:
                temp = [element+'.'+label]
            parsed_labels.extend(temp)
            # Remove duplicates if any
            _ = [parsed_labels.remove(L) for L in parsed_labels
                 if parsed_labels.count(L) > 1]
        return parsed_labels

    def _parse_mode(self, mode, allowed=None, single=False):
        r"""
        This private method is for checking the \'mode\' used in the calling
        method.

        Parameters
        ----------
        mode : str or List[str]
            The mode(s) to be parsed
        allowed : List[str]
            A list containing the allowed modes.  This list is defined by the
            calling method.  If any of the received modes are not in the
            allowed list an exception is raised.
        single : bool (default is False)
            Indicates if only a single mode is allowed.  If this argument is
            True than a string is returned rather than a list of strings, which
            makes it easier to work with in the caller method.

        Returns
        -------
        A list containing the received modes as strings, checked to ensure they
        are all within the allowed set (if provoided).  Also, if the ``single``
        argument was True, then a string is returned.

        """
        if isinstance(mode, str):
            mode = [mode]
        for item in mode:
            if (allowed is not None) and (item not in allowed):
                raise Exception('\'mode\' must be one of the following: '
                                + allowed.__str__())
        # Remove duplicates, if any
        _ = [mode.remove(L) for L in mode if mode.count(L) > 1]
        if single:
            if len(mode) > 1:
                raise Exception('Multiple modes received when only one mode '
                                + 'is allowed by this method')
            mode = mode[0]
        return mode

    def _parse_prop(self, propname, element):
        element = self._parse_element(element, single=True)
        if propname.split('.', 1)[0] in ['pore', 'throat']:
            propname = propname.split('.', 1)[-1]
        return element + '.' + propname

class LabelMixin:
    """r
    This mixin adds functionality to the Base2 class so that boolean arrays
    are treated as labels
    """

    def _get_labels(self, element, locations, mode):
        r"""
        This is the actual label getter method, but it should not be called
        directly.  Use ``labels`` instead.
        """
        # Parse inputs
        locations = self._parse_indices(locations)
        element = self._parse_element(element=element)
        # Collect list of all pore OR throat labels
        labels = [i for i in self.keys(mode='labels') if i.split('.', 1)[0] in element]
        labels.sort()
        labels = np.array(labels)  # Convert to ndarray for following checks
        # Make an 2D array with locations in rows and labels in cols
        arr = np.vstack([self[item][locations] for item in labels]).T
        num_hits = np.sum(arr, axis=0)  # Number of locations with each label
        if mode in ['or', 'union', 'any']:
            temp = labels[num_hits > 0]
        elif mode in ['and', 'intersection']:
            temp = labels[num_hits == locations.size]
        elif mode in ['xor', 'exclusive_or']:
            temp = labels[num_hits == 1]
        elif mode in ['nor', 'not', 'none']:
            temp = labels[num_hits == 0]
        elif mode in ['nand']:
            temp = labels[num_hits == (locations.size - 1)]
        elif mode in ['xnor', 'nxor']:
            temp = labels[num_hits > 1]
        else:
            raise Exception('Unrecognized mode:'+str(mode))
        return PrintableList(temp)

    def labels(self, pores=[], throats=[], element=None, mode='union'):
        r"""
        Returns a list of labels present on the object

        Additionally, this function can return labels applied to a specified
        set of pores or throats

        Parameters
        ----------
        element : str
            Controls whether pore or throat labels are returned.  If empty then
            both are returned (default).
        pores (or throats) : array_like
            The pores (or throats) whose labels are sought.  If left empty a
            list containing all pore and throat labels is returned.
        mode : str, optional
            Controls how the query should be performed.  Only applicable
            when ``pores`` or ``throats`` are specified:

            ==============  ===================================================
            mode            meaning
            ==============  ===================================================
            'or'            Returns the labels that are assigned to *any* of
                            the given locations. Also accepts 'union' and 'any'
            'and'           Labels that are present on all the given locations.
                            also accepts 'intersection' and 'all'
            'xor'           Labels that are present on *only one*
                            of the given locations.Also accepts 'exclusive_or'
            'nor'           Labels that are *not* present on any of
                            the given locations. Also accepts 'not' and 'none'
            'nand'          Labels that are present on *all but one* of the
                            given locations
            'xnor'          Labels that are present on *more than one* of the
                            given locations.
            ==============  ===================================================

        Returns
        -------
        A list containing the labels on the object.  If ``pores`` or
        ``throats`` are given, the results are filtered according to the
        specified ``mode``.

        See Also
        --------
        props
        keys

        Notes
        -----
        Technically, *'nand'* and *'xnor'* should also return pores with *none*
        of the labels but these are not included.  This makes the returned list
        more useful.

        """
        # Short-circuit query when no pores or throats are given
        if (np.size(pores) == 0) and (np.size(throats) == 0):
            if element is None:
                element = ['pore', 'throat']
            if isinstance(element, str):
                element = [element]
            labels = PrintableList()
            for k, v in self.items():
                el, prop = k.split('.', 1)
                if (el in element) and (v.dtype == bool) and not prop.startswith('_'):
                    labels.append(k)
        elif (np.size(pores) > 0) and (np.size(throats) > 0):
            raise Exception('Cannot perform label query on pores and '
                            + 'throats simultaneously')
        elif np.size(pores) > 0:
            labels = self._get_labels(element='pore', locations=pores,
                                      mode=mode)
        elif np.size(throats) > 0:
            labels = self._get_labels(element='throat', locations=throats,
                                      mode=mode)
        return sorted(labels)

    def set_label(self, label, pores=None, throats=None, mode='add'):
        r"""
        Creates or updates a label array

        Parameters
        ----------
        label : str
            The label to apply to the specified locations
        pores : array_like
            A list of pore indices or a boolean mask of where given label
            should be added or removed (see ``mode``)
        throats : array_like
            A list of throat indices or a boolean mask of where given label
            should be added or removed (see ``mode``)
        mode : str
            Controls how the labels are handled.  Options are:

            =========== ======================================================
            mode        description
            =========== ======================================================
            'add'       (default) Adds the given label to the specified
                        locations while keeping existing labels

            'overwrite' Removes existing label from all locations before
                        adding the label in the specified locations

            'remove'    Removes the given label from the specified locations
                        leaving the remainder intact

            'purge'     Removes the specified label from the object completely.
                        This ignores the ``pores`` and ``throats`` arguments.

            'clear'     Sets all the labels to ``False`` but does not remove
                        the label array
            =========== ======================================================

        """
        self._parse_mode(mode=mode,
                         allowed=['add', 'overwrite', 'remove', 'purge',
                                  'clear'])

        if label.split('.', 1)[0] in ['pore', 'throat']:
            label = label.split('.', 1)[1]

        if (pores is not None) and (throats is not None):
            self.set_label(label=label, pores=pores, mode=mode)
            self.set_label(label=label, throats=throats, mode=mode)
            return
        elif pores is not None:
            locs = self._parse_indices(pores)
            element = 'pore'
        elif throats is not None:
            locs = self._parse_indices(throats)
            element = 'throat'

        if mode == 'add':
            if element + '.' + label not in self.keys():
                self[element + '.' + label] = False
            self[element + '.' + label][locs] = True
        if mode == 'overwrite':
            self[element + '.' + label] = False
            self[element + '.' + label][locs] = True
        if mode == 'remove':
            self[element + '.' + label][locs] = False
        if mode == 'clear':
            self['pore' + '.' + label] = False
            self['throat' + '.' + label] = False
        if mode == 'purge':
            _ = self.pop('pore.' + label, None)
            _ = self.pop('throat.' + label, None)

    def _get_indices(self, element, labels, mode='or'):
        r"""
        This is the actual method for getting indices, but should not be called
        directly.  Use ``pores`` or ``throats`` instead.
        """
        # Parse and validate all input values.
        element = self._parse_element(element, single=True)
        labels = self._parse_labels(labels=labels, element=element)

        # Begin computing label array
        if mode in ['or', 'any', 'union']:
            union = np.zeros([self._count(element), ], dtype=bool)
            for item in labels:  # Iterate over labels and collect all indices
                union = union + self[element+'.'+item.split('.', 1)[-1]]
            ind = union
        elif mode in ['and', 'all', 'intersection']:
            intersect = np.ones([self._count(element), ], dtype=bool)
            for item in labels:  # Iterate over labels and collect all indices
                intersect = intersect*self[element+'.'+item.split('.', 1)[-1]]
            ind = intersect
        elif mode in ['xor', 'exclusive_or']:
            xor = np.zeros([self._count(element), ], dtype=int)
            for item in labels:  # Iterate over labels and collect all indices
                info = self[element+'.'+item.split('.', 1)[-1]]
                xor = xor + np.int8(info)
            ind = (xor == 1)
        elif mode in ['nor', 'not', 'none']:
            nor = np.zeros([self._count(element), ], dtype=int)
            for item in labels:  # Iterate over labels and collect all indices
                info = self[element+'.'+item.split('.', 1)[-1]]
                nor = nor + np.int8(info)
            ind = (nor == 0)
        elif mode in ['nand']:
            nand = np.zeros([self._count(element), ], dtype=int)
            for item in labels:  # Iterate over labels and collect all indices
                info = self[element+'.'+item.split('.', 1)[-1]]
                nand = nand + np.int8(info)
            ind = (nand < len(labels)) * (nand > 0)
        elif mode in ['xnor', 'nxor']:
            xnor = np.zeros([self._count(element), ], dtype=int)
            for item in labels:  # Iterate over labels and collect all indices
                info = self[element+'.'+item.split('.', 1)[-1]]
                xnor = xnor + np.int8(info)
            ind = (xnor > 1)
        else:
            raise Exception('Unsupported mode: '+mode)
        # Extract indices from boolean mask
        ind = np.where(ind)[0]
        ind = ind.astype(dtype=int)
        return ind

    def pores(self, labels=None, mode='or', asmask=False):
        r"""
        Returns pore indicies where given labels exist, according to the logic
        specified by the ``mode`` argument.

        Parameters
        ----------
        labels : str or list[str]
            The label(s) whose pores locations are requested.  This argument
            also accepts '*' for wildcard searches.
        mode : str
            Specifies how the query should be performed.  The options are:

            ==============  ===================================================
            mode            meaning
            ==============  ===================================================
            'or'            Returns the labels that are assigned to *any* of
                            the given locations. Also accepts 'union' and 'any'
            'and'           Labels that are present on all the given locations.
                            also accepts 'intersection' and 'all'
            'xor'           Labels that are present on *only one*
                            of the given locations.Also accepts 'exclusive_or'
            'nor'           Labels that are *not* present on any of
                            the given locations. Also accepts 'not' and 'none'
            'nand'          Labels that are present on *all but one* of the
                            given locations
            'xnor'          Labels that are present on *more than one* of the
                            given locations.
            ==============  ===================================================

        asmask : bool
            If ``True`` then a boolean array of length Np is returned with
            ``True`` values indicating the pores that satisfy the query.

        Returns
        -------
        A Numpy array containing pore indices filtered by the logic specified
        in ``mode``.

        See Also
        --------
        throats

        Notes
        -----
        Technically, *nand* and *xnor* should also return pores with *none* of
        the labels but these are not included.  This makes the returned list
        more useful.

        To perform more complex or compound queries, you can opt to receive
        the result a a boolean mask (``asmask=True``), then manipulate the
        arrays manually.

        """
        if labels is None:
            labels = self.name
        ind = self._get_indices(element='pore', labels=labels, mode=mode)
        if asmask:
            ind = self.to_mask(pores=ind)
        return ind

    def throats(self, labels=None, mode='or', asmask=False):
        r"""
        Returns throat locations where given labels exist, according to the
        logic specified by the ``mode`` argument.

        Parameters
        ----------
        labels : str or list[str]
            The throat label(s) whose locations are requested.  If omitted,
            'all' throat inidices are returned.  This argument also accepts
            '*' for wildcard searches.
        mode : str
            Specifies how the query should be performed. The options are:

            ==============  ===================================================
            mode            meaning
            ==============  ===================================================
            'or'            Returns the labels that are assigned to *any* of
                            the given locations. Also accepts 'union' and 'any'
            'and'           Labels that are present on all the given locations.
                            also accepts 'intersection' and 'all'
            'xor'           Labels that are present on *only one*
                            of the given locations.Also accepts 'exclusive_or'
            'nor'           Labels that are *not* present on any of
                            the given locations. Also accepts 'not' and 'none'
            'nand'          Labels that are present on *all but one* of the
                            given locations
            'xnor'          Labels that are present on *more than one* of the
                            given locations.
            ==============  ===================================================

        asmask : bool
            If ``True`` then a boolean array of length Nt is returned with
            ``True`` values indicating the throats that satisfy the query.

        Returns
        -------
        A Numpy array containing throat indices filtered by the logic specified
        in ``mode``.

        See Also
        --------
        pores

        """
        if labels is None:
            labels = self.name
        ind = self._get_indices(element='throat', labels=labels, mode=mode)
        if asmask:
            ind = self.to_mask(throats=ind)
        return ind

    def filter_by_label(self, pores=[], throats=[], labels=None, mode='or'):
        r"""
        Returns which of the supplied pores (or throats) has the specified
        label(s)

        Parameters
        ----------
        pores, or throats : array_like
            List of pores or throats to be filtered
        labels : list of strings
            The labels to apply as a filter
        mode : str
            Controls how the filter is applied. The default value is
            'or'. Options include:

            ==============  ===================================================
            mode            meaning
            ==============  ===================================================
            'or'            Returns the labels that are assigned to *any* of
                            the given locations. Also accepts 'union' and 'any'
            'and'           Labels that are present on all the given locations.
                            also accepts 'intersection' and 'all'
            'xor'           Labels that are present on *only one*
                            of the given locations.Also accepts 'exclusive_or'
            'nor'           Labels that are *not* present on any of
                            the given locations. Also accepts 'not' and 'none'
            'nand'          Labels that are present on *all but one* of the
                            given locations
            'xnor'          Labels that are present on *more than one* of the
                            given locations.
            ==============  ===================================================

        Returns
        -------
        A list of pores (or throats) that have been filtered according the
        given criteria.  The returned list is a subset of the received list of
        pores (or throats).

        See Also
        --------
        pores
        throats

        """
        # Convert inputs to locations and element
        if (np.size(throats) > 0) and (np.size(pores) > 0):
            raise Exception('Can only filter either pores OR labels')
        if np.size(pores) > 0:
            element = 'pore'
            locations = self._parse_indices(pores)
        elif np.size(throats) > 0:
            element = 'throat'
            locations = self._parse_indices(throats)
        else:
            return np.array([], dtype=int)
        labels = self._parse_labels(labels=labels, element=element)
        labels = [element+'.'+item.split('.', 1)[-1] for item in labels]
        all_locs = self._get_indices(element=element, labels=labels, mode=mode)
        mask = self._tomask(indices=all_locs, element=element)
        ind = mask[locations]
        return locations[ind]

    def num_pores(self, labels='all', mode='or'):
        r"""
        Returns the number of pores of the specified labels

        Parameters
        ----------
        labels : list of strings, optional
            The pore labels that should be included in the count.
            If not supplied, all pores are counted.
        labels : list of strings
            Label of pores to be returned
        mode : str, optional
            Specifies how the count should be performed. The options are:

            ==============  ===================================================
            mode            meaning
            ==============  ===================================================
            'or'            Returns the labels that are assigned to *any* of
                            the given locations. Also accepts 'union' and 'any'
            'and'           Labels that are present on all the given locations.
                            also accepts 'intersection' and 'all'
            'xor'           Labels that are present on *only one*
                            of the given locations.Also accepts 'exclusive_or'
            'nor'           Labels that are *not* present on any of
                            the given locations. Also accepts 'not' and 'none'
            'nand'          Labels that are present on *all but one* of the
                            given locations
            'xnor'          Labels that are present on *more than one* of the
                            given locations.
            ==============  ===================================================

        Returns
        -------
        Np : int
            Number of pores with the specified labels

        See Also
        --------
        num_throats
        count

        Notes
        -----
        Technically, *'nand'* and *'xnor'* should also count pores with *none*
        of the labels, however, to make the count more useful these are not
        included.

        """
        # Count number of pores of specified type
        Ps = self._get_indices(labels=labels, mode=mode, element='pore')
        Np = np.shape(Ps)[0]
        return Np

    def num_throats(self, labels='all', mode='union'):
        r"""
        Return the number of throats of the specified labels

        Parameters
        ----------
        labels : list of strings, optional
            The throat labels that should be included in the count.
            If not supplied, all throats are counted.
        mode : str, optional
            Specifies how the count should be performed.  The options are:

            ==============  ===================================================
            mode            meaning
            ==============  ===================================================
            'or'            Returns the labels that are assigned to *any* of
                            the given locations. Also accepts 'union' and 'any'
            'and'           Labels that are present on all the given locations.
                            also accepts 'intersection' and 'all'
            'xor'           Labels that are present on *only one*
                            of the given locations.Also accepts 'exclusive_or'
            'nor'           Labels that are *not* present on any of
                            the given locations. Also accepts 'not' and 'none'
            'nand'          Labels that are present on *all but one* of the
                            given locations
            'xnor'          Labels that are present on *more than one* of the
                            given locations.
            ==============  ===================================================

        Returns
        -------
        Nt : int
            Number of throats with the specified labels

        See Also
        --------
        num_pores
        count

        Notes
        -----
        Technically, *'nand'* and *'xnor'* should also count throats with
        *none* of the labels, however, to make the count more useful these are
        not included.

        """
        # Count number of pores of specified type
        Ts = self._get_indices(labels=labels, mode=mode, element='throat')
        Nt = np.shape(Ts)[0]
        return Nt


text:
//
// async_udp_echo_server.cpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#include <cstdlib>
#include <iostream>
#include <boost/asio.hpp>

using boost::asio::ip::udp;

class server
{
public:
  server(boost::asio::io_context& io_context, short port)
    : socket_(io_context, udp::endpoint(udp::v4(), port))
  {
    do_receive();
  }

  void do_receive()
  {
    socket_.async_receive_from(
        boost::asio::buffer(data_, max_length), sender_endpoint_,
        [this](boost::system::error_code ec, std::size_t bytes_recvd)
        {
          if (!ec && bytes_recvd > 0)
          {
            do_send(bytes_recvd);
          }
          else
          {
            do_receive();
          }
        });
  }

  void do_send(std::size_t length)
  {
    socket_.async_send_to(
        boost::asio::buffer(data_, length), sender_endpoint_,
        [this](boost::system::error_code /*ec*/, std::size_t /*bytes_sent*/)
        {
          do_receive();
        });
  }

private:
  udp::socket socket_;
  udp::endpoint sender_endpoint_;
  enum { max_length = 1024 };
  char data_[max_length];
};

int main(int argc, char* argv[])
{
  try
  {
    if (argc != 2)
    {
      std::cerr << "Usage: async_udp_echo_server <port>\n";
      return 1;
    }

    boost::asio::io_context io_context;

    server s(io_context, std::atoi(argv[1]));

    io_context.run();
  }
  catch (std::exception& e)
  {
    std::cerr << "Exception: " << e.what() << "\n";
  }

  return 0;
}

redpajama_set_name: RedPajamaGithub


text:
//
//  CRRestfulObject.h
//  Pods
//
//  Created by Vincil Bishop on 6/24/15.
//
//

#import <Foundation/Foundation.h>
#import "EKMappingProtocol.h"
#import "CoreRestMapping-Blocks.h"

@class AFHTTPSessionManager;

@protocol CRRestfulObject <NSObject,EKManagedMappingProtocol>

+ (void) CR_setBackgroundOperationQueue:(NSOperationQueue*)operationQueue;
+ (NSOperationQueue*) CR_BackgroundQueue;

+ (void) CR_setHTTPSessionManager:(AFHTTPSessionManager*)httpSessionManager;

+ (AFHTTPSessionManager*) CR_HTTPSessionManager;

+ (NSString*) CR_rootResponseElement;

+ (NSString*) CR_RESTPath;

/**
 *  Gets all entities from the RESTPath endpoint.
 *
 *  @param completion An optional completion block to be executed upon completion.
 *
 *  @discussion Once this call is complete, the retrieved objects will be serialized and stored in the persistent store.
 */
+ (void) CR_getRemoteEntitiesWithCompletion:(CRRestCompletionBlock)completion;

/**
 *  Gets a specific entity with an identifier, then serializes the response into CoreData.
 *
 *  @param identifier The identifier (_id) of the entity.
 *  @param completion A block to be executed when the transaction completes.
 */
+ (void) CR_getRemoteEntityWithID:(NSString*)identifier withCompletion:(CRRestCompletionBlock)completion;

+ (void) CR_createRemoteEntity:(NSDictionary*)entityRepresentation withCompletion:(CRRestCompletionBlock)completion;

/**
 *  Deletes the entities from the server.
 *
 *  @param entities     An array of NSManagedObject subclasses to delete.
 *  @param completion A completion block to be run when the transaction completes.
 *
 */
+ (void) CR_deleteRemoteEntities:(NSArray*)entities withCompletion:(CRRestCompletionBlock)completion;

/**
 *  Updates the entity, then serializes the response into CoreData.
 *
 *  @param entity     The entity with updated values to be PUT.
 *  @param completion A completion block to be run when the transaction completes.
 */
+ (void) CR_updateRemoteEntity:(id)entity withCompletion:(CRRestCompletionBlock)completion;

- (void) CR_updateRemoteWithCompletion:(CRRestCompletionBlock)completion;

+ (void) CR_createRemoteEntity:(NSDictionary*)entityRepresentation atPath:(NSString*)path completion:(CRRestCompletionBlock)completion;

/**
 *  Creates a collection of entities at a specific path, then serializes the response to CoreData.
 *
 *  @param requestDictionaries An array of NSDictionary object representations.
 *  @param path                The path to POST the entities to.
 *  @param params              Parameters to send along with the request.
 *  @param completion          A completion block to be run when the transaction completes.
 */
+ (void) CR_createRemoteEntities:(NSArray*)requestDictionaries atPath:(NSString*)path parameters:(NSDictionary*)params completion:(CRRestCompletionBlock)completion;

/**
 *  Creates a collection of entities at a specific path, then serializes the response to CoreData.
 *
 *  @param requestDictionaries An array of NSDictionary object representations.
 *  @param path                The path to POST the entities to.
 *  @param params              Parameters to send along with the request.
 *  @param progress            A progress block to be run when each operation completes.
 *  @param completion          A completion block to be run when the transaction completes.
 */
+ (void) CR_createRemoteEntities:(NSArray*)requestDictionaries atPath:(NSString*)path parameters:(NSDictionary*)params progress:(CRRestCompletionBlock)progress completion:(CRRestCompletionBlock)completion;

+ (void) CR_createRemoteEntities:(NSArray*)requestDictionaries atPath:(NSString*)path parameters:(NSDictionary*)params queue:(NSOperationQueue*)operationQueue progress:(CRRestCompletionBlock)progress completion:(CRRestCompletionBlock)completion;

/**
 *  Deletes a single entity.
 *
 *  @param entity     The entity to delete.
 *  @param completion A completion block to be run when the transaction completes.
 */
+ (void) CR_deleteRemoteEntity:(NSManagedObject*)entity completion:(CRRestCompletionBlock)completion;

/**
 *  Deletes a collection of entities at a specific path, then serializes the response to CoreData.
 *
 *  @param requestDictionaries An array of NSManagedObject subclasses to delete.
 *  @param path                The path to DELETE the entities from.
 *  @param params              Parameters to send along with the request.
 *  @param completion          A completion block to be run when the transaction completes.
 */
+ (void) CR_deleteRemoteEntities:(NSArray*)entities atPath:(NSString*)path parameters:(NSDictionary*)params completion:(CRRestCompletionBlock)completion;

/**
 *  Deletes a collection of entities at a specific path, then serializes the response to CoreData.
 *
 *  @param requestDictionaries An array of NSManagedObject subclasses to delete.
 *  @param path                The path to DELETE the entities from.
 *  @param params              Parameters to send along with the request.
 *  @param progress            A progress block to be run when each operation completes.
 *  @param completion          A completion block to be run when the transaction completes.
 */
+ (void) CR_deleteRemoteEntities:(NSArray*)entities atPath:(NSString*)path parameters:(NSDictionary*)params progress:(CRRestCompletionBlock)progress completion:(CRRestCompletionBlock)completion;

+ (void) CR_deleteRemoteEntities:(NSArray*)entities atPath:(NSString*)path parameters:(NSDictionary*)params queue:(NSOperationQueue*)operationQueue progress:(CRRestCompletionBlock)progress completion:(CRRestCompletionBlock)completion;

/**
 *  Gets a collection of entities at a specific path, then serializes the response to CoreData.
 *
 *  @param path                The path to GET the entities from.
 *  @param params              Parameters to send along with the request.
  *  @param rootResponseElement              The root element from which to extract the response or nil.
 *  @param completion          A completion block to be run when the transaction completes.
 */
+ (void) CR_getRemoteEntitiesAtPath:(NSString*)path parameters:(NSDictionary*)params rootResponseElement:(NSString*)rootElement completion:(CRRestCompletionBlock)completion;

/**
 *  Gets a single entity at a specific path, then serializes the response to CoreData.
 *
 *  @param path       The path to GET the entity from.
 *  @param identifier The identifier (_id) of the entity to GET.
 *  @param params              Parameters to send along with the request.
 *  @param rootResponseElement              The root element from which to extract the response or nil.
 *  @param completion          A completion block to be run when the transaction completes.
 */
+ (void) CR_getRemoteEntityAtPath:(NSString*)path withID:(NSString*)identifier parameters:(NSDictionary*)params completion:(CRRestCompletionBlock)completion;

+ (void) CR_getRemoteEntityAtPath:(NSString*)path parameters:(NSDictionary*)params rootResponseElement:(NSString*)rootElement completion:(CRRestCompletionBlock)completion;

/**
 *  Updates the supplied entity at a specific path.
 *
 *  @param entity     The entity with updated values to be PUT.
 *  @param path        The path to PUT the entities to.
 *  @param completion A completion block to be run when the transaction completes.
 */
+ (void) CR_updateRemoteEntity:(NSManagedObject*)entity atPath:(NSString*)path completion:(CRRestCompletionBlock)completion;

+ (void) CR_updateRemoteEntity:(NSManagedObject*)entity atPath:(NSString*)path withID:(id)uniqueID withParameters:(NSDictionary*)parameters completion:(CRRestCompletionBlock)completion;

@end


text:
/* $Id$ */

package org.apache.fop.fo.properties;

import java.awt.Color;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;

import org.apache.xmlgraphics.image.loader.ImageException;
import org.apache.xmlgraphics.image.loader.ImageInfo;
import org.apache.xmlgraphics.image.loader.ImageManager;
import org.apache.xmlgraphics.image.loader.ImageSessionContext;

import org.apache.fop.ResourceEventProducer;
import org.apache.fop.apps.FOUserAgent;
import org.apache.fop.datatypes.Length;
import org.apache.fop.datatypes.PercentBaseContext;
import org.apache.fop.datatypes.URISpecification;
import org.apache.fop.fo.Constants;
import org.apache.fop.fo.FObj;
import org.apache.fop.fo.PropertyList;
import org.apache.fop.fo.expr.PropertyException;
import org.apache.fop.util.CompareUtil;

/**
 * Stores all common border and padding properties.
 * See Sec. 7.7 of the XSL-FO Standard.
 */
public class CommonBorderPaddingBackground {

    /**
     *  cache holding all canonical instances
     *  (w/ absolute background-position-* and padding-*)
     */
    private static final PropertyCache<CommonBorderPaddingBackground> CACHE
            = new PropertyCache<CommonBorderPaddingBackground>();

    private int hash = -1;

    /**
     * The "background-attachment" property.
     */
    public final int backgroundAttachment;                      // CSOK: VisibilityModifier

    /**
     * The "background-color" property.
     */
    public final Color backgroundColor;                         // CSOK: VisibilityModifier

    /**
     * The "background-image" property.
     */
    public final String backgroundImage;                        // CSOK: VisibilityModifier

    /**
     * The "background-repeat" property.
     */
    public final int backgroundRepeat;                          // CSOK: VisibilityModifier

    /**
     * The "background-position-horizontal" property.
     */
    public final Length backgroundPositionHorizontal;           // CSOK: VisibilityModifier

    /**
     * The "background-position-vertical" property.
     */
    public final Length backgroundPositionVertical;             // CSOK: VisibilityModifier

    private ImageInfo backgroundImageInfo;

    /** the "before" edge */
    public static final int BEFORE = 0;
    /** the "after" edge */
    public static final int AFTER = 1;
    /** the "start" edge */
    public static final int START = 2;
    /** the "end" edge */
    public static final int END = 3;

    /**
     * Utility class to express border info.
     */
    public static final class BorderInfo {

        /** cache holding all canonical instances */
        private static final PropertyCache<BorderInfo> CACHE
                = new PropertyCache<BorderInfo>();

        private int mStyle; // Enum for border style
        private Color mColor; // Border color
        private CondLengthProperty mWidth;

        private int hash = -1;

        /**
         * Hidden constructor
         */
        private BorderInfo(int style, CondLengthProperty width, Color color) {
            mStyle = style;
            mWidth = width;
            mColor = color;
        }

        /**
         * Returns a BorderInfo instance corresponding to the given values
         *
         * @param style the border-style
         * @param width the border-width
         * @param color the border-color
         * @return a cached BorderInfo instance
         */
        public static BorderInfo getInstance(int style, CondLengthProperty width, Color color) {
            return CACHE.fetch(new BorderInfo(style, width, color));
        }

        /**
         * @return  the border-style
         */
        public int getStyle() {
            return this.mStyle;
        }

        /**
         * @return the border-color
         */
        public Color getColor() {
            return this.mColor;
        }

        /**
         * @return the border-width
         */
        public CondLengthProperty getWidth() {
            return this.mWidth;
        }

        /**
         * Convenience method returning the border-width,
         * taking into account values of "none" and "hidden"
         *
         * @return  the retained border-width
         */
        public int getRetainedWidth() {
            if ((mStyle == Constants.EN_NONE)
                    || (mStyle == Constants.EN_HIDDEN)) {
                return 0;
            } else {
                return mWidth.getLengthValue();
            }
        }

        @Override
        public String toString() {
            StringBuffer sb = new StringBuffer("BorderInfo");
            sb.append(" {");
            sb.append(mStyle);
            sb.append(", ");
            sb.append(mColor);
            sb.append(", ");
            sb.append(mWidth);
            sb.append("}");
            return sb.toString();
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj) {
                return true;
            }
            if (!(obj instanceof BorderInfo)) {
                return false;
            }
            BorderInfo other = (BorderInfo) obj;
            return CompareUtil.equal(mColor, other.mColor)
                    && mStyle == other.mStyle
                    && CompareUtil.equal(mWidth, other.mWidth);
        }

        @Override
        public int hashCode() {
            if (this.hash == -1) {
                int hash = 17;
                hash = 37 * hash + (mColor == null ? 0 : mColor.hashCode());
                hash = 37 * hash + mStyle;
                hash = 37 * hash + (mWidth == null ? 0 : mWidth.hashCode());
                this.hash = hash;
            }
            return this.hash;
        }
    }

    /**
     * A border info with style "none". Used as a singleton, in the collapsing-border model,
     * for elements which don't specify any border on some of their sides.
     */
    private static final BorderInfo DEFAULT_BORDER_INFO
            = BorderInfo.getInstance(Constants.EN_NONE, new ConditionalNullLength(), null);

    /**
     * A conditional length of value 0. Returned by the
     * {@link CommonBorderPaddingBackground#getBorderInfo(int)} method when the
     * corresponding border isn't specified, to avoid to callers painful checks for null.
     */
    private static class ConditionalNullLength extends CondLengthProperty {

        @Override
        public Property getComponent(int cmpId) {
            throw new UnsupportedOperationException();
        }

        @Override
        public Property getConditionality() {
            throw new UnsupportedOperationException();
        }

        @Override
        public Length getLength() {
            throw new UnsupportedOperationException();
        }

        @Override
        public Property getLengthComponent() {
            throw new UnsupportedOperationException();
        }

        @Override
        public int getLengthValue() {
            return 0;
        }

        @Override
        public int getLengthValue(PercentBaseContext context) {
            return 0;
        }

        @Override
        public boolean isDiscard() {
            return true;
        }

        @Override
        public void setComponent(int cmpId, Property cmpnValue, boolean isDefault) {
            throw new UnsupportedOperationException();
        }

        @Override
        public String toString() {
            return "CondLength[0mpt, discard]";
        }
    }

    /**
     * Returns a default BorderInfo of style none.
     *
     * @return a BorderInfo instance with style set to {@link Constants#EN_NONE}
     */
    public static BorderInfo getDefaultBorderInfo() {
        return DEFAULT_BORDER_INFO;
    }

    private BorderInfo[] borderInfo = new BorderInfo[4];
    private CondLengthProperty[] padding = new CondLengthProperty[4];

    /**
     * Construct a CommonBorderPaddingBackground object.
     *
     * @param pList The PropertyList to get properties from.
     * @throws PropertyException if there's an error while binding the properties
     */
    CommonBorderPaddingBackground(PropertyList pList) throws PropertyException {

        backgroundAttachment = pList.get(Constants.PR_BACKGROUND_ATTACHMENT).getEnum();

        Color bc = pList.get(Constants.PR_BACKGROUND_COLOR).getColor(
                                        pList.getFObj().getUserAgent());
        if (bc.getAlpha() == 0) {
            backgroundColor = null;
        } else {
            backgroundColor = bc;
        }

        String img = pList.get(Constants.PR_BACKGROUND_IMAGE).getString();
        if (img == null || "none".equals(img)) {
            backgroundImage = "";
            backgroundRepeat = -1;
            backgroundPositionHorizontal = null;
            backgroundPositionVertical = null;
        } else {
            backgroundImage = img;
            backgroundRepeat = pList.get(Constants.PR_BACKGROUND_REPEAT).getEnum();
            backgroundPositionHorizontal = pList.get(
                    Constants.PR_BACKGROUND_POSITION_HORIZONTAL).getLength();
            backgroundPositionVertical = pList.get(
                    Constants.PR_BACKGROUND_POSITION_VERTICAL).getLength();
        }

        initBorderInfo(pList, BEFORE,
                Constants.PR_BORDER_BEFORE_COLOR,
                Constants.PR_BORDER_BEFORE_STYLE,
                Constants.PR_BORDER_BEFORE_WIDTH,
                Constants.PR_PADDING_BEFORE);
        initBorderInfo(pList, AFTER,
                Constants.PR_BORDER_AFTER_COLOR,
                Constants.PR_BORDER_AFTER_STYLE,
                Constants.PR_BORDER_AFTER_WIDTH,
                Constants.PR_PADDING_AFTER);
        initBorderInfo(pList, START,
                Constants.PR_BORDER_START_COLOR,
                Constants.PR_BORDER_START_STYLE,
                Constants.PR_BORDER_START_WIDTH,
                Constants.PR_PADDING_START);
        initBorderInfo(pList, END,
                Constants.PR_BORDER_END_COLOR,
                Constants.PR_BORDER_END_STYLE,
                Constants.PR_BORDER_END_WIDTH,
                Constants.PR_PADDING_END);

    }

    /**
     * Obtain a CommonBorderPaddingBackground instance based on the
     * related property valus in the given {@link PropertyList}
     *
     * @param pList the {@link PropertyList} to use
     * @return a CommonBorderPaddingBackground instance (cached if possible)
     * @throws PropertyException in case of an error
     */
    public static CommonBorderPaddingBackground getInstance(PropertyList pList)
        throws PropertyException {
        CommonBorderPaddingBackground newInstance = new CommonBorderPaddingBackground(pList);
        CommonBorderPaddingBackground cachedInstance = null;
        /* if padding-* and background-position-* resolve to absolute lengths
         * the whole instance can be cached */
        if ((newInstance.padding[BEFORE] == null
             || newInstance.padding[BEFORE].getLength().isAbsolute())
                && (newInstance.padding[AFTER] == null
                    || newInstance.padding[AFTER].getLength().isAbsolute())
                && (newInstance.padding[START] == null
                    || newInstance.padding[START].getLength().isAbsolute())
                && (newInstance.padding[END] == null
                    || newInstance.padding[END].getLength().isAbsolute())
                && (newInstance.backgroundPositionHorizontal == null
                    || newInstance.backgroundPositionHorizontal.isAbsolute())
                && (newInstance.backgroundPositionVertical == null
                    || newInstance.backgroundPositionVertical.isAbsolute())) {
            cachedInstance = CACHE.fetch(newInstance);
        }
        synchronized (newInstance.backgroundImage.intern()) {
            /* for non-cached, or not-yet-cached instances, preload the image */
            if ((cachedInstance == null || cachedInstance == newInstance)
                && !("".equals(newInstance.backgroundImage))) {
                //Additional processing: preload image
                String uri = URISpecification.getURL(newInstance.backgroundImage);
                FObj fobj = pList.getFObj();
                FOUserAgent userAgent = pList.getFObj().getUserAgent();
                ImageManager manager = userAgent.getFactory().getImageManager();
                ImageSessionContext sessionContext = userAgent.getImageSessionContext();
                ImageInfo info;
                try {
                    info = manager.getImageInfo(uri, sessionContext);
                    newInstance.backgroundImageInfo = info;
                } catch (ImageException e) {
                    ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
                            fobj.getUserAgent().getEventBroadcaster());
                    eventProducer.imageError(fobj, uri, e, fobj.getLocator());
                } catch (FileNotFoundException fnfe) {
                    ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
                            fobj.getUserAgent().getEventBroadcaster());
                    eventProducer.imageNotFound(fobj, uri, fnfe, fobj.getLocator());
                } catch (IOException ioe) {
                    ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get(
                            fobj.getUserAgent().getEventBroadcaster());
                    eventProducer.imageIOError(fobj, uri, ioe, fobj.getLocator());
                }
            }
        }

        return (cachedInstance != null ? cachedInstance : newInstance);
    }

    private void initBorderInfo(PropertyList pList, int side,
                    int colorProp, int styleProp, int widthProp, int paddingProp)
                throws PropertyException {

        padding[side] = pList.get(paddingProp).getCondLength();
        // If style = none, force width to 0, don't get Color (spec 7.7.20)
        int style = pList.get(styleProp).getEnum();
        if (style != Constants.EN_NONE) {
            FOUserAgent ua = pList.getFObj().getUserAgent();
            setBorderInfo(BorderInfo.getInstance(style,
                pList.get(widthProp).getCondLength(),
                pList.get(colorProp).getColor(ua)), side);
        }

    }

    /**
     * Sets a border.
     * @param info the border information
     * @param side the side to apply the info to
     */
    private void setBorderInfo(BorderInfo info, int side) {
        this.borderInfo[side] = info;
    }

    /**
     * @param side the side to retrieve
     * @return the border info for a side
     */
    public BorderInfo getBorderInfo(int side) {
        if (this.borderInfo[side] == null) {
            return getDefaultBorderInfo();
        } else {
            return this.borderInfo[side];
        }
    }

    /**
     * @return the background image info object, null if there is
     *     no background image.
     */
    public ImageInfo getImageInfo() {
        return this.backgroundImageInfo;
    }

    /**
     * @param discard indicates whether the .conditionality component should be
     * considered (start of a reference-area)
     * @return the width of the start-border, taking into account the specified conditionality
     */
    public int getBorderStartWidth(boolean discard) {
        return getBorderWidth(START, discard);
    }

    /**
     * @param discard indicates whether the .conditionality component should be
     * considered (end of a reference-area)
     * @return the width of the end-border, taking into account the specified conditionality
     */
    public int getBorderEndWidth(boolean discard) {
        return getBorderWidth(END, discard);
    }

    /**
     * @param discard indicates whether the .conditionality component should be
     * considered (start of a reference-area)
     * @return the width of the before-border, taking into account the specified conditionality
     */
    public int getBorderBeforeWidth(boolean discard) {
        return getBorderWidth(BEFORE, discard);
    }

    /**
     * @param discard indicates whether the .conditionality component should be
     * considered (end of a reference-area)
     * @return the width of the after-border, taking into account the specified conditionality
     */
    public int getBorderAfterWidth(boolean discard) {
        return getBorderWidth(AFTER, discard);
    }

    /**
     * @param discard indicates whether the .conditionality component should be
     * considered (start of a reference-area)
     * @param context the context to evaluate percentage values
     * @return the width of the start-padding, taking into account the specified conditionality
     */
    public int getPaddingStart(boolean discard, PercentBaseContext context) {
        return getPadding(START, discard, context);
    }

    /**
     * @param discard indicates whether the .conditionality component should be
     * considered (start of a reference-area)
     * @param context the context to evaluate percentage values
     * @return the width of the end-padding, taking into account the specified conditionality
     */
    public int getPaddingEnd(boolean discard, PercentBaseContext context) {
        return getPadding(END, discard, context);
    }

    /**
     * @param discard indicates whether the .conditionality component should be
     * considered (start of a reference-area)
     * @param context the context to evaluate percentage values
     * @return the width of the before-padding, taking into account the specified conditionality
     */
    public int getPaddingBefore(boolean discard, PercentBaseContext context) {
        return getPadding(BEFORE, discard, context);
    }

    /**
     * @param discard indicates whether the .conditionality component should be
     * considered (start of a reference-area)
     * @param context the context to evaluate percentage values
     * @return the width of the after-padding, taking into account the specified conditionality
     */
    public int getPaddingAfter(boolean discard, PercentBaseContext context) {
        return getPadding(AFTER, discard, context);
    }

    /**
     * @param side the side of the border
     * @param discard indicates whether the .conditionality component should be considered (end of a
     * reference-area)
     * @return the width of the start-border, taking into account the specified conditionality
     */
    public int getBorderWidth(int side, boolean discard) {
        if ((borderInfo[side] == null)
                || (borderInfo[side].mStyle == Constants.EN_NONE)
                || (borderInfo[side].mStyle == Constants.EN_HIDDEN)
                || (discard && borderInfo[side].mWidth.isDiscard())) {
            return 0;
        } else {
            return borderInfo[side].mWidth.getLengthValue();
        }
    }

    /**
     * The border-color for the given side
     *
     * @param side one of {@link #BEFORE}, {@link #AFTER}, {@link #START}, {@link #END}
     * @return  the border-color for the given side
     */
    public Color getBorderColor(int side) {
        if (borderInfo[side] != null) {
            return borderInfo[side].getColor();
        } else {
            return null;
        }
    }

    /**
     * The border-style for the given side
     *
     * @param side one of {@link #BEFORE}, {@link #AFTER}, {@link #START}, {@link #END}
     * @return  the border-style for the given side
     */
    public int getBorderStyle(int side) {
        if (borderInfo[side] != null) {
            return borderInfo[side].mStyle;
        } else {
            return Constants.EN_NONE;
        }
    }

    /**
     * Return the padding for the given side, taking into account
     * the conditionality and evaluating any percentages in the given
     * context.
     *
     * @param side  one of {@link #BEFORE}, {@link #AFTER}, {@link #START}, {@link #END}
     * @param discard   true if the conditionality component should be considered
     * @param context   the context for percentage-resolution
     * @return  the computed padding for the given side
     */
    public int getPadding(int side, boolean discard, PercentBaseContext context) {
        if ((padding[side] == null) || (discard && padding[side].isDiscard())) {
            return 0;
        } else {
            return padding[side].getLengthValue(context);
        }
    }

    /**
     * Returns the CondLengthProperty for the padding on one side.
     * @param side the side
     * @return the requested CondLengthProperty
     */
    public CondLengthProperty getPaddingLengthProperty(int side) {
        return padding[side];
    }

    /**
     * Return all the border and padding width in the inline progression
     * dimension.
     * @param discard the discard flag.
     * @param context for percentage evaluation.
     * @return all the padding and border width.
     */
    public int getIPPaddingAndBorder(boolean discard, PercentBaseContext context) {
        return getPaddingStart(discard, context)
            + getPaddingEnd(discard, context)
            + getBorderStartWidth(discard)
            + getBorderEndWidth(discard);
    }

    /**
     * Return all the border and padding height in the block progression
     * dimension.
     * @param discard the discard flag.
     * @param context for percentage evaluation
     * @return all the padding and border height.
     */
    public int getBPPaddingAndBorder(boolean discard, PercentBaseContext context) {
        return getPaddingBefore(discard, context) + getPaddingAfter(discard, context)
               + getBorderBeforeWidth(discard) + getBorderAfterWidth(discard);
    }

    @Override
    public String toString() {
        return "CommonBordersAndPadding (Before, After, Start, End):\n"
            + "Borders: (" + getBorderBeforeWidth(false) + ", " + getBorderAfterWidth(false) + ", "
            + getBorderStartWidth(false) + ", " + getBorderEndWidth(false) + ")\n"
            + "Border Colors: (" + getBorderColor(BEFORE) + ", " + getBorderColor(AFTER) + ", "
            + getBorderColor(START) + ", " + getBorderColor(END) + ")\n"
            + "Padding: (" + getPaddingBefore(false, null) + ", " + getPaddingAfter(false, null)
            + ", " + getPaddingStart(false, null) + ", " + getPaddingEnd(false, null) + ")\n";
    }

    /**
     * @return true if there is any kind of background to be painted
     */
    public boolean hasBackground() {
        return ((backgroundColor != null || getImageInfo() != null));
    }

    /** @return true if border is non-zero. */
    public boolean hasBorder() {
        return ((getBorderBeforeWidth(false) + getBorderAfterWidth(false)
                + getBorderStartWidth(false) + getBorderEndWidth(false)) > 0);
    }

    /**
     * @param context for percentage based evaluation.
     * @return true if padding is non-zero.
     */
    public boolean hasPadding(PercentBaseContext context) {
        return ((getPaddingBefore(false, context) + getPaddingAfter(false, context)
                + getPaddingStart(false, context) + getPaddingEnd(false, context)) > 0);
    }

    /** @return true if there are any borders defined. */
    public boolean hasBorderInfo() {
        return (borderInfo[BEFORE] != null || borderInfo[AFTER] != null
                || borderInfo[START] != null || borderInfo[END] != null);
    }

    /**
     * Returns the "background-color" property.
     * @return the "background-color" property.
     */
    public Color getBackgroundColor() {
        return backgroundColor;
    }

    /**
     * Returns the "background-attachment" property.
     * @return the "background-attachment" property.
     */
    public int getBackgroundAttachment() {
        return backgroundAttachment;
    }

    /**
     * Returns the "background-image" property.
     * @return the "background-image" property.
     */
    public String getBackgroundImage() {
        return backgroundImage;
    }

    /**
     * Returns the "background-repeat" property.
     * @return the "background-repeat" property.
     */
    public int getBackgroundRepeat() {
        return backgroundRepeat;
    }

    /**
     * Returns the "background-position-horizontal" property.
     * @return the "background-position-horizontal" property.
     */
    public Length getBackgroundPositionHorizontal() {
        return backgroundPositionHorizontal;
    }

    /**
     * Returns the "background-position-vertical" property.
     * @return the "background-position-vertical" property.
     */
    public Length getBackgroundPositionVertical() {
        return backgroundPositionVertical;
    }

    /**
     * Returns the background image info
     * @return the background image info
     */
    public ImageInfo getBackgroundImageInfo() {
        return backgroundImageInfo;
    }

    /**
     * Returns the border info
     * @return the border info
     */
    public BorderInfo[] getBorderInfo() {
        return borderInfo;
    }

    /**
     * Returns the padding
     * @return the padding
     */
    public CondLengthProperty[] getPadding() {
        return padding;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (!(obj instanceof CommonBorderPaddingBackground)) {
            return false;
        }

        CommonBorderPaddingBackground other = (CommonBorderPaddingBackground) obj;
        return backgroundAttachment == other.backgroundAttachment
                && CompareUtil.equal(backgroundColor, other.backgroundColor)
                && CompareUtil.equal(backgroundImage, other.backgroundImage)
                && CompareUtil.equal(backgroundPositionHorizontal, backgroundPositionHorizontal)
                && CompareUtil.equal(backgroundPositionVertical, other.backgroundPositionVertical)
                && backgroundRepeat == other.backgroundRepeat
                && Arrays.equals(borderInfo, other.borderInfo)
                && Arrays.equals(padding, other.padding);
    }

    @Override
    public int hashCode() {
        if (this.hash == -1) {
            int hash = getHashCode(backgroundColor,
                    backgroundImage,
                    backgroundPositionHorizontal,
                    backgroundPositionVertical,
                    borderInfo[BEFORE],
                    borderInfo[AFTER],
                    borderInfo[START],
                    borderInfo[END],
                    padding[BEFORE],
                    padding[AFTER],
                    padding[START],
                    padding[END]);
            hash = 37 * hash + backgroundAttachment;
            hash = 37 * hash + backgroundRepeat;
            this.hash = hash;
        }
        return this.hash;
    }

    private int getHashCode(Object... objects) {
        int hash = 17;
        for (Object o : objects) {
            hash = 37 * hash + (o == null ? 0 : o.hashCode());
        }
        return hash;
    }
}


text:
import os
import sys
import platform

#----------------------------------------------------------------------------------------
# Defines
#----------------------------------------------------------------------------------------

kMac     = 0
kLinux   = 1
kWindows = 2

currentDir = os.path.dirname(os.path.realpath(__file__))

#----------------------------------------------------------------------------------------
# Methods
#----------------------------------------------------------------------------------------

def getOs():
    name = platform.system()
    if name == 'Darwin':
        return kMac
    if name == 'Linux':
        return kLinux
    if name == 'Windows':
        return kWindows

if getOs() == kMac:
    module = os.path.join(currentDir, 'mac')

if getOs() == kLinux:
    module = os.path.join(currentDir, 'linux')

if getOs() == kWindows:
    module = os.path.join(currentDir, 'windows')

#----------------------------------------------------------------------------------------
# Package handler
#----------------------------------------------------------------------------------------
# insert os specific PIL package path into sys.path
sys.path.insert(0, module)
# delete empty PIL package
del sys.modules[__name__]
# import os specific PIL package
import PIL


text:
namespace nbla {

NBLA_REGISTER_FUNCTION_SOURCE(RoiAlign, const vector<int> &,
                              const vector<float> &, int, bool);

template <typename T>
void RoiAlign<T>::setup_impl(const Variables &inputs,
                             const Variables &outputs) {
#define CHECK(condition, msg, ...)                                             \
  NBLA_CHECK(condition, error_code::value, msg, ##__VA_ARGS__);

  auto const input = inputs.at(0);
  auto const boxes = inputs.at(1);

  CHECK(input->shape().size() == 4, "input variable must be 4-D.");
  CHECK(boxes->shape().size() == 2, "boxes variable must be 2-D.");
  CHECK(boxes->shape().at(1) == 5, "boxes shape must be [K, 5]");
  CHECK(output_size_.size() == 2, "output_size must be (height, width) tuple");
  CHECK(output_size_.at(0) > 0, "output height must be greater zero");
  CHECK(output_size_.at(1) > 0, "output width must be greater zero");
  CHECK(spatial_scale_.size() == 2, "spatial_scale must be an (y, x) tuple");

  if (!this->channel_last_) {
    auto const K = boxes->shape().at(0);
    auto const C = input->shape().at(1);
    auto const H = output_size_.at(0);
    auto const W = output_size_.at(1);
    outputs.at(0)->reshape({K, C, H, W}, true);
  } else {
    auto const K = boxes->shape().at(0);
    auto const C = input->shape().at(3);
    auto const H = output_size_.at(0);
    auto const W = output_size_.at(1);
    outputs.at(0)->reshape({K, H, W, C}, true);
  }

#undef CHECK
}

template <typename T> struct Box { T batch_index, x1, y1, x2, y2; };

template <typename T> inline T clamp(const T x, const T low, const T high) {
  return std::max(low, std::min(high, x));
}

template <typename T>
inline int sampling_grid(const int sampling_ratio, const T step_size) {
  return sampling_ratio > 0 ? sampling_ratio
                            : static_cast<int>(std::ceil(step_size));
}

template <typename T>
void RoiAlign<T>::forward_impl(const Variables &inputs,
                               const Variables &outputs) {
  NBLA_CHECK(this->channel_last_ == false, error_code::not_implemented,
             "Argument channel_last=true is not supported in CPU context.");

  auto input = inputs.at(0);
  auto boxes = inputs.at(1);
  auto output = outputs.at(0);

  auto input_data = input->get_data_pointer<T>(this->ctx_);
  auto boxes_data = boxes->get_data_pointer<T>(this->ctx_);
  auto output_data = output->cast_data_and_get_pointer<T>(this->ctx_, true);

  auto const samples = input->shape().at(0);
  auto const channels = input->shape().at(1);
  auto const roiboxes = boxes->shape().at(0);

  auto const image_rows = input->shape().at(2);
  auto const image_cols = input->shape().at(3);
  auto const image_size = image_rows * image_cols;

  auto const output_rows = output->shape().at(2);
  auto const output_cols = output->shape().at(3);

  for (auto n = 0; n < roiboxes; n++) {
    auto const roi = *reinterpret_cast<Box<T> const *>(boxes_data + n * 5);
    auto const roi_x1 = static_cast<T>(roi.x1 * spatial_scale_.at(1) - 0.5f);
    auto const roi_x2 = static_cast<T>(roi.x2 * spatial_scale_.at(1) - 0.5f);
    auto const roi_y1 = static_cast<T>(roi.y1 * spatial_scale_.at(0) - 0.5f);
    auto const roi_y2 = static_cast<T>(roi.y2 * spatial_scale_.at(0) - 0.5f);
    auto const roi_index = static_cast<int>(roi.batch_index);
    NBLA_CHECK(roi_index >= 0 && roi_index < samples, error_code::value,
               "Batch index must be within the number of input samples.");

    auto const step_size_x = (roi_x2 - roi_x1) / output_cols;
    auto const step_size_y = (roi_y2 - roi_y1) / output_rows;

    auto const grid_size_x = sampling_grid(this->sampling_ratio_, step_size_x);
    auto const grid_size_y = sampling_grid(this->sampling_ratio_, step_size_y);

    auto const step_size_xx = step_size_x / grid_size_x;
    auto const step_size_yy = step_size_y / grid_size_y;
    auto const half_step_xx = T(0.5) * step_size_xx;
    auto const half_step_yy = T(0.5) * step_size_yy;

    auto const grid_size_xy = grid_size_x * grid_size_y;
    auto const inverse_grid_count = T(1) / grid_size_xy;

    auto channel_data = input_data + roi_index * channels * image_size;

    for (auto c = 0; c < channels; c++) {
      auto output_index = (n * channels + c) * output_rows * output_cols;

      for (auto y = 0; y < output_rows; y++) {
        auto yf = roi_y1 + static_cast<T>(y) * step_size_y;

        for (auto x = 0; x < output_cols; x++) {
          auto xf = roi_x1 + static_cast<T>(x) * step_size_x;
          auto output_value = T(0);

          for (auto yy = 0; yy < grid_size_y; yy++) {
            auto yyf = yf + static_cast<T>(yy) * step_size_yy + half_step_yy;

            if (yyf < T(-1) || yyf > static_cast<T>(image_rows))
              continue;

            yyf = clamp<T>(yyf, 0, image_rows - 1);
            auto const y_lo = static_cast<Size_t>(yyf);
            auto const y_hi = std::min(y_lo + 1, image_rows - 1);
            auto const ly = yyf - std::floor(yyf);
            auto const hy = T(1) - ly;

            for (auto xx = 0; xx < grid_size_x; xx++) {
              auto xxf = xf + static_cast<T>(xx) * step_size_xx + half_step_xx;

              if (xxf < T(-1) || xxf > static_cast<T>(image_cols))
                continue;

              xxf = clamp<T>(xxf, 0, image_cols - 1);
              auto const x_lo = static_cast<Size_t>(xxf);
              auto const x_hi = std::min(x_lo + 1, image_cols - 1);
              auto const lx = xxf - std::floor(xxf);
              auto const hx = T(1) - lx;

              auto const p1 = y_lo * image_cols + x_lo;
              auto const p2 = y_lo * image_cols + x_hi;
              auto const p3 = y_hi * image_cols + x_lo;
              auto const p4 = y_hi * image_cols + x_hi;
              output_value += hy * hx * channel_data[p1];
              output_value += hy * lx * channel_data[p2];
              output_value += ly * hx * channel_data[p3];
              output_value += ly * lx * channel_data[p4];
            }
          }
          output_data[output_index++] = output_value * inverse_grid_count;
        }
      }
      channel_data += image_size;
    }
  }
}

template <typename T>
void RoiAlign<T>::backward_impl(const Variables &inputs,
                                const Variables &outputs,
                                const vector<bool> &propagate_down,
                                const vector<bool> &accum) {
  if (!propagate_down.at(0))
    return;

  NBLA_CHECK(this->channel_last_ == false, error_code::not_implemented,
             "Argument channel_last=true is not supported in CPU context.");

  auto input = inputs.at(0);
  auto boxes = inputs.at(1);
  auto output = outputs.at(0);

  if (!accum.at(0)) {
    input->grad()->zero();
  }

  auto input_grad = input->cast_grad_and_get_pointer<T>(this->ctx_, false);
  auto boxes_data = boxes->get_data_pointer<T>(this->ctx_);
  auto output_grad = output->get_grad_pointer<T>(this->ctx_);

  auto const samples = input->shape().at(0);
  auto const channels = input->shape().at(1);
  auto const roiboxes = boxes->shape().at(0);

  auto const image_rows = input->shape().at(2);
  auto const image_cols = input->shape().at(3);
  auto const image_size = image_rows * image_cols;

  auto const output_rows = output->shape().at(2);
  auto const output_cols = output->shape().at(3);

  for (auto n = 0; n < roiboxes; n++) {
    auto const roi = *reinterpret_cast<Box<T> const *>(boxes_data + n * 5);
    auto const roi_x1 = static_cast<T>(roi.x1 * spatial_scale_.at(1) - 0.5f);
    auto const roi_x2 = static_cast<T>(roi.x2 * spatial_scale_.at(1) - 0.5f);
    auto const roi_y1 = static_cast<T>(roi.y1 * spatial_scale_.at(0) - 0.5f);
    auto const roi_y2 = static_cast<T>(roi.y2 * spatial_scale_.at(0) - 0.5f);
    auto const roi_index = static_cast<int>(roi.batch_index);
    NBLA_CHECK(roi_index >= 0 && roi_index < samples, error_code::value,
               "Batch index must be within the number of input samples.");

    auto const step_size_x = (roi_x2 - roi_x1) / output_cols;
    auto const step_size_y = (roi_y2 - roi_y1) / output_rows;

    auto const grid_size_x = sampling_grid(this->sampling_ratio_, step_size_x);
    auto const grid_size_y = sampling_grid(this->sampling_ratio_, step_size_y);

    auto const step_size_xx = step_size_x / grid_size_x;
    auto const step_size_yy = step_size_y / grid_size_y;
    auto const half_step_xx = T(0.5) * step_size_xx;
    auto const half_step_yy = T(0.5) * step_size_yy;

    auto const grid_size_xy = grid_size_x * grid_size_y;
    auto const inverse_grid_count = T(1) / grid_size_xy;

    auto channel_grad = input_grad + roi_index * channels * image_size;

    for (auto c = 0; c < channels; c++) {
      auto output_index = (n * channels + c) * output_rows * output_cols;

      for (auto y = 0; y < output_rows; y++) {
        auto yf = roi_y1 + static_cast<T>(y) * step_size_y;

        for (auto x = 0; x < output_cols; x++) {
          auto xf = roi_x1 + static_cast<T>(x) * step_size_x;
          auto grad_value = output_grad[output_index++] * inverse_grid_count;

          for (auto yy = 0; yy < grid_size_y; yy++) {
            auto yyf = yf + static_cast<T>(yy) * step_size_yy + half_step_yy;

            if (yyf < T(-1) || yyf > static_cast<T>(image_rows))
              continue;

            yyf = clamp<T>(yyf, 0, image_rows - 1);
            auto const y_lo = static_cast<Size_t>(yyf);
            auto const y_hi = std::min(y_lo + 1, image_rows - 1);
            auto const ly = yyf - std::floor(yyf);
            auto const hy = T(1) - ly;

            for (auto xx = 0; xx < grid_size_x; xx++) {
              auto xxf = xf + static_cast<T>(xx) * step_size_xx + half_step_xx;

              if (xxf < T(-1) || xxf > static_cast<T>(image_cols))
                continue;

              xxf = clamp<T>(xxf, 0, image_cols - 1);
              auto const x_lo = static_cast<Size_t>(xxf);
              auto const x_hi = std::min(x_lo + 1, image_cols - 1);
              auto const lx = xxf - std::floor(xxf);
              auto const hx = T(1) - lx;

              auto const p1 = y_lo * image_cols + x_lo;
              auto const p2 = y_lo * image_cols + x_hi;
              auto const p3 = y_hi * image_cols + x_lo;
              auto const p4 = y_hi * image_cols + x_hi;
              channel_grad[p1] += hy * hx * grad_value;
              channel_grad[p2] += hy * lx * grad_value;
              channel_grad[p3] += ly * hx * grad_value;
              channel_grad[p4] += ly * lx * grad_value;
            }
          }
        }
      }
      channel_grad += image_size;
    }
  }
}
}


text:
package com.junichi11.netbeans.modules.template.settings.ui.customizers;

/**
 *
 * @author junichi11
 */
public class TemplateSettingsCustomizerPanel extends javax.swing.JPanel {

    private static final long serialVersionUID = 4444747316722998838L;

    /**
     * Creates new form TemplateSettingsCustomizerPanel
     */
    public TemplateSettingsCustomizerPanel() {
        initComponents();
    }

    public boolean isSettingsEnabled() {
        return enableCheckBox.isSelected();
    }

    public void setSettingsEnabled(boolean isEnabled) {
        enableCheckBox.setSelected(isEnabled);
    }

    public void setSettings(String settings) {
        settingsEditorPane.setText(settings);
    }

    public String getSettings() {
        return settingsEditorPane.getText();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        enableCheckBox = new javax.swing.JCheckBox();
        settingsScrollPane = new javax.swing.JScrollPane();
        settingsEditorPane = new javax.swing.JEditorPane();

        org.openide.awt.Mnemonics.setLocalizedText(enableCheckBox, org.openide.util.NbBundle.getMessage(TemplateSettingsCustomizerPanel.class, "TemplateSettingsCustomizerPanel.enableCheckBox.text")); // NOI18N

        settingsEditorPane.setContentType("text/x-properties"); // NOI18N
        settingsScrollPane.setViewportView(settingsEditorPane);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(settingsScrollPane)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(enableCheckBox)
                        .addGap(0, 219, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(enableCheckBox)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(settingsScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 246, Short.MAX_VALUE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JCheckBox enableCheckBox;
    private javax.swing.JEditorPane settingsEditorPane;
    private javax.swing.JScrollPane settingsScrollPane;
    // End of variables declaration//GEN-END:variables
}


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

import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import edu.wpi.first.wpilibj.templates.RobotMap;
import edu.wpi.first.wpilibj.templates.util.MathUtils;

/**
 *
 * @author Michael Hrcek
 */
public class TankCommand extends CommandBase {

    public TankCommand() {
        // Use requires() here to declare subsystem dependencies
        // eg. requires(chassis);
        requires(tank);
    }

    // Called just before this Command runs the first time
    protected void initialize() {

    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {

        if(oi.getDrive() == RobotMap.TANK_DRIVE){

            double leftY = MathUtils.limit(oi.getXbox().GetLeftY(), .1, 1, 0, 1);
            double rightY = MathUtils.limit(oi.getXbox().GetRightY(), .1, 1, 0, 1);

            double speedModifier = .75;

            if(oi.getXbox().GetLeftBumperValue()){ //turtle
                if(oi.getXbox().GetStartButton().get()){ //super turtle
                    speedModifier = .25;
                    SmartDashboard.putString("Speed", "Super Turtle");
                } else{
                    speedModifier = .5;
                    SmartDashboard.putString("Speed", "Turtle");
                }
            } else if(oi.getXbox().GetRightBumperValue()){ //turbo
                speedModifier = 1;
                SmartDashboard.putString("Speed", "Turbo");
            } else{
                SmartDashboard.putString("Speed", "Normal");
            }

//            SmartDashboard.putString("LeftX", "NULL");
//            SmartDashboard.putString("LeftY", "" + leftY);
//            SmartDashboard.putString("RightX", "NULL");
//            SmartDashboard.putString("RightY", "" + rightY);

            tank.move(leftY * speedModifier, rightY * speedModifier);
        }
    }

    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
        return false;
    }

    // Called once after isFinished returns true
    protected void end() {
        tank.stop();
    }

    // Called when another command which requires one or more of the same
    // subsystems is scheduled to run
    protected void interrupted() {
        tank.stop();
        SmartDashboard.putString("Shitter1", "Tank got fucked yo.");
    }
}


text:
package wanghaokang.android.gdei.weathertest.gson;

import com.google.gson.annotations.SerializedName;

/**
 * Created by yixinyijin on 2017/7/18.
 */

public class Now {
    @SerializedName("tmp")
    public String temperature;

    @SerializedName("cond")
    public More more;

    public class More {
        @SerializedName("txt")
        public String info;
    }
}


text:
require_relative './spec_helper.rb'

RSpec.describe Elasticsearch::Model::CascadeUpdate, type: :model do
  @@counter = 0

  before do
    @clz = Article.dup
    eval("ArticleD#{@@counter} = @clz")
    @clz.table_name = 'articles'

    @dep_clz = Review.dup
    eval("ReviewD#{@@counter} = @dep_clz")
    @dep_clz.table_name = 'reviews'

    @@counter += 1

    review_class = @dep_clz
    @clz.class_eval do
      has_many :reviews, class_name: review_class.name, foreign_key: 'article_id', inverse_of: :article
    end

    article_class = @clz
    @dep_clz.class_eval do
      belongs_to :article, class_name: article_class.name, foreign_key: 'article_id', inverse_of: :reviews
    end

    @clz.__send__ :include, Elasticsearch::Model
    @clz.__send__ :include, Elasticsearch::Model::Callbacks
    @clz.__send__ :include, Elasticsearch::Model::CascadeUpdate
  end

  context 'attrs' do
    describe 'load'  do
      before do
        @clz.class_eval do
          es_register_attrs :title, :content
        end

        @article = @clz.new(title: 'nani', content: 'oops')
      end

      it { expect(@article.as_indexed_json).to eq({"title"=>"nani", "content"=>"oops"}) }
    end

    describe 'silent' do
      before do
        @clz.class_eval do
          es_register_silent_attrs :title
          es_register_attrs :content, explicit_title: lambda {|o| o.title}
        end

        @article = @clz.new(title: 'nani', content: 'oops')
      end

      it { expect(@article.as_indexed_json(include: [:title])).to eq({
        "explicit_title"=>"nani", "content"=>"oops", "title" => "nani"
      }) }
    end
  end

  context 'assoc' do
    before do
      @article = @clz.create!(title: 'nani', content: 'oops')
      @article.reviews.create!(content: 'review 1')
      @article.reviews.create!(content: 'review 2')
    end

    describe 'basis' do
      before do
        @clz.class_eval do
          es_register_assoc :reviews, reverse_relationship: 'article'
        end
      end

      it { expect(@article.as_indexed_json).to eq({
        "reviews"=>[{"id"=>1, "article_id"=>1, "content"=>"review 1", "nonsense"=>nil},
                    {"id"=>2, "article_id"=>1, "content"=>"review 2", "nonsense"=>nil}]
      }) }
    end

    describe 'blk passed in' do
      before do
        @clz.class_eval do
          es_register_assoc :reviews, reverse_relationship: 'article' do |review|
            review.as_json(only: [:content])
          end
        end
      end

      it { expect(@article.as_indexed_json).to eq({
        "reviews"=>[ {"content"=>"review 1"},
                     {"content"=>"review 2"}]
      }) }
    end

    describe 'reverse' do
      context '#reverse_relationship' do
        before do
          @clz.class_eval do
            es_register_attrs :title
            es_register_assoc :reviews, reverse_relationship: 'article' do |review|
              review.as_json(only: [:content])
            end
          end

        end

        it do
          expect(@article.__elasticsearch__).to receive(:update_document_attributes).with(
            "reviews"=>[ {"content"=>"review 1"},
                         {"content"=>"review 2 changed"}]
          )

          @review = @article.reviews[1]
          @review.content = 'review 2 changed'
          @review.save!
        end
      end

      context '#reverse_trigger' do
        before do
          @clz.class_eval do
            es_register_attrs :title
            es_register_assoc(:reviews, reverse_relationship: 'article',
                              reverse_trigger: lambda {|review, changes| changes.has_key? :content }
                             ) do |review|
              review.as_json(only: [:content])
            end
          end
        end

        describe 'include changed key' do
          it do
            expect(@article.__elasticsearch__).to receive(:update_document_attributes).with(
              "reviews"=>[ {"content"=>"review 1"},
                           {"content"=>"review 2 changed"}]
            )

            @review = @article.reviews[1]
            @review.content = 'review 2 changed'
            @review.save!
          end
        end

        describe 'exclude changed key' do
          it do
            expect(@article.__elasticsearch__).to receive(:update_document_attributes).never

            @review = @article.reviews[1]
            @review.nonsense = 'change does not matter much'
            @review.save!
          end
        end

        describe 'destroy' do
          it do
            expect(@article.__elasticsearch__).to receive(:update_document_attributes).with(
              "reviews"=>[ {"content"=>"review 1"} ]
            )

            @review = @article.reviews[1]
            @review.destroy!
          end
        end

      end
    end
  end

  context 'searchable' do
    before do
      @clz.class_eval do
        es_register_attrs :title
        es_to_json_when(:searchable) {|record| record.is_searchable }
      end
    end

    it 'not send to es upon creation & update' do
      @article = @clz.new title: 'oops', content: 'OooPs', is_searchable: false
      expect(@article.__elasticsearch__).to receive(:update_document_attributes).never
      @article.save!
      @article.update(title: 'is changed')
    end

  end

end


text:
import {Component, OnInit} from '@angular/core';

@Component({
  selector   : 'app-user',
  templateUrl: './user.component.html'
})
export class UserComponent implements OnInit {

  constructor() {
  }

  ngOnInit() {
  }

}


text:
#include "tensorflow/core/grappler/clusters/virtual_cluster.h"
#include "tensorflow/core/framework/cost_graph.pb.h"
#include "tensorflow/core/framework/tensor_shape.pb.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/grappler/clusters/utils.h"
#include "tensorflow/core/grappler/costs/op_level_cost_estimator.h"
#include "tensorflow/core/grappler/costs/virtual_scheduler.h"

namespace tensorflow {
namespace grappler {

VirtualCluster::VirtualCluster(
    const std::unordered_map<string, DeviceProperties>& devices)
    : Cluster(0),
      node_estimator_(new OpLevelCostEstimator()),
      node_manager_(new FirstReadyManager()) {
  devices_ = devices;
}

VirtualCluster::VirtualCluster(
    const std::unordered_map<string, DeviceProperties>& devices,
    std::unique_ptr<OpLevelCostEstimator> node_estimator,
    std::unique_ptr<ReadyNodeManager> node_manager)
    : Cluster(0),
      node_estimator_(std::move(node_estimator)),
      node_manager_(std::move(node_manager)) {
  devices_ = devices;
}

VirtualCluster::VirtualCluster(const DeviceSet* device_set)
    : VirtualCluster(std::unordered_map<string, DeviceProperties>()) {
  device_set_ = device_set;
  for (const auto& device : device_set_->devices()) {
    DeviceProperties props = GetDeviceInfo(device->parsed_name());
    if (props.type() == "UNKNOWN") continue;
    auto attrs = device->attributes();
    props.set_memory_size(attrs.memory_limit());
    devices_[device->name()] = props;
  }
}

VirtualCluster::~VirtualCluster() {}

Status VirtualCluster::Provision() { return Status::OK(); }

Status VirtualCluster::Initialize(const GrapplerItem& item) {
  return Status::OK();
}

Status VirtualCluster::Run(const GraphDef& graph,
                           const std::vector<std::pair<string, Tensor>>& feed,
                           const std::vector<string>& fetch,
                           RunMetadata* metadata) {
  // Initialize a virtual scheduler to process the graph. Make sure to use
  // static shape inference to prevent the schedulrer from calling the Run
  // method on the cluster, and create an infinite loop.
  GrapplerItem item;
  item.graph = graph;
  item.feed = feed;
  item.fetch = fetch;
  VirtualScheduler scheduler(true, this, node_manager_.get());
  TF_RETURN_IF_ERROR(scheduler.Init(&item));

  if (metadata) {
    metadata->clear_step_stats();
    metadata->clear_cost_graph();
    metadata->clear_partition_graphs();
  }

  Costs node_costs;
  int node_id = 0;
  do {
    OpContext op_context = scheduler.GetCurrNode();
    node_costs = node_estimator_->PredictCosts(op_context);
    if (metadata) {
      CostGraphDef::Node* cost_node =
          metadata->mutable_cost_graph()->add_node();
      const string& op_name = op_context.name;
      cost_node->set_id(node_id++);
      cost_node->set_name(op_name);
      cost_node->set_device(op_context.device_name);
      cost_node->set_compute_cost(
          node_costs.execution_time.asMicroSeconds().count());
      cost_node->set_compute_time(
          node_costs.compute_time.asMicroSeconds().count());
      cost_node->set_memory_time(
          node_costs.memory_time.asMicroSeconds().count());
      for (const auto& output : op_context.op_info.outputs()) {
        auto output_info = cost_node->add_output_info();
        output_info->set_dtype(output.dtype());
        *output_info->mutable_shape() = output.shape();

        int64 size = DataTypeSize(output.dtype());
        for (const auto& dim : output.shape().dim()) {
          size *= std::max<int64>(1, dim.size());
        }
        output_info->set_size(size);
      }
    }
  } while (scheduler.MarkCurrNodeExecuted(node_costs));

  if (metadata) {
    scheduler.Summary(metadata);
  }

  const std::unordered_map<string, DeviceProperties>& device = GetDevices();
  std::unordered_map<string, int64> peak_mem_usage =
      scheduler.GetPeakMemoryUsage();
  for (const auto& mem_usage : peak_mem_usage) {
    const string& device_name = mem_usage.first;
    auto it = device.find(device_name);
    if (it == device.end()) {
      // It's probably the fake send/recv device. Eventually we'll need to
      // remove this fake device to ensure proper memory accounting for
      // multi-device settings.
      continue;
    }
    const DeviceProperties& dev = it->second;
    if (dev.memory_size() <= 0) {
      // Available device memory unknown
      continue;
    }
    int64 peak_mem = mem_usage.second;
    if (peak_mem >= dev.memory_size()) {
      return errors::ResourceExhausted(
          "Graph requires ", peak_mem, " bytes of memory on device ",
          device_name, " to run ", " but device only has ", dev.memory_size(),
          " available.");
    }
  }

  return Status::OK();
}

}  // namespace grappler
}  // namespace tensorflow


text:
package giki.parser;

import giki.runtime.Symbol;

public class ExpansionContext {
	public void addModuleUsage(String identifier, Action1<Symbol> expansionInterpolater) {
		// TODO Auto-generated method stub

	}
}


text:
"""
This module is for reading the html tables that list world leaders off of varying webpages.
It is not very dynamic or robust, and has priority for updates.

More tables of FEs from countries around the world will be added so users can compare their data sets to different
world leaders.
"""

import pandas as pd

# A website with an html table to scrape for presidential term data
fe_url = 'http://www.enchantedlearning.com/history/us/pres/list.shtml'
fe_term_column = 2
header_row = 0
unique_text = 'Vice-President'
fe_table = pd.read_html(fe_url, match=unique_text, flavor='bs4', header=header_row,
                        index_col=fe_term_column, parse_dates=True)[0]
fe_names = []
index_list = fe_table.index.get_level_values(0).values.tolist()  # slice the data frame index as a list
year_list = []

for term in index_list:
    term_num = term.split('-')[0]  # get the first year of the term number
    year_list.append(term_num)  # add it to the year list

fe_table['Year'] = year_list
fe_table.set_index('President', drop=False, inplace=True)

#  Some formatting transformations are  required for this table. This loop sets the fe names to only alpha chars
for item in fe_table.index.get_level_values(0).values.tolist():
    fe_name = ''  # reset the name
    for char in item:  # loop through each character to check if it is alpha-nonnumeric, and append it to a string
        if char.isalpha() or char == ' ':
            fe_name = fe_name + char
    fe_names.append(fe_name)  # append the string to the presidential names list
fe_table['President'] = fe_names  # add the name list to the 'President' column of the fe dataframe
fe_table.set_index('Year', drop=True, inplace=True)  # Set the index to the year column

# A simple getter function to return the fe dataframe when needed in other modules
def get_fe():
    return fe_table


text:
<?php
session_start();

require_once 'include/AccesDonneesInit.inc.php'; //appelle fichier sql qui se connecte à la bdd
require_once 'include/flash.lib.php';
require_once 'include/database.lib.php';
require_once 'include/config.inc.php';
require_once 'include/password.inc.php';

/* verifier si les valeurs existe */
if (($_POST['password'] == null)
		|| ($_POST['repeatpassword'] == null)) {
	//mise en session du message flash
	addFlash('Erreur', 'Merci de remplir tous les champs.');

	header('location: visiteur-changerMotDePasseForm.php');							//redirige vers changerMotDePasseForm.php
	exit;
}

$password = md5($_POST['password']);
$repeatpassword = md5($_POST['repeatpassword']);

$errors = array();
checkPassword($_POST['password'], $errors);

if(count($errors) > 0) {
	foreach ($errors as $message) {
		addFlash('Erreur', $message);
	}

	header('location: visiteur-changerMotDePasseForm.php');							//redirige vers changerMotDePasseForm.php
	exit;
}

//vérifie si les mots de passes sont identiques
if ($password != $repeatpassword) {
	//mise en session du message flash
	addFlash('Erreur', 'Les mots de passes ne sont pas identiques.');

	header('location: visiteur-changerMotDePasseForm.php');							//redirige vers changerMotDePasseForm.php
	exit;
} else {
	$idVisiteur = $_SESSION['idVisiteur'];

	// vérifie si l'utilisateur a déjà eu ce mot de passe
	$sql = "SELECT * FROM historiquePassword
	WHERE idVisiteur='$idVisiteur'
	AND pwd='$password'";			//requete sql

	$resultat = tableSQL($sql);

	if(count($resultat) > 0) {
		//mise en session du message flash
		addFlash('Erreur', 'Vous avez déjà eu ce mot de passe.');

		header('location: visiteur-changerMotDePasseForm.php');							//redirige vers changerMotDePasseForm.php
		exit;
	} else {
		$sql = "INSERT INTO historiquePassword(idVisiteur, pwd, updated_date)
		VALUES ('$idVisiteur', '$password', NOW())";

		executeSQL($sql);

		header('location: index.php');							//redirige vers index.php
		exit;
	}

}

$id = secureVariable($resultat[0]['id']);

$sql = "SELECT * FROM historiquePassword
WHERE idVisiteur='$id'
ORDER BY updated_date DESC
LIMIT 1";			//requete sql

$resultat = tableSQL($sql);

$dateDuDernierMotDePasse = $resultat[0]["updated_date"];

if ($resultat[0]["pwd"] != $password) {					//	compte le nombre de resultat
	//mise en session du message flash
	addFlash('Erreur', 'Mot de passe incorrect.');

	header('location: connexion.php');							//redirige vers login.php
	exit;
}

$_SESSION['login']      = secureVariable($pseudo);							//stock donner de $pseudo dans $_session
$_SESSION['idVisiteur'] = secureVariable($id);				//stock l'id du visiteur dans la session

$dateLimitMotDePasse= strtotime("+".TEMPS_VALIDITE_PASSWORD." days", strtotime($dateDuDernierMotDePasse));

$now = date("Y-m-d");
$limit = date("Y-m-d", $dateLimitMotDePasse);
if($now >= $limit) {
	header('location: visiteur-changerMotDePasseForm.php');							//redirige vers index.php
	exit;
} else {
	header('location: index.php');							//redirige vers index.php
	exit;
}


text:
AddCSLuaFile("shared.lua")
AddCSLuaFile("cl_init.lua")

include("shared.lua")

function ENT:Initialize()
	self:SetModel("models/props_wasteland/SpeakerCluster01a.mdl")
	self:SetSolid(SOLID_VPHYSICS)
	self:SetMoveType(MOVETYPE_NONE)
end

function ENT:OnRemove()
	self:SetEnabled(false)
end