text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.jdisc.state;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.yahoo.component.annotation.Inject;
import com.yahoo.collections.Tuple2;
import com.yahoo.component.provider.ComponentRegistry;
import com.yahoo.jdisc.Request;
import com.yahoo.jdisc.Response;
import com.yahoo.jdisc.Timer;
import com.yahoo.jdisc.handler.AbstractRequestHandler;
import com.yahoo.jdisc.handler.ContentChannel;
import com.yahoo.jdisc.handler.ResponseDispatch;
import com.yahoo.jdisc.handler.ResponseHandler;
import com.yahoo.jdisc.http.HttpHeaders;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import static com.yahoo.container.jdisc.state.JsonUtil.sanitizeDouble;
import static com.yahoo.container.jdisc.state.StateHandler.getSnapshotProviderOrThrow;

/**
 * This handler outputs metrics in a json-like format, consisting of a series of metrics packets.
 * Each packet is a json object but there is no outer array or object that wraps the packets.
 * To reduce the amount of output, a packet contains all metrics that share the same set of dimensions.
 *
 * This handler is not set up by default, but can be added to the applications's services configuration.
 *
 * This handler is protocol agnostic, so it cannot discriminate between e.g. http request
 * methods (get/head/post etc.).
 *
 * Based on {@link StateHandler}.
 *
 * @author gjoranv
 */
public class MetricsPacketsHandler extends AbstractRequestHandler {

    private static final ObjectMapper jsonMapper = new ObjectMapper();

    static final String APPLICATION_KEY = "application";
    static final String TIMESTAMP_KEY   = "timestamp";
    static final String STATUS_CODE_KEY = "status_code";
    static final String STATUS_MSG_KEY  = "status_msg";
    static final String METRICS_KEY     = "metrics";
    static final String DIMENSIONS_KEY  = "dimensions";

    static final String PACKET_SEPARATOR = "\n\n";

    private final StateMonitor monitor;
    private final Timer timer;
    private final SnapshotProvider snapshotProvider;
    private final String applicationName;
    private final String hostDimension;

    @Inject
    public MetricsPacketsHandler(StateMonitor monitor,
                                 Timer timer,
                                 ComponentRegistry<SnapshotProvider> snapshotProviders,
                                 MetricsPacketsHandlerConfig config) {
        this.monitor = monitor;
        this.timer = timer;
        snapshotProvider = getSnapshotProviderOrThrow(snapshotProviders);
        applicationName = config.application();
        hostDimension = config.hostname();
    }

    @Override
    public ContentChannel handleRequest(Request request, ResponseHandler handler) {
        new ResponseDispatch() {
            @Override
            protected Response newResponse() {
                Response response = new Response(Response.Status.OK);
                response.headers().add(HttpHeaders.Names.CONTENT_TYPE, getContentType(request.getUri().getQuery()));
                return response;
            }

            @Override
            protected Iterable<ByteBuffer> responseContent() {
                return Collections.singleton(ByteBuffer.wrap(buildMetricOutput(request.getUri().getQuery())));
            }
        }.dispatch(handler);

        return null;
    }

    private byte[] buildMetricOutput(String query) {
        try {
            if (query != null && query.equals("array-formatted")) {
                return getMetricsArray();
            }
            if ("format=prometheus".equals(query)) {
                return buildPrometheusOutput();
            }

            String output = jsonToString(getStatusPacket()) + getAllMetricsPackets() + "\n";
            return output.getBytes(StandardCharsets.UTF_8);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Bad JSON construction.", e);
        } catch (IOException e) {
            throw new RuntimeException("Unexcpected IOException.", e);
        }
    }

    private byte[] getMetricsArray() throws JsonProcessingException {
        ObjectNode root = jsonMapper.createObjectNode();
        ArrayNode jsonArray = jsonMapper.createArrayNode();
        jsonArray.add(getStatusPacket());
        getPacketsForSnapshot(getSnapshot(), applicationName, timer.currentTimeMillis())
                .forEach(jsonArray::add);
        MetricGatherer.getAdditionalMetrics().forEach(jsonArray::add);
        root.set("metrics", jsonArray);
        return jsonToString(root)
                .getBytes(StandardCharsets.UTF_8);
    }

    /**
     * Returns metrics in Prometheus format
     */
    private byte[] buildPrometheusOutput() throws IOException {
        return PrometheusHelper.buildPrometheusOutput(getSnapshot(), applicationName, timer.currentTimeMillis());
    }

    /**
     * Exactly one status packet is added to the response.
     */
    private JsonNode getStatusPacket() {
        ObjectNode packet = jsonMapper.createObjectNode();
        packet.put(APPLICATION_KEY, applicationName);

        StateMonitor.Status status = monitor.status();
        packet.put(STATUS_CODE_KEY, status.ordinal());
        packet.put(STATUS_MSG_KEY, status.name());
        return packet;
    }

    private static String jsonToString(JsonNode jsonObject) throws JsonProcessingException {
        return jsonMapper.writerWithDefaultPrettyPrinter()
                .writeValueAsString(jsonObject);
    }

    private String getAllMetricsPackets() throws JsonProcessingException {
        StringBuilder ret = new StringBuilder();
        List<JsonNode> metricsPackets = getPacketsForSnapshot(getSnapshot(), applicationName, timer.currentTimeMillis());
        for (JsonNode packet : metricsPackets) {
            ret.append(PACKET_SEPARATOR); // For legibility and parsing in unit tests
            ret.append(jsonToString(packet));
        }
        return ret.toString();
    }

    private MetricSnapshot getSnapshot() {
        return snapshotProvider.latestSnapshot();
    }

    private List<JsonNode> getPacketsForSnapshot(MetricSnapshot metricSnapshot, String application, long timestamp) {
        if (metricSnapshot == null) return Collections.emptyList();

        List<JsonNode> packets = new ArrayList<>();

        for (Map.Entry<MetricDimensions, MetricSet> snapshotEntry : metricSnapshot) {
            MetricDimensions metricDimensions = snapshotEntry.getKey();
            MetricSet metricSet = snapshotEntry.getValue();

            ObjectNode packet = jsonMapper.createObjectNode();
            addMetaData(timestamp, application, packet);
            addDimensions(metricDimensions, packet);
            addMetrics(metricSet, packet);
            packets.add(packet);
        }
        return packets;
    }

    private void addMetaData(long timestamp, String application, ObjectNode packet) {
        packet.put(APPLICATION_KEY, application);
        packet.put(TIMESTAMP_KEY, TimeUnit.MILLISECONDS.toSeconds(timestamp));
    }

    private void addDimensions(MetricDimensions metricDimensions, ObjectNode packet) {
        if (metricDimensions == null && hostDimension.isEmpty()) return;

        ObjectNode jsonDim = jsonMapper.createObjectNode();
        packet.set(DIMENSIONS_KEY, jsonDim);
        Iterable<Map.Entry<String, String>> dimensionIterator = metricDimensions == null ? Set.of() : metricDimensions;
        for (Map.Entry<String, String> dimensionEntry : dimensionIterator) {
            jsonDim.put(dimensionEntry.getKey(), dimensionEntry.getValue());
        }
        if (!hostDimension.isEmpty() && !jsonDim.has("host"))
            jsonDim.put("host", hostDimension);
    }

    private void addMetrics(MetricSet metricSet, ObjectNode packet) {
        ObjectNode metrics = jsonMapper.createObjectNode();
        packet.set(METRICS_KEY, metrics);
        for (Map.Entry<String, MetricValue> metric : metricSet) {
            String name = metric.getKey();
            MetricValue value = metric.getValue();
            if (value instanceof CountMetric) {
                metrics.put(name + ".count", ((CountMetric) value).getCount());
            } else if (value instanceof GaugeMetric) {
                GaugeMetric gauge = (GaugeMetric) value;
                metrics.put(name + ".average", sanitizeDouble(gauge.getAverage()))
                        .put(name + ".last", sanitizeDouble(gauge.getLast()))
                        .put(name + ".max", sanitizeDouble(gauge.getMax()));
                if (gauge.getPercentiles().isPresent()) {
                    for (Tuple2<String, Double> prefixAndValue : gauge.getPercentiles().get()) {
                        metrics.put(name + "." + prefixAndValue.first + "percentile", prefixAndValue.second.doubleValue());
                    }
                }
            } else {
                throw new UnsupportedOperationException("Unknown metric class: " + value.getClass().getName());
            }
        }
    }

    private String getContentType(String query) {
        if ("format=prometheus".equals(query)) {
            return "text/plain;charset=utf-8";
        }
        return "application/json";
    }

}


text:
<?php

/**
 * Spiral Framework.
 *
 * @license   MIT
 * @author    Anton Titov (Wolfy-J)
 */

declare(strict_types=1);

namespace Spiral\Stempler\Directive;

use ReflectionObject;
use Spiral\Stempler\Node\Dynamic\Directive;

/**
 * Automatically invokes methods associated with directive name.
 */
abstract class AbstractDirective implements DirectiveRendererInterface
{
    /** @var ReflectionObject */
    private $r;

    /**
     * AbstractDirective constructor.
     */
    public function __construct()
    {
        $this->r = new ReflectionObject($this);
    }

    /**
     * @param string $name
     * @return bool
     */
    public function hasDirective(string $name): bool
    {
        return $this->r->hasMethod('render' . ucfirst($name));
    }

    /**
     * @param Directive $directive
     * @return string|null
     */
    public function render(Directive $directive): ?string
    {
        if (!$this->hasDirective($directive->name)) {
            return null;
        }

        return call_user_func([$this, 'render' . ucfirst($directive->name)], $directive);
    }
}

redpajama_set_name: RedPajamaGithub


text:
#pragma once
#include <aws/resiliencehub/ResilienceHub_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/resiliencehub/model/ResourceError.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace ResilienceHub
{
namespace Model
{

  /**
   *
 A list of errors retrieving an application's resources.

See
   * Also:
   AWS
   * API Reference

   */
  class AWS_RESILIENCEHUB_API ResourceErrorsDetails
  {
  public:
    ResourceErrorsDetails();
    ResourceErrorsDetails(Aws::Utils::Json::JsonView jsonValue);
    ResourceErrorsDetails& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
 This indicates if there are more errors not listed in the resourceErrors
     * list.

     */
    inline bool GetHasMoreErrors() const{ return m_hasMoreErrors; }

    /**
     *
 This indicates if there are more errors not listed in the resourceErrors
     * list.

     */
    inline bool HasMoreErrorsHasBeenSet() const { return m_hasMoreErrorsHasBeenSet; }

    /**
     *
 This indicates if there are more errors not listed in the resourceErrors
     * list.

     */
    inline void SetHasMoreErrors(bool value) { m_hasMoreErrorsHasBeenSet = true; m_hasMoreErrors = value; }

    /**
     *
 This indicates if there are more errors not listed in the resourceErrors
     * list.

     */
    inline ResourceErrorsDetails& WithHasMoreErrors(bool value) { SetHasMoreErrors(value); return *this;}

    /**
     *
 A list of errors retrieving an application's resources.

     */
    inline const Aws::Vector<ResourceError>& GetResourceErrors() const{ return m_resourceErrors; }

    /**
     *
 A list of errors retrieving an application's resources.

     */
    inline bool ResourceErrorsHasBeenSet() const { return m_resourceErrorsHasBeenSet; }

    /**
     *
 A list of errors retrieving an application's resources.

     */
    inline void SetResourceErrors(const Aws::Vector<ResourceError>& value) { m_resourceErrorsHasBeenSet = true; m_resourceErrors = value; }

    /**
     *
 A list of errors retrieving an application's resources.

     */
    inline void SetResourceErrors(Aws::Vector<ResourceError>&& value) { m_resourceErrorsHasBeenSet = true; m_resourceErrors = std::move(value); }

    /**
     *
 A list of errors retrieving an application's resources.

     */
    inline ResourceErrorsDetails& WithResourceErrors(const Aws::Vector<ResourceError>& value) { SetResourceErrors(value); return *this;}

    /**
     *
 A list of errors retrieving an application's resources.

     */
    inline ResourceErrorsDetails& WithResourceErrors(Aws::Vector<ResourceError>&& value) { SetResourceErrors(std::move(value)); return *this;}

    /**
     *
 A list of errors retrieving an application's resources.

     */
    inline ResourceErrorsDetails& AddResourceErrors(const ResourceError& value) { m_resourceErrorsHasBeenSet = true; m_resourceErrors.push_back(value); return *this; }

    /**
     *
 A list of errors retrieving an application's resources.

     */
    inline ResourceErrorsDetails& AddResourceErrors(ResourceError&& value) { m_resourceErrorsHasBeenSet = true; m_resourceErrors.push_back(std::move(value)); return *this; }

  private:

    bool m_hasMoreErrors;
    bool m_hasMoreErrorsHasBeenSet = false;

    Aws::Vector<ResourceError> m_resourceErrors;
    bool m_resourceErrorsHasBeenSet = false;
  };

} // namespace Model
} // namespace ResilienceHub
} // namespace Aws


text:
@implementation UMEPopoverController

- (id)initWithContentViewController:(UMEViewController *)viewController {
    if (self = [super init]) {

    }
    return self;
}

- (void)dealloc {

    [super dealloc];
}

- (void)setContentViewController:(UMEViewController *)viewController animated:(BOOL)animated {

}

- (void)setPopoverContentSize:(CGSize)size animated:(BOOL)animated {

}

- (void)presentPopoverFromRect:(CGRect)rect inView:(UMEView *)view permittedArrowDirections:(UMEPopoverArrowDirection)arrowDirections animated:(BOOL)animated {

}

- (void)presentPopoverFromBarButtonItem:(UMEBarButtonItem *)item permittedArrowDirections:(UMEPopoverArrowDirection)arrowDirections animated:(BOOL)animated {

}

- (void)dismissPopoverAnimated:(BOOL)animated {

}

@synthesize delegate;
@synthesize contentViewController;
@synthesize popoverContentSize;
@synthesize popoverVisible;
@synthesize popoverArrowDirection;
@synthesize passthroughViews;
@end

//@implementation UMEViewController (UMEPopoverController)
//@synthesize contentSizeForViewInPopover;
//@synthesize modalInPopover;
//@end


text:
package main

import (
	"sync"

	"github.com/satori/go.uuid"
)

// Input channel map, used to send messages to components. Key is component ID
var reqChMap = map[string]chan *RequestObject{}
var reqChLock sync.RWMutex

// Return data map, used for RRPC component return data to its requester. Key is requster ID
var retChMap = map[uuid.UUID]chan *ResponseObject{}
var retChLock sync.RWMutex


text:
/* This is a managed file. Do not delete this comment. */

#include <include/downsampling.h>

/* Enter code outside of main here. */

int downsamplingMain(int argc, char *argv[]) {

    /* Load mount that has sampleRate set to 1Hz */
    if (corto_load("config.json", 0, NULL)) {
        goto error;
    }

    /* Publish a new value every 1msec */
    while (true) {
        corto_publish(CORTO_UPDATE, "data/foo", "int32", "text/corto", "10");
        corto_sleep(0, 1000000);
    }

    return 0;
error:
    corto_error("%s", corto_lasterr());
    return -1;
}


text:
CREATE DATABASE IF NOT EXISTS Dynalite;
USE Dynalite;

-- Uncomment below to drop tables first
-- ------------------------------------
-- DROP TABLE IF EXISTS User;
-- DROP TABLE IF EXISTS Location;
-- DROP TABLE IF EXISTS UserModel;
-- ------------------------------------

-- CREATE TABLE IF NOT EXISTS User (
-- 	id INTEGER PRIMARY KEY,

-- );

-- CREATE TABLE IF NOT EXISTS Location (
-- 	id
-- 	timestamp
-- 	loc
-- );

CREATE TABLE IF NOT EXISTS UserModel (
	time_stamp	TIMESTAMP,
	u1_loc		INTEGER,
	u2_loc		INTEGER,
	u1_emotion	INTEGER,
	u2_emotion	INTEGER
);


text:
import React from 'react';
import PropTypes from 'prop-types';
import Paper from 'material-ui/Paper';
import Typography from 'material-ui/Typography';
import { withStyles } from 'material-ui/styles';
import GridRow from '../../common/grid/gridRow';
import GridColumn from '../../common/grid/gridColumn';
import PaddedContent from '../../common/paddedContent';

const messages = {
  title: 'Number Of Concept Notes to Score',
};

const styleSheet = theme => ({
  number: {
    paddingRight: theme.spacing.unit * 2,
  },
  paper: {
    height: '100%',
  },
});

const NumberOfConceptNotes = (props) => {
  const { number, classes } = props;
  return (
    <Paper className={classes.paper}>
      <PaddedContent>
        <GridRow>
          <Typography type="headline">{messages.title}</Typography>
          <GridColumn alignItems="flex-end">
            {typeof number !== 'undefined' && (
              <Typography
                key={0}
                className={classes.number}
                type="display2"
              >
                {number}
              </Typography>
            )}
          </GridColumn>
        </GridRow>
      </PaddedContent>
    </Paper>
  );
};

NumberOfConceptNotes.propTypes = {
  number: PropTypes.number,
  classes: PropTypes.object,
};

export default withStyles(styleSheet, { name: 'NumberOfConceptNotes;' })(NumberOfConceptNotes);


text:
        <form zippy="docform">

Списаие ТМЦ на потери

                        Номер документа
                        <input class="form-control" type="text" zippy="document_number" required="required">

                         Дата
                        <input class="form-control" type="text" zippy="document_date" required="required">

                        Склад
                        <select class="form-control" zippy="store">
                        </select>

                        Тип потерь
                        <select class="form-control" zippy="expenses">
                        </select>

                    Добавить ТМЦ

                            Наименование
                            Ед.изм.
                            Кол.
                            Цена
                            Сумма

                    <input type="button" value="Отменить" zippy="backtolist" class="btn btn-light  ">
                    <input zippy="savedoc" type="submit" value="Зберегти" class="btn  btn-outline-info  ">
                     <input zippy="execdoc" type="submit" value="Провести" class="btn btn-outline-info ">

        </form>
        <form zippy="editdetail">

Ввод ТМЦ

                        Наименование
                        <input placeholder="Начните вводить..." class="form-control "   zippy="edititem" />

                        Количество
                        <input class="form-control" type="text" zippy="editquantity" required="required" pattern="[0-9\.]+"
                               style="width: 70px;">

                        Цена
                        <input class="form-control" type="text" zippy="editprice" required="required" pattern="[0-9\.]+"
                               style="width: 70px;" readonly="readonly">

                        <input type="submit" zippy="submitrow" value="Сохранить" class="btn  btn-outline-info">
                          <input type="button" zippy="cancelrow" value="Отменить" class="btn  btn-light">

        </form>


text:
(function () {
    "use strict";

    /**
     * Create a new style object.
     * @class HYPER.Graphics.Style
     * @param {object} e Object to pass all style info.
     * @param {object} e.alpha=1 The alpha value to be rendered.
     * @param {object} e.color="#000000" The fill color value to be rendered.
     * @param {number} e.linecap="butt" The line cap type to be rendered.
     * @param {number} e.linejoin="miter" The line join type to be rendered.
     * @param {number} e.miterLimit=10 The miter limit to be rendered.
     * @param {number} e.strokeColor="#000000" Stroke color to be rendered.
     * @param {number} e.lineWidth=1  Line width of the line to be rendered.
     * @param {number} e.fill=true Should the graphicl objects be filled?
     * @param {number} e.stroke=false Should the graphicl objects be stroked?
     * @param {number} e.lineDashOffset=0 What should the dashed offset be?
     * @param {number} e.fontSize=12 What should the font size be?
     * @param {number} e.fontFamily="Arial" What should the font family be?
     * @param {number} e.globalCompositeOperation="source-over" Set the global compisit opperation.
     * @param {number} e.shadow Set the shadow properties.
     * @param {number} e.shadow.color="#000000" Set the shadow color.
     * @param {number} e.shadow.blur=0 Set the shadow blur.
     * @param {number} e.shadow.offsetX=0 Set the shadow offset x.
     * @param {number} e.shadow.offsetY=0 Set the shadow offset y.
     */
    HYPER.Graphics.Style = function (e) {
        e = (typeof e === 'undefined') ? {} : e;
        e.shadow = e.shadow || {};

        /**
         * @property {string} _ID - The specific ID for this object.
         */

        this._ID = "style " + Math.random() + "" + Math.random();

        /**
         * @property {string} type - What type of object this is.
         */

        this.type = "style";

        /**
         * @property {number} alpha=1 - The alpha value to be rendered.
         */

        this.alpha = (typeof e.alpha === 'undefined') ? 1 : e.alpha;

        /**
         * @property {string} color="#000000" - The fill color value to be rendered.
         */

        this.color = (typeof e.color === 'undefined') ? "#000000" : e.color;

        /**
         * @property {string} linecap="butt" - The line cap type to be rendered.
         */

        this.linecap = (typeof e.linecap === 'undefined') ? "butt" : e.linecap;

        /**
         * @property {string} linejoin="miter" - The line join type to be rendered.
         */

        this.linejoin = (typeof e.linejoin === 'undefined') ? "miter" : e.linejoin;

        /**
         * @property {number} miterLimit=10 - The miter limit to be rendered.
         */

        this.miterLimit = (typeof e.miterLimit === 'undefined') ? 10 : e.miterLimit;

        /**
         * @property {number} strokeColor="#000000" - Stroke color to be rendered.
         */

        this.strokeColor = (typeof e.strokeColor === 'undefined') ? "#000000" : e.strokeColor;

        /**
         * @property {number} lineWidth=1 - Line width of the line to be rendered.
         */

        this.lineWidth = (typeof e.lineWidth === 'undefined') ? 1 : e.lineWidth;

        /**
         * @property {boolean} fill=true - Should the graphicl objects be filled?
         */

        this.fill = (typeof e.fill === 'undefined') ? true : e.fill;

        /**
         * @property {boolean} stroke=false - Should the graphicl objects be stroked?
         */

        this.stroke = (typeof e.stroke === 'undefined') ? false : e.stroke;

        /**
         * @property {number} lineDashOffset=0 - What should the dashed offset be?
         */

        this.lineDashOffset = (typeof e.lineDashOffset === 'undefined') ? 0 : e.lineDashOffset;

        /**
         * @property {number} fontSize=12 - What should the font size be?
         */

        this.fontSize = (typeof e.fontSize === 'undefined') ? 12 : e.fontSize;

        /**
         * @property {string} fontSize="Arial" - What should the font family be?
         */

        this.fontFamily = (typeof e.fontFamily === 'undefined') ? "Arial" : e.fontFamily;

        /**
         * @property {string} globalCompositeOperation="source-over" - Set the global compisit opperation.
         */

        this.globalCompositeOperation = (typeof e.globalCompositeOperation === 'undefined') ? "source-over" : e.globalCompositeOperation;

        /**
         * @property {object} shadow - Set the shadow properties.
         */

        this.shadow = e.shadow;

        /**
         * @property {string} shadow.color="#000000" - Set the shadow color.
         */

        this.shadow.color = (typeof e.shadow.color === 'undefined') ? "#000000" : e.shadow.color;

        /**
         * @property {string} shadow.blur=0 - Set the shadow blur.
         */

        this.shadow.blur = (typeof e.shadow.blur === 'undefined') ? 0 : e.shadow.blur;

        /**
         * @property {string} shadow.offsetX=0 - Set the shadow offset x.
         */

        this.shadow.offsetX = (typeof e.shadow.offsetX === 'undefined') ? 0 : e.shadow.offsetX;

        /**
         * @property {string} shadow.offsetY=0 - Set the shadow offset y.
         */

        this.shadow.offsetY = (typeof e.shadow.offsetY === 'undefined') ? 0 : e.shadow.offsetY;

    };

    HYPER.Graphics.Style.prototype = {
        /**
         * Apply this style to any context.
         * @method HYPER.Graphics.Style.applyTo
         * @param {object} ctx Context for the style.
         */
        applyTo: function (ctx) {
            HYPER.Graphics.styleToCTX(this, ctx);
        },
    };
    /**
     * Apply a style to any context.
     * @method HYPER.Graphics.styleToCTX
     * @param {HYPER.Graphics.Style} style Style to apply.
     * @param {object} ctx Context for the style.
     */
    HYPER.Graphics.styleToCTX = function (style, ctx) {
        ctx.globalAlpha = style.alpha || 1;
        ctx.fillStyle = style.color || "#000000";
        ctx.lineCap = style.lineCap || "butt";
        ctx.linejoin = style.linejoin || "miter";
        ctx.miterLimit = style.miterLimit || 10;
        ctx.strokeStyle = style.strokeColor || "#000000";
        ctx.lineWidth = style.lineWidth || 1;
        ctx.lineDashOffset = style.lineDashOffset || 0;
        ctx.textAlign = "left";
        ctx.textBaseline = "top";
        ctx.font = style.fontSize || 12 + "px " + style.fontFamily || "Arial";
        ctx.globalCompositeOperation = style.globalCompositeOperation || "source-over";
        ctx.shadowColor = style.shadow.color || "#000000";
        ctx.shadowBlur = style.shadow.blur || 0;
        ctx.shadowOffsetX = style.shadow.offsetX || 0;
        ctx.shadowOffsetY = style.shadow.offsetY || 0;
    };
    HYPER.Graphics.DEFAULT_STYLE = new HYPER.Graphics.Style();
})();


text:
/* eslint react/no-multi-comp: 0, react/prop-types: 0 */
import React from 'react';
import { mount } from 'enzyme';
import { DropdownItem } from 'reactstrap';

describe('DropdownItem', () => {
  let isOpen;
  let toggle;

  beforeEach(() => {
    isOpen = false;
    toggle = () => isOpen = !isOpen;
  });

  it('should render a single child', () => {
    const wrapper = mount(<DropdownItem isOpen={isOpen} toggle={toggle}>Ello world</DropdownItem>);

    expect(wrapper.text()).toBe('Ello world');
    expect(wrapper.find('button').hasClass('dropdown-item')).toBe(true);
    expect(wrapper.find('button').length).toBe(1);
  });

  it('should render custom element', () => {
    const Link = (props) => {props.children};
    const wrapper = mount(<DropdownItem isOpen={isOpen} toggle={toggle} tag={Link}>Home</DropdownItem>);

    expect(wrapper.find('a').length).toBe(1);
    expect(wrapper.find('a').hasClass('dropdown-item')).toBe(true);
    expect(wrapper.text()).toBe('Home');
  });

  describe('header', () => {
    it('should render h6 tag heading', () => {
      const wrapper = mount(<DropdownItem isOpen={isOpen} toggle={toggle} header>Heading</DropdownItem>);

      expect(wrapper.find('h6').length).toBe(1);
      expect(wrapper.find('h6').hasClass('dropdown-header')).toBe(true);
      expect(wrapper.text()).toBe('Heading');
    });
  });

  describe('divider', () => {
    it('should render a divider element', () => {
      const wrapper = mount(<DropdownItem isOpen={isOpen} toggle={toggle} divider/>);

      expect(wrapper.find('.dropdown-divider').length).toBe(1);
    });
  });

  describe('onClick', () => {
    it('should not be called when disabled', () => {
      const e = { preventDefault: jasmine.createSpy('preventDefault') };
      const wrapper = mount(<DropdownItem isOpen={isOpen} toggle={toggle} disabled>Item</DropdownItem>);
      const instance = wrapper.instance();

      instance.onClick(e);
      expect(e.preventDefault).toHaveBeenCalled();
    });

    it('should not be called when divider is set', () => {
      const e = { preventDefault: jasmine.createSpy('preventDefault') };
      const wrapper = mount(<DropdownItem isOpen={isOpen} toggle={toggle} divider/>);
      const instance = wrapper.instance();

      instance.onClick(e);
      expect(e.preventDefault).toHaveBeenCalled();
    });

    it('should not be called when header item', () => {
      const e = { preventDefault: jasmine.createSpy('preventDefault') };
      const wrapper = mount(<DropdownItem isOpen={isOpen} toggle={toggle} header>Header</DropdownItem>);
      const instance = wrapper.instance();

      instance.onClick(e);
      expect(e.preventDefault).toHaveBeenCalled();
    });

    it('should be called when not disabled, heading, or divider', () => {
      const e = { preventDefault: jasmine.createSpy('preventDefault') };
      const onClick = jasmine.createSpy('onClick');
      const wrapper = mount(<DropdownItem isOpen={isOpen} toggle={toggle} onClick={onClick.bind(this)}>Click me</DropdownItem>);
      const instance = wrapper.instance();

      instance.onClick(e);
      expect(onClick).toHaveBeenCalled();
    });

    it('should call toggle', () => {
      isOpen = true;
      let props = jasmine.createSpyObj('props', ['toggle']);
      const wrapper = mount(<DropdownItem isOpen={isOpen} toggle={props.toggle}>Click me</DropdownItem>);

      wrapper.simulate('click');
      expect(props.toggle).toHaveBeenCalled();
    });
  });
});


text:
if [ $# = 0 ];
then
    echo "please input boot port number.for example 2012";
    exit
fi
#current_path example /opt/modules/daemon
current_path=`pwd`;
jdk_bin="jdk.bin";
jdk_bin_path=$current_path"/"$jdk_bin;
java_home=$current_path"/jdk1.6.0_30";
echo "please input the cronhub center server's ip..."
read center_server_ip;
echo "please input the cronhub center server's port..."
read center_server_port;
base_url="http://${center_server_ip}:${center_server_port}/download/";
jdk_download_url=$base_url"jdk-6u30-linux-x64.bin"
jsvc_zip="jsvc.zip";
jsvc_dir="jsvc";
jsvc_url=$base_url$jsvc_zip;
jar_name="DispatchSystemDaemon.jar";
daemon_url=$base_url$jar_name;
daemon_jar_path=$current_path"/"$jar_name;
jsvc_dir=$current_path"/"$jsvc_dir;
jsvc_target_bin=$jsvc_dir"/jsvc";

#install jdk
if [ ! -e $jdk_bin_path ];
then
    wget $jdk_download_url -O $jdk_bin_path;
    chmod 755 $jdk_bin_path;
    $jdk_bin_path;
fi;

#install jsvc
if [ ! -e $current_path"/"$jsvc_zip ];
then
    wget $jsvc_url;
fi
if [[ -e $current_path"/"$jsvc_zip && ! -e $jsvc_target_bin ]];
then
    unzip $jsvc_zip;
fi;
if [ ! -e $jsvc_target_bin ];
then
    cd $jsvc_dir;
    chmod +x configure;
    chmod +x make;
    ./configure --with-java=$java_home;
    make;
    cd $current_path;
fi;

#install daemon jar
if [ ! -e $daemon_jar_path ];
then
    wget $daemon_url;
fi;
ps_num=`ps -ef|grep $jar_name|grep $1|grep -v grep|grep -v sh|wc -l`;
if [ $ps_num -gt 0 ];
then
    kill_pid=`ps -ef|grep $jar_name|grep $1|grep -v grep|grep -v sh|awk -F ' ' '{print $2}'`;
    echo "kill  "$kill_pid" .process numer is "$ps_num;
    kill $kill_pid;
    echo "killing service to reboot service...";
    sleep 2;
fi;
cmd="$jsvc_target_bin -home $java_home -Xmx2000m -pidfile $current_path/$1.pid -cp $daemon_jar_path com.baofeng.dispatchexecutor.boot.DaemonBoot -p $1";
echo -e "#description:dispatch_daemon
#chkconfig:231 80 80
case \"\$1\" in
start)
\t${current_path}/jsvc/jsvc -home ${current_path}/jdk1.6.0_30 -Xmx2000m -pidfile ${current_path}/$1.pid -cp ${current_path}/DispatchSystemDaemon.jar com.baofeng.dispatchexecutor.boot.DaemonBoot -p $1
\t;;
esac
" > /etc/init.d/dispatch_daemon
/sbin/chkconfig --add dispatch_daemon
chmod +x /etc/init.d/dispatch_daemon
/sbin/service dispatch_daemon start
#the final start cmd
#$jsvc_target_bin -home $java_home -Xmx2000m -pidfile $current_path"/"$1".pid" -cp $daemon_jar_path com.baofeng.dispatchexecutor.boot.DaemonBoot -p $1


text:
import { Farmbot } from "farmbot";
import { devices } from "../device";
import { error, success } from "../ui";
import { Everything } from "../interfaces";
import { GithubRelease, ChangeSettingsBuffer } from "./interfaces";
import { ReduxAction, Thunk } from "../redux/interfaces";
import { put, get } from "axios";
import {
    DeviceAccountSettingsUpdate,
    DeviceAccountSettings,
    BotState
} from "../devices/interfaces";
import { t } from "i18next";
import { configKey, Configuration } from "farmbot/dist/interfaces";
import { MovementRequest } from "farmbot/dist/bot_commands";
import { Notification } from "farmbot/dist/jsonrpc";
import { Sequence } from "../sequences/interfaces";
import { handleIncomingBotNotification } from "./incoming_bot_notification";
import { Regimen } from "../regimens/interfaces";
import * as _ from "lodash";
import { API } from "../api";

const ON = 1, OFF = 0;

export function startRegimen(regimen: Regimen) {
    let noun = "Start Regimen";
    if (regimen.id != undefined) {
        devices
            .current
            .startRegimen(regimen.id)
            .then(() => { commandOK(noun); })
            .catch(() => { commandErr(noun); });
    }
}

export function stopRegimen(regimen: Regimen) {
    let noun = "Stop Regimen";
    if (regimen.id != undefined) {
        devices
            .current
            .stopRegimen(regimen.id)
            .then(() => { commandOK(noun); })
            .catch(() => { commandErr(noun); });
    }
}

export function updateConfig(config: Configuration) {
    let noun = "Update Config";
    devices
        .current
        .updateConfig(config)
        .then(() => { commandOK(noun); })
        .catch(() => { commandErr(noun); });
}

export function checkControllerUpdates() {
    let noun = "Check for Updates";
    devices
        .current
        .checkUpdates()
        .then(commandOK(noun), commandErr(noun));
}

export function powerOff() {
    let noun = "Power Off Bot";
    devices
        .current
        .powerOff()
        .then(commandOK(noun), commandErr(noun));
}

export function reboot() {
    let noun = "Reboot Bot";
    devices
        .current
        .reboot()
        .then(commandOK(noun), commandErr(noun));
}

export function checkArduinoUpdates() {
    let noun = "Check Firmware Updates";
    devices
        .current
        .checkArduinoUpdates()
        .then(commandOK(noun), commandErr(noun));
}

export function emergencyLock() {
    let noun = "Emergency stop";
    devices
        .current
        .emergencyLock()
        .then(commandOK(noun), commandErr(noun));
}

export function emergencyUnlock() {
    let noun = "Emergency unlock";
    devices
        .current
        .emergencyUnlock()
        .then(commandOK(noun), commandErr(noun));
}

export function sync(): Thunk {
    let noun = "Sync";
    return function (dispatch, getState) {
        devices
            .current
            .sync()
            .then(() => {
                commandOK(noun);
                dispatch({ type: "BOT_SYNC_OK", payload: {} });
            }).catch(() => {
                commandErr(noun);
            });
    };
}

export function execSequence(sequence: Sequence) {
    const noun = "Sequence execution";
    console.warn("Fix this / remove any type here!");
    return devices
        .current
        .execSequence(sequence as any)
        .then(commandOK(noun), commandErr(noun));
}

export let saveAccountChanges: Thunk = function (dispatch, getState) {
    let state = getState();
    let bot = getState().bot.account;
    let url = API.current.baseUrl;
    return updateDevice(url, bot, dispatch);
};

let commandErr = (noun = "Command") => () => {
    let msg = noun + " request failed.";
    error(msg, t("Farmbot Didn't Get That!"));
};

let commandOK = (noun = "Command") => () => {
    let msg = noun + " request sent to device.";
    success(msg, t("Request sent"));
};

export function fetchOSUpdateInfo(url: string): Thunk {
    return (dispatch: Function, getState: Function) => {
        get<GithubRelease>(url)
            .then((resp) => {
                let version = resp.data.tag_name;
                let versionWithoutV = version.slice(1, version.length);
                dispatch({
                    type: "FETCH_OS_UPDATE_INFO_OK",
                    payload: versionWithoutV
                });
            })
            .catch((ferror) => {
                error(t("Could not download OS update information."));
                dispatch({
                    type: "FETCH_OS_UPDATE_INFO_ERROR",
                    payload: ferror
                });
            });
    };
}

export function fetchFWUpdateInfo(url: string) {
    return (dispatch: Function, getState: Function) => {
        get<GithubRelease>(url)
            .then((resp) => {
                let version = resp.data.tag_name;
                let versionWithoutV = version.slice(1, version.length);
                dispatch({
                    type: "FETCH_FW_UPDATE_INFO_OK",
                    payload: versionWithoutV
                });
            })
            .catch((ferror) => {
                error(t("Could not download firmware update information."));
                dispatch({
                    type: "FETCH_FW_UPDATE_INFO_ERROR",
                    payload: ferror
                });
            });
    };
}

export function updateDevice(apiUrl: string,
    optns: DeviceAccountSettingsUpdate, dispatch: Function) {
    let url = API.current.devicePath;
    return put<DeviceAccountSettingsUpdate>(url, optns)
        .then(res => dispatch({
            type: "REPLACE_DEVICE_ACCOUNT_INFO",
            payload: res.data
        }))
        .catch((payload) => dispatch({ type: "DEVICE_ACCOUNT_ERR", payload }));
    ;
}

export function changeDevice(newAttrs: any) {
    // Flips the "dirty" flag to true.
    return {
        type: "CHANGE_DEVICE",
        payload: newAttrs
    };
}

export function addDevice(deviceAttrs: DeviceAccountSettings): Thunk {
    return (dispatch, getState) => {
        updateDevice(API.current.baseUrl, deviceAttrs, dispatch);
    };
}

export function settingToggle(name: configKey, bot: BotState) {
    // TODO : This should be an atomic operation handled at the bot level
    // as a lower level command.
    const noun = "Setting toggle";
    return devices
        .current
        .updateMcu({
            [name]: ((bot.hardware.mcu_params as any)[name] === 0) ? ON : OFF
        })
        .then(commandOK(noun), commandErr(noun));
};

export function moveRelative(props: MovementRequest) {
    const noun = "Relative movement";
    return devices
        .current
        .moveRelative(props)
        .then(commandOK(noun), commandErr(noun));
}

export function pinToggle(pin_number: number) {
    const noun = "Setting toggle";
    return devices
        .current
        .togglePin({ pin_number })
        .then(commandOK(noun), commandErr(noun));
}

export function homeAll(speed: number) {
    let noun = "'Home All' command";
    devices
        .current
        .homeAll({ speed })
        .then(commandOK(noun), commandErr(noun));
}

export function readStatus() {
    let noun = "'Read Status' command";
    return devices
        .current
        .readStatus()
        .then(() => {
            commandOK(noun);
        })
        .catch(commandErr(noun));
}

export function connectDevice(token: string): {} | ((dispatch: any) => any) {
    return (dispatch) => {
        let bot = new Farmbot({ token });
        return bot
            .connect()
            .then(() => {
                devices.current = bot;
                readStatus();
                dispatch(sync());
                bot.on("notification",
                    (msg: Notification<any>) => {
                        handleIncomingBotNotification(msg, dispatch);
                    });
            }, (err) => dispatch(fetchDeviceErr(err)));
    };
};

function fetchDeviceErr(err: Error) {
    return {
        type: "FETCH_DEVICE_ERR",
        payload: err
    };
}

export function changeSettingsBuffer(key: configKey, val: string):
    ReduxAction<ChangeSettingsBuffer> {

    return {
        type: "CHANGE_SETTINGS_BUFFER",
        payload: { key, val: parseInt(val, 10) }
    };
}

export function changeConfigBuffer(config: Configuration):
    ReduxAction<Configuration> {
    return {
        type: "CHANGE_CONFIG_BUFFER",
        payload: config
    };
}

export function changeStepSize(integer: number) {
    return {
        type: "CHANGE_STEP_SIZE",
        payload: integer
    };
}

export function commitAxisChanges() {
    return function (
        dispatch: Function,
        getState: () => Everything) {
        let {axisBuffer, hardware} = getState().bot;
        let speed: number = devices.current.getState()["speed"] as number;
        /** Pick the value in axisBuffer or hardware settings dictionary.
         *  axisBuffer has higher priortiy, but may not be available. */
        function pick(attr: string,
            fallback?: number) {
            return Number(axisBuffer[attr] ||
                (hardware as any)[attr] || fallback);
        };
        let packet: MovementRequest = {
            speed: pick("speed", speed),
            x: pick("x", 0),
            y: pick("y", 0),
            z: pick("z", 0),
        };
        let noun = "Move Absolute Command";
        return devices
            .current
            .moveAbsolute(packet)
            .then(commandOK(noun), commandErr(noun));
    };
}

export function commitSettingsChanges() {
    return function (dispatch: Function,
        getState: () => Everything) {
        let { settingsBuffer, configBuffer, hardware } = getState().bot;
        let mcuPacket = _({})
            .assign(hardware.mcu_params)
            .assign(settingsBuffer)
            .value();
        let configPacket = _({})
            .assign(hardware.configuration)
            .assign(configBuffer)
            .value();
        Promise.all([
            devices.current.updateMcu(mcuPacket),
            devices.current.updateConfig(configPacket)
        ]).then(() => {
            dispatch(commitSettingsChangesOk());
        }).catch(() => {
            commandErr("Commit Settings Change");
        });
    };
}

function commitSettingsChangesOk() {
    return {
        type: "COMMIT_SETTINGS_OK",
        payload: {}
    };
}

export function changeAxisBuffer(key: string, val: number) {
    return {
        type: "CHANGE_AXIS_BUFFER",
        payload: { key, val }
    };
}

export function clearLogs(): Thunk {
    return function (dispatch, getState) {
        dispatch({ type: "CLEAR_BOT_LOG", payload: {} });
    };
}


text:
var page = require('webpage').create();
var server = require('webserver').create();
var system = require('system');
var host, port;

if (system.args.length !== 2) {
    console.log('Usage: server.js <some port>');
    phantom.exit(1);
} else {
    port = system.args[1];
    var listening = server.listen(port, function (request, response) {
        console.log("GOT HTTP REQUEST");
        console.log(JSON.stringify(request, null, 4));

        // we set the headers here
        response.statusCode = 200;
        response.headers = {"Cache": "no-cache", "Content-Type": "text/html"};
        // this is also possible:
        response.setHeader("foo", "bar");
        // now we write the body
        // note: the headers above will now be sent implictly
        response.write("<title>YES!</title>");
        // note: writeBody can be called multiple times
        response.write("
pretty cool :)");
        response.close();
    });
    if (!listening) {
        console.log("could not create web server listening on port " + port);
        phantom.exit();
    }
    var url = "http://localhost:" + port + "/foo/bar.php?asdf=true";
    console.log("SENDING REQUEST TO:");
    console.log(url);
    page.open(url, function (status) {
        if (status !== 'success') {
            console.log('FAIL to load the address');
        } else {
            console.log("GOT REPLY FROM SERVER:");
            console.log(page.content);
        }
        phantom.exit();
    });
}


text:
#ifndef VRSCAN_H
#define VRSCAN_H

#include "dcmtk/config/osconfig.h"    /* make sure OS specific configuration is included first */

#include "dcmtk/ofstd/ofstring.h"

class vrscan
{
public:
    static int scan(const OFString& vr, const OFString& value);
private:
    static char* makeBuffer(const OFString& vr, const OFString& value, size_t& size);
};

#endif // VRSCAN_H

/*
** CVS/RCS Log:
** $Log: vrscan.h,v $
** Revision 1.5  2010-10-14 13:15:43  joergr
** Updated copyright header. Added reference to COPYRIGHT file.
**
** Revision 1.4  2010-09-02 10:16:02  uli
** The VR scanner now only copies the input data once, not twice.
**
** Revision 1.3  2010-09-02 09:49:38  uli
** Add the VR prefix into the scanner instead of adding it in the caller.
**
** Revision 1.2  2010-08-26 12:29:47  uli
** Ported vrscan from ancient flex++ to current flex version.
**
**
*/


text:
<?php
include('server/php-image-magician/php_image_magician.php');
//$target_dir = "uploads/";
if(isset($_POST['target_dir'])) $target_dir=$_POST['target_dir'];
if(isset($_POST['target_name'])) $target_name=$_POST['target_name'];
if(isset($_POST['image_type'])) $image_type=$_POST['image_type'];
if(isset($_POST['currentURL'])) $currentURL=$_POST['currentURL'];

//$target_dir = ($target_dir);
echo "Target Directory: ". $target_dir;
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
// Check if file already exists
//if (file_exists($target_file)) {
//    echo "Sorry, file already exists.";
//    //$uploadOk = 0;
//}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 5000000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_dir.$target_name)) {

        if ($image_type=="asset_shot_cover"){
          $magicianObj = new imageLib($target_dir.$target_name);
          $magicianObj -> resizeImage(320, 180, 4);
          $magicianObj -> saveImage($target_dir.$target_name, 95);
        }
        if ($image_type=="project_cover"){
          $magicianObj = new imageLib($target_dir.$target_name);
          //$magicianObj -> resizeImage(1920, 1920, 4);
          //$magicianObj -> saveImage($target_dir.$target_name, 100);
          $magicianObj -> resizeImage(1920, 300, array('crop', 'tr'), false);
          $magicianObj -> saveImage($target_dir.$target_name, 95);
        }
        if ($image_type=="project_thumbnail"){
          $magicianObj = new imageLib($target_dir.$target_name);
          $magicianObj -> resizeImage(320, 180, 4);
          $magicianObj -> saveImage($target_dir.$target_name, 95);
        }
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
        //header("Location:".$currentURL);
        //header("Refresh:0");
        //header("Refresh:0; url=".$currentURL);
    } else {
        echo "Sorry, there was an error uploading your file.";
        echo "Target was ".$target_dir.$target_name;
    }
}
?>


text:
package com.amazonaws.services.elasticmapreduce.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * Specifies the execution engine (cluster) to run the notebook and perform the notebook execution, for example, an EMR
 * cluster.
 *

 *
 * @see AWS API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ExecutionEngineConfig implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * The unique identifier of the execution engine. For an EMR cluster, this is the cluster ID.
     *

     */
    private String id;
    /**
     *

     * The type of execution engine. A value of EMR specifies an EMR cluster.
     *

     */
    private String type;
    /**
     *

     * An optional unique ID of an EC2 security group to associate with the master instance of the EMR cluster for this
     * notebook execution. For more information see Specifying EC2 Security Groups for EMR Notebooks in the EMR Management Guide.
     *

     */
    private String masterInstanceSecurityGroupId;

    /**
     *

     * The unique identifier of the execution engine. For an EMR cluster, this is the cluster ID.
     *

     *
     * @param id
     *        The unique identifier of the execution engine. For an EMR cluster, this is the cluster ID.
     */

    public void setId(String id) {
        this.id = id;
    }

    /**
     *

     * The unique identifier of the execution engine. For an EMR cluster, this is the cluster ID.
     *

     *
     * @return The unique identifier of the execution engine. For an EMR cluster, this is the cluster ID.
     */

    public String getId() {
        return this.id;
    }

    /**
     *

     * The unique identifier of the execution engine. For an EMR cluster, this is the cluster ID.
     *

     *
     * @param id
     *        The unique identifier of the execution engine. For an EMR cluster, this is the cluster ID.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ExecutionEngineConfig withId(String id) {
        setId(id);
        return this;
    }

    /**
     *

     * The type of execution engine. A value of EMR specifies an EMR cluster.
     *

     *
     * @param type
     *        The type of execution engine. A value of EMR specifies an EMR cluster.
     * @see ExecutionEngineType
     */

    public void setType(String type) {
        this.type = type;
    }

    /**
     *

     * The type of execution engine. A value of EMR specifies an EMR cluster.
     *

     *
     * @return The type of execution engine. A value of EMR specifies an EMR cluster.
     * @see ExecutionEngineType
     */

    public String getType() {
        return this.type;
    }

    /**
     *

     * The type of execution engine. A value of EMR specifies an EMR cluster.
     *

     *
     * @param type
     *        The type of execution engine. A value of EMR specifies an EMR cluster.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see ExecutionEngineType
     */

    public ExecutionEngineConfig withType(String type) {
        setType(type);
        return this;
    }

    /**
     *

     * The type of execution engine. A value of EMR specifies an EMR cluster.
     *

     *
     * @param type
     *        The type of execution engine. A value of EMR specifies an EMR cluster.
     * @return Returns a reference to this object so that method calls can be chained together.
     * @see ExecutionEngineType
     */

    public ExecutionEngineConfig withType(ExecutionEngineType type) {
        this.type = type.toString();
        return this;
    }

    /**
     *

     * An optional unique ID of an EC2 security group to associate with the master instance of the EMR cluster for this
     * notebook execution. For more information see Specifying EC2 Security Groups for EMR Notebooks in the EMR Management Guide.
     *

     *
     * @param masterInstanceSecurityGroupId
     *        An optional unique ID of an EC2 security group to associate with the master instance of the EMR cluster
     *        for this notebook execution. For more information see Specifying EC2 Security Groups for EMR Notebooks in the EMR Management Guide.
     */

    public void setMasterInstanceSecurityGroupId(String masterInstanceSecurityGroupId) {
        this.masterInstanceSecurityGroupId = masterInstanceSecurityGroupId;
    }

    /**
     *

     * An optional unique ID of an EC2 security group to associate with the master instance of the EMR cluster for this
     * notebook execution. For more information see Specifying EC2 Security Groups for EMR Notebooks in the EMR Management Guide.
     *

     *
     * @return An optional unique ID of an EC2 security group to associate with the master instance of the EMR cluster
     *         for this notebook execution. For more information see Specifying EC2 Security Groups for EMR Notebooks in the EMR Management Guide.
     */

    public String getMasterInstanceSecurityGroupId() {
        return this.masterInstanceSecurityGroupId;
    }

    /**
     *

     * An optional unique ID of an EC2 security group to associate with the master instance of the EMR cluster for this
     * notebook execution. For more information see Specifying EC2 Security Groups for EMR Notebooks in the EMR Management Guide.
     *

     *
     * @param masterInstanceSecurityGroupId
     *        An optional unique ID of an EC2 security group to associate with the master instance of the EMR cluster
     *        for this notebook execution. For more information see Specifying EC2 Security Groups for EMR Notebooks in the EMR Management Guide.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public ExecutionEngineConfig withMasterInstanceSecurityGroupId(String masterInstanceSecurityGroupId) {
        setMasterInstanceSecurityGroupId(masterInstanceSecurityGroupId);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getId() != null)
            sb.append("Id: ").append(getId()).append(",");
        if (getType() != null)
            sb.append("Type: ").append(getType()).append(",");
        if (getMasterInstanceSecurityGroupId() != null)
            sb.append("MasterInstanceSecurityGroupId: ").append(getMasterInstanceSecurityGroupId());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof ExecutionEngineConfig == false)
            return false;
        ExecutionEngineConfig other = (ExecutionEngineConfig) obj;
        if (other.getId() == null ^ this.getId() == null)
            return false;
        if (other.getId() != null && other.getId().equals(this.getId()) == false)
            return false;
        if (other.getType() == null ^ this.getType() == null)
            return false;
        if (other.getType() != null && other.getType().equals(this.getType()) == false)
            return false;
        if (other.getMasterInstanceSecurityGroupId() == null ^ this.getMasterInstanceSecurityGroupId() == null)
            return false;
        if (other.getMasterInstanceSecurityGroupId() != null
                && other.getMasterInstanceSecurityGroupId().equals(this.getMasterInstanceSecurityGroupId()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getId() == null) ? 0 : getId().hashCode());
        hashCode = prime * hashCode + ((getType() == null) ? 0 : getType().hashCode());
        hashCode = prime * hashCode + ((getMasterInstanceSecurityGroupId() == null) ? 0 : getMasterInstanceSecurityGroupId().hashCode());
        return hashCode;
    }

    @Override
    public ExecutionEngineConfig clone() {
        try {
            return (ExecutionEngineConfig) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.elasticmapreduce.model.transform.ExecutionEngineConfigMarshaller.getInstance().marshall(this, protocolMarshaller);
    }
}


text:
package com.thoughtworks.go.server.service;

import com.thoughtworks.go.config.CaseInsensitiveString;
import com.thoughtworks.go.config.JobConfig;
import com.thoughtworks.go.config.PipelineConfig;
import com.thoughtworks.go.config.StageConfig;
import com.thoughtworks.go.config.elastic.ClusterProfile;
import com.thoughtworks.go.config.elastic.ElasticProfile;
import com.thoughtworks.go.config.exceptions.StageNotFoundException;
import com.thoughtworks.go.domain.*;
import com.thoughtworks.go.domain.buildcause.BuildCause;
import com.thoughtworks.go.util.Clock;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class InstanceFactory {

    public Pipeline createPipelineInstance(PipelineConfig pipelineConfig, BuildCause buildCause, SchedulingContext context, String md5, Clock clock) {
        buildCause.assertMaterialsMatch(pipelineConfig.materialConfigs());
        buildCause.assertPipelineConfigAndMaterialRevisionMatch(pipelineConfig);

        EnvironmentVariables variables = EnvironmentVariables.toEnvironmentVariables(pipelineConfig.getVariables());
        variables.overrideWith(buildCause.getVariables());

        return new Pipeline(CaseInsensitiveString.str(pipelineConfig.name()), pipelineConfig.getLabelTemplate(), buildCause, variables, createStageInstance(pipelineConfig.first(), context, md5, clock));
    }

    public Stage createStageInstance(PipelineConfig pipelineConfig, CaseInsensitiveString stageName, SchedulingContext context, String md5, Clock clock) {
        StageConfig stageConfig = pipelineConfig.findBy(stageName);
        if (stageConfig == null) {
            throw new StageNotFoundException(pipelineConfig.name(), stageName);
        }
        return createStageInstance(stageConfig, context, md5, clock);
    }

    public Stage createStageInstance(StageConfig stageConfig, SchedulingContext context, String md5, Clock clock) {
        return new Stage(CaseInsensitiveString.str(stageConfig.name()), createJobInstances(stageConfig, context, clock),
                context.getApprovedBy(), null, stageConfig.approvalType(), stageConfig.isFetchMaterials(), stageConfig.isCleanWorkingDir(), md5, clock);
    }

    public Stage createStageForRerunOfJobs(Stage stage, List<String> jobNames, SchedulingContext context, StageConfig stageConfig, Clock clock, String latestMd5) {
        Stage newStage = stage.createClone();
        newStage.prepareForRerunOf(context, latestMd5);
        createRerunJobs(newStage, jobNames, context, stageConfig, clock);
        return newStage;
    }

    public JobInstances createJobInstance(CaseInsensitiveString stageName, JobConfig jobConfig, SchedulingContext context, Clock clock, JobType.JobNameGenerator jobNameGenerator) {
        JobInstances instances = new JobInstances();
        createJobType(jobConfig.isRunOnAllAgents(), jobConfig.isRunMultipleInstanceType()).createJobInstances(instances, context, jobConfig, CaseInsensitiveString.str(stageName), jobNameGenerator, clock, this);
        return instances;
    }

    private JobInstances createJobInstances(StageConfig stageConfig, SchedulingContext context, Clock clock) {
        JobInstances instances = new JobInstances();
        for (JobConfig jobConfig : stageConfig.getJobs()) {
            JobType.JobNameGenerator nameGenerator = null;
            if (jobConfig.isRunOnAllAgents()) {
                nameGenerator = new RunOnAllAgents.CounterBasedJobNameGenerator(CaseInsensitiveString.str(jobConfig.name()));
            } else if (jobConfig.isRunMultipleInstanceType()) {
                nameGenerator = new RunMultipleInstance.CounterBasedJobNameGenerator(CaseInsensitiveString.str(jobConfig.name()));
            }
            JobInstances configInstances = createJobInstance(stageConfig.name(), jobConfig, context, clock, nameGenerator);
            instances.addAll(configInstances);
        }
        return instances;
    }

    private void createRerunJobs(Stage newStage, List<String> jobNames, SchedulingContext context, StageConfig stageConfig, Clock clock) {
        for (String jobName : jobNames) {
            JobInstances jobInstances = newStage.getJobInstances();
            JobInstance oldJob = jobInstances.getByName(jobName);
            jobInstances.remove(oldJob);
            createJobType(oldJob.isRunOnAllAgents(), oldJob.isRunMultipleInstance()).createRerunInstances(oldJob, jobInstances, context, stageConfig, clock, this);
        }
    }

    private JobType createJobType(boolean runOnAllAgents, boolean runMultipleInstances) {
        if (runOnAllAgents) {
            return new RunOnAllAgents();
        }
        if (runMultipleInstances) {
            return new RunMultipleInstance();
        }
        return new SingleJobInstance();
    }

    public void reallyCreateJobInstance(JobConfig config, JobInstances jobs, String uuid, String jobName, boolean runOnAllAgents, boolean runMultipleInstance, SchedulingContext context, final Clock clock) {
        JobInstance instance = new JobInstance(jobName, clock);
        instance.setPlan(createJobPlan(config, context));
        instance.setAgentUuid(uuid);
        instance.setRunOnAllAgents(runOnAllAgents);
        instance.setRunMultipleInstance(runMultipleInstance);
        jobs.add(instance);
    }

    public JobPlan createJobPlan(JobConfig config, SchedulingContext context) {
        JobIdentifier identifier = new JobIdentifier();
        String elasticProfileId = config.getElasticProfileId();
        String clusterProfileId = null;
        ElasticProfile elasticProfile = null;
        ClusterProfile clusterProfile = null;

        if (elasticProfileId != null) {
            elasticProfile = context.getElasticProfile(elasticProfileId);
            clusterProfileId = elasticProfile.getClusterProfileId();
        }

        if (clusterProfileId != null) {
            clusterProfile = context.getClusterProfile(clusterProfileId);
        }

        final EnvironmentVariables variables = EnvironmentVariables.toEnvironmentVariables(context.overrideEnvironmentVariables(config.getVariables()).getEnvironmentVariablesConfig());

        return new DefaultJobPlan(new Resources(config.resourceConfigs()),
                ArtifactPlan.toArtifactPlans(config.artifactConfigs()),
                ArtifactPropertiesGenerator.toArtifactProperties(config.getProperties()), -1, identifier, null, variables, new EnvironmentVariables(), elasticProfile, clusterProfile);
    }
}