text:
package uk.ac.ebi.gxa.tasks;

import com.google.common.collect.HashMultimap;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.ac.ebi.gxa.loader.*;
import uk.ac.ebi.gxa.loader.listener.AtlasLoaderEvent;
import uk.ac.ebi.gxa.loader.listener.AtlasLoaderListener;
import uk.ac.ebi.microarray.atlas.model.Experiment;

import java.net.MalformedURLException;

/**
 * Set of loader tasks implementation. Handles loads of experiments and arry designs,
 * unloads of experiments and updates of experiment's NetCDFs.
 *
 * @author pashky
 */
public class LoaderTask extends AbstractWorkingTask {
    private static Logger log = LoggerFactory.getLogger(LoaderTask.class);

    public static final String TYPE_LOADEXPERIMENT = "loadexperiment";
    public static final String TYPE_LOADARRAYDESIGN = "loadarraydesign";
    private static final String TYPE_LOADANNOTATIONS = "loadannotations";
    private static final String TYPE_LOADMAPPING = "loadmapping";
    public static final String TYPE_UPDATEEXPERIMENT = "updateexperiment";
    private static final String TYPE_UNLOADEXPERIMENT = "unloadexperiment";
    private static final String TYPE_PRIVATEEXPERIMENT = "makeexperimentprivate";
    private static final String TYPE_PUBLICEXPERIMENT = "makeexperimentpublic";

    public static TaskSpec SPEC_UPDATEEXPERIMENT(String accession) {
        return new TaskSpec(TYPE_UPDATEEXPERIMENT, accession, HashMultimap.<String, String>create());
    }

    private volatile boolean stop = false;

    private AtlasLoaderCommand getLoaderCommand() throws MalformedURLException {
        if (TYPE_LOADEXPERIMENT.equals(getTaskSpec().getType()))
            return new LoadExperimentCommand(getTaskSpec().getAccession(),
                    taskMan.getAtlasProperties().getLoaderPossibleQuantitaionTypes(), getTaskSpec().getUserData());

        else if (TYPE_UPDATEEXPERIMENT.equals(getTaskSpec().getType()))
                    return new UpdateNetCDFForExperimentCommand(getTaskSpec().getAccession());

        else if (TYPE_UNLOADEXPERIMENT.equals(getTaskSpec().getType()))
            return new UnloadExperimentCommand(getTaskSpec().getAccession());

        else if (TYPE_PRIVATEEXPERIMENT.equals(getTaskSpec().getType()))
            return new MakeExperimentPrivateCommand(getTaskSpec().getAccession());

        else if (TYPE_PUBLICEXPERIMENT.equals(getTaskSpec().getType()))
            return new MakeExperimentPublicCommand(getTaskSpec().getAccession());

        throw new IllegalStateException();
    }

    public void start() {
        if (nothingToDo())
            return;

        startTimer();
        taskMan.updateTaskStage(getTaskSpec(), TaskStatus.INCOMPLETE);
        taskMan.writeTaskLog(LoaderTask.this, TaskEvent.STARTED, "");

        AtlasLoaderListener listener = new AtlasLoaderListener() {
            public void loadSuccess(AtlasLoaderEvent event) {
                taskMan.writeTaskLog(LoaderTask.this, TaskEvent.FINISHED, "");
                taskMan.updateTaskStage(getTaskSpec(), TaskStatus.DONE);

                for (String accession : event.getAccessions()) {
                    if (TYPE_LOADEXPERIMENT.equals(getTaskSpec().getType()) ||
                            TYPE_UPDATEEXPERIMENT.equals(getTaskSpec().getType())) {
                        taskMan.addTaskTag(LoaderTask.this, TaskTagType.EXPERIMENT, accession);

                        if (TYPE_LOADEXPERIMENT.equals(getTaskSpec().getType()))
                            taskMan.updateTaskStage(SPEC_UPDATEEXPERIMENT(accession), TaskStatus.DONE);

                        TaskSpec analyticsTask = AnalyticsTask.SPEC_ANALYTICS(accession);
                        if (event.isRecomputeStatistics()) {
                            taskMan.updateTaskStage(analyticsTask, TaskStatus.INCOMPLETE);
                        } else {
                            log.info("Analytics was preserved in NetCDF, no need to recompute");
                        }

                        final TaskSpec indexTask = IndexTask.SPEC_INDEXALL;
                        taskMan.updateTaskStage(indexTask, TaskStatus.INCOMPLETE);

                        if (!stop && isRunningAutoDependencies()) {
                            taskMan.scheduleTask(
                                    LoaderTask.this,
                                    event.isRecomputeStatistics() ? analyticsTask : indexTask,
                                    TaskRunMode.RESTART,
                                    getUser(),
                                    true,
                                    "Automatically added by experiment " + getTaskSpec().getAccession() + " loading task");
                        }
                    } else if (TYPE_UNLOADEXPERIMENT.equals(getTaskSpec().getType())) {
                        TaskSpec experimentTask = AnalyticsTask.SPEC_ANALYTICS(accession);
                        taskMan.updateTaskStage(experimentTask, TaskStatus.NONE);

                        taskMan.updateTaskStage(IndexTask.SPEC_INDEXALL, TaskStatus.INCOMPLETE);
                        if (!stop && isRunningAutoDependencies()) {
                            taskMan.scheduleTask(LoaderTask.this, IndexTask.SPEC_INDEXALL, TaskRunMode.CONTINUE, getUser(), true,
                                    "Automatically added by experiment " + getTaskSpec().getAccession() + " unloading task");
                        }
                    } else if (TYPE_LOADARRAYDESIGN.equals(getTaskSpec().getType())) {
                        taskMan.addTaskTag(LoaderTask.this, TaskTagType.ARRAYDESIGN, accession);

                        for (Experiment experiment : taskMan.getAtlasDAO().getExperimentsByArrayDesignAccession(accession)) {
                            taskMan.addTaskTag(LoaderTask.this, TaskTagType.EXPERIMENT, experiment.getAccession());
                            taskMan.updateTaskStage(LoaderTask.SPEC_UPDATEEXPERIMENT(experiment.getAccession()), TaskStatus.INCOMPLETE);
                        }

                        if (!stop && isRunningAutoDependencies()) {
                            for (Experiment experiment : taskMan.getAtlasDAO().getExperimentsByArrayDesignAccession(accession)) {
                                taskMan.scheduleTask(LoaderTask.this, LoaderTask.SPEC_UPDATEEXPERIMENT(experiment.getAccession()),
                                        TaskRunMode.CONTINUE, getUser(), true,
                                        "Automatically added by array design " + getTaskSpec().getAccession() + " loading task");
                            }
                        }
                    } else if (TYPE_LOADANNOTATIONS.equals(getTaskSpec().getType())) {
                        taskMan.addTaskTag(LoaderTask.this, TaskTagType.ANNOTATIONS, accession);

                    } else if (TYPE_LOADMAPPING.equals(getTaskSpec().getType())) {
                        taskMan.addTaskTag(LoaderTask.this, TaskTagType.MAPPING, accession);
                    }
                }
                taskMan.notifyTaskFinished(LoaderTask.this);
            }

            public void loadError(AtlasLoaderEvent event) {
                for (Throwable e : event.getErrors()) {
                    log.error("Task failed because of:", e);
                }
                taskMan.writeTaskLog(LoaderTask.this, TaskEvent.FAILED, StringUtils.join(event.getErrors(), '\n'));
                taskMan.notifyTaskFinished(LoaderTask.this);
            }

            public void loadProgress(String progress) {
                currentProgress = progress;
            }

            public void loadWarning(String message) {
                taskMan.writeTaskLog(LoaderTask.this, TaskEvent.WARNING, message);
            }
        };

        try {
            getLoaderCommand();
            taskMan.getLoader().doCommand(getLoaderCommand(), listener);
        } catch (MalformedURLException e) {
            taskMan.writeTaskLog(LoaderTask.this, TaskEvent.FAILED, "Invalid URL " + getTaskSpec().getAccession());
            taskMan.notifyTaskFinished(LoaderTask.this);
        } catch (Throwable e) {
            taskMan.writeTaskLog(LoaderTask.this, TaskEvent.FAILED, e.toString());
            taskMan.notifyTaskFinished(LoaderTask.this);
        }
    }

    public void stop() {
        stop = true;
    }

    private LoaderTask(TaskManager taskMan, long taskId, TaskSpec taskSpec, TaskRunMode runMode, TaskUser user, boolean runningAutoDependencies) {
        super(taskMan, taskId, taskSpec, runMode, user, runningAutoDependencies);
        taskMan.addTaskTag(LoaderTask.this,
                TYPE_UPDATEEXPERIMENT.equals(taskSpec.getType()) || TYPE_UNLOADEXPERIMENT.equals(taskSpec.getType())
                        ? TaskTagType.EXPERIMENT : TaskTagType.URL,
                getTaskSpec().getAccession());
    }

    public boolean isBlockedBy(Task by) {
        return false;
    }

    public static final TaskFactory FACTORY = new TaskFactory() {
        public QueuedTask createTask(TaskManager taskMan, long taskId, TaskSpec taskSpec, TaskRunMode runMode, TaskUser user, boolean runningAutoDependencies) {
            return new LoaderTask(taskMan, taskId, taskSpec, runMode, user, runningAutoDependencies);
        }

        public boolean isFor(TaskSpec taskSpec) {

            return TYPE_LOADEXPERIMENT.equals(taskSpec.getType())
                    || TYPE_LOADARRAYDESIGN.equals(taskSpec.getType())
                    || TYPE_LOADANNOTATIONS.equals(taskSpec.getType())
                    || TYPE_LOADMAPPING.equals(taskSpec.getType())
                    || TYPE_UPDATEEXPERIMENT.equals(taskSpec.getType())
                    || TYPE_UNLOADEXPERIMENT.equals(taskSpec.getType())
                    || TYPE_PRIVATEEXPERIMENT.equals(taskSpec.getType())
                    || TYPE_PUBLICEXPERIMENT.equals(taskSpec.getType())
                    ;
        }
    };

}


text:
/* eslint-env jasmine */
import { parser } from './parser/classDiagram';
import classDb from './classDb';

describe('class diagram, ', function() {
  describe('when parsing an info graph it', function() {
    beforeEach(function() {
      parser.yy = classDb;
    });

    it('should handle relation definitions', function() {
      const str =
        'classDiagram\n' +
        'Class01 <|-- Class02\n' +
        'Class03 *-- Class04\n' +
        'Class05 o-- Class06\n' +
        'Class07 .. Class08\n' +
        'Class09 -- Class1';

      parser.parse(str);
    });
    it('should handle relation definition of different types and directions', function() {
      const str =
        'classDiagram\n' +
        'Class11 <|.. Class12\n' +
        'Class13 --> Class14\n' +
        'Class15 ..> Class16\n' +
        'Class17 ..|> Class18\n' +
        'Class19 <--* Class20';

      parser.parse(str);
    });

    it('should handle cardinality and labels', function() {
      const str =
        'classDiagram\n' +
        'Class01 "1" *-- "many" Class02 : contains\n' +
        'Class03 o-- Class04 : aggregation\n' +
        'Class05 --> "1" Class06';

      parser.parse(str);
    });
    it('should handle class definitions', function() {
      const str =
        'classDiagram\n' +
        'class Car\n' +
        'Driver -- Car : drives >\n' +
        'Car *-- Wheel : have 4 >\n' +
        'Car -- Person : < owns';

      parser.parse(str);
    });

    it('should handle method statements', function() {
      const str =
        'classDiagram\n' +
        'Object <|-- ArrayList\n' +
        'Object : equals()\n' +
        'ArrayList : Object[] elementData\n' +
        'ArrayList : size()';

      parser.parse(str);
    });
    it('should handle parsing of method statements  grouped by brackets', function() {
      const str =
        'classDiagram\n' +
        'class Dummy {\n' +
        'String data\n' +
        '  void methods()\n' +
        '}\n' +
        '\n' +
        'class Flight {\n' +
        '   flightNumber : Integer\n' +
        '   departureTime : Date\n' +
        '}';

      parser.parse(str);
    });

    it('should handle parsing of separators', function() {
      const str =
        'classDiagram\n' +
        'class Foo1 {\n' +
        '  You can use\n' +
        '  several lines\n' +
        '..\n' +
        'as you want\n' +
        'and group\n' +
        '==\n' +
        'things together.\n' +
        '__\n' +
        'You can have as many groups\n' +
        'as you want\n' +
        '--\n' +
        'End of class\n' +
        '}\n' +
        '\n' +
        'class User {\n' +
        '.. Simple Getter ..\n' +
        '+ getName()\n' +
        '+ getAddress()\n' +
        '.. Some setter ..\n' +
        '+ setName()\n' +
        '__ private data __\n' +
        'int age\n' +
        '-- encrypted --\n' +
        'String password\n' +
        '}';

      parser.parse(str);
    });
  });

  describe('when fetching data from an classDiagram graph it', function() {
    beforeEach(function() {
      parser.yy = classDb;
      parser.yy.clear();
    });
    it('should handle relation definitions EXTENSION', function() {
      const str = 'classDiagram\n' + 'Class01 <|-- Class02';

      parser.parse(str);

      const relations = parser.yy.getRelations();

      expect(parser.yy.getClass('Class01').id).toBe('Class01');
      expect(parser.yy.getClass('Class02').id).toBe('Class02');
      expect(relations[0].relation.type1).toBe(classDb.relationType.EXTENSION);
      expect(relations[0].relation.type2).toBe('none');
      expect(relations[0].relation.lineType).toBe(classDb.lineType.LINE);
    });
    it('should handle relation definitions AGGREGATION and dotted line', function() {
      const str = 'classDiagram\n' + 'Class01 o.. Class02';

      parser.parse(str);

      const relations = parser.yy.getRelations();

      expect(parser.yy.getClass('Class01').id).toBe('Class01');
      expect(parser.yy.getClass('Class02').id).toBe('Class02');
      expect(relations[0].relation.type1).toBe(classDb.relationType.AGGREGATION);
      expect(relations[0].relation.type2).toBe('none');
      expect(relations[0].relation.lineType).toBe(classDb.lineType.DOTTED_LINE);
    });
    it('should handle relation definitions COMPOSITION on both sides', function() {
      const str = 'classDiagram\n' + 'Class01 *--* Class02';

      parser.parse(str);

      const relations = parser.yy.getRelations();

      expect(parser.yy.getClass('Class01').id).toBe('Class01');
      expect(parser.yy.getClass('Class02').id).toBe('Class02');
      expect(relations[0].relation.type1).toBe(classDb.relationType.COMPOSITION);
      expect(relations[0].relation.type2).toBe(classDb.relationType.COMPOSITION);
      expect(relations[0].relation.lineType).toBe(classDb.lineType.LINE);
    });
    it('should handle relation definitions no types', function() {
      const str = 'classDiagram\n' + 'Class01 -- Class02';

      parser.parse(str);

      const relations = parser.yy.getRelations();

      expect(parser.yy.getClass('Class01').id).toBe('Class01');
      expect(parser.yy.getClass('Class02').id).toBe('Class02');
      expect(relations[0].relation.type1).toBe('none');
      expect(relations[0].relation.type2).toBe('none');
      expect(relations[0].relation.lineType).toBe(classDb.lineType.LINE);
    });
    it('should handle relation definitions with type only on right side', function() {
      const str = 'classDiagram\n' + 'Class01 --|> Class02';

      parser.parse(str);

      const relations = parser.yy.getRelations();

      expect(parser.yy.getClass('Class01').id).toBe('Class01');
      expect(parser.yy.getClass('Class02').id).toBe('Class02');
      expect(relations[0].relation.type1).toBe('none');
      expect(relations[0].relation.type2).toBe(classDb.relationType.EXTENSION);
      expect(relations[0].relation.lineType).toBe(classDb.lineType.LINE);
    });

    it('should handle multiple classes and relation definitions', function() {
      const str =
        'classDiagram\n' +
        'Class01 <|-- Class02\n' +
        'Class03 *-- Class04\n' +
        'Class05 o-- Class06\n' +
        'Class07 .. Class08\n' +
        'Class09 -- Class10';

      parser.parse(str);

      const relations = parser.yy.getRelations();

      expect(parser.yy.getClass('Class01').id).toBe('Class01');
      expect(parser.yy.getClass('Class10').id).toBe('Class10');

      expect(relations.length).toBe(5);

      expect(relations[0].relation.type1).toBe(classDb.relationType.EXTENSION);
      expect(relations[0].relation.type2).toBe('none');
      expect(relations[0].relation.lineType).toBe(classDb.lineType.LINE);
      expect(relations[3].relation.type1).toBe('none');
      expect(relations[3].relation.type2).toBe('none');
      expect(relations[3].relation.lineType).toBe(classDb.lineType.DOTTED_LINE);
    });
  });
});

redpajama_set_name: RedPajamaGithub


text:
<?php

require_once '../repository/HotelRepository.php';
require_once '../repository/CommentRepository.php';
require_once '../lib/Validation.php';

/**
 *
 */
class CommentController
{

  /**
      *Beim aufrufen der Funktion showhotels werden alle Hotels angazeigt und der User kann auswählen wo er einen Komentar abgeben möchte.
  **/

  public function showhotels(){
    {
        $view = new View('comment_showhotels');
        $view->title = 'Bewertung';
        $view->heading = 'Bewertung';

        $hotelRepo = new HotelRepository();

        $hotels = $hotelRepo->readAllWithProperties();
        $view->hotels = $hotels;

        $view->display();
    }
  }

  /**
      *Beim aufrufen der Funktion rate wird das ausgewählte Hotel angezeigt so wie ein Bereich wo der User seinen Kommentar da lassen kann.
      * @param $fault wird dazu verwendet falls ein Fehler auftaucht diesen auszugeben
      * @param $comment Wird dazu verwendet, das wenn ein fehler auftaucht der komentar nicht neu geschrieben werden muss sondern übergeben werden kann.
  **/

  public function rate($comment = '', $fault = ''){
      $hotelRepo = new HotelRepository();
      $hotel = $hotelRepo->readById($_GET['hotel']);

      $view = new View('comment_rate');
      $view->title = 'Bewertung';
      $view->heading = 'Bewertung';
      $view->hotel = $hotel;
      $view->comment = $comment;
      $view->fault = $fault;
      $view->display();

  }

  /**
      *Beim aufrufen der Funktion sendcomment wird geprüft ob der neue Kommentar valied ist. Wenn ja wird er in die DB gespeichert und der User ladet auf der azeige aller Kommentare.
      *Wenn nein wir der User wieder auf die Seite zurückgeschickt auf welcher er den Kommentar erfasst hat und er erhält eine fehlermeldung.
  **/

  public function sendcomment(){
    $validator = new Validation();
    $comentrepo = new CommentRepository();

    $hotel_id = $_GET['hotel'];
    $content = $_POST['content'];
    $user_id = $_SESSION['Userid'];

    if(!empty($content) && is_string($content) && $validator->maxlengthchecker($content, 400)){
        $content = htmlspecialchars($content);
        $comentrepo->insert($user_id, $hotel_id, $content);
        header("Location: /hotel/showcomments?hotel=$hotel_id");
      } else {
        $fault = 'Bei der Übermitlung ist ein fehler pasiert bitte senden sie den Kommentar erneut.';
        $this->rate($content, $fault);
      }
  }

  /**
  *Diese Funktion erstellt ein fenster auf welchem ein eintrag geladen wird und verändert werden kann.
  **/

  public function update($comment = '', $fault = ''){
    $hotelRepo = new HotelRepository();
    $hotel = $hotelRepo->readById($_GET['hotel']);

    if($comment == ''){
      $commentReop = new CommentRepository();
      $comment = $commentReop->readById($_GET['id']);
    }

    $view = new View('comment_update');
    $view->title = 'Bewertung ändern';
    $view->heading = 'Bewertung ändern';
    $view->hotel = $hotel;
    $view->comment = $comment;
    $view->fault = $fault;
    $view->display();

  }

  /**
  *Diese Funktion Prüfft ob etwas eingegeben worden ist und updated anschliessend diesen Kommentar in der DB.
  */

  public function doupdate(){
    $validator = new Validation();
    $comentrepo = new CommentRepository();

    $hotel_id = $_GET['hotel'];
    $comment_id = $_GET['comment'];
    $content = $_POST['content'];
    $user_id = $_SESSION['Userid'];

    if(!empty($content) && is_string($content) && $validator->maxlengthchecker($content, 400)){
        $content = htmlspecialchars($content);
        $comentrepo->update($comment_id, $content);
        header("Location: /hotel/showcomments?hotel=$hotel_id");
      } else {
        $fault = 'Bei der Übermitlung ist ein fehler pasiert bitte senden sie den Kommentar erneut.';
        $this->rate($content, $fault);
      }
  }
}


text:
class InflectionalObject < ActiveRecord::Base;
  belongs_to :inflectional_form
end


text:
import {V1StepModel, V1WorkflowInputParameterModel, V1WorkflowOutputParameterModel} from "../v1.0";
import {V1WorkflowStepInputModel} from "../v1.0/V1WorkflowStepInputModel";
import {V1WorkflowStepOutputModel} from "../v1.0/V1WorkflowStepOutputModel";
import {expect} from "chai";
import {checkIfConnectionIsValid} from "./connection-util";

describe("checkIfConnectionIsValid", () => {

    it("should be invalid when ource and destination port belong to the same step", () => {

        const parentStep = new V1StepModel();

        const input  = new V1WorkflowStepInputModel(null, parentStep);
        const output = new V1WorkflowStepOutputModel(null, parentStep);

        expect(() => checkIfConnectionIsValid(input, output))
            .to.throws("Invalid connection. Source and destination ports belong to the same step");

    });

    it("should be valid for same types or same items", () => {

        const inputFile = new V1WorkflowInputParameterModel({
            id: "pointA",
            type: "File"
        });

        const outputFile = new V1WorkflowOutputParameterModel({
            id: "pointB",
            type: "File"
        });

        const inputFileArray = new V1WorkflowInputParameterModel({
            id: "pointA",
            type: "[File]"
        });

        const outputFileArray = new V1WorkflowOutputParameterModel({
            id: "pointB",
            type: "[File]"
        });

        expect(checkIfConnectionIsValid(inputFile, outputFile)).equal(true);
        expect(checkIfConnectionIsValid(inputFileArray, outputFileArray)).equal(true);

    });

    it("should be invalid for different types or different items", () => {

        const inputFile = new V1WorkflowInputParameterModel({
            id: "pointA",
            type: "File"
        });

        const outputString = new V1WorkflowOutputParameterModel({
            id: "pointB",
            type: "string"
        });

        const inputFileArray = new V1WorkflowInputParameterModel({
            id: "pointA",
            type: "File[]"
        });

        const outputStringArray = new V1WorkflowOutputParameterModel({
            id: "pointB",
            type: "string[]"
        });

        expect(() => checkIfConnectionIsValid(inputFile, outputString))
            .to.throw(`Invalid connection. Connection type mismatch, attempting to connect "File" to "string"`);

        expect(() => checkIfConnectionIsValid(inputFileArray, outputStringArray))
            .to.throw(`Invalid connection. Connection type mismatch, attempting to connect "File[]" to "string[]"`);

    });

    it("should be valid when source type is equal to destination items", () => {

        const inputFile = new V1WorkflowInputParameterModel({
            id: "pointA",
            type: "File"
        });

        const outputFileArray = new V1WorkflowOutputParameterModel({
            id: "pointB",
            type: "File[]"
        });

        expect(checkIfConnectionIsValid(inputFile, outputFileArray)).equal(true);
    });

    it("should be invalid when destination type is equal to source items", () => {

        const inputFile = new V1WorkflowInputParameterModel({
            id: "pointA",
            type: "File[]"
        });

        const outputFileArray = new V1WorkflowOutputParameterModel({
            id: "pointB",
            type: "File"
        });

        // inputFile to outputFileArray
        expect(() => checkIfConnectionIsValid(inputFile, outputFileArray))
            .to.throws(`Invalid connection. Connection type mismatch, attempting to connect "File[]" to "File"`);

        // outputFileArray to inputFile
        expect(checkIfConnectionIsValid(inputFile, outputFileArray, false)).equal(true);
    });

    it("should be valid when source (File) and destination (File) file-types have an intersection or one or both are empty", () => {

        const inputFile = new V1WorkflowInputParameterModel({
            id: "pointA",
            type: "File"
        });

        const outputFile = new V1WorkflowOutputParameterModel({
            id: "pointB",
            type: "File"
        });

        inputFile.fileTypes  = [];
        outputFile.fileTypes = [];

        expect(checkIfConnectionIsValid(inputFile, outputFile)).equal(true);

        inputFile.fileTypes = ["s", "c", "d"];
        expect(checkIfConnectionIsValid(inputFile, outputFile)).equal(true);

        inputFile.fileTypes  = [];
        outputFile.fileTypes = ["B", "c", "d"];
        expect(checkIfConnectionIsValid(inputFile, outputFile)).equal(true);

        inputFile.fileTypes  = ["D", "c"];
        outputFile.fileTypes = ["b", "C", "d"];
        expect(checkIfConnectionIsValid(inputFile, outputFile)).equal(true);
    });

    it("should be valid when source (File[]) and destination (File[]) file-types have an intersection or one or both are empty", () => {

        const inputFileArray = new V1WorkflowInputParameterModel({
            id: "pointA",
            type: "File[]"
        });

        const outputFileArray = new V1WorkflowOutputParameterModel({
            id: "pointB",
            type: "File[]"
        });

        inputFileArray.fileTypes  = [];
        outputFileArray.fileTypes = [];

        expect(checkIfConnectionIsValid(inputFileArray, outputFileArray)).equal(true);

        inputFileArray.fileTypes = ["s", "c", "d"];
        expect(checkIfConnectionIsValid(inputFileArray, outputFileArray)).equal(true);

        inputFileArray.fileTypes  = [];
        outputFileArray.fileTypes = ["B", "c", "d"];
        expect(checkIfConnectionIsValid(inputFileArray, outputFileArray)).equal(true);

        inputFileArray.fileTypes  = ["D", "c"];
        outputFileArray.fileTypes = ["b", "C", "d"];
        expect(checkIfConnectionIsValid(inputFileArray, outputFileArray)).equal(true);
    });

    it("should be invalid when source (File) and destination (File) file-types does not have an intersection", () => {

        const inputFile     = new V1WorkflowInputParameterModel({
            id: "pointA",
            type: "File"
        });
        inputFile.fileTypes = ["a"];

        const outputFile = new V1WorkflowOutputParameterModel({
            id: "pointB",
            type: "File"
        });

        outputFile.fileTypes = ["d", "c"];

        expect(() => checkIfConnectionIsValid(inputFile, outputFile))
            .to.throws(`Invalid connection. File type mismatch, connecting formats "a" to "d,c"`);
    });

    it("should be invalid when source (File[]) and destination (File[]) file-types does not have an intersection", () => {

        const inputFileArray     = new V1WorkflowInputParameterModel({
            id: "pointA",
            type: "File[]"
        });
        inputFileArray.fileTypes = ["a"];

        const outputFileArray = new V1WorkflowOutputParameterModel({
            id: "pointB",
            type: "File[]"
        });

        outputFileArray.fileTypes = ["d", "c"];

        expect(() => checkIfConnectionIsValid(inputFileArray, outputFileArray))
            .to.throws(`Invalid connection. File type mismatch, connecting formats "a" to "d,c"`);
    });

    it("should be valid when source is (File)[] and destination is (union)[]", () => {

        const input = new V1WorkflowInputParameterModel({
            id: "pointA",
            type: "File[]"
        });

        const output = new V1WorkflowOutputParameterModel({
            id: "pointB",
            type: {
                type: "array",
                items: ["File", "null"]
            }
        });

        expect(checkIfConnectionIsValid(input, output)).equal(true);

    });

    it("should be valid when source is object[] and destination is object[]", () => {

        const input = new V1WorkflowInputParameterModel({
            id: "pointA",
            type: {
                type: "array",
                items: {
                    "items": "string",
                    "type": "array"
                }
            }
        });

        const output = new V1WorkflowOutputParameterModel({
            id: "pointB",
            type: {
                type: "array",
                items: {
                    "items": "string",
                    "type": "array"
                }
            }
        });

        expect(checkIfConnectionIsValid(input, output)).equal(true);

    });

    it("should be valid when source is object[] and destination is union[]", () => {

        const input = new V1WorkflowInputParameterModel({
            id: "pointA",
            type: {
                type: "array",
                items: {
                    "items": "string",
                    "type": "array"
                }
            }
        });

        const output = new V1WorkflowOutputParameterModel({
            id: "pointB",
            type: {
                type: "array",
                items: ["File", "null"]
            }
        });

        expect(checkIfConnectionIsValid(input, output)).equal(true);

    });

    it("should be valid when source is union[] and destination is object[]", () => {

        const input = new V1WorkflowInputParameterModel({
            id: "pointA",
            type: {
                type: "array",
                items: ["File", "null"]
            }
        });

        const output = new V1WorkflowOutputParameterModel({
            id: "pointB",
            type: {
                type: "array",
                items: {
                    "items": "string",
                    "type": "array"
                }
            }
        });

        expect(checkIfConnectionIsValid(input, output)).equal(true);

    });

    it("should be valid when source is File and destination is union[]", () => {

        const input = new V1WorkflowInputParameterModel({
            id: "pointA",
            type: "File"
        });

        const output = new V1WorkflowOutputParameterModel({
            id: "pointB",
            type: {
                type: "array",
                items: ["File", "null"]
            }
        });

        expect(checkIfConnectionIsValid(input, output)).equal(true);
    });

    it("should be invalid when source is object[] and destination is File", () => {

        const input = new V1WorkflowInputParameterModel({
            id: "pointA",
            type: {
                type: "array",
                items: {
                    "items": "string",
                    "type": "array"
                }
            }
        });

        const output = new V1WorkflowOutputParameterModel({
            id: "pointB",
            type: "File"
        });

        expect(() => checkIfConnectionIsValid(input, output))
            .to.throw(`Invalid connection. Connection type mismatch, attempting to connect "object[]" to "File"`);
    });

    it("should be invalid when source is union[] and destination is File", () => {

        const input = new V1WorkflowInputParameterModel({
            id: "pointA",
            type: {
                type: "array",
                items: ["File", "null"]
            }
        });

        const output = new V1WorkflowOutputParameterModel({
            id: "pointB",
            type: "File"
        });

        expect(() => checkIfConnectionIsValid(input, output))
            .to.throw(`Invalid connection. Connection type mismatch, attempting to connect "union[]" to "File"`);
    });

    it("should be invalid when source is File and destination is object[]", () => {

        const input = new V1WorkflowInputParameterModel({
            id: "pointA",
            type: "File"
        });

        const output = new V1WorkflowOutputParameterModel({
            id: "pointB",
            type: {
                type: "array",
                items: {
                    "items": "string",
                    "type": "array"
                }
            }
        });

        expect(() => checkIfConnectionIsValid(input, output))
            .to.throw(`Invalid connection. Connection type mismatch, attempting to connect "File" to "object[]"`);
    });

    it("should be invalid when source is File[] and destination is object[]", () => {

        const input = new V1WorkflowInputParameterModel({
            id: "pointA",
            type: "File[]"
        });

        const output = new V1WorkflowOutputParameterModel({
            id: "pointB",
            type: {
                type: "array",
                items: {
                    "items": "string",
                    "type": "array"
                }
            }
        });

        expect(() => checkIfConnectionIsValid(input, output))
            .to.throw(`Invalid connection. Connection type mismatch, attempting to connect "File[]" to "object[]"`);
    });

    it("should be invalid when source is File and destination is record", () => {

        const input = new V1WorkflowInputParameterModel({
            id: "pointA",
            type: "File"
        });

        const output = new V1WorkflowOutputParameterModel({
            id: "pointB",
            type: {
                type: "record",
                fields: [
                    {
                        "name": "description",
                        "type": "string"
                    }]
            }
        });

        expect(() => checkIfConnectionIsValid(input, output))
            .to.throw(`Invalid connection. Connection type mismatch, attempting to connect "File" to "record"`);
    });

    it("should be valid when source is (record)[] and destination is (object)[]", () => {

        const input = new V1WorkflowInputParameterModel({
            id: "pointA",
            type: {
                type: "array",
                items: {
                    type: "record",
                    fields: [{
                        name: "files",
                        type: "File[]"
                    }]
                }
            }
        });

        const output = new V1WorkflowOutputParameterModel({
            id: "pointB",
            type: {
                type: "array",
                items: {
                    "items": "string",
                    "type": "array"
                }
            }
        });

        expect(checkIfConnectionIsValid(input, output)).equal(true);
    });

    it("should be valid when source is object[] and destination is record[]", () => {

        const input = new V1WorkflowInputParameterModel({
            id: "pointA",
            type: {
                type: "array",
                items: {
                    "items": "string",
                    "type": "array"
                }
            }
        });

        const output = new V1WorkflowOutputParameterModel({
            id: "pointB",
            type: {
                type: "array",
                items: {
                    type: "record",
                    fields: [{
                        name: "files",
                        type: "File[]"
                    }]
                }
            }
        });

        expect(checkIfConnectionIsValid(input, output)).equal(true);
    });

});


text:
.class public final enum Lcom/sonyericsson/fmradio/service/TimerHandler$TimerType;
.super Ljava/lang/Enum;
.source "TimerHandler.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/sonyericsson/fmradio/service/TimerHandler;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x4019
    name = "TimerType"
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "Ljava/lang/Enum",
        "<",
        "Lcom/sonyericsson/fmradio/service/TimerHandler$TimerType;",
        ">;"
    }
.end annotation

# static fields
.field private static final synthetic $VALUES:[Lcom/sonyericsson/fmradio/service/TimerHandler$TimerType;

.field public static final enum PHF_REMOVED:Lcom/sonyericsson/fmradio/service/TimerHandler$TimerType;

.field public static final enum POWER_OFF:Lcom/sonyericsson/fmradio/service/TimerHandler$TimerType;

# instance fields
.field private mTimeout:I

# direct methods
.method static constructor <clinit>()V
    .locals 5

    .prologue
    const/16 v4, 0x2710

    const/4 v3, 0x1

    const/4 v2, 0x0

    .line 28
    new-instance v0, Lcom/sonyericsson/fmradio/service/TimerHandler$TimerType;

    const-string v1, "POWER_OFF"

    invoke-direct {v0, v1, v2, v4}, Lcom/sonyericsson/fmradio/service/TimerHandler$TimerType;-><init>(Ljava/lang/String;II)V

    sput-object v0, Lcom/sonyericsson/fmradio/service/TimerHandler$TimerType;->POWER_OFF:Lcom/sonyericsson/fmradio/service/TimerHandler$TimerType;

    .line 29
    new-instance v0, Lcom/sonyericsson/fmradio/service/TimerHandler$TimerType;

    const-string v1, "PHF_REMOVED"

    invoke-direct {v0, v1, v3, v4}, Lcom/sonyericsson/fmradio/service/TimerHandler$TimerType;-><init>(Ljava/lang/String;II)V

    sput-object v0, Lcom/sonyericsson/fmradio/service/TimerHandler$TimerType;->PHF_REMOVED:Lcom/sonyericsson/fmradio/service/TimerHandler$TimerType;

    .line 27
    const/4 v0, 0x2

    new-array v0, v0, [Lcom/sonyericsson/fmradio/service/TimerHandler$TimerType;

    sget-object v1, Lcom/sonyericsson/fmradio/service/TimerHandler$TimerType;->POWER_OFF:Lcom/sonyericsson/fmradio/service/TimerHandler$TimerType;

    aput-object v1, v0, v2

    sget-object v1, Lcom/sonyericsson/fmradio/service/TimerHandler$TimerType;->PHF_REMOVED:Lcom/sonyericsson/fmradio/service/TimerHandler$TimerType;

    aput-object v1, v0, v3

    sput-object v0, Lcom/sonyericsson/fmradio/service/TimerHandler$TimerType;->$VALUES:[Lcom/sonyericsson/fmradio/service/TimerHandler$TimerType;

    return-void
.end method

.method private constructor <init>(Ljava/lang/String;II)V
    .locals 0
    .parameter
    .parameter
    .parameter "timeout"
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(I)V"
        }
    .end annotation

    .prologue
    .line 36
    invoke-direct {p0, p1, p2}, Ljava/lang/Enum;-><init>(Ljava/lang/String;I)V

    .line 37
    iput p3, p0, Lcom/sonyericsson/fmradio/service/TimerHandler$TimerType;->mTimeout:I

    .line 38
    return-void
.end method

.method public static valueOf(Ljava/lang/String;)Lcom/sonyericsson/fmradio/service/TimerHandler$TimerType;
    .locals 1
    .parameter "name"

    .prologue
    .line 27
    const-class v0, Lcom/sonyericsson/fmradio/service/TimerHandler$TimerType;

    invoke-static {v0, p0}, Ljava/lang/Enum;->valueOf(Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/Enum;

    move-result-object v0

    check-cast v0, Lcom/sonyericsson/fmradio/service/TimerHandler$TimerType;

    return-object v0
.end method

.method public static values()[Lcom/sonyericsson/fmradio/service/TimerHandler$TimerType;
    .locals 1

    .prologue
    .line 27
    sget-object v0, Lcom/sonyericsson/fmradio/service/TimerHandler$TimerType;->$VALUES:[Lcom/sonyericsson/fmradio/service/TimerHandler$TimerType;

    invoke-virtual {v0}, [Lcom/sonyericsson/fmradio/service/TimerHandler$TimerType;->clone()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, [Lcom/sonyericsson/fmradio/service/TimerHandler$TimerType;

    return-object v0
.end method

# virtual methods
.method getTimeout()I
    .locals 1

    .prologue
    .line 41
    iget v0, p0, Lcom/sonyericsson/fmradio/service/TimerHandler$TimerType;->mTimeout:I

    return v0
.end method


text:
<?php namespace Pact;

class Pact {

  public static function mockService($args) {
    return new MockService($args);
  }
}


text:
require_relative '../../test_helper'
require_relative 'flow_test_helper'

class TowingRulesTest < ActiveSupport::TestCase
  include FlowTestHelper

  setup do
    setup_for_testing_flow 'towing-rules'
  end
  ## Cars and light vehicles
  ##
  ## Q1
  should "ask which type of tow vehicle" do
    assert_current_node :towing_vehicle_type?
  end

  context "answer car or light vehicle" do
    setup do
      add_response "car-or-light-vehicle"
    end
    ## Q2
    should "ask if you have existing towing entitlements" do
      assert_current_node :existing_towing_entitlements?
    end
    context "answer yes" do
      setup do
        add_response :yes
      end
      ## Q2A
      should "ask when did you get this entitlement on your licence" do
        assert_current_node :how_long_entitlements?
      end
      context "answer before 19 jan 2013" do
        ## A3
        should "take you to car_light_vehicle_entitlement outcome" do
          add_response :"before-19-Jan-2013"
          assert_current_node :car_light_vehicle_entitlement
        end
      end
      context "answer after 19 jan 2013" do
        ## A4
        should "take you to full_entitlement outcome" do
          add_response :"after-19-Jan-2013"
          assert_current_node :full_entitlement
        end
      end
    end
    context "answer no" do
      setup do
        add_response :no
      end
      ## Q5
      should "ask when your licence was issued" do
        assert_current_node :date_licence_was_issued?
      end
      context "answer before 19 jan 2013" do
        ## A6
        should "take you to limited_trailer_entitlement outcome" do
          add_response "licence-issued-before-19-Jan-2013"
          assert_current_node :limited_trailer_entitlement
        end
      end
      context "answer after 19 jan 2013" do
        ## A7
        should "take you to limited_trailer_entitlement_2013 outcome" do
          add_response "licence-issued-after-19-Jan-2013"
          assert_current_node :limited_trailer_entitlement_2013
        end
      end
    end
  end ## Cars and light vehicles

  ## Medium sized vehicles
  context "answer medium sized vehicles" do
    setup do
      add_response "medium-sized-vehicle"
    end
    ## Q9
    should "ask if you have existing entitlement" do
      assert_current_node :medium_sized_vehicle_licenceholder?
    end
    context "answer yes" do
      setup do
        add_response :yes
      end
      ## Q9
      should "ask how old you are" do
        assert_current_node :how_old_are_you_msv?
      end
      context "answer under 21" do
        should "specify entitlement" do
          add_response "under-21"
          assert_current_node :limited_conditional_trailer_entitlement_msv
        end
      end
      context "answer 21 or over" do
        should "specify entitlement" do
          add_response "21-or-over"
          assert_current_node :limited_trailer_entitlement_msv
        end
      end
    end
    context "answer no" do
      setup do
        add_response :no
      end
      ## Q12
      should "ask if you have existing large vehicle towing entitlements" do
        assert_current_node :existing_large_vehicle_towing_entitlements?
      end
      context "answer yes" do
        should "" do
          add_response :yes
          assert_current_node :included_entitlement_msv
        end
      end
      context "answer no" do
        setup do
          add_response :no
        end
        ## Q14
        should "ask when your licence was issued" do
          assert_current_node :date_licence_was_issued_msv?
        end
        context "answer before january 1997" do
          ## A15
          should "specify entitlement" do
            add_response "before-jan-1997"
            assert_current_node :full_entitlement_msv
          end
        end
        context "answer after jan 1997" do
          setup do
            add_response "from-jan-1997"
          end
          ## Q16
          should "ask how old you are" do
            assert_current_node :how_old_are_you_msv_2?
          end
          context "answer under 18" do
            ## A17
            should "specify entitlement" do
              add_response "under-18"
              assert_current_node :too_young_msv
            end
          end
          context "answer under 21" do
            ## A18
            should "specify entitlement" do
              add_response "under-21"
              assert_current_node :apply_for_provisional_with_exceptions_msv
            end
          end
          context "answer 21 or over" do
            ## A19
            should "specify entitlement" do
              add_response "21-or-over"
              assert_current_node :apply_for_provisional_msv
            end
          end
        end
      end
    end
  end ## Medium sized vehicles

  ## Large vehicles
  context "answer large vehicle" do
    setup do
      add_response "large-vehicle"
    end
    ## Q20
    should "ask if you have a large vehicle licence" do
      assert_current_node :existing_large_vehicle_licence?
    end
    context "answer yes" do
      should "specify entitlement" do
        add_response :yes
        assert_current_node :full_cat_c_entitlement
      end
    end
    context "answer no" do
      setup do
        add_response :no
      end
      ## Q22
      should "ask how old you are" do
        assert_current_node :how_old_are_you_lv?
      end
      context "answer under 21" do
        ## A23
        should "specify entitlement" do
          add_response "under-21"
          assert_current_node :not_old_enough_lv
        end
      end
      context "answer 21 or over" do
        ## A24
        should "specify entitlement" do
          add_response "21-or-over"
          assert_current_node :apply_for_provisional_lv
        end
      end
    end
  end ## Large vehicles

  ## Minibuses
  context "answer minibus" do
    setup do
      add_response :minibus
    end
    ## Q25
    should "ask if you held a car licence before jan 1997" do
      assert_current_node :car_licence_before_jan_1997?
    end
    context "answer yes" do
      should "" do
        add_response :yes
        assert_current_node :full_entitlement_minibus
      end
    end
    context "answer no" do
      setup do
        add_response :no
      end
      ## Q27
      should "ask if you have bus or large vehicle towing entitlement" do
        assert_current_node :do_you_have_lv_or_bus_towing_entitlement?
      end
      context "answer yes" do
        ## A28
        should "specify entitlement" do
          add_response :yes
          assert_current_node :included_entitlement_minibus
        end
      end
      context "answer no" do
        setup do
          add_response :no
        end
        ## Q29
        should "ask if you have a full minibus licence" do
          assert_current_node :full_minibus_licence?
        end
        context "answer yes" do
          ## A30
          should "specify entitlement" do
            add_response :yes
            assert_current_node :limited_towing_entitlement_minibus
          end
        end
        context "answer no" do
          setup do
            add_response :no
          end
          ##  Q31
          should "ask how old you are" do
            assert_current_node :how_old_are_you_minibus?
          end
          context "answer under 21" do
            ## A32
            should "specify entitlement" do
              add_response "under-21"
              assert_current_node :not_old_enough_minibus
            end
          end
          context "answer 21 or above" do
            setup do
              add_response "21-or-over"
            end
            ## A34
            should "specify entitlement" do
              assert_current_node :limited_overall_entitlement_minibus
            end
          end
        end
      end
    end
  end ## Minibuses

  ## Buses
  context "answer bus" do
    setup do
      add_response :bus
    end
    ## Q36
    should "ask if you already have a licence to drive a bus" do
      assert_current_node :bus_licenceholder?
    end
    context "answer yes" do
      ## A37
      should "specify entitlement" do
        add_response :yes
        assert_current_node :full_entitlement_bus
      end
    end
    context "answer no" do
      setup do
        add_response :no
      end
      ## Q38
      should "ask how old you are" do
        assert_current_node :how_old_are_you_bus?
      end
      context "answer under 21" do
        ## A39
        should "specify entitlement" do
          add_response "under-21"
          assert_current_node :not_old_enough_bus
        end
      end
      context "amswer 21 or over" do
        ## A40
        should "specify entitlement" do
          add_response "21-or-over"
          assert_current_node :apply_for_provisional_bus
        end
      end
    end
  end ## Buses
end


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('test_app', '0005_foreignmodel'),
        ('test_second_app', '0002_mymodel_number'),
    ]

    operations = [
        migrations.AddField(
            model_name='mymodel',
            name='my_model',
            field=models.ForeignKey(blank=True, to='test_app.MyModel', null=True, on_delete=models.CASCADE),
        ),
    ]


text:
import $ from "jquery"
import domHelper from "../dom-helper"

/**
 * Check if this extractor should be used based on the page URL and selection.
 * @param  {string} url.
 * @param  {DomSelectionRange} domSelectionRange - selection range.
 * @return {boolean}
 */
function canHandleUrl(url, domSelectionRange) {
  try {
    let firstRowColCount = domHelper.getColumnCount(domSelectionRange.start)
    let lastRowColCount = domHelper.getColumnCount(domSelectionRange.end)
    return url.includes('itaubankline.itau.com.br') &&
      (firstRowColCount === 3 || lastRowColCount === 3)
  } catch (any) {
    return false
  }
}

/**
 * Extract tabular (rows and columns) from the selection.
 * @param  {DomSelectionRange} domSelectionRange - selection range.
 * @return {TabularData} Tabular data.
 * @throws {Error} If no tabular data was found in the selection.
 */
function getTabularDataFromSelection(domSelectionRange) {
  try {
    let firstRow = domHelper.getContainerElement(domSelectionRange.start, 'tr')
    let lastRow = domHelper.getContainerElement(domSelectionRange.end, 'tr')
    let rowRange = domHelper.getSiblingsRange(firstRow, lastRow)
    let tabularData = rowRange.map(getTabularDataFromRow)
    return {
      header: ['date', 'payee', 'value'],
      data: tabularData
    }
  } catch (any) {
    throw Error('Could not find tabular data.')
  }
}

/**
 * Extract tabular from a table row.
 * @param {jQuery} row - Table row.
 * @return {string[]} Tabular data.
 */
function getTabularDataFromRow(row) {
  let date = row.find('td:first-child').text().trim()
  let payee = row.find('td:nth-child(2)').text().trim()
  let value = row.find('td:nth-child(3)').text().trim()
  return [date, payee, value]
}

module.exports = {
  canHandleUrl: canHandleUrl,
  getTabularDataFromSelection: getTabularDataFromSelection
}


text:
@implementation AOPLibTest

- (void) addInterceptor:(NSInvocation *) i {
    NSLog(@"ADD intercepted.");
}

- (void) removeInterceptor:(NSInvocation *) i {
    NSLog(@"REMOVE END intercepted !");
}

- (void) testAOP {

    NSMutableArray* testArray = [[AOPProxy alloc] initWithNewInstanceOfClass:[NSMutableArray class]];

    [(AOPProxy*)testArray interceptMethodStartForSelector:@selector(addObject:)
                                    withInterceptorTarget:self
                                      interceptorSelector:@selector( addInterceptor: )];

    [(AOPProxy*)testArray interceptMethodEndForSelector:@selector(removeObjectAtIndex:)
                                  withInterceptorTarget:self
                                    interceptorSelector:@selector( removeInterceptor: )];

    [testArray addObject:[NSNumber numberWithInt:1]];

    [testArray removeObjectAtIndex:0];

    [testArray release];

}

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<snippet filetemplate="false" extension="cfm">
<name>new MXUnit TestCase</name>
<help></help>
<starttext><![CDATA[<cfcomponent extends="mxunit.framework.TestCase">

	<cffunction name="setUp" returntype="void" access="public" hint="put things here that you want to run before each test">
		]]></starttext>
<endtext><![CDATA[
	</cffunction>

	<cffunction name="tearDown" returntype="void" access="public" hint="put things here that you want to run after each test">

	</cffunction>

	<cffunction name="xxx_should_xxxx_When_xxx" returntype="void" access="public">
		<cfset fail("this test not yet implemented")>

	</cffunction>

	<cffunction name="xxx_shouldThrowErrorBecause_xxx" returntype="void" hint="tests error path" mxunit:expectedException="">
		<!--- do something here to cause an error --->

	</cffunction>

</cfcomponent>]]></endtext>
</snippet>


text:
<?php
/**
 * Jibirish.php.
 */
namespace Jsc;

/**
 * Jibirish.
 *
 * A library for creating jiberish, as in psuedo-random strings, salt, hashes
 * and noise.
 */
class Jibirish
{
    /**
     * Generates a random string of a specified length and character set.
     *
     * @param int         $length       The length of the string
     * @param bool        $upper        Add the A-Z character set
     * @param bool        $lower        Add the a-z character set
     * @param bool        $numeric      Add the numeric character set
     * @param bool        $special      Add the special character set
     * @param bool        $disambiguate Removes potentially ambiguous characters from the alphabets
     * @param bool|string $custom       allows the use of a custom character set
     *
     * @return string
     */
    private function __randomizer($length, $upper, $lower, $numeric, $special, $disambiguate, $custom = false)
    {
        $characters = '';
        $string = '';

        if ($numeric) {
            $characters .= ($disambiguate) ? '23456789' : '0123456789';
        }

        if ($lower) {
            $characters .= ($disambiguate) ? 'abcdefghijmnpqrstuvwxyz' : 'abcdefghijklmnopqrstuvwxyz';
        }

        if ($upper) {
            $characters .= ($disambiguate) ? 'ABCDEFGHLMNPQRSTUVWXYZ' : 'ABCDEFGHIKLMNOPQRSTUVWXYZ';
        }

        if ($special) {
            $characters .= ($disambiguate) ? '!@#$%^&*()-_=+;:\'"<>,./?\\`~' : '!@#$%^&*()-_=+;:\'"<>,./?\\`~';
        }

        if ($custom) {
            $characters .= $custom;
        }

        $size = strlen($characters);

    //try to increase entropy by shuffling the character set
    $characters .= str_shuffle($characters);

        for ($i = 0; $i < $length; ++$i) {
            $string .= $characters[mt_rand(0, $size - 1)];
        }

        return $string;
    }

    /**
     * Returns a random string matching the input requirements. These requirements may consist of custom or predefined
     * types.
     *
     * Predefined Random String Types
     *
     * - CAKECIPHER returns a CakePHP cipher string
     * - CAKESALT returns a CakePHP salt string
     *
     * Custom Random String Types
     * Passing a string consiting of any of the following characters. For example Utility::random('ul', 10); will
     * return a 10 character string containing upper and lower case letters.
     *
     * - u Calls the uppercase character set
     * - l Calls the lowercase character set
     * - n Calls the numeric character set
     * - s Calls the special character set
     * - d Disambiguate all character sets
     *
     * @param string $type
     * @param int    $length
     *
     * @return string
     */
    public function random($type = null, $length = null)
    {

        //If no string is passed, set the default string type
        if (is_null($type)) {
            $type = 'ulnsd';
        }

        //If the string is not all caps we will parse it for args, otherwise we assume it's a predefined type
        if (!ctype_upper($type)) {
            $chars = str_split($type);

            $upper = in_array('u', $chars) ? true : false;
            $lower = in_array('l', $chars) ? true : false;
            $numeric = in_array('n', $chars) ? true : false;
            $special = in_array('s', $chars) ? true : false;
            $disambiguate = in_array('d', $chars) ? true : false;

            return $this->__randomizer($length, $upper, $lower, $numeric, $special, $disambiguate);
        }

        //If we have made it this far, try and set a default type
        switch ($type) {
            //$this->__randomizer($length, $upper, $lower, $numeric, $special, $disambiguate);
            case 'CAKECIPHER':
                return $this->__randomizer(128, false, false, true, false, false);
            break;

            case 'CAKESALT':
                return $this->__randomizer(128, true, true, true, false, false, '!@#$%^&*()-_=+;:<>,./?`~');
            break;
        }
    }

    /**
     * Returns a large high entropy string.
     *
     * @return string
     */
    public function entropy()
    {
        //$seed will pad itself with more and more psuedo-random data
        //$salt is a hash of seed, it will use a 512-bit hash to digest the seed. it will then use multiple (and only)
        //512 bit algos. to redigest the salt value until a high number of passes have been made.

        //Generate some entropy
        $seed = openssl_random_pseudo_bytes(4096);

        //While it might seem silly, it is entropy.
        $seed .= (mt_getrandmax() / rand());

        //Use Tinker's random uuid generator to add more entropy
        for ($i = 0; $i < 10; ++$i) {
            $seed .= $this->uuid();
        }

        //Use mt_rand to pad the seed out with more entropy
        $seed .= mt_rand(1000000000, 2147483647);

        //Create a really large psuedo-random string for more entropy
        $seed .= $this->random(4096, 'ulns');

        //Hash php.ini to add more entropy
        $seed .= hash('sha512', php_ini_loaded_file());

        //read from dev rand to create more entropy
        //@link http://www.php.net/manual/en/function.uniqid.php#88023
        $fp = @fopen('/dev/urandom', 'rb');
        if ($fp !== false) {
            $seed .= @fread($fp, 16);
            @fclose($fp);
        }

        //Use mt_rand() to add more entropy to the seed
        //@link http://www.php.net/manual/en/function.uniqid.php#88023
        for ($i = 0; $i < 16; ++$i) {
            $seed .= chr(mt_rand(0, 255));
        }

        //More entropy
        //http://stackoverflow.com/questions/9883359/gathering-entropy-in-web-apps-to-create-more-secure-random-numbers
        $noise = microtime()
            .serialize($_SERVER)
            .serialize($_POST)
            .serialize($_GET)
            .serialize($_COOKIE);

        $seed .= hash('sha512', $noise);
        $seed .= hash('whirlpool', $noise);

        if (is_dir(DS.'var')) {
            $seed .= hash('sha512', implode(scandir(DS.'var')));
            $seed .= hash('whirlpool', implode(scandir(DS.'var')));
        }

        return $seed;
    }

    /**
     * Returns 512 bits of psuedo-random noise.
     *
     * @return string A 512 bit psuedo-random string
     */
    public function salt()
    {
        $seed = $this->entropy();

        $salt = $hash = hash('sha512', $seed);
        $salt = hash('whirlpool', $salt);

        for ($i = 0; $i < 10; ++$i) {
            $salt = hash('sha512', $salt);
            $salt = hash('whirlpool', $salt);
        }

        return $salt;
    }

    /**
     * Generates a  version 4 compliant psuedo-random UUID.
     *
     * @link http://www.php.net/manual/en/function.uniqid.php#88023
     * @see http://tools.ietf.org/html/rfc4122#section-4.4
     * @see http://en.wikipedia.org/wiki/UUID
     *
     * @return string A UUID, made up of 32 hex digits and 4 hyphens.
     */
    public function uuid()
    {
        $pr_bits = null;
        $fp = @fopen('/dev/urandom', 'rb');
        if ($fp !== false) {
            $pr_bits .= @fread($fp, 16);
            @fclose($fp);
        } else {
            // If /dev/urandom isn't available (eg: in non-unix systems), use mt_rand().
            $pr_bits = '';
            for ($cnt = 0; $cnt < 16; ++$cnt) {
                $pr_bits .= chr(mt_rand(0, 255));
            }
        }

        $time_low = bin2hex(substr($pr_bits, 0, 4));
        $time_mid = bin2hex(substr($pr_bits, 4, 2));
        $time_hi_and_version = bin2hex(substr($pr_bits, 6, 2));
        $clock_seq_hi_and_reserved = bin2hex(substr($pr_bits, 8, 2));
        $node = bin2hex(substr($pr_bits, 10, 6));

        /*
         * Set the four most significant bits (bits 12 through 15) of the
         * time_hi_and_version field to the 4-bit version number from
         * Section 4.1.3.
         * @see http://tools.ietf.org/html/rfc4122#section-4.1.3
         */
        $time_hi_and_version = hexdec($time_hi_and_version);
        $time_hi_and_version = $time_hi_and_version >> 4;
        $time_hi_and_version = $time_hi_and_version | 0x4000;

        /*
         * Set the two most significant bits (bits 6 and 7) of the
         * clock_seq_hi_and_reserved to zero and one, respectively.
         */
        $clock_seq_hi_and_reserved = hexdec($clock_seq_hi_and_reserved);
        $clock_seq_hi_and_reserved = $clock_seq_hi_and_reserved >> 2;
        $clock_seq_hi_and_reserved = $clock_seq_hi_and_reserved | 0x8000;

        return sprintf(
            '%08s-%04s-%04x-%04x-%012s',
            $time_low,
            $time_mid,
            $time_hi_and_version,
            $clock_seq_hi_and_reserved,
            $node
        );
    }
}


text:
<Alloy>
	<Window class="container">

    <View id="table">
        <View class="row">
            <View id="letter_container_0_0" class="letter_container">

            </View>
            <View id="letter_container_0_1" class="letter_container">

            </View>
            <View id="letter_container_0_2" class="letter_container">

            </View>
            <View id="letter_container_0_3" class="letter_container">

            </View>
        </View>
        <View class="row">
            <View id="letter_container_1_0" class="letter_container">

            </View>
            <View id="letter_container_1_1" class="letter_container">

            </View>
            <View id="letter_container_1_2" class="letter_container">

            </View>
            <View id="letter_container_1_3" class="letter_container">

            </View>
        </View>
        <View class="row">
            <View id="letter_container_2_0" class="letter_container">

            </View>
            <View id="letter_container_2_1" class="letter_container">

            </View>
            <View id="letter_container_2_2" class="letter_container">

            </View>
            <View id="letter_container_2_3" class="letter_container">

            </View>
        </View>
        <View class="row">
            <View id="letter_container_3_0" class="letter_container">

            </View>
            <View id="letter_container_3_1" class="letter_container">

            </View>
            <View id="letter_container_3_2" class="letter_container">

            </View>
            <View id="letter_container_3_3" class="letter_container">

            </View>
        </View>
    </View>
    <View id="touchTable"></View>

	</Window>
</Alloy>


text:
use read::WadRead;
use math::Vec2;
use sdl2::pixels::PixelFormatEnum;
use std::path::Path;
use std::vec::Vec;
use types::WadTextureHeader;
use std::borrow::Cow;
use std::fmt::{self, Debug, Display};

pub struct Image {
    width: usize,
    height: usize,
    x_offset: isize,
    y_offset: isize,
    pixels: Vec<u16>,
}

#[derive(Debug)]
pub struct ImageError(Cow<'static, str>);
impl Image {
    pub fn new(width: usize, height: usize) -> Result<Image, ImageError> {
        if width >= 4096 || height >= 4096 {
            return Err(format!("image too large {}x{}", width, height).into());
        }
        Ok(Image {
            width: width,
            height: height,
            x_offset: 0,
            y_offset: 0,
            pixels: vec![0xff00; width * height],
        })
    }

    pub fn new_from_header(header: &WadTextureHeader) -> Result<Image, ImageError> {
        Image::new(header.width as usize, header.height as usize)
    }

    pub fn from_buffer(buffer: &[u8]) -> Result<Image, ImageError> {
        let mut reader = buffer;
        let width = try!(reader.wad_read::<u16>().to_err("missing width")) as usize;
        let height = try!(reader.wad_read::<u16>().to_err("missing height")) as usize;
        if width >= 4096 || height >= 4096 {
            return Err(format!("image too large {}x{}", width, height).into());
        }

        let x_offset = try!(reader.wad_read::<i16>().to_err("missing x offset")) as isize;
        let y_offset = try!(reader.wad_read::<i16>().to_err("missing y offset")) as isize;

        let mut pixels = vec![!0; width * height];

        // Process each column of the image.
        for i_column in 0..width {
            // Each column is defined as a number of vertical `runs' which are
            // defined starting at `offset' in the buffer.
            let offset = try!(reader.wad_read::<u32>()
                                    .to_err_with(|| {
                                        format!("unfinished column {}, {}x{}",
                                                i_column,
                                                width,
                                                height)
                                    })) as isize;
            if offset >= buffer.len() as isize {
                return Err(format!("invalid column offset in {}, offset={}, size={}",
                                   i_column,
                                   offset,
                                   buffer.len())
                               .into());
            }
            let mut source = buffer[offset as usize..].iter();
            let mut i_run = 0;
            loop {
                // The first byte contains the vertical coordinate of the run's
                // start.
                let row_start = *try!(source.next()
                                            .to_err_with(|| {
                                                format!("unfinshed column {}, run {}",
                                                        i_column,
                                                        i_run)
                                            })) as usize;

                // The special value of 255 means this is the last run in the
                // column, so move on to the next one.
                if row_start == 255 {
                    break;
                }

                // The second byte is the length of this run. Skip an additional
                // byte which is ignored for some reason.
                let run_length = *try!(source.next()
                                             .to_err_with(|| {
                                                 format!("missing run length: column {}, run {}",
                                                         i_column,
                                                         i_run)
                                             })) as usize;

                // Check that the run fits in the image.
                if row_start + run_length > height {
                    return Err(format!("run too big: column {}, run {} ({} +{}), size {}x{}",
                                       i_column,
                                       i_run,
                                       row_start,
                                       run_length,
                                       width,
                                       height)
                                   .into());
                }

                // An ignored padding byte.
                try!(source.next()
                           .to_err_with(|| {
                               format!("missing padding byte 1: column {}, run {}", i_column, i_run)
                           }));

                // Iterator to the beginning of the run in `pixels`. Guaranteed to be in bounds
                // by the check above.
                let mut destination = pixels[row_start * width + i_column..]
                                          .chunks_mut(width)
                                          .map(|row| &mut row[0])
                                          .take(run_length);

                // Copy the bytes from source to destination, but first check there's enough of
                // those left.
                if source.size_hint().0 < run_length {
                    return Err(format!("source underrun: column {}, run {} ({}, +{}), bytes \
                                        left {}",
                                       i_column,
                                       i_run,
                                       row_start,
                                       run_length,
                                       source.size_hint().0)
                                   .into());
                }
                for dest_pixel in &mut destination {
                    *dest_pixel = *source.next().expect("missing pixel despite check") as u16;
                }

                // And another ignored byte after the run.
                try!(source.next()
                           .to_err_with(|| {
                               format!("missing padding byte 2: column {}, run {}", i_column, i_run)
                           }));
                i_run += 1;
            }
        }

        Ok(Image {
            width: width,
            height: height,
            x_offset: x_offset,
            y_offset: y_offset,
            pixels: pixels,
        })
    }

    pub fn blit(&mut self, source: &Image, offset: Vec2<isize>, ignore_transparency: bool) {
        // Figure out the region in source which is not out of bounds when
        // copied into self.
        let y_start = if offset[1] < 0 {
            (-offset[1]) as usize
        } else {
            0
        };
        let x_start = if offset[0] < 0 {
            (-offset[0]) as usize
        } else {
            0
        };
        let y_end = if self.height as isize > source.height as isize + offset[1] {
            source.height
        } else {
            (self.height as isize - offset[1]) as usize
        };
        let x_end = if self.width as isize > source.width as isize + offset[0] {
            source.width
        } else {
            (self.width as isize - offset[0]) as usize
        };

        let src_pitch = source.width as usize;
        let dest_pitch = self.width as usize;
        let copy_width = x_end - x_start;
        let copy_height = (y_end - y_start) as usize;
        let (x_start, y_start) = (x_start as usize, y_start as usize);

        let src_rows = &source.pixels[x_start + y_start * src_pitch..];
        let src_rows = src_rows.chunks(src_pitch)
                               .take(copy_height)
                               .map(|row| &row[..copy_width]);

        let dest_rows = &mut self.pixels[(x_start as isize + offset[0]) as usize +
                                         (y_start as isize + offset[1]) as usize * dest_pitch..];
        let dest_rows = dest_rows.chunks_mut(dest_pitch)
                                 .take(copy_height)
                                 .map(|row| &mut row[..copy_width]);

        if ignore_transparency {
            // If we don't care about transparency we can copy row by row.
            for (dest_row, source_row) in dest_rows.zip(src_rows) {
                for (dest_pixel, &source_pixel) in dest_row.iter_mut().zip(source_row.iter()) {
                    *dest_pixel = source_pixel;
                }
            }
        } else {
            // Only copy pixels whose high bits are not set.
            for (dest_row, source_row) in dest_rows.zip(src_rows) {
                for (dest_pixel, &source_pixel) in dest_row.iter_mut().zip(source_row.iter()) {
                    // `Blending' is a simple copy/no copy, but using bit ops we can avoid
                    // branching.
                    let blend = 0u16.wrapping_sub(source_pixel >> 15);
                    *dest_pixel = (source_pixel & !blend) | (*dest_pixel & blend);
                }
            }
        }
    }

    pub fn x_offset(&self) -> isize {
        self.x_offset
    }
    pub fn y_offset(&self) -> isize {
        self.y_offset
    }

    pub fn width(&self) -> usize {
        self.width
    }

    pub fn height(&self) -> usize {
        self.height
    }

    pub fn size(&self) -> Vec2<usize> {
        Vec2::new(self.width, self.height)
    }

    pub fn num_pixels(&self) -> usize {
        self.pixels.len()
    }

    pub fn pixels(&self) -> &[u16] {
        &self.pixels
    }

    pub fn into_pixels(self) -> Vec<u16> {
        self.pixels
    }

    pub fn save_bmp<P: AsRef<Path> + Debug>(&self,
                                            palette: &[[u8; 3]; 256],
                                            path: &P)
                                            -> Result<(), ImageError> {
        use sdl2::surface::Surface;
        let mut pixels = vec![0u8; 3 * self.width * self.height];
        for (index, pixel) in self.pixels.iter().enumerate() {
            let pixel = palette[(pixel & 0xff) as usize];
            pixels[index * 3] = pixel[2];
            pixels[index * 3 + 1] = pixel[1];
            pixels[index * 3 + 2] = pixel[0];
        }
        let surface = try!(Surface::from_data(&mut pixels[..],
                                              self.width as u32,
                                              self.height as u32,
                                              self.width as u32 * 3,
                                              PixelFormatEnum::BGR24)
                               .to_err("failed to create surface"));
        surface.save_bmp(path).to_err_with(|| format!("failed to save bmp {:?}", path))
    }
}

trait ToError {
    type Success;

    fn to_err(self, &'static str) -> Result<Self::Success, ImageError>;
    fn to_err_with<F: FnOnce() -> String>(self, with: F) -> Result<Self::Success, ImageError>;
}

impl<S, E> ToError for Result<S, E> {
    type Success = S;

    fn to_err(self, message: &'static str) -> Result<Self::Success, ImageError> {
        self.map_err(|_| ImageError(Cow::Borrowed(message)))
    }

    fn to_err_with<F: FnOnce() -> String>(self, with: F) -> Result<Self::Success, ImageError> {
        self.map_err(|_| ImageError(Cow::Owned(with())))
    }
}

impl<S> ToError for Option<S> {
    type Success = S;

    fn to_err(self, message: &'static str) -> Result<Self::Success, ImageError> {
        self.ok_or(ImageError(Cow::Borrowed(message)))
    }

    fn to_err_with<F: FnOnce() -> String>(self, with: F) -> Result<Self::Success, ImageError> {
        self.ok_or_else(|| ImageError(Cow::Owned(with())))
    }
}

impl From<String> for ImageError {
    fn from(value: String) -> ImageError {
        ImageError(Cow::Owned(value))
    }
}

impl From<&'static str> for ImageError {
    fn from(value: &'static str) -> ImageError {
        ImageError(Cow::Borrowed(value))
    }
}

impl Display for ImageError {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(formatter, "{}", self.0)
    }
}


text:
//
//  MQTTSubscribeAckMessage.m
//  MQTTLibrary
//
//  Created by Bryant Luk on 2/4/14.
//  Copyright (c) 2014 Bryant Luk. All rights reserved.
//

#import "MQTTSubscribeAckMessage.h"

@implementation MQTTSubscribeAckMessage

- (instancetype)initWithQOSForTopics:(NSArray *)qosForTopics
                           messageId:(uint16_t)messageId {
  self = [super initWithType:MQTT_MESSAGE_TYPE_SUBACK];

  if (self) {
    _qosForTopics = [qosForTopics copy];
    _messageId = messageId;
  }

  return self;
}

- (instancetype)initWithData:(NSData *)data {
  if ([data length] < 4) {
    // TODO throw an exception
  }

  if ([MQTTMessage messageTypeFromFixedHeader:data] ==
      MQTT_MESSAGE_TYPE_SUBACK) {
    /* Assume message is correct */
    NSUInteger remainingLength =
        [MQTTMessage decodeRemainingLengthFromFixedHeaderData:data];
    NSUInteger numberOfBytesInRemainingLength =
        [MQTTMessage numberOfBytesInRemainingLength:data];

    uint8_t *bytes = (uint8_t *)[data bytes];
    bytes += 1 + numberOfBytesInRemainingLength;

    uint16_t messageId = CFSwapInt16BigToHost((*((uint16_t *)bytes)));
    bytes += 2;

    NSMutableArray *qosForTopics = [[NSMutableArray alloc] init];
    while (((bytes - (uint8_t *)[data bytes]) - 1 -
            numberOfBytesInRemainingLength) < remainingLength) {

      /* read the topic QOS */
      uint8_t requestedQos = *bytes;
      ++bytes;

      [qosForTopics addObject:[NSNumber numberWithUnsignedInt:requestedQos]];
    }

    self = [self initWithQOSForTopics:qosForTopics messageId:messageId];

  } else {
    // TODO throw an exception
  }

  return self;
}

- (NSData *)variableHeader {
  NSMutableData *variableHeader = [[NSMutableData alloc] init];

  uint16_t messageIdBigEndian = CFSwapInt16HostToBig(self.messageId);
  [variableHeader appendBytes:&messageIdBigEndian length:2];

  return [variableHeader copy];
}

- (NSData *)payload {
  NSMutableData *payload = [[NSMutableData alloc] init];

  for (NSNumber *qos in self.qosForTopics) {
    uint8_t qosForTopic = [qos unsignedIntValue];
    [payload appendBytes:&qosForTopic length:1];
  }

  return [payload copy];
}

@end


text:
package org.magenta;

import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;

import org.magenta.core.FixtureContext;
import org.magenta.core.GenerationStrategyFactory;
import org.magenta.core.Injector;
import org.magenta.core.automagic.generation.CompositeGeneratorFactory;
import org.magenta.core.automagic.generation.DataKeyDeterminedFromFieldTypeMappingFunction;
import org.magenta.core.automagic.generation.DynamicGeneratorFactory;
import org.magenta.core.automagic.generation.provider.ConditionalGeneratorFactory;
import org.magenta.core.automagic.generation.provider.ObjectGeneratorFactory;
import org.magenta.core.automagic.generation.provider.PrimitiveDynamicGeneratorFactoryProvider;
import org.magenta.core.context.ThreadLocalFixtureContext;
import org.magenta.core.injector.FieldInjectionChainProcessor;
import org.magenta.core.injector.FieldInjectionHandler;
import org.magenta.core.injector.FieldsExtractor;
import org.magenta.core.injector.extractors.HiearchicalFieldsExtractor;
import org.magenta.core.injector.handlers.DataSetFieldHandler;
import org.magenta.core.injector.handlers.SequenceFieldHandler;
import org.magenta.random.FluentRandom;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Lists;

public class Dependencies {

  private static Logger log = LoggerFactory.getLogger(Dependencies.class);

  public FixtureFactory fixtureFactory() {

    FluentRandom.incrementSeed();

    FixtureContext fixtureContext = fixtureContext();
    DynamicGeneratorFactory generatorFactory = generatorFactory();
    return new FixtureFactory(null, generationStrategyFactory(fixtureContext), generatorFactory, fixtureContext);
  }

  public DynamicGeneratorFactory generatorFactory() {
    List<DynamicGeneratorFactory> factories = Lists.newArrayList();

    factories.addAll(PrimitiveDynamicGeneratorFactoryProvider.get());
    factories.add(new ConditionalGeneratorFactory(type -> type.isSubtypeOf(Date.class), () -> FluentRandom.dates().any()));
    factories.add(new ObjectGeneratorFactory( fieldExtractor(), new DataKeyDeterminedFromFieldTypeMappingFunction()));

    return new CompositeGeneratorFactory(factories);
  }

  public GenerationStrategyFactory generationStrategyFactory(FixtureContext fixtureContext) {
    return new GenerationStrategyFactory(fixtureContext, injector());
  }

  public Injector injector(){
    return new FieldInjectionChainProcessor(fieldInjectionHandlers());
  }

  public List<FieldInjectionHandler> fieldInjectionHandlers(){

    List<FieldInjectionHandler> handlers = Lists.newArrayList();

    handlers.add(new DataSetFieldHandler(fieldExtractor()));
    handlers.add(new SequenceFieldHandler(fieldExtractor()));

    return handlers;

  }

  public FieldsExtractor fieldExtractor() {
    return HiearchicalFieldsExtractor.SINGLETON;
  }

  public FixtureContext fixtureContext() {
    return new ThreadLocalFixtureContext();
  }

}


text:
"use strict";
var _1 = require("../../../../../");
describe("QueryString", function () {
    it("empty string", function () {
        expect(_1.QueryString("")).toBe(undefined);
    });
    it("with string + options", function () {
        var qs = _1.QueryString("foo", {
            analyzer: "english",
            fields: ["title"],
            use_dis_max: true
        });
        expect(qs).toEqual({
            query_string: {
                query: "foo",
                analyzer: "english",
                fields: ["title"],
                use_dis_max: true
            }
        });
    });
});
//# sourceMappingURL=QueryStringSpec.js.map


text:
package org.bitbucket.kilda.storm.topology.kafka.bolt.selector;

import org.apache.storm.tuple.Tuple;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Uses field name to select topic name from tuple .
 */
public class FieldNameTopicSelector implements KafkaTopicSelector {
    private static final long serialVersionUID = -3903708904533396833L;
    private static final Logger LOG = LoggerFactory.getLogger(FieldNameTopicSelector.class);

    private final String fieldName;
    private final String defaultTopicName;

    public FieldNameTopicSelector(String fieldName, String defaultTopicName) {
        this.fieldName = fieldName;
        this.defaultTopicName = defaultTopicName;
    }

    @Override
    public String getTopic(Tuple tuple) {
        if (tuple.contains(fieldName)) {
            return tuple.getStringByField(fieldName);
        } else {
            LOG.warn("Field {} Not Found. Returning default topic {}", fieldName, defaultTopicName);
            return defaultTopicName;
        }
    }
}


text:
package org.pitest.mutationtest.execute;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import org.pitest.extension.common.TestUnitDecorator;
import org.pitest.functional.SideEffect;
import org.pitest.mutationtest.TimeoutLengthStrategy;
import org.pitest.testapi.ResultCollector;
import org.pitest.testapi.TestUnit;
import org.pitest.util.Unchecked;

public final class MutationTimeoutDecorator extends TestUnitDecorator {

  private final TimeoutLengthStrategy timeOutStrategy;
  private final SideEffect            timeOutSideEffect;
  private final long                  executionTime;

  public MutationTimeoutDecorator(final TestUnit child,
      final SideEffect timeOutSideEffect,
      final TimeoutLengthStrategy timeStrategy, final long executionTime) {
    super(child);
    this.timeOutSideEffect = timeOutSideEffect;
    this.executionTime = executionTime;
    this.timeOutStrategy = timeStrategy;
  }

  @Override
  public void execute(final ClassLoader loader, final ResultCollector rc) {

    final long maxTime = this.timeOutStrategy
        .getAllowedTime(this.executionTime);

    final FutureTask<?> future = createFutureForChildTestUnit(loader, rc);
    executeFutureWithTimeOut(maxTime, future);
    if (!future.isDone()) {
      this.timeOutSideEffect.apply();
    }

  }

  private void executeFutureWithTimeOut(final long maxTime,
      final FutureTask<?> future) {
    try {
      future.get(maxTime, TimeUnit.MILLISECONDS);
    } catch (final TimeoutException ex) {
      // swallow
    } catch (final InterruptedException e) {
      // swallow
    } catch (final ExecutionException e) {
      throw Unchecked.translateCheckedException(e);
    }
  }

  private FutureTask<?> createFutureForChildTestUnit(final ClassLoader loader,
      final ResultCollector rc) {
    final FutureTask<?> future = new FutureTask<Object>(createCallableForChild(
        loader, rc));
    final Thread thread = new Thread(future);
    thread.setDaemon(true);
    thread.setName("mutationTestThread");
    thread.start();
    return future;
  }

  private Callable<Object> createCallableForChild(final ClassLoader loader,
      final ResultCollector rc) {
    return new Callable<Object>() {

      public Object call() throws Exception {
        child().execute(
            loader,
            new TimingMetaDataResultCollector(rc,
                MutationTimeoutDecorator.this.executionTime));
        return null;
      }

    };
  }

}


text:
#ifndef IP_UPDATES_HISTORY_DLG_H__
#define IP_UPDATES_HISTORY_DLG_H__

#include "resource.h"

// TODO: sorting by the columns

class CIpUpdatesHistoryDlg : public CDialogImpl<CIpUpdatesHistoryDlg>
{
	IpUpdate *m_ipUpdates; // a reference, doesn't own this

public:
	enum { IDD = IDD_DIALOG_IP_UPDATES_HISTORY};

	BEGIN_MSG_MAP(CSelectNetworkDlg)
		MSG_WM_INITDIALOG(OnInitDialog)
		COMMAND_ID_HANDLER(IDOK, OnButtonOk)
		COMMAND_ID_HANDLER(IDCANCEL, OnButtonOk) // to make 'close window' button work
		COMMAND_ID_HANDLER(IDC_BUTTON_COPY_TO_CLIPBOARD, OnButtonCopyToClipboard)
	END_MSG_MAP()

	CIpUpdatesHistoryDlg(IpUpdate *ipUpdates)
	{
		m_ipUpdates = ipUpdates;
	}

	BOOL OnInitDialog(CWindow /* wndFocus */, LPARAM /* lInitParam */)
	{
		CListViewCtrl m_ipUpdatesList;
		m_ipUpdatesList = GetDlgItem(IDC_LIST_IP_UPDATES_HISTORY);
		// unfortunately LVS_EX_AUTOSIZECOLUMNS is Vista+ only
		//m_ipUpdatesList.SetExtendedListViewStyle(LVS_EX_AUTOSIZECOLUMNS);
		m_ipUpdatesList.AddColumn(_T("Date"), 0);
		m_ipUpdatesList.AddColumn(_T("IP Address"), 1);
		// TOTAL_WIDTH was determined empirically on XP. Not sure if it will be
		// the same on Vista/7 or on systems with a different fonts/dpis
		static const int TOTAL_WIDTH = 246;
		static const int DATE_COLUMN_WIDTH = 150;
		m_ipUpdatesList.SetColumnWidth(0, DATE_COLUMN_WIDTH);
		m_ipUpdatesList.SetColumnWidth(1, TOTAL_WIDTH - DATE_COLUMN_WIDTH);
		IpUpdate *curr = m_ipUpdates;
		int i = 0;
		while (curr && (i < IP_UPDATES_HISTORY_MAX)) {
			TCHAR *ipAddr = StrToTStr(curr->ipAddress);
			TCHAR *time = StrToTStr(curr->time);
			if (time && ipAddr) {
				m_ipUpdatesList.AddItem(i, 0, time);
				if (curr->ok) {
					m_ipUpdatesList.AddItem(i, 1, ipAddr);
				} else {
					TCHAR *s = TStrCat(_T("!"), ipAddr);
					if (s) {
						m_ipUpdatesList.AddItem(i, 1, s);
						free(s);
					}
				}
			}
			free(ipAddr);
			free(time);
			curr = curr->next;
			i++;
		}
		return FALSE;
	}

	LRESULT OnButtonOk(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
	{
		EndDialog(wID);
		return 0;
	};

	LRESULT OnButtonCopyToClipboard(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
	{
		size_t		sLen;
		char *		s = NULL;
		WCHAR *		unicode = NULL;
		void *		tmp;
		HGLOBAL		handle = NULL;

		if (!OpenClipboard())
			return 0;

		s = IpUpdatesAsText(m_ipUpdates, &sLen);
		if (!s)
			goto Exit;

		::EmptyClipboard();
		handle = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, sLen);
		if (!handle)
			goto Exit;
		tmp = GlobalLock(handle);
		memcpy(tmp, s, sLen);
		GlobalUnlock(handle);
		::SetClipboardData(CF_TEXT, handle);
		// clipboard takes ownership of the handle => no need to GlobalFree() it

#if 0
		unicode = StrToWstrSimple(s);
		if (!unicode)
			goto Exit;
		size_t cbUnicodeSize = (wcslen(unicode)) * sizeof(WCHAR);
		handle = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, cbUnicodeSize);
		if (!handle)
			goto Exit;
		tmp = GlobalLock(handle);
		memcpy(tmp, unicode, cbUnicodeSize);
		GlobalUnlock(handle);
		::SetClipboardData(CF_UNICODETEXT, handle);
		// clipboard takes ownership of the handle => no need to GlobalFree() it
#endif

Exit:
		::CloseClipboard();
		free(s);
		free(unicode);
		return 0;
	};

};

#endif


text:
package com.github.nmorel.gwtjackson.client.deser;

import java.sql.Time;
import java.sql.Timestamp;
import java.util.Date;

import com.github.nmorel.gwtjackson.client.JsonDeserializationContext;
import com.github.nmorel.gwtjackson.client.JsonDeserializer;
import com.github.nmorel.gwtjackson.client.JsonDeserializerParameters;
import com.github.nmorel.gwtjackson.client.stream.JsonReader;
import com.github.nmorel.gwtjackson.client.stream.JsonToken;
import com.github.nmorel.gwtjackson.client.utils.DateFormat;

/**
 * Base implementation of {@link JsonDeserializer} for dates.
 *
 * @author Nicolas Morel
 */
public abstract class BaseDateJsonDeserializer<D extends Date> extends JsonDeserializer<D> {

    /**
     * Default implementation of {@link BaseDateJsonDeserializer} for {@link Date}
     */
    public static final class DateJsonDeserializer extends BaseDateJsonDeserializer<Date> {

        private static final DateJsonDeserializer INSTANCE = new DateJsonDeserializer();

        /**
         * @return an instance of {@link DateJsonDeserializer}
         */
        public static DateJsonDeserializer getInstance() {
            return INSTANCE;
        }

        private DateJsonDeserializer() { }

        @Override
        protected Date deserializeNumber( long millis, JsonDeserializerParameters params ) {
            return new Date( millis );
        }

        @Override
        protected Date deserializeString( String date, JsonDeserializationContext ctx, JsonDeserializerParameters params ) {
            return DateFormat.parse(ctx.isUseBrowserTimezone(), params.getPattern(), null, date );
        }
    }

    /**
     * Default implementation of {@link BaseDateJsonDeserializer} for {@link java.sql.Date}
     */
    public static final class SqlDateJsonDeserializer extends BaseDateJsonDeserializer<java.sql.Date> {

        private static final SqlDateJsonDeserializer INSTANCE = new SqlDateJsonDeserializer();

        private static final String SQL_DATE_FORMAT = "yyyy-MM-dd";

        /**
         * @return an instance of {@link SqlDateJsonDeserializer}
         */
        public static SqlDateJsonDeserializer getInstance() {
            return INSTANCE;
        }

        private SqlDateJsonDeserializer() { }

        @Override
        protected java.sql.Date deserializeNumber( long millis, JsonDeserializerParameters params ) {
            return new java.sql.Date( millis );
        }

        @Override
        protected java.sql.Date deserializeString( String date, JsonDeserializationContext ctx, JsonDeserializerParameters params ) {
            return new java.sql.Date( DateFormat.parse(ctx.isUseBrowserTimezone(), SQL_DATE_FORMAT, false, date).getTime() );
        }
    }

    /**
     * Default implementation of {@link BaseDateJsonDeserializer} for {@link Time}
     */
    public static final class SqlTimeJsonDeserializer extends BaseDateJsonDeserializer<Time> {

        private static final SqlTimeJsonDeserializer INSTANCE = new SqlTimeJsonDeserializer();

        /**
         * @return an instance of {@link SqlTimeJsonDeserializer}
         */
        public static SqlTimeJsonDeserializer getInstance() {
            return INSTANCE;
        }

        private SqlTimeJsonDeserializer() { }

        @Override
        protected Time deserializeNumber( long millis, JsonDeserializerParameters params ) {
            return new Time( millis );
        }

        @Override
        protected Time deserializeString( String date, JsonDeserializationContext ctx, JsonDeserializerParameters params ) {
            return Time.valueOf( date );
        }
    }

    /**
     * Default implementation of {@link BaseDateJsonDeserializer} for {@link Timestamp}
     */
    public static final class SqlTimestampJsonDeserializer extends BaseDateJsonDeserializer<Timestamp> {

        private static final SqlTimestampJsonDeserializer INSTANCE = new SqlTimestampJsonDeserializer();

        /**
         * @return an instance of {@link SqlTimestampJsonDeserializer}
         */
        public static SqlTimestampJsonDeserializer getInstance() {
            return INSTANCE;
        }

        private SqlTimestampJsonDeserializer() { }

        @Override
        protected Timestamp deserializeNumber( long millis, JsonDeserializerParameters params ) {
            return new Timestamp( millis );
        }

        @Override
        protected Timestamp deserializeString( String date, JsonDeserializationContext ctx, JsonDeserializerParameters params ) {
            return new Timestamp( DateFormat.parse(ctx.isUseBrowserTimezone(), params.getPattern(), null, date ).getTime() );
        }
    }

    @Override
    public D doDeserialize( JsonReader reader, JsonDeserializationContext ctx, JsonDeserializerParameters params ) {
        if ( params.getShape().isNumeric() || JsonToken.NUMBER.equals( reader.peek() ) ) {
            return deserializeNumber( reader.nextLong(), params );
        } else {
            return deserializeString( reader.nextString(), ctx, params );
        }
    }

    protected abstract D deserializeNumber( long millis, JsonDeserializerParameters params );

    protected abstract D deserializeString( String date, JsonDeserializationContext ctx, JsonDeserializerParameters params );
}