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

// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.

// This file was modified by Oracle on 2013, 2014, 2017, 2018.
// Modifications copyright (c) 2013-2018 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_ALGORITHMS_DETAIL_OVERLAY_GET_TURN_INFO_FOR_ENDPOINT_HPP
#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_OVERLAY_GET_TURN_INFO_FOR_ENDPOINT_HPP

#include <boost/core/ignore_unused.hpp>

#include <boost/geometry/algorithms/detail/equals/point_point.hpp>
#include <boost/geometry/algorithms/detail/overlay/get_turn_info.hpp>
#include <boost/geometry/core/assert.hpp>
#include <boost/geometry/policies/robustness/no_rescale_policy.hpp>

namespace boost { namespace geometry {

#ifndef DOXYGEN_NO_DETAIL
namespace detail { namespace overlay {

// SEGMENT_INTERSECTION RESULT

//                   C  H0  H1  A0  A1   O              IP1 IP2

// D0 and D1 == 0

// |-------->        2   0   0   0   0   F              i/i x/x
// |-------->
//
// |-------->        2   0   0   0   0   T              i/x x/i
// <--------|
//
// |----->           1   0   0   0   0   T              x/x
//       <-----|
//

// |--------->       2   0   0   0   1   T              i/x x/i
//      <----|
//
// |--------->       2   0   0   0   0   F              i/i x/x
//      |---->
//
// |--------->       2   0   0  -1   1   F              i/i u/x
// |---->
//
// |--------->       2   0   0  -1   0   T              i/x u/i
// <----|

// |------->         2   0   0   1  -1   F   and        i/i x/u
//     |------->     2   0   0  -1   1   F   symetric   i/i u/x
// |------->
//
//     |------->     2   0   0  -1  -1   T              i/u u/i
// <-------|
//
// |------->         2   0   0   1   1   T              i/x x/i
//     <-------|
//
// |-------->        2   0   0  -1   1   F              i/i u/x
//   |---->
//
// |-------->        2   0   0  -1   1   T              i/x u/i
//   <----|

//       |----->     1  -1  -1  -1  -1   T              u/u
// <-----|
//
//       |----->     1  -1   0  -1   0   F   and        u/x
// |----->           1   0  -1   0  -1   F   symetric   x/u
//       |----->

// D0 or D1 != 0

//          ^
//          |
//          +        1  -1   1  -1   1   F   and        u/x  (P is vertical)
// |-------->        1   1  -1   1  -1   F   symetric   x/u  (P is horizontal)
// ^
// |
// +
//
//          +
//          |
//          v
// |-------->        1   1   1   1   1   F              x/x  (P is vertical)
//
// ^
// |
// +
// |-------->        1  -1  -1  -1  -1   F              u/u  (P is vertical)
//
//      ^
//      |
//      +
// |-------->        1   0  -1   0  -1   F              u/u  (P is vertical)
//
//      +
//      |
//      v
// |-------->        1   0   1   0   1   F              u/x  (P is vertical)
//

class linear_intersections
{
public:
    template <typename Point1, typename Point2, typename IntersectionResult, typename EqPPStrategy>
    linear_intersections(Point1 const& pi,
                         Point2 const& qi,
                         IntersectionResult const& result,
                         bool is_p_last, bool is_q_last,
                         EqPPStrategy const& strategy)
    {
        int arrival_a = result.template get<1>().arrival[0];
        int arrival_b = result.template get<1>().arrival[1];
        bool same_dirs = result.template get<1>().dir_a == 0
                      && result.template get<1>().dir_b == 0;

        if ( same_dirs )
        {
            if ( result.template get<0>().count == 2 )
            {
                if ( ! result.template get<1>().opposite )
                {
                    ips[0].p_operation = operation_intersection;
                    ips[0].q_operation = operation_intersection;
                    ips[1].p_operation = union_or_blocked_same_dirs(arrival_a, is_p_last);
                    ips[1].q_operation = union_or_blocked_same_dirs(arrival_b, is_q_last);

                    ips[0].is_pi
                        = equals::equals_point_point(
                            pi, result.template get<0>().intersections[0], strategy);
                    ips[0].is_qi
                        = equals::equals_point_point(
                            qi, result.template get<0>().intersections[0], strategy);
                    ips[1].is_pj = arrival_a != -1;
                    ips[1].is_qj = arrival_b != -1;
                }
                else
                {
                    ips[0].p_operation = operation_intersection;
                    ips[0].q_operation = union_or_blocked_same_dirs(arrival_b, is_q_last);
                    ips[1].p_operation = union_or_blocked_same_dirs(arrival_a, is_p_last);
                    ips[1].q_operation = operation_intersection;

                    ips[0].is_pi = arrival_b != 1;
                    ips[0].is_qj = arrival_b != -1;
                    ips[1].is_pj = arrival_a != -1;
                    ips[1].is_qi = arrival_a != 1;
                }
            }
            else
            {
                BOOST_GEOMETRY_ASSERT(result.template get<0>().count == 1);
                ips[0].p_operation = union_or_blocked_same_dirs(arrival_a, is_p_last);
                ips[0].q_operation = union_or_blocked_same_dirs(arrival_b, is_q_last);

                ips[0].is_pi = arrival_a == -1;
                ips[0].is_qi = arrival_b == -1;
                ips[0].is_pj = arrival_a == 0;
                ips[0].is_qj = arrival_b == 0;
            }
        }
        else
        {
            ips[0].p_operation = union_or_blocked_different_dirs(arrival_a, is_p_last);
            ips[0].q_operation = union_or_blocked_different_dirs(arrival_b, is_q_last);

            ips[0].is_pi = arrival_a == -1;
            ips[0].is_qi = arrival_b == -1;
            ips[0].is_pj = arrival_a == 1;
            ips[0].is_qj = arrival_b == 1;
        }
    }

    struct ip_info
    {
        inline ip_info()
            : p_operation(operation_none), q_operation(operation_none)
            , is_pi(false), is_pj(false), is_qi(false), is_qj(false)
        {}

        operation_type p_operation, q_operation;
        bool is_pi, is_pj, is_qi, is_qj;
    };

    template <std::size_t I>
    ip_info const& get() const
    {
        BOOST_STATIC_ASSERT(I < 2);
        return ips[I];
    }

private:

    // only if collinear (same_dirs)
    static inline operation_type union_or_blocked_same_dirs(int arrival, bool is_last)
    {
        if ( arrival == 1 )
            return operation_blocked;
        else if ( arrival == -1 )
            return operation_union;
        else
            return is_last ? operation_blocked : operation_union;
            //return operation_blocked;
    }

    // only if not collinear (!same_dirs)
    static inline operation_type union_or_blocked_different_dirs(int arrival, bool is_last)
    {
        if ( arrival == 1 )
            //return operation_blocked;
            return is_last ? operation_blocked : operation_union;
        else
            return operation_union;
    }

    ip_info ips[2];
};

template <bool EnableFirst, bool EnableLast>
struct get_turn_info_for_endpoint
{
    typedef std::pair<operation_type, operation_type> operations_pair;

    BOOST_STATIC_ASSERT(EnableFirst || EnableLast);

    template<typename UniqueSubRange1,
             typename UniqueSubRange2,
             typename TurnInfo,
             typename IntersectionInfo,
             typename OutputIterator,
             typename EqPPStrategy
    >
    static inline bool apply(UniqueSubRange1 const& range_p,
                             UniqueSubRange2 const& range_q,
                             TurnInfo const& tp_model,
                             IntersectionInfo const& inters,
                             method_type /*method*/,
                             OutputIterator out,
                             EqPPStrategy const& strategy)
    {
        std::size_t ip_count = inters.i_info().count;
        // no intersection points
        if (ip_count == 0)
        {
            return false;
        }

        if (! range_p.is_first_segment()
            && ! range_q.is_first_segment()
            && ! range_p.is_last_segment()
            && ! range_q.is_last_segment())
        {
            // Not an end-point from segment p or q
            return false;
        }

        linear_intersections intersections(range_p.at(0),
                                           range_q.at(0),
                                           inters.result(),
                                           range_p.is_last_segment(),
                                           range_q.is_last_segment(),
                                           strategy);

        bool append0_last
            = analyse_segment_and_assign_ip(range_p, range_q,
                                            intersections.template get<0>(),
                                            tp_model, inters, 0, out);

        // NOTE: opposite && ip_count == 1 may be true!
        bool opposite = inters.d_info().opposite;

        // don't ignore only for collinear opposite
        bool result_ignore_ip0 = append0_last && ( ip_count == 1 || !opposite );

        if ( intersections.template get<1>().p_operation == operation_none )
            return result_ignore_ip0;

        bool append1_last
            = analyse_segment_and_assign_ip(range_p, range_q,
                                            intersections.template get<1>(),
                                            tp_model, inters, 1, out);

        // don't ignore only for collinear opposite
        bool result_ignore_ip1 = append1_last && !opposite /*&& ip_count == 2*/;

        return result_ignore_ip0 || result_ignore_ip1;
    }

    template <typename UniqueSubRange1,
              typename UniqueSubRange2,
              typename TurnInfo,
              typename IntersectionInfo,
              typename OutputIterator>
    static inline
    bool analyse_segment_and_assign_ip(UniqueSubRange1 const& range_p,
                                       UniqueSubRange2 const& range_q,
                                       linear_intersections::ip_info const& ip_info,
                                       TurnInfo const& tp_model,
                                       IntersectionInfo const& inters,
                                       unsigned int ip_index,
                                       OutputIterator out)
    {
        // TODO - calculate first/last only if needed
        bool is_p_first_ip = range_p.is_first_segment() && ip_info.is_pi;
        bool is_p_last_ip = range_p.is_last_segment() && ip_info.is_pj;
        bool is_q_first_ip = range_q.is_first_segment() && ip_info.is_qi;
        bool is_q_last_ip = range_q.is_last_segment() && ip_info.is_qj;
        bool append_first = EnableFirst && (is_p_first_ip || is_q_first_ip);
        bool append_last = EnableLast && (is_p_last_ip || is_q_last_ip);

        operation_type p_operation = ip_info.p_operation;
        operation_type q_operation = ip_info.q_operation;

        if ( append_first || append_last )
        {
            bool handled = handle_internal<0>(range_p, range_q,
                                              is_p_first_ip, is_p_last_ip,
                                              is_q_first_ip, is_q_last_ip,
                                              ip_info.is_qi, ip_info.is_qj,
                                              tp_model, inters, ip_index,
                                              p_operation, q_operation);
            if ( !handled )
            {
                // Reverse p/q
                handle_internal<1>(range_q, range_p,
                                   is_q_first_ip, is_q_last_ip,
                                   is_p_first_ip, is_p_last_ip,
                                   ip_info.is_pi, ip_info.is_pj,
                                   tp_model, inters, ip_index,
                                   q_operation, p_operation);
            }

            if ( p_operation != operation_none )
            {
                method_type method = endpoint_ip_method(ip_info.is_pi, ip_info.is_pj,
                                                        ip_info.is_qi, ip_info.is_qj);
                turn_position p_pos = ip_position(is_p_first_ip, is_p_last_ip);
                turn_position q_pos = ip_position(is_q_first_ip, is_q_last_ip);

                // handle spikes

                // P is spike and should be handled
                if (ip_info.is_pj // this check is redundant (also in is_spike_p) but faster
                  && inters.i_info().count == 2
                  && inters.is_spike_p() )
                {
                    assign(inters.result(), ip_index, method, operation_blocked, q_operation,
                           p_pos, q_pos, is_p_first_ip, is_q_first_ip, true, false, tp_model, out);
                    assign(inters.result(), ip_index, method, operation_intersection, q_operation,
                           p_pos, q_pos, is_p_first_ip, is_q_first_ip, true, false, tp_model, out);
                }
                // Q is spike and should be handled
                else if (ip_info.is_qj // this check is redundant (also in is_spike_q) but faster
                       && inters.i_info().count == 2
                       && inters.is_spike_q() )
                {
                    assign(inters.result(), ip_index, method, p_operation, operation_blocked,
                           p_pos, q_pos, is_p_first_ip, is_q_first_ip, false, true, tp_model, out);
                    assign(inters.result(), ip_index, method, p_operation, operation_intersection,
                           p_pos, q_pos, is_p_first_ip, is_q_first_ip, false, true, tp_model, out);
                }
                // no spikes
                else
                {
                    assign(inters.result(), ip_index, method, p_operation, q_operation,
                           p_pos, q_pos, is_p_first_ip, is_q_first_ip, false, false, tp_model, out);
                }
            }
        }

        return append_last;
    }

    // TODO: IT'S ALSO PROBABLE THAT ALL THIS FUNCTION COULD BE INTEGRATED WITH handle_segment
    //       however now it's lazily calculated and then it would be always calculated

    template<std::size_t G1Index,
             typename UniqueRange1,
             typename UniqueRange2,
             typename TurnInfo,
             typename IntersectionInfo
    >
    static inline bool handle_internal(UniqueRange1 const& range1,
                                       UniqueRange2 const& range2,
                                       bool first1, bool last1, bool first2, bool last2,
                                       bool ip_i2, bool ip_j2, TurnInfo const& tp_model,
                                       IntersectionInfo const& inters, unsigned int ip_index,
                                       operation_type & op1, operation_type & op2)
    {
        boost::ignore_unused(ip_index, tp_model);

        typename IntersectionInfo::side_strategy_type const& sides
                = inters.get_side_strategy();

        if ( !first2 && !last2 )
        {
            if ( first1 )
            {
#ifdef BOOST_GEOMETRY_DEBUG_GET_TURNS_LINEAR_LINEAR
                // may this give false positives for INTs?
                typename IntersectionResult::point_type const&
                    inters_pt = inters.i_info().intersections[ip_index];
                BOOST_GEOMETRY_ASSERT(ip_i2 == equals::equals_point_point(i2, inters_pt));
                BOOST_GEOMETRY_ASSERT(ip_j2 == equals::equals_point_point(j2, inters_pt));
#endif
                if ( ip_i2 )
                {
                    // don't output this IP - for the first point of other geometry segment
                    op1 = operation_none;
                    op2 = operation_none;
                    return true;
                }
                else if ( ip_j2 )
                {
                    int const side_pj_q2 = sides.apply(range2.at(1), range2.at(2), range1.at(1));
                    int const side_pj_q1 = sides.apply(range2.at(0), range2.at(1), range1.at(1));
                    int const side_qk_q1 = sides.apply(range2.at(0), range2.at(1), range2.at(2));

                    operations_pair operations = operations_of_equal(side_pj_q2, side_pj_q1, side_qk_q1);

// TODO: must the above be calculated?
// wouldn't it be enough to check if segments are collinear?

                    if ( operations_both(operations, operation_continue) )
                    {
                        if ( op1 != operation_union
                          || op2 != operation_union
                          || ! ( G1Index == 0 ? inters.is_spike_q() : inters.is_spike_p() ) )
                        {
                            // THIS IS WRT THE ORIGINAL SEGMENTS! NOT THE ONES ABOVE!
                            bool opposite = inters.d_info().opposite;

                            op1 = operation_intersection;
                            op2 = opposite ? operation_union : operation_intersection;
                        }
                    }
                    else
                    {
                        BOOST_GEOMETRY_ASSERT(operations_combination(operations, operation_intersection, operation_union));
                        //op1 = operation_union;
                        //op2 = operation_union;
                    }

                    return true;
                }
                // else do nothing - shouldn't be handled this way
            }
            else if ( last1 )
            {
#ifdef BOOST_GEOMETRY_DEBUG_GET_TURNS_LINEAR_LINEAR
                // may this give false positives for INTs?
                typename IntersectionResult::point_type const&
                    inters_pt = inters.i_info().intersections[ip_index];
                BOOST_GEOMETRY_ASSERT(ip_i2 == equals::equals_point_point(i2, inters_pt));
                BOOST_GEOMETRY_ASSERT(ip_j2 == equals::equals_point_point(j2, inters_pt));
#endif
                if ( ip_i2 )
                {
                    // don't output this IP - for the first point of other geometry segment
                    op1 = operation_none;
                    op2 = operation_none;
                    return true;
                }
                else if ( ip_j2 )
                {
                    int const side_pi_q2 = sides.apply(range2.at(1), range2.at(2), range1.at(0));
                    int const side_pi_q1 = sides.apply(range2.at(0), range2.at(1), range1.at(0));
                    int const side_qk_q1 = sides.apply(range2.at(0), range2.at(1), range2.at(2));

                    operations_pair operations = operations_of_equal(side_pi_q2, side_pi_q1, side_qk_q1);

// TODO: must the above be calculated?
// wouldn't it be enough to check if segments are collinear?

                    if ( operations_both(operations, operation_continue) )
                    {
                        if ( op1 != operation_blocked
                          || op2 != operation_union
                          || ! ( G1Index == 0 ? inters.is_spike_q() : inters.is_spike_p() ) )
                        {
                            // THIS IS WRT THE ORIGINAL SEGMENTS! NOT THE ONES ABOVE!
                            bool second_going_out = inters.i_info().count > 1;

                            op1 = operation_blocked;
                            op2 = second_going_out ? operation_union : operation_intersection;
                        }
                    }
                    else
                    {
                        BOOST_GEOMETRY_ASSERT(operations_combination(operations, operation_intersection, operation_union));
                        //op1 = operation_blocked;
                        //op2 = operation_union;
                    }

                    return true;
                }
                // else do nothing - shouldn't be handled this way
            }
            // else do nothing - shouldn't be handled this way
        }

        return false;
    }

    static inline method_type endpoint_ip_method(bool ip_pi, bool ip_pj, bool ip_qi, bool ip_qj)
    {
        if ( (ip_pi || ip_pj) && (ip_qi || ip_qj) )
            return method_touch;
        else
            return method_touch_interior;
    }

    static inline turn_position ip_position(bool is_ip_first_i, bool is_ip_last_j)
    {
        return is_ip_first_i ? position_front :
               ( is_ip_last_j ? position_back : position_middle );
    }

    template <typename IntersectionResult,
              typename TurnInfo,
              typename OutputIterator>
    static inline void assign(IntersectionResult const& result,
                              unsigned int ip_index,
                              method_type method,
                              operation_type op0, operation_type op1,
                              turn_position pos0, turn_position pos1,
                              bool is_p_first_ip, bool is_q_first_ip,
                              bool is_p_spike, bool is_q_spike,
                              TurnInfo const& tp_model,
                              OutputIterator out)
    {
        TurnInfo tp = tp_model;

        //geometry::convert(ip, tp.point);
        //tp.method = method;
        base_turn_handler::assign_point(tp, method, result.template get<0>(), ip_index);

        tp.operations[0].operation = op0;
        tp.operations[1].operation = op1;
        tp.operations[0].position = pos0;
        tp.operations[1].position = pos1;

        if ( result.template get<0>().count > 1 )
        {
            // NOTE: is_collinear is NOT set for the first endpoint
            // for which there is no preceding segment

            //BOOST_GEOMETRY_ASSERT( result.template get<1>().dir_a == 0 && result.template get<1>().dir_b == 0 );
            if ( ! is_p_first_ip )
            {
                tp.operations[0].is_collinear = op0 != operation_intersection
                                             || is_p_spike;
            }

            if ( ! is_q_first_ip )
            {
                tp.operations[1].is_collinear = op1 != operation_intersection
                                             || is_q_spike;
            }
        }
        else //if ( result.template get<0>().count == 1 )
        {
            if ( op0 == operation_blocked && op1 == operation_intersection )
            {
                tp.operations[0].is_collinear = true;
            }
            else if ( op0 == operation_intersection && op1 == operation_blocked )
            {
                tp.operations[1].is_collinear = true;
            }
        }

        *out++ = tp;
    }

    static inline operations_pair operations_of_equal(int side_px_q2,
                                                      int side_px_q1,
                                                      int side_qk_q1)
    {
        // If px (pi or pj) is collinear with qj-qk (q2), they continue collinearly.
        // This can be on either side of q1, or collinear
        // The second condition checks if they do not continue
        // oppositely
        if (side_px_q2 == 0 && side_px_q1 == side_qk_q1)
        {
            return std::make_pair(operation_continue, operation_continue);
        }

        // If they turn to same side (not opposite sides)
        if ( ! base_turn_handler::opposite(side_px_q1, side_qk_q1) )
        {
            // If px is left of q2 or collinear: p: union, q: intersection
            if (side_px_q2 != -1 )
            {
                return std::make_pair(operation_union, operation_intersection);
            }
            else
            {
               return std::make_pair(operation_intersection, operation_union);
            }
        }
        else
        {
            // They turn opposite sides. If p turns left (or collinear),
           // p: union, q: intersection
            if (side_px_q1 != -1 )
            {
                return std::make_pair(operation_union, operation_intersection);
            }
           else
            {
                return std::make_pair(operation_intersection, operation_union);
            }
        }
   }

    static inline bool operations_both(operations_pair const& operations,
                                       operation_type const op)
    {
        return operations.first == op && operations.second == op;
    }

    static inline bool operations_combination(operations_pair const& operations,
                                              operation_type const op1,
                                              operation_type const op2)
    {
        return ( operations.first == op1 && operations.second == op2 )
            || ( operations.first == op2 && operations.second == op1 );
    }
};

}} // namespace detail::overlay
#endif // DOXYGEN_NO_DETAIL

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_OVERLAY_GET_TURN_INFO_FOR_ENDPOINT_HPP


text:
<?php

namespace Kapi\Http;

use InvalidArgumentException;
use Psr\Http\Message\UriInterface;

class Request extends AbstractRequest
{
    /**
     * @var string[]
     */
    protected $allowedMethod = [
        'GET',
        'POST',
        'PUT',
        'PATCH',
        'DELETE',
        'HEAD',
        'OPTIONS',
        'TRACE',
    ];

    /**
     * Request constructor.
     * @param null|string|UriInterface $uri
     * @param string $method
     * @param array $headers
     * @param $body
     * @param string $version
     */
    public function __construct($uri, $method, array $headers = [], $body = 'php://memory', $version = '1.1')
    {
        parent::__construct($headers, $body, $version);
        $this->setUri($uri);
        $this->setMethod($method);
    }

    /**
     * @inheritDoc
     */
    public function withMethod($method)
    {
        $new = clone $this;
        $new->setMethod($method);

        return $new;
    }

    /**
     * @param string $method
     */
    public function setMethod($method)
    {
        if (!is_string($method)) {
            throw new InvalidArgumentException(sprintf(
                'Unsupported HTTP method; must be a string, received %s',
                is_object($method) ? get_class($method) : gettype($method)
            ));
        }

        if (!in_array($method, $this->allowedMethod)) {
            throw new InvalidArgumentException(sprintf(
                'Unsupported HTTP method "%s" provided',
                $method
            ));
        }

        $this->method = $method;
    }

    /**
     * @param null|string|UriInterface $uri
     * @param bool $preserveHost
     */
    public function setUri($uri, $preserveHost = false)
    {
        $uri = new Uri((string) $uri);
        $this->uri = $uri;

        if (!$preserveHost || !$this->getHeader('Host')) {
            if ($host = $uri->getHost()) {
                if ($port = $uri->getPort()) {
                    $host .= ':' . $port;
                }
                $this->setHeader('Host', $host);
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
"""empty message

Revision ID: 7e8e08e5c5d9
Revises: e1192d825b94
Create Date: 2017-02-24 10:34:43.808000

"""

# revision identifiers, used by Alembic.
revision = '7e8e08e5c5d9'
down_revision = 'e1192d825b94'

from alembic import op
import sqlalchemy as sa

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.create_table('follows',
    sa.Column('follower_id', sa.Integer(), nullable=False),
    sa.Column('followed_id', sa.Integer(), nullable=False),
    sa.Column('timestamp', sa.DateTime(), nullable=True),
    sa.ForeignKeyConstraint(['followed_id'], ['users.id'], ),
    sa.ForeignKeyConstraint(['follower_id'], ['users.id'], ),
    sa.PrimaryKeyConstraint('follower_id', 'followed_id')
    )
    ### end Alembic commands ###

def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('follows')
    ### end Alembic commands ###


text:
module Slack
  module Web
    module Api
      module Endpoints
        module Stars
          #
          # Save an item for later. Formerly known as _adding a star_.
          #
          # @option options [channel] :channel
          #   Channel to add star to, or channel where the message to add star to was posted (used with timestamp).
          # @option options [file] :file
          #   File to add star to.
          # @option options [string] :file_comment
          #   File comment to add star to.
          # @option options [string] :timestamp
          #   Timestamp of the message to add star to.
          # @see https://api.slack.com/methods/stars.add
          # @see https://github.com/slack-ruby/slack-api-ref/blob/master/methods/stars/stars.add.json
          def stars_add(options = {})
            options = options.merge(channel: conversations_id(options)['channel']['id']) if options[:channel]
            post('stars.add', options)
          end

          #
          # List a user's saved items, formerly known as _stars_.
          #
          # @option options [string] :cursor
          #   Parameter for pagination. Set cursor equal to the next_cursor attribute returned by the previous request's response_metadata. This parameter is optional, but pagination is mandatory: the default value simply fetches the first "page" of the collection. See pagination for more details.
          # @option options [integer] :limit
          #   The maximum number of items to return. Fewer than the requested number of items may be returned, even if the end of the list hasn't been reached.
          # @option options [string] :team_id
          #   encoded team id to list stars in, required if org token is used.
          # @see https://api.slack.com/methods/stars.list
          # @see https://github.com/slack-ruby/slack-api-ref/blob/master/methods/stars/stars.list.json
          def stars_list(options = {})
            if block_given?
              Pagination::Cursor.new(self, :stars_list, options).each do |page|
                yield page
              end
            else
              post('stars.list', options)
            end
          end

          #
          # Removes a saved item (star) from an item.
          #
          # @option options [channel] :channel
          #   Channel to remove star from, or channel where the message to remove star from was posted (used with timestamp).
          # @option options [file] :file
          #   File to remove star from.
          # @option options [string] :file_comment
          #   File comment to remove star from.
          # @option options [string] :timestamp
          #   Timestamp of the message to remove star from.
          # @see https://api.slack.com/methods/stars.remove
          # @see https://github.com/slack-ruby/slack-api-ref/blob/master/methods/stars/stars.remove.json
          def stars_remove(options = {})
            options = options.merge(channel: conversations_id(options)['channel']['id']) if options[:channel]
            post('stars.remove', options)
          end
        end
      end
    end
  end
end


text:
"""
Forms and validation code for user registration.

"""

from django import forms
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from django.conf import settings
from signbank.settings.server_specific import *
from django.utils.safestring import mark_safe
from django.utils.functional import lazy
from django.utils import six

mark_safe_lazy = lazy(mark_safe, six.text_type)

from signbank.registration.models import RegistrationProfile, UserProfile

from signbank.dictionary.models import Dataset
from django_select2 import *
from easy_select2.widgets import Select2, Select2Multiple

import re
alnum_re = re.compile(r'^\w+$')

# I put this on all required fields, because it's easier to pick up
# on them with CSS or JavaScript if they have a class of "required"
# in the HTML. Your mileage may vary. If/when Django ticket #3515
# lands in trunk, this will no longer be necessary.
attrs_reqd = { 'class': 'required form-control' }
attrs_default = {'class': 'form-control'}

class RegistrationForm(forms.Form):
    """
    Form for registering a new user account.

    Validates that the request username is not already in use, and
    requires the password to be entered twice to catch typos.

    Subclasses should feel free to add any additional validation they
    need, but should either preserve the base ``save()`` or implement
    a ``save()`` which accepts the ``profile_callback`` keyword
    argument and passes it through to
    ``RegistrationProfile.objects.create_inactive_user()``.

    """
    error_css_class = 'error'

    username = forms.CharField(max_length=30, required=True,
                               widget=forms.TextInput(attrs=attrs_reqd),
                               label=_(u'Username'))
    first_name = forms.CharField(max_length=30, required=True,
                               widget=forms.TextInput(attrs=attrs_reqd),
                               label=_(u'First Name'))
    last_name = forms.CharField(max_length=30, required=True,
                                 widget=forms.TextInput(attrs=attrs_reqd),
                                 label=_(u'Last Name'))
    email = forms.EmailField(widget=forms.TextInput(attrs=attrs_reqd), required=True,
                             label=_(u'Your Email Address'))
    password1 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_reqd), required=True,
                                label=_(u'Password'))
    password2 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_reqd),
                                label=_(u'Password (again)'))

    if hasattr(settings, 'SHOW_DATASET_INTERFACE_OPTIONS') and settings.SHOW_DATASET_INTERFACE_OPTIONS:

        dataset_choices = [ (ds.name, ds.name) for ds in Dataset.objects.filter(is_public='1') ]
        if not dataset_choices:
            dataset_choices = [(ds.name, ds.name) for ds in Dataset.objects.filter(acronym=settings.DEFAULT_DATASET_ACRONYM)]
        dataset = forms.TypedMultipleChoiceField(label=_(u'Requested Datasets'),
                                                  choices=dataset_choices,
                                                  required=False, widget=Select2)
        motivation = forms.CharField(widget=forms.Textarea(attrs={'cols': 80, 'rows': 5,
                                                                  'placeholder': 'Motivation'}),
                                     label=_(u'Motivation'), required=False, # this has to be False
                                     # the motivation field is not stored in the database
                                     # it is retrieved from the form to be used in the request access email sent to the dataset manager
                                     # in order to avoid default Django behaviour, it is renamed in the form to motivation_for_use
                                     # required needs to be False
                                     # otherwise Django can't match the new field name with this one
                                     # requested datasets are also passed this way rather than stored in the database
                                     help_text=_("Please explain why you would like to get access to this dataset. What are the purposes for which you wish to use it?"))

    tos_choices = [(True, 'Agree'), (False, 'Disagree')]
    href_hyperlink = settings.URL + settings.PREFIX_URL + '/about/conditions/'
    tos_hyperlink = _(u'I have read and agree to the Terms of Service')
    tos = forms.BooleanField(label=mark_safe_lazy(tos_hyperlink),
                             widget=forms.RadioSelect(choices=tos_choices),
                             error_messages={'required': 'Error: You must agree to the Terms of Service in order to register'})

    def clean_username(self):
        """
        Validates that the username is alphanumeric and is not already
        in use.

        """
        try:
            user = User.objects.get(username__exact=self.cleaned_data['username'])
        except User.DoesNotExist:
            return self.cleaned_data['username']
        raise forms.ValidationError(_(u'This username is already taken. Please choose another.'))

    def clean_password2(self):
        """
        Validates that the two password inputs match.

        """
        if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
            if self.cleaned_data['password1'] == self.cleaned_data['password2']:
                return self.cleaned_data['password2']
            raise forms.ValidationError(_(u'You must type the same password each time'))

    def clean_motivation(self):

        if 'motivation_for_use' in self.cleaned_data:
            return self.cleaned_data['motivation_for_use']
        elif 'motivation' in self.cleaned_data:
            return self.cleaned_data['motivation']
        else:
            raise forms.ValidationError(_(u'Please provide motivation for your request'))

    def clean_tos(self):
        """
        Validates that the user accepted the Terms of Service.

        """
        if self.cleaned_data.get('tos', True):
            return self.cleaned_data['tos']
        raise forms.ValidationError()

    def save(self, profile_callback=None):
        """
        Creates the new ``User`` and ``RegistrationProfile``, and
        returns the ``User``.

        This is essentially a light wrapper around
        ``RegistrationProfile.objects.create_inactive_user()``,
        feeding it the form data and a profile callback (see the
        documentation on ``create_inactive_user()`` for details) if
        supplied.

        """
        new_user = RegistrationProfile.objects.create_inactive_user(username=self.cleaned_data['username'],
                                                                    password=self.cleaned_data['password1'],
                                                                    email=self.cleaned_data['email'],
                                                                    firstname=self.cleaned_data['first_name'],
                                                                    lastname=self.cleaned_data['last_name'],
                                                                    agree=self.cleaned_data['tos'],
                                                                    profile_callback=profile_callback)
        return new_user

class RegistrationFormTermsOfService(RegistrationForm):
    """
    Subclass of ``RegistrationForm`` which adds a required checkbox
    for agreeing to a site's Terms of Service.

    """
    tos = forms.BooleanField(widget=forms.CheckboxInput(attrs=attrs_reqd),
                             label=_(u'I have read and agree to the Terms of Service'))

    def clean_tos(self):
        """
        Validates that the user accepted the Terms of Service.

        """
        if self.cleaned_data.get('tos', False):
            return self.cleaned_data['tos']
        raise forms.ValidationError(_(u'You must agree to the terms to register'))

class RegistrationFormUniqueEmail(RegistrationForm):
    """
    Subclass of ``RegistrationForm`` which enforces uniqueness of
    email addresses.

    """
    def clean_email(self):
        """
        Validates that the supplied email address is unique for the
        site.

        """
        try:
            user = User.objects.get(email__exact=self.cleaned_data['email'])
        except User.DoesNotExist:
            return self.cleaned_data['email']
        raise forms.ValidationError(_(u'This email address is already in use. Please supply a different email address.'))

yesnoChoices = ((1, 'yes'), (0, 'no'))

import string

def t(message):
    """Replace $country and $language in message with date from settings"""

    tpl = string.Template(message)
    return tpl.substitute(country=settings.COUNTRY_NAME, language=settings.LANGUAGE_NAME)

from django.views.decorators.cache import never_cache
from django.contrib.auth import authenticate

class EmailAuthenticationForm(forms.Form):
    """
    Base class for authenticating users. Extend this to get a form that accepts
    username/password logins.
    """
    email = forms.CharField(label=_("Email"), max_length=100)
    password = forms.CharField(label=_("Password"), widget=forms.PasswordInput)

    def __init__(self, request=None, *args, **kwargs):
        """
        If request is passed in, the form will validate that cookies are
        enabled. Note that the request (a HttpRequest object) must have set a
        cookie with the key TEST_COOKIE_NAME and value TEST_COOKIE_VALUE before
        running this validation.
        """
        self.request = request
        self.user_cache = None
        super(EmailAuthenticationForm, self).__init__(*args, **kwargs)

    def clean(self):
        email = self.cleaned_data.get('email')
        password = self.cleaned_data.get('password')

        if email and password:
            self.user_cache = authenticate(username=email, password=password)
            if self.user_cache is None:
                raise forms.ValidationError(_("Please enter a correct email and password. Note that password is case-sensitive."))
            elif not self.user_cache.is_active:
                raise forms.ValidationError(_("This account is inactive."))

        # TODO: determine whether this should move to its own method.
        if self.request:
            if not self.request.session.test_cookie_worked():
                raise forms.ValidationError(_("Your Web browser doesn't appear to have cookies enabled. Cookies are required for logging in."))

        return self.cleaned_data

    def get_user_id(self):
        if self.user_cache:
            return self.user_cache.id
        return None

    def get_user(self):
        return self.user_cache


text:
//
//  GTLYouTubeI18nRegion.m
//

// ----------------------------------------------------------------------------
// NOTE: This file is generated from Google APIs Discovery Service.
// Service:
//   YouTube Data API (youtube/v3)
// Description:
//   Programmatic access to YouTube features.
// Documentation:
//   https://developers.google.com/youtube/v3
// Classes:
//   GTLYouTubeI18nRegion (0 custom class methods, 4 custom properties)

#import "GTLYouTubeI18nRegion.h"

#import "GTLYouTubeI18nRegionSnippet.h"

// ----------------------------------------------------------------------------
//
//   GTLYouTubeI18nRegion
//

@implementation GTLYouTubeI18nRegion
@dynamic ETag, identifier, kind, snippet;

+ (NSDictionary *)propertyToJSONKeyMap {
  NSDictionary *map =
    [NSDictionary dictionaryWithObjectsAndKeys:
      @"etag", @"ETag",
      @"id", @"identifier",
      nil];
  return map;
}

+ (void)load {
  [self registerObjectClassForKind:@"youtube#i18nRegion"];
}

@end


text:
package org.springframework.cloud.netflix.eureka.support;

import org.springframework.util.StringUtils;

/**
 * Utility class for dealing with zones.
 *
 * @author Ryan Baxter
 *
 */
public final class ZoneUtils {

	private ZoneUtils() {
		throw new AssertionError("Must not instantiate utility class.");
	}

	/**
	 * Approximates Eureka zones from a host name. This method approximates the zone to be
	 * everything after the first "." in the host name.
	 * @param host The host name to extract the host name from
	 * @return The approximate zone
	 */
	public static String extractApproximateZone(String host) {
		String[] split = StringUtils.split(host, ".");
		return split == null ? host : split[1];
	}

}


text:
{{companyItem.company.name}}

{{companyItem.company.creator | displayNameFilter:[companyItem.users] }}


text:
<component name="libraryTable">
  <library name="Maven: mysql:mysql-connector-java:5.1.38">
    <CLASSES>
      <root url="jar://D:/Maven/Maven-Repository/mysql/mysql-connector-java/5.1.38/mysql-connector-java-5.1.38.jar!/" />
    </CLASSES>
    <JAVADOC>
      <root url="jar://D:/Maven/Maven-Repository/mysql/mysql-connector-java/5.1.38/mysql-connector-java-5.1.38-javadoc.jar!/" />
    </JAVADOC>
    <SOURCES>
      <root url="jar://D:/Maven/Maven-Repository/mysql/mysql-connector-java/5.1.38/mysql-connector-java-5.1.38-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
import { AnonymousSubject } from '../../Subject';
import { Subscriber } from '../../Subscriber';
import { Observable } from '../../Observable';
import { Subscription } from '../../Subscription';
import { Operator } from '../../Operator';
import { Observer, NextObserver } from '../../Observer';
export interface WebSocketSubjectConfig {
    url: string;
    protocol?: string | Array<string>;
    resultSelector?: <T>(e: MessageEvent) => T;
    openObserver?: NextObserver<Event>;
    closeObserver?: NextObserver<CloseEvent>;
    closingObserver?: NextObserver<void>;
    WebSocketCtor?: {
        new (url: string, protocol?: string | Array<string>): WebSocket;
    };
}
/**
 * We need this JSDoc comment for affecting ESDoc.
 * @extends {Ignored}
 * @hide true
 */
export declare class WebSocketSubject<T> extends AnonymousSubject<T> {
    url: string;
    protocol: string | Array<string>;
    socket: WebSocket;
    openObserver: NextObserver<Event>;
    closeObserver: NextObserver<CloseEvent>;
    closingObserver: NextObserver<void>;
    WebSocketCtor: {
        new (url: string, protocol?: string | Array<string>): WebSocket;
    };
    private _output;
    resultSelector(e: MessageEvent): any;
    /**
     * @param urlConfigOrSource
     * @return {WebSocketSubject}
     * @static true
     * @name webSocket
     * @owner Observable
     */
    static create<T>(urlConfigOrSource: string | WebSocketSubjectConfig): WebSocketSubject<T>;
    constructor(urlConfigOrSource: string | WebSocketSubjectConfig | Observable<T>, destination?: Observer<T>);
    lift<R>(operator: Operator<T, R>): WebSocketSubject<R>;
    multiplex(subMsg: () => any, unsubMsg: () => any, messageFilter: (value: T) => boolean): Observable<{}>;
    private _connectSocket();
    protected _subscribe(subscriber: Subscriber<T>): Subscription;
    unsubscribe(): void;
}


text:
/**
 * Class that all elements subclass from.
 *
 * @param {Object} definition User-defined element options defined in page object.
 * @param {Object} [options] Additional options to be given to the element.
 * @constructor
 */
function Element(definition, options) {
  options = options || {};

  this.name = options.name;

  if (!definition.selector) {
    throw new Error('No selector property for ' + getDescription(this) +
      '. Instead found properties: ' +
      Object
        .keys(definition)
        .filter(hasValidValueIn(definition))
        .join(', ')
    );
  }

  this.selector = definition.selector;
  this.locateStrategy = definition.locateStrategy || options.locateStrategy;
  this.index = definition.index;
  this.parent = options.parent;
}

Element.prototype.toString = function() {
  if (Array.isArray(this.selector)) { // recursive
    return this.selector.join(',');
  }

  var index = parseInt(this.index, 10);
  var indexStr = isNaN(index) ? '' : '[' + index + ']';

  if (!this.name) { // inline (not defined in page or section)
    return this.selector;
  }

  var classType = this.constructor.name;
  var prefix = this.constructor === Element ? '@' : '';
  return classType + '[name=' + prefix + this.name + indexStr + ']';
};

/**
 * Determines whether or not the element contains an @ element reference
 * for its selector.
 *
 * @returns {boolean} True if the selector is an element reference starting with an
 *    @ symbol, false if it does not.
 */
Element.prototype.hasElementSelector = function() {
  return String(this.selector)[0] === '@';
};

/**
 * If the element object requires a recursive lookup to resolve its
 * selector, a new element containing the recursive lookup values
 * is created and returned.
 *
 * @returns {Object} A new Element object containing the element and its
 *    parents with a recursive lookup strategy for resolving the element
 *    if one is needed. If not, null is returned.
 */
Element.prototype.getRecursiveLookupElement = function () {
  var lookupList = getAncestorsWithElement(this);

  if (lookupList.length > 1) {
    return new Element({
      selector: lookupList,
      locateStrategy: 'recursion'
    });
  }

  return null;
};

/**
 * Copies selector properties to the first object from the second if the first
 * object has undefined values for any of those properties.
 *
 * @param {Object} target The object to assign values to.
 * @param {Object} source The object to capture values from.
 */
Element.copyDefaults = function(target, source) {
  var props = ['name', 'parent', 'selector', 'locateStrategy', 'index'];
  props.forEach(function(prop) {
    if (target[prop] === undefined || target[prop] === null) {
      target[prop] = source[prop];
    }
  });
};

/**
 * Parses the value/selector parameter of an element command creating a
 * new Element instance with the values it contains, if any. The standard
 * format for this is a selector string, but additional, complex formats
 * in the form of an array or object are also supported.
 *
 * @param {string|Object} value Selector value to parse into an Element.
 * @param {string} [using] The using/locateStrategy to use if the selector
 *    doesn't provide one of its own.
 */
Element.fromSelector = function(value, using) {

  if (!value) {
    throw new Error('Invalid selector value specified');
  }

  if (value instanceof Element) {
    value.locateStrategy = value.locateStrategy || using;
    return value;
  }

  var definition;
  var options = { locateStrategy: using };

  if (using !== 'recursion' && typeof value === 'object') {
    definition = value;
  } else {
    definition = { selector : value };
  }

  return new Element(definition, options);
};

/**
 * Returns true when an elements() request is needed to capture
 * the result of the Element definition.  When false, it means the
 * Element targets the first result the selector match meaning an
 * element() (single match only) result can be used.
 *
 * @param {Object} element The Element instance to check to see if
 *    it will apply filtering.
 */
Element.requiresFiltering = function(element) {

  var usingIndex = !isNaN(parseInt(element.index, 10));
  if (usingIndex) {
    return true;
  }

  return false;
};

/**
 * Filters an elements() results array to a more specific set based
 * on an Element object's definition.
 *
 * @param {Object} element The Element instance to check to see if
 *    it will apply filtering.
 * @param {Array} resultElements Array of WebElement JSON objects
 *    returned from a call to elements() or elementIdElements().
 * @returns {Array} A filtered version of the elements array or, if
 *    the filter failed (no matches found) null.
 */
Element.applyFiltering = function(element, resultElements) {

  var index = parseInt(element.index, 10);
  var usingIndex = !isNaN(index);
  if (usingIndex) {
    var foundElem = resultElements[index];
    return foundElem ? [foundElem] : null; // null = not found
  }

  return resultElements;
};

/**
 * Gets a simple description of the element based on whether or not
 * it is used as an inline selector in a command call or a definition
 * within a page object or section.
 */
function getDescription(instance) {
  if (instance.name) {
    var classType = instance.constructor.name.toLowerCase(); // Element, Section or any other subclass's name
    return classType + ' "' + instance.name + '"';
  }
  return 'selector object';
}

/**
 * Array filter method removing elements that may be defined (in) but
 * do not have a recognizable value.
 */
function hasValidValueIn (definition) {
  return function(key) {
    return definition[key] !== undefined && definition[key] !== null;
  };
}

/**
 * Retrieves an array of ancestors of the supplied element. The last element in the array is the element object itself
 *
 * @param {Object} element The element
 * @returns {Array}
 */
function getAncestorsWithElement(element) {
  var elements = [];
  function addElement(e) {
    elements.unshift(e);
    if (e.parent && e.parent.selector) {
      addElement(e.parent);
    }
  }
  addElement(element);
  return elements;
}

module.exports = Element;


text:
<?php

namespace spec\Sylius\Component\Core\Model;

use Doctrine\Common\Collections\Collection;
use PhpSpec\ObjectBehavior;
use Sylius\Component\Channel\Model\ChannelInterface;
use Sylius\Component\Core\Model\AddressInterface;
use Sylius\Component\Core\Model\AdjustmentInterface;
use Sylius\Component\Core\Model\Order;
use Sylius\Component\Core\Model\OrderItemInterface;
use Sylius\Component\Core\Model\OrderShippingStates;
use Sylius\Component\Core\Model\PaymentInterface;
use Sylius\Component\Core\Model\PromotionInterface;
use Sylius\Component\Core\Model\ShipmentInterface;
use Sylius\Component\Core\OrderCheckoutStates;
use Sylius\Component\Order\Model\Order as BaseOrder;
use Sylius\Component\Order\Model\OrderInterface;
use Sylius\Component\Promotion\Model\CouponInterface;
use Sylius\Component\Customer\Model\CustomerInterface;

/**
 * @mixin Order
 *
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
final class OrderSpec extends ObjectBehavior
{
    function it_is_initializable()
    {
        $this->shouldHaveType(Order::class);
    }

    function it_should_implement_Sylius_order_interface()
    {
        $this->shouldImplement(OrderInterface::class);
    }

    function it_should_extend_Sylius_order_mapped_superclass()
    {
        $this->shouldHaveType(BaseOrder::class);
    }

    function it_should_not_have_customer_defined_by_default()
    {
        $this->getCustomer()->shouldReturn(null);
    }

    function it_should_allow_defining_customer(CustomerInterface $customer)
    {
        $this->setCustomer($customer);
        $this->getCustomer()->shouldReturn($customer);
    }

    function its_channel_is_mutable(ChannelInterface $channel)
    {
        $this->setChannel($channel);
        $this->getChannel()->shouldReturn($channel);
    }

    function it_should_not_have_shipping_address_by_default()
    {
        $this->getShippingAddress()->shouldReturn(null);
    }

    function it_should_allow_defining_shipping_address(AddressInterface $address)
    {
        $this->setShippingAddress($address);
        $this->getShippingAddress()->shouldReturn($address);
    }

    function it_should_not_have_billing_address_by_default()
    {
        $this->getBillingAddress()->shouldReturn(null);
    }

    function it_should_allow_defining_billing_address(AddressInterface $address)
    {
        $this->setBillingAddress($address);
        $this->getBillingAddress()->shouldReturn($address);
    }

    function its_checkout_state_is_mutable()
    {
        $this->setCheckoutState(OrderCheckoutStates::STATE_CART);
        $this->getCheckoutState()->shouldReturn(OrderCheckoutStates::STATE_CART);
    }

    function its_payment_state_is_mutable()
    {
        $this->setPaymentState(PaymentInterface::STATE_COMPLETED);
        $this->getPaymentState()->shouldReturn(PaymentInterface::STATE_COMPLETED);
    }

    function it_should_initialize_item_units_collection_by_default()
    {
        $this->getItemUnits()->shouldHaveType(Collection::class);
    }

    function it_should_initialize_shipments_collection_by_default()
    {
        $this->getShipments()->shouldHaveType(Collection::class);
    }

    function it_should_add_shipment_properly(ShipmentInterface $shipment)
    {
        $this->shouldNotHaveShipment($shipment);

        $shipment->setOrder($this)->shouldBeCalled();
        $this->addShipment($shipment);

        $this->shouldHaveShipment($shipment);
    }

    function it_should_remove_shipment_properly(ShipmentInterface $shipment)
    {
        $shipment->setOrder($this)->shouldBeCalled();
        $this->addShipment($shipment);

        $this->shouldHaveShipment($shipment);

        $shipment->setOrder(null)->shouldBeCalled();
        $this->removeShipment($shipment);

        $this->shouldNotHaveShipment($shipment);
    }

    function it_should_return_shipping_adjustments(
        AdjustmentInterface $shippingAdjustment,
        AdjustmentInterface $taxAdjustment
    ) {
        $shippingAdjustment->getType()->willReturn(AdjustmentInterface::SHIPPING_ADJUSTMENT);
        $shippingAdjustment->setAdjustable($this)->shouldBeCalled();
        $shippingAdjustment->isNeutral()->willReturn(true);

        $taxAdjustment->getType()->willReturn(AdjustmentInterface::TAX_ADJUSTMENT);
        $taxAdjustment->setAdjustable($this)->shouldBeCalled();
        $taxAdjustment->isNeutral()->willReturn(true);

        $this->addAdjustment($shippingAdjustment);
        $this->addAdjustment($taxAdjustment);

        $this->getAdjustments()->count()->shouldReturn(2); //both adjustments have been added

        $shippingAdjustments = $this->getAdjustments(AdjustmentInterface::SHIPPING_ADJUSTMENT);
        $shippingAdjustments->count()->shouldReturn(1); //but here we only get shipping
        $shippingAdjustments->first()->shouldReturn($shippingAdjustment);
    }

    function it_should_remove_shipping_adjustments(
        AdjustmentInterface $shippingAdjustment,
        AdjustmentInterface $taxAdjustment
    ) {
        $shippingAdjustment->getType()->willReturn(AdjustmentInterface::SHIPPING_ADJUSTMENT);
        $shippingAdjustment->setAdjustable($this)->shouldBeCalled();
        $shippingAdjustment->isNeutral()->willReturn(true);

        $taxAdjustment->getType()->willReturn(AdjustmentInterface::TAX_ADJUSTMENT);
        $taxAdjustment->setAdjustable($this)->shouldBeCalled();
        $taxAdjustment->isNeutral()->willReturn(true);

        $this->addAdjustment($shippingAdjustment);
        $this->addAdjustment($taxAdjustment);

        $this->getAdjustments()->count()->shouldReturn(2); //both adjustments have been added

        $shippingAdjustment->isLocked()->willReturn(false);
        $shippingAdjustment->setAdjustable(null)->shouldBeCalled();
        $this->removeAdjustments(AdjustmentInterface::SHIPPING_ADJUSTMENT);

        $this->getAdjustments()->count()->shouldReturn(1); //one has been removed
        $this->getAdjustments(AdjustmentInterface::SHIPPING_ADJUSTMENT)->count()->shouldReturn(0); //shipping adjustment has been removed
    }

    function it_should_return_tax_adjustments(
        AdjustmentInterface $shippingAdjustment,
        AdjustmentInterface $taxAdjustment
    ) {
        $shippingAdjustment->getType()->willReturn(AdjustmentInterface::SHIPPING_ADJUSTMENT);
        $shippingAdjustment->setAdjustable($this)->shouldBeCalled();
        $shippingAdjustment->isNeutral()->willReturn(true);

        $taxAdjustment->getType()->willReturn(AdjustmentInterface::TAX_ADJUSTMENT);
        $taxAdjustment->setAdjustable($this)->shouldBeCalled();
        $taxAdjustment->isNeutral()->willReturn(true);

        $this->addAdjustment($shippingAdjustment);
        $this->addAdjustment($taxAdjustment);

        $this->getAdjustments()->count()->shouldReturn(2); //both adjustments have been added

        $taxAdjustments = $this->getAdjustments(AdjustmentInterface::TAX_ADJUSTMENT);
        $taxAdjustments->count()->shouldReturn(1); //but here we only get tax
        $taxAdjustments->first()->shouldReturn($taxAdjustment);
    }

    function it_should_remove_tax_adjustments(
        AdjustmentInterface $shippingAdjustment,
        AdjustmentInterface $taxAdjustment
    ) {
        $shippingAdjustment->getType()->willReturn(AdjustmentInterface::SHIPPING_ADJUSTMENT);
        $shippingAdjustment->setAdjustable($this)->shouldBeCalled();
        $shippingAdjustment->isNeutral()->willReturn(true);

        $taxAdjustment->getType()->willReturn(AdjustmentInterface::TAX_ADJUSTMENT);
        $taxAdjustment->setAdjustable($this)->shouldBeCalled();
        $taxAdjustment->isNeutral()->willReturn(true);

        $this->addAdjustment($shippingAdjustment);
        $this->addAdjustment($taxAdjustment);

        $this->getAdjustments()->count()->shouldReturn(2); //both adjustments have been added

        $taxAdjustment->isLocked()->willReturn(false);
        $taxAdjustment->setAdjustable(null)->shouldBeCalled();
        $this->removeAdjustments(AdjustmentInterface::TAX_ADJUSTMENT);

        $this->getAdjustments()->count()->shouldReturn(1); //one has been removed
        $this->getAdjustments(AdjustmentInterface::TAX_ADJUSTMENT)->count()->shouldReturn(0); //tax adjustment has been removed
    }

    function it_should_not_have_currency_code_defined_by_default()
    {
        $this->getCurrencyCode()->shouldReturn(null);
    }

    function it_should_allow_defining_currency_code()
    {
        $this->setCurrencyCode('PLN');
        $this->getCurrencyCode()->shouldReturn('PLN');
    }

    function it_has_default_exchange_rate_equal_to_1()
    {
        $this->getExchangeRate()->shouldReturn(1.0);
    }

    function its_exchange_rate_is_mutable()
    {
        $this->setExchangeRate(1.25);
        $this->getExchangeRate()->shouldReturn(1.25);
    }

    function it_has_cart_shipping_state_by_default()
    {
        $this->getShippingState()->shouldReturn(OrderShippingStates::STATE_CART);
    }

    function its_shipping_state_is_mutable()
    {
        $this->setShippingState(OrderShippingStates::STATE_SHIPPED);
        $this->getShippingState()->shouldReturn(OrderShippingStates::STATE_SHIPPED);
    }

    function it_adds_and_removes_payments(PaymentInterface $payment)
    {
        $payment->getState()->willReturn(PaymentInterface::STATE_NEW);
        $payment->setOrder($this)->shouldBeCalled();

        $this->addPayment($payment);
        $this->shouldHavePayment($payment);

        $payment->setOrder(null)->shouldBeCalled();

        $this->removePayment($payment);
        $this->shouldNotHavePayment($payment);
    }

    function it_returns_last_payment(PaymentInterface $payment1, PaymentInterface $payment2)
    {
        $payment1->getState()->willReturn(PaymentInterface::STATE_NEW);
        $payment1->setOrder($this)->shouldBeCalled();
        $payment2->getState()->willReturn(PaymentInterface::STATE_NEW);
        $payment2->setOrder($this)->shouldBeCalled();

        $this->addPayment($payment1);
        $this->addPayment($payment2);

        $this->getLastPayment()->shouldReturn($payment2);
    }

    function it_adds_and_removes_shipments(ShipmentInterface $shipment)
    {
        $shipment->setOrder($this)->shouldBeCalled();

        $this->addShipment($shipment);
        $this->shouldHaveShipment($shipment);

        $shipment->setOrder(null)->shouldBeCalled();

        $this->removeShipment($shipment);
        $this->shouldNotHaveShipment($shipment);
    }

    function it_has_promotion_coupon(CouponInterface $coupon)
    {
        $this->setPromotionCoupon($coupon);
        $this->getPromotionCoupon()->shouldReturn($coupon);
    }

    function it_count_promotions_subjects(OrderItemInterface $item1, OrderItemInterface $item2)
    {
        $this->addItem($item1);
        $item1->getQuantity()->willReturn(4);
        $this->addItem($item2);
        $item2->getQuantity()->willReturn(3);

        $this->getPromotionSubjectCount()->shouldReturn(7);
    }

    function it_adds_and_removes_promotions(PromotionInterface $promotion)
    {
        $this->addPromotion($promotion);
        $this->shouldHavePromotion($promotion);

        $this->removePromotion($promotion);
        $this->shouldNotHavePromotion($promotion);
    }

    function it_returns_0_tax_total_when_there_are_no_items_and_adjustments()
    {
        $this->getTaxTotal()->shouldReturn(0);
    }

    function it_returns_tax_of_all_items_as_tax_total_when_there_are_no_tax_adjustments(
        OrderItemInterface $orderItem1,
        OrderItemInterface $orderItem2
    ) {
        $orderItem1->getTotal()->willReturn(1100);
        $orderItem1->getTaxTotal()->willReturn(100);
        $orderItem2->getTotal()->willReturn(1050);
        $orderItem2->getTaxTotal()->willReturn(50);

        $orderItem1->setOrder($this)->shouldBeCalled();
        $orderItem2->setOrder($this)->shouldBeCalled();
        $this->addItem($orderItem1);
        $this->addItem($orderItem2);

        $this->getTaxTotal()->shouldReturn(150);
    }

    function it_returns_tax_of_all_items_and_non_neutral_shipping_tax_as_tax_total(
        OrderItemInterface $orderItem1,
        OrderItemInterface $orderItem2,
        AdjustmentInterface $shippingAdjustment,
        AdjustmentInterface $shippingTaxAdjustment
    ) {
        $orderItem1->getTotal()->willReturn(1100);
        $orderItem1->getTaxTotal()->willReturn(100);
        $orderItem2->getTotal()->willReturn(1050);
        $orderItem2->getTaxTotal()->willReturn(50);

        $shippingAdjustment->getType()->willReturn(AdjustmentInterface::SHIPPING_ADJUSTMENT);
        $shippingAdjustment->isNeutral()->willReturn(false);
        $shippingAdjustment->getAmount()->willReturn(1000);
        $shippingTaxAdjustment->getType()->willReturn(AdjustmentInterface::TAX_ADJUSTMENT);
        $shippingTaxAdjustment->isNeutral()->willReturn(false);
        $shippingTaxAdjustment->getAmount()->willReturn(70);

        $orderItem1->setOrder($this)->shouldBeCalled();
        $orderItem2->setOrder($this)->shouldBeCalled();
        $this->addItem($orderItem1);
        $this->addItem($orderItem2);

        $shippingAdjustment->setAdjustable($this)->shouldBeCalled();
        $this->addAdjustment($shippingAdjustment);

        $shippingTaxAdjustment->setAdjustable($this)->shouldBeCalled();
        $this->addAdjustment($shippingTaxAdjustment);

        $this->getTaxTotal()->shouldReturn(220);
    }

    function it_returns_tax_of_all_items_and_neutral_shipping_tax_as_tax_total(
        OrderItemInterface $orderItem1,
        OrderItemInterface $orderItem2,
        AdjustmentInterface $shippingAdjustment,
        AdjustmentInterface $shippingTaxAdjustment
    ) {
        $orderItem1->getTotal()->willReturn(1100);
        $orderItem1->getTaxTotal()->willReturn(100);
        $orderItem2->getTotal()->willReturn(1050);
        $orderItem2->getTaxTotal()->willReturn(50);

        $shippingAdjustment->getType()->willReturn(AdjustmentInterface::SHIPPING_ADJUSTMENT);
        $shippingAdjustment->isNeutral()->willReturn(false);
        $shippingAdjustment->getAmount()->willReturn(1000);

        $shippingTaxAdjustment->getType()->willReturn(AdjustmentInterface::TAX_ADJUSTMENT);
        $shippingTaxAdjustment->isNeutral()->willReturn(true);
        $shippingTaxAdjustment->getAmount()->willReturn(70);

        $orderItem1->setOrder($this)->shouldBeCalled();
        $orderItem2->setOrder($this)->shouldBeCalled();
        $this->addItem($orderItem1);
        $this->addItem($orderItem2);

        $shippingAdjustment->setAdjustable($this)->shouldBeCalled();
        $shippingTaxAdjustment->setAdjustable($this)->shouldBeCalled();
        $this->addAdjustment($shippingAdjustment);
        $this->addAdjustment($shippingTaxAdjustment);

        $this->getTaxTotal()->shouldReturn(220);
    }

    function it_includes_non_neutral_tax_adjustments_in_shipping_total(
        AdjustmentInterface $shippingAdjustment,
        AdjustmentInterface $shippingTaxAdjustment
    ) {
        $shippingAdjustment->getType()->willReturn(AdjustmentInterface::SHIPPING_ADJUSTMENT);
        $shippingAdjustment->isNeutral()->willReturn(false);
        $shippingAdjustment->getAmount()->willReturn(1000);

        $shippingTaxAdjustment->getType()->willReturn(AdjustmentInterface::TAX_ADJUSTMENT);
        $shippingTaxAdjustment->isNeutral()->willReturn(false);
        $shippingTaxAdjustment->getAmount()->willReturn(70);

        $shippingAdjustment->setAdjustable($this)->shouldBeCalled();
        $shippingTaxAdjustment->setAdjustable($this)->shouldBeCalled();
        $this->addAdjustment($shippingAdjustment);
        $this->addAdjustment($shippingTaxAdjustment);

        $this->getShippingTotal()->shouldReturn(1070);
    }

    function it_returns_shipping_total_decreased_by_shipping_promotion(
        AdjustmentInterface $shippingAdjustment,
        AdjustmentInterface $shippingTaxAdjustment,
        AdjustmentInterface $shippingPromotionAdjustment
    ) {
        $shippingAdjustment->getType()->willReturn(AdjustmentInterface::SHIPPING_ADJUSTMENT);
        $shippingAdjustment->isNeutral()->willReturn(false);
        $shippingAdjustment->getAmount()->willReturn(1000);

        $shippingTaxAdjustment->getType()->willReturn(AdjustmentInterface::TAX_ADJUSTMENT);
        $shippingTaxAdjustment->isNeutral()->willReturn(false);
        $shippingTaxAdjustment->getAmount()->willReturn(70);

        $shippingPromotionAdjustment->getType()->willReturn(AdjustmentInterface::ORDER_SHIPPING_PROMOTION_ADJUSTMENT);
        $shippingPromotionAdjustment->isNeutral()->willReturn(false);
        $shippingPromotionAdjustment->getAmount()->willReturn(-100);

        $shippingAdjustment->setAdjustable($this)->shouldBeCalled();
        $shippingTaxAdjustment->setAdjustable($this)->shouldBeCalled();
        $shippingPromotionAdjustment->setAdjustable($this)->shouldBeCalled();
        $this->addAdjustment($shippingAdjustment);
        $this->addAdjustment($shippingTaxAdjustment);
        $this->addAdjustment($shippingPromotionAdjustment);

        $this->getShippingTotal()->shouldReturn(970);
    }

    function it_does_not_include_neutral_tax_adjustments_in_shipping_total(
        AdjustmentInterface $shippingAdjustment,
        AdjustmentInterface $neutralShippingTaxAdjustment
    ) {
        $shippingAdjustment->getType()->willReturn(AdjustmentInterface::SHIPPING_ADJUSTMENT);
        $shippingAdjustment->isNeutral()->willReturn(false);
        $shippingAdjustment->getAmount()->willReturn(1000);

        $neutralShippingTaxAdjustment->getType()->willReturn(AdjustmentInterface::TAX_ADJUSTMENT);
        $neutralShippingTaxAdjustment->isNeutral()->willReturn(true);
        $neutralShippingTaxAdjustment->getAmount()->willReturn(70);

        $shippingAdjustment->setAdjustable($this)->shouldBeCalled();
        $neutralShippingTaxAdjustment->setAdjustable($this)->shouldBeCalled();
        $this->addAdjustment($shippingAdjustment);
        $this->addAdjustment($neutralShippingTaxAdjustment);

        $this->getShippingTotal()->shouldReturn(1000);
    }

    function it_returns_0_as_promotion_total_when_there_are_no_order_promotion_adjustments()
    {
        $this->getOrderPromotionTotal()->shouldReturn(0);
    }

    function it_returns_sum_of_all_order_promotion_adjustments_applied_to_items_as_order_promotion_total(
        OrderItemInterface $orderItem1,
        OrderItemInterface $orderItem2
    ) {
        $orderItem1->getTotal()->willReturn(500);
        $orderItem2->getTotal()->willReturn(300);

        $orderItem1->getAdjustmentsTotalRecursively(AdjustmentInterface::ORDER_PROMOTION_ADJUSTMENT)->willReturn(-400);
        $orderItem2->getAdjustmentsTotalRecursively(AdjustmentInterface::ORDER_PROMOTION_ADJUSTMENT)->willReturn(-600);

        $orderItem1->setOrder($this)->shouldBeCalled();
        $orderItem2->setOrder($this)->shouldBeCalled();
        $this->addItem($orderItem1);
        $this->addItem($orderItem2);

        $this->getOrderPromotionTotal()->shouldReturn(-1000);
    }

    function it_does_not_include_shipping_promotion_adjustment_in_order_promotion_total(
        AdjustmentInterface $shippingPromotionAdjustment,
        OrderItemInterface $orderItem1
    ) {
        $orderItem1->getTotal()->willReturn(500);
        $orderItem1->getAdjustmentsTotalRecursively(AdjustmentInterface::ORDER_PROMOTION_ADJUSTMENT)->willReturn(-400);

        $shippingPromotionAdjustment->getType()->willReturn(AdjustmentInterface::ORDER_PROMOTION_ADJUSTMENT);
        $shippingPromotionAdjustment->isNeutral()->willReturn(false);
        $shippingPromotionAdjustment->getAmount()->willReturn(-100);

        $orderItem1->setOrder($this)->shouldBeCalled();
        $this->addItem($orderItem1);

        $shippingPromotionAdjustment->setAdjustable($this)->shouldBeCalled();
        $this->addAdjustment($shippingPromotionAdjustment);

        $this->getOrderPromotionTotal()->shouldReturn(-400);
    }
}


text:
module.exports = function(app) {
    var express = require('express');
    var postsRouter = express.Router();
    // we already have posts with ID 1 & 2
    var postID = 2;
    var posts = [{
        id: 1,
        title: 'First Post',
	comments: [1]
    }, {
        id: 2,
        title: 'Second Post'
    }];

    postsRouter.get('/', function(req, res) {
        res.send({
            'posts': posts
        });
    });

    postsRouter.post('/', function(req, res) {
        var newBody = req.body;
        // increment the ID
        postID += 1;
        newBody.post.id = postID;
	posts.push(newBody.post);
        res.status(201);
        res.send(newBody);
        //res.status(201).end();

    });

    postsRouter.get('/:id', function(req, res) {
        var thisPost;
        var found = false;
        posts.forEach(function(post, index) {
            if (found === false && post.id == req.params.id) {
                thisPost = post;
                found = true;
            }
        });
        if (found === true) {
            res.send({
                'posts': {
                    id: req.params.id,
                    title: thisPost.title,
		    comments: thisPost.comments
                }
            });
        } else {
            res.status(404).end();
        }
    });

    postsRouter.put('/:id', function(req, res) {
        res.send({
            'posts': {
                id: req.params.id
            }
        });
    });

    postsRouter.delete('/:id', function(req, res) {
        res.status(204).end();
    });

    //app.use('/api/posts', postsRouter);
    app.use('/api/posts', require('body-parser').json(), postsRouter);
};


text:
#ifndef VECTOR_H_INCLUDED
#define VECTOR_H_INCLUDED

typedef struct {

	int size;
	int capacity;
	int *data;
} IntVector, *IntVectorPtr;

IntVectorPtr VecNew(int  initialCapacity);
void VecDelete(IntVectorPtr vector);
int VecAdd(IntVectorPtr vector, int element);
int VecErase(IntVectorPtr vector, int position);
int VecGet(IntVectorPtr vector, int position);
int VecMin(IntVectorPtr vector, int size);
int VecMax(IntVectorPtr vector, int size);
double VecAverage(IntVectorPtr vector, int size);
int compare(const void *arg1, const void *arg2);
void VecQuickSort(IntVectorPtr vector);
void VecQuickSort2(IntVectorPtr vector, int start, int end);
int VecBinarySearch(IntVectorPtr vector, int element);
int VecBinarySearch2(IntVectorPtr vector, int element, int start, int end);
int VecBinarySearch3(IntVectorPtr vector, int element, int start, int end);

#endif	/* end VECTOR_H_INCLUDED */


text:
require 'bundler/setup'
require 'sinatra'
require 'haml'
require 'rest_client'
require 'json'
require 'erb'
require 'yaml'
require 'pry'
require './installer'

template = ERB.new File.new('config.yml').read
config = YAML.load template.result(binding)

CALLBACK_URL  = "#{config['this_host']}/auth/callback"
SIGN_UP_URL   = "https://www.digitalocean.com/?refcode=#{config['ref_code']}"
CLIENT_ID     = config['client_id']
CLIENT_SECRET = config['client_secret']

enable :sessions, :logging

enable :show_exceptions if development?

set :session_secret, config['cookie_secret']

def csrf_token_matches?(token)
  token.to_s != '' && token == session[:csrf_token]
end

def authenticate(installer)
  if (installer.auth_token = session[:token])
    begin
      installer.account
    rescue RestClient::Unauthorized
      session[:token] = nil
      redirect "https://cloud.digitalocean.com/v1/oauth/authorize?response_type=code&client_id=#{CLIENT_ID}&redirect_uri=#{CALLBACK_URL}&scope=read+write"
    rescue Installer::NoSSHKeyError
      redirect '/add_ssh_key'
    else
      return true
    end
  else
    redirect "https://cloud.digitalocean.com/v1/oauth/authorize?response_type=code&client_id=#{CLIENT_ID}&redirect_uri=#{CALLBACK_URL}&scope=read+write"
  end
  false
end

get '/' do
  @configured = config['client_id'] != 'your-do-client-id'
  haml :index
end

get '/terms' do
  haml :terms
end

get '/install' do
  begin
    @installer = Installer.new(params[:url])
  rescue Installer::URLParseError
    haml :error_parsing_url
  rescue Installer::ConfigFetchError
    haml :error_getting_config
  rescue Installer::ConfigParseError
    haml :error_parsing_config
  else
    session[:csrf_token] = SecureRandom.hex
    haml :install
  end
end

post '/install' do
  return [400, 'invalid token'] unless csrf_token_matches?(params[:token])
  begin
    if params[:url]
      installer = Installer.new(params[:url])
      installer.region = params[:region]
      installer.size = params[:size]
      session[:config] = installer.as_json
    else
      installer = Installer.from_json(session[:config])
    end
  rescue
    haml :error_generic
  else
    if authenticate(installer)
      begin
        installer.go!
      rescue Installer::NoSSHKeyError
        redirect '/add_ssh_key'
      else
        session[:config] = installer.as_json
        redirect '/status'
      end
    end
  end
end

get '/update_regions_and_sizes' do
  installer = Installer.new('https://github.com/seven1m/do-install-button') # doesn't matter
  if authenticate(installer)
    File.write('regions.json', installer.regions.to_json)
    File.write('sizes.json', installer.sizes.to_json)
    'written'
  end
end

get '/auth/callback' do
  result = RestClient.post 'https://cloud.digitalocean.com/v1/oauth/token',
    { client_id:     CLIENT_ID,
      client_secret: CLIENT_SECRET,
      grant_type:    'authorization_code',
      code:          params[:code],
      redirect_uri:  CALLBACK_URL }
  session[:token] = JSON.parse(result)['access_token']
  unless session[:config]
    redirect '/'
    return
  end
  installer = Installer.from_json(session[:config])
  installer.auth_token = session[:token]
  begin
    installer.go!
  rescue Installer::NoSSHKeyError
    redirect '/add_ssh_key'
  else
    session[:config] = installer.as_json
    redirect '/status'
  end
end

get '/add_ssh_key' do
  @installer = Installer.from_json(session[:config])
  haml :add_ssh_key
end

get '/status' do
  haml :status
end

get '/status.json' do
  installer = Installer.from_json(session[:config])
  installer.auth_token = session[:token]
  status = {
    id:       installer.droplet_id,
    ip:       installer.droplet_ip,
    droplet:  installer.droplet_status,
    status:   installer.install_status
  }
  content_type :json
  status.to_json
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>DataTableContext (ARX GUI Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.deidentifier.arx.gui.view.impl.common.datatable

Class DataTableContext

java.lang.Object

org.deidentifier.arx.gui.view.impl.common.datatable.DataTableContext

public class DataTableContext
extends java.lang.Object

A context for the data view. It provides all necessary data to be displayed.

Constructor Summary

Constructors

Constructor and Description

DataTableContext(Controller controller)

Creates a new instance.

Method Summary

Methods

Modifier and Type
Method and Description

Controller
getController()

Returns the controller.

org.eclipse.swt.graphics.Font
getFont()

Sets the font.

int[]
getGroups()

Returns information about the equivalence classes.

DataHandle
getHandle()

Returns the data handle, if any.

java.util.List<org.eclipse.swt.graphics.Image>
getImages()

Returns the header images.

java.util.List<org.eclipse.nebula.widgets.nattable.layer.ILayerListener>
getListeners()

Returns all layer listeners.

RowSet
getRows()

Returns the research subset.

int
getSelectedIndex()

Returns the selected index.

org.eclipse.nebula.widgets.nattable.NatTable
getTable()

Returns the underlying table.

boolean
isColumnExpanded()

boolean
isRowExpanded()

void
reset()

Resets the context.

void
setFont(org.eclipse.swt.graphics.Font font)

Gets the font.

void
setGroups(int[] groups)

Sets the groups.

void
setHandle(DataHandle handle)

Sets a data handle.

void
setImages(java.util.List<org.eclipse.swt.graphics.Image> images)

Sets the header images.

void
setListeners(java.util.List<org.eclipse.nebula.widgets.nattable.layer.ILayerListener> listeners)

Sets the layer listeners.

void
setRows(RowSet rows)

Sets the research subset.

void
setSelectedIndex(int index)

Sets the selected column index.

void
setTable(org.eclipse.nebula.widgets.nattable.NatTable table)

Sets the underlying table.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DataTableContext

public DataTableContext(Controller controller)

Creates a new instance.

Parameters:

controller -

Method Detail

getController

public Controller getController()

Returns the controller.

Returns:

getFont

public org.eclipse.swt.graphics.Font getFont()

Sets the font.

Returns:

getGroups

public int[] getGroups()

Returns information about the equivalence classes.

Returns:

getHandle

public DataHandle getHandle()

Returns the data handle, if any.

Returns:

getImages

public java.util.List<org.eclipse.swt.graphics.Image> getImages()

Returns the header images.

Returns:

getListeners

public java.util.List<org.eclipse.nebula.widgets.nattable.layer.ILayerListener> getListeners()

Returns all layer listeners.

Returns:

getRows

public RowSet getRows()

Returns the research subset.

Returns:

getSelectedIndex

public int getSelectedIndex()

Returns the selected index.

Returns:

getTable

public org.eclipse.nebula.widgets.nattable.NatTable getTable()

Returns the underlying table.

Returns:

isColumnExpanded

public boolean isColumnExpanded()

Returns:

isRowExpanded

public boolean isRowExpanded()

Returns:

reset

public void reset()

Resets the context.

setFont

public void setFont(org.eclipse.swt.graphics.Font font)

Gets the font.

Parameters:

font -

setGroups

public void setGroups(int[] groups)

Sets the groups.

Parameters:

groups -

setHandle

public void setHandle(DataHandle handle)

Sets a data handle.

Parameters:

handle -

setImages

public void setImages(java.util.List<org.eclipse.swt.graphics.Image> images)

Sets the header images.

Parameters:

images -

setListeners

public void setListeners(java.util.List<org.eclipse.nebula.widgets.nattable.layer.ILayerListener> listeners)

Sets the layer listeners.

Parameters:

listeners -

setRows

public void setRows(RowSet rows)

Sets the research subset.

Parameters:

rows -

setSelectedIndex

public void setSelectedIndex(int index)

Sets the selected column index.

Parameters:

index -

setTable

public void setTable(org.eclipse.nebula.widgets.nattable.NatTable table)

Sets the underlying table.

Parameters:

table -

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
module Berkshelf
  module Formatters
    class Null
      include AbstractFormatter

      register_formatter :null

      # The abstract formatter dynamically defines methods that raise an
      # AbstractFunction error. We need to define all of those on our class,
      # otherwise they will be inherited by the Ruby object model.
      AbstractFormatter.instance_methods.each do |meth|
        define_method(meth) do |*args|
          # intentionally do nothing
        end
      end

      def method_missing(meth, *args, &block)
        # intentionally do nothing
      end
    end
  end
end


text:
title: "Обновление ViewModel в ExtJs 5"
date: "2015-02-02T21:55:00+03:00"
published: true
tags: [extjs, javascript, программирование, работа]
cover:
    img: /images/3rd-party/extjs-logo.png
    small: true
    color: white
---

[Sencha] добавила в\ ExtJs\ 5 крайне удобную концепцию\ --- ViewModel. Она позволяет динамически связывать данные
с\ представлением. Причём данные могут зависеть друг от\ друга и\ вычисляться по\ сложным алгоритмам. Результат
кешируется, и\ до\ тех пор, пока исходные данные не\ поменяются, конечный результат пересчитываться и\ обновляться
не\ будет. [Обязательно посмотрите][view-model], если ещё не\ сталкивались,\ --- очень удобная штука.

Но, к\ сожалению, есть случаи, когда вселенская гармония нарушается и\ ViewModel перестаёт вести себя как подобает.
Например, когда исходные данные\ --- Store. ViewModel не\ умеет подписываться на\ события изменения ни\ Store,
ни\ вложенных объектов. И\ как назло, разработчики не\ предусмотрели метода, который позволил\ бы заставить ViewModel
пересчитать какое-нибудь значение. В\ таких случаях приходится лезть в\ дебри реализации и\ искать обходные пути.

Делюсь заклинанием:

~~~~~js
viewModel.getRoot().descend(['info']).formula.react();
~~~~~

Эта конструкция заставит ViewModel пересчитать значение `info` и\ обновить все связанные View. Просто подставьте
название вашей формулы вместо `info`.

Проверено на\ ExtJS версий\ 5.0 и\ 5.1. Пользуйтесь и\ не\ позволяйте мелочам портить настроение.

[Sencha]: http://www.sencha.com/
[view-model]: http://docs.sencha.com/extjs/5.0/application_architecture/view_models_data_binding.html


text:
using System;
using System.Net.Http.Formatting;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using kolbasik.NCommandBus.Core;
using kolbasik.NCommandBus.Web;
using Sample.Core;

namespace Sample.WebApp
{
    public sealed class CommandBusHttpHandler : HttpTaskAsyncHandler
    {
        private readonly CommandBusRpc commandBusRpc;

        public CommandBusHttpHandler() : this(SampleDependencyResolver.Instance.Resolve<CommandBus>(), GlobalConfiguration.Configuration.Formatters)
        {
        }

        public CommandBusHttpHandler(CommandBus commandBus, MediaTypeFormatterCollection mediaTypeFormatterCollection)
        {
            if (commandBus == null)
                throw new ArgumentNullException(nameof(commandBus));

            commandBusRpc = new CommandBusRpc(commandBus, mediaTypeFormatterCollection);
        }

        public override bool IsReusable => true;

        public override Task ProcessRequestAsync(HttpContext context)
        {
            return commandBusRpc.ProcessRequest(new HttpContextWrapper(context));
        }
    }
}


text:
package io.getquill.context.jdbc

import java.time.{ LocalDate, LocalDateTime }
import java.util
import java.util.Calendar

import scala.math.BigDecimal.javaBigDecimal2bigDecimal

trait Decoders {
  this: JdbcContextBase[_, _] =>

  type Decoder[T] = JdbcDecoder[T]

  case class JdbcDecoder[T](decoder: BaseDecoder[T]) extends BaseDecoder[T] {
    def apply(index: Index, row: ResultRow) =
      decoder(index + 1, row)
  }

  def decoder[T](d: BaseDecoder[T]): Decoder[T] =
    JdbcDecoder(d)

  def decoder[T](f: ResultRow => Index => T): Decoder[T] =
    decoder((index, row) => f(row)(index))

  implicit def mappedDecoder[I, O](implicit mapped: MappedEncoding[I, O], d: Decoder[I]): Decoder[O] =
    JdbcDecoder(mappedBaseDecoder(mapped, d.decoder))

  implicit def optionDecoder[T](implicit d: Decoder[T]): Decoder[Option[T]] =
    JdbcDecoder(
      (index, row) => {
        try {
          val res = d.decoder(index, row)
          if (row.wasNull()) {
            None
          } else {
            Some(res)
          }
        } catch {
          case _: NullPointerException if row.wasNull() => None
        }
      }
    )

  implicit val stringDecoder: Decoder[String] = decoder(_.getString)
  implicit val bigDecimalDecoder: Decoder[BigDecimal] =
    decoder((index, row) => {
      val v = row.getBigDecimal(index)
      if (v == null)
        BigDecimal(0)
      else
        v
    })
  implicit val byteDecoder: Decoder[Byte] = decoder(_.getByte)
  implicit val shortDecoder: Decoder[Short] = decoder(_.getShort)
  implicit val intDecoder: Decoder[Int] = decoder(_.getInt)
  implicit val longDecoder: Decoder[Long] = decoder(_.getLong)
  implicit val floatDecoder: Decoder[Float] = decoder(_.getFloat)
  implicit val doubleDecoder: Decoder[Double] = decoder(_.getDouble)
  implicit val byteArrayDecoder: Decoder[Array[Byte]] = decoder(_.getBytes)
  implicit val dateDecoder: Decoder[util.Date] =
    decoder((index, row) => {
      val v = row.getTimestamp(index, Calendar.getInstance(dateTimeZone))
      if (v == null)
        new util.Date(0)
      else
        new util.Date(v.getTime)
    })
  implicit val localDateDecoder: Decoder[LocalDate] =
    decoder((index, row) => {
      val v = row.getDate(index, Calendar.getInstance(dateTimeZone))
      if (v == null)
        LocalDate.ofEpochDay(0)
      else
        v.toLocalDate
    })
  implicit val localDateTimeDecoder: Decoder[LocalDateTime] =
    decoder((index, row) => {
      val v = row.getTimestamp(index, Calendar.getInstance(dateTimeZone))
      if (v == null)
        LocalDate.ofEpochDay(0).atStartOfDay()
      else
        v.toLocalDateTime
    })
}