text:
! Array related routines (Integration, Interpolation, etc.)
!
! ------------------------------------------------------------------------------
! Copyright (c) 2009-13, Thomas P. Robitaille
!
! All rights reserved.
!
! Redistribution and use in source and binary forms, with or without
! modification, are permitted provided that the following conditions are met:
!
!  * Redistributions of source code must retain the above copyright notice, this
!    list of conditions and the following disclaimer.
!
!  * Redistributions in binary form must reproduce the above copyright notice,
!    this list of conditions and the following disclaimer in the documentation
!    and/or other materials provided with the distribution.
!
! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
! DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
! FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
! DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
! SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
! CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
! OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
! OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
! ------------------------------------------------------------------------------

module lib_array

  implicit none
  save

  private

  integer,parameter :: idp = selected_int_kind(13)
  integer,parameter :: sp = selected_real_kind(p=6,r=37)
  integer,parameter :: dp = selected_real_kind(p=15,r=307)

  public :: is_nan
  interface is_nan
     module procedure is_nan_int
     module procedure is_nan_int8
     module procedure is_nan_sp
     module procedure is_nan_dp
  end interface is_nan

  public :: linspace
  interface linspace
     module procedure linspace_sp
     module procedure linspace_dp
  end interface linspace

  public :: logspace
  interface logspace
     module procedure logspace_sp
     module procedure logspace_dp
  end interface logspace

  public :: integral
  interface integral
     module procedure integral_sp
     module procedure integral_dp
     module procedure integral_subset_sp
     module procedure integral_subset_dp
  end interface integral

  public :: cumulative_integral
  interface cumulative_integral
     module procedure cumulative_integral_sp
     module procedure cumulative_integral_dp
     ! module procedure cumulative_integral_subset_sp
     ! module procedure cumulative_integral_subset_dp
  end interface cumulative_integral

  public :: integral_linlog
  interface integral_linlog
     module procedure integral_linlog_sp
     module procedure integral_linlog_dp
     module procedure integral_linlog_subset_sp
     module procedure integral_linlog_subset_dp
  end interface integral_linlog

  public :: cumulative_integral_linlog
  interface cumulative_integral_linlog
     module procedure cumulative_integral_linlog_sp
     module procedure cumulative_integral_linlog_dp
     ! module procedure cumulative_integral_linlog_subset_sp
     ! module procedure cumulative_integral_linlog_subset_dp
  end interface cumulative_integral_linlog

  public :: integral_loglin
  interface integral_loglin
     module procedure integral_loglin_sp
     module procedure integral_loglin_dp
     module procedure integral_loglin_subset_sp
     module procedure integral_loglin_subset_dp
  end interface integral_loglin

  public :: cumulative_integral_loglin
  interface cumulative_integral_loglin
     module procedure cumulative_integral_loglin_sp
     module procedure cumulative_integral_loglin_dp
     ! module procedure cumulative_integral_loglin_subset_sp
     ! module procedure cumulative_integral_loglin_subset_dp
  end interface cumulative_integral_loglin

  public :: integral_loglog
  interface integral_loglog
     module procedure integral_loglog_sp
     module procedure integral_loglog_dp
     module procedure integral_loglog_subset_sp
     module procedure integral_loglog_subset_dp
  end interface integral_loglog

  public :: cumulative_integral_loglog
  interface cumulative_integral_loglog
     module procedure cumulative_integral_loglog_sp
     module procedure cumulative_integral_loglog_dp
     ! module procedure cumulative_integral_loglog_subset_sp
     ! module procedure cumulative_integral_loglog_subset_dp
  end interface cumulative_integral_loglog

  public :: locate
  interface locate
     module procedure locate_sp
     module procedure locate_dp
  end interface locate

  public :: interp1d
  interface interp1d
     module procedure interp1d_sp
     module procedure interp1d_dp
     module procedure interp1d_array_sp
     module procedure interp1d_array_dp
  end interface interp1d

  public :: interp1d_linlog
  interface interp1d_linlog
     module procedure interp1d_linlog_sp
     module procedure interp1d_linlog_dp
     module procedure interp1d_array_linlog_sp
     module procedure interp1d_array_linlog_dp
  end interface interp1d_linlog

  public :: interp1d_loglin
  interface interp1d_loglin
     module procedure interp1d_loglin_sp
     module procedure interp1d_loglin_dp
     module procedure interp1d_array_loglin_sp
     module procedure interp1d_array_loglin_dp
  end interface interp1d_loglin

  public :: interp1d_loglog
  interface interp1d_loglog
     module procedure interp1d_loglog_sp
     module procedure interp1d_loglog_dp
     module procedure interp1d_array_loglog_sp
     module procedure interp1d_array_loglog_dp
  end interface interp1d_loglog

  public :: rebin
  interface rebin
     module procedure rebin_sp
     module procedure rebin_dp
  end interface rebin

  public :: rebin_linlog
  interface rebin_linlog
     module procedure rebin_linlog_sp
     module procedure rebin_linlog_dp
  end interface rebin_linlog

  public :: rebin_loglin
  interface rebin_loglin
     module procedure rebin_loglin_sp
     module procedure rebin_loglin_dp
  end interface rebin_loglin

  public :: rebin_loglog
  interface rebin_loglog
     module procedure rebin_loglog_sp
     module procedure rebin_loglog_dp
  end interface rebin_loglog

  public :: interp2d
  interface interp2d
     module procedure interp2d_sp
     module procedure interp2d_dp
  end interface interp2d

  public :: histogram1d
  interface histogram1d
     module procedure histogram1d_sp
     module procedure histogram1d_dp
  end interface histogram1d

  public :: histogram2d
  interface histogram2d
     module procedure histogram2d_sp
     module procedure histogram2d_dp
  end interface histogram2d

  public :: ipos
  interface ipos
     module procedure ipos_sp
     module procedure ipos_dp
  end interface ipos

  public :: xval
  interface xval
     module procedure xval_sp
     module procedure xval_dp
  end interface xval

  public :: quicksort
  interface quicksort
     module procedure quicksort_sp
     module procedure quicksort_all_sp
     module procedure quicksort_dp
     module procedure quicksort_all_dp
  end interface quicksort

  public :: quicksort_index
  interface quicksort_index
     module procedure quicksort_index_sp
     module procedure quicksort_index_all_sp
     module procedure quicksort_index_dp
     module procedure quicksort_index_all_dp
  end interface quicksort_index

  public :: test_quicksort_sp
  public :: test_quicksort_dp

  public :: int
  interface int
     module procedure logical2int
  end interface int

contains

  elemental integer function logical2int(a) result(b)
    implicit none
    logical,intent(in) :: a
    if(a) then
       b = 1
    else
       b = 0
    end if
  end function logical2int

  !!@FOR real(sp):sp real(dp):dp integer:int integer(idp):int8

  logical elemental function is_nan_<T>(value) result(nan)
    ! x != x does not work with pgfortran
    @T,intent(in) :: value
    nan = .not. (value > -1 .or. value < 1)
  end function is_nan_<T>

  !!@END FOR

  !!@FOR real(sp):sp real(dp):dp

  subroutine linspace_<T>(xmin,xmax,x)
    implicit none
    @T,intent(in) :: xmin,xmax
    @T,intent(out) :: x(:)
    integer :: i,n
    n = size(x)
    if (n == 1) then
       if(xmin /= xmax) then
          write(0,'("ERROR: Cannot call linspace with n=1 and xmin /= xmax")')
          stop
       else
          x = xmin
       end if
    else
       do i=1,n
          x(i) = (xmax-xmin) * real(i-1,<T>) / real(n-1,<T>) + xmin
       end do
    end if
  end subroutine linspace_<T>

  subroutine logspace_<T>(xmin,xmax,x)
    implicit none
    @T,intent(in) :: xmin,xmax
    @T,intent(out) :: x(:)
    if (size(x) == 1 .and. xmin /= xmax) then
       write(0,'("ERROR: Cannot call logspace with n=1 and xmin /= xmax")')
       stop
    end if
    call linspace(log10(xmin),log10(xmax),x)
    x = 10._<T>**x
  end subroutine logspace_<T>

  real(<T>) function integral_<T>(x,y)
    ! Total integral of a function
    implicit none
    real(<T>),intent(in) :: x(:),y(:)
    integral_<T> = integral_general_<T>(x, y, trapezium_<T>)
  end function integral_<T>

  real(<T>) function integral_subset_<T>(x,y,x1,x2)
    ! Integral of a function between two limits
    implicit none
    real(<T>),intent(in) :: x(:),y(:),x1,x2
    integral_subset_<T> = integral_general_subset_<T>(x, y, x1, x2, interp1d_<T>, trapezium_<T>)
  end function integral_subset_<T>

  real(<T>) function integral_linlog_<T>(x,y)
    ! Total integral of a function
    ! (uses linlog interpolation)
    implicit none
    real(<T>),intent(in) :: x(:),y(:)
    integral_linlog_<T> = integral_general_<T>(x, y, trapezium_linlog_<T>)
  end function integral_linlog_<T>

  real(<T>) function integral_linlog_subset_<T>(x,y,x1,x2)
    ! Integral of a function between two limits
    ! (uses linlog interpolation)
    implicit none
    real(<T>),intent(in) :: x(:),y(:),x1,x2
    integral_linlog_subset_<T> = integral_general_subset_<T>(x, y, x1, x2, interp1d_linlog_<T>, trapezium_linlog_<T>)
  end function integral_linlog_subset_<T>

  real(<T>) function integral_loglin_<T>(x,y)
    ! Total integral of a function
    ! (uses loglin interpolation)
    implicit none
    real(<T>),intent(in) :: x(:),y(:)
    integral_loglin_<T> = integral_general_<T>(x, y, trapezium_loglin_<T>)
  end function integral_loglin_<T>

  real(<T>) function integral_loglin_subset_<T>(x,y,x1,x2)
    ! Integral of a function between two limits
    ! (uses loglin interpolation)
    implicit none
    real(<T>),intent(in) :: x(:),y(:),x1,x2
    integral_loglin_subset_<T> = integral_general_subset_<T>(x, y, x1, x2, interp1d_loglin_<T>, trapezium_loglin_<T>)
  end function integral_loglin_subset_<T>

  real(<T>) function integral_loglog_<T>(x,y)
    ! Total integral of a function
    ! (uses log10 interpolation)
    implicit none
    real(<T>),intent(in) :: x(:),y(:)
    integral_loglog_<T> = integral_general_<T>(x, y, trapezium_loglog_<T>)
  end function integral_loglog_<T>

  real(<T>) function integral_loglog_subset_<T>(x,y,x1,x2)
    ! Integral of a function between two limits
    ! (uses log10 interpolation)
    implicit none
    real(<T>),intent(in) :: x(:),y(:),x1,x2
    integral_loglog_subset_<T> = integral_general_subset_<T>(x, y, x1, x2, interp1d_loglog_<T>, trapezium_loglog_<T>)
  end function integral_loglog_subset_<T>

  function cumulative_integral_<T>(x,y)
    ! Total cumulative_integral of a function
    implicit none
    real(<T>),intent(in) :: x(:),y(:)
    real(<T>), dimension(size(y)) :: cumulative_integral_<T>
    cumulative_integral_<T> = cumulative_integral_general_<T>(x, y, trapezium_<T>)
  end function cumulative_integral_<T>

  function cumulative_integral_linlog_<T>(x,y)
    ! Total cumulative_integral of a function
    ! (uses linlog interpolation)
    implicit none
    real(<T>),intent(in) :: x(:),y(:)
    real(<T>), dimension(size(y)) :: cumulative_integral_linlog_<T>
    cumulative_integral_linlog_<T> = cumulative_integral_general_<T>(x, y, trapezium_linlog_<T>)
  end function cumulative_integral_linlog_<T>

  function cumulative_integral_loglin_<T>(x,y)
    ! Total cumulative_integral of a function
    ! (uses loglin interpolation)
    implicit none
    real(<T>),intent(in) :: x(:),y(:)
    real(<T>), dimension(size(y)) :: cumulative_integral_loglin_<T>
    cumulative_integral_loglin_<T> = cumulative_integral_general_<T>(x, y, trapezium_loglin_<T>)
  end function cumulative_integral_loglin_<T>

  function cumulative_integral_loglog_<T>(x,y)
    ! Total cumulative_integral of a function
    ! (uses log10 interpolation)
    implicit none
    real(<T>),intent(in) :: x(:),y(:)
    real(<T>), dimension(size(y)) :: cumulative_integral_loglog_<T>
    cumulative_integral_loglog_<T> = cumulative_integral_general_<T>(x, y, trapezium_loglog_<T>)
  end function cumulative_integral_loglog_<T>

  real(<T>) function integral_general_<T>(x,y,f_chunk) result(sum)
    ! Total integral of a function
    implicit none
    real(<T>),intent(in) :: x(:),y(:)
    integer :: j
    interface
       real(<T>) function f_chunk(x1,y1,x2,y2)
         import :: <T>
         implicit none
         real(<T>),intent(in) :: x1,y1,x2,y2
       end function f_chunk
    end interface
    sum = 0._<T>
    do j=1,size(x)-1
       sum=sum+f_chunk(x(j),y(j),x(j+1),y(j+1))
    end do
  end function integral_general_<T>

  function cumulative_integral_general_<T>(x,y,f_chunk) result(c)
    ! Total integral of a function
    implicit none
    real(<T>),intent(in) :: x(:),y(:)
    integer :: j
    interface
       real(<T>) function f_chunk(x1,y1,x2,y2)
         import :: <T>
         implicit none
         real(<T>),intent(in) :: x1,y1,x2,y2
       end function f_chunk
    end interface
    real(<T>), dimension(size(y)) :: c
    c(1) = 0._<T>
    do j=1,size(x)-1
       c(j+1)=c(j)+f_chunk(x(j),y(j),x(j+1),y(j+1))
    end do
  end function cumulative_integral_general_<T>

  real(<T>) function integral_general_subset_<T>(x,y,x1,x2,f_interp,f_chunk) result(sum)
    ! Integral of a function between two limits

    implicit none

    real(<T>),intent(in) :: x(:),y(:),x1,x2
    integer :: i1,i2
    real(<T>) :: f1,f2
    integer :: n

    interface
       real(<T>) function f_interp(x, y, xval,bounds_error,fill_value)
         import :: <T>
         implicit none
         real(<T>),dimension(:),intent(in) :: x,y
         real(<T>),intent(in) :: xval
         logical,intent(in),optional :: bounds_error
         real(<T>),intent(in),optional :: fill_value
       end function f_interp
       real(<T>) function f_chunk(x1,y1,x2,y2)
         import :: <T>
         implicit none
         real(<T>),intent(in) :: x1,y1,x2,y2
       end function f_chunk
    end interface

    n = size(x)

    if(x1.gt.x(n).or.x2.lt.x(1)) then
       sum = 0._<T>
       return
    end if

    if(x1.gt.x(1)) then
       i1 = locate(x,x1)
       f1 = f_interp(x,y,x1)
    else
       i1 = 0
       f1 = 0._<T>
    end if

    if(x2.lt.x(n)) then
       i2 = locate(x,x2)
       f2 = f_interp(x,y,x2)
    else
       i2 = n
       f2 = 0._<T>
    end if

    if(i2.gt.i1) then

       ! Add main part
       if(i2 > i1+1) then
          sum = integral_general_<T>(x(i1+1:i2), y(i1+1:i2), f_chunk)
       else
          sum = 0._<T>
       end if

       ! Add extremities
       sum = sum + f_chunk(x1,f1,x(i1+1),y(i1+1))
       sum = sum + f_chunk(x(i2),y(i2),x2,f2)

    else

       sum = f_chunk(x1,f1,x2,f2)

    end if

  end function integral_general_subset_<T>

  real(<T>) function trapezium_<T>(x1,y1,x2,y2)
    implicit none
    real(<T>),intent(in) :: x1,y1,x2,y2
    trapezium_<T> = 0.5_<T>*(y1+y2)*(x2-x1)
  end function trapezium_<T>

  real(<T>) function trapezium_loglin_<T>(x1,y1,x2,y2)
    implicit none
    real(<T>),intent(in) :: x1,y1,x2,y2
    real(<T>) :: a,b
    if(x1==x2) then
       trapezium_loglin_<T> = 0._<T>
    else
       a = (y1-y2) / log10(x1/x2)
       b = y1 - a * log10(x1)
       trapezium_loglin_<T> = a*(x2*log10(x2) - x1*log10(x1)) &
            &                     + (b-a/log(10._<T>)) * (x2 - x1)
    end if
  end function trapezium_loglin_<T>

  real(<T>) function trapezium_linlog_<T>(x1,y1,x2,y2)
    implicit none
    real(<T>),intent(in) :: x1,y1,x2,y2
    real(<T>) :: dx
    if(x1==x2) then
       trapezium_linlog_<T> = 0._<T>
    else if(y1==y2) then
       trapezium_linlog_<T> = y1*(x2-x1)
    else
       dx = x2 - x1
       trapezium_linlog_<T> = (y2-y1)*(x2-x1)/log(10._<T>)/log10(y2/y1)
    end if
  end function trapezium_linlog_<T>

  real(<T>) function trapezium_loglog_<T>(x1,y1,x2,y2)
    implicit none
    real(<T>),intent(in) :: x1,y1,x2,y2
    real(<T>) :: b
    if(x1==x2) then
       trapezium_loglog_<T> = 0._<T>
    else if(y1==0..or.y2==0.) then
       trapezium_loglog_<T> = 0._<T>
    else
       b = log10(y1/y2) / log10(x1/x2)
       if(abs(b+1._dp) < 1e-10) then
          trapezium_loglog_<T> = x1 * y1 * log(x2/x1)
       else
          trapezium_loglog_<T> = y1 * (x2*(x2/x1)**b-x1) / (b+1)
       end if
    end if
  end function trapezium_loglog_<T>

  real(<T>) function interp1d_single_<T>(x1,y1,x2,y2,xval) result(yval)
    real(<T>),intent(in) :: x1,y1,x2,y2,xval
    real(<T>) :: frac
    frac = ( xval - x1 ) / ( x2 - x1 )
    yval = y1 + frac * ( y2 - y1 )
  end function interp1d_single_<T>

  real(<T>) function interp1d_single_linlog_<T>(x1,y1,x2,y2,xval) result(yval)
    real(<T>),intent(in) :: x1,y1,x2,y2,xval
    real(<T>) :: frac
    if(y1==0..or.y2==0.) then
       yval = 0._<T>
    else
       frac = ( xval - x1 ) / ( x2 - x1 )
       yval = 10._<T>**(log10(y1) + frac * ( log10(y2) - log10(y1) ))
    end if
  end function interp1d_single_linlog_<T>

  real(<T>) function interp1d_single_loglin_<T>(x1,y1,x2,y2,xval) result(yval)
    real(<T>),intent(in) :: x1,y1,x2,y2,xval
    real(<T>) :: frac
    frac = ( log10(xval) - log10(x1) ) / ( log10(x2) - log10(x1) )
    yval = y1 + frac * ( y2 - y1 )
  end function interp1d_single_loglin_<T>

  real(<T>) function interp1d_single_loglog_<T>(x1,y1,x2,y2,xval) result(yval)
    real(<T>),intent(in) :: x1,y1,x2,y2,xval
    real(<T>) :: frac
    if(y1==0..or.y2==0.) then
       yval = 0._<T>
    else
       frac = ( log10(xval) - log10(x1) ) / ( log10(x2) - log10(x1) )
       yval = 10._<T>**(log10(y1) + frac * ( log10(y2) - log10(y1) ))
    end if
  end function interp1d_single_loglog_<T>

  real(<T>) function interp1d_<T>(x,y,xval,bounds_error,fill_value) result(yval)
    implicit none
    real(<T>),dimension(:),intent(in) :: x,y
    real(<T>),intent(in) :: xval
    logical,intent(in),optional :: bounds_error
    real(<T>),intent(in),optional :: fill_value
    yval = interp1d_general_<T>(x,y,xval,interp1d_single_<T>,bounds_error,fill_value)
  end function interp1d_<T>

  function interp1d_array_<T>(x,y,xval,bounds_error,fill_value)
    implicit none
    real(<T>),intent(in) :: x(:),y(:)
    real(<T>),intent(in) :: xval(:)
    logical,intent(in),optional :: bounds_error
    real(<T>),intent(in),optional :: fill_value
    real(<T>) :: interp1d_array_<T>(size(xval))
    integer :: i
    do i=1,size(xval)
       interp1d_array_<T>(i) = interp1d_<T>(x,y,xval(i),bounds_error,fill_value)
    end do
  end function interp1d_array_<T>

  real(<T>) function interp1d_linlog_<T>(x,y,xval,bounds_error,fill_value) result(yval)
    implicit none
    real(<T>),dimension(:),intent(in) :: x,y
    real(<T>),intent(in) :: xval
    logical,intent(in),optional :: bounds_error
    real(<T>),intent(in),optional :: fill_value
    yval = interp1d_general_<T>(x,y,xval,interp1d_single_linlog_<T>,bounds_error,fill_value)
  end function interp1d_linlog_<T>

  function interp1d_array_linlog_<T>(x,y,xval,bounds_error,fill_value)
    implicit none
    real(<T>),intent(in) :: x(:),y(:)
    real(<T>),intent(in) :: xval(:)
    logical,intent(in),optional :: bounds_error
    real(<T>),intent(in),optional :: fill_value
    real(<T>) :: interp1d_array_linlog_<T>(size(xval))
    integer :: i
    do i=1,size(xval)
       interp1d_array_linlog_<T>(i) = interp1d_linlog_<T>(x,y,xval(i),bounds_error,fill_value)
    end do
  end function interp1d_array_linlog_<T>

  real(<T>) function interp1d_loglin_<T>(x,y,xval,bounds_error,fill_value) result(yval)
    implicit none
    real(<T>),dimension(:),intent(in) :: x,y
    real(<T>),intent(in) :: xval
    logical,intent(in),optional :: bounds_error
    real(<T>),intent(in),optional :: fill_value
    yval = interp1d_general_<T>(x,y,xval,interp1d_single_loglin_<T>,bounds_error,fill_value)
  end function interp1d_loglin_<T>

  function interp1d_array_loglin_<T>(x,y,xval,bounds_error,fill_value)
    implicit none
    real(<T>),intent(in) :: x(:),y(:)
    real(<T>),intent(in) :: xval(:)
    logical,intent(in),optional :: bounds_error
    real(<T>),intent(in),optional :: fill_value
    real(<T>) :: interp1d_array_loglin_<T>(size(xval))
    integer :: i
    do i=1,size(xval)
       interp1d_array_loglin_<T>(i) = interp1d_loglin_<T>(x,y,xval(i),bounds_error,fill_value)
    end do
  end function interp1d_array_loglin_<T>

  real(<T>) function interp1d_loglog_<T>(x,y,xval,bounds_error,fill_value) result(yval)
    implicit none
    real(<T>),dimension(:),intent(in) :: x,y
    real(<T>),intent(in) :: xval
    logical,intent(in),optional :: bounds_error
    real(<T>),intent(in),optional :: fill_value
    yval = interp1d_general_<T>(x,y,xval,interp1d_single_loglog_<T>,bounds_error,fill_value)
  end function interp1d_loglog_<T>

  function interp1d_array_loglog_<T>(x,y,xval,bounds_error,fill_value)
    implicit none
    real(<T>),intent(in) :: x(:),y(:)
    real(<T>),intent(in) :: xval(:)
    logical,intent(in),optional :: bounds_error
    real(<T>),intent(in),optional :: fill_value
    real(<T>) :: interp1d_array_loglog_<T>(size(xval))
    integer :: i
    do i=1,size(xval)
       interp1d_array_loglog_<T>(i) = interp1d_loglog_<T>(x,y,xval(i),bounds_error,fill_value)
    end do
  end function interp1d_array_loglog_<T>

  real(<T>) function interp1d_general_<T>(x,y,xval,f_single,bounds_error,fill_value) result(yval)

    implicit none

    integer :: n
    ! the size of the array

    real(<T>),dimension(:),intent(in) :: x,y
    ! the x and y arrays

    real(<T>),intent(in) :: xval
    ! the value at which to interpolate y

    interface
       real(<T>) function f_single(x1,y1,x2,y2,xval)
         import :: <T>
         implicit none
         real(<T>),intent(in) :: x1,y1,x2,y2,xval
       end function f_single
    end interface

    logical,intent(in),optional :: bounds_error
    ! whether to raise an out of bounds error

    real(<T>),intent(in),optional :: fill_value
    ! value for out of bounds if bounds_error is .false.

    integer :: ipos
    ! position of x value in x array

    logical :: bounds_error_tmp
    real(<T>) :: fill_value_tmp

    if(present(bounds_error)) then
       bounds_error_tmp = bounds_error
    else
       bounds_error_tmp = .true.
    end if

    if(.not.bounds_error_tmp) then
       if(present(fill_value)) then
          fill_value_tmp = fill_value
       else
          fill_value_tmp = 0._<T>
       end if
    end if

    n = size(x)

    ipos = locate(x,xval)

    ! --- First some error checking --- !

    if(ipos == -1) then
       if(bounds_error_tmp) then
          write(0,'("ERROR: Interpolation out of bounds : ",ES11.4," in [",ES11.4,":",ES11.4,"]")') xval,x(1),x(n)
          stop
       else
          yval = fill_value_tmp
          return
       end if
    end if

    if( ipos < n .and. ipos > 0) then
       yval = f_single(x(ipos), y(ipos), x(ipos+1), y(ipos+1), xval)
    else if(ipos == n) then
       yval = y(n)
    else if(ipos == 0) then
       yval = y(1)
    else
       write(0,'("ERROR: Unexpected value of ipos : ",I0)') ipos
       stop
    end if

  end function interp1d_general_<T>

  function interp2d_<T>(x,y,array,x0,y0,bounds_error,fill_value) result(value)
    ! Bilinar interpolation of array = f(x,y) at (x0,y0)

    implicit none

    real(<T>),intent(in) :: x(:),y(:),array(:,:),x0,y0

    logical,intent(in),optional :: bounds_error
    ! whether to raise an out of bounds error

    real(<T>),intent(in),optional :: fill_value
    ! value for out of bounds if bounds_error is .false.

    real(<T>) :: value,norm
    integer :: i1,i2,j1,j2

    logical :: bounds_error_tmp
    real(<T>) :: fill_value_tmp

    if(present(bounds_error)) then
       bounds_error_tmp = bounds_error
    else
       bounds_error_tmp = .true.
    end if

    if(.not.bounds_error_tmp) then
       if(present(fill_value)) then
          fill_value_tmp = fill_value
       else
          fill_value_tmp = 0._<T>
       end if
    end if

    if(size(x).ne.size(array,1)) stop "x does not match array"
    if(size(y).ne.size(array,2)) stop "y does not match array"

    i1 = locate(x,x0) ; i2 = i1 + 1
    j1 = locate(y,y0) ; j2 = j1 + 1

    if(i1==-1) then
       if(bounds_error_tmp) then
          write(0,'("ERROR: Interpolation out of bounds : ",ES11.4," in [",ES11.4,":",ES11.4,"]")') x0,x(1),x(size(x))
          stop
       else
          value = fill_value_tmp
          return
       end if
    end if

    if(j1==-1) then
       if(bounds_error_tmp) then
          write(0,'("ERROR: Interpolation out of bounds : ",ES11.4," in [",ES11.4,":",ES11.4,"]")') y0,y(1),y(size(y))
          stop
       else
          value = fill_value_tmp
          return
       end if
    end if

    norm = 1._<T> / (x(i2) - x(i1)) / (y(j2)-y(j1))

    value =   array(i1,j1) * (x(i2)-x0) * (y(j2)-y0) * norm &
         &       + array(i2,j1) * (x0-x(i1)) * (y(j2)-y0) * norm &
         &       + array(i1,j2) * (x(i2)-x0) * (y0-y(j1)) * norm &
         &       + array(i2,j2) * (x0-x(i1)) * (y0-y(j1)) * norm

  end function interp2d_<T>

  real(<T>) function average_lin_<T>(a,b)
    implicit none
    real(<T>),intent(in) :: a,b
    average_lin_<T> = 0.5_<T> * (a + b)
  end function average_lin_<T>

  real(<T>) function average_log_<T>(a,b)
    implicit none
    real(<T>),intent(in) :: a,b
    average_log_<T> = sqrt(a*b)
  end function average_log_<T>

  subroutine rebin_<T>(x, y, xx, yy)
    real(<T>),intent(in) :: x(:), y(:), xx(:)
    real(<T>),intent(out) :: yy(:)
    call rebin_general_<T>(x, y, xx, yy, average_lin_<T>, integral_subset_<T>)
  end subroutine rebin_<T>

  subroutine rebin_linlog_<T>(x, y, xx, yy)
    real(<T>),intent(in) :: x(:), y(:), xx(:)
    real(<T>),intent(out) :: yy(:)
    call rebin_general_<T>(x, y, xx, yy, average_lin_<T>, integral_linlog_subset_<T>)
  end subroutine rebin_linlog_<T>

  subroutine rebin_loglin_<T>(x, y, xx, yy)
    real(<T>),intent(in) :: x(:), y(:), xx(:)
    real(<T>),intent(out) :: yy(:)
    call rebin_general_<T>(x, y, xx, yy, average_log_<T>, integral_loglin_subset_<T>)
  end subroutine rebin_loglin_<T>

  subroutine rebin_loglog_<T>(x, y, xx, yy)
    real(<T>),intent(in) :: x(:), y(:), xx(:)
    real(<T>),intent(out) :: yy(:)
    call rebin_general_<T>(x, y, xx, yy, average_log_<T>, integral_loglog_subset_<T>)
  end subroutine rebin_loglog_<T>

  subroutine rebin_general_<T>(x, y, xx, yy, f_average, f_integral)
    implicit none
    real(<T>),intent(in) :: x(:), y(:), xx(:)
    real(<T>),intent(out) :: yy(:)
    integer :: i
    real(<T>) :: xmin, xmax
    interface
       real(<T>) function f_average(a,b)
         import :: <T>
         implicit none
         real(<T>),intent(in) :: a,b
       end function f_average
       real(<T>) function f_integral(x,y,x1,x2)
         import :: <T>
         implicit none
         real(<T>),intent(in) :: x(:),y(:),x1,x2
       end function f_integral
    end interface
    do i=1,size(xx)
       if(i==1) then
          xmin = xx(1)
       else
          xmin = f_average(xx(i-1), xx(i))
       end if
       if(i==size(xx)) then
          xmax = xx(size(xx))
       else
          xmax = f_average(xx(i), xx(i+1))
       end if
       yy(i) = f_integral(x, y, xmin, xmax) / (xmax - xmin)
    end do
  end subroutine rebin_general_<T>

  integer function locate_<T>(xx,x)
    ! Locate a value in a sorted array

    implicit none
    real(<T>), dimension(:), intent(in) :: xx
    real(<T>), intent(in) :: x
    integer :: n,jl,jm,ju
    logical :: ascnd
    n=size(xx)
    ascnd = (xx(n) >= xx(1))
    jl=0
    ju=n+1
    do
       if (ju-jl <= 1) exit
       jm=(ju+jl)/2
       if (ascnd .eqv. (x >= xx(jm))) then
          jl=jm
       else
          ju=jm
       end if
    end do

    if (x == xx(1)) then
       locate_<T> = 1
    else if (x == xx(n)) then
       locate_<T> = n-1
    else if(ascnd.and. (x > xx(n) .or. x < xx(1))) then
       locate_<T> = -1
    else if(.not.ascnd.and. (x < xx(n) .or. x > xx(1))) then
       locate_<T> = -1
    else
       locate_<T> = jl
    end if

  end function locate_<T>

  integer function ipos_<T>(xmin,xmax,x,nbin)
    ! Find bin a value falls in for a regular histogram

    implicit none

    real(<T>),intent(in) :: xmin,xmax
    ! range of values

    real(<T>),intent(in) :: x
    ! the value to bin

    integer,intent(in) :: nbin
    ! number of bins

    real(<T>) :: frac

    if(xmax > xmin) then

       if(x < xmin) then
          ipos_<T> = 0
       else if(x > xmax) then
          ipos_<T> = nbin+1
       else if(x < xmax) then
          frac=(x-xmin)/(xmax-xmin)
          ipos_<T>=int(frac*real(nbin, <T>))+1
       else  ! x == xmax
          ipos_<T> = nbin
       end if

    else

       if(x < xmax) then
          ipos_<T> = 0
       else if(x > xmin) then
          ipos_<T> = nbin+1
       else if(x < xmin) then
          frac=(x-xmin)/(xmax-xmin)
          ipos_<T>=int(frac*real(nbin, <T>))+1
       else  ! x == xmin
          ipos_<T> = nbin
       end if

    end if

  end function ipos_<T>

  real(<T>) function xval_<T>(xmin,xmax,i,nbin)
    ! Find central value of a bin for a regular histogram

    implicit none

    real(<T>),intent(in) :: xmin,xmax
    ! range of values

    integer,intent(in) :: i
    ! the bin number

    integer,intent(in) :: nbin
    ! number of bins

    real(<T>) :: frac

    frac=(real(i-1)+0.5)/real(nbin)

    xval_<T>=frac*(xmax-xmin)+xmin

  end function xval_<T>

  subroutine histogram1d_<T>(array,xmin,xmax,nbin,hist_x,hist_y,mask,weights)
    ! Bin 1D array of values into 1D regular histogram

    implicit none

    real(<T>),dimension(:),intent(in) :: array
    real(<T>),dimension(:),intent(in),optional :: weights
    ! the array of values to bin

    real(<T>),intent(in) :: xmin,xmax
    ! the range of the histogram

    integer,intent(in) :: nbin
    ! number of bins

    real(<T>),dimension(nbin),intent(out) :: hist_x,hist_y
    ! the histogram

    integer :: i,ibin
    ! binning variables

    logical,optional,intent(in) :: mask(:)
    logical,allocatable:: keep(:)

    allocate(keep(size(array)))

    if(present(mask)) then
       keep = mask
    else
       keep = .true.
    end if

    hist_x=0._<T> ; hist_y=0._<T>

    do i=1,size(array)
       if(keep(i)) then
          ibin=ipos(xmin,xmax,array(i),nbin)
          if(ibin.ge.1.and.ibin.le.nbin) then
             if(present(weights)) then
                hist_y(ibin)=hist_y(ibin)+weights(i)
             else
                hist_y(ibin)=hist_y(ibin)+1._<T>
             end if
          end if
       end if
    end do

    do ibin=1,nbin
       hist_x(ibin)=xval(xmin,xmax,ibin,nbin)
    end do

    deallocate(keep)

  end subroutine histogram1d_<T>

  subroutine histogram2d_<T>(n,x,y,xmin,xmax,ymin,ymax,nx,ny,array,mask_in)
    ! Bin two 1D array of values into 2D regular grid

    implicit none

    integer,intent(in) :: n
    ! number of values to bin

    real(<T>),dimension(n),intent(in) :: x,y
    logical,dimension(n),intent(in),optional :: mask_in
    ! the array of values to bin

    real(<T>),intent(in) :: xmin,xmax,ymin,ymax
    ! the range of the histogram

    integer,intent(in) :: nx,ny
    ! number of bins

    real(<T>),dimension(nx,ny),intent(out) :: array
    ! the histogram

    integer :: i,ix,iy
    ! binning variables

    logical,dimension(n) :: mask

    if(present(mask_in)) then
       mask = mask_in
    else
       mask = .true.
    end if

    array = 0._<T>

    do i=1,n

       if(mask(i)) then

          ix=ipos(xmin,xmax,x(i),nx)
          iy=ipos(ymin,ymax,y(i),ny)

          if(ix.ge.1.and.ix.le.nx) then
             if(iy.ge.1.and.iy.le.ny) then
                array(ix,iy) = array(ix,iy) + 1.
             end if
          end if

       end if

    end do

  end subroutine histogram2d_<T>

  subroutine swap_<T>(array, i, j)
    implicit none
    real(<T>),intent(inout) :: array(:)
    integer,intent(in) :: i, j
    real(<T>) :: temp
    temp = array(j)
    array(j) = array(i)
    array(i) = temp
  end subroutine swap_<T>

  subroutine partition_<T>(array, left, right, pivot_index, store_index)
    implicit none
    real(<T>),intent(inout) :: array(:)
    integer,intent(in) :: left, right, pivot_index
    integer,intent(out) :: store_index
    real(<T>) :: pivot_value
    integer :: i
    pivot_value = array(pivot_index)
    call swap_<T>(array, pivot_index, right)
    store_index = left
    do i=left, right-1
       if(array(i) <= pivot_value) then
          call swap_<T>(array, i, store_index)
          store_index = store_index + 1
       end if
    end do
    call swap_<T>(array, store_index, right)
  end subroutine partition_<T>

  recursive subroutine quicksort_<T>(array, left, right)
    implicit none
    real(<T>),intent(inout) :: array(:)
    integer,intent(in) :: left, right
    integer :: pivot_index, new_pivot_index
    if(right > left) then
       pivot_index = left+(right-left)/2
       call partition_<T>(array, left, right, pivot_index, new_pivot_index)
       call quicksort_<T>(array, left, new_pivot_index - 1)
       call quicksort_<T>(array, new_pivot_index + 1, right)
    end if
  end subroutine quicksort_<T>

  recursive subroutine quicksort_all_<T>(array)
    implicit none
    real(<T>),intent(inout) :: array(:)
    call quicksort_<T>(array, 1, size(array))
  end subroutine quicksort_all_<T>

  subroutine swap_index_<T>(array, index, i, j)
    implicit none
    real(<T>),intent(inout) :: array(:)
    integer,intent(inout) :: index(:)
    integer,intent(in) :: i, j
    real(<T>) :: temp
    integer :: temp_i
    temp = array(j)
    temp_i = index(j)
    array(j) = array(i)
    index(j) = index(i)
    array(i) = temp
    index(i) = temp_i
  end subroutine swap_index_<T>

  subroutine partition_index_<T>(array, index, left, right, pivot_index, store_index)
    implicit none
    real(<T>),intent(inout) :: array(:)
    integer,intent(inout) :: index(:)
    integer,intent(in) :: left, right, pivot_index
    integer,intent(out) :: store_index
    real(<T>) :: pivot_value
    integer :: i
    pivot_value = array(pivot_index)
    call swap_index_<T>(array, index, pivot_index, right)
    store_index = left
    do i=left, right-1
       if(array(i) <= pivot_value) then
          call swap_index_<T>(array, index, i, store_index)
          store_index = store_index + 1
       end if
    end do
    call swap_index_<T>(array, index, store_index, right)
  end subroutine partition_index_<T>

  recursive subroutine quicksort_index_<T>(array, index, left, right)
    implicit none
    real(<T>),intent(inout) :: array(:)
    integer,intent(inout) :: index(:)
    integer,intent(in) :: left, right
    integer :: pivot_index, new_pivot_index
    if(right > left) then
       pivot_index = left+(right-left)/2
       call partition_index_<T>(array, index, left, right, pivot_index, new_pivot_index)
       call quicksort_index_<T>(array, index, left, new_pivot_index - 1)
       call quicksort_index_<T>(array, index, new_pivot_index + 1, right)
    end if
  end subroutine quicksort_index_<T>

  recursive subroutine quicksort_index_all_<T>(array, index)
    implicit none
    real(<T>),intent(inout) :: array(:)
    integer,intent(inout) :: index(:)
    call quicksort_index_<T>(array, index, 1, size(array))
  end subroutine quicksort_index_all_<T>

  subroutine check_sort_<T>(array)
    implicit none
    real(<T>),intent(inout) :: array(:)
    integer :: j
    do j=1,size(array)-1
       if(array(j+1) < array(j)) stop "Incorrectly sorted array"
    end do
  end subroutine check_sort_<T>

  subroutine test_quicksort_<T>()

    implicit none

    real(<T>),allocatable :: array1(:), array2(:)
    integer,allocatable :: index(:)
    integer :: j,i

    write(*,'(" Testing quicksort")')

    do j=1,20

       write(*,'("  - n=",I0)') 2**j

       allocate(array1(2**j))

       call random_number(array1)

       call quicksort(array1)

       call check_sort_<T>(array1)

       deallocate(array1)

    end do

    write(*,'(" Testing quicksort_index")')

    do j=1,20

       write(*,'("  - n=",I0)') 2**j

       allocate(array1(2**j), array2(2**j), index(2**j))

       call random_number(array1)
       array2 = array1
       forall(i=1:2**j) index(i) = i

       call quicksort_index(array1, index)

       call check_sort_<T>(array1)

       if(any(array2(index).ne.array1)) stop "Failure in quicksort_index"

       deallocate(array1, array2, index)

    end do

  end subroutine test_quicksort_<T>

  !!@END FOR

  subroutine invert_matrix(n,a,c)

    implicit none

    integer,intent(in) :: n
    ! size of the matrix

    real(dp),dimension(n,n),intent(in)  :: a
    real(dp),dimension(n,n),intent(out) :: c
    ! the input and output matrices

    real(dp),dimension(n,n) :: b

    integer :: i,j
    real(dp) :: scale

    ! a is the input matrix

    ! b is initially set to a

    b = a

    ! c is initially an identity matrix

    c = 0._dp
    forall(i=1:n) c(i,i) = 1._dp

    ! Go through each row, and sutract from all subsequent rows

    do i=1,n
       do j=i+1,n
          scale = -b(i,j)/b(i,i)
          b(:,j) = b(:,j)+scale*b(:,i)
          c(:,j) = c(:,j)+scale*c(:,i)
       end do
    end do

    do j=1,n-1
       do i=j+1,n
          scale = -b(i,j)/b(i,i)
          b(:,j) = b(:,j)+scale*b(:,i)
          c(:,j) = c(:,j)+scale*c(:,i)
       end do
    end do

    forall(i=1:n,j=1:n) c(i,j) = c(i,j)/b(j,j)
    forall(i=1:n,j=1:n) b(i,j) = b(i,j)/b(j,j)

  end subroutine invert_matrix

  subroutine print_matrix(a)

    implicit none

    integer :: nx,ny
    real(dp),dimension(:,:),intent(in) :: a

    integer :: i

    character(len=20) :: fmt

    nx = size(a,1)
    ny = size(a,2)

    write(fmt,'("(",I3.3,"(F9.5,1X))")') nx

    do i=1,ny
       write(*,fmt) a(:,i)
    end do

  end subroutine print_matrix

  subroutine bin_array(n,x,y,n_bin,xmin,xmax,x_bin,y_bin)

    implicit none

    integer,intent(in) :: n,n_bin
    real(dp),dimension(n),intent(in) :: x,y
    real(dp),dimension(n_bin),intent(out) :: x_bin,y_bin

    real(dp),dimension(n_bin) :: s,c

    real(dp) :: xmin,xmax

    integer :: i,ix

    s = 0.
    c = 0.

    do i=1,n

       ix = ipos(xmin,xmax,x(i),n_bin)

       if(ix.ge.1.and.ix.le.n_bin) then
          c(ix)  = c(ix) + 1.
          s(ix)  = s(ix) + y(i)
       end if

    end do

    do i=1,n_bin
       x_bin(i) = xval(xmin,xmax,i,n_bin)
    end do

    y_bin = s / c

  end subroutine bin_array

  subroutine smooth_2d(array,sigma)

    implicit none

    real,intent(inout) :: array(:,:)

    integer :: nx,ny
    real,allocatable :: array_orig(:,:),array_count(:,:)

    real,intent(in) :: sigma

    integer :: i,j,ii,jj,imin,imax,jmin,jmax,w

    real :: dx,dy,d

    nx = size(array,1)
    ny = size(array,2)

    allocate(array_orig(nx,ny),array_count(nx,ny))

    array_orig  = array
    array       = 0.
    array_count = 0.

    w = nint(sigma * 5._dp)

    do i=1,nx
       do j=1,ny

          imin = max( 1,i-w)
          imax = min(nx,i+w)
          jmin = max( 1,j-w)
          jmax = min(ny,j+w)

          do ii=imin,imax
             do jj=jmin,jmax

                dx = real(ii-i) / sigma
                dy = real(jj-j) / sigma

                d = dx*dx+dy*dy

                array(i,j) = array(i,j) + array_orig(ii,jj) * exp(-d/2._dp)
                array_count(i,j) = array_count(i,j) + exp(-d/2._dp)

             end do
          end do

       end do
    end do

    array = array / array_count

  end subroutine smooth_2d

end module lib_array


text:
@interface GP_Array2Tests : SenTestCase

@end

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Popup iframes - jQuery Mobile Demos</title>
	<link rel="shortcut icon" href="../favicon.ico">
    <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:300,400,700">
	<link rel="stylesheet" href="../css/themes/default/jquery.mobile-1.4.3.min.css">
	<link rel="stylesheet" href="../_assets/css/jqm-demos.css">

 Demos

            Menu
            Search

iframes in popups

You may need to embed an iframe into a popup to use a 3rd party widget. Here, we'll walk through a few real-world examples of working with iframes: videos and maps.

Video example

Here is an example of a 3rd party video player embedded in a popup:

        		Launch video player

The markup is an iframe inside a popup container. The popup will have a 15 pixels padding because of class ui-content and a one pixel border because the framework will add class ui-body-a to the popup.

When using an iframe inside a popup it is important to initially set the width and height attributes to 0. This prevents the page to breaking on platforms like Android 2.3. Note that you have to set the attributes, because setting the width and height with CSS is not sufficient. You can leave the actual width and height in the markup for browsers that have JavaScript disabled and use attr() to set the zero values upon the pagecreate event.

Next, bind to the popupbeforeposition event to set the desired size of the iframe when the popup is shown or when the window is resized (e.g. orientation change). For the iframe examples on this page a custom function scale() is used to scale down the iframe to fit smaller screens.

When the popup is closed the width and height should be set back to 0. You can do this by binding to the popupafterclose event.

Note that the video will still be playing in the iframe when the popup is closed. If available you can use the 3rd party API to stop the video on the popupafterclose event. Another way is to create the iframe when the popup is opened and destroy it when the popup is closed, but this would drop support for browsers that have JavaScript disabled.

Map example

In the second example, an iframe is used to display Google Maps API. Using an iframe prevents issues with the controls of the map.

    			Open Map

    				Close

Expand the section below to view the source of the iframe.

map.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Map</title>
    <script>
        function initialize() {
            var myLatlng = new google.maps.LatLng( 51.520838, -0.140261 );
            var myOptions = {
                zoom: 15,
                center: myLatlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            }
            var map = new google.maps.Map( document.getElementById( "map_canvas" ), myOptions );
        }
    </script>
    <script src="http://maps.google.com/maps/api/js?sensor=false"></script>
    <style>
        html {
            height: 100%;
            overflow: hidden;
        }
        body {
            margin: 0;
            padding: 0;
            height: 100%;
        }
        #map_canvas {
            height: 100%;
        }
    </style>
</head>
<body onload="initialize()">

    <div id="map_canvas"></div>

</body>
</html>

Setting the size of the iframe is done exactly the same as for the video example, with one exception. You should also set the width and height of the div that contains the map to prevent the page to break on platforms like Android 2.3. In this example the ID of this div is #map_canvas.

Home

Introduction

Buttons

Button widget

		    Checkboxradio widget click to expand contents

Checkboxes

Radio buttons

			Collapsible (set) widget click to expand contents

Collapsible

Dynamic collapsibles

Collapsible set

			Controlgroup widget click to expand contents

Controlgroup

Dynamic controlgroups

Datepicker

			Events click to expand contents

Swipe list items

Swipe page navigation

Filterable widget

Flipswitch widget

			Forms click to expand contents

Forms

Hide labels

Field containers

Forms disabled

Forms gallery

			Grids click to expand contents

Grids

Buttons in grids

Custom responsive grids

Grouping and dividing content

			Icons click to expand contents

Icons

Grunticon loader

			Listview widget click to expand contents

Listview

Listview autocomplete

Listview autocomplete remote data

Listview autodividers linkbar

Listview autodividers selector

Nested Listviews

Listview collapsible list items (flat)

Listview collapsible list items (indented)

Listview responsive grid

Loader widget

Navbar widget

			Navigation click to expand contents

Navigation

Linking pages

Hash processing demo

Page Navigation Events

			Pages click to expand contents

Pages

Single page

Multi-page template

Dialog page

			Panel widget click to expand contents

Panel

External panels

Fixed panels

Panels responsive

Custom panel style

Panel open on swipe

Panel external and internal

			Popup widget click to expand contents

Popup

Popup alignment

Popup arrow size

Dynamic popups

Popups with iframes

Popup image scaling

Popup outside multi-page

Rangeslider widget

Responsive Web Design

			Selectmenu widget click to expand contents

Selectmenu

Custom select menu

Custom select menu with filter

			Slider widget click to expand contents

Slider

Slider flip toggle switch

Slider tooltip

			Table widget click to expand contents

Table Column Toggle

Table Column Toggle demo

Table Column Toggle heading groups

Table Column Toggle options

Table Reflow

Table Reflow heading groups

Table Reflow stripes and strokes

Table Reflow custom styles

Tabs widget

Textinput widget

			Theming click to expand contents

Default theme

Classic theme

			Toolbar widget click to expand contents

Toolbar

Dynamic toolbars

External toolbars

Fixed toolbars

Fullscreen toolbars

Fixed external toolbars

Persistent toolbars

Ajax optimized toolbars

Form in toolbar

Transitions

			3rd party API demos click to expand contents

Backbone RequireJS

Google Maps geolocation

Google Maps list toggle

jQuery Mobile Demos version

Copyright 2014 The jQuery Foundation

Home

Introduction

Buttons

Button widget

		    Checkboxradio widget click to expand contents

Checkboxes

Radio buttons

			Collapsible (set) widget click to expand contents

Collapsible

Dynamic collapsibles

Collapsible set

			Controlgroup widget click to expand contents

Controlgroup

Dynamic controlgroups

Datepicker

			Events click to expand contents

Swipe list items

Swipe page navigation

Filterable widget

Flipswitch widget

			Forms click to expand contents

Forms

Hide labels

Field containers

Forms disabled

Forms gallery

			Grids click to expand contents

Grids

Buttons in grids

Custom responsive grids

Grouping and dividing content

			Icons click to expand contents

Icons

Grunticon loader

			Listview widget click to expand contents

Listview

Listview autocomplete

Listview autocomplete remote data

Listview autodividers linkbar

Listview autodividers selector

Nested Listviews

Listview collapsible list items (flat)

Listview collapsible list items (indented)

Listview responsive grid

Loader widget

Navbar widget

			Navigation click to expand contents

Navigation

Linking pages

Hash processing demo

Page Navigation Events

			Pages click to expand contents

Pages

Single page

Multi-page template

Dialog page

			Panel widget click to expand contents

Panel

External panels

Fixed panels

Panels responsive

Custom panel style

Panel open on swipe

Panel external and internal

			Popup widget click to expand contents

Popup

Popup alignment

Popup arrow size

Dynamic popups

Popups with iframes

Popup image scaling

Popup outside multi-page

Rangeslider widget

Responsive Web Design

			Selectmenu widget click to expand contents

Selectmenu

Custom select menu

Custom select menu with filter

			Slider widget click to expand contents

Slider

Slider flip toggle switch

Slider tooltip

			Table widget click to expand contents

Table Column Toggle

Table Column Toggle demo

Table Column Toggle heading groups

Table Column Toggle options

Table Reflow

Table Reflow heading groups

Table Reflow stripes and strokes

Table Reflow custom styles

Tabs widget

Textinput widget

			Theming click to expand contents

Default theme

Classic theme

			Toolbar widget click to expand contents

Toolbar

Dynamic toolbars

External toolbars

Fixed toolbars

Fullscreen toolbars

Fixed external toolbars

Persistent toolbars

Ajax optimized toolbars

Form in toolbar

Transitions

			3rd party API demos click to expand contents

Backbone RequireJS

Google Maps geolocation

Google Maps list toggle


text:
require_relative '../metadata/column'

module GoodData
  module Model
    ##
    # GoodData display form abstraction. Represents a default representation
    # of an attribute column or an additional representation defined in a LABEL
    # field
    #
    class Label < Column
      attr_accessor :attribute

      def type_prefix;
        'label';
      end

      # def initialize(hash, schema)
      def initialize(hash, attribute, schema)
        super hash, schema
        attribute = attribute.nil? ? schema.fields.find { |field| field.name === hash[:reference] } : attribute
        @attribute = attribute
        attribute.labels << self
      end

      def to_maql_create
        '# LABEL FROM LABEL'
        "ALTER ATTRIBUTE {#{@attribute.identifier}} ADD LABELS {#{identifier}}" \
              + " VISUAL (TITLE #{title.inspect}) AS {#{column}};\n"
      end

      def to_manifest_part(mode)
        {
          'populates' => [identifier],
          'mode' => mode,
          'columnName' => name
        }
      end

      def column
        "#{@attribute.table}.#{LABEL_COLUMN_PREFIX}#{name}"
      end

      alias :inspect_orig :inspect

      def inspect
        inspect_orig.sub(/>$/, " @attribute=#{@attribute.to_s.sub(/>$/, " @name=#{@attribute.name}")}>")
      end
    end
  end
end


text:
<?php

use Nails\Survey\Constants;

/**
 * This config file defines email types for this module.
 *
 * @package     Nails
 * @subpackage  module-survey
 * @category    Config
 * @author      Nails Dev Team
 * @link
 */

$config['email_types'] = [
    (object) [
        'slug'            => 'survey_notification',
        'name'            => 'Survey: Submission Notification',
        'description'     => 'Email sent when a survey response is submitted',
        'template_header' => '',
        'template_body'   => 'survey/email/survey_notification',
        'template_footer' => '',
        'default_subject' => 'Response to {{survey.label}} survey has been received',
        'can_unsubscribe' => true,
        'factory'         => Constants::MODULE_SLUG . '::EmailNotification',
    ],
    (object) [
        'slug'            => 'survey_save',
        'name'            => 'Survey: Submission Saved',
        'description'     => 'Email sent when a survey response is saved',
        'template_header' => '',
        'template_body'   => 'survey/email/survey_save',
        'template_footer' => '',
        'default_subject' => 'Response to {{survey.label}} survey has been saved',
        'can_unsubscribe' => false,
        'factory'         => Constants::MODULE_SLUG . '::EmailNotification',
    ],
];


text:
#ifndef LOG_H
#define LOG_H

#include <string>
#include <iostream>

#define LOG_STREAM std::cerr
//#define LOG_STREAM std::cout

/**
 * Log a normal message or error to a stream, e.g., std::cerr or std::cout.
 * Note: This is *not* to be used in any classes within "core." It is exclusively for the MDP-like objects
 * and the various utilities provided.
 * @param	msg		The message to output along with the error.
 * @param	error	The detailed error message.
 */
void log_message(const std::string &classFunctionName, const std::string &message);

#endif // LOG_H


text:
package com.linkedin.pinot.queries;

import com.linkedin.pinot.common.data.FieldSpec;
import com.linkedin.pinot.common.utils.DataSchema;
import com.linkedin.pinot.core.operator.ExecutionStatistics;
import com.linkedin.pinot.core.operator.blocks.IntermediateResultsBlock;
import com.linkedin.pinot.core.operator.query.MSelectionOnlyOperator;
import com.linkedin.pinot.core.operator.query.MSelectionOrderByOperator;
import java.io.Serializable;
import java.util.List;
import java.util.Queue;
import org.testng.Assert;
import org.testng.annotations.Test;

@SuppressWarnings("ConstantConditions")
public class InnerSegmentSelectionMultiValueQueriesTest extends BaseMultiValueQueriesTest {
  private static final String SELECTION = " column1, column5, column6";
  private static final String ORDER_BY = " ORDER BY column5, column9";

  @Test
  public void testSelectStar() {
    String query = "SELECT * FROM testTable";

    // Test query without filter.
    MSelectionOnlyOperator selectionOnlyOperator = getOperatorForQuery(query);
    IntermediateResultsBlock resultsBlock = (IntermediateResultsBlock) selectionOnlyOperator.nextBlock();
    ExecutionStatistics executionStatistics = selectionOnlyOperator.getExecutionStatistics();
    Assert.assertEquals(executionStatistics.getNumDocsScanned(), 10L);
    Assert.assertEquals(executionStatistics.getNumEntriesScannedInFilter(), 0L);
    Assert.assertEquals(executionStatistics.getNumEntriesScannedPostFilter(), 100L);
    Assert.assertEquals(executionStatistics.getNumTotalRawDocs(), 100000L);
    DataSchema selectionDataSchema = resultsBlock.getSelectionDataSchema();
    Assert.assertEquals(selectionDataSchema.size(), 10);
    Assert.assertEquals(selectionDataSchema.getColumnName(0), "column1");
    Assert.assertEquals(selectionDataSchema.getColumnName(5), "column6");
    Assert.assertEquals(selectionDataSchema.getColumnType(0), FieldSpec.DataType.INT);
    Assert.assertEquals(selectionDataSchema.getColumnType(5), FieldSpec.DataType.INT_ARRAY);
    List<Serializable[]> selectionResult = (List<Serializable[]>) resultsBlock.getSelectionResult();
    Assert.assertEquals(selectionResult.size(), 10);
    Serializable[] firstRow = selectionResult.get(0);
    Assert.assertEquals(firstRow.length, 10);
    Assert.assertEquals(((Integer) firstRow[0]).intValue(), 890282370);
    Assert.assertEquals(firstRow[5], new int[]{2147483647});

    // Test query with filter.
    selectionOnlyOperator = getOperatorForQueryWithFilter(query);
    resultsBlock = (IntermediateResultsBlock) selectionOnlyOperator.nextBlock();
    executionStatistics = selectionOnlyOperator.getExecutionStatistics();
    Assert.assertEquals(executionStatistics.getNumDocsScanned(), 10L);
    Assert.assertEquals(executionStatistics.getNumEntriesScannedInFilter(), 230501L);
    Assert.assertEquals(executionStatistics.getNumEntriesScannedPostFilter(), 100L);
    Assert.assertEquals(executionStatistics.getNumTotalRawDocs(), 100000L);
    selectionDataSchema = resultsBlock.getSelectionDataSchema();
    Assert.assertEquals(selectionDataSchema.size(), 10);
    Assert.assertEquals(selectionDataSchema.getColumnName(0), "column1");
    Assert.assertEquals(selectionDataSchema.getColumnName(5), "column6");
    Assert.assertEquals(selectionDataSchema.getColumnType(0), FieldSpec.DataType.INT);
    Assert.assertEquals(selectionDataSchema.getColumnType(5), FieldSpec.DataType.INT_ARRAY);
    selectionResult = (List<Serializable[]>) resultsBlock.getSelectionResult();
    Assert.assertEquals(selectionResult.size(), 10);
    firstRow = selectionResult.get(0);
    Assert.assertEquals(firstRow.length, 10);
    Assert.assertEquals(((Integer) firstRow[0]).intValue(), 890282370);
    Assert.assertEquals(firstRow[5], new int[]{2147483647});
  }

  @Test
  public void testSelectionOnly() {
    String query = "SELECT" + SELECTION + " FROM testTable";

    MSelectionOnlyOperator selectionOnlyOperator = getOperatorForQuery(query);
    IntermediateResultsBlock resultsBlock = (IntermediateResultsBlock) selectionOnlyOperator.nextBlock();
    ExecutionStatistics executionStatistics = selectionOnlyOperator.getExecutionStatistics();
    Assert.assertEquals(executionStatistics.getNumDocsScanned(), 10L);
    Assert.assertEquals(executionStatistics.getNumEntriesScannedInFilter(), 0L);
    Assert.assertEquals(executionStatistics.getNumEntriesScannedPostFilter(), 30L);
    Assert.assertEquals(executionStatistics.getNumTotalRawDocs(), 100000L);
    DataSchema selectionDataSchema = resultsBlock.getSelectionDataSchema();
    Assert.assertEquals(selectionDataSchema.size(), 3);
    Assert.assertEquals(selectionDataSchema.getColumnName(0), "column1");
    Assert.assertEquals(selectionDataSchema.getColumnName(2), "column6");
    Assert.assertEquals(selectionDataSchema.getColumnType(0), FieldSpec.DataType.INT);
    Assert.assertEquals(selectionDataSchema.getColumnType(2), FieldSpec.DataType.INT_ARRAY);
    List<Serializable[]> selectionResult = (List<Serializable[]>) resultsBlock.getSelectionResult();
    Assert.assertEquals(selectionResult.size(), 10);
    Serializable[] firstRow = selectionResult.get(0);
    Assert.assertEquals(firstRow.length, 3);
    Assert.assertEquals(((Integer) firstRow[0]).intValue(), 890282370);
    Assert.assertEquals(firstRow[2], new int[]{2147483647});

    // Test query with filter.
    selectionOnlyOperator = getOperatorForQueryWithFilter(query);
    resultsBlock = (IntermediateResultsBlock) selectionOnlyOperator.nextBlock();
    executionStatistics = selectionOnlyOperator.getExecutionStatistics();
    Assert.assertEquals(executionStatistics.getNumDocsScanned(), 10L);
    Assert.assertEquals(executionStatistics.getNumEntriesScannedInFilter(), 230501L);
    Assert.assertEquals(executionStatistics.getNumEntriesScannedPostFilter(), 30L);
    Assert.assertEquals(executionStatistics.getNumTotalRawDocs(), 100000L);
    selectionDataSchema = resultsBlock.getSelectionDataSchema();
    Assert.assertEquals(selectionDataSchema.size(), 3);
    Assert.assertEquals(selectionDataSchema.getColumnName(0), "column1");
    Assert.assertEquals(selectionDataSchema.getColumnName(2), "column6");
    Assert.assertEquals(selectionDataSchema.getColumnType(0), FieldSpec.DataType.INT);
    Assert.assertEquals(selectionDataSchema.getColumnType(2), FieldSpec.DataType.INT_ARRAY);
    selectionResult = (List<Serializable[]>) resultsBlock.getSelectionResult();
    Assert.assertEquals(selectionResult.size(), 10);
    firstRow = selectionResult.get(0);
    Assert.assertEquals(firstRow.length, 3);
    Assert.assertEquals(((Integer) firstRow[0]).intValue(), 890282370);
    Assert.assertEquals(firstRow[2], new int[]{2147483647});
  }

  @Test
  public void testSelectionOrderBy() {
    String query = "SELECT" + SELECTION + " FROM testTable" + ORDER_BY;

    // Test query without filter.
    MSelectionOrderByOperator selectionOrderByOperator = getOperatorForQuery(query);
    IntermediateResultsBlock resultsBlock = (IntermediateResultsBlock) selectionOrderByOperator.nextBlock();
    ExecutionStatistics executionStatistics = selectionOrderByOperator.getExecutionStatistics();
    Assert.assertEquals(executionStatistics.getNumDocsScanned(), 100000L);
    Assert.assertEquals(executionStatistics.getNumEntriesScannedInFilter(), 0L);
    Assert.assertEquals(executionStatistics.getNumEntriesScannedPostFilter(), 400000L);
    Assert.assertEquals(executionStatistics.getNumTotalRawDocs(), 100000L);
    DataSchema selectionDataSchema = resultsBlock.getSelectionDataSchema();
    Assert.assertEquals(selectionDataSchema.size(), 4);
    Assert.assertEquals(selectionDataSchema.getColumnName(0), "column5");
    Assert.assertEquals(selectionDataSchema.getColumnName(3), "column6");
    Assert.assertEquals(selectionDataSchema.getColumnType(0), FieldSpec.DataType.STRING);
    Assert.assertEquals(selectionDataSchema.getColumnType(3), FieldSpec.DataType.INT_ARRAY);
    Queue<Serializable[]> selectionResult = (Queue<Serializable[]>) resultsBlock.getSelectionResult();
    Assert.assertEquals(selectionResult.size(), 10);
    Serializable[] lastRow = selectionResult.peek();
    Assert.assertEquals(lastRow.length, 4);
    Assert.assertEquals((String) lastRow[0], "AKXcXcIqsqOJFsdwxZ");
    Assert.assertEquals(lastRow[3], new int[]{1252});

    // Test query with filter.
    selectionOrderByOperator = getOperatorForQueryWithFilter(query);
    resultsBlock = (IntermediateResultsBlock) selectionOrderByOperator.nextBlock();
    executionStatistics = selectionOrderByOperator.getExecutionStatistics();
    Assert.assertEquals(executionStatistics.getNumDocsScanned(), 15620L);
    Assert.assertEquals(executionStatistics.getNumEntriesScannedInFilter(), 282430L);
    Assert.assertEquals(executionStatistics.getNumEntriesScannedPostFilter(), 62480L);
    Assert.assertEquals(executionStatistics.getNumTotalRawDocs(), 100000L);
    selectionDataSchema = resultsBlock.getSelectionDataSchema();
    Assert.assertEquals(selectionDataSchema.size(), 4);
    Assert.assertEquals(selectionDataSchema.getColumnName(0), "column5");
    Assert.assertEquals(selectionDataSchema.getColumnName(3), "column6");
    Assert.assertEquals(selectionDataSchema.getColumnType(0), FieldSpec.DataType.STRING);
    Assert.assertEquals(selectionDataSchema.getColumnType(3), FieldSpec.DataType.INT_ARRAY);
    selectionResult = (Queue<Serializable[]>) resultsBlock.getSelectionResult();
    Assert.assertEquals(selectionResult.size(), 10);
    lastRow = selectionResult.peek();
    Assert.assertEquals(lastRow.length, 4);
    Assert.assertEquals((String) lastRow[0], "AKXcXcIqsqOJFsdwxZ");
    Assert.assertEquals(lastRow[3], new int[]{2147483647});
  }
}


text:
using System;
using System.ComponentModel;

namespace OutlookDesktop.Utility
{
    /// <summary>
    /// Extension method to allow accessing properties and fields in a worker thread without throwing:
    /// "Cross-thread operation not valid: Control 'MainForm' accessed from a thread other than the thread it was created on."
    /// </summary>
    public static class SynchronizeInvokeExtensions
    {
        public static void InvokeEx<T>(this T @this, Action<T> action) where T : ISynchronizeInvoke
        {
            if (@this.InvokeRequired)
            {
                @this.Invoke(action, new object[] {@this});
            }
            else
            {
                action(@this);
            }
        }
    }
}


text:
var express = require('express');
var router = express.Router();

// service to add ticketing process feedback
// expecting the following fields to be posted in the body of the request:
// citation_number, age, race, gender, def_city, def_state, income_range, violation, municipality, comment, rating
router.post('/ticket', function(req, res) {
  var query = req.pgQuery;

  var crypto = require('crypto');
  var sha1 = crypto.createHash('sha1').update(req.body.citation_number).digest("hex");

  var values = [sha1, req.body.age, req.body.race, req.body.gender, req.body.def_city, req.body.def_state, req.body.income_range, req.body.violation, req.body.municipality, req.body.comment, req.body.rating];

  query('INSERT INTO ticket_feedback(hashed_citation_number, age, race, gender, def_city, def_state, incomeRange, violation_description, municipality, optional_comment, experience_rating) VALUES ($1::text, $2::integer, $3::text, $4::text, $5::text, $6::text, $7::integer, $8::text, $9::text, $10::text, $11::integer);', values, function(err, rows, result) {

    res.send(
      (err === null) ? { msg: '' } : (err.code == '23505') ? { msg: 'Feedback already received.' } : { msg: err }
    );
  });
});

// service to add court process feedback
// expecting the following fields to be posted in the body of the request:
// citation_number, age, race, gender, def_city, def_state, income_range, violation, municipality, checkin_time, appearance_time, attorney, comment, rating
router.post('/court', function(req, res) {
  var query = req.pgQuery;

  var crypto = require('crypto');
  var sha1 = crypto.createHash('sha1').update(req.body.citation_number).digest("hex");

  var values = [sha1, req.body.age, req.body.race, req.body.gender, req.body.def_city, req.body.def_state, req.body.income_range, req.body.violation, req.body.municipality, req.body.checkin_time, req.body.appearance_time, req.body.attorney, req.body.comment, req.body.rating];

  query('INSERT INTO court_feedback(hashed_citation_number, age, race, gender, def_city, def_state, incomeRange, violation_description, municipality, checkin_time, appearance_time, attorney, optional_comment, experience_rating) VALUES ($1::text, $2::integer, $3::text, $4::text, $5::text, $6::text, $7::integer, $8::text, $9::text, $10::timestamp, $11::timestamp, $12::boolean, $13::text, $14::integer);', values, function(err, rows, result) {
    res.send(
      (err === null) ? { msg: '' } : (err.code == '23505') ? { msg: 'Feedback already received.' } : { msg: err }
    );
  });
});

module.exports = router;


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>java-a-to-z</artifactId>
        <groupId>ru.apetrov</groupId>
        <version>1.0-SNAPSHOT</version>
        <relativePath>../../pom.xml</relativePath>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <groupId>ru.apetrov</groupId>
    <artifactId>Lesson-10.2</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/postgresql/postgresql -->
        <dependency>
            <groupId>postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>9.1-901-1.jdbc4</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.3.6.Final</version>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-jdbc</artifactId>
            <version>8.5.23</version>
        </dependency>
    </dependencies>
</project>


text:
package fs

import (
	"fmt"
	"strconv"
	"testing"

	"github.com/opencontainers/runc/libcontainer/cgroups"
)

func TestCpuSetShares(t *testing.T) {
	helper := NewCgroupTestUtil("cpu", t)
	defer helper.cleanup()

	const (
		sharesBefore = 1024
		sharesAfter  = 512
	)

	helper.writeFileContents(map[string]string{
		"cpu.shares": strconv.Itoa(sharesBefore),
	})

	helper.CgroupData.config.Resources.CpuShares = sharesAfter
	cpu := &CpuGroup{}
	if err := cpu.Set(helper.CgroupPath, helper.CgroupData.config); err != nil {
		t.Fatal(err)
	}

	value, err := getCgroupParamUint(helper.CgroupPath, "cpu.shares")
	if err != nil {
		t.Fatalf("Failed to parse cpu.shares - %s", err)
	}

	if value != sharesAfter {
		t.Fatal("Got the wrong value, set cpu.shares failed.")
	}
}

func TestCpuSetBandWidth(t *testing.T) {
	helper := NewCgroupTestUtil("cpu", t)
	defer helper.cleanup()

	const (
		quotaBefore     = 8000
		quotaAfter      = 5000
		periodBefore    = 10000
		periodAfter     = 7000
		rtRuntimeBefore = 8000
		rtRuntimeAfter  = 5000
		rtPeriodBefore  = 10000
		rtPeriodAfter   = 7000
	)

	helper.writeFileContents(map[string]string{
		"cpu.cfs_quota_us":  strconv.Itoa(quotaBefore),
		"cpu.cfs_period_us": strconv.Itoa(periodBefore),
		"cpu.rt_runtime_us": strconv.Itoa(rtRuntimeBefore),
		"cpu.rt_period_us":  strconv.Itoa(rtPeriodBefore),
	})

	helper.CgroupData.config.Resources.CpuQuota = quotaAfter
	helper.CgroupData.config.Resources.CpuPeriod = periodAfter
	helper.CgroupData.config.Resources.CpuRtRuntime = rtRuntimeAfter
	helper.CgroupData.config.Resources.CpuRtPeriod = rtPeriodAfter
	cpu := &CpuGroup{}
	if err := cpu.Set(helper.CgroupPath, helper.CgroupData.config); err != nil {
		t.Fatal(err)
	}

	quota, err := getCgroupParamUint(helper.CgroupPath, "cpu.cfs_quota_us")
	if err != nil {
		t.Fatalf("Failed to parse cpu.cfs_quota_us - %s", err)
	}
	if quota != quotaAfter {
		t.Fatal("Got the wrong value, set cpu.cfs_quota_us failed.")
	}

	period, err := getCgroupParamUint(helper.CgroupPath, "cpu.cfs_period_us")
	if err != nil {
		t.Fatalf("Failed to parse cpu.cfs_period_us - %s", err)
	}
	if period != periodAfter {
		t.Fatal("Got the wrong value, set cpu.cfs_period_us failed.")
	}
	rtRuntime, err := getCgroupParamUint(helper.CgroupPath, "cpu.rt_runtime_us")
	if err != nil {
		t.Fatalf("Failed to parse cpu.rt_runtime_us - %s", err)
	}
	if rtRuntime != rtRuntimeAfter {
		t.Fatal("Got the wrong value, set cpu.rt_runtime_us failed.")
	}
	rtPeriod, err := getCgroupParamUint(helper.CgroupPath, "cpu.rt_period_us")
	if err != nil {
		t.Fatalf("Failed to parse cpu.rt_period_us - %s", err)
	}
	if rtPeriod != rtPeriodAfter {
		t.Fatal("Got the wrong value, set cpu.rt_period_us failed.")
	}
}

func TestCpuStats(t *testing.T) {
	helper := NewCgroupTestUtil("cpu", t)
	defer helper.cleanup()

	const (
		nrPeriods     = 2000
		nrThrottled   = 200
		throttledTime = uint64(18446744073709551615)
	)

	cpuStatContent := fmt.Sprintf("nr_periods %d\n nr_throttled %d\n throttled_time %d\n",
		nrPeriods, nrThrottled, throttledTime)
	helper.writeFileContents(map[string]string{
		"cpu.stat": cpuStatContent,
	})

	cpu := &CpuGroup{}
	actualStats := *cgroups.NewStats()
	err := cpu.GetStats(helper.CgroupPath, &actualStats)
	if err != nil {
		t.Fatal(err)
	}

	expectedStats := cgroups.ThrottlingData{
		Periods:          nrPeriods,
		ThrottledPeriods: nrThrottled,
		ThrottledTime:    throttledTime}

	expectThrottlingDataEquals(t, expectedStats, actualStats.CpuStats.ThrottlingData)
}

func TestNoCpuStatFile(t *testing.T) {
	helper := NewCgroupTestUtil("cpu", t)
	defer helper.cleanup()

	cpu := &CpuGroup{}
	actualStats := *cgroups.NewStats()
	err := cpu.GetStats(helper.CgroupPath, &actualStats)
	if err != nil {
		t.Fatal("Expected not to fail, but did")
	}
}

func TestInvalidCpuStat(t *testing.T) {
	helper := NewCgroupTestUtil("cpu", t)
	defer helper.cleanup()
	cpuStatContent := `nr_periods 2000
	nr_throttled 200
	throttled_time fortytwo`
	helper.writeFileContents(map[string]string{
		"cpu.stat": cpuStatContent,
	})

	cpu := &CpuGroup{}
	actualStats := *cgroups.NewStats()
	err := cpu.GetStats(helper.CgroupPath, &actualStats)
	if err == nil {
		t.Fatal("Expected failed stat parsing.")
	}
}

func TestCpuSetRtSchedAtApply(t *testing.T) {
	helper := NewCgroupTestUtil("cpu", t)
	defer helper.cleanup()

	const (
		rtRuntimeBefore = 0
		rtRuntimeAfter  = 5000
		rtPeriodBefore  = 0
		rtPeriodAfter   = 7000
	)

	helper.writeFileContents(map[string]string{
		"cpu.rt_runtime_us": strconv.Itoa(rtRuntimeBefore),
		"cpu.rt_period_us":  strconv.Itoa(rtPeriodBefore),
	})

	helper.CgroupData.config.Resources.CpuRtRuntime = rtRuntimeAfter
	helper.CgroupData.config.Resources.CpuRtPeriod = rtPeriodAfter
	cpu := &CpuGroup{}
	if err := cpu.ApplyDir(helper.CgroupPath, helper.CgroupData.config, 1234); err != nil {
		t.Fatal(err)
	}

	rtRuntime, err := getCgroupParamUint(helper.CgroupPath, "cpu.rt_runtime_us")
	if err != nil {
		t.Fatalf("Failed to parse cpu.rt_runtime_us - %s", err)
	}
	if rtRuntime != rtRuntimeAfter {
		t.Fatal("Got the wrong value, set cpu.rt_runtime_us failed.")
	}
	rtPeriod, err := getCgroupParamUint(helper.CgroupPath, "cpu.rt_period_us")
	if err != nil {
		t.Fatalf("Failed to parse cpu.rt_period_us - %s", err)
	}
	if rtPeriod != rtPeriodAfter {
		t.Fatal("Got the wrong value, set cpu.rt_period_us failed.")
	}
	pid, err := getCgroupParamUint(helper.CgroupPath, "cgroup.procs")
	if err != nil {
		t.Fatalf("Failed to parse cgroup.procs - %s", err)
	}
	if pid != 1234 {
		t.Fatal("Got the wrong value, set cgroup.procs failed.")
	}
}


text:
<?php

namespace Afrihost\BaseCommandBundle\Helper;

use Afrihost\BaseCommandBundle\Command\BaseCommand;
use Afrihost\BaseCommandBundle\Helper\Config\RuntimeConfig;

/**
 * Most enhancements will need access to the command that they augment and its config. This base class provides this
 */
abstract class AbstractEnhancement implements EnhancementInterface
{
    /**
     * @var BaseCommand
     */
    protected $command;

    /**
     * @var RuntimeConfig
     */
    protected $runtimeConfig;

    /**
     * AbstractEnhancement constructor.
     *
     * @param BaseCommand   $command
     * @param RuntimeConfig $runtimeConfig
     */
    public function __construct(BaseCommand $command, RuntimeConfig $runtimeConfig)
    {
        $this->command = $command;
        $this->runtimeConfig = $runtimeConfig;
    }

    /**
     * @return BaseCommand
     */
    protected function getCommand()
    {
        return $this->command;
    }

    /**
     * @return RuntimeConfig
     */
    protected function getRuntimeConfig()
    {
        return $this->runtimeConfig;
    }

    /**
     * Returns the name of the PHP file in which the User of the library's Command is defined
     *
     * @return string
     */
    protected function getUserCommandClassFilename()
    {
        $reflectionClass = new \ReflectionClass($this->getCommand());
        return basename($reflectionClass->getFileName());
    }

}


text:
Config::Config(NginxConfig *conf) {
  config = conf;
}

unsigned short Config::get_port() {
  for(unsigned int i = 0; i < config->statements_.size(); i++) {
    NginxConfigStatement *stmt = config->statements_[i].get();
    std::string tok_name = stmt->tokens_[0];
    if(tok_name == "listen") {
      // The second token will then be the port number, so convert that to an
      // unsigned short and return
      return stoi(stmt->tokens_[1]);
    }
  }
  return 0;
}

std::map<std::string, RequestHandler *> Config::get_handlers() {
  std::map<std::string, RequestHandler *> map;
  for(unsigned int i = 0; i < config->statements_.size(); i++) {
    NginxConfigStatement *stmt = config->statements_[i].get();
    if(stmt->tokens_[0] == "handler") {
      std::string handler_type = stmt->tokens_[1];
      std::string path = stmt->tokens_[2];
      RequestHandler *handler;
      if(handler_type == "static") {
        handler = new StaticHandler();
      } else if(handler_type == "echo") {
        handler = new EchoHandler();
      } else {
        continue;
      }
      handler->Configure(*stmt->child_block_.get());
      map[path] = handler;
    }
  }

  return map;
}


text:
package com.strobel.assembler.metadata;

import com.strobel.core.StringUtilities;
import com.strobel.core.VerifyArgument;
import com.strobel.util.ContractUtils;

import java.util.Collections;
import java.util.List;

/**
 * User: Mike Strobel
 * Date: 1/6/13
 * Time: 2:29 PM
 */
public abstract class MethodReference extends MemberReference implements IMethodSignature,
                                                                         IGenericParameterProvider,
                                                                         IGenericContext {
    protected final static String CONSTRUCTOR_NAME = "<init>";
    protected final static String STATIC_INITIALIZER_NAME = "<clinit>";

    // <editor-fold defaultstate="collapsed" desc="Signature">

    public abstract TypeReference getReturnType();

    public boolean hasParameters() {
        return !getParameters().isEmpty();
    }

    public abstract List<ParameterDefinition> getParameters();

    public List<TypeReference> getThrownTypes() {
        return Collections.emptyList();
    }

    @Override
    public void invalidateSignature() {
    }

    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="Method Attributes">

    @Override
    public boolean isSpecialName() {
        return CONSTRUCTOR_NAME.equals(getName()) ||
               STATIC_INITIALIZER_NAME.equals(getName());
    }

    @Override
    public boolean containsGenericParameters() {
        if (super.containsGenericParameters() || hasGenericParameters()) {
            return true;
        }

        if (getReturnType().containsGenericParameters()) {
            return true;
        }

        if (hasParameters()) {
            final List<ParameterDefinition> parameters = getParameters();

            for (int i = 0, n = parameters.size(); i < n; i++) {
                if (parameters.get(i).getParameterType().containsGenericParameters()) {
                    return true;
                }
            }
        }

        return false;
    }

    @Override
    public boolean isEquivalentTo(final MemberReference member) {
        if (super.isEquivalentTo(member)) {
            return true;
        }

        if (member instanceof MethodReference) {
            final MethodReference method = (MethodReference) member;

            return StringUtilities.equals(method.getName(), this.getName()) &&
                   StringUtilities.equals(method.getErasedSignature(), this.getErasedSignature()) &&
                   MetadataResolver.areEquivalent(method.getDeclaringType(), this.getDeclaringType());
        }

        return false;

    }

    @Override
    protected StringBuilder appendName(final StringBuilder sb, final boolean fullName, final boolean dottedName) {
        if (fullName) {
            final TypeReference declaringType = getDeclaringType();

            if (declaringType != null) {
                return declaringType.appendName(sb, true, false).append('.').append(getName());
            }
        }

        return sb.append(getName());
    }

    public boolean isConstructor() {
        return MethodDefinition.CONSTRUCTOR_NAME.equals(getName());
    }

    public boolean isTypeInitializer() {
        return MethodDefinition.STATIC_INITIALIZER_NAME.equals(getName());
    }

    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="Generics">

    public boolean isGenericMethod() {
        return hasGenericParameters();
    }

    @Override
    public boolean hasGenericParameters() {
        return !getGenericParameters().isEmpty();
    }

    @Override
    public boolean isGenericDefinition() {
        return hasGenericParameters() &&
               isDefinition();
    }

    public List<GenericParameter> getGenericParameters() {
        return Collections.emptyList();
    }

    @Override
    public GenericParameter findTypeVariable(final String name) {
        for (final GenericParameter genericParameter : getGenericParameters()) {
            if (StringUtilities.equals(genericParameter.getName(), name)) {
                return genericParameter;
            }
        }

        final TypeReference declaringType = getDeclaringType();

        if (declaringType != null) {
            return declaringType.findTypeVariable(name);
        }

        return null;
    }

    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="Member Resolution">

    public MethodDefinition resolve() {
        final TypeReference declaringType = getDeclaringType();

        if (declaringType == null)
            throw ContractUtils.unsupported();

        return declaringType.resolve(this);
    }

    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="Name and Signature Formatting">

    @Override
    public StringBuilder appendSignature(final StringBuilder sb) {
        return appendSignature(this, sb);
    }

    @Override
    public StringBuilder appendErasedSignature(final StringBuilder sb) {
        return appendErasedSignature(this, sb);
    }

    static StringBuilder appendSignature(final IMethodSignature method, final StringBuilder sb) {
        final List<ParameterDefinition> parameters = method.getParameters();

        StringBuilder s = sb;
        s.append('(');

        for (int i = 0, n = parameters.size(); i < n; ++i) {
            final ParameterDefinition p = parameters.get(i);
            s = p.getParameterType().appendSignature(s);
        }

        s.append(')');
        s = method.getReturnType().appendSignature(s);

        return s;
    }

    static StringBuilder appendErasedSignature(final IMethodSignature method, final StringBuilder sb) {
        StringBuilder s = sb;
        s.append('(');

        final List<ParameterDefinition> parameterTypes = method.getParameters();

        for (int i = 0, n = parameterTypes.size(); i < n; ++i) {
            s = parameterTypes.get(i).getParameterType().appendErasedSignature(s);
        }

        s.append(')');
        s = method.getReturnType().appendErasedSignature(s);

        return s;
    }

    // </editor-fold>
}


text:
// Package util implements various utility functions used in both testing and implementation
// of Kubernetes. Package util may not depend on any other package in the Kubernetes
// package tree.
package util


text:
AppEngineCodeLab
================

Code Lab for Google App Engine


text:
import functools
import math
import operator

from .utils import bound

def sieve_to_primes(sieve):
    """Accepts a zero-indexed sieve and returns all primes found."""
    primes = []
    for i in range(len(sieve)):
        if sieve[i]:
            primes.append(i)

    return primes

def eratosthenes(n):
    """Returns all primes in [2, n] using the Sieve of Eratosthenes."""
    n = bound(n)
    sieve = [True] * (n - 1) # represents 2 through n
    for d in range(2, int(math.sqrt(n)) + 1):
        focus = 2 * d
        while focus <= n:
            sieve[focus - 2] = False
            focus += d

    zero_indexed_sieve = 2 * [False] + sieve
    return sieve_to_primes(zero_indexed_sieve)

def wheel(n, basis):
    """Returns a relatively prime set in [2, n] using the Wheel Algorithm."""
    n = bound(n)
    size = functools.reduce(operator.mul, basis)
    wheel = []
    for x in range(0, n + size, size):
        wheel.append([True] * size)

    inside = wheel[0]
    prime_spokes = [p - 1 for p in basis] # subtract one for zero-indexing
    mults = [k for k in range(1, size + 1) if any([k % p == 0 for p in basis])]
    mult_spokes = [mult - 1 for mult in mults if mult not in basis]
    wheel[0][0] = False

    for x in range(len(wheel)):
        spokes = mult_spokes
        if x != 0:
            spokes.extend(prime_spokes)
        if x == 0:
            pass
        for spoke in spokes:
            wheel[x][spoke] = False

    flat_wheel = [False] + [value for circle in wheel for value in circle]
    return [k for k in sieve_to_primes(flat_wheel) if k <= n]


text:
/**
 *************************************************************************
 * @file   M4MCS_API.c
 * @brief  MCS implementation (Video Compressor Service)
 * @note   This file implements the API and the processing of the MCS
 *************************************************************************
 **/

/****************/
/*** Includes ***/
/****************/

/**
 * OSAL headers */
#include "M4OSA_Memory.h"   /**< OSAL memory management */
#include "M4OSA_Debug.h"    /**< OSAL debug management */

/* Our headers */
#include "M4MCS_API.h"
#include "M4MCS_ErrorCodes.h"
#include "M4MCS_InternalTypes.h"
#include "M4MCS_InternalConfig.h"
#include "M4MCS_InternalFunctions.h"

/* Common headers (for aac) */
#include "M4_Common.h"

#ifdef M4VSS_ENABLE_EXTERNAL_DECODERS
#include "M4VD_EXTERNAL_Interface.h"
#endif /* M4VSS_ENABLE_EXTERNAL_DECODERS */

/**
 ******************************************************************************
 * M4OSA_ERR M4MCS_intCheckAudioEffects(M4MCS_InternalContext* pContext)
 * @brief    Check if an effect has to be applied currently
 * @note    It is called by the stepEncoding function
 * @param    pContext    (IN) MCS internal context
 * @return    M4NO_ERROR:    No error
 ******************************************************************************
 */
M4OSA_ERR M4MCS_intCheckAudioEffects(M4MCS_InternalContext* pC)
{
    M4OSA_Int8 *pActiveEffectNumber = &(pC->pActiveEffectNumber);

    *pActiveEffectNumber = -1;

    if(pC->ReaderAudioAU.m_CTS > pC->uiBeginCutTime
    && pC->ReaderAudioAU.m_CTS < pC->uiEndCutTime)
    {
        M4OSA_UInt32 outputRelatedTime = 0;
        M4OSA_UInt8 uiEffectIndex = 0;
        outputRelatedTime =
        (M4OSA_UInt32)(pC->ReaderAudioAU.m_CTS  - pC->uiBeginCutTime + 0.5);

        for(uiEffectIndex=0; uiEffectIndex<pC->nbEffects; uiEffectIndex++)
        {
            if ((outputRelatedTime >=
                (M4OSA_UInt32)(pC->pEffects[uiEffectIndex].uiStartTime)) &&
                (outputRelatedTime <
                (M4OSA_UInt32)(pC->pEffects[uiEffectIndex].uiStartTime +\
                pC->pEffects[uiEffectIndex].uiDuration)))
            {
                *pActiveEffectNumber = uiEffectIndex;
                uiEffectIndex = pC->nbEffects;
            }
        }
    }

    return M4NO_ERROR;
}

/**
 ******************************************************************************
 * M4OSA_ERR M4MCS_editAudioEffectFct_FadeIn()
 * @brief    Apply audio effect FadeIn to pPCMdata
 * @param   pC            (IN/OUT) Internal edit context
 * @param    pPCMdata    (IN/OUT) Input and Output PCM audio data
 * @param    uiPCMsize    (IN)     Size of pPCMdata
 * @param    pProgress    (IN)     Effect progress
 * @return    M4NO_ERROR:             No error
 ******************************************************************************
 */
M4OSA_ERR M4MCS_editAudioEffectFct_FadeIn(  M4OSA_Void *pFunctionContext,
                                            M4OSA_Int16 *pPCMdata,
                                            M4OSA_UInt32 uiPCMsize,
                                            M4MCS_ExternalProgress *pProgress)
{
    /* we will cast each Int16 sample into this Int32 variable */
    M4OSA_Int32 i32sample;

    /**
     * Sanity check */
    if(pProgress->uiProgress > 1000)
    {
        pProgress->uiProgress = 1000;
    }

    /**
     * From buffer size (bytes) to number of sample (int16): divide by two */
    uiPCMsize >>= 1;

    /**
     * Loop on samples */
    while (uiPCMsize-->0) /**< decrementing to optimize */
    {
        i32sample = *pPCMdata;
        i32sample *= pProgress->uiProgress;
        i32sample /= 1000;
        *pPCMdata++ = (M4OSA_Int16)i32sample;
    }

    /**
     *    Return */
    M4OSA_TRACE3_0("M4MCS_editAudioEffectFct_FadeIn: returning M4NO_ERROR");
    return M4NO_ERROR;
}

/**
 ******************************************************************************
 * M4OSA_ERR M4MCS_editAudioEffectFct_FadeOut()
 * @brief    Apply audio effect FadeIn to pPCMdata
 * @param    pC            (IN/OUT) Internal edit context
 * @param    pPCMdata    (IN/OUT) Input and Output PCM audio data
 * @param    uiPCMsize    (IN)     Size of pPCMdata
 * @param    pProgress    (IN)     Effect progress
 * @return   M4NO_ERROR:             No error
 ******************************************************************************
 */
M4OSA_ERR M4MCS_editAudioEffectFct_FadeOut( M4OSA_Void *pFunctionContext,
                                            M4OSA_Int16 *pPCMdata,
                                            M4OSA_UInt32 uiPCMsize,
                                            M4MCS_ExternalProgress *pProgress)
{
    /* we will cast each Int16 sample into this Int32 variable */
    M4OSA_Int32 i32sample;

    /**
     * Sanity check */
    if(pProgress->uiProgress > 1000)
    {
        pProgress->uiProgress = 1000;
    }
    pProgress->uiProgress = 1000 - pProgress->uiProgress;

    /**
     * From buffer size (bytes) to number of sample (int16): divide by two */
    uiPCMsize >>= 1;

    /**
     * Loop on samples */
    while (uiPCMsize-->0) /**< decrementing to optimize */
    {
        i32sample = *pPCMdata;
        i32sample *= pProgress->uiProgress;
        i32sample /= 1000;
        *pPCMdata++ = (M4OSA_Int16)i32sample;
    }

    /**
     *    Return */
    M4OSA_TRACE3_0("M4MCS_editAudioEffectFct_FadeOut: returning M4NO_ERROR");
    return M4NO_ERROR;
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CSharpGL;

namespace ComputeShader.HelloComputeShader
{
    public partial class FormMain : Form
    {
        private Scene scene;
        private ActionList actionList;

        public FormMain()
        {
            InitializeComponent();

            this.Load += FormMain_Load;
            this.winGLCanvas1.OpenGLDraw += winGLCanvas1_OpenGLDraw;
            this.winGLCanvas1.Resize += winGLCanvas1_Resize;
        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            var position = new vec3(0, 0, 1);
            var center = new vec3(0, 0, 0);
            var up = new vec3(0, 1, 0);
            var camera = new Camera(position, center, up, CameraType.Perspective, this.winGLCanvas1.Width, this.winGLCanvas1.Height);
            this.scene = new Scene(camera)
;
            {
                var node = SimpleComputeNode.Create();
                this.scene.RootNode = node;
                this.propGrid.SelectedObject = node;
            }
            var list = new ActionList();
            var transformAction = new TransformAction(scene);
            list.Add(transformAction);
            var renderAction = new RenderAction(scene);
            list.Add(renderAction);
            this.actionList = list;
        }

        private void winGLCanvas1_OpenGLDraw(object sender, PaintEventArgs e)
        {
            ActionList list = this.actionList;
            if (list != null)
            {
                vec4 clearColor = this.scene.ClearColor;
                GL.Instance.ClearColor(clearColor.x, clearColor.y, clearColor.z, clearColor.w);
                GL.Instance.Clear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT | GL.GL_STENCIL_BUFFER_BIT);

                list.Act(new ActionParams(Viewport.GetCurrent()));
            }
        }

        void winGLCanvas1_Resize(object sender, EventArgs e)
        {
            this.scene.Camera.AspectRatio = ((float)this.winGLCanvas1.Width) / ((float)this.winGLCanvas1.Height);
        }

    }
}


text:
<!doctype html>

    <meta charset="utf-8">
    <title>training-while-marbles</title>

Rangement de billes

                  Programmer le robot pour qu'il ramasse lachaque bille et la mette dans le trou plus loin sur sa rangée.

                  Le robot ne peut transporter qu'une bille à la fois.

                     Vous aurez besoin d'utiliser
                     le bloc « répéter tant que » ou « répéter jusqu'à »,
                     le bloc « répéter jusqu'à »,
                     boucles for,
                     comme dans l'exemple ci-dessous.

                      ou

                     Ce type de boucle est utile lorsque l'on ne connaît pas à l'avance le nombre de répétitions. Ici, vous ne connaissez pas le nombre de cases entre la bille et le trou :Dans cette version, vous ne connaissez pas le nombre de lignes contenant une bille et un trou :

                     Ce sujet contient deux tests, avec une position différente pour le trouavec un nombre de billes différent. Votre programme doit fonctionner sur les deux.


text:
<?php

class GroepsactiviteitenIntakesController extends AppController
{
    public $name = 'GroepsactiviteitenIntakes';

    public function add_edit($persoon_model, $foreign_key)
    {
        if (!empty($this->data)) {
            if (empty($this->data['GroepsactiviteitenIntake']['id'])) {
                $this->GroepsactiviteitenIntake->create();
                $this->data['GroepsactiviteitenIntake']['model'] = $persoon_model;
                $this->data['GroepsactiviteitenIntake']['foreign_key'] = $foreign_key;
                $this->data['GroepsactiviteitenIntake']['medewerker_id'] = $this->Session->read('Auth.Medewerker.id');
            }

            $this->data['GroepsactiviteitenIntake']['gespreksverslag'] = nl2br(htmlentities($this->data['GroepsactiviteitenIntake']['gespreksverslag']));
            if ($this->GroepsactiviteitenIntake->save($this->data)) {
                $this->data['ZrmReport']['model'] = 'Intake';
                $this->data['ZrmReport']['foreign_key'] = $this->Intake->id;
                $this->data['ZrmReport']['klant_id'] = $klant_id;

                $this->ZrmReport->create();

                if ($this->ZrmReport->save($this->data)) {
                    $this->Intake->commit();
                    $this->flash(__('De intake is opgeslagen', true));
                    $this->redirect(array('controller' => 'klanten', 'action' => 'view', $klant_id));
                }

                $this->Session->setFlash(__('Success', true));
            } else {
                $this->Session->setFlash(__('Error', true));
            }
        }

        $this->redirect(array('controller' => 'Groepsactiviteiten', 'action' => 'intakes', $persoon_model, $foreign_key));
    }
}


text:
using System;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Debugger.Interop;
using NSubstitute;
using NUnit.Framework;
using YetiCommon;
using YetiVSI.DebugEngine;
using YetiVSI.DebugEngine.Exit;
using YetiVSI.ProjectSystem.Abstractions;

namespace YetiVSI.Test.DebugEngine
{
    [TestFixture]
    partial class DebugEngineTests
    {
        [Test]
        public async Task LaunchSuspendedWhenBothArgsAndOptionsCoreFilePathEmptyFailsAsync(
            [Values("", null)] string args,
            [Values("{}", "{\"CoreFilePath\":\"\"}")] string options)
        {
            await _mainThreadContext.JoinableTaskContext.Factory.SwitchToMainThreadAsync();

            var debugSessionLauncherFactory = Substitute.For<IDebugSessionLauncherFactory>();
            IGgpDebugEngine debugEngine = CreateGgpDebugEngine(debugSessionLauncherFactory);
            int result = debugEngine.LaunchSuspended("", null, _exePath, args, null, null, options,
                                                     enum_LAUNCH_FLAGS.LAUNCH_DEBUG, 0, 0, 0, null,
                                                     out var _);
            Assert.That(result, Is.EqualTo(VSConstants.E_FAIL));
        }

        [Test]
        public async Task
        LaunchSuspendedWhenOptionsNullAndArgsEmptySucceedsAsync([Values("", null)] string args)
        {
            await _mainThreadContext.JoinableTaskContext.Factory.SwitchToMainThreadAsync();

            var debugSessionLauncherFactory = Substitute.For<IDebugSessionLauncherFactory>();
            IGgpDebugEngine debugEngine = CreateGgpDebugEngine(debugSessionLauncherFactory);
            string options = null;
            var debugPort = Substitute.For<IDebugPort2>();
            int result = debugEngine.LaunchSuspended("", debugPort, _exePath, args, null, null,
                                                     options, enum_LAUNCH_FLAGS.LAUNCH_DEBUG, 0, 0,
                                                     0, null, out var _);
            Assert.That(result, Is.EqualTo(VSConstants.S_OK));

            ReleaseTransportSession(debugEngine);
        }

        [Test]
        public async Task LaunchSuspendedWhenEndpointSetSucceedsAsync(
            [Values(StadiaEndpoint.AnyEndpoint, StadiaEndpoint.PlayerEndpoint,
                    StadiaEndpoint.TestClient)] StadiaEndpoint endpoint)
        {
            await _mainThreadContext.JoinableTaskContext.Factory.SwitchToMainThreadAsync();

            var debugSessionLauncherFactory = Substitute.For<IDebugSessionLauncherFactory>();
            IGgpDebugEngine debugEngine = CreateGgpDebugEngine(debugSessionLauncherFactory);
            string options = null;
            var launchParams = new LaunchParams { Endpoint = endpoint };
            string args = Convert.ToBase64String(
                Encoding.UTF8.GetBytes(new JsonUtil().Serialize(launchParams)));
            var debugPort = Substitute.For<IDebugPort2>();
            int result = debugEngine.LaunchSuspended("", debugPort, _exePath, args, null, null,
                                                     options, enum_LAUNCH_FLAGS.LAUNCH_DEBUG, 0, 0,
                                                     0, null, out var _);
            Assert.That(result, Is.EqualTo(VSConstants.S_OK));

            ReleaseTransportSession(debugEngine);
        }
    }

}


text:
use juniper::GraphQLInputObject;

#[derive(GraphQLInputObject)]
struct Object {
    test: String,
    #[graphql(name = "test")]
    test2: String,
}

fn main() {}