text:
% The JPMExpManager is a modified version of ExpManager to use with JPM
% Experiments.

% Author/Date : Caleb Howington / Oct 2015

% Copyright 2013 Raytheon BBN Technologies
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
%     http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.

classdef JPMExpManager < handle
    properties
        dataFileHandler
        instruments = struct();
        instrSettings = struct();
        measurements = struct();
        sweeps = {}
        sweep_callbacks = {}
        data = struct();
        scopes
        AWGs
        listeners = {}
        plotScopeTimer
        CWMode = false
        saveVariances = false
        dataFileHeader = struct();
        dataTimeout = 60 % timeout in seconds
        saveAllSettings = true;
    end

    methods
        %Constructor
        function obj = JPMExpManager()
        end

        %Destructor
        function delete(obj)
            % turn off uW sources
            function turn_uwave_off(instr)
                if isa(instr, 'deviceDrivers.lib.uWSource')
                    instr.output = 0;
                end
            end
            structfun(@turn_uwave_off, obj.instruments);

            %If we botched something and ctrl-c'd out then mark the file as
            %incomplete
            if isa(obj.dataFileHandler, 'JPMDataHandler') && obj.dataFileHandler.fileOpen == 1
                obj.dataFileHandler.close();
                obj.dataFileHandler.markAsIncomplete();
            end

            %clean up DataReady listeners and plot timer
            cellfun(@delete, obj.listeners);
            delete(obj.plotScopeTimer);
            fprintf('JPMExpManager Finished!\n');
        end

        %Initialize
        function init(obj)

            %For initialize each instrument via setAll()
            instrNames = fieldnames(obj.instruments);
            for instr = instrNames'
                instrName= instr{1};
                instrHandle = obj.instruments.(instrName);
                instrHandle.setAll(obj.instrSettings.(instrName));
                % keep track of digitizers and AWGs
                if obj.is_scope(instrHandle)
                    obj.scopes{end+1} = instrHandle;
                end
                if obj.is_AWG(instrHandle)
                    obj.AWGs{end+1} = instrHandle;
                    if obj.instrSettings.(instrName).isMaster
                        masterAWGIndex = length(obj.AWGs);
                    end
                end
            end

            %Rearrange the AWG list to put the Master first
            obj.AWGs([1, masterAWGIndex]) = obj.AWGs([masterAWGIndex, 1]);

            %Stop all the AWGs if not in CWMode
            if(~obj.CWMode)
                cellfun(@(awg) stop(awg), obj.AWGs);
            else
                cellfun(@(awg) run(awg), obj.AWGs);
            end

            if ~isempty(obj.dataFileHandler)
                %Construct data file header and info structs
                labels = cellfun(@(s) s.axisLabel, obj.sweeps, 'UniformOutput', false);
                xyz = {'x', 'y', 'z'};
                points = cellfun(@(s) s.points, obj.sweeps, 'UniformOutput', false);
                dataInfo = struct();
                for ct = 1:length(obj.sweeps)
                    xyzIdx = length(obj.sweeps)-ct+1;
                    dataInfo.([xyz{xyzIdx}, 'label']) = labels{ct};
                    dataInfo.([xyz{xyzIdx}, 'points']) = points{ct};
                end
                dataInfo.dimension = length(obj.sweeps);
                % add measurement names to dataInfo structs
                measNames = fieldnames(obj.measurements);
                dataInfos = {};
                for ct = 1:length(measNames)
                    if obj.measurements.(measNames{ct}).saved
                        dataInfos{end+1} = dataInfo;
                        dataInfos{end}.name = measNames{ct};
                    end
                end
                %Open data file
                obj.dataFileHandler.open(obj.dataFileHeader, dataInfos);
            end

        end

        function connect_meas_to_source(obj, meas)
            instrNames = fieldnames(obj.instruments);
            function connect_to_source(meas, src)
                %First look for an instrument (scope)
                if (~isempty(find(strcmp(src, instrNames))))
                    obj.listeners{end+1} = addlistener(obj.instruments.(src), 'DataReady', @meas.apply);
                %Otherwise assume another measurement
                else
                    obj.listeners{end+1} = addlistener(obj.measurements.(src), 'DataReady', @meas.apply);
                end
            end
            %Correlators have mulitple sources
            if isa(meas, 'MeasFilters.Correlator')
                cellfun(@(x) connect_to_source(meas, x), strsplit(meas.dataSource, ','))
            else
                connect_to_source(meas, meas.dataSource);
            end
        end

        %Runner
        function run(obj)
            %Connect a polling scope plotter
            obj.plotScopeTimer = timer('TimerFcn', @obj.plot_scope_callback, 'StopFcn', @obj.plot_scope_callback, 'Period', 0.5, 'ExecutionMode', 'fixedSpacing');

            %Connect measurement consumers to producers
            structfun(@(x) obj.connect_meas_to_source(x), obj.measurements);

            %Set the cleanup function so that even if we ctrl-c out we
            %correctly cleanup
            c = onCleanup(@() obj.cleanUp());

            %Start the plot timer
            start(obj.plotScopeTimer);

            %Loop over all the sweeps
            idx = 1;
            ct = zeros(1, length(obj.sweeps));
            stops = cellfun(@(x) x.numSteps, obj.sweeps);
            sizes = cellfun(@(x) length(x.points), obj.sweeps);
            if length(sizes) == 1
                sizes = [sizes 1];
            end
            % initialize data storage
            obj.data = structfun(@(x) struct('counts', nan(sizes)), obj.measurements, 'UniformOutput', false );

            fprintf('Taking data....\n');

            % generic nested loop sweeper through "stack"
            while idx > 0 && ct(1) <= stops(1)

                if ct(idx) < stops(idx)
                    ct(idx) = ct(idx) + 1;
                    if stops(idx) > 1
                        % print one status message on the inner sweep
                        if idx == length(stops)
                            if ct(idx) == 1
                              fprintf('Stepping sweep %d: %d points       ', idx, stops(idx));
                            else
                              fprintf('\b\b\b\b\b\b(%3d%%)',round(100*ct(idx)/stops(idx)));
                            end
                            if ct(idx) == stops(idx)
                                fprintf('\n');
                            end
                        elseif idx < length(stops)
                            fprintf('Stepping sweep %d: %d of %d\n', idx, ct(idx), stops(idx));
                        end
                    end
                    obj.sweeps{idx}.step(ct(idx));
                    if ~isempty(obj.sweep_callbacks{idx})
                        feval(obj.sweep_callbacks{idx}, obj);
                    end
                    if idx < length(ct)
                        idx = idx + 1;
                    else % inner most loop... take data

                        obj.take_data();
                        % pull data out of measurements
                        stepData = structfun(@(m) m.get_data(), obj.measurements, 'UniformOutput', false);
                        for measName = fieldnames(stepData)'
                            if ~obj.measurements.(measName{1}).saved
                                continue
                            end
                            if isa(obj.sweeps{end}, 'sweeps.SegmentNum')
                                % we are sweeping segment number, so we
                                % have an entire row of data
                                % what we want to do is:
                                % obj.data.(measNames{ct})(ct(1), ct(2), ..., ct(n-1), :) = stepData{ct};
                                % lacking an idiomatic way to build the generic
                                % assignment, we manually call subsasgn
                                indexer = struct('type', '()', 'subs', {[num2cell(ct(1:end-1)), ':']});
                                obj.data.(measName{1}).counts = subsasgn(obj.data.(measName{1}).counts, indexer, stepData.(measName{1}));
                            else
                                % we have a single point
                                indexer = struct('type', '()', 'subs', {num2cell(ct)});
                                obj.data.(measName{1}).counts = subsasgn(obj.data.(measName{1}).counts, indexer, stepData.(measName{1}));
                            end
                        end
                        plotResetFlag = all(ct == 1);
                        obj.plot_data(plotResetFlag);
                        obj.save_data(stepData);
                    end
                else
                    %We've rolled over so reset this sweeps counter and
                    %step back to the next sweep
                    ct(idx) = 0;
                    idx = idx - 1;
                end
            end

            % close data file
            if ~isempty(obj.dataFileHandler)
                obj.dataFileHandler.close();
            end

            if obj.saveAllSettings
               %saves json settings files
               fileName = obj.dataFileHandler.fileName;
               [pathname,basename,~] = fileparts(fileName);
               mkdir(fullfile(pathname,strcat(basename,'_cfg')));
               copyfile(getpref('qlab','CurScripterFile'),fullfile(pathname,strcat(basename,'_cfg'),'DefaultExpSettings.json'));
               copyfile(getpref('qlab','ChannelParamsFile'),fullfile(pathname,strcat(basename,'_cfg'),'ChannelParams.json'));
               copyfile(getpref('qlab','InstrumentLibraryFile'),fullfile(pathname,strcat(basename,'_cfg'),'Instruments.json'));
               copyfile(strrep(getpref('qlab','InstrumentLibraryFile'),'Instruments','Measurements'),fullfile(pathname,strcat(basename,'_cfg'),'Measurements.json'));
               copyfile(strrep(getpref('qlab','InstrumentLibraryFile'),'Instruments','Sweeps'),fullfile(pathname,strcat(basename,'_cfg'),'Sweeps.json'));
            end
        end

        function cleanUp(obj)
            % stop the scopes
            cellfun(@(scope) stop(scope), obj.scopes);
            % stop AWGs
            cellfun(@(awg) stop(awg), obj.AWGs);
            % stop plot timer and clear it
            stop(obj.plotScopeTimer);
            delete(obj.plotScopeTimer);
            %clean up DataReady listeners
            cellfun(@delete, obj.listeners);

        end

        %Helper function to take data (basically, start/stop AWGs and
        %digitizers)
        function take_data(obj)

            %Clear all the measurement filters
            structfun(@(m) reset(m), obj.measurements);

            %%Swapped this with the 'Ready the digitizers' below
            if(~obj.CWMode)
                %Start the slaves up again
                cellfun(@(awg) run(awg), obj.AWGs(2:end))
                %And the master
                run(obj.AWGs{1});
            end

            %Ready the digitizers
            cellfun(@(scope) acquire(scope), obj.scopes);

            %Wait for data taking to finish
            obj.scopes{1}.wait_for_acquisition(obj.dataTimeout);

            if(~obj.CWMode)
                %Stop all the AWGs
                cellfun(@(awg) stop(awg), obj.AWGs);
            end
        end

        function save_data(obj, stepData)
            if isempty(obj.dataFileHandler) || obj.dataFileHandler.fileOpen == 0
                return
            end
            measNames = fieldnames(stepData)';
            savect = 1;
            for ct = 1:length(measNames)
                if ~obj.measurements.(measNames{ct}).saved
                    continue
                end
                measData = squeeze(stepData.(measNames{ct}));
                obj.dataFileHandler.write(measData, savect);
                savect = savect + 1;
            end
        end

        function plot_data(obj, reset)
            %Plot the accumulated swept data
            %We keep track of figure handles to not pop new ones up all the
            %time

            %TODO: Handle changes in data size
            persistent figHandles plotHandles
            if isempty(figHandles)
                figHandles = struct();
                plotHandles = struct();
            end

            % available plotting modes
            plotMap = struct();
            plotMap.abs = struct('label','Amplitude', 'func', @abs);
            plotMap.phase = struct('label','Phase (degrees)', 'func', @(x) (180/pi)*angle(x));
            plotMap.real = struct('label','Real Quad.', 'func', @real);
            plotMap.imag = struct('label','Imag. Quad.', 'func', @imag);
            plotMap.counts = struct('label', 'Counts', 'func', @(x) x);

            for measName = fieldnames(obj.data)'
                measData = squeeze(obj.data.(measName{1}).counts);
                if isempty(measData)
                    continue;
                end

                toPlot = {plotMap.counts};
                numRows=1; numCols=1;

                %Check whether we have an open figure handle to plot to
                if ~isfield(figHandles, measName{1}) || ~ishandle(figHandles.(measName{1}))
                    %If we've closed the figure then we probably
                    %need to reset the axes and plot handles too
                    if isfield(figHandles, measName{1})
                       plotHandles.(measName{1}) = cell(length(toPlot),1);
                    end
                    figHandles.(measName{1}) = figure('WindowStyle', 'docked', 'HandleVisibility', 'callback', 'NumberTitle', 'off', 'Name', [measName{1} ' - Data']);
                end
                figHandle = figHandles.(measName{1});

                for ct = 1:length(toPlot)
                    if reset || isempty(plotHandles.(measName{1}){ct}) || ~ishandle(plotHandles.(measName{1}){ct})
                        axesH = subplot(numRows, numCols, ct, 'Parent', figHandle);
                        sizes = cellfun(@(x) length(x.points), obj.sweeps);
                        switch nsdims(measData)
                            case 1
                                %Find non-singleton sweep dimension
                                goodSweepIdx = find(sizes ~= 1, 1);
                                plotHandles.(measName{1}){ct} = plot(axesH, obj.sweeps{goodSweepIdx}.plotPoints, toPlot{ct}.func(measData));
                                xlabel(axesH, obj.sweeps{goodSweepIdx}.axisLabel);
                                ylabel(axesH, toPlot{ct}.label)

                            case 2
                                goodSweepIdx = find(sizes ~= 1, 2);
                                xPoints = obj.sweeps{goodSweepIdx(2)}.plotPoints;
                                yPoints = obj.sweeps{goodSweepIdx(1)}.plotPoints;
                                plotHandles.(measName{1}){ct} = imagesc(xPoints, yPoints, toPlot{ct}.func(measData), 'Parent', axesH);
                                title(axesH, toPlot{ct}.label)
                                xlabel(axesH, obj.sweeps{goodSweepIdx(2)}.axisLabel);
                                ylabel(axesH, obj.sweeps{goodSweepIdx(1)}.axisLabel);
                            case 3
                                goodSweepIdx = find(sizes ~= 1, 2);
                                xPoints = obj.sweeps{goodSweepIdx(1)}.plotPoints;
                                yPoints = obj.sweeps{goodSweepIdx(2)}.plotPoints;
                                plotHandles.(measName{1}){ct} = imagesc(xPoints, yPoints, toPlot{ct}.func(squeeze(measData(1,:,:))), 'Parent', axesH);
                                title(axesH, toPlot{ct}.label)
                                xlabel(axesH, obj.sweeps{goodSweepIdx(1)}.axisLabel);
                                ylabel(axesH, obj.sweeps{goodSweepIdx(2)}.axisLabel);
                        end
                    else
                        switch nsdims(measData)
                            case 1
                                set(plotHandles.(measName{1}){ct}, 'YData', toPlot{ct}.func(measData));
                            case 2
                                set(plotHandles.(measName{1}){ct}, 'CData', toPlot{ct}.func(measData));
                            case 3
                                %Here we'll try to plot the last updated
                                %slice
                                curSliceIdx = find(~isnan(measData(:,1,1)), 1, 'last');
                                curSlice = measData(curSliceIdx,:,:);
                                set(plotHandles.(measName{1}){ct}, 'CData', toPlot{ct}.func(squeeze(curSlice)));
                        end
                    end
                end
            end
            drawnow()
        end

        function plot_scope_callback(obj, ~, ~)
            %We keep track of figure handles to not pop new ones up all the
            %time
            persistent figHandles
            if isempty(figHandles)
                figHandles = struct();
            end

            for measName = fieldnames(obj.measurements)'
                if obj.measurements.(measName{1}).plotScope
                    if ~isfield(figHandles, measName{1}) || ~ishandle(figHandles.(measName{1}))
                        figHandles.(measName{1}) = figure('WindowStyle', 'docked', 'HandleVisibility', 'callback', 'NumberTitle', 'off', 'Name', [measName{1} ' - Scope']);
                    end
                    figHandle = figHandles.(measName{1});
                    obj.measurements.(measName{1}).plot(figHandle);
                end
            end
            drawnow()
        end

        %Helpers to flesh out properties
        function add_instrument(obj, name, instr, settings)
            obj.instruments.(name) = instr;
            obj.instrSettings.(name) = settings;
        end

        function add_measurement(obj, name, meas)
            obj.measurements.(name) = meas;
        end

        function add_sweep(obj, order, sweep, callback)
            % order = 1-indexed position to insert the sweep in the list of sweeps
            % sweep = a sweep object
            % callback = a method to call after each sweep.step()
            obj.sweeps{order} = sweep;
            if exist('callback', 'var')
                obj.sweep_callbacks{order} = callback;
            else
                obj.sweep_callbacks{order} = [];
            end
        end

        function clear_sweeps(obj)
            obj.sweeps = {};
            obj.sweep_callbacks = {};
        end

    end

    methods (Static)
        %forward reference static methods
        out = is_scope(instr)
        out = is_AWG(instr)
    end

end


text:
.class Lcom/android/gallery3d/filtershow/FilterShowActivity$5;
.super Ljava/lang/Object;
.source "FilterShowActivity.java"

# interfaces
.implements Ljava/lang/Runnable;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/android/gallery3d/filtershow/FilterShowActivity;->toggleHistoryPanel()V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/android/gallery3d/filtershow/FilterShowActivity;

.field final synthetic val$viewList:Landroid/view/View;

# direct methods
.method constructor <init>(Lcom/android/gallery3d/filtershow/FilterShowActivity;Landroid/view/View;)V
    .locals 0
    .parameter
    .parameter

    .prologue
    .line 887
    iput-object p1, p0, Lcom/android/gallery3d/filtershow/FilterShowActivity$5;->this$0:Lcom/android/gallery3d/filtershow/FilterShowActivity;

    iput-object p2, p0, Lcom/android/gallery3d/filtershow/FilterShowActivity$5;->val$viewList:Landroid/view/View;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public run()V
    .locals 3

    .prologue
    .line 890
    iget-object v0, p0, Lcom/android/gallery3d/filtershow/FilterShowActivity$5;->val$viewList:Landroid/view/View;

    const/4 v1, 0x0

    invoke-virtual {v0, v1}, Landroid/view/View;->setAlpha(F)V

    .line 891
    iget-object v0, p0, Lcom/android/gallery3d/filtershow/FilterShowActivity$5;->val$viewList:Landroid/view/View;

    const/4 v1, 0x0

    invoke-virtual {v0, v1}, Landroid/view/View;->setVisibility(I)V

    .line 892
    iget-object v0, p0, Lcom/android/gallery3d/filtershow/FilterShowActivity$5;->val$viewList:Landroid/view/View;

    invoke-virtual {v0}, Landroid/view/View;->animate()Landroid/view/ViewPropertyAnimator;

    move-result-object v0

    const-wide/16 v1, 0x64

    invoke-virtual {v0, v1, v2}, Landroid/view/ViewPropertyAnimator;->setDuration(J)Landroid/view/ViewPropertyAnimator;

    move-result-object v0

    const/high16 v1, 0x3f80

    invoke-virtual {v0, v1}, Landroid/view/ViewPropertyAnimator;->alpha(F)Landroid/view/ViewPropertyAnimator;

    move-result-object v0

    invoke-virtual {v0}, Landroid/view/ViewPropertyAnimator;->start()V

    .line 894
    return-void
.end method

redpajama_set_name: RedPajamaGithub


text:
/**
 * Tareas de scraper separadas para generar web workers
 * @package sitp-api
 * @author Andrés Zorro <zorrodg@gmail.com>
 * @module app
 */
'use strict';

require('./config');

var _       = require('underscore'),
    Scraper = require('./lib/scraper/module'),
    args    = [].concat(process.argv);

args.shift();
args.shift();

switch(args[0]){
  case 'scraper':
    var startTime = new Date().getTime(), endTime;
    Scraper.getList(function(data){
      if(data){
        var rutas = require('./output/rutas.json');
        Scraper.writeLines(rutas, function(data){
          if(data){
            var paraderos = require('./output/paraderos.json');
            Scraper.writeStops(paraderos, function(data){
              endTime = new Date().getTime();
              console.log('Finalizado en ' + (endTime - startTime)/1000 + 's.');
              process.exit();
            });
          }
        });
      }
    });
    break;
  case 'lines':
    var startTime = new Date().getTime(), endTime;
    Scraper.getList(function(data){
      if(data){
        var rutas = require('./output/rutas.json');
        Scraper.writeLines(rutas, function(data){
          endTime = new Date().getTime();
          console.log('Finalizado en ' + (endTime - startTime)/1000 + 's.');
          process.exit();
        });
      }
    });
    break;
  case 'stops':
    var startTime = new Date().getTime(), endTime;
    var paraderos = require('./output/paraderos.json');
    Scraper.writeStops(paraderos, function(data){
      endTime = new Date().getTime();
      console.log('Finalizado en ' + (endTime - startTime)/1000 + 's.');
      process.exit();
    });
    break;
  default:
    console.log('Inserta un comando');
    process.exit();
    break;
}


text:
<?php

declare(strict_types=1);

namespace Gtt\Bundle\WorkflowExtensionsBundle\Actions;

use Gtt\Bundle\WorkflowExtensionsBundle\WorkflowContext;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
use Symfony\Component\Workflow\Exception\LogicException;
use Symfony\Component\Workflow\Workflow;

class TransitionApplierTest extends TestCase
{
    /**
     * @dataProvider exceptionAndLogLevelProvider
     */
    public function testUnavailabilityToPerformTransitionIsReportedByLogger(
        \Exception $exception,
        string $loggerLevel,
        bool $throw = true
    ): void {
        $transitionName  = "t1";
        $subject         = new \StdClass();

        $workflow = $this->getMockBuilder(Workflow::class)->disableOriginalConstructor()->getMock();
        $workflow->expects(self::once())->method('apply')->with($subject, $transitionName)->willThrowException($exception);
        if ($throw) {
            $this->expectException(get_class($exception));
        }

        $workflowContext = new WorkflowContext($workflow, $subject, "id");

        $logger = $this->getMockBuilder(LoggerInterface::class)->getMockForAbstractClass();
        $logger->expects(self::once())->method($loggerLevel);

        $applier = new TransitionApplier($logger);

        $applier->applyTransition($workflowContext, $transitionName);
    }

    public function exceptionAndLogLevelProvider(): array
    {
        return [
            // workflow logic exception should trigger info-level logging
            [new LogicException(), "info", false],
            [new \Exception(), "error"]
        ];
    }

    /**
     * @dataProvider transitionEnvironmentProvider
     */
    public function testSeveralTransitionsHandledCorrectly(
        array $transitions = [],
        array $transitionsToBeTriedToApply = [],
        bool $cascade = false
    ): void {
        $subject = new \StdClass();
        $workflow = $this->getMockBuilder(Workflow::class)->disableOriginalConstructor()->getMock();

        $callIndex = 0;
        $transitionsToApplyCount = 0;
        $workflow->expects(self::at($callIndex))->method('getName');
        $callIndex++;
        foreach ($transitionsToBeTriedToApply as $transitionName => $applicationResult) {
            $invocationMocker = $workflow->expects(self::at($callIndex))->method('apply')->with($subject, $transitionName);
            $transitionsToApplyCount++;
            if (is_array($applicationResult)) {
                [$exception, $throw] = $applicationResult;
                $invocationMocker->willThrowException($exception);
                if ($throw) {
                    $this->expectException(get_class($exception));
                    break;
                }
            }
            $callIndex++;
        }
        $workflow->expects($this->exactly($transitionsToApplyCount))->method('apply');

        $workflowContext = new WorkflowContext($workflow, $subject, "id");

        $applier = new TransitionApplier($this->getMockBuilder(LoggerInterface::class)->getMockForAbstractClass());

        $applier->applyTransitions($workflowContext, $transitions, $cascade);
    }

    public function transitionEnvironmentProvider()
    {
        return [
            [['t1', 't2'], ['t1' => true]],
            [['t1', 't2'], ['t1' => [new \Exception(), true], 't2' => true], true],
            [['t1', 't2'], ['t1' => [new \Exception(), true], 't2' => true], false],
            [['t1', 't2'], ['t1' => [new LogicException(), false], 't2' => true], true],
            [['t1', 't2'], ['t1' => [new LogicException(), false], 't2' => true], false],
        ];
    }
}


text:
#include <aws/elasticbeanstalk/model/PlatformFramework.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>

#include <utility>

using namespace Aws::Utils::Xml;
using namespace Aws::Utils;

namespace Aws
{
namespace ElasticBeanstalk
{
namespace Model
{

PlatformFramework::PlatformFramework() :
    m_nameHasBeenSet(false),
    m_versionHasBeenSet(false)
{
}

PlatformFramework::PlatformFramework(const XmlNode& xmlNode) :
    m_nameHasBeenSet(false),
    m_versionHasBeenSet(false)
{
  *this = xmlNode;
}

PlatformFramework& PlatformFramework::operator =(const XmlNode& xmlNode)
{
  XmlNode resultNode = xmlNode;

  if(!resultNode.IsNull())
  {
    XmlNode nameNode = resultNode.FirstChild("Name");
    if(!nameNode.IsNull())
    {
      m_name = StringUtils::Trim(nameNode.GetText().c_str());
      m_nameHasBeenSet = true;
    }
    XmlNode versionNode = resultNode.FirstChild("Version");
    if(!versionNode.IsNull())
    {
      m_version = StringUtils::Trim(versionNode.GetText().c_str());
      m_versionHasBeenSet = true;
    }
  }

  return *this;
}

void PlatformFramework::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const
{
  if(m_nameHasBeenSet)
  {
      oStream << location << index << locationValue << ".Name=" << StringUtils::URLEncode(m_name.c_str()) << "&";
  }

  if(m_versionHasBeenSet)
  {
      oStream << location << index << locationValue << ".Version=" << StringUtils::URLEncode(m_version.c_str()) << "&";
  }

}

void PlatformFramework::OutputToStream(Aws::OStream& oStream, const char* location) const
{
  if(m_nameHasBeenSet)
  {
      oStream << location << ".Name=" << StringUtils::URLEncode(m_name.c_str()) << "&";
  }
  if(m_versionHasBeenSet)
  {
      oStream << location << ".Version=" << StringUtils::URLEncode(m_version.c_str()) << "&";
  }
}

} // namespace Model
} // namespace ElasticBeanstalk
} // namespace Aws


text:
from __future__ import division, print_function
from difflib import SequenceMatcher
import sys
import unicode

from gigacluster import SentenceMatch, read_info, is_punctuation, STOPWORDS
import nltk
stem = nltk.stem.PorterStemmer().stem

LENGTH_RATIO = 1.5
INV_LR = 1/LENGTH_RATIO

RED    = '\033[0;31m'
GREEN  = '\033[0;32m'
NORMAL = '\033[0m'

red = lambda i: '{}{}{}'.format(RED, i, NORMAL)
green = lambda i: '{}{}{}'.format(GREEN, i, NORMAL)

def first_norm(s):
    return [tok.lower() for tok in s if not is_punctuation(tok)]

def second_norm(s):
    return [stem(tok)
            for tok in s
            if tok not in STOPWORDS]

matcher = SequenceMatcher(None)
for f in sys.argv[1:]:
    with open(f) as f:
        for line in f:
            window, line = line.decode('utf-8').split('\t', 1)
            m = SentenceMatch.from_string(line)
            if m.sentence_score < 0.4:
                continue
            s, t = read_info(m.info)
            if s == t:
                continue

            s_nopunct = first_norm(s)
            t_nopunct = first_norm(t)

            s_normed = second_norm(s_nopunct)
            t_normed = second_norm(t_nopunct)
            stoks = set(s_normed)
            ttoks = set(t_normed)

            if len(stoks & ttoks) in (len(stoks), len(ttoks)):
                # one is subset of the other
                if ' '.join(s_nopunct) in ' '.join(t_nopunct) or ' '.join(t_nopunct) in ' '.join(s_nopunct):
                    #substring not interesting
                    continue

                # check substantial unnormalised distances
                ratio = len(s) / len(t)
                if ratio > LENGTH_RATIO or ratio < INV_LR:
                    if ratio < 1:
                        ratio = 1/ratio
                    print(ratio, unicode(m).encode('utf-8'), sep='\t')


text:
import argparse
import os
import subprocess
import sys
import tempfile
from Crypto.PublicKey import RSA
from jinja2 import Template

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--github-user', help='The GitHub user whose keys will'
    ' be preloaded for the pi user. If absent authentication will have to use the '
    ' default password "raspberry".')
    parser.add_argument('-u', '--ssh-user', help='The user to use for sshing to the'
    ' target. Github user will be specified if this is not given.')
    parser.add_argument('-t', '--ssh-target', help='', required=True)
    parser.add_argument('-p', '--ssh-target-pubkey', help='The SSH targets pubkey'
        ' can be specified for complete two-way trust. If absent, any key presented'
        ' will be accepted and enables a MiTM attack. This argument can be given'
        ' several times. Make sure you quote the pubkeys correctly: -p "ssh-rsa <snip>"', nargs='*', default=[])
    parser.add_argument('-k', '--ssh-key', help='The SSH key to use for connecting'
        ' to the target. If not specified, a key will be created and the public part'
        ' echoed when creating the inject binary')
    parser.add_argument('-s', '--script-out', help="Don't encode the script, just"
        ' echo it to stdout', action='store_true')
    parser.add_argument('-o', '--output', default='inject.bin', help='Where to output'
        ' the final binary. Default: %(default)s')
    parser.add_argument('-e', '--encoder', default='encoder.jar', help='Path to the'
        ' encoder. Default: %(default)s')

    args = parser.parse_args()

    if not (args.ssh_user or args.github_user):
        parser.print_help()
        print('Error: Either --ssh-user or --github-user is required', file=sys.stderr)
        sys.exit(1)

    # Build the script to be passed to the encoder
    build_target = tempfile.NamedTemporaryFile(delete=False)
    for line in build(github_user=args.github_user,
        ssh_target=args.ssh_target, ssh_target_pubkeys=args.ssh_target_pubkey,
        ssh_key=args.ssh_key, ssh_user=args.ssh_user):
        build_target.write((line + '\n').encode('utf-8'))
    build_target.close()

    if args.script_out:
        with open(build_target.name) as fh:
            for line in fh:
                print(line.strip())
    else:
        # Do the actual encoding
        subprocess.check_call(['java',
            '-jar', args.encoder,
            '-l', 'gb.properties',
            '-i', build_target.name,
            '-o', args.output])

    os.remove(build_target.name)

def build(github_user=None, ssh_target=None, ssh_target_pubkeys=None,
          ssh_key=None, ssh_user=None):

    ssh_key_file = None
    if ssh_key is None:
        ssh_key_file = tempfile.NamedTemporaryFile(delete=False)
        ssh_private_key = RSA.generate(2048)
        ssh_key_file.write(ssh_private_key.exportKey())
        ssh_key_file.close()
        print('Add this key to authorized_keys on the target host: ')
        subprocess.check_call(['ssh-keygen', '-y', '-f', ssh_key_file.name])
        print()
        ssh_key = ssh_key_file.name

    yield 'REM Use to bootstrap raspberry pis headless.'
    yield 'REM Waits for first boot, expands filesystem through raspi-config,'
    yield 'REM then reboots. On next boot will forward ssh through other server and'
    yield 'REM add a known key it will connect with.'
    yield 'DELAY 30000'
    yield 'DELAY 10000'
    yield 'REM Do filesystem expansion'
    yield 'ENTER'
    yield 'DELAY 15000'
    yield 'REM Accept that it will be booted into on next reboot'
    yield 'ENTER'
    yield 'DELAY 2000'
    yield 'REM Click right two times to exit raspi-config'
    yield 'RIGHTARROW'
    yield 'DELAY 300'
    yield 'RIGHTARROW'
    yield 'DELAY 300'
    yield 'REM Click on finish'
    yield 'ENTER'
    yield 'DELAY 2000'
    yield 'REM Drop back to shell'
    yield 'RIGHTARROW'
    yield 'DELAY 300'
    yield 'ENTER'
    yield 'DELAY 4000'
    yield 'STRING sudo -i'
    yield 'ENTER'
    yield 'DELAY 1000'

    tunnel_context = {
        'ssh_user': ssh_user or github_user,
        'ssh_target': ssh_target,
        'no_strict_checking': len(ssh_target_pubkeys) == 0,
    }
    yield from place_file('/etc/init.d/ssh-tunnel', 'ssh-tunnel.sh', tunnel_context)

    yield 'DELAY 500'
    yield 'STRING chmod +x /etc/init.d/ssh-tunnel'
    yield 'ENTER'
    yield 'DELAY 300'

    if ssh_target_pubkeys:
        yield from place_ssh_known_hosts(ssh_target, ssh_target_pubkeys)

    yield 'DELAY 500'
    yield 'REM Exit sudo'
    yield 'STRING exit'
    yield 'ENTER'
    yield 'DELAY 300'
    yield 'ENTER'
    yield 'STRING mkdir .ssh'
    yield 'ENTER'
    yield 'DELAY 200'
    yield 'STRING chmod 700 .ssh'
    yield 'ENTER'
    yield 'DELAY 200'

    yield from place_file('.ssh/id_rsa', ssh_key)

    yield 'DELAY 200'
    yield 'STRING chmod 600 .ssh/id_rsa'
    yield 'ENTER'
    yield 'DELAY 200'

    yield from place_file('/tmp/bootstrap.sh', 'bootstrap.sh', {'github_user': github_user})

    yield 'STRING sudo bash /tmp/bootstrap.sh'
    yield 'ENTER'

    if ssh_key_file:
        os.remove(ssh_key_file.name)

def place_ssh_known_hosts(host, known_host_keys):
    yield 'STRING cat > /etc/ssh/ssh_known_hosts <<"EOF"'
    yield 'ENTER'
    for known_host_key in known_host_keys:
        yield 'STRING {} {}'.format(host, known_host_key)
        yield 'ENTER'
    yield 'STRING EOF'
    yield 'ENTER'

def place_file(path, source_file, context={}):
    yield 'STRING cat > {} <<"EOF"'.format(path)
    yield 'ENTER'
    with open(source_file) as fh:
        template = Template(fh.read())
    for block in template.stream(**context):
        for line in block.split('\n'):
            if line:
                yield 'STRING {}'.format(line)
            yield 'ENTER'
    yield 'STRING EOF'
    yield 'ENTER'

if __name__ == '__main__':
    main()


text:
namespace Microsoft.Azure.Management.Compute.Models
{
    using Microsoft.Rest;
    using Microsoft.Rest.Serialization;
    using Newtonsoft.Json;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// disk encryption set resource.
    /// </summary>
    [Rest.Serialization.JsonTransformation]
    public partial class DiskEncryptionSet : Resource
    {
        /// <summary>
        /// Initializes a new instance of the DiskEncryptionSet class.
        /// </summary>
        public DiskEncryptionSet()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the DiskEncryptionSet class.
        /// </summary>
        /// <param name="location">Resource location</param>
        /// <param name="id">Resource Id</param>
        /// <param name="name">Resource name</param>
        /// <param name="type">Resource type</param>
        /// <param name="tags">Resource tags</param>
        /// <param name="encryptionType">Possible values include:
        /// 'EncryptionAtRestWithCustomerKey',
        /// 'EncryptionAtRestWithPlatformAndCustomerKeys'</param>
        /// <param name="activeKey">The key vault key which is currently used
        /// by this disk encryption set.</param>
        /// <param name="previousKeys">A readonly collection of key vault keys
        /// previously used by this disk encryption set while a key rotation is
        /// in progress. It will be empty if there is no ongoing key
        /// rotation.</param>
        /// <param name="provisioningState">The disk encryption set
        /// provisioning state.</param>
        public DiskEncryptionSet(string location, string id = default(string), string name = default(string), string type = default(string), IDictionary<string, string> tags = default(IDictionary<string, string>), EncryptionSetIdentity identity = default(EncryptionSetIdentity), string encryptionType = default(string), KeyVaultAndKeyReference activeKey = default(KeyVaultAndKeyReference), IList<KeyVaultAndKeyReference> previousKeys = default(IList<KeyVaultAndKeyReference>), string provisioningState = default(string))
            : base(location, id, name, type, tags)
        {
            Identity = identity;
            EncryptionType = encryptionType;
            ActiveKey = activeKey;
            PreviousKeys = previousKeys;
            ProvisioningState = provisioningState;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// </summary>
        [JsonProperty(PropertyName = "identity")]
        public EncryptionSetIdentity Identity { get; set; }

        /// <summary>
        /// Gets or sets possible values include:
        /// 'EncryptionAtRestWithCustomerKey',
        /// 'EncryptionAtRestWithPlatformAndCustomerKeys'
        /// </summary>
        [JsonProperty(PropertyName = "properties.encryptionType")]
        public string EncryptionType { get; set; }

        /// <summary>
        /// Gets or sets the key vault key which is currently used by this disk
        /// encryption set.
        /// </summary>
        [JsonProperty(PropertyName = "properties.activeKey")]
        public KeyVaultAndKeyReference ActiveKey { get; set; }

        /// <summary>
        /// Gets a readonly collection of key vault keys previously used by
        /// this disk encryption set while a key rotation is in progress. It
        /// will be empty if there is no ongoing key rotation.
        /// </summary>
        [JsonProperty(PropertyName = "properties.previousKeys")]
        public IList<KeyVaultAndKeyReference> PreviousKeys { get; private set; }

        /// <summary>
        /// Gets the disk encryption set provisioning state.
        /// </summary>
        [JsonProperty(PropertyName = "properties.provisioningState")]
        public string ProvisioningState { get; private set; }

        /// <summary>
        /// Validate the object.
        /// </summary>
        /// <exception cref="ValidationException">
        /// Thrown if validation fails
        /// </exception>
        public override void Validate()
        {
            base.Validate();
            if (ActiveKey != null)
            {
                ActiveKey.Validate();
            }
            if (PreviousKeys != null)
            {
                foreach (var element in PreviousKeys)
                {
                    if (element != null)
                    {
                        element.Validate();
                    }
                }
            }
        }
    }
}


text:
package com.streamsets.pipeline.lib.generator;

public interface StreamCloseEventHandler<T> {
  void handleCloseEvent(T eventInfo);
}


text:
object Options {

  val something: Option[String] = Some("A string")
  val nothing: Option[String] = None

  something.isEmpty
  //res4: Boolean = false
  nothing.isEmpty
  //res5: Boolean = true

  something.getOrElse("")
  //res6: String = A string
  nothing.getOrElse("")
  //res7: String = ""

  something.get
  //res6: String = A string
  nothing.get
  //java.util.NoSuchElementException: None.get
}

object Options2 {

  object request {
    def getParameter(key: String) = ""
  }

  val name: String = request.getParameter("name")

  val upperCaseName = if (name != null) {
    val trimmed = name.trim
    if (!trimmed.isEmpty) {
      trimmed.toUpperCase
    } else {
      null
    }
  } else {
    null
  }
}

object Options3 {

  object request {
    def getParameter(key: String): Option[String] = Some("")
  }

  val name: Option[String] = request.getParameter("name")

  val upperCaseName = name map (_.trim) filter (!_.isEmpty) map (_.toUpperCase)

}

object Options4 {
  val myOptional: Option[String] = Some("Hello")

  myOptional.foreach(println)
  // Hello
  myOptional.exists(_.startsWith("H"))
  //res0: Boolean = true
  myOptional.isEmpty
  //res1: Boolean = false
  myOptional.map(_.toLowerCase)
  //res2: Option[String] = Some(hello)
  myOptional.flatMap(s => Some(s + " Frode"))
  //res3: Option[String] = Some(Hello Frode)
  myOptional.getOrElse("!!")
  //res4: String = Hello
}

object Options5 {
  val myOptional: Option[String] = None

  myOptional.foreach(println)
  // println is never invoked
  myOptional.exists(_.startsWith("H"))
  //res0: Boolean = false
  myOptional.isEmpty
  //res1: Boolean = true
  myOptional.map(_.toLowerCase)
  //res2: Option[String] = None
  myOptional.flatMap(s => Some(s + " Frode"))
  //res3: Option[String] = None
  myOptional.getOrElse("!!")
  //res4: String = !!
}

object Options6 {

  case class Person(name: String)

  val optionalPerson: Option[Person] = Some(Person("Frode"))

  optionalPerson match {
    case Some(Person("Frode")) => println("Fant Frode")
    case Some(_) => println("Fant noen andre")
    case None => println("Ikke en person")
  }
}

object Options7 {

  case class Person(name: String)

val firstName: Option[String] = Some("Arild")
val lastName: Option[String] = Some("Nilsen")

val fullName = for {
  first <- firstName
  last <- lastName
} yield first + " " last
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package de.jdynameta.jdy.model.jpa;

import de.jdynameta.base.metainfo.ClassInfo;
import de.jdynameta.base.metainfo.ClassRepository;
import de.jdynameta.base.metainfo.PrimitiveType;
import de.jdynameta.base.metainfo.impl.DefaultClassRepositoryValidator;
import de.jdynameta.base.metainfo.impl.JdyAbstractAttributeModel;
import de.jdynameta.base.metainfo.impl.JdyAssociationModel;
import de.jdynameta.base.metainfo.impl.JdyBooleanType;
import de.jdynameta.base.metainfo.impl.JdyClassInfoModel;
import de.jdynameta.base.metainfo.impl.JdyDecimalType;
import de.jdynameta.base.metainfo.impl.JdyFloatType;
import de.jdynameta.base.metainfo.impl.JdyLongType;
import de.jdynameta.base.metainfo.impl.JdyObjectReferenceModel;
import de.jdynameta.base.metainfo.impl.JdyPrimitiveAttributeModel;
import de.jdynameta.base.metainfo.impl.JdyRepositoryModel;
import de.jdynameta.base.metainfo.impl.JdyTextType;
import de.jdynameta.base.metainfo.impl.JdyTimeStampType;
import de.jdynameta.base.view.DbDomainValue;
import de.jdynameta.model.asm.jpa.info.JpaAsmClassInfo;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.OneToMany;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.metamodel.Attribute;
import javax.persistence.metamodel.EntityType;
import javax.persistence.metamodel.Metamodel;
import static javax.persistence.metamodel.Attribute.PersistentAttributeType.BASIC;
import static javax.persistence.metamodel.Attribute.PersistentAttributeType.ELEMENT_COLLECTION;
import static javax.persistence.metamodel.Attribute.PersistentAttributeType.MANY_TO_MANY;
import static javax.persistence.metamodel.Attribute.PersistentAttributeType.MANY_TO_ONE;
import static javax.persistence.metamodel.Attribute.PersistentAttributeType.ONE_TO_MANY;
import static javax.persistence.metamodel.Attribute.PersistentAttributeType.ONE_TO_ONE;
import javax.persistence.metamodel.IdentifiableType;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.Type;

/**
 *
 * @author Rainer_2
 */
public class JpaMetamodelReader
{

    public ClassRepository createMetaRepository(final Metamodel metaModel, String anAppName) {

        return createMetaRepository(metaModel.getEntities(), anAppName);
    }

    public ClassRepository createMetaRepository(Set<EntityType<?>> allEntityInfos, String anAppName)
    {
        JdyRepositoryModel metaRepo = new JdyRepositoryModel(anAppName);
        metaRepo.addListener(new DefaultClassRepositoryValidator());
        final Map<String, JdyClassInfoModel> className2InfoMap = new HashMap<>();

        // build base classes
        for (EntityType<?> curEntity : allEntityInfos)
        {
            JdyClassInfoModel newModel = addClassToMetaRepo(metaRepo, curEntity);
            className2InfoMap.put(newModel.getInternalName(), newModel);
        }

        for (EntityType<?> curEntity : allEntityInfos)
        {
            buildAttrForMetaRepo(metaRepo, curEntity, false);
        }

         for (EntityType<?> curEntity : allEntityInfos)
        {
            buildAssocsForMetaRepo(metaRepo, curEntity);
        }

         for (EntityType<?> curEntity : allEntityInfos)
        {
            buildSubclassesForMetaRepo(metaRepo, curEntity);
        }

        return metaRepo;
    }

    private JdyClassInfoModel addClassToMetaRepo(JdyRepositoryModel metaRepo, EntityType aEntity)
    {
        JdyClassInfoModel metaClass = metaRepo.addClassInfo(aEntity.getName());

        //metaClass.setAbstract(curClass.isAbstract());
        if (aEntity.getSupertype() != null) {
            metaClass.setExternalName(aEntity.getJavaType().getName());
        } else {
            metaClass.setExternalName(aEntity.getName());
        }
        metaClass.setShortName(aEntity.getName());
        metaClass.setNameSpace(aEntity.getJavaType().getName().replace('.', '_'));

        return metaClass;
    }

    private void buildAttrForMetaRepo(ClassRepository metaRepo, EntityType<?> anEntity,boolean embeddedId)
    {
        JdyClassInfoModel metaClass = (JdyClassInfoModel) metaRepo.getClassForName(anEntity.getName());

        for (Attribute<?, ?> curAttr : anEntity.getAttributes())
        {
            if (!curAttr.isCollection()) {

                if (curAttr.getPersistentAttributeType() == BASIC)
                {
                    JdyAbstractAttributeModel metaAttr = createPrimitiveField(curAttr, embeddedId);
                    if (metaAttr != null) {
                        metaClass.addAttributeInfo(metaAttr);
                    }
                }else if (curAttr.getPersistentAttributeType() == ONE_TO_ONE || curAttr.getPersistentAttributeType() == MANY_TO_ONE)
                {
                    JdyObjectReferenceModel metaAttr = createObjectReference(curAttr, embeddedId, metaRepo);
                    if (metaAttr != null) {
                        metaClass.addAttributeInfo(metaAttr);
                    }
                } else
                {

                }

            }
        }
    }

    	private void buildAssocsForMetaRepo(ClassRepository metaRepo, EntityType<?> anEntity)
	{
            JdyClassInfoModel metaClass = (JdyClassInfoModel) metaRepo.getClassForName(anEntity.getName());

            for (Attribute<?, ?> curAttr : anEntity.getAttributes())
            {
                if (curAttr.isCollection()) {
                    if (curAttr.getPersistentAttributeType() == ELEMENT_COLLECTION) {
//                        JpaCollectionWrapper wrapper = new JpaCollectionWrapper(curAttr);
//                        System.out.println(wrapper.getType());
//                        System.out.println((wrapper.getType()).ordinal());
//                        System.out.println((wrapper.getType()).name());
                    } else if (curAttr.getPersistentAttributeType() == ONE_TO_MANY) {
                        JpaCollectionWrapper wrapper = new JpaCollectionWrapper(curAttr);
                        System.out.println(anEntity.getName());
			JdyClassInfoModel metaDetailClass = (JdyClassInfoModel) metaRepo.getClassForName(wrapper.getReferencedType().getName());

                        OneToMany mapping = wrapper.getAnntotationInfo(OneToMany.class);
			JdyObjectReferenceModel metaMasterClassRef = (JdyObjectReferenceModel) metaDetailClass.getAttributeInfoForExternalName(mapping.mappedBy());
			String metaAssocName = curAttr.getName();
			JdyAssociationModel metaAssoc = new JdyAssociationModel(metaMasterClassRef, metaDetailClass, metaAssocName);
			metaClass.addAssociation(metaAssoc);

                    } else if (curAttr.getPersistentAttributeType() == MANY_TO_MANY) {
                        // not supported at the momment
                    }
                }
            }

	}

    private void buildSubclassesForMetaRepo(ClassRepository metaRepo, EntityType<?> anEntity)
    {
        JdyClassInfoModel metaClass = (JdyClassInfoModel) metaRepo.getClassForName(anEntity.getName());

        EntityType jpaSuper = (EntityType) anEntity.getSupertype();

        while (jpaSuper != null)
        {
            JdyClassInfoModel metaSuper = (JdyClassInfoModel) metaRepo.getClassForName(jpaSuper.getName());
            if (metaSuper != null)
            {
                metaSuper.addSubclass(metaClass);
                break;
            }

        }

    }

    private JdyObjectReferenceModel createObjectReference(Attribute<?, ?> curAttr, boolean embeddedId, ClassRepository metaRepo)
    {
        JpaFieldWrapper wrapper = new JpaFieldWrapper(curAttr);
        Type type = wrapper.getType();
        boolean isKey = ((SingularAttribute)curAttr).isId() || embeddedId;
        boolean isNotNull = !((SingularAttribute)curAttr).isOptional()|| !wrapper.isNullable();
        boolean isGenerated = wrapper.getGeneratedInfo() != null;
        String refTypeName = ((EntityType)type).getName();
        ClassInfo referenceType = metaRepo.getClassForName(refTypeName);

        JdyObjectReferenceModel  metaAttr = new JdyObjectReferenceModel(referenceType, curAttr.getName(), curAttr.getName(), isKey, isNotNull);
        metaAttr.setGenerated(isGenerated);
        return metaAttr;
    }

    private JdyAbstractAttributeModel createPrimitiveField(Attribute<?, ?> curAttr, boolean embeddedId) {

        JpaFieldWrapper wrapper = new JpaFieldWrapper(curAttr);
        PrimitiveType metaType = getPrimiviveType(wrapper);
        if (metaType != null)
        {
            JdyAbstractAttributeModel metaAttr = null;
            boolean isKey = ((SingularAttribute)curAttr).isId() || embeddedId;
            boolean isNotNull = !((SingularAttribute)curAttr).isOptional()|| !wrapper.isNullable();
            boolean isGenerated = wrapper.getGeneratedInfo() != null;
            metaAttr = new JdyPrimitiveAttributeModel(metaType, curAttr.getName(), curAttr.getName(), isKey, isNotNull);
            metaAttr.setGenerated(isGenerated);
            return metaAttr;
        } else {
            return null;
        }
    }

    private PrimitiveType getPrimiviveType(JpaFieldWrapper wrapper)
    {
        Class aTypeClass = wrapper.getJavaType();

        if (aTypeClass.isAssignableFrom(Integer.class))
        {
            return new JdyLongType((long) Integer.MIN_VALUE, (long) Integer.MAX_VALUE);
        } else if (aTypeClass.isAssignableFrom(Long.class))
        {
            return new JdyLongType(Long.MIN_VALUE, Long.MAX_VALUE);
        } else if (aTypeClass.isAssignableFrom(Short.class))
        {
            return new JdyLongType((long) Short.MIN_VALUE, (long) Short.MAX_VALUE);
        } else if (aTypeClass.isAssignableFrom(Byte.class))
        {
            return new JdyLongType((long) Byte.MIN_VALUE, (long) Byte.MAX_VALUE);
        } else if (aTypeClass.isAssignableFrom(String.class))
        {
            Column column = wrapper.getAnntotationInfo(Column.class);
            int length = (column != null) ? column.length() : 40;

            return new JdyTextType(length);

        } else if (aTypeClass.isAssignableFrom(Date.class) || aTypeClass.isAssignableFrom(Timestamp.class))
        {
            Temporal temporal = wrapper.getAnntotationInfo(Temporal.class);
            TemporalType temporalType = (temporal != null ) ? temporal.value() : TemporalType.TIMESTAMP;
            boolean hasDate = (temporalType==TemporalType.TIMESTAMP) || (temporalType==TemporalType.DATE);
            boolean hasTime = (temporalType==TemporalType.TIMESTAMP) || (temporalType==TemporalType.TIME);
            return new JdyTimeStampType(hasDate, hasTime);
        } else if (aTypeClass.isAssignableFrom(Boolean.class))
        {
            return new JdyBooleanType();
        } else if (aTypeClass.isAssignableFrom(Double.class) || aTypeClass.isAssignableFrom(Float.class))
        {
            return new JdyFloatType();
        } else if (aTypeClass.isAssignableFrom(BigDecimal.class))
        {
            Column comlumn = wrapper.getAnntotationInfo(Column.class);
            int scale = comlumn.scale();
            int precision = comlumn.precision();

            return new JdyDecimalType();
        } else
        {
            if (aTypeClass.isEnum()) {
                Column column = wrapper.getAnntotationInfo(Column.class);
                int length = (column != null) ? column.length() : 40;

                List<DbDomainValue<String>> domainValues = new ArrayList<>();
                for (Field jpaField : aTypeClass.getDeclaredFields())
                {
                    if(jpaField.isEnumConstant())
                    {
                        domainValues.add(new DomValue<>(jpaField.getName(), jpaField.getName()));
                    }
                }

                return new JdyTextType(length, null, domainValues);

            }
            return null;
        }
    }

    private static class DomValue<Type> implements DbDomainValue<Type>
    {
        private final Type domValue;
        private final String representation;

        private DomValue(Type domValue, String representation)
        {
            this.domValue = domValue;
            this.representation = representation;
        }

        @Override
        public Type getDbValue()
        {
            return domValue;
        }

        @Override
        public String getRepresentation()
        {
            return representation;
        }
    }

}


text:
/* eslint-disable func-names, space-before-function-paren, wrap-iife, prefer-arrow-callback, max-len */
(function() {
  this.ProjectFork = (function() {
    function ProjectFork() {
      $('.fork-thumbnail a').on('click', function() {
        $('.fork-namespaces').hide();
        return $('.save-project-loader').show();
      });
    }

    return ProjectFork;
  })();
}).call(window);


text:
namespace PaymentsSdk.Moneris.Common.Entity
{
    using System.Collections.Generic;

    public class CustomerInfo : ICustomerInfo
    {
        public string Id { get; set; }
        public string Email { get; set; }
        public string Note { get; set; }

        public IBillingInfo BillingInfo { get; set; }
        public IBillingInfo ShippingInfo { get; set; }
        public IList<ISalesItem> OrderDetails { get; set; }

        public CustomerInfo(IBillingInfo billingInfo = null, IBillingInfo shippingInfo = null, IList<ISalesItem> orderDetails = null)
        {
            this.BillingInfo = billingInfo ?? new BillingInfo();
            this.ShippingInfo = shippingInfo ?? new BillingInfo();
            this.OrderDetails = orderDetails;
        }
    }
}


text:
//
//  DiscoverCrosshairTooltip.m
//  ShinobiControls
//
//  Created by  on 21/06/2012.
//  Copyright (c) 2012 Scott Logic. All rights reserved.
//

#import "TDFCrosshairTooltip.h"

@implementation TDFCrosshairTooltip

/**
 We override the default behaviour to display the units for our x and y values.
 */
- (void)setDataPoint:(id<SChartData>)dataPoint fromSeries:(SChartSeries *)series fromChart:(ShinobiChart *)chart    {
    SChartDataPoint *dp = dataPoint;
    self.label.text = [NSString stringWithFormat:@"%.0f km, %.0f m", [dp.xValue floatValue], [dp.yValue floatValue]];
}

@end


text:
<?php

namespace Nixilla\CqrsBundle\Services;

class HandlerCollection
{
    private $handlers = [];

    public function setHandler($callable, $eventName)
    {
        $this->handlers[$eventName] = $callable;
    }

    public function getHandler($eventName)
    {
        return isset($this->handlers[$eventName]) ? $this->handlers[$eventName] : null;
    }
}


text:
import { BaseException } from '@angular-devkit/core';
import { dirname, join, resolve } from 'path';
import { RuleFactory } from '../src';
import { FileSystemCollectionDesc, FileSystemSchematicDesc } from './description';
import { ExportStringRef } from './export-ref';
import {
  CollectionCannotBeResolvedException,
  CollectionMissingSchematicsMapException,
  FileSystemEngineHostBase,
  SchematicMissingFieldsException,
} from './file-system-engine-host-base';
import { readJsonFile } from './file-system-utility';

export class NodePackageDoesNotSupportSchematics extends BaseException {
  constructor(name: string) {
    super(`Package ${JSON.stringify(name)} was found but does not support schematics.`);
  }
}

/**
 * A simple EngineHost that uses NodeModules to resolve collections.
 */
export class NodeModulesEngineHost extends FileSystemEngineHostBase {
  constructor(private readonly paths?: string[]) {
    super();
  }

  private resolve(name: string, requester?: string, references = new Set<string>()): string {
    if (requester) {
      if (references.has(requester)) {
        references.add(requester);
        throw new Error(
          'Circular schematic reference detected: ' + JSON.stringify(Array.from(references)),
        );
      } else {
        references.add(requester);
      }
    }

    const relativeBase = requester ? dirname(requester) : process.cwd();
    let collectionPath: string | undefined = undefined;

    if (name.startsWith('.')) {
      name = resolve(relativeBase, name);
    }

    const resolveOptions = {
      paths: requester ? [dirname(requester), ...(this.paths || [])] : this.paths,
    };

    // Try to resolve as a package
    try {
      const packageJsonPath = require.resolve(join(name, 'package.json'), resolveOptions);
      const { schematics } = require(packageJsonPath);

      if (!schematics || typeof schematics !== 'string') {
        throw new NodePackageDoesNotSupportSchematics(name);
      }

      collectionPath = this.resolve(schematics, packageJsonPath, references);
    } catch (e) {
      if ((e as NodeJS.ErrnoException).code !== 'MODULE_NOT_FOUND') {
        throw e;
      }
    }

    // If not a package, try to resolve as a file
    if (!collectionPath) {
      try {
        collectionPath = require.resolve(name, resolveOptions);
      } catch (e) {
        if ((e as NodeJS.ErrnoException).code !== 'MODULE_NOT_FOUND') {
          throw e;
        }
      }
    }

    // If not a package or a file, error
    if (!collectionPath) {
      throw new CollectionCannotBeResolvedException(name);
    }

    return collectionPath;
  }

  protected _resolveCollectionPath(name: string, requester?: string): string {
    const collectionPath = this.resolve(name, requester);
    readJsonFile(collectionPath);

    return collectionPath;
  }

  protected _resolveReferenceString(
    refString: string,
    parentPath: string,
    collectionDescription?: FileSystemCollectionDesc,
  ) {
    const ref = new ExportStringRef<RuleFactory<{}>>(refString, parentPath);
    if (!ref.ref) {
      return null;
    }

    return { ref: ref.ref, path: ref.module };
  }

  protected _transformCollectionDescription(
    name: string,
    desc: Partial<FileSystemCollectionDesc>,
  ): FileSystemCollectionDesc {
    if (!desc.schematics || typeof desc.schematics != 'object') {
      throw new CollectionMissingSchematicsMapException(name);
    }

    return {
      ...desc,
      name,
    } as FileSystemCollectionDesc;
  }

  protected _transformSchematicDescription(
    name: string,
    _collection: FileSystemCollectionDesc,
    desc: Partial<FileSystemSchematicDesc>,
  ): FileSystemSchematicDesc {
    if (!desc.factoryFn || !desc.path || !desc.description) {
      throw new SchematicMissingFieldsException(name);
    }

    return desc as FileSystemSchematicDesc;
  }
}


text:
namespace ts
{

class IValue;

class ILiteral : public virtual ITemplate_Argument
{
public:
    virtual ~ILiteral() = default;

    virtual std::shared_ptr<const IValue> get_value() const = 0;
};

}


text:
package driver

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"net/http/httputil"
	"time"
)

const (
	DefaultTimeout = 10 * time.Second
	None           = "-"
	Any            = "*"
)

// HTTPCall sends a HTTP request to a localhost port, and then check the response code, and response headers.
type HTTPCall struct {
	// Method
	Method string
	// URL path
	Path string
	// Port specifies the port in 127.0.0.1:PORT
	Port uint16
	// Body is the expected body
	Body string
	// RequestHeaders to send with the request
	RequestHeaders map[string]string
	// ResponseCode to expect
	ResponseCode int
	// ResponseHeaders to expect
	ResponseHeaders map[string]string
	// Timeout (must be set to avoid the default)
	Timeout time.Duration
	// DisableRedirect prevents the client from following redirects and returns the original response.
	DisableRedirect bool
}

func Get(port uint16, body string) Step {
	return &HTTPCall{
		Method: http.MethodGet,
		Port:   port,
		Body:   body,
	}
}

func (g *HTTPCall) Run(_ *Params) error {
	url := fmt.Sprintf("http://127.0.0.1:%d%v", g.Port, g.Path)
	if g.Timeout == 0 {
		g.Timeout = DefaultTimeout
	}
	req, err := http.NewRequest(g.Method, url, nil)
	if err != nil {
		return err
	}
	for key, val := range g.RequestHeaders {
		req.Header.Add(key, val)
	}
	dump, _ := httputil.DumpRequest(req, false)
	log.Printf("HTTP request:\n%s", string(dump))

	client := &http.Client{Timeout: g.Timeout}
	if g.DisableRedirect {
		client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
			return http.ErrUseLastResponse
		}
	}
	resp, err := client.Do(req)
	if err != nil {
		return err
	}
	code := resp.StatusCode
	wantCode := 200
	if g.ResponseCode != 0 {
		wantCode = g.ResponseCode
	}
	if code != wantCode {
		return fmt.Errorf("error code for :%d: %d", g.Port, code)
	}

	bodyBytes, err := io.ReadAll(resp.Body)
	defer resp.Body.Close()
	if err != nil {
		return err
	}
	body := string(bodyBytes)
	if g.Body != "" && g.Body != body {
		return fmt.Errorf("got body %q, want %q", body, g.Body)
	}

	for key, val := range g.ResponseHeaders {
		got := resp.Header.Get(key)
		switch val {
		case Any:
			if got == "" {
				return fmt.Errorf("got response header %q, want any", got)
			}
		case None:
			if got != "" {
				return fmt.Errorf("got response header %q, want none", got)
			}
		default:
			if got != val {
				return fmt.Errorf("got response header %q, want %q", got, val)
			}
		}
	}

	return nil
}
func (g *HTTPCall) Cleanup() {}


text:
/* Generated By:JJTree: Do not edit this line. ASTPostIncrement.java Version 4.3 */
/* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=false,TRACK_TOKENS=false,NODE_PREFIX=AST,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */
package lcr.c2bsv.parser;

public
class ASTPostIncrement extends SimpleNode {
  public ASTPostIncrement(int id) {
    super(id);
  }

  public ASTPostIncrement(C2BSVParser p, int id) {
    super(p, id);
  }

}
/* JavaCC - OriginalChecksum=b66b5ba89725ce2cf04034a1475274b1 (do not edit this line) */


text:
#include "TiUIAlertDialogProxy.h"
#include <bb/system/SystemDialog>

static QList<bb::system::SystemDialog*> _alertQueue;
static bool _alertShowing = false;

namespace TiUI {

TiUIAlertDialogProxy::TiUIAlertDialogProxy(const char* name) : TiProxy(name), _cancel(-1)
{
	_alert = new bb::system::SystemDialog("OK");
	_eventHandler = new TiUIAlertDialogEventHandler(this);

	QObject::connect(_alert, SIGNAL(finished(bb::system::SystemUiResult::Type)), _eventHandler, SLOT(buttonSelected(bb::system::SystemUiResult::Type)));

	createPropertySetterGetter("buttonNames", _setButtonNames,  _getButtonNames);
	createPropertySetterGetter("cancel", _setCancel,  _getCancel);
	createPropertySetterGetter("message", _setMessage,  _getMessage);
	createPropertySetterGetter("style", _setStyle,  _getStyle);
	createPropertySetterGetter("title", _setTitle,  _getTitle);
	createPropertySetterGetter("ok", _setOk,  _getOk);
	createPropertySetterGetter("persistent", _setPersistent,  _getPersistent);

	createPropertyFunction("show", _show);
	createPropertyFunction("hide", _hide);

	clearWeak();
}

TiUIAlertDialogProxy::~TiUIAlertDialogProxy()
{
	delete _alert;
	delete _eventHandler;
}

Ti::TiValue TiUIAlertDialogProxy::getButtonNames()
{
	Ti::TiValue val;
	QList<Ti::TiValue> array;
	foreach(QString name, _buttonNames)
	{
		Ti::TiValue btn;
		btn.setString(name);
		array.append(btn);
	}
	val.setList(array);
	return val;
}

void TiUIAlertDialogProxy::setButtonNames(Ti::TiValue val)
{
	if(val.isNull())
	{
		_alert->clearButtons();
		_alert->confirmButton()->setLabel("OK");
		return;
	}
	if(!val.isList())
	{
		return;
	}

	_alert->confirmButton()->setLabel(QString::null);
	_alert->cancelButton()->setLabel(QString::null);
	_alert->clearButtons();
	_buttonNames.clear();
	foreach(Ti::TiValue current, val.toList())
	{
		bb::system::SystemUiButton* button = new bb::system::SystemUiButton();
		QString title = current.toString();
		_buttonNames.append(title);
		button->setLabel(title);
		_alert->appendButton(button);
	}
}

Ti::TiValue TiUIAlertDialogProxy::getCancel()
{
	Ti::TiValue val;
	val.setNumber(_cancel);
	return val;
}

void TiUIAlertDialogProxy::setCancel(Ti::TiValue val)
{
	_cancel = val.toNumber();
}

TI_GETTER_DEFER(TiUIAlertDialogProxy, getMessage)
void TiUIAlertDialogProxy::setMessage(Ti::TiValue val)
{
	_alert->setBody(val.toString());
}

TI_GETTER_DEFER(TiUIAlertDialogProxy, getStyle)
void TiUIAlertDialogProxy::setStyle(Ti::TiValue)
{
}

TI_GETTER_DEFER(TiUIAlertDialogProxy, getTitle)
void TiUIAlertDialogProxy::setTitle(Ti::TiValue val)
{
	_alert->setTitle(val.toString());
}

TI_GETTER_DEFER(TiUIAlertDialogProxy, getOk)
void TiUIAlertDialogProxy::setOk(Ti::TiValue)
{
}

TI_GETTER_DEFER(TiUIAlertDialogProxy, getPersistent)
void TiUIAlertDialogProxy::setPersistent(Ti::TiValue)
{
}

Ti::TiValue TiUIAlertDialogProxy::show(Ti::TiValue)
{
	clearWeak();
	_alertQueue.append(_alert);
	if(!_alertShowing) {
		_alert->show();
		_alertShowing = true;
	}

	Ti::TiValue val;
	val.setUndefined();
	return val;
}
Ti::TiValue TiUIAlertDialogProxy::hide(Ti::TiValue)
{
	_alert->cancel();
	_alertQueue.removeOne(_alert);
	if(_alertQueue.isEmpty())
	{
		_alertShowing = false;
	}
	else
	{
		_alertQueue.last()->show();
	}
	makeWeak();
	Ti::TiValue val;
	val.setUndefined();
	return val;
}

TiUIAlertDialogEventHandler::TiUIAlertDialogEventHandler(TiUIAlertDialogProxy* proxy) : _proxy(proxy)
{

}

void TiUIAlertDialogEventHandler::buttonSelected(bb::system::SystemUiResult::Type type)
{
	bb::system::SystemDialog* dialog = static_cast<bb::system::SystemDialog*>(sender());
	bb::system::SystemUiButton* selectedButton = dialog->buttonSelection();

	_alertQueue.removeOne(dialog);
	int index = -1;

	for(int i = 0, len = dialog->buttonCount(); i < len; i++) {
		if(dialog->buttonAt(i) == selectedButton) {
			index = i;
			break;
		}
	}
	bool cancel = index == (int)_proxy->getCancel().toNumber();

	Ti::TiEventParameters eventParams;
	eventParams.addParam("index", index);
	eventParams.addParam("cancel", cancel);
	_proxy->fireEvent(Ti::TiConstants::EventClick, eventParams);

	if(_alertQueue.isEmpty())
	{
		_alertShowing = false;
	}
	else
	{
		_alertQueue.last()->show();
	}
	_proxy->makeWeak();
}
}


text:
## SpotSpec

* [SpotSpec](#SpotSpec)
  * [new SpotSpec(options)](#new_SpotSpec_new)
  * [.prices(options)](#SpotSpec+prices)
  * [.launch(options)](#SpotSpec+launch)
  * [.describeRequests(options)](#SpotSpec+describeRequests)
  * [.describeInstances(options, instanceIds)](#SpotSpec+describeInstances)
  * [.terminateInstances(options, [instanceIds])](#SpotSpec+terminateInstances)
  * [.cancelSpotRequest(options, [spotInstanceRequestIds])](#SpotSpec+cancelSpotRequest)
  * ["initialized" (err, [initData])](#SpotSpec+event_initialized)
  * ["priced" (err, [priceData])](#SpotSpec+event_priced)
  * ["launched" (err, [launchData])](#SpotSpec+event_launched)
  * ["requests" (err, [spotInstanceRequests])](#SpotSpec+event_requests)
  * ["instances" (err, [instances])](#SpotSpec+event_instances)
  * ["terminated" (err)](#SpotSpec+event_terminated)
  * ["canceled" (err)](#SpotSpec+event_canceled)

### new SpotSpec(options)
Constructs a new SpotSpec Library

**Throws**:

- error

| Param | Type | Default | Description |
| --- | --- | --- | --- |
| options | object |  | The AWS service IAM credentials - See [aws docs](http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Credentials.html) |
| options.keys | object |  | AWS credentials |
| options.keys.accessKeyId | string |  | AWS access key ID |
| options.keys.secretAccessKey | string |  | AWS secret access key. |
| options.keys.region | string |  | The EC2 region to send service requests |
| options.upgrade | object |  | Temporary Session Token credentials - See [aws docs](http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/STS.html#getSessionToken-property) |
| options.upgrade.serialNumber | string |  | Identifies the user's hardware or virtual MFA device. |
| options.upgrade.tokenCode | string |  | Time-based one-time password (TOTP) that the MFA devices produces |
| [options.upgrade.durationSeconds] | number | 900 | How long the temporary key will last |
| [options.isLogging] | boolean | false | Use internal logging |

### spotSpec.prices(options)
prices - Request the latest spot prices

**Kind**: instance method of [SpotSpec](#SpotSpec)
**Emits**: [priced](#SpotSpec+event_priced)

| Param | Type | Default | Description |
| --- | --- | --- | --- |
| options | object |  | JSON options to request current price |
| poptions.type | string |  | The instance type to be priced e.g. m3.medium |
| [options.InstanceTypes] | Array.<string> |  | Array of instance types to be priced |
| [options.product] | string |  | The ProductDescriptions, e.g. 'Windows' |
| [options.ProductDescriptions] | Array.<string> |  | Array of ProductDescriptions, e.g. 'Windows' |
| [options.dryRun] | boolean | false | Only verify parameters. |
| [options.isLogging] | boolean | false |  |

### spotSpec.launch(options)
Launch a spot instance

**Kind**: instance method of [SpotSpec](#SpotSpec)
**Throws**:

- error

**Emits**: [launched](#SpotSpec+event_launched)

| Param | Type | Default | Description |
| --- | --- | --- | --- |
| options | object |  | JSON options to request a spot instance |
| options.ami | string |  | The amazon machine image name |
| options.type | string |  | The amazon Instance Type e.g. m3.medium |
| options.price | string |  | The maximum price limit |
| options.keyName | string |  | The name of the key pair needed to access the launched instance. See [user guide](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html) |
| [options.dryRun] | boolean | false | Only verify launch parameters. if TRUE, do not launch an instance |
| [options.count] | number | 1 | The InstanceCount number to launch |
| [options.securityGroupIds] | Array.<string> |  | Array of one or more security group ids. See [user guide](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html) |
| [options.securityGroups] | Array.<string> |  | Array of one or more security group names. See [user guide](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html) |
| [options.userData] | string |  | cloud-init *base64-encoded* text. See [user guide](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html#user-data-cloud-init) |
| options.launchSpecification | object |  | JSON of any additional launch specification. See [api guide](http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#requestSpotInstances-property) |

### spotSpec.describeRequests(options)
describeRequests - Describe the status of all current spot requests See [aws docs](http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/EC2.html#describeSpotInstanceRequests-property)

**Kind**: instance method of [SpotSpec](#SpotSpec)
**Emits**: [priced](#SpotSpec+event_priced)

| Param | Type | Default | Description |
| --- | --- | --- | --- |
| options | object |  | JSON options to request current price |
| [options.dryRun] | boolean | false | Only verify parameters. |

### spotSpec.describeInstances(options, instanceIds)
Describe the status of all running instance.

**Kind**: instance method of [SpotSpec](#SpotSpec)
**Emits**: {SpotSpec#event:Reservations[]} Array of EC2 instances

| Param | Type | Default | Description |
| --- | --- | --- | --- |
| options | object |  | JSON options to request current price |
| [options.dryRun] | boolean | false | Only verify parameters |
| instanceIds | Array.<string> |  | Array of instance ids to search |

### spotSpec.terminateInstances(options, [instanceIds])
Terminate an instance

**Kind**: instance method of [SpotSpec](#SpotSpec)
**Emits**: [terminated](#SpotSpec+event_terminated)

| Param | Type | Default | Description |
| --- | --- | --- | --- |
| options | object |  | JSON options to request current price |
| [instanceIds] | Array.<string> |  | Array of instance ids to terminate |
| [options.dryRun] | boolean | false | Only verify parameters. |

### spotSpec.cancelSpotRequest(options, [spotInstanceRequestIds])
Cancel a spot request

**Kind**: instance method of [SpotSpec](#SpotSpec)
**Emits**: [canceled](#SpotSpec+event_canceled)

| Param | Type | Default | Description |
| --- | --- | --- | --- |
| options | object |  | JSON options to request current price |
| [spotInstanceRequestIds] | Array.<string> |  | Array of instance ids to terminate |
| [options.dryRun] | boolean | false | Only verify parameters. |

### "initialized" (err, [initData])
Emitted as the response to constuct SpotSpec

**Kind**: event emitted by [SpotSpec](#SpotSpec)

| Param | Type | Description |
| --- | --- | --- |
| err | error | Only on error |
| [initData] | object | Null on error |

### "priced" (err, [priceData])
Emitted as the response to a prices request

**Kind**: event emitted by [SpotSpec](#SpotSpec)

| Param | Type | Description |
| --- | --- | --- |
| err | error | Only on error |
| [priceData] | Array.<SpotSpec#SpotPriceHistory> | Null on error |

### "launched" (err, [launchData])
Emitted as the response to a launch request

**Kind**: event emitted by [SpotSpec](#SpotSpec)

| Param | Type | Description |
| --- | --- | --- |
| err | error | Only on error |
| [launchData] | object | Null on error |

### "requests" (err, [spotInstanceRequests])
Emitted as the response to a describe requests 'request'

**Kind**: event emitted by [SpotSpec](#SpotSpec)

| Param | Type | Description |
| --- | --- | --- |
| err | error | Only on error |
| [spotInstanceRequests] | Array.<SpotSpec#SpotInstanceRequests> | Null on error |

### "instances" (err, [instances])
Emitted as the response to a describe instances request

**Kind**: event emitted by [SpotSpec](#SpotSpec)

| Param | Type | Description |
| --- | --- | --- |
| err | error | Only on error |
| [instances] | Array.<SpotSpec#reservations> | Null on error |

### "terminated" (err)
Emitted as the response to a terminate request

**Kind**: event emitted by [SpotSpec](#SpotSpec)

| Param | Type | Description |
| --- | --- | --- |
| err | error | Only on error |
|  | Array.<SpotSpec#TerminatingInstances> | Null on error |

### "canceled" (err)
Emitted as the response to a cancel request

**Kind**: event emitted by [SpotSpec](#SpotSpec)

| Param | Type | Description |
| --- | --- | --- |
| err | error | Only on error |
|  | Array.<SpotSpec#CancelledSpotInstanceRequests> | Null on error |


text:
;(function(factory){
	if(typeof define === 'function' && define.amd) {
		define(['../dd'], factory);
	} else {
		factory($dd);
	}
})(function(lib){
	lib.mixin({
		ioc: (function(){
			var ret = {},
				hash = {};

			ret.register = function(lookup,constructor){
				hash[lookup] = { c: constructor, i: null };
			};

			ret.get = function(lookup){
				if(!hash.hasOwnProperty(lookup)){
					throw new Error('$dd.di: nothing hooked up to ' + lookup);
				}
				if(!hash[lookup].i){
					hash[lookup].i = new hash[lookup].c();
				}
				return hash[lookup].i;
			};

			return ret;
		})()
	});
});