component extends="org.lucee.cfml.test.LuceeTestCase"{
	function run( testResults , testBox ) {
		describe( "Test suite for LDEV-1167", function() {
			it(title="checking WDDX tag, with action = 'wddx2cfml' when the struct empty ", body = function( currentSpec ) {
				var myWDDX = "<wddxPacket version='1.0'><header/><data><struct type='coldfusion.server.ConfigMap'/></data></wddxPacket>";
				cfwddx( action='wddx2cfml', input=myWDDX, output='local.myData');
				expect(local.myData).toBeTypeOf('struct')
			});

			it(title="checking WDDX tag, with action = 'wddx2cfml' when the query empty ", body = function( currentSpec ) {
				myWDDX = "<wddxPacket version='1.0'><header/><data><recordset rowCount='0' fieldNames='id,name' type='coldfusion.sql.QueryTable'><field name='id'></field><field name='name'></field></recordset></data></wddxPacket>";
				cfwddx( action='wddx2cfml', input=myWDDX, output='local.myData');
				expect(local.myData).toBeTypeOf('query')
			});
		});
	}
}


component
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public void function up()
    {
        var table = schema('tblEPOS_Items');
        table.foreign('eiNomID').references('tblEPOS_Account', 'eaID').onDelete('restrict');
        table.update();
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public void function down()
    {
        schema('tblEPOS_Items').dropForeign('eiNomID');
    }
}


;; @file macros.cl
;;
;; @breif Examples using macros
;;

; `progn` implementation with lambda function
(defmacro progn1 (&rest body)
  `(funcall (lambda () ,@body)))
; `when` macro
(defmacro when1 (condition &rest body)
  `(if ,condition (progn1 ,@body)))
; `unless` macro
(defmacro unless1 (condition &rest body)
  `(if (not ,condition) (progn1 ,@body)))
; `cond` macro
(defmacro cond1 (&rest branches)
  `(dolist (branch ,branches)
    (let ((condition (pop branch)) (body branch))
      (if condition (progn @body) break))))

Fix `cond` macro, usable now

;; @file macros.cl
;;
;; @breif Examples using macros
;;

; `progn` implementation with lambda function
(defmacro progn1 (&rest body)
  `(funcall (lambda () ,@body)))
; `when` macro
(defmacro when1 (condition &rest body)
  `(if ,condition (progn1 ,@body)))
; `unless` macro
(defmacro unless1 (condition &rest body)
  `(if (not ,condition) (progn1 ,@body)))
; `cond1` macro
(defmacro cond1 ((condition body))
  (let ((condition-value condition))
    (when condition-value `(progn ,body ,condition-value))))
; `cond` macro
(defmacro cond-a (&body branches)
  (dolist (branch branches)
    (let ((condition (pop branch)) (body branch))
      (when condition (return `(progn ,@body))))))
(defmacro cond-b (&body branches)
  (with-gensyms (branch condition body)
    (dolist (branch branches)
      (let ((condition (pop branch)) (body branch))
        (when condition (return `(progn ,@body)))))))


kernel
void test_convert_sat_regression() {
    volatile long2 input = (long2)(0, 1);
    uint2 res = convert_uint2_sat(input);
    if (res[0] != 0 || res[1] != 1) {
        printf("expected (0, 1), got (%x, %x)\n", res[0], res[1]);
    }
}

Test 'long's only if target has them.

kernel
void test_convert_sat_regression() {
#ifdef cles_khr_int64
    volatile long2 input = (long2)(0, 1);
    uint2 res = convert_uint2_sat(input);
    if (res[0] != 0 || res[1] != 1) {
        printf("expected (0, 1), got (%x, %x)\n", res[0], res[1]);
    }
#endif
}


__constant sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_CLAMP | CLK_FILTER_NEAREST;

__kernel void renderToTexture(
        __global float* inputTensor,
        __write_only image2d_t output,
        __constant float* colors,
        __private float minConfidence,
        __private float maxOpacity,
        __private int channels
) {
    const int2 position = {get_global_id(0), get_global_id(1)};

    float4 color = {0.0f, 0.0f, 0.0f, 0.0f};
    // TODO blend colorsd
    for(int channel = 0; channel < channels; ++channel) { // TODO skip first?
        float intensity = inputTensor[(position.x + position.y*get_global_size(0))*channels + channel];
        //printf("confidence of channel %d: %f\n", channel, intensity);
        intensity = clamp(intensity, 0.0f, 1.0f);

        if(intensity < minConfidence) {
            intensity = 0;
        } else {
            intensity *= maxOpacity;
            float3 colorToUse = vload3(channel, colors);
            color = color + 1.0f * colorToUse.xyzz;
            color.w = intensity;
            color = clamp(color, 0.0f, 1.0f);
            //printf("%f %f %f\n", color.x, color.y, color.z);
        }
    }
    write_imagef(output, (int2)(position.x, get_image_height(output) - position.y - 1), color);
}

Use transparent white as default color in heatmap renderer

__constant sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_CLAMP | CLK_FILTER_NEAREST;

__kernel void renderToTexture(
        __global float* inputTensor,
        __write_only image2d_t output,
        __constant float* colors,
        __private float minConfidence,
        __private float maxOpacity,
        __private int channels
) {
    const int2 position = {get_global_id(0), get_global_id(1)};

    float4 color = {1.0f, 1.0f, 1.0f, 0.0f};
    // TODO blend colorsd
    for(int channel = 0; channel < channels; ++channel) { // TODO skip first?
        float intensity = inputTensor[(position.x + position.y*get_global_size(0))*channels + channel];
        //printf("confidence of channel %d: %f\n", channel, intensity);
        intensity = clamp(intensity, 0.0f, 1.0f);

        if(intensity < minConfidence) {
            intensity = 0;
        } else {
            intensity *= maxOpacity;
            float3 colorToUse = vload3(channel, colors);
            color = colorToUse.xyzz;
            color.w = intensity;
            color = clamp(color, 0.0f, 1.0f);
            //printf("%f %f %f\n", color.x, color.y, color.z);
        }
    }
    write_imagef(output, (int2)(position.x, get_image_height(output) - position.y - 1), color);
}


// Test this without pch.
// RUN: %clang_cc1 -include %S/ocl_types.h -fsyntax-only %s -cl-std=CL2.0 -D__OPENCL_VERSION__=200

// Test with pch.
// RUN: %clang_cc1 -x cl -emit-pch -o %t %S/ocl_types.h -cl-std=CL2.0 -D__OPENCL_VERSION__=200
// RUN: %clang_cc1 -include-pch %t -fsyntax-only %s -ast-print -cl-std=CL2.0 -D__OPENCL_VERSION__=200

void foo1(img1d_t img);

void foo2(img1darr_t img);

void foo3(img1dbuff_t img);

void foo4(img2d_t img);

void foo5(img2darr_t img);

void foo6(img3d_t img);

void foo7(smp_t smp) {
  smp_t loc_smp;
}

void foo8(evt_t evt) {
  evt_t loc_evt;
}

#if __OPENCL_VERSION__ >= 200

void foo9(pipe int P) {
  int_pipe_function(P);
}

void foo10(pipe Person P) {
  person_pipe_function(P);
}

#endif

Fix a lit test issue exposed by r290056

// Test this without pch.
// RUN: %clang_cc1 -triple spir-unknown-unknown -include %S/ocl_types.h -fsyntax-only %s -cl-std=CL2.0 -D__OPENCL_VERSION__=200

// Test with pch.
// RUN: %clang_cc1 -triple spir-unknown-unknown -x cl -emit-pch -o %t %S/ocl_types.h -cl-std=CL2.0 -D__OPENCL_VERSION__=200
// RUN: %clang_cc1 -triple spir-unknown-unknown -include-pch %t -fsyntax-only %s -ast-print -cl-std=CL2.0 -D__OPENCL_VERSION__=200

void foo1(img1d_t img);

void foo2(img1darr_t img);

void foo3(img1dbuff_t img);

void foo4(img2d_t img);

void foo5(img2darr_t img);

void foo6(img3d_t img);

void foo7(smp_t smp) {
  smp_t loc_smp;
}

void foo8(evt_t evt) {
  evt_t loc_evt;
}

#if __OPENCL_VERSION__ >= 200

void foo9(pipe int P) {
  int_pipe_function(P);
}

void foo10(pipe Person P) {
  person_pipe_function(P);
}

#endif


kernel
void test_fmin_fmax_fma() {
    volatile float2 a = (float2)(-1.0f, -2.2f);
    volatile float2 b = (float2)(-3.1f, fma(a[0], -4.2f, a[1]));
    float2 max_ = fmax(a, b);
    float2 min_ = fmin(a, b);
    if ((int)max_[0] == -3 && (int)max_[1] == 8 &&
        (int)min_[0] == 1 && (int)min_[1] == 2)
        printf("OK\n");
}

Fix tests/fmin_fmax_fma - was accessing vector elements with

kernel
void test_fmin_fmax_fma()
{
    volatile float2 a = (float2)(-1.0f, -2.2f);
    volatile float c = fma(a.x, -4.2f, a.y);
    volatile float2 b = (float2)(-3.1f, c);

    float2 max_ = fmax(a, b);

    float2 min_ = fmin(a, b);

    if (((int)max_.x == -3) && ((int)max_.y == 8) &&
        ((int)min_.x == 1) && ((int)min_.y == 2))
    {

        printf("OK\n");
    }
}


#!/usr/bin/env sbcl

(require :asdf)

(defconstant *freebsd-type* "FreeBSD")

;-- MAIN

(format t "Hello World!~%")

Install a few basic packages on FreeBSD

#!/usr/bin/env sbcl

(require :asdf)

(defconstant *freebsd-type* "FreeBSD")

(defun freebsd-update ()
  (format t "Checking for FreeBSD patches~%")
  (uiop:run-program (list "/usr/sbin/freebsd-update" "Fetch") :ignore-error-status t)
  (uiop:run-program (list "/usr/sbin/freebsd-update" "install") :ignore-error-status t))

(defun portsnap-fetch-update ()
  (format t "Portsnap refresh of ports~%")
  (uiop:run-program (list "/usr/sbin/portsnap" "--interactive" "fetch" "update") :output nil))

(defun cmd-package-install (a-package)
  (cond ((string= (software-type) *freebsd-type*)
         (format t "FreeBSD pkg installing ~s~%" a-package)
         (uiop:run-program `("/usr/sbin/pkg" "install" "-yqU" ,a-package)))
        (t (error "Platform ~s (~s) on ~s is not supported~%" (software-type) (software-version) (machine-type)))))

(defun cmd-package (a-command a-package)
  (cond ((string= a-command "install") (cmd-package-install a-package))))

;-- MAIN

(format t "Hello World!~%")
(freebsd-update)
(dolist (p '("curl" "git" "bzip2" "zip" "unzip" "bash" "gnutls"))
  (cmd-package "install" p))

(portsnap-fetch-update)
(format t "Installing nginx~%")
(uiop:chdir "/usr/ports/www/nginx-devel")
(uiop:run-program (list "/usr/bin/make" "-DWITH=\"HTTPV2\"" "install" "clean" "BATCH=yes"))


kernel void test_sizeof() {
    printf("sizeof(uint) == %lu\n", sizeof(uint));
    printf("sizeof(uint2) == %lu\n", sizeof(uint2));
    printf("sizeof(uint3) == %lu\n", sizeof(uint3));
    printf("sizeof(uint4) == %lu\n", sizeof(uint4));
    printf("sizeof(uint8) == %lu\n", sizeof(uint8));
    printf("sizeof(uint16) == %lu\n", sizeof(uint16));
}

Fix the sizeof test for __EMBEDDED_PROFILE__. In this mode the 64-bit long ints might not be available and Clang produced a warning (tested on my Pentium4).

kernel void test_sizeof() {
#ifdef __EMBEDDED_PROFILE__
// 64-bit longs might not be available
    printf("sizeof(uint) == %d\n", (int)sizeof(uint));
    printf("sizeof(uint2) == %d\n", (int)sizeof(uint2));
    printf("sizeof(uint3) == %d\n", (int)sizeof(uint3));
    printf("sizeof(uint4) == %d\n", (int)sizeof(uint4));
    printf("sizeof(uint8) == %d\n", (int)sizeof(uint8));
    printf("sizeof(uint16) == %d\n", (int)sizeof(uint16));
#else
    printf("sizeof(uint) == %lu\n", sizeof(uint));
    printf("sizeof(uint2) == %lu\n", sizeof(uint2));
    printf("sizeof(uint3) == %lu\n", sizeof(uint3));
    printf("sizeof(uint4) == %lu\n", sizeof(uint4));
    printf("sizeof(uint8) == %lu\n", sizeof(uint8));
    printf("sizeof(uint16) == %lu\n", sizeof(uint16));
#endif
}


/*
* Multiply a vector by a sparse matrix and get the resultant
* vector.
* The global # of work items will be equal to the number rows in the
* sparse matrix, which is assumed to be square (what would happen if it wasn't?)
*/
__kernel void sparseMatVec(int nVals, __global int *rows, __global int *cols,
	__global float *vals, __global float *vec, __global float *res)
{
	int id = get_global_id(0);
	//We use these to select the range of i to read our row's values from (row # == id)
	int startIdx = -1;
	int endIdx = -1;
	//Determine the indices containing the values for the row this kernel will be working on
	for (int i = id; i < nVals; ++i){
		if (rows[i] == id && startIdx == -1)
			startIdx = i;
		if (rows[i] == id + 1 && endIdx == -1){
			endIdx = i - 1;
			break;
		}
		if (i == nVals - 1 && endIdx == -1)
			endIdx = i;
	}
	float sum = 0.0f;
	for (int i = startIdx; i <= endIdx; ++i)
			sum += vals[i] * vec[cols[i]];

	res[id] = sum;
}

Make sure the startIdx is set before setting endIdx

/*
* Multiply a vector by a sparse matrix and get the resultant
* vector.
* The global # of work items will be equal to the number rows in the
* sparse matrix, which is assumed to be square (what would happen if it wasn't?)
*/
__kernel void sparseMatVec(int nVals, __global int *rows, __global int *cols,
	__global float *vals, __global float *vec, __global float *res)
{
	int id = get_global_id(0);
	//We use these to select the range of i to read our row's values from (row # == id)
	int startIdx = -1;
	int endIdx = -1;
	//Determine the indices containing the values for the row this kernel will be working on
	for (int i = id; i < nVals; ++i){
		if (rows[i] == id && startIdx == -1)
			startIdx = i;
		if (rows[i] == id + 1 && startIdx != -1 && endIdx == -1){
			endIdx = i - 1;
			break;
		}
		if (i == nVals - 1 && startIdx != -1 && endIdx == -1)
			endIdx = i;
	}
	float sum = 0.0f;
	for (int i = startIdx; i <= endIdx; ++i)
			sum += vals[i] * vec[cols[i]];

	res[id] = sum;
}


// REQUIRES: amdgpu-registered-target
// UNSUPPORTED: system-darwin
// RUN: not %clang_cc1 -emit-codegen-only -triple=amdgcn-- %s 2>&1 | FileCheck %s

// CHECK: error: local memory limit exceeded (480000) in use_huge_lds
kernel void use_huge_lds()
{
    volatile local int huge[120000];
    huge[0] = 2;
}

Revert "Mark test as unsupported until r315808 is fixed"

// REQUIRES: amdgpu-registered-target
// RUN: not %clang_cc1 -emit-codegen-only -triple=amdgcn-- %s 2>&1 | FileCheck %s

// CHECK: error: local memory limit exceeded (480000) in use_huge_lds
kernel void use_huge_lds()
{
    volatile local int huge[120000];
    huge[0] = 2;
}


include node-core
main = do
  data <- readFile process.argv[2]
  writeFile process.argv[3] data

Update test without inbuilt `readFile` and `writeFile` methods

include node-core

fs = require 'fs'

main = do
  err data <- IO (fs.readFile process.argv[2] 'utf8')
  maybeErr err (putLine err)
  err1 <- IO (fs.writeFile process.argv[3] data)
  maybeErr err1 (putLine err1)


// RUN: %clang_cc1 -emit-llvm -O0 -o - %s | FileCheck %s

typedef float float4 __attribute__((ext_vector_type(4)));

kernel __attribute__((reqd_work_group_size(1,2,4))) void kernel1(int a) {}

kernel __attribute__((work_group_size_hint(8,16,32))) void kernel2(float4 a) {}

// CHECK: opencl.kernels = !{[[MDNODE0:![0-9]+]], [[MDNODE3:![0-9]+]]}

// CHECK: [[MDNODE0]] = metadata !{void (i32)* @kernel1, metadata [[MDNODE2:![0-9]+]]}
// CHECK: [[MDNODE2]] = metadata !{metadata !"reqd_work_group_size", i32 1, i32 2, i32 4}
// CHECK: [[MDNODE3]] = metadata !{void (<4 x float>)* @kernel2, metadata [[MDNODE5:![0-9]+]]}
// CHECK: [[MDNODE5]] = metadata !{metadata !"work_group_size_hint", i32 8, i32 16, i32 32}

Fix the test case. Now it does not depend on the method used to pass vector arguments to the function. Reviewed by Anton Lokhmotov.

// RUN: %clang_cc1 -emit-llvm -O0 -o - %s | FileCheck %s

kernel __attribute__((reqd_work_group_size(1,2,4))) void kernel1(int a) {}

kernel __attribute__((work_group_size_hint(8,16,32))) void kernel2(int a) {}

// CHECK: opencl.kernels = !{[[MDNODE0:![0-9]+]], [[MDNODE3:![0-9]+]]}

// CHECK: [[MDNODE0]] = metadata !{void (i32)* @kernel1, metadata [[MDNODE2:![0-9]+]]}
// CHECK: [[MDNODE2]] = metadata !{metadata !"reqd_work_group_size", i32 1, i32 2, i32 4}
// CHECK: [[MDNODE3]] = metadata !{void (i32)* @kernel2, metadata [[MDNODE5:![0-9]+]]}
// CHECK: [[MDNODE5]] = metadata !{metadata !"work_group_size_hint", i32 8, i32 16, i32 32}


// RUN: %clang_cc1 %s -emit-llvm -o %t

typedef __attribute__((ext_vector_type(8)))  unsigned char uchar8;
typedef __attribute__((ext_vector_type(4)))  unsigned long ulong4;
typedef __attribute__((ext_vector_type(16))) unsigned char uchar16;

// OpenCL allows vectors to be initialized by vectors Handle bug in
// VisitInitListExpr for this case below.
void foo( ulong4 v )
{
  uchar8 val[4] = {{(uchar8){((uchar16)(v.lo)).lo}}};
}

Modify test for 32 and 64 bit.

// RUN: %clang_cc1 %s -emit-llvm -o %t

typedef __attribute__((ext_vector_type(4)))  unsigned char uchar4;
typedef __attribute__((ext_vector_type(4)))  unsigned int int4;
typedef __attribute__((ext_vector_type(8))) unsigned char uchar8;

// OpenCL allows vectors to be initialized by vectors Handle bug in
// VisitInitListExpr for this case below.
void foo( int4 v )
{
  uchar4 val[4] = {{(uchar4){((uchar8)(v.lo)).lo}}};
}


// RUN: rm %S/cl-strict-aliasing.ll
// RUN: %clang_cc1 -x cl -emit-llvm -cl-strict-aliasing < %s

Revert r229409: "Hack to try deleting file from build bots"


// RUN: %clang -### -target amdgcn-- -mcpu=gfx803 %s 2>&1 | FileCheck %s
// RUN: %clang -### -target amdgcn-amd- -mcpu=gfx803 %s 2>&1 | FileCheck %s
// RUN: %clang -### -target amdgcn-amd-amdhsa -mcpu=gfx803 %s 2>&1 | FileCheck %s
// RUN: %clang -### -target amdgcn-amd-amdpal -mcpu=gfx803 %s 2>&1 | FileCheck %s
// RUN: %clang -### -target amdgcn-amd-mesa3d -mcpu=gfx803 %s 2>&1 | FileCheck %s

// CHECK: clang{{.*}} "-mrelocation-model" "pic" "-pic-level" "1"

Add -no-canonical-prefixes to allow different build modes.

// RUN: %clang -no-canonical-prefixes -### -target amdgcn-- -mcpu=gfx803 %s 2>&1 | FileCheck %s
// RUN: %clang -no-canonical-prefixes -### -target amdgcn-amd- -mcpu=gfx803 %s 2>&1 | FileCheck %s
// RUN: %clang -no-canonical-prefixes -### -target amdgcn-amd-amdhsa -mcpu=gfx803 %s 2>&1 | FileCheck %s
// RUN: %clang -no-canonical-prefixes -### -target amdgcn-amd-amdpal -mcpu=gfx803 %s 2>&1 | FileCheck %s
// RUN: %clang -no-canonical-prefixes -### -target amdgcn-amd-mesa3d -mcpu=gfx803 %s 2>&1 | FileCheck %s

// CHECK: clang{{.*}} "-mrelocation-model" "pic" "-pic-level" "1"


/*******************************************************
 * Copyright (c) 2014, ArrayFire
 * All rights reserved.
 *
 * This file is distributed under 3-clause BSD license.
 * The complete license agreement can be obtained at:
 * http://arrayfire.com/licenses/BSD-3-Clause
 ********************************************************/

#if CPLX
#define sabs(in) ((in.x)*(in.x) + (in.y)*(in.y))
#else
#define sabs(in) in
#endif

#ifdef MIN_OP
void binOp(T *lhs, uint *lidx, T rhs, uint ridx)
{
    if ((*lhs > rhs) ||
        (*lhs == rhs && *lidx < ridx)) {
        *lhs = rhs;
        *lidx = ridx;
    }
}
#endif

#ifdef MAX_OP
void binOp(T *lhs, uint *lidx, T rhs, uint ridx)
{
    if ((*lhs < rhs) ||
        (*lhs == rhs && *lidx > ridx)) {
        *lhs = rhs;
        *lidx = ridx;
    }
}
#endif

Fix indexed reductions with complex types in OpenCL backend

/*******************************************************
 * Copyright (c) 2014, ArrayFire
 * All rights reserved.
 *
 * This file is distributed under 3-clause BSD license.
 * The complete license agreement can be obtained at:
 * http://arrayfire.com/licenses/BSD-3-Clause
 ********************************************************/

#if CPLX
#define sabs(in) ((in.x)*(in.x) + (in.y)*(in.y))
#ifdef MIN_OP
void binOp(T *lhs, uint *lidx, T rhs, uint ridx)
{
    if ((sabs(lhs[0]) > sabs(rhs)) ||
        (sabs(lhs[0]) == sabs(rhs) && *lidx < ridx)) {
        *lhs = rhs;
        *lidx = ridx;
    }
}
#endif

#ifdef MAX_OP
void binOp(T *lhs, uint *lidx, T rhs, uint ridx)
{
    if ((sabs(lhs[0]) < sabs(rhs)) ||
        (sabs(lhs[0]) == sabs(rhs) && *lidx > ridx)) {
        *lhs = rhs;
        *lidx = ridx;
    }
}
#endif
#else
#define sabs(in) in
#ifdef MIN_OP
void binOp(T *lhs, uint *lidx, T rhs, uint ridx)
{
    if ((*lhs > rhs) ||
        (*lhs == rhs && *lidx < ridx)) {
        *lhs = rhs;
        *lidx = ridx;
    }
}
#endif

#ifdef MAX_OP
void binOp(T *lhs, uint *lidx, T rhs, uint ridx)
{
    if ((*lhs < rhs) ||
        (*lhs == rhs && *lidx > ridx)) {
        *lhs = rhs;
        *lidx = ridx;
    }
}
#endif
#endif


; I tested this code with GNU CLISP 2.49 running on x64 Ubuntu.
;
; $ clisp multi.cl
;
; Eli Bendersky [http://eli.thegreenplace.net]
; This code is in the public domain.
(defclass Shape () ())

(defclass Rectangle (Shape) ())

(defclass Ellipse (Shape) ())

(defclass Triangle (Shape) ())

(defmethod name ((shape Shape))
  (type-of shape))

(defmethod intersect ((r Rectangle) (e Ellipse))
  (format t "Rectangle x Ellipse [names r=~a, e=~a]~&" (name r) (name e)))

(defmethod intersect ((r1 Rectangle) (r2 Rectangle))
  (format t "Rectangle x Rectangle [names r1=~a, r2=~a]~&" (name r1) (name r2)))

(defmethod intersect ((r Rectangle) (s Shape))
  (format t "Rectangle x Shape [names r=~a, s=~a]~&" (name r) (name s)))

(setf r1 (make-instance 'Rectangle))
(setf r2 (make-instance 'Rectangle))
(setf e1 (make-instance 'Ellipse))
(setf t1 (make-instance 'Triangle))

(intersect r1 e1)
(intersect r1 r2)
(intersect r1 t1)

Reformat the CL example a bit and clean up

;;; I tested this code with GNU CLISP 2.49 running on x64 Ubuntu.
;;;
;;; $ clisp multi.cl
;;;
;;; Eli Bendersky [http://eli.thegreenplace.net]
;;; This code is in the public domain.

(defclass Shape () ())
(defclass Rectangle (Shape) ())
(defclass Ellipse (Shape) ())
(defclass Triangle (Shape) ())

(defmethod intersect ((r Rectangle) (e Ellipse))
  (format t "Rectangle x Ellipse [names r=~a, e=~a]~&"
          (type-of r) (type-of e)))

(defmethod intersect ((r1 Rectangle) (r2 Rectangle))
  (format t "Rectangle x Rectangle [names r1=~a, r2=~a]~&"
          (type-of r1) (type-of r2)))

(defmethod intersect ((r Rectangle) (s Shape))
  (format t "Rectangle x Shape [names r=~a, s=~a]~&"
          (type-of r) (type-of s)))

(setf r1 (make-instance 'Rectangle))
(setf r2 (make-instance 'Rectangle))
(setf e1 (make-instance 'Ellipse))
(setf t1 (make-instance 'Triangle))

(intersect r1 e1)
(intersect r1 r2)
(intersect r1 t1)


extern void externFunc(global float *a);

kernel void externFunction(global float *a)
{
  a[0] = externFunc(a);
}

Fix a false positive (test passed, but for the wrong reason)

extern float externFunc(global float *a);

kernel void externFunction(global float *a)
{
  a[0] = externFunc(a);
}


// Global parameters that will be set via a template during compilation time.
__constant unsigned int frameW = 512;
__constant unsigned int frameH = 512;
__constant float texelStepX = 1.0 / 512.0;
__constant float texelStepY = 1.0 / 512.0;

// Emit the color of a pixel by tracing a ray through the scene.
__kernel void tracePixel(
		__global float4 *frameBuffer,
		__global float4 *frustrumCorners,
		const unsigned int blockY,
		const unsigned int samplesPerPixel,
		const float exposure
){
	// Get pixel coordinates
	unsigned int x = get_global_id(0);
	unsigned int y = blockY + get_global_id(1);
	if ( x > frameW || y > frameH ) {
		return;
	}

	// Just set target to white
	frameBuffer[y * frameW + x] = 1.0;
}

Interpolate x,y coordinates to test kernel output

// Global parameters that will be set via a template during compilation time.
__constant unsigned int frameW = 512;
__constant unsigned int frameH = 512;
__constant float texelStepX = 1.0 / 512.0;
__constant float texelStepY = 1.0 / 512.0;

// Emit the color of a pixel by tracing a ray through the scene.
__kernel void tracePixel(
		__global float4 *frameBuffer,
		__global float4 *frustrumCorners,
		const unsigned int blockY,
		const unsigned int samplesPerPixel,
		const float exposure
){
	// Get pixel coordinates
	unsigned int x = get_global_id(0);
	unsigned int y = get_global_id(1);
	if ( x > frameW || y > frameH ) {
		return;
	}

	// Just interpolate the x,y coordinates
	float tx = (float)(x) * texelStepX;
	float ty = (float)(y) * texelStepY;
	frameBuffer[y * frameW + x] = (float4)(tx, ty, 0, 0.0);
}


// Valid combinations
// RUN: clspv %s -pod-pushconstant -global-offset 2>&1
// RUN: clspv %s -pod-ubo -global-offset-push-constant 2>&1
// RUN: clspv %s -pod-ubo -cl-std=CL2.0 -inline-entry-points 2>&1

// POD args cannot be push constants if there are module scope push constants
// RUN: not clspv %s -pod-pushconstant -global-offset-push-constant 2>&1 | FileCheck %s
// RUN: not clspv %s -pod-pushconstant -cl-std=CL2.0 -inline-entry-points 2>&1 | FileCheck %s
// CHECK: POD arguments as push constants are not compatible with module scope push constants

Add output file to successful tests

// Valid combinations
// RUN: clspv %s -o %t.spv -pod-pushconstant -global-offset 2>&1
// RUN: clspv %s -o %t.spv -pod-ubo -global-offset-push-constant 2>&1
// RUN: clspv %s -o %t.spv -pod-ubo -cl-std=CL2.0 -inline-entry-points 2>&1

// POD args cannot be push constants if there are module scope push constants
// RUN: not clspv %s -pod-pushconstant -global-offset-push-constant 2>&1 | FileCheck %s
// RUN: not clspv %s -pod-pushconstant -cl-std=CL2.0 -inline-entry-points 2>&1 | FileCheck %s
// CHECK: POD arguments as push constants are not compatible with module scope push constants


kernel void test_kernel() {
  printf("global: %zd-%zd-%zd\n",
           get_global_id(0),
           get_global_id(1),
           get_global_id(2));
  printf("local: %zd-%zd-%zd\n",
           get_local_id(0),
           get_local_id(1),
           get_local_id(2));
}

Correct printf usage in test case

kernel void test_kernel() {
  printf("global: %d-%d-%d\n",
           (int)get_global_id(0),
           (int)get_global_id(1),
           (int)get_global_id(2));
  printf("local: %d-%d-%d\n",
           (int)get_local_id(0),
           (int)get_local_id(1),
           (int)get_local_id(2));
}


void output(float (^op)(float))
{
  printf("op(1)=%f\n", op(1.0f));
}

kernel void test_block()
{
  // Two simple tests
  float (^add1)(float) = ^(float x) { return x + 1.0f; };
  float (^mul2)(float) = ^(float x) { return x * 2.0f; };
  output(add1);
  output(mul2);

  // Capture a pointer to a local variable
  float counter = 0.0f;
  float* counterp = &counter;
  float (^stepcounter)(float) = ^(float x) {
    return *counterp += x;
  };
  output(stepcounter);
  output(stepcounter);
}


Add test for program scope variable restrictions in OpenCL v2.0

// RUN: %clang_cc1 %s -verify -pedantic -fsyntax-only -DCL20 -cl-std=CL2.0

static constant int G1 = 0;
int G2 = 0;// expected-error{{program scope variable must reside in global or constant address space}}
global int G3 = 0;
local int G4 = 0;// expected-error{{program scope variable must reside in global or constant address space}}

void kernel foo() {
  static int S1 = 5;// expected-error{{program scope variable must reside in global or constant address space}}
  static global int S2 = 5;
  static private int S3 = 5;// expected-error{{program scope variable must reside in global or constant address space}}

  constant int L1 = 0;
  local int L2;
}


Add the lit test for image size which was omitted by r277647.

// RUN: %clang_cc1 -emit-llvm -o - -triple amdgcn--amdhsa %s | FileCheck --check-prefix=AMDGCN %s
// RUN: %clang_cc1 -emit-llvm -o - -triple spir-unknown-unknown %s | FileCheck --check-prefix=SPIR %s

#ifdef __AMDGCN__

constant int* convert(image2d_t img) {
  // AMDGCN: bitcast %opencl.image2d_ro_t addrspace(2)* %img to i32 addrspace(2)*
  return __builtin_astype(img, constant int*);
}

#else

global int* convert(image2d_t img) {
  // SPIR: bitcast %opencl.image2d_ro_t addrspace(1)* %img to i32 addrspace(1)*
  return __builtin_astype(img, global int*);
}

#endif


Add demo for the hexagonBox shape and the repeat operator

/**
 * Samples using the camelSCAD library.
 *
 * A parametric honeycombed style box
 *
 * @author jsconan
 * @license CC0-1.0
 */

// As we need to use some shapes, use the right entry point of the library
use <../shapes.scad>

/**
 * Renders a honeycomb at the origin.
 *
 * @param Vector|Number size - The outer dimensions of the honeycomb
 * @param Number thickness - The thickness of the box walls (default 1). Cannot be greater than 10% of the lowest dimension.
 */
module honeycomb(size, thickness) {
    // Adjust the values to get usable size and thickness
    size = vector3D(size);
    width = min(size[0], size[1]);
    thickness = min(numberOr(thickness, 1), width / 10);
    adjust = max(size[0], size[1]) - width;
    innerWidth = width - thickness * 2;

    difference() {
        // This is the outside of the honeycomb
        hexagonBox(l=width, w=width, h=size[2], adjust=adjust);

        // This is the inside of the honeycomb
        translate([0, 0, thickness]) {
            hexagonBox(l=innerWidth, w=innerWidth, h=size[2], adjust=adjust);
        }
    }

}

// We will render the object using the specifications of this mode
renderMode = "prod";

// Defines the dimensions of the honeycomb
length = 60;
width = 50;
height = 30;
thickness = 2;

// intervals between honeycombs
adjustX = (max(length, width) - min(length, width)) / 4;
spaceX = cos(60) * length / 2 + thickness - adjustX;
spaceY = cos(30) * width - thickness;

// The number of honeycombs to render on both X and Y axis
nbX = 4;
nbY = 4;

// Sets the minimum facet angle and size using the defined render mode.
$fa = facetAngle(renderMode);
$fs = facetSize(renderMode);

// The honeycombed box is drawed by rendering several honeycombs using the repeat2D operator
repeat2D(countX=nbX, countY=nbY, intervalX=[length - spaceX, spaceY / 2, 0], intervalY=[0, spaceY, 0]) {
    honeycomb(size = [length, width, height], thickness=thickness);
}


//
// Machine
//

// Coding-style
// ------------
//
// Global variables are written in UpperCamelCase.
// A logical hierarchy should be indicated using underscores, for example:
//     StepperMotor_Connections_Axle
//
// Global short-hand references should be kept to a minimum to avoid name-collisions

// Global Settings for Printed Parts
//

DefaultWall 	= 4*perim;
ThickWall 		= 8*perim;

// short-hand
dw 				= DefaultWall;
tw 				= ThickWall;

// Global design parameters
GroundClearance = 20;

// Motor references
MotorOffsetX = -16;
MotorOffsetZ = 10;
MotorShaftDiameter = 5;
MotorShaftFlatThickness = 2;

// Wheels
//

WheelDiameter 	= 2*(GroundClearance + MotorOffsetZ);
WheelRadius 	= WheelDiameter / 2;
WheelThickness 	= dw;   // used to determine the size of slot in the base, clearance factor is added later

// Base
//

BaseDiameter 	= 140;
BaseThickness 	= dw;

// Pen
//

PenHoleDiameter = 25;

Update MotorshaftFlatThickness to measured value

//
// Machine
//

// Coding-style
// ------------
//
// Global variables are written in UpperCamelCase.
// A logical hierarchy should be indicated using underscores, for example:
//     StepperMotor_Connections_Axle
//
// Global short-hand references should be kept to a minimum to avoid name-collisions

// Global Settings for Printed Parts
//

DefaultWall 	= 4*perim;
ThickWall 		= 8*perim;

// short-hand
dw 				= DefaultWall;
tw 				= ThickWall;

// Global design parameters
GroundClearance = 20;

// Motor references
MotorOffsetX = -16;
MotorOffsetZ = 10;
MotorShaftDiameter = 5;
MotorShaftFlatThickness = 3;

// Wheels
//

WheelDiameter 	= 2*(GroundClearance + MotorOffsetZ);
WheelRadius 	= WheelDiameter / 2;
WheelThickness 	= dw;   // used to determine the size of slot in the base, clearance factor is added later

// Base
//

BaseDiameter 	= 140;
BaseThickness 	= dw;

// Pen
//

PenHoleDiameter = 25;


Use openscad to replace kokopelli piece to be more standard

width = 97; // External width (except clipping mechanism)
height = 142; // External height (except clipping mechanism)
corner_radius = 14; // Round corner at the bottom corners
top_width = 114; // Clipping mechanism width
top_height = 20; // Clipping mechanism height
thickness = 2*0.7; // Thickness of clipping mechanism
clip_height = 12;

//Main pocket
difference()
{
	union(){
	cube(size = [width,height,thickness], center = true);
	translate([-width/2, 0,0]) cylinder(r=20, h=thickness, center = true);
	translate([width/2, 0,0]) cylinder(r=20, h=thickness, center = true);
	}
	cube(size = [width-20,height-24,thickness], center = true);
}

// Existing top clip
//translate([0, height/2 + top_height/2, 0]) cube(size = [top_width,top_height,thickness], center = true);

clip_width = width +20;
// Top clip support
translate([0, height/2 - clip_height/2, 0]) cube(size = [clip_width, clip_height, thickness], center = true);

// Top clip
translate([-clip_height, 0 , 0]) cube(size = [clip_height, clip_width, thickness], center = true);

// Bottom clip support
translate([0, -height/2+clip_height/2, 0]) cube(size = [clip_width, clip_height, thickness], center = true);

// Bottom clip
translate([clip_height, 0, 0]) cube(size = [clip_height, clip_width, thickness], center = true);


/*
* font3d
* (C) Copyright 2014 Cameron Lai
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 3.0 which accompanies this distribution, and is available at
* https://www.gnu.org/licenses/lgpl-3.0.txt
*
* font3d is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/

include<dimension.scad>
include<basic.scad>

module font3d(inputString, fontType)
{
	// Loop around characters
	for (i=[0:len(inputString)-1])
	{
		// Pick corresponding font
		translate([i*xdim,0,0])
		if (fontType=="basic") basic(inputString[i]);
		else
		{
		   echo("Font type not recognized");
		}
	}
	// Add support bar
	support_bar(len(inputString));
}

Add support bar only for length greater than 1

/*
* font3d
* (C) Copyright 2014 Cameron Lai
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 3.0 which accompanies this distribution, and is available at
* https://www.gnu.org/licenses/lgpl-3.0.txt
*
* font3d is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/

include<dimension.scad>
include<basic.scad>

font3d("AB", "basic");

module font3d(inputString, fontType)
{
	numChar = len(inputString);
	// Loop around characters
	for (i=[0:numChar-1])
	{
		// Pick corresponding font
		translate([i*xdim,0,0])
		if (fontType=="basic") basic(inputString[i]);
		else
		{
		   echo("Font type not recognized");
		}
	}
	// Add support bar
	if (numChar>1) support_bar(len(inputString));
}


use <compass.scad>
use <arduino_footprint.scad>
use <battery_footprint.scad>

thickness = 5;

difference()
{
	union()
	{
		arm();
		translate([20,0,0]) cube(size=[50,150,thickness], center=true);
	}
	translate([20,-45,0]) nano_connector_footprint(2*thickness);
	translate([20,5,0]) 9V_battery();
	translate([0,5,0]) cube(size=[3,12,2*thickness], center=true);
	translate([40,5,0]) cube(size=[3,12,2*thickness], center=true);
	translate([0,-45,0]) cube(size=[3,12,2*thickness], center=true);
	translate([40,-45,0]) cube(size=[3,12,2*thickness], center=true);
}

Add minkowski sum to get rounded corners

use <compass.scad>
use <arduino_footprint.scad>
use <battery_footprint.scad>

module support_arm()
{
	thickness = 5;

	difference()
	{
		union()
		{
			arm();
			minkowski()
			{
				cylinder(r=5, h=thickness/3.0);
				translate([20,0,0]) cube(size=[50,150,thickness/3.0], center=true);
			}
		}
		translate([20,-45,0]) nano_connector_footprint(2*thickness);
		translate([20,5,0]) 9V_battery();
		translate([0,5,0]) cube(size=[3,12,2*thickness], center=true);
		translate([40,5,0]) cube(size=[3,12,2*thickness], center=true);
		translate([0,-45,0]) cube(size=[3,12,2*thickness], center=true);
		translate([40,-45,0]) cube(size=[3,12,2*thickness], center=true);
	}
}
projection() support_arm();


include <cap.scad>;

// Note that I get a very strange behavior with F5 mode, a fixed polygon covers
// half my screen and some of the tee part is missing.  When rendering in F6
// mode, everying behaves.

M5_head = 8.8/2;
M5_tall = 5;
M5_pegrad = 4/2;

num_caps = 1;

union() {
  for(i=[1:num_caps]) {
    translate([i*40, 0, 0])
      Knob(outerRad=M5_head*1.65, pegRad=M5_pegrad, capRad=M5_head,
           chamfer=0.9, $fn=100);
  }
}

// vim: ft=c sw=2 sts=2 ts=2 et


Add a sample to illustrate use of new mesh shapes

/**
 * Samples using the camelSCAD library.
 *
 * A simple mesh grid
 *
 * @author jsconan
 * @license CC0-1.0
 */

// As we need to use some shapes, use the right entry point of the library
use <../shapes.scad>
include <../core/constants.scad>

// We will render the object using the specifications of this mode
renderMode = MODE_PROD;

// Defines the dimensions of the object
length = 120;
width = 120;
thickness = 2;
corner = 8;
paddingX = 6;
paddingY = 6;
holeDiameter = 5;
holeIntervalX = length - 2 * holeDiameter;
holeIntervalY = width - 2 * holeDiameter;

cellCountX = 10;
cellCountY = 10;
cellSpaceX = 1;
cellSpaceY = 1;
meshLength = length - 2 * paddingX;
meshWidth  = width - 2 * paddingY;

// Sets the minimum facet angle and size using the defined render mode.
// Displays a build box visualization to preview the printer area.
applyMode(mode=renderMode) {
    difference() {
        cushion([length, width, thickness], d=corner);

        negativeExtrude(thickness, direction=2) {
            translate([holeIntervalX, holeIntervalY, 0] / -2) {
                repeat2D(countX=2, countY=2, intervalX=[holeIntervalX, 0, 0], intervalY=[0, holeIntervalY, 0]) {
                    circle(d=holeDiameter);
                }
            }

            mesh(
                size  = [meshLength, meshWidth],
                count = [cellCountX, cellCountY],
                gap   = [cellSpaceX, cellSpaceY],
                linear = true,
                even = true,
                pointy = false
            );
        }
    }
}


tube_diameter = 28;
space_margin = 1;
thickness = 5;
screw_diameter = 5;
screw_head_thickness = 5;

a = tube_diameter + 2* space_margin +2*thickness;
difference(){
	union(){
		//Main part
		cube(size=[a,a,a], center = true);

		//Screw tube
		translate([0, a/2+screw_diameter/2,0]) difference(){
			cylinder(r = screw_diameter/2+thickness, h = a, center=				true);
			cylinder(r = screw_diameter/2, h = a, center=true);
		}
		//Second screw tube
		translate([0, -a/2-screw_diameter/2,0]) difference(){
			cylinder(r = screw_diameter/2+thickness, h = a, center=				true);
			cylinder(r = screw_diameter/2, h = a, center=true);

		}
	}
	rotate([0,90,0])  cylinder(r=tube_diameter/2. + space_margin, h= 2*a, center = true);
   cube(size =[2*a, 2*a,tube_diameter/5.], center = true);
	translate([0,-a/2-screw_diameter/2,a/2]) cylinder(r = screw_diameter/2+thickness+0.1, h = 2*screw_head_thickness, center=				true);
	translate([0,-a/2-screw_diameter/2,-a/2]) cylinder(r = screw_diameter/2+thickness+0.1, h = 2*screw_head_thickness, center=				true);
	translate([0,+a/2+screw_diameter/2,a/2]) cylinder(r = screw_diameter/2+thickness+0.1, h = 2*screw_head_thickness, center=				true);
	translate([0,+a/2+screw_diameter/2,-a/2]) cylinder(r = screw_diameter/2+thickness+0.1, h = 2*screw_head_thickness, center=				true);
}


Add demo for the starBox shape and some other shapes

/**
 * Samples using the camelSCAD library.
 *
 * A parametric christmas star.
 *
 * @author jsconan
 * @license CC0-1.0
 */

// As we need to use some shapes, use the right entry point of the library
use <../shapes.scad>

// We will render the object using the specifications of this mode
renderMode = "prod";

// Defines the dimensions of the star
radius = 40;
thickness = 3;
holeDiameter = 4;
ringThickness = 2;
ringDiameter = holeDiameter + ringThickness * 2;
coreRadius = (radius * 2) * (1 - 3 / 5);

// Sets the minimum facet angle and size using the defined render mode.
$fa = facetAngle(renderMode);
$fs = facetSize(renderMode);

// And draw the star
union() {
    // This is the frame of the star
    difference() {
        starBox(size=radius, h=thickness, edges=5, center=true);
        starBox(size=radius / 1.5, h=thickness + 1, edges=5, center=true);
    }
    // This is the core of the star
    rotateZ(180) {
        difference() {
            regularPolygonBox(size=coreRadius, n=5, h=thickness, center=true);
            cylinder(r=radius / 5, h=thickness + 1, center=true);
        }
    }
    // This the ring to hook the star
    translate([0, radius + ringThickness]) {
        pipe(d=ringDiameter, w=ringThickness, h=thickness, center=true);
    }
}


Create a support for component to be integrated in waterproof pocket

thickness = 2;
width=85;
length=133-30;
nano_length_max=43.6;
nano_length_min = 37.1;
nano_width_max = 22.7;
nano_internal_width = 9;
nano_thickness=7;
9V_width=26.2;
9V_length=45;
transmitter_width = 30;
transmitter_length= 45;
IMU_screw_spacing_width = 12.1;
IMU_screw_spacing_length = 16.3;
corner_radius=5;

module support()
{
	difference()
	{
		minkowski(){
		translate([0,-15,0]) cube(size=[width-2*corner_radius,length-2*corner_radius,thickness/3.], center=true);
		cylinder(h=thickness/3., r=corner_radius);
}
		translate([10,12,0]) difference(){
			cube(size=[nano_width_max,nano_length_min,2*thickness], center=true);
		 	cube(size=[nano_internal_width,nano_length_min,2*thickness], center=true);
	}
		translate([-23,8,0]) cube(size=[9V_width,9V_length,2*thickness], center=true);
		//translate([10,-45,0]) cube(size=[transmitter_length,transmitter_width,2*thickness], center=true);
	translate([0,-60,0]) cube(size=[12,3,2*thickness], center=true);
	translate([0,-60 +transmitter_width ,0]) cube(size=[12,3,2*thickness], center=true);

	// Holes to screw drotek IMU board
		translate([-30, -50,0]) cylinder(r=0.3, h=2*thickness, center=true);
		translate([-30+IMU_screw_spacing_length, -50+IMU_screw_spacing_width,0]) cylinder(r=0.3, h=2*thickness, center=true);
		translate([-30+IMU_screw_spacing_length, -50,0]) cylinder(r=0.3, h=2*thickness, center=true);
	}
}
projection() support();


Add a piece to support embedded sensor, battery, and RF module

RF_module_length  = 160;
9V_battery_length = 50;
length_for_arduino_nano = 30;
total_length = RF_module_length +9V_battery_length+length_for_arduino_nano;
width = 30; // Based on arduino nano length between "legs"
thickness = 5;

projection() embedded_support();

module embedded_support(){
	difference(){
		union(){
			// Main support
			cube(size = [total_length +20, width, thickness], center = true);

			// Right plate to attach strap
			translate([total_length/2+20/2-30/2,0,0]) cube(size = [30, width+20, thickness], center = true);

			// Left plate to attach strap
			translate([-total_length/2-20/2+30/2,0,0]) cube(size = [30, width+20, thickness], center = true);
		}
				// Right holes to attach strap
			translate([total_length/2+20/2-30/2,17.5,0]) cube(size = [20, 5, 2*thickness], center = true);
			translate([total_length/2+20/2-30/2,-17.5,0]) cube(size = [20, 5, 2*thickness], center = true);

			// Left holes to attach strap
			translate([-total_length/2-20/2+30/2,17.5,0]) cube(size = [20, 5, 2*thickness], center = true);
			translate([-total_length/2-20/2+30/2,-17.5,0]) cube(size = [20, 5, 2*thickness], center = true);
	}
}


/* Tutorial 7 - Using libraries */

/* You can "include" or "use" scad files to use the modules they contain */

translate([0, 0, -20]) {
	/* "include" is like pasting the file contents here */
	include <tut6_surfaces.scad>
}

/* "use" just makes the file's modules available */

/* OpenSCAD comes with MCAD - a library of useful modules
 * It contains many things - look here: https://github.com/openscad/MCAD */
s = 20;

use <MCAD/regular_shapes.scad>
translate([0, 0, 0]) {
	pentagon(5);
	translate([15, 0, 0]) nonagon_prism(10, 5);
}

/* Gears */
use <MCAD/involute_gears.scad>
translate([0, s, 0]) scale(0.1) bevel_gear_pair();

/* Lego! */
use <MCAD/lego_compatibility.scad>
translate([2 * s, 0, 0])
	block(4, 2, 1, reinforcement = true, solid_bottom = false);

/* *models* of bearings */
use <MCAD/bearing.scad>
translate([0, -s, 0]) bearing();

/* Stepper motor mounts */
use <MCAD/motors.scad>
translate([-50, 0, 0]) stepper_motor_mount(23);

/* Have a look around the 'net for other libraries, or write your own! */


$fn = 50;
button_h = 13;
overlap = 5;
total_height = 23;
th = 2; // enclosure thickness
eps = 1e-1;

cap_r = 7 / 2;
cap_h = total_height - button_h + overlap;

border_offset = 5.5 + th;
border_h = 3;
border_r = cap_r + 3;

socket_r = 3.2 / 2;

difference() {
  union() {
    cylinder(r=cap_r, h=cap_h);
    translate([0, 0, cap_h - border_h - border_offset]) {
      cylinder(r=border_r, h=border_h);
    }
  }
  translate([0, 0, -eps]) {
    cylinder(r=socket_r, h=overlap+eps);
  }
}

Revert "adjust buttons diameter again"

$fn = 50;
button_h = 13;
overlap = 5;
total_height = 23;
th = 2; // enclosure thickness
eps = 1e-1;

cap_r = 6.5 / 2;
cap_h = total_height - button_h + overlap;

border_offset = 5.5 + th;
border_h = 3;
border_r = cap_r + 3;

socket_r = 3.2 / 2;

difference() {
  union() {
    cylinder(r=cap_r, h=cap_h);
    translate([0, 0, cap_h - border_h - border_offset]) {
      cylinder(r=border_r, h=border_h);
    }
  }
  translate([0, 0, -eps]) {
    cylinder(r=socket_r, h=overlap+eps);
  }
}


Add sample to demo the render modes feature

/**
 * Samples using the camelSCAD library.
 *
 * Rendering mode.
 *
 * @author jsconan
 * @license CC0-1.0
 */

// Only include the core of the library as only the render mode helpers are needed
use <../core.scad>

// Defines the list of shapes sizes
DEMO_RANGE = [1 : 10];

// The space between each shape on the same line
DEMO_STEP = 5;

// The start offset of a line
DEMO_OFFSET_X = 20;

// The space between two lines
DEMO_OFFSET_Y = 30;

// The size of the displayed text (the name of illustrated render mode)
DEMO_FONT_SIZE = 10;

// The list of render modes to illustrate
DEMO_MODES = [
    [[.5, 0, 0], "dirty"],
    [[0, .5, 0], "dev"],
    [[0, 0, .5], "prod"],
];

/**
 * Will illustrate the current render mode by drawing some shapes
 * @param String mode
 */
module demo(mode) {
    // Draw some shapes
    for(i = DEMO_RANGE) {
        translate([DEMO_OFFSET_X + DEMO_STEP * i, 0, 0]) {
            sphere(i);
        }
    }

    // Display the mode name
    text(mode, DEMO_FONT_SIZE, halign="center", valign="center");
}

/**
 * Sets the minimum facet angle and size using the default render mode.
 */
$fa = facetAngle();
$fs = facetSize();

/**
 * Will apply each render mode and will illustrate them by drawing some shapes
 */
translate([DEMO_OFFSET_X, 0, 0]) {
    demo("default");
}
for (i = [0 : len(DEMO_MODES) - 1]) {
    translate([DEMO_OFFSET_X, (i + 1) * DEMO_OFFSET_Y, 0]) {
        color(DEMO_MODES[i][0]) {
            mode = DEMO_MODES[i][1];

            $fa = facetAngle(mode);
            $fs = facetSize(mode);

            demo(mode);
        }
    }
}


Add a sample to illustrate the use of Bezier curves

/**
 * Samples using the camelSCAD library.
 *
 * A simple framed heart using Bezier curve.
 *
 * @author jsconan
 * @license CC0-1.0
 */

// As we need to use some shapes, use the right entry point of the library
use <../shapes.scad>
include <../core/constants.scad>

// We will render the object using the specifications of this mode
renderMode = MODE_PROD;

// Defines the constraints of the print
printResolution = 0.2;

// Defines the constraints of the object
scaleFactor = 5;
height = 4;
controls = [[0, 0], [5, 3], [5, 10], [0, 7]] * scaleFactor;

// Sets the minimum facet angle and size using the defined render mode.
// Displays a build box visualization to preview the printer area.
applyMode(renderMode) {
    // As we are using function to generate points based on the current render mode
    // we need to wrap the call into one union to ensure the render mode is well applied
    union() {
        // Computes the points that draw half the heart
        half = cubicBezierCurve(controls[0], controls[1], controls[2], controls[3]);

        // Assembles the points that draw the full heart
        points = concat(half, mirror2D(half));

        // Compute the size of the heart
        size = dimensions2D(points);
        echo("Size", size);

        // Draws the heart
        linear_extrude(height=height, convexity=10) {
            // Frame
            difference() {
                rectangle(size + vector2D(scaleFactor));
                rectangle(size);
            }

            // Heart
            translateY(-size[1] / 2) {
                polygon(
                    points=points
                );
            }
        }

        // Displays the control points to illustrate how the curve is constrained
        translate([0, -size[1] / 2, height]) {
            controlPoints(controls, size=2);
        }
        buildPlate();
    }
}


/**
 * Samples using the camelSCAD library.
 *
 * A simple parametric pipe.
 *
 * @author jsconan
 * @license CC0-1.0
 */

// As we need to use some shapes, use the right entry point of the library
use <../shapes.scad>

// We will render the object using the specifications of this mode
renderMode = "prod";

// Defines the dimensions of the pipe
height = 50;
width = 1;
innerDiameter = 9.5;
outerDiameter = innerDiameter + width * 2;

// Sets the minimum facet angle and size using the defined render mode.
$fa = facetAngle(renderMode);
$fs = facetSize(renderMode);

// And draw the pipe accordingly
pipe(d=outerDiameter, h=height, w=width);


/*
    Vitamin: MicroUSB
    Model of a Micro USB receptacle

    TODO: Add different types of Micro USB Connectors

    Derived from: http://www.farnell.com/datasheets/1693470.pdf

    Authors:
        Jamie Osborne (@jmeosbn)

    Local Frame:
        Part width is in x+ (meeting PCB edge), depth is through center in y+

    Parameters:
        None

    Returns:
        Model of a Micro USB receptacle (SMT)
*/

module MicroUSB_Receptacle() {
    // dimensions for micro usb header
    // http://www.farnell.com/datasheets/1693470.pdf
    depth  = 5.3;
    width  = 7.5;
    height = 2.8;
    flange = 7.8;                 // width of front flange
    offset  = 2.15 + 0.6 - 1.45;  // distance to overhang board edge

    color(Grey90, 0.3)
    linear_extrude(height) {
        translate([0, offset - depth/2, 0])
            square(size=[flange, depth], center=true);
    }
}

Undo transparency of microusb connector

/*
    Vitamin: MicroUSB
    Model of a Micro USB receptacle

    TODO: Add different types of Micro USB Connectors

    Derived from: http://www.farnell.com/datasheets/1693470.pdf

    Authors:
        Jamie Osborne (@jmeosbn)

    Local Frame:
        Part width is in x+ (meeting PCB edge), depth is through center in y+

    Parameters:
        None

    Returns:
        Model of a Micro USB receptacle (SMT)
*/

module MicroUSB_Receptacle() {
    // dimensions for micro usb header
    // http://www.farnell.com/datasheets/1693470.pdf
    depth  = 5.3;
    width  = 7.5;
    height = 2.8;
    flange = 7.8;                 // width of front flange
    offset  = 2.15 + 0.6 - 1.45;  // distance to overhang board edge

    color(Grey90)
    linear_extrude(height) {
        translate([0, offset - depth/2, 0])
            square(size=[flange, depth], center=true);
    }
}


Add a piece to link two potentiometer to make "gimbal measurement"

use <MCAD/nuts_and_bolts.scad>

guiding_length = 10;
x = 2;
space = 15;

difference(){
union(){
	hull(){
	translate([space +guiding_length/2,0,0]) cube(size=[15,10,guiding_length], center = true);
	translate([x, 0, x]) sphere(3);
	}

	hull(){
		translate([0,0,space+guiding_length/2]) rotate([0,90,0])cube(size=[15,10,guiding_length], center = true);
		translate([x, 0, x]) sphere(3);
	}
}

	translate([space +guiding_length/2,0,0]) cylinder(r=3.25, h=10*guiding_length, center = true);
	translate([0,0,space+guiding_length/2]) rotate([0,90,0])cylinder(r=3.25, h=10*guiding_length, center = true);

//space for nut
	rotate([0,-90,0])
union(){translate([space +guiding_length/2+4.5,0, 0]) rotate([0,90,0]) translate([0,0,-1.25])  nutHole(3);
 translate([space +guiding_length/2+2.5,0, 0]) rotate([0,90,0]) translate([0,0,-1.25]) nutHole(3);

	translate([space +guiding_length/2+5,0, 0]) rotate([0,90,0]) cylinder(r=1.5, h=15, center=true);}

	translate([space +guiding_length/2+4.5,0, 0]) rotate([0,90,0]) translate([0,0,-1.25])  nutHole(3);
	translate([space +guiding_length/2+2.5,0, 0]) rotate([0,90,0]) translate([0,0,-1.25])  nutHole(3);
	translate([space +guiding_length/2+5,0, 0]) rotate([0,90,0]) cylinder(r=1.5, h=15, center=true);

//Cube to visualize
	//cube(space +guiding_length/2+7);

}

//cube(size=[sqrt(guiding_length


module TravelBracket(){
difference(){
	union(){
		import("..//..//approved//TRV_BRKT.stl");

		// Fill in unneeded holes
		color([255,0,0])translate([16,17,3])rotate([90,0,0])cylinder(h=10,r=1.8,$fn=40);
		color([255,0,0])translate([16,17,11])rotate([90,0,0])cylinder(h=10,r=1.8,$fn=40);

		translate([22,9,0])cube([6,8,14]);
		translate([-22,9,0])mirror([1,0,0])cube([6,8,14]);
		translate([22,-9,0])mirror([0,1,0])cube([6,6,14]);
		translate([-22,-9,0])mirror([1,1,0])cube([6,6,14]);

		translate([13,11,0])cube([6,3,14]);

		// Linear bearing holes
		difference(){
			union(){
				translate([25,0,0])cylinder(h=14,r=10,$fn=40);
				translate([-25,0,0])cylinder(h=14,r=10,$fn=40);
			}

			union(){
				translate([25,0,-1])cylinder(h=18,r=8,$fn=40);
				translate([-25,0,-1])cylinder(h=18,r=8,$fn=40);
			}
		}

	}

		// Mount screw Linear bearing
		translate([-25,0,7])rotate([90,0,0])cylinder(h=40,r=1.8,$fn=40,center=true);
		translate([25,0,7])rotate([90,0,0])cylinder(h=40,r=1.8,$fn=40,center=true);

}

}

module NutSocket(width,depth,height)
{
	side_length=sqrt(pow(width,2)/2);
	translate([0,0,height/2])cube([width,depth,height],center=true);
	rotate([0,45,0])cube([side_length,depth,side_length],center=true);
}

difference(){
	TravelBracket();

	union(){
		translate([-25,12.5,5.5])NutSocket(6,3,14);
		translate([25,12.5,5.5])NutSocket(6,3,14);
		mirror([0,1,0])translate([-25,11,5.5])NutSocket(6,3,14);
		mirror([0,1,0])translate([25,11,5.5])NutSocket(6,3,14);
	}
}


Add demo for the cushion shape and some helpers

/**
 * Samples using the camelSCAD library.
 *
 * A simple parametric box with rounded corners.
 *
 * @author jsconan
 * @license CC0-1.0
 */

// As we need to use some shapes, use the right entry point of the library
use <../shapes.scad>

/**
 * Renders a rounded box at the origin.
 *
 * @param Vector|Number size - The outer dimensions of the box
 * @param Number thickness - The thickness of the box walls (default 1). Cannot be greater than 10% of the lowest dimension.
 * @param Number radius - The radius of the corner (default 10% of the lowest dimension)
 */
module simpleBox(size, thickness, radius) {
    // Adjust the values to get usable size, thickness, and rounded corner radius
    size = vector3D(size);
    lowest = min(size[0], size[1]) / 10;
    thickness = min(numberOr(thickness, 1), lowest);
    radius = numberOr(radius, lowest);

    // Compute the size and position of the handle hole
    handleRadius = size[0] + size[1];
    handleCenter = center2D(
        a=apply2D(x=-size[0] / 2 + radius, y=size[2]),
        b=apply2D(x=size[0] / 2 - radius, y=size[2]),
        r=handleRadius,
        negative=true
    );

    difference() {
        // This is the outside of the box
        cushion(size=size, r=radius);

        // This is the inside of the box
        translate([0, 0, thickness]) {
            cushion(size=apply3D(size, x=size[0] - thickness * 2, y=size[1] - thickness * 2), r=radius-thickness/2);
        }

        // This is the handle hole
        rotateX(90) {
            translate(vector3D(handleCenter)) {
                cylinder(r=handleRadius, h=size[1] + 1, center=true);
            }
        }
    }

}

// We will render the object using the specifications of this mode
renderMode = "prod";

// Defines the dimensions of the box
length = 100;
width = 70;
height = 40;
thickness = 1;
radius = 5;

// Sets the minimum facet angle and size using the defined render mode.
$fa = facetAngle(renderMode);
$fs = facetSize(renderMode);

// And draw the box accordingly
simpleBox(size = [length, width, height], thickness=thickness, radius=radius);

// You may also draw a cover by rendering another box that has an increased size with respect to the wall thickness...
%translate([0, 0, height + thickness]) {
    rotateX(180) {
        // Use an additional adjustment value (0.1) to counter the printer's precision lack and
        // allow to put the cover in place once printed.
        sizeAdjust = thickness * 2 + 0.1;
        simpleBox(size = [length + sizeAdjust, width + sizeAdjust, height + thickness], thickness=thickness, radius=radius);
    }
}


yaw = 90;
roll = 0;
pitch=0;
lineLength=20;
bearing =90;
elevation = 45;
useNED=-1;
 rotate(a=bearing, v=[0,0,1*useNED]) rotate(a=elevation, v=[0,1*useNED,0])  translate(v=[lineLength,0,0])  rotate(a=-1*elevation, v=[0,1*useNED,0]) rotate(a=-1*bearing, v=[0,0,1*useNED])   rotate(a=yaw ,v=[0,0,1*useNED]) rotate(a=pitch, v=[0,1*useNED,0]) rotate(a=roll, v=[1,0,0]) cube(size=[1,3,0.1]);

Add animation in figure of 8

lineLength=20;
bearing =0 + sin($t*360)*45;
elevation = 30+sin(-$t*360*2)*15;
yaw = bearing-sin($t*360)*30;
drift=5;
roll = sin(360*$t+90+drift)*120;
angleOfAttack=15;
pitch=elevation + angleOfAttack;
useNED=-1;
rotate(a=bearing, v=[0,0,1*useNED]) rotate(a=elevation, v=[0,1*useNED,0]){
	translate(v=[lineLength/2,0,0]) cube(size=[lineLength,0.1,0.1], center=true);
	translate(v=[lineLength,0,0])
 	  rotate(a=-1*elevation, v=[0,1*useNED,0]) rotate(a=-1*bearing, v=[0,0,1*useNED])
	  rotate(a=yaw ,v=[0,0,1*useNED]) rotate(a=pitch, v=[0,1*useNED,0]) rotate(a=roll, v=[1,0,0])
       color("red") cube(size=[0.1,,3,1],center=true); }


#######################################################################
#
# Standard repositories to use for Quattor configuration based on
# Quattor release.
#
#######################################################################

unique template repository/config/quattor;

include { 'quattor/functions/repository' };

# Ordered list of repository to load
variable QUATTOR_REPOSITORY_LIST ?= if ( is_defined(QUATTOR_RELEASE) ) {
                                      if ( match(QUATTOR_RELEASE,'13\.1') && (QUATTOR_RELEASE != '13.12') ) {
                                        repos = list('quattor_'+QUATTOR_RELEASE,'quattor_externals','quattor_components');
                                      } else {
                                        repos = list('quattor_'+QUATTOR_RELEASE,'quattor_externals');
                                      };
                                      debug("Repositories added for Quattor release "+QUATTOR_RELEASE+": "+to_string(repos));
                                      repos;
                                    } else {
                                      error("Quattor release undefined: not supported anymore, define QUATTOR_RELEASE to a version >= 13.1");
                                    };

'/software/repositories' = add_repositories(QUATTOR_REPOSITORY_LIST);

Add more flexibily to Quattor version repository configuration

#######################################################################
#
# Standard repositories to use for Quattor configuration based on
# Quattor release.
#
#######################################################################

unique template repository/config/quattor;

include { 'quattor/functions/repository' };

# Ordered list of repository to load
# QUATTOR_REPOSITORY_RELEASE allows to define the Quattor release repository to use, in case
# there is no repository specific to the release
variable QUATTOR_REPOSITORY_RELEASE ?= QUATTOR_RELEASE;
variable QUATTOR_REPOSITORY_LIST ?= if ( is_defined(QUATTOR_RELEASE) ) {
                                      if ( match(QUATTOR_RELEASE,'13\.1') && (QUATTOR_RELEASE != '13.12') ) {
                                        repos = list('quattor_'+QUATTOR_REPOSITORY_RELEASE,'quattor_externals','quattor_components');
                                      } else {
                                        repos = list('quattor_'+QUATTOR_REPOSITORY_RELEASE,'quattor_externals');
                                      };
                                      debug("Repositories added for Quattor release "+QUATTOR_RELEASE+": "+to_string(repos));
                                      repos;
                                    } else {
                                      error("Quattor release undefined: not supported anymore, define QUATTOR_RELEASE to a version >= 13.1");
                                    };

'/software/repositories' = add_repositories(QUATTOR_REPOSITORY_LIST);


declaration template quattor/functions/hardware;

# Returns the number of cores on the current machine or another machine
# specifified as a HW template (string) or a HW configuration (nlist).
function get_num_of_cores = {
    if ( ARGC == 0 ) {
      hw_config = value('/hardware');
    } else if ( ARGC == 1 ) {
      if ( is_nlist(ARGV[0]) ) {
        hw_config = ARGV[0];
      } else if ( is_string(ARGV[0]) ) {
        hw_config = create(ARGV[0]);
      } else {
        error(format('Invalid argument type (%s)',to_string(ARGV[0])));
      }
    } else {
      error(format('get_num_of_cores requires 0 or 1 argument (%s specified)',ARGC));
    };
    debug(format('%s: HW config = %s',OBJECT,to_string(hw_config)));

    if ( is_defined(hw_config['cpu']) && (length(hw_config['cpu']) > 0) ) {
      cores = 0;
      foreach (i;cpu;hw_config['cpu']) {
        if ( is_defined(cpu['cores']) ) {
          cores = cores + cpu['cores'];
        } else {
          cores = cores + 1;
        };
      };
      debug(format('%s: num of CPUs=%d, num of cores=%d',OBJECT,length(hw_config['cpu']),cores));
    } else {
      error('Invalid hardware configuration (no CPU defined)');
    };

    cores;
};


@{
    Data structures described on
    https://twiki.cern.ch/twiki/bin/view/FIOgroup/TsiCDBPhysicalDevices
    and
    https://twiki.cern.ch/twiki/bin/view/FIOgroup/TsiCDBBlockDevices#Hardware_RAID
}
declaration template quattor/physdevices;

include 'quattor/types/annotation';

type structure_raidport = {
    include structure_annotation
    "capacity" : long # In MB or GB? Quattor always used MB for this...
    "interface" : string with match (SELF, "^(sata|sas|ide|scsi)$")
    "boot" ? boolean
    # To handle disk device names as /dev/cciss/xxxpn, where 'p' must be inserted
    # between device name and partition number (e.g. HP SmartArray)
    "part_prefix" : string = ''
};

@documentation{
    Structure modelling a RAID controller
}
type structure_raid = {
    include structure_annotation
    "bbu" ? boolean
    "numberports" : long (1..)
    "cache" ? long # In MB
    "ports" : structure_raidport{}
} with length (SELF["ports"]) <= SELF["numberports"];

Add NVME to block device interface types

@{
    Data structures described on
    https://twiki.cern.ch/twiki/bin/view/FIOgroup/TsiCDBPhysicalDevices
    and
    https://twiki.cern.ch/twiki/bin/view/FIOgroup/TsiCDBBlockDevices#Hardware_RAID
}
declaration template quattor/physdevices;

include 'quattor/types/annotation';

type structure_raidport = {
    include structure_annotation
    "capacity" : long # In MB or GB? Quattor always used MB for this...
    "interface" : choice('sata', 'sas', 'ide', 'scsi', 'nvme')
    "boot" ? boolean
    # To handle disk device names as /dev/cciss/xxxpn, where 'p' must be inserted
    # between device name and partition number (e.g. HP SmartArray)
    "part_prefix" : string = ''
};

@documentation{
    Structure modelling a RAID controller
}
type structure_raid = {
    include structure_annotation
    "bbu" ? boolean
    "numberports" : long (1..)
    "cache" ? long # In MB
    "ports" : structure_raidport{}
} with length (SELF["ports"]) <= SELF["numberports"];


# ${license-info}
# ${developer-info}
# ${author-info}
# ${build-info}

unique template components/${project.artifactId}/config-common;

include { 'components/${project.artifactId}/schema' };

# Set prefix to root of component configuration.
prefix '/software/components/${project.artifactId}';

#'version' = '${project.version}';
#'package' = 'NCM::Component';

'active' ?= true;
'dispatch' ?= true;

Use no-snapshot-version as the profile value for a component version.

# ${license-info}
# ${developer-info}
# ${author-info}
# ${build-info}

unique template components/${project.artifactId}/config-common;

include { 'components/${project.artifactId}/schema' };

# Set prefix to root of component configuration.
prefix '/software/components/${project.artifactId}';

'version' = '${no-snapshot-version}';
#'package' = 'NCM::Component';

'active' ?= true;
'dispatch' ?= true;


object template simple;

# TT relpath is mycomp
# use /metaconfig as default for Test::Quattor::RegexpTest
"/metaconfig/module" = "main";

prefix "/metaconfig/contents";
"data" = "default_simple";
"extra" = "more_simple";

Use unique pan test profiles

object template simple;

# Make sure it's different from the other simple.pan files in same test
"/unique" = 1;

# TT relpath is mycomp
# use /metaconfig as default for Test::Quattor::RegexpTest
"/metaconfig/module" = "main";

prefix "/metaconfig/contents";
"data" = "default_simple";
"extra" = "more_simple";


unique template rpms/base;

variable OS_CORE_ONLY ?= false;
variable OS_CORE_ISCSI_ENABLED ?= false;

# Standard YUM groups for all machines
'/software/groups' = {
  SELF['core'] = dict();
  if ( ! OS_CORE_ONLY ) {
    SELF['base'] = dict();
  };
  SELF;
};
# grub2 doesn't seem to be part of core or base group...
'/software/packages' = pkg_repl('grub2');
include { if ( ! OS_CORE_ONLY ) 'rpms/management-utils' };

# Additional packages
'/software/packages' = {
  if ( ! OS_CORE_ONLY ) {
      pkg_repl('ntp');
      pkg_repl('ntpdate');
    if ( OS_CORE_ISCSI_ENABLED ) {
      pkg_repl('iscsi-initiator-utils');
    };
  };
  SELF;
};

Use only mandatory packages from core group - Default packages are mainly firmware for Wifi - A few packages from core group default list added explicitly

unique template rpms/base;

variable OS_CORE_ONLY ?= false;
variable OS_CORE_ISCSI_ENABLED ?= false;
variable OS_CORE_RDMA_ENABLED ?= false;

# Standard YUM groups for all machines

'/software/groups' = {
  # Default packages are mainly firmware for Wifi
  SELF['core'] = dict('mandatory', true,
                      'default',false,
                      'optional', false,
                     );
  if ( ! OS_CORE_ONLY ) {
    SELF['base'] = dict('mandatory', true,
                        'default', true,
                        'optional', false,
                       );
  };
  SELF;
};

# Additional packages

'/software/packages' = {
  # grub2 doesn't seem to be part of core or base group...
  pkg_repl('grub2');

  # Some useful packages from core default packages
  pkg_repl('dracut-config-rescue');
  pkg_repl('kernel-tools');
  pkg_repl('libsysfs');
  pkg_repl('linux-firmware');
  pkg_repl('postfix');
  if ( OS_CORE_RDMA_ENABLED ) pkg_repl('rdma');

  if ( ! OS_CORE_ONLY ) {
      pkg_repl('ntp');
      pkg_repl('ntpdate');
    if ( OS_CORE_ISCSI_ENABLED ) {
      pkg_repl('iscsi-initiator-utils');
    };
  };
  SELF;
};

include { if ( ! OS_CORE_ONLY ) 'rpms/management-utils' };


unique template features/accounts/config;

########################
# Keep Openstack Users #
########################

include 'components/accounts/config';
prefix '/software/components/accounts';

# Nova user
'kept_users/nova' = '';
'kept_groups/nova' = '';

# Glance user
'kept_users/glance' = '';
'kept_groups/glance' = '';

# Keystone user
'kept_users/keystone' = '';
'kept_groups/keystone' = '';

# Neutron user
'kept_users/neutron' = '';
'kept_groups/neutron' = '';

# Cinder user
'kept_users/cinder' = '';
'kept_groups/cinder' = '';

# Ceilometer user
'kept_users/ceilometer' = '';
'kept_groups/ceilometer' = '';

# Heat user
'kept_users/heat' = '';
'kept_groups/heat' = '';

# Rabbitmq user
'kept_users/rabbitmq' = '';
'kept_groups/rabbitmq' = '';

# Memcached user
'kept_users/memcached' = '';
'kept_groups/memcached' = '';

# MongoDB user
'kept_users/mongod' = '';
'kept_groups/mongod' = '';

Add mongodb user as kept_users

unique template features/accounts/config;

########################
# Keep Openstack Users #
########################

include 'components/accounts/config';
prefix '/software/components/accounts';

# Nova user
'kept_users/nova' = '';
'kept_groups/nova' = '';

# Glance user
'kept_users/glance' = '';
'kept_groups/glance' = '';

# Keystone user
'kept_users/keystone' = '';
'kept_groups/keystone' = '';

# Neutron user
'kept_users/neutron' = '';
'kept_groups/neutron' = '';

# Cinder user
'kept_users/cinder' = '';
'kept_groups/cinder' = '';

# Ceilometer user
'kept_users/ceilometer' = '';
'kept_groups/ceilometer' = '';

# Heat user
'kept_users/heat' = '';
'kept_groups/heat' = '';

# Rabbitmq user
'kept_users/rabbitmq' = '';
'kept_groups/rabbitmq' = '';

# Memcached user
'kept_users/memcached' = '';
'kept_groups/memcached' = '';

# MongoDB user
'kept_users/mongod' = '';
'kept_groups/mongod' = '';
'kept_users/mongodb' = '';
'kept_groups/mongodb' = '';


unique template rpms/editors;

prefix '/software/packages';

'{emacs}' = nlist();
'{emacs-nox}'     ?= nlist();
'{emacs-gnuplot}' ?= nlist();
'{emacs-auctex}'  ?= nlist();
'{vim-enhanced}' = nlist();
'{vim-X11}'       ?= nlist();
'{xemacs}' = nlist();
'{xemacs-devel}' = nlist();
'{xemacs-el}' = nlist();
'{xemacs-info}' = nlist();
'{xemacs-packages-base-el}' = nlist();
'{xemacs-packages-extra}' = nlist();
'{xemacs=packages-extra-el}' = nlist();
'{xemacs-packages-extra-info}' = nlist();
'{nedit}'       ?= nlist();

Remove xemeacs (not available in standard repos for EL7)


declaration template quattor/types/metadata;

@{Metadata about the source code management branch from which this
  profile was generated}
type structure_branch = {
    "author" ? string
    "name" : string
    "type" : string
    @{id/hash of (last) commit}
    "commit-id" ? string
    @{timestamp (in seconds since 1970), e.g. timestamp of last git commit}
    "timestamp" ? long(0..)
};

@{Metadata about the templates that generated this profile}
type structure_template = {
    "branch" : structure_branch
};

@{Information about how the profile was generated. For example, the
  provenance of templates used as input to the compile, and which specific
  templates were selected for inclusion.
}
type structure_metadata = {
    @{provenance of the template set}
    "template" : structure_template
    @{list of templates from the features tree that were included}
    "features" ? string[]
};

Add validation to the structure_branch type

declaration template quattor/types/metadata;

@{Metadata about the source code management branch from which this
  profile was generated}
type structure_branch = {
    "author" ? string
    "name" : string
    "type" : string with match(SELF, "^(domain|sandbox)$")
    @{id/hash of (last) commit}
    "commit-id" ? string
    @{timestamp (in seconds since 1970), e.g. timestamp of last git commit}
    "timestamp" ? long(0..)
};

@{Metadata about the templates that generated this profile}
type structure_template = {
    "branch" : structure_branch
};

@{Information about how the profile was generated. For example, the
  provenance of templates used as input to the compile, and which specific
  templates were selected for inclusion.
}
type structure_metadata = {
    @{provenance of the template set}
    "template" : structure_template
    @{list of templates from the features tree that were included}
    "features" ? string[]
};


unique template features/cvmfs/rpms;

'/software/packages/{cvmfs}' ?= dict();

Set required RPMs accordingly to cvmfs version

unique template features/cvmfs/rpms;

'/software/packages/{cvmfs}' ?= dict();

include 'quattor/functions/package';

'/software/packages' = {
  if ((pkg_compare_version(CVMFS_CLIENT_VERSION, '2.1.20') <= 0) && (OS_VERSION_PARAMS['major'] != 'sl5')) {
    SELF[escape('cvmfs-config-default')] = dict();
  } else {
    SELF[escape('cvmfs-keys')] = dict();
  };
  SELF;
};


# ${license-info}
# ${developer-info}
# ${author-info}
# ${build-info}

unique template components/ganglia/config-common;

include { 'components/ganglia/schema' };

# Set prefix to root of component configuration.
prefix '/software/components/ganglia';

'version' = '${no-snapshot-version}-${RELEASE}';
'package' = 'NCM::Component';

'active' ?= true;
'dispatch' ?= true;

Remove version definition to avoid scdb issu

# ${license-info}
# ${developer-info}
# ${author-info}
# ${build-info}

unique template components/ganglia/config-common;

include { 'components/ganglia/schema' };

# Set prefix to root of component configuration.
prefix '/software/components/ganglia';

#'version' = '${no-snapshot-version}-${RELEASE}';
'package' = 'NCM::Component';

'active' ?= true;
'dispatch' ?= true;


declaration template pan/legacy;

type legacy_binary_affirmation_string = string with match(SELF, "^(yes|no)$");

Add a transitional type to allow components to migrate to real booleans

declaration template pan/legacy;

type legacy_binary_affirmation_string = string with match(SELF, "^(yes|no)$");

function is_yes_no_true_false = {
    v = ARGV[0];
    if (is_boolean(v)) return(true);
    if (is_string(v) && match(v, "^(yes|no)$")) {
        deprecated(0, 'Legacy yes/no value in use, please migrate to true/false.');
        return(true);
    };
    false;
};

type transitional_yes_no_true_false = property with is_yes_no_true_false(SELF);


@{
    type definitions for filesystems
}
declaration template quattor/filesystems;

@{
    Filestystem definition
}
type structure_filesystem = {
	"block_device"	: string with exists ("/system/blockdevices/" + SELF)
			  # "References an entry in /software/components/blockdevices"
	"format"	: boolean
	"preserve"	: boolean
	"mountpoint"	: string
	"mount"		: boolean
	"mountopts"	: string = "defaults" # "Mount options"
	"type"		: string with match (SELF,
			     "^(ext[2-4]|reiserfs|reiser4|xfs|swap|vfat|jfs|ntfs|tmpfs|none)$")
			  # "Filesystem type."
	"quota"		? long # "Quota percentage"
	"freq"		: long = 0 # "Dump frequency"
	"pass"		: long = 0 # "fsck pass number"
	"mkfsopts"	? string # Extra options passed to mkfs.
	"tuneopts"	? string # Options for filesystem tuning commands (tune2fs, xfs_admin...)
	"label"		? string # Filesystem label, as in LABEL=foo
};

Add optional ksfsformat filesystem attribute

@{
    type definitions for filesystems
}
declaration template quattor/filesystems;

@{
    Filestystem definition
}
type structure_filesystem = {
	"block_device"	: string with exists ("/system/blockdevices/" + SELF)
			  # "References an entry in /software/components/blockdevices"
	"format"	: boolean
	"preserve"	: boolean
	"mountpoint"	: string
	"mount"		: boolean
	"mountopts"	: string = "defaults" # "Mount options"
	"type"		: string with match (SELF,
			     "^(ext[2-4]|reiserfs|reiser4|xfs|swap|vfat|jfs|ntfs|tmpfs|none)$")
			  # "Filesystem type."
	"quota"		? long # "Quota percentage"
	"freq"		: long = 0 # "Dump frequency"
	"pass"		: long = 0 # "fsck pass number"
	"mkfsopts"	? string # Extra options passed to mkfs.
	"tuneopts"	? string # Options for filesystem tuning commands (tune2fs, xfs_admin...)
	"label"		? string # Filesystem label, as in LABEL=foo
    "ksfsformat" ? boolean # If true, anaconda formats the filesystem (with undef/false, --noformat is used)
};


structure template hardware/nic/legacy/e100;

# This driver supports Intel 10/100 Mbps PCI Ethernet Interfaces
# Including 82550, 82551, 82557, 82558, 82559 and 82562

"driver" = "e100";
"pxe"    = false;
"boot"   = false;
"media"  = "Ethernet";
"name"   = "Intel(R) PRO/100 Network Driver";
"maxspeed" = 100;
"manufacturer" = "intel";

Fix namespace casing for some NIC templates

structure template hardware/nic/by_driver/e100;

# This driver supports Intel 10/100 Mbps PCI Ethernet Interfaces
# Including 82550, 82551, 82557, 82558, 82559 and 82562

"driver" = "e100";
"pxe"    = false;
"boot"   = false;
"media"  = "Ethernet";
"name"   = "Intel(R) PRO/100 Network Driver";
"maxspeed" = 100;
"manufacturer" = "intel";


# ${license-info}
# ${developer-info}
# ${author-info}
# ${build-info}
unique template quattor/aii/pxelinux/schema;

# PXE configuration.
type structure_pxelinux_pxe_info = {
    "initrd"	: string
    "kernel"	: string
    "ksdevice"	: string with match (SELF, ("^(eth[0-9]+|link|p[0-9]+p[0-9]+|fd|em[0-9]+|bootif)$")) || is_hwaddr (SELF)
    "kslocation"	: type_absoluteURI
    "label"		: string
    "append"	? string
    "rescue"	? string
    "livecd"	? string
    "firmware"	? string
    "setifnames" ? boolean
    "updates" ? type_absoluteURI
};

bind "/system/aii/nbp/pxelinux" = structure_pxelinux_pxe_info;

Support all five systemd device naming schemes

# ${license-info}
# ${developer-info}
# ${author-info}
# ${build-info}
unique template quattor/aii/pxelinux/schema;

# PXE configuration.
type structure_pxelinux_pxe_info = {
    "initrd"	: string
    "kernel"	: string
    "ksdevice"  : string with match (SELF, ('^(bootif|link|(eth|seth|em|bond|br|vlan|usb|ib|p\d+p|en(o|(p\d+)?s))\d+(\.\d+)?|enx\p{XDigit}{12})$')) || is_hwaddr (SELF)
    "kslocation"	: type_absoluteURI
    "label"		: string
    "append"	? string
    "rescue"	? string
    "livecd"	? string
    "firmware"	? string
    "setifnames" ? boolean
    "updates" ? type_absoluteURI
};

bind "/system/aii/nbp/pxelinux" = structure_pxelinux_pxe_info;


#
# Packages needed for a quattor client.
# RPMs are for Scientific Linux
#

template quattor/client/rpms;

variable QUATTOR_RELEASE_RPM_VERSION = format("%s.%s-%s",QUATTOR_RELEASE,0,1);

# Quattor services.

prefix "/software/packages";

"{ccm}" = nlist();
"{perl-Crypt-SSLeay}" = nlist(); # TODO remove when ccm has it as dependency
"{cdp-listend}" = nlist();

# NCM components.
"{ncm-cdispd}" = nlist();
"{ncm-ncd}" = nlist();
"{ncm-query}" = nlist();

# Include RPMs provided by OS.
# This is done last to allow redefining some RPMs that may be provided
# by the OS if the previous list is not suitable for a specific
# version/arch.
variable QUATTOR_CLIENT_OS_INCLUDE = 'config/quattor/client';
include { QUATTOR_CLIENT_OS_INCLUDE };

Make the platform-dependent Quattor RPMs optional

#
# Packages needed for a quattor client.
# RPMs are for Scientific Linux
#

template quattor/client/rpms;

variable QUATTOR_RELEASE_RPM_VERSION = format("%s.%s-%s",QUATTOR_RELEASE,0,1);

# Quattor services.

prefix "/software/packages";

"{ccm}" = nlist();
"{perl-Crypt-SSLeay}" = nlist(); # TODO remove when ccm has it as dependency
"{cdp-listend}" = nlist();

# NCM components.
"{ncm-cdispd}" = nlist();
"{ncm-ncd}" = nlist();
"{ncm-query}" = nlist();

# Include RPMs provided by OS.
# This is done last to allow redefining some RPMs that may be provided
# by the OS if the previous list is not suitable for a specific
# version/arch.
variable QUATTOR_CLIENT_OS_INCLUDE ?= 'config/quattor/client';
include if_exists(QUATTOR_CLIENT_OS_INCLUDE);


unique template machine-types/example/wn;

variable FILESYSTEM_LAYOUT_CONFIG_SITE ?= 'site/filesystems/wn';
variable GLEXEC_ARGUS_PEPD_ENDPOINTS ?= list('https://polgrid30.in2p3.fr:8154/authz');

include { 'machine-types/grid/wn' };

##################
# Include Pakiti #
##################
include { 'features/pakiti/config' };

#################################
# Include tmpdir cleanup script #
#################################
variable WN_CLEANUP_TMPDIR_TEMPLATE ?= if_exists('glite/wn/cleanup-tmpdir');
variable WN_CLEANUP_TMPDIR_TEMPLATE ?= if_exists('personality/wn/cleanup-tmpdir');
include { WN_CLEANUP_TMPDIR_TEMPLATE };

#################
# Include CVMFS #
#################
include { 'site/feature/cvmfs/config' };

# Only check mounted cvmfs filesystems
'/software/components/nrpe/options/command/cvmfs_wrapper' = {
    if (is_defined(SELF)) {
        SELF + ' -m';
    };
};

Remove pakiti and CVMFS from WN example (too many missing parts)

unique template machine-types/example/wn;

variable FILESYSTEM_LAYOUT_CONFIG_SITE ?= 'site/filesystems/wn';
variable GLEXEC_ARGUS_PEPD_ENDPOINTS ?= list('https://polgrid30.in2p3.fr:8154/authz');

include { 'machine-types/grid/wn' };

##################
# Include Pakiti #
##################
#include { 'features/pakiti/config' };

#################################
# Include tmpdir cleanup script #
#################################
variable WN_CLEANUP_TMPDIR_TEMPLATE ?= if_exists('glite/wn/cleanup-tmpdir');
variable WN_CLEANUP_TMPDIR_TEMPLATE ?= if_exists('personality/wn/cleanup-tmpdir');
include { WN_CLEANUP_TMPDIR_TEMPLATE };


# ${license-info}
# ${developer-info
# ${author-info}
# ${build-info}
unique template quattor/aii/pxelinux/schema;

# PXE configuration.
type structure_pxelinux_pxe_info = {
	"initrd"	: string
	"kernel"	: string
	"ksdevice"	: string with match (SELF, ("^(eth[0-9]+|link|fd|bootif)$")) || is_hwaddr (SELF)
	"kslocation"	: type_absoluteURI
	"label"		: string
	"append"	? string
	"rescue"	? string
	"livecd"	? string
	"firmware"	? string
};

bind "/system/aii/nbp/pxelinux" = structure_pxelinux_pxe_info;

Extend the validation regexp for bootif

# ${license-info}
# ${developer-info
# ${author-info}
# ${build-info}
unique template quattor/aii/pxelinux/schema;

# PXE configuration.
type structure_pxelinux_pxe_info = {
	"initrd"	: string
	"kernel"	: string
	"ksdevice"	: string with match (SELF, ("^(eth[0-9]+|link|p[0-9]+p[0-9]+|fd|em[0-9]+|bootif)$")) || is_hwaddr (SELF)
	"kslocation"	: type_absoluteURI
	"label"		: string
	"append"	? string
	"rescue"	? string
	"livecd"	? string
	"firmware"	? string
};

bind "/system/aii/nbp/pxelinux" = structure_pxelinux_pxe_info;


# Define default version of packages required during initial installation.
# Needed by AII to add the proper instruction in the KS config.

unique template rpms/package_default_versions;

# Entries in PKG_DEFAULT_VERSIONS must be either an OS version in the usual format (eg. sl640-x86_64)
# or 'default'.
# Normally there should be no OS specific version as OS-provided RPMs can be YUM installed as part
# of the base installation, using KS 'packages'.
variable PKG_DEFAULT_VERSIONS = nlist(
  'default',    nlist( '_perl-common-sense',      list('3.6-4.el7', 'noarch'),
                       '_perl-JSON-XS',           list('3.01-2.el7', PKG_ARCH_DEFAULT),
                       '_perl-Proc-ProcessTable', list('0.48-1.el7', PKG_ARCH_DEFAULT),
                       '_perl-Set-Scalar',        list('1.25-9.el7', 'noarch'),
                     ),
);

variable package_default = {
  os_version = OS_VERSION_PARAMS['version'];
  if ( is_defined(PKG_DEFAULT_VERSIONS[os_version])) {
    PKG_DEFAULT_VERSIONS[os_version];
  } else if ( is_defined(PKG_DEFAULT_VERSIONS['default'])) {
    PKG_DEFAULT_VERSIONS['default'];
  } else {
    error('No default packages defined for '+os_version);
  };
};

Fix some default versions (used for install with 13.1.x).


# ${license-info}
# ${developer-info}
# ${author-info}
# ${build-info}

unique template components/${project.artifactId}/config-rpm;

include { 'components/${project.artifactId}/config-common' };

# Set prefix to root of component configuration.
prefix '/software/components/${project.artifactId}';

# Install Quattor configuration module via RPM package.
'/software/packages' = pkg_repl('ncm-${project.artifactId}','${no-snapshot-version}-${RELEASE}','noarch');
'dependencies/pre' ?= list('spma');

Use rpm.release instead of RELEASE in the component archetypes

# ${license-info}
# ${developer-info}
# ${author-info}
# ${build-info}

unique template components/${project.artifactId}/config-rpm;

include { 'components/${project.artifactId}/config-common' };

# Set prefix to root of component configuration.
prefix '/software/components/${project.artifactId}';

# Install Quattor configuration module via RPM package.
'/software/packages' = pkg_repl('ncm-${project.artifactId}','${no-snapshot-version}-${rpm.release}','noarch');
'dependencies/pre' ?= list('spma');


# Template to help adding the current version of the pan compiler to the configuration.
# Mainly useful for Quattor template development.

unique template quattor/client/pan_compiler;

'/software/packages' = pkg_repl('panc','10.2-1','noarch');

Upgrade default panc version to 10.3-1

# Template to help adding the current version of the pan compiler to the configuration.
# Mainly useful for Quattor template development.

unique template quattor/client/pan_compiler;

@{
desc = Pan compiler version to install
values = string (version number)
default = 10.3-1
required = no
}
variable PANC_DEFAULT_VERSION ?= '10.3-1';

'/software/packages' = pkg_repl('panc',PANC_DEFAULT_VERSION,'noarch');


unique template features/wlcg/config;

@{
desc = add libraries required by WLCG applications
values = boolean
required = no
default = true
}
variable HEP_OSLIBS ?= true;

variable HEP_OSLIBS_MAPPING ?= dict(
    'sl5', 'HEP_OSlibs_SL5',
    'sl6', 'HEP_OSlibs_SL6',
    'el7', 'HEP_OSlibs_SL7',
);

"/software/packages" = {
  if ( HEP_OSLIBS ) {
    if ( is_defined(HEP_OSLIBS_MAPPING[OS_VERSION_PARAMS['major']]) ) {
      pkg_repl(HEP_OSLIBS_MAPPING[OS_VERSION_PARAMS['major']]);
    } else {
      error(format('No HEP_OSlibs mapping defined for an OS whose major version is %s.',OS_VERSION_PARAMS['major']));
    };
  };
  SELF;
};

Set the HEP_OSlib RPM name for CentOS 7 accordingly to the RPM available in the WLCG repo

unique template features/wlcg/config;

@{
desc = add libraries required by WLCG applications
values = boolean
required = no
default = true
}
variable HEP_OSLIBS ?= true;

variable HEP_OSLIBS_MAPPING ?= dict(
    'sl5', 'HEP_OSlibs_SL5',
    'sl6', 'HEP_OSlibs_SL6',
    'el7', 'HEP_OSlibs',
);

"/software/packages" = {
  if ( HEP_OSLIBS ) {
    if ( is_defined(HEP_OSLIBS_MAPPING[OS_VERSION_PARAMS['major']]) ) {
      pkg_repl(HEP_OSLIBS_MAPPING[OS_VERSION_PARAMS['major']]);
    } else {
      error(format('No HEP_OSlibs mapping defined for an OS whose major version is %s.',OS_VERSION_PARAMS['major']));
    };
  };
  SELF;
};


unique template rpms/quattor-development;

prefix '/software/packages';

'{perl-Template-Toolkit}' = nlist();
'{perl-Text-Autoformat}' = nlist();
'{perl-Pod-POM}' = nlist();
'{perl-Test-Harness}' = nlist();
'{perl-Test-Simple}' = nlist();
'{perl-Test-MockModule}' = nlist();
'{perl-Test-MockObject}' = nlist();
'{perl-Test-NoWarnings}' = nlist();
'{perl-Class-Inspector}' = nlist();

'{rpmdevtools}' = nlist();

# Pan compiler
include { 'quattor/client/pan_compiler' };

Add missing dependency for Quattor development (unit tests)

unique template rpms/quattor-development;

prefix '/software/packages';

'{perl-Template-Toolkit}' = nlist();
'{perl-Text-Autoformat}' = nlist();
'{perl-Text-Glob}' = nlist();
'{perl-Pod-POM}' = nlist();
'{perl-Test-Harness}' = nlist();
'{perl-Test-Simple}' = nlist();
'{perl-Test-MockModule}' = nlist();
'{perl-Test-MockObject}' = nlist();
'{perl-Test-NoWarnings}' = nlist();
'{perl-Class-Inspector}' = nlist();

'{rpmdevtools}' = nlist();

# Pan compiler
include { 'quattor/client/pan_compiler' };


program recpass;

(* Record passing, assignment of records, etc *)

type
r = record
       x : integer;
       y : real;
       z : boolean;
    end;

var
   c : r;
   d : r;

procedure test(a : r; var b :r);
begin
   b := a;
end; { test }

begin
   c.x := 4;
   c.y := 9.2;
   c.z := true;
   test(c, d);
   writeln('x=', d.x:1, ' y=', c.y:3:1, ' z=',c.z);
end.

Extend record passing test to function returning record

program recpass;

(* Record passing, assignment of records, etc *)

type
r = record
       x : integer;
       y : real;
       z : boolean;
    end;

var
   c : r;
   d : r;
   e : r;

procedure test(a : r; var b :r);
begin
   b := a;
end; { test }

function test2(a : r) : r;
begin
   test2 := a;
end;

begin
   c.x := 4;
   c.y := 9.2;
   c.z := true;
   test(c, d);
   e := test2(d);
   writeln('x=', e.x:1, ' y=', e.y:3:1, ' z=',e.z);
end.


unit uHelloWorld;

interface

  function Hello: string;

implementation

function Hello: string;
begin
  result := 'Hello, World!';
end;

end.

Simplify the `hello-world` exercise's stub. The goal of this is to make things easier for students to get started and to introduce as little syntax as possible.

unit uHelloWorld;

interface

  function Hello: string;

implementation

function Hello: string;
begin
  result := 'Goodbye, Mars!';
end;

end.


unit KM_CommonShellUtils;
{$I KaM_Remake.inc}
interface

  function OpenPDF(const aURL: string): Boolean;

implementation
uses
  {$IFDEF MSWindows}Windows, {$ENDIF}
  Forms
  {$IFDEF WDC}, ShellApi {$ENDIF}
  ;

function OpenPDF(const aURL: string): Boolean;
begin
  if aURL = '' then Exit(False);

  {$IFDEF WDC}
  Result := ShellExecute(Application.Handle, 'open', PChar(aURL), nil, nil, SW_SHOWNORMAL) > 32;
  {$ENDIF}

  {$IFDEF FPC}
  Result := OpenDocument(aURL);
  {$ENDIF}
end;

end.

Add methods to get used memory by the app

unit KM_CommonShellUtils;
{$I KaM_Remake.inc}
interface

  function OpenPDF(const aURL: string): Boolean;

  function GetMemUsed: NativeUInt;
  function GetCommittedStackSize: NativeUInt;

implementation
uses
  {$IFDEF MSWindows}Windows, PsAPI,{$ENDIF}
  Forms
  {$IFDEF WDC}, ShellApi {$ENDIF}
  ;

function OpenPDF(const aURL: string): Boolean;
begin
  if aURL = '' then Exit(False);

  {$IFDEF WDC}
  Result := ShellExecute(Application.Handle, 'open', PChar(aURL), nil, nil, SW_SHOWNORMAL) > 32;
  {$ENDIF}

  {$IFDEF FPC}
  Result := OpenDocument(aURL);
  {$ENDIF}
end;

function GetMemUsed: NativeUInt;
var
  pmc: PPROCESS_MEMORY_COUNTERS;
  cb: Integer;
begin
  cb := SizeOf(_PROCESS_MEMORY_COUNTERS);
  GetMem(pmc, cb);
  pmc^.cb := cb;
  if GetProcessMemoryInfo(GetCurrentProcess(), pmc, cb) then
    Result := pmc^.WorkingSetSize
  else
    Result := 0;

  FreeMem(pmc);
end;

function GetCommittedStackSize: NativeUInt;
//NB: Win32 uses FS, Win64 uses GS as base for Thread Information Block.
asm
 {$IFDEF WIN32}
  mov eax, [fs:04h] // TIB: base of the stack
  mov edx, [fs:08h] // TIB: lowest committed stack page
  sub eax, edx      // compute difference in EAX (=Result)
 {$ENDIF}
 {$IFDEF WIN64}
  mov rax, abs [gs:08h] // TIB: base of the stack
  mov rdx, abs [gs:10h] // TIB: lowest committed stack page
  sub rax, rdx          // compute difference in RAX (=Result)
 {$ENDIF}
end;

end.


unit KM_MapUtilsExt;
interface
uses
  KM_Maps;

  function TryOpenMapPDF(aMap: TKMapInfo): Boolean;

implementation
uses
  KM_CommonShellUtils;

function TryOpenMapPDF(aMap: TKMapInfo): Boolean;
var
  pdfPath: string;
begin
  Result := False;
  if aMap = nil then Exit;

  pdfPath := aMap.DetermineReadmeFilePath;
  if pdfPath <> '' then
    Result := OpenPDF(pdfPath);
end;

end.

Add missing KaM_Remake.inc to a new unit

unit KM_MapUtilsExt;
{$I KaM_Remake.inc}
interface
uses
  KM_Maps;

  function TryOpenMapPDF(aMap: TKMapInfo): Boolean;

implementation
uses
  KM_CommonShellUtils;

function TryOpenMapPDF(aMap: TKMapInfo): Boolean;
var
  pdfPath: string;
begin
  Result := False;
  if aMap = nil then Exit;

  pdfPath := aMap.DetermineReadmeFilePath;
  if pdfPath <> '' then
    Result := OpenPDF(pdfPath);
end;

end.


program cfuncname;

(* Test to ensure we don't have name collisions with C function names *)

(* Use an arbitrary C function name to do something completely different in Pascal *)
function strcpy(x : integer; y : integer) : integer;
begin
   strcpy := x * y
end; { strcpy }

begin
   writeln(strcpy(3,4):1)
end.

Make test try to detect when it's used wrong

program cfuncname;

(* Test to ensure we don't have name collisions with C function names *)

var x : integer;

(* Use an arbitrary C function name to do something completely different in Pascal *)
function strcpy(var x : integer; y : integer) : integer;
begin
   if x <> 3 then
      writeln('Huh?');
   strcpy := x * y
end; { strcpy }

begin
   x := 3;
   writeln(strcpy(x,4):1)
end.


(* **************************************************************** *)
(*     Copyright (C) 1999-2010, Jon Gentle, All right reserved.     *)
(* **************************************************************** *)
(* This program is free software; you can redistribute it under the *)
(* terms of the Artistic License, as specified in the LICENSE file. *)
(* **************************************************************** *)

unit Macro;

interface

uses hashs, error, gmrdrv, parser, classes;

type

  TMacroDrv = class
    constructor create; virtual; abstract;
    procedure execute(inNode: PParseNode); virtual; abstract;
   protected
    Ferr: TError;
    Fgmr: TGmr;
    FoutCode: TStringList;
    FoutData: TStringList;
    FsearchDirs: string;
    FgiantError: boolean;
   public
    property err: TError read Ferr write Ferr;
    property gmr: TGmr read Fgmr write Fgmr;
    property outCode: TStringList read FoutCode write FoutCode;
    property outData: TStringList read FoutData write FoutData;
    property searchDirs: string read FsearchDirs write FSearchDirs;
    property giantError: boolean read FgiantError write FgiantError;
  end;

  TMacroClass = class of TMacroDrv;

implementation

end.

Add a join method to all macro drivers.

(* **************************************************************** *)
(*     Copyright (C) 1999-2010, Jon Gentle, All right reserved.     *)
(* **************************************************************** *)
(* This program is free software; you can redistribute it under the *)
(* terms of the Artistic License, as specified in the LICENSE file. *)
(* **************************************************************** *)

unit Macro;

interface

uses hashs, error, gmrdrv, parser, classes;

type

  TMacroDrv = class(TPersistent)
    constructor create; virtual; abstract;
    procedure execute(inNode: PParseNode); virtual; abstract;
   protected
    Ferr: TError;
    Fgmr: TGmr;
    FoutCode: TStringList;
    FoutData: TStringList;
    FsearchDirs: string;
    FgiantError: boolean;
    function join(data: strArr; joinStr: string = #10; lower: word = 0; upper: word = 65535): string;
   public
    property err: TError read Ferr write Ferr;
    property gmr: TGmr read Fgmr write Fgmr;
    property outCode: TStringList read FoutCode write FoutCode;
    property outData: TStringList read FoutData write FoutData;
    property searchDirs: string read FsearchDirs write FSearchDirs;
    property giantError: boolean read FgiantError write FgiantError;
  end;

  TMacroClass = class of TMacroDrv;

implementation

function TMacroDrv.join(data: strArr; joinStr: string = #10; lower: word = 0; upper: word = 65535): string;
var i: word;
begin
  result := '';
  if length(data) <= lower then exit;
  for i := lower to length(data)-1 do
  begin
    if i > upper then break;
    result := result + data[i] + joinStr;
  end;
end;

end.


program gc;

uses
    Sysutils;

var
    FastaFile: TextFile;
    CurrentLine: String;
    GCCount: LongInt;
    ATCount: LongInt;
    TotalBaseCount: LongInt;
    c: Char;
    GCFraction: Single;
    PC,PCEnd: PChar;

begin
    ATCount := 0;
    GCCount := 0;
    TotalBaseCount := 0;

    Assign(FastaFile, 'Homo_sapiens.GRCh37.67.dna_rm.chromosome.Y.fa');
    Reset(FastaFile);
    while not EOF(FastaFile) do begin
        Readln(FastaFile, CurrentLine);
        PC := @CurrentLine[1];
        PCEnd := @CurrentLine[Length(CurrentLine)];
        while PC <= PCEnd do
        begin
            c := PC^;
            if c in ['G','C']  then
                Inc(GCCount)
            else if c in ['A','T'] then
                Inc(ATCount);
            Inc(PC);
        end;
    end;
    Close(FastaFile);
    TotalBaseCount := GCCount + ATCount;
    Writeln(TotalBaseCount);
    GCFraction := GCCount / TotalBaseCount;
    Writeln(FormatFloat('00.0000', GCFraction * 100));
end.

Implement check for header row in FPC

program gc;

uses
    Sysutils;

var
    FastaFile: TextFile;
    CurrentLine: String;
    GCCount: LongInt;
    ATCount: LongInt;
    TotalBaseCount: LongInt;
    c: Char;
    GCFraction: Single;
    PC,PCEnd: PChar;

begin
    ATCount := 0;
    GCCount := 0;
    TotalBaseCount := 0;

    Assign(FastaFile, 'Homo_sapiens.GRCh37.67.dna_rm.chromosome.Y.fa');
    Reset(FastaFile);
    while not EOF(FastaFile) do begin
        Readln(FastaFile, CurrentLine);
        if CurrentLine[0] <> '>' then begin
            PC := @CurrentLine[1];
            PCEnd := @CurrentLine[Length(CurrentLine)];
            while PC <= PCEnd do
            begin
                c := PC^;
                if c in ['G','C']  then
                    Inc(GCCount)
                else if c in ['A','T'] then
                    Inc(ATCount);
                Inc(PC);
            end;
        end;
    end;
    Close(FastaFile);
    TotalBaseCount := GCCount + ATCount;
    GCFraction := GCCount / TotalBaseCount;
    Writeln(FormatFloat('00.0000', GCFraction * 100));
end.


unit uMainForm;

{$IFDEF FPC}{$MODE Delphi}{$ENDIF}

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, Menus, StdCtrls;

type
  TForm1 = class(TForm)
    Memo1: TMemo;
    MainMenu1: TMainMenu;
    OpenDelphiUnit1: TMenuItem;
    OpenDialog1: TOpenDialog;
    procedure OpenDelphiUnit1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

uses
  DelphiAST, DelphiAST.Writer, DelphiAST.Classes;

{$R *.lfm}

function Parse(const FileName: string): string;
var
  SyntaxTree: TSyntaxNode;
begin
  Result := '';
  SyntaxTree := TPasSyntaxTreeBuilder.Run(FileName);
  try
    Result := TSyntaxTreeWriter.ToXML(SyntaxTree, True);
  finally
    SyntaxTree.Free;
  end;
end;

procedure TForm1.OpenDelphiUnit1Click(Sender: TObject);
begin
  if OpenDialog1.Execute then
  begin
    try
      Memo1.Lines.Text := Parse(OpenDialog1.FileName);
    except
      on E: EParserException do
        Memo1.Lines.Add(Format('[%d, %d] %s', [E.Line, E.Col, E.Message]));
    end;
  end;
end;

end.

Correct resource include in demo project's main form

unit uMainForm;

{$IFDEF FPC}{$MODE Delphi}{$ENDIF}

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, Menus, StdCtrls;

type
  TForm1 = class(TForm)
    Memo1: TMemo;
    MainMenu1: TMainMenu;
    OpenDelphiUnit1: TMenuItem;
    OpenDialog1: TOpenDialog;
    procedure OpenDelphiUnit1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

uses
  DelphiAST, DelphiAST.Writer, DelphiAST.Classes;

{$IFNDEF FPC}
  {$R *.dfm}
{$ELSE}
  {$R *.lfm}
{$ENDIF}

function Parse(const FileName: string): string;
var
  SyntaxTree: TSyntaxNode;
begin
  Result := '';
  SyntaxTree := TPasSyntaxTreeBuilder.Run(FileName);
  try
    Result := TSyntaxTreeWriter.ToXML(SyntaxTree, True);
  finally
    SyntaxTree.Free;
  end;
end;

procedure TForm1.OpenDelphiUnit1Click(Sender: TObject);
begin
  if OpenDialog1.Execute then
  begin
    try
      Memo1.Lines.Text := Parse(OpenDialog1.FileName);
    except
      on E: EParserException do
        Memo1.Lines.Add(Format('[%d, %d] %s', [E.Line, E.Col, E.Message]));
    end;
  end;
end;

end.