text:
% TestTag provides tests for all supported nix.Tag methods.
%
% Copyright (c) 2016, German Neuroinformatics Node (G-Node)
%
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted under the terms of the BSD License. See
% LICENSE file in the root of the Project.

function funcs = TestTag
    funcs = {};
    funcs{end+1} = @testAddSource;
    funcs{end+1} = @testAddSources;
    funcs{end+1} = @testRemoveSource;
    funcs{end+1} = @testAddReference;
    funcs{end+1} = @testAddReferences;
    funcs{end+1} = @testRemoveReference;
    funcs{end+1} = @testCreateFeature;
    funcs{end+1} = @testDeleteFeature;
    funcs{end+1} = @testFetchReferences;
    funcs{end+1} = @testReferenceCount;
    funcs{end+1} = @testFetchSources;
    funcs{end+1} = @testFetchFeatures;
    funcs{end+1} = @testFeatureCount;
    funcs{end+1} = @testOpenSource;
    funcs{end+1} = @testOpenSourceIdx;
    funcs{end+1} = @testHasSource;
    funcs{end+1} = @testSourceCount;
    funcs{end+1} = @testOpenFeature;
    funcs{end+1} = @testOpenFeatureIdx;
    funcs{end+1} = @testOpenReference;
    funcs{end+1} = @testOpenReference_idx;
    funcs{end+1} = @testSetMetadata;
    funcs{end+1} = @testOpenMetadata;
    funcs{end+1} = @testRetrieveData;
    funcs{end+1} = @testRetrieveDataIdx;
    funcs{end+1} = @testRetrieveFeatureData;
    funcs{end+1} = @testRetrieveFeatureDataIdx;
    funcs{end+1} = @testAttributes;
    funcs{end+1} = @testHasFeature;
    funcs{end+1} = @testHasReference;
    funcs{end+1} = @testCompare;
    funcs{end+1} = @testFilterSource;
    funcs{end+1} = @testFilterReference;
    funcs{end+1} = @testFilterFeature;
end

%% Test: Add Sources by entity and id
function [] = testAddSource ( varargin )
    fileName = fullfile(pwd, 'tests', 'testRW.h5');
    f = nix.File(fileName, nix.FileMode.Overwrite);
    b = f.createBlock('sourceTest', 'nixBlock');
    s = b.createSource('sourceTest', 'nixSource');
    tmp = s.createSource('nestedSource1', 'nixSource');
    tmp = s.createSource('nestedSource2', 'nixSource');
    position = [1.0 1.2 1.3 15.9];
    t = b.createTag('sourcetest', 'nixTag', position);

    assert(isempty(t.sources));
    assert(isempty(f.blocks{1}.tags{1}.sources));
    t.addSource(s.sources{1}.id);
    t.addSource(s.sources{2});
    assert(size(t.sources, 1) == 2);
    assert(size(f.blocks{1}.tags{1}.sources, 1) == 2);

    clear tmp t s b f;
    f = nix.File(fileName, nix.FileMode.ReadOnly);
    assert(size(f.blocks{1}.tags{1}.sources, 1) == 2);
end

%% Test: Add Sources by entity cell array
function [] = testAddSources ( varargin )
    testFile = fullfile(pwd, 'tests', 'testRW.h5');
    f = nix.File(testFile, nix.FileMode.Overwrite);
    b = f.createBlock('testBlock', 'nixBlock');
    t = b.createTag('testTag', 'nixTag', [1 2]);
    tmp = b.createSource('testSource1', 'nixSource');
    tmp = b.createSource('testSource2', 'nixSource');
    tmp = b.createSource('testSource3', 'nixSource');

    assert(isempty(t.sources));

    try
        t.addSources('hurra');
    catch ME
        assert(strcmp(ME.message, 'Expected cell array'));
    end;
    assert(isempty(t.sources));

    try
        t.addSources({12, 13});
    catch ME
        assert(~isempty(strfind(ME.message, 'not a nix.Source')));
    end;
    assert(isempty(t.sources));

    t.addSources(b.sources());
    assert(size(t.sources, 1) == 3);

    clear t tmp b f;
    f = nix.File(testFile, nix.FileMode.ReadOnly);
    assert(size(f.blocks{1}.tags{1}.sources, 1) == 3);
end

%% Test: Remove Sources by entity and id
function [] = testRemoveSource ( varargin )
    f = nix.File(fullfile(pwd, 'tests', 'testRW.h5'), nix.FileMode.Overwrite);
    b = f.createBlock('test', 'nixBlock');
    s = b.createSource('test', 'nixSource');
    tmp = s.createSource('nestedSource1', 'nixSource');
    tmp = s.createSource('nestedSource2', 'nixSource');
    position = [1.0 1.2 1.3 15.9];
    t = b.createTag('sourcetest', 'nixTag', position);
    t.addSource(s.sources{1}.id);
    t.addSource(s.sources{2});

    assert(size(t.sources,1) == 2);
    t.removeSource(s.sources{2});
    assert(size(t.sources,1) == 1);
    t.removeSource(s.sources{1}.id);
    assert(isempty(t.sources));
    assert(t.removeSource('I do not exist'));
    assert(size(s.sources,1) == 2);
end

%% Test: Add references by entity and id
function [] = testAddReference ( varargin )
    fileName = fullfile(pwd, 'tests', 'testRW.h5');
    f = nix.File(fileName, nix.FileMode.Overwrite);
    b = f.createBlock('referenceTest', 'nixBlock');
    tmp = b.createDataArray('referenceTest1', 'nixDataArray', nix.DataType.Double, [1 2]);
    tmp = b.createDataArray('referenceTest2', 'nixDataArray', nix.DataType.Double, [3 4]);

    position = [1.0 1.2 1.3 15.9];
    t = b.createTag('referenceTest', 'nixTag', position);

    assert(isempty(t.references));
    assert(isempty(f.blocks{1}.tags{1}.references));

    t.addReference(b.dataArrays{1}.id);
    t.addReference(b.dataArrays{2});
    assert(size(t.references, 1) == 2);
    assert(size(f.blocks{1}.tags{1}.references, 1) == 2);

    clear tmp t b f;
    f = nix.File(fileName, nix.FileMode.ReadOnly);
    assert(size(f.blocks{1}.tags{1}.references, 1) == 2);
end

%% Test: Add references by entity cell array
function [] = testAddReferences ( varargin )
    testFile = fullfile(pwd, 'tests', 'testRW.h5');
    f = nix.File(testFile, nix.FileMode.Overwrite);
    b = f.createBlock('testBlock', 'nixBlock');
    t = b.createTag('testTag', 'nixTag', [1 2]);
    tmp = b.createDataArray('referenceTest1', 'nixDataArray', nix.DataType.Double, [1 2]);
    tmp = b.createDataArray('referenceTest2', 'nixDataArray', nix.DataType.Double, [3 4]);
    tmp = b.createDataArray('referenceTest3', 'nixDataArray', nix.DataType.Double, [3 4]);

    assert(isempty(t.references));

    try
        t.addReferences('hurra');
    catch ME
        assert(strcmp(ME.message, 'Expected cell array'));
    end;
    assert(isempty(t.references));

    try
        t.addReferences({12, 13});
    catch ME
        assert(~isempty(strfind(ME.message, 'not a nix.DataArray')));
    end;
    assert(isempty(t.references));

    t.addReferences(b.dataArrays);
    assert(size(t.references, 1) == 3);

    clear t tmp b f;
    f = nix.File(testFile, nix.FileMode.ReadOnly);
    assert(size(f.blocks{1}.tags{1}.references, 1) == 3);
end

%% Test: Remove references by entity and id
function [] = testRemoveReference ( varargin )
    f = nix.File(fullfile(pwd, 'tests', 'testRW.h5'), nix.FileMode.Overwrite);
    b = f.createBlock('referenceTest', 'nixBlock');
    getRefDA1 = b.createDataArray('referenceTest1', 'nixDataArray', nix.DataType.Double, [1 2]);
    getRefDA2 = b.createDataArray('referenceTest2', 'nixDataArray', nix.DataType.Double, [3 4]);

    position = [1.0 1.2 1.3 15.9];
    t = b.createTag('referenceTest', 'nixTag', position);
    t.addReference(b.dataArrays{1}.id);
    t.addReference(b.dataArrays{2});
    assert(size(t.references, 1) == 2);

    t.removeReference(b.dataArrays{2});
    assert(size(t.references, 1) == 1);
    t.removeReference(b.dataArrays{1}.id);
    assert(isempty(t.references));
    assert(~t.removeReference('I do not exist'));
    assert(size(b.dataArrays, 1) == 2);
end

%% Test: Create Features by entity and id
function [] = testCreateFeature ( varargin )
    fileName = fullfile(pwd, 'tests', 'testRW.h5');
    f = nix.File(fileName, nix.FileMode.Overwrite);
    b = f.createBlock('featureTest', 'nixBlock');
    tmp = b.createDataArray('featureTestDataArray1', 'nixDataArray', nix.DataType.Double, [1 2]);
    tmp = b.createDataArray('featureTestDataArray2', 'nixDataArray', nix.DataType.Double, [3 4]);
    tmp = b.createDataArray('featureTestDataArray3', 'nixDataArray', nix.DataType.Double, [5 6]);
    tmp = b.createDataArray('featureTestDataArray4', 'nixDataArray', nix.DataType.Double, [7 8]);
    tmp = b.createDataArray('featureTestDataArray5', 'nixDataArray', nix.DataType.Double, [9 10]);
    tmp = b.createDataArray('featureTestDataArray6', 'nixDataArray', nix.DataType.Double, [11 12]);
    position = [1.0 1.2 1.3 15.9];
    t = b.createTag('featureTest', 'nixTag', position);

    assert(isempty(t.features));
    assert(isempty(f.blocks{1}.tags{1}.features));
    tmp = t.createFeature(b.dataArrays{1}.id, nix.LinkType.Tagged);
    tmp = t.createFeature(b.dataArrays{2}, nix.LinkType.Tagged);
    tmp = t.createFeature(b.dataArrays{3}.id, nix.LinkType.Untagged);
    tmp = t.createFeature(b.dataArrays{4}, nix.LinkType.Untagged);
    tmp = t.createFeature(b.dataArrays{5}.id, nix.LinkType.Indexed);
    tmp = t.createFeature(b.dataArrays{6}, nix.LinkType.Indexed);
    assert(size(t.features, 1) == 6);
    assert(size(f.blocks{1}.tags{1}.features, 1) == 6);

    clear tmp t b f;
    f = nix.File(fileName, nix.FileMode.ReadOnly);
    assert(size(f.blocks{1}.tags{1}.features, 1) == 6);
end

%% Test: Remove Features by entity and id
function [] = testDeleteFeature ( varargin )
    f = nix.File(fullfile(pwd, 'tests', 'testRW.h5'), nix.FileMode.Overwrite);
    b = f.createBlock('featureTest', 'nixBlock');
    tmp = b.createDataArray('featureTestDataArray1', 'nixDataArray', nix.DataType.Double, [1 2]);
    tmp = b.createDataArray('featureTestDataArray2', 'nixDataArray', nix.DataType.Double, [3 4]);
    position = [1.0 1.2 1.3 15.9];
    t = b.createTag('featureTest', 'nixTag', position);
    tmp = t.createFeature(b.dataArrays{1}.id, nix.LinkType.Tagged);
    tmp = t.createFeature(b.dataArrays{2}, nix.LinkType.Tagged);

    assert(t.deleteFeature(t.features{2}.id));
    assert(t.deleteFeature(t.features{1}));
    assert(isempty(t.features));

    assert(~t.deleteFeature('I do not exist'));
    assert(size(b.dataArrays, 1) == 2);
end

%% Test: Fetch references
function [] = testFetchReferences( varargin )
    f = nix.File(fullfile(pwd, 'tests', 'testRW.h5'), nix.FileMode.Overwrite);
    b = f.createBlock('referenceTest', 'nixBlock');
    tmp = b.createDataArray('referenceTest1', 'nixDataArray', nix.DataType.Double, [1 2]);
    tmp = b.createDataArray('referenceTest2', 'nixDataArray', nix.DataType.Double, [3 4]);
    tmp = b.createDataArray('referenceTest3', 'nixDataArray', nix.DataType.Double, [5 6]);
    position = [1.0 1.2 1.3 15.9];
    t = b.createTag('referenceTest', 'nixTag', position);

    t.addReference(b.dataArrays{1});
    t.addReference(b.dataArrays{2});
    t.addReference(b.dataArrays{3});
    assert(size(t.references, 1) == 3);
end

%% Test: Reference count
function [] = testReferenceCount( varargin )
    testFile = fullfile(pwd, 'tests', 'testRW.h5');
    f = nix.File(testFile, nix.FileMode.Overwrite);
    b = f.createBlock('testBlock', 'nixBlock');
    t = b.createTag('testTag', 'nixTag', [1 2]);

    assert(t.referenceCount() == 0);
    t.addReference(b.createDataArray('testDataArray1', 'nixDataArray', nix.DataType.Double, [1 2]));
    assert(t.referenceCount() == 1);
    t.addReference(b.createDataArray('testDataArray2', 'nixDataArray', nix.DataType.Double, [3 4]));

    clear t b f;
    f = nix.File(testFile, nix.FileMode.ReadOnly);
    assert(f.blocks{1}.tags{1}.referenceCount() == 2);
end

%% Test: Fetch Sources
function [] = testFetchSources( varargin )
    f = nix.File(fullfile(pwd, 'tests', 'testRW.h5'), nix.FileMode.Overwrite);
    b = f.createBlock('test', 'nixBlock');
    s = b.createSource('test','nixSource');
    tmp = s.createSource('nestedsource1', 'nixSource');
    tmp = s.createSource('nestedsource2', 'nixSource');
    tmp = s.createSource('nestedsource3', 'nixSource');
    position = [1.0 1.2 1.3 15.9];
    t = b.createTag('tagtest', 'nixTag', position);

    t.addSource(s.sources{1});
    t.addSource(s.sources{2});
    t.addSource(s.sources{3});
    assert(size(t.sources, 1) == 3);
end

%% Test: Fetch Features
function [] = testFetchFeatures( varargin )
    f = nix.File(fullfile(pwd, 'tests', 'testRW.h5'), nix.FileMode.Overwrite);
    b = f.createBlock('featureTest', 'nixBlock');
    tmp = b.createDataArray('featureTestDataArray1', 'nixDataArray', nix.DataType.Double, [1 2]);
    tmp = b.createDataArray('featureTestDataArray2', 'nixDataArray', nix.DataType.Double, [3 4]);
    position = [1.0 1.2 1.3 15.9];
    t = b.createTag('featureTest', 'nixTag', position);

    tmp = t.createFeature(b.dataArrays{1}, nix.LinkType.Tagged);
    tmp = t.createFeature(b.dataArrays{2}, nix.LinkType.Tagged);

    assert(size(t.features, 1) == 2);
end

%% Test: Feature count
function [] = testFeatureCount( varargin )
    testFile = fullfile(pwd, 'tests', 'testRW.h5');
    f = nix.File(testFile, nix.FileMode.Overwrite);
    b = f.createBlock('testBlock', 'nixBlock');
    t = b.createTag('testTag', 'nixTag', [1 2]);

    assert(t.featureCount() == 0);
    t.createFeature(b.createDataArray('testDataArray1', 'nixDataArray', ...
        nix.DataType.Double, [1 2]), nix.LinkType.Tagged);
    assert(t.featureCount() == 1);
    t.createFeature(b.createDataArray('testDataArray2', 'nixDataArray', ...
        nix.DataType.Double, [3 4]), nix.LinkType.Tagged);

    clear t b f;
    f = nix.File(testFile, nix.FileMode.ReadOnly);
    assert(f.blocks{1}.tags{1}.featureCount() == 2);
end

%% Test: Open Source by id or name
function [] = testOpenSource( varargin )
    f = nix.File(fullfile(pwd, 'tests', 'testRW.h5'), nix.FileMode.Overwrite);
    b = f.createBlock('test', 'nixBlock');
    s = b.createSource('test', 'nixSource');
    sourceName = 'nestedsource';
    createSource = s.createSource(sourceName, 'nixSource');
    position = [1.0 1.2 1.3 15.9];
    t = b.createTag('tagtest', 'nixTag', position);
    t.addSource(s.sources{1});

    getSourceByID = t.openSource(createSource.id);
    assert(~isempty(getSourceByID));

    getSourceByName = t.openSource(sourceName);
    assert(~isempty(getSourceByName));

    %-- test open non existing source
    getNonSource = t.openSource('I do not exist');
    assert(isempty(getNonSource));
end

function [] = testOpenSourceIdx( varargin )
%% Test Open Source by index
    f = nix.File(fullfile(pwd, 'tests', 'testRW.h5'), nix.FileMode.Overwrite);
    b = f.createBlock('testBlock', 'nixBlock');
    t = b.createTag('testTag', 'nixTag', [2 9]);
    s1 = b.createSource('testSource1', 'nixSource');
    s2 = b.createSource('testSource2', 'nixSource');
    s3 = b.createSource('testSource3', 'nixSource');
    t.addSource(s1);
    t.addSource(s2);
    t.addSource(s3);

    assert(strcmp(f.blocks{1}.tags{1}.openSourceIdx(1).name, s1.name));
    assert(strcmp(f.blocks{1}.tags{1}.openSourceIdx(2).name, s2.name));
    assert(strcmp(f.blocks{1}.tags{1}.openSourceIdx(3).name, s3.name));
end

%% Test: Has Source by id or entity
function [] = testHasSource( varargin )
    fileName = 'testRW.h5';
    sName = 'sourceTest1';
    f = nix.File(fullfile(pwd, 'tests', fileName), nix.FileMode.Overwrite);
    b = f.createBlock('testblock', 'nixBlock');
    s = b.createSource(sName, 'nixSource');
    sID = s.id;
    position = [1.0 1.2 1.3 15.9];
    t = b.createTag('tagTest', 'nixTag', position);
    t.addSource(b.sources{1});

    assert(~t.hasSource('I do not exist'));
    assert(t.hasSource(s));

    clear t s b f;
    f = nix.File(fullfile(pwd, 'tests', fileName), nix.FileMode.ReadOnly);
    assert(f.blocks{1}.tags{1}.hasSource(sID));
    assert(~f.blocks{1}.tags{1}.hasSource(sName));
end

%% Test: Source count
function [] = testSourceCount( varargin )
    testFile = fullfile(pwd, 'tests', 'testRW.h5');
    f = nix.File(testFile, nix.FileMode.Overwrite);
    b = f.createBlock('testBlock', 'nixBlock');
    t = b.createTag('testTag', 'nixTag', [1.0 1.2]);

    assert(t.sourceCount() == 0);
    t.addSource(b.createSource('testSource1', 'nixSource'));
    assert(t.sourceCount() == 1);
    t.addSource(b.createSource('testSource2', 'nixSource'));

    clear t b f;
    f = nix.File(testFile, nix.FileMode.ReadOnly);
    assert(f.blocks{1}.tags{1}.sourceCount() == 2);
end

%% Test: Open Feature by id
function [] = testOpenFeature( varargin )
    f = nix.File(fullfile(pwd, 'tests', 'testRW.h5'), nix.FileMode.Overwrite);
    b = f.createBlock('featureTest', 'nixBlock');
    tmp = b.createDataArray('featureTestDataArray', 'nixDataArray', nix.DataType.Double, [1 2]);
    position = [1.0 1.2 1.3 15.9];
    t = b.createTag('featureTest', 'nixTag', position);
    tmp = t.createFeature(b.dataArrays{1}, nix.LinkType.Tagged);

    assert(~isempty(t.openFeature(t.features{1}.id)));

    %-- test open non existing feature
    feat = t.openFeature('I do not exist');
    assert(isempty(feat));
end

%% Test Open Feature by index
function [] = testOpenFeatureIdx( varargin )
    f = nix.File(fullfile(pwd, 'tests', 'testRW.h5'), nix.FileMode.Overwrite);
    b = f.createBlock('testBlock', 'nixBlock');
    t = b.createTag('testTag', 'nixTag', [2 9]);
    d1 = b.createDataArray('testFeature1', 'nixDataArray', nix.DataType.Double, [1 2]);
    d2 = b.createDataArray('testFeature2', 'nixDataArray', nix.DataType.Double, [3 2]);
    d3 = b.createDataArray('testFeature3', 'nixDataArray', nix.DataType.Double, [7 2]);
    t.createFeature(d1, nix.LinkType.Tagged);
    t.createFeature(d2, nix.LinkType.Untagged);
    t.createFeature(d3, nix.LinkType.Indexed);

    assert(f.blocks{1}.tags{1}.openFeatureIdx(1).linkType == nix.LinkType.Tagged);
    assert(f.blocks{1}.tags{1}.openFeatureIdx(2).linkType == nix.LinkType.Untagged);
    assert(f.blocks{1}.tags{1}.openFeatureIdx(3).linkType == nix.LinkType.Indexed);
end

%% Test: Open reference by id or name
function [] = testOpenReference( varargin )
    f = nix.File(fullfile(pwd, 'tests', 'testRW.h5'), nix.FileMode.Overwrite);
    b = f.createBlock('referenceTest', 'nixBlock');
    tmp = b.createDataArray('referenceTest', 'nixDataArray', nix.DataType.Double, [1 2]);
    position = [1.0 1.2 1.3 15.9];
    t = b.createTag('referenceTest', 'nixTag', position);
    t.addReference(b.dataArrays{1});

    getRefByID = t.openReference(t.references{1,1}.id);
    assert(~isempty(getRefByID));

    getRefByName = t.openReference(t.references{1,1}.name);
    assert(~isempty(getRefByName));

    %-- test open non existing source
    getNonRef = t.openReference('I do not exist');
    assert(isempty(getNonRef));
end

%% Test Open reference by index
function [] = testOpenReference_idx( varargin )
    f = nix.File(fullfile(pwd, 'tests', 'testRW.h5'), nix.FileMode.Overwrite);
    b = f.createBlock('testBlock', 'nixBlock');
    t = b.createTag('testTag', 'nixTag', [2 9]);
    d1 = b.createDataArray('testReference1', 'nixDataArray', nix.DataType.Double, [1 2]);
    d2 = b.createDataArray('testReference2', 'nixDataArray', nix.DataType.Double, [3 2]);
    d3 = b.createDataArray('testReference3', 'nixDataArray', nix.DataType.Double, [7 2]);
    t.addReference(d1);
    t.addReference(d2);
    t.addReference(d3);

    assert(strcmp(f.blocks{1}.tags{1}.openReferenceIdx(1).name, d1.name));
    assert(strcmp(f.blocks{1}.tags{1}.openReferenceIdx(2).name, d2.name));
    assert(strcmp(f.blocks{1}.tags{1}.openReferenceIdx(3).name, d3.name));
end

%% Test: Set metadata
function [] = testSetMetadata ( varargin )
    fileName = fullfile(pwd, 'tests', 'testRW.h5');
    secName1 = 'testSection1';
    secName2 = 'testSection2';
    f = nix.File(fileName, nix.FileMode.Overwrite);
    tmp = f.createSection(secName1, 'nixSection');
    tmp = f.createSection(secName2, 'nixSection');

    b = f.createBlock('testBlock', 'nixBlock');
    t = b.createTag('testTag', 'nixTag', [1, 2, 3, 4]);

    assert(isempty(t.openMetadata));
    assert(isempty(f.blocks{1}.tags{1}.openMetadata));

    t.setMetadata(f.sections{1});
    assert(strcmp(t.openMetadata.name, secName1));
    assert(strcmp(f.blocks{1}.tags{1}.openMetadata.name, secName1));

    t.setMetadata(f.sections{2});
    assert(strcmp(t.openMetadata.name, secName2));
    assert(strcmp(f.blocks{1}.tags{1}.openMetadata.name, secName2));

    t.setMetadata('');
    assert(isempty(t.openMetadata));
    assert(isempty(f.blocks{1}.tags{1}.openMetadata));

    t.setMetadata(f.sections{2});
    clear tmp b f;
    f = nix.File(fileName, nix.FileMode.ReadOnly);
    assert(strcmp(f.blocks{1}.tags{1}.openMetadata.name, secName2));
end

%% Test: Open metadata
function [] = testOpenMetadata( varargin )
    f = nix.File(fullfile(pwd, 'tests', 'testRW.h5'), nix.FileMode.Overwrite);
    tmp = f.createSection('testSection', 'nixSection');
    b = f.createBlock('testBlock', 'nixBlock');
    t = b.createTag('testTag', 'nixTag', [1, 2, 3, 4]);

    t.setMetadata(f.sections{1});
    assert(strcmp(t.openMetadata.name, 'testSection'));
end

%% Test: Retrieve referenced data by name and id
function [] = testRetrieveData( varargin )
    f = nix.File(fullfile(pwd, 'tests', 'testRW.h5'), nix.FileMode.Overwrite);
    b = f.createBlock('testBlock', 'nixBlock');
    tagStartPos = [3];
    t = b.createTag('testTag', 'nixTag', tagStartPos);
    t.extent = [3];

    rawName = [1, 2, 3, 4, 5, 6, 7, 8, 9];
    rawID = [11, 12, 13, 14, 15, 16, 17];
    d = b.createDataArrayFromData('testDataArrayName', 'nixDataArray', rawName);
    d.appendSampledDimension(1);
    t.addReference(d);

    d = b.createDataArrayFromData('testDataArrayID', 'nixDataArray', rawID);
    d.appendSampledDimension(1);
    t.addReference(d);

    % test get non existent
    try
        retData = t.retrieveData('I do not exist, dont hate me!');
    catch ME
        assert(~isempty(strfind(ME.message, 'no DataArray with the specified name')), ...
            'Non existent check fail');
    end

    % test get referenced data by name
    retData = t.retrieveData('testDataArrayName');
    assert(size(retData, 2) == t.extent + 1, 'Get by name extent check fail');
    assert(retData(1) == rawName(t.position + 1), 'Get by name position check fail');

    % test get referenced data by id
    retData = t.retrieveData(d.id);
    assert(size(retData, 2) == t.extent + 1, 'Get by id extent check fail');
    assert(retData(1) == rawID(t.position + 1), 'Get by id position check fail');
end

%% Test: Retrieve referenced data by index
function [] = testRetrieveDataIdx( varargin )
    f = nix.File(fullfile(pwd, 'tests', 'testRW.h5'), nix.FileMode.Overwrite);
    b = f.createBlock('testBlock', 'nixBlock');
    raw = [1, 2, 3, 4, 5, 6, 7, 8, 9];
    d = b.createDataArrayFromData('testDataArray', 'nixDataArray', raw);
    d.appendSampledDimension(1);
    % tag positon is used like an index, therfore starts with 0!
    tagStartPos = [3];
    t = b.createTag('testTag', 'nixTag', tagStartPos);
    t.extent = [3];
    t.addReference(d);

    try
        t.retrieveDataIdx(12);
    catch ME
        assert(~isempty(strfind(ME.message, 'out of bounds')), 'Invalid index failed');
    end

    retData = t.retrieveDataIdx(1);
    assert(size(retData, 2) == t.extent + 1, 'Extent check failed');
    assert(retData(1) == raw(t.position + 1), 'Position check failed');
end

%% Test: Retrieve Feature data by name and id
function [] = testRetrieveFeatureData( varargin )
    f = nix.File(fullfile(pwd, 'tests', 'testRW.h5'), nix.FileMode.Overwrite);
    b = f.createBlock('testBlock', 'nixBlock');
    raw = [1, 2, 3, 4, 5, 6, 7, 8, 9];
    d = b.createDataArrayFromData('testDataArray', 'nixDataArray', raw);
    d.appendSampledDimension(1);
    tagStartPos = [3];
    t = b.createTag('testTag', 'nixTag', tagStartPos);
    t.extent = [3];
    t.addReference(d);

    rawFeature = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19];

    % test get non existent
    try
        t.retrieveData('I do not exist, dont hate me!');
    catch ME
        assert(~isempty(strfind(ME.message, 'no DataArray with the specified name')), ...
            'Non existent check fail');
    end

    % test retrieve untagged feature data by name
    df = b.createDataArrayFromData('testUntagged', 'nixDataArray', rawFeature);
    df.appendSampledDimension(1);
    t.createFeature(df, nix.LinkType.Untagged);
    retData = t.retrieveFeatureData('testUntagged');
    assert(size(retData, 2) == size(rawFeature, 2), 'Untagged size check fail');

    % test retrieve tagged feature data by id
    df = b.createDataArrayFromData('testTagged', 'nixDataArray', rawFeature);
    df.appendSampledDimension(1);
    t.createFeature(df, nix.LinkType.Tagged);
    retData = t.retrieveFeatureData(df.id);
    assert(size(retData, 2) == t.extent + 1, 'Tagged Extent check fail');
    assert(retData(1) == rawFeature(t.position + 1), 'Tagged Position check fail');

    % test retrieve indexed feature data by id
    df = b.createDataArrayFromData('testIndexed', 'nixDataArray', rawFeature);
    df.appendSampledDimension(1);
    t.createFeature(df, nix.LinkType.Indexed);
    retData = t.retrieveFeatureData(df.id);
    assert(size(retData, 2) == size(rawFeature, 2), 'Indexed size check fail');
end

%% Test: Retrieve Feature data by index
function [] = testRetrieveFeatureDataIdx( varargin )
    f = nix.File(fullfile(pwd, 'tests', 'testRW.h5'), nix.FileMode.Overwrite);
    b = f.createBlock('testBlock', 'nixBlock');
    raw = [1, 2, 3, 4, 5, 6, 7, 8, 9];
    d = b.createDataArrayFromData('testDataArray', 'nixDataArray', raw);
    d.appendSampledDimension(1);
    tagStartPos = [3];
    t = b.createTag('testTag', 'nixTag', tagStartPos);
    t.extent = [3];
    t.addReference(d);

    rawFeature = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19];

    % test retrieve untagged feature data
    df = b.createDataArrayFromData('testUntagged', 'nixDataArray', rawFeature);
    df.appendSampledDimension(1);
    t.createFeature(df, nix.LinkType.Untagged);
    retData = t.retrieveFeatureDataIdx(1);
    assert(size(retData, 2) == size(rawFeature, 2), 'Untagged size check fail');

    % test retrieve tagged feature data
    df = b.createDataArrayFromData('testTagged', 'nixDataArray', rawFeature);
    df.appendSampledDimension(1);
    t.createFeature(df, nix.LinkType.Tagged);
    retData = t.retrieveFeatureDataIdx(2);
    assert(size(retData, 2) == t.extent + 1, 'Tagged Extent check fail');
    assert(retData(1) == rawFeature(t.position + 1), 'Tagged Position check fail');

    % test retrieve indexed feature data
    df = b.createDataArrayFromData('testIndexed', 'nixDataArray', rawFeature);
    df.appendSampledDimension(1);
    t.createFeature(df, nix.LinkType.Indexed);
    retData = t.retrieveFeatureDataIdx(3);
    assert(size(retData, 2) == size(rawFeature, 2), 'Indexed size check fail');

    try
        t.retrieveFeatureDataIdx(12);
    catch ME
        assert(~isempty(strfind(ME.message, 'out of bounds')), 'Invalid index check fail');
    end
end

%% Test: Read and write Tag attributes
function [] = testAttributes( varargin )
    fileName = 'testRW.h5';
    f = nix.File(fullfile(pwd, 'tests', fileName), nix.FileMode.Overwrite);
    b = f.createBlock('testBlock', 'nixBlock');
    pos = [1, 2, 3, 4];
    t1 = b.createTag('testTag', 'nixTag', pos);

    assert(~isempty(t1.id));
    assert(strcmp(t1.name, 'testTag'));
    assert(strcmp(t1.type, 'nixTag'));

    t1.type = 'nixTagTest';
    assert(strcmp(t1.type, 'nixTagTest'));

    assert(isempty(t1.definition));
    t1.definition = 'definition';
    assert(strcmp(t1.definition, 'definition'));

    t1.definition = '';
    assert(isempty(t1.definition));

    assert(isempty(t1.units));
    try
        t1.units = 'mV';
    catch ME
        assert(strcmp(ME.identifier, 'MATLAB:class:SetProhibited'));
    end;
    try
        t1.units = ['mV', 'uA'];
    catch ME
        assert(strcmp(ME.identifier, 'MATLAB:class:SetProhibited'));
    end;

    t1.units = {'ms', 'mV'};
    assert(isequal(t1.units, {'ms', 'mV'}));

    t1.units = {};
    assert(isempty(t1.units));

    assert(isequal(t1.position, pos));
    newPos = [1, 2.2, 3];
    t1.position = newPos;
    assert(~isequal(t1.position, pos));
    assert(isequal(t1.position, newPos));

    assert(isempty(t1.extent));
    ext = [1 2];
    newExt = [3 4.5];
    lastExt = [6 7.8 9];
    t1.extent = ext;
    assert(isequal(t1.extent, ext));
    t1.extent = newExt;
    assert(~isequal(t1.extent, ext));
    assert(isequal(t1.extent, newExt));
    t1.extent = [];
    assert(isempty(t1.extent));
    t1.extent = lastExt;

    clear t1 b f;
    f = nix.File(fullfile(pwd, 'tests', fileName), nix.FileMode.ReadOnly);
    assert(isequal(f.blocks{1}.tags{1}.position, newPos));
    assert(isequal(f.blocks{1}.tags{1}.extent, lastExt));
end

%% Test: Has Feature by id
function [] = testHasFeature( varargin )
    fileName = 'testRW.h5';
    f = nix.File(fullfile(pwd, 'tests', fileName), nix.FileMode.Overwrite);
    b = f.createBlock('featureTest', 'nixBlock');
    da = b.createDataArray('featureTestDataArray', 'nixDataArray', nix.DataType.Double, [1 2]);
    t = b.createTag('featureTest', 'nixTag', [1.0 1.2 1.3 15.9]);
    feature = t.createFeature(b.dataArrays{1}, nix.LinkType.Tagged);
    featureID = feature.id;

    assert(~t.hasFeature('I do not exist'));
    assert(t.hasFeature(featureID));

    clear tmp t da b f;
    f = nix.File(fullfile(pwd, 'tests', fileName), nix.FileMode.ReadOnly);
    assert(f.blocks{1}.tags{1}.hasFeature(featureID));
end

%% Test: Has reference by id or name
function [] = testHasReference( varargin )
    fileName = 'testRW.h5';
    daName = 'referenceTest';
    f = nix.File(fullfile(pwd, 'tests', fileName), nix.FileMode.Overwrite);
    b = f.createBlock('referenceTest', 'nixBlock');
    da = b.createDataArray(daName, 'nixDataArray', nix.DataType.Double, [1 2]);
    t = b.createTag('referenceTest', 'nixTag', [1.0 1.2 1.3 15.9]);
    t.addReference(b.dataArrays{1});

    assert(~t.hasReference('I do not exist'));
    assert(t.hasReference(da.id));

    clear t da b f;
    f = nix.File(fullfile(pwd, 'tests', fileName), nix.FileMode.ReadOnly);
    assert(f.blocks{1}.tags{1}.hasReference(daName));
end

%% Test: Compare Tag entities
function [] = testCompare( varargin )
    f = nix.File(fullfile(pwd, 'tests', 'testRW.h5'), nix.FileMode.Overwrite);
    b1 = f.createBlock('testBlock1', 'nixBlock');
    b2 = f.createBlock('testBlock2', 'nixBlock');
    t1 = b1.createTag('testTag1', 'nixTag', [1 2 3]);
    t2 = b1.createTag('testTag2', 'nixTag', [1 2 3]);
    t3 = b2.createTag('testTag1', 'nixTag', [1 2 3]);

    assert(t1.compare(t2) < 0);
    assert(t1.compare(t1) == 0);
    assert(t2.compare(t1) > 0);
    assert(t1.compare(t3) ~= 0);
end

%% Test: Filter Sources
function [] = testFilterSource( varargin )
    filterName = 'filterMe';
    filterType = 'filterType';
    f = nix.File(fullfile(pwd, 'tests', 'testRW.h5'), nix.FileMode.Overwrite);
    b = f.createBlock('testBlock', 'nixBlock');
    t = b.createTag('testTag', 'nixTag', [1 2 3]);
    s = b.createSource(filterName, 'nixSource');
    t.addSource(s);
    filterID = s.id;
	s = b.createSource('testSource1', filterType);
    t.addSource(s);
    filterIDs = {filterID, s.id};
    s = b.createSource('testSource2', filterType);
    t.addSource(s);

    % test empty id filter
    assert(isempty(f.blocks{1}.tags{1}.filterSources(nix.Filter.id, 'IdoNotExist')));

    % test nix.Filter.acceptall
    filtered = f.blocks{1}.tags{1}.filterSources(nix.Filter.acceptall, '');
    assert(size(filtered, 1) == 3);

    % test nix.Filter.id
    filtered = f.blocks{1}.tags{1}.filterSources(nix.Filter.id, filterID);
    assert(size(filtered, 1) == 1);
    assert(strcmp(filtered{1}.id, filterID));

    % test nix.Filter.ids
    filtered = f.blocks{1}.tags{1}.filterSources(nix.Filter.ids, filterIDs);
    assert(size(filtered, 1) == 2);
    assert(strcmp(filtered{1}.id, filterIDs{1}) || strcmp(filtered{1}.id, filterIDs{2}));

    % test nix.Filter.name
    filtered  = f.blocks{1}.tags{1}.filterSources(nix.Filter.name, filterName);
    assert(size(filtered, 1) == 1);
    assert(strcmp(filtered{1}.name, filterName));

    % test nix.Filter.type
    filtered = f.blocks{1}.tags{1}.filterSources(nix.Filter.type, filterType);
    assert(size(filtered, 1) == 2);

    % test nix.Filter.metadata
    mainName = 'testSubSection';
    mainSource = b.createSource(mainName, 'nixSource');
    t.addSource(mainSource);
    subName = 'testSubSection1';
    s = f.createSection(subName, 'nixSection');
    mainSource.setMetadata(s);
    subID = s.id;

    assert(isempty(f.blocks{1}.tags{1}.filterSources(nix.Filter.metadata, 'Do not exist')));
    filtered = f.blocks{1}.tags{1}.filterSources(nix.Filter.metadata, subID);
    assert(size(filtered, 1) == 1);
    assert(strcmp(filtered{1}.name, mainName));

    % test nix.Filter.source
    mainName = 'testSubSource';
    main = b.createSource(mainName, 'nixSource');
    t.addSource(main);
    mainID = main.id;
    subName = 'testSubSource1';
    s = main.createSource(subName, 'nixSource');
    subID = s.id;

    assert(isempty(f.blocks{1}.tags{1}.filterSources(nix.Filter.source, 'Do not exist')));
    filtered = f.blocks{1}.tags{1}.filterSources(nix.Filter.source, subName);
    assert(size(filtered, 1) == 1);
    assert(strcmp(filtered{1}.id, mainID));

    filtered = f.blocks{1}.tags{1}.filterSources(nix.Filter.source, subID);
    assert(size(filtered, 1) == 1);
    assert(strcmp(filtered{1}.name, mainName));
end

%% Test: Filter references
function [] = testFilterReference( varargin )
    filterName = 'filterMe';
    filterType = 'filterType';
    f = nix.File(fullfile(pwd, 'tests', 'testRW.h5'), nix.FileMode.Overwrite);
    b = f.createBlock('testBlock', 'nixBlock');
    t = b.createTag('testTag', 'nixTag', [1 2 3]);
    d = b.createDataArray(filterName, 'nixDataArray', nix.DataType.Double, [1 2]);
    t.addReference(d);
    filterID = d.id;
	d = b.createDataArray('testDataArray1', filterType, nix.DataType.Double, [1 2]);
    t.addReference(d);
    filterIDs = {filterID, d.id};
    d = b.createDataArray('testDataArray2', filterType, nix.DataType.Double, [1 2]);
    t.addReference(d);

    % test empty id filter
    assert(isempty(f.blocks{1}.tags{1}.filterReferences(nix.Filter.id, 'IdoNotExist')));

    % test nix.Filter.acceptall
    filtered = f.blocks{1}.tags{1}.filterReferences(nix.Filter.acceptall, '');
    assert(size(filtered, 1) == 3);

    % test nix.Filter.id
    filtered = f.blocks{1}.tags{1}.filterReferences(nix.Filter.id, filterID);
    assert(size(filtered, 1) == 1);
    assert(strcmp(filtered{1}.id, filterID));

    % test nix.Filter.ids
    filtered = f.blocks{1}.tags{1}.filterReferences(nix.Filter.ids, filterIDs);
    assert(size(filtered, 1) == 2);
    assert(strcmp(filtered{1}.id, filterIDs{1}) || strcmp(filtered{1}.id, filterIDs{2}));

    % test nix.Filter.name
    filtered  = f.blocks{1}.tags{1}.filterReferences(nix.Filter.name, filterName);
    assert(size(filtered, 1) == 1);
    assert(strcmp(filtered{1}.name, filterName));

    % test nix.Filter.type
    filtered = f.blocks{1}.tags{1}.filterReferences(nix.Filter.type, filterType);
    assert(size(filtered, 1) == 2);

    % test nix.Filter.metadata
    mainName = 'testSubSection';
    main = b.createDataArray(mainName, 'nixDataArray', nix.DataType.Bool, [2 2]);
    t.addReference(main);
    subName = 'testSubSection1';
    s = f.createSection(subName, 'nixSection');
    main.setMetadata(s);
    subID = s.id;

    assert(isempty(f.blocks{1}.tags{1}.filterReferences(nix.Filter.metadata, 'Do not exist')));
    filtered = f.blocks{1}.tags{1}.filterReferences(nix.Filter.metadata, subID);
    assert(size(filtered, 1) == 1);
    assert(strcmp(filtered{1}.name, mainName));

    % test nix.Filter.source
    mainName = 'testSubSource';
    main = b.createDataArray(mainName, 'nixDataArray', nix.DataType.Bool, [2 2]);
    t.addReference(main);
    mainID = main.id;
    subName = 'testSubSource1';
    s = b.createSource(subName, 'nixSource');
    main.addSource(s);
    subID = s.id;

    assert(isempty(f.blocks{1}.tags{1}.filterReferences(nix.Filter.source, 'Do not exist')));

    % filter works only for ID, not for name
    filtered = f.blocks{1}.tags{1}.filterReferences(nix.Filter.source, subID);
    assert(size(filtered, 1) == 1);
    assert(strcmp(filtered{1}.name, mainName));
end

%% Test: Filter Features
function [] = testFilterFeature( varargin )
    f = nix.File(fullfile(pwd, 'tests', 'testRW.h5'), nix.FileMode.Overwrite);
    b = f.createBlock('testBlock', 'nixBlock');
    t = b.createTag('testTag', 'nixTag', [1 2 3]);
    d = b.createDataArray('testDataArray1', 'nixDataArray', nix.DataType.Double, [1 2]);
    feat = t.createFeature(d, nix.LinkType.Tagged);
    filterID = feat.id;
	d = b.createDataArray('testDataArray2', 'nixDataArray', nix.DataType.Double, [1 2]);
    feat = t.createFeature(d, nix.LinkType.Tagged);
    filterIDs = {filterID, feat.id};

    % test empty id filter
    assert(isempty(f.blocks{1}.tags{1}.filterFeatures(nix.Filter.id, 'IdoNotExist')));

    % test nix.Filter.acceptall
    filtered = f.blocks{1}.tags{1}.filterFeatures(nix.Filter.acceptall, '');
    assert(size(filtered, 1) == 2);

    % test nix.Filter.id
    filtered = f.blocks{1}.tags{1}.filterFeatures(nix.Filter.id, filterID);
    assert(size(filtered, 1) == 1);
    assert(strcmp(filtered{1}.id, filterID));

    % test nix.Filter.ids
    filtered = f.blocks{1}.tags{1}.filterFeatures(nix.Filter.ids, filterIDs);
    assert(size(filtered, 1) == 2);
    assert(strcmp(filtered{1}.id, filterIDs{1}) || strcmp(filtered{1}.id, filterIDs{2}));

    % test fail on nix.Filter.name
    err = 'unknown or unsupported filter';
    try
        f.blocks{1}.tags{1}.filterFeatures(nix.Filter.name, 'someName');
    catch ME
        assert(strcmp(ME.message, err));
    end

    % test fail on nix.Filter.type
    err = 'unknown or unsupported filter';
    try
        f.blocks{1}.tags{1}.filterFeatures(nix.Filter.type, 'someType');
    catch ME
        assert(strcmp(ME.message, err));
    end

    % test fail on nix.Filter.metadata
    err = 'unknown or unsupported filter';
    try
        f.blocks{1}.tags{1}.filterFeatures(nix.Filter.metadata, 'someMetadata');
    catch ME
        assert(strcmp(ME.message, err));
    end

    % test fail on nix.Filter.source
    try
        f.blocks{1}.tags{1}.filterFeatures(nix.Filter.source, 'someSource');
    catch ME
        assert(strcmp(ME.message, err));
    end
end


text:
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'jdb'
require 'pry'

RSpec.configure do |config|
  config.formatter = :documentation
  config.color = true
  config.tty = true
end

Dir['spec/dummies/*.rb'].each {|file| load file }

redpajama_set_name: RedPajamaGithub


text:
import { LetterMm20 } from "../../";

export = LetterMm20;


text:
//
//  RKManagedObjectMapping.m
//  RestKit
//
//  Created by Blake Watters on 5/31/11.
//  Copyright (c) 2009-2012 RestKit. All rights reserved.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//

#import "RKManagedObjectMapping.h"
#import "NSManagedObject+ActiveRecord.h"
#import "RKManagedObjectStore.h"
#import "RKDynamicObjectMappingMatcher.h"
#import "RKObjectPropertyInspector+CoreData.h"
#import "NSEntityDescription+RKAdditions.h"
#import "RKLog.h"

// Set Logging Component
#undef RKLogComponent
#define RKLogComponent lcl_cRestKitCoreData

@implementation RKManagedObjectMapping

@synthesize entity = _entity;
@synthesize primaryKeyAttribute = _primaryKeyAttribute;
@synthesize objectStore = _objectStore;

+ (id)mappingForClass:(Class)objectClass
{
    @throw [NSException exceptionWithName:NSInternalInconsistencyException
                                   reason:[NSString stringWithFormat:@"You must provide a managedObjectStore. Invoke mappingForClass:inManagedObjectStore: instead."]
                                 userInfo:nil];
}

+ (id)mappingForClass:(Class)objectClass inManagedObjectStore:(RKManagedObjectStore *)objectStore
{
    return [self mappingForEntityWithName:NSStringFromClass(objectClass) inManagedObjectStore:objectStore];
}

+ (RKManagedObjectMapping *)mappingForEntity:(NSEntityDescription *)entity inManagedObjectStore:(RKManagedObjectStore *)objectStore
{
    return [[[self alloc] initWithEntity:entity inManagedObjectStore:objectStore] autorelease];
}

+ (RKManagedObjectMapping *)mappingForEntityWithName:(NSString *)entityName inManagedObjectStore:(RKManagedObjectStore *)objectStore
{
    return [self mappingForEntity:[NSEntityDescription entityForName:entityName inManagedObjectContext:objectStore.primaryManagedObjectContext]
             inManagedObjectStore:objectStore];
}

- (id)initWithEntity:(NSEntityDescription *)entity inManagedObjectStore:(RKManagedObjectStore *)objectStore
{
    NSAssert(entity, @"Cannot initialize an RKManagedObjectMapping without an entity. Maybe you want RKObjectMapping instead?");
    NSAssert(objectStore, @"Object store cannot be nil");
    Class objectClass = NSClassFromString([entity managedObjectClassName]);
    NSAssert(objectClass, @"The managedObjectClass for an object mapped entity cannot be nil.");
    self = [self init];
    if (self) {
        _objectClass = [objectClass retain];
        _entity = [entity retain];
        _objectStore = objectStore;

        [self addObserver:self forKeyPath:@"entity" options:NSKeyValueObservingOptionInitial context:nil];
        [self addObserver:self forKeyPath:@"primaryKeyAttribute" options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew context:nil];
    }

    return self;
}

- (id)init
{
    self = [super init];
    if (self) {
        _relationshipToPrimaryKeyMappings = [[NSMutableDictionary alloc] init];
    }

    return self;
}

- (void)dealloc
{
    [self removeObserver:self forKeyPath:@"entity"];
    [self removeObserver:self forKeyPath:@"primaryKeyAttribute"];

    [_entity release];
    [_relationshipToPrimaryKeyMappings release];
    [super dealloc];
}

- (NSDictionary *)relationshipsAndPrimaryKeyAttributes
{
    return _relationshipToPrimaryKeyMappings;
}

- (void)connectRelationship:(NSString *)relationshipName withObjectForPrimaryKeyAttribute:(NSString *)primaryKeyAttribute
{
    NSAssert([_relationshipToPrimaryKeyMappings objectForKey:relationshipName] == nil, @"Cannot add connect relationship %@ by primary key, a mapping already exists.", relationshipName);
    [_relationshipToPrimaryKeyMappings setObject:primaryKeyAttribute forKey:relationshipName];
}

- (void)connectRelationshipsWithObjectsForPrimaryKeyAttributes:(NSString *)firstRelationshipName, ...
{
    va_list args;
    va_start(args, firstRelationshipName);
    for (NSString *relationshipName = firstRelationshipName; relationshipName != nil; relationshipName = va_arg(args, NSString *)) {
        NSString *primaryKeyAttribute = va_arg(args, NSString *);
        NSAssert(primaryKeyAttribute != nil, @"Cannot connect a relationship without an attribute containing the primary key");
        [self connectRelationship:relationshipName withObjectForPrimaryKeyAttribute:primaryKeyAttribute];
        // TODO: Raise proper exception here, argument error...
    }
    va_end(args);
}

- (void)connectRelationship:(NSString *)relationshipName withObjectForPrimaryKeyAttribute:(NSString *)primaryKeyAttribute whenValueOfKeyPath:(NSString *)keyPath isEqualTo:(id)value
{
    NSAssert([_relationshipToPrimaryKeyMappings objectForKey:relationshipName] == nil, @"Cannot add connect relationship %@ by primary key, a mapping already exists.", relationshipName);
    RKDynamicObjectMappingMatcher *matcher = [[RKDynamicObjectMappingMatcher alloc] initWithKey:keyPath value:value primaryKeyAttribute:primaryKeyAttribute];
    [_relationshipToPrimaryKeyMappings setObject:matcher forKey:relationshipName];
    [matcher release];
}

- (void)connectRelationship:(NSString *)relationshipName withObjectForPrimaryKeyAttribute:(NSString *)primaryKeyAttribute usingEvaluationBlock:(BOOL (^)(id data))block
{
    NSAssert([_relationshipToPrimaryKeyMappings objectForKey:relationshipName] == nil, @"Cannot add connect relationship %@ by primary key, a mapping already exists.", relationshipName);
    RKDynamicObjectMappingMatcher *matcher = [[RKDynamicObjectMappingMatcher alloc] initWithPrimaryKeyAttribute:primaryKeyAttribute evaluationBlock:block];
    [_relationshipToPrimaryKeyMappings setObject:matcher forKey:relationshipName];
    [matcher release];
}

- (id)defaultValueForMissingAttribute:(NSString *)attributeName
{
    NSAttributeDescription *desc = [[self.entity attributesByName] valueForKey:attributeName];
    return [desc defaultValue];
}

- (id)mappableObjectForData:(id)mappableData
{
    NSAssert(mappableData, @"Mappable data cannot be nil");

    id object = nil;
    id primaryKeyValue = nil;
    NSString *primaryKeyAttribute;

    NSEntityDescription *entity = [self entity];
    RKObjectAttributeMapping *primaryKeyAttributeMapping = nil;

    primaryKeyAttribute = [self primaryKeyAttribute];
    if (primaryKeyAttribute) {
        // If a primary key has been set on the object mapping, find the attribute mapping
        // so that we can extract any existing primary key from the mappable data
        for (RKObjectAttributeMapping *attributeMapping in self.attributeMappings) {
            if ([attributeMapping.destinationKeyPath isEqualToString:primaryKeyAttribute]) {
                primaryKeyAttributeMapping = attributeMapping;
                break;
            }
        }

        // Get the primary key value out of the mappable data (if any)
        if ([primaryKeyAttributeMapping isMappingForKeyOfNestedDictionary]) {
            RKLogDebug(@"Detected use of nested dictionary key as primaryKey attribute...");
            primaryKeyValue = [[mappableData allKeys] lastObject];
        } else {
            NSString *keyPathForPrimaryKeyElement = primaryKeyAttributeMapping.sourceKeyPath;
            if (keyPathForPrimaryKeyElement) {
                primaryKeyValue = [mappableData valueForKeyPath:keyPathForPrimaryKeyElement];
            } else {
                RKLogWarning(@"Unable to find source attribute for primaryKeyAttribute '%@': unable to find existing object instances by primary key.", primaryKeyAttribute);
            }
        }
    }

    // If we have found the primary key attribute & value, try to find an existing instance to update
    if (primaryKeyAttribute && primaryKeyValue && NO == [primaryKeyValue isEqual:[NSNull null]])
    {
        // Raj:
        id coercedPrimaryKeyValue = [entity coerceValueForPrimaryKey:primaryKeyValue];

        object = [self.objectStore.cacheStrategy findInstanceOfEntity:entity
                                              withPrimaryKeyAttribute:primaryKeyAttribute
                                                                value:coercedPrimaryKeyValue    // Raj
                                               inManagedObjectContext:[self.objectStore managedObjectContextForCurrentThread]];

        if (object && [self.objectStore.cacheStrategy respondsToSelector:@selector(didFetchObject:)]) {
            [self.objectStore.cacheStrategy didFetchObject:object];
        }
    }

    if (object == nil) {
        object = [[[NSManagedObject alloc] initWithEntity:entity
                           insertIntoManagedObjectContext:[_objectStore managedObjectContextForCurrentThread]] autorelease];
        if (primaryKeyAttribute && primaryKeyValue && ![primaryKeyValue isEqual:[NSNull null]]) {
            id coercedPrimaryKeyValue = [entity coerceValueForPrimaryKey:primaryKeyValue];
            [object setValue:coercedPrimaryKeyValue forKey:primaryKeyAttribute];
        }

        if ([self.objectStore.cacheStrategy respondsToSelector:@selector(didCreateObject:)]) {
            [self.objectStore.cacheStrategy didCreateObject:object];
        }
    }
    return object;
}

- (Class)classForProperty:(NSString *)propertyName
{
    Class propertyClass = [super classForProperty:propertyName];
    if (! propertyClass) {
        propertyClass = [[RKObjectPropertyInspector sharedInspector] typeForProperty:propertyName ofEntity:self.entity];
    }

    return propertyClass;
}

/*
 Allows the primaryKeyAttributeName property on the NSEntityDescription to configure the mapping and vice-versa
 */
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"entity"]) {
        if (! self.primaryKeyAttribute) {
            self.primaryKeyAttribute = [self.entity primaryKeyAttributeName];
        }
    } else if ([keyPath isEqualToString:@"primaryKeyAttribute"]) {
        if (! self.entity.primaryKeyAttribute) {
            self.entity.primaryKeyAttributeName = self.primaryKeyAttribute;
        }
    }
}
@end


text:
require "test_helper"
require "database/setup"

class ActiveStorage::VariantsControllerTest < ActionDispatch::IntegrationTest
  setup do
    @blob = create_file_blob filename: "racecar.jpg"
  end

  test "showing variant inline" do
    get rails_blob_variation_url(
      filename: @blob.filename,
      signed_blob_id: @blob.signed_id,
      variation_key: ActiveStorage::Variation.encode(resize: "100x100"))

    assert_redirected_to(/racecar\.jpg\?.*disposition=inline/)

    image = read_image(@blob.variant(resize: "100x100"))
    assert_equal 100, image.width
    assert_equal 67, image.height
  end

  test "showing variant with invalid signed blob ID" do
    get rails_blob_variation_url(
      filename: @blob.filename,
      signed_blob_id: "invalid",
      variation_key: ActiveStorage::Variation.encode(resize: "100x100"))

    assert_response :not_found
  end
end


text:
@interface NSHTTPCookieStorageDemoViewController : BaseViewController

@end


text:
import { Event } from './Event';
import { Session } from '../../OpenVidu/Session';
import { Stream } from '../../OpenVidu/Stream';
import { StreamManager } from '../../OpenVidu/StreamManager';
import { StreamPropertyChangedEventReason, ChangedPropertyType } from './Types/Types';

/**
 * Triggered by `streamPropertyChanged` (available for [Session](/en/stable/api/openvidu-browser/interfaces/SessionEventMap.html#streamPropertyChanged) and [StreamManager](/en/stable/api/openvidu-browser/interfaces/StreamManagerEventMap.html#streamPropertyChanged) objects)
 */
export class StreamPropertyChangedEvent extends Event {
    /**
     * The Stream whose property has changed. You can always identify the user publishing the changed stream by consulting property {@link Stream.connection}
     */
    stream: Stream;

    /**
     * The property of the stream that changed. This value is either `"videoActive"`, `"audioActive"`, `"videoTrack"`, `"audioTrack"`, `"videoDimensions"` or `"filter"`
     */
    changedProperty: ChangedPropertyType;

    /**
     * Cause of the change on the stream's property:
     * - For `videoActive`: `"publishVideo"`
     * - For `audioActive`: `"publishAudio"`
     * - For `videoTrack`: `"trackReplaced"`
     * - For `audioTrack`: `"trackReplaced"`
     * - For `videoDimensions`: `"deviceRotated"`, `"screenResized"` or `"trackReplaced"`
     * - For `filter`: `"applyFilter"`, `"execFilterMethod"` or `"removeFilter"`
     */
    reason: StreamPropertyChangedEventReason;

    /**
     * New value of the property (after change, current value)
     */
    newValue: Object;

    /**
     * Previous value of the property (before change)
     */
    oldValue: Object;

    /**
     * @hidden
     */
    constructor(
        target: Session | StreamManager,
        stream: Stream,
        changedProperty: ChangedPropertyType,
        newValue: Object,
        oldValue: Object,
        reason: StreamPropertyChangedEventReason
    ) {
        super(false, target, 'streamPropertyChanged');
        this.stream = stream;
        this.changedProperty = changedProperty;
        this.newValue = newValue;
        this.oldValue = oldValue;
        this.reason = reason;
    }

    /**
     * @hidden
     */
    // tslint:disable-next-line:no-empty
    callDefaultBehavior() { }
}


text:
Los formularios son importantes. Este ejercicio te enseñará como procesar los formularios web tradicionales (no-AJAX).

Escribe una ruta (`'/form'`) que procese la entrada del formulario HTML
(`<form><input name="str"/></form>`) e imprima el valor de `str` al revés.

Para manipular una solicitud POST, usa el método `post()`, que es utilizado de la misma manera que `get()`:

```js
app.post('/path', function(req, res){...})
```

Espress.js usa middleware para proveer funcionalidades extra a tu servidor web.

En pocas palabras, un middleware es una función invocada por Express.js
antes de tu propio manejador de peticiones (request handler)

Los middleware proveen una gran variedad de funcionalidades como manipulación de registros,
entregar archivos estáticos y manipulación de errores.

Un middleware es agregado invocando `use()` en la aplicación y pasando el middleware
como un parámetro.

Para parsear el contenido de las peticiones `x-www-form-urlencoded`, Espress.js puede usar
el middleware `urlencoded()` del módulo `body-parser`.

```js
const bodyparser = require('body-parser')
app.use(bodyparser.urlencoded({extended: false}))
```

-----------------------------

## PISTAS

Así es como podemos imprimir caracteres al revés (una de las formas de hacerlo):

```js
req.body.str.split('').reverse().join('')
```

El parámetro extended pasado como true (qs) o false (querystring) determina el módulo del parser.

Puedes leer más sobre el middleware Connect en este link (inglés):

  https://github.com/senchalabs/connect#middleware

La documentación (en inglés) del módulo body-parser puede ser encontrada aquí:

  https://github.com/expressjs/body-parser

Videos: http://bit.ly/1jW1sBf.

-----------------------------

## NOTA
Cuando crees tus proyectos desde cero, instala la dependencia `body-parser` con
npm tipeando en tu terminal:

```sh
$ npm install body-parser
```
Nuevamente, el puerto que debes usar es provisto por `process.argv[2]`.


text:
package org.apache.druid.indexing.kinesis;

import com.amazonaws.services.kinesis.AmazonKinesis;
import com.amazonaws.services.kinesis.AmazonKinesisClient;
import com.amazonaws.services.kinesis.model.DescribeStreamResult;
import com.amazonaws.services.kinesis.model.GetRecordsRequest;
import com.amazonaws.services.kinesis.model.GetRecordsResult;
import com.amazonaws.services.kinesis.model.GetShardIteratorResult;
import com.amazonaws.services.kinesis.model.Record;
import com.amazonaws.services.kinesis.model.Shard;
import com.amazonaws.services.kinesis.model.StreamDescription;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import org.apache.druid.indexing.seekablestream.common.OrderedPartitionableRecord;
import org.apache.druid.indexing.seekablestream.common.StreamPartition;
import org.apache.druid.java.util.common.ISE;
import org.apache.druid.java.util.common.StringUtils;
import org.easymock.Capture;
import org.easymock.EasyMockSupport;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static org.easymock.EasyMock.anyObject;
import static org.easymock.EasyMock.anyString;
import static org.easymock.EasyMock.capture;
import static org.easymock.EasyMock.eq;
import static org.easymock.EasyMock.expect;

public class KinesisRecordSupplierTest extends EasyMockSupport
{
  private static final String stream = "stream";
  private static long poll_timeout_millis = 2000;
  private static int recordsPerFetch;
  private static String shardId1 = "1";
  private static String shardId0 = "0";
  private static String shard1Iterator = "1";
  private static String shard0Iterator = "0";
  private static AmazonKinesis kinesis;
  private static DescribeStreamResult describeStreamResult;
  private static GetShardIteratorResult getShardIteratorResult0;
  private static GetShardIteratorResult getShardIteratorResult1;
  private static GetRecordsResult getRecordsResult0;
  private static GetRecordsResult getRecordsResult1;
  private static StreamDescription streamDescription;
  private static Shard shard0;
  private static Shard shard1;
  private static KinesisRecordSupplier recordSupplier;
  private static List<Record> shard1Records = ImmutableList.of(
      new Record().withData(JB("2011", "d", "y", "10", "20.0", "1.0")).withSequenceNumber("0"),
      new Record().withData(JB("2011", "e", "y", "10", "20.0", "1.0")).withSequenceNumber("1"),
      new Record().withData(JB("246140482-04-24T15:36:27.903Z", "x", "z", "10", "20.0", "1.0")).withSequenceNumber("2"),
      new Record().withData(ByteBuffer.wrap(StringUtils.toUtf8("unparseable"))).withSequenceNumber("3"),
      new Record().withData(ByteBuffer.wrap(StringUtils.toUtf8("unparseable2"))).withSequenceNumber("4"),
      new Record().withData(ByteBuffer.wrap(StringUtils.toUtf8("{}"))).withSequenceNumber("5"),
      new Record().withData(JB("2013", "f", "y", "10", "20.0", "1.0")).withSequenceNumber("6"),
      new Record().withData(JB("2049", "f", "y", "notanumber", "20.0", "1.0")).withSequenceNumber("7"),
      new Record().withData(JB("2012", "g", "y", "10", "20.0", "1.0")).withSequenceNumber("8"),
      new Record().withData(JB("2011", "h", "y", "10", "20.0", "1.0")).withSequenceNumber("9")
  );
  private static List<Record> shard0Records = ImmutableList.of(
      new Record().withData(JB("2008", "a", "y", "10", "20.0", "1.0")).withSequenceNumber("0"),
      new Record().withData(JB("2009", "b", "y", "10", "20.0", "1.0")).withSequenceNumber("1")
  );
  private static List<Object> allRecords = ImmutableList.builder()
                                                        .addAll(shard0Records.stream()
                                                                             .map(x -> new OrderedPartitionableRecord<>(
                                                                                stream,
                                                                                shardId0,
                                                                                x.getSequenceNumber(),
                                                                                Collections
                                                                                .singletonList(
                                                                                toByteArray(
                                                                                x.getData()))
                                                                             ))
                                                                             .collect(
                                                                                Collectors
                                                                                .toList()))
                                                        .addAll(shard1Records.stream()
                                                                             .map(x -> new OrderedPartitionableRecord<>(
                                                                                stream,
                                                                                shardId1,
                                                                                x.getSequenceNumber(),
                                                                                Collections
                                                                                .singletonList(
                                                                                toByteArray(
                                                                                x.getData()))
                                                                             ))
                                                                             .collect(
                                                                                Collectors
                                                                                .toList()))
                                                        .build();

  private static ByteBuffer JB(String timestamp, String dim1, String dim2, String dimLong, String dimFloat, String met1)
  {
    try {
      return ByteBuffer.wrap(new ObjectMapper().writeValueAsBytes(
          ImmutableMap.builder()
                      .put("timestamp", timestamp)
                      .put("dim1", dim1)
                      .put("dim2", dim2)
                      .put("dimLong", dimLong)
                      .put("dimFloat", dimFloat)
                      .put("met1", met1)
                      .build()
      ));
    }
    catch (Exception e) {
      throw Throwables.propagate(e);
    }
  }

  @Before
  public void setupTest()
  {
    kinesis = createMock(AmazonKinesisClient.class);
    describeStreamResult = createMock(DescribeStreamResult.class);
    getShardIteratorResult0 = createMock(GetShardIteratorResult.class);
    getShardIteratorResult1 = createMock(GetShardIteratorResult.class);
    getRecordsResult0 = createMock(GetRecordsResult.class);
    getRecordsResult1 = createMock(GetRecordsResult.class);
    streamDescription = createMock(StreamDescription.class);
    shard0 = createMock(Shard.class);
    shard1 = createMock(Shard.class);
    recordsPerFetch = 1;
  }

  @After
  public void tearDownTest()
  {
    recordSupplier.close();
    recordSupplier = null;
  }

  @Test
  public void testSupplierSetup()
  {
    Capture<String> captured = Capture.newInstance();
    expect(kinesis.describeStream(capture(captured))).andReturn(describeStreamResult).once();
    expect(describeStreamResult.getStreamDescription()).andReturn(streamDescription).once();
    expect(streamDescription.getShards()).andReturn(ImmutableList.of(shard0, shard1)).once();
    expect(shard0.getShardId()).andReturn(shardId0).once();
    expect(shard1.getShardId()).andReturn(shardId1).once();

    replayAll();

    Set<StreamPartition<String>> partitions = ImmutableSet.of(
        StreamPartition.of(stream, shardId0),
        StreamPartition.of(stream, shardId1)
    );

    recordSupplier = new KinesisRecordSupplier(
        kinesis,
        recordsPerFetch,
        0,
        2,
        false,
        100,
        5000,
        5000,
        60000,
        5
    );

    Assert.assertTrue(recordSupplier.getAssignment().isEmpty());

    recordSupplier.assign(partitions);

    Assert.assertEquals(partitions, recordSupplier.getAssignment());
    Assert.assertEquals(ImmutableSet.of(shardId1, shardId0), recordSupplier.getPartitionIds(stream));
    Assert.assertEquals(Collections.emptyList(), recordSupplier.poll(100));

    verifyAll();
    Assert.assertEquals(stream, captured.getValue());
  }

  private static GetRecordsRequest generateGetRecordsReq(String shardIterator, int limit)
  {
    return new GetRecordsRequest().withShardIterator(shardIterator).withLimit(limit);
  }

  // filter out EOS markers
  private static List<OrderedPartitionableRecord<String, String>> cleanRecords(List<OrderedPartitionableRecord<String, String>> records)
  {
    return records.stream()
                  .filter(x -> !x.getSequenceNumber()
                                 .equals(KinesisSequenceNumber.END_OF_SHARD_MARKER))
                  .collect(Collectors.toList());
  }

  @Test
  public void testPoll() throws InterruptedException
  {
    recordsPerFetch = 100;

    expect(kinesis.getShardIterator(
        anyObject(),
        eq(shardId0),
        anyString(),
        anyString()
    )).andReturn(
        getShardIteratorResult0).anyTimes();

    expect(kinesis.getShardIterator(
        anyObject(),
        eq(shardId1),
        anyString(),
        anyString()
    )).andReturn(
        getShardIteratorResult1).anyTimes();

    expect(getShardIteratorResult0.getShardIterator()).andReturn(shard0Iterator).anyTimes();
    expect(getShardIteratorResult1.getShardIterator()).andReturn(shard1Iterator).anyTimes();
    expect(kinesis.getRecords(generateGetRecordsReq(shard0Iterator, recordsPerFetch))).andReturn(getRecordsResult0)
                                                                                .anyTimes();
    expect(kinesis.getRecords(generateGetRecordsReq(shard1Iterator, recordsPerFetch))).andReturn(getRecordsResult1)
                                                                                .anyTimes();
    expect(getRecordsResult0.getRecords()).andReturn(shard0Records).once();
    expect(getRecordsResult1.getRecords()).andReturn(shard1Records).once();
    expect(getRecordsResult0.getNextShardIterator()).andReturn(null).anyTimes();
    expect(getRecordsResult1.getNextShardIterator()).andReturn(null).anyTimes();

    replayAll();

    Set<StreamPartition<String>> partitions = ImmutableSet.of(
        StreamPartition.of(stream, shardId0),
        StreamPartition.of(stream, shardId1)
    );

    recordSupplier = new KinesisRecordSupplier(
        kinesis,
        recordsPerFetch,
        0,
        2,
        false,
        100,
        5000,
        5000,
        60000,
        100
    );

    recordSupplier.assign(partitions);
    recordSupplier.seekToEarliest(partitions);
    recordSupplier.start();

    while (recordSupplier.bufferSize() < 12) {
      Thread.sleep(100);
    }

    List<OrderedPartitionableRecord<String, String>> polledRecords = cleanRecords(recordSupplier.poll(
        poll_timeout_millis));

    verifyAll();

    Assert.assertEquals(partitions, recordSupplier.getAssignment());
    Assert.assertTrue(polledRecords.containsAll(allRecords));
  }

  @Test
  public void testSeek()
      throws InterruptedException
  {
    recordsPerFetch = 100;

    expect(kinesis.getShardIterator(
        anyObject(),
        eq(shardId0),
        anyString(),
        anyString()
    )).andReturn(
        getShardIteratorResult0).anyTimes();

    expect(kinesis.getShardIterator(
        anyObject(),
        eq(shardId1),
        anyString(),
        anyString()
    )).andReturn(
        getShardIteratorResult1).anyTimes();

    expect(getShardIteratorResult0.getShardIterator()).andReturn(shard0Iterator).anyTimes();
    expect(getShardIteratorResult1.getShardIterator()).andReturn(shard1Iterator).anyTimes();
    expect(kinesis.getRecords(generateGetRecordsReq(shard0Iterator, recordsPerFetch))).andReturn(getRecordsResult0)
                                                                                .anyTimes();
    expect(kinesis.getRecords(generateGetRecordsReq(shard1Iterator, recordsPerFetch))).andReturn(getRecordsResult1)
                                                                                .anyTimes();
    expect(getRecordsResult0.getRecords()).andReturn(shard0Records.subList(1, shard0Records.size())).once();
    expect(getRecordsResult1.getRecords()).andReturn(shard1Records.subList(2, shard1Records.size())).once();
    expect(getRecordsResult0.getNextShardIterator()).andReturn(null).anyTimes();
    expect(getRecordsResult1.getNextShardIterator()).andReturn(null).anyTimes();

    replayAll();

    StreamPartition<String> shard0Partition = StreamPartition.of(stream, shardId0);
    StreamPartition<String> shard1Partition = StreamPartition.of(stream, shardId1);
    Set<StreamPartition<String>> partitions = ImmutableSet.of(
        shard0Partition,
        shard1Partition
    );

    recordSupplier = new KinesisRecordSupplier(
        kinesis,
        recordsPerFetch,
        0,
        2,
        false,
        100,
        5000,
        5000,
        60000,
        100
    );

    recordSupplier.assign(partitions);
    recordSupplier.seek(shard1Partition, shard1Records.get(2).getSequenceNumber());
    recordSupplier.seek(shard0Partition, shard0Records.get(1).getSequenceNumber());
    recordSupplier.start();

    for (int i = 0; i < 10 && recordSupplier.bufferSize() < 9; i++) {
      Thread.sleep(100);
    }

    List<OrderedPartitionableRecord<String, String>> polledRecords = cleanRecords(recordSupplier.poll(
        poll_timeout_millis));

    verifyAll();
    Assert.assertEquals(9, polledRecords.size());
    Assert.assertTrue(polledRecords.containsAll(allRecords.subList(4, 12)));
    Assert.assertTrue(polledRecords.containsAll(allRecords.subList(1, 2)));

  }

  @Test
  public void testSeekToLatest()
      throws InterruptedException
  {
    recordsPerFetch = 100;

    expect(kinesis.getShardIterator(
        anyObject(),
        eq(shardId0),
        anyString(),
        anyString()
    )).andReturn(
        getShardIteratorResult0).anyTimes();

    expect(kinesis.getShardIterator(
        anyObject(),
        eq(shardId1),
        anyString(),
        anyString()
    )).andReturn(
        getShardIteratorResult1).anyTimes();

    expect(getShardIteratorResult0.getShardIterator()).andReturn(null).once();
    expect(getShardIteratorResult1.getShardIterator()).andReturn(null).once();

    replayAll();

    StreamPartition<String> shard0 = StreamPartition.of(stream, shardId0);
    StreamPartition<String> shard1 = StreamPartition.of(stream, shardId1);
    Set<StreamPartition<String>> partitions = ImmutableSet.of(
        shard0,
        shard1
    );

    recordSupplier = new KinesisRecordSupplier(
        kinesis,
        recordsPerFetch,
        0,
        2,
        false,
        100,
        5000,
        5000,
        60000,
        100
    );

    recordSupplier.assign(partitions);
    recordSupplier.seekToLatest(partitions);
    recordSupplier.start();

    for (int i = 0; i < 10 && recordSupplier.bufferSize() < 2; i++) {
      Thread.sleep(100);
    }
    Assert.assertEquals(Collections.emptyList(), cleanRecords(recordSupplier.poll(poll_timeout_millis)));

    verifyAll();
  }

  @Test(expected = ISE.class)
  public void testSeekUnassigned() throws InterruptedException
  {
    StreamPartition<String> shard0 = StreamPartition.of(stream, shardId0);
    StreamPartition<String> shard1 = StreamPartition.of(stream, shardId1);
    Set<StreamPartition<String>> partitions = ImmutableSet.of(
        shard1
    );

    recordSupplier = new KinesisRecordSupplier(
        kinesis,
        1,
        0,
        2,
        false,
        100,
        5000,
        5000,
        60000,
        5
    );

    recordSupplier.assign(partitions);
    recordSupplier.seekToEarliest(Collections.singleton(shard0));
  }

  @Test
  public void testPollAfterSeek()
      throws InterruptedException
  {
    // tests that after doing a seek, the now invalid records in buffer is cleaned up properly
    recordsPerFetch = 100;

    expect(kinesis.getShardIterator(
        anyObject(),
        eq(shardId1),
        anyString(),
        eq("5")
    )).andReturn(
        getShardIteratorResult1).once();

    expect(kinesis.getShardIterator(anyObject(), eq(shardId1), anyString(), eq("7"))).andReturn(getShardIteratorResult0)
                                                                                .once();

    expect(getShardIteratorResult1.getShardIterator()).andReturn(shard1Iterator).once();
    expect(getShardIteratorResult0.getShardIterator()).andReturn(shard0Iterator).once();
    expect(kinesis.getRecords(generateGetRecordsReq(shard1Iterator, recordsPerFetch))).andReturn(getRecordsResult1)
                                                                                .once();
    expect(kinesis.getRecords(generateGetRecordsReq(shard0Iterator, recordsPerFetch))).andReturn(getRecordsResult0)
                                                                                .once();
    expect(getRecordsResult1.getRecords()).andReturn(shard1Records.subList(5, shard1Records.size())).once();
    expect(getRecordsResult0.getRecords()).andReturn(shard1Records.subList(7, shard1Records.size())).once();
    expect(getRecordsResult1.getNextShardIterator()).andReturn(null).anyTimes();
    expect(getRecordsResult0.getNextShardIterator()).andReturn(null).anyTimes();

    replayAll();

    Set<StreamPartition<String>> partitions = ImmutableSet.of(
        StreamPartition.of(stream, shardId1)
    );

    recordSupplier = new KinesisRecordSupplier(
        kinesis,
        recordsPerFetch,
        0,
        2,
        false,
        100,
        5000,
        5000,
        60000,
        1
    );

    recordSupplier.assign(partitions);
    recordSupplier.seek(StreamPartition.of(stream, shardId1), "5");
    recordSupplier.start();

    for (int i = 0; i < 10 && recordSupplier.bufferSize() < 6; i++) {
      Thread.sleep(100);
    }

    OrderedPartitionableRecord<String, String> firstRecord = recordSupplier.poll(poll_timeout_millis).get(0);

    Assert.assertEquals(
        allRecords.get(7),
        firstRecord
    );

    recordSupplier.seek(StreamPartition.of(stream, shardId1), "7");
    recordSupplier.start();

    while (recordSupplier.bufferSize() < 4) {
      Thread.sleep(100);
    }

    OrderedPartitionableRecord<String, String> record2 = recordSupplier.poll(poll_timeout_millis).get(0);

    Assert.assertEquals(allRecords.get(9), record2);
    verifyAll();
  }

  @Test
  public void testPollDeaggregate() throws InterruptedException
  {
    recordsPerFetch = 100;

    expect(kinesis.getShardIterator(
        anyObject(),
        eq(shardId0),
        anyString(),
        anyString()
    )).andReturn(
        getShardIteratorResult0).anyTimes();

    expect(kinesis.getShardIterator(
        anyObject(),
        eq(shardId1),
        anyString(),
        anyString()
    )).andReturn(
        getShardIteratorResult1).anyTimes();

    expect(getShardIteratorResult0.getShardIterator()).andReturn(shard0Iterator).anyTimes();
    expect(getShardIteratorResult1.getShardIterator()).andReturn(shard1Iterator).anyTimes();
    expect(kinesis.getRecords(generateGetRecordsReq(shard0Iterator, recordsPerFetch))).andReturn(getRecordsResult0)
                                                                                .anyTimes();
    expect(kinesis.getRecords(generateGetRecordsReq(shard1Iterator, recordsPerFetch))).andReturn(getRecordsResult1)
                                                                                .anyTimes();
    expect(getRecordsResult0.getRecords()).andReturn(shard0Records).once();
    expect(getRecordsResult1.getRecords()).andReturn(shard1Records).once();
    expect(getRecordsResult0.getNextShardIterator()).andReturn(null).anyTimes();
    expect(getRecordsResult1.getNextShardIterator()).andReturn(null).anyTimes();

    replayAll();

    Set<StreamPartition<String>> partitions = ImmutableSet.of(
        StreamPartition.of(stream, shardId0),
        StreamPartition.of(stream, shardId1)
    );

    recordSupplier = new KinesisRecordSupplier(
        kinesis,
        recordsPerFetch,
        0,
        2,
        true,
        100,
        5000,
        5000,
        60000,
        100
    );

    recordSupplier.assign(partitions);
    recordSupplier.seekToEarliest(partitions);
    recordSupplier.start();

    for (int i = 0; i < 10 && recordSupplier.bufferSize() < 12; i++) {
      Thread.sleep(100);
    }

    List<OrderedPartitionableRecord<String, String>> polledRecords = cleanRecords(recordSupplier.poll(
        poll_timeout_millis));

    verifyAll();

    Assert.assertEquals(partitions, recordSupplier.getAssignment());
    Assert.assertTrue(polledRecords.containsAll(allRecords));
  }

  /**
   * Returns an array with the content between the position and limit of "buffer". This may be the buffer's backing
   * array itself. Does not modify position or limit of the buffer.
   */
  private static byte[] toByteArray(final ByteBuffer buffer)
  {
    if (buffer.hasArray()
        && buffer.arrayOffset() == 0
        && buffer.position() == 0
        && buffer.array().length == buffer.limit()) {
      return buffer.array();
    } else {
      final byte[] retVal = new byte[buffer.remaining()];
      buffer.duplicate().get(retVal);
      return retVal;
    }
  }
}


text:
// Template Source: BaseEntityRequest.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All Rights Reserved.  Licensed under the MIT License.  See License in the project root for license information.
// ------------------------------------------------------------------------------

package com.microsoft.graph.requests;

import com.microsoft.graph.http.IRequestBuilder;
import com.microsoft.graph.core.ClientException;
import com.microsoft.graph.models.PolicyRoot;
import java.util.Arrays;
import java.util.EnumSet;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;
import com.microsoft.graph.core.IBaseClient;
import com.microsoft.graph.http.BaseRequest;
import com.microsoft.graph.http.HttpMethod;

// **NOTE** This file was generated by a tool and any changes will be overwritten.

/**
 * The class for the Policy Root Request.
 */
public class PolicyRootRequest extends BaseRequest<PolicyRoot> {

    /**
     * The request for the PolicyRoot
     *
     * @param requestUrl     the request URL
     * @param client         the service client
     * @param requestOptions the options for this request
     */
    public PolicyRootRequest(@Nonnull final String requestUrl, @Nonnull final IBaseClient<?> client, @Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) {
        super(requestUrl, client, requestOptions, PolicyRoot.class);
    }

    /**
     * Gets the PolicyRoot from the service
     *
     * @return a future with the result
     */
    @Nonnull
    public java.util.concurrent.CompletableFuture<PolicyRoot> getAsync() {
        return sendAsync(HttpMethod.GET, null);
    }

    /**
     * Gets the PolicyRoot from the service
     *
     * @return the PolicyRoot from the request
     * @throws ClientException this exception occurs if the request was unable to complete for any reason
     */
    @Nullable
    public PolicyRoot get() throws ClientException {
       return send(HttpMethod.GET, null);
    }

    /**
     * Delete this item from the service
     *
     * @return a future with the deletion result
     */
    @Nonnull
    public java.util.concurrent.CompletableFuture<PolicyRoot> deleteAsync() {
        return sendAsync(HttpMethod.DELETE, null);
    }

    /**
     * Delete this item from the service
     * @return the resulting response if the service returns anything on deletion
     *
     * @throws ClientException if there was an exception during the delete operation
     */
    @Nullable
    public PolicyRoot delete() throws ClientException {
        return send(HttpMethod.DELETE, null);
    }

    /**
     * Patches this PolicyRoot with a source
     *
     * @param sourcePolicyRoot the source object with updates
     * @return a future with the result
     */
    @Nonnull
    public java.util.concurrent.CompletableFuture<PolicyRoot> patchAsync(@Nonnull final PolicyRoot sourcePolicyRoot) {
        return sendAsync(HttpMethod.PATCH, sourcePolicyRoot);
    }

    /**
     * Patches this PolicyRoot with a source
     *
     * @param sourcePolicyRoot the source object with updates
     * @return the updated PolicyRoot
     * @throws ClientException this exception occurs if the request was unable to complete for any reason
     */
    @Nullable
    public PolicyRoot patch(@Nonnull final PolicyRoot sourcePolicyRoot) throws ClientException {
        return send(HttpMethod.PATCH, sourcePolicyRoot);
    }

    /**
     * Creates a PolicyRoot with a new object
     *
     * @param newPolicyRoot the new object to create
     * @return a future with the result
     */
    @Nonnull
    public java.util.concurrent.CompletableFuture<PolicyRoot> postAsync(@Nonnull final PolicyRoot newPolicyRoot) {
        return sendAsync(HttpMethod.POST, newPolicyRoot);
    }

    /**
     * Creates a PolicyRoot with a new object
     *
     * @param newPolicyRoot the new object to create
     * @return the created PolicyRoot
     * @throws ClientException this exception occurs if the request was unable to complete for any reason
     */
    @Nullable
    public PolicyRoot post(@Nonnull final PolicyRoot newPolicyRoot) throws ClientException {
        return send(HttpMethod.POST, newPolicyRoot);
    }

    /**
     * Creates a PolicyRoot with a new object
     *
     * @param newPolicyRoot the object to create/update
     * @return a future with the result
     */
    @Nonnull
    public java.util.concurrent.CompletableFuture<PolicyRoot> putAsync(@Nonnull final PolicyRoot newPolicyRoot) {
        return sendAsync(HttpMethod.PUT, newPolicyRoot);
    }

    /**
     * Creates a PolicyRoot with a new object
     *
     * @param newPolicyRoot the object to create/update
     * @return the created PolicyRoot
     * @throws ClientException this exception occurs if the request was unable to complete for any reason
     */
    @Nullable
    public PolicyRoot put(@Nonnull final PolicyRoot newPolicyRoot) throws ClientException {
        return send(HttpMethod.PUT, newPolicyRoot);
    }

    /**
     * Sets the select clause for the request
     *
     * @param value the select clause
     * @return the updated request
     */
     @Nonnull
     public PolicyRootRequest select(@Nonnull final String value) {
         addSelectOption(value);
         return this;
     }

    /**
     * Sets the expand clause for the request
     *
     * @param value the expand clause
     * @return the updated request
     */
     @Nonnull
     public PolicyRootRequest expand(@Nonnull final String value) {
         addExpandOption(value);
         return this;
     }

}


text:
import unittest

import numpy as np
import torch
from examples.speech_recognition.data.collaters import Seq2SeqCollater

class TestSeq2SeqCollator(unittest.TestCase):
    def test_collate(self):

        eos_idx = 1
        pad_idx = 0
        collater = Seq2SeqCollater(
            feature_index=0, label_index=1, pad_index=pad_idx, eos_index=eos_idx
        )

        # 2 frames in the first sample and 3 frames in the second one
        frames1 = np.array([[7, 8], [9, 10]])
        frames2 = np.array([[1, 2], [3, 4], [5, 6]])
        target1 = np.array([4, 2, 3, eos_idx])
        target2 = np.array([3, 2, eos_idx])
        sample1 = {"id": 0, "data": [frames1, target1]}
        sample2 = {"id": 1, "data": [frames2, target2]}
        batch = collater.collate([sample1, sample2])

        # collate sort inputs by frame's length before creating the batch
        self.assertTensorEqual(batch["id"], torch.tensor([1, 0]))
        self.assertEqual(batch["ntokens"], 7)
        self.assertTensorEqual(
            batch["net_input"]["src_tokens"],
            torch.tensor(
                [[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10], [pad_idx, pad_idx]]]
            ),
        )
        self.assertTensorEqual(
            batch["net_input"]["prev_output_tokens"],
            torch.tensor([[eos_idx, 3, 2, pad_idx], [eos_idx, 4, 2, 3]]),
        )
        self.assertTensorEqual(batch["net_input"]["src_lengths"], torch.tensor([3, 2]))
        self.assertTensorEqual(
            batch["target"],
            torch.tensor([[3, 2, eos_idx, pad_idx], [4, 2, 3, eos_idx]]),
        )
        self.assertEqual(batch["nsentences"], 2)

    def assertTensorEqual(self, t1, t2):
        self.assertEqual(t1.size(), t2.size(), "size mismatch")
        self.assertEqual(t1.ne(t2).long().sum(), 0)

if __name__ == "__main__":
    unittest.main()


text:
var path = require('path');
var __path__ = path.join(__dirname, '../../src/js/components/RadioButton');

var GrommetTestUtils = require('../../src/utils/test/GrommetTestUtils');

describe('Grommet RadioButton', function() {
  it('loads a basic RadioButton', function() {
    var Component = GrommetTestUtils.getComponent(__path__, undefined, {
      id: 'radio-id',
      label: 'Test Label'
    });

    GrommetTestUtils.componentShouldExist(Component, 'radio-button');
    GrommetTestUtils.componentShouldExist(Component,
      'radio-button__label', 'Test Label');
  });

  it('loads a disabled RadioButton', function () {
    var Component = GrommetTestUtils.getComponent(__path__, undefined, {
      id: 'radio-id',
      label: 'Test Label',
      disabled: true
    });

    GrommetTestUtils.componentShouldExist(Component, 'radio-button');
    GrommetTestUtils.componentShouldExist(Component,
      'radio-button__label', 'Test Label');
    GrommetTestUtils.componentShouldExist(Component, 'radio-button--disabled');
  });

  it('loads a basic RadioButton with an additional class', function() {
    var Component = GrommetTestUtils.getComponent(__path__, undefined, {
      id: 'radio-id',
      label: 'Test Label',
      className: 'test'
    });

    GrommetTestUtils.componentShouldExist(Component, 'radio-button');
    GrommetTestUtils.componentShouldExist(Component, 'test');
    GrommetTestUtils.componentShouldExist(Component,
      'radio-button__label', 'Test Label');
  });

});


text:
package org.springframework.boot.test.autoconfigure.graphql;

import org.springframework.boot.test.context.SpringBootTestContextBootstrapper;
import org.springframework.core.annotation.MergedAnnotations;
import org.springframework.test.context.TestContextBootstrapper;

/**
 * {@link TestContextBootstrapper} for {@link GraphQlTest @GraphQlTest}.
 *
 * @author Brian Clozel
 */
class GraphQlTestContextBootstrapper extends SpringBootTestContextBootstrapper {

	@Override
	protected String[] getProperties(Class<?> testClass) {
		return MergedAnnotations.from(testClass, MergedAnnotations.SearchStrategy.INHERITED_ANNOTATIONS)
				.get(GraphQlTest.class).getValue("properties", String[].class).orElse(null);
	}

}


text:
import argparse
import logging
import os
import sys
import gzip
import re
from Bio import motifs
from Bio import SeqIO
from Bio.Seq import Seq

def parse_args():
    parser = argparse.ArgumentParser(description="Position Weight Matrices of sequence")

    parser.add_argument("-v", "--verbose", help='verbosely print information',
                        action="count", default=0)

    group = parser.add_mutually_exclusive_group()
    group.add_argument("--stdin", action="store_true",
                       help='read from stdin, one sequence per line')
    group.add_argument('-i', '--infile', type=str,
                       help='file name should like this: infile.[fasta|fa|fastq|fq][.gz]')

    args = parser.parse_args()
    if not ( args.stdin or args.infile ):
        print("option --stdin or -i should be given", file=sys.stderr)
        sys.exit(1)

    return args

def seq_iter(file):
    if file:
        found = re.search(r'(?i)(fasta|fa|fastq|fq)(.gz)?$', file)
        if not found:
            print("invalid file name suffix.\nfile name should like this: infile.[fasfa|fa|fastq|fq][.gz]", file=sys.stderr)
            sys.exit(1)
        seq_format, is_gz = found.groups()
        if seq_format == 'fa':
            seq_format = 'fasta'
        if seq_format == 'fq':
            seq_format = 'fastq'

        fh = gzip.open(file, 'rt') if is_gz else open(file, 'r')
        for record in SeqIO.parse(fh, seq_format):
            yield record.seq
        fh.close()
    else:
        for line in sys.stdin:
            yield Seq(line.strip())

if __name__ == '__main__':
    args = parse_args()
    seqs = seq_iter(args.infile)
    seqs2 = [seq for seq in seqs if not 'N' in seq]
    m = motifs.create(seqs2)
    print(m.pwm)
    # print(m.pssm)
    # m.weblogo("motif.png")


text: from pyface.grid.grid_cell_renderer import *


text:
define(['mn',
    'text!templates/trading/productItem.html'
], function(Mn, template) {
    var ProductItemView = Mn.ItemView.extend({
        tagName: "tr",
        className: "item",
        events: {
            "click td": "loadModal",
            "click .photoManager": "loadPhotoManager",
            "click .quotingList": "loadQuotingList"
        },
        loadModal: function() {
            App.modal.show("views/trading/itemDetail", {
                title: this.model.get("Name"),
                model: this.model
            })
        },
        loadQuotingList: function(e) {
            e.preventDefault();
            e.stopPropagation();
            App.modal.show('views/trading/quotingList', {
                title: "报价记录",
                model: this.model
            })
        },
        loadPhotoManager: function(e) {
            e.preventDefault();
            e.stopPropagation();
            App.modal.show('views/photoView', {
                title: "照片管理",
                model: this.model
            })
        },
        onRender: function(option) {
            var model = option.model;
            if (model.get("DateVoid")) {
                this.$el.hide()
            } else {
                this.$el.show()
            }
        },
        template: function(model) {
            return _.template(template, {
                model: model
            })
        },
    })

    //usually returning the object you created...
    return ProductItemView;
});


text:
#include <vector>
using std::vector;

#include <iterator>
using std::inserter;

#include <iostream>
using std::cin; using std::cout; using std::endl;

#include <algorithm>
using std::for_each; using std::transform;

int main() {
	vector<int> vi;
	int i;
	while (cin >> i)
		vi.push_back(i);
	// pass a lambda to for_each to print each element in vi
	for_each(vi.begin(), vi.end(), [](int i) { cout << i << " "; });
	cout << endl;

	vector<int> orig = vi; // save original data in vi

	// replace negative values by their absolute value
	transform(vi.begin(), vi.end(), vi.begin(),
	          [](int i) { return i < 0 ? -i : i; });
	// print the elements now in vi
	for_each(vi.begin(), vi.end(), [](int i) { cout << i << " "; });
	cout << endl;

	vi = orig;  // start afresh
	// use a lambda with a specified return type to transform vi
	transform(vi.begin(), vi.end(), vi.begin(),
	          [](int i) -> int
	          { if (i < 0) return -i; else return i; });
	// print the elements now in vi
	for_each(vi.begin(), vi.end(), [](int i) { cout << i << " "; });
	cout << endl;

    return 0;
}


text:
package com.google.spanner.admin.instance.v1;

import com.google.api.resourcenames.ResourceNameType;

// AUTO-GENERATED DOCUMENTATION AND CLASS
@javax.annotation.Generated("by GAPIC protoc plugin")
public class InstanceNameType implements ResourceNameType {

  private static InstanceNameType instance = new InstanceNameType();

  private InstanceNameType() {}

  public static InstanceNameType instance() {
    return instance;
  }
}


text:
Pattern: Malformed operator spacing

Issue: -

## Description

Verifies that operators have valid spacing surrounding them.

## Configuration

Sometimes long statements are broken over multiple lines to work within a maximum line length, but this rule will generate an error for these cases by default. Setting the `ignoreNewlines` property to `true` will allow newline characters before or after an operator, and any required padding for alignment.

```xml
<rule ref="Squiz.WhiteSpace.OperatorSpacing">
    <properties>
        <property name="ignoreNewlines" value="true" />
    </properties>
</rule>
```

## Further Reading

* [PHP_CodeSniffer - Squiz.WhiteSpace.OperatorSpacing](https://github.com/squizlabs/PHP_CodeSniffer/blob/master/src/Standards/Squiz/Sniffs/WhiteSpace/OperatorSpacingSniff.php)


text:
require 'dijkstra/edge'

class Dijkstra::EdgeBuilder
  def self.build(edge_as_string)
    edge_as_array = edge_as_string[1..-2].split(',')
    Dijkstra::Edge.new(edge_as_array[0], edge_as_array[1], edge_as_array[2].to_i)
  end
end