text:
#include "src/hkxclasses/hkxobject.h"
#include "src/filetypes/behaviorfile.h"
#include "src/xml/hkxxmlreader.h"
#include "src/hkxclasses/behavior/hkbvariablebindingset.h"
#include "src/ui/treegraphicsitem.h"
#include "src/hkxclasses/behavior/modifiers/hkbmodifier.h"

/**
 * HkxObject
 */

HkxObject::HkxObject(HkxFile *parent, long ref)
    : parentFile(parent),
      dataValid(true),
      isWritten(false),
      isMerged(false),
      refsUpdated(false),
      reference(ref)
{
    if (!parentFile){
        CRITICAL_ERROR_MESSAGE("HkxObject constructor was passed a null parent file!!! This program will terminate!!!");
        std::terminate();
    }
}

HkxSignature HkxObject::getSignature() const{
    //std::lock_guard <std::mutex> guard(mutex);  not needed, this should never change...
    return signature;
}

void HkxObject::setIsFileChanged(bool ischanged){
    std::lock_guard <std::mutex> guard(mutex);
    parentFile->setIsChanged(ischanged);
}

void HkxObject::setReference(int ref){
    std::lock_guard <std::mutex> guard(mutex);
    reference = ref;
}

long HkxObject::getReference() const{
    std::lock_guard <std::mutex> guard(mutex);
    return reference;
}

bool HkxObject::getIsMerged() const{
    std::lock_guard <std::mutex> guard(mutex);
    return isMerged;
}

void HkxObject::setIsMerged(bool value){
    std::lock_guard <std::mutex> guard(mutex);
    isMerged = value;
}

bool HkxObject::getRefsUpdated() const{
    std::lock_guard <std::mutex> guard(mutex);
    return refsUpdated;
}

void HkxObject::setRefsUpdated(bool value){
    std::lock_guard <std::mutex> guard(mutex);
    refsUpdated = value;
}

void HkxObject::setParentFile(HkxFile *parent){
    std::lock_guard <std::mutex> guard(mutex);
    (parent) ? parentFile = parent : NULL;
}

int HkxObject::getIndexOfGenerator(const HkxSharedPtr &gen) const{
    std::lock_guard <std::mutex> guard(mutex);
    auto index = -1;
    BehaviorFile *behavior = dynamic_cast<BehaviorFile *>(parentFile);
    (behavior) ? index = behavior->getIndexOfGenerator(gen) : NULL;
    return index;
}

QString HkxObject::getParentFilename() const{
    std::lock_guard <std::mutex> guard(mutex);
    return parentFile->getFileName();
}

HkxFile *HkxObject::getParentFile() const{
    std::lock_guard <std::mutex> guard(mutex);
    return parentFile;
}

QVector<HkxObject *> HkxObject::getChildrenOtherTypes() const{
    return QVector<HkxObject *>();
}

QString HkxObject::getReferenceString() const{
    std::lock_guard <std::mutex> guard(mutex);
    QString temp("#"+QString::number(reference));
    reference >= 0 ? NULL: temp = "null";
    return temp;
}

QString HkxObject::getBoolAsString(bool b) const{
    if (b){
        return "true";
    }
    return "false";
}

HkxObject::HkxType HkxObject::getType() const{
    std::lock_guard <std::mutex> guard(mutex);
    return typeCheck;
}

void HkxObject::setDataValidity(bool isValid){
    std::lock_guard <std::mutex> guard(mutex);
    dataValid = isValid;
    if (typeCheck != TYPE_OTHER){
        static_cast<DataIconManager *>(this)->setIconValidity(isValid);
    }
}

bool HkxObject::isDataValid() const{
    std::lock_guard <std::mutex> guard(mutex);
    return dataValid;
}

void HkxObject::setIsWritten(bool written){
    std::lock_guard <std::mutex> guard(mutex);
    isWritten = written;
}

bool HkxObject::getIsWritten() const{
    std::lock_guard <std::mutex> guard(mutex);
    return isWritten;
}

void HkxObject::setType(HkxSignature sig, HkxType type){
    std::lock_guard <std::mutex> guard(mutex);
    signature = sig;
    typeCheck = type;
}

bool HkxObject::readReferences(const QByteArray &line, QVector <HkxSharedPtr> & children) const{
    auto size = 0;
    auto start = 0;
    auto ok = false;
    for (auto i = 0; i < line.size(); i++){
        if (line.at(i) == '#'){
            i++;
            start = i;
            size = 0;
            do{
                size++;
                i++;
            }while (i < line.size() && line.at(i) != ' ' && line.at(i) != '\n' && line.at(i) != '\r');
            QByteArray value(size, '\0');
            for (auto j = 0; j < size; j++){
                value[j] = line[start];
                start++;
            }
            children.append(HkxSharedPtr(nullptr, value.toLong(&ok)));
            if (!ok){
                return false;
            }
        }else if (line.at(i) == 'n'){
            start = i;
            size = 0;
            do{
                size++;
                i++;
            }while (i < line.size() && line.at(i) != ' ' && line.at(i) != '\n' && line.at(i) != '\r');
            QByteArray value(size, '\0');
            for (auto j = 0; j < size; j++){
                value[j] = line[start];
                start++;
            }
            if (value == "null"){
                children.append(HkxSharedPtr(nullptr));
                ok = true;
            } else {
                return false;
            }
        }
    }
    return ok;
}

bool HkxObject::readIntegers(const QByteArray &line, QVector<int> & ints) const{
    auto size = 0;
    auto start = 0;
    auto ok = true;
    for (auto i = 0; i < line.size(); i++){
        if ((line.at(i) >= '0' && line.at(i) <= '9') || (line.at(i) == '-')){
            start = i;
            size = 0;
            do{
                size++;
                i++;
            }while (i < line.size() && line.at(i) != ' ' && line.at(i) != '\n' && line.at(i) != '\r');
            QByteArray value(size, '\0');
            for (auto j = 0; j < size; j++){
                value[j] = line[start];
                start++;
            }
            ints.append(value.toInt(&ok));
            if (!ok){
                return false;
            }
        }
    }
    return ok;
}

bool HkxObject::toBool(const QByteArray &line, bool *ok) const{
    *ok = true;
    if (line == "true"){
        return true;
    }else if (line == "false"){
        return false;
    }else {
        *ok = false;
        return false;
    }
}

bool HkxObject::readDoubles(const QByteArray &line, QVector<qreal> & doubles) const{
    auto size = 0;
    auto start = 0;
    auto ok = false;
    for (auto i = 0; i < line.size(); i++){
        if ((line.at(i) >= '0' && line.at(i) <= '9') || (line.at(i) == '-')){
            start = i;
            size = 0;
            do{
                size++;
                i++;
            }while (i < line.size() && line.at(i) != ' ' && line.at(i) != '\n' && line.at(i) != '\r');
            QByteArray value(size, '\0');
            for (auto j = 0; j < size; j++){
                value[j] = line[start];
                start++;
            }
            doubles.append(value.toDouble(&ok));
            if (!ok){
                return false;
            }
        }
    }
    return ok;
}

hkVector3 HkxObject::readVector3(const QByteArray &lineIn, bool *ok) const{
    enum {X = 1, Y = 2, Z = 3};
    auto size = 0;
    auto start = 0;
    auto axisVar = 0;
    hkVector3 vector3;
    for (auto i = 0; i < lineIn.size(); i++){
        if ((lineIn.at(i) >= '0' && lineIn.at(i) <= '9') || (lineIn.at(i) == '-')){
            start = i;
            size = 0;
            do{
                size++;
                i++;
            }while (i < lineIn.size() && lineIn.at(i) != ' ' && lineIn.at(i) != ')');
            QByteArray value(size, '\0');
            for (auto j = 0; j < size; j++){
                value[j] = lineIn[start];
                start++;
            }
            axisVar++;
            switch (axisVar){
            case X:
                vector3.x = value.toDouble(ok);
                break;
            case Y:
                vector3.y = value.toDouble(ok);
                break;
            case Z:
                vector3.z = value.toDouble(ok);
                if (lineIn.at(i) != ')'){
                    *ok = false;
                    return hkVector3();
                }
                break;
            default:
                *ok = false;
                return hkVector3();
            }
            if (!*ok){
                return hkVector3();
            }
        }
    }
    return vector3;
}

hkQuadVariable HkxObject::readVector4(const QByteArray &lineIn, bool *ok) const{
    enum {X = 1, Y = 2, Z = 3, W = 4};
    auto size = 0;
    auto start = 0;
    auto axisVar = 0;
    hkQuadVariable vector;
    for (auto i = 0; i < lineIn.size(); i++){
        if ((lineIn.at(i) >= '0' && lineIn.at(i) <= '9') || (lineIn.at(i) == '-')){
            start = i;
            size = 0;
            do{
                size++;
                i++;
            }while (i < lineIn.size() && lineIn.at(i) != ' ' && lineIn.at(i) != ')');
            QByteArray value(size, '\0');
            for (auto j = 0; j < size; j++){
                value[j] = lineIn[start];
                start++;
            }
            axisVar++;
            switch (axisVar){
            case X:
                vector.x = value.toDouble(ok);
                break;
            case Y:
                vector.y = value.toDouble(ok);
                break;
            case Z:
                vector.z = value.toDouble(ok);
                break;
            case W:
                vector.w = value.toDouble(ok);
                if (lineIn.at(i) != ')'){
                    *ok = false;
                    return hkQuadVariable();
                }
                break;
            default:
                *ok = false;
                return hkQuadVariable();
            }
            if (!*ok){
                return hkQuadVariable();
            }
        }
    }
    return vector;
}

hkQsTransform HkxObject::readQsTransform(const QByteArray &lineIn, bool *ok) const{
    enum {V3_1_X, V3_1_Y, V3_1_Z, V4_X, V4_Y, V4_Z, V4_W, V3_2_X, V3_2_Y, V3_2_Z};
    hkQsTransform transform;
    qreal number = 0;
    auto size = V3_2_Z + 1;
    auto leftparcount = 0;
    auto rightparcount = 0;
    auto dotcount = 0;
    auto lineindex = 0;
    QByteArray value("", size);
    for (auto transformindex = 0; transformindex <= V3_2_Z; transformindex++){
        auto valueindex = 0;
        for (; lineindex < lineIn.size(); lineindex++, valueindex++){
            valueindex >= size ? size = size*2, value.resize(size) : NULL;
            if ((lineIn.at(lineindex) >= '0' && lineIn.at(lineindex) <= '9') || (lineIn.at(lineindex) == '-' && valueindex != 0)){
                value[valueindex] = lineIn.at(lineindex);
            }else if (lineIn.at(lineindex) == '.' && (!dotcount && valueindex > 0)){
                value[valueindex] = lineIn.at(lineindex);
                ++dotcount;
            }else if (lineIn.at(lineindex) == '('){
                ++leftparcount;
            }else if (lineIn.at(lineindex) == ')'){
                (leftparcount != ++rightparcount) ? (ok ? *ok = false : NULL) : valueindex = size;
            }else if (lineIn.at(lineindex) == ' '){
                valueindex = size;
            }else{
                ok ? *ok = false : NULL;
                return hkQsTransform();
            }
        }
        value.truncate(valueindex);
        number = value.toDouble();
        switch (transformindex){
        case V3_1_X:
            transform.v1.x = number; break;
        case V3_1_Y:
            transform.v1.y = number; break;
        case V3_1_Z:
            transform.v1.z = number; break;
        case V4_X:
            transform.v2.x = number; break;
        case V4_Y:
            transform.v2.y = number; break;
        case V4_Z:
            transform.v2.z = number; break;
        case V4_W:
            transform.v2.w = number; break;
        case V3_2_X:
            transform.v3.x = number; break;
        case V3_2_Y:
            transform.v3.y = number; break;
        case V3_2_Z:
            transform.v3.z = number; break;
        }
    }
    return transform;
}

bool HkxObject::readMultipleVector4(const QByteArray &lineIn,  QVector <hkQuadVariable> & vectors) const{
    enum {X = 1, Y = 2, Z = 3, W = 4};
    auto size = 0;
    auto start = 0;
    auto axisVar = 0;
    hkQuadVariable vector;
    auto ok = false;
    auto loop = false;
    for (auto i = 0; i < lineIn.size(); i++){
        if (lineIn.at(i) == '('){
            loop = true;
            i++;
            while (loop && i < lineIn.size()){
                if ((lineIn.at(i) >= '0' && lineIn.at(i) <= '9') || (lineIn.at(i) == '-')){
                    start = i;
                    size = 0;
                    do{
                        size++;
                        i++;
                    }while (i < lineIn.size() && lineIn.at(i) != ' ' && lineIn.at(i) != ')');
                    QByteArray value(size, '\0');
                    for (auto j = 0; j < size; j++){
                        value[j] = lineIn[start];
                        start++;
                    }
                    axisVar++;
                    switch (axisVar){
                    case X:
                        vector.x = value.toDouble(&ok);
                        break;
                    case Y:
                        vector.y = value.toDouble(&ok);
                        break;
                    case Z:
                        vector.z = value.toDouble(&ok);
                        break;
                    case W:
                        vector.w = value.toDouble(&ok);
                        if (!ok){
                            return false;
                        }
                        loop = false;
                        vectors.append(vector);
                        axisVar = 0;
                        if (lineIn.at(i) != ')'){
                            return false;
                        }
                        break;
                    default:
                        return false;
                    }
                }
                i++;
            }
        }
    }
    return ok;
}

void HkxObject::updateReferences(long &){}

void HkxObject::unlink(){}

bool HkxObject::readData(const HkxXmlReader & , long & ){return false;}

bool HkxObject::merge(HkxObject *){return false;}

void HkxObject::mergeEventIndex(int, int){}

bool HkxObject::isEventReferenced(int) const{return false;}

bool HkxObject::isVariableReferenced(int) const{return false;}

void HkxObject::updateEventIndices(int ){}

void HkxObject::fixMergedEventIndices(BehaviorFile *){}

bool HkxObject::fixMergedIndices(BehaviorFile *){return true;}

bool HkxObject::write(HkxXMLWriter *){return false;}

QString HkxObject::evaluateDataValidity(){return "";}

/**
 * HkxObjectExpSharedPtr
 */

HkxSharedPtr::HkxSharedPtr(HkxObject *obj, long ref)
    :QExplicitlySharedDataPointer(obj), smtreference(ref)
{
    //
}

bool HkxSharedPtr::operator==(const HkxSharedPtr & other) const{
    if (data() == other.data()){
        return true;
    }
    return false;
}

void HkxSharedPtr::setShdPtrReference(long ref){
    smtreference = ref;
}

long HkxSharedPtr::getShdPtrReference() const{
    return smtreference;
}

bool HkxSharedPtr::readShdPtrReference(long index, const HkxXmlReader & reader){
    auto ok = true;
    auto temp = reader.getElementValueAt(index);
    if (temp.at(0) == '#'){
        temp.remove(0, 1);
    }
    if (temp == "null"){
        setShdPtrReference(-1);
    }else{
        setShdPtrReference(temp.toLong(&ok));
    }
    return ok;
}

/**
 * HkDynamicObject
 */

HkDynamicObject::HkDynamicObject(HkxFile *parent, long ref)
    : HkxObject(parent, ref)
{
    //
}

HkxSharedPtr& HkDynamicObject::getVariableBindingSet(){
    std::lock_guard <std::mutex> guard(mutex);
    return variableBindingSet;
}

hkbVariableBindingSet *HkDynamicObject::getVariableBindingSetData() const{
    std::lock_guard <std::mutex> guard(mutex);
    return static_cast<hkbVariableBindingSet *>(variableBindingSet.data());
}

void HkDynamicObject::addBinding(const QString & path, int varIndex, bool isProperty){
    std::lock_guard <std::mutex> guard(mutex);
    if (variableBindingSet.data()){
        static_cast<hkbVariableBindingSet *>(variableBindingSet.data())->addBinding(path, varIndex,(hkbVariableBindingSet::hkBinding::BindingType)(isProperty));
    }else{
        hkbVariableBindingSet *bind = new hkbVariableBindingSet(getParentFile());
        bind->addBinding(path, varIndex,(hkbVariableBindingSet::hkBinding::BindingType)(isProperty));
        variableBindingSet = HkxSharedPtr(bind);
    }
}

void HkDynamicObject::removeBinding(const QString & path){
    std::lock_guard <std::mutex> guard(mutex);
    if (variableBindingSet.data()){
        static_cast<hkbVariableBindingSet *>(variableBindingSet.data())->removeBinding(path);
    }
}

void HkDynamicObject::removeBinding(int varIndex){
    std::lock_guard <std::mutex> guard(mutex);
    if (variableBindingSet.data()){
        static_cast<hkbVariableBindingSet *>(variableBindingSet.data())->removeBinding(varIndex);
    }
}

bool HkDynamicObject::isVariableReferenced(int variableindex) const{
    std::lock_guard <std::mutex> guard(mutex);
    if (variableBindingSet.constData() && static_cast<const hkbVariableBindingSet *>(variableBindingSet.constData())->isVariableRefed(variableindex)){
        return true;
    }
    return false;
}

bool HkDynamicObject::merge(HkxObject *recessiveObject){ //TO DO: Make thread safe!!!
    std::lock_guard <std::mutex> guard(mutex);
    hkbVariableBindingSet *obj = nullptr;
    if (!getIsMerged() && recessiveObject && recessiveObject->getSignature() == HKB_VARIABLE_BINDING_SET){
        obj = static_cast<hkbVariableBindingSet *>(recessiveObject);
        if (variableBindingSet.data()){
            variableBindingSet->merge(obj);
        }else if (obj){
            variableBindingSet = HkxSharedPtr(obj);
            getParentFile()->addObjectToFile(obj, -1);
        }
        return true;
    }
    return false;
}

void HkDynamicObject::setBindingReference(int ref){
    std::lock_guard <std::mutex> guard(mutex);
    if (variableBindingSet.data()){
        variableBindingSet->setReference(ref);
    }
}

void HkDynamicObject::updateReferences(long &ref){
    std::lock_guard <std::mutex> guard(mutex);
    setReference(ref);
    if (variableBindingSet.data()){
        variableBindingSet->setReference(ref++);
    }
}

void HkDynamicObject::mergeVariableIndices(int oldindex, int newindex){
    std::lock_guard <std::mutex> guard(mutex);
    if (variableBindingSet.data()){
        static_cast<hkbVariableBindingSet *>(variableBindingSet.data())->mergeVariableIndex(oldindex, newindex);
    }
}

bool HkDynamicObject::fixMergedIndices(BehaviorFile *dominantfile){
    std::lock_guard <std::mutex> guard(mutex);
    if (variableBindingSet.data()){
        return variableBindingSet->fixMergedIndices(dominantfile);
    }
    return true;
}

bool HkDynamicObject::linkVar(){
    std::lock_guard <std::mutex> guard(mutex);
    auto ptr = static_cast<BehaviorFile *>(getParentFile())->findHkxObject(variableBindingSet.getShdPtrReference());
    if (ptr){
        if ((*ptr)->getSignature() != HKB_VARIABLE_BINDING_SET){
            LogFile::writeToLog("HkDynamicObject: linkVar()!\nThe linked object is not a HKB_VARIABLE_BINDING_SET!\nRemoving the link to the invalid object!");
            variableBindingSet = nullptr;
            return false;
        }
        variableBindingSet = *ptr;
    }
    return true;
}

void HkDynamicObject::unlink(){
    std::lock_guard <std::mutex> guard(mutex);
    variableBindingSet = HkxSharedPtr();
}

QString HkDynamicObject::evaluateDataValidity(){
    std::lock_guard <std::mutex> guard(mutex);
    if (variableBindingSet.data()){
        setDataValidity(false);
        if (variableBindingSet->getSignature() != HKB_VARIABLE_BINDING_SET){
            variableBindingSet = HkxSharedPtr();
            return QString(getParentFilename()+": HkDynamicObject: Ref: "+getReferenceString()+": variableBindingSet is invalid type! Signature: "+QString::number(variableBindingSet->getSignature(), 16)+"\n");
        }else if (static_cast<hkbVariableBindingSet *>(variableBindingSet.data())->getNumberOfBindings() < 1){
            variableBindingSet = HkxSharedPtr();
            return QString(getParentFilename()+": HkDynamicObject: Ref: "+getReferenceString()+": variableBindingSet has no bindings! Setting null value!");
        }
    }
    setDataValidity(true);
    return QString();
}


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using CorySignalGenerator.Utils;

namespace UnitTests
{
    [TestClass]
    public class CircularBufferTests
    {
        [TestMethod]
        public void TestArrayIndex()
        {
            int size=3;

            BasicCircularBuffer<int> circularBuffer = new BasicCircularBuffer<int>(size);

            for (int n = 0; n < size; n++)
            {
                circularBuffer[n]=n;
            }
            Assert.AreEqual(0, circularBuffer[0]);
            Assert.AreEqual(1, circularBuffer[1]);
            Assert.AreEqual(2, circularBuffer[2]);

            circularBuffer.Advance(1);
            Assert.AreEqual(0, circularBuffer[1]);
            Assert.AreEqual(1, circularBuffer[2]);

            circularBuffer[0]=10;
            Assert.AreEqual(10, circularBuffer[0]);
            Assert.AreEqual(0, circularBuffer[1]);
            Assert.AreEqual(1, circularBuffer[2]);

            circularBuffer.Advance(1);
            Assert.AreEqual(10, circularBuffer[1]);
            Assert.AreEqual(0, circularBuffer[2]);
        }

    }
}

redpajama_set_name: RedPajamaGithub


text:
package DIJ;

public class Criminal extends Policia {
    private String nombre;
    private String cedula;
    private String delito;
    private String policia;

    public void setNombre(String n) {
        this.nombre = n;
    }

    public String getNombre() {
        return this.nombre;
    }

    public void setCedula(String c) {
        this.cedula = c;
    }

    public String getCedula() {
        return this.cedula;
    }

    public void setDelito(int idDelito) {
        if (idDelito == 1)
            this.delito = "Robo";
        else if (idDelito == 2)
            this.delito = "Violacion";
        else if (idDelito == 3)
            this.delito = "Homicidio";
        else
            this.delito = "Desconocido";
    }

    public String getDelito() {
        return this.delito;
    }

    public void setPolicia(String policia ) {
        this.policia = policia;
    }
    public String getPolicia() {
        return this.policia;
    }

}


text:
it.skip('FormulaInput')

// Cases:
// - applying a suggestion and then typing ' ' (e.g. before +) does not cause
//   suggestions to be shown


text:
using System;
using System.ComponentModel.DataAnnotations;
using Cik.Magazine.Shared.Messages.Category;

namespace Cik.Magazine.Shared.Models.Category
{
    [Serializable]
    public class CategoryModel
    {
        [Required]
        public string Name { get; set; }
        public Status Status { get; set; }
    }
}


text:
@class LDBCollection;
@class LDBObject;

@interface LDBCursor : NSObject
- (id)initWithCollection:(LDBCollection *)coll query:(LDBObject *)query keys:(LDBObject *)keys;
- (LDBCursor *)limit:(int)limit;
- (LDBCursor *)sort:(LDBObject *)sort;
- (LDBCursor *)showPending;

- (BOOL)hasNext;
- (LDBObject *)next;
- (LDBObject *)one;
- (int64_t)count;
@end


text:
package com.intellij.lexer;

import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.psi.tree.IElementType;
import org.jetbrains.annotations.NotNull;

public interface EmbeddedTokenTypesProvider {
  ExtensionPointName<EmbeddedTokenTypesProvider> EXTENSION_POINT_NAME = ExtensionPointName.create("com.intellij.embeddedTokenTypesProvider");

  /**
   * @return name of provider, doesn't related to language name.
   */
  @NotNull
  String getName();

  @NotNull
  IElementType getElementType();
}


text:
{
  let obj: string;
  // Error: 'number' is not assignable to type 'string'.
  // obj = 10;
  obj = 'yo';

  function sayIt(what: string): string {
    return `Saying: ${what}`;
  }

  const said: string = sayIt(obj);
  console.log(said);
  class Sayer {
    what: string;
    constructor(what) {
      this.what = what;
    }
    sayIt(): string {
      return `Saying: ${this.what}`;
    }
  }

  let sayer: Sayer = new Sayer(obj);
  console.log(sayer.sayIt());

  // class implicitly defines interface
  sayer = {
    what: 'something',
    sayIt() {
      return 'whatever'
    }
  }

  interface SayerInterface {
    sayIt: () => string;
  }

  let sayerInterface: SayerInterface;
  sayerInterface = sayer;

  // Function Type Interface
  interface SayerFunctionInterface {
    (string): string;
  }

  const func: SayerFunctionInterface = sayIt;

  interface AnotherSayer {
    what: string;
    that: string;
    sayIt: () => string;
    sayThat: () => string;
  }

  let anotherSayer: AnotherSayer;
  sayer = anotherSayer;
}


text:
this script adds multi users to one group in active directory using python, there is alot of complicated modules which lets python talk to AD using LDAP, but why the hell when we have dsquery and dsmod
so this is a merge of python and AD command line
please feel free to use it

#
# Author: Mohamed Garrana
# Creation Date: 26 may'09
#
#
# Description: Adding AD users to a group importing the users from a txt file,where they are written in userlogon name per line
#for example:
#amohsen
#mibrahim
#jsmith
# some lines with # are used for troubleshooting you can comment them out for further diagnostics
########################################################################################
import os
#opening the file users.txt and reading it line by line while stripping the line
fo = open('users.txt','r')
for line in fo:
name= line.strip()
#using the AD command dsmod piped with dsquery
command = 'dsquery user -samid %s | dsmod group "CN for the group, for example CN=group1;DN=microsoft;DN=com" -addmbr' %(name,)
nr=os.popen(command)
# readd=nr.read()


text:
Release History
===============

3.0.0 (2016-08-05)
------------------

- Added resource role for tower3.0 and permission for previous tower versions
- Added notification templates
- Added labels
- Added description display option
- Added text indicator for resource change
- Added deprecation warnings
- Help text upgrades
- Give indication of "changed" apart from color
- New credential fields to support openstack-v2, networking and azure
- New options for inventory source/group. Add implicit resource inventory
  script.
- credentials (no longer require user/team)
- Added support for system auditors
- projects (do not post to organizations/N/projects)
- prompt-for JT fields + job launch options (allow blank inventory too)
- Update the POST protocol for associate and disassociate actions
- New job launch option for backwards compatibility
- New tower-cli option to display tower-cli version
- Enhanced debug log format (support multi-line debug log)

2.3.2 (2016-07-21)
------------------

- Add RPM specfile and Makefile
- Tower compatibility fixes
- Allow scan JTs as an option for "job_type"
- Add ability to create group as subgroup of another group
- Add YAML output format against JSON and humanized output formats
- Add SSL corner case error handling and suggestion
- Allow resource disassociation with "null"

2.3.1 (2015-12-10)
------------------

- Fixed bug affecting force-on-exists and fail_on_found options
- Changed extra_vars behavior to be more compliant by re-parsing vars,
  even when only one source exists
- Fixed group modify bug, avoid sending unwanted fields in modify requests

2.3.0 (2015-10-20)
------------------

-  Fixed an issue where the settings file could be world readable
-  Added the ability to associate a project with an organization
-  Added setting "verify\_ssl" to disallow insecure connections
-  Added support for additional cloud credentials
-  Exposed additional options for a cloud inventory source
-  Combined " launch-time extra\_vars" with " job\_template extra\_vars"
   for older Tower versions
-  Changed the extra\_vars parameters to align with Ansible parameter
   handling
-  Added the ability to run ad hoc commands
-  Included more detail when displaying job information
-  Added an example bash script to demonstrate tower-cli usage

2.1.1 (2015-01-27)
------------------

-  Added tests for Python versions 2.6 through 3.4
-  Added shields for github README
-  Added job\_tags on job launches
-  Added option for project local path

2.1.0 (2015-01-21)
------------------

-  Added the ability to customize the set of fields used as options for
   a resource
-  Expanded monitoring capability to include projects and inventory
   sources
-  Added support for new job\_template job launch endpoint

2.0.2 (2014-10-02)
------------------

-  Added ability to set local scope for config file
-  Expanded credential resource to allow options for cloud credentials

2.0.1 (2014-07-18)
------------------

-  Updated README and error text

2.0.0 (2014-07-15)
------------------

-  Pluggable resource architecture built around click


text: export default {name: "bar"}


text:
<?php

namespace bmwx591\yrl;

/**
 * Class Location
 * @package bmwx591\yrl
 */
class Location extends NestedObject
{
    protected $country;

    protected $region;

    protected $district;

    protected $localityName;

    protected $subLocalityName;

    protected $address;

    protected $apartment;

    protected $direction;

    protected $distance;

    protected $latitude;

    protected $longitude;

    /**
     * @var Metro[]
     */
    protected $metro = [];

    protected $railwayStation;

    protected $nonAdminSubLocality;

    /**
     * @return string
     */
    public function getCountry()
    {
        return $this->country;
    }

    /**
     * @param string $country
     * @return $this
     */
    public function setCountry($country)
    {
        $this->country = $country;
        return $this;
    }

    /**
     * @return string
     */
    public function getRegion()
    {
        return $this->region;
    }

    /**
     * @param string $region
     * @return $this
     */
    public function setRegion($region)
    {
        $this->region = $region;
        return $this;
    }

    /**
     * @return string
     */
    public function getDistrict()
    {
        return $this->district;
    }

    /**
     * @param string $district
     * @return $this
     */
    public function setDistrict($district)
    {
        $this->district = $district;
        return $this;
    }

    /**
     * @return string
     */
    public function getLocalityName()
    {
        return $this->localityName;
    }

    /**
     * @param string $localityName
     * @return $this
     */
    public function setLocalityName($localityName)
    {
        $this->localityName = $localityName;
        return $this;
    }

    /**
     * @return string
     */
    public function getSubLocalityName()
    {
        return $this->subLocalityName;
    }

    /**
     * @param string $subLocalityName
     * @return $this
     */
    public function setSubLocalityName($subLocalityName)
    {
        $this->subLocalityName = $subLocalityName;
        return $this;
    }

    /**
     * @return string
     */
    public function getAddress()
    {
        return $this->address;
    }

    /**
     * @param string $address
     * @return $this
     */
    public function setAddress($address)
    {
        $this->address = $address;
        return $this;
    }

    /**
     * @return integer
     */
    public function getApartment()
    {
        return $this->apartment;
    }

    /**
     * @param integer $apartment
     * @return $this
     */
    public function setApartment($apartment)
    {
        $this->apartment = $apartment;
        return $this;
    }

    /**
     * @return string
     */
    public function getDirection()
    {
        return $this->direction;
    }

    /**
     * @param string $direction
     * @return $this
     */
    public function setDirection($direction)
    {
        $this->direction = $direction;
        return $this;
    }

    /**
     * @return integer
     */
    public function getDistance()
    {
        return $this->distance;
    }

    /**
     * @param integer $distance
     * @return $this
     */
    public function setDistance($distance)
    {
        $this->distance = $distance;
        return $this;
    }

    /**
     * @return float
     */
    public function getLatitude()
    {
        return $this->latitude;
    }

    /**
     * @param float $latitude
     * @return $this
     */
    public function setLatitude($latitude)
    {
        $this->latitude = $latitude;
        return $this;
    }

    /**
     * @return float
     */
    public function getLongitude()
    {
        return $this->longitude;
    }

    /**
     * @param float $longitude
     * @return $this
     */
    public function setLongitude($longitude)
    {
        $this->longitude = $longitude;
        return $this;
    }

    /**
     * @return Metro[]
     */
    public function getMetro()
    {
        return $this->metro;
    }

    /**
     * @param Metro $metro
     * @return $this
     */
    public function addMetro(Metro $metro)
    {
        array_push($this->metro, $metro);
        return $this;
    }

    /**
     * @param Metro[] $metro
     * @return $this
     */
    public function setMetro(array $metro)
    {
        $this->metro = $metro;
        return $this;
    }

    /**
     * @return string
     */
    public function getRailwayStation()
    {
        return $this->railwayStation;
    }

    /**
     * @param string $railwayStation
     * @return $this
     */
    public function setRailwayStation($railwayStation)
    {
        $this->railwayStation = $railwayStation;
        return $this;
    }

    /**
     * @return string
     */
    public function getNonAdminSubLocality()
    {
        return $this->nonAdminSubLocality;
    }

    /**
     * @param string $nonAdminSubLocality
     * @return $this
     */
    public function setNonAdminSubLocality($nonAdminSubLocality)
    {
        $this->nonAdminSubLocality = $nonAdminSubLocality;
        return $this;
    }

    /**
     * @inheritdoc
     */
    public function setAttribute(array $attrNode)
    {
        if ('metro' == $attrNode['name']) {
            return $this->addMetro((new Metro($this))->setOptions($attrNode));
        }
        return parent::setAttribute($attrNode);
    }

    /**
     * @return bool
     */
    public function isValid()
    {
        parent::isValid();
        if (is_null($this->country)) {
            $this->addError('Required location field "country" is empty');
        }
        return $this->hasErrors();
    }
}


text:
using namespace rj_geometry;

namespace planning::CreatePath {

Trajectory simple(const LinearMotionInstant& start, const LinearMotionInstant& goal,
                  const MotionConstraints& motion_constraints, RJ::Time start_time,
                  const std::vector<Point>& intermediate_points) {
    std::vector<Point> points;
    points.push_back(start.position);
    for (const Point& pt : intermediate_points) {
        points.push_back(pt);
    }
    points.push_back(goal.position);
    BezierPath bezier(points, start.velocity, goal.velocity, motion_constraints);
    Trajectory path = profile_velocity(bezier, start.velocity.mag(), goal.velocity.mag(),
                                       motion_constraints, start_time);
    return path;
}

Trajectory rrt(const LinearMotionInstant& start, const LinearMotionInstant& goal,
               const MotionConstraints& motion_constraints, RJ::Time start_time,
               const ShapeSet& static_obstacles,
               const std::vector<DynamicObstacle>& dynamic_obstacles,
               const std::vector<Point>& bias_waypoints) {
    // if already on goal, no need to move
    if (start.position.dist_to(goal.position) < 1e-6) {
        return Trajectory{{RobotInstant{Pose(start.position, 0), Twist(), start_time}}};
    }

    // maybe we don't need an RRT
    Trajectory straight_trajectory =
        CreatePath::simple(start, goal, motion_constraints, start_time);

    // If we are very close to the goal (i.e. there physically can't be a robot
    // in our way) or the straight trajectory is feasible, we can use it.
    if (start.position.dist_to(goal.position) < kRobotRadius ||
        (!trajectory_hits_static(straight_trajectory, static_obstacles, start_time, nullptr) &&
         !trajectory_hits_dynamic(straight_trajectory, dynamic_obstacles, start_time, nullptr,
                                  nullptr))) {
        return straight_trajectory;
    }

    ShapeSet obstacles = static_obstacles;
    Trajectory path{{}};
    constexpr int kAttemptsToAvoidDynamics = 10;
    for (int i = 0; i < kAttemptsToAvoidDynamics; i++) {
        std::vector<Point> points =
            generate_rrt(start.position, goal.position, obstacles, bias_waypoints);

        BezierPath post_bezier(points, start.velocity, goal.velocity, motion_constraints);

        path = profile_velocity(post_bezier, start.velocity.mag(), goal.velocity.mag(),
                                motion_constraints, start_time);

        Circle hit_circle;
        if (!trajectory_hits_dynamic(path, dynamic_obstacles, path.begin_time(), &hit_circle,
                                     nullptr)) {
            break;
        }

        // Inflate the radius slightly so we don't try going super close to
        // it and hitting it again.
        hit_circle.radius(hit_circle.radius() * 1.5f);
        obstacles.add(std::make_shared<Circle>(hit_circle));
    }

    return path;
}

}  // namespace planning::CreatePath


text:
Ti=Ownership

=[G/Agt-Cooperate-CmA/Sec/Relate/Own/NoTransferOfRightsInConfInfo/0.md]


text:
package com.intropro.prairie.unit.hdfs.cmd;

import com.intropro.prairie.unit.cmd.Command;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FsShell;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.List;

/**
 * Created by presidentio on 8/19/16.
 */
public class HdfsShell implements Command {

    private static final Logger LOGGER = LogManager.getLogger(HdfsShell.class);

    private Configuration configuration;

    public HdfsShell(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public int exec(List<String> args, Reader in, Writer out) throws InterruptedException, IOException {
        FsShell fsShell = new FsShellWithIO(configuration, in, out);
        try {
            return fsShell.run(args.subList(1, args.size()).toArray(new String[args.size() - 1]));
        } catch (Exception e) {
            LOGGER.error("Failed to execute hdfs shell with args: " + args, e);
            return 1;
        }
    }

    @Override
    public boolean useInputStream() {
        return false;
    }

}


text:
package com.imotspot.model.imot.interfaces;

import java.net.URI;

public interface Media extends Named {
    public abstract URI uri();
}


text:
<?php

namespace Ilios\CoreBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation as JMS;
use Symfony\Component\Validator\Constraints as Assert;

use Ilios\CoreBundle\Traits\IdentifiableEntity;
use Ilios\CoreBundle\Traits\StringableIdEntity;

/**
 * Class MeshPreviousIndexing
 * @package Ilios\CoreBundle\Entity
 *
 * @ORM\Table(name="mesh_previous_indexing",
 *  uniqueConstraints={
 *      @ORM\UniqueConstraint(name="descriptor_previous", columns={"mesh_descriptor_uid"})
 *  })
 * @ORM\Entity
 *
 * @JMS\ExclusionPolicy("all")
 * @JMS\AccessType("public_method")
 */
class MeshPreviousIndexing implements MeshPreviousIndexingInterface
{
    use IdentifiableEntity;
    use StringableIdEntity;

    /**
     * @var int
     *
     * @ORM\Column(name="mesh_previous_indexing_id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     *
     * @Assert\Type(type="integer")
     *
     * @JMS\Expose
     * @JMS\Type("integer")
     */
    protected $id;

    /**
     * @var MeshDescriptorInterface
     *
     * @ORM\OneToOne(targetEntity="MeshDescriptor", inversedBy="previousIndexing")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="mesh_descriptor_uid", referencedColumnName="mesh_descriptor_uid", unique=true)
     * })
     *
     * @JMS\Expose
     * @JMS\Type("string")
     */
    protected $descriptor;

    /**
     * @var string
     *
     * @ORM\Column(name="previous_indexing", type="text")
     *
     * @Assert\NotBlank()
     * @Assert\Type(type="string")
     * @Assert\Length(
     *      min = 1,
     *      max = 65000
     * )
     *
     * @JMS\Expose
     * @JMS\Type("string")
     * @JMS\SerializedName("previousIndexing")
     */
    protected $previousIndexing;

    /**
     * @param MeshDescriptorInterface $descriptor
     */
    public function setDescriptor(MeshDescriptorInterface $descriptor)
    {
        $this->descriptor = $descriptor;
    }

    /**
     * @return MeshDescriptorInterface
     */
    public function getDescriptor()
    {
        return $this->descriptor;
    }

    /**
     * @param string $previousIndexing
     */
    public function setPreviousIndexing($previousIndexing)
    {
        $this->previousIndexing = $previousIndexing;
    }

    /**
     * @return string
     */
    public function getPreviousIndexing()
    {
        return $this->previousIndexing;
    }
}


text:
package main

import (
	"flag"
	"fmt"
	"os"
	"os/signal"
	"strconv"
	"syscall"
	"time"

	"github.com/drone/drone-exec/docker"
	"github.com/drone/drone-exec/parser"
	"github.com/drone/drone-exec/runner"
	"github.com/drone/drone-exec/yaml/inject"
	"github.com/drone/drone-exec/yaml/path"
	"github.com/drone/drone-exec/yaml/secure"
	"github.com/drone/drone-exec/yaml/shasum"
	"github.com/drone/drone-plugin-go/plugin"
	"github.com/samalba/dockerclient"

	log "github.com/Sirupsen/logrus"
)

var (
	cache  bool // execute cache steps
	clone  bool // execute clone steps
	build  bool // execute build steps
	deploy bool // execute deploy steps
	notify bool // execute notify steps
	debug  bool // execute in debug mode
	force  bool // force pull plugin images
)

// payload defines the raw plugin payload that
// stores the build metadata and configuration.
var payload = struct {
	Yaml      string            `json:"config"`
	YamlEnc   string            `json:"secret"`
	Repo      *plugin.Repo      `json:"repo"`
	Build     *plugin.Build     `json:"build"`
	BuildLast *plugin.Build     `json:"build_last"`
	Job       *plugin.Job       `json:"job"`
	System    *plugin.System    `json:"system"`
	Workspace *plugin.Workspace `json:"workspace"`
}{}

func main() {

	// parses command line flags
	flag.BoolVar(&cache, "cache", false, "")
	flag.BoolVar(&clone, "clone", false, "")
	flag.BoolVar(&build, "build", false, "")
	flag.BoolVar(&deploy, "deploy", false, "")
	flag.BoolVar(&notify, "notify", false, "")
	flag.BoolVar(&debug, "debug", false, "")
	flag.BoolVar(&force, "pull", false, "")
	flag.Parse()

	// unmarshal the json payload via stdin or
	// via the command line args (whichever was used)
	plugin.MustUnmarshal(&payload)

	// configure the default log format and
	// log levels
	if debug {
		log.SetLevel(log.DebugLevel)
	}

	var sec *secure.Secure
	if payload.Workspace.Keys != nil {
		var err error
		sec, err = secure.Parse(payload.YamlEnc, payload.Workspace.Keys.Private)
		if err != nil {
			log.Debugln("Unable to decrypt encrypted secrets", err)
		} else {
			log.Debugln("Successfully decrypted secrets")
		}

	}
	// TODO This block of code (and the above block) need to be cleaned
	//      up and written in a manner that facilitates better unit testing.
	if sec != nil {
		verified := shasum.Check(payload.Yaml, sec.Checksum)

		// the checksum should be invalidated if the repository is
		// public, and the build is a pull request, and the checksum
		// value was not provided.
		if plugin.IsPullRequest(payload.Build) && !payload.Repo.Private && len(sec.Checksum) == 0 {
			verified = false
		}

		switch {
		case verified && plugin.IsPullRequest(payload.Build):
			log.Debugln("Injected secrets into Yaml safely")
			var err error
			payload.Yaml, err = inject.InjectSafe(payload.Yaml, sec.Environment.Map())
			if err != nil {
				fmt.Println("Error injecting Yaml secrets")
				os.Exit(1)
			}
		case verified:
			log.Debugln("Injected secrets into Yaml")
			payload.Yaml = inject.Inject(payload.Yaml, sec.Environment.Map())
		case !verified:
			// if we can't validate the Yaml file we don't inject
			// secrets, and therefore shouldn't bother running the
			// deploy and notify tests.
			deploy = false
			notify = false
			fmt.Println("Unable to validate Yaml checksum.", sec.Checksum)
		}
	}

	// injects the matrix configuration parameters
	// into the yaml prior to parsing.
	payload.Yaml = inject.Inject(payload.Yaml, payload.Job.Environment)
	payload.Yaml = inject.Inject(payload.Yaml, map[string]string{
		"COMMIT":       payload.Build.Commit.Sha[:7],
		"BRANCH":       payload.Build.Commit.Branch,
		"BUILD_NUMBER": strconv.Itoa(payload.Build.Number),
	})

	// extracts the clone path from the yaml. If
	// the clone path doesn't exist it uses a path
	// derrived from the repository uri.
	payload.Workspace.Path = path.Parse(payload.Yaml, payload.Repo.Link)
	payload.Workspace.Root = "/drone/src"

	rules := []parser.RuleFunc{
		parser.ImageName,
		parser.ImageMatchFunc(payload.System.Plugins),
		parser.ImagePullFunc(force),
		parser.SanitizeFunc(payload.Repo.Trusted), //&& !plugin.PullRequest(payload.Build)
		parser.CacheFunc(payload.Repo.FullName),
		parser.Escalate,
	}
	tree, err := parser.Parse(payload.Yaml, rules)
	if err != nil {
		log.Debugln(err) // print error messages in debug mode only
		log.Fatalln("Error parsing the .drone.yml")
		os.Exit(1)
	}
	r := runner.Load(tree)

	client, err := dockerclient.NewDockerClient("unix:///var/run/docker.sock", nil)
	if err != nil {
		log.Debugln(err)
		log.Fatalln("Error creating the docker client.")
		os.Exit(1)
	}

	// // creates a wrapper Docker client that uses an ambassador
	// // container to create a pod-like environment.
	controller, err := docker.NewClient(client)
	if err != nil {
		log.Debugln(err)
		log.Fatalln("Error creating the docker ambassador.")
		os.Exit(1)
	}
	defer controller.Destroy()

	// watch for sigkill (timeout or cancel build)
	killc := make(chan os.Signal, 1)
	signal.Notify(killc, syscall.SIGINT, syscall.SIGTERM)
	go func() {
		<-killc
		log.Println("Cancel request received, killing process")
		controller.Destroy() // possibe race here. implement lock on the other end
		os.Exit(130)         // cancel is treated like ctrl+c
	}()

	go func() {
		var timeout = payload.Repo.Timeout
		if timeout == 0 {
			timeout = 60
		}
		<-time.After(time.Duration(timeout) * time.Minute)
		log.Println("Timeout request received, killing process")
		controller.Destroy() // possibe race here. implement lock on the other end
		os.Exit(128)         // cancel is treated like ctrl+c
	}()

	state := &runner.State{
		Client:    controller,
		Stdout:    os.Stdout,
		Stderr:    os.Stdout,
		Repo:      payload.Repo,
		Build:     payload.Build,
		BuildLast: payload.BuildLast,
		Job:       payload.Job,
		System:    payload.System,
		Workspace: payload.Workspace,
	}
	if cache {
		err = r.RunNode(state, parser.NodeCache)
		if err != nil {
			log.Debugln(err)
		}
	}
	if clone {
		err = r.RunNode(state, parser.NodeClone)
		if err != nil {
			log.Debugln(err)
		}
	}
	if build && !state.Failed() {
		err = r.RunNode(state, parser.NodeCompose|parser.NodeBuild)
		if err != nil {
			log.Debugln(err)
		}
	}

	if deploy && !state.Failed() {
		err = r.RunNode(state, parser.NodePublish|parser.NodeDeploy)
		if err != nil {
			log.Debugln(err)
		}
	}

	// if the build is not failed, at this point
	// we can mark as successful
	if !state.Failed() {
		state.Job.Status = plugin.StateSuccess
		state.Build.Status = plugin.StateSuccess
	}

	if cache {
		err = r.RunNode(state, parser.NodeCache)
		if err != nil {
			log.Debugln(err)
		}
	}
	if notify {
		err = r.RunNode(state, parser.NodeNotify)
		if err != nil {
			log.Debugln(err)
		}
	}

	if state.Failed() {
		controller.Destroy()
		os.Exit(state.ExitCode())
	}
}


text:
<?xml version="1.0" encoding="utf-8" ?>
<Table Name="BoardReferenceTable" Namespace="Imageboard10.Core.ModelStorage.Boards" Visibility="public">
  <Columns>
    <Column Name="Id" Type="Text" Codepage="Unicode" Grbit="NotNULL" Size="50"/>
    <Column Name="Category" Type="LongText" Codepage="Unicode" Grbit="NotNULL" />
    <Column Name="ShortName" Type="LongText" Codepage="Unicode" Grbit="None" />
    <Column Name="DisplayName" Type="LongText" Codepage="Unicode" Grbit="None" />
    <Column Name="IsAdult" Type="Boolean" Codepage="Unicode" Grbit="NotNULL" />
    <Column Name="ExtendedData" Type="LongBinary" Grbit="None" />
    <Column Name="BumpLimit" Type="SignedInt32" Grbit="None" />
    <Column Name="DefaultName" Type="LongText" Codepage="Unicode" Grbit="None" />
    <Column Name="Pages" Type="SignedInt32" Grbit="None" />
  </Columns>
  <Indexes>
    <Index Name="PrimaryIndex" Grbit="Primary Unique">
      <Fields>
        <Field Name="Id" Sort="Asc"/>
      </Fields>
    </Index>
    <Index Name="CategoryIndex" Grbit="None">
      <Fields>
        <Field Name="Category" Sort="Asc"/>
      </Fields>
      <Views>
        <ViewName>CategoryFromIndex</ViewName>
      </Views>
    </Index>
    <Index Name="IsAdultIndex" Grbit="None">
      <Fields>
        <Field Name="IsAdult" Sort="Asc"/>
      </Fields>
    </Index>
    <Index Name="IsAdultAndCategoryIndex" Grbit="None">
      <Fields>
        <Field Name="IsAdult" Sort="Asc"/>
        <Field Name="Category" Sort="Asc"/>
      </Fields>
      <Views>
        <ViewName>IsAdultFromIndex</ViewName>
        <ViewName>IsAdultAndCategoryFromIndex</ViewName>
      </Views>
    </Index>
  </Indexes>
  <Views>
    <View Name="IsAdultFromIndex" Role="IndexFetch">
      <Field FetchFlags="FromIndex">IsAdult</Field>
    </View>
    <View Name="CategoryFromIndex" Role="IndexFetch">
      <Field FetchFlags="FromIndex">Category</Field>
    </View>
    <View Name="IsAdultAndCategoryFromIndex" Role="IndexFetch">
      <Field FetchFlags="FromIndex">IsAdult</Field>
      <Field FetchFlags="FromIndex">Category</Field>
    </View>
    <View Name="ShortInfoView" Role="Fetch">
      <Field>Id</Field>
      <Field>Category</Field>
      <Field>ShortName</Field>
      <Field>DisplayName</Field>
      <Field>IsAdult</Field>
    </View>
    <View Name="FullRowView" Role="Fetch Insert Update">
      <Field>Id</Field>
      <Field>Category</Field>
      <Field>ShortName</Field>
      <Field>DisplayName</Field>
      <Field>IsAdult</Field>
      <Field>ExtendedData</Field>
      <Field>BumpLimit</Field>
      <Field>DefaultName</Field>
      <Field>Pages</Field>
    </View>
  </Views>
</Table>


text:
var spawn = require('child_process').spawn,
    path = require('path'),
    gulp = require('gulp'),
    nodemon = require('gulp-nodemon');

exports.start = start;

function start() {
  var config = {
    execMap: {
      js: "node --harmony",
    },
    script: 'server.js',
    watch: ['server.js', 'dist/**/*.js'],

    stdout: false
  };

  return nodemon(config)
    .on('readable', function() {
      var bunyan = spawn('node', [path.join(__dirname, '/../node_modules/bunyan/bin/bunyan'), '-o', 'short'], { stdio: ['pipe', process.stdout, process.stderr] });
      this.stdout.pipe(bunyan.stdin);
      this.stderr.pipe(bunyan.stdin);
    });
}


text:
<?php

?>
    <?php # affichage des éventuels messages d'erreurs
    if ($app['messages']->hasError()) :
        echo $view->render('Common/message', [
            'type'        => 'danger',
            'messages'    => $app['messages']->getError()
        ]);
    endif; ?>

    <?php # affichage des éventuels messages d'avertissements
    if ($app['messages']->hasWarning()) :
        echo $view->render('Common/message', [
            'type'        => 'warning',
            'messages'    => $app['messages']->getWarning()
        ]);
    endif; ?>

    <?php # affichage des éventuels messages de confirmation
    if ($app['messages']->hasSuccess()) :
        echo $view->render('Common/message', [
            'type'        => 'success',
            'messages'    => $app['messages']->getSuccess()
        ]);
    endif; ?>

    <?php # affichage des éventuels messages d'information
    if ($app['messages']->hasInfo()) :
        echo $view->render('Common/message', [
            'type'        => 'info',
            'messages'    => $app['messages']->getInfo()
        ]);
    endif; ?>


text:
/**********
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.)

This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for
more details.

You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
**********/
// Copyright (c) 1996-2017 Live Networks, Inc.  All rights reserved.
// 'Group sockets'
// Implementation

#include "Groupsock.hh"
#include "GroupsockHelper.hh"
//##### Eventually fix the following #include; we shouldn't know about tunnels
#include "TunnelEncaps.hh"

#ifndef NO_SSTREAM
#include <sstream>
#endif
#include <stdio.h>

///////// OutputSocket //////////

OutputSocket::OutputSocket(UsageEnvironment& env)
  : Socket(env, 0 /* let kernel choose port */),
    fSourcePort(0), fLastSentTTL(256/*hack: a deliberately invalid value*/) {
}

OutputSocket::OutputSocket(UsageEnvironment& env, Port port)
  : Socket(env, port),
    fSourcePort(0), fLastSentTTL(256/*hack: a deliberately invalid value*/) {
}

OutputSocket::~OutputSocket() {
}

Boolean OutputSocket::write(netAddressBits address, portNumBits portNum, u_int8_t ttl,
			    unsigned char* buffer, unsigned bufferSize) {
  struct in_addr destAddr; destAddr.s_addr = address;
  if ((unsigned)ttl == fLastSentTTL) {
    // Optimization: Don't do a 'set TTL' system call again
    if (!writeSocket(env(), socketNum(), destAddr, portNum, buffer, bufferSize)) return False;
  } else {
    if (!writeSocket(env(), socketNum(), destAddr, portNum, ttl, buffer, bufferSize)) return False;
    fLastSentTTL = (unsigned)ttl;
  }

  if (sourcePortNum() == 0) {
    // Now that we've sent a packet, we can find out what the
    // kernel chose as our ephemeral source port number:
    if (!getSourcePort(env(), socketNum(), fSourcePort)) {
      if (DebugLevel >= 1)
	env() << *this
	     << ": failed to get source port: "
	     << env().getResultMsg() << "\n";
      return False;
    }
  }

  return True;
}

// By default, we don't do reads:
Boolean OutputSocket
::handleRead(unsigned char* /*buffer*/, unsigned /*bufferMaxSize*/,
	     unsigned& /*bytesRead*/, struct sockaddr_in& /*fromAddressAndPort*/) {
  return True;
}

///////// destRecord //////////

destRecord
::destRecord(struct in_addr const& addr, Port const& port, u_int8_t ttl, unsigned sessionId,
	     destRecord* next)
  : fNext(next), fGroupEId(addr, port.num(), ttl), fSessionId(sessionId) {
}

destRecord::~destRecord() {
  delete fNext;
}

///////// Groupsock //////////

NetInterfaceTrafficStats Groupsock::statsIncoming;
NetInterfaceTrafficStats Groupsock::statsOutgoing;
NetInterfaceTrafficStats Groupsock::statsRelayedIncoming;
NetInterfaceTrafficStats Groupsock::statsRelayedOutgoing;

// Constructor for a source-independent multicast group
Groupsock::Groupsock(UsageEnvironment& env, struct in_addr const& groupAddr,
		     Port port, u_int8_t ttl)
  : OutputSocket(env, port),
    deleteIfNoMembers(False), isSlave(False),
    fDests(new destRecord(groupAddr, port, ttl, 0, NULL)),
    fIncomingGroupEId(groupAddr, port.num(), ttl) {

  if (!socketJoinGroup(env, socketNum(), groupAddr.s_addr)) {
    if (DebugLevel >= 1) {
      env << *this << ": failed to join group: "
	  << env.getResultMsg() << "\n";
    }
  }

  // Make sure we can get our source address:
  if (ourIPAddress(env) == 0) {
    if (DebugLevel >= 0) { // this is a fatal error
      env << "Unable to determine our source address: "
	  << env.getResultMsg() << "\n";
    }
  }

  if (DebugLevel >= 2) env << *this << ": created\n";
}

// Constructor for a source-specific multicast group
Groupsock::Groupsock(UsageEnvironment& env, struct in_addr const& groupAddr,
		     struct in_addr const& sourceFilterAddr,
		     Port port)
  : OutputSocket(env, port),
    deleteIfNoMembers(False), isSlave(False),
    fDests(new destRecord(groupAddr, port, 255, 0, NULL)),
    fIncomingGroupEId(groupAddr, sourceFilterAddr, port.num()) {
  // First try a SSM join.  If that fails, try a regular join:
  if (!socketJoinGroupSSM(env, socketNum(), groupAddr.s_addr,
			  sourceFilterAddr.s_addr)) {
    if (DebugLevel >= 3) {
      env << *this << ": SSM join failed: "
	  << env.getResultMsg();
      env << " - trying regular join instead\n";
    }
    if (!socketJoinGroup(env, socketNum(), groupAddr.s_addr)) {
      if (DebugLevel >= 1) {
	env << *this << ": failed to join group: "
	     << env.getResultMsg() << "\n";
      }
    }
  }

  if (DebugLevel >= 2) env << *this << ": created\n";
}

Groupsock::~Groupsock() {
  if (isSSM()) {
    if (!socketLeaveGroupSSM(env(), socketNum(), groupAddress().s_addr,
			     sourceFilterAddress().s_addr)) {
      socketLeaveGroup(env(), socketNum(), groupAddress().s_addr);
    }
  } else {
    socketLeaveGroup(env(), socketNum(), groupAddress().s_addr);
  }

  delete fDests;

  if (DebugLevel >= 2) env() << *this << ": deleting\n";
}

destRecord* Groupsock
::createNewDestRecord(struct in_addr const& addr, Port const& port, u_int8_t ttl,
		      unsigned sessionId, destRecord* next) {
  // Default implementation:
  return new destRecord(addr, port, ttl, sessionId, next);
}

void
Groupsock::changeDestinationParameters(struct in_addr const& newDestAddr,
				       Port newDestPort, int newDestTTL, unsigned sessionId) {
  destRecord* dest;
  for (dest = fDests; dest != NULL && dest->fSessionId != sessionId; dest = dest->fNext) {}

  if (dest == NULL) { // There's no existing 'destRecord' for this "sessionId"; add a new one:
    fDests = createNewDestRecord(newDestAddr, newDestPort, newDestTTL, sessionId, fDests);
    return;
  }

  // "dest" is an existing 'destRecord' for this "sessionId"; change its values to the new ones:
  struct in_addr destAddr = dest->fGroupEId.groupAddress();
  if (newDestAddr.s_addr != 0) {
    if (newDestAddr.s_addr != destAddr.s_addr
	&& IsMulticastAddress(newDestAddr.s_addr)) {
      // If the new destination is a multicast address, then we assume that
      // we want to join it also.  (If this is not in fact the case, then
      // call "multicastSendOnly()" afterwards.)
      socketLeaveGroup(env(), socketNum(), destAddr.s_addr);
      socketJoinGroup(env(), socketNum(), newDestAddr.s_addr);
    }
    destAddr.s_addr = newDestAddr.s_addr;
  }

  portNumBits destPortNum = dest->fGroupEId.portNum();
  if (newDestPort.num() != 0) {
    if (newDestPort.num() != destPortNum
	&& IsMulticastAddress(destAddr.s_addr)) {
      // Also bind to the new port number:
      changePort(newDestPort);
      // And rejoin the multicast group:
      socketJoinGroup(env(), socketNum(), destAddr.s_addr);
    }
    destPortNum = newDestPort.num();
  }

  u_int8_t destTTL = ttl();
  if (newDestTTL != ~0) destTTL = (u_int8_t)newDestTTL;

  dest->fGroupEId = GroupEId(destAddr, destPortNum, destTTL);

  // Finally, remove any other 'destRecord's that might also have this "sessionId":
  removeDestinationFrom(dest->fNext, sessionId);
}

unsigned Groupsock
::lookupSessionIdFromDestination(struct sockaddr_in const& destAddrAndPort) const {
  destRecord* dest = lookupDestRecordFromDestination(destAddrAndPort);
  if (dest == NULL) return 0;

  return dest->fSessionId;
}

void Groupsock::addDestination(struct in_addr const& addr, Port const& port, unsigned sessionId) {
  // Default implementation:
  // If there's no existing 'destRecord' with the same "addr", "port", and "sessionId", add a new one:
  for (destRecord* dest = fDests; dest != NULL; dest = dest->fNext) {
    if (sessionId == dest->fSessionId
	&& addr.s_addr == dest->fGroupEId.groupAddress().s_addr
	&& port.num() == dest->fGroupEId.portNum()) {
      return;
    }
  }

  fDests = createNewDestRecord(addr, port, 255, sessionId, fDests);
}

void Groupsock::removeDestination(unsigned sessionId) {
  // Default implementation:
  removeDestinationFrom(fDests, sessionId);
}

void Groupsock::removeAllDestinations() {
  delete fDests; fDests = NULL;
}

void Groupsock::multicastSendOnly() {
  // We disable this code for now, because - on some systems - leaving the multicast group seems to cause sent packets
  // to not be received by other applications (at least, on the same host).
#if 0
  socketLeaveGroup(env(), socketNum(), fIncomingGroupEId.groupAddress().s_addr);
  for (destRecord* dests = fDests; dests != NULL; dests = dests->fNext) {
    socketLeaveGroup(env(), socketNum(), dests->fGroupEId.groupAddress().s_addr);
  }
#endif
}

Boolean Groupsock::output(UsageEnvironment& env, unsigned char* buffer, unsigned bufferSize,
			  DirectedNetInterface* interfaceNotToFwdBackTo) {
  do {
    // First, do the datagram send, to each destination:
    Boolean writeSuccess = True;
    for (destRecord* dests = fDests; dests != NULL; dests = dests->fNext) {
      if (!write(dests->fGroupEId.groupAddress().s_addr, dests->fGroupEId.portNum(), dests->fGroupEId.ttl(),
		 buffer, bufferSize)) {
	writeSuccess = False;
	break;
      }
    }
    if (!writeSuccess) break;
    statsOutgoing.countPacket(bufferSize);
    statsGroupOutgoing.countPacket(bufferSize);

    // Then, forward to our members:
    int numMembers = 0;
    if (!members().IsEmpty()) {
      numMembers =
	outputToAllMembersExcept(interfaceNotToFwdBackTo,
				 ttl(), buffer, bufferSize,
				 ourIPAddress(env));
      if (numMembers < 0) break;
    }

    if (DebugLevel >= 3) {
      env << *this << ": wrote " << bufferSize << " bytes, ttl " << (unsigned)ttl();
      if (numMembers > 0) {
	env << "; relayed to " << numMembers << " members";
      }
      env << "\n";
    }
    return True;
  } while (0);

  if (DebugLevel >= 0) { // this is a fatal error
    UsageEnvironment::MsgString msg = strDup(env.getResultMsg());
    env.setResultMsg("Groupsock write failed: ", msg);
    delete[] (char*)msg;
  }
  return False;
}

Boolean Groupsock::handleRead(unsigned char* buffer, unsigned bufferMaxSize,
			      unsigned& bytesRead,
			      struct sockaddr_in& fromAddressAndPort) {
  // Read data from the socket, and relay it across any attached tunnels
  //##### later make this code more general - independent of tunnels

  bytesRead = 0;

  int maxBytesToRead = bufferMaxSize - TunnelEncapsulationTrailerMaxSize;
  int numBytes = readSocket(env(), socketNum(),
			    buffer, maxBytesToRead, fromAddressAndPort);
  if (numBytes < 0) {
    if (DebugLevel >= 0) { // this is a fatal error
      UsageEnvironment::MsgString msg = strDup(env().getResultMsg());
      env().setResultMsg("Groupsock read failed: ", msg);
      delete[] (char*)msg;
    }
    return False;
  }

  // If we're a SSM group, make sure the source address matches:
  if (isSSM()
      && fromAddressAndPort.sin_addr.s_addr != sourceFilterAddress().s_addr) {
    return True;
  }

  // We'll handle this data.
  // Also write it (with the encapsulation trailer) to each member,
  // unless the packet was originally sent by us to begin with.
  bytesRead = numBytes;

  int numMembers = 0;
  if (!wasLoopedBackFromUs(env(), fromAddressAndPort)) {
    statsIncoming.countPacket(numBytes);
    statsGroupIncoming.countPacket(numBytes);
    numMembers =
      outputToAllMembersExcept(NULL, ttl(),
			       buffer, bytesRead,
			       fromAddressAndPort.sin_addr.s_addr);
    if (numMembers > 0) {
      statsRelayedIncoming.countPacket(numBytes);
      statsGroupRelayedIncoming.countPacket(numBytes);
    }
  }
  if (DebugLevel >= 3) {
    env() << *this << ": read " << bytesRead << " bytes from " << AddressString(fromAddressAndPort).val() << ", port " << ntohs(fromAddressAndPort.sin_port);
    if (numMembers > 0) {
      env() << "; relayed to " << numMembers << " members";
    }
    env() << "\n";
  }

  return True;
}

Boolean Groupsock::wasLoopedBackFromUs(UsageEnvironment& env,
				       struct sockaddr_in& fromAddressAndPort) {
  if (fromAddressAndPort.sin_addr.s_addr == ourIPAddress(env) ||
      fromAddressAndPort.sin_addr.s_addr == 0x7F000001/*127.0.0.1*/) {
    if (fromAddressAndPort.sin_port == sourcePortNum()) {
#ifdef DEBUG_LOOPBACK_CHECKING
      if (DebugLevel >= 3) {
	env() << *this << ": got looped-back packet\n";
      }
#endif
      return True;
    }
  }

  return False;
}

destRecord* Groupsock
::lookupDestRecordFromDestination(struct sockaddr_in const& destAddrAndPort) const {
  for (destRecord* dest = fDests; dest != NULL; dest = dest->fNext) {
    if (destAddrAndPort.sin_addr.s_addr == dest->fGroupEId.groupAddress().s_addr
	&& destAddrAndPort.sin_port == dest->fGroupEId.portNum()) {
      return dest;
    }
  }
  return NULL;
}

void Groupsock::removeDestinationFrom(destRecord*& dests, unsigned sessionId) {
  destRecord** destsPtr = &dests;
  while (*destsPtr != NULL) {
    if (sessionId == (*destsPtr)->fSessionId) {
      // Remove the record pointed to by *destsPtr :
      destRecord* next = (*destsPtr)->fNext;
      (*destsPtr)->fNext = NULL;
      delete (*destsPtr);
      *destsPtr = next;
    } else {
      destsPtr = &((*destsPtr)->fNext);
    }
  }
}

int Groupsock::outputToAllMembersExcept(DirectedNetInterface* exceptInterface,
					u_int8_t ttlToFwd,
					unsigned char* data, unsigned size,
					netAddressBits sourceAddr) {
  // Don't forward TTL-0 packets
  if (ttlToFwd == 0) return 0;

  DirectedNetInterfaceSet::Iterator iter(members());
  unsigned numMembers = 0;
  DirectedNetInterface* interf;
  while ((interf = iter.next()) != NULL) {
    // Check whether we've asked to exclude this interface:
    if (interf == exceptInterface)
      continue;

    // Check that the packet's source address makes it OK to
    // be relayed across this interface:
    UsageEnvironment& saveEnv = env();
    // because the following call may delete "this"
    if (!interf->SourceAddrOKForRelaying(saveEnv, sourceAddr)) {
      if (strcmp(saveEnv.getResultMsg(), "") != 0) {
				// Treat this as a fatal error
	return -1;
      } else {
	continue;
      }
    }

    if (numMembers == 0) {
      // We know that we're going to forward to at least one
      // member, so fill in the tunnel encapsulation trailer.
      // (Note: Allow for it not being 4-byte-aligned.)
      TunnelEncapsulationTrailer* trailerInPacket
	= (TunnelEncapsulationTrailer*)&data[size];
      TunnelEncapsulationTrailer* trailer;

      Boolean misaligned = ((uintptr_t)trailerInPacket & 3) != 0;
      unsigned trailerOffset;
      u_int8_t tunnelCmd;
      if (isSSM()) {
	// add an 'auxilliary address' before the trailer
	trailerOffset = TunnelEncapsulationTrailerAuxSize;
	tunnelCmd = TunnelDataAuxCmd;
      } else {
	trailerOffset = 0;
	tunnelCmd = TunnelDataCmd;
      }
      unsigned trailerSize = TunnelEncapsulationTrailerSize + trailerOffset;
      unsigned tmpTr[TunnelEncapsulationTrailerMaxSize];
      if (misaligned) {
	trailer = (TunnelEncapsulationTrailer*)&tmpTr;
      } else {
	trailer = trailerInPacket;
      }
      trailer += trailerOffset;

      if (fDests != NULL) {
	trailer->address() = fDests->fGroupEId.groupAddress().s_addr;
	Port destPort(ntohs(fDests->fGroupEId.portNum()));
	trailer->port() = destPort; // structure copy
      }
      trailer->ttl() = ttlToFwd;
      trailer->command() = tunnelCmd;

      if (isSSM()) {
	trailer->auxAddress() = sourceFilterAddress().s_addr;
      }

      if (misaligned) {
	memmove(trailerInPacket, trailer-trailerOffset, trailerSize);
      }

      size += trailerSize;
    }

    interf->write(data, size);
    ++numMembers;
  }

  return numMembers;
}

UsageEnvironment& operator<<(UsageEnvironment& s, const Groupsock& g) {
  UsageEnvironment& s1 = s << timestampString() << " Groupsock("
			   << g.socketNum() << ": "
			   << AddressString(g.groupAddress()).val()
			   << ", " << g.port() << ", ";
  if (g.isSSM()) {
    return s1 << "SSM source: "
	      <<  AddressString(g.sourceFilterAddress()).val() << ")";
  } else {
    return s1 << (unsigned)(g.ttl()) << ")";
  }
}

////////// GroupsockLookupTable //////////

// A hash table used to index Groupsocks by socket number.

static HashTable*& getSocketTable(UsageEnvironment& env) {
  _groupsockPriv* priv = groupsockPriv(env);
  if (priv->socketTable == NULL) { // We need to create it
    priv->socketTable = HashTable::create(ONE_WORD_HASH_KEYS);
  }
  return priv->socketTable;
}

static Boolean unsetGroupsockBySocket(Groupsock const* groupsock) {
  do {
    if (groupsock == NULL) break;

    int sock = groupsock->socketNum();
    // Make sure "sock" is in bounds:
    if (sock < 0) break;

    HashTable*& sockets = getSocketTable(groupsock->env());

    Groupsock* gs = (Groupsock*)sockets->Lookup((char*)(long)sock);
    if (gs == NULL || gs != groupsock) break;
    sockets->Remove((char*)(long)sock);

    if (sockets->IsEmpty()) {
      // We can also delete the table (to reclaim space):
      delete sockets; sockets = NULL;
      reclaimGroupsockPriv(gs->env());
    }

    return True;
  } while (0);

  return False;
}

static Boolean setGroupsockBySocket(UsageEnvironment& env, int sock,
				    Groupsock* groupsock) {
  do {
    // Make sure the "sock" parameter is in bounds:
    if (sock < 0) {
      char buf[100];
      sprintf(buf, "trying to use bad socket (%d)", sock);
      env.setResultMsg(buf);
      break;
    }

    HashTable* sockets = getSocketTable(env);

    // Make sure we're not replacing an existing Groupsock (although that shouldn't happen)
    Boolean alreadyExists
      = (sockets->Lookup((char*)(long)sock) != 0);
    if (alreadyExists) {
      char buf[100];
      sprintf(buf, "Attempting to replace an existing socket (%d)", sock);
      env.setResultMsg(buf);
      break;
    }

    sockets->Add((char*)(long)sock, groupsock);
    return True;
  } while (0);

  return False;
}

static Groupsock* getGroupsockBySocket(UsageEnvironment& env, int sock) {
  do {
    // Make sure the "sock" parameter is in bounds:
    if (sock < 0) break;

    HashTable* sockets = getSocketTable(env);
    return (Groupsock*)sockets->Lookup((char*)(long)sock);
  } while (0);

  return NULL;
}

Groupsock*
GroupsockLookupTable::Fetch(UsageEnvironment& env,
			    netAddressBits groupAddress,
			    Port port, u_int8_t ttl,
			    Boolean& isNew) {
  isNew = False;
  Groupsock* groupsock;
  do {
    groupsock = (Groupsock*) fTable.Lookup(groupAddress, (~0), port);
    if (groupsock == NULL) { // we need to create one:
      groupsock = AddNew(env, groupAddress, (~0), port, ttl);
      if (groupsock == NULL) break;
      isNew = True;
    }
  } while (0);

  return groupsock;
}

Groupsock*
GroupsockLookupTable::Fetch(UsageEnvironment& env,
			    netAddressBits groupAddress,
			    netAddressBits sourceFilterAddr, Port port,
			    Boolean& isNew) {
  isNew = False;
  Groupsock* groupsock;
  do {
    groupsock
      = (Groupsock*) fTable.Lookup(groupAddress, sourceFilterAddr, port);
    if (groupsock == NULL) { // we need to create one:
      groupsock = AddNew(env, groupAddress, sourceFilterAddr, port, 0);
      if (groupsock == NULL) break;
      isNew = True;
    }
  } while (0);

  return groupsock;
}

Groupsock*
GroupsockLookupTable::Lookup(netAddressBits groupAddress, Port port) {
  return (Groupsock*) fTable.Lookup(groupAddress, (~0), port);
}

Groupsock*
GroupsockLookupTable::Lookup(netAddressBits groupAddress,
			     netAddressBits sourceFilterAddr, Port port) {
  return (Groupsock*) fTable.Lookup(groupAddress, sourceFilterAddr, port);
}

Groupsock* GroupsockLookupTable::Lookup(UsageEnvironment& env, int sock) {
  return getGroupsockBySocket(env, sock);
}

Boolean GroupsockLookupTable::Remove(Groupsock const* groupsock) {
  unsetGroupsockBySocket(groupsock);
  return fTable.Remove(groupsock->groupAddress().s_addr,
		       groupsock->sourceFilterAddress().s_addr,
		       groupsock->port());
}

Groupsock* GroupsockLookupTable::AddNew(UsageEnvironment& env,
					netAddressBits groupAddress,
					netAddressBits sourceFilterAddress,
					Port port, u_int8_t ttl) {
  Groupsock* groupsock;
  do {
    struct in_addr groupAddr; groupAddr.s_addr = groupAddress;
    if (sourceFilterAddress == netAddressBits(~0)) {
      // regular, ISM groupsock
      groupsock = new Groupsock(env, groupAddr, port, ttl);
    } else {
      // SSM groupsock
      struct in_addr sourceFilterAddr;
      sourceFilterAddr.s_addr = sourceFilterAddress;
      groupsock = new Groupsock(env, groupAddr, sourceFilterAddr, port);
    }

    if (groupsock == NULL || groupsock->socketNum() < 0) break;

    if (!setGroupsockBySocket(env, groupsock->socketNum(), groupsock)) break;

    fTable.Add(groupAddress, sourceFilterAddress, port, (void*)groupsock);
  } while (0);

  return groupsock;
}

GroupsockLookupTable::Iterator::Iterator(GroupsockLookupTable& groupsocks)
  : fIter(AddressPortLookupTable::Iterator(groupsocks.fTable)) {
}

Groupsock* GroupsockLookupTable::Iterator::next() {
  return (Groupsock*) fIter.next();
};


text:
import * as React from 'react';
import { Icon, grid1 } from '../components';
import { Link } from 'react-router-dom';

const Post = ({ cover, title, description, permalink, datePublished, dateModified, keywords, style = {} }) => {
    let published = new Date(datePublished);
    let publishedStr = published.toLocaleTimeString(undefined, { hour: 'numeric', minute: 'numeric' });

    let updated = new Date(dateModified);

    return (
        <Link
            to={permalink.replace('*', '')}
            style={
                {
                    ...styles.blogPost,
                    ...style,
                    backgroundImage: `url('${cover}')`
                } as any
            }
        >

        </Link>
    );
};
const slideshow = [
    {
        cover: '/blog/raytracing-denoising/assets/cover.jpg',
        title: 'Ray Tracing Denoising',
        description: 'A review of denoising and sampling techniques for real time raytracing.',
        keywords: [ 'blog' ],
        permalink: '/blog/raytracing-denoising'
    },
    {
        cover: '/blog/noise-generation-survey/assets/cover.jpg',
        title: 'Noise Generation Survey',
        description: 'A summary of different procedural noise functions.',
        keywords: [ 'blog' ],
        permalink: '/blog/noise-generation-survey'
    },
    {
        cover: '/blog/raw-opengl/assets/cover.jpg',
        title: 'Raw OpenGL',
        description: 'A post to get from 0 to drawing in no time flat.',
        keywords: [ 'blog' ],
        permalink: '/blog/raw-opengl'
    },
    {
        cover: '/research/baked-texture-generation/assets/cover.jpg',
        title: 'GPU Zen 2 - Baked Texture Generation',
        description: 'A technical chapter detailing a technique for handling artist driven baking.',
        keywords: [ 'research' ],
        permalink: '/research/baked-texture-generation'
    },
    {
        cover: '/libraries/coronal/assets/cover.jpg',
        permalink: '/libraries/coronal'
    },
    {
        cover: '/blog/raw-metal/assets/cover.jpg',
        permalink: '/blog/raw-metal'
    }
];

export class Featured extends React.Component<any, any> {
    intervalHandle: any;

    componentWillMount() {
        if (typeof window !== 'undefined' && typeof document !== 'undefined') {
            window.scrollTo(0, 0);
            document.title = 'Alain Galvan | Engineer @ Marmoset';
        }
    }

    render() {
        return (

                        Let's Work Hard!

                        I'm{' '}
                        <Link to="/about" style={{color: '#fff'}}>

                            {' '}
                            Alain
                        {' '}

                            (pronounced Alan)
                        </Link>, a Graphics Software Engineer @{' '}

                            <Icon type="marmoset" size={32} /> Marmoset
                        , working remotely just north of{' '}

                            <Icon type="palm" size={32} /> West Palm Beach.

                        Here's my most recent work, let's talk shop!

                    {grid1(Post, slideshow, this.props.tabletQuery)}

        );
    }
}

const styles = {
    root: {
        width: '100%',
        height: '100%',
        display: 'flex',
        alignItems: 'center',
        overflow: 'visible'
    },
    blogPost: {
        display: 'flex',
        height: 400,
        alignItems: 'flex-end',
        backgroundSize: 'cover',
        backgroundPosition: 'center'
    },
    h1: {
        textTransform: 'uppercase',
        fontWeight: 200,
        fontSize: '14vmin'
    },
    h3: {
        fontWeight: 200,
        fontSize: '4.5vmin',
        letterSpacing: '0',
        padding: '4vmin 0 0 0',
        margin: '8vmin'
    },
    title: {
        lineHeight: '8vmin',
        display: 'flex',
        alignItems: 'center',
        transformOrigin: '0 50%',
        transition: 'transform 0.3s ease-out',
        justifyContent: 'center',
        textAlign: 'center',
        flexDirection: 'column'
    },
    logotype: {
        paddingTop: '4vmin',
        color: '#fff'
    },
    marmoset: {
        color: '#e7557c'
    },
    logo: {
        height: '30vw'
    },

    footer: {
        position: 'absolute',
        bottom: 0,
        color: 'rgba(255,255,255,.5)',
        left: 0,
        textAlign: 'center',
        width: '100%'
    },
    socialBar: {
        position: 'absolute',
        bottom: '2.5em',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center'
    },

    figure: {
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        flexDirection: 'column',
        height: '100vh',
        position: 'relative',
        zIndex: 1,
        backgroundSize: 'cover',
        backgroundPosition: 'center'
    },
    p: {
        textAlign: 'center',
        lineHeight: '1.5em',
        paddingTop: '.5em'
    },
    link: {
        width: '100%',
        height: '100%',
        transition: 'opacity 0.3s ease-out'
    }
};


text:
package org.jnosql.artemis.reflection;

/**
 * The tuple between the instance value and {@link FieldMapping}
 */
public interface FieldValue {

    /**
     * Creates a {@link FieldValue} instance
     *
     * @param value the value
     * @param field the field
     * @return the {@link FieldValue} instance
     */
    static FieldValue of(Object value, FieldMapping field) {
        return new DefaultFieldValue(value, field);
    }

    /**
     * Returns the instance
     *
     * @return the instance
     */
    Object getValue();

    /**
     * returns the {@link FieldMapping}
     *
     * @return the {@link FieldMapping} instance
     */
    FieldMapping getField();

    /**
     * Returns true if {@link FieldValue#getValue()} is different of null
     *
     * @return if {@link FieldValue#getValue()} is different of null
     */
    boolean isNotEmpty();

}


text:
// <copyright file="NumericalHessian.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
//
// Copyright (c) 2009-2015 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>

using System;

namespace MathNet.Numerics.Differentiation
{
    /// <summary>
    /// Class for evaluating the Hessian of a smooth continuously differentiable function using finite differences.
    /// By default, a central 3-point method is used.
    /// </summary>
    public class NumericalHessian
    {
        /// <summary>
        /// Number of function evaluations.
        /// </summary>
        public int FunctionEvaluations
        {
            get { return _df.Evaluations; }
        }

        private readonly NumericalDerivative _df;

        /// <summary>
        /// Creates a numerical Hessian object with a three point central difference method.
        /// </summary>
        public NumericalHessian() : this(3, 1) { }

        /// <summary>
        /// Creates a numerical Hessian with a specified differentiation scheme.
        /// </summary>
        /// <param name="points">Number of points for Hessian evaluation.</param>
        /// <param name="center">Center point for differentiation.</param>
        public NumericalHessian(int points, int center)
        {
            _df = new NumericalDerivative(points, center);
        }

        /// <summary>
        /// Evaluates the Hessian of the scalar univariate function f at points x.
        /// </summary>
        /// <param name="f">Scalar univariate function handle.</param>
        /// <param name="x">Point at which to evaluate Hessian.</param>
        /// <returns>Hessian tensor.</returns>
        public double[] Evaluate(Func<double, double> f, double x)
        {
            return new[] { _df.EvaluateDerivative(f, x, 2) };
        }

        /// <summary>
        /// Evaluates the Hessian of a multivariate function f at points x.
        /// </summary>
        /// <remarks>
        /// This method of computing the Hessian is only vaid for Lipschitz continuous functions.
        /// The function mirrors the Hessian along the diagonal since d2f/dxdy = d2f/dydx for continuously differentiable functions.
        /// </remarks>
        /// <param name="f">Multivariate function handle.></param>
        /// <param name="x">Points at which to evaluate Hessian.></param>
        /// <returns>Hessian tensor.</returns>
        public double[,] Evaluate(Func<double[], double> f, double[] x)
        {
            var hessian = new double[x.Length, x.Length];

            // Compute diagonal elements
            for (var row = 0; row < x.Length; row++)
            {
                hessian[row, row] = _df.EvaluatePartialDerivative(f, x, row, 2);
            }

            // Compute non-diagonal elements
            for (var row = 0; row < x.Length; row++)
            {
                for (var col = 0; col < row; col++)
                {
                    var mixedPartial = _df.EvaluateMixedPartialDerivative(f, x, new[] { row, col }, 2);

                    hessian[row, col] = mixedPartial;
                    hessian[col, row] = mixedPartial;
                }
            }
            return hessian;
        }

        /// <summary>
        /// Resets the function evaluation counter for the Hessian.
        /// </summary>
        public void ResetFunctionEvaluations()
        {
            _df.ResetEvaluations();
        }
    }
}


text:
package com.google.common.collect;

import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;

import javax.annotation.Nullable;

/**
 * Implementation of {@code Multimap} that does not allow duplicate key-value
 * entries and that returns collections whose iterators follow the ordering in
 * which the data was added to the multimap.
 *
 *
The collections returned by {@code keySet}, {@code keys}, and {@code
 * asMap} iterate through the keys in the order they were first added to the
 * multimap. Similarly, {@code get}, {@code removeAll}, and {@code
 * replaceValues} return collections that iterate through the values in the
 * order they were added. The collections generated by {@code entries} and
 * {@code values} iterate across the key-value mappings in the order they were
 * added to the multimap.
 *
 *
The iteration ordering of the collections generated by {@code keySet},
 * {@code keys}, and {@code asMap} has a few subtleties. As long as the set of
 * keys remains unchanged, adding or removing mappings does not affect the key
 * iteration order. However, if you remove all values associated with a key and
 * then add the key back to the multimap, that key will come last in the key
 * iteration order.
 *
 *
The multimap does not store duplicate key-value pairs. Adding a new
 * key-value pair equal to an existing key-value pair has no effect.
 *
 *
Keys and values may be null. All optional multimap methods are supported,
 * and all returned views are modifiable.
 *
 *
This class is not threadsafe when any concurrent operations update the
 * multimap. Concurrent read operations will work correctly. To allow concurrent
 * update operations, wrap your multimap with a call to {@link
 * Multimaps#synchronizedSetMultimap}.
 *
 * @author Jared Levy
 * @since 2010.01.04 stable (imported from Google Collections Library)
 */
@GwtCompatible(serializable = true)
public final class LinkedHashMultimap<K, V> extends AbstractSetMultimap<K, V> {
  private static final int DEFAULT_VALUES_PER_KEY = 8;

  @VisibleForTesting
  transient int expectedValuesPerKey = DEFAULT_VALUES_PER_KEY;

  /**
   * Map entries with an iteration order corresponding to the order in which the
   * key-value pairs were added to the multimap.
   */
  // package-private for GWT deserialization
  transient Collection<Map.Entry<K, V>> linkedEntries;

  /**
   * Creates a new, empty {@code LinkedHashMultimap} with the default initial
   * capacities.
   */
  public static <K, V> LinkedHashMultimap<K, V> create() {
    return new LinkedHashMultimap<K, V>();
  }

  /**
   * Constructs an empty {@code LinkedHashMultimap} with enough capacity to hold
   * the specified numbers of keys and values without rehashing.
   *
   * @param expectedKeys the expected number of distinct keys
   * @param expectedValuesPerKey the expected average number of values per key
   * @throws IllegalArgumentException if {@code expectedKeys} or {@code
   *      expectedValuesPerKey} is negative
   */
  public static <K, V> LinkedHashMultimap<K, V> create(
      int expectedKeys, int expectedValuesPerKey) {
    return new LinkedHashMultimap<K, V>(expectedKeys, expectedValuesPerKey);
  }

  /**
   * Constructs a {@code LinkedHashMultimap} with the same mappings as the
   * specified multimap. If a key-value mapping appears multiple times in the
   * input multimap, it only appears once in the constructed multimap. The new
   * multimap has the same {@link Multimap#entries()} iteration order as the
   * input multimap, except for excluding duplicate mappings.
   *
   * @param multimap the multimap whose contents are copied to this multimap
   */
  public static <K, V> LinkedHashMultimap<K, V> create(
      Multimap<? extends K, ? extends V> multimap) {
    return new LinkedHashMultimap<K, V>(multimap);
  }

  private LinkedHashMultimap() {
    super(new LinkedHashMap<K, Collection<V>>());
    linkedEntries = Sets.newLinkedHashSet();
  }

  private LinkedHashMultimap(int expectedKeys, int expectedValuesPerKey) {
    super(new LinkedHashMap<K, Collection<V>>(expectedKeys));
    Preconditions.checkArgument(expectedValuesPerKey >= 0);
    this.expectedValuesPerKey = expectedValuesPerKey;
    linkedEntries = new LinkedHashSet<Map.Entry<K, V>>(
        expectedKeys * expectedValuesPerKey);
  }

  private LinkedHashMultimap(Multimap<? extends K, ? extends V> multimap) {
    super(new LinkedHashMap<K, Collection<V>>(
        Maps.capacity(multimap.keySet().size())));
    linkedEntries
        = new LinkedHashSet<Map.Entry<K, V>>(Maps.capacity(multimap.size()));
    putAll(multimap);
  }

  /**
   * {@inheritDoc}
   *
   *
Creates an empty {@code LinkedHashSet} for a collection of values for
   * one key.
   *
   * @return a new {@code LinkedHashSet} containing a collection of values for
   *     one key
   */
  @Override Set<V> createCollection() {
    return new LinkedHashSet<V>(Maps.capacity(expectedValuesPerKey));
  }

  /**
   * {@inheritDoc}
   *
   *
Creates a decorated {@code LinkedHashSet} that also keeps track of the
   * order in which key-value pairs are added to the multimap.
   *
   * @param key key to associate with values in the collection
   * @return a new decorated {@code LinkedHashSet} containing a collection of
   *     values for one key
   */
  @Override Collection<V> createCollection(@Nullable K key) {
    return new SetDecorator(key, createCollection());
  }

  private class SetDecorator extends ForwardingSet<V> {
    final Set<V> delegate;
    final K key;

    SetDecorator(@Nullable K key, Set<V> delegate) {
      this.delegate = delegate;
      this.key = key;
    }

    @Override protected Set<V> delegate() {
      return delegate;
    }

    <E> Map.Entry<K, E> createEntry(@Nullable E value) {
      return Maps.immutableEntry(key, value);
    }

    <E> Collection<Map.Entry<K, E>> createEntries(Collection<E> values) {
      // converts a collection of values into a list of key/value map entries
      Collection<Map.Entry<K, E>> entries
          = Lists.newArrayListWithExpectedSize(values.size());
      for (E value : values) {
        entries.add(createEntry(value));
      }
      return entries;
    }

    @Override public boolean add(@Nullable V value) {
      boolean changed = delegate.add(value);
      if (changed) {
        linkedEntries.add(createEntry(value));
      }
      return changed;
    }

    @Override public boolean addAll(Collection<? extends V> values) {
      boolean changed = delegate.addAll(values);
      if (changed) {
        linkedEntries.addAll(createEntries(delegate()));
      }
      return changed;
    }

    @Override public void clear() {
      linkedEntries.removeAll(createEntries(delegate()));
      delegate.clear();
    }

    @Override public Iterator<V> iterator() {
      final Iterator<V> delegateIterator = delegate.iterator();
      return new Iterator<V>() {
        V value;

        public boolean hasNext() {
          return delegateIterator.hasNext();
        }
        public V next() {
          value = delegateIterator.next();
          return value;
        }
        public void remove() {
          delegateIterator.remove();
          linkedEntries.remove(createEntry(value));
        }
      };
    }

    @Override public boolean remove(@Nullable Object value) {
      boolean changed = delegate.remove(value);
      if (changed) {
        /*
         * linkedEntries.remove() will return false when this method is called
         * by entries().iterator().remove()
         */
        linkedEntries.remove(createEntry(value));
      }
      return changed;
    }

    @Override public boolean removeAll(Collection<?> values) {
      boolean changed = delegate.removeAll(values);
      if (changed) {
        linkedEntries.removeAll(createEntries(values));
      }
      return changed;
    }

    @Override public boolean retainAll(Collection<?> values) {
      /*
       * Calling linkedEntries.retainAll() would incorrectly remove values
       * with other keys.
       */
      boolean changed = false;
      Iterator<V> iterator = delegate.iterator();
      while (iterator.hasNext()) {
        V value = iterator.next();
        if (!values.contains(value)) {
          iterator.remove();
          linkedEntries.remove(Maps.immutableEntry(key, value));
          changed = true;
        }
      }
      return changed;
    }
  }

  /**
   * {@inheritDoc}
   *
   *
Generates an iterator across map entries that follows the ordering in
   * which the key-value pairs were added to the multimap.
   *
   * @return a key-value iterator with the correct ordering
   */
  @Override Iterator<Map.Entry<K, V>> createEntryIterator() {
    final Iterator<Map.Entry<K, V>> delegateIterator = linkedEntries.iterator();

    return new Iterator<Map.Entry<K, V>>() {
      Map.Entry<K, V> entry;

      public boolean hasNext() {
        return delegateIterator.hasNext();
      }

      public Map.Entry<K, V> next() {
        entry = delegateIterator.next();
        return entry;
      }

      public void remove() {
        // Remove from iterator first to keep iterator valid.
        delegateIterator.remove();
        LinkedHashMultimap.this.remove(entry.getKey(), entry.getValue());
      }
    };
  }

  /**
   * {@inheritDoc}
   *
   *
If {@code values} is not empty and the multimap already contains a
   * mapping for {@code key}, the {@code keySet()} ordering is unchanged.
   * However, the provided values always come last in the {@link #entries()} and
   * {@link #values()} iteration orderings.
   */
  @Override public Set<V> replaceValues(
      @Nullable K key, Iterable<? extends V> values) {
    return super.replaceValues(key, values);
  }

  /**
   * Returns a set of all key-value pairs. Changes to the returned set will
   * update the underlying multimap, and vice versa. The entries set does not
   * support the {@code add} or {@code addAll} operations.
   *
   *
The iterator generated by the returned set traverses the entries in the
   * order they were added to the multimap.
   *
   *
Each entry is an immutable snapshot of a key-value mapping in the
   * multimap, taken at the time the entry is returned by a method call to the
   * collection or its iterator.
   */
  @Override public Set<Map.Entry<K, V>> entries() {
    return super.entries();
  }

  /**
   * Returns a collection of all values in the multimap. Changes to the returned
   * collection will update the underlying multimap, and vice versa.
   *
   *
The iterator generated by the returned collection traverses the values
   * in the order they were added to the multimap.
   */
  @Override public Collection<V> values() {
    return super.values();
  }

  // Unfortunately, the entries() ordering does not determine the key ordering;
  // see the example in the LinkedListMultimap class Javadoc.

  /**
   * @serialData the number of distinct keys, and then for each distinct key:
   *     the first key, the number of values for that key, and the key's values,
   *     followed by successive keys and values from the entries() ordering
   */
  private void writeObject(ObjectOutputStream stream) throws IOException {
    stream.defaultWriteObject();
    stream.writeInt(expectedValuesPerKey);
    Serialization.writeMultimap(this, stream);
    for (Map.Entry<K, V> entry : linkedEntries) {
      stream.writeObject(entry.getKey());
      stream.writeObject(entry.getValue());
    }
  }

  private void readObject(ObjectInputStream stream)
      throws IOException, ClassNotFoundException {
    stream.defaultReadObject();
    expectedValuesPerKey = stream.readInt();
    int distinctKeys = Serialization.readCount(stream);
    setMap(new LinkedHashMap<K, Collection<V>>(Maps.capacity(distinctKeys)));
    linkedEntries = new LinkedHashSet<Map.Entry<K, V>>(
        distinctKeys * expectedValuesPerKey);
    Serialization.populateMultimap(this, stream, distinctKeys);
    linkedEntries.clear(); // will clear and repopulate entries
    for (int i = 0; i < size(); i++) {
      @SuppressWarnings("unchecked") // reading data stored by writeObject
      K key = (K) stream.readObject();
      @SuppressWarnings("unchecked") // reading data stored by writeObject
      V value = (V) stream.readObject();
      linkedEntries.add(Maps.immutableEntry(key, value));
    }
  }

  private static final long serialVersionUID = 0;
}


text:
/* eslint-disable max-len */

import { sm } from '../jssm';

describe('reject and accept correctly', () => {

  const machine = sm` a ~> b -> c; `;

  test('starts in a',                    () => expect( machine.state()               ).toBe('a')   );
  test('rejects transition to b',        () => expect( machine.transition('b')       ).toBe(false) );
  test('still in a',                     () => expect( machine.state()               ).toBe('a')   );
  test('rejects transition to c',        () => expect( machine.transition('c')       ).toBe(false) );
  test('still in a 2',                   () => expect( machine.state()               ).toBe('a')   );
  test('rejects forced transition to c', () => expect( machine.force_transition('c') ).toBe(false) );
  test('still in a 3',                   () => expect( machine.state()               ).toBe('a')   );
  test('accepts forced transition to b', () => expect( machine.force_transition('b') ).toBe(true)  );
  test('now in b',                       () => expect( machine.state()               ).toBe('b')   );
  test('accepts transition to c',        () => expect( machine.transition('c')       ).toBe(true)  );
  test('now in c',                       () => expect( machine.state()               ).toBe('c')   );

});

describe('uses_forced_transitions', () => {

  test( 'standard transition', () => expect(sm`a -> b;`.uses_forced_transitions).toBe(false) );
  test( 'main transition',     () => expect(sm`a => b;`.uses_forced_transitions).toBe(false) );
  test( 'forced transition',   () => expect(sm`a ~> b;`.uses_forced_transitions).toBe(true)  );

  test( 'standard and main transition',   () => expect(sm`a -> b; c => d;`.uses_forced_transitions).toBe(false) );
  test( 'forced and main transition',     () => expect(sm`a ~> b; c => d;`.uses_forced_transitions).toBe(true)  );
  test( 'main and forced transition',     () => expect(sm`a => b; c ~> d;`.uses_forced_transitions).toBe(true)  );
  test( 'standard and forced transition', () => expect(sm`a -> b; c ~> d;`.uses_forced_transitions).toBe(true)  );

  test( 'standard and main transition, chain',   () => expect(sm`a -> c => d;`.uses_forced_transitions).toBe(false) );
  test( 'forced and main transition, chain',     () => expect(sm`a ~> c => d;`.uses_forced_transitions).toBe(true)  );
  test( 'main and forced transition, chain',     () => expect(sm`a => c ~> d;`.uses_forced_transitions).toBe(true)  );
  test( 'standard and forced transition, chain', () => expect(sm`a -> c ~> d;`.uses_forced_transitions).toBe(true)  );

});