text:
#include "idl_genCHelper.h"
#include "idl_genLanguageHelper.h"

#include "os_abstract.h"
#include "os_iterator.h"
#include "os_heap.h"
#include "os_stdlib.h"

static os_iter definitions = NULL;

/* Specify a list of all C keywords */
static const char *c_keywords[] = {
    "asm", "auto", "break", "case", "char", "const", "continue", "default",
    "do", "double", "else", "enum", "extern", "float", "for", "goto", "if",
    "int", "long", "register", "return", "short", "signed", "sizeof",
    "static", "struct", "switch", "typedef", "union", "unsigned", "void",
    "volatile", "while", "true", "false"
};

/* Translate an IDL identifier into a C language identifier.
 * The IDL specification states that all identifiers that match
 * a C keyword must be prepended by "_c_".
 */
c_char *
idl_cId (
    const char *identifier)
{
    c_long i;
    char *cId;

    /* search through the C keyword list */
    /* QAC EXPECT 5003; Bypass qactools error, why is this a violation */
    for (i = 0; i < (c_long)(sizeof(c_keywords)/sizeof(c_char *)); i++) {
	/* QAC EXPECT 5007, 3416; will not use wrapper, no side effects here */
	if (strcmp(c_keywords[i], identifier) == 0) {
	    /* If a keyword matches the specified identifier, prepend _c_ */
	    /* QAC EXPECT 5007; will not use wrapper */
	    cId = os_malloc(strlen(identifier)+1+3);
	    snprintf(cId, strlen(identifier)+1+3, "_c_%s", identifier);
	    return cId;
	}
    }
    /* No match with a keyword is found, thus return the identifier itself */
    cId = os_strdup(identifier);
    return cId;
    /* QAC EXPECT 2006; performance is selected above rules here */
}

/* Build a textual presenation of the provided scope stack taking the
 * C++ keyword identifier translation into account. Further the function
 * equals "idl_scopeStack".
 */
c_char *
idl_scopeStackC(
    idl_scope scope,
    const char *scopeSepp,
    const char *name)
{
    c_long si;
    c_long sz;
    c_char *scopeStack;
    c_char *Id;

    si = 0;
    sz = idl_scopeStackSize(scope);
    if (si < sz) {
        /* The scope stack is not empty */
        /* Copy the first scope element name */
        scopeStack = os_strdup(idl_cId(idl_scopeElementName(idl_scopeIndexed(scope, si))));
        si++;
        while (si < sz) {
            /* Translate the scope name to a C identifier */
            Id = idl_cId(idl_scopeElementName(idl_scopeIndexed(scope, si)));
            /* allocate space for the current scope stack + the separator
             * and the next scope name
             */
            /* QAC EXPECT 5007; will not use wrapper */
            scopeStack = os_realloc(scopeStack, strlen(scopeStack)+strlen(scopeSepp)+strlen(Id)+1);
            /* Concatenate the separator */
            /* QAC EXPECT 5007; will not use wrapper */
            os_strcat(scopeStack, scopeSepp);
            /* Concatenate the scope name */
            /* QAC EXPECT 5007; will not use wrapper */
            os_strcat(scopeStack, Id);
            si++;
        }
        if (name) {
            /* A user identifier is specified */
            /* Translate the user identifier to a C identifier */
            Id = idl_cId(name);
            /* allocate space for the current scope stack + the separator
             * and the user identifier
             */
            /* QAC EXPECT 5007; will not use wrapper */
            scopeStack = os_realloc(scopeStack, strlen(scopeStack)+strlen(scopeSepp)+strlen(Id)+1);
            /* Concatenate the separator */
            /* QAC EXPECT 5007; will not use wrapper */
            os_strcat(scopeStack, scopeSepp);
            /* Concatenate the user identifier */
            /* QAC EXPECT 5007; will not use wrapper */
            os_strcat(scopeStack, Id);
        }
    } else {
	/* The stack is empty */
	if (name) {
	    /* A user identifier is specified */
	    scopeStack = os_strdup(idl_cId(name));
	} else {
	    /* make the stack represenation empty */
	    scopeStack = os_strdup("");
	}
    }
    /* return the scope stack representation */
    return scopeStack;
}

/* Return the C specific type identifier for the
 * specified type specification
 */
c_char *
idl_corbaCTypeFromTypeSpec(
    idl_typeSpec typeSpec)
{
    c_char *typeName = NULL;

    /* QAC EXPECT 3416; No side effects here */
    if (idl_typeSpecType(typeSpec) == idl_tbasic) {
        /* if the specified type is a basic type */
        if (idl_getCorbaMode() == IDL_MODE_ORB_BOUND) {
            switch (idl_typeBasicType(idl_typeBasic(typeSpec))) {
                case idl_short:
                    typeName = os_strdup("CORBA_Short");
                    break;
                case idl_ushort:
                    typeName = os_strdup("CORBA_UShort");
                    break;
                case idl_long:
                    typeName = os_strdup("CORBA_Long");
                    break;
                case idl_ulong:
                    typeName = os_strdup("CORBA_ULong");
                    break;
                case idl_longlong:
                    typeName = os_strdup("CORBA_LongLong");
                    break;
                case idl_ulonglong:
                    typeName = os_strdup("CORBA_ULongLong");
                    break;
                case idl_float:
                    typeName = os_strdup("CORBA_Float");
                    break;
                case idl_double:
                    typeName = os_strdup("CORBA_Double");
                    break;
                case idl_char:
                    typeName = os_strdup("CORBA_Char");
                    break;
                case idl_string:
                    typeName = os_strdup("char *");
                    break;
                case idl_boolean:
                    typeName = os_strdup("CORBA_Boolean");
                    break;
                case idl_octet:
                    typeName = os_strdup("CORBA_Octet");
                    break;
                default:
                    /* No processing required, empty statement to satisfy QAC */
                    break;
                    /* QAC EXPECT 2016; Default case must be empty here */
            }
        } else {
            switch (idl_typeBasicType(idl_typeBasic(typeSpec))) {
                case idl_short:
                    typeName = os_strdup("DDS_short");
                    break;
                case idl_ushort:
                    typeName = os_strdup("DDS_unsigned_short");
                    break;
                case idl_long:
                    typeName = os_strdup("DDS_long");
                    break;
                case idl_ulong:
                    typeName = os_strdup("DDS_unsigned_long");
                    break;
                case idl_longlong:
                    typeName = os_strdup("DDS_long_long");
                    break;
                case idl_ulonglong:
                    typeName = os_strdup("DDS_unsigned_long_long");
                    break;
                case idl_float:
                    typeName = os_strdup("DDS_float");
                    break;
                case idl_double:
                    typeName = os_strdup("DDS_double");
                    break;
                case idl_char:
                    typeName = os_strdup("DDS_char");
                    break;
                case idl_string:
                    typeName = os_strdup("char *");
                    break;
                case idl_boolean:
                    typeName = os_strdup("DDS_boolean");
                    break;
                case idl_octet:
                    typeName = os_strdup("DDS_octet");
                    break;
                default:
                    /* No processing required, empty statement to satisfy QAC */
                    break;
                    /* QAC EXPECT 2016; Default case must be empty here */
            }
        }
        /* QAC EXPECT 3416; No side effects here */
    } else if ((idl_typeSpecType(typeSpec) == idl_tseq) ||
            (idl_typeSpecType(typeSpec) == idl_tarray)) {
        /* sequence does not have an identification */
        typeName = os_strdup("");
        printf("idl_corbaTypeFromTypeSpec: Unexpected type handled\n");
    } else {
        /* if a user type is specified build it from its scope and its name.
         * The type should be one of idl_ttypedef, idl_tenum, idl_tstruct,
         * idl_tunion.
         */
        typeName = idl_scopeStackC(
                idl_typeUserScope(idl_typeUser(typeSpec)),
                "_",
                idl_typeSpecName(typeSpec));
    }
    return typeName;
    /* QAC EXPECT 5101; The switch statement is simple, therefor the total complexity is low */
}

c_char *
idl_genCLiteralValueImage(
    c_value literal,
    c_type type)
{
    c_char * valueImg = NULL;
    c_char *val2;
    int i;

    if (c_baseObject(type)->kind != M_ENUMERATION) {
        switch (literal.kind) {
        case V_OCTET:
            valueImg = os_malloc (40);
            snprintf(valueImg, 40, "%x", literal.is.Octet);
            break;
        case V_FLOAT:
        case V_DOUBLE:
            val2 = os_malloc(45);
            valueImg = os_malloc(45);
            snprintf(val2, 45, "%40.17g", literal.is.Double);
            i = 0;
            while (val2[i] == ' ') {
                i++;
            }
            os_strncpy(valueImg, &val2[i], 40);
            os_free(val2);
            if ((strchr(valueImg, '.') == NULL) && (strchr(valueImg, 'E') == NULL)) {
                strcat(valueImg, ".0");
            }
            break;
        case V_STRING:
            valueImg = os_malloc(strlen(literal.is.String)+3);
            snprintf(valueImg, strlen(literal.is.String)+3, "\"%s\"", literal.is.String);
            break;
        case V_BOOLEAN:
            valueImg = os_malloc(10);
            if (literal.is.Boolean) {
                snprintf(valueImg, 10, "%s", "TRUE");
            } else {
                snprintf (valueImg, 10, "%s", "FALSE");
            }
            break;
        case V_LONGLONG:
            valueImg = os_malloc(40);
            switch (c_primitive(type)->kind) {
            case P_SHORT:
                snprintf(valueImg, 40, "%hu", (c_short)literal.is.LongLong);
                break;
            case P_USHORT:
                snprintf(valueImg, 40, "%huU", (c_ushort)literal.is.LongLong);
                break;
            case P_LONG:
                if ((c_long)literal.is.LongLong != INT_MIN) {
                    snprintf(valueImg, 40, "%u", (c_long)literal.is.LongLong);
                } else {
                    // We cannot represent minus 2^31 directly, due to the fact that it
                    // is constructed in two steps:
                    // 1) the specification of the unsigned literal.
                    // 2) the application of the minus sign.
                    // However, due to the inclusion of number 0 the positive range
                    // is one lower than the negative range and therefore the most
                    // negative number cannot be expressed as unsigned literal without
                    // overflow (with subsequent compilation warning). Therefore we
                    // construct it in 3 steps:
                    // 1) Specification of most positive value
                    // 2) Application of the minus sign
                    // 3) Subtraction of 1 to reach most negative value.
                    snprintf(valueImg, 40, "2147483647 - 1");
                }
                break;
            case P_ULONG:
                snprintf(valueImg, 40, "%uU", (c_ulong)literal.is.LongLong);
                break;
            case P_LONGLONG:
                if ((c_longlong)literal.is.LongLong != LLONG_MIN) {
                    snprintf(valueImg, 40, "%"PA_PRIu64"LL", (c_longlong)literal.is.LongLong);
                } else {
                    // We cannot represent minus 2^63 directly, due to the fact that it
                    // is constructed in two steps:
                    // 1) the specification of the unsigned literal.
                    // 2) the application of the minus sign.
                    // However, due to the inclusion of number 0 the positive range
                    // is one lower than the negative range and therefore the most
                    // negative number cannot be expressed as unsigned literal without
                    // overflow (with subsequent compilation warning). Therefore we
                    // construct it in 3 steps:
                    // 1) Specification of most positive value
                    // 2) Application of the minus sign
                    // 3) Subtraction of 1 to reach most negative value.
                    snprintf(valueImg, 40, "9223372036854775807LL - 1LL");
                }
                break;
            case P_ULONGLONG:
                snprintf(valueImg, 40, "%"PA_PRIu64"ULL", (c_ulonglong)literal.is.LongLong);
                break;
            case P_CHAR:
                snprintf(valueImg, 40, "%u", (unsigned char)literal.is.LongLong);
                break;
            case P_OCTET:
                snprintf(valueImg, 40, "%u", (unsigned char)literal.is.LongLong);
            break;
            case P_ADDRESS:
                snprintf(valueImg, 40, PA_ADDRFMT, (PA_ADDRCAST)literal.is.LongLong);
                break;
            case P_UNDEFINED:
            case P_BOOLEAN:
            case P_WCHAR:
            case P_FLOAT:
            case P_DOUBLE:
            case P_VOIDP:
            case P_MUTEX:
            case P_LOCK:
            case P_COND:
            case P_COUNT:
            case P_PA_UINT32:
            case P_PA_UINTPTR:
            case P_PA_VOIDP:
                /* Do nothing */
                break;
            }
            break;
        case V_SHORT:
            valueImg = os_malloc(40);
            snprintf(valueImg, 40, "%hu", literal.is.Short);
            break;
        case V_LONG:
            valueImg = os_malloc(40);
            if ((c_long)literal.is.LongLong != INT_MIN) {
                snprintf(valueImg, 40, "%u", literal.is.Long);
            } else {
                // We cannot represent minus 2^31 directly, due to the fact that it
                // is constructed in two steps:
                // 1) the specification of the unsigned literal.
                // 2) the application of the minus sign.
                // However, due to the inclusion of number 0 the positive range
                // is one lower than the negative range and therefore the most
                // negative number cannot be expressed as unsigned literal without
                // overflow (with subsequent compilation warning). Therefore we
                // construct it in 3 steps:
                // 1) Specification of most positive value
                // 2) Application of the minus sign
                // 3) Subtraction of 1 to reach most negative value.
                snprintf(valueImg, 40, "2147483647 - 1");
            }
            break;
        case V_USHORT:
            valueImg = os_malloc(40);
            snprintf(valueImg, 40, "%huU", literal.is.UShort);
            break;
        case V_ULONG:
            valueImg = os_malloc(40);
            snprintf(valueImg, 40, "%uU", literal.is.ULong);
            break;
        case V_ULONGLONG:
            valueImg = os_malloc(40);
            snprintf(valueImg, 40, "%" PA_PRIu64 "ULL", literal.is.ULongLong);
            break;
        case V_ADDRESS:
            valueImg = os_malloc(40);
            snprintf(valueImg, 40, PA_ADDRFMT, (PA_ADDRCAST)literal.is.Address);
            break;
        case V_CHAR:
            valueImg = os_malloc(40);
            snprintf(valueImg, 40, "%u", (unsigned char)literal.is.Char);
            break;
        case V_UNDEFINED:
        case V_WCHAR:
        case V_WSTRING:
        case V_FIXED:
        case V_VOIDP:
        case V_OBJECT:
        case V_COUNT:
            /* Invalid types for literal constants*/
            /* FALL THROUGH */
        default:
            valueImg = NULL;
            break;
        }
    } else {
        valueImg = os_strdup(c_metaObject(c_constant(c_enumeration(type)->elements[literal.is.Long]))->name);
    }

    return valueImg;
}

void
idl_definitionClean (
    void
    )
{
    char *def;

    if (definitions) {
        while ((def = os_iterTakeFirst(definitions))) {
	    os_free(def);
        }
        os_iterFree(definitions);
	definitions = NULL;
    }
}

void
idl_definitionAdd (
    char *class,
    char *name
    )
{
    char *def;

    def = os_malloc(strlen(class) + strlen (name) + 1);
    os_strcpy(def, class);
    os_strcat(def, name);
    if (definitions == NULL) {
	definitions = os_iterNew(NULL);
    }
    os_iterInsert(definitions, def);
}

static os_equality
defName(
    const void *iterElem,
    const void *arg)
{
    if (strcmp((const char *)iterElem, (const char *)arg) == 0) {
	return OS_EQ;
    }
    return OS_NE;
}

int
idl_definitionExists(
    char *class,
    char *name)
{
    char *def;

    def = os_malloc(strlen(class) + strlen (name) + 1);
    os_strcpy(def, class);
    os_strcat(def, name);
    if (definitions != NULL) {
        if (os_iterResolve(definitions, defName, def) != NULL) {
	    os_free(def);
	    return 1;
        }
    }
    os_free(def);
    return 0;
}

c_char *
idl_genCConstantGetter(void)
{
    return NULL;
}


text:
'use strict';

var coverage    = require('gulp-coverage');
var coveralls   = require('gulp-coveralls');
var eventStream = require('event-stream');
var gulp        = require('gulp');
var jshint      = require('gulp-jshint');
var lazypipe    = require('lazypipe');
var mocha       = require('gulp-mocha');
var notify      = require('gulp-notify');
var path        = require('path');
var plumber     = require('gulp-plumber');
var watch       = require('gulp-watch');

var ROOT      = __dirname;
var LIB_ROOT  = path.join(ROOT, 'lib');
var TEST_ROOT = path.join(ROOT, 'test');

gulp.task('default', ['watch']);

gulp.task('watch', function() {
  var config = {
    glob:       '{lib,test}/**/*.js',
    emitOnGlob: false,
    gaze:       {debounceDelay: 10},
  };
  return watch(config, function(files) {
    files
      .pipe(plumber({errorHandler: notify.onError('<%= error.message %>')}))
      .pipe(jshintFlow())
      .pipe(eventStream.map(testForFile))
      .pipe(mocha({reporter: 'dot'}))
  });
});

gulp.task('test', ['test:style', 'test:unit']);

gulp.task('test:style', function() {
  return gulp.src('{lib,test}/**/*.js').pipe(jshintFlow());
});

gulp.task('test:unit', function() {
  return gulp.src('test/**/*.js')
    .pipe(coverage.instrument({pattern: ['lib/**/*.js']}))
    .pipe(mocha({reporter: 'spec'}))
    .pipe(coverage.gather())
    .pipe(coverage.format({outFile: 'coverage.html'}))
    .pipe(gulp.dest('.'))
    .pipe(coverage.enforce({
      statements: 95,
      blocks:     80, // web support drops us :(
      lines:      95,
    }));
});

// Flows

var jshintFlow = lazypipe()
  .pipe(jshint)
  .pipe(jshint.reporter, 'jshint-stylish')
  .pipe(jshint.reporter, 'fail');

// Transformation

function testForFile(file, callback) {
  if (file.path.indexOf(LIB_ROOT) !== 0) return callback(null, file);

  var testPath = path.join(TEST_ROOT, file.path.substr(LIB_ROOT.length));
  gulp.src(testPath)
    .on('data',  callback.bind(null, null))
    .on('error', callback);
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.flink.test.windowing.sessionwindows;

import org.apache.flink.util.Preconditions;

/** Test payload that contains useful information for the correctness checks in our test. */
public final class TestEventPayload {

    // id of the session w.r.t the key
    private int sessionId;

    // id of the event w.r.t. tje session id
    private int eventId;

    // the watermark under which the event was emitted
    private long watermark;

    // the timing characteristic of the event w.r.t. the watermark
    private SessionEventGeneratorImpl.Timing timing;

    public TestEventPayload(
            long watermark,
            int sessionId,
            int eventSequenceNumber,
            SessionEventGeneratorImpl.Timing timing) {
        setWatermark(watermark);
        setSessionId(sessionId);
        setEventId(eventSequenceNumber);
        setTiming(timing);
    }

    /** @return global watermark at the time this event was generated */
    public long getWatermark() {
        return watermark;
    }

    public void setWatermark(long watermark) {
        this.watermark = watermark;
    }

    /**
     * @return id of the session to identify a sessions in the sequence of all sessions for the same
     *     key
     */
    public int getSessionId() {
        return sessionId;
    }

    public void setSessionId(int sessionId) {
        this.sessionId = sessionId;
    }

    /** @return a sequence number that acts as an id for the even inside the session */
    public int getEventId() {
        return eventId;
    }

    public void setEventId(int eventId) {
        this.eventId = eventId;
    }

    /**
     * @return indicates whether the event is on time, late within the timing, or late after the
     *     timing
     */
    public SessionEventGeneratorImpl.Timing getTiming() {
        return timing;
    }

    public void setTiming(SessionEventGeneratorImpl.Timing timing) {
        Preconditions.checkNotNull(timing);
        this.timing = timing;
    }

    @Override
    public String toString() {
        return "TestEventPayload{"
                + "sessionId="
                + sessionId
                + ", eventId="
                + eventId
                + ", watermark="
                + watermark
                + ", timing="
                + timing
                + '}';
    }

    public static TestEventPayload of(
            long watermark, int sessionId, int eventId, SessionEventGeneratorImpl.Timing timing) {
        return new TestEventPayload(watermark, sessionId, eventId, timing);
    }
}


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android">

<item android:enabled="true"
	android:titleCondensed="@string/menu_resetprefs"
	android:title="@string/menu_resetprefs" android:id="@+id/m_resetprefs"
	android:orderInCategory="1" />

</menu>


text:
package crypto

import (
	"crypto/hmac"
	"crypto/md5"
	"crypto/sha1"
	"crypto/sha256"
	"crypto/sha512"
	"encoding/hex"
	"fmt"
	"hash"
	"hash/fnv"

	"github.com/spf13/cast"
)

// New returns a new instance of the crypto-namespaced template functions.
func New() *Namespace {
	return &Namespace{}
}

// Namespace provides template functions for the "crypto" namespace.
type Namespace struct{}

// MD5 hashes the given input and returns its MD5 checksum.
func (ns *Namespace) MD5(in any) (string, error) {
	conv, err := cast.ToStringE(in)
	if err != nil {
		return "", err
	}

	hash := md5.Sum([]byte(conv))
	return hex.EncodeToString(hash[:]), nil
}

// SHA1 hashes the given input and returns its SHA1 checksum.
func (ns *Namespace) SHA1(in any) (string, error) {
	conv, err := cast.ToStringE(in)
	if err != nil {
		return "", err
	}

	hash := sha1.Sum([]byte(conv))
	return hex.EncodeToString(hash[:]), nil
}

// SHA256 hashes the given input and returns its SHA256 checksum.
func (ns *Namespace) SHA256(in any) (string, error) {
	conv, err := cast.ToStringE(in)
	if err != nil {
		return "", err
	}

	hash := sha256.Sum256([]byte(conv))
	return hex.EncodeToString(hash[:]), nil
}

// FNV32a hashes using fnv32a algorithm
func (ns *Namespace) FNV32a(in any) (int, error) {
	conv, err := cast.ToStringE(in)
	if err != nil {
		return 0, err
	}
	algorithm := fnv.New32a()
	algorithm.Write([]byte(conv))
	return int(algorithm.Sum32()), nil
}

// HMAC returns a cryptographic hash that uses a key to sign a message.
func (ns *Namespace) HMAC(h any, k any, m any, e ...any) (string, error) {
	ha, err := cast.ToStringE(h)
	if err != nil {
		return "", err
	}

	var hash func() hash.Hash
	switch ha {
	case "md5":
		hash = md5.New
	case "sha1":
		hash = sha1.New
	case "sha256":
		hash = sha256.New
	case "sha512":
		hash = sha512.New
	default:
		return "", fmt.Errorf("hmac: %s is not a supported hash function", ha)
	}

	msg, err := cast.ToStringE(m)
	if err != nil {
		return "", err
	}

	key, err := cast.ToStringE(k)
	if err != nil {
		return "", err
	}

	mac := hmac.New(hash, []byte(key))
	_, err = mac.Write([]byte(msg))
	if err != nil {
		return "", err
	}

	var encoding = "hex"
	if len(e) > 0 && e[0] != nil {
		encoding, err = cast.ToStringE(e[0])
		if err != nil {
			return "", err
		}
	}

	switch encoding {
	case "binary":
		return string(mac.Sum(nil)[:]), nil
	case "hex":
		return hex.EncodeToString(mac.Sum(nil)[:]), nil
	default:
		return "", fmt.Errorf("%q is not a supported encoding method", encoding)
	}

}


text:
package ru.avhaliullin.whatever.semantic.module

import ru.avhaliullin.whatever.semantic.Structure
import ru.avhaliullin.whatever.semantic.function.FnSignature

/**
  * @author avhaliullin
  */
case class ModuleAPI(name: ModuleName, functions: Map[String, FnSignature], structs: Map[String, Structure]) {
  def withFunction(fn: FnSignature): ModuleAPI = {
    if (functions.contains(fn.name)) {
      throw new RuntimeException(s"Duplicated function ${fn.name} in module $name")
    }
    copy(functions = functions + (fn.name -> fn))
  }

  def withStruct(st: Structure): ModuleAPI = {
    if (structs.contains(st.fullTpe.name)) {
      throw new RuntimeException(s"Duplicated struct ${st.fullTpe.name} in module $name")
    }
    copy(structs = structs + (st.fullTpe.name -> st))
  }
}


text:
import Core from '../core';
import { InputManager } from '../managers';
import { Word } from '../models';
import { Alignment, Rectangle, setContextProperties } from '../utilities/canvas';
import { COLORS } from '../utilities/constants';

export default class Player {
    constructor(playerNumber, rect) {
        this.id = playerNumber;
        const x = (this.id % 2) * rect.centerX;
        this.rect = new Rectangle(x, 0, rect.centerX, rect.centerY);
        if (this.id === 0 || this.id === 3) {
            this.rect.y = (this.id % 2) * rect.centerY;
        } else if (this.id === 2) {
            this.rect.y = rect.centerY;
        }
        this.rect.centerX += this.rect.x;
        this.rect.centerY += this.rect.y;
        this.currentWord = null;
        this.mode = 'normal';
        this.score = 0;

    }
    getColor(index, tint) {
        const tints = ['lightest', 'light', 'regular'];
        if ((index > 3 || index < 0)) {
            return '';
        }
        const colors = ['reds', 'blues', 'yellows', 'greens'];
        const category = COLORS[colors[index]];
        const categoryKeys = Object.keys(category);
        if (!categoryKeys.includes(tint)) {
            return '';
        }
        return category[tint];
    }
    setWord(newWord) {
        this.currentWord = new Word(newWord, this.rect);
    }
    update() {
        if (this.mode !== 'click') {
            InputManager.get().keyHandle(this.currentWord);
        }
        if (this.currentWord.solved) {
            const instance = Core.get();
            const currentLevel = instance.level;
            this.setWord(currentLevel.randomWordFromList());
            this.score += 100;
        }
    }
    draw(ctx) {
        ctx = setContextProperties(ctx, {
            fillStyle: this.getColor(this.id, 'lightest')
        });
        ctx.fillRect(this.rect.x, this.rect.y, this.rect.width, this.rect.height);
        this.currentWord.draw(ctx, this.getColor(this.id, 'light'), this.getColor(this.id, 'regular'));
        ctx = setContextProperties(ctx, {
            fillStyle: COLORS.grays['67'],
            font: 'normal 16pt Raleway Light',
            textAlign: Alignment.right
        });
        const x = this.rect.width * ((this.id % 2) + 1) - 25;
        const y = this.rect.height * ((this.id > 1) + 1) - 25;
        const scoreRect = { x, y };
        ctx.fillText(this.score, scoreRect.x, scoreRect.y);
    }
}


text:
Rails.application.configure do
  default_locale = config.i18n.default_locale
  config.i18n.available_locales = [default_locale, :en, :'en-US'].compact # see https://github.com/stympy/faker/issues/480 and https://github.com/stympy/faker/issues/266
end


text:
<script type="text/javascript" charset="utf-8">
  window.location = 'http://www.facturagem.madridonrails.com'
</script>


text:
title: Managing Your CI/CD Build Notifications
shortTitle: Managing Notifications
tags:
  - administration
  - notifications
  - alerts
  - slack
  - hipchat
  - stride
  - webhook
  - email
  - campfire
  - flowdock
categories:
  - Project
redirect_from:
  - /administration/notifications/
  - /basic/getting-started/webhooks/
  - /integrations/webhooks/
  - /general/account/notifications
menus:
  general/account:
    title: Notifications
    weight: 3
---

* include a table of contents
{:toc}

## Notifications Overview

As a default, we've setup a notification rule that sends an email to everyone on the team, whenever something happens to the builds in the project, regardless of branch.

Notification rules are grouped by branch, or branches, and you can setup as many as you like. Each rule applies to one service, so if you want to e.g. send the same notification to two slack channels, you'll have to setup two rules.

Each group can apply to a specific branch, e.g. `master`, or multiple branches that match a pattern, e.g. `feature/*`.

![Notifications]({{ site.baseurl }}/images/general/notifications.gif)

### Branch Matching

If you use the wildcard `*` in the branch name, it will try and match to multiple branches. Let's say you have a naming convention for your feature branches that have start with "feature/" followed by some name, you could create a notification rule that matches all feature branches by specifying `feature/*` as the branch name.

The wildcard allows you to replace any amount of characters, so you could even do `*design*feature*` to match any branch that have those two words in it.

### Integrated Notification Services

We have in-build support for the following services:

1. [Campfire](#campfire)
1. [Email](#email-notification)
1. [Flowdock](#flowdock)
1. [Hipchat](#hipchat)
1. [Slack](#slack)
1. [Stride](#stride)
1. [Webhooks](#webhook)

If the service you're looking for isn't on the list, you might be able to use the `webhook` option but if not, feel free to reach out to us (see bottom of the page).

## Configuring Build Notifications

To configure build notifications, go to your *Project Settings* and then click into the **Notifications** tab.

If you want to add more rules to an existing branch (or branch match) click the `add` button to the right of the branch name. If you want to add rules for a new branch (or branch match) click the big `new notification` button at the bottom of the page.

In case you no longer want to have a specific rule trigger notifications, you can either disable it (use the toggle on the right hand side) or delete it completely.

**Note**: Each service have different detail fields that will need to be populated, so refer to the sections below to see which apply for the service you want to configure.

## Common Configuration

All rules apply to either "All Branches", a names branch, or a branch match. If the field is left empty, the rule will apply to all branches.

Additionally, all rules can select between `started`, `failed`, `succeeded`, and `recovered` as events that trigger a notification. You must select at least one event in order to save the rule.

* `started` -> sends a notification when a new build is triggered
* `failed` -> sends a notification if a build fails or is stopped for some reason
* `succeeded` -> sends a notification if the build finishes successfully
* `recovered` -> sends a notification if the previous build failed, but the current build succeeded
* `requires approval` -> sends a notification if a build is paused pending a [manual approval]({{ site.baseurl }}{% link _pro/builds-and-configuration/steps.md %}#manual-approval-steps)

## Campfire

For campfire, we need both an API key and your domain name (just the first part, without `.campfirenow.com`) as well as the specific room you want the notifications to end up in.

## Email Notification

For an email rule, you can select whether all members of the project will receive notifications, or only the person whos commit triggered the build.

If only the committer should be notified, either the emails or usernames must be the same in both Codeship and Github/Bitbucket/Gitlab. If they're different, no notifications are sent.

#### Disable Email

If you don't want to receive any emails you can set that on your [account page](https://app.codeship.com/user/edit). This applies to all emails though, and not just for one project.

#### Not Receiving Email

If you are not receiving email notifications, but are expecting them, there are a few things to check. First make sure notifications are enabled for your [account](https://app.codeship.com/user/edit). Next make sure that the email address on your [Codeship account](https://app.codeship.com/user/edit) matches the email you have set in your Git configuration on your local machine.  You can check this with:

```
git config --get user.email
```

If all those settings look correct and you are still not receiving notifications, please [contact us](mailto:support@codeship.com) and we can further investigate.

## Flowdock

Flowdock expects a token as well, but the where to send the notification is handled on the flowdock side of things.

## Hipchat

Hipchat mainly requires a token and the room that you want the notification to be posted to.

## Slack

For Slack, the only thing you need is the webhook URL Slack provides when you configure a Codeship integration. Copy-paste the URL to the Webhook URL field.

## Stride

Stride needs an access token as well as a webhook URL. In Stride, you need to add a 'custom app' from the Apps menu for the room you want the notifications to be delivered to. You're given a token and a webhook URL as part of the app creation.

## Webhook

Webhooks allows for a range of custom integrations. It's pretty similar to the other services in terms of setup though, as you just need to provide the URL of the webhook we'll need to call.

#### Webhook Payload

When sending the notification to a webhook, we send an HTTP POST request containing the following build data

```json
{
  "build": {
    "build_url":"https://www.codeship.com/projects/10213/builds/973711",
    "commit_url":"https://github.com/codeship/docs/
                  commit/96943dc5269634c211b6fbb18896ecdcbd40a047",
    "project_id":10213,
    "build_id":973711,
    "status":"initiated",
    # PROJECT_FULL_NAME IS DEPRECATED AND WILL BE REMOVED IN THE FUTURE
    "project_full_name":"codeship/docs",
    "project_name":"codeship/docs",
    "commit_id":"96943dc5269634c211b6fbb18896ecdcbd40a047",
    "short_commit_id":"96943",
    "message":"Merge pull request #34 from codeship/feature/shallow-clone",
    "committer":"beanieboi",
    "branch":"master"
  }
}
```

The _status_ field can have one of the following values:

- `initiated` for newly started build
- `error` for failed builds
- `success` for passed builds
- `stopped` for stopped builds
- `waiting` for waiting builds
- `ignored` for builds ignored because the account is over the monthly build limit
- `blocked` for builds blocked because of excessive resource consumption
- `infrastructure_failure` for builds which failed because of an internal error on the build VM

## Custom Notifications With Codeship Pro

Due to Codeship Pro's unique architecture, you have  more flexibility in implementing custom notifications via your [codeship-steps.yml file]({% link _pro/builds-and-configuration/steps.md %}).

In addition to using the above webhooks method, you can also define custom steps in your build pipeline to push notifications via methods not otherwise supported by Codeship.

#### The Notification Script

To look at using your Codeship Pro pipeline for flexible, custom notifications we will review a simple Slack script as a custom notification method.

First of all, we can create a simple notification script, pulling all configuration and credentials from environment variables, or mounted volumes should we need to use build artifacts.

```shell
#!/bin/sh
# Post to Slack channel on new deployment
# https://api.slack.com/incoming-webhooks

# script available at: https://github.com/codeship/scripts/blob/master/notifications/slack.sh

# You can either add those here, or configure them on the environment tab of your
# project settings.

SLACK_WEBHOOK_TOKEN=${SLACK_WEBHOOK_TOKEN:?'You need to configure the SLACK_WEBHOOK_TOKEN environment variable!'}
SLACK_BOT_NAME=${SLACK_BOT_NAME:="Codeship Bot"}
SLACK_ICON_URL=${SLACK_ICON_URL:="https://d1089v03p3mzyq.cloudfront.net/assets/website/logo-dark-90f893a2645c98929b358b2f93fa614b.png"}
SLACK_MESSAGE=${SLACK_MESSAGE:?"${CI_COMMITTER_USERNAME} just deployed version ${CI_COMMIT_ID}"}

curl -X POST \
  -H "Content-Type: application/json" \
  -d '{"username": "'"${SLACK_BOT_NAME}"'",
  "text": "'"${SLACK_MESSAGE}"'",
  "icon_url": "'"${SLACK_ICON_URL}"'"}' \
  https://hooks.slack.com/services/$SLACK_WEBHOOK_TOKEN
```

#### Integrating the Notification Script

It's quite simple to integrate a simple script like this into the deployment pipeline. First we can build it into a standalone container, or use an existing one from elsewhere in the pipeline which has the deploy script added to it.

```dockerfile
# Dockerfile.notify
FROM ubuntu

RUN apt-get install -y curl

COPY ./slack ./
```

We'll need to provide this container with the necessary environment variables. The standard `CI_*` variables will be provided automatically, however we'll need to provide the `SLACK_WEBHOOK_TOKEN`. This can be safely injected via the `encrypted_env_file` service declaration, and the [encryption commands]({{ site.baseurl }}{% link _pro/jet-cli/encrypt.md %}). By encrypting this environment variable, and adding it to our repository, it can be later decoded and provided to our notifications container.

```yaml
deploynotify
  build:
    image: myuser/myrepo-deploynotify
    dockerfile: Dockerfile.notify
  encrypted_env_file: deploy.env.encrypted
```

By adding a relevant step to the steps file, we can control under what conditions this notification fires.

```yaml
- service: deploynotify
  command: ./slack
  tag: master
```

#### Other Integrations With Codeship Pro

Since you can integrate any container you wish into your pipeline, there are no limitations on what notifications you can use. In our scripts repo, [you can see other examples of custom notifications.](https://github.com/codeship/scripts/tree/master/notifications).

## Other Ways to Get Notified

### GitHub, Bitbucket and Gitlab Status API

We will automatically use the status API for pull requests on Github, Bitbucket and Gitlab. This does not need to be explicitly enabled, although it can be disabled via the **General** settings of your project.

### Status Badges On Your Repo

If you want to add a badge showing your last builds status to your ReadMe, you can find the code in the **General** settings of your project.

![Codeship Status for codeship/documentation](https://codeship.com/projects/0bdb0440-3af5-0133-00ea-0ebda3a33bf6/status?branch=master)

The raw URL for the image looks like the this:

```
https://codeship.com/projects/YOUR_PROJECT_UUID/status?branch=BRANCH_NAME
```

(The UUID for a specific project is also available on the **General** tab in your project settings)

### CCMenu

CCMenu is not supported at this time, although we hope to address it at a later stage.


text:
package com.laytonsmith.core;

import com.laytonsmith.abstraction.MCPlayer;
import com.laytonsmith.abstraction.MCServer;
import com.laytonsmith.core.constructs.Target;
import com.laytonsmith.core.constructs.Token;
import com.laytonsmith.core.constructs.Variable;
import com.laytonsmith.core.environments.CommandHelperEnvironment;
import com.laytonsmith.core.exceptions.ConfigCompileException;
import com.laytonsmith.core.exceptions.ConfigCompileGroupException;
import com.laytonsmith.core.exceptions.ConfigRuntimeException;
import com.laytonsmith.testing.StaticTest;
import static com.laytonsmith.testing.StaticTest.RunCommand;
import static com.laytonsmith.testing.StaticTest.SRun;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.After;
import org.junit.AfterClass;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
//import org.powermock.api.mockito.PowerMockito;
//import org.powermock.core.classloader.annotations.PowerMockIgnore;
//import org.powermock.core.classloader.annotations.PrepareForTest;
//import org.powermock.modules.junit4.PowerMockRunner;

/**
 *
 *
 */
//@RunWith(PowerMockRunner.class)
//@PrepareForTest(CommandHelperPlugin.class)
//@PowerMockIgnore({"javax.xml.parsers.*", "com.sun.org.apache.xerces.internal.jaxp.*"})
public class MethodScriptCompilerTest {

    MCServer fakeServer;
    MCPlayer fakePlayer;
    com.laytonsmith.core.environments.Environment env;

    public MethodScriptCompilerTest() {
		//StaticTest.InstallFakeServerFrontend();
    }

    @BeforeClass
    public static void setUpClass() throws Exception {
		StaticTest.InstallFakeServerFrontend();
    }

    @AfterClass
    public static void tearDownClass() throws Exception {
		new File("profiler.config").deleteOnExit();
    }

    @Before
    public void setUp() throws Exception {
        fakePlayer = StaticTest.GetOnlinePlayer();
        fakeServer = StaticTest.GetFakeServer();
		env = Static.GenerateStandaloneEnvironment();
        env.getEnv(CommandHelperEnvironment.class).SetPlayer(fakePlayer);
    }

    @After
    public void tearDown() {
    }

    /**
     * Test of lex method, of class MethodScriptCompiler.
     */
    @Test
    public void testLex() throws Exception {
        String config = "/cmd = msg('string')";
        List e = null;
        e = new ArrayList();
        //This is the decomposed version of the above config
        e.add(new Token(Token.TType.COMMAND, "/cmd", Target.UNKNOWN));
        e.add(new Token(Token.TType.WHITESPACE, " ", Target.UNKNOWN));
        e.add(new Token(Token.TType.ALIAS_END, "=", Target.UNKNOWN));
        e.add(new Token(Token.TType.WHITESPACE, " ", Target.UNKNOWN));
        e.add(new Token(Token.TType.FUNC_NAME, "msg", Target.UNKNOWN));
        e.add(new Token(Token.TType.FUNC_START, "(", Target.UNKNOWN));
        e.add(new Token(Token.TType.STRING, "string", Target.UNKNOWN));
        e.add(new Token(Token.TType.FUNC_END, ")", Target.UNKNOWN));
        e.add(new Token(Token.TType.NEWLINE, "\n", Target.UNKNOWN));

        List result = MethodScriptCompiler.lex(config, null, false);
        assertEquals(e, result);

        String[] badConfigs = {
            "'\\q'", //Bad escape sequences
            "'\\m'",};
        for (String c : badConfigs) {
            try {
                MethodScriptCompiler.lex(c, null, false);
                //Shouldn't get here
                fail(c + " should not have lexed, but did.");
            } catch (ConfigCompileException ex) {
                //Success!
            }
        }
    }

    @Test
    public void testCompile() throws Exception {
        MethodScriptCompiler.preprocess(MethodScriptCompiler.lex("/cmd = msg('this is a string', if(true, 'and', 'another') 'function')", null, false)).get(0).compileRight();
        try {
            //extra parameter
            MethodScriptCompiler.preprocess(MethodScriptCompiler.lex("/cmd = msg('this is a string', if(true, 'and', 'another', 'oops') 'function')", null, false)).get(0).compileRight();
            fail("Did not expect test to pass");
        } catch (ConfigCompileException e) {
            //passed
        }
        try {
            //missing parenthesis
            MethodScriptCompiler.preprocess(MethodScriptCompiler.lex("/cmd = msg('this is a string', if(true, 'and', 'another') 'function'", null, false)).get(0).compileRight();
            fail("Did not expect test to pass");
        } catch (ConfigCompileException e) {
            //passed
        }
        try {
            //extra parenthesis
            MethodScriptCompiler.preprocess(MethodScriptCompiler.lex("/cmd = msg('this is a string', if(true, 'and', 'another') 'function')))))", null, false)).get(0).compileRight();
            fail("Did not expect test to pass");
        } catch (ConfigCompileException e) {
            //passed
        }
        try {
            //extra multiline end construct
            MethodScriptCompiler.preprocess(MethodScriptCompiler.lex("/cmd = msg('this is a string', if(true, 'and', 'another') 'function') <<<", null, false)).get(0).compileRight();
            fail("Did not expect test to pass");
        } catch (ConfigCompileException e) {
            //passed
        }

        try{
            //no multiline end construct
            MethodScriptCompiler.preprocess(MethodScriptCompiler.lex("/cmd = >>>\nmsg('hi')\n", null, false)).get(0).compileRight();
            fail("Did not expect no multiline end construct to pass");
        } catch(ConfigCompileException e){
            //passed
        }

        MethodScriptCompiler.compile(MethodScriptCompiler.lex("if(1, msg('') msg(''))", null, true));

    }

    @Test public void testLabel() throws Exception{
        assertEquals(PermissionsResolver.GLOBAL_PERMISSION, MethodScriptCompiler.preprocess(MethodScriptCompiler.lex("*:/cmd = die()", null, false)).get(0).compile().getLabel());
        assertEquals(PermissionsResolver.GLOBAL_PERMISSION, MethodScriptCompiler.preprocess(MethodScriptCompiler.lex("* : /cmd = die()", null, false)).get(0).compile().getLabel());
        assertEquals("~lol/fun", MethodScriptCompiler.preprocess(MethodScriptCompiler.lex("~lol/fun: /cmd = die()", null, false)).get(0).compile().getLabel());
    }

    @Test
    public void testCompile13() throws Exception{
        MethodScriptCompiler.compile(MethodScriptCompiler.lex("msg ('hi')", null, true));
    }

    @Test public void testCompile14() throws Exception{
        MethodScriptCompiler.compile(MethodScriptCompiler.lex("msg(('hi'))", null, true));
    }

    @Test
    public void testCompile15() throws Exception{
        try{
            SRun("\n\nmsg(/, 'test')\n\n", fakePlayer);
        } catch(ConfigCompileException e){
            assertEquals("3", e.getLineNum());
        }
    }

    @Test
    public void testExecute1() throws Exception {
        String script = "proc(_hello, @hello0,"
                + "         msg(@hello0)"
                + "      )"
                + "      assign(@hello1, 'hello')"
                + "      _hello(@hello1)";

        MethodScriptCompiler.execute(MethodScriptCompiler.compile(MethodScriptCompiler.lex(script, null, true)), env, null, null);
        verify(fakePlayer).sendMessage("hello");
    }

    @Test
    public void testExecute2() throws Exception {
        String script =
                "proc(_hello,\n"
                + "     assign(@hello, 'hello')\n"
                + "     return(@hello)\n"
                + ")\n"
                + "assign(@blah, 'blah')\n"
                + "assign(@blah, _hello())\n"
                + "msg(@blah)\n";

        MethodScriptCompiler.execute(MethodScriptCompiler.compile(MethodScriptCompiler.lex(script, null, true)), env, null, null);
        verify(fakePlayer).sendMessage("hello");
    }

    /**
     * Here we are testing for mismatched (or empty) square brackets. Essentially, it should throw an exception.
     */
    @Test
    public void testExecute3() {
        try {
            String script =
                    "[";
            MethodScriptCompiler.execute(MethodScriptCompiler.compile(MethodScriptCompiler.lex(script, null, true)), env, null, null);
            fail("Test passed, but wasn't supposed to");
        } catch (ConfigCompileException|ConfigCompileGroupException ex) {
            //Passed
        }
        try {
            String script =
                    "]";
            MethodScriptCompiler.execute(MethodScriptCompiler.compile(MethodScriptCompiler.lex(script, null, true)), env, null, null);
            fail("Test passed, but wasn't supposed to");
        } catch (ConfigCompileException|ConfigCompileGroupException ex) {
            //Passed
        }
    }

    @Test
    public void testExecute4() throws Exception {
        String script =
                "proc(_hello,"
                + "     return('hello')"
                + ")"
                + "msg(_hello())";
        MethodScriptCompiler.execute(MethodScriptCompiler.compile(MethodScriptCompiler.lex(script, null, true)), env, null, null);
        verify(fakePlayer).sendMessage("hello");
    }

    @Test
    public void testExecute5() throws Exception {
        String script =
                "proc(_hello,"
                + "     return('hello')"
                + ")"
                + "msg(_hello())";
        MethodScriptCompiler.execute(MethodScriptCompiler.compile(MethodScriptCompiler.lex(script, null, true)), env, null, null);
        verify(fakePlayer).sendMessage("hello");
    }

    @Test
    public void testExecute6() throws Exception {
        String script =
                "#This is a comment invalid()'\"'' function\n"
                + "msg('hello')";
        MethodScriptCompiler.execute(MethodScriptCompiler.compile(MethodScriptCompiler.lex(script, null, true)), env, null, null);
        verify(fakePlayer).sendMessage("hello");
    }

    @Test
    public void testExecute7() throws Exception {
        String script =
                "msg('hello') #This is a comment too invalid()'\"'' function\n";
        MethodScriptCompiler.execute(MethodScriptCompiler.compile(MethodScriptCompiler.lex(script, null, true)), env, null, null);
        verify(fakePlayer).sendMessage("hello");
    }

    @Test
    public void testExecute9() throws Exception {
        String script =
                "msg('hello') /* This is a comment too invalid()'\"'' function\n"
                + "yup, still a comment. yay() */";
        MethodScriptCompiler.execute(MethodScriptCompiler.compile(MethodScriptCompiler.lex(script, null, true)), env, null, null);
        verify(fakePlayer).sendMessage("hello");
    }

    @Test(expected = ConfigCompileException.class)
    public void testExecute10() throws Exception {
        String script =
                "msg('hello') /* This is a comment too invalid()'\"'' function\n"
                + "yup, still a comment. yay() This will fail though, because the comment is unended.";
        MethodScriptCompiler.execute(MethodScriptCompiler.compile(MethodScriptCompiler.lex(script, null, true)), env, null, null);
    }

    @Test(expected = ConfigCompileException.class)
    public void testExecute11() throws Exception {
        String script =
                "msg('hello') 'unended string";
        MethodScriptCompiler.execute(MethodScriptCompiler.compile(MethodScriptCompiler.lex(script, null, true)), env, null, null);
    }

    @Test
    public void testExecute12() throws Exception {
        String script =
                "msg('hello') /* This is a comment too invalid()'\"'' function\n"
                + "yup, still a comment. yay() */";
        MethodScriptCompiler.execute(MethodScriptCompiler.compile(MethodScriptCompiler.lex(script, null, true)), env, null, null);
        verify(fakePlayer).sendMessage("hello");
    }

    @Test
    public void testExecute13() throws Exception {
        String script =
                "assign(@a, array(0, 1, 2))"
                + "msg(@a[0])";
        MethodScriptCompiler.execute(MethodScriptCompiler.compile(MethodScriptCompiler.lex(script, null, true)), env, null, null);
        verify(fakePlayer).sendMessage("0");
    }

    @Test
    public void testExecute14() throws Exception {
        String script =
                "proc(_hello, assign(@i, 'world'),"
                + "     return(@i)"
                + ")"
                + "msg(_hello('hello'))"
                + "msg(_hello())";
        MethodScriptCompiler.execute(MethodScriptCompiler.compile(MethodScriptCompiler.lex(script, null, true)), env, null, null);
        verify(fakePlayer).sendMessage("hello");
        verify(fakePlayer).sendMessage("world");
    }

    @Test public void testExecute15() throws Exception{
        String script =
                "assign(@i, 0)\n"
                + "msg('@i is currently' @i)\n"
                + "proc(_out, @i,\n"
                + "     msg(trim('@i is currently' @i 'and @j is' @j))\n"
                + ")\n"
                + "_out('hello')\n"
                + "assign(@j, 'goodbye')\n"
                + "_out('world')\n";
        MethodScriptCompiler.execute(MethodScriptCompiler.compile(MethodScriptCompiler.lex(script, null, true)), env, null, null);
        verify(fakePlayer).sendMessage("@i is currently 0");
        verify(fakePlayer).sendMessage("@i is currently hello and @j is null");
        verify(fakePlayer).sendMessage("@i is currently world and @j is null");
    }

    @Test public void testExecute16() throws Exception{
        String script =
                "proc(_myProc, @i, @j, @k, msg(trim(@i @j @k)))\n"
                + "_myProc()\n"
                + "_myProc(1)\n"
                + "_myProc(1, 2)\n"
                + "_myProc(1, 2, 3)\n"
                + "_myProc(1, 2, 3, 4)\n";
        MethodScriptCompiler.execute(MethodScriptCompiler.compile(MethodScriptCompiler.lex(script, null, true)), env, null, null);
        verify(fakePlayer).sendMessage("1");
        verify(fakePlayer).sendMessage("1 2");
        verify(fakePlayer, times(2)).sendMessage("1 2 3");
    }

    @Test public void testExecute17() throws Exception{
        String script =
                "proc(_addition, @i, @j, msg(add(@i, @j)))\n"
                + "_addition(1, 1)\n"
                + "_addition(2, 2)";
        MethodScriptCompiler.execute(MethodScriptCompiler.compile(MethodScriptCompiler.lex(script, null, true)), env, null, null);
        //verify(fakePlayer).sendMessage("null null null");
        verify(fakePlayer).sendMessage("2");
        verify(fakePlayer).sendMessage("4");
    }

    @Test public void testExecute18() throws Exception{
        String script =
                "proc(_myProc, msg(@arguments))\n"
                + "_myProc()\n"
                + "_myProc(1)\n"
                + "_myProc(1, 2)";
        MethodScriptCompiler.execute(MethodScriptCompiler.compile(MethodScriptCompiler.lex(script, null, true)), env, null, null);
        //verify(fakePlayer).sendMessage("null null null");
        verify(fakePlayer).sendMessage("{}");
        verify(fakePlayer).sendMessage("{1}");
        verify(fakePlayer).sendMessage("{1, 2}");
    }

    /**
     * Variables are locked in when the procedure is defined
     * @throws Exception
     */
    @Test
    public void testExecute19() throws Exception {
        String script =
                "assign(@j, 'world')\n"
                + "proc(_hello, assign(@i, @j),"
                + "     return(@i)"
                + ")\n"
                + "assign(@j, 'goodbye')\n"
                + "msg(_hello('hello'))"
                + "msg(_hello())";
        MethodScriptCompiler.execute(MethodScriptCompiler.compile(MethodScriptCompiler.lex(script, null, true)), env, null, null);
        verify(fakePlayer).sendMessage("hello");
        verify(fakePlayer).sendMessage("world");
    }
    @Test
    public void testExecute20() throws Exception {
        final AtomicBoolean bool = new AtomicBoolean(false);
        String script =
                "msg('hello') world";
        MethodScriptCompiler.execute(MethodScriptCompiler.compile(MethodScriptCompiler.lex(script, null, true)), env, new MethodScriptComplete() {

			@Override
            public void done(String output) {
                assertEquals("world", output.trim());
                bool.set(true);
            }
        }, null);
        verify(fakePlayer).sendMessage("hello");
        assertTrue(bool.get());
    }

    @Test
    public void testExecute21() throws Exception{
        String script = "#*\n"
                + "msg('Not a comment')\n"
                + "#*#";
        SRun(script, fakePlayer);
        verify(fakePlayer).sendMessage("Not a comment");
    }

    @Test public void testExecute22() throws Exception{
        SRun("msg('hi' (this is a thing))", fakePlayer);
        verify(fakePlayer).sendMessage("hi this is a thing");
    }

    @Test
    public void testCompile1() {
        try {
            String config = "/cmd [$p] $q = msg('')";
            MethodScriptCompiler.preprocess(MethodScriptCompiler.lex(config, null, false)).get(0).compile();
            fail("Test passed, but wasn't supposed to");
        } catch (ConfigCompileException|ConfigCompileGroupException ex) {
            //Passed
        }
    }

//    @Test
//    public void testCompileWithDoubleSlashCommand() throws Exception{
//        AliasCore ac = mock(AliasCore.class);
//        ac.autoIncludes = new ArrayList<File>();
//        PowerMockito.mockStatic(CommandHelperPlugin.class);
//        when(CommandHelperPlugin.getCore()).thenReturn(ac);
//        assertEquals(ac, CommandHelperPlugin.getCore());
//        String config = "//cmd blah = msg('success')";
//        Script s = MethodScriptCompiler.preprocess(MethodScriptCompiler.lex(config, null, false)).get(0);
//        s.compile();
//        env.getEnv(CommandHelperEnvironment.class).SetPlayer(fakePlayer);
//        s.run(Arrays.asList(new Variable("$var", "hello", Target.UNKNOWN)), env, null);
//        verify(fakePlayer).sendMessage("success");
//    }
//
//    @Test
//    public void testCompileTwoAliases() throws Exception{
//        AliasCore ac = mock(AliasCore.class);
//        ac.autoIncludes = new ArrayList<File>();
//        PowerMockito.mockStatic(CommandHelperPlugin.class);
//        when(CommandHelperPlugin.getCore()).thenReturn(ac);
//        assertEquals(ac, CommandHelperPlugin.getCore());
//        String config = "/cmd1 = msg('success')\n"
//                + "                 \n" //Spaces and tabs are here
//                + "/cmd2 = msg('success')";
//        env.getEnv(CommandHelperEnvironment.class).SetPlayer(fakePlayer);
//        Script s1 = MethodScriptCompiler.preprocess(MethodScriptCompiler.lex(config, null, false)).get(0);
//        s1.compile();
//        s1.run(Arrays.asList(new Variable("$var", "hello", Target.UNKNOWN)), env, null);
//        Script s2 = MethodScriptCompiler.preprocess(MethodScriptCompiler.lex(config, null, false)).get(1);
//        s2.compile();
//        s2.run(Arrays.asList(new Variable("$var", "hello", Target.UNKNOWN)), env, null);
//        verify(fakePlayer, times(2)).sendMessage("success");
//    }

    @Test
    public void testCompile2() {
        try {
            String config = "/cmd [$p=player()] = msg('')";
            MethodScriptCompiler.preprocess(MethodScriptCompiler.lex(config, null, false)).get(0).compile();
            fail("Test passed, but wasn't supposed to");
        } catch (ConfigCompileException|ConfigCompileGroupException ex) {
            //Passed
        }
    }

    @Test
    public void testCompile4() throws Exception {
        String config = "/cmd = >>>\n"
                + "msg('hello') #This is a comment too invalid()'\"'' function\n"
                + "<<<";
        MethodScriptCompiler.preprocess(MethodScriptCompiler.lex(config, null, false));
    }

    @Test
    public void testCompile5() throws Exception {
        String config = "label:/cmd = >>>\n"
                + "msg('hello') #This is a comment too invalid()'\"'' function\n"
                + "<<<";
        Script s = MethodScriptCompiler.preprocess(MethodScriptCompiler.lex(config, null, false)).get(0);
        s.compile();
        assertEquals("label", s.getLabel());
    }

    @Test
    public void testCompile6() throws Exception {
        String config = "/cmd = >>>\n"
                + "msg(trim(hello 'world \\\\ \\' \\n'))"
                + "<<<";
        RunCommand(config, fakePlayer, "/cmd");
        verify(fakePlayer).sendMessage("hello world \\ '");
    }

    @Test
    public void testCompile7() throws Exception {
        String config = "/cmd = >>>\n"
                + "msg(hello) \\ msg(world)"
                + "<<<";
        RunCommand(config, fakePlayer, "/cmd");
        verify(fakePlayer).sendMessage("hello");
        verify(fakePlayer).sendMessage("world");
    }

    //TODO: Make these tests possible
//    @Test
//    public void testCompile8() throws Exception {
//        String config = "/cmd $one $ = >>>\n"
//                + "msg($one) \\ msg($)"
//                + "<<<";
//
//        RunVars(Arrays.asList(new Variable[]{new Variable("$one", "first", false, false, Target.UNKNOWN),
//            new Variable("$", "several variables", false, true, Target.UNKNOWN)}), config, fakePlayer);
//        Script s = MethodScriptCompiler.preprocess(MethodScriptCompiler.lex(config, null), env).get(0);
//        s.compile();
//        s.run(Arrays.asList(new Variable[]{new Variable("$one", "first", false, false, Target.UNKNOWN),
//            new Variable("$", "several variables", false, true, Target.UNKNOWN)}), env, null);
//        verify(fakePlayer).sendMessage("first");
//        verify(fakePlayer).sendMessage("several variables");
//    }
//
//    @Test
//    public void testCompile9() throws Exception {
//        String config = "/test [$var=1] = >>>\n"
//                + "msg($var)"
//                + "<<<";
//        Script s = MethodScriptCompiler.preprocess(MethodScriptCompiler.lex(config, null), env).get(0);
//        s.compile();
//        assertTrue(s.match("/test 2"));
//        s.run(Arrays.asList(new Variable[]{new Variable("$var", "2", true, false, Target.UNKNOWN)}), env, null);
//        verify(fakePlayer).sendMessage("2");
//        assertTrue(s.match("/test"));
//        s.run(new ArrayList<Variable>(), env, null);
//        verify(fakePlayer).sendMessage("1");
//    }

    @Test
    public void testCompile10() throws Exception{
        String config = "/test $var = >>>\n"
                + "msg($var)"
                + "<<<";
        Script s = MethodScriptCompiler.preprocess(MethodScriptCompiler.lex(config, null, false)).get(0);
        s.compile();
        assertTrue(s.match("/test 2"));
        assertFalse(s.match("/test"));
        s.run(Arrays.asList(new Variable[]{new Variable("$var", "2", true, false, Target.UNKNOWN)}), env, null);
    }

    //TODO: Make this test possible
//    @Test public void testCompile11() throws Exception{
//
//        CommandHelperPlugin.perms = mock(PermissionsResolverManager.class);
//        when(CommandHelperPlugin.perms.hasPermission(fakePlayer.getName(), "ch.alias.safe")).thenReturn(true);
//        CommandHelperPlugin.myServer = fakeServer;
//        when(fakeServer.getOnlinePlayers()).thenReturn(new MCPlayer[]{fakePlayer});
//        String config = "safe:/test $var = >>>\n"
//                + "all_players()\n"
//                + "msg($var)\n"
//                + "<<<";
//        Script s = MethodScriptCompiler.preprocess(MethodScriptCompiler.lex(config, null), env).get(0);
//        s.compile();
//        assertEquals("safe", s.getLabel());
//        assertTrue(s.match("/test 2"));
//        s.run(Arrays.asList(new Variable[]{new Variable("$var", "2", true, false, Target.UNKNOWN)}), env, null);
//        verify(fakePlayer).sendMessage("2");
//        verify(CommandHelperPlugin.perms).hasPermission(fakePlayer.getName(), "ch.alias.safe");
//    }

    @Test public void testCompile12() throws Exception{
        String config = "/*/one = bad()*/\n"
                + "/two = msg('Good')\n";
        Script s = MethodScriptCompiler.preprocess(MethodScriptCompiler.lex(config, null, false)).get(0);
        s.compile();
        assertFalse(s.match("/one"));
        assertTrue(s.match("/two"));
    }

    @Test public void testUnicode() throws Exception{
        SRun("msg('\\u0037 is win!')", fakePlayer);
        verify(fakePlayer).sendMessage("7 is win!");
        SRun("msg('\\u20ac')", fakePlayer);
        verify(fakePlayer).sendMessage("€");
    }

    @Test public void testInfixMath1() throws Exception{
        assertEquals("4", SRun("2 + 2", fakePlayer));
        assertEquals("4", SRun("8 - 4", fakePlayer));
        assertEquals("4", SRun("2 * 2", fakePlayer));
        assertEquals("4", SRun("16/4", fakePlayer));
    }

    @Test public void testInfixMath2() throws Exception{
        assertEquals("2", SRun("-2 + 2 + 2", fakePlayer));
        assertEquals("18", SRun("(2 + 4) * 3", fakePlayer));
        assertEquals("14", SRun("2 + 4 * 3", fakePlayer));
    }

    @Test public void testInfixMath3() throws Exception{
        assertEquals("8.0", SRun("2 ** 3", fakePlayer));
    }

    @Test public void testUnary() throws Exception{
        assertEquals("1", SRun("2 + - 1", fakePlayer));
    }

    @Test public void testSymbolicConcat() throws Exception{
        SRun("@hello = 'hello'\n"
				+ "@world = 'world'\n"
				+ "msg(@hello.@world)", fakePlayer);
		verify(fakePlayer).sendMessage("helloworld");
    }

    @Test public void testSymbolicLogic1() throws Exception{
        assertEquals("true", SRun("2 <= 5", fakePlayer));
        assertEquals("false", SRun("2 === '2'", fakePlayer));
        assertEquals("true", SRun("g(assign(@var, false)) !@var", fakePlayer));
    }

    @Test public void testSymbolicLogic2() throws Exception{
        assertEquals("true", SRun("true || true", fakePlayer));
        assertEquals("false", SRun("true && false", fakePlayer));
    }

    @Test public void testComplexSymbolicLogic() throws Exception{
        assertEquals("true", SRun("2 == 2 && true", fakePlayer));
    }

    @Test public void testSymbolCompileError() throws Exception {
        try{
            SRun("(+ * 2)", fakePlayer);
            fail("Did not expect test to pass");
        } catch(ConfigCompileException e){
            //pass
        } catch(ConfigRuntimeException e){
            //pass?
        }
    }

    @Test public void testComplexSymbols() throws Exception{
        SRun("assign(@var, 2) if((@var + 2) == 4, msg('Success!'))", fakePlayer);
        verify(fakePlayer).sendMessage("Success!");
    }

    @Test public void testPostfix() throws Exception{
        SRun("assign(@var, 2) msg(@var++) msg(@var)", fakePlayer);
        verify(fakePlayer).sendMessage("2");
        verify(fakePlayer).sendMessage("3");
    }

    @Test public void testPrefix() throws Exception{
        SRun("assign(@var, 2) msg(++@var) msg(@var)", fakePlayer);
        verify(fakePlayer, times(2)).sendMessage("3");
    }

    @Test public void testModulo() throws Exception{
        assertEquals(Integer.toString(2 % 3), SRun("2 % 3", fakePlayer));
    }

    @Test public void TestOperationsWithFunction() throws Exception{
        SRun("if(!and(false, false), msg('yes'))", fakePlayer);
        verify(fakePlayer).sendMessage("yes");
    }

    @Test public void testArrayBooleanType() throws Exception{
        assertEquals("true", SRun("boolean(array(1))", null));
        assertEquals("false", SRun("boolean(array())", null));
    }

    @Test public void testParenthesisAfterQuotedString() throws Exception{
        assertEquals("2 + 2 is 4", SRun("'2 + 2 is' (2 + 2)", fakePlayer));
    }

    @Test(expected=ConfigCompileException.class)
    public void testCompileErrorOfStaticConstructOptimization() throws Exception{
        MethodScriptCompiler.compile(MethodScriptCompiler.lex("2 / 0", null, true));
    }

    @Test public void testLineNumberCorrectInException1() throws Exception{
        String script =
                "try(\n" //Line 1
                + "assign(@a, array(1, 2))\n" //Line 2
                + "\n" //Line 3
                + "assign(@d, @a[@b])\n" //Line 4
                + "\n" //Line 5
                + ", @e, msg(@e[3]))\n"; //Line 6
        SRun(script, fakePlayer);
        verify(fakePlayer).sendMessage("4");
    }

    @Test public void testLineNumberCorrectInException2() throws Exception{
        String script =
                "assign(@a, array(1, 2))\n" //Line 1
                + "\n" //Line 2
                + "assign(@d, @a[@b])\n"; //Line 3
        try{
            SRun(script, fakePlayer);
        } catch(ConfigRuntimeException e){
            assertEquals(3, e.getLineNum());
        }

    }

    @Test public void testLineNumberCorrectInException3() throws Exception{
        String script =
                "\n"
                + "assign(@a, array('aaa', 'bbb'))\n"
                + "assign(@b, 'test')\n"
                + "msg('test1')\n"
                + "assign(@d, @a[@b])\n"
                + "msg('test2')\n";
        try{
            SRun(script, fakePlayer);
        } catch(ConfigRuntimeException e){
            assertEquals(5, e.getLineNum());
        }
    }

    @Test public void testExtraParenthesis() throws Exception {
        try{
            SRun("\n"
                    + "\n"
                    + "player())\n", fakePlayer);
        } catch(ConfigCompileException e){
            assertEquals("3", e.getLineNum());
        }
    }

    @Test(expected=ConfigCompileException.class)
    public void testSpuriousSymbols() throws Exception{
        SRun("2 +", fakePlayer);
    }

    @Test
    public void testBraceIf() throws Exception{
        SRun("if(true)\n\n"
                + "{\n"
                + "msg('success!')\n"
                + "}", fakePlayer);
        verify(fakePlayer).sendMessage("success!");
    }

    @Test
    public void testBraceElseIfElse() throws Exception{
        SRun("if(false){"
                + "msg('fail')"
                + "} else if(true == true){"
                + "msg('success!')"
                + "} else {\n"
                + "msg('fail')"
                + "}", fakePlayer);
        verify(fakePlayer).sendMessage("success!");
    }

    @Test
    public void testBraceElseIfElseWithElseCondTrue() throws Exception{
        SRun("if(false){"
                + "msg('fail')"
                + "} else if(false){"
                + "msg('fail')"
                + "} else {"
                + "msg('success!')"
                + "}", fakePlayer);
        verify(fakePlayer).sendMessage("success!");
    }

    @Test(expected=ConfigCompileException.class)
    public void testFailureOfBraces() throws Exception{
        SRun("and(1){ 1 }", fakePlayer);
    }

    @Test(expected=ConfigCompileException.class)
    public void testInnerElseInElseIf() throws Exception{
        SRun("if(true){"
                + "msg('fail')"
                + "} else {"
                + "msg('fail')"
                + "} else if(true){"
                + "msg('fail')"
                + "}", fakePlayer);
    }

    @Test
    public void testBracketsOnFor() throws Exception{
        SRun("for(assign(@i, 0), @i < 5, @i++){\n"
                + "msg('worked')\n"
                + "}", fakePlayer);
        verify(fakePlayer, times(5)).sendMessage("worked");
    }

    @Test
    public void testBracketsOnForeach() throws Exception{
        SRun("foreach(range(2), @i){\n"
                + "msg(@i)\n"
                + "}", fakePlayer);
        verify(fakePlayer).sendMessage("0");
        verify(fakePlayer).sendMessage("1");
    }

    @Test public void testWhitespaceInBetweenFunctionAndParen() throws Exception{
        SRun("msg ('hi')", fakePlayer);
        verify(fakePlayer).sendMessage("hi");
    }

    @Test public void testMultipleFunctionsWithBraces() throws Exception{
        SRun("if(dyn(false)){\n"
                + "msg('nope')\n"
                + "} else {\n"
                + " msg('hi')\n"
                + " msg('hi')\n"
                + "}", fakePlayer);
        verify(fakePlayer, times(2)).sendMessage("hi");
    }

    @Test
    public void testArrayGetCatchesInvalidParameter() throws Exception {
        try{
            try {
                SRun("1[4]", null);
                fail("Did not expect test to pass");
            } catch(ConfigCompileException e){
                //Pass
            }
            try {
                SRun("'string'['index']", null);
                fail("Did not expect test to pass");
            } catch(ConfigCompileException e){
                //Pass
            }
        } catch(ConfigRuntimeException e){
            fail("Expecting a compile error here, not a runtime exception");
        }
    }

    @Test
    public void testBlockComments1() throws Exception{
        SRun(     "/*\n"
                + " * Herp\n"
                + " * Derp\n"
                + " */\n"
				+ "msg('hi');", fakePlayer);
    }

    @Test
    public void testCommentsInStrings() throws Exception{
	    SRun("'#'", fakePlayer);
    }

    @Test
    public void testCommentsInStrings2() throws Exception{
	    SRun("'/*'", fakePlayer);
    }

	@Test
	public void testDoubleQuotesInSingleQuotes() throws Exception{
		SRun("'This \"should work\" correctly, and not throw an exception'", null);
	}

	@Test public void testClosureToString1() throws Exception{
		SRun("msg(closure(msg('')))", fakePlayer);
		verify(fakePlayer).sendMessage("msg('')");
	}

	@Test public void testClosureToString2() throws Exception{
		SRun("msg(closure('\\n'))", fakePlayer);
		verify(fakePlayer).sendMessage("'\\n'");
	}

	@Test public void testClosureToString3() throws Exception{
		SRun("msg(closure('\\\\'))", fakePlayer);
		verify(fakePlayer).sendMessage("'\\\\'");
	}

	@Test public void testClosureToString4() throws Exception{
		SRun("msg(closure('\\''))", fakePlayer);
		verify(fakePlayer).sendMessage("'\\''");
	}

	@Test public void testCSlices() throws Exception{
		assertEquals("-1", SRun("p(-1..-3[0])", null));
		assertEquals("-2", SRun("p(-1..-3[1])", null));
		assertEquals("-3", SRun("p(-1..-3[2])", null));

		assertEquals("0", SRun("p(0..2[0])", null));
		assertEquals("1", SRun("p(0..2[1])", null));
		assertEquals("2", SRun("p(0..2[2])", null));

		assertEquals("5", SRun("p(5..3[0])", null));
		assertEquals("4", SRun("p(5..3[1])", null));
		assertEquals("3", SRun("p(5..3[2])", null));

		assertEquals("1", SRun("p(1..3[0])", null));
		assertEquals("2", SRun("p(1..3[1])", null));
		assertEquals("3", SRun("p(1..3[2])", null));

		try{
			SRun("1..2[10]", null);
			fail("Expected an exception");
		} catch (ConfigRuntimeException e){
			//pass
		}

		assertEquals("2", SRun("array_size(1..2)", null));

		assertEquals("true", SRun("array_contains(1..2, 1)", null));
		assertEquals("false", SRun("array_contains(1..2, 3)", null));

		assertEquals("true", SRun("array_contains(-1..-2, -2)", null));
		assertEquals("false", SRun("array_contains(-1..-2, -3)", null));

		assertEquals("true", SRun("array_index_exists(1..2, 0)", null));
		assertEquals("false", SRun("array_index_exists(1..2, 2)", null));
	}

	@Test public void testWhitespaceAroundSymbol1() throws Exception{
		assertEquals("true", SRun("false == false", null));
	}
	//This is accounted for in the new compiler branch, and will not be fixed in this branch.
//	@Test public void testWhitespaceAroundSymbol2() throws Exception{
//		assertEquals("true", SRun("false==false", null));
//	}

    //TODO: Once the lexer is rewritten, this should work
//    @Test
//    public void testAssignmentWithEquals1() throws Exception{
//	    SRun("@var=yep nope msg(@var)", fakePlayer);
//	    verify(fakePlayer).sendMessage("yep");
//    }
//
//    @Test
//    public void testAssignmentWithEquals2() throws Exception{
//	    SRun("@var = yep nope msg(@var)", fakePlayer);
//	    verify(fakePlayer).sendMessage("yep");
//    }
//
//    @Test
//    public void testAssignmentWithEquals3() throws Exception{
//	    SRun("@var = 'yep yep' msg(@var)", fakePlayer);
//	    verify(fakePlayer).sendMessage("yep yep");
//    }

}


text:
A simple Super Mario clone written in Python using Pygame.

Python version 3.6.0

Libraries used:

* Pygame

* Os

* Sys

If you want to run this game, you should probably edit image paths.

The file to run is levelOne.py. It contains the first level of the game and is the most current prototype of the game.


text:
'use strict';

beforeEach(function() {

  function cssMatcher(presentClasses, absentClasses) {
    return function() {
      return {
        compare: function(actual) {
          var element = angular.element(actual);
          var present = true;
          var absent = false;

          angular.forEach(presentClasses.split(' '), function(className) {
            present = present && element.hasClass(className);
          });

          angular.forEach(absentClasses.split(' '), function(className) {
            absent = absent || element.hasClass(className);
          });

          var message = function() {
            return 'Expected to have ' + presentClasses +
              (absentClasses ? (' and not have ' + absentClasses + '') : '') +
              ' but had ' + element[0].className + '.';
          };
          return {
            pass: present && !absent,
            message: message
          };
        }
      };
    };
  }

  function DOMTester(a, b) {
    if (a && b && a.nodeType > 0 && b.nodeType > 0) {
      return a === b;
    }
  }

  function isNgElementHidden(element) {
    // we need to check element.getAttribute for SVG nodes
    var hidden = true;
    forEach(angular.element(element), function(element) {
      if ((' '  + (element.getAttribute('class') || '') + ' ').indexOf(' ng-hide ') === -1) {
        hidden = false;
      }
    });
    return hidden;
  }

  function MinErrMatcher(isNot, namespace, code, content, wording) {
    var codeRegex = new RegExp('^' + escapeRegexp('[' + namespace + ':' + code + ']'));
    var contentRegex = angular.isUndefined(content) || jasmine.isA_('RegExp', content) ?
        content : new RegExp(escapeRegexp(content));

    this.test = test;

    function escapeRegexp(str) {
      // This function escapes all special regex characters.
      // We use it to create matching regex from arbitrary strings.
      // http://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex
      return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
    }

    function test(exception) {
      var exceptionMessage = (exception && exception.message) || exception || '';

      var codeMatches = codeRegex.test(exceptionMessage);
      var contentMatches = angular.isUndefined(contentRegex) || contentRegex.test(exceptionMessage);
      var matches = codeMatches && contentMatches;

      return {
        pass: isNot ? !matches : matches,
        message: message
      };

      function message() {
        return 'Expected ' + wording.inputType + (isNot ? ' not' : '') + ' to ' +
            wording.expectedAction + ' ' + namespace + 'MinErr(\'' + code + '\')' +
            (contentRegex ? ' matching ' + contentRegex.toString() : '') +
            (!exception ? '.' : ', but it ' + wording.actualAction + ': ' + exceptionMessage);
      }
    }
  }

  jasmine.addMatchers({
    toBeEmpty: cssMatcher('ng-empty', 'ng-not-empty'),
    toBeNotEmpty: cssMatcher('ng-not-empty', 'ng-empty'),
    toBeInvalid: cssMatcher('ng-invalid', 'ng-valid'),
    toBeValid: cssMatcher('ng-valid', 'ng-invalid'),
    toBeDirty: cssMatcher('ng-dirty', 'ng-pristine'),
    toBePristine: cssMatcher('ng-pristine', 'ng-dirty'),
    toBeUntouched: cssMatcher('ng-untouched', 'ng-touched'),
    toBeTouched: cssMatcher('ng-touched', 'ng-untouched'),

    toBeAPromise: function() {
      return {
        compare: generateCompare(false),
        negativeCompare: generateCompare(true)
      };
      function generateCompare(isNot) {
        return function(actual) {
          var message = valueFn(
            'Expected object ' + (isNot ? 'not ' : '') + 'to be a promise');
          return { pass: isPromiseLike(actual), message: message };
        };
      }
    },

    toBeShown: function() {
      return {
        compare: generateCompare(false),
        negativeCompare: generateCompare(true)
      };
      function generateCompare(isNot) {
        return function(actual) {
          var message = valueFn('Expected element ' + (isNot ? '' : 'not ') + 'to have \'ng-hide\' class');
          var pass = !isNgElementHidden(actual);
          if (isNot) {
            pass = !pass;
          }
          return { pass: pass, message: message };
        };
      }
    },

    toBeHidden: function() {
      return {
        compare: generateCompare(false),
        negativeCompare: generateCompare(true)
      };
      function generateCompare(isNot) {
        return function(actual) {
          var message = valueFn('Expected element ' + (isNot ? 'not ' : '') + 'to have \'ng-hide\' class');
          var pass = isNgElementHidden(actual);
          if (isNot) {
            pass = !pass;
          }
          return { pass: pass, message: message };
        };
      }
    },

    toEqual: function(util) {
      return {
        compare: function(actual, expected) {
          if (actual && actual.$$log) {
            actual = (typeof expected === 'string')
                ? actual.toString()
                : actual.toArray();
          }
          return {
            pass: util.equals(actual, expected, [DOMTester])
          };
        }
      };
    },

    toEqualOneOf: function(util) {
      return {
        compare: function(actual) {
          var expectedArgs = Array.prototype.slice.call(arguments, 1);
          return {
            pass: expectedArgs.some(function(expected) {
              return util.equals(actual, expected, [DOMTester]);
            })
          };
        }
      };
    },

    toEqualData: function() {
      return {
        compare: function(actual, expected) {
          return { pass: angular.equals(actual, expected) };
        }
      };
    },

    toHaveBeenCalledOnce: function() {
      return {
        compare: function(actual) {
          if (arguments.length > 1) {
            throw new Error('`toHaveBeenCalledOnce` does not take arguments, ' +
                            'use `toHaveBeenCalledOnceWith`');
          }

          if (!jasmine.isSpy(actual)) {
            throw new Error('Expected a spy, but got ' + jasmine.pp(actual) + '.');
          }

          var count = actual.calls.count();
          var pass = count === 1;

          var message = function() {
            var msg = 'Expected spy ' + actual.and.identity() + (pass ? ' not ' : ' ') +
                      'to have been called once, but ';

            switch (count) {
              case 0:
                msg += 'it was never called.';
                break;
              case 1:
                msg += 'it was called once.';
                break;
              default:
                msg += 'it was called ' + count + ' times.';
                break;
            }

            return msg;
          };

          return {
            pass: pass,
            message: message
          };
        }
      };
    },

    toHaveBeenCalledOnceWith: function(util, customEqualityTesters) {
      return {
        compare: generateCompare(false),
        negativeCompare: generateCompare(true)
      };

      function generateCompare(isNot) {
        return function(actual) {
          if (!jasmine.isSpy(actual)) {
            throw new Error('Expected a spy, but got ' + jasmine.pp(actual) + '.');
          }

          var expectedArgs = Array.prototype.slice.call(arguments, 1);
          var actualCount = actual.calls.count();
          var actualArgs = actualCount && actual.calls.argsFor(0);

          var pass = (actualCount === 1) && util.equals(actualArgs, expectedArgs);
          if (isNot) pass = !pass;

          var message = function() {
            var msg = 'Expected spy ' + actual.and.identity() + (isNot ? ' not ' : ' ') +
                      'to have been called once with ' + jasmine.pp(expectedArgs) + ', but ';

            if (isNot) {
              msg += 'it was.';
            } else {
              switch (actualCount) {
                case 0:
                  msg += 'it was never called.';
                  break;
                case 1:
                  msg += 'it was called with ' + jasmine.pp(actualArgs) + '.';
                  break;
                default:
                  msg += 'it was called ' + actualCount + ' times.';
                  break;
              }
            }

            return msg;
          };

          return {
            pass: pass,
            message: message
          };
        };
      }
    },

    toBeOneOf: function() {
      return {
        compare: function(actual) {
          var expectedArgs = Array.prototype.slice.call(arguments, 1);
          return { pass: expectedArgs.indexOf(actual) !== -1 };
        }
      };
    },

    toHaveClass: function() {
      return {
        compare: generateCompare(false),
        negativeCompare: generateCompare(true)
      };
      function hasClass(element, selector) {
        if (!element.getAttribute) return false;
        return ((' ' + (element.getAttribute('class') || '') + ' ').replace(/[\n\t]/g, ' ').
            indexOf(' ' + selector + ' ') > -1);
      }
      function generateCompare(isNot) {
        return function(actual, clazz) {
          var message = function() {
            return 'Expected \'' + angular.mock.dump(actual) + '\'' + (isNot ? ' not ' : '') + ' to have class \'' + clazz + '\'.';
          };
          var classes = clazz.trim().split(/\s+/);
          for (var i = 0; i < classes.length; ++i) {
            if (!hasClass(actual[0], classes[i])) {
              return { pass: isNot };
            }
          }
          return { pass: !isNot };
        };
      }
    },

    toEqualMinErr: function() {
      return {
        compare: generateCompare(false),
        negativeCompare: generateCompare(true)
      };

      function generateCompare(isNot) {
        return function(actual, namespace, code, content) {
          var matcher = new MinErrMatcher(isNot, namespace, code, content, {
            inputType: 'error',
            expectedAction: 'equal',
            actualAction: 'was'
          });

          return matcher.test(actual);
        };
      }
    },

    toThrowMinErr: function() {
      return {
        compare: generateCompare(false),
        negativeCompare: generateCompare(true)
      };

      function generateCompare(isNot) {
        return function(actual, namespace, code, content) {
          var exception;

          if (!angular.isFunction(actual)) {
            throw new Error('Actual is not a function');
          }

          try {
            actual();
          } catch (e) {
            exception = e;
          }

          var matcher = new MinErrMatcher(isNot, namespace, code, content, {
            inputType: 'function',
            expectedAction: 'throw',
            actualAction: 'threw'
          });

          return matcher.test(exception);
        };
      }
    },

    toBeMarkedAsSelected: function() {
      // Selected is special because the element property and attribute reflect each other's state.
      // IE9 will wrongly report hasAttribute('selected') === true when the property is
      // undefined or null, and the dev tools show that no attribute is set
      return {
        compare: function(actual) {
          var errors = [];
          if (actual.selected === null || typeof actual.selected === 'undefined' || actual.selected === false) {
            errors.push('Expected option property "selected" to be truthy');
          }

          if (msie !== 9 && actual.hasAttribute('selected') === false) {
            errors.push('Expected option to have attribute "selected"');
          }

          var result = {
            pass: errors.length === 0,
            message: errors.join('\n')
          };

          return result;
        },
        negativeCompare: function(actual) {
          var errors = [];
          if (actual.selected) {
            errors.push('Expected option property "selected" to be falsy');
          }

          if (msie !== 9 && actual.hasAttribute('selected')) {
            errors.push('Expected option not to have attribute "selected"');
          }

          var result = {
            pass: errors.length === 0,
            message: errors.join('\n')
          };

          return result;
        }
      };
    }
  });
});

/**
 * Create jasmine.Spy on given method, but ignore calls without arguments
 * This is helpful when need to spy only setter methods and ignore getters
 */
function spyOnlyCallsWithArgs(obj, method) {
  var originalFn = obj[method];
  var spy = spyOn(obj, method);
  obj[method] = function() {
    if (arguments.length) return spy.apply(this, arguments);
    return originalFn.apply(this);
  };
  return spy;
}

// Minimal implementation to mock what was removed from Jasmine 1.x
function createAsync(doneFn) {
  function Job() {
    this.next = [];
  }
  Job.prototype.done = function() {
    return this.runs(doneFn);
  };
  Job.prototype.runs = function(fn) {
    var newJob = new Job();
    this.next.push(function() {
      fn();
      newJob.start();
    });
    return newJob;
  };
  Job.prototype.waitsFor = function(fn, error, timeout) {
    var newJob = new Job();
    timeout = timeout || 5000;
    this.next.push(function() {
      var counter = 0,
        intervalId = window.setInterval(function() {
          if (fn()) {
            window.clearInterval(intervalId);
            newJob.start();
          }
          counter += 5;
          if (counter > timeout) {
            window.clearInterval(intervalId);
            throw new Error(error);
          }
        }, 5);
    });
    return newJob;
  };
  Job.prototype.waits = function(timeout) {
    return this.waitsFor(function() { return true; }, undefined, timeout);
  };
  Job.prototype.start = function() {
    var i;
    for (i = 0; i < this.next.length; i += 1) {
      this.next[i]();
    }
  };
  return new Job();
}


text:
<!doctype html>

    <meta charset="UTF-8">
    <title>caniuse-es5 helper extension</title>
    <link rel="stylesheet" href="css/style.css" type="text/css" />

 caniuse

es5-compat

            <input type="text" id="search-input" placeholder="Enter search keywords" />


text:
<!DOCTYPE html>

<link rel="stylesheet" href="../style.css"/>

Processing.js

Pulses

Software drawing instruments can follow a rhythm or abide by rules independent
of drawn gestures. This is a form of collaborative drawing in which the draftsperson
controls some aspects of the image and the software controls others.

Original Processing.org Example: Pulses

<canvas width="200" height="200"></canvas>

// All Examples Written by Casey Reas and Ben Fry
// unless otherwise stated.
int angle = 0;

void setup()
{
  size(200, 200);
  background(102);
  smooth();
  noStroke();
  fill(0, 102);
}

void draw()
{
  // Draw only when mouse is pressed
  if (mousePressed == true) {
    angle += 10;
    float val = cos(radians(angle)) * 6.0;
    for (int a = 0; a < 360; a += 75) {
      float xoff = cos(radians(a)) * val;
      float yoff = sin(radians(a)) * val;
      fill(0);
      ellipse(mouseX + xoff, mouseY + yoff, val/2, val/2);
    }
    fill(255);
    ellipse(mouseX, mouseY, 2, 2);
  }
}


text:
package uk.co.exemel.disco.core.api.exception;

import uk.co.exemel.disco.api.ResponseCode;
import uk.co.exemel.disco.api.security.CredentialFaultCode;

// todo: would love to rename this to FaultCode (and FaultCode to FaultOrigin), but that would break hessian enum serialisation.
//       we really need to takeover hessian enum serialisation to allow us to change internal structures
//       in fact we really need to stop entrusting our internals to hessian
public enum ServerFaultCode {
	StartupError(ResponseCode.InternalError, 1),
	FrameworkError(ResponseCode.InternalError, 2),
	InvocationResultIncorrect(ResponseCode.InternalError, 3),
	ServiceCheckedException(null, 4), // Response code defined by the checked exception
	ServiceRuntimeException(ResponseCode.InternalError, 5),
    /**
     * @deprecated Replaced by either {@link ServerFaultCode.ClientDeserialisationFailure} or
     *             {@link ServerFaultCode.ServerDeserialisationFailure}
     */
	SOAPDeserialisationFailure(ResponseCode.BadRequest, 6), // not used - kept for compatibility with old client/servers
    /**
     * @deprecated Replaced by either {@link ServerFaultCode.ClientDeserialisationFailure} or
     *             {@link ServerFaultCode.ServerDeserialisationFailure}
     */
	XMLDeserialisationFailure(ResponseCode.BadRequest, 7), // not used - kept for compatibility with old client/servers
    /**
     * @deprecated Replaced by either {@link ServerFaultCode.ClientDeserialisationFailure} or
     *             {@link ServerFaultCode.ServerDeserialisationFailure}
     */
	JSONDeserialisationFailure(ResponseCode.BadRequest, 8), // not used - kept for compatibility with old client/servers
    /**
     * @deprecated Replaced by either {@link ServerFaultCode.ClientDeserialisationFailure} or
     *             {@link ServerFaultCode.ServerDeserialisationFailure}
     */
	ClassConversionFailure(ResponseCode.BadRequest, 9), // not used - kept for compatibility with old client/servers
	InvalidInputMediaType(ResponseCode.UnsupportedMediaType, 10),
	ContentTypeNotValid(ResponseCode.UnsupportedMediaType, 11),
	MediaTypeParseFailure(ResponseCode.UnsupportedMediaType, 12),
	AcceptTypeNotValid(ResponseCode.MediaTypeNotAcceptable, 13),
	ResponseContentTypeNotValid(ResponseCode.InternalError, 14),
	SecurityException(ResponseCode.Forbidden, 15),
	MandatoryNotDefined(ResponseCode.BadRequest, 18),
	Timeout(ResponseCode.Timeout,19),
    /**
     * @deprecated Replaced by either {@link ServerFaultCode.ClientDeserialisationFailure} or
     *             {@link ServerFaultCode.ServerDeserialisationFailure}
     */
	BinDeserialisationFailure(ResponseCode.BadRequest, 20), // not used - kept for compatibility with old client/servers
	NoSuchOperation(ResponseCode.NotFound, 21),
    SubscriptionAlreadyActiveForEvent(ResponseCode.InternalError, 22),
    NoSuchService(ResponseCode.NotFound, 23),
    /**
     * @deprecated Replaced by either {@link ServerFaultCode.ClientDeserialisationFailure} or
     *             {@link ServerFaultCode.ServerDeserialisationFailure}
     */
    RescriptDeserialisationFailure(ResponseCode.BadRequest, 24), // not used - kept for compatibility with old client/servers
    JMSTransportCommunicationFailure(ResponseCode.InternalError, 25),
	RemoteDiscoCommunicationFailure(ResponseCode.ServiceUnavailable, 26),
    OutputChannelClosedCantWrite(ResponseCode.CantWriteToSocket, 27),
    /**
     * @deprecated Replaced by either {@link ServerFaultCode.ClientSerialisationFailure} or
     *             {@link ServerFaultCode.ServerSerialisationFailure}
     */
    XMLSerialisationFailure(ResponseCode.InternalError, 28), // not used - kept for compatibility with old client/servers
    /**
     * @deprecated Replaced by either {@link ServerFaultCode.ClientSerialisationFailure} or
     *             {@link ServerFaultCode.ServerSerialisationFailure}
     */
    JSONSerialisationFailure(ResponseCode.InternalError, 29), // not used - kept for compatibility with old client/servers
    /**
     * @deprecated Replaced by either {@link ServerFaultCode.ClientSerialisationFailure} or
     *             {@link ServerFaultCode.ServerSerialisationFailure}
     */
    SOAPSerialisationFailure(ResponseCode.InternalError, 30), // not used - kept for compatibility with old client/servers
    NoRequestsFound(ResponseCode.BadRequest, 31),
    UnidentifiedCaller(ResponseCode.BadRequest, 33, CredentialFaultCode.UnidentifiedCaller),
    UnknownCaller(ResponseCode.BadRequest, 34, CredentialFaultCode.UnknownCaller),
    UnrecognisedCredentials(ResponseCode.BadRequest, 35, CredentialFaultCode.UnrecognisedCredentials),
    InvalidCredentials(ResponseCode.BadRequest, 36, CredentialFaultCode.InvalidCredentials),
    SubscriptionRequired(ResponseCode.Forbidden, 37, CredentialFaultCode.SubscriptionRequired),
    OperationForbidden(ResponseCode.Forbidden, 38, CredentialFaultCode.OperationForbidden),
    NoLocationSupplied(ResponseCode.BadRequest, 39, CredentialFaultCode.NoLocationSupplied),
    BannedLocation(ResponseCode.Forbidden, 40, CredentialFaultCode.BannedLocation),
    ClientSerialisationFailure(ResponseCode.BadRequest, 41),
    ClientDeserialisationFailure(ResponseCode.BadResponse, 42),
    ServerSerialisationFailure(ResponseCode.BadResponse, 43),
    ServerDeserialisationFailure(ResponseCode.BadRequest, 44);

    private final ResponseCode errorCode;
    private final String errorString;
    private final String toString;
    private final CredentialFaultCode cfc;
    public static final String DISCO_EXCEPTION_PREFIX="DSC";

    private ServerFaultCode(ResponseCode errorCode, int detailCode) {
        this(errorCode, detailCode, null);
    }

	private ServerFaultCode(ResponseCode errorCode, int detailCode, CredentialFaultCode cfc) {
		this.errorCode = errorCode;
		errorString = DISCO_EXCEPTION_PREFIX+"-"+String.format("%04d", detailCode);
        toString = name() + "(" + errorString + ")";
        this.cfc = cfc;
	}

	public String getDetail() {
		return errorString;
	}

	public ResponseCode getResponseCode() {
		return errorCode;
	}

    public CredentialFaultCode getCredentialFaultCode() {
        return cfc;
    }

    public static ServerFaultCode getByDetailCode(String prefix) {
        for (ServerFaultCode sfc : ServerFaultCode.values()) {
            if (sfc.getDetail().equals(prefix)) {
                return sfc;
            }
        }
        return null;
    }

    public static ServerFaultCode getByCredentialFaultCode(CredentialFaultCode credentialFaultCode) {
        for (ServerFaultCode sfc : ServerFaultCode.values()) {
            CredentialFaultCode cfc = sfc.getCredentialFaultCode();
            if (cfc != null && cfc.equals(credentialFaultCode)) {
                return sfc;
            }
        }
        return null;
    }

    @Override
    public String toString() {
        return toString;
    }
}