text:
import { NgModule } from '@angular/core';
import { ArtemisSharedModule } from 'app/shared/shared.module';
import { ArtemisCodeEditorManagementRoutingModule } from 'app/exercises/programming/manage/code-editor/code-editor-management-routing.module';
import { ArtemisCodeEditorModule } from 'app/exercises/programming/shared/code-editor/code-editor.module';
import { CodeEditorInstructorAndEditorContainerComponent } from 'app/exercises/programming/manage/code-editor/code-editor-instructor-and-editor-container.component';
import { CodeEditorInstructorAndEditorOrionContainerComponent } from 'app/orion/management/code-editor-instructor-and-editor-orion-container.component';
import { ArtemisProgrammingExerciseStatusModule } from 'app/exercises/programming/manage/status/programming-exercise-status.module';
import { ArtemisResultModule } from 'app/exercises/shared/result/result.module';
import { ArtemisProgrammingExerciseActionsModule } from 'app/exercises/programming/shared/actions/programming-exercise-actions.module';
import { OrionModule } from 'app/shared/orion/orion.module';
import { ArtemisProgrammingExerciseInstructionsEditorModule } from 'app/exercises/programming/manage/instructions-editor/programming-exercise-instructions-editor.module';
import { ArtemisExerciseHintParticipationModule } from 'app/exercises/shared/exercise-hint/participate/exercise-hint-participation.module';
import { ArtemisHeaderExercisePageWithDetailsModule } from 'app/exercises/shared/exercise-headers/exercise-headers.module';
import { SubmissionResultStatusModule } from 'app/overview/submission-result-status.module';

@NgModule({
    imports: [
        ArtemisSharedModule,
        ArtemisCodeEditorManagementRoutingModule,
        ArtemisCodeEditorModule,
        ArtemisProgrammingExerciseStatusModule,
        ArtemisResultModule,
        ArtemisProgrammingExerciseActionsModule,
        ArtemisExerciseHintParticipationModule,
        OrionModule,
        ArtemisProgrammingExerciseInstructionsEditorModule,
        ArtemisHeaderExercisePageWithDetailsModule,
        SubmissionResultStatusModule,
    ],
    declarations: [CodeEditorInstructorAndEditorContainerComponent, CodeEditorInstructorAndEditorOrionContainerComponent],
})
export class ArtemisCodeEditorManagementModule {}


text:
/**
 * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
 * @version v7.2.0
 * @link http://www.ag-grid.com/
 * @license MIT
 */
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var utils_1 = require("../utils");
var svgFactory_1 = require("../svgFactory");
var columnController_1 = require("../columnController/columnController");
var filterManager_1 = require("../filter/filterManager");
var gridOptionsWrapper_1 = require("../gridOptionsWrapper");
var column_1 = require("../entities/column");
var horizontalDragService_1 = require("./horizontalDragService");
var context_1 = require("../context/context");
var cssClassApplier_1 = require("./cssClassApplier");
var dragAndDropService_1 = require("../dragAndDrop/dragAndDropService");
var setLeftFeature_1 = require("../rendering/features/setLeftFeature");
var touchListener_1 = require("../widgets/touchListener");
var component_1 = require("../widgets/component");
var svgFactory = svgFactory_1.SvgFactory.getInstance();
var RenderedHeaderGroupCell = (function (_super) {
    __extends(RenderedHeaderGroupCell, _super);
    function RenderedHeaderGroupCell(columnGroup, eRoot, dragSourceDropTarget, pinned) {
        _super.call(this, "<div/>");
        this.columnGroup = columnGroup;
        this.eRoot = eRoot;
        this.dragSourceDropTarget = dragSourceDropTarget;
        this.pinned = pinned;
    }
    RenderedHeaderGroupCell.prototype.init = function () {
        cssClassApplier_1.CssClassApplier.addHeaderClassesFromColDef(this.columnGroup.getColGroupDef(), this.getGui(), this.gridOptionsWrapper, null, this.columnGroup);
        // this.displayName = this.columnGroup.getHeaderName();
        this.displayName = this.columnController.getDisplayNameForColumnGroup(this.columnGroup, 'header');
        this.setupResize();
        this.addClasses();
        this.setupLabel();
        this.setupMove();
        this.setWidth();
        var setLeftFeature = new setLeftFeature_1.SetLeftFeature(this.columnGroup, this.getGui());
        this.addDestroyFunc(function () { return setLeftFeature.destroy(); });
    };
    RenderedHeaderGroupCell.prototype.setupLabel = function () {
        // no renderer, default text render
        if (this.displayName && this.displayName !== '') {
            var eGroupCellLabel = document.createElement("div");
            eGroupCellLabel.className = 'ag-header-group-cell-label';
            this.getGui().appendChild(eGroupCellLabel);
            if (utils_1.Utils.isBrowserSafari()) {
                eGroupCellLabel.style.display = 'table-cell';
            }
            var eInnerText = document.createElement("span");
            eInnerText.className = 'ag-header-group-text';
            eInnerText.innerHTML = this.displayName;
            eGroupCellLabel.appendChild(eInnerText);
            if (this.columnGroup.isExpandable()) {
                this.addGroupExpandIcon(eGroupCellLabel);
            }
        }
    };
    RenderedHeaderGroupCell.prototype.addClasses = function () {
        utils_1.Utils.addCssClass(this.getGui(), 'ag-header-group-cell');
        // having different classes below allows the style to not have a bottom border
        // on the group header, if no group is specified
        // columnGroup.getColGroupDef
        if (this.columnGroup.isPadding()) {
            utils_1.Utils.addCssClass(this.getGui(), 'ag-header-group-cell-no-group');
        }
        else {
            utils_1.Utils.addCssClass(this.getGui(), 'ag-header-group-cell-with-group');
        }
    };
    RenderedHeaderGroupCell.prototype.setupResize = function () {
        var _this = this;
        if (!this.gridOptionsWrapper.isEnableColResize()) {
            return;
        }
        this.eHeaderCellResize = document.createElement("div");
        this.eHeaderCellResize.className = "ag-header-cell-resize";
        this.getGui().appendChild(this.eHeaderCellResize);
        this.dragService.addDragHandling({
            eDraggableElement: this.eHeaderCellResize,
            eBody: this.eRoot,
            cursor: 'col-resize',
            startAfterPixels: 0,
            onDragStart: this.onDragStart.bind(this),
            onDragging: this.onDragging.bind(this)
        });
        if (!this.gridOptionsWrapper.isSuppressAutoSize()) {
            this.eHeaderCellResize.addEventListener('dblclick', function (event) {
                // get list of all the column keys we are responsible for
                var keys = [];
                _this.columnGroup.getDisplayedLeafColumns().forEach(function (column) {
                    // not all cols in the group may be participating with auto-resize
                    if (!column.getColDef().suppressAutoSize) {
                        keys.push(column.getColId());
                    }
                });
                if (keys.length > 0) {
                    _this.columnController.autoSizeColumns(keys);
                }
            });
        }
    };
    RenderedHeaderGroupCell.prototype.isSuppressMoving = function () {
        // if any child is fixed, then don't allow moving
        var childSuppressesMoving = false;
        this.columnGroup.getLeafColumns().forEach(function (column) {
            if (column.getColDef().suppressMovable) {
                childSuppressesMoving = true;
            }
        });
        var result = childSuppressesMoving
            || this.gridOptionsWrapper.isSuppressMovableColumns()
            || this.gridOptionsWrapper.isForPrint();
        return result;
    };
    RenderedHeaderGroupCell.prototype.setupMove = function () {
        var _this = this;
        var eLabel = this.queryForHtmlElement('.ag-header-group-cell-label');
        if (!eLabel) {
            return;
        }
        if (this.isSuppressMoving()) {
            return;
        }
        if (eLabel) {
            var dragSource = {
                type: dragAndDropService_1.DragSourceType.HeaderCell,
                eElement: eLabel,
                dragItemName: this.displayName,
                // we add in the original group leaf columns, so we move both visible and non-visible items
                dragItem: this.getAllColumnsInThisGroup(),
                dragSourceDropTarget: this.dragSourceDropTarget
            };
            this.dragAndDropService.addDragSource(dragSource, true);
            this.addDestroyFunc(function () { return _this.dragAndDropService.removeDragSource(dragSource); });
        }
    };
    // when moving the columns, we want to move all the columns in this group in one go, and in the order they
    // are currently in the screen.
    RenderedHeaderGroupCell.prototype.getAllColumnsInThisGroup = function () {
        var allColumnsOriginalOrder = this.columnGroup.getOriginalColumnGroup().getLeafColumns();
        var allColumnsCurrentOrder = [];
        this.columnController.getAllDisplayedColumns().forEach(function (column) {
            if (allColumnsOriginalOrder.indexOf(column) >= 0) {
                allColumnsCurrentOrder.push(column);
                utils_1.Utils.removeFromArray(allColumnsOriginalOrder, column);
            }
        });
        // we are left with non-visible columns, stick these in at the end
        allColumnsOriginalOrder.forEach(function (column) { return allColumnsCurrentOrder.push(column); });
        return allColumnsCurrentOrder;
    };
    RenderedHeaderGroupCell.prototype.setWidth = function () {
        var _this = this;
        this.columnGroup.getLeafColumns().forEach(function (column) {
            return _this.addDestroyableEventListener(column, column_1.Column.EVENT_WIDTH_CHANGED, _this.onWidthChanged.bind(_this));
        });
        this.onWidthChanged();
    };
    RenderedHeaderGroupCell.prototype.onWidthChanged = function () {
        this.getGui().style.width = this.columnGroup.getActualWidth() + 'px';
    };
    RenderedHeaderGroupCell.prototype.addGroupExpandIcon = function (eGroupCellLabel) {
        var _this = this;
        var eGroupIcon;
        if (this.columnGroup.isExpanded()) {
            eGroupIcon = utils_1.Utils.createIcon('columnGroupOpened', this.gridOptionsWrapper, null, svgFactory.createGroupContractedIcon);
            utils_1.Utils.addCssClass(eGroupIcon, 'ag-header-expand-icon-expanded');
        }
        else {
            eGroupIcon = utils_1.Utils.createIcon('columnGroupClosed', this.gridOptionsWrapper, null, svgFactory.createGroupExpandedIcon);
            utils_1.Utils.addCssClass(eGroupIcon, 'ag-header-expand-icon-collapsed');
        }
        utils_1.Utils.addCssClass(eGroupIcon, 'ag-header-expand-icon');
        eGroupCellLabel.appendChild(eGroupIcon);
        var expandAction = function () {
            var newExpandedValue = !_this.columnGroup.isExpanded();
            _this.columnController.setColumnGroupOpened(_this.columnGroup, newExpandedValue);
        };
        this.addDestroyableEventListener(eGroupIcon, 'click', expandAction);
        var touchListener = new touchListener_1.TouchListener(eGroupIcon);
        this.addDestroyableEventListener(touchListener, touchListener_1.TouchListener.EVENT_TAP, expandAction);
        this.addDestroyFunc(function () { return touchListener.destroy(); });
    };
    RenderedHeaderGroupCell.prototype.onDragStart = function () {
        var _this = this;
        this.groupWidthStart = this.columnGroup.getActualWidth();
        this.childrenWidthStarts = [];
        this.columnGroup.getDisplayedLeafColumns().forEach(function (column) {
            _this.childrenWidthStarts.push(column.getActualWidth());
        });
    };
    // optionally inverts the drag, depending on pinned and RTL
    // note - this method is duplicated in RenderedHeaderCell - should refactor out?
    RenderedHeaderGroupCell.prototype.normaliseDragChange = function (dragChange) {
        var result = dragChange;
        if (this.gridOptionsWrapper.isEnableRtl()) {
            // for RTL, dragging left makes the col bigger, except when pinning left
            if (this.pinned !== column_1.Column.PINNED_LEFT) {
                result *= -1;
            }
        }
        else {
            // for LTR (ie normal), dragging left makes the col smaller, except when pinning right
            if (this.pinned === column_1.Column.PINNED_RIGHT) {
                result *= -1;
            }
        }
        return result;
    };
    RenderedHeaderGroupCell.prototype.onDragging = function (dragChange, finished) {
        var _this = this;
        var dragChangeNormalised = this.normaliseDragChange(dragChange);
        var newWidth = this.groupWidthStart + dragChangeNormalised;
        var minWidth = this.columnGroup.getMinWidth();
        if (newWidth < minWidth) {
            newWidth = minWidth;
        }
        // distribute the new width to the child headers
        var changeRatio = newWidth / this.groupWidthStart;
        // keep track of pixels used, and last column gets the remaining,
        // to cater for rounding errors, and min width adjustments
        var pixelsToDistribute = newWidth;
        var displayedColumns = this.columnGroup.getDisplayedLeafColumns();
        displayedColumns.forEach(function (column, index) {
            var notLastCol = index !== (displayedColumns.length - 1);
            var newChildSize;
            if (notLastCol) {
                // if not the last col, calculate the column width as normal
                var startChildSize = _this.childrenWidthStarts[index];
                newChildSize = startChildSize * changeRatio;
                if (newChildSize < column.getMinWidth()) {
                    newChildSize = column.getMinWidth();
                }
                pixelsToDistribute -= newChildSize;
            }
            else {
                // if last col, give it the remaining pixels
                newChildSize = pixelsToDistribute;
            }
            _this.columnController.setColumnWidth(column, newChildSize, finished);
        });
    };
    __decorate([
        context_1.Autowired('filterManager'),
        __metadata('design:type', filterManager_1.FilterManager)
    ], RenderedHeaderGroupCell.prototype, "filterManager", void 0);
    __decorate([
        context_1.Autowired('gridOptionsWrapper'),
        __metadata('design:type', gridOptionsWrapper_1.GridOptionsWrapper)
    ], RenderedHeaderGroupCell.prototype, "gridOptionsWrapper", void 0);
    __decorate([
        context_1.Autowired('horizontalDragService'),
        __metadata('design:type', horizontalDragService_1.HorizontalDragService)
    ], RenderedHeaderGroupCell.prototype, "dragService", void 0);
    __decorate([
        context_1.Autowired('columnController'),
        __metadata('design:type', columnController_1.ColumnController)
    ], RenderedHeaderGroupCell.prototype, "columnController", void 0);
    __decorate([
        context_1.Autowired('dragAndDropService'),
        __metadata('design:type', dragAndDropService_1.DragAndDropService)
    ], RenderedHeaderGroupCell.prototype, "dragAndDropService", void 0);
    __decorate([
        context_1.PostConstruct,
        __metadata('design:type', Function),
        __metadata('design:paramtypes', []),
        __metadata('design:returntype', void 0)
    ], RenderedHeaderGroupCell.prototype, "init", null);
    return RenderedHeaderGroupCell;
}(component_1.Component));
exports.RenderedHeaderGroupCell = RenderedHeaderGroupCell;

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Runtime.Serialization;

namespace YamlDotNet.Core
{
    /// <summary>
    /// Exception that is thrown when an infinite recursion is detected.
    /// </summary>
    [Serializable]
    public class MaximumRecursionLevelReachedException : YamlException
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="MaximumRecursionLevelReachedException"/> class.
        /// </summary>
        public MaximumRecursionLevelReachedException()
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="MaximumRecursionLevelReachedException"/> class.
        /// </summary>
        /// <param name="message">The message.</param>
        public MaximumRecursionLevelReachedException(string message)
            : base(message)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="MaximumRecursionLevelReachedException"/> class.
        /// </summary>
        public MaximumRecursionLevelReachedException(Mark start, Mark end, string message)
            : base(start, end, message)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="MaximumRecursionLevelReachedException"/> class.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="inner">The inner.</param>
        public MaximumRecursionLevelReachedException(string message, Exception inner)
            : base(message, inner)
        {
        }

#if !(PORTABLE || UNITY)
        /// <summary>
        /// Initializes a new instance of the <see cref="MaximumRecursionLevelReachedException"/> class.
        /// </summary>
        /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param>
        /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"/> that contains contextual information about the source or destination.</param>
        /// <exception cref="T:System.ArgumentNullException">The <paramref name="info"/> parameter is null. </exception>
        /// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult"/> is zero (0). </exception>
        protected MaximumRecursionLevelReachedException(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
        }
#endif
    }
}


text:
@interface ZipResult : NSObject {
}

@property(copy) NSString* source;
@property(copy) NSString* target;
@property(copy) id context;
@property(assign) BOOL zip;
@property(assign) BOOL ok;

+ (id) newResult:(BOOL)aZip ok:(BOOL)aOk source:(NSString*)aSource target:(NSString*)aTarget context:(NSString*)context;

- (NSDictionary*) toDictionary;

@end

@interface ZipProgress : NSObject {
}

@property(copy) NSString* source;
@property(copy) NSString* filename;
@property(copy) id context;
@property(assign) BOOL zip;
@property(assign) uint64_t entryNumber;
@property(assign) uint64_t entryTotal;

+ (id) newProgress:(BOOL)aEncrypt source:(NSString*)aSource filename:(NSString*)aFilename context:(id)aContext
		 entryNumber:(uint64_t)entryNumber entryTotal:(uint64_t)entryTotal;

- (NSDictionary*) toDictionary;

@end

@protocol ZipOperationDelegate<NSObject>

- (void) zipResult:(ZipResult*)result;
- (void) zipProgress:(ZipProgress*)progress;

@end

@interface ZipOperation : NSOperation <ZipArchiveDelegate> {
}

@property(copy) NSString* source;
@property(copy) NSString* target;
@property(copy) id context;
@property(assign) BOOL zip;
@property(assign) NSObject<ZipOperationDelegate>* delegate;

- (id)initAsDeflate:(BOOL)zip withSource:(NSString*)source target:(NSString*)target andContext:(id)context;

@end


text:
import { print } from "graphql-tag/printer";
import { withLikes, LIKES_QUERY } from "../userLikes";

it("should contain user likes query", () => {
  expect(print(LIKES_QUERY)).toMatchSnapshot();
});

// TODO: integration test


text:
<?php

namespace Symfony\Bundle\FrameworkBundle\Command;

use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Component\Config\Definition\Dumper\XmlReferenceDumper;
use Symfony\Component\Config\Definition\Dumper\YamlReferenceDumper;
use Symfony\Component\Console\Exception\InvalidArgumentException;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\DependencyInjection\Extension\ConfigurationExtensionInterface;
use Symfony\Component\DependencyInjection\Extension\ExtensionInterface;

/**
 * A console command for dumping available configuration reference.
 *
 * @author Kevin Bond <kevinbond@gmail.com>
 * @author Wouter J <waldio.webdesign@gmail.com>
 * @author Grégoire Pineau <lyrixx@lyrixx.info>
 *
 * @final
 */
class ConfigDumpReferenceCommand extends AbstractConfigCommand
{
    protected static $defaultName = 'config:dump-reference';

    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            ->setDefinition([
                new InputArgument('name', InputArgument::OPTIONAL, 'The Bundle name or the extension alias'),
                new InputArgument('path', InputArgument::OPTIONAL, 'The configuration option path'),
                new InputOption('format', null, InputOption::VALUE_REQUIRED, 'The output format (yaml or xml)', 'yaml'),
            ])
            ->setDescription('Dumps the default configuration for an extension')
            ->setHelp(<<<'EOF'
The <info>%command.name%</info> command dumps the default configuration for an
extension/bundle.

Either the extension alias or bundle name can be used:

  <info>php %command.full_name% framework</info>
  <info>php %command.full_name% FrameworkBundle</info>

With the <info>--format</info> option specifies the format of the configuration,
this is either <comment>yaml</comment> or <comment>xml</comment>.
When the option is not provided, <comment>yaml</comment> is used.

  <info>php %command.full_name% FrameworkBundle --format=xml</info>

For dumping a specific option, add its path as second argument (only available for the yaml format):

  <info>php %command.full_name% framework profiler.matcher</info>

EOF
            )
        ;
    }

    /**
     * {@inheritdoc}
     *
     * @throws \LogicException
     */
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io = new SymfonyStyle($input, $output);
        $errorIo = $io->getErrorStyle();

        if (null === $name = $input->getArgument('name')) {
            $this->listBundles($errorIo);

            $kernel = $this->getApplication()->getKernel();
            if ($kernel instanceof ExtensionInterface
                && ($kernel instanceof ConfigurationInterface || $kernel instanceof ConfigurationExtensionInterface)
                && $kernel->getAlias()
            ) {
                $errorIo->table(['Kernel Extension'], [[$kernel->getAlias()]]);
            }

            $errorIo->comment([
                'Provide the name of a bundle as the first argument of this command to dump its default configuration. (e.g. <comment>config:dump-reference FrameworkBundle</comment>)',
                'For dumping a specific option, add its path as the second argument of this command. (e.g. <comment>config:dump-reference FrameworkBundle profiler.matcher</comment> to dump the <comment>framework.profiler.matcher</comment> configuration)',
            ]);

            return 0;
        }

        $extension = $this->findExtension($name);

        if ($extension instanceof ConfigurationInterface) {
            $configuration = $extension;
        } else {
            $configuration = $extension->getConfiguration([], $this->getContainerBuilder());
        }

        $this->validateConfiguration($extension, $configuration);

        $format = $input->getOption('format');
        $path = $input->getArgument('path');

        if (null !== $path && 'yaml' !== $format) {
            $errorIo->error('The "path" option is only available for the "yaml" format.');

            return 1;
        }

        if ($name === $extension->getAlias()) {
            $message = sprintf('Default configuration for extension with alias: "%s"', $name);
        } else {
            $message = sprintf('Default configuration for "%s"', $name);
        }

        if (null !== $path) {
            $message .= sprintf(' at path "%s"', $path);
        }

        switch ($format) {
            case 'yaml':
                $io->writeln(sprintf('# %s', $message));
                $dumper = new YamlReferenceDumper();
                break;
            case 'xml':
                $io->writeln(sprintf('<!-- %s -->', $message));
                $dumper = new XmlReferenceDumper();
                break;
            default:
                $io->writeln($message);
                throw new InvalidArgumentException('Only the yaml and xml formats are supported.');
        }

        $io->writeln(null === $path ? $dumper->dump($configuration, $extension->getNamespace()) : $dumper->dumpAtPath($configuration, $path));

        return 0;
    }
}


text:
namespace wfl
{

namespace fs = boost::filesystem;

template <GLenum type>
class Shader
{
    public:
        Shader(const std::string s)
        {
            std::cout << "[Waffle] Loading shader from string\n";

            const GLchar* src = s.c_str();
            shader_ = glCreateShader(type);
            glShaderSource(shader_, 1, &src, NULL);
            glCompileShader(shader_);

            GLint success;
            GLchar log[512];
            glGetShaderiv(shader_, GL_COMPILE_STATUS, &success);
            if (!success)
            {
                glGetShaderInfoLog(shader_, 512, NULL, log);
                std::cout << log << std::endl;
                throw std::runtime_error("[Waffle] Shader compilation failed \n");
            }
        }

        Shader(const fs::path& p)
        {
            fs::path full_p = fs::complete(p);

            std::cout << "[Waffle] Loading shader from: " << full_p << "\n";

            std::string source;
            std::ifstream file;

            try
            {
                file.open(full_p.string());
                std::stringstream stream;
                stream << file.rdbuf();
                file.close();

                source = stream.str();
            }
            catch (std::ifstream::failure e)
            {
                std::cout << "[Waffle] Error reading file" << full_p << " : " << e.what() << "\n";
            }

            const GLchar* src = source.c_str();
            shader_ = glCreateShader(type);
            glShaderSource(shader_, 1, &src, NULL);
            glCompileShader(shader_);

            GLint success;
            GLchar log[512];
            glGetShaderiv(shader_, GL_COMPILE_STATUS, &success);
            if (!success)
            {
                glGetShaderInfoLog(shader_, 512, NULL, log);
                std::cout << log << std::endl;
                throw std::runtime_error("[Waffle] Shader compilation failed \n");
            }
        }

        ~Shader()
        {
            glDeleteShader(shader_);
        }

        inline GLuint get_shader()
        {
            return shader_;
        }

    private:
        GLuint shader_;
};

    using VertShader = Shader<GL_VERTEX_SHADER>;
    using GeomShader = Shader<GL_GEOMETRY_SHADER>;
    using FragShader = Shader<GL_FRAGMENT_SHADER>;

}


text:
package org.apache.hadoop.yarn.logaggregation.filecontroller.tfile;

import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.hadoop.yarn.api.records.ApplicationAttemptId;
import org.apache.hadoop.yarn.logaggregation.ContainerLogFileInfo;
import org.apache.hadoop.yarn.logaggregation.ExtendedLogMetaRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.commons.math3.util.Pair;
import org.apache.hadoop.classification.InterfaceAudience.Private;
import org.apache.hadoop.classification.InterfaceStability.Unstable;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.HarFs;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.RemoteIterator;
import org.apache.hadoop.hdfs.protocol.DSQuotaExceededException;
import org.apache.hadoop.yarn.api.records.ApplicationAccessType;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.logaggregation.AggregatedLogFormat.LogKey;
import org.apache.hadoop.yarn.logaggregation.AggregatedLogFormat.LogReader;
import org.apache.hadoop.yarn.logaggregation.AggregatedLogFormat.LogValue;
import org.apache.hadoop.yarn.logaggregation.AggregatedLogFormat.LogWriter;
import org.apache.hadoop.yarn.logaggregation.filecontroller.LogAggregationDFSException;
import org.apache.hadoop.yarn.logaggregation.filecontroller.LogAggregationFileController;
import org.apache.hadoop.yarn.logaggregation.filecontroller.LogAggregationFileControllerContext;
import org.apache.hadoop.yarn.logaggregation.ContainerLogAggregationType;
import org.apache.hadoop.yarn.logaggregation.ContainerLogMeta;
import org.apache.hadoop.yarn.logaggregation.ContainerLogsRequest;
import org.apache.hadoop.yarn.logaggregation.LogAggregationUtils;
import org.apache.hadoop.yarn.logaggregation.LogToolUtils;
import org.apache.hadoop.yarn.util.Times;
import org.apache.hadoop.yarn.webapp.View.ViewContext;
import org.apache.hadoop.yarn.webapp.view.HtmlBlock.Block;

/**
 * The TFile log aggregation file Controller implementation.
 */
@Private
@Unstable
public class LogAggregationTFileController
    extends LogAggregationFileController {

  private static final Logger LOG = LoggerFactory.getLogger(
      LogAggregationTFileController.class);

  private LogWriter writer;
  private TFileLogReader tfReader = null;

  public LogAggregationTFileController(){}

  @Override
  public void initInternal(Configuration conf) {
    // do nothing
  }

  @Override
  public void initializeWriter(LogAggregationFileControllerContext context)
      throws IOException {
    this.writer = new LogWriter();
    writer.initialize(this.conf, context.getRemoteNodeTmpLogFileForApp(),
        context.getUserUgi());
    // Write ACLs once when the writer is created.
    writer.writeApplicationACLs(context.getAppAcls());
    writer.writeApplicationOwner(context.getUserUgi().getShortUserName());
  }

  @Override
  public void closeWriter() throws LogAggregationDFSException {
    if (this.writer != null) {
      try {
        this.writer.close();
      } catch (DSQuotaExceededException e) {
        throw new LogAggregationDFSException(e);
      } finally {
        this.writer = null;
      }
    }
  }

  @Override
  public void write(LogKey logKey, LogValue logValue) throws IOException {
    this.writer.append(logKey, logValue);
  }

  @Override
  public void postWrite(final LogAggregationFileControllerContext record)
      throws Exception {
    // Before upload logs, make sure the number of existing logs
    // is smaller than the configured NM log aggregation retention size.
    if (record.isUploadedLogsInThisCycle() &&
        record.isLogAggregationInRolling()) {
      cleanOldLogs(record.getRemoteNodeLogFileForApp(), record.getNodeId(),
          record.getUserUgi());
      record.increcleanupOldLogTimes();
    }

    // close the writer before the file is renamed or deleted
    closeWriter();

    final Path renamedPath = record.getRollingMonitorInterval() <= 0
        ? record.getRemoteNodeLogFileForApp() : new Path(
            record.getRemoteNodeLogFileForApp().getParent(),
            record.getRemoteNodeLogFileForApp().getName() + "_"
            + record.getLogUploadTimeStamp());
    final boolean rename = record.isUploadedLogsInThisCycle();
    try {
      record.getUserUgi().doAs(new PrivilegedExceptionAction<Object>() {
        @Override
        public Object run() throws Exception {
          FileSystem remoteFS = record.getRemoteNodeLogFileForApp()
              .getFileSystem(conf);
          if (rename) {
            remoteFS.rename(record.getRemoteNodeTmpLogFileForApp(),
                renamedPath);
          } else {
            remoteFS.delete(record.getRemoteNodeTmpLogFileForApp(), false);
          }
          return null;
        }
      });
    } catch (Exception e) {
      LOG.error(
          "Failed to move temporary log file to final location: ["
          + record.getRemoteNodeTmpLogFileForApp() + "] to ["
          + renamedPath + "]", e);
      throw new Exception("Log uploaded failed for Application: "
          + record.getAppId() + " in NodeManager: "
          + LogAggregationUtils.getNodeString(record.getNodeId()) + " at "
          + Times.format(record.getLogUploadTimeStamp()) + "\n");
    }
  }

  @Override
  public boolean readAggregatedLogs(ContainerLogsRequest logRequest,
      OutputStream os) throws IOException {
    boolean findLogs = false;
    boolean createPrintStream = (os == null);
    ApplicationId appId = logRequest.getAppId();
    String nodeId = logRequest.getNodeId();
    List<String> logTypes = new ArrayList<>();
    if (logRequest.getLogTypes() != null && !logRequest
        .getLogTypes().isEmpty()) {
      logTypes.addAll(logRequest.getLogTypes());
    }
    String containerIdStr = logRequest.getContainerId();
    boolean getAllContainers = (containerIdStr == null
        || containerIdStr.isEmpty());
    long size = logRequest.getBytes();
    RemoteIterator<FileStatus> nodeFiles = LogAggregationUtils
        .getRemoteNodeFileDir(conf, appId, logRequest.getAppOwner(),
        remoteRootLogDir, remoteRootLogDirSuffix);
    byte[] buf = new byte[65535];
    while (nodeFiles != null && nodeFiles.hasNext()) {
      final FileStatus thisNodeFile = nodeFiles.next();
      String nodeName = thisNodeFile.getPath().getName();
      if (nodeName.equals(appId + ".har")) {
        Path p = new Path("har:///"
            + thisNodeFile.getPath().toUri().getRawPath());
        nodeFiles = HarFs.get(p.toUri(), conf).listStatusIterator(p);
        continue;
      }
      if ((nodeId == null || nodeName.contains(LogAggregationUtils
          .getNodeString(nodeId))) && !nodeName.endsWith(
              LogAggregationUtils.TMP_FILE_SUFFIX)) {
        try (LogReader reader = new LogReader(conf, thisNodeFile.getPath())) {
          DataInputStream valueStream;
          LogKey key = new LogKey();
          valueStream = reader.next(key);
          while (valueStream != null) {
            if (getAllContainers || (key.toString().equals(containerIdStr))) {
              if (createPrintStream) {
                os = LogToolUtils.createPrintStream(
                    logRequest.getOutputLocalDir(),
                    thisNodeFile.getPath().getName(), key.toString());
              }
              try {
                while (true) {
                  try {
                    String fileType = valueStream.readUTF();
                    String fileLengthStr = valueStream.readUTF();
                    long fileLength = Long.parseLong(fileLengthStr);
                    if (logTypes == null || logTypes.isEmpty() ||
                        logTypes.contains(fileType)) {
                      LogToolUtils.outputContainerLog(key.toString(),
                          nodeName, fileType, fileLength, size,
                          Times.format(thisNodeFile.getModificationTime()),
                          valueStream, os, buf,
                          ContainerLogAggregationType.AGGREGATED);
                      byte[] b = aggregatedLogSuffix(fileType).getBytes(
                          Charset.forName("UTF-8"));
                      os.write(b, 0, b.length);
                      findLogs = true;
                    } else {
                      long totalSkipped = 0;
                      long currSkipped = 0;
                      while (currSkipped != -1 && totalSkipped < fileLength) {
                        currSkipped = valueStream.skip(
                            fileLength - totalSkipped);
                        totalSkipped += currSkipped;
                      }
                    }
                  } catch (EOFException eof) {
                    break;
                  }
                }
              } finally {
                os.flush();
                if (createPrintStream) {
                  closePrintStream(os);
                }
              }
              if (!getAllContainers) {
                break;
              }
            }
            // Next container
            key = new LogKey();
            valueStream = reader.next(key);
          }
        } catch (IOException ex) {
          LOG.error("Skipping empty or corrupt file " +
              thisNodeFile.getPath(), ex);
          continue; // skip empty or corrupt files
        }
      }
    }
    return findLogs;
  }

  @Override
  public Map<String, List<ContainerLogFileInfo>> getLogMetaFilesOfNode(
      ExtendedLogMetaRequest logRequest, FileStatus currentNodeFile,
      ApplicationId appId) throws IOException {
    Map<String, List<ContainerLogFileInfo>> logMetaFiles = new HashMap<>();
    Path nodePath = currentNodeFile.getPath();

    try (LogReader reader = new LogReader(conf, nodePath)) {
      DataInputStream valueStream;
      LogKey key = new LogKey();
      valueStream = reader.next(key);
      while (valueStream != null) {
        if (logRequest.getContainerId() == null ||
            logRequest.getContainerId().equals(key.toString())) {
          logMetaFiles.put(key.toString(), new ArrayList<>());
          fillMetaFiles(currentNodeFile, valueStream,
              logMetaFiles.get(key.toString()));
        }
        // Next container
        key = new LogKey();
        valueStream = reader.next(key);
      }
    }
    return logMetaFiles;
  }

  private void fillMetaFiles(
      FileStatus currentNodeFile, DataInputStream valueStream,
      List<ContainerLogFileInfo> logMetaFiles)
      throws IOException {
    while (true) {
      try {
        Pair<String, String> logMeta =
            LogReader.readContainerMetaDataAndSkipData(
                valueStream);
        ContainerLogFileInfo logMetaFile = new ContainerLogFileInfo();
        logMetaFile.setLastModifiedTime(
            Long.toString(currentNodeFile.getModificationTime()));
        logMetaFile.setFileName(logMeta.getFirst());
        logMetaFile.setFileSize(logMeta.getSecond());
        logMetaFiles.add(logMetaFile);
      } catch (EOFException eof) {
        break;
      }
    }
  }

  @Override
  public List<ContainerLogMeta> readAggregatedLogsMeta(
      ContainerLogsRequest logRequest) throws IOException {
    List<ContainerLogMeta> containersLogMeta = new ArrayList<>();
    String containerIdStr = logRequest.getContainerId();
    String nodeId = logRequest.getNodeId();
    ApplicationId appId = logRequest.getAppId();
    String appOwner = logRequest.getAppOwner();
    ApplicationAttemptId appAttemptId = logRequest.getAppAttemptId();
    boolean getAllContainers = (containerIdStr == null &&
        appAttemptId == null);
    boolean getOnlyOneContainer = containerIdStr != null;
    String nodeIdStr = (nodeId == null) ? null
        : LogAggregationUtils.getNodeString(nodeId);
    RemoteIterator<FileStatus> nodeFiles = LogAggregationUtils
        .getRemoteNodeFileDir(conf, appId, appOwner,
        remoteRootLogDir, remoteRootLogDirSuffix);
    if (nodeFiles == null) {
      throw new IOException("There is no available log file for "
          + "application:" + appId);
    }
    while (nodeFiles.hasNext()) {
      FileStatus thisNodeFile = nodeFiles.next();
      if (thisNodeFile.getPath().getName().equals(appId + ".har")) {
        Path p = new Path("har:///"
            + thisNodeFile.getPath().toUri().getRawPath());
        nodeFiles = HarFs.get(p.toUri(), conf).listStatusIterator(p);
        continue;
      }
      if (nodeIdStr != null) {
        if (!thisNodeFile.getPath().getName().contains(nodeIdStr)) {
          continue;
        }
      }
      if (!thisNodeFile.getPath().getName()
          .endsWith(LogAggregationUtils.TMP_FILE_SUFFIX)) {
        try (LogReader reader = new LogReader(conf,
            thisNodeFile.getPath())) {
          DataInputStream valueStream;
          LogKey key = new LogKey();
          valueStream = reader.next(key);
          while (valueStream != null) {
            if (getAllContainers || (key.toString().equals(containerIdStr)) ||
                belongsToAppAttempt(appAttemptId, key.toString())) {
              ContainerLogMeta containerLogMeta = new ContainerLogMeta(
                  key.toString(), thisNodeFile.getPath().getName());
              while (true) {
                try {
                  Pair<String, String> logMeta =
                      LogReader.readContainerMetaDataAndSkipData(
                          valueStream);
                  containerLogMeta.addLogMeta(
                      logMeta.getFirst(),
                      logMeta.getSecond(),
                      Times.format(thisNodeFile.getModificationTime()));
                } catch (EOFException eof) {
                  break;
                }
              }
              containersLogMeta.add(containerLogMeta);
              if (getOnlyOneContainer) {
                break;
              }
            }
            // Next container
            key = new LogKey();
            valueStream = reader.next(key);
          }
        } catch (IOException ex) {
          LOG.error("Skipping empty or corrupt file " +
              thisNodeFile.getPath(), ex);
          continue; // skip empty or corrupt files
        }
      }
    }
    return containersLogMeta;
  }

  @Override
  public void renderAggregatedLogsBlock(Block html, ViewContext context) {
    TFileAggregatedLogsBlock block = new TFileAggregatedLogsBlock(
        context, conf, remoteRootLogDir, remoteRootLogDirSuffix);
    block.render(html);
  }

  @Override
  public String getApplicationOwner(Path aggregatedLog, ApplicationId appId)
      throws IOException {
    createTFileLogReader(aggregatedLog);
    return this.tfReader.getLogReader().getApplicationOwner();
  }

  @Override
  public Map<ApplicationAccessType, String> getApplicationAcls(
      Path aggregatedLog, ApplicationId appId) throws IOException {
    createTFileLogReader(aggregatedLog);
    return this.tfReader.getLogReader().getApplicationAcls();
  }

  private void createTFileLogReader(Path aggregatedLog) throws IOException {
    if (this.tfReader == null || !this.tfReader.getAggregatedLogPath()
        .equals(aggregatedLog)) {
      LogReader logReader = new LogReader(conf, aggregatedLog);
      this.tfReader = new TFileLogReader(logReader, aggregatedLog);
    }
  }

  private static class TFileLogReader {
    private LogReader logReader;
    private Path aggregatedLogPath;

    TFileLogReader(LogReader logReader, Path aggregatedLogPath) {
      this.setLogReader(logReader);
      this.setAggregatedLogPath(aggregatedLogPath);
    }
    public LogReader getLogReader() {
      return logReader;
    }
    public void setLogReader(LogReader logReader) {
      this.logReader = logReader;
    }
    public Path getAggregatedLogPath() {
      return aggregatedLogPath;
    }
    public void setAggregatedLogPath(Path aggregatedLogPath) {
      this.aggregatedLogPath = aggregatedLogPath;
    }
  }
}


text:
package com.reactnativenavigation.viewcontrollers;

import android.app.Activity;

import com.facebook.react.ReactInstanceManager;
import com.reactnativenavigation.BaseTest;
import com.reactnativenavigation.parse.ExternalComponent;
import com.reactnativenavigation.parse.Options;
import com.reactnativenavigation.parse.params.Text;
import com.reactnativenavigation.presentation.ExternalComponentPresenter;
import com.reactnativenavigation.presentation.Presenter;
import com.reactnativenavigation.react.events.ComponentType;
import com.reactnativenavigation.react.events.EventEmitter;
import com.reactnativenavigation.viewcontrollers.externalcomponent.ExternalComponentViewController;
import com.reactnativenavigation.viewcontrollers.externalcomponent.FragmentCreatorMock;
import com.reactnativenavigation.views.ExternalComponentLayout;

import org.json.JSONObject;
import org.junit.Test;
import org.mockito.Mockito;

import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.fragment.app.FragmentActivity;

import static org.assertj.core.api.Java6Assertions.assertThat;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

public class ExternalComponentViewControllerTest extends BaseTest {
    private ExternalComponentViewController uut;
    private FragmentCreatorMock componentCreator;
    private Activity activity;
    private ExternalComponent ec;
    private ReactInstanceManager reactInstanceManager;
    private EventEmitter emitter;
    private ChildControllersRegistry childRegistry;

    @Override
    public void beforeEach() {
        componentCreator = spy(new FragmentCreatorMock());
        activity = newActivity();
        ec = createExternalComponent();
        reactInstanceManager = Mockito.mock(ReactInstanceManager.class);
        emitter = Mockito.mock(EventEmitter.class);
        childRegistry = new ChildControllersRegistry();
        uut = spy(new ExternalComponentViewController(activity,
                childRegistry,
                "fragmentId",
                new Presenter(activity, Options.EMPTY),
                ec,
                componentCreator,
                reactInstanceManager,
                emitter,
                new ExternalComponentPresenter(),
                new Options())
        );
    }

    @Test
    public void createView_returnsFrameLayout() {
        ExternalComponentLayout view = uut.getView();
        assertThat(CoordinatorLayout.class.isAssignableFrom(view.getClass())).isTrue();
    }

    @Test
    public void createView_createsExternalComponent() {
        ExternalComponentLayout view = uut.getView();
        verify(componentCreator, times(1)).create((FragmentActivity) activity, reactInstanceManager, ec.passProps);
        assertThat(view.getChildCount()).isGreaterThan(0);
    }

    @Test
    public void onViewAppeared_appearEventIsEmitted() {
        uut.onViewAppeared();
        verify(emitter).emitComponentDidAppear(uut.getId(), ec.name.get(), ComponentType.Component);
    }

    @Test
    public void onViewDisappear_disappearEventIsEmitted() {
        uut.onViewDisappear();
        verify(emitter).emitComponentDidDisappear(uut.getId(), ec.name.get(), ComponentType.Component);
    }

    @Test
    public void registersInChildRegister() {
        uut.onViewAppeared();
        assertThat(childRegistry.size()).isOne();
        uut.onViewDisappear();
        assertThat(childRegistry.size()).isZero();
    }

    private ExternalComponent createExternalComponent() {
        ExternalComponent component = new ExternalComponent();
        component.name = new Text("fragmentComponent");
        component.passProps = new JSONObject();
        return component;
    }
}


text:
<demo-template [description]="description" [demoSources]="demoSources">

        单选
        <j-combo-select [value]="comboValue1">
            <ng-template>
                <j-cascade
                    width="418"
                    labelField="name"
                    [(selectedItems)]="selectedItems1"
                    [dataGenerator]="generator"
                    [generatorContext]="this"
                    style="min-height: 335px"
                >
                </j-cascade>
            </ng-template>
        </j-combo-select>

        多选
        <j-combo-select [value]="comboValue2">
            <ng-template>
                <j-cascade
                    width="418"
                    labelField="name"
                    [(selectedItems)]="selectedItems2"
                    [dataGenerator]="generator"
                    [generatorContext]="this"
                    [multipleSelect]="true"
                    style="min-height: 335px"
                >
                </j-cascade>
            </ng-template>
        </j-combo-select>

</demo-template>


text:
require File.expand_path(File.dirname(__FILE__))  + '/helper'

class IdealTest < Test::Unit::TestCase
  def setup
    Base.mode = :test
    setup_ideal_gateway(fixtures(:ideal_ing_postbank))

    @gateway = IdealGateway.new

    @valid_options = {
      :issuer_id         => '0151',
      :expiration_period => 'PT10M',
      :return_url        => 'http://return_to.example.com',
      :order_id          => '123456789012',
      :currency          => 'EUR',
      :description       => 'A classic Dutch windmill',
      :entrance_code     => '1234'
    }
  end

  def test_making_test_requests
    assert @gateway.issuers.test?
  end

  def test_setup_purchase_with_valid_options
    response = @gateway.setup_purchase(550, @valid_options)

    assert_success response
    assert_not_nil response.service_url
    assert_not_nil response.transaction_id
    assert_equal @valid_options[:order_id], response.order_id
  end

  def test_setup_purchase_with_invalid_amount
    response = @gateway.setup_purchase(0.5, @valid_options)

    assert_failure response
    assert_equal "BR1210", response.error_code
    assert_not_nil response.error_message
    assert_not_nil response.consumer_error_message
  end

  # TODO: Should we raise a SecurityError instead of setting success to false?
  def test_status_response_with_invalid_signature
    IdealStatusResponse.any_instance.stubs(:signature).returns('db82/jpJRvKQKoiDvu33X0yoDAQpayJOaW2Y8zbR1qk1i3epvTXi+6g+QVBY93YzGv4w+Va+vL3uNmzyRjYsm2309d1CWFVsn5Mk24NLSvhYfwVHEpznyMqizALEVUNSoiSHRkZUDfXowBAyLT/tQVGbuUuBj+TKblY826nRa7U=')
    response = capture_transaction(:success)

    assert_failure response
    assert !response.verified?
  end

  ###
  #
  # These are the 7 integration tests of ING which need to be ran sucessfuly
  # _before_ you'll get access to the live environment.
  #
  # See test_transaction_id for info on how the remote tests are ran.
  #

  def test_retrieval_of_issuers
    assert_equal [{ :id => '0151', :name => 'Issuer Simulator' }], @gateway.issuers.list
  end

  def test_successful_transaction
    p capture_transaction(:success)
    assert_success capture_transaction(:success)
  end

  def test_cancelled_transaction
    captured_response = capture_transaction(:cancelled)

    assert_failure captured_response
    assert_equal :cancelled, captured_response.status
  end

  def test_expired_transaction
    captured_response = capture_transaction(:expired)

    assert_failure captured_response
    assert_equal :expired, captured_response.status
  end

  def test_still_open_transaction
    captured_response = capture_transaction(:open)

    assert_failure captured_response
    assert_equal :open, captured_response.status
  end

  def test_failed_transaction
    captured_response = capture_transaction(:failure)

    assert_failure captured_response
    assert_equal :failure, captured_response.status
  end

  def test_internal_server_error
    captured_response = capture_transaction(:server_error)

    assert_failure captured_response
    assert_equal 'SO1000', captured_response.error_code
  end

  private

  # Shortcut method which does a #setup_purchase through #test_transaction and
  # captures the resulting transaction and returns the capture response.
  def capture_transaction(type)
    @gateway.capture test_transaction(type).transaction_id
  end

  # Calls #setup_purchase with the amount corresponding to the named test and
  # returns the response. Before returning an assertion will be ran to test
  # whether or not the transaction was successful.
  def test_transaction(type)
    amount = case type
    when :success      then 100
    when :cancelled    then 200
    when :expired      then 300
    when :open         then 400
    when :failure      then 500
    when :server_error then 700
    end

    response = @gateway.setup_purchase(amount, @valid_options)
    assert response.success?
    response
  end

  # Setup the gateway by providing a hash of aatributes and values.
  def setup_ideal_gateway(fixture)
    fixture = fixture.dup
    if passphrase = fixture.delete(:passphrase)
      IdealGateway.passphrase = passphrase
    end
    fixture.each { |key, value| IdealGateway.send("#{key}=", value) }
    IdealGateway.live_url = nil
  end
end


text:
package in.twizmwaz.cardinal.module.modules.worldFreeze;

import in.twizmwaz.cardinal.match.Match;
import in.twizmwaz.cardinal.module.ModuleBuilder;
import in.twizmwaz.cardinal.module.ModuleCollection;

public class WorldFreezeBuilder implements ModuleBuilder {

    @Override
    public ModuleCollection<WorldFreeze> load(Match match) {
        return new ModuleCollection<>(new WorldFreeze(match));
    }

}


text:
module AppsHelper
  def link_to_copy_attributes_from_other_app
    if App.count > 1
      html =  link_to('copy settings from another app', '#',
                       :class => 'button copy_config')
      html << select("duplicate", "app",
                     App.all.asc(:name).reject{|a| a == @app }.
                     collect{|p| [ p.name, p.id ] }, {:include_blank => "[choose app]"},
                     {:class => "choose_other_app", :style => "display: none;"})
      return html
    end
  end

  def any_github_repos?
    detect_any_apps_with_attributes unless @any_github_repos
    @any_github_repos
  end

  def any_notification_services?
    detect_any_apps_with_attributes unless @any_notification_services
    @any_notification_services
  end

  def any_bitbucket_repos?
    detect_any_apps_with_attributes unless @any_bitbucket_repos
    @any_bitbucket_repos
  end

  def any_issue_trackers?
    detect_any_apps_with_attributes unless @any_issue_trackers
    @any_issue_trackers
  end

  def any_deploys?
    detect_any_apps_with_attributes unless @any_deploys
    @any_deploys
  end

  private

  def detect_any_apps_with_attributes
    @any_github_repos = @any_issue_trackers = @any_deploys = @any_bitbucket_repos = @any_notification_services = false

    apps.each do |app|
      @any_github_repos   ||= app.github_repo?
      @any_bitbucket_repos   ||= app.bitbucket_repo?
      @any_issue_trackers ||= app.issue_tracker_configured?
      @any_deploys        ||= !!app.last_deploy_at
      @any_notification_services ||= app.notification_service_configured?
    end
  end
end


text:
require 'rails_helper'

describe "Front end builds API", type: :request do
  let!(:front_end_app) { create :front_end_builds_app, name: "dummy" }
  let(:endpoint) { "http://www.ted.com/builds/1" }

  before(:each) do
    stub_request(:get, endpoint)
      .to_return(body: 'your app!')

    create(:front_end_builds_pubkey, :fixture_pubkey)
  end

  it "creates a new build and then uses it" do
    post "/dummy",
      params: {
        branch: "master",
        sha: "a1b2c3",
        job: "jenkins-build-1",
        endpoint: endpoint,
        signature: create_signature("dummy-#{endpoint}")
      }

    expect(response.successful?).to be true

    # Index loads
    get "/dummy"
    expect(response.successful?).to be true
    expect(response.body).to match(/your app!$/)

    # Deep routes load
    get "/dummy/posts/1"
    expect(response.successful?).to be true
    expect(response.body).to match(/your app!$/)
  end

  it "should be able to create a build from a generic endpoint" do
    post "/front_end_builds/builds",
      params: {
        app_name: 'dummy',
        branch: "master",
        sha: "a1b2c3",
        job: "jenkins-build-1",
        endpoint: endpoint,
        signature: create_signature("dummy-#{endpoint}")
      }

    expect(response.successful?).to be true
    expect(front_end_app.builds.length).to eq(1)
    expect(front_end_app.builds.first.html).to eq('your app!')
  end
end


text:
package io.coala.resource;

import io.coala.exception.CoalaException;
import io.coala.exception.CoalaExceptionFactory;
import io.coala.log.LogUtil;
import io.coala.util.Util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;

import org.apache.log4j.Logger;

/**
 * {@link FileUtil} provides some file related utilities
 *
 * @date $Date: 2014-08-08 07:08:29 +0200 (Fri, 08 Aug 2014) $
 * @version $Revision: 349 $ $Author: krevelen $
 * @author Rick van Krevelen
 */
public class FileUtil implements Util
{

	/** */
	private static final Logger LOG = LogUtil.getLogger(FileUtil.class);

	/**
	 * {@link FileUtil} constructor
	 */
	private FileUtil()
	{
		// empty
	}

	/**
	 * @param path
	 * @return
	 * @throws A4GException
	 */
	public static InputStream getFileAsInputStream(final File path)
			throws CoalaException
	{
		return getFileAsInputStream(path.getPath());
	}

	/**
	 * @param path
	 * @return
	 * @throws A4GException
	 */
	public static InputStream getFileAsInputStream(final URI path)
			throws CoalaException
	{
		try
		{
			return getFileAsInputStream(path.toURL());
		} catch (final CoalaException e)
		{
			throw e;
		} catch (final Exception e)
		{
			throw CoalaExceptionFactory.VALUE_NOT_ALLOWED.create(e, "path",
					path.toASCIIString());
		}
	}

	/**
	 * @param path
	 * @return
	 * @throws A4GException
	 */
	public static InputStream getFileAsInputStream(final URL path)
			throws CoalaException
	{
		return getFileAsInputStream(path.toExternalForm());
	}

	/**
	 * Searches the file system first and then the context class path for a file
	 *
	 * @param path an absolute path in the file system or (context) classpath
	 * @return an {@link InputStream} for the specified {@code path}
	 * @throws A4GException e.g. if the file was not found
	 */
	public static InputStream getFileAsInputStream(final String path)
			throws CoalaException
	{
		if (path == null)
			throw CoalaExceptionFactory.VALUE_NOT_SET.createRuntime("path");

		final File file = new File(path);
		if (file.exists())
		{
			LOG.debug("Found '" + path + "' at location: "
					+ file.getAbsolutePath());
			try
			{
				// if (path.exists() && path.isFile())
				return new FileInputStream(file);

			} catch (final FileNotFoundException e)
			{
				throw CoalaExceptionFactory.VALUE_NOT_ALLOWED.create(e,
						"path (not found or inaccessible)",
						file.getAbsolutePath());
			}
		}

		try
		{
			final URL url = new URL(path);
			LOG.trace("Downloading '" + path + "'");
			return url.openStream();
		} catch (final MalformedURLException e)
		{
			// ignore
		} catch (final IOException e)
		{
			throw CoalaExceptionFactory.VALUE_NOT_ALLOWED.create(e, "path",
					path);
		}

		final ClassLoader cl = Thread.currentThread().getContextClassLoader();
		// FileUtil.class.getClassLoader()
		final URL resourcePath = cl.getResource(path);
		if (resourcePath == null)
		{
			throw CoalaExceptionFactory.VALUE_NOT_ALLOWED.create("path", path,
					"File not found, looked in " + file.getAbsolutePath()
							+ " and classpath");
		}
		LOG.debug("Found '" + path + "' in classpath: " + resourcePath);
		return cl.getResourceAsStream(path);
	}

	/**
	 * @param path
	 * @return
	 */
	public static OutputStream getFileAsOutputStream(final String path)
			throws CoalaException
	{
		if (path == null)
			throw CoalaExceptionFactory.VALUE_NOT_SET.createRuntime("path");

		return getFileAsOutputStream(new File(path), true);
	}

	/**
	 * @param path
	 * @return
	 */
	public static OutputStream getFileAsOutputStream(final File file,
			final boolean append) throws CoalaException
	{
		if (file == null)
			throw CoalaExceptionFactory.VALUE_NOT_SET.createRuntime("file");

		try
		{
			if (file.createNewFile())
				LOG.info("Created '" + file.getName() + "' at location: "
						+ file.getAbsolutePath());
			else
				LOG.debug("Found '" + file.getName() + "' at location: "
						+ file.getAbsolutePath());
			return new FileOutputStream(file, append);
		} catch (final IOException e)
		{
			throw CoalaExceptionFactory.VALUE_NOT_ALLOWED.create(e, "file",
					file);
		}
	}

}


text:
using System;
using TCC.Data;
using TCC.UI.Windows.Widgets;

namespace TCC.Settings.WindowSettings
{
    public class CooldownWindowSettings : WindowSettingsBase
    {
        public event Action? ShowItemsChanged;
        public event Action? ModeChanged;

        private bool _showItems;
        private CooldownBarMode _mode;

        public bool ShowItems
        {
            get => _showItems;
            set
            {
                if (_showItems == value) return;
                _showItems = value;
                N();
                ShowItemsChanged?.Invoke();
            }
        }

        public CooldownBarMode Mode
        {
            get => _mode;
            set
            {
                if (_mode == value) return;
                _mode = value;
                N();
                ModeChanged?.Invoke();
            }
        }

        public CooldownWindowSettings()
        {
            _visible = true;
            _clickThruMode = ClickThruMode.Never;
            _scale = 1;
            _autoDim = true;
            _dimOpacity = .5;
            _showAlways = false;
            _enabled = true;
            _allowOffScreen = false;
            Positions = new ClassPositions(.4, .7, ButtonsPosition.Above);

            Mode = CooldownBarMode.Fixed;
            ShowItems = true;
            UndimOnFlyingGuardian = false;

        }
    }
}


text:
package com.cronutils.model.time.generator;

import com.cronutils.model.field.CronField;
import com.cronutils.model.field.CronFieldName;
import com.cronutils.model.field.constraint.FieldConstraints;
import com.cronutils.model.field.constraint.FieldConstraintsBuilder;
import com.cronutils.model.field.expression.FieldExpression;
import com.cronutils.model.field.expression.On;
import com.cronutils.model.field.value.IntegerFieldValue;
import org.junit.Before;
import org.junit.Test;

import java.util.Random;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;

public class OnDayOfMonthValueGeneratorTest {
    private OnDayOfMonthValueGenerator fieldValueGenerator;
    private FieldConstraints constraints;
    private static final int YEAR = 2015;
    private static final int MONTH = 2;
    private final Random random = new Random();

    @Before
    public void setUp() {
        constraints = FieldConstraintsBuilder.instance().createConstraintsInstance();
        fieldValueGenerator =
                new OnDayOfMonthValueGenerator(
                        new CronField(
                                CronFieldName.DAY_OF_MONTH,
                                new On(new IntegerFieldValue(3)), constraints),
                        YEAR, MONTH);
    }

    @Test(expected = NoSuchValueException.class)
    public void testGenerateNextValue() throws NoSuchValueException {
        fieldValueGenerator.generateNextValue(randomNumber());
    }

    @Test(expected = NoSuchValueException.class)
    public void testGeneratePreviousValue() throws NoSuchValueException {
        fieldValueGenerator.generatePreviousValue(randomNumber());
    }

    @Test
    public void testMatchesFieldExpressionClass() {
        assertTrue(fieldValueGenerator.matchesFieldExpressionClass(mock(On.class)));
        assertFalse(fieldValueGenerator.matchesFieldExpressionClass(mock(FieldExpression.class)));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testConstructorNotMatchesOn() {
        new OnDayOfMonthValueGenerator(new CronField(CronFieldName.YEAR, mock(FieldExpression.class), constraints), YEAR, MONTH);
    }

    private int randomNumber() {
        return random.nextInt(10);
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<title>Option: insertlink_callback</title>
<link href="css/screen.css" rel="stylesheet" type="text/css" />

(deprecated) Option: insertlink_callback

		This callback was removed in 2.0.3, use execcommand_callback instead this also enables you to override other things than the image and link dialogs.

		This option enables you to override the built in functionality for inserting links. This option should contain a function name to be executed when a new link is inserted into TinyMCE. The format of this callback function is: insertLink(href, target, title, onclick, action). Where most of these options are self explained the action can be "update" or "insert" depending on what operation type. This function should return an array with the same values as the incomming parameters, the example below describes how this is done. This option is set to a internal TinyMCE function by default.

Example of usage of the insertlink_callback option:

function myCustomInsertLink(href, target, title, onclick, action) {
	var result = new Array();

	// Do some custom logic
	result['href'] = "some_page.htm";
	result['target'] = "_self";
	result['title'] = "Some link title";
	result['onclick'] = "";

	return data;
}

tinyMCE.init({
	...
	insertlink_callback : "myCustomInsertLink"
});

Index

Copyright © 2003-2006 Moxiecode Systems AB


text:
namespace librealsense
{
    class LRS_EXTENSION_API depth_decompression_huffman : public functional_processing_block
    {
    public:
        depth_decompression_huffman();

        void process_function(byte* const dest[], const byte* source, int width, int height, int actual_size, int input_size) override;

    protected:
        depth_decompression_huffman(const depth_decompression_huffman&) = delete;
    };

    MAP_EXTENSION(RS2_EXTENSION_DEPTH_HUFFMAN_DECODER, librealsense::depth_decompression_huffman);
}


text:
using System;

namespace OmniBeanEB.Library.Internal
{
	public delegate void InvokeHelper();
}


text:
Maphper
=======

Maphper - A php ORM using the Data Mapper pattern

A work in progress!

[![Scrutinizer-CI](https://scrutinizer-ci.com/g/Level-2/Maphper/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/Level-2/Maphper/)

Features:
--------

1) Creates database tables on the fly

2) Currently supports database tables but will support XML files, web services even twitter feeds as Data Sources

3) Supports relations between any two data sources

4) Composite primary keys

Maphper takes a simplistic and minimalist approach to data mapping and aims to provide the end user with an intuitive and easy to use API.

The main philosophy of Maphper is that the programmer should deal with sets of data and then be able to manipulate the set and extract other data from it.

Basic Usage
----------

This sets up a Data Mapper that maps to the 'blog' table in a MySQL database. Each mapper has a data source. This source could be anything, a database table, an XML file, a folder full of XML files, a CSV, a Twitter feed, a web service, or anything.

The aim is to give the developer a consistent and simple API which is shared between any of the data sources.

It's then possible to treat the $blogs object like an array.

To set up a Maphper object using a Database Table as its Data Source, first create a standard PDO instance:

```php
$pdo = new PDO('mysql:dbname=maphpertest;host=127.0.0.1', 'username', 'password');
```

Then create an instance of \Maphper\DataSource\Database passing it the PDO instance, name of the table and primary key:

```php
$blogSource = new \Maphper\DataSource\Database($pdo, 'blog', 'id');
```

Finally create an instance of \Maphper\Maphper and pass it the data source:

```php
$blogs = new \Maphper\Maphper($blogSource);
```

You can loop through all the blogs using:

```php
// Equivalent to SELECT * FROM blogs
foreach ($blogs as $blog) {
  echo $blog->title . '<br />';
}
```

Any fields from the database table (or xml file, web service, etc) will be available in the $blog object

Alternatively you can find a specific blog using the ID

```php
//Equivalent to SELECT * FROM blogs WHERE id = 142
echo $blogs[142]->title;
```

Which will find a blog with the id of 142 and display the title.

Filters
-------

Maphper supports filtering the data:

```php
//find blogs that were posted on a specific date
//Equivalent to SELECT * FROM blogs WHERE date = '2015-04-09'
$filteredBlogs = $blogs->filter(['date' => '2014-04-09']);

//this will only retrieve blogs that were matched by the filter
foreach ($filteredBlogs as $blog) {
	echo $blog->title;
}
````

Filters can be extended and chained together:

```php
//find blogs that were posted with the title "My Blog" by the author with the id of 7
//Equivalent to SELECT * FROM blogs WHERE title = 'My Blog' AND authorId = 7
$filteredBlogs = $blogs->filter(['title' => 'My Blog'])->filter(['authorId' => 7]);

//this will only retrieve blogs that were matched by both filters
foreach ($filteredBlogs as $blog) {
	echo $blog->title;
}
````

As well as filtering there are both sort() and limit() methods which can all be chained:

```php
foreach ($blogs->filter(['date' => '2014-04-09']) as $blog) {
  echo $blog->title;
}
```

To find the latest 5 blogs you could use:

```php
//Equivalent to SELECT * FROM blogs LIMIT 5 ORDER BY date DESC
foreach ($blogs->limit(5)->sort('date desc') as $blog) {
  echo $blog->title;
}
```

Like any array, you can count the total number of blogs using:

```php
//Equivalent to SELECT count(*) FROM lblogs
echo 'Total number of blogs is ' . count($blogs);
```

This will count the total number of blogs in the table. You can also count filtered results:

```php
//Count the number of blogs in category 3
//Equivalent to SELECT count(*) FROM blogs WHERE categoryId =  3
echo count($blogs->filter(['categoryId' => 3]);
```

Saving Data
-----------

To save an object back into the data mapper, simply create an instance of stdClass:

```php
$pdo = new PDO('mysql:dbname=maphpertest;host=127.0.0.1', 'username', 'password');
$blogSource = new \Maphper\DataSource\Database($pdo, 'blog', 'id');
$blogs = new \Maphper\Maphper($blogSource);

$blog = new stdClass;

$blog->title = 'My Blog Title';
$blog->content = 'This is my first blog entry';

//Store the blog using the next available ID
$blogs[] = $blog;

echo 'The new blog ID is :' . $blog->id;

```

Alternatively, you can write a record to a specific ID by specifying the index:

```php
$blog = new stdClass;

$blog->title = 'My Blog Title';
$blog->content = 'This is my first blog entry';

//Store the blog with the primary key of 7
$blogs[7] = $blog;

```

Note: The behaviour of this is identical to setting the id property on the $blog object directly:

```php

$blog = new stdClass;

$blog->id = 7;
$blog->title = 'My Blog Title';
$blog->content = 'This is my first blog entry';

//Store the blog with the primary key of 7
$blogs[] = $blog;

```

Relationships
-------------

If there was an `author` table which stored information about blog authors, it could be set up in a similar way:

```php
$authorSource = new \Maphper\DataSource\Database($pdo, 'author', 'id');
$authors = new \Maphper\Maphper($authorSource);
```

This could be used similarly:

```php
$author = $authors[123];
echo $author->name;
```

Once both the blogs and authors mappers have been defined, you can create a relationship between them.

This is a one-to-one relationship (one blog has one author) and can be achieved using the addRelation method on the blog mapper:

```php
//Create a one-to-one relationship between blogs and authors (a blog can only have one author)
$relation = new \Maphper\Relation\One($authors, 'authorId', 'id');
$blogs->addRelation('author', $relation);
```

Using an instance of \Maphper\Relation\One tells Maphper that it's a one-to-one relationship

The first parameter, `$authors` tells Maphper that the relationship is to the `$authors` mapper (in this case, the author database table, although you can define relationships between different data sources)

`authorId` is the field in the blog table that's being joined from

`id` is the field in the author table that's being joined to

After the relation is constructed it can be added to the blog mapper using:

```php
$blogs->addRelation('author', $relation);
```

The first parameter (here: 'author') is the name of the property the related data will be available under. So any object retrieved from the $blogs mapper will now have an 'author' property that contains the author
of the blog and can be used like this:

```php
foreach ($blogs as $blog) {
  echo $blog->title . '<br />';
  echo $blog->author->name . '<br />';
}
```

Similarly, you can define the inverse relation between authors and blogs. This is a one-to-many relationship because an author can post more than one blog.

```php
//Create a one-to-many relationship between blogs and authors (an author can have multiple blog entries)
//Joining from the 'id' field in the authors mapper to the 'authorId' field in the blogs mapper
$relation = new \Maphper\Relation\Many($blogs, 'id', 'authorId');
$authors->addRelation('blogs', $relation);
```

This is creating a One:Many relationship between the `$authors` and `$blogs` mappers using the `id` field in the `$authors` mapper to the `authorId` field in the `$blogs` mapper and making a `blogs` property available for any object returned by the `$authors` mapper.

```php
//Count all the blogs by the author with id 4
$authors[4]->name . ' has posted ' .  count($authors[4]->blogs)  . ' blogs:<br />';

//Loop through all the blogs created by the author with id 4
foreach ($authors[4]->blogs as $blog) {
    echo $blog->title . '<br />';
}
```

Saving values with relationships
--------------------------------

Once you have created your mappers and defined the relationships between them, you can write data using the relationship. This will automatically set any related fileds behind the scenes.

```php
$authors = new \Maphper\Maphper(new \Maphper\DataSource\Database($pdo, 'author'));
$blogs = new \Maphper\Maphper(new \Maphper\DataSource\Database($pdo, 'blog', 'id'));
$blogs->addRelation('author', new \Maphper\Relation\One($authors, 'authorId', 'id'));

$blog = new stdClass;
$blog->title = 'My First Blog';
$blog->date = new \DateTime();
$blog->author = new stdClass;
$blog->author->name = 'Tom Butler';

$blogs[] = $blog;
```

This will save both the `$blog` object into the `blog` table and the `$author` object into the `author` table as well as setting the blog record's authorId column to the id that was generated.

You can also do the same with one-to-many relationships:

```php
$authors = new \Maphper\Maphper(new \Maphper\DataSource\Database($pdo, 'author'));
$blogs = new \Maphper\Maphper(new \Maphper\DataSource\Database($pdo, 'blog', 'id'))

$authors->addRelation('blogs', new \Maphper\Relation\Many($blogs, 'id', 'authorId'));

//Find the author with id 4
$author = $authors[4];

$blog = new stdClass;
$blog->title = 'My New Blog';
$blog->date = new \DateTime();

//Add the blog to the author. This will save to the database at the this point, you do not need to explicitly
//Save the $author object after adding a blog to it.
$author->blogs[] = $blog;
```

Composite Primary Keys
----------------------

Maphper allows composite primary keys. For example, if you had a table of products you could use the manufacturer id and manufacturer part number as primary keys (Two manufacuterers may use the same part number)

To do this, define the data source with an array for the primary key:

```php
$pdo = new PDO('mysql:dbname=maphpertest;host=127.0.0.1', 'username', 'password');
$productSource = new \Maphper\DataSource\Database($pdo, 'products', ['manufacturerId', 'partNumber']);
$products = new \Maphper\Maphper($productSource);
```

Once you have defined the source to use multiple keys, you can treat the `$products` variable like a two dimensional array:

```php
//Get the product with manufacturerId 7 and partNumber AC294
echo $products[7]['AC294']->name;
```

To write data using composite keys, you simply write an object to a specified index:

```php
$pdo = new PDO('mysql:dbname=maphpertest;host=127.0.0.1', 'username', 'password');
$productSource = new \Maphper\DataSource\Database($pdo, 'products', ['manufacturerId', 'partNumber']);
$products = new \Maphper\Maphper($productSource);

$product = new stdClass;
$product->name 'Can of cola';

$products[1]['CANCOLA'] = $product;

```

Dates
-----

Maphper uses the inbuilt PHP `\DateTime` class to store and search by dates:

```php
$blog = new stdClass;
$blog->title = 'A blog entry';

//You can construct the date object using any of the formats availble in the inbuilt PHP datetime class
$blog->date = new \DateTime('2015-11-14');

```

This can also be used in filters:

```php
//Find all blogs posted on 2015-11-14
$maphper->filter(['date' => new \DateTime('2015-11-14')]);

```

*It is recommended to use the DateTime class rather than passing the date value as a string as not all mappers will use the same internal date format*

Automatic Database Table creation/amendment
-------------------------------------------

Maphper can be instructed to automatically construct database tables. This is done on the fly, you just need to tell maphper you want to use this behaviour. When you construct your Database Data source, set editmode to true:

```php
$pdo = new PDO('mysql:dbname=maphpertest;host=127.0.0.1', 'username', 'password');
$blogs = new \Maphper\DataSource\Database($pdo, 'blogs', 'id', ['editmode' => true]);
```

n.b. `'editmode => true`' is shorthand for \Maphper\DataSoruce\Database::EDIT_STRUCTURE | \Maphper\DataSoruce\Database::EDIT_INDEX | \Maphper\DataSoruce\Database::EDIT_OPTIMISE;

The available flags can be interchanged using bitwise or e.g `\Maphper\DataSoruce\Database::EDIT_STRUCTURE | \Maphper\DataSoruce\Database::EDIT_INDEX` will enable structure and index modification but will not allow column optimisation.

The three options for `editmode` are:

`\Maphper\DataSoruce\Database::EDIT_STRUCTURE` - When this is set, Maphper automatically creates tables that don't exist, creates columns when writing to properties that don't yet exist and changes data types on out-of-bounds columns:

```php
$blog = new stdClass;
$blog->title = 'A blog';
$blog->date = new \DateTime();
$blogs[] = $blog;
```

For database mappers, this will issue a `CREATE TABLE` statement that creates a table called `blogs` with the columns `id INT auto_increment`, `title VARCHAR`, `date DATETIME`.

### Type juggling

Maphper will use the strictest possible type when creating a table. For instance:

```php
$blog = new stdClass;
$blog->title = 1;
$blogs[] = $blog;
```

This would create a `title` column as an integer because only an integer has been stored in it. However, if another record was added to the table after it was created with a different type:

```php

$blog = new stdClass;
$blog->title = 'Another blog';
$blogs[] = $blog;
```

This would issue an `ALTER TABLE` query and change the `title` colum to `varchar`. Similarly if a very long string was added as the title the column would be changed to `LONGBLOG`. This is all done on the fly and behind the scenes, as the developer you don't need to worry about the table structure at all.

### Indexes

`\Maphper\DataSoruce\Database::EDIT_INDEX` When this is set, Maphper will automatically add indexes to columns used in WHERE, ORDER and GROUP statements. If a mutli-column where is done, a multi-column index is also added.

### Database optimisation

`\Maphper\DataSoruce\Database::EDIT_OPTIMISE` when this is set, Maphper automatically periodically optimises database tables. For example, a column set to VARCHAR(255) where the longest entry is 7 characters will be changed to VARCHAR(7) or a VARCHAR(255) column that has 3 records with values 1,2,3 will be converted to INT(11). This will also automatically delete any columns that have NULL in every record.

Currently optimisation happens once every 500 times the DataSource is created. In future versions this value will be configurable.

Concrete classes for mapped objects
-----------------------------------

It's possible to use your own classes instead of stdClass for any object managed by Maphper. This object will automatically have its properties set when it is created.

For example, if you had a product class:

```php
class Product {
	private $name;
	private $price;

	const TAX_RATE = 0.2;

	public function getTax() {
		return $this->price * self::TAX_RATE;
	}

	public function getTotalPrice() {
		return $this->price + $this->getTax();
	}

	public function setName($name) {
		$this->name = $name;
	}
}
```

You can instruct Maphper to use this class using the `resultClass` option in the `$options` array when creating the Maphper instance:

```php
$dataSource = new \Maphper\DataSource\Database($pdo, 'product', 'id');
$products = new \Maphper\Maphper($dataSource, ['resultClass' => 'Product']);

$product = $products[123];

echo get_class($product); //"Product" instance

//And as expected, the methods from Product are available:
$tax = $product->getTax();
$total = $product->getTotalPrice();
```

Private properties are both saved and loaded as any normal properties.

Similarly, you can create an instance of the `Product` class and save it to the mapper.

```php
$product = new Product;
$product->setName('A Product');
//Write the product to the mapper. Even though $product->name is private it will still be stored
$products[] = $product;
```

### Factory creation for new objects

Sometimes your result class may have dependencies. In this case, you can specify a method rather than a class name to act as a factory. Consider the following:

```php

class TaxCalculator {
	const TAX_RATE = 0.2;

	public function getTax($price) {
		return $price * self::TAX_RATE;
	}
}

class Product {
	private $name;
	private $price;
	private $taxCalculator;

	public function __construct(TaxCalculator $taxCalculator) {
		$this->taxCalculator = $taxCalculator;
	}

	public function getTax() {
		return $this->taxCalculator->getTax($this->price);
	}

	public function getTotalPrice() {
		return $this->price + $this->getTax();
	}
}
```

In this case using:

```php
$dataSource = new \Maphper\Maphper($database, ['resultClass' => 'Product']);
```

Will error, because when an instance of `Product` is constructed, Maphper isn't smart enough to guess that a `TaxCalculator` instance is required as a constructor argument. Instead, you can pass a closure that returns a fully constructed object:

```php
$taxCalculator = new TaxCalculator;

$dataSource = new \Maphper\Maphper($database, ['resultClass' => function() use ($taxCalculator) {
	return new Product($taxCalculator);
}]);
```

Alternatively if you want considerably more control over the dependencies you can use a Dependency Injection Container such as [Dice](https://r.je/dice.html):

```php
$dice = new \Dice\Dice;

$dataSource = new \Maphper\Maphper($database, ['resultClass' => function() use ($dice) {
	return $dice->create('Product');
}]);
````

## Many to Many relationships

Consider tables `movie` and `actor` an actor can be in more than one movie and a movie has more than one actor it's impossible to model the relationship with just two tables using primary/foregin keys.

In relational databases (and Maphper) this requires an intermediate table that stores the `actorId` and the `movieId`.

To model this relationship using Maphper first set up the standard `actor` and `movie` mappers:

```php
$actors = new \Maphper\Maphper(new \Maphper\Datasource\Database($pdo, 'actor', 'id'));
$movies = new \Maphper\Maphper(new \Maphper\Datasource\Database($pdo, 'movie', 'id'));
```

Then add a table for the intermediate table. Note this requires two primary keys, one for the `actorId` and one for the `movieId`

```php
$cast = new \Maphper\Maphper(new \Maphper\Datasource\Database($pdo, 'cast', ['movieId', 'actorId']));
```

*Note that Maphper can, of course, create this table for you with editmode turned on*

Now it's possible to set up Many to Many relationships using the `\Maphper\Relation\ManyMany` class as the relationship. Firstly for the actor to movie relationship:

```php
$actors->addRelation('movies', new \Maphper\Relation\ManyMany($cast, $movies, 'id', 'movieId'));
```

This creates a relationship on `actor` objects called `movies`.

The first constructor argument for the ManyMany class is the intermediate table.

The second constructor argument is the table being mapped to.

The third is the primary key of the `movies` table.

The fourth is the key in the intermeidate table.

This joins the $actors mapper to the $cast mapper and then the $cast mapper to the $movies mapper.

Once this is done, you can also set up the inverse relationship, mapping movies to the actors that starred in them in the same way:

```php
$movies->addRelation('actors', new \Maphper\Relation\ManyMany($cast, $actors, 'id', 'actorId'));
```

Once both of these relationships are set up you can add an actor with movies:

```php

$actor = new \stdclass;
$actor->id = 123;
$actor->name = 'Samuel L. Jackson';

//save the actor
$actors[] = $actor;

//now add some movies to the actor
$movie1 = new \stdclass;
$movie1->title = 'Pulp Fiction';

$actor->movies[] = $movie1;

//now add some movies to the actor
$movie2 = new \stdclass;
$movie2->title = 'Snakes on a Plane';

$actor->movies[] = $movie2;

```

once this is done you can get all movies played by an actor using:

```php

$actor = $actors[123];

echo $actor->name . ' was in the movies:' . "\n";

foreach ($actor->movies as $movie) {
	echo $movie->title . "\n";
}
```

Which will print:

```
Samuel L. Jackson was in the movies:
Pulp Fiction
Snakes on a Plane
```

Of course that's possible with a normal one to many relationship. A many to many relationship is only useful when there are more actors:

```php
$actor = new \stdclass;
$actor->id = 124;
$actor->name = 'John Travolta';
$actors[] = $actor;

//Find the movie 'Pulp Fiction and add it to John Travolta
$movie = $movies->filter(['title' =>'Pulp Fiction'])->item(0);
$actor->movies[] = $movie;

```

Now it's possible to find all the actors who were in Pulp Fiction using:

```php
$movie = $movies->filter(['title' =>'Pulp Fiction'])->item(0);

echo 'The actors in ' . $movie->title . ' are :' . "\n";
foreach ($movie->actors as $actor) {
	echo $actor->name . "\n";
}
```

Which prints

```
The actors in Pulp Fiction are:
Samuel L. Jackson
John Travolta
```

### Storing data in the intermediate table

Sometimes it's useful to store extra information in the intermediate table. In the example above, it would be nice to know the name of the character the actor played in a given movie. For this, there are two extra fields used when setting up the relationship.

Instead of

```php
$actors->addRelation('movies', new \Maphper\Relation\ManyMany($cast, $movies, 'id', 'movieId'));
$movies->addRelation('actors', new \Maphper\Relation\ManyMany($cast, $actors, 'id', 'actorId'));
```

You can use:

```php
$actors->addRelation('roles', new \Maphper\Relation\ManyMany($cast, $movies, 'id', 'movieId', 'movie');
$movies->addRelation('cast', new \Maphper\Relation\ManyMany($cast, $actors, 'id', 'actorId', 'actor');
```

The 5th argument to the  `\Maphper\Relation\ManyMany` constructor have been added.

This argument is the name of the field to use on objects from the intermediate table. When this is supplied, the intermediate mapper is not traversed automatically, instead it is accessed like a normal one:many relationship between the parent table (e.g. actors) and the intermediate table e.g. cast.

In this example, actors have `roles` and movies have a `cast`. Now that this is set up it's possible to assign some roles to an actor:

```php
$actor = $actors[123];

//Find the movie
$movie = $movies->filter(['title' =>'Pulp Fiction'])->item(0);

//Create a role
$role = new \stdClass;
//Set the character name for the role
$role->characterName = 'Jules Winnfield';
//Assign the movie to the role
$role->movie = $movie;
//Assign the role to the actor
$actor->roles[] = $role;

//Find the movie
$movie = $movies->filter(['title' =>'Snakes on a Plane'])->item(0);
//Create a role
$role = new \stdClass;
//Set the character name for the role
$role->characterName = 'Neville Flynn';
//Assign the movie to the role
$role->movie = $movie;
//Assign the role to the actor
$actor->roles[] = $role;

```

This has assigned the movies Pulp Fiction and Snakes on a Plane to Samuel L. Jackson via the 'role' attribue. It's now possible to show the movies:

```php
$actor = $actors[123];

echo $actor->name . ' has the roles:' . "\n"
foreach ($actors[123]->roles as $role) {
    echo $role->characterName . ' in the movie . ' . $role->movie->title . "\n";
}
```

Which will print out:

```php
Samuel L. Jackson has the roles:
Jules Winnfield in Pulp Fiction
Neville Flynn in Snakes on a plane
```


text:
namespace donut
{
	namespace vk
	{
		TGraphicSettings default_settings();

		namespace render_system
		{
			bool init_render_system();
			void shutdown_render_system();

			RenderEnvironment create_render_environment(const TGraphicSettings& graphic_settings);
			void destroy_render_environment(RenderEnvironment render_environment);

			RenderWindow render_window(RenderEnvironment render_environement);

			void collect_inputs(RenderEnvironment render_environement);

			float get_time(RenderEnvironment render_environement);
		}

		namespace window
		{
			void show(RenderWindow window);
			void hide(RenderWindow window);
			bool is_active(RenderWindow window);
			void swap(RenderWindow window);
		}

		namespace framebuffer
		{
			FramebufferObject create(RenderEnvironment renderEnvironment, const TFrameBufferOutput& frameBufferOuput);
			void destroy(FramebufferObject frame_buffer);

			bool check(FramebufferObject framebuffer);

			void bind(FramebufferObject framebuffer);
			void unbind(FramebufferObject framebuffer);

			void bind_texture(FramebufferObject framebuffer, const TTextureInfo& _tex);

			void enable_depth_test(FramebufferObject framebuffer);
			void disable_depth_test(FramebufferObject framebuffer);

			void clear(FramebufferObject frame_buffer);
			void set_clear_color(FramebufferObject frame_buffer, const bento::Vector4& _color);

			void set_num_render_targets(FramebufferObject frmabuffer, uint8_t num_render_targets);
		}

		namespace texture2D
		{
			// Create and destroy textures
			TextureObject create(const TTexture& source);
			void destroy(TextureObject tex);

			// Set the debug name of the texture
			void set_debug_name(TextureObject texture, const char* debug_name);
		}

		namespace textureCUBE
		{
			CubemapObject create(const TSkybox& source_skybox);
			void destroy(CubemapObject cubemap);
		}

		namespace geometry
		{
			GeometryObject create_vnt(const float* dataArray, uint32_t numVert, const unsigned* indexArray, uint32_t numFaces);
			void destroy_vnt(GeometryObject object);

			void draw(GeometryObject geometry_object);

			void set_bbox(GeometryObject geometry, const TBox3& outbbox);
			void bbox(GeometryObject geometry, TBox3& outbbox);
		}

		namespace shader
		{
			ShaderPipelineObject create_shader(const TShaderPipelineDescriptor& shader_pipeline);
			ShaderPipelineObject create_shader_from_source(const char* vertex_shader_source, const char* tess_control_shader_source,
				const char* tess_eval_shader_source, const char* geometry_shader_source,
				const char* fragment_shader_source);
			void destroy_shader(ShaderPipelineObject program);

			void bind_shader(ShaderPipelineObject program);
			void unbind_shader(ShaderPipelineObject program);

			void inject_int(ShaderPipelineObject program, int value, const char* slot);
			void inject_float(ShaderPipelineObject program, float value, const char* slot);
			void inject_vec3(ShaderPipelineObject program, const bento::Vector3& value, const char* slot);
			void inject_vec4(ShaderPipelineObject program, const bento::Vector4& value, const char* slot);
			void inject_mat3(ShaderPipelineObject program, const bento::Matrix3& value, const char* slot);
			void inject_mat4(ShaderPipelineObject program, const bento::Matrix4& value, const char* slot);

			void inject_array(ShaderPipelineObject program, const float* value_array, uint32_t numValues, const char* slot);

			void inject_texture(ShaderPipelineObject program, TextureObject texture_object, uint32_t offset, const char* slot);
			void inject_cubemap(ShaderPipelineObject program, CubemapObject cubemap_object, uint32_t offset, const char* slot);
		}

		namespace render_section
		{
			void start_render_section(const char* sectionName);
			void end_render_section();
		}
	}
}
#endif // VULKAN_BACKEND_H