text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Windows.Forms;

using Autodesk.Revit.DB;

namespace Revit.SDK.Samples.CurtainWallGrid.CS
{
   /// <summary>
   /// Maintain the matrixes needed by 3D & 2D operations: pan, zoom, 2D->3D, 3D->2D
   /// </summary>
   public class GridCoordinates
   {
      #region Fields
      // scale the size of the image to let it shown in the canvas
      private float m_scaleFactor = 0.85f;

      // the document of this sample
      private MyDocument m_myDocument;

      // stores the current GridDrawing data
      private GridDrawing m_drawing;

      // stores the client rectangle of the canvas of the curtain grid
      // will be used in the scale matrix and move-to-center matrix
      private System.Drawing.Rectangle m_boundary;

      // stores the midpoint of the client rectangle
      // will be used in the scale matrix and move-to-center matrix
      private System.Drawing.Point m_center;

      // store the Matrix used to transform 3D points to 2D
      Matrix4 m_to2DMatrix = null;

      // store the Matrix used to move points to center
      Matrix4 m_moveToCenterMatrix = null;

      // store the Matrix used to scale profile fit to pictureBox
      Matrix4 m_scaleMatrix = null;

      // store the Matrix used to transform Revit coordinate to window UI
      Matrix4 m_transformMatrix = null;

      // store the Matrix used to transform window UI coordinate to Revit
      Matrix4 m_restoreMatrix = null;

      // stores the boundary of the curtain grid
      List<PointF> m_boundPoints;

      #endregion

      #region Properties
      /// <summary>
      /// stores the GridDrawing data used in the current dialog
      /// </summary>
      public GridDrawing Drawing
      {
         get
         {
            return m_drawing;
         }
         set
         {
            m_drawing = value;
         }
      }

      /// <summary>
      /// store the Matrix used to transform 3D points to 2D
      /// </summary>
      public Matrix4 To2DMatrix
      {
         get
         {
            return m_to2DMatrix;
         }
      }

      /// <summary>
      /// store the Matrix used to transform Revit coordinate to window UI
      /// </summary>
      public Matrix4 TransformMatrix
      {
         get
         {
            return m_transformMatrix;
         }
      }

      /// <summary>
      /// store the Matrix used to transform window UI coordinate to Revit
      /// </summary>
      public Matrix4 RestoreMatrix
      {
         get
         {
            return m_restoreMatrix;
         }
      }
      #endregion

      #region Constructors
      /// <summary>
      /// constructor
      /// </summary>
      /// <param name="myDoc">
      /// the document of this sample
      /// </param>
      /// <param name="drawing">
      /// the GridDrawing data used in the dialog
      /// </param>
      public GridCoordinates(MyDocument myDoc, GridDrawing drawing)
      {
         m_myDocument = myDoc;

         if (null == drawing)
         {
            MessageBox.Show("Error! There's no grid information in the curtain wall.");
         }
         m_drawing = drawing;
         drawing.Coordinates = this;
      }
      #endregion

      #region Public Methods
      /// <summary>
      /// obtain the matrixes used in this dialog
      /// </summary>
      public void GetMatrix()
      {
         // initialize the class members, obtain the location information of the canvas
         m_boundary = m_drawing.Boundary;
         m_center = m_drawing.Center;

         // Get a matrix which can transform points to 2D
         m_to2DMatrix = GetTo2DMatrix();

         // get the vertexes of the canvas (in Point/PointF format)
         m_boundPoints = GetBoundsPoints();

         // get a matrix which can keep all the points in the center of the canvas
         m_moveToCenterMatrix = GetMoveToCenterMatrix();

         // get a matrix for scaling all the points and lines within the canvas
         m_scaleMatrix = GetScaleMatrix();

         // transform 3D points to 2D
         m_transformMatrix = Get3DTo2DMatrix();

         // transform from 2D to 3D
         m_restoreMatrix = Get2DTo3DMatrix();
      }
      #endregion

      #region Private Methods
      /// <summary>
      /// calculate the matrix used to transform 2D to 3D
      /// </summary>
      /// <returns>
      /// matrix used to transform 2d points to 3d
      /// </returns>
      private Matrix4 Get2DTo3DMatrix()
      {
         Matrix4 matrix = Matrix4.Multiply(
             new Matrix4(new Vector4(-m_center.X, -m_center.Y, 0)), m_scaleMatrix.Inverse());
         matrix = Matrix4.Multiply(
             matrix, m_moveToCenterMatrix);
         return Matrix4.Multiply(matrix, m_to2DMatrix);
      }

      /// <summary>
      /// calculate the matrix used to transform 3D to 2D
      /// </summary>
      /// <returns>
      /// matrix used to transform 3d points to 2d
      /// </returns>
      private Matrix4 Get3DTo2DMatrix()
      {
         Matrix4 result = Matrix4.Multiply(
            m_to2DMatrix.Inverse(), m_moveToCenterMatrix.Inverse());
         result = Matrix4.Multiply(result, m_scaleMatrix);
         return Matrix4.Multiply(result, new Matrix4(new Vector4(m_center.X, m_center.Y, 0)));
      }

      /// <summary>
      /// calculate the matrix used to scale
      /// </summary>
      /// <returns>
      /// matrix used to scale the to-be-painted image
      /// </returns>
      private Matrix4 GetScaleMatrix()
      {
         float xScale = m_boundary.Width / (m_boundPoints[1].X - m_boundPoints[0].X);
         float yScale = m_boundary.Height / (m_boundPoints[1].Y - m_boundPoints[0].Y);
         float factor = xScale <= yScale ? xScale : yScale;
         return new Matrix4((float)(factor * m_scaleFactor));
      }

      /// <summary>
      /// Get a matrix which can move points to center
      /// </summary>
      /// <returns>
      /// matrix used to move point to center of canvas
      /// </returns>
      private Matrix4 GetMoveToCenterMatrix()
      {
         //translate the origin to bound center
         PointF min = m_boundPoints[0];
         PointF max = m_boundPoints[1];
         PointF center = new PointF((min.X + max.X) / 2, (min.Y + max.Y) / 2);
         return new Matrix4(new Vector4(center.X, center.Y, 0));
      }

      /// <summary>
      /// Get max and min coordinates of all points
      /// </summary>
      /// <returns>
      /// points array stores the bounding box of all points
      /// </returns>
      private List<PointF> GetBoundsPoints()
      {
         Matrix4 matrix = m_to2DMatrix;
         Matrix4 inverseMatrix = matrix.Inverse();
         float minX = 0, maxX = 0, minY = 0, maxY = 0;
         bool bFirstPoint = true;
         List<PointF> resultPoints = new List<PointF>();

         //get the max and min point on the face
         foreach (Autodesk.Revit.DB.XYZ point in m_drawing.Geometry.GridVertexesXYZ)
         {
            Vector4 v = new Vector4(point);
            Vector4 v1 = inverseMatrix.Transform(v);

            if (bFirstPoint)
            {
               minX = maxX = v1.X;
               minY = maxY = v1.Y;
               bFirstPoint = false;
            }
            else
            {
               if (v1.X < minX) { minX = v1.X; }
               else if (v1.X > maxX) { maxX = v1.X; }

               if (v1.Y < minY) { minY = v1.Y; }
               else if (v1.Y > maxY) { maxY = v1.Y; }
            }
         }
         resultPoints.Add(new PointF(minX, minY));
         resultPoints.Add(new PointF(maxX, maxY));
         return resultPoints;
      }

      /// <summary>
      /// Get a matrix which can transform points to 2D
      /// </summary>
      /// <returns>
      /// matrix which can transform points to 2D
      /// </returns>
      private Matrix4 GetTo2DMatrix()
      {
         Autodesk.Revit.DB.XYZ startXYZ = m_myDocument.WallGeometry.StartXYZ;
         Autodesk.Revit.DB.XYZ endXYZ = m_myDocument.WallGeometry.EndXYZ;
         XYZ sub = endXYZ - startXYZ;
         Vector4 xAxis = new Vector4(new Autodesk.Revit.DB.XYZ(sub.X, sub.Y, sub.Z));
         xAxis.Normalize();
         //because in the windows UI, Y axis is downward
         Vector4 yAxis = new Vector4(new Autodesk.Revit.DB.XYZ(0, 0, -1));
         yAxis.Normalize();
         Vector4 zAxis = Vector4.CrossProduct(xAxis, yAxis);
         zAxis.Normalize();
         Vector4 origin = new Vector4(m_drawing.Geometry.GridVertexesXYZ[0]);

         return new Matrix4(xAxis, yAxis, zAxis, origin);
      }
      #endregion
   } // end of class
}


text:
package com.eusecom.attendance;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.eusecom.attendance.models.Employee;
import com.eusecom.attendance.rxbus.RxBus;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.flowables.ConnectableFlowable;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;

//by https://chelseatroy.com/2015/09/27/android-examples-a-test-driven-recyclerview/

@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class)
public class EmployeesRxAdapterRoboelectricTest {

    private RxBus _rxBus;
    private CompositeDisposable _disposables;

    private EmployeesRxAdapter mAdapter;
    private EmployeesRxViewHolder holder;

    private View mockView;

    @Before
    public void setUp() throws Exception {

        MockitoAnnotations.initMocks(this);

        _rxBus = getRxBusSingleton();
        _disposables = new CompositeDisposable();

        ConnectableFlowable<Object> tapEventEmitter = _rxBus.asFlowable().publish();
        //rewrite _disposables from retrolambda to classic annotation bebause of testcompiler has problem with lambda expression

        _disposables
                .add(tapEventEmitter.subscribe(event -> {

                    if (event instanceof EmployeeMvvmActivity.FobTapEvent) {
                        System.out.println("rxBus longClickOnItemOfAdapter");
                    }
                    if (event instanceof Employee) {
                        String keys = ((Employee) event).getUsatw();
                        //Log.d("In FRGM longClick", keys);

                        Employee model= (Employee) event;

                        System.out.println("username " + model.username);
                        assertThat(model.username).isEqualTo("andrejd");

                    }

                }));

        _disposables.add(tapEventEmitter.connect());

        mAdapter = new EmployeesRxAdapter(Collections.<Employee>emptyList(), _rxBus);

        mockView = mock(View.class);

    }

    public RxBus getRxBusSingleton() {
        if (_rxBus == null) {
            _rxBus = new RxBus();
        }

        return _rxBus;
    }

    @After
    public void tearDown() {
        _disposables.dispose();
    }

    @Test
    public void adapter_itemCount() {
        List<Employee> mockEmployees =  Arrays
                .asList(new Employee("andrejd", "1"),
                        new Employee("petere", "2"),
                        new Employee("pavols", "3"));

        mAdapter.setData(mockEmployees);

        assertThat(mAdapter.getItemCount()).isEqualTo(3);
    }

    @Test
    public void adapter_getItemAtPosition() {
        List<Employee> mockEmployees =  Arrays
                .asList(new Employee("andrejd", "1"),
                        new Employee("petere", "2"),
                        new Employee("pavols", "3"));

        mAdapter.setData(mockEmployees);
        assertThat(mAdapter.getItemAtPosition(0)).isEqualTo(mockEmployees.get(0));
        assertThat(mAdapter.getItemAtPosition(1)).isEqualTo(mockEmployees.get(1));
    }

    @Test
    public void onBindViewHolder_setsTextAndClickEventForEmployeeView() {

        List<Employee> mockEmployees =  Arrays
                .asList(new Employee("andrejd", "1"),
                        new Employee("petere", "2"),
                        new Employee("pavols", "3"));

        mAdapter.setData(mockEmployees);
        //adapter.setContext(mockFragment);
        LayoutInflater inflater = (LayoutInflater) RuntimeEnvironment.application.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        //We have a layout especially for the items in our recycler view. We will see it in a moment.
        View listItemView = inflater.inflate(R.layout.employee_item, null, false);
        holder = new EmployeesRxViewHolder(listItemView);
        //click on item 0
        mAdapter.onBindViewHolder(holder, 0);
        assertThat(holder.employee_name.getText().toString()).isEqualTo("andrejd");

        //send to rxbus
        holder.itemView.performLongClick();

    }

}

redpajama_set_name: RedPajamaGithub


text:
//Distributed under the Boost Software License, Version 1.0. (See accompanying
//file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#ifndef UUID_0552D49838DD11DD90146B8956D89593
#define UUID_0552D49838DD11DD90146B8956D89593
#if defined(__GNUC__) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS)
#pragma GCC system_header
#endif
#if defined(_MSC_VER) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS)
#pragma warning(push,1)
#endif

#include <boost/config.hpp>
#include <boost/exception/get_error_info.hpp>
#include <boost/utility/enable_if.hpp>
#ifndef BOOST_NO_RTTI
#include <boost/units/detail/utility.hpp>
#endif
#include <exception>
#include <sstream>
#include <string>

#ifndef BOOST_NO_EXCEPTIONS
#include <boost/exception/current_exception_cast.hpp>
namespace
boost
    {
    namespace
    exception_detail
        {
        std::string diagnostic_information_impl( boost::exception const *, std::exception const *, bool );
        }

    inline
    std::string
    current_exception_diagnostic_information()
        {
        boost::exception const * be=current_exception_cast<boost::exception const>();
        std::exception const * se=current_exception_cast<std::exception const>();
        if( be || se )
            return exception_detail::diagnostic_information_impl(be,se,true);
        else
            return "No diagnostic information available.";
        }
    }
#endif

namespace
boost
    {
    namespace
    exception_detail
        {
        inline
        exception const *
        get_boost_exception( exception const * e )
            {
            return e;
            }

        inline
        exception const *
        get_boost_exception( ... )
            {
            return 0;
            }

        inline
        std::exception const *
        get_std_exception( std::exception const * e )
            {
            return e;
            }

        inline
        std::exception const *
        get_std_exception( ... )
            {
            return 0;
            }

        inline
        char const *
        get_diagnostic_information( exception const & x, char const * header )
            {
            if( error_info_container * c=x.data_.get() )
#ifndef BOOST_NO_EXCEPTIONS
                try
                    {
#endif
                    return c->diagnostic_information(header);
#ifndef BOOST_NO_EXCEPTIONS
                    }
                catch(...)
                    {
                    }
#endif
            return 0;
            }

        inline
        std::string
        diagnostic_information_impl( boost::exception const * be, std::exception const * se, bool with_what )
            {
            if( !be && !se )
                return "Unknown exception.";
#ifndef BOOST_NO_RTTI
            if( !be )
                be=dynamic_cast<boost::exception const *>(se);
            if( !se )
                se=dynamic_cast<std::exception const *>(be);
#endif
            char const * wh=0;
            if( with_what && se )
                {
                wh=se->what();
                if( be && exception_detail::get_diagnostic_information(*be,0)==wh )
                    return wh;
                }
            std::ostringstream tmp;
            if( be )
                {
                if( char const * const * f=get_error_info<throw_file>(*be) )
                    {
                    tmp << *f;
                    if( int const * l=get_error_info<throw_line>(*be) )
                        tmp << '(' << *l << "): ";
                    }
                tmp << "Throw in function ";
                if( char const * const * fn=get_error_info<throw_function>(*be) )
                    tmp << *fn;
                else
                    tmp << "(unknown)";
                tmp << '\n';
                }
#ifndef BOOST_NO_RTTI
            tmp << std::string("Dynamic exception type: ") <<
                units::detail::demangle((be?BOOST_EXCEPTION_DYNAMIC_TYPEID(*be):BOOST_EXCEPTION_DYNAMIC_TYPEID(*se)).type_.name()) << '\n';
#endif
            if( with_what && se )
                tmp << "std::exception::what: " << wh << '\n';
            if( be )
                if( char const * s=exception_detail::get_diagnostic_information(*be,tmp.str().c_str()) )
                    if( *s )
                        return s;
            return tmp.str();
            }
        }

    template <class T>
    std::string
    diagnostic_information( T const & e )
        {
        return exception_detail::diagnostic_information_impl(exception_detail::get_boost_exception(&e),exception_detail::get_std_exception(&e),true);
        }

    inline
    char const *
    diagnostic_information_what( exception const & e ) throw()
        {
        char const * w=0;
#ifndef BOOST_NO_EXCEPTIONS
        try
            {
#endif
            (void) exception_detail::diagnostic_information_impl(&e,0,false);
            return exception_detail::get_diagnostic_information(e,0);
#ifndef BOOST_NO_EXCEPTIONS
            }
        catch(
        ... )
            {
            }
#endif
        return w;
        }
    }

#if defined(_MSC_VER) && !defined(BOOST_EXCEPTION_ENABLE_WARNINGS)
#pragma warning(pop)
#endif
#endif


text:
package sumus.mobile.sopt_7.OthersFiiles;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import retrofit.Call;
import retrofit.Callback;
import retrofit.Response;
import retrofit.Retrofit;
import sumus.mobile.sopt_7.Models.Content;
import sumus.mobile.sopt_7.Models.Thumbnail;
import sumus.mobile.sopt_7.R;
import sumus.mobile.sopt_7.component.ApplicationController;
import sumus.mobile.sopt_7.network.NetworkService;

public class ThumbnailListActivity extends AppCompatActivity {

    private NetworkService networkService;
    private EditText editTitle;
    private EditText editContent;
    private Button btnSend;
    private ListView listViewThumbnails;
    private ThumbnailAdapter adapter;

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

        initNetworkService();
        initView();
        initAdapter();
        sendData();
        itemClick();
    }

    private void itemClick() {
        // TODO: 10. ListView의 아이템 클릭 시 이벤트
        listViewThumbnails.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Thumbnail thumbnail = (Thumbnail) adapter.getItem(position);
                Intent intent = new Intent(getApplicationContext(), DetailActivity.class);
                intent.putExtra("article_id", thumbnail.id);
                startActivity(intent);
            }
        });
        listViewThumbnails.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                Thumbnail thumbnail = (Thumbnail) adapter.getItem(position);
                //Toast.makeText(getApplicationContext(), "thumbnail.id : " + thumbnail.id, Toast.LENGTH_SHORT).show();

                long delete_id = thumbnail.id;
                /*
                Call<Content> contentCall = networkService.getDelete(delete_id);

                contentCall.enqueue(new Callback<Content>() {
                    @Override
                    public void onResponse(Response<Content> response, Retrofit retrofit) {
                        if (response.isSuccess()) {
                            reset();
                            Toast.makeText(getApplicationContext(), "삭제완료", Toast.LENGTH_SHORT).show();
                            Log.i("SOPT", "isSuccess: ");
                        } else {
                            int statusCode = response.code();
                            Log.i("SOPT", "false: ");
                        }
                    }

                    @Override
                    public void onFailure(Throwable t) {
                        Toast.makeText(getApplicationContext(), "Failed to load", Toast.LENGTH_LONG).show();
                        Log.i("SOPT", "에러내용: " + t.getMessage());
                        finish();
                    }
                });
                */
               // adapter.delete(position); // 리스트뷰에서 삭제
                return true;
            }
        });
    }

    private void sendData() {
        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Content content = new Content();
              content.user_id = editTitle.getText().toString();
                content.user_pw = editContent.getText().toString();
                // TODO: 9. NetworkService를 이용하여 POST 방식의 요청 구현

                Call<Content> thumbnailCall = networkService.newContent(content);
                thumbnailCall.enqueue(new Callback<Content>() {
                    @Override
                    public void onResponse(Response<Content> response, Retrofit retrofit) {
                        if (response.isSuccess()) {
                            Content thumbnail_temp = response.body();
                            //adapter.append(thumbnail_temp);
                            editTitle.setText("");
                            editContent.setText("");
                            Log.i("SOPT", "썸네일 제목 : " +thumbnail_temp.user_id);
                        } else {
                            int statusCode = response.code();
                            Log.i("SOPT", "응답코드 : " + statusCode);
                        }
                    }

                    @Override
                    public void onFailure(Throwable t) {
                        Log.i("SOPT", "에러내용  : " + t.getMessage());
                    }
                });

            }
        });
    }

    private void initAdapter() {
        adapter = new ThumbnailAdapter();
        listViewThumbnails.setAdapter(adapter);
    }

    private void initView() {
        editTitle = (EditText) findViewById(R.id.editTitle);
        editContent = (EditText) findViewById(R.id.editContent);
        btnSend = (Button) findViewById(R.id.btnSend);
        listViewThumbnails = (ListView) findViewById(R.id.list_thumbnails);
    }

    private void initNetworkService() {
        // TODO: 8. ApplicationConoller 객체를 이용하여 NetworkService 가져오기
        networkService = ApplicationController.getInstance().getNetworkService();

    }

    @Override
    protected void onResume() {
        super.onResume();
        /*
        // TODO: 11. 서버에서 Thumbnail을 리스트로 받아오기 위한 GET 방식의 요청 구현
        Call<List<Thumbnail>> thumbnailsCall = networkService.getThumbnail();
        thumbnailsCall.enqueue(new Callback<List<Thumbnail>>() {
            @Override
            public          void onResponse(Response<List<Thumbnail>> response, Retrofit retrofit) {
                if (response.isSuccess()) {
                    List<Thumbnail> thumbnails = response.body();
                    adapter.setSource(thumbnails);
                } else {
                    int statusCode = response.code();
                    Log.i("SOPT", "응답코드: " + statusCode);
                }
            }

            @Override
            public           void onFailure(Throwable t) {
                Toast.makeText(getApplicationContext(), "Failed to load thumbnails", Toast.LENGTH_LONG).show();
                Log.i("SOPT", "에러내용: " + t.getMessage());
            }
        });*/
    }

//    public void reset()
//    {
//        Call<List<Thumbnail>> thumbnailsCall = networkService.getThumbnail();
//        thumbnailsCall.enqueue(new Callback<List<Thumbnail>>() {
//            @Override
//            public          void onResponse(Response<List<Thumbnail>> response, Retrofit retrofit) {
//                if (response.isSuccess()) {
//                    List<Thumbnail> thumbnails = response.body();
//                    adapter.setSource(thumbnails);
//                } else {
//                    int statusCode = response.code();
//                    Log.i("SOPT", "응답코드: " + statusCode);
//                }
//            }
//
//            @Override
//            public           void onFailure(Throwable t) {
//                Toast.makeText(getApplicationContext(), "Failed to load thumbnails", Toast.LENGTH_LONG).show();
//                Log.i("SOPT", "에러내용: " + t.getMessage());
//            }
//        });
//    }
}


text:
#pragma once

#include "Config.h"

#include <functional>

template <typename T, typename R, class... Types>
std::function<R(Types...)> qtnMemFn(T *t, R (T::*memFn)(Types...) const)
{
	return [t, memFn](Types... args) {
		return std::mem_fn(memFn)(t, std::forward<Types>(args)...);
	};
}

template <typename T, typename R, class... Types>
std::function<R(Types...)> qtnMemFn(T *t, R (T::*memFn)(Types...))
{
	return [t, memFn](Types... args) {
		return std::mem_fn(memFn)(t, std::forward<Types>(args)...);
	};
}


text:
<?php

namespace Zend\Server;

use ReflectionClass;

/**
 * Abstract Server implementation
 */
abstract class AbstractServer implements Server
{
    /**
     * @var bool Flag; whether or not overwriting existing methods is allowed
     */
    protected $overwriteExistingMethods = false;

    /**
     * @var Definition
     */
    protected $table;

    /**
     * Constructor
     *
     * Setup server description
     *
     */
    public function __construct()
    {
        $this->table = new Definition();
        $this->table->setOverwriteExistingMethods($this->overwriteExistingMethods);
    }

    /**
     * Returns a list of registered methods
     *
     * Returns an array of method definitions.
     *
     * @return Definition
     */
    public function getFunctions()
    {
        return $this->table;
    }

    /**
     * Build callback for method signature
     *
     * @param  Reflection\AbstractFunction $reflection
     * @return Method\Callback
     */
    protected function _buildCallback(Reflection\AbstractFunction $reflection)
    {
        $callback = new Method\Callback();
        if ($reflection instanceof Reflection\ReflectionMethod) {
            $callback->setType($reflection->isStatic() ? 'static' : 'instance')
                     ->setClass($reflection->getDeclaringClass()->getName())
                     ->setMethod($reflection->getName());
        } elseif ($reflection instanceof Reflection\ReflectionFunction) {
            $callback->setType('function')
                     ->setFunction($reflection->getName());
        }
        return $callback;
    }

    /**
     * Build a method signature
     *
     * @param  Reflection\AbstractFunction $reflection
     * @param  null|string|object $class
     * @return Method\Definition
     * @throws Exception\RuntimeException on duplicate entry
     */
    protected function _buildSignature(Reflection\AbstractFunction $reflection, $class = null)
    {
        $ns         = $reflection->getNamespace();
        $name       = $reflection->getName();
        $method     = empty($ns) ? $name : $ns . '.' . $name;

        if (!$this->overwriteExistingMethods && $this->table->hasMethod($method)) {
            throw new Exception\RuntimeException('Duplicate method registered: ' . $method);
        }

        $definition = new Method\Definition();
        $definition->setName($method)
                   ->setCallback($this->_buildCallback($reflection))
                   ->setMethodHelp($reflection->getDescription())
                   ->setInvokeArguments($reflection->getInvokeArguments());

        foreach ($reflection->getPrototypes() as $proto) {
            $prototype = new Method\Prototype();
            $prototype->setReturnType($this->_fixType($proto->getReturnType()));
            foreach ($proto->getParameters() as $parameter) {
                $param = new Method\Parameter(array(
                    'type'     => $this->_fixType($parameter->getType()),
                    'name'     => $parameter->getName(),
                    'optional' => $parameter->isOptional(),
                ));
                if ($parameter->isDefaultValueAvailable()) {
                    $param->setDefaultValue($parameter->getDefaultValue());
                }
                $prototype->addParameter($param);
            }
            $definition->addPrototype($prototype);
        }
        if (is_object($class)) {
            $definition->setObject($class);
        }
        $this->table->addMethod($definition);
        return $definition;
    }

    /**
     * Dispatch method
     *
     * @param  Method\Definition $invokable
     * @param  array $params
     * @return mixed
     */
    protected function _dispatch(Method\Definition $invokable, array $params)
    {
        $callback = $invokable->getCallback();
        $type     = $callback->getType();

        if ('function' == $type) {
            $function = $callback->getFunction();
            return call_user_func_array($function, $params);
        }

        $class  = $callback->getClass();
        $method = $callback->getMethod();

        if ('static' == $type) {
            return call_user_func_array(array($class, $method), $params);
        }

        $object = $invokable->getObject();
        if (!is_object($object)) {
            $invokeArgs = $invokable->getInvokeArguments();
            if (!empty($invokeArgs)) {
                $reflection = new ReflectionClass($class);
                $object     = $reflection->newInstanceArgs($invokeArgs);
            } else {
                $object = new $class;
            }
        }
        return call_user_func_array(array($object, $method), $params);
    }

    /**
     * Map PHP type to protocol type
     *
     * @param  string $type
     * @return string
     */
    abstract protected function _fixType($type);
}


text:
<?php

namespace GDS\Gateway;
use GDS\Entity;
use GDS\Exception\Contention;
use GDS\Mapper\ProtoBufGQLParser;
use google\appengine\datastore\v4\BeginTransactionRequest;
use google\appengine\datastore\v4\BeginTransactionResponse;
use google\appengine\datastore\v4\CommitRequest;
use google\appengine\datastore\v4\CommitRequest\Mode;
use google\appengine\datastore\v4\CommitResponse;
use google\appengine\datastore\v4\Key;
use google\appengine\datastore\v4\LookupRequest;
use google\appengine\datastore\v4\LookupResponse;
use google\appengine\datastore\v4\PropertyFilter;
use google\appengine\datastore\v4\QueryResultBatch;
use google\appengine\datastore\v4\RunQueryRequest;
use google\appengine\datastore\v4\RunQueryResponse;
use google\appengine\datastore\v4\Value;
use google\appengine\runtime\ApiProxy;
use google\appengine\runtime\ApplicationError;
use google\net\ProtocolMessage;

/**
 * Protocol Buffer v4 Datastore Gateway
 *
 * @author Tom Walder <tom@docnet.nu>
 * @package GDS\Gateway
 */
class ProtoBuf extends \GDS\Gateway
{

    /**
     * Batch size for un-limited queries
     */
    const BATCH_SIZE = 1000;

    /**
     * Set up the dataset and optional namespace
     *
     * @todo Review use of $_SERVER.
     * Google propose a 'better' way of auto detecting app id,
     * but it's not perfect (does not work) in the dev environment
     * \google\appengine\api\app_identity\AppIdentityService::getApplicationId();
     *
     * @param null|string $str_dataset
     * @param null|string $str_namespace
     * @throws \Exception
     */
    public function __construct($str_dataset = null, $str_namespace = null)
    {
        if(null === $str_dataset) {
            if(isset($_SERVER['APPLICATION_ID'])) {
                $this->str_dataset_id = $_SERVER['APPLICATION_ID'];
            } else {
                throw new \Exception('Could not determine DATASET, please pass to ' . get_class($this) . '::__construct()');
            }
        } else {
            $this->str_dataset_id = $str_dataset;
        }
        $this->str_namespace = $str_namespace;
    }

    /**
     * Put an array of Entities into the Datastore. Return any that need AutoIDs
     *
     * @todo Validate support for per-entity Schemas
     *
     * @param \GDS\Entity[] $arr_entities
     * @return \GDS\Entity[]
     */
    public function upsert(array $arr_entities)
    {
        $obj_request = $this->setupCommit();
        $obj_mutation = $obj_request->mutableDeprecatedMutation();
        $arr_auto_id_required = [];
        foreach($arr_entities as $obj_gds_entity) {
            if(null === $obj_gds_entity->getKeyId() && null === $obj_gds_entity->getKeyName()) {
                $obj_entity = $obj_mutation->addInsertAutoId();
                $arr_auto_id_required[] = $obj_gds_entity; // maintain reference to the array of requested auto-ids
            } else {
                $obj_entity = $obj_mutation->addUpsert();
            }
            $this->applyNamespace($obj_entity->mutableKey());
            $this->determineMapper($obj_gds_entity)->mapToGoogle($obj_gds_entity, $obj_entity);
        }
        $this->execute('Commit', $obj_request, new CommitResponse());
        return $arr_auto_id_required;
    }

    /**
     * Extract Auto Insert IDs from the last response
     *
     * @return array
     */
    protected function extractAutoIDs()
    {
        $arr_ids = [];
        foreach($this->obj_last_response->getDeprecatedMutationResult()->getInsertAutoIdKeyList() as $obj_key) {
            $arr_key_path = $obj_key->getPathElementList();
            $obj_path_end = end($arr_key_path);
            $arr_ids[] = $obj_path_end->getId();
        }
        return $arr_ids;
    }

    /**
     * Apply dataset and namespace ("partition") to an object
     *
     * Usually a Key or RunQueryRequest
     *
     * @param object $obj_target
     * @return mixed
     */
    private function applyNamespace($obj_target)
    {
        $obj_partition = $obj_target->mutablePartitionId();
        $obj_partition->setDatasetId($this->str_dataset_id);
        if(null !== $this->str_namespace) {
            $obj_partition->setNamespace($this->str_namespace);
        }
        return $obj_target;
    }

    /**
     * Apply a transaction to an object
     *
     * @param $obj
     * @return mixed
     */
    private function applyTransaction($obj)
    {
        if(null !== $this->str_next_transaction) {
            $obj->setTransaction($this->str_next_transaction);
            $this->str_next_transaction = null;
        }
        return $obj;
    }

    /**
     * Set up a RunQueryRequest
     *
     * @todo setReadConsistency
     * @todo Be more intelligent about when we set the suggested batch size (e.g. on LIMITed queries)
     *
     * @return RunQueryRequest
     */
    private function setupRunQuery()
    {
        $obj_request = ($this->applyNamespace(new RunQueryRequest()));
        $obj_request->setSuggestedBatchSize(self::BATCH_SIZE); // Avoid having to run multiple batches
        $this->applyTransaction($obj_request->mutableReadOptions()); // ->setReadConsistency('some-val');
        return $obj_request;
    }

    /**
     * Set up a LookupRequest
     *
     * @todo setReadConsistency
     *
     * @return LookupRequest
     */
    private function setupLookup()
    {
        $obj_request = new LookupRequest();
        $this->applyTransaction($obj_request->mutableReadOptions()); // ->setReadConsistency('some-val');
        return $obj_request;
    }

    /**
     * Set up a commit request
     *
     * @return CommitRequest
     */
    private function setupCommit()
    {
        $obj_commit_request = new CommitRequest();
        if(null === $this->str_next_transaction) {
            $obj_commit_request->setMode(Mode::NON_TRANSACTIONAL);
        } else {
            $obj_commit_request->setMode(Mode::TRANSACTIONAL);
            $this->applyTransaction($obj_commit_request);
        }
        return $obj_commit_request;
    }

    /**
     * Execute a method against the Datastore
     *
     * Use Google's static ApiProxy method
     *
     * Will attempt to convert GQL queries in local development environments
     *
     * @param $str_method
     * @param ProtocolMessage $obj_request
     * @param ProtocolMessage $obj_response
     * @return mixed
     * @throws ApplicationError
     * @throws \google\appengine\runtime\CapabilityDisabledError
     * @throws \google\appengine\runtime\FeatureNotEnabledError
     * @throws Contention
     */
    private function execute($str_method, ProtocolMessage $obj_request, ProtocolMessage $obj_response)
    {
        try {
            ApiProxy::makeSyncCall('datastore_v4', $str_method, $obj_request, $obj_response, 60);
            $this->obj_last_response = $obj_response;
        } catch (ApplicationError $obj_exception) {
            $this->obj_last_response = NULL;
            if($obj_request instanceof RunQueryRequest && 'GQL not supported.' === $obj_exception->getMessage()) {
                $this->executeGqlAsBasicQuery($obj_request); // recursive
            } elseif (FALSE !== strpos($obj_exception->getMessage(), 'too much contention') || FALSE !== strpos($obj_exception->getMessage(), 'Concurrency')) {
                // LIVE: "too much contention on these datastore entities. please try again." LOCAL : "Concurrency exception."
                throw new Contention('Datastore contention', 409, $obj_exception);
            } else {
                throw $obj_exception;
            }
        }
        return $this->obj_last_response;
    }

    /**
     * Fetch 1-many Entities, using the Key parts provided
     *
     * @param array $arr_key_parts
     * @param $str_setter
     * @return \GDS\Entity[]|null
     */
    protected function fetchByKeyPart(array $arr_key_parts, $str_setter)
    {
        $obj_request = $this->setupLookup();
        foreach($arr_key_parts as $mix_key_part) {
            $obj_key = $obj_request->addKey();
            $this->applyNamespace($obj_key);
            $obj_kpe = $obj_key->addPathElement();
            $obj_kpe->setKind($this->obj_schema->getKind());
            $obj_kpe->$str_setter($mix_key_part);
        }
        $this->execute('Lookup', $obj_request, new LookupResponse());
        $arr_mapped_results = $this->createMapper()->mapFromResults($this->obj_last_response->getFoundList());
        $this->obj_schema = null; // Consume Schema
        return $arr_mapped_results;
    }

    /**
     * Delete 1 or many entities, using their Keys
     *
     * Consumes Schema
     *
     * @todo Determine success. Not 100% how to do this from the response yet.
     *
     * @param array $arr_entities
     * @return bool
     */
    public function deleteMulti(array $arr_entities)
    {
        $obj_mapper = $this->createMapper();
        $obj_request = $this->setupCommit();
        $obj_mutation = $obj_request->mutableDeprecatedMutation();
        foreach($arr_entities as $obj_gds_entity) {
            $this->applyNamespace(
                $obj_mapper->configureGoogleKey(
                    $obj_mutation->addDelete(), $obj_gds_entity
                )
            );
        }
        $this->execute('Commit', $obj_request, new CommitResponse());
        $this->obj_schema = null;
        return TRUE; // really?
    }

    /**
     * Fetch some Entities, based on the supplied GQL and, optionally, parameters
     *
     * In local dev environments, we may convert the GQL query later.
     *
     * @todo Consider automatically handling multiple response batches?
     *
     * @param string $str_gql
     * @param array|null $arr_params
     * @return \GDS\Entity[]|null
     * @throws \Exception
     */
    public function gql($str_gql, $arr_params = null)
    {
        $obj_query_request = $this->setupRunQuery();
        $obj_gql_query = $obj_query_request->mutableGqlQuery();
        $obj_gql_query->setQueryString($str_gql);
        $obj_gql_query->setAllowLiteral(TRUE);
        if(null !== $arr_params) {
            $this->addParamsToQuery($obj_gql_query, $arr_params);
        }
        $obj_gql_response = $this->execute('RunQuery', $obj_query_request, new RunQueryResponse());
        $arr_mapped_results = $this->createMapper()->mapFromResults($obj_gql_response->getBatch()->getEntityResultList());
        $this->obj_schema = null; // Consume Schema
        return $arr_mapped_results;
    }

    /**
     * Take a GQL RunQuery request and convert to a standard RunQuery request
     *
     * Always expected to be called in the stack ->gql()->execute()->runGqlAsBasicQuery()
     *
     * @param ProtocolMessage $obj_gql_request
     * @return null
     * @throws \GDS\Exception\GQL
     */
    private function executeGqlAsBasicQuery(ProtocolMessage $obj_gql_request)
    {
        // Set up the new request
        $obj_query_request = $this->setupRunQuery();
        $obj_query = $obj_query_request->mutableQuery();

        // Transfer any transaction data to the new request
        /** @var RunQueryRequest $obj_gql_request */
        if($obj_gql_request->mutableReadOptions()->hasTransaction()) {
            $obj_query_request->mutableReadOptions()->setTransaction($obj_gql_request->mutableReadOptions()->getTransaction());
        }

        // Parse the GQL string
        $obj_gql_query = $obj_gql_request->getGqlQuery();
        $obj_parser = new ProtoBufGQLParser();
        $obj_parser->parse($obj_gql_query->getQueryString(), $obj_gql_query->getNameArgList());

        // Start applying to the new RunQuery request
        $obj_query->addKind()->setName($obj_parser->getKind());
        foreach($obj_parser->getOrderBy() as $arr_order_by) {
            $obj_query->addOrder()->setDirection($arr_order_by['direction'])->mutableProperty()->setName($arr_order_by['property']);
        }

        // Limits, Offsets, Cursors
        $obj_parser->getLimit() && $obj_query->setLimit($obj_parser->getLimit());
        $obj_parser->getOffset() && $obj_query->setOffset($obj_parser->getOffset());
        $obj_parser->getStartCursor() && $obj_query->setStartCursor($obj_parser->getStartCursor());
        // @todo @ $obj_query->setEndCursor();

        // Filters
        $int_filters = count($obj_parser->getFilters());
        if(1 === $int_filters) {
            $this->configureFilterFromGql($obj_query->mutableFilter()->mutablePropertyFilter(), $obj_parser->getFilters()[0]);
        } else if (1 < $int_filters) {
            $obj_composite_filter = $obj_query->mutableFilter()->mutableCompositeFilter()->setOperator(\google\appengine\datastore\v4\CompositeFilter\Operator::AND_);
            foreach ($obj_parser->getFilters() as $arr_filter) {
                $this->configureFilterFromGql($obj_composite_filter->addFilter()->mutablePropertyFilter(), $arr_filter);
            }
        }
        return $this->execute('RunQuery', $obj_query_request, new RunQueryResponse());
    }

    /**
     * @param PropertyFilter $obj_filter
     * @param $arr_filter
     */
    private function configureFilterFromGql(PropertyFilter $obj_filter, $arr_filter)
    {
        $obj_filter->mutableProperty()->setName($arr_filter['lhs']);
        $mix_value = $arr_filter['rhs'];
        if($mix_value instanceof Value) {
            $obj_filter->mutableValue()->mergeFrom($mix_value);
        } else {
            $obj_filter->mutableValue()->setStringValue($mix_value); // @todo Improve type detection using Schema
        }
        $obj_filter->setOperator($arr_filter['op']);
    }

    /**
     * Add Parameters to a GQL Query object
     *
     * @param \google\appengine\datastore\v4\GqlQuery $obj_query
     * @param array $arr_params
     */
    private function addParamsToQuery(\google\appengine\datastore\v4\GqlQuery $obj_query, array $arr_params)
    {
        if(count($arr_params) > 0) {
            foreach ($arr_params as $str_name => $mix_value) {
                $obj_arg = $obj_query->addNameArg();
                $obj_arg->setName($str_name);
                if ('startCursor' == $str_name) {
                    $obj_arg->setCursor($mix_value);
                } else {
                    $this->configureValueParamForQuery($obj_arg->mutableValue(), $mix_value);
                }
            }
        }
    }

    /**
     * Configure a Value parameter, based on the supplied object-type value
     *
     * @todo Re-use one Mapper instance
     *
     * @param \google\appengine\datastore\v4\Value $obj_val
     * @param object $mix_value
     */
    protected function configureObjectValueParamForQuery($obj_val, $mix_value)
    {
        if($mix_value instanceof Entity) {
            $obj_key_value = $obj_val->mutableKeyValue();
            $this->createMapper()->configureGoogleKey($obj_key_value, $mix_value);
            $this->applyNamespace($obj_key_value);
        } elseif ($mix_value instanceof \DateTime) {
            $obj_val->setTimestampMicrosecondsValue($mix_value->format('Uu'));
        } elseif (method_exists($mix_value, '__toString')) {
            $obj_val->setStringValue($mix_value->__toString());
        } else {
            throw new \InvalidArgumentException('Unexpected, non-string-able object parameter: ' . get_class($mix_value));
        }
    }

    /**
     * Get the end cursor from the last response
     */
    public function getEndCursor()
    {
        return $this->obj_last_response->getBatch()->getEndCursor();
    }

    /**
     * Create a mapper that's right for this Gateway
     *
     * @return \GDS\Mapper\ProtoBuf
     */
    protected function createMapper()
    {
        return (new \GDS\Mapper\ProtoBuf())->setSchema($this->obj_schema);
    }

    /**
     * Begin a transaction
     *
     * @todo Evaluate cross-request transactions [setCrossRequest]
     *
     * @param bool $bol_cross_group
     * @return string|null
     */
    public function beginTransaction($bol_cross_group = FALSE)
    {
        $obj_request = new BeginTransactionRequest();
        if($bol_cross_group) {
            $obj_request->setCrossGroup(TRUE);
        }
        $obj_response = $this->execute('BeginTransaction', $obj_request, new BeginTransactionResponse());
        return isset($obj_response->transaction) ? $obj_response->transaction : null;
    }
}


text:
namespace g{namespace Fuse{namespace Navigation{struct DefaultNavigationAnimatorPlayer;}}}
namespace g{namespace Fuse{namespace Navigation{struct ProgressTimer;}}}

namespace g{
namespace Fuse{
namespace Navigation{

// internal sealed class DefaultNavigationAnimatorPlayer :90
// {
struct DefaultNavigationAnimatorPlayer_type : uType
{
    ::g::Fuse::Navigation::INavigationAnimatorPlayer interface0;
};

DefaultNavigationAnimatorPlayer_type* DefaultNavigationAnimatorPlayer_typeof();
void DefaultNavigationAnimatorPlayer__ctor__fn(DefaultNavigationAnimatorPlayer* __this, ::g::Fuse::Navigation::ProgressTimer* progressTimer, uObject* animators, uDelegate* progressSetCallback, uDelegate* doneCallback);
void DefaultNavigationAnimatorPlayer__EnsureAtEnd_fn(DefaultNavigationAnimatorPlayer* __this);
void DefaultNavigationAnimatorPlayer__New1_fn(::g::Fuse::Navigation::ProgressTimer* progressTimer, uObject* animators, uDelegate* progressSetCallback, uDelegate* doneCallback, DefaultNavigationAnimatorPlayer** __retval);
void DefaultNavigationAnimatorPlayer__Update_fn(DefaultNavigationAnimatorPlayer* __this);

struct DefaultNavigationAnimatorPlayer : uObject
{
    uStrong<uObject*> _animators;
    uStrong<uDelegate*> _doneCallback;
    uStrong<uDelegate*> _progressSetCallback;
    uStrong< ::g::Fuse::Navigation::ProgressTimer*> _progressTimer;

    void ctor_(::g::Fuse::Navigation::ProgressTimer* progressTimer, uObject* animators, uDelegate* progressSetCallback, uDelegate* doneCallback);
    void EnsureAtEnd();
    void Update();
    static DefaultNavigationAnimatorPlayer* New1(::g::Fuse::Navigation::ProgressTimer* progressTimer, uObject* animators, uDelegate* progressSetCallback, uDelegate* doneCallback);
};
// }

}}} // ::g::Fuse::Navigation


text:
module MiniCore.Parse
  ( parseCore
  ) where

import MiniCore.Types

import Text.ParserCombinators.Parsec hiding ((<|>), many)
import Text.ParserCombinators.Parsec.Expr
import Text.ParserCombinators.Parsec.Language
import qualified Text.ParserCombinators.Parsec.Token as Token
import Control.Monad.Except
import Control.Applicative
import Data.List

-- Language definition for lexer
languageDef = emptyDef
  { Token.commentStart    = "{-"
  , Token.commentEnd      = "-}"
  , Token.commentLine     = "--"
  , Token.identStart      = lower <|> char '_'
  , Token.identLetter     = alphaNum <|> char '_' <|> char '\''
  , Token.reservedNames   =
    [ "data"
    , "let"
    , "letrec"
    , "case"
    , "in"
    , "of"
    , "Pack"
    ]
  , Token.reservedOpNames =
    [ "|"
    , "\\"
    , "="
    , "->"
    ] ++ map fst precByOp
  }

-- Generate lexer and bind names that we'll use
lexer      = Token.makeTokenParser languageDef
identifier = Token.identifier lexer
reserved   = Token.reserved   lexer
reservedOp = Token.reservedOp lexer
parens     = Token.parens     lexer
braces     = Token.braces     lexer
angles     = Token.angles     lexer
natural    = Token.natural    lexer
semi       = Token.semi       lexer
comma      = Token.comma      lexer
symbol     = Token.symbol     lexer
whiteSpace = Token.whiteSpace lexer

-- Data specifications and constructors must start with an uppercase letter
uppercased :: Parser Name
uppercased = do
  whiteSpace
  first <- upper
  rest <- many (alphaNum <|> char '_' <|> char '\'')
  whiteSpace
  return (first:rest)

-- Parser entry point
parseCore :: String -> Stage Program
parseCore s = case parse pCore "core" s of
  Left e  -> parseError (show e)
  Right r -> return r

-- Program -> Declaration*
pCore :: Parser Program
pCore = do
  whiteSpace
  declarations <- pDeclaration `sepEndBy1` semi
  eof
  return declarations

-- Declaration -> Data | Combinator
pDeclaration :: Parser Declaration
pDeclaration = pData <|> pCombinator <?> "data type or supercombinator"

-- Data -> data name TyVar* = Constructor [| Constructor]*;
pData :: Parser Declaration
pData = do
  reserved "data"
  name <- uppercased
  vars <- many identifier
  reservedOp "="
  constructors <- pConstructor `sepBy1` reservedOp "|"
  return (Data name vars constructors)

-- Constructor -> name Type*
pConstructor :: Parser Constructor
pConstructor = Constructor <$> uppercased <*> many pType

-- Type -> TyCon | TyVar | (TyApp)
pType :: Parser Type
pType =
  (flip TCon [] <$> uppercased) <|> (TVar <$> identifier) <|> parens pTypeApp
    <?> "type variable or type constructor"

-- TypeApp -> TyCon Type*
pTypeApp :: Parser Type
pTypeApp = TCon <$> uppercased <*> many pType

-- Combinator -> var [ args]* = Expr;
pCombinator :: Parser Declaration
pCombinator = do
  name <- identifier
  args <- many identifier
  reservedOp "="
  expr <- pExpr
  return (Combinator name args expr)

-- Atom -> Let | BinOp | Case | Lambda
pExpr :: Parser Expr
pExpr = pLet <|> pBinOp <|> pCase <|> pLambda <?> "expression"

-- Let -> (let | letrec) Bindings in Expr
pLet :: Parser Expr
pLet = Let
  <$> (False <$ reserved "let" <|> True <$ reserved "letrec")
  <*> braces (pBinding `sepEndBy1` semi)
  <*> (reserved "in" *> pExpr)

-- Binding -> var = Expr
pBinding :: Parser (Name, Expr)
pBinding = (,)
  <$> identifier
  <*> (reservedOp "=" *> pExpr)

-- Case -> case Expr of { Alt;+ }
pCase :: Parser Expr
pCase = Case
  <$> (reserved "case" *> pExpr)
  <*> (reserved "of" *> braces (pAlt `sepEndBy1` semi))

-- Alt -> Constructor -> Expr
--pAlt = do (name, components) <- pConstructor
pAlt :: Parser Alt
pAlt = (,,)
  <$> (PCon <$> uppercased)
  <*> many identifier
  <*> (reservedOp "->" *> pExpr)

-- Lambda -> \var+ -> Expr
pLambda :: Parser Expr
pLambda = Lambda
  <$> (reservedOp "\\" *> many1 identifier)
  <*> (reservedOp "->" *> pExpr)

-- Precedence/associativity for binary operators
pBinOp :: Parser Expr
pBinOp = buildExpressionParser binOpTable pApp
 where
  parseOp op = reservedOp op >> return (BinOp op)
  binOpTable =
    [ [ Infix (parseOp ".")  AssocRight ]
    , [ Infix (parseOp "*")  AssocLeft
      , Infix (parseOp "/")  AssocLeft
      ]
    , [ Infix (parseOp "+")  AssocLeft
      , Infix (parseOp "-")  AssocLeft
      ]
    , [ Infix (parseOp "<")  AssocNone
      , Infix (parseOp ">")  AssocNone
      , Infix (parseOp "<=") AssocNone
      , Infix (parseOp ">=") AssocNone
      , Infix (parseOp "==") AssocNone
      , Infix (parseOp "/=") AssocNone
      ]
    , [ Infix (parseOp "&&") AssocLeft ]
    , [ Infix (parseOp "||") AssocLeft ]
    , [ Infix (parseOp "$")  AssocRight ]
    ]

-- Application -> Atom [Atom]*
pApp :: Parser Expr
pApp = makeSpine <$> many1 pAtom
 where
  makeSpine (x:xs) = foldl' App x xs

-- Atom -> Constructor | var | num | ( Expr )
pAtom :: Parser Expr
pAtom =
  (Var <$> uppercased) <|> (Var <$> identifier) <|> (Num . fromInteger <$> natural) <|> parens pExpr
    <?> "constructor, identifier, number, or parenthesized expression"


text:
package org.wso2.developerstudio.eclipse.gmf.esb.presentation.condition.manager;

import java.util.List;
import java.util.Map;

public abstract class EnableCondition {

    private String targetComponentName;

    public abstract List<String> getComponentsList();

    public String getTargetComponentName() {

        return targetComponentName;
    }

    public void setTargetComponent(String targetComponent) {

        this.targetComponentName = targetComponent;
    }

    public abstract boolean isValid(Map<String, String> componentsValueMap);
}


text:
.theme-grey .navbar {
  background-color: #9E9E9E; }

.theme-grey .navbar-brand {
  color: #fff; }
  .theme-grey .navbar-brand:hover {
    color: #fff; }
  .theme-grey .navbar-brand:active {
    color: #fff; }
  .theme-grey .navbar-brand:focus {
    color: #fff; }

.theme-grey .nav > li > a {
  color: #fff; }
  .theme-grey .nav > li > a:hover {
    background-color: transparent; }
  .theme-grey .nav > li > a:focus {
    background-color: transparent; }

.theme-grey .nav .open > a {
  background-color: transparent; }
  .theme-grey .nav .open > a:hover {
    background-color: transparent; }
  .theme-grey .nav .open > a:focus {
    background-color: transparent; }

.theme-grey .bars {
  color: #fff; }

.theme-grey .sidebar .menu .list li.active {
  background-color: transparent; }
  .theme-grey .sidebar .menu .list li.active > :first-child i, .theme-grey .sidebar .menu .list li.active > :first-child span {
    color: #9E9E9E; }

.theme-grey .sidebar .menu .list .toggled {
  background-color: transparent; }

.theme-grey .sidebar .menu .list .ml-menu {
  background-color: transparent; }

.theme-grey .sidebar .legal {
  background-color: #fff; }
  .theme-grey .sidebar .legal .copyright a {
    color: #9E9E9E !important; }


text:
package org.spongepowered.api.event.entity.player.fishing;

import org.spongepowered.api.event.entity.living.human.fishing.HumanRetractFishingLineEvent;

/**
 * Called when a {@link org.spongepowered.api.entity.player.Player} retracts
 * a fishing line.
 */
public interface PlayerRetractFishingLineEvent extends HumanRetractFishingLineEvent, PlayerFishEvent {

}


text:
%% An explained example on how to simulate a li-ion battery constant-current discharge using _Spectral li-ion SPM_
%
% <mailto:adrien.bizeray@eng.ox.ac.uk Adrien Bizeray>,
% <mailto:jorn.reniers@eng.ox.ac.uk Jorn Reniers>,
% <mailto:stephen.duncan@eng.ox.ac.uk Stephen Duncan>
% and
% <mailto:david.howey@eng.ox.ac.uk David Howey>,
% Department of Engineering Science, University of Oxford,
% Parks Road, Oxford OX1 3PJ
%
% This file explains how the single particle model is built and implemented
% in _Spectral li-ion SPM_ and describes step-by-step how to run a 1C
% constant-current discharge simulation.
% This script is formatted using MATLAB(R) <matlab:doc('publish') publish>
% markups and an easy to read HTML version can be generated by hitting the
% <matlab:doc('publish') publish> command (this may take a few
% minutes the first time as pictures will be automatically generated).
%
% _Spectral li-ion SPM_ solves the so-called lithium-ion battery Single
% Particle Model (SPM).
% The SPM is an electrochemical model describing lithium transport,
% reaction kinetics and thermodynamics in lithium-ion batteries.
% This SPM implementation is also coupled to a bulk thermal model
% describing battery temperature.
% The SPM is an approximation to the electrochemical pseudo-two dimensional
% lithium-ion battery model where electrolyte transport limitations are
% neglected.
% The SPM is therefore only valid at low currents up to 1C or 2C depending
% on battery design.
% In _Spectral li-ion SPM_ the diffusion partial-differential equations of
% the SPM are discretised in space using an efficient spectral numerical
% method called Chebyshev orthogonal collocation.
% This implementation of the SPM is similar to our implementation of the
% more complex pseudo-two dimensional battery model which is discussed in
% our paper:
%
% * Bizeray, A.M. , Zhao, S., Duncan, S. R., and Howey, D. A., "Lithium-ion
% battery thermal-electrochemical model-based state estimation using
% orthogonal collocation and a modified extended Kalman filter", Journal
% of Power Sources, vol. 296, pp. 400-412, 2015.
% <http://www.sciencedirect.com/science/article/pii/S0378775315300677
% Publisher copy> and <http://arxiv.org/abs/1506.08689 Open access
% pre-print>
%
% If you use _Spectral li-ion SPM_ in your work, please cite our paper.
% This code has been developed at the Department of Engineering Science of
% the University of Oxford.
% For information about our lithium-ion battery research,
% visit the <http://users.ox.ac.uk/~engs1053/ Howey Research Group>
% website.
% If you are interested in our energy research, check out our research
% group website <http://epg.eng.ox.ac.uk/ Energy and Power Group>.
%
% For more information and comments, please contact
% <mailto:david.howey@eng.ox.ac.uk 'david.howey@eng.ox.ac.uk'>.
%
%
% Copyright (c) 2016, The Chancellor, Masters and Scholars of the University
% of Oxford, and the 'Spectral li-ion SPM' Developers.
% See the licence file <../LICENSE.txt LICENSE.txt> for more information.

%% Electrochemical Single Particle Model (SPM)
% The SPM is a simplification of the more complex pseudo-two dimensional
% lithium-ion battery model where the porous active material of each
% electrode - anode and cathode - is represented by a single spherical
% particle of active material.
% The radii of these particles are chosen to approximate the
% porosity of the electrodes' material.
% During battery discharge, lithium stored in the anode particle diffuses
% to the surface of the particle where it is de-intercalated and transfered
% in the electrolyte. Simultaneously, lithium ions from the electrolyte
% intercalate at the surface of the cathode particle and diffuse through
% the cathode particle.
% This process is reversed during battery charging.
% The SPM assumes that the transport of lithium in the electrolyte is fast
% compared to the solid-phase transport in the particle of active material.
% The electrolyte diffusion and migration are therefore unmodelled in the
% SPM, limiting its validity to low C-rates.
% We give a brief overview of the model in this document with the aim of
% explaining our numerical implementation using Chebyshev orthogonal
% collocation but we refer the reader to the literature for more details on
% the SPM and its derivation, e.g.:
%
% * Guo M, Sikha G, White RE
% "Single-Particle Model for a Lithium-Ion Cell:
% Thermal Behavior",
% Journal of The Electrochemical Society, 158 (2) A122-A132 (2011)
% * Chaturvedi N, Klein R, Christensen J, Ahmed J, Kojic A,
% "Algorithms for Advanced Battery-Management Systems"
% IEEE Control Systems Magazine, 30 (3) 49-68 (2010)
%
%
% The transport of lithium in each electrode particle is governed by the
% following Fickian spherical diffusion equation:
%
% $$\frac{\partial c\left(r,t\right)}{\partial t} =
% \frac{1}{r^2} \frac{\partial}{\partial r}
% \left( D_{s,i}(T) r^2 \frac{\partial c\left(r,t\right)}{\partial r}\right)$$
%
% where $t$ is the time, $r$ is the radial coordinate, $c$ the lithium
% concentration in $mol.m^{-3}$, $D_{s,i}(T)$ the temperature-dependent
% diffusion coefficient of lithium in the active material in $m^2.s^{-1}$
% and $R_{s,i}$ the radius of the particle in electrode $i$.
% This diffusion equation is subject to the following Neumann boundary
% conditions at the centre and surface of each particle:
%
% $$\left.\frac{\partial c\left(r,t\right)}{\partial r} \right|_{r=0} = 0$$
% and
% $$D_{s,i}(T) \left.\frac{\partial c\left(r,t\right)}{\partial r}
% \right|_{r=R_{s,i}} = -j_i\left(t\right)$$
%
% The reaction rate $j_i$ in $mol.m^{-2}.s^{-1}$ is the flux of lithium
% exchanged at the surface between the particle and the electrolyte.
% In the SPM this flux can directly be related to the battery input current
% $I$ in $A$ by conservation of charge. This is because the flux  $j_i$ is
% inherently assumed uniform along the electrode thickness since only one
% particle is considered for each electrode. The relationships between $j_i$
% and $I$ in each electrode are given by:
%
% $$j_{-} = \frac{+I}{a_{s,-}\mathcal{F}\mathcal{A}\delta_{-}}$$
% and
% $$j_{+} = \frac{-I}{a_{s,+}\mathcal{F}\mathcal{A}\delta_{+}}$$
%
% where $a_{s,i} = 3\epsilon_{s,i} /R_{s,i}$ is the specific interfacial
% area in $m^{-1}$, $\mathcal{F}$ is the  Faraday constant, $\mathcal{A}$
% is the electrode surface area (assumed equal in anode and cathode) and
% $\delta_{i}$ is the thickness of electrode $i$ in $m$.
%
% To simplify the model implementation we introduce the following change of
% variable $u=rc$.
% We also rescale the radial coordinate $r$ by introducing the change of
% variable $x=r/R_{s,i}$.
% This maps the physical coordinates $r \in [0,R_{s,i}]$ onto the
% coordinates $x \in [0,1]$.
% The discretization using Chebyshev orthogonal collocation requires
% rescaling the domain on $[-1,1]$.
% However, mapping $r \in [0,R_{s,i}]$ onto $[-1,1]$ would result in
% discretization nodes clustered at both the surface and centre of the
% particles.
% A higher density of nodes is more sensible at the surface than the centre
% of particles because the concentration gradient is sharp at the surface,
% but relatively small at the centre.
% Instead, by introducing $x=r/R_{s,i}$ and solving the model on the domain
% $r \in [-R_{s,i},R_{s,i}]$ mapped onto $x \in [-1,1]$, the Chebyshev
% nodes are only clustered at the surface, and by symmetry we only need to
% solve the equation on $x \in [0,1]$, i.e. $r \in [0,R_{s,i}]$.
% Introducing the changes of variable defined above results in the
% following partial-differential equation for the spherical diffusion:
%
% $$
% \frac{\partial u\left(x,t\right)}{\partial t} =
% \frac{D_{s,i}(T)}{R_{s,i}^2}
% \frac{\partial^2 u\left(x,t\right)}{\partial x^2}
% $$
%
% subject to:
%
% $$
% \left.\frac{\partial u\left(x,t\right)}{\partial x}\right|_{x=1}
% - u\left(1,t\right) =
% \frac{-R_{s,i}^2}{D_{s,i}(T)} j_i(t)
% $$
%
% By symmetry, we have that $c(r)=c(-r) \Leftrightarrow u(r) = -u(-r)$, or
% equivalently $u(x) = -u(-x)$.
% We must also ensure that $c=u/r$ remains finite as $r \rightarrow 0$,
% therefore it follows that $u(r=0)=0$.
% More details on the model discretization are given in the 'Discretization
% using Chebyshev orthogonal collocation' section.
%
% The transformed lithium concentration profiles $c(r,t) = u(r,t)/r$
% in each particle and the temperature T  are the only states of the SPM.
% The current $I$ is the input of the model. The output voltage $V$ can
% be computed from the states according to:
%
% $$ V =
% \left( U_{+}\left( \theta_+, T \right) + \eta_+ \right)
% - \left( U_{-}\left( \theta_-, T \right) + \eta_- \right) - R_c i_{app} $$
%
% The term $-R_c i_{app}$ is the voltage drop due to the contact resistance
% of the battery with $R_c$ the contact resistance in $\Omega.m^2$ and
% $i_{app} = I/\mathcal{A}$ the current density in $A.m^{-2}$.
%
% $U_{+}$ and $U_{-}$ are the cathode and anode open-circuit potentials
% respectively. These open-circuit potentials are experimentally fitted
% functions of the surface stoichiometry of the active material
% $\theta_i = c_{s,i}^{surf}/c_{s,i}^{max}$, where $c_{s,i}^{max}$ is the
% theoretical maximum lithium concentration in the material. The
% open-circuit potentials are also temperature-dependent through a
% first-order Taylor series approximation with respect to temperature.
%
% The overpotentials $\eta_i$ are the voltage drops due to the departure
% from equilibrium potential associated with the
% intercalation/de-intercalation reaction in each electrode.
% The relationship between the reaction rate $j_i$ and the overpotential
% $\eta_i$ is given by the Butler-Volmer equation:
%
% $$ j_i = \frac{i_{0,i}}{\mathcal{F}} \left(
% \exp{ \left(\frac{ \alpha_a \mathcal{F}}{RT}\eta_i \right) } -
% \exp{ \left(\frac{-\alpha_c \mathcal{F}}{RT}\eta_i \right)}
% \right)$$
%
% where the exchange current density $i_{0,i}$ is a function of the
% reactants and products concentrations:
%
% $$ i_{0,i} = k_i(T) \mathcal{F} \sqrt{c_e^{avg}}
% \sqrt{c_{s,i}^{surf}} \sqrt{c_{s,i}^{max} - c_{s,i}^{surf}}$$
%
% By assuming that the anodic and cathodic charge transfer coefficients
% $\alpha_a$ and $\alpha_c$ are equal, i.e. $\alpha_a=\alpha_c=0.5$, we can
% express the overpotential $\eta_i$ as a function of the reaction rate
% $j_i$ (and therefore $I$):
%
% $$\eta_i =
% \frac{2RT}{\mathcal{F}} \sinh^{-1} \left(
% \frac{j_i}{2 i_{0,i}}\right)$$

%% Bulk thermal model
% The thermal model is a simple bulk thermal model, i.e. the cell
% temperature T is assumed uniform, governed by the following
% zero-dimensional heat equation:
%
% $$\rho c_p \frac{d T}{dt} = \dot{q}_{gen} + \dot{q}_{conv}$$
%
% where $c_p$ is the lumped specific heat of the cell in
% $J.kg^{-1}.K^{-1}$ and $\rho$ is the cell bulk density in $kg.m^{-3}$.
%
% The total heat generation rate per unit volume $\dot{q}_{gen}$ is the sum
% of the reversible, reaction and ohmic heat contributions:
%
% $$\dot{q}_{gen}= \dot{q}_{rev} + \dot{q}_{rx} + \dot{q}_c =
%  -\frac{i_{app}}{L} T \left(\frac{dU_+}{dT}-
% \frac{dU_-}{dT}\right)
% + \frac{i_{app}}{L} \left(\eta_- -\eta_+ \right) +
% \frac{R_c A_s i_{app}^2}{V_c}$$
%
% We assumed a convective boundary condition with the ambient and the
% convective heat removal rate is given by:
%
% $$\dot{q}_{conv}= \frac{-h A_c\left(T - T^{amb}\right)}{V_c}$$
%
% where $h$ is the convective heat transfer coefficient in
% $W.m^{-2}.K^{-1}$, $A_c$ is the cell surface area in $m^{2}$,
% $V_c$ is the cell volume in $m^{3}$, and $T^{amb}$ is the ambient
% temperature in $K$.

%% Discretization using Chebyshev orthogonal collocation
% The partial-differential equation constituting the solid-phase particle
% model is discretized in space using the Chebyshev orthogonal collocation
% method.
% The underlying principle of Chebyshev orthogonal collocation consists in
% approximating the solution of the PDE by a sum of Chebyshev polynomials
% that interpolates the solution at the discretizing Chebyshev nodes
% defined on $[-1,1]$.
% The derivative of this solution-interpolant can be conveniently
% calculated using Chebyshev differentiation matrices computed by the
% _chebdif.m_ function of the MATLAB Differentiation Matrix Suite developed
% by Weideman and Reddy:
%
% * JAC Weideman, SC Reddy, A MATLAB differentiation matrix suite,
% ACM Transactions of Mathematical Software, Vol 26, pp 465-519 (2000)
%
% Denoting $D_M^1$ and $D_M^2$ the first- and second- derivative Chebyshev
% differentiation matrices with $M+1$ Chebyshev nodes, we have:
%
% $$
% \frac{\partial u}{\partial x} \approx D_M^{1} \mathbf{u}
% $$
%
% and
%
% $$
% \frac{\partial^2 u}{\partial x^2} \approx D_M^{2} \mathbf{u}
% $$
%
% where $\mathbf{u}$ is the vector containing the values of the solution
% $u$ at the $M+1$ Chebyshev nodes.
%
% The discrete approximation to the diffusion equation with the changes of
% variable $u=rc$ and $x=r/R_{s,i}$ can therefore be written:
%
% $$
% \frac{\partial \mathbf{u}}{\partial t} =
% \frac{D_{s,i}(T)}{R_{s,i}^2} D_M^2 \mathbf{u}
% $$
%
%
% *Notations*
%
% * $\mathbf{u}_i$ denotes the $i^{th}$ element of the vector $\mathbf{u}$.
% * $\left[D_M^2\right]_{i,j}$ denotes the row $i$ and column $j$ of the
%   matrix $D_M^2$.
% * We also adopt the MATLAB convention $i:j$ for denoting the rows or
%   columns ranging from $i$ to $j$.
%
% We define $M = 2N$ where $N$ is an integer defined by the user ($N+1$ is
% the number of discretizing Chebyshev nodes in half of the sphere
% including the surface and centre).
% By recalling the symmetry $u(x)=-u(-x)$ and that
% $u(r=0)=0 \Leftrightarrow \mathbf{u}_{N+1}=0$, we can solve the diffusion
% equation for the first half of the states $\mathbf{u}_{1:N}$ only on
% $x \in [0,1]$ and write:
%
% $$
% \frac{\partial \mathbf{u}_{1:N}}{\partial t} =
% \frac{D_{s,i}(T)}{R_{s,i}^2}  \left(
% \left[ D_M^2 \right]_{1:N,1:N}  \mathbf{u}_{1:N} +
% \left[ D_M^2 \right]_{1:N,N+2:M+1} \mathbf{u}_{N+2:M+1}
% \right)
% $$
%
% By symmetry, we have shown that:
%
% $$
% u(r) = -u(-r) \Rightarrow \mathbf{u}_{N+2:M+1} = - P \mathbf{u}_{1:N}
% $$
%
% where the permutation matrix $P=P^{-1}$ is the backward-identity matrix,
% or exchange matrix (matrix with 1 elements on the counter-diagonal and
% 0 elements everywhere else).
% Therefore, we can write the diffusion equation in terms of
% $\mathbf{u}_{1:N}$ only:
%
% $$
% \frac{\partial \mathbf{u}_{1:N}}{\partial t} =
% \frac{D_{s,i}(T)}{R_{s,i}^2}  \left(
% \left[ D_M^2 \right]_{1:N,1:N} -  \left[ D_M^2 \right]_{1:N,N+2:M+1} P
% \right) \mathbf{u}_{1:N}
% $$
%
% For convenience, we define the matrices:
%
% $$
% \tilde{D}_N^2 = \left[ D_M^2 \right]_{1:N,1:N} -
% \left[ D_M^2 \right]_{1:N,N+2:M+1} P
% $$
%
% and
%
% $$
% \tilde{D}_N^1 = \left[ D_M^1 \right]_{1:N,1:N} -
% \left[ D_M^1 \right]_{1:N,N+2:M+1} P
% $$
%
% And the diffusion equation further simplifies to:
%
% $$
% \frac{\partial \mathbf{u}_{1:N}}{\partial t} =
% \frac{D_{s,i}(T)}{R_{s,i}^2}
% \tilde{D}_N^2
% \mathbf{u}_{1:N}
% $$
%
% Similarly, we can write the discrete approximation to the boundary
% condition at the particle surface $r=R \Leftrightarrow x = 1$ as:
%
% $$
% \left[ \tilde{D}_N^1 \right]_{1,:} \mathbf{u}_{1:N} -
% \mathbf{u}_{1} =
% \frac{-R_{s,i}^2}{D_{s,i}(T)} j_i(t)
% $$
%
% or equivalently:
%
% $$
% \left[ \tilde{D}_N^1 \right]_{1,2:N} \mathbf{u}_{2:N} +
% \left( \left[ \tilde{D}_N^1 \right]_{1,1} - 1 \right)\mathbf{u}_{1} =
% \frac{R_{s,i}^2}{D_{s,i}(T)} j_i(t)
% $$
%
% This allows us to express the value of $u$ at the surface $\mathbf{u}_1$
% in terms of the value of $u$ at the other nodes $\mathbf{u}_{2:N}$ as:
%
% $$
% \mathbf{u}_{1} =
% \frac{\left[ \tilde{D}_N^1 \right]_{1,2:N}}{1-
% \left[ \tilde{D}_N^1 \right]_{1,1}} \mathbf{u}_{2:N} +
% \frac{1}{1-  \left[ \tilde{D}_N^1 \right]_{1,1} }
% \frac{R_{s,i}^2}{D_{s,i}(T)}    j_i(t)
% $$
%
% We now substitute the expression of $\mathbf{u}_{1}$ into the diffusion
% equation for $\mathbf{u}_{1:N}$ to obtain the following reduced diffusion
% equation for the inner nodes only $\mathbf{u}_{2:N}$, which automatically
% satisfies the surface boundary condition:
%
% $$
% \frac{\partial \mathbf{u}_{2:N}}{\partial t} =
% \frac{D_{s,i}(T)}{R_{s,i}^2}
% \left( \left[ \tilde{D}_N^2 \right]_{2:N,2:N}  +
% \frac{\left[ \tilde{D}_N^2 \right]_{2:N,1}
% \left[ \tilde{D}_N^1 \right]_{1,2:N}}
% {1- \left[ \tilde{D}_N^1 \right]_{1,1}}
% \right) \mathbf{u}_{2:N} +
% \frac{\left[ \tilde{D}_N^2 \right]_{2:N,1}}
% {1-\left[ \tilde{D}_N^1 \right]_{1,1} }
% j_i(t)
% $$
%
% And we can cast this diffusion equation into the following state-space
% form:
%
% $$
% \frac{\partial \mathbf{u}_{2:N}}{\partial t} =
% D_{s,i}(T) A \mathbf{u}_{2:N} + B j_{i}(t)
% $$
%
% and
%
% $$
% \mathbf{c}_{2:N+1} = C \mathbf{u}_{2:N} + \frac{D}{D_{s,i}(T)} j_{i}(t)
% $$
%
% where $\mathbf{c}$ is the vector containing the lithium concentration
% values at the Chebyshev nodes, and the matrices $A$, $B$, $C$ and $D$ are
% defined as follows:
%
% $$
% A = \frac{1}{R_{s,i}^2}
% \left( \left[ \tilde{D}_N^2 \right]_{2:N,2:N}  +
% \frac{\left[ \tilde{D}_N^2 \right]_{2:N,1}\left[ \tilde{D}_N^1 \right]_{1,2:N}}
% {1- \left[ \tilde{D}_N^1 \right]_{1,1}} \right)
% $$
%
% $$
% B = \frac{\left[ \tilde{D}_N^2 \right]_{2:N,1}}
% {1- \left[ \tilde{D}_N^1 \right]_{1,1} }
% $$
%
% $$
% C =
% \left[
% \begin{array}{ccc}
% \multicolumn{3}{c}{
% \frac{1}{R_{s,i}} \frac{\left[ \tilde{D}_N^1 \right]_{1,2:N}}{1-
% \left[ \tilde{D}_N^1 \right]_{1,1}}
% } \\
% \frac{1}{\mathbf{r}_2} & & \\
%  & \ddots & \\
%  &   & \frac{1}{\mathbf{r}_N}
% \end{array}
% \right]
% $$
%
% $$
% D =
% \left[
% \begin{array}{c}
% \frac{R_{s,i}}{1- \left[ \tilde{D}_N^1 \right]_{1,1} } \\
% 0 \\
% \vdots \\
% 0
% \end{array}
% \right]
% $$
%
% The value of concentration at the centre of the particle
% $\mathbf{c}_{N+1}$ can be computed by recalling the original boundary
% condition:
%
% $$
% \left.\frac{\partial c\left(r,t\right)}{\partial x}
% \right|_{x=1} = \frac{-R_{s,i}}{D_{s,i}(T)} j_i\left(t\right)
% $$
%
% Recalling that $c(x) = c(-x)$, this can be written in discrete form:
%
% $$
% \left( \left[ D_M^1 \right]_{1,1:N} +
% \left[ D_M^1 \right]_{1,N+2:M+1} P \right) \mathbf{c}_{1:N} +
% \left[ D_M^1 \right]_{1,N+1} \mathbf{c}_{N+1}=
%  \frac{-R_{s,i}}{D_{s,i}(T)}  j_i(t)
% $$
%
% which gives the expression for the concentration at the centre of the
% particle:
%
% $$
% \mathbf{c}_{N+1}=
% - \frac{\left[ D_M^1 \right]_{1,1:N} +
% \left[ D_M^1 \right]_{1,N+2:M+1} P}{\left[ D_M^1 \right]_{1,N+1} }
% \mathbf{c}_{1:N} -
% \frac{1}{\left[ D_M^1 \right]_{1,N+1} }
% \frac{R_{s,i}}{D_{s,i}(T)}  j_i(t)
% $$

%% Example: constant-current discharge simulation
% In this example script, we will simulate the constant-current discharge
% of a lithium-ion battery using _Spectral li-ion SPM_.
% The parameters provided are for a LCO cell and were found in the
% literature. Please see our paper for more details:
%
% * Bizeray A.M. , Zhao, S., Duncan, S. R., and Howey, D. A., "Lithium-ion
% battery thermal-electrochemical model-based state estimation using
% orthogonal collocation and a modified extended Kalman filter", Journal
% of Power Sources, vol. 296, pp. 400-412, 2015.
% <http://www.sciencedirect.com/science/article/pii/S0378775315300677
% Publisher copy> and <http://arxiv.org/abs/1506.08689 Open access
% pre-print>

%%
% We first need to add the source files to the MATLAB path. Also, make sure
% the _chebdif.m_ file from the _MATLAB Differentiation Matrix Suite_ is
% available on the MATLAB path.
% The _MATLAB Differentiation Matrix Suite_ can be downloaded at
% <http://uk.mathworks.com/matlabcentral/fileexchange/29-dmsuite>.
% We suggest to drop the unzip _dmsuite_ folder into the <../source source>
% folder of _Spectral li-ion SPM_ and then run the following commands at
% the beginning of your script.

% Adding required folder / subfolder on the MATLAB path
clear; close all;
addpath(genpath('source'));
addpath(genpath('model_parameters'));

%{
    Note: Make sure the 'MATLAB Differentiation Matrix Suite' developed by
    Weideman and Reddy is on your MATLAB path.
    Ref: JAC Weideman, SC Reddy, A MATLAB differentiation matrix suite,
    ACM Transactions of Mathematical Software, Vol 26, pp 465-519 (2000).)

    The 'MATLAB Differentiation Matrix Suite' is available for download at:
    http://uk.mathworks.com/matlabcentral/fileexchange/29-dmsuite
%}

%%
% All the model parameters are defined in the
% <../model_parameters/get_modelData.m get_modelData.m> file.
% The open-circuit potential and entropic coefficient for both electrodes
% are defined in the
% <../model_parameters/get_openCircuitPotential.m get_openCircuitPotential.m>
% file.  You should modify these files to define your own model parameters.
% A _data_ structure containing the parameters is created by calling the
% <../model_parameters/get_modelData.m get_modelData.m> function:

data = get_modelData;    % Load the model parameters for a cell
%{
    Model parameters can be defined by the user by editing the file
    'model_parameters/get_modelData.m'
    The open-circuit potential and entropy coefficients of each electrode
    are defined in the file 'model_parameters/openCircuitPotential.m'
%}

%%
% The model is built by calling the <../source/get_model.m get_model.m>
% function which creates a _matrices_spm_ structure containing the
% differentiation matrices and the matrices A, B, C, and D of the diffusion
% state-space model.
% The Chebyshev nodes are computed by the <../source/get_nodes.m
% get_nodes.m> function with $N+1$ the number of Chebyshev nodes.

% Building the model
N = 6;      % N+1 is the number of Chebyshev nodes used to discretize
            % the diffusion equation in each particle
nodes           = get_nodes(data,N);        % Create the Chebyshev nodes
matrices_spm    = get_model(data,nodes,N);  % Create the SPM model

%%
% The user must supply initial conditions to the model, i.e. the initial
% active material stoichiometry in anode _x1_init_ and cathode _y3_init_
% and the initial cell temperature _T_. The initial stoichiometry is
% assumed uniform within each particle (cell at equilibrium).
% The initial state vector is then created in the _initSPM_ structure as
% _initSPM.y0_ by calling the <../source/get_init.m get_init.m> function.

% Initial conditions
x1_init = data.x1_soc1;
y3_init = data.y3_soc1;
T_init  = data.T_amb;
%{
    The user must define 3 initial conditions:
        x1_init : initial stoichiometry in the anode particle (assumed uniform)
        y3_init : initial stoichiometry in the cathode particle (assumed uniform)
        T_init  : initial cell temperature
%}
initSPM = get_init(x1_init,y3_init,T_init,data,nodes,matrices_spm);

%%
% The input of the model is the current I in Amperes. Any current input can
% be set by the user by defining an anonymous function _I_ of time, which
% returns a current vector associated with a time vector.

% Input current
C_rate = 1;     % C-rate
I = @(t) C_rate*data.C_nom*ones(size(t));   % Applied current [A]

%%
% The time span for the time integration can be set by defining the _tspan_
% vector.
% If the _tspan_ vector contains the initial and final times only, the time
% steps chosen by the solver will be returned.
% If the _tspan_ vector contains more than two values, the user-defined time
% steps will be returned by the solver
% (see <matlab:doc('ode45') ode45> help).
% The voltage limits to stop the simulation are defined in a _V_limit_
% vector containing the lower and upper cut-off voltages.
% This vector is then provided to the
% <../source/cutOffVoltage.m cutOffVoltage.m> function.

% Time integration & Terminal conditions
% There are 2 terminal conditions:
%   the simulation time span (i.e. model 1 hour)
%   the voltage limits (i.e. the minimum and maximum voltage is reached)
% Whichever occurs first will stop time integration
tspan = 0:10:3600;  	% Simulation time span
V_limit = [3.0 4.2];  	% Minimum and maximum voltage

%%
% The model is then integrated in time by running the following code using
% the <matlab:doc('ode45') ode45> ODE solver. The function
% <../source/cutOffVoltage.m cutOffVoltage.m> stops the simulation if the
% voltage reaches the limits defined in the _V_limit_ vector.
% The <../source/derivs_spm.m derivs_spm.m> function is the actual single
% particle model and returns the time derivative of the state vector
% $\partial \mathbf{y} / \partial t$ at a given time $t$ and state
% $\mathbf{y}$.

% Solution
event = @(t,y) cutOffVoltage(t,y,I,data,matrices_spm,V_limit);
fun = @(t,y) derivs_spm(t,y,I,data,matrices_spm);
opt = odeset('Events',event);
[result.time,result.state] = ode45(fun,tspan,initSPM.y0,opt);

%%
% The ODE solver <matlab:doc('ode45') ode45> only returns the time steps
% and associated states of the model, other quantities of interest such as
% voltage, temperature, SOC, concentration profiles etc. are computed by
% the <../source/get_postproc.m get_postproc.m> function.
% The _result_ structure containing the _time_ and _state_ vectors computed
% by the ODE solver is provided to the
% <../source/get_postproc.m get_postproc.m> function, which returns a
% structure with additional quantities of interest.

% Postprocessing result (compute voltage, temperature, etc. from states)
result = get_postproc( result,data,nodes,matrices_spm,I);

%% Plotting some results
% We plot here some results for the 1C constant-current discharge
% simulation, such as the voltage and temperature.

% Voltage vs time
figure;
plot(result.time,result.voltage,'.-');
xlabel('Time [s]');
ylabel('Voltage [V]');
grid on;

% Temperature vs time
figure;
plot(result.time,result.temperature,'.-');
xlabel('Time [s]');
ylabel('Temperature [K]');
grid on;

%%
% We can also plot the states of the model. For instance the evolution
% of the lithium concentration profile in each electrode particle is
% plotted here as a surface plot.

% Concentration profiles vs time
[R1,T] = meshgrid(nodes.xc2xp(nodes.xr,'r1')*1e6,result.time);
[R3,~] = meshgrid(nodes.xc2xp(nodes.xr,'r3')*1e6,result.time);

figure;
subplot(121)
mesh(T,R1,result.cs1/data.cs1_max); grid on;
title('Anode')
xlabel('Time [s]');
ylabel('Radial coordinate r [microns]');
zlabel('Stoichiometry [-]');

subplot(122)
mesh(T,R3,result.cs3/data.cs3_max); grid on;
title('Cathode');
xlabel('Time [s]');
ylabel('Radial coordinate r [microns]');
zlabel('Stoichiometry [-]');

%%
% Or, if you prefer 2D graphs:

figure;
plot_idx = [1,101,201,301];     % Chosen times to plot

for i = 1:length(plot_idx)
    subplot(121)
    h1(i) = plot(nodes.xc2xp(nodes.xr,'r1')*1e6 , ...
        result.cs1(plot_idx(i),:)/data.cs1_max,'o-');
    xlabel('Radial coordinate r [microns]');
    ylabel('Stoichiometry [-]');
    title('Anode particle');
    hold on; grid on;

    subplot(122)
    h2(i) = plot(nodes.xc2xp(nodes.xr,'r3')*1e6 , ...
        result.cs3(plot_idx(i),:)/data.cs3_max,'o-');
    xlabel('Radial coordinate r [microns]');
    ylabel('Stoichiometry [-]');
    title('Anode particle');
    hold on; grid on;
end
legend_label = [ ...
    repmat('t = ',length(plot_idx),1),num2str(result.time(plot_idx)) , ...
    repmat(' s',length(plot_idx),1) ];

legend(h1,legend_label,'Location','Best');
legend(h2,legend_label,'Location','Best');


text:
package org.traccar.protocol;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import org.traccar.BaseProtocolDecoder;
import org.traccar.DeviceSession;
import org.traccar.NetworkMessage;
import org.traccar.Protocol;
import org.traccar.helper.BitUtil;
import org.traccar.helper.DateBuilder;
import org.traccar.helper.UnitsConverter;
import org.traccar.model.Position;

import java.net.SocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

public class DmtProtocolDecoder extends BaseProtocolDecoder {

    public DmtProtocolDecoder(Protocol protocol) {
        super(protocol);
    }

    public static final int MSG_HELLO = 0x00;
    public static final int MSG_HELLO_RESPONSE = 0x01;
    public static final int MSG_DATA_RECORD = 0x04;
    public static final int MSG_COMMIT = 0x05;
    public static final int MSG_COMMIT_RESPONSE = 0x06;
    public static final int MSG_DATA_RECORD_64 = 0x10;

    public static final int MSG_CANNED_REQUEST_1 = 0x14;
    public static final int MSG_CANNED_RESPONSE_1 = 0x15;
    public static final int MSG_CANNED_REQUEST_2 = 0x22;
    public static final int MSG_CANNED_RESPONSE_2 = 0x23;

    private void sendResponse(Channel channel, int type, ByteBuf content) {
        if (channel != null) {
            ByteBuf response = Unpooled.buffer();
            response.writeByte(0x02); response.writeByte(0x55); // header
            response.writeByte(type);
            response.writeShortLE(content != null ? content.readableBytes() : 0);
            if (content != null) {
                response.writeBytes(content);
                content.release();
            }
            channel.writeAndFlush(new NetworkMessage(response, channel.remoteAddress()));
        }
    }

    private List<Position> decodeFixed64(Channel channel, SocketAddress remoteAddress, ByteBuf buf) {

        DeviceSession deviceSession = getDeviceSession(channel, remoteAddress);
        if (deviceSession == null) {
            return null;
        }

        List<Position> positions = new LinkedList<>();

        while (buf.readableBytes() >= 64) {
            Position position = new Position(getProtocolName());
            position.setDeviceId(deviceSession.getDeviceId());

            buf.readByte(); // type

            position.set(Position.KEY_INDEX, buf.readUnsignedIntLE());

            long time = buf.readUnsignedIntLE();
            position.setTime(new DateBuilder()
                    .setYear((int) (2000 + (time & 0x3F)))
                    .setMonth((int) (time >> 6) & 0xF)
                    .setDay((int) (time >> 10) & 0x1F)
                    .setHour((int) (time >> 15) & 0x1F)
                    .setMinute((int) (time >> 20) & 0x3F)
                    .setSecond((int) (time >> 26) & 0x3F)
                    .getDate());

            position.setLongitude(buf.readIntLE() * 0.0000001);
            position.setLatitude(buf.readIntLE() * 0.0000001);
            position.setSpeed(UnitsConverter.knotsFromCps(buf.readUnsignedShortLE()));
            position.setCourse(buf.readUnsignedByte() * 2);
            position.setAltitude(buf.readShortLE());

            buf.readUnsignedShortLE(); // position accuracy
            buf.readUnsignedByte(); // speed accuracy

            position.set(Position.KEY_EVENT, buf.readUnsignedByte());

            position.setValid(BitUtil.check(buf.readByte(), 0));

            position.set(Position.KEY_INPUT, buf.readUnsignedIntLE());
            position.set(Position.KEY_OUTPUT, buf.readUnsignedShortLE());

            for (int i = 1; i <= 5; i++) {
                position.set(Position.PREFIX_ADC + i, buf.readShortLE());
            }

            position.set(Position.KEY_DEVICE_TEMP, buf.readByte());

            buf.readShortLE(); // accelerometer x
            buf.readShortLE(); // accelerometer y
            buf.readShortLE(); // accelerometer z

            buf.skipBytes(8); // device id

            position.set(Position.KEY_PDOP, buf.readUnsignedShortLE() * 0.01);

            buf.skipBytes(2); // reserved

            buf.readUnsignedShortLE(); // checksum

            positions.add(position);
        }

        return positions;
    }

    private List<Position> decodeStandard(Channel channel, SocketAddress remoteAddress, ByteBuf buf) {

        DeviceSession deviceSession = getDeviceSession(channel, remoteAddress);
        if (deviceSession == null) {
            return null;
        }

        List<Position> positions = new LinkedList<>();

        while (buf.isReadable()) {
            int recordEnd = buf.readerIndex() + buf.readUnsignedShortLE();

            Position position = new Position(getProtocolName());
            position.setDeviceId(deviceSession.getDeviceId());

            position.set(Position.KEY_INDEX, buf.readUnsignedIntLE());

            position.setDeviceTime(new Date(1356998400000L + buf.readUnsignedIntLE() * 1000)); // since 1 Jan 2013

            position.set(Position.KEY_EVENT, buf.readUnsignedByte());

            while (buf.readerIndex() < recordEnd) {

                int fieldId = buf.readUnsignedByte();
                int fieldLength = buf.readUnsignedByte();
                int fieldEnd = buf.readerIndex() + (fieldLength == 255 ? buf.readUnsignedShortLE() : fieldLength);

                if (fieldId == 0) {

                    position.setFixTime(new Date(1356998400000L + buf.readUnsignedIntLE() * 1000));
                    position.setLatitude(buf.readIntLE() * 0.0000001);
                    position.setLongitude(buf.readIntLE() * 0.0000001);
                    position.setAltitude(buf.readShortLE());
                    position.setSpeed(UnitsConverter.knotsFromCps(buf.readUnsignedShortLE()));

                    buf.readUnsignedByte(); // speed accuracy

                    position.setCourse(buf.readUnsignedByte() * 2);

                    position.set(Position.KEY_PDOP, buf.readUnsignedByte() * 0.1);

                    position.setAccuracy(buf.readUnsignedByte());
                    position.setValid(buf.readUnsignedByte() != 0);

                } else if (fieldId == 2) {

                    int input = buf.readIntLE();
                    int output = buf.readUnsignedShortLE();
                    int status = buf.readUnsignedShortLE();

                    position.set(Position.KEY_IGNITION, BitUtil.check(input, 0));

                    position.set(Position.KEY_INPUT, input);
                    position.set(Position.KEY_OUTPUT, output);
                    position.set(Position.KEY_STATUS, status);

                } else if (fieldId == 6) {

                    while (buf.readerIndex() < fieldEnd) {
                        switch (buf.readUnsignedByte()) {
                            case 1:
                                position.set(Position.KEY_BATTERY, buf.readUnsignedShortLE() * 0.001);
                                break;
                            case 2:
                                position.set(Position.KEY_POWER, buf.readUnsignedShortLE() * 0.01);
                                break;
                            case 3:
                                position.set(Position.KEY_DEVICE_TEMP, buf.readShortLE() * 0.01);
                                break;
                            case 4:
                                position.set(Position.KEY_RSSI, buf.readUnsignedShortLE());
                                break;
                            case 5:
                                position.set("solarPower", buf.readUnsignedShortLE() * 0.001);
                                break;
                            default:
                                break;
                        }
                    }

                }

                buf.readerIndex(fieldEnd);

            }

            if (position.getFixTime() == null) {
                getLastLocation(position, position.getDeviceTime());
            }

            positions.add(position);
        }

        return positions;
    }

    @Override
    protected Object decode(
            Channel channel, SocketAddress remoteAddress, Object msg) throws Exception {

        ByteBuf buf = (ByteBuf) msg;

        buf.skipBytes(2); // header

        int type = buf.readUnsignedByte();
        int length = buf.readUnsignedShortLE();

        if (type == MSG_HELLO) {

            buf.readUnsignedIntLE(); // device serial number

            DeviceSession deviceSession = getDeviceSession(
                    channel, remoteAddress, buf.readSlice(15).toString(StandardCharsets.US_ASCII));

            ByteBuf response = Unpooled.buffer();
            if (length == 51) {
                response.writeByte(0); // reserved
                response.writeIntLE(0); // reserved
            } else {
                response.writeIntLE((int) ((System.currentTimeMillis() - 1356998400000L) / 1000));
                response.writeIntLE(deviceSession != null ? 0 : 1); // flags
            }

            sendResponse(channel, MSG_HELLO_RESPONSE, response);

        } else if (type == MSG_COMMIT) {

            ByteBuf response = Unpooled.buffer(0);
            response.writeByte(1); // flags (success)
            sendResponse(channel, MSG_COMMIT_RESPONSE, response);

        } else if (type == MSG_CANNED_REQUEST_1) {

            ByteBuf response = Unpooled.buffer(0);
            response.writeBytes(new byte[12]);
            sendResponse(channel, MSG_CANNED_RESPONSE_1, response);

        } else if (type == MSG_CANNED_REQUEST_2) {

            sendResponse(channel, MSG_CANNED_RESPONSE_2, null);

        } else if (type == MSG_DATA_RECORD_64) {

            return decodeFixed64(channel, remoteAddress, buf);

        } else if (type == MSG_DATA_RECORD) {

            return decodeStandard(channel, remoteAddress, buf);

        }

        return null;
    }

}


text:
#ifndef GW_DISPLAYMANAGER_H
#define GW_DISPLAYMANAGER_H

#include "sdk/include/displaymanager.h"
#include "sdk/gwapi/service_observer.h"
#include "sdk/include/sdk_export.h"
using namespace LTE::TRUNK::SDK;

class SDK_IMPORT_EXPORT Gw_DisplayManager : public DisplayManager
{
public:
    Gw_DisplayManager();
    //virtual ~Gw_DisplayManager();

    //通知组呼的状态变更信息
    virtual void notifyGroupStatus(GrpDspInfo * grpInfo);
    //通知用户和群组资源的状态变更信息
    virtual void notifyResourceStatus(ResourceStatusIndicator * resourceStatus);
    //通知点对点呼叫的状态变更信息
    virtual void notifyP2pcallStatus(P2pcallStatusIndicator * callStatus);
    //通知视频呼叫的状态变更信息(包括视频回传)
    virtual void notifyP2pvideocallStatus(P2pvideocallStatusIndicator * callStatus);

    virtual void notifyUserStatus(ResourceStatusIndicator * resourceStatus);
    virtual void notifyUserSdsStatus(SdsMessageIndicator * sdsmsg);
    virtual void notifyModuleStatus(DCModuleStatusIndicator * moduleStatus);

    //短数据信息上报给GUI
    virtual void notifySMS(SdsMessageIndicator * sdsmsg);

    //通知配置对象的变更信息, 参数为一个多态指针, 使用者需要downcast 为对应的变更子类
    virtual void notifyProvisionChange(ProvChangeIndicator* ){;}

    //通知配置对象的全同步, 参数为一个多态指针, 使用者需要downcast 为对应的变更子类
    virtual void notifyProvisionAllResync(ProvChangeIndicator* );

    //通知状态对象的全同步, 参数为一个多态指针, 使用者需要downcast 为对应的变更子类
    virtual void notifyStatusAllResync(ResourceStatusIndicator* ) {;}

    virtual void setObserver(AudioServiceObserver* it){audioObserver = it;}
    virtual void setObserver(VideoServiceObserver* it){videoObserver = it;}
    virtual void setObserver(MessageServiceObserver* it){MessageObserver = it;}
    virtual void setObserver(GroupServiceObserver* it){groupObserver = it;}
    virtual void setObserver(QueryServiceObserver* it){queryObserver = it;}

    virtual void setObserver(ModuleStatusObserver* it){moduleObserver = it;}
    virtual void setObserver(ResourceStatusObserver* it){resourceObserver = it;}
private:
    AudioServiceObserver* audioObserver;
    VideoServiceObserver* videoObserver;
    MessageServiceObserver* MessageObserver;
    GroupServiceObserver* groupObserver;
    QueryServiceObserver* queryObserver;

    ModuleStatusObserver* moduleObserver;
    ResourceStatusObserver* resourceObserver;
};

#endif // GW_DISPLAYMANAGER_H


text:
class LogsController < ApplicationController
  def index
    @last = (params[:last] or "50")
    File.open(Rails.root.join('log/my.log'), 'r') do |file|
      @logs = file.each_line.to_a.last(@last.to_i)
    end
  end
end


text:
@protocol BHTNestedSelectionObjectProtocol <NSObject>

@property (strong, nonatomic, readonly) NSString *navigationBarTitle;
@property (strong, nonatomic, readonly) NSString *recordName;
@property (strong, nonatomic, readonly) NSString *detailName;

@property (strong, nonatomic, readonly) NSArray  *children; // array of objects conforming to BHTNestedSelectionObjectProtocol
@property (strong, nonatomic, readonly) id<BHTNestedSelectionObjectProtocol> parent;

@end


text:
class AddTitleToProjects < ActiveRecord::Migration
  def change
    add_column :projects, :title, :string
    add_column :projects, :description, :string
    add_index :projects, :title, unique: true
  end
end