text:
.. Copyright (C) 2004-2008 The Trustees of Indiana University.
   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)

==================================
|Logo| Parallel BGL Process Groups
==================================

.. contents::

Introduction
------------

Process groups are an abstraction of a set of communicating processes
that coordinate to solve the same problem. Process groups contain
facilities for identifying the processes within that group, sending
and receiving messages between the processes in that group, and
performing collective communications involving all processes in the
group simultaneously.

Communication model
-------------------

Process groups are based on an extended version of the Bulk
Synchronous Parallel (BSP) model of computation. Parallel computations
in the BSP model are organized into *supersteps*, each of which
consists of a computation phase followed by a communication
phase. During the computation phase, all processes in the process
group work exclusively on local data, and there is no inter-process
communication. During the communication phase, all of the processes
exchange message with each other. Messages sent in the communication
phase of a superstep will be received in the next superstep.

The boundary between supersteps in the Parallel BGL corresponds to the
``synchronize`` operation. Whenever a process has completed its local
computation phase and sent all of the messages required for that
superstep, it invokes the ``synchronize`` operation on the process
group. Once all processes in the process group have entered
``synchronize``, they exchange messages and then continue with the
next superstep.

The Parallel BGL loosens the BSP model significantly, to provide a
more natural programming model that also provides some performance
benefits over the strict BSP model. The primary extension is the
ability to receive messages sent within the same superstep
"asynchronously", either to free up message buffers or to respond to
an immediate request for information. For particularly unstructured
computations, the ability to send a message and get an immediate reply
can simplify many computations that would otherwise need to be split
into two separate supersteps. Additionally, the Parallel BGL augments
the BSP model with support for multiple distributed data structures,
each of which are provided with a different communication space but
whose messages will all be synchronized concurrently.

Distributed data structures
~~~~~~~~~~~~~~~~~~~~~~~~~~~

A typical computation with the Parallel BGL involves several
distributed data structures working in concern. For example, a simple
breadth-first search involves the distributed graph data structure
containing the graph itself, a distributed queue that manages the
traversal through the graph, and a distributed property map that
tracks which vertices have already been visited as part of the
search.

The Parallel BGL manages these distributed data structures by allowing
each of the data structures to attach themselves to the process group
itself. When a distributed data structure attaches to the process
group, it receives its own copy of the process group that allows the
distributed data structure to communicate without colliding with the
communications from other distributed data structures. When the
process group is synchronized, all of the distributed data structures
attached to that process group are automatically synchronized, so that
all of the distributed data structures in a computation remain
synchronized.

A distributed data structure attaches itself to the process group by
creating a copy of the process group and passing an
``attach_distributed_object`` flag to the process group
constructor. So long as this copy of the process group persists, the
distributed data structure is attached the process group. For this
reason, most distributed data structures keep a copy of the process
group as member data, constructing the member with
``attach_distributed_object``, e.g.,

::

  template<typename ProcessGroup>
  struct distributed_data_structure
  {
    explicit distributed_data_structure(const ProcessGroup& pg)
      : process_group(pg, boost::parallel::attach_distributed_object())
    { }

  private:
    ProcessGroup process_group;
  };

Asynchronous receives
~~~~~~~~~~~~~~~~~~~~~

Distributed data structures in the Parallel BGL can "asynchronously"
receive and process messages before the end of a BSP
superstep. Messages can be received any time that a process is inside
the process group operations, and the scheduling of message receives
is entirely managed by the process group.

Distributed data structures receive messages through
"triggers". Triggers are function objects responsible for processing a
received message. Each trigger is registered with the ``trigger``
method of the process group using a specific message
tag (an integer) and the type of data that is expected to be
contained within that message. Whenever a message with that tag
becomes available, the progress group will call the trigger with the
source of the message, the message tag, the data contained in the
message, and the "context" of the message.

The majority of triggers have no return value, although it is common
that the triggers send messages back to the source process. In certain
cases where the trigger's purpose is to immediately reply with a
value, the trigger should be registered with the
``trigger_with_reply`` method and should return the value that will be
sent back to the caller. The ``trigger_with_reply`` facility is only
useful in conjunction with out-of-band messaging, discussed next.

Out-of-band messaging
~~~~~~~~~~~~~~~~~~~~~

The majority of messages sent by the Parallel BGL are sent through the
normal send operations, to be received in the next superstep or, in
some cases, received "early" by a trigger. These messages are not
time-sensitive, so they will be delivered whenever the process group
processes them.

Some messages, however, require immediate responses. For example, if a
process needs to determine the current value associated with a vertex
owned by another process, the first process must send a request to the
second process and block while waiting for a response. For such
messages, the Parallel BGL's process groups provide an out-of-band
messaging mechanism. Out-of-band messages are transmitted immediately,
with a much higher priority than other messages. The sending of
out-of-band messages can be coupled with a receive operation that
waits until the remote process has received the message and sent its
reply. For example, in the following code the process sends a message
containing the string ``name`` to process ``owner`` with tag
``msg_get_descriptor_by_name`` via an out-of-band message. The
receiver of that message will immediately deliver the message via a
trigger, that returns the resulting value--a
``vertex_descriptor``--that will be passed back to the process that
initiated the communication. The full communication happens
immediately, within the current superstep.

::

  std::string name;
  vertex_descriptor descriptor;
  send_oob_with_reply(process_group, owner, msg_get_descriptor_by_name,
                      name, descriptor);

Reference
---------

The Parallel BGL process groups specify an interface that can be
implemented by various communication subsystems. In this reference
section, we use the placeholder type ``ProcessGroup`` to stand in for
the various process group implementations that exist. There is only
one implementation of the process group interface at this time:

  - `MPI BSP process group`_

::

  enum trigger_receive_context {
    trc_none,
    trc_in_synchronization,
    trc_early_receive,
    trc_out_of_band
  };

  class ProcessGroup
  {
    // Process group constructors
    ProcessGroup();
    ProcessGroup(const ProcessGroup&, boost::parallel::attach_distributed_object);

    // Triggers
    template<typename Type, typename Handler>
      void trigger(int tag, const Handler& handler);

    template<typename Type, typename Handler>
      void trigger_with_reply(int tag, const Handler& handler);

    trigger_receive_context trigger_context() const;

    // Helper operations
    void poll();
    ProcessGroup base() const;
  };

  // Process query
  int process_id(const ProcessGroup&);
  int num_processes(const ProcessGroup&);

  // Message transmission
  template<typename T>
    void send(const ProcessGroup& pg, int dest, int tag, const T& value);

  template<typename T>
    void receive(const ProcessGroup& pg, int source, int tag, T& value);

  optional<std::pair<int, int> > probe(const ProcessGroup& pg);

  // Synchronization
  void synchronize(const ProcessGroup& pg);

  // Out-of-band communication
  template<typename T>
    void send_oob(const ProcessGroup& pg, int dest, int tag, const T& value);

  template<typename T, typename U>
    void
    send_oob_with_reply(const ProcessGroup& pg, int dest, int
                        tag, const T& send_value, U& receive_value);

  template<typename T>
    void receive_oob(const ProcessGroup& pg, int source, int tag, T& value);

Process group constructors
~~~~~~~~~~~~~~~~~~~~~~~~~~

::

    ProcessGroup();

Constructs a new process group with a different communication space
from any other process group.

-----------------------------------------------------------------------------

::

    ProcessGroup(const ProcessGroup& pg, boost::parallel::attach_distributed_object);

Attaches a new distributed data structure to the process group
``pg``. The resulting process group can be used for communication
within that new distributed data structure. When the newly-constructed
process group is eventually destroyed, the distributed data structure
is detached from the process group.

Triggers
~~~~~~~~

::

    template<typename Type, typename Handler>
      void trigger(int tag, const Handler& handler);

Registers a trigger with the given process group. The trigger will
watch for messages with the given ``tag``. When such a message is
available, it will be received into a value of type ``Type``, and the
function object ``handler`` will be invoked with four parameters:

source
  The rank of the source process (an ``int``)

tag
  The tag used to send the message (also an ``int``)

data:
  The data transmitted with the message. The data will have the type
  specified when the trigger was registered.

context:
  The context in which the trigger is executed. This will be a value of
  type ``trigger_receive_context``, which stages whether the trigger
  is being executed during synchronization, asynchronously in response
  to an "early" receive (often to free up communication buffers), or
  in response to an "out-of-band" message.

Triggers can only be registered by process groups that result from
attaching a distributed data structure. A trigger can be invoked in
response to either a normal send operation or an out-of-band send
operation. There is also a `simple trigger interface`_ for defining
triggers in common cases.

-----------------------------------------------------------------------------

::

    template<typename Type, typename Handler>
      void trigger_with_reply(int tag, const Handler& handler);

Like the ``trigger`` method, registers a trigger with the given
process group. The trigger will watch for messages with the given
``tag``. When such a message is available, it will be received into a
value of type ``Type`` and ``handler`` will be invoked, just as with a
normal trigger. However, a trigger registered with
``trigger_with_reply`` must return a value, which will be immediately
sent back to the process that initiated the send resulting in this
trigger. Thus, ``trigger_with_reply`` should only be used for messages
that need immediate responses. These triggers can only be invoked via
the out-of-band sends that wait for the reply, via
``send_oob_with_reply``. There is also a `simple trigger interface`_
for defining triggers in common cases.

-----------------------------------------------------------------------------

::

    trigger_receive_context trigger_context() const;

Retrieves the current context of the process group with respect to the
invocation of triggers. When ``trc_none``, the process group is not
currently invoking any triggers. Otherwise, this value describes in
what context the currently executing trigger is being invoked.

Helper operations
~~~~~~~~~~~~~~~~~

::

  void poll();

Permits the process group to receive any incomining messages,
processing them via triggers. If you have a long-running computation
that does not invoke any of the process group's communication
routines, you should call ``poll`` occasionally to along incoming
messages to be processed.

-----------------------------------------------------------------------------

::

    ProcessGroup base() const;

Retrieves the "base" process group for this process group, which is a
copy of the underlying process group that does not reference any
specific distributed data structure.

Process query
~~~~~~~~~~~~~

::

  int process_id(const ProcessGroup& pg);

Retrieves the ID (or "rank") of the calling process within the process
group. Process IDs are values in the range [0, ``num_processes(pg)``)
that uniquely identify the process. Process IDs can be used to
initiate communication with another process.

-----------------------------------------------------------------------------

::

  int num_processes(const ProcessGroup& pg);

Returns the number of processes within the process group.

Message transmission
~~~~~~~~~~~~~~~~~~~~

::

  template<typename T>
    void send(const ProcessGroup& pg, int dest, int tag, const T& value);

Sends a message with the given ``tag`` and carrying the given
``value`` to the process with ID ``dest`` in the given process
group. All message sends are non-blocking, meaning that this send
operation will not block while waiting for the communication to
complete. There is no guarantee when the message will be received,
except that it will become available to the destination process by the
end of the superstep, in the collective call to ``synchronize``.

Any type of value can be transmitted via ``send``, so long as it
provides the appropriate functionality to be serialized with the
Boost.Serialization library.

-----------------------------------------------------------------------------

::

  template<typename T>
    void receive(const ProcessGroup& pg, int source, int tag, T& value);

Receives a message with the given ``tag`` sent from the process
``source``, updating ``value`` with the payload of the message. This
receive operation can only receive messages sent within the previous
superstep via the ``send`` operation. If no such message is available
at the time ``receive`` is called, the program is ill-formed.

-----------------------------------------------------------------------------

::

  optional<std::pair<int, int> > probe(const ProcessGroup& pg);

Determines whether a message is available. The probe operation checks
for any messages that were sent in the previous superstep but have not
yet been received. If such a message exists, ``probe`` returns a
(source, tag) pair describing the message. Otherwise, ``probe`` will
return an empty ``boost::optional``.

A typical use of ``probe`` is to continually probe for messages at the
beginning of the superstep, receiving and processing those messages
until no messages remain.

Synchronization
~~~~~~~~~~~~~~~

::

  void synchronize(const ProcessGroup& pg);

The ``synchronize`` function is a collective operation that must be
invoked by all of the processes within the process group. A call to
``synchronize`` marks the end of a superstep in the parallel
computation. All messages sent before the end of the superstep will be
received into message buffers, and can be processed by the program in
the next superstep. None of the processes will leave the
``synchronize`` function until all of the processes have entered the
function and exchanged messages, so that all processes are always on
the same superstep.

Out-of-band communication
~~~~~~~~~~~~~~~~~~~~~~~~~

::

  template<typename T>
    void send_oob(const ProcessGroup& pg, int dest, int tag, const T& value);

Sends and out-of-band message. This out-of-band send operation acts
like the normal ``send`` operation, except that out-of-band messages
are delivered immediately through a high-priority channel.

-----------------------------------------------------------------------------

::

  template<typename T, typename U>
    void
    send_oob_with_reply(const ProcessGroup& pg, int dest, int
                        tag, const T& send_value, U& receive_value);

Sends an out-of-band message and waits for a reply. The
``send_oob_with_reply`` function can only be invoked with message tags
that correspond to triggers registered with
``trigger_with_reply``. This operation will send the message
immediately (through the high-priority, out-of-band channel), then
wait until the remote process sends a reply. The data from the reply
is stored into ``receive_value``.

-----------------------------------------------------------------------------

::

  template<typename T>
    void receive_oob(const ProcessGroup& pg, int source, int tag, T& value);

Receives an out-of-band message with the given ``source`` and
``tag``. As with the normal ``receive`` operation, it is an error to
call ``receive_oob`` if no message matching the source and tag is
available. This routine is used only rarely; for most circumstances,
use ``send_oob_with_reply`` to perform an immediate send with a
reply.

-----------------------------------------------------------------------------

Copyright (C) 2007 Douglas Gregor

Copyright (C) 2007 Matthias Troyer

.. |Logo| image:: pbgl-logo.png
            :align: middle
            :alt: Parallel BGL
            :target: http://www.osl.iu.edu/research/pbgl

.. _MPI BSP process group: mpi_bsp_process_group.html
.. _Simple trigger interface: simple_trigger.html


text:
#ifndef IVW_CAMERA_H
#define IVW_CAMERA_H

#include <inviwo/core/common/inviwocoredefine.h>
#include <inviwo/core/common/inviwo.h>

namespace inviwo {

/**
 * \class Camera
 *
 * \brief Base class for cameras.
 * Override this class to set your own projection matrix.
 * @see PerspectiveCamera
 * @see OrthographicCamera
 */
class IVW_CORE_API Camera : public IvwSerializable {
public:
    /**
     * \brief Default parameters creates a right handed coordinate system
     * with camera looking towards the negative z-axis.
     * with X = (1, 0, 0), Y = (0, 1, 0), Z = (0, 0, -1)
     *
     * @param vec3 lookFrom Camera position (eye)
     * @param vec3 lookTo Camera focus point (center)
     * @param vec3 lookUp Camera up direction
     */
    Camera(vec3 lookFrom = vec3(0.0f, 0.0f, 2.0f), vec3 lookTo = vec3(0.0f),
               vec3 lookUp = vec3(0.0f, 1.0f, 0.0f), float nearPlane = 0.01f,
               float farPlane = 10000.0f);
    virtual ~Camera() = default;
    Camera(const Camera& other) = default;
    //Camera(Camera&& other) = default;
    Camera& operator=(const Camera& other) = default;

    vec3& getLookFrom() { return lookFrom_; }
    const vec3& getLookFrom() const;
    void setLookFrom(vec3 val);

    vec3& getLookTo() { return lookTo_; }
    const vec3& getLookTo() const;
    void setLookTo(vec3 val);

    vec3& getLookUp() { return lookUp_; }
    const vec3& getLookUp() const;
    void setLookUp(vec3 val);

    /**
     * \brief Get unnormalized direction of camera: lookTo - lookFrom
     *
     * @return Unnormalized direction of camera
     */
    vec3 getDirection() const { return lookTo_ - lookFrom_; }

    float getNearPlaneDist() const;
    /**
     * \brief Set distance to the near plane from lookFrom.
     *
     * @param val Distance
     */
    void setNearPlaneDist(float val);

    float getFarPlaneDist() const;
    /**
     * \brief Set distance to the far plane from lookFrom.
     *
     * @param val Distance
     */
    void setFarPlaneDist(float val);

    const mat4& viewMatrix() const;
    const mat4& projectionMatrix() const;
    const mat4& inverseViewMatrix() const;
    const mat4& inverseProjectionMatrix() const;

    /**
    * \brief Convert from normalized device coordinates (xyz in [-1 1]) to world coordinates.
    *
    * @param ndcCoords Coordinates in [-1 1]
    * @return World space position
    */
    vec3 getWorldPosFromNormalizedDeviceCoords(const vec3& ndcCoords) const;

    /**
    * \brief Convert from normalized device coordinates (xyz in [-1 1]) to clip coordinates,
    * where z value of -1 correspond to the near plane and 1 to the far plane.
    * Coordinates outside of the [-1 1]^3 range will be clipped.
    *
    * @param ndcCoords xyz clip-coordinates in [-1 1]^3, and the clip w-coordinate used for perspective division.
    * @return Clip space position
    */
    vec4 getClipPosFromNormalizedDeviceCoords(const vec3& ndcCoords) const;

    virtual void serialize(IvwSerializer& s) const override;
    virtual void deserialize(IvwDeserializer& d) override;

protected:

    bool equalTo(const Camera& other) const;
    /**
     * \brief Calculate and return the projection matrix for the camera.
     *
     * Implement this function to provide your own projection computation functionality.
     * For example orthogonal or perspective projection.
     * This function will be called when the projection matrix is invalid.
     * @see PerspectiveCamera
     * @see OrthographicCamera
     */
    virtual mat4 calculateProjectionMatrix() const = 0;
    void invalidateViewMatrix();
    void invalidateProjectionMatrix();

    vec3 lookFrom_;
    vec3 lookTo_;
    vec3 lookUp_;

    float nearPlaneDist_; ///< Distance to the near plane from lookFrom.
    float farPlaneDist_;  ///< Distance to the far plane from lookFrom.

    // Make mutable to allow then to be changed even though they are called from const function.
    // This allows us to perform lazy evaluation.
    mutable bool invalidViewMatrix_;
    mutable bool invalidProjectionMatrix_;
    mutable mat4 viewMatrix_;
    mutable mat4 projectionMatrix_;
    mutable mat4 inverseViewMatrix_;
    mutable mat4 inverseProjectionMatrix_;
};

class IVW_CORE_API PerspectiveCamera : public Camera {
public:
    PerspectiveCamera(vec3 lookFrom = vec3(0.0f, 0.0f, 2.0f), vec3 lookTo = vec3(0.0f),
                      vec3 lookUp = vec3(0.0f, 1.0f, 0.0f), float nearPlane = 0.01f,
                      float farPlane = 10000.0f, float fieldOfView = 60.f, float aspectRatio = 1.f);
    virtual ~PerspectiveCamera() = default;
    PerspectiveCamera(const PerspectiveCamera& other) = default;
    //Camera(Camera&& other) = default;
    PerspectiveCamera& operator=(const PerspectiveCamera& other) = default;

    friend bool operator==(const PerspectiveCamera& lhs, const PerspectiveCamera& rhs);
    friend bool operator!=(const PerspectiveCamera& lhs, const PerspectiveCamera& rhs);

    float getFovy() const;
    void setFovy(float val);
    float getAspectRatio() const;
    void setAspectRatio(float val);

    virtual void serialize(IvwSerializer& s) const override;
    virtual void deserialize(IvwDeserializer& d) override;

protected:
    virtual mat4 calculateProjectionMatrix() const override;

    float fovy_;
    float aspectRatio_;
};

bool operator==(const PerspectiveCamera& lhs, const PerspectiveCamera& rhs);
bool operator!=(const PerspectiveCamera& lhs, const PerspectiveCamera& rhs);

/**
 * \class OrthographicCamera
 *
 * \brief Camera with no perspective projection.
 * Objects far away will apear as large as objects close.
 * @see Camera
 * @see OrthographicCamera
 */
class IVW_CORE_API OrthographicCamera : public Camera {
public:
    OrthographicCamera(vec3 lookFrom = vec3(0.0f, 0.0f, 2.0f), vec3 lookTo = vec3(0.0f),
                       vec3 lookUp = vec3(0.0f, 1.0f, 0.0f), float nearPlane = 0.01f,
                       float farPlane = 10000.0f, vec4 frustum = vec4(-1, 1, -1, 1));
    virtual ~OrthographicCamera() = default;
    OrthographicCamera(const OrthographicCamera& other) = default;
    //Camera(Camera&& other) = default;
    OrthographicCamera& operator=(const OrthographicCamera& other) = default;

    friend bool operator==(const OrthographicCamera& lhs, const OrthographicCamera& rhs);
    friend bool operator!=(const OrthographicCamera& lhs, const OrthographicCamera& rhs);

    const vec4& getFrustum() const;
    /**
     * \brief Left, right, bottom, top view volume
     *
     * Set view frustum used for projection matrix calculation.
     *
     * @param inviwo::vec4 val
     * @return void
     */
    void setFrustum(vec4 val);

    virtual void serialize(IvwSerializer& s) const override;
    virtual void deserialize(IvwDeserializer& d) override;

protected:
    virtual mat4 calculateProjectionMatrix() const override;

    // Left, right, bottom, top view volume
    vec4 frustum_;
};

bool operator==(const OrthographicCamera& lhs, const OrthographicCamera& rhs);
bool operator!=(const OrthographicCamera& lhs, const OrthographicCamera& rhs);

// Implementation details

inline const vec3& Camera::getLookFrom() const { return lookFrom_; }
inline void Camera::setLookFrom(vec3 val) {
    lookFrom_ = val;
    invalidateViewMatrix();
}
inline const vec3& Camera::getLookTo() const { return lookTo_; }
inline void Camera::setLookTo(vec3 val) {
    lookTo_ = val;
    invalidateViewMatrix();
}
inline const vec3& Camera::getLookUp() const { return lookUp_; }
inline void Camera::setLookUp(vec3 val) {
    lookUp_ = val;
    invalidateViewMatrix();
}

inline float Camera::getNearPlaneDist() const { return nearPlaneDist_; }
inline void Camera::setNearPlaneDist(float val) {
    nearPlaneDist_ = val;
    invalidateProjectionMatrix();
}
inline float Camera::getFarPlaneDist() const { return farPlaneDist_; }
inline void Camera::setFarPlaneDist(float val) {
    farPlaneDist_ = val;
    invalidateProjectionMatrix();
}

inline void Camera::invalidateViewMatrix() { invalidViewMatrix_ = true; }
inline void Camera::invalidateProjectionMatrix() { invalidProjectionMatrix_ = true; }

inline float PerspectiveCamera::getFovy() const { return fovy_; }
inline void PerspectiveCamera::setFovy(float val) {
    fovy_ = val;
    invalidateProjectionMatrix();
}
inline float PerspectiveCamera::getAspectRatio() const { return aspectRatio_; }
inline void PerspectiveCamera::setAspectRatio(float val) {
    aspectRatio_ = val;
    invalidateProjectionMatrix();
}

inline mat4 PerspectiveCamera::calculateProjectionMatrix() const {
    return glm::perspective(glm::radians(fovy_), aspectRatio_, nearPlaneDist_, farPlaneDist_);
};

inline const vec4& OrthographicCamera::getFrustum() const { return frustum_; }

inline void OrthographicCamera::setFrustum(inviwo::vec4 val) {
    frustum_ = val;
    invalidateProjectionMatrix();
}

inline mat4 OrthographicCamera::calculateProjectionMatrix() const {
    return glm::ortho(frustum_.x, frustum_.y, frustum_.z, frustum_.w, nearPlaneDist_, farPlaneDist_);
};

}  // namespace

#endif  // IVW_CAMERA_H

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace BB\GalleryBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use BB\GalleryBundle\Entity\BbUserScore;

class UserScoreController extends Controller {

  public function ajaxGetBeerScoreAction(Request $request) {
    if ($request->isXmlHttpRequest()) {
      $bb_services = $this->get('bb_services');
      $beer_id = $request->query->get('beer_id');
      $beer = $bb_services->getBeer($beer_id);
      $user = $bb_services->getCurrentUser();

      $scores = $this->getDoctrine()
              ->getManager()
              ->getRepository('BBGalleryBundle:BbUserScore')
              ->findBeerScoreByUser($beer, $user);
      $serializer = $this->get('jms_serializer');
      $json_scores = $serializer->serialize($scores, 'json');
      return new Response($json_scores, 200, array('Content-Type' => 'application/json'));
    } else {
      throw new \Exception('Ongeldige bewerking');
    }
    return new Response('ajaxScoreAction was not an xmlHttpRequest');
  }

  public function ajaxInsertBeerScoreAction(Request $request) {
    if ($request->isXmlHttpRequest()) {
      $bb_services = $this->get('bb_services');
      $beer_id = $request->query->get('beer_id');
      $beer = $bb_services->getBeer($beer_id);
      $stars = $request->query->get('ajax_score');
      $score = $this->getDoctrine()
              ->getManager()
              ->getRepository('BBGalleryBundle:BbScore')
              ->findBy(array('stars' => $stars));
      $user = $this->getUser();
      $user_score = new BbUserScore();
      $user_score->setUser($user);
      $user_score->setBeer($beer);
      $user_score->setScore($score[0]);
      $em = $this->get('doctrine')->getManager();
      $em->persist($user_score);
      $em->flush();
      return new Response('SCORE INSERTTED');
    } else {
      throw new \Exception('Ongeldige bewerking');
    }
  }

  public function ajaxUpdateBeerScoreAction(Request $request) {
    if ($request->isXmlHttpRequest()) {
      $bb_services = $this->get('bb_services');

      //retrieve score
      $beer_id = $request->query->get('beer_id'); //GET
      $user = $bb_services->getCurrentUser();
      $beer = $bb_services->getBeer($beer_id);
      $user_score = $this->getDoctrine()
              ->getManager()
              ->getRepository('BBGalleryBundle:BbUserScore')
              ->findBy(array('user' => $user, 'beer' => $beer));

      // update score with new value
      $stars = $request->query->get('ajax_score'); //GET
      $score = $this->getDoctrine()
              ->getManager()
              ->getRepository('BBGalleryBundle:BbScore')
              ->findBy(array('stars' => $stars));
      $user_score[0]->setScore($score[0]);
      $em = $this->get('doctrine')->getManager();
      $em->persist($user_score[0]);
      $em->flush();

      return new Response('SCORE UPDATED');
    } else {
      throw new Exception('Ongeldige bewerking');
    }
  }

  public function ajaxGetAverageRatingAction(Request $request) {
    if ($request->isXmlHttpRequest()) {
      $beer_id = $request->query->get('beer_id');

      $scores = $this->getDoctrine()
              ->getManager()
              ->getRepository('BBGalleryBundle:BbUserScore')
              ->getAverageScore($beer_id);

      //$average = array('average' => 3.65);
      $serializer = $this->get('jms_serializer');
      $json_average = $serializer->serialize($scores, 'json');

      return new Response($json_average, 200, array('Content-Type' => 'application/json'));
    } else {
      throw new Exception('Ongeldige bewerking');
    }
  }

}


text:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var fs = require('fs');

// init
var initLeanCloud = require('./utils/initleancloud');
initLeanCloud();

var stockApi = require('./routes/stock');
var userApi = require('./routes/user');
var tableApi = require('./routes/table');

var app = express();
var ejs = require('ejs');

//allow custom header and CORS
app.all('*', function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With, X-Token');
    res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
    res.header("X-Powered-By", ' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");

    if (req.method == 'OPTIONS') {
        res.send(200); // 让options请求快速返回
    }
    else {
        next();
    }
});

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.engine('.html', ejs.__express);
app.set('view engine', 'html'); // app.set('view engine', 'ejs');

app.use(favicon(path.join(__dirname, 'favicon', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// 处理webpack服务请求
app.get('/__webpack_hmr', function (req, res) {
    res.send('')
})

app.get('/', (req, res) => {
    res.redirect('app');
});

app.use('/list', (req, res) => {
    res.render('index');
});

// API路由
app.use('/stock', stockApi);
app.use('/user', userApi);
app.use('/table', tableApi);

app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

if (app.get('env') === 'development') {
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

module.exports = app;


text:
#ifndef __G_FAM_FILE_MONITOR_H__
#define __G_FAM_FILE_MONITOR_H__

#include <glib-object.h>
#include <string.h>
#include <gio/gfilemonitor.h>
#include "glocalfilemonitor.h"
#include "giomodule.h"

G_BEGIN_DECLS

#define G_TYPE_FAM_FILE_MONITOR		(g_fam_file_monitor_get_type ())
#define G_FAM_FILE_MONITOR(o)			(G_TYPE_CHECK_INSTANCE_CAST ((o), G_TYPE_FAM_FILE_MONITOR, GFamFileMonitor))
#define G_FAM_FILE_MONITOR_CLASS(k)		(G_TYPE_CHECK_CLASS_CAST ((k), G_TYPE_FAM_FILE_MONITOR, GFamFileMonitorClass))
#define G_IS_FAM_FILE_MONITOR(o)		(G_TYPE_CHECK_INSTANCE_TYPE ((o), G_TYPE_FAM_FILE_MONITOR))
#define G_IS_FAM_FILE_MONITOR_CLASS(k)	(G_TYPE_CHECK_CLASS_TYPE ((k), G_TYPE_FAM_FILE_MONITOR))

typedef struct _GFamFileMonitor      GFamFileMonitor;
typedef struct _GFamFileMonitorClass GFamFileMonitorClass;

struct _GFamFileMonitorClass {
  GLocalFileMonitorClass parent_class;
};

GType g_fam_file_monitor_get_type (void);
void g_fam_file_monitor_register (GIOModule *module);

G_END_DECLS

#endif /* __G_FAM_FILE_MONITOR_H__ */


text:
"""
Add color cycling fun to your i3bar.

This is the most pointless yet most exciting module you can imagine.

It allows color cycling of modules. Imagine the joy of having the current time
change through the colors of the rainbow.

If you were completely insane you could also use it to implement the i3bar
equivalent of the <blink> tag and cause yourself endless headaches and the
desire to vomit.

The color for the contained module(s) is changed and cycles through your chosen
gradient by default this is the colors of the rainbow.  This module will
increase the amount of updates that py3status needs to do so should be used
sparingly.

Configuration parameters:
    cycle_time: How often we change this color in seconds
        (default 1)
    force: If True then the color will always be set.  If false the color will
        only be changed if it has not been set by a module.
        (default False)
    format: display format for this module (default '{output}')
    gradient: The colors we will cycle through, This is a list of hex values
        *(default [ '#FF0000', '#FFFF00', '#00FF00', '#00FFFF',
        '#0000FF', '#FF00FF', '#FF0000', ])*
    multi_color: If True then each module the rainbow contains will be colored
        differently (default True)
    steps: Number of steps between each color in the gradient
        (default 10)

Format placeholders:
    {output} rainbow output

Examples:
```
# show time colorfully
order += "rainbow time"
rainbow time {
    time {}
}

# blinking text black/white
order += "rainbow blink_time"
rainbow blink_time {
    gradient = [
        '#FFFFFF',
        '#000000',
    ]
    steps = 1
    time {}
}
```

@author tobes

SAMPLE OUTPUT
[
    {'color': '#FF0000', 'full_text': 'module 1'},
    {'color': '#CCFF00', 'full_text': 'module 2', 'separator': True},
    {'color': '#00FF66', 'full_text': 'module 3', 'separator': True},
    {'color': '#0066FF', 'full_text': 'module 4', 'separator': True},
    {'color': '#CC00FF', 'full_text': 'module 5', 'separator': True}
]
"""

import re
import math
import time

HEX_RE = re.compile("#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})")

class Py3status:
    """ """

    # available configuration parameters
    cycle_time = 1
    force = False
    format = "{output}"
    gradient = [
        "#FF0000",
        "#FFFF00",
        "#00FF00",
        "#00FFFF",
        "#0000FF",
        "#FF00FF",
        "#FF0000",
    ]
    multi_color = True
    steps = 10

    class Meta:
        container = True

    def post_config_hook(self):
        def from_hex(color):
            """
            Convert hex color #xxx or #xxxxxx to [r, g, b].
            """
            if not HEX_RE.match(color):
                color = "#FFF"
            if len(color) == 7:
                return (int(color[1:3], 16), int(color[3:5], 16), int(color[5:], 16))
            return (
                int(color[1], 16) * 17,
                int(color[2], 16) * 17,
                int(color[3], 16) * 17,
            )

        def to_hex(color):
            """
            Convert [r, g, b] to hex.
            """
            return "#{:02X}{:02X}{:02X}".format(
                int(color[0]), int(color[1]), int(color[2])
            )

        def make_color(c1, c2, t):
            """
            Generate a mid color between c1 and c2.
            """

            def fade(i):
                a = c1[i]
                b = c2[i]
                x = b * t
                x += a * (1 - t)
                return x

            c1 = from_hex(c1)
            c2 = from_hex(c2)
            return (fade(0), fade(1), fade(2))

        colors = []
        if self.steps == 1:
            colors = [to_hex(from_hex(x)) for x in self.gradient]
        else:
            for grad_a, grad_b in zip(self.gradient, self.gradient[1:]):
                for j in range(self.steps):
                    colors.append(to_hex(make_color(grad_a, grad_b, j / self.steps)))
        self.colors = colors
        self.active_color = 0
        self._set_cycle_time()

    def _set_cycle_time(self):
        """
        Set next cycle update time synced to nearest second or 0.1 of second.
        """
        now = time.monotonic()
        try:
            cycle_time = now - self._cycle_time
            if cycle_time < 0:
                cycle_time = 0
        except AttributeError:
            cycle_time = 0
        cycle_time += self.cycle_time
        if cycle_time == int(cycle_time):
            self._cycle_time = math.ceil(now + cycle_time)
        else:
            self._cycle_time = math.ceil((now + cycle_time) * 10) / 10
        self._cycle_time = now + self.cycle_time

    def _get_current_output(self):
        """
        Get child modules output.
        """
        output = []
        for item in self.items:
            out = self.py3.get_output(item)
            if out and "separator" not in out[-1]:
                out[-1]["separator"] = True
            output += out
        return output

    def rainbow(self):
        """
        Make a rainbow!
        """
        if not self.items:
            return {"full_text": "", "cached_until": self.py3.CACHE_FOREVER}

        if time.monotonic() >= self._cycle_time - (self.cycle_time / 10):
            self.active_color = (self.active_color + 1) % len(self.colors)
            self._set_cycle_time()

        color = self.colors[self.active_color]
        content = self._get_current_output()
        output = []

        if content:
            step = len(self.colors) // len(content)
        for index, item in enumerate(content):
            if self.multi_color:
                offset = (self.active_color + (index * step)) % len(self.colors)
                color = self.colors[offset]
            obj = item.copy()
            if self.force or not obj.get("color"):
                obj["color"] = color
            output.append(obj)

        composites = {"output": self.py3.composite_create(output)}
        rainbow = self.py3.safe_format(self.format, composites)

        return {"cached_until": self._cycle_time, "full_text": rainbow}

if __name__ == "__main__":
    """
    Run module in test mode.
    """
    from py3status.module_test import module_test

    module_test(Py3status)


text:
<?php

namespace App;

use Nette,
	Nette\Application\Routers\RouteList,
	Nette\Application\Routers\Route,
	Nette\Application\Routers\SimpleRouter;

/**
 * Router factory.
 */
class RouterFactory
{

	/**
	 * @return \Nette\Application\IRouter
	 */
	public static function createRouter($urlFilter = 'en')
	{
		$router = new RouteList();

		$router[] = $adminRouter = new RouteList('Admin');
		// $adminRouter[] = new Route('admin/[<locale=cs cs|en>/]<presenter>/<action>[/<id>]', 'Homepage:default', Route::SECURED); // , Route::SECURED for admin
		$adminRouter[] = new Route('admin/[<locale=cs cs|en>/]<presenter>/<action>[/<id>]', 'Homepage:default'); // for localhost

		$router[] = $frontRouter = new RouteList('Front');

		$frontRouter[] = new Route('robots.txt', [
			'presenter' => 'Robot',
			'action' => 'default',
		]);

		$frontRouter[] = new Route('sitemap.xml', [
			'presenter' => 'Sitemap',
			'action' => 'default',
		]);

		$frontRouter[] = new Route('[<locale=cs cs|en>/]index.php', 'Homepage:default', Route::ONE_WAY); // For NetBeans Connector only.

		$frontRouter[] = new Route('[<locale=cs cs|en>/]<presenter>/<action>[/<slug>]', [
			'presenter' => 'Homepage',
			'action' => 'default',
		]);

		return $router;

	}

}


text:
There are several options to use fiware-cloto very easily using docker. These are (in order of complexity):

- _"Have everything automatically done for me"_. See Section **1. The Fastest Way** (recommended).
- _"Check the unit tests associated to the component"_. See Section **2. Run Unit Test of fiware-cloto**.
- _"Check the acceptance tests are running properly"_ or _"I want to check that my fiware-cloto instance run properly"_ . See Section **3. Run Acceptance tests**.

You do not need to do all of them, just use the first one if you want to have a fully operational fiware-cloto instance and maybe third one to check if your fiware-cloto instance run properly.

You do need to have docker in your machine. See the [documentation](https://docs.docker.com/installation/) on how to do this. Additionally, you can use the proper FIWARE Lab docker functionality to deploy dockers image there. See the [documentation](https://docs.docker.com/installation/)

----
## 1. The Fastest Way

Docker allows you to deploy an fiware-cloto container in a few minutes. This method requires that you have installed docker or can deploy container into the FIWARE Lab (see previous details about it).

Consider this method if you want to try fiware-cloto and do not want to bother about losing data.

Follow these steps:

- Download [fiware-cloto' source code](https://github.com/telefonicaid/fiware-cloto) from GitHub (`git clone https://github.com/telefonicaid/fiware-cloto.git`)
- `cd fiware-cloto/docker`
- Using the command-line and within the directory you created type: `docker build -t fiware-cloto -f Dockerfile .`.

After a few seconds you should have your fiware-cloto image created. Just run the command `docker images` and you see the following response:

    REPOSITORY          TAG                 IMAGE ID            CREATED              SIZE
    fiware-cloto       latest              bd78d006c2ea        About a minute ago   480.8 MB
    ...

fiware-cloto image needs somce dockers mysql and rabbit alredy deployed. Thus, to deploy the container we need to execute the command `docker run -p 8000:8000 -e PASSWORD=$PASSWORD -l rabbit -l mysql fiware-cloto`.
It will launch the fiware-cloto service listening on port 8000, which is linked to mysql and rabbit dockers.

To check that the service is running correcly, just do

	curl <IP address of a machine>:8000

You can obtain the IP address of the machine just executing `docker-machine ip`. What you have done with this method is the creation of the [fiware-cloto](https://hub.docker.com/r/fiware/bosun-cloto/)
image from the public repository of images called [Docker Hub](https://hub.docker.com/).

If you want to stop the scenario you have to execute `docker ps` and you see something like this:

    CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                    NAMES
    b8e1de41deb5        fiware-cloto       "/bin/sh -c ./start.s"   6 minutes ago       Up 6 minutes        0.0.0.0:8000->8000/tcp   fervent_davinci
    ...

Take the Container ID and execute `docker stop b8e1de41deb5` or `docker kill b8e1de41deb5`. Note that you will lose any data that was being used in fiware-cloto using this method.

However, there is a simpler way to deploy the container. That is docker-compose and it avoids to deploy containers previously and specifies the port for fiware-cloto.
It involves just executing docker-compose up -d to launch the architecture, after exporting a set of environment variables.

    export KEYSTONE_IP=<IP of the keystone instance>
    export ADM_TENANT_ID=<admin tenant id in the OpenStack environment>
    export ADM_TENANT_NAME=<admin tenant name>
    export ADM_USERNAME=<admin username>
    export ADM_PASSWORD=<admin password>
    export OS_USER_DOMAIN_NAME=<OpenStack user domain name>
    export OS_PROJECT_DOMAIN_NAME=<OpenStack project domain name>

If you want to check the containers just execute docker-compose ps.

           Name                      Command               State                                                Ports
    ----------------------------------------------------------------------------------------------------------------------------------------------------------------
    docker_fiwarecloto_1   /bin/sh -c ./start.sh            Up      0.0.0.0:8000->8000/tcp
    mysql                  docker-entrypoint.sh mysqld      Up      0.0.0.0:3306->3306/tcp
    rabbit                 /docker-entrypoint.sh rabb ...   Up      0.0.0.0:25672->25672/tcp, 0.0.0.0:4369->4369/tcp, 0.0.0.0:5671->5671/tcp, 0.0.0.0:5672->5672/tc

You can take a look to the log generated executing docker-compose logs.

----
## 2. Run Unit Test of fiware-cloto

Taking into account that you download the repository from GitHub (See Section **1. The Fastest Way**), this method will launch a container running fiware-cloto, and execute the unit tests associated to the component. You should move to the UnitTests folder `./UnitTests`. Just create a new docker image executind `docker build -t fiware-cloto-unittests -f Dockerfile .`. Please keep in mind that if you do not change the name of the image it will automatically create a new one for unit tests and change the previous one to tag none.

To see that the image is created run `docker images` and you see something like this:

    REPOSITORY                TAG                 IMAGE ID            CREATED             SIZE
    fiware-cloto-unittests    latest              103464a8ede0        30 seconds ago      551.3 MB
    ...

To execute the unit tests of this component, just execute `docker run --name fiware-cloto-unittests fiware-cloto-unittests`. Finally you can extract the information of the executed tests
just executing `docker cp fiware-cloto-unittests:/opt/fiware-cloto/report .`

> TIP: If you are trying these methods or run them more than once and come across an error saying that the container already exists you can delete it with `docker rm fiware-cloto-unittests`.
If you have to stop it first do `docker stop fiware-cloto-unittests`.

Keep in mind that if you use these commands you get access to the tags and specific versions of fiware-cloto. If you do not specify a version you are pulling from `latest` by default.

----
## 3. Run Acceptance tests

Taking into account that you download the repository from GitHub (See Section **1. The Fastest Way**). This method will launch a container to run the E2E tests of the fiware-cloto component, previously you should launch or configure a FIWARE Lab access. You have to define the following environment variables:

    export KEYSTONE_IP=<IP of the keystone instance>
    export ADM_TENANT_ID=<admin tenant id in the OpenStack environment>
    export ADM_TENANT_NAME=<admin tenant name>
    export ADM_USERNAME=<admin username>
    export ADM_PASSWORD=<admin password>
    export OS_USER_DOMAIN_NAME=<OpenStack user domain name>
    export OS_PROJECT_DOMAIN_NAME=<OpenStack project domain name>

Take it, You should move to the AcceptanceTests folder `./AcceptanceTests`. Just create a new docker image executing `docker build -t fiware-cloto-acceptance .`. To see that the image is created run `docker images` and you see something like this:

    REPOSITORY                 TAG                 IMAGE ID            CREATED             SIZE
    fiware-cloto-acceptance   latest              eadbe0b2e186        About an hour ago   579.3 MB
    fiware-cloto              latest              a46ffad45e60        4 hours ago         480.8 MB
    ...

Now is time to execute the container. This time, we take advantage of the docker compose. Just execute `docker-compose up` to launch the architecture. You can take a look to the log generated executing `docker-compose logs`. If you want to get the result of the acceptance tests, just execute `docker cp docker_fiware-cloto-acceptance_1:/opt/fiware-aiakos/test/acceptance/testreport .`

Please keep in mind that if you do not change the name of the image it will automatically create a new one for unit tests and change the previous one to tag none.

> TIP: you can launch a FIWARE Lab testbed container to execute the fiware-cloto E2E test. Just follow the indications in [FIWARE Testbed Deploy](https://hub.docker.com/r/fiware/testbed-deploy/). It will launch a virtual machine in which a reproduction of the FIWARE Lab is installed. Keep in mind that in that case Region1 have to be configured with the value qaregion.

----
## 4. Other info

Things to keep in mind while working with docker containers and fiware-cloto.

### 4.1 Data persistence
Everything you do with fiware-cloto when dockerized is non-persistent. *You will lose all your data* if you turn off the fiware-cloto container. This will happen with either method presented in this README.

### 4.2 Using `sudo`

If you do not want to have to use `sudo` follow [these instructions](http://askubuntu.com/questions/477551/how-can-i-use-docker-without-sudo).

# How to use fiware-cloto with Docker

There are several options to use fiware-cloto very easily using docker. These are (in order of complexity):

- _"Have everything automatically done for me"_. See Section **1. The Fastest Way** (recommended).
- _"Check the unit tests associated to the component"_. See Section **2. Run Unit Test of fiware-cloto**.
- _"Check the acceptance tests are running properly"_ or _"I want to check that my fiware-cloto instance run properly"_ . See Section **3. Run Acceptance tests**.

You do not need to do all of them, just use the first one if you want to have a fully operational fiware-cloto instance and maybe third one to check if your fiware-cloto instance run properly.

You do need to have docker in your machine. See the [documentation](https://docs.docker.com/installation/) on how to do this. Additionally, you can use the proper FIWARE Lab docker functionality to deploy dockers image there. See the [documentation](https://docs.docker.com/installation/)


text:
package com.foobarsite.rss.feed;

public interface IEntity {
	String getGenId();
	void setGenId(String id);
}


text:
package org.clarksnut.common.jpa;

import javax.persistence.PrePersist;
import java.util.Calendar;

public class CreatedAtListener {

    @PrePersist
    public void setCreatedAt(final CreatableEntity entity) {
        entity.setCreatedAt(Calendar.getInstance().getTime());
    }

}


text:
package org.xwalk.embedded.api.sample.client;

import org.xwalk.embedded.api.sample.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import org.xwalk.core.XWalkActivity;
import org.xwalk.core.XWalkUIClient;
import org.xwalk.core.XWalkView;

public class XWalkViewWithReceivedTitle extends XWalkActivity{

    private XWalkView mXWalkView;

    private Activity thisActivity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_xwalk_view_with_received_title);
    }

    @Override
    protected void onXWalkReady() {
        StringBuffer mess = new StringBuffer();
        mess.append("Test Purpose: \n\n")
                .append("Verifies onReceivedTitle work in XWalkView.\n\n")
                .append("Expected Result:\n\n")
                .append("Test passes if the Activity Title will be changed by submitting HTML form");
        new  AlertDialog.Builder(this)
                .setTitle("Info")
                .setMessage(mess.toString())
                .setPositiveButton("confirm", null)
                .show();
        mXWalkView = (XWalkView) findViewById(R.id.console_xwalk_view);
        mXWalkView.load("file:///android_asset/title_change.html", null);
        thisActivity = this;
        mXWalkView.setUIClient(new XWalkUIClient(mXWalkView) {
            @Override
            public void onReceivedTitle(XWalkView view, String title) {
                super.onReceivedTitle(view, title);
                if(!TextUtils.isEmpty(title)) {
                    thisActivity.setTitle(title);
                }
            }
        });
    }
}


text:
import React, { useState } from 'react';
import { Info, Home } from '@styled-icons/material-outlined';
import { defaultArgTypes as argTypes } from '@looker/storybook';
import { IconButton } from '../../Button';
import { Aside } from '../../Layout';
import { ListItem } from '../../ListItem';
import { ProgressCircular } from '../../ProgressCircular';
import { NavTree, NavTreeItem } from '../../NavTree';
import { NavList } from '../NavList';
export default {
  argTypes,
  component: NavList,
  title: 'NavList'
};
export { LeftNav } from './LeftNav';
export const Basic = () => {
  const [selected, setSelected] = useState(false);

  const handleClick = () => {
    setSelected(!selected);
  };

  return React.createElement(NavList, null, React.createElement(ListItem, {
    description: "Description",
    detail: "Interesting details",
    icon: React.createElement(Home, null),
    selected: true
  }, "Explore"), React.createElement(ListItem, {
    icon: React.createElement(Info, null),
    onClick: handleClick,
    selected: selected,
    truncate: {
      description: "It's an item"
    }
  }, "Develop"), React.createElement(ListItem, {
    icon: React.createElement(Info, null),
    truncate: {
      description: 'Word Document - Last update 3 days ago'
    }
  }, "This is a really long navigation list item that should get truncated at some point waaaayyyy out in the nether regions of a long line of text"));
};
export const MixedNavigation = () => React.createElement(Aside, {
  width: "navigation"
}, React.createElement(NavList, null, React.createElement(ListItem, {
  icon: React.createElement(Home, null),
  selected: true
}, "Home"), React.createElement(NavTree, {
  icon: React.createElement(Info, null),
  label: "NavTree",
  selected: true,
  defaultOpen: true
}, React.createElement(NavTree, {
  defaultOpen: true,
  label: "Blah",
  icon: React.createElement(Info, null)
}, React.createElement(NavTreeItem, {
  parentIcon: true,
  color: "text2"
}, React.createElement("em", null, "Not yet available")), React.createElement(NavTreeItem, {
  parentIcon: true,
  icon: React.createElement(ProgressCircular, {
    size: "xsmall",
    progress: 0.75
  })
}, "Loading..."))), React.createElement(NavTree, {
  icon: React.createElement(Info, null),
  label: "NavTree w icon-free NavTreeItems and long title",
  defaultOpen: true
}, React.createElement(NavTree, {
  label: "Folders",
  defaultOpen: true
}, React.createElement(NavTreeItem, {
  description: "description",
  detail: "detail",
  selected: true
}, "My Awesome Item"), React.createElement(NavTreeItem, null, "Truncate example with long text running off screen"), React.createElement(NavTreeItem, {
  description: "description",
  detail: "detail"
}, "Truncate example with long text running off screen")))));
export const KeyboardNavigation = () => {
  const getDetail = label => ({
    content: React.createElement(IconButton, {
      label: `${label}-button`,
      icon: React.createElement(Info, null),
      tooltipDisabled: true
    }),
    options: {
      hoverDisclosure: true
    }
  });

  return React.createElement(NavList, null, React.createElement(ListItem, {
    icon: React.createElement(Info, null),
    detail: getDetail('list-item-detail'),
    itemRole: "none"
  }, "List Item"), React.createElement(NavTree, {
    icon: React.createElement(Info, null),
    label: "Nav Tree Default",
    detail: getDetail('nav-tree-detail'),
    defaultOpen: true
  }, React.createElement(NavTreeItem, {
    parentIcon: true,
    detail: getDetail('nav-tree-item-detail'),
    itemRole: "none"
  }, "Nav Tree Item")), React.createElement(NavTree, {
    icon: React.createElement(Info, null),
    indicatorLabel: "Nav Tree Link Indicator",
    label: "Nav Tree Link",
    detail: getDetail('nav-tree-link-detail'),
    defaultOpen: true,
    href: "https://google.com",
    target: "_blank"
  }, React.createElement(NavTreeItem, {
    parentIcon: true,
    itemRole: "none"
  }, "Now You See Me")));
};
KeyboardNavigation.parameters = {
  storyshots: {
    disable: true
  }
};
//# sourceMappingURL=NavList.stories.js.map


text:
<?php
/*
Plugin Name: Contact Form 7 MailChimp
Plugin URI: http://github.com/wukerplank/contact-form-7-mailchimp
Description: Enables you to send you Contact Form 7 data to Mailchimp
Author: Christoph Edthofer
Author URI: http://wukerplank.com
Version: 0.1.0
*/

require 'lib/mailchimp.php';
require 'lib/form_handler.php';

define('WPCF7MC_PLUGIN_VERSION', '0.1.0');
define('WPCF7MC_PLUGIN_DIR', '/wp-content/plugins/' . trim(dirname(plugin_basename(__FILE__)), '/'));

define('WPCF7MC_FIELD_MAILCHIMP_API_TOKEN', 'mailchimp_api_token');
define('WPCF7MC_FIELD_MAILCHIMP_LIST_ID', 'mailchimp_list_id');
define('WPCF7MC_FIELD_EMAIL', 'email');
define('WPCF7MC_FIELD_FIRSTNAME', 'firstname');
define('WPCF7MC_FIELD_LASTNAME', 'lastname');
define('WPCF7MC_FIELD_SUBSCRIBE', 'subscribe');
define('WPCF7MC_FIELD_CUSTOM_FIELDS', 'custom_fields_active');
define('WPCF7MC_FIELD_CUSTOM_FORM_FIELD_PREFIX', 'custom_form_field_');
define('WPCF7MC_FIELD_CUSTOM_MAILCHIMP_FIELD_PREFIX', 'custom_mailchimp_field_');

require 'enqueue.php';
require 'backend_actions.php';
require 'frontend_actions.php';


text:
package com.max.tang.demokiller.main.fragment;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.max.tang.demokiller.BuildConfig;
import com.max.tang.demokiller.DataLoader;
import com.max.tang.demokiller.R;
import com.max.tang.demokiller.adapter.DemoAdapter;
import com.max.tang.demokiller.fragment.OnFragmentInteractionListener;
import com.max.tang.demokiller.itemanimator.ItemAnimatorFactory;
import com.max.tang.demokiller.model.DemoEntity;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link DemoListFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class DemoListFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    @BindView(R.id.recycler_view_main)
    RecyclerView mRecyclerView;

    @BindView(R.id.text_view_build_info) TextView mTextViewBuildInfo;

    private OnFragmentInteractionListener mListener;

    public DemoListFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment DemoListFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static DemoListFragment newInstance(String param1, String param2) {
        DemoListFragment fragment = new DemoListFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        View view = inflater.inflate(R.layout.fragment_demo_list_fragmenty, container, false);
        ButterKnife.bind(this, view);

        // load content
        List<DemoEntity> demoEntities = DataLoader.getInstance().getTestList();
        DemoAdapter demoAdapter = new DemoAdapter(mListener, demoEntities);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.setItemAnimator(ItemAnimatorFactory.slidein()); //设置Iem动画
        mRecyclerView.setAdapter(demoAdapter);

        Date buildDate = new Date(BuildConfig.TIMESTAMP);
        final String text = String.format(Locale.getDefault(), "%s(%d) Build at %s", BuildConfig.VERSION_NAME, BuildConfig.VERSION_CODE, buildDate.toString());
        mTextViewBuildInfo.setText(text);
        return view;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }
}


text:
import React, { ReactElement } from 'react';
import ReactDOM from 'react-dom';
import { MatrixClient } from 'matrix-js-sdk/src/matrix';

import { MatrixClientPeg } from '../../../../src/MatrixClientPeg';
import * as TestUtils from '../../../test-utils';
import CryptographyPanel from '../../../../src/components/views/settings/CryptographyPanel';

describe('CryptographyPanel', () => {
    it('shows the session ID and key', () => {
        const sessionId = "ABCDEFGHIJ";
        const sessionKey = "AbCDeFghIJK7L/m4nOPqRSTUVW4xyzaBCDef6gHIJkl";
        const sessionKeyFormatted = "<b>AbCD eFgh IJK7 L/m4 nOPq RSTU VW4x yzaB CDef 6gHI Jkl</b>";

        TestUtils.stubClient();
        const client: MatrixClient = MatrixClientPeg.get();
        client.deviceId = sessionId;
        client.getDeviceEd25519Key = () => sessionKey;

        // When we render the CryptographyPanel
        const rendered = render(<CryptographyPanel />);

        // Then it displays info about the user's session
        const codes = rendered.querySelectorAll("code");
        expect(codes.length).toEqual(2);
        expect(codes[0].innerHTML).toEqual(sessionId);
        expect(codes[1].innerHTML).toEqual(sessionKeyFormatted);
    });
});

function render(component: ReactElement<CryptographyPanel>): HTMLDivElement {
    const parentDiv = document.createElement('div');
    document.body.appendChild(parentDiv);
    ReactDOM.render(component, parentDiv);
    return parentDiv;
}


text:
require 'spec_helper'

describe Lazyman::Page do
	before :all do
		@app_name = 'test'
		Lazyman::Initializer.new File.dirname(__FILE__), @app_name
	end

	before(:each) do
		@browser = mock_watir_browser
	end

	def mock_watir_browser
		watir_browser = double('watir')
		watir_browser.stub!(:is_a?).with(anything()).and_return(false)
		watir_browser.stub!(:is_a?).with(Watir::Browser).and_return(true)
		watir_browser
	end

	it 'method missing' do
		@browser.stub :close
		@browser.should_receive :close
		Lazyman::Page.new(@browser).close
	end

	it 'should turn to page' do
		p = Lazyman::Page.new(@browser).turn_to TestPage
		p.is_a?(TestPage).should be_true
	end

	it 'should data driven with hash' do
		btn = double();
		hash = {:one => 'click', :two => 'ok'}

		p = TestPage.new(@browser)
		p.stub(:one).and_return(btn)
		p.stub(:two=)
		btn.should_receive(:click)
		p.should_receive(:one)
		p.should_receive(:two=).with('ok')
		p.data_driven(hash)
	end

end


text:
require File.expand_path(File.dirname(__FILE__) + "/../spec_helper")

describe Braintree::Customer do
  describe "inspect" do
    it "includes the id first" do
      output = Braintree::Customer._new(:gateway, {:first_name => 'Dan', :id => '1234'}).inspect
      output.should include("#<Braintree::Customer id: \"1234\",")
    end

    it "includes all customer attributes" do
      customer = Braintree::Customer._new(
        :gateway,
        :company => "Company",
        :email => "e@mail.com",
        :fax => "483-438-5821",
        :first_name => "Patrick",
        :last_name => "Smith",
        :phone => "802-483-5932",
        :website => "patrick.smith.com",
        :created_at => Time.now,
        :updated_at => Time.now
      )
      output = customer.inspect
      output.should include(%q(company: "Company"))
      output.should include(%q(email: "e@mail.com"))
      output.should include(%q(fax: "483-438-5821"))
      output.should include(%q(first_name: "Patrick"))
      output.should include(%q(last_name: "Smith"))
      output.should include(%q(phone: "802-483-5932"))
      output.should include(%q(website: "patrick.smith.com"))
      output.should include(%Q(created_at: #{customer.created_at.inspect}))
      output.should include(%Q(updated_at: #{customer.updated_at.inspect}))
    end
  end

  describe "self.create" do
    it "raises an exception if hash includes an invalid key" do
      expect do
        Braintree::Customer.create(:first_name => "Joe", :invalid_key => "foo")
      end.to raise_error(ArgumentError, "invalid keys: invalid_key")
    end
  end

  describe "self.find" do
    it "raises an exception if the id is blank" do
      expect do
        Braintree::Customer.find("  ")
      end.to raise_error(ArgumentError)
    end

    it "raises an exception if the id is nil" do
      expect do
        Braintree::Customer.find(nil)
      end.to raise_error(ArgumentError)
    end

    it "does not raise an exception if the id is a fixnum" do
      Braintree::Http.stub(:new).and_return stub.as_null_object
      expect do
        Braintree::Customer.find(8675309)
      end.to_not raise_error(NoMethodError)
    end
  end

  describe "self.update" do
    it "raises an exception if hash includes an invalid key" do
      expect do
        Braintree::Customer.update("customer_id", :first_name => "Joe", :invalid_key => "foo")
      end.to raise_error(ArgumentError, "invalid keys: invalid_key")
    end
  end

  describe "self.create_signature" do
    it "should be what we expect" do
      Braintree::CustomerGateway._create_signature.should == [
        :company,
        :email,
        :fax,
        :first_name,
        :id,
        :last_name,
        :phone,
        :website,
        {:credit_card => [
          :billing_address_id,
          :cardholder_name,
          :cvv,
          :expiration_date,
          :expiration_month,
          :expiration_year,
          :number,
          :token,
          {:options => [:make_default, :verification_merchant_account_id, :verify_card, :fail_on_duplicate_payment_method]},
          {:billing_address => [
            :company,
            :country_code_alpha2,
            :country_code_alpha3,
            :country_code_numeric,
            :country_name,
            :extended_address,
            :first_name,
            :last_name,
            :locality,
            :postal_code,
            :region,
            :street_address
          ]}
        ]},
        {:custom_fields => :_any_key_}
      ]
    end
  end

  describe "self.update_signature" do
    it "should be what we expect" do
      Braintree::CustomerGateway._update_signature.should == [
        :company,
        :email,
        :fax,
        :first_name,
        :id,
        :last_name,
        :phone,
        :website,
        {:credit_card => [
          :billing_address_id,
          :cardholder_name,
          :cvv,
          :expiration_date,
          :expiration_month,
          :expiration_year,
          :number,
          :token,
          {:options => [
            :make_default,
            :verification_merchant_account_id,
            :verify_card,
            :update_existing_token
          ]},
          {:billing_address => [
            :company,
            :country_code_alpha2,
            :country_code_alpha3,
            :country_code_numeric,
            :country_name,
            :extended_address,
            :first_name,
            :last_name,
            :locality,
            :postal_code,
            :region,
            :street_address,
            {:options => [:update_existing]}
          ]}
        ]},
        {:custom_fields => :_any_key_}
      ]
    end
  end

  describe "self.create_from_transparent_redirect" do
    it "raises an exception if the query string is forged" do
      expect do
        Braintree::Customer.create_from_transparent_redirect("http_status=200&forged=query_string")
      end.to raise_error(Braintree::ForgedQueryString)
    end
  end

  describe "==" do
    it "returns true when given a customer with the same id" do
      first = Braintree::Customer._new(:gateway, :id => 123)
      second = Braintree::Customer._new(:gateway, :id => 123)

      first.should == second
      second.should == first
    end

    it "returns false when given a customer with a different id" do
      first = Braintree::Customer._new(:gateway, :id => 123)
      second = Braintree::Customer._new(:gateway, :id => 124)

      first.should_not == second
      second.should_not == first
    end

    it "returns false when not given a customer" do
      customer = Braintree::Customer._new(:gateway, :id => 123)
      customer.should_not == "not a customer"
    end
  end

  describe "initialize" do
    it "converts payment method hashes into payment method objects" do
      customer = Braintree::Customer._new(
        :gateway,
        :credit_cards => [
          {:token => "pm1"},
          {:token => "pm2"}
        ]
      )
      customer.credit_cards.size.should == 2
      customer.credit_cards[0].token.should == "pm1"
      customer.credit_cards[1].token.should == "pm2"
    end
  end

  describe "new" do
    it "is protected" do
      expect do
        Braintree::Customer.new
      end.to raise_error(NoMethodError, /protected method .new/)
    end
  end
end


text:
/**
 */
package Library3;

import org.eclipse.emf.ecore.EObject;

/**
 *
 * A representation of the model object 'Book Type'.
 *
 *
 *

 * The following features are supported:
 *

 *

 *
{@link Library3.BookType#getName Name}

 *
{@link Library3.BookType#getTitle Title}

 *
{@link Library3.BookType#getAuthor Author}

 *
{@link Library3.BookType#getPages Pages}

 *
{@link Library3.BookType#getBookInfo Book Info}

 *
{@link Library3.BookType#getIsbn Isbn}

 *

 *
 * @see Library3.Library3Package#getBookType()
 * @model extendedMetaData="name='bookType' kind='elementOnly'"
 * @generated
 */
public interface BookType extends EObject {
	/**
	 * Returns the value of the 'Name' attribute.
	 *
	 *

	 * If the meaning of the 'Name' attribute isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Name' attribute.
	 * @see #setName(String)
	 * @see Library3.Library3Package#getBookType_Name()
	 * @model id="true" dataType="org.eclipse.emf.ecore.xml.type.ID" required="true"
	 *        extendedMetaData="kind='element' name='name' namespace='##targetNamespace'"
	 * @generated
	 */
	String getName();

	/**
	 * Sets the value of the '{@link Library3.BookType#getName Name}' attribute.
	 *
	 *
	 * @param value the new value of the 'Name' attribute.
	 * @see #getName()
	 * @generated
	 */
	void setName(String value);

	/**
	 * Returns the value of the 'Title' attribute.
	 *
	 *

	 * If the meaning of the 'Title' attribute isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Title' attribute.
	 * @see #setTitle(String)
	 * @see Library3.Library3Package#getBookType_Title()
	 * @model dataType="org.eclipse.emf.ecore.xml.type.String" required="true"
	 *        extendedMetaData="kind='element' name='title' namespace='##targetNamespace'"
	 * @generated
	 */
	String getTitle();

	/**
	 * Sets the value of the '{@link Library3.BookType#getTitle Title}' attribute.
	 *
	 *
	 * @param value the new value of the 'Title' attribute.
	 * @see #getTitle()
	 * @generated
	 */
	void setTitle(String value);

	/**
	 * Returns the value of the 'Author' attribute.
	 *
	 *

	 * If the meaning of the 'Author' attribute isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Author' attribute.
	 * @see #setAuthor(String)
	 * @see Library3.Library3Package#getBookType_Author()
	 * @model dataType="Library3.NameType" required="true"
	 *        extendedMetaData="kind='element' name='author' namespace='##targetNamespace'"
	 * @generated
	 */
	String getAuthor();

	/**
	 * Sets the value of the '{@link Library3.BookType#getAuthor Author}' attribute.
	 *
	 *
	 * @param value the new value of the 'Author' attribute.
	 * @see #getAuthor()
	 * @generated
	 */
	void setAuthor(String value);

	/**
	 * Returns the value of the 'Pages' attribute.
	 *
	 *

	 * If the meaning of the 'Pages' attribute isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Pages' attribute.
	 * @see #isSetPages()
	 * @see #unsetPages()
	 * @see #setPages(int)
	 * @see Library3.Library3Package#getBookType_Pages()
	 * @model unsettable="true" dataType="org.eclipse.emf.ecore.xml.type.Int" required="true"
	 *        extendedMetaData="kind='element' name='pages' namespace='##targetNamespace'"
	 * @generated
	 */
	int getPages();

	/**
	 * Sets the value of the '{@link Library3.BookType#getPages Pages}' attribute.
	 *
	 *
	 * @param value the new value of the 'Pages' attribute.
	 * @see #isSetPages()
	 * @see #unsetPages()
	 * @see #getPages()
	 * @generated
	 */
	void setPages(int value);

	/**
	 * Unsets the value of the '{@link Library3.BookType#getPages Pages}' attribute.
	 *
	 *
	 * @see #isSetPages()
	 * @see #getPages()
	 * @see #setPages(int)
	 * @generated
	 */
	void unsetPages();

	/**
	 * Returns whether the value of the '{@link Library3.BookType#getPages Pages}' attribute is set.
	 *
	 *
	 * @return whether the value of the 'Pages' attribute is set.
	 * @see #unsetPages()
	 * @see #getPages()
	 * @see #setPages(int)
	 * @generated
	 */
	boolean isSetPages();

	/**
	 * Returns the value of the 'Book Info' containment reference.
	 *
	 *

	 * If the meaning of the 'Book Info' containment reference isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Book Info' containment reference.
	 * @see #setBookInfo(BookInfoType)
	 * @see Library3.Library3Package#getBookType_BookInfo()
	 * @model containment="true"
	 *        extendedMetaData="kind='element' name='bookInfo' namespace='##targetNamespace'"
	 * @generated
	 */
	BookInfoType getBookInfo();

	/**
	 * Sets the value of the '{@link Library3.BookType#getBookInfo Book Info}' containment reference.
	 *
	 *
	 * @param value the new value of the 'Book Info' containment reference.
	 * @see #getBookInfo()
	 * @generated
	 */
	void setBookInfo(BookInfoType value);

	/**
	 * Returns the value of the 'Isbn' attribute.
	 *
	 *

	 * If the meaning of the 'Isbn' attribute isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Isbn' attribute.
	 * @see #setIsbn(String)
	 * @see Library3.Library3Package#getBookType_Isbn()
	 * @model dataType="Library3.IsbnType" required="true"
	 *        extendedMetaData="kind='attribute' name='isbn' namespace='##targetNamespace'"
	 * @generated
	 */
	String getIsbn();

	/**
	 * Sets the value of the '{@link Library3.BookType#getIsbn Isbn}' attribute.
	 *
	 *
	 * @param value the new value of the 'Isbn' attribute.
	 * @see #getIsbn()
	 * @generated
	 */
	void setIsbn(String value);

} // BookType


text:
The sample source code below will teach you how to copy range in C#. Want to copy range in your C# app? ByteScout Spreadsheet SDK is designed for it. ByteScout Spreadsheet SDK is the library (SDK) that is capable of writing, reading, modifying and calculating Excel and CSV spreadsheets. Most popular formulas can be calculated and reculculated with Excel installed. You may import or export data to and from CSV, XML, JSON as well as to and from databases, arrays.

Fast application programming interfaces of ByteScout Spreadsheet SDK for C# plus the instruction and the code below will help you quickly learn how to copy range. In your C# project or application you may simply copy & paste the code and then run your app! Test C# sample code examples whether they respond your needs and requirements for the project.

Trial version of ByteScout Spreadsheet SDK is available for free. Source code samples are included to help you with your C# app.

## REQUEST FREE TECH SUPPORT

[Click here to get in touch](https://bytescout.zendesk.com/hc/en-us/requests/new?subject=ByteScout%20Spreadsheet%20SDK%20Question)

or just send email to [support@bytescout.com](mailto:support@bytescout.com?subject=ByteScout%20Spreadsheet%20SDK%20Question)

## ON-PREMISE OFFLINE SDK

[Get Your 60 Day Free Trial](https://bytescout.com/download/web-installer?utm_source=github-readme)
[Explore SDK Docs](https://bytescout.com/documentation/index.html?utm_source=github-readme)
[Sign Up For Online Training](https://academy.bytescout.com/)

## ON-DEMAND REST WEB API

[Get your API key](https://pdf.co/documentation/api?utm_source=github-readme)
[Explore Web API Documentation](https://pdf.co/documentation/api?utm_source=github-readme)
[Explore Web API Samples](https://github.com/bytescout/ByteScout-SDK-SourceCode/tree/master/PDF.co%20Web%20API)

## VIDEO REVIEW

[https://www.youtube.com/watch?v=nm_7I0PN1TY](https://www.youtube.com/watch?v=nm_7I0PN1TY)

<!-- code block begin -->

##### ****CopyRange.VS2005.csproj:**

```
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProductVersion>8.0.50727</ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>{4DAAE7C2-2B6B-4F6D-8D65-873BE1AAFC88}</ProjectGuid>
    <OutputType>Exe</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>CopyRange</RootNamespace>
    <AssemblyName>CopyRange</AssemblyName>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="Bytescout.Spreadsheet, Version=2.2.0.360, Culture=neutral, PublicKeyToken=f7dd1bd9d40a50eb, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>..\..\..\..\..\..\XLSRW\bin\Release\Bytescout.Spreadsheet.dll</HintPath>
    </Reference>
    <Reference Include="System" />
    <Reference Include="System.Data" />
    <Reference Include="System.Xml" />
  </ItemGroup>
  <ItemGroup>
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Program.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
  </ItemGroup>
  <ItemGroup>
    <Content Include="example.xls">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
  </ItemGroup>
  <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
</Project>
```

<!-- code block end -->

<!-- code block begin -->

##### ****CopyRange.VS2008.csproj:**

```
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5">
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProductVersion>9.0.21022</ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>{4DAAE7C2-2B6B-4F6D-8D65-873BE1AAFC88}</ProjectGuid>
    <OutputType>Exe</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>CopyRange</RootNamespace>
    <AssemblyName>CopyRange</AssemblyName>
    <OldToolsVersion>2.0</OldToolsVersion>
    <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="Bytescout.Spreadsheet, Version=2.2.0.360, Culture=neutral, PublicKeyToken=f7dd1bd9d40a50eb, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>..\..\..\..\..\..\XLSRW\bin\Release\Bytescout.Spreadsheet.dll</HintPath>
    </Reference>
    <Reference Include="System" />
    <Reference Include="System.Data" />
    <Reference Include="System.Xml" />
  </ItemGroup>
  <ItemGroup>
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Program.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
  </ItemGroup>
  <ItemGroup>
    <Content Include="example.xls">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
</Project>
```

<!-- code block end -->

<!-- code block begin -->

##### ****CopyRange.VS2010.csproj:**

```
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProductVersion>
    </ProductVersion>
    <SchemaVersion>2.0</SchemaVersion>
    <ProjectGuid>{4DAAE7C2-2B6B-4F6D-8D65-873BE1AAFC88}</ProjectGuid>
    <OutputType>Exe</OutputType>
    <AppDesignerFolder>Properties</AppDesignerFolder>
    <RootNamespace>CopyRange</RootNamespace>
    <AssemblyName>CopyRange</AssemblyName>
    <OldToolsVersion>3.5</OldToolsVersion>
    <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <ItemGroup>
    <Reference Include="Bytescout.Spreadsheet, Version=2.2.0.360, Culture=neutral, PublicKeyToken=f7dd1bd9d40a50eb, processorArchitecture=MSIL">
      <SpecificVersion>False</SpecificVersion>
      <HintPath>..\..\..\..\..\..\XLSRW\bin\Release\Bytescout.Spreadsheet.dll</HintPath>
    </Reference>
    <Reference Include="System" />
    <Reference Include="System.Data" />
    <Reference Include="System.Xml" />
  </ItemGroup>
  <ItemGroup>
  </ItemGroup>
  <ItemGroup>
    <Compile Include="Program.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
  </ItemGroup>
  <ItemGroup>
    <Content Include="example.xls">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
  </ItemGroup>
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
       Other similar extension points exist, see Microsoft.Common.targets.
  <Target Name="BeforeBuild">
  </Target>
  <Target Name="AfterBuild">
  </Target>
  -->
</Project>
```

<!-- code block end -->

<!-- code block begin -->

##### ****Program.cs:**

```
using System.Diagnostics;
using System.IO;
using Bytescout.Spreadsheet;

namespace CopyRange
{
    class Program
    {
        static void Main(string[] args)
        {
            // Open spreadsheet from file
            Spreadsheet document = new Spreadsheet();
            document.LoadFromFile("example.xls");

            // Get first worksheet
            Worksheet worksheet = document.Workbook.Worksheets[0];

            // Select cell range
            Range range = worksheet.Range("A2:B8");

            // Copy range to C10 cell
            range.CopyInto("C10");

            // Delete output file if exists
            if (File.Exists("changed.xls"))
            {
                File.Delete("changed.xls");
            }

            // Save document
            document.SaveAs("changed.xls");

            // Close spreadsheet
            document.Close();

            // Open generated XLS document in default program
            Process.Start("changed.xls");
        }
    }
}

```

<!-- code block end -->


text:
module Ebay # :nodoc:
  module Types # :nodoc:
    # == Attributes
    #  numeric_node :group_id, 'GroupID', :optional => true
    #  numeric_node :id, 'ID', :optional => true
    #  text_node :image_url, 'ImageURL', :optional => true
    #  text_node :name, 'Name', :optional => true
    #  text_node :template_xml, 'TemplateXML', :optional => true
    #  text_node :type, 'Type', :optional => true
def type
  @type
end

    class DescriptionTemplate
      include XML::Mapping
      include Initializer
      root_element_name 'DescriptionTemplate'
      numeric_node :group_id, 'GroupID', :optional => true
      numeric_node :id, 'ID', :optional => true
      text_node :image_url, 'ImageURL', :optional => true
      text_node :name, 'Name', :optional => true
      text_node :template_xml, 'TemplateXML', :optional => true
      text_node :type, 'Type', :optional => true
def type
  @type
end

    end
  end
end


text:
var addons = {};

//add React add-ons to the package.json
addons.iassign = require("immutable-assign");

module.exports = addons;


text:
<?php
namespace Models;

class Authorization extends Models {
	public function getUserId($credentials) {
		if (is_array($credentials)) {
			$query = "SELECT `id` FROM `users` WHERE `login`=? AND `password`=PASSWORD(?)";
			$vars = [$credentials['login'], $credentials['password']];
		}
		else {
			$query = "SELECT `user_id` FROM `users_tokens` WHERE `expiration_date` >= NOW() AND `token`=? AND `secret`=SHA(?)";
			$vars = [$credentials, $this->getSecret()];
		}

		$user_id = $this->Database->getValue($query, $vars);
		if ($user_id) { $this->checkVisit($user_id); }

		return $user_id;
	}

	private function checkVisit($user_id) {
		$query = "UPDATE `users` SET `prelast_visit_date`=`last_visit_date`, `last_visit_date`=NOW() WHERE `id`=?";
		$this->Database->executeQuery($query, [$user_id]);
	}

	public function getNewToken() {
		$token = uniqid("token_", true);

		return $token;
	}

	public function setNewToken($user_id) {
		$this->loadModels(["Settings"]);
		$settings = $this->Settings->getSettings("user");
		$token = $this->getNewToken();
		$secret = $this->getSecret();

		// Remove existed token from DB
		$query = "DELETE FROM `users_tokens` WHERE `user_id`=? AND `secret`=SHA(?)";
		$this->Database->executeQuery($query, [$user_id, $secret]);

		$this->normalizeTokenQuantity($user_id, $settings->token_max_qty);

		$query = "
			INSERT INTO `users_tokens` (
				`user_id`,
				`token`,
				`expiration_date`,
				`secret`
			)
			VALUES (
				?,
				?,
				DATE_ADD(NOW(), INTERVAL ? SECOND),
				SHA(?)
			)
		";
		$vars = [
			['type'=>"i", 'value'=>$user_id],
			['type'=>"s", 'value'=>$token],
			['type'=>"i", 'value'=>$settings->token_life],
			['type'=>"s", 'value'=>$secret]
		];
		$result = $this->Database->executeQuery($query, $vars);

		if ($result) {
			setcookie("token", $token, time()+$settings->token_life);
		}

		return $result;
	}

	private function normalizeTokenQuantity($user_id, $qty_limit) {
		$query = "DELETE FROM `users_tokens` WHERE `expiration_date` < NOW() AND `user_id`=?";
		$this->Database->executeQuery($query, [$user_id]);

		$query = "SELECT COUNT(`id`) AS 'qty' FROM `users_tokens` WHERE `user_id`=? AND `expiration_date`>=NOW()";
		$qty = $this->Database->getValue($query, [$user_id]);

		if ($qty >= $qty_limit) {
			$qty_excess = $qty-($qty_limit-1);

			$query = "DELETE FROM `users_tokens` WHERE `user_id`=? ORDER BY `expiration_date` ASC LIMIT $qty_excess";
			$this->Database->executeQuery($query, [$user_id]);
		}
	}

	public function removeToken() {
		setcookie("token", "", time()-1000000000000);
	}

	private function getSecret() {
		return $_SERVER['HTTP_USER_AGENT'] . $_SERVER['HTTP_ACCEPT_LANGUAGE'] . $_SERVER['HTTP_ACCEPT_ENCODING'];
	}
}


text:
package org.apache.kylin.invertedindex.invertedindex;

import com.google.common.collect.Lists;

import org.apache.kylin.common.util.BytesUtil;
import org.apache.kylin.common.util.LocalFileMetadataTestCase;
import org.apache.kylin.dict.Dictionary;
import org.apache.kylin.invertedindex.IIInstance;
import org.apache.kylin.invertedindex.IIManager;
import org.apache.kylin.invertedindex.index.*;
import org.apache.kylin.invertedindex.model.IIKeyValueCodec;
import org.apache.commons.io.IOUtils;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.util.Pair;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;

import static org.junit.Assert.assertEquals;

public class InvertedIndexLocalTest extends LocalFileMetadataTestCase {

	IIInstance ii;
	TableRecordInfo info;

	@Before
	public void setUp() throws Exception {
		this.createTestMetadata();
		this.ii = IIManager.getInstance(getTestConfig()).getII("test_kylin_ii");
		this.info = new TableRecordInfo(ii.getFirstSegment());
	}

	@After
	public void after() throws Exception {
		this.cleanupTestMetadata();
	}

	@Test
	public void testBitMapContainer() {
		// create container
		BitMapContainer container = new BitMapContainer(info.getDigest(), 0);
		Dictionary<String> dict = info.dict(0);
		for (int v = dict.getMinId(); v <= dict.getMaxId(); v++) {
			container.append(v);
		}
		container.append(Dictionary.NULL_ID[dict.getSizeOfId()]);
		container.closeForChange();

		// copy by serialization
		List<ImmutableBytesWritable> bytes = container.toBytes();
		BitMapContainer container2 = new BitMapContainer(info.getDigest(), 0);
		container2.fromBytes(bytes);

		// check the copy
		int i = 0;
		for (int v = dict.getMinId(); v <= dict.getMaxId(); v++) {
			int value = container2.getValueIntAt(i++);
			assertEquals(v, value);
		}
		assertEquals(Dictionary.NULL_ID[dict.getSizeOfId()],
				container2.getValueIntAt(i++));
		assertEquals(container, container2);
	}

	@Test
	public void testCompressedValueContainer() {
		// create container
		CompressedValueContainer container = new CompressedValueContainer(
				info.getDigest(), 0, 500);
		Dictionary<String> dict = info.dict(0);

		byte[] buf = new byte[dict.getSizeOfId()];
		ImmutableBytesWritable bytes = new ImmutableBytesWritable(buf);

		for (int v = dict.getMinId(); v <= dict.getMaxId(); v++) {
			BytesUtil.writeUnsigned(v, buf, 0, dict.getSizeOfId());
			container.append(bytes);
		}
		BytesUtil.writeUnsigned(Dictionary.NULL_ID[dict.getSizeOfId()], buf, 0,
				dict.getSizeOfId());
		container.append(bytes);
		container.closeForChange();

		// copy by serialization
		ImmutableBytesWritable copy = container.toBytes();
		CompressedValueContainer container2 = new CompressedValueContainer(
				info.getDigest(), 0, 500);
		container2.fromBytes(copy);

		// check the copy
		int i = 0;
		for (int v = dict.getMinId(); v <= dict.getMaxId(); v++) {
			container2.getValueAt(i++, bytes);
			int value = BytesUtil.readUnsigned(bytes.get(), bytes.getOffset(),
					bytes.getLength());
			assertEquals(v, value);
		}
		container2.getValueAt(i++, bytes);
		int value = BytesUtil.readUnsigned(bytes.get(), bytes.getOffset(),
				bytes.getLength());
		assertEquals(Dictionary.NULL_ID[dict.getSizeOfId()], value);
		assertEquals(container, container2);
	}

	@Test
	public void testCodec() throws IOException {
		List<TableRecord> records = loadRecordsSorted();
		System.out.println(records.size() + " records");
		List<Slice> slices = buildTimeSlices(records);
		System.out.println(slices.size() + " slices");

		IIKeyValueCodec codec = new IIKeyValueCodec(info.getDigest());
		List<Pair<ImmutableBytesWritable, ImmutableBytesWritable>> kvs = encodeKVs(
				codec, slices);
		System.out.println(kvs.size() + " KV pairs");

		List<Slice> slicesCopy = decodeKVs(codec, kvs);
		assertEquals(slices, slicesCopy);

		List<TableRecord> recordsCopy = iterateRecords(slicesCopy);
		assertEquals(new HashSet<TableRecord>(records),
				new HashSet<TableRecord>(recordsCopy));
		dump(recordsCopy);
	}

	private List<TableRecord> loadRecordsSorted() throws IOException {
		File file = new File(LOCALMETA_TEST_DATA,
				"data/flatten_data_for_ii.csv");
		FileInputStream in = new FileInputStream(file);
		List<String> lines = IOUtils.readLines(in, "UTF-8");
		in.close();

		List<TableRecord> records = Lists.newArrayList();
		for (String line : lines) {
			String[] fields = line.split(",");
			TableRecord rec = info.createTableRecord();
			for (int col = 0; col < fields.length; col++) {
				rec.setValueString(col, fields[col]);
			}
			records.add(rec);
		}

		Collections.sort(records, new Comparator<TableRecord>() {
			@Override
			public int compare(TableRecord a, TableRecord b) {
				long x = a.getTimestamp() - b.getTimestamp();
				if (x > 0)
					return 1;
				else if (x == 0)
					return 0;
				else
					return -1;
			}
		});

		return records;
	}

	private List<Slice> buildTimeSlices(List<TableRecord> records)
			throws IOException {
		ShardingSliceBuilder builder = new ShardingSliceBuilder(info);
		List<Slice> slices = Lists.newArrayList();
		for (TableRecord rec : records) {
			Slice slice = builder.append(rec);
			if (slice != null)
				slices.add(slice);
		}
		List<Slice> finals = builder.close();
		slices.addAll(finals);

		Collections.sort(slices);
		return slices;
	}

	private List<Pair<ImmutableBytesWritable, ImmutableBytesWritable>> encodeKVs(
			IIKeyValueCodec codec, List<Slice> slices) {

		List<Pair<ImmutableBytesWritable, ImmutableBytesWritable>> kvs = Lists
				.newArrayList();
		for (Slice slice : slices) {
			kvs.addAll(codec.encodeKeyValue(slice));
		}
		return kvs;
	}

	private List<Slice> decodeKVs(IIKeyValueCodec codec,
			List<Pair<ImmutableBytesWritable, ImmutableBytesWritable>> kvs) {
		List<Slice> slices = Lists.newArrayList();
		for (Slice slice : codec.decodeKeyValue(kvs)) {
			slices.add(slice);
		}
		return slices;
	}

	private List<TableRecord> iterateRecords(List<Slice> slices) {
		List<TableRecord> records = Lists.newArrayList();
		for (Slice slice : slices) {
			for (RawTableRecord rec : slice) {
				records.add(new TableRecord((RawTableRecord) rec.clone(), info));
			}
		}
		return records;
	}

	private void dump(Iterable<TableRecord> records) {
		for (TableRecord rec : records) {
			System.out.println(rec.toString());
		}
	}

}


text:
package com.yundroid.kokpit.commands;

public enum EnemyColor {
	ORANGE_GREEN(0x10),
	YELLOW_BLUE(0x11);

	private int value;

	private EnemyColor(int value){
		this.value = value;
	}

	public int getValue(){
		return value;
	}
}