text:
// Boost.Geometry (aka GGL, Generic Geometry Library)

// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.

// This file was modified by Oracle on 2020.
// Modifications copyright (c) 2020, Oracle and/or its affiliates.
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle

// Use, modification and distribution is subject to 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)

#ifndef BOOST_GEOMETRY_IO_WKB_DETAIL_PARSER_HPP
#define BOOST_GEOMETRY_IO_WKB_DETAIL_PARSER_HPP

#include <algorithm>
#include <cassert>
#include <cstddef>
#include <iterator>
#include <limits>
#include <type_traits>

#include <boost/geometry/core/exception.hpp>

#include <boost/concept_check.hpp>
#include <boost/cstdint.hpp>
#include <boost/static_assert.hpp>

#include <boost/geometry/core/access.hpp>
#include <boost/geometry/core/assert.hpp>
#include <boost/geometry/core/coordinate_dimension.hpp>
#include <boost/geometry/core/coordinate_type.hpp>
#include <boost/geometry/core/exterior_ring.hpp>
#include <boost/geometry/core/interior_rings.hpp>
#include <boost/geometry/extensions/gis/io/wkb/detail/endian.hpp>
#include <boost/geometry/extensions/gis/io/wkb/detail/ogc.hpp>

namespace boost { namespace geometry
{

/*!
\brief Read WKB Exception
\ingroup core
\details The read_wkb_exception is thrown when there is an error in wkb parsing
 */
class read_wkb_exception : public geometry::exception
{
public:

    inline read_wkb_exception() {}

    virtual char const* what() const throw()
    {
        return "Boost.Geometry Read WKB exception";
    }
};

#ifndef DOXYGEN_NO_DETAIL
namespace detail { namespace wkb
{

template <typename T>
struct value_parser
{
    typedef T value_type;

    template <typename Iterator>
    static bool parse(Iterator& it, Iterator end, T& value, byte_order_type::enum_t order)
    {
        // Very basic pre-conditions check on stream of bytes passed in
        BOOST_STATIC_ASSERT((
            std::is_integral<typename std::iterator_traits<Iterator>::value_type>::value
        ));
        BOOST_STATIC_ASSERT((sizeof(boost::uint8_t) ==
            sizeof(typename std::iterator_traits<Iterator>::value_type)
        ));

        typedef typename std::iterator_traits<Iterator>::difference_type diff_type;
        diff_type const required_size = sizeof(T);
        if (it != end && std::distance(it, end) >= required_size)
        {
            typedef endian::endian_value<T> parsed_value_type;
            parsed_value_type parsed_value;

            // Decide on direcion of endianness translation, detault to native
            if (byte_order_type::xdr == order)
            {
                parsed_value.template load<endian::big_endian_tag>(it);
            }
            else if (byte_order_type::ndr == order)
            {
                parsed_value.template load<endian::little_endian_tag>(it);
            }
            else
            {
                parsed_value.template load<endian::native_endian_tag>(it);
            }

            value = parsed_value;
            std::advance(it, required_size);
            return true;
        }

        return false;
    }
};

struct byte_order_parser
{
    template <typename Iterator>
    static bool parse(Iterator& it, Iterator end, byte_order_type::enum_t& order)
    {
        boost::uint8_t value;
        if (value_parser<boost::uint8_t>::parse(it, end, value, byte_order_type::unknown))
        {
            if (byte_order_type::unknown > value)
            {
                order = byte_order_type::enum_t(value);
            }else{
                order = byte_order_type::unknown;
            }
            return true;
        }
        return false;
    }
};

template <typename Geometry>
struct geometry_type_parser
{
    template <typename Iterator>
    static bool parse(Iterator& it, Iterator end,
                byte_order_type::enum_t order)
    {
        boost::uint32_t value;
        if (value_parser<boost::uint32_t>::parse(it, end, value, order))
        {
            return geometry_type<Geometry>::check(value);
        }
        return false;
    }
};

template <typename P,
          std::size_t I = 0,
          std::size_t N = dimension<P>::value>
struct parsing_assigner
{
    template <typename Iterator>
    static void run(Iterator& it, Iterator end, P& point,
                byte_order_type::enum_t order)
    {
        typedef typename coordinate_type<P>::type coordinate_type;

        // coordinate type in WKB is always double
        double value(0);
        if (value_parser<double>::parse(it, end, value, order))
        {
            // actual coordinate type of point may be different
            set<I>(point, static_cast<coordinate_type>(value));
        }
        else
        {
            // TODO: mloskot - Report premature termination at coordinate level
            //throw failed to read coordinate value

            // default initialized value as fallback
            set<I>(point, coordinate_type());
        }
        parsing_assigner<P, I+1, N>::run(it, end, point, order);
    }
};

template <typename P, std::size_t N>
struct parsing_assigner<P, N, N>
{
    template <typename Iterator>
    static void run(Iterator& /*it*/, Iterator /*end*/, P& /*point*/,
                byte_order_type::enum_t /*order*/)
    {
        // terminate
    }
};

template <typename P>
struct point_parser
{
    template <typename Iterator>
    static bool parse(Iterator& it, Iterator end, P& point,
                byte_order_type::enum_t order)
    {
        if (geometry_type_parser<P>::parse(it, end, order))
        {
            if (it != end)
            {
                parsing_assigner<P>::run(it, end, point, order);
            }
            return true;
        }
        return false;
    }
};

template <typename C>
struct point_container_parser
{
    template <typename Iterator>
    static bool parse(Iterator& it, Iterator end, C& container,
                byte_order_type::enum_t order)
    {
        typedef typename point_type<C>::type point_type;

        boost::uint32_t num_points(0);
        if (!value_parser<boost::uint32_t>::parse(it, end, num_points, order))
        {
            return false;
        }

        typedef typename std::iterator_traits<Iterator>::difference_type size_type;
        if(num_points > (std::numeric_limits<boost::uint32_t>::max)() )
        {
            throw boost::geometry::read_wkb_exception();
        }

        size_type const container_size = static_cast<size_type>(num_points);
        size_type const point_size = dimension<point_type>::value * sizeof(double);

        if (std::distance(it, end) >= (container_size * point_size))
        {
            point_type point_buffer;

            // Read coordinates into point and append point to line (ring)
            size_type points_parsed = 0;
            while (points_parsed < container_size && it != end)
            {
                parsing_assigner<point_type>::run(it, end, point_buffer, order);
                boost::geometry::append(container, point_buffer);
                ++points_parsed;
            }

            if (container_size != points_parsed)
            {
                return false;
            }
        }
        else
        {
            return false;
        }

        return true;
    }
};

template <typename L>
struct linestring_parser
{
    template <typename Iterator>
    static bool parse(Iterator& it, Iterator end, L& linestring,
                byte_order_type::enum_t order)
    {
        if (!geometry_type_parser<L>::parse(it, end, order))
        {
            return false;
        }

        if(it == end)
        {
            throw boost::geometry::read_wkb_exception();
        }

        return point_container_parser<L>::parse(it, end, linestring, order);
    }
};

template <typename Polygon>
struct polygon_parser
{
    template <typename Iterator>
    static bool parse(Iterator& it, Iterator end, Polygon& polygon,
                byte_order_type::enum_t order)
    {
        if (!geometry_type_parser<Polygon>::parse(it, end, order))
        {
            return false;
        }

        boost::uint32_t num_rings(0);
        if (!value_parser<boost::uint32_t>::parse(it, end, num_rings, order))
        {
            return false;
        }

        typedef typename boost::geometry::ring_return_type<Polygon>::type ring_type;

        std::size_t rings_parsed = 0;
        while (rings_parsed < num_rings && it != end)
        {
            if (0 == rings_parsed)
            {
                ring_type ring0 = exterior_ring(polygon);
                if (!point_container_parser<ring_type>::parse(it, end, ring0, order))
                {
                    return false;
                }
            }
            else
            {
                boost::geometry::range::resize(interior_rings(polygon), rings_parsed);
                ring_type ringN = boost::geometry::range::back(interior_rings(polygon));

                if (!point_container_parser<ring_type>::parse(it, end, ringN, order))
                {
                    return false;
                }
            }

            ++rings_parsed;
        }

        return true;
    }
};

}} // namespace detail::wkb
#endif // DOXYGEN_NO_IMPL

}} // namespace boost::geometry
#endif // BOOST_GEOMETRY_IO_WKB_DETAIL_PARSER_HPP


text:
package org.jrimum.bopepo.campolivre;

import org.jrimum.domkee.financeiro.banco.febraban.Titulo;

/**
 *

 * Interface comum para todos os campos livres do Banco Santander que venham a
 * existir.
 *

 *
 * @author Gilmar P.S.L
 *
 * @since 0.2
 *
 * @version 0.2
 */
abstract class AbstractCLSantander extends AbstractCampoLivre {

	/**
	 *
	 */
	private static final long serialVersionUID = 1882819688182515282L;

	/**
	 *
Cria um campo livre com um determinado número de campos

	 *
	 * @see AbstractCampoLivre
	 *
	 * @param fieldsLength - Número de campos
	 */
	protected AbstractCLSantander(Integer fieldsLength) {

		super(fieldsLength);
	}

	protected static CampoLivre create(Titulo titulo) {

		return new CLBancoSantander(titulo);
	}
}

redpajama_set_name: RedPajamaGithub


text:
class CreateComments < ActiveRecord::Migration
  def change
    create_table :comments do |t|
      t.string :body
      t.integer :user_id
      t.integer :post_id
      t.decimal :pos
      t.decimal :neg
      t.decimal :neutral
      t.string :label

      t.timestamps null: false
    end
  end
end


text:
using System;

namespace Jojo.Common.Helpers.Switch
{
    /// <summary>
    /// Représentation d'un <c>switch</c> sur le type d'un objet.
    /// </summary>
    /// <remarks>
    /// Voir <c>http://stackoverflow.com/questions/298976/is-there-a-better-alternative-than-this-to-switch-on-type</c>.
    /// Définition complète de la classe : <c>https://gist.github.com/Virtlink/8722649</c>.
    /// </remarks>
    public static class TypeSwitch
    {
        /// <summary>
        /// <c>switch</c> sur le type de l'objet.
        /// </summary>
        /// <typeparam name="TSource">Le type de l'objet.</typeparam>
        /// <param name="value">La valeur de l'objet.</param>
        /// <returns>Une instance de la classe <see cref="Switch{TSource}"/>.</returns>
        public static Switch<TSource> On<TSource>(TSource value)
        {
            return new Switch<TSource>(value);
        }

        /// <summary>
        /// Classe représentant l'instance de <c>switch</c>.
        /// </summary>
        /// <typeparam name="TSource">Le type de l'objet source.</typeparam>
        public sealed class Switch<TSource>
        {
            /// <summary>
            /// La valeur de l'objet source.
            /// </summary>
            private readonly TSource value;

            /// <summary>
            /// Indique si la valeur a été trouvée dans le <c>switch</c>.
            /// </summary>
            private bool handled = false;

            /// <summary>
            /// Initialise une nouvelle instance de la classe <see cref="Switch{TSource}"/>.
            /// </summary>
            /// <param name="value">La valeur de l'objet.</param>
            internal Switch(TSource value)
            {
                this.value = value;
            }

            /// <summary>
            /// Cas d'un <c>switch</c>.
            /// </summary>
            /// <typeparam name="TTarget">Le type de sortie de l'objet.</typeparam>
            /// <param name="action">L'action à exécuter sur l'objet.</param>
            /// <returns>Une instance de la classe <see cref="Switch{TSource}"/>.</returns>
            public Switch<TSource> Case<TTarget>(Action<TTarget> action)
                where TTarget : TSource
            {
                if (!this.handled && this.value is TTarget)
                {
                    action((TTarget)this.value);
                    this.handled = true;
                }

                return this;
            }

            /// <summary>
            /// Cas par défaut d'un <c>switch</c>.
            /// </summary>
            /// <param name="action">L'action à exécuter sur l'objet dans le cas par défaut.</param>
            public void Default(Action<TSource> action)
            {
                if (!this.handled)
                {
                    action(this.value);
                }
            }
        }
    }
}


text:
package com.evolveum.midpoint.prism.query;

import java.io.Serializable;

import javax.xml.namespace.QName;

import com.evolveum.midpoint.util.DebugDumpable;
import com.evolveum.midpoint.util.DebugUtil;

public class ObjectPaging implements DebugDumpable, Serializable {

	private Integer offset;
	private Integer maxSize;
	private QName orderBy;
	private OrderDirection direction;

	ObjectPaging() {
		// TODO Auto-generated constructor stub
	}

	ObjectPaging(Integer offset, Integer maxSize){
		this.offset = offset;
		this.maxSize = maxSize;
	}

	ObjectPaging(Integer offset, Integer maxSize, QName orderBy, OrderDirection direction){
		this.offset = offset;
		this.maxSize = maxSize;
		this.orderBy = orderBy;
		this.direction = direction;
	}

	public static ObjectPaging createPaging(Integer offset, Integer maxSize){
		return new ObjectPaging(offset, maxSize);
	}

	public static ObjectPaging createPaging(Integer offset, Integer maxSize, QName orderBy, OrderDirection direction){
		return new ObjectPaging(offset, maxSize, orderBy, direction);
	}

	public static ObjectPaging createPaging(Integer offset, Integer maxSize, String orderBy, String namespace, OrderDirection direction){
		return new ObjectPaging(offset, maxSize, new QName(namespace, orderBy), direction);
	}

	public static ObjectPaging createEmptyPaging(){
		return new ObjectPaging();
	}

	public OrderDirection getDirection() {
		return direction;
	}
	public void setDirection(OrderDirection direction) {
		this.direction = direction;
	}

	public Integer getOffset() {
		return offset;
	}

	public void setOffset(Integer offset) {
		this.offset = offset;
	}

	public QName getOrderBy() {
		return orderBy;
	}

	public void setOrderBy(QName orderBy) {
		this.orderBy = orderBy;
	}

	public Integer getMaxSize() {
		return maxSize;
	}

	public void setMaxSize(Integer maxSize) {
		this.maxSize = maxSize;
	}

	public ObjectPaging clone() {
		return new ObjectPaging(offset, maxSize, orderBy, direction);
	}

	@Override
	public String debugDump() {
		return debugDump(0);
	}

	@Override
	public String debugDump(int indent) {
		StringBuilder sb = new StringBuilder();
		sb.append("PAGING: \n");
		DebugUtil.indentDebugDump(sb, indent + 1);
		if (getOffset() != null) {
			sb.append("Offset: " + getOffset());
			sb.append("\n");
		}
		if (getMaxSize() != null) {
			sb.append("Max size: " + getMaxSize());
			sb.append("\n");
		}
		if (getOrderBy() != null) {
			sb.append("Order by: " + getOrderBy().toString());
			sb.append("\n");
		}
		if (getDirection() != null) {
			sb.append("Order direction: " + getDirection());
			sb.append("\n");
		}
		return sb.toString();
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append("PAGING: ");
		if (this == null){
			sb.append("null");
			return sb.toString();
		}
		if (getOffset() != null){
			sb.append("O: ");
			sb.append(getOffset());
			sb.append(",");
		}
		if (getMaxSize() != null){
			sb.append("M: ");
			sb.append(getMaxSize());
			sb.append(",");
		}
		if (getOrderBy() != null){
			sb.append("BY: ");
			sb.append(getOrderBy().getLocalPart());
			sb.append(", ");
		}
		if (getDirection() != null){
			sb.append("D:");
			sb.append(getDirection());
		}

		return sb.toString();
	}

}


text:
package greek.morphology.verb;

import greek.code.PhonoCode;
import greek.grammar.Person;
import greek.grammar.Number;
import greek.morphology.Morpheme;

/**
 * The present indicative active verb endings.
 * @author Brian DuSell <bdusell@gmail.com>
 * @deprecated
 */
public enum PresIndActEnding {
	FIRST_SING("o:"), SECOND_SING("eis"), THIRD_SING("ei"),
	FIRST_PLUR("omen"), SECOND_PLUR("ete"), THIRD_PLUR("ousin?");

	private final Morpheme _morpheme;

	private PresIndActEnding(String phonoCode) {
		_morpheme = PhonoCode.toMorpheme(phonoCode);
	}

	public Morpheme getMorpheme() {
		return (Morpheme) _morpheme.clone();
	}

	public static PresIndActEnding getEnding(Person p, Number n) {
		return PresIndActEnding.values()[Person.values().length * n.ordinal() + p.ordinal()];
	}

	public Person getPerson() {
		return Person.values()[this.ordinal() % Person.values().length];
	}

	public Number getNumber() {
		return Number.values()[this.ordinal() / Person.values().length];
	}

}


text:
title: Список форм в структуре приложения
sidebar: flexberry-designer_sidebar
keywords: Flexberry Designer, структура приложения, все формы
summary:
toc: true
permalink: ru/fd_structure_all_forms.html
lang: ru
---

## Левое "дерево"

На странице структуры приложения слева отображается дерево с перечнем всех классов данных проектируемого приложения, а также все списковые формы и формы редактирования, привязанные к соответствующим классам данных (вложенные узлы).

### Инструменты работы с формами

Название контрола | Обозначение | Описание
:------------|:------------| :------------
Удалить | | Удаление класса данных или формы, привязанной к классу данных
Добавить сущность | | Создание нового объекта данных
Добавить форму редактирование | | Создание формы редактирования для объекта данных
Добавить спискову форму | | Создание списковой формы для объекта данных
Редактировать | | Редактирование выбранного класса данных, списковой формы или формы редактирования
Открыть список всех классов | | Переход к списку классов данных

## Правое "дерево"

Справа на странице находится дерево для редактирования навигационной структуры (структуры меню) проектируемого приложения. В данном дереве можно создавать меню произвольной вложенности, группируя элементы меню по «папкам» на различных уровнях. Элементами навигации (не считая «папки», которые используются для группировки элементов) могут быть списковые формы, формы редактирования или пункты меню, ссылающиеся на произвольный адрес URL.

### Инструменты работы с навигацией

Название контрола | Обозначение | Описание
:------------|:------------| :------------
Добавить URL || Добавление нового элемента навигации (пункта меню) со ссылкой на произвольный адрес URL
Редактировать || Редактирование свойств (заголовка и описания) выбранного элемента навигации
Удалить || Удаление элемента навигации
Добавить каталог || Добавление новой «папки» в структуру навигации
Переместить вверх/ переместить вниз || Изменение порядка элементов навигации (перемещение вверх и вниз)
Сохранить || Сохранение структуры навигации


text:
    <meta content="HTML Tidy for HTML5 for Linux version 5.2.0" name="generator"/>
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
    <meta content="FreeRTOS is an open source, small footprint RTOS for microcontrollers. This page describes the vTaskPrioritySet() FreeRTOS API function which is part of the RTOS task control API." name="description"/>
    <meta content="vTaskPrioritySet, task, thread, RTOS task, RTOS thread, mailbox, RTOS mailbox, FreeRTOS API, RTOS API, FreeRTOS queue, RTOS queue, queue API, xQueueCreate, ARM7, ARM9, Cortex-M3, RX600, RX62N, 8051, 8052, Free RTOS, royalty free, RTOS, free, RTOS free, open source, real time, embedded, FreeRTOS, source code, AVR, GNU, PIC, PIC18, development tools" name="keywords"/>
    <title>This page describes the RTOS vTaskPrioritySet() FreeRTOS
      API function which is part of the RTOS task control API. FreeRTOS
      is a professional grade, small footprint, open source RTOS for
      microcontrollers.</title>

    <link href="doxygen.css" rel="stylesheet"/>

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

    <link href="code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css" rel="stylesheet"/>

Quality RTOS & Embedded
                                      Software

                          Hint: Use the tree menu
                            to navigate groups of related pages

vTaskPrioritySet

                      [Task
                      Control]

                    task. h

void vTaskPrioritySet(
                      TaskHandle_t xTask, UBaseType_t uxNewPriority
                      );

INCLUDE_vTaskPrioritySet must be defined as 1 for this function to be available. See the RTOS Configuration documentation for more information.

Set the priority of any task.

A context switch will occur before the function returns if the priority being set is higher than the currently executing task.

Parameters:

                              xTask

                              Handle to the
                                task for which the priority is being
                                set. Passing a NULL handle results in
                                the priority of the calling task being
                                set.

                              uxNewPriority

                              The priority to
                                which the task will be set.

Example usage:

void vAFunction( void ) { TaskHandle_t
                      xHandle;

// Create a task, storing the handle.
                      xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL,
                      tskIDLE_PRIORITY, &xHandle );

// ...

// Use the handle to raise the priority of
                      the created task. vTaskPrioritySet( xHandle,
                      tskIDLE_PRIORITY + 1 );

// ...

// Use a NULL handle to raise our priority to
                      the same value. vTaskPrioritySet( NULL,
                      tskIDLE_PRIORITY + 1 ); }

[
                      Back to the top ]    [ About FreeRTOS
                      ]    [ Sitemap
                      ]    [

                      Report an error on this page (with anti-spam) ]

Copyright (C) 2004-2010 Richard Barry. Copyright
                      (C) 2010-2016 Real Time Engineers Ltd.

                      Any and all data, files, source code, html
                      content and documentation included in the
                      FreeRTOSTM
                      distribution or available on this site are the
                      exclusive property of Real Time Engineers Ltd..
                      See the files license.txt (included in the
                      distribution) and this copyright notice for more information.
                      FreeRTOSTM and FreeRTOS.orgTM are trade marks of Real Time Engineers
                      Ltd.


text:
<?php

class Google_Service_Dfareporting_DimensionFilter extends Google_Model
{
  public $dimensionName;
  public $kind;
  public $value;

  public function setDimensionName($dimensionName)
  {
    $this->dimensionName = $dimensionName;
  }
  public function getDimensionName()
  {
    return $this->dimensionName;
  }
  public function setKind($kind)
  {
    $this->kind = $kind;
  }
  public function getKind()
  {
    return $this->kind;
  }
  public function setValue($value)
  {
    $this->value = $value;
  }
  public function getValue()
  {
    return $this->value;
  }
}


text:
"""
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

For example:
Given the below binary tree and sum = 22,
              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1
return
[
   [5,4,11,2],
   [5,8,4,5]
]
"""
__author__ = 'Danyang'
# Definition for a  binary tree node
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution:
    def pathSum(self, root, sum):
        """
        :param root: TreeNode
        :param sum: integer
        :return: a list of lists of integers
        """
        result = []
        self.accumulatePathSum(root, sum, [], result)
        return result

    def accumulatePathSum(self, root, sum, cur_path, result):
        """
        DFS
        Similar to previous path sum
        """
        # trivial
        if not root:
            return

        sum = sum - root.val
        cur_path.append(root.val)
        # terminal condition
        if sum==0 and root.left is None and root.right is None:
            result.append(list(cur_path))  # new copy
            return

        # dfs with pre-checking
        if root.left: self.accumulatePathSum(root.left, sum, list(cur_path), result)  # new copy
        if root.right: self.accumulatePathSum(root.right, sum, list(cur_path), result)  # new copy


text:
import './tasks/table';
import './tasks/release';
import './tasks/clean';


text:
<!DOCTYPE html>

    <meta name="project_path" value="/nodejs/docs/reference/_project.yaml">
    <meta name="book_path" value="/nodejs/docs/reference/scheduler/latest/_book.yaml">

    {% verbatim %}

Interface google.cloud.scheduler.v1.IOAuthToken (2.1.1)

Properties of a OAuthToken.

Package

  @google-cloud/scheduler!

Properties

scope

scope?: (string|null);

OAuthToken scope

  Property Value

        Type
        Description

        (string|null)

serviceAccountEmail

serviceAccountEmail?: (string|null);

OAuthToken serviceAccountEmail

  Property Value

        Type
        Description

        (string|null)

    {% endverbatim %}


text:
<DOC id="NYT_ENG_20130603.0008" type="story" from_file="/newswire/daily_process/nyt/english/source_data/20130603/20130603,0667a514b8c3472dceccd7f354ac0d59.xml">
<HEADLINE>
SCORES DIE IN FIRE AT CHINESE POULTRY PLANT
</HEADLINE>
<TEXT>

Sue-Lin Wong contributed research from Beijing.

HONG KONG - Explosions and fire tore through parts of a poultry plant in northeast China on Monday, killing at least 119 people, in one of the country's worst factory accidents in recent years.

Residents near the factory, the Baoyuanfeng Poultry Plant, in Jilin province, heard blasts at about 6 a.m. Parts of the plant were engulfed in flames but it was unclear whether the fire broke out before or after the explosions, Chinese television reported. The Jilin province government said on its microblog news site that 119 people were confirmed dead.

"When I woke up, there was smoke rising in the air and sirens and you knew straight away that it was bad news," Dong Wenjun, a metal trader in the town of Mishazi, where the plant is, said in a telephone interview. "But I didn't expect it to be this bad. They were all local people, I think."

The police and officials at the plant are investigating the cause of the accident, said the television report. It showed the charred remains of a shed attached to a larger building, which also burned.

The police evacuated residents near the plant, fearing more explosions from gas stored there, the China News Service reported. Dozens of factory workers were taken to the hospital, mostly for breathing difficulties from inhaling toxic gases, the report said.

The state-run news agency, Xinhua, quoted an employee of the plant, Guo Yan, as saying she heard a boom and then people shouting that there was a fire. One of the fire exits was blocked and she had to escape through another exit, she told Xinhua.

"People were all rushing, pressing and crushing each other," said Guo. "I fell over and had to crawl forward using all my might."

China's food-processing industry has grown rapidly in recent years to feed an increasingly prosperous and urbanized population and the poultry plant appeared to be one beneficiary of that growth.

Dehui City, which administers the area that includes the poultry plant, has promoted itself as a base for commercial agriculture, animal feed and food processing. By 2011, Dehui's poultry industry could produce 250 million broiler chickens a year and slaughter 150 million of them, according to information on the Jilin government's website.

Jilin Baoyuanfeng Poultry, which owns the Mishazi plant, was started in 2009 and has more than 1,200 employees, the China News Service said. The company, which raises and slaughters poultry, can produce 67,000 tons of chicken products every year, the Agriculture Ministry said on its website in 2010.

China's rapid economic expansion has brought with it factories and mines troubled by work hazards, and frequent industrial accidents have drawn criticism that officials put economic growth before safety. The government does not issue detailed figures for industrial accidents but has said that in 2011 the number of people killed in mines, factories and other work sites fell to fewer than 10,000.

China's coal mines are notoriously unsafe. But Geoffrey Crothall, the communications director for China Labour Bulletin, an advocacy group based in Hong Kong, said he could not recall the last time there was a disaster of this magnitude in a factory or production plant.

In 1993, a fire in a toy factory in far southern China killed 87 workers, he said. In late 2000, a fire at a shopping center in Luoyang in Henan province in central China killed 309 people. Preliminary reports from the latest accident suggested that a fire escape exit may have been blocked or ineffective, he said.

"Clearly, the lack of proper fire escapes is a longstanding problem in many Chinese workplaces," said Crothall. He noted that it was too early to draw firm conclusions about the latest disaster. "But many factories are locked for what the owners or managers consider to be security reasons and fire exits are not properly maintained or given the priority they should be."

Some residents contacted by telephone said they had not heard of any safety problems at the poultry plant. "They are a pretty big, famous company in these parts and employ a lot of people," said Sun Wei, a delivery worker in the area.

</TEXT>
</DOC>


text:
{-# LANGUAGE DataKinds         #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeOperators     #-}

{-|
Module : Web.Mastodon.API.Accounts
Description : Logic for generating API stuff related to accounts (based on arbitrary id)
-}
module Web.Mastodon.API.Accounts
  ( Accounts
  , accountsApi
  , getAccountByUid
  , verifyCredentials
  , getFollowersForUid
  , getFollowingForUid
  , getStatusesForUid
  , followUid
  , unfollowUid
  , blockUid
  , unblockUid
  , muteUid
  , unmuteUid
  , getRelationships
  , searchAccounts
  ) where

import           Control.Monad.Trans.Reader
import           Data.Proxy
import qualified Data.Text                  as T
import           Servant.API
import           Servant.Client

import           Web.Mastodon.Auth
import           Web.Mastodon.Monad
import           Web.Mastodon.Types

-- TODO: Re-export Auth (and maybe types) to avoid others having to import it when importing api?

-- TODO: Int instead of Integer?
type AccountsInsecure = "accounts" :> Capture "id" (Uid Account) :> Get '[JSON] Account
                   :<|> "accounts" :> "verify_credentials" :> Get '[JSON] Account
                   :<|> "accounts" :> Capture "id" (Uid Account) :> "followers" :> Get '[JSON] [Account]
                   :<|> "accounts" :> Capture "id" (Uid Account) :> "following" :> Get '[JSON] [Account]
                   :<|> "accounts" :> Capture "id" (Uid Account) :> "statuses" :> QueryFlag "only_media" :> QueryFlag "exclude_replies" :> Get '[JSON] [Status]
                   :<|> "accounts" :> Capture "id" (Uid Account) :> "follow" :> Get '[JSON] Account
                   :<|> "accounts" :> Capture "id" (Uid Account) :> "unfollow" :> Get '[JSON] Account
                   :<|> "accounts" :> Capture "id" (Uid Account) :> "block" :> Get '[JSON] Account
                   :<|> "accounts" :> Capture "id" (Uid Account) :> "unblock" :> Get '[JSON] Account
                   :<|> "accounts" :> Capture "id" (Uid Account) :> "mute" :> Get '[JSON] Account
                   :<|> "accounts" :> Capture "id" (Uid Account) :> "unmute" :> Get '[JSON] Account
                   :<|> "accounts" :> "relationships" :> QueryParams "id" (Uid Account) :> Get '[JSON] [Relationship]
                   :<|> "accounts" :> "search" :> QueryParam "q" T.Text :> QueryParam "limit" Integer :> Get '[JSON] [Account]

-- | Secure Accounts API type
type Accounts = AuthWrapper (AuthProtect MastodonAuth) AccountsInsecure

accountsApi :: Proxy Accounts
accountsApi = Proxy

account_           :: Auth -> Uid Account -> ClientM Account
verifyCredentials_ :: Auth -> ClientM Account
followers_         :: Auth -> Uid Account -> ClientM [Account]
following_         :: Auth -> Uid Account -> ClientM [Account]
statuses_          :: Auth -> Uid Account -> Bool -> Bool -> ClientM [Status]
follow_            :: Auth -> Uid Account -> ClientM Account
unfollow_          :: Auth -> Uid Account -> ClientM Account
block_             :: Auth -> Uid Account -> ClientM Account
unblock_           :: Auth -> Uid Account -> ClientM Account
mute_              :: Auth -> Uid Account -> ClientM Account
unmute_            :: Auth -> Uid Account -> ClientM Account
relationships_     :: Auth -> [Uid Account] -> ClientM [Relationship]
search_            :: Auth -> Maybe T.Text -> Maybe Integer -> ClientM [Account]

account_
  :<|> verifyCredentials_
  :<|> followers_
  :<|> following_
  :<|> statuses_
  :<|> follow_
  :<|> unfollow_
  :<|> block_
  :<|> unblock_
  :<|> mute_
  :<|> unmute_
  :<|> relationships_
  :<|> search_
  = client accountsApi

-- | Retrieve an @Account@ from an account id.
getAccountByUid :: Uid Account -> Mastodon Account
getAccountByUid aid = ReaderT $ \t -> account_ (tokenToAuth t) aid

verifyCredentials :: Mastodon Account
verifyCredentials = ReaderT $ \t -> verifyCredentials_ $ tokenToAuth t

getFollowersForUid :: Uid Account -> Mastodon [Account]
getFollowersForUid aid = ReaderT $ \t -> followers_ (tokenToAuth t) aid

getFollowingForUid :: Uid Account -> Mastodon [Account]
getFollowingForUid aid = ReaderT $ \t -> following_ (tokenToAuth t) aid

getStatusesForUid :: Uid Account -> Bool -> Bool -> Mastodon [Status]
getStatusesForUid aid onlyMedia noReplies = ReaderT $ \t -> statuses_ (tokenToAuth t) aid onlyMedia noReplies

followUid :: Uid Account -> Mastodon Account
followUid tid = ReaderT $ \t -> follow_ (tokenToAuth t) tid

unfollowUid :: Uid Account -> Mastodon Account
unfollowUid tid = ReaderT $ \t -> unfollow_ (tokenToAuth t) tid

blockUid :: Uid Account -> Mastodon Account
blockUid tid = ReaderT $ \t -> block_ (tokenToAuth t) tid

unblockUid :: Uid Account -> Mastodon Account
unblockUid tid = ReaderT $ \t -> unblock_ (tokenToAuth t) tid

muteUid :: Uid Account -> Mastodon Account
muteUid tid = ReaderT $ \t -> mute_ (tokenToAuth t) tid

unmuteUid :: Uid Account -> Mastodon Account
unmuteUid tid = ReaderT $ \t -> unmute_ (tokenToAuth t) tid

getRelationships :: [Uid Account] -> Mastodon [Relationship]
getRelationships tids = ReaderT $ \t -> relationships_ (tokenToAuth t) tids

searchAccounts :: Maybe T.Text -> Maybe Integer -> Mastodon [Account]
searchAccounts q i = ReaderT $ \t -> search_ (tokenToAuth t) q i


text:
<?php
require __DIR__ . '/../vendor/autoload.php';

use Facebook\WebDriver\Remote\RemoteWebDriver;

$config_file = getenv('CONFIG_FILE');
if(!$config_file) $config_file = 'tests-browserstack/browserstack.json';
$GLOBALS['CONFIG'] = json_decode(file_get_contents($config_file), true);

$GLOBALS['BROWSERSTACK_USERNAME'] = getenv('BROWSERSTACK_USERNAME');
if(!$GLOBALS['BROWSERSTACK_USERNAME']) $GLOBALS['BROWSERSTACK_USERNAME'] = $CONFIG['user'];

$GLOBALS['BROWSERSTACK_ACCESS_KEY'] = getenv('BROWSERSTACK_ACCESS_KEY');
if(!$GLOBALS['BROWSERSTACK_ACCESS_KEY']) $GLOBALS['BROWSERSTACK_ACCESS_KEY'] = $CONFIG['key'];

abstract class BrowserStackTest extends PHPUnit_Framework_TestCase
{
    protected static $driver;
    protected static $bs_local;

    public static function setUpBeforeClass()
    {
        $CONFIG = $GLOBALS['CONFIG'];
        $task_id = getenv('TASK_ID') ? getenv('TASK_ID') : 0;

        $url = "https://" . $GLOBALS['BROWSERSTACK_USERNAME'] . ":" . $GLOBALS['BROWSERSTACK_ACCESS_KEY'] . "@" . $CONFIG['server'] ."/wd/hub";
        $caps = $CONFIG['environments'][$task_id];

        foreach ($CONFIG["capabilities"] as $key => $value) {
            if(!array_key_exists($key, $caps))
                $caps[$key] = $value;
        }

        if(array_key_exists("browserstack.local", $caps) && $caps["browserstack.local"])
        {
            $bs_local_args = array("key" => $GLOBALS['BROWSERSTACK_ACCESS_KEY']);
            self::$bs_local = new BrowserStack\Local();
            self::$bs_local->start($bs_local_args);
        }

        self::$driver = RemoteWebDriver::create($url, $caps);
    }

    public static function tearDownAfterClass()
    {
        self::$driver->quit();
        if(self::$bs_local) self::$bs_local->stop();
    }
}


text:
<!DOCTYPE HTML>

  <title>Test for Bug 391728</title>

  <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css" />

Mozilla Bug 391728


text:
//Modules act as naming containers that encapsulate other things like
//'classes, 'interfaces', etc.
module test
{
    export class MyTest {
        name = "hello";
        private ab = new PrivateTest();

        public myPublicMethod() : string {
            return this.ab.myMethod();
        }

    }

    class PrivateTest {
        //Exposing private value on private method only accessible within the scope of this module
        public myMethod() {
            return this.name1;
        }

        private name1 = "hi";
    }
}

interface ISimple {
    name: string;
}

class MyTest implements ISimple {
    name = "hello";
}

//var a = new test.PrivateTest(); //Not accessible - it's not exported on 'test'
var b = new MyTest();


text:
Installing WSO2 MSF4J (Micro-Services Framework for Java) framework into WSO2 Carbon Kernel
===========================================================================================

Download the latest source code of the WSO2 Carbon Kernel. This can be done via

* Download the WSO2 Carbon Kernel source code zip file from https://github.com/wso2/carbon-kernel

OR

* Git clone WSO2 Carbon Kernel
    * Navigate to the directory you want to git clone WSO2 Carbon Kernel
    * Open a terminal window and type `git clone https://github.com/wso2/carbon-kernel.git`

The directory of the WSO2 Carbon Kernel sources (typically known as "carbon-kernel") will referred to as <PRODUCT_HOME> from here onwards.

Follow the following steps in order to install the WSO2 MSF4J feature and it's dependencies to the WSO2 Carbon Kernel.

* Navigate to <PRODUCT_HOME>/distribution directory.

* Open pom.xml file and do the following changes

    * Add the following dependencies to the "dependencies" section of the pon.xml file

    ```xml
            <!-- MSF4J -->
            <!-- Dependancies -->
            <dependency>
                <groupId>org.wso2.carbon.metrics</groupId>
                <artifactId>org.wso2.carbon.metrics.core.feature</artifactId>
                <version>${carbon.metrics.version}</version>
                <type>zip</type>
            </dependency>
            <dependency>
                <groupId>org.wso2.carbon.metrics</groupId>
                <artifactId>org.wso2.carbon.metrics.jdbc.core.feature</artifactId>
                <version>${carbon.metrics.version}</version>
                <type>zip</type>
            </dependency>
            <dependency>
                <groupId>org.wso2.carbon.metrics</groupId>
                <artifactId>org.wso2.carbon.metrics.das.core.feature</artifactId>
                <version>${carbon.metrics.version}</version>
                <type>zip</type>
            </dependency>

            <dependency>
                <groupId>org.wso2.carbon.messaging</groupId>
                <artifactId>org.wso2.carbon.messaging.feature</artifactId>
                <version>${carbon.messaging.version}</version>
                <type>zip</type>
            </dependency>

            <dependency>
                <groupId>org.wso2.carbon.jndi</groupId>
                <artifactId>org.wso2.carbon.jndi.feature</artifactId>
                <version>${carbon.jndi.version}</version>
                <type>zip</type>
            </dependency>

            <dependency>
                <groupId>org.wso2.carbon.datasources</groupId>
                <artifactId>org.wso2.carbon.datasource.core.feature</artifactId>
                <version>${carbon.datasources.version}</version>
                <type>zip</type>
            </dependency>

            <dependency>
                <groupId>org.wso2.carbon.transport</groupId>
                <artifactId>org.wso2.carbon.transport.http.netty.feature</artifactId>
                <version>${carbon.transport.http.netty.version}</version>
                <type>zip</type>
            </dependency>

            <!-- MSF4J -->
            <dependency>
                <groupId>org.wso2.msf4j</groupId>
                <artifactId>org.wso2.msf4j.feature</artifactId>
                <version>${msffourj.version}</version>
                <type>zip</type>
            </dependency>

    ```

    * Navigate to the "plugins" section of the pom.xml file and find the plugin with the following information

    **Group ID:** `org.wso2.carbon.maven`
    **Artifact ID:** `carbon-feature-plugin`

    Add the following features inside `executions` > `execution` (goal = "generate-repo") > `configuration` > `features` element

    ``` xml
            <!-- MSF4J Features -->
            <feature>
                <id>org.wso2.carbon.metrics.core.feature</id>
                <version>${carbon.metrics.version}</version>
            </feature>
            <feature>
                <id>org.wso2.carbon.metrics.jdbc.core.feature</id>
                <version>${carbon.metrics.version}</version>
            </feature>
            <feature>
                <id>org.wso2.carbon.metrics.das.core.feature</id>
                <version>${carbon.metrics.version}</version>
            </feature>
            <feature>
                <id>org.wso2.carbon.messaging.feature</id>
                <version>${carbon.messaging.version}</version>
            </feature>
            <feature>
                <id>org.wso2.carbon.jndi.feature</id>
                <version>${carbon.jndi.version}</version>
            </feature>
            <feature>
                <id>org.wso2.carbon.datasource.core.feature</id>
                <version>${carbon.datasources.version}</version>
            </feature>
            <feature>
                <id>org.wso2.carbon.transport.http.netty.feature</id>
                <version>${carbon.transport.http.netty.version}</version>
            </feature>

            <!-- MSF4J -->
            <feature>
                <id>org.wso2.msf4j.feature</id>
                <version>${msffourj.version}</version>
            </feature>
    ```

    * Navigate to the "plugins" section of the pom.xml file and find the plugin with the following information (same plugin as the previous step)

    **Group ID:** `org.wso2.carbon.maven`
    **Artifact ID:** `carbon-feature-plugin`

    Add the following features inside `executions` > `execution` (goal = "install") > `configuration` > `features` element

    ``` xml
            <!-- MSF4J feature -->
            <feature>
                <id>org.wso2.carbon.metrics.core.feature.group</id>
                <version>${carbon.metrics.version}</version>
            </feature>
            <feature>
                <id>org.wso2.carbon.metrics.jdbc.core.feature.group</id>
                <version>${carbon.metrics.version}</version>
            </feature>
            <feature>
                <id>org.wso2.carbon.metrics.das.core.feature.group</id>
                <version>${carbon.metrics.version}</version>
            </feature>
            <feature>
                <id>org.wso2.carbon.messaging.feature.group</id>
                <version>${carbon.messaging.version}</version>
            </feature>

            <feature>
                <id>org.wso2.carbon.jndi.feature.group</id>
                <version>${carbon.jndi.version}</version>
            </feature>
            <feature>
                <id>org.wso2.carbon.datasource.core.feature.group</id>
                <version>${carbon.datasources.version}</version>
            </feature>
            <feature>
                <id>org.wso2.carbon.transport.http.netty.feature.group</id>
                <version>${carbon.transport.http.netty.version}</version>
            </feature>

            <!-- MSF4J -->
            <feature>
                <id>org.wso2.msf4j.feature.group</id>
                <version>${msffourj.version}</version>
            </feature>
    ```

* Build WSO2 Carbon Kernel by opening a terminal window and typing `mvn clean install`. The following prerequisites are required to complete this step

    * Oracle Java SE Development Kit (JDK) version 1.8.*
    * Apache Maven version 3.3.x

* Navigate to <PRODUCT_HOME>/distribution/target and find the `wso2carbon-kernel-{version}.zip` file. This version of the WSO2 Carbon Kernel now has the WSO2 MSF4J feature installed.

* In order to run the WSO2 Carbon Kernel, extract the above zip file to a location of preference, navigate to the /bin directory and run `carbon.sh` (Linux) or `carbon.bat` (Windows).


text:
FROM python:3.6.5
ADD . /Discord-Selfbot

RUN cd Discord-Selfbot && \
    pip install -r requirements.txt

CMD ["/Discord-Selfbot/run_linuxmac.sh"]


text:
module VelvetCushion
  class Stuffer

    attr_accessor :model

    def initialize(model)
      self.model = model
    end

    def stuff(source, opts = {})
      decoder = get_decoder(model, opts)
      hash = decoder.decode(source)

      stuff_from_hash model, hash
    end

    def stuff_from_hash(model, hash)
      hash.each do |key, value|
        inject(model, key.to_sym, value) if model.respond_to? key
      end
      model
    end

    private

      def inject(model, key, value)
        reflections = model.reflections[key.to_sym]
        if reflections.present?
          self.send "stuff_#{reflections.macro}", model, key, value
        else
          key_sym = :"#{key}="
          model.send(key_sym, value) if model.respond_to?(key_sym)
        end
      end

      def get_decoder(model, config = {})
        decoder = config[:decoder] ||  model.class.cushion_model_decoder || VelvetCushion.configuration.default_decoder
        decoder_classname = ActiveSupport::Inflector.camelize decoder
        class_from_string("VelvetCushion::Decoders::#{decoder_classname}").new
      end

      # Required for Ruby 1.9.3. Ruby 2 allows Object.const_get with delimiters
      def class_from_string(str)
        str.split('::').inject(Object) do |mod, class_name|
          mod.const_get(class_name)
        end
      end

      def stuff_has_many(model, key, value)
        inject_list(model, key, value)
      end
      alias :stuff_has_and_belongs_to_many :stuff_has_many

      def stuff_has_one(model, key, value)
        inject_object(model, key, value)
      end
      alias :stuff_belongs_to :stuff_has_one

      def create_related_object(model, key, value)
        rel_model = model.send(key).build
        rel_model.stuff_with(value, :decoder => :hash)
      end

      def create_singular_object(model, key, value)
        rel_model = model.send(:"build_#{key}")
        rel_model.stuff_with(value, :decoder => :hash)
      end

      def inject_object(model, key, value)
        rel_model = create_singular_object(model, key, value)
        model.send :"#{key}=", rel_model
      end

      def inject_list(model, key, value)
        value.each do |v|
          rel_model = create_related_object(model, key, v)
          model.send(key).send(:<<, rel_model)
        end
      end
    end
end


text:
package org.apache.geode.modules.session.catalina;

import static org.apache.geode.util.internal.UncheckedUtils.uncheckedCast;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.juli.logging.Log;
import org.junit.Test;

import org.apache.geode.cache.CustomExpiry;
import org.apache.geode.cache.EntryNotFoundException;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.RegionShortcut;
import org.apache.geode.cache.execute.Execution;
import org.apache.geode.distributed.DistributedSystem;
import org.apache.geode.modules.util.RegionConfiguration;

public abstract class AbstractSessionCacheTest {

  protected String sessionRegionName = "sessionRegion";
  private final String sessionRegionAttributesId = RegionShortcut.PARTITION.toString();
  private final boolean gatewayDeltaReplicationEnabled = true;
  private final boolean gatewayReplicationEnabled = true;
  private final boolean enableDebugListener = true;

  protected SessionManager sessionManager = mock(SessionManager.class);
  protected Region<String, HttpSession> sessionRegion = uncheckedCast(mock(Region.class));
  protected DistributedSystem distributedSystem = mock(DistributedSystem.class);
  protected Log logger = mock(Log.class);
  protected Execution<Object, Object, List<Object>> emptyExecution =
      uncheckedCast(mock(Execution.class));

  protected AbstractSessionCache sessionCache;

  @Test
  public void createRegionConfigurationSetsAppropriateValuesWithDefaultMaxInactiveInterval() {
    final RegionConfiguration config = spy(new RegionConfiguration());
    doReturn(config).when(sessionCache).getNewRegionConfiguration();

    when(sessionManager.getRegionName()).thenReturn(sessionRegionName);
    when(sessionManager.getRegionAttributesId()).thenReturn(sessionRegionAttributesId);
    when(sessionManager.getMaxInactiveInterval())
        .thenReturn(RegionConfiguration.DEFAULT_MAX_INACTIVE_INTERVAL);
    when(sessionManager.getEnableGatewayDeltaReplication())
        .thenReturn(gatewayDeltaReplicationEnabled);
    when(sessionManager.getEnableGatewayReplication()).thenReturn(gatewayReplicationEnabled);
    when(sessionManager.getEnableDebugListener()).thenReturn(enableDebugListener);

    sessionCache.createRegionConfiguration();

    verify(config).setRegionName(sessionRegionName);
    verify(config).setRegionAttributesId(sessionRegionAttributesId);
    verify(config, times(0)).setMaxInactiveInterval(anyInt());
    verify(config, times(0)).setCustomExpiry(any(CustomExpiry.class));
    verify(config).setEnableGatewayDeltaReplication(gatewayDeltaReplicationEnabled);
    verify(config).setEnableGatewayReplication(gatewayReplicationEnabled);
    verify(config).setEnableDebugListener(enableDebugListener);
  }

  @Test
  public void createRegionConfigurationSetsAppropriateValuesWithNonDefaultMaxInactiveInterval() {
    final RegionConfiguration config = spy(new RegionConfiguration());
    doReturn(config).when(sessionCache).getNewRegionConfiguration();

    when(sessionManager.getRegionName()).thenReturn(sessionRegionName);
    when(sessionManager.getRegionAttributesId()).thenReturn(sessionRegionAttributesId);
    final int nonDefaultMaxInactiveInterval = RegionConfiguration.DEFAULT_MAX_INACTIVE_INTERVAL + 1;
    when(sessionManager.getMaxInactiveInterval()).thenReturn(nonDefaultMaxInactiveInterval);
    when(sessionManager.getEnableGatewayDeltaReplication())
        .thenReturn(gatewayDeltaReplicationEnabled);
    when(sessionManager.getEnableGatewayReplication()).thenReturn(gatewayReplicationEnabled);
    when(sessionManager.getEnableDebugListener()).thenReturn(enableDebugListener);

    sessionCache.createRegionConfiguration();

    verify(config).setRegionName(sessionRegionName);
    verify(config).setRegionAttributesId(sessionRegionAttributesId);
    verify(config).setMaxInactiveInterval(nonDefaultMaxInactiveInterval);
    verify(config).setCustomExpiry(any(CustomExpiry.class));
    verify(config).setEnableGatewayDeltaReplication(gatewayDeltaReplicationEnabled);
    verify(config).setEnableGatewayReplication(gatewayReplicationEnabled);
    verify(config).setEnableDebugListener(enableDebugListener);
  }

  @Test
  public void destroySessionDoesNotThrowExceptionWhenGetOperatingRegionThrowsEntryNotFoundException() {
    final EntryNotFoundException exception = new EntryNotFoundException("Entry not found.");
    final String sessionId = "sessionId";
    // For Client/Server the operating Region is always the session Region, for peer to peer this is
    // only true when
    // local caching is not enabled. For the purposes of this test the behavior is equivalent
    // regardless of local
    // caching.
    when(sessionCache.getOperatingRegion()).thenReturn(sessionRegion);
    doThrow(exception).when(sessionRegion).destroy(sessionId);

    sessionCache.destroySession(sessionId);
    verify(sessionCache).getOperatingRegion();
  }
}


text:
layout: falloutnvrec
title: fopdoc
---
XDCR Subrecord
==========

As used in the [ACHR](../ACHR.md) and [ACRE](../ACRE.md) record types.

## Format

Name | Type | Info
-----|------|-----
Reference | formid | FormID of a [REFR](../REFR.md) record.
Unknown | ?? |


text:
package apoc.spatial;

import apoc.date.Date;
import apoc.util.JsonUtil;
import apoc.util.TestUtil;
import apoc.util.Util;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.net.URL;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Result;
import org.neo4j.procedure.Name;
import org.neo4j.procedure.Procedure;
import org.neo4j.test.TestGraphDatabaseFactory;

import static apoc.util.MapUtil.map;
import static apoc.util.TestUtil.testCallCount;
import static apoc.util.TestUtil.testCallEmpty;
import static apoc.util.TestUtil.testResult;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

public class SpatialTest {

    private GraphDatabaseService db;
    private Map<String, Map<String, Object>> eventNodes = new LinkedHashMap<>();
    private Map<String, Map<String, Object>> spaceNodes = new LinkedHashMap<>();
    private Map<String, Map<String, Object>> spaceTimeNodes = new LinkedHashMap<>();

    public static class MockGeocode {
        public static Map<String, Map> geocodeResults = null;

        public MockGeocode() {
        }

        @Procedure("apoc.spatial.geocodeOnce")
        public Stream<Geocode.GeoCodeResult> geocodeOnce(@Name("location") String address) {
            return geocode(address, 1);
        }

        @Procedure("apoc.spatial.geocode")
        public Stream<Geocode.GeoCodeResult> geocode(@Name("location") String address, @Name("maxResults") long maxResults) {
            if (geocodeResults != null && geocodeResults.containsKey(address)) {
                Map data = geocodeResults.get(address);
                return Stream.of(new Geocode.GeoCodeResult(Util.toDouble(data.get("lat")), Util.toDouble(data.get("lon")), String.valueOf(data.get("display_name")), data));
            } else {
                return Stream.empty();
            }
        }
    }

    @Before
    public void setUp() throws Exception {
        db = new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().setConfig("apoc.import.file.enabled","true").newGraphDatabase();
        TestUtil.registerProcedure(db, Date.class);
        TestUtil.registerProcedure(db, MockGeocode.class);
        URL url = ClassLoader.getSystemResource("spatial.json");
        Map tests = (Map) JsonUtil.loadJson(url.toString()).findFirst().orElse(null);
        for (Object event : (List) tests.get("events")) {
            addEventData((Map) event);
        }
        MockGeocode.geocodeResults = (Map<String, Map>) tests.get("geocode");
    }

    private void addEventData(Map<String, Object> event) {
        Map<String, Object> params = map("params", event);
        Result result = db.execute("CREATE (e:Event {params})", params);
        int created = result.getQueryStatistics().getNodesCreated();
        assertTrue("Expected a node to be created", created == 1);
        String name = event.get("name").toString();
        if (!event.containsKey("toofar")) {
            spaceNodes.put(name, event);
            if (!event.containsKey("toosoon") && !event.containsKey("toolate")) {
                spaceTimeNodes.put(name, event);
            }
        }
        eventNodes.put(name, event);
    }

    @After
    public void tearDown() {
        db.shutdown();
    }

    @Test
    public void testSimpleGeocode() {
        String query = "MATCH (a:Event) \n" +
                "WHERE exists(a.address) AND exists(a.name) \n" +
                "CALL apoc.spatial.geocodeOnce(a.address) YIELD location\n" +
                "RETURN a.name, location.latitude AS latitude, \n" +
                "location.longitude AS longitude, location.description AS description";
        testCallCount(db, query, null, eventNodes.size());
    }

    @Test
    public void testGeocodePointAndDistance() {
        String query = "WITH point({latitude: 48.8582532, longitude: 2.294287}) AS eiffel\n" +
                "MATCH (a:Event) \n" +
                "WHERE exists(a.address)\n" +
                "CALL apoc.spatial.geocodeOnce(a.address) YIELD location\n" +
                "WITH location, distance(point(location), eiffel) AS distance\n" +
                "WHERE distance < 5000\n" +
                "RETURN location.description AS description, distance\n" +
                "ORDER BY distance\n" +
                "LIMIT 100\n";
        testCallCount(db, query, null, spaceNodes.size());
    }

    @Test
    public void testGraphRefactoring() {
        String refactorQuery = "MATCH (a:Event) \n" +
                "WHERE exists(a.address) AND NOT exists(a.latitude)\n" +
                "WITH a LIMIT 1000\n" +
                "CALL apoc.spatial.geocodeOnce(a.address) YIELD location \n" +
                "SET a.latitude = location.latitude\n" +
                "SET a.longitude = location.longitude";
        testCallEmpty(db, refactorQuery, null);
        String query = "WITH point({latitude: 48.8582532, longitude: 2.294287}) AS eiffel\n" +
                "MATCH (a:Event) \n" +
                "WHERE exists(a.latitude) AND exists(a.longitude)\n" +
                "WITH a, distance(point(a), eiffel) AS distance\n" +
                "WHERE distance < 5000\n" +
                "RETURN a.name AS event, distance\n" +
                "ORDER BY distance\n" +
                "LIMIT 100\n";
        testCallCount(db, query, null, spaceNodes.size());
    }

    @Test
    public void testAllTheThings() throws Exception {
        String query = "WITH apoc.date.parse('2016-06-01 00:00:00','h') as due_date,\n" +
                "     point({latitude: 48.8582532, longitude: 2.294287}) as eiffel\n" +
                "MATCH (e:Event)\n" +
                "WHERE exists(e.address) AND exists(e.datetime)\n" +
                "WITH apoc.date.parse(e.datetime,'h') as hours, e, due_date, eiffel\n" +
                "CALL apoc.spatial.geocodeOnce(e.address) YIELD location\n" +
                "WITH e, location,\n" +
                "     distance(point(location), eiffel) as distance,\n" +
                "     (due_date - hours)/24.0 as days_before_due\n" +
                "WHERE distance < 5000 AND days_before_due < 14 AND hours < due_date\n" +
                "RETURN e.name as event, e.datetime as date,\n" +
                "       location.description as description, distance\n" +
                "ORDER BY distance\n" +
                "LIMIT 100\n";
        int expectedCount = spaceTimeNodes.size();
        testResult(db, query, res -> {
            int left = expectedCount;
            while (left > 0) {
                assertTrue("Expected " + expectedCount + " results, but got only " + (expectedCount - left),
                        res.hasNext());
                Map<String, Object> result = res.next();
                assertTrue("Event should have 'event' property", result.containsKey("event"));
                String name = (String) result.get("event");
                assertTrue("Event '" + name + "' was not expected", spaceTimeNodes.containsKey(name));
                left--;
            }
            assertFalse("Expected " + expectedCount + " results, but there are more ", res.hasNext());
        });
    }
}


text:
var createMessagesIndex = function(client,indexName){
  client.indices.create({
    index: indexName,
    body: {
      settings: {
        number_of_shards: 3,
        number_of_replicas: 0
      },
      mappings: {
        messages: {
          properties: {
            timestamp: {
              type: "date"
            },
            myUserId: {
              type: "string",
              index: "not_analyzed"
            },
            profileImageUrl: {
              type: "string",
              index: "not_analyzed"
            },
            displayName: {
              type: "string"
            },
            message: {
              type: "string"
            },
            messageType: {
              type: "string",
              index: "not_analyzed"
            },
            messageSecret: {
              type: "string",
              index: "not_analyzed"
            },
            payloadId: {
              type: "string",
              index: "not_analyzed"
            },
            payloadType: {
              type: "string",
              index: "not_analyzed"
            },
            location: {
              type: "geo_point",
            },
            radius: {
              type: "float"
            },
            isReady:{
              type: "boolean"
            },
            visibility: {
              precision: "1m",
              tree: "quadtree",
              type: "geo_shape"
            }
          }
        }
      }
    }
  }, function(error, response){
    console.log('response in creating indecies ' + error);
  });
};

exports.createMessagesIndex = createMessagesIndex;


text:
namespace Imf {

using Imath::Box2i;
using Imath::V2i;
using std::string;
using std::vector;

namespace {

struct TInSliceInfo
{
    PixelType   typeInFrameBuffer;
    PixelType   typeInFile;
    char *      base;
    size_t      xStride;
    size_t      yStride;
    bool        fill;
    bool        skip;
    double      fillValue;

    TInSliceInfo (PixelType typeInFrameBuffer = HALF,
                  PixelType typeInFile = HALF,
                  char *base = 0,
                  size_t xStride = 0,
                  size_t yStride = 0,
                  bool fill = false,
                  bool skip = false,
                  double fillValue = 0.0);
};

TInSliceInfo::TInSliceInfo (PixelType tifb,
                            PixelType tifl,
                            char *b,
                            size_t xs, size_t ys,
                            bool f, bool s,
                            double fv)
:
    typeInFrameBuffer (tifb),
    typeInFile (tifl),
    base (b),
    xStride (xs),
    yStride (ys),
    fill (f),
    skip (s),
    fillValue (fv)
{
    // empty
}

} // namespace

//
// struct TiledInputFile::Data stores things that will be
// needed between calls to readTile()
//

struct TiledInputFile::Data
{
    Header	    header;		    // the image header
    TileDescription tileDesc;		    // describes the tile layout
    int		    version;		    // file's version
    FrameBuffer	    frameBuffer;	    // framebuffer to write into
    LineOrder	    lineOrder;		    // the file's lineorder
    int		    minX;		    // data window's min x coord
    int		    maxX;		    // data window's max x coord
    int		    minY;		    // data window's min y coord
    int		    maxY;		    // data window's max x coord

    //
    // cached tile information:
    //

    int		    numXLevels;		    // number of x levels
    int		    numYLevels;		    // number of y levels
    int *	    numXTiles;		    // number of x tiles at a level
    int *	    numYTiles;		    // number of y tiles at a level

    TileOffsets	    tileOffsets;	    // stores offsets in file for
					    // each tile

    bool	    fileIsComplete;	    // True if no tiles are missing
    					    // in the file

    Int64	    currentPosition;        // file offset for current tile,
					    // used to prevent unnecessary
					    // seeking

    Compressor*	    compressor;		    // the compressor
    Compressor::Format  format;		    // compressor's data format
    vector<TInSliceInfo> slices;	    // info about channels in file
    IStream *	    is;			    // file stream to read from

    size_t	    bytesPerPixel;          // size of an uncompressed pixel

    size_t	    maxBytesPerTileLine;    // combined size of a line
					    // over all channels

    size_t	    tileBufferSize;	    // size of the tile buffer
    Array<char>	    tileBuffer;		    // holds a single tile
    const char*	    uncompressedData;	    // the uncompressed tile

    bool	    deleteStream;	    // should we delete the stream
					    // ourselves? or does someone
					    // else do it?
     Data (bool deleteStream);
    ~Data ();
};

TiledInputFile::Data::Data (bool del):
    numXTiles (0),
    numYTiles (0),
    compressor (0),
    is (0),
    uncompressedData (0),
    deleteStream (del)
{
    // empty
}

TiledInputFile::Data::~Data ()
{
    delete [] numXTiles;
    delete [] numYTiles;
    delete compressor;

    if (deleteStream)
	delete is;
}

namespace {

void
readTileData (TiledInputFile::Data *ifd,
	      int dx, int dy,
	      int lx, int ly,
              int &dataSize)
{
    //
    // Read a single tile block from the file
    //

    //
    // Look up the location for this tile in the Index and
    // seek to that position if necessary
    //

    Int64 tileOffset = ifd->tileOffsets (dx, dy, lx, ly);

    if (tileOffset == 0)
    {
        THROW (Iex::InputExc, "Tile (" << dx << ", " << dy << ", " <<
			      lx << ", " << ly << ") is missing.");
    }

    //
    // Seek to the start of the tile in the file,
    // if necessary.
    //

    if (ifd->currentPosition != tileOffset)
        ifd->is->seekg (tileOffset);

    #ifdef DEBUG

	assert (ifd->is->tellg() == tileOffset);

    #endif

    //
    // Read the first few bytes of the tile (the header).
    // Test that the tile coords and the level number are
    // correct.
    //

    int tileXCoord, tileYCoord, levelX, levelY;

    Xdr::read <StreamIO> (*ifd->is, tileXCoord);
    Xdr::read <StreamIO> (*ifd->is, tileYCoord);
    Xdr::read <StreamIO> (*ifd->is, levelX);
    Xdr::read <StreamIO> (*ifd->is, levelY);
    Xdr::read <StreamIO> (*ifd->is, dataSize);

    if (tileXCoord != dx)
        throw Iex::InputExc ("Unexpected tile x coordinate.");

    if (tileYCoord != dy)
        throw Iex::InputExc ("Unexpected tile y coordinate.");

    if (levelX != lx)
        throw Iex::InputExc ("Unexpected tile x level number coordinate.");

    if (levelY != ly)
        throw Iex::InputExc ("Unexpected tile y level number coordinate.");

    if (dataSize > (int) ifd->tileBufferSize)
        throw Iex::InputExc ("Unexpected tile block length.");

    //
    // Read the pixel data.
    //

    ifd->is->read (ifd->tileBuffer, dataSize);

    //
    // Keep track of which tile is the next one in
    // the file, so that we can avoid redundant seekg()
    // operations (seekg() can be fairly expensive).
    //

    ifd->currentPosition = tileOffset + 5 * Xdr::size<int>() + dataSize;
}

void
readNextTileData (TiledInputFile::Data *ifd,
		  int &dx, int &dy,
		  int &lx, int &ly,
		  int &dataSize)
{
    //
    // Read the next tile block from the file
    //

    //
    // Read the first few bytes of the tile (the header).
    //

    Xdr::read <StreamIO> (*ifd->is, dx);
    Xdr::read <StreamIO> (*ifd->is, dy);
    Xdr::read <StreamIO> (*ifd->is, lx);
    Xdr::read <StreamIO> (*ifd->is, ly);
    Xdr::read <StreamIO> (*ifd->is, dataSize);

    if (dataSize > (int) ifd->tileBufferSize)
        throw Iex::InputExc ("Unexpected tile block length.");

    //
    // Read the pixel data.
    //

    ifd->is->read (ifd->tileBuffer, dataSize);

    //
    // Keep track of which tile is the next one in
    // the file, so that we can avoid redundant seekg()
    // operations (seekg() can be fairly expensive).
    //

    ifd->currentPosition += 5 * Xdr::size<int>() + dataSize;
}

} // namespace

TiledInputFile::TiledInputFile (const char fileName[]):
    _data (new Data (true))
{
    //
    // This constructor is called when a user
    // explicitly wants to read a tiled file.
    //

    try
    {
	_data->is = new StdIFStream (fileName);
	_data->header.readFrom (*_data->is, _data->version);
	initialize();
    }
    catch (Iex::BaseExc &e)
    {
	delete _data;

	REPLACE_EXC (e, "Cannot open image file "
			"\"" << fileName << "\". " << e);
	throw;
    }
}

TiledInputFile::TiledInputFile (IStream &is):
    _data (new Data (false))
{
    //
    // This constructor is called when a user
    // explicitly wants to read a tiled file.
    //

    try
    {
	_data->is = &is;
	_data->header.readFrom (*_data->is, _data->version);
	initialize();
    }
    catch (Iex::BaseExc &e)
    {
	delete _data;

	REPLACE_EXC (e, "Cannot open image file "
			"\"" << is.fileName() << "\". " << e);
	throw;
    }
}

TiledInputFile::TiledInputFile (const Header &header, IStream *is, int version):
    _data (new Data (false))
{
    //
    // This constructor called by class Imf::InputFile
    // when a user wants to just read an image file, and
    // doesn't care or know if the file is tiled.
    //

    _data->is = is;
    _data->header = header;
    _data->version = version;
    initialize();
}

void
TiledInputFile::initialize ()
{
    if (!isTiled (_data->version))
	throw Iex::ArgExc ("Expected a tiled file but the file is not tiled.");

    _data->header.sanityCheck (true);

    _data->tileDesc = _data->header.tileDescription();
    _data->lineOrder = _data->header.lineOrder();

    //
    // Save the dataWindow information
    //

    const Box2i &dataWindow = _data->header.dataWindow();
    _data->minX = dataWindow.min.x;
    _data->maxX = dataWindow.max.x;
    _data->minY = dataWindow.min.y;
    _data->maxY = dataWindow.max.y;

    //
    // Precompute level and tile information to speed up utility functions
    //

    precalculateTileInfo (_data->tileDesc,
			  _data->minX, _data->maxX,
			  _data->minY, _data->maxY,
			  _data->numXTiles, _data->numYTiles,
			  _data->numXLevels, _data->numYLevels);

    _data->bytesPerPixel = calculateBytesPerPixel (_data->header);

    _data->maxBytesPerTileLine = _data->bytesPerPixel * _data->tileDesc.xSize;

    _data->compressor = newTileCompressor (_data->header.compression(),
					   _data->maxBytesPerTileLine,
					   tileYSize(),
					   _data->header);

    _data->format = _data->compressor? _data->compressor->format():
				       Compressor::XDR;

    _data->tileBufferSize = _data->maxBytesPerTileLine * tileYSize();
    _data->tileBuffer.resizeErase (_data->tileBufferSize);

    _data->uncompressedData = 0;

    _data->tileOffsets = TileOffsets (_data->tileDesc.mode,
				      _data->numXLevels,
				      _data->numYLevels,
				      _data->numXTiles,
				      _data->numYTiles);

    _data->tileOffsets.readFrom (*(_data->is), _data->fileIsComplete);

    _data->currentPosition = _data->is->tellg();
}

TiledInputFile::~TiledInputFile ()
{
    delete _data;
}

const char *
TiledInputFile::fileName () const
{
    return _data->is->fileName();
}

const Header &
TiledInputFile::header () const
{
    return _data->header;
}

int
TiledInputFile::version () const
{
    return _data->version;
}

void
TiledInputFile::setFrameBuffer (const FrameBuffer &frameBuffer)
{
    //
    // Set the frame buffer
    //

    //
    // Check if the new frame buffer descriptor is
    // compatible with the image file header.
    //

    const ChannelList &channels = _data->header.channels();

    for (FrameBuffer::ConstIterator j = frameBuffer.begin();
         j != frameBuffer.end();
         ++j)
    {
        ChannelList::ConstIterator i = channels.find (j.name());

        if (i == channels.end())
            continue;

        if (i.channel().xSampling != j.slice().xSampling ||
            i.channel().ySampling != j.slice().ySampling)
        {
            THROW (Iex::ArgExc, "X and/or y subsampling factors "
				"of \"" << i.name() << "\" channel "
				"of input file \"" << fileName() << "\" are "
				"not compatible with the frame buffer's "
				"subsampling factors.");
        }
    }

    //
    // Initialize the slice table for readPixels().
    //

    vector<TInSliceInfo> slices;
    ChannelList::ConstIterator i = channels.begin();

    for (FrameBuffer::ConstIterator j = frameBuffer.begin();
         j != frameBuffer.end();
         ++j)
    {
        while (i != channels.end() && strcmp (i.name(), j.name()) < 0)
        {
            //
            // Channel i is present in the file but not
            // in the frame buffer; data for channel i
            // will be skipped during readPixels().
            //

            slices.push_back (TInSliceInfo (i.channel().type,
					    i.channel().type,
					    0, // base
					    0, // xStride
					    0, // yStride
					    false,  // fill
					    true, // skip
					    0.0)); // fillValue
            ++i;
        }

        bool fill = false;

        if (i == channels.end() || strcmp (i.name(), j.name()) > 0)
        {
            //
            // Channel i is present in the frame buffer, but not in the file.
            // In the frame buffer, slice j will be filled with a default value.
            //

            fill = true;
        }

        slices.push_back (TInSliceInfo (j.slice().type,
                                        fill? j.slice().type: i.channel().type,
                                        j.slice().base,
                                        j.slice().xStride,
                                        j.slice().yStride,
                                        fill,
                                        false, // skip
                                        j.slice().fillValue));

        if (i != channels.end() && !fill)
            ++i;
    }

    while (i != channels.end())
    {
	//
	// Channel i is present in the file but not
	// in the frame buffer; data for channel i
	// will be skipped during readPixels().
	//

	slices.push_back (TInSliceInfo (i.channel().type,
					i.channel().type,
					0, // base
					0, // xStride
					0, // yStride
					false,  // fill
					true, // skip
					0.0)); // fillValue
	++i;
    }

    //
    // Store the new frame buffer.
    //

    _data->frameBuffer = frameBuffer;
    _data->slices = slices;
}

const FrameBuffer &
TiledInputFile::frameBuffer () const
{
    return _data->frameBuffer;
}

bool
TiledInputFile::isComplete () const
{
    return _data->fileIsComplete;
}

void
TiledInputFile::readTile (int dx, int dy, int lx, int ly)
{
    //
    // Read a tile from the file into the framebuffer
    //

    try
    {
        if (_data->slices.size() == 0)
	{
            throw Iex::ArgExc ("No frame buffer specified "
			       "as pixel data destination.");
	}

        if (!isValidTile (dx, dy, lx, ly))
        {
            THROW (Iex::ArgExc, "Tile (" << dx << ", " << dy << ", " <<
				lx << "," << ly << ") is not a valid tile.");
        }

	//
        // Calculate information about the tile
	//

        Box2i tileRange = dataWindowForTile (dx, dy, lx, ly);

        int numPixelsPerScanLine = tileRange.max.x - tileRange.min.x + 1;

        int numPixelsInTile = (tileRange.max.x - tileRange.min.x + 1) *
                              (tileRange.max.y - tileRange.min.y + 1);

        int sizeOfTile = _data->bytesPerPixel * numPixelsInTile;

        //
        // The forceXdr flag is used to force the lineBuffer to be
	// interpreted as Xdr.  This is needed because some compressors
	// can store in the machine's native format, but when a lineBuffer
	// is not compressed, it has to be saved in Xdr format so that
	// it works across machines with different byte orders.
        //

        bool forceXdr = false;

        //
        // Read the data block for this tile into _data->tileBuffer.
        //

        int dataSize;
        readTileData (_data, dx, dy, lx, ly, dataSize);

        //
        // Uncompress the data.
        //

        if (_data->compressor && dataSize < sizeOfTile)
        {
            dataSize = _data->compressor->uncompressTile
			    (_data->tileBuffer,
			     dataSize, tileRange,
			     _data->uncompressedData);
        }
        else
        {
	    //
            // If the line is uncompressed, but the compressor
            // says that its in native format, don't believe it.
	    //

            if (_data->format != Compressor::XDR)
                forceXdr = true;
            _data->uncompressedData = _data->tileBuffer;
        }

        //
        // Convert the tile of pixel data back
        // from the machine-independent representation, and
        // store the result in the frame buffer.
        //

        const char *readPtr = _data->uncompressedData; // points to where we
						       // read from in the
						       // tile block
	//
	// Iterate over the scan lines in the tile.
	//

	for (int y = tileRange.min.y; y <= tileRange.max.y; ++y)
	{
	    //
	    // Iterate over all image channels.
	    //

	    for (unsigned int i = 0; i < _data->slices.size(); ++i)
	    {
		const TInSliceInfo &slice = _data->slices[i];

		//
		// Iterate over the sampled pixels.
		//

		if (slice.skip)
		{
		    //
		    // The file contains data for this channel, but
		    // the frame buffer contains no slice for this channel.
		    //

		    switch (slice.typeInFile)
		    {
		      case UINT:

			Xdr::skip <CharPtrIO>
			    (readPtr, Xdr::size <unsigned int>() *
			     numPixelsPerScanLine);

			break;

		      case HALF:

			Xdr::skip <CharPtrIO>
			    (readPtr, Xdr::size <half>() *
			     numPixelsPerScanLine);

			break;

		      case FLOAT:

			Xdr::skip <CharPtrIO>
			    (readPtr, Xdr::size <float>() *
			     numPixelsPerScanLine);

			break;

		      default:

			throw Iex::ArgExc ("Unknown pixel data type.");
		    }
		}
		else
		{
		    //
		    // The frame buffer contains a slice for this channel.
		    //

		    //
		    // pixelPtr points to where we write to
		    // in the frame buffer
		    //

		    char *pixelPtr = slice.base +
				     y * slice.yStride +
				     tileRange.min.x * slice.xStride;

		    if (slice.fill)
		    {
			//
			// The file contains no data for this channel.
			// Store a default value in the frame buffer.
			//

			switch (slice.typeInFrameBuffer)
			{
			  case UINT:

			    {
				unsigned int fillValue =
				    (unsigned int) (slice.fillValue);

				for (int x = tileRange.min.x;
				     x <= tileRange.max.x;
				     ++x)
				{
				    *(unsigned int *) pixelPtr = fillValue;
				    pixelPtr += slice.xStride;
				}
			    }
			    break;

			  case HALF:

			    {
				half fillValue = half (slice.fillValue);

				for (int x = tileRange.min.x;
				     x <= tileRange.max.x;
				     ++x)
				{
				    *(half *) pixelPtr = fillValue;
				    pixelPtr += slice.xStride;
				}
			    }
			    break;

			  case FLOAT:

			    {
				float fillValue = float (slice.fillValue);

				for (int x = tileRange.min.x;
				     x <= tileRange.max.x;
				     ++x)
				{
				    *(float *) pixelPtr = fillValue;
				    pixelPtr += slice.xStride;
				}
			    }
			    break;

			  default:

			    throw Iex::ArgExc ("Unknown pixel data type.");
			}
		    }
		    else if (_data->format == Compressor::XDR || forceXdr)
		    {
			//
			// The compressor produced data for this
			// channel in Xdr format.
			//
			// Convert the pixels from the file's machine-
			// independent representation, and store the
			// results the frame buffer.
			//

			switch (slice.typeInFrameBuffer)
			{
			  case UINT:

			    switch (slice.typeInFile)
			    {
			      case UINT:

				for (int x = tileRange.min.x;
				     x <= tileRange.max.x;
				     ++x)
				{
				    Xdr::read <CharPtrIO>
					(readPtr, *(unsigned int *) pixelPtr);

				    pixelPtr += slice.xStride;
				}

				break;

			      case HALF:

				for (int x = tileRange.min.x;
				     x <= tileRange.max.x;
				     ++x)
				{
				    half h;
				    Xdr::read <CharPtrIO> (readPtr, h);

				    *(unsigned int *) pixelPtr = halfToUint (h);
				    pixelPtr += slice.xStride;
				}

				break;

			      case FLOAT:

				for (int x = tileRange.min.x;
				     x <= tileRange.max.x;
				     ++x)
				{
				    float f;
				    Xdr::read <CharPtrIO> (readPtr, f);

				    *(unsigned int *)pixelPtr = floatToUint (f);
				    pixelPtr += slice.xStride;
				}

				break;
			    }
			    break;

			  case HALF:

			    switch (slice.typeInFile)
			    {
			      case UINT:

				for (int x = tileRange.min.x;
				     x <= tileRange.max.x;
				     ++x)
				{
				    unsigned int ui;
				    Xdr::read <CharPtrIO> (readPtr, ui);

				    *(half *) pixelPtr = uintToHalf (ui);
				    pixelPtr += slice.xStride;
				}

				break;

			      case HALF:

				for (int x = tileRange.min.x;
				     x <= tileRange.max.x;
				     ++x)
				{
				    Xdr::read <CharPtrIO>
					(readPtr, *(half *) pixelPtr);

				    pixelPtr += slice.xStride;
				}

				break;

			      case FLOAT:

				for (int x = tileRange.min.x;
				     x <= tileRange.max.x;
				     ++x)
				{
				    float f;
				    Xdr::read <CharPtrIO> (readPtr, f);

				    *(half *) pixelPtr = floatToHalf (f);
				    pixelPtr += slice.xStride;
				}

				break;
			    }
			    break;

			  case FLOAT:

			    switch (slice.typeInFile)
			    {
			      case UINT:

				for (int x = tileRange.min.x;
				     x <= tileRange.max.x;
				     ++x)
				{
				    unsigned int ui;
				    Xdr::read <CharPtrIO> (readPtr, ui);

				    *(float *) pixelPtr = float (ui);
				    pixelPtr += slice.xStride;
				}

				break;

			      case HALF:

				for (int x = tileRange.min.x;
				     x <= tileRange.max.x;
				     ++x)
				{
				    half h;
				    Xdr::read <CharPtrIO> (readPtr, h);

				    *(float *) pixelPtr = float (h);
				    pixelPtr += slice.xStride;
				}

				break;

			      case FLOAT:

				for (int x = tileRange.min.x;
				     x <= tileRange.max.x;
				     ++x)
				{
				    Xdr::read <CharPtrIO>
					(readPtr, *(float *) pixelPtr);

				    pixelPtr += slice.xStride;
				}

				break;
			    }
			    break;

			  default:

			    throw Iex::ArgExc ("Unknown pixel data type.");
			}
		    }
		    else
		    {
			//
			// The compressor produced data for this
			// channel in the machine's native format.
			//
			// Convert the pixels from the file's machine-
			// dependent representation, and store the
			// results the frame buffer.
			//

			switch (slice.typeInFrameBuffer)
			{
			  case UINT:

			    switch (slice.typeInFile)
			    {
			      case UINT:

				for (int x = tileRange.min.x;
				     x <= tileRange.max.x;
				     ++x)
				{
				    for (size_t i = 0;
					 i < sizeof (unsigned int);
					 ++i)
				    {
					pixelPtr[i] = readPtr[i];
				    }

				    readPtr += sizeof (unsigned int);
				    pixelPtr += slice.xStride;
				}

				break;

			      case HALF:

				for (int x = tileRange.min.x;
				     x <= tileRange.max.x;
				     ++x)
				{
				    half h = *(half *) readPtr;
				    *(unsigned int *) pixelPtr = halfToUint (h);
				    readPtr += sizeof (half);
				    pixelPtr += slice.xStride;
				}

				break;

			      case FLOAT:

				for (int x = tileRange.min.x;
				     x <= tileRange.max.x;
				     ++x)
				{
				    float f;

				    for (size_t i = 0; i < sizeof (float); ++i)
				    {
					((char *)&f)[i] = readPtr[i];
				    }

				    *(unsigned int *)pixelPtr = floatToUint (f);
				    readPtr += sizeof (float);
				    pixelPtr += slice.xStride;
				}

				break;
			    }
			    break;

			  case HALF:

			    switch (slice.typeInFile)
			    {
			      case UINT:

				for (int x = tileRange.min.x;
				     x <= tileRange.max.x;
				     ++x)
				{
				    unsigned int ui;

				    for (size_t i = 0;
					 i < sizeof (unsigned int);
					 ++i)
				    {
					((char *)&ui)[i] = readPtr[i];
				    }

				    *(half *) pixelPtr = uintToHalf (ui);
				    readPtr += sizeof (unsigned int);
				    pixelPtr += slice.xStride;
				}

				break;

			      case HALF:

				for (int x = tileRange.min.x;
				     x <= tileRange.max.x;
				     ++x)
				{
				    *(half *) pixelPtr = *(half *)readPtr;

				    readPtr += sizeof (half);
				    pixelPtr += slice.xStride;
				}

				break;

			      case FLOAT:

				for (int x = tileRange.min.x;
				     x <= tileRange.max.x;
				     ++x)
				{
				    float f;

				    for (size_t i = 0; i < sizeof (float); ++i)
				    {
					((char *)&f)[i] = readPtr[i];
				    }

				    *(half *) pixelPtr = floatToHalf (f);
				    readPtr += sizeof (float);
				    pixelPtr += slice.xStride;
				}

				break;
			    }
			    break;

			  case FLOAT:

			    switch (slice.typeInFile)
			    {
			      case UINT:

				for (int x = tileRange.min.x;
				     x <= tileRange.max.x;
				     ++x)
				{
				    unsigned int ui;

				    for (size_t i = 0;
					 i < sizeof (unsigned int);
					 ++i)
				    {
					((char *)&ui)[i] = readPtr[i];
				    }

				    *(float *) pixelPtr = float (ui);
				    readPtr += sizeof (unsigned int);
				    pixelPtr += slice.xStride;
				}

				break;

			      case HALF:

				for (int x = tileRange.min.x;
				     x <= tileRange.max.x;
				     ++x)
				{
				    half h = *(half *) readPtr;
				    *(float *) pixelPtr = float (h);
				    readPtr += sizeof (half);
				    pixelPtr += slice.xStride;
				}

				break;

			      case FLOAT:

				for (int x = tileRange.min.x;
				     x <= tileRange.max.x;
				     ++x)
				{
				    for (size_t i = 0; i < sizeof (float); ++i)
					pixelPtr[i] = readPtr[i];

				    readPtr += sizeof (float);
				    pixelPtr += slice.xStride;
				}

				break;
			    }
			    break;

			  default:

			    throw Iex::ArgExc ("Unknown pixel data type.");
			}
		    }
		}
	    }
	}
    }
    catch (Iex::BaseExc &e)
    {
        REPLACE_EXC (e, "Error reading pixel data from image "
                        "file \"" << fileName() << "\". " << e);
        throw;
    }
}

void
TiledInputFile::readTile (int dx, int dy, int l)
{
    readTile (dx, dy, l, l);
}

void
TiledInputFile::rawTileData (int &dx, int &dy,
			     int &lx, int &ly,
                             const char *&pixelData,
			     int &pixelDataSize)
{
    try
    {
        if (!isValidTile (dx, dy, lx, ly))
        {
            throw Iex::ArgExc ("Tried to read a tile outside "
			       "the image file's data window.");
        }

        readNextTileData (_data, dx, dy, lx, ly, pixelDataSize);
        pixelData = _data->tileBuffer;
    }
    catch (Iex::BaseExc &e)
    {
        REPLACE_EXC (e, "Error reading pixel data from image "
			"file \"" << fileName() << "\". " << e);
        throw;
    }
}

unsigned int
TiledInputFile::tileXSize () const
{
    return _data->tileDesc.xSize;
}

unsigned int
TiledInputFile::tileYSize () const
{
    return _data->tileDesc.ySize;
}

LevelMode
TiledInputFile::levelMode () const
{
    return _data->tileDesc.mode;
}

LevelRoundingMode
TiledInputFile::levelRoundingMode () const
{
    return _data->tileDesc.roundingMode;
}

int
TiledInputFile::numLevels () const
{
    if (levelMode() == RIPMAP_LEVELS)
    {
	THROW (Iex::LogicExc, "Error calling numLevels() on image "
			      "file \"" << fileName() << "\" "
			      "(numLevels() is not defined for files "
			      "with RIPMAP level mode).");
    }

    return _data->numXLevels;
}

int
TiledInputFile::numXLevels () const
{
    return _data->numXLevels;
}

int
TiledInputFile::numYLevels () const
{
    return _data->numYLevels;
}

bool
TiledInputFile::isValidLevel (int lx, int ly) const
{
    if (lx < 0 || ly < 0)
	return false;

    if (levelMode() == MIPMAP_LEVELS && lx != ly)
	return false;

    if (lx >= numXLevels() || ly >= numYLevels())
	return false;

    return true;
}

int
TiledInputFile::levelWidth (int lx) const
{
    try
    {
	return levelSize (_data->minX, _data->maxX, lx,
			  _data->tileDesc.roundingMode);
    }
    catch (Iex::BaseExc &e)
    {
	REPLACE_EXC (e, "Error calling levelWidth() on image "
			"file \"" << fileName() << "\". " << e);
	throw;
    }
}

int
TiledInputFile::levelHeight (int ly) const
{
    try
    {
	return levelSize (_data->minY, _data->maxY, ly,
			  _data->tileDesc.roundingMode);
    }
    catch (Iex::BaseExc &e)
    {
	REPLACE_EXC (e, "Error calling levelWidth() on image "
			"file \"" << fileName() << "\". " << e);
	throw;
    }
}

int
TiledInputFile::numXTiles (int lx) const
{
    if (lx < 0 || lx >= numXLevels())
    {
        THROW (Iex::ArgExc, "Error calling numXTiles() on image "
			    "file \"" << fileName() << "\" "
			    "(Argument is not in valid range).");

    }

    return _data->numXTiles[lx];
}

int
TiledInputFile::numYTiles (int ly) const
{
    if (ly < 0 || ly >= numYLevels())
    {
        THROW (Iex::ArgExc, "Error calling numYTiles() on image "
			    "file \"" << fileName() << "\" "
			    "(Argument is not in valid range).");
    }

    return _data->numYTiles[ly];
}

Box2i
TiledInputFile::dataWindowForLevel (int l) const
{
    return dataWindowForLevel (l, l);
}

Box2i
TiledInputFile::dataWindowForLevel (int lx, int ly) const
{
    try
    {
	return Imf::dataWindowForLevel (_data->tileDesc,
					_data->minX, _data->maxX,
				        _data->minY, _data->maxY,
				        lx, ly);
    }
    catch (Iex::BaseExc &e)
    {
	REPLACE_EXC (e, "Error calling dataWindowForLevel() on image "
			"file \"" << fileName() << "\". " << e);
	throw;
    }
}

Box2i
TiledInputFile::dataWindowForTile (int dx, int dy, int l) const
{
    return dataWindowForTile (dx, dy, l, l);
}

Box2i
TiledInputFile::dataWindowForTile (int dx, int dy, int lx, int ly) const
{
    try
    {
	if (!isValidTile (dx, dy, lx, ly))
	    throw Iex::ArgExc ("Arguments not in valid range.");

	return Imf::dataWindowForTile (_data->tileDesc,
				       _data->minX, _data->maxX,
				       _data->minY, _data->maxY,
				       dx, dy, lx, ly);
    }
    catch (Iex::BaseExc &e)
    {
	REPLACE_EXC (e, "Error calling dataWindowForTile() on image "
			"file \"" << fileName() << "\". " << e);
	throw;
    }
}

bool
TiledInputFile::isValidTile(int dx, int dy, int lx, int ly) const
{
    return ((lx < numXLevels() && lx >= 0) &&
            (ly < numYLevels() && ly >= 0) &&
            (dx < numXTiles(lx) && dx >= 0) &&
            (dy < numYTiles(ly) && dy >= 0));
}

} // namespace Imf


text:
require 'rails_helper'

feature 'Articles' do
  scenario 'show article' do
    article = create(:article)

    visit article_path(article)
    expect(page).to have_content 'MyString'
  end

  scenario 'show drafts' do
    user = create(:user)
    article = create(:article, title: 'Draft', author: user, status: :draft)

    visit root_path
    fill_in '名前', with: user.name
    fill_in 'Password', with: user.password
    click_button 'Log in'

    visit drafts_path
    expect(page).to have_content 'Draft'
  end
end


text:
<?php

use DesignPatterns\Behavioral\Strategy\{
    BasicSortStrategy, SpaceSortStrategy, StrategyInterface
};
use PHPUnit\Framework\TestCase;

class StrategyTest extends TestCase
{
    public function getStrategy()
    {
        return [
            [new SpaceSortStrategy()],
            [new BasicSortStrategy()]
        ];
    }

    /**
     * @param $strategy StrategyInterface
     * @dataProvider getStrategy
     */
    public function testStrategy(StrategyInterface $strategy)
    {
        $unsorted = [31, 41, 59, 26, 53, 58];

        usort($unsorted, [$strategy, 'sort']);

        $this->assertEquals([26, 31, 41, 53, 58, 59], $unsorted);
    }
}


text:
//
//  SSFObjectMappingCollector.h
//  SFiOSKit
//
//  Created by yangzexin on 11/22/13.
//  Copyright (c) 2013 yangzexin. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "SFObjectMapping.h"

@protocol SFObjectMappingCollector <NSObject>

- (id<SFObjectMapping>)objectMappingForClass:(Class)clss;

@end

@interface SFObjectMappingCollectorContext : NSObject

@property (nonatomic, strong) NSDictionary *keyPropertyNameValueKeyMapping;
@property (nonatomic, strong) NSDictionary *keyPropertyNameValueClass;
@property (nonatomic, strong) NSArray *propertyProcessors;

+ (instancetype)contextWithKeyPropertyNameValueKeyMapping:(NSDictionary *)keyPropertyNameValueKeyMapping
                                keyPropertyNameValueClass:(NSDictionary *)keyPropertyNameValueClass;

+ (instancetype)contextWithKeyPropertyNameValueKeyMapping:(NSDictionary *)keyPropertyNameValueKeyMapping;

+ (instancetype)contextWithKeyPropertyNameValueClass:(NSDictionary *)keyPropertyNameValueClass;

@end

@protocol SFObjectMappingCollectorDelegate <NSObject>

- (SFObjectMappingCollectorContext *)collectorContextForClass:(Class)clss;

@end

/**
 This class is used by SFDict2ObjectEnhanced
 */
@interface SFObjectMappingCollector : NSObject <SFObjectMappingCollector>

/**
 Using delegate to get unknown ObjectMappings
 */
@property (nonatomic, assign) id<SFObjectMappingCollectorDelegate> delegate;

@end


text:
namespace FizzWare.NBuilder.Tests.TestClasses
{
    public interface IMyOtherInterface
    {

    }
}


text:
                    <input ng-model="searchTerm" type="text" class="form-control search-box" placeholder="Search" />

                                Name

                                Strategy

                                Next Review Date

                            {{ portfolio.name }}
                            {{ portfolio.strategy }}
                            {{ portfolio.nextReviewDate | date : 'yyyy-MM-dd' }}

                                 Edit
                                Delete

                    No portfolios match your current search filter.

                Create New