text:
require 'spec_helper'

describe 'freeradius::module::ldap' do
  include_context 'redhat_common_dependencies'

  let(:title) { 'test' }

  let(:params) do
    {
      identity: 'cn=root,dc=example,dc=com',
      password: 'test password',
      basedn: 'dc=example,dc=com',
      server: ['localhost'],
    }
  end

  let(:facts) do
    {
      freeradius_version: '3.0.21',
    }
  end

  let(:node_params) do
    {
      'freeradius::fr_3_1' => false,
    }
  end

  it do
    is_expected.to contain_file('/etc/raddb/mods-available/test')
      .with_content(%r{^ldap test \{\n})
      .with_content(%r{^\s+server = 'localhost'\n})
      .with_content(%r{^\s+identity = 'cn=root,dc=example,dc=com'\n})
      .with_content(%r{^\s+password = 'test password'\n})
      .with_content(%r{^\s+base_dn = 'dc=example,dc=com'\n})
      .without_content(%r{^\s+connect_timeout = .*})
      .with_ensure('present')
      .with_group('radiusd')
      .with_mode('0640')
      .with_owner('root')
      .that_notifies('Service[radiusd]')
      .that_requires('Package[freeradius]')
      .that_requires('Group[radiusd]')
  end

  it do
    is_expected.to contain_file('/etc/raddb/mods-enabled/test')
      .with_ensure('link')
      .with_target('../mods-available/test')
  end

  context 'when freeradius::fr_3_1 is true' do
    let(:facts) do
      super().merge(
        'freeradius_version' => '3.1.1',
      )
    end

    let(:node_params) do
      {
        'freeradius::fr_3_1' => true,
      }
    end

    it do
      is_expected.to contain_file('/etc/raddb/mods-available/test')
        .with_content(%r{^\s+connect_timeout = 3.0})
        .with_content(%r{^\s+use_referral_credentials = no})
        .without_content(%r{^\s+session_tracking = .*})
    end

    context 'with connect_timeout, session_tracking, and use_referral_credentials specified' do
      let(:params) do
        super().merge(
          connect_timeout: 5.0,
          session_tracking: 'yes',
          use_referral_credentials: 'yes',
        )
      end

      it do
        is_expected.to contain_file('/etc/raddb/mods-available/test')
          .with_content(%r{^\s+connect_timeout = 5.0})
          .with_content(%r{^\s+use_referral_credentials = yes})
          .with_content(%r{^\s+session_tracking = yes})
      end

      # it do
      #   is_expected.to create_notify('warning_test').with_message(%r{^The `connect_timeout` parameter requires FreeRADIUS 3.1.x})
      # end

      # it do
      #   is_expected.to create_notify('warning_test').with_message(%r{^The `use_referral_credentials` parameter requires FreeRADIUS 3.1.x})
      # end

      # it do
      #   is_expected.to create_notify('warning_test').with_message(%r{^The `session_tracking` parameter requires FreeRADIUS 3.1.x})
      # end
    end
  end

  # context 'with connect_timeout specified' do
  #   let(:params) do
  #     super().merge(
  #       connect_timeout: 5.0,
  #     )
  #   end

  #   it do
  #     is_expected.to compile.and_raise_error(%r{^The \`connect_timeout` parameter requires FreeRADIUS 3\.1\.x})
  #   end
  # end

  # context 'with session_tracking specified' do
  #   let(:params) do
  #     super().merge(
  #       session_tracking: 'yes',
  #     )
  #   end

  #   it do
  #     is_expected.to compile.and_raise_error(%r{^The `session_tracking` parameter requires FreeRADIUS 3.1.x})
  #   end
  # end

  # context 'with use_referral_credentials specified' do
  #   let(:params) do
  #     super().merge(
  #       use_referral_credentials: 'yes',
  #     )
  #   end

  #   it do
  #     is_expected.to compile.and_raise_error(%r{^The `use_referral_credentials` parameter requires FreeRADIUS 3.1.x})
  #   end
  # end

  context 'with password containing a newline' do
    let(:params) do
      super().merge(
        password: "foo\nbar",
      )
    end

    it do
      is_expected.to compile.and_raise_error(%r{parameter 'password' expects a match for Freeradius::Password})
    end
  end
end


text:
//
// @author raver119@gmail.com
//

#ifndef DEV_TESTS_EXTRAARGUMENTS_H
#define DEV_TESTS_EXTRAARGUMENTS_H

#include <dll.h>
#include <initializer_list>
#include <vector>
#include <array/DataType.h>
#include <pointercast.h>
#include <stdlib.h>

namespace nd4j {
    class ND4J_EXPORT ExtraArguments {
    private:
        std::vector<double> _fpArgs;
        std::vector<Nd4jLong> _intArgs;

        std::vector<Nd4jPointer> _pointers;

        template <typename T>
        void convertAndCopy(Nd4jPointer pointer, Nd4jLong offset);

        void* allocate(size_t length, size_t elementSize);
    public:
        explicit ExtraArguments(std::initializer_list<double> arguments);
        explicit ExtraArguments(std::initializer_list<Nd4jLong> arguments);

        explicit ExtraArguments(const std::vector<double> &arguments);
        explicit ExtraArguments(const std::vector<int> &arguments);
        explicit ExtraArguments(const std::vector<Nd4jLong> &arguments);

        explicit ExtraArguments();
        ~ExtraArguments();

        template <typename T>
        void* argumentsAsT(Nd4jLong offset = 0);

        void* argumentsAsT(nd4j::DataType dataType, Nd4jLong offset = 0);

        size_t length();
    };
}

#endif //DEV_TESTS_EXTRAARGUMENTS_H

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>

<!--L
   Copyright Ekagra Software Technologies Ltd.
   Copyright SAIC, SAIC-Frederick

   Distributed under the OSI-approved BSD 3-Clause License.
   See http://ncip.github.com/common-security-module/LICENSE.txt for details.
L-->

<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>

	<!-- Properties for the session factory -->

	<property name="connection.driver_class">org.gjt.mm.mysql.Driver</property>
	<property name="connection.url">jdbc:mysql://localhost:3306/csmapitest</property>
	<property name="connection.username">root</property>
	<property name="connection.password">IpgSanju10</property>
	<property name="dialect">org.hibernate.dialect.MySQLDialect</property>

	<!--
	<property name="connection.driver_class">
		oracle.jdbc.driver.OracleDriver
	</property>
	<property name="connection.url">
		jdbc:oracle:thin:@cbiodb30.nci.nih.gov:1521:CBTEST
	</property>

		<property name="connection.username">ncisecurity</property>
		<property name="connection.password">ncisecurity</property>
		<property name="dialect">org.hibernate.dialect.OracleDialect</property>
	-->
	<!--<property name="connection.provider_class">
		org.hibernate.connection.C3P0ConnectionProvider
	</property>
	<property name="c3p0.max_size">10</property>
	<property name="c3p0.min_size">2</property>
	<property name="c3p0.timeout">5000</property>
	<property name="c3p0.max_statements">100</property>
	<property name="c3p0.idle_test_period">3000</property>
	<property name="c3p0.acquire_increment">2</property>
	<property name="c3p0.validate">false</property>-->
	<property name="hibernate.show_sql">false</property>

	<property name="max_fetch_depth">1</property>
	<property name="cglib.use_reflection_optimizer">false</property>
	<property name="jdbc.batch_versioned_data">true</property>
	<property name="jdbc.use_streams_for_binary">true</property>
	<property name="jdbc.use_streams_for_binary">true</property>
	<property name="cache.use_query_cache">false</property>
	<property name="hibernate.cache.use_second_level_cache">false</property>
	<property name="cache.provider_class">
		org.hibernate.cache.EhCacheProvider
	</property>

	<!-- Mapped Resources -->

	<mapping class="test.gov.nih.nci.security.instancelevel.domainobjects.Card" />
	<mapping class="test.gov.nih.nci.security.instancelevel.domainobjects.Deck" />
	<mapping class="test.gov.nih.nci.security.instancelevel.domainobjects.Suit" />
</session-factory>
</hibernate-configuration>


text:
static NSString * const CLOUD_DATABASE_ID     = @"cloudDatabaseID";

@interface PCCloudUser : NSObject

+ (void)registerUserWithUserName: (NSString *)username
                        Password: (NSString *)password
                 andOtherOptions: (NSDictionary *)otherOptions;

+ (AVUser *)validUserWithUserName: (NSString *)username
                  andPassword: (NSString *)password;

+ (void)saveCloudDatabaseID: (NSString *)cloudDatabaseID;
+ (NSString *)cloudDatabaseID;
@end


text:
$script:dscModuleName = 'NetworkingDsc'
$script:dscResourceName = 'DSC_NetAdapterName'

try
{
    Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop'
}
catch [System.IO.FileNotFoundException]
{
    throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.'
}

$script:testEnvironment = Initialize-TestEnvironment `
    -DSCModuleName $script:dscModuleName `
    -DSCResourceName $script:dscResourceName `
    -ResourceType 'Mof' `
    -TestType 'Integration'

Import-Module -Name (Join-Path -Path $PSScriptRoot -ChildPath '..\TestHelpers\CommonTestHelper.psm1')

# Begin Testing
try
{
    Describe 'NetAdapterName Integration Tests' {
        Describe "$($script:dscResourceName)_Integration using all parameters" {
            $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dscResourceName)_all.config.ps1"
            . $configFile -Verbose -ErrorAction Stop

            BeforeAll {
                New-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA'
                $adapter = Get-NetAdapter -Name 'NetworkingDscLBA'
            }

            AfterAll {
                # Remove Loopback Adapter
                Remove-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA'
                Remove-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBANew'
            }

            It 'Should compile and apply the MOF without throwing' {
                {
                    # This is to pass to the Config
                    $configData = @{
                        AllNodes = @(
                            @{
                                NodeName             = 'localhost'
                                NewName              = 'NetworkingDscLBANew'
                                Name                 = $adapter.Name
                                PhysicalMediaType    = $adapter.PhysicalMediaType
                                Status               = $adapter.Status
                                MacAddress           = $adapter.MacAddress
                                InterfaceDescription = $adapter.InterfaceDescription
                                InterfaceIndex       = $adapter.InterfaceIndex
                                InterfaceGuid        = $adapter.InterfaceGuid
                            }
                        )
                    }

                    & "$($script:dscResourceName)_Config_All" `
                        -OutputPath $TestDrive `
                        -ConfigurationData $configData

                    Start-DscConfiguration `
                        -Path $TestDrive `
                        -ComputerName localhost `
                        -Wait `
                        -Verbose `
                        -Force `
                        -ErrorAction Stop
                } | Should -Not -Throw
            }

            It 'Should reapply the MOF without throwing' {
                {
                    Start-DscConfiguration `
                        -Path $TestDrive `
                        -ComputerName localhost `
                        -Wait `
                        -Verbose `
                        -Force `
                        -ErrorAction Stop
                } | Should -Not -Throw
            }

            It 'Should be able to call Get-DscConfiguration without throwing' {
                {
                    Get-DscConfiguration -Verbose -ErrorAction Stop
                } | Should -Not -Throw
            }

            It 'Should have set the resource and all the parameters should match' {
                $current = Get-DscConfiguration | Where-Object -FilterScript {
                    $_.ConfigurationName -eq "$($script:dscResourceName)_Config_All"
                }
                $current.Name | Should -Be 'NetworkingDscLBANew'
            }
        }

        Describe "$($script:dscResourceName)_Integration using name parameter only" {
            $configFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:dscResourceName)_nameonly.config.ps1"
            . $configFile -Verbose -ErrorAction Stop

            BeforeAll {
                New-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA'
                $adapter = Get-NetAdapter -Name 'NetworkingDscLBA'
            }

            AfterAll {
                # Remove Loopback Adapter
                Remove-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBA'
                Remove-IntegrationLoopbackAdapter -AdapterName 'NetworkingDscLBANew'
            }

            It 'Should compile and apply the MOF without throwing' {
                {
                    # This is to pass to the Config
                    $configData = @{
                        AllNodes = @(
                            @{
                                NodeName = 'localhost'
                                NewName  = 'NetworkingDscLBANew'
                                Name     = $adapter.Name
                            }
                        )
                    }

                    & "$($script:dscResourceName)_Config_NameOnly" `
                        -OutputPath $TestDrive `
                        -ConfigurationData $configData

                    Start-DscConfiguration `
                        -Path $TestDrive `
                        -ComputerName localhost `
                        -Wait `
                        -Verbose `
                        -Force `
                        -ErrorAction Stop
                } | Should -Not -Throw
            }

            It 'Should reapply the MOF without throwing' {
                {
                    Start-DscConfiguration `
                        -Path $TestDrive `
                        -ComputerName localhost `
                        -Wait `
                        -Verbose `
                        -Force `
                        -ErrorAction Stop
                } | Should -Not -Throw
            }

            It 'Should be able to call Get-DscConfiguration without throwing' {
                {
                    Get-DscConfiguration -Verbose -ErrorAction Stop
                } | Should -Not -Throw
            }

            It 'Should have set the resource and all the parameters should match' {
                $current = Get-DscConfiguration | Where-Object -FilterScript {
                    $_.ConfigurationName -eq "$($script:dscResourceName)_Config_NameOnly"
                }
                $current.Name | Should -Be 'NetworkingDscLBANew'
            }
        }
    }
}
finally
{
    Restore-TestEnvironment -TestEnvironment $script:testEnvironment
}


text:
function [result meegstruct]=checkmeeg(meegstruct, option)
% Function for checking the internal struct of meeg objects
% FORMAT [result meegstruct]=checkmeeg(meegstruct, option)
% result - 1 - OK, 0- failed
% meegstruct - the struct to check (is returned modified if necessary)
% option - 'basic' (default) - just check the essential fields
%          'sensfid' - also checks sensor and fiducial definitions
% _______________________________________________________________________
% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging

% Vladimir Litvak
% $Id: checkmeeg.m 4437 2011-08-23 13:09:24Z vladimir $

if nargin==1
    option = 'basic';
end

result=0;

if ~isfield(meegstruct, 'Nsamples')
    disp('checkmeeg: number of samples per trial is missing');
    return;
else
    Nsamples = meegstruct.Nsamples;
end

if ~isfield(meegstruct, 'Fsample') && (Nsamples~=0)
    disp('checkmeeg: sampling rate is missing');
    return;
elseif (Nsamples==0)  % This is to enable creation of empty meeg objects
    meegstruct.Fsample = 0;
end

if ~isfield(meegstruct, 'timeOnset')
    meegstruct.timeOnset = 0;
elseif isempty(meegstruct.timeOnset)
    if meegstruct.Fsample ~= 0
        meegstruct.timeOnset = 1/meegstruct.Fsample;
    else
        meegstruct.timeOnset = 0; % This is to enable creation of empty meeg objects
    end
end

if ~isfield(meegstruct, 'trials') && (Nsamples~=0)
    disp('checkmeeg: no trials description');
    return;
elseif (Nsamples==0)  % This is to enable creation of empty meeg objects
    meegstruct.trials = struct([]);
else
    Ntrials = length(meegstruct.trials);
    if ~isfield(meegstruct.trials, 'label')
        disp('checkmeeg: no trial label, assigning default');
        [meegstruct.trials.label] = deal('Undefined');
    elseif any(cellfun('isempty', {meegstruct.trials(:).label}))
        disp('checkmeeg: some trial labels empty, assigning default');
        [meegstruct.trials(cellfun('isempty', {meegstruct.trials(:).label})).label] = deal('Undefined');
    end
    if ~isfield(meegstruct.trials, 'bad')
        [meegstruct.trials.bad] = deal(0);
    end
    if ~isfield(meegstruct.trials, 'events')
        [meegstruct.trials.events] = deal([]);
    end

    for k = 1:Ntrials

        label = meegstruct.trials(k).label;

        if iscell(label) && numel(label) == 1
            label = label{1};
        end

        if isnumeric(label)
            label = num2str(label);
        end

        if isa(label, 'char')
           meegstruct.trials(k).label = label;
        else
           meegstruct.trials(k).label = 'Unknown';
           disp('checkmeeg: some trial labels were not strings, changing back to ''Unknown''');
        end

        if  length(meegstruct.trials(k).bad)>1 || ~ismember(meegstruct.trials(k).bad, [0, 1])
            disp(['checkmeeg: illegal value for bad flag in trial ' num2str(k) ', setting to zero.']);
            meegstruct.trials(k).bad = 0;
        end

        event = meegstruct.trials(k).events;

        if ~isempty(event) && ~(numel(event) == 1 && isequal(event.type, 'no events'))
            % make sure that all required elements are present
            if ~isfield(event, 'type'),     error('type field not defined for each event');  end
            if ~isfield(event, 'time'),     error('time field not defined for each event');  end
            if ~isfield(event, 'value'),    [event.value]    = deal([]);                     end
            if ~isfield(event, 'offset'),   [event.offset]   = deal(0);                      end
            if ~isfield(event, 'duration'), [event.duration] = deal([]);                     end

            % make sure that all numeric values are double
            for i=1:length(event)
                if isnumeric(event(i).value)
                    event(i).value = double(event(i).value);
                end
                event(i).time      = double(event(i).time);
                event(i).offset    = double(event(i).offset);
                event(i).duration  = double(event(i).duration);
            end

            if ~isempty(event)
                % sort the events on the sample on which they occur
                % this has the side effect that events without time are discarded
                [dum, indx] = sort([event.time]);
                event = event(indx);
            end
        else
            event = [];
        end

        meegstruct.trials(k).events = event;
    end

    if ~isfield(meegstruct.trials, 'onset')
        [meegstruct.trials.onset] = deal(0);
    else
        [meegstruct.trials(find(cellfun('isempty', {meegstruct.trials.onset}))).onset] = deal(0);
    end
    if ~isfield(meegstruct.trials, 'repl')
        [meegstruct.trials.repl] = deal(1);
    end
end

if ~isfield(meegstruct, 'channels') && (Nsamples~=0)
    disp('checkmeeg: no channels description');
    return;
elseif (Nsamples==0)  % This is to enable creation of empty meeg objects
    meegstruct.channels = struct([]);
else
    Nchannels = length(meegstruct.channels);
    if ~isfield(meegstruct.channels, 'label')
        disp('checkmeeg: no channel label, assigning default');
        for i = 1:Nchannels
            meegstruct.channels(i).label = ['Ch' num2str(i)];
        end
    end
    if ~isfield(meegstruct.channels, 'bad')
        [meegstruct.channels.bad] = deal(0);
    else
        [meegstruct.channels(find(cellfun('isempty', {meegstruct.channels.bad}))).bad] = deal(0);
    end

    for i = 1:Nchannels
        meegstruct.channels(i).bad = double(~~meegstruct.channels(i).bad);
    end

    if ~isfield(meegstruct.channels, 'type')
        disp('checkmeeg: no channel type, assigning default');
        [meegstruct.channels.type] = deal('Other');
    end

    % This is for backward compatibility with early SPM8b. Can be removed
    % after a while.
    ind = strmatch('MEGREF', {meegstruct.channels.type}, 'exact');
    [meegstruct.channels(ind).type] = deal('REF');

    if ~isfield(meegstruct.channels, 'X_plot2D')
        [meegstruct.channels.X_plot2D] = deal([]);
        [meegstruct.channels.Y_plot2D] = deal([]);
    end
    if ~isfield(meegstruct.channels, 'units')
        disp('checkmeeg: no units, assigning default');
        [meegstruct.channels.units] = deal('unknown');
    else
        [meegstruct.channels(find(cellfun('isempty', {meegstruct.channels.units}))).units] = deal('unknown');
    end
end

try
    meegstruct.transform.ID;
catch
    meegstruct.transform.ID = 'time';
    disp('checkmeeg: transform type missing, assigning default');
end

if strncmp(meegstruct.transform.ID, 'TF', 2) % TF and TFphase
    try
        Nfrequencies = length(meegstruct.transform.frequencies);
    catch
        error('Information about frequencies missing');
    end
end

if isfield(meegstruct, 'path')
    filepath = meegstruct.path;
else
    filepath = pwd;
end

if ~isfield(meegstruct, 'data') && (Nsamples~=0)
    disp('checkmeeg: no data field');
    return;
elseif (Nsamples==0)  % This is to enable creation of empty meeg objects
    meegstruct.data = struct([]);
else
    if ~isfield(meegstruct.data, 'fnamedat')
        disp('checkmeeg: data file name missing');
        return;
    else
        fname = meegstruct.data.fnamedat;
        if ~ispc, fname = strrep(fname,'\',filesep); end
        [junk, fnamedat, ext] = fileparts(fname);
        if isempty(ext)
            meegstruct.data.fnamedat = [fnamedat '.dat'];
        else
            meegstruct.data.fnamedat = [fnamedat ext];
        end
    end
    if ~isfield(meegstruct.data, 'datatype')
        disp('checkmeeg: data type missing, assigning default');
        meegstruct.data.datatype = 'float32';
    end

    if ~isfield(meegstruct.data, 'y')
        meegstruct.data.y=[];
    end

    if isa(meegstruct.data.y, 'file_array')
        % catching up (unlikely case) where filearray.fname is
        % different from data.fnamedat -> set data.fnamedat
        fname = meegstruct.data.y.fname;
        if ~ispc, fname = strrep(fname,'\',filesep); end
        [junk, yfname, yext] = fileparts(fname);

        fnamedat = meegstruct.data.fnamedat;
        if ~ispc, fnamedat = strrep(fnamedat,'\',filesep); end
        [junk, dfname, dext] = fileparts(fnamedat);
        if ~strcmp([yfname yext],[dfname dext])
            meegstruct.data.fnamedat = [yfname yext];
        end

        meegstruct.data.y.fname = fullfile(filepath, [yfname yext]);

        % save original file_array scale & offset, just in case
        sav_sc = meegstruct.data.y.scl_slope;
        sav_os = meegstruct.data.y.offset;
        try
            % Try reading data, i.e. check if it's a "good" filearray
            meegstruct.data.y(1, 1, 1);
        catch
            meegstruct.data.y = [];
        end
    end

    if isa(meegstruct.data.y, 'file_array')
        fn = meegstruct.data.y.fname;
        if ~ispc, fn = strrep(fn,'\',filesep); end
    else
        fn = '';
    end
    if ~isa(meegstruct.data.y, 'file_array') ...
            || isempty(fileparts(fn)) ...
            || ~exist(meegstruct.data.y.fname, 'file')
        switch(meegstruct.transform.ID)
            case 'time'
                meegstruct.data.y = file_array(fullfile(filepath, meegstruct.data.fnamedat), ...
                    [Nchannels Nsamples Ntrials], meegstruct.data.datatype);

            case {'TF', 'TFphase'}
                meegstruct.data.y = file_array(fullfile(filepath, meegstruct.data.fnamedat), ...
                    [Nchannels Nfrequencies Nsamples Ntrials], meegstruct.data.datatype);
                if Ntrials>1
                    expected_size = [Nchannels Nfrequencies Nsamples Ntrials];
                else
                    expected_size = [Nchannels Nfrequencies Nsamples];
                end

            otherwise
                error('Unknown transform type');
        end
        % and restore original file_array scale, if available (exist) & useful (~=[])
        if exist('sav_sc','var') && ~isempty(sav_sc) && ...
                   size(meegstruct.data.y, 1) == length(sav_sc)
            meegstruct.data.y.scl_slope = sav_sc;
        end
        % and restore original file_array offset, if available (exist) & useful (~=0)
        if exist('sav_os','var') && sav_os
            meegstruct.data.y.offset = sav_os;
        end

    end

    switch(meegstruct.transform.ID)
        case 'time'
            if Ntrials>1
                expected_size = [Nchannels Nsamples Ntrials];
            else
                expected_size = [Nchannels Nsamples];
            end
        case {'TF', 'TFphase'}
            if Ntrials>1
                expected_size = [Nchannels Nfrequencies Nsamples Ntrials];
            else
                expected_size = [Nchannels Nfrequencies Nsamples];
            end

        otherwise
            error('Unknown transform type');
    end

    if any(size(meegstruct.data.y) ~= expected_size)
        disp('checkmeeg: data size does not match the header');
        return;
    end
end

if ~isfield(meegstruct, 'type') ||...
        (strcmp(meegstruct.type, 'continuous') && Ntrials>1) ||...
        (strcmp(meegstruct.type, 'evoked') && (numel(unique({meegstruct.trials.label})) ~= Ntrials)) ||...
        (strcmp(meegstruct.type, 'continuous') && strncmp(meegstruct.transform.ID, 'TF', 2)) ||...
        strcmp(meegstruct.type, 'grandmean')
    disp('checkmeeg: data type is missing or incorrect, assigning default');
    % rule of thumb - 10 sec
    if Nsamples == 0
        meegstruct.type = 'continuous';
    elseif Ntrials==1 && (Nsamples/meegstruct.Fsample) > 10 &&...
            ~strncmp(meegstruct.transform.ID, 'TF', 2)
        meegstruct.type = 'continuous';
    elseif numel(unique({meegstruct.trials.label})) == Ntrials
        meegstruct.type = 'evoked';
    else
        meegstruct.type = 'single';
    end
end

try
    fname = meegstruct.data.y.fname;
    if ~ispc, fname = strrep(fname,'\',filesep); end
    [pdat, fdat] = fileparts(fname);
catch
    fdat = 'spm8';
end

if ~isfield(meegstruct, 'fname')
    meegstruct.fname = [fdat '.mat'];
else
    fname = meegstruct.fname;
    if ~ispc, fname = strrep(fname,'\',filesep); end
    [p, f] = fileparts(fname);
    if isempty(f)
        f = fdat;
    end
    meegstruct.fname = [f '.mat'];
end

if ~isfield(meegstruct, 'path')
    try
        fname = meegstruct.data.y.fname;
        if ~ispc, fname = strrep(fname,'\',filesep); end
        meegstruct.path = fileparts(fname);
    catch
        meegstruct.path = pwd;
    end
end

if ~isfield(meegstruct, 'sensors')
    meegstruct.sensors = struct([]);
else
    if isfield(meegstruct.sensors, 'eeg')
        if isempty(meegstruct.sensors.eeg) || isempty(meegstruct.sensors.eeg.pnt)
            meegstruct.sensors = rmfield(meegstruct.sensors, 'eeg');
        end
    end
    if isfield(meegstruct.sensors, 'meg')
        if isempty(meegstruct.sensors.meg) || isempty(meegstruct.sensors.meg.pnt)
            meegstruct.sensors = rmfield(meegstruct.sensors, 'meg');
        end
    end
end

if ~isfield(meegstruct, 'fiducials')
    meegstruct.fiducials = struct([]);
end

if ~isfield(meegstruct, 'artifacts')
    meegstruct.artifacts = struct([]);
end

if ~isfield(meegstruct, 'transform')
    meegstruct.transform = struct('ID', 'time');
end

if ~isfield(meegstruct, 'other')
    meegstruct.other = struct([]);
else
    if isfield(meegstruct.other, 'origchantypes')
        % This is for backward compatibility
        % Can be removed after a while
        if iscell(meegstruct.other.origchantypes)
            if numel(meegstruct.other.origchantypes) == Nchannels
                origchantypes = meegstruct.other.origchantypes;
                meegstruct.other.origchantypes = struct([]);
                meegstruct.other.origchantypes(1).type = origchantypes;
                meegstruct.other.origchantypes(1).label = {meegstruct.channels(:).label}';
            else
                meegstruct.other = rmfield(meegstruct.other, 'origchantypes');
            end
        end
    end
    if isfield(meegstruct.other, 'condlist') && ~isempty(meegstruct.other.condlist)
        % This a workaround for the absence of 'first' option in unique()
        % of Matlab 7.1 and last occurence being the default
        clist = meegstruct.other.condlist(end:-1:1);
        [junk, ind] = unique(clist);
        clist = clist(sort(ind));
        meegstruct.other.condlist = clist(end:-1:1);
    end
end

if ~isfield(meegstruct, 'history')
    meegstruct.history = struct([]);
end

if ~isfield(meegstruct, 'cache')
    meegstruct.cache = struct([]);
end

% This makes sure the order of the fields in the struct is right. This
% seems to matter to the class function.

fieldnames_order = {
    'type'
    'Nsamples'
    'Fsample'
    'timeOnset'
    'trials'
    'channels'
    'data'
    'fname'
    'path'
    'sensors'
    'fiducials'
    'artifacts'
    'transform'
    'other'
    'history'
    'cache'};

[sel1, sel2] = match_str(fieldnames_order, fieldnames(meegstruct));
tempcell = struct2cell(meegstruct);
meegstruct = cell2struct(tempcell(sel2), fieldnames_order, 1);

if strcmp(option, 'basic')
    result = 1;
    return;
end

chantypes = getset(meegstruct, 'channels', 'type');
eegind = strmatch('EEG', chantypes, 'exact');
megind = strmatch('MEG', chantypes);
lfpind = strmatch('LFP', chantypes, 'exact');

% Allow DCM on a pure LFP dataset
if strcmp(option, 'dcm') && isempty([eegind(:); megind(:)])...
        && ~isempty(lfpind) && ismember(meegstruct.transform.ID, {'time', 'TF'})
    result = 1;
    return;
end

if strcmp(option, 'sensfid') || strcmp(option, '3d') ||...
        (strcmp(option, 'dcm') && ~isempty([eegind(:); megind(:)]))

    if ~strcmp(meegstruct.transform.ID, 'time')
        disp('checkmeeg: incorrect data type for source reconstruction');
        return;
    end

    if isempty(meegstruct.sensors)
        disp('checkmeeg: no sensor positions are defined');
        return;
    end

    if ~isempty(eegind)
        if ~isfield(meegstruct.sensors, 'eeg') || isempty(meegstruct.sensors.eeg)
            disp('checkmeeg: EEG channel locations are not specified');
            return;
        else
            if ~isempty(setdiff({meegstruct.channels(eegind).label}, meegstruct.sensors.eeg.label))
                disp('checkmeeg: not all EEG channel locations are specified');
                return;
            end
        end
    end

    if ~isempty(megind)
        if ~isfield(meegstruct.sensors, 'meg') || isempty(meegstruct.sensors.meg)
            disp('checkmeeg: MEG channel locations are not specified');
            return;
        else
            if ~isempty(setdiff({meegstruct.channels(megind).label}, meegstruct.sensors.meg.label))
                disp('checkmeeg: not all MEG channel locations are specified');
                return;
            end
        end
    end

    if isempty(meegstruct.fiducials)
        disp('checkmeeg: no fiducials are defined');
        return;
    end

    if ~isfield(meegstruct.fiducials, 'pnt') || isempty(meegstruct.fiducials.pnt)
        if ~isempty(eegind)
            % Copy EEG sensors to fiducials.
            meegstruct.fiducials.pnt = meegstruct.sensors.eeg.pnt;
        else
            meegstruct.fiducials.pnt = sparse(0, 3);
        end
    end

    if ~isfield(meegstruct.fiducials, 'fid') || ...
            ~all(isfield(meegstruct.fiducials.fid, {'pnt', 'label'})) ||...
            (length(meegstruct.fiducials.fid.label) ~= size(meegstruct.fiducials.fid.pnt, 1)) || ...
            length(meegstruct.fiducials.fid.label) < 3
        disp('checkmeeg: at least 3 fiducials with labels are required');
        return
    end

    nzlbl = {'fidnz', 'nz', 'nas', 'nasion', 'spmnas'};
    lelbl = {'fidle', 'fidt9', 'lpa', 'lear', 'earl', 'le', 'l', 't9', 'spmlpa'};
    relbl = {'fidre', 'fidt10', 'rpa', 'rear', 'earr', 're', 'r', 't10', 'spmrpa'};

    [sel1, nzind] = match_str(nzlbl, lower(meegstruct.fiducials.fid.label));
    if isempty(nzind)
        disp('checkmeeg: could not find the nasion fiducial');
    else
        nzind = nzind(1);
    end

    [sel1, leind] = match_str(lelbl, lower(meegstruct.fiducials.fid.label));
    if isempty(leind)
        disp('checkmeeg: could not find the left fiducial');
    else
        leind = leind(1);
    end

    [sel1, reind] = match_str(relbl, lower(meegstruct.fiducials.fid.label));
    if isempty(reind)
        disp('checkmeeg: could not find the right fiducial');
    else
        reind = reind(1);
    end

    restind = setdiff(1:length(meegstruct.fiducials.fid.label), [nzind(:)', leind(:)', reind(:)']);

    meegstruct.fiducials.fid.label = meegstruct.fiducials.fid.label([nzind(:)', leind(:)', reind(:)', restind(:)']);
    meegstruct.fiducials.fid.pnt = meegstruct.fiducials.fid.pnt([nzind(:)', leind(:)', reind(:)', restind(:)'], :);

    result = 1;
end


text:
module Main (main) where

import Test.Tasty

import qualified AbstractFilePathSpec

main :: IO ()
main = defaultMain $ testGroup "All"
  AbstractFilePathSpec.tests


text:
/**
* Unit tests for the Orator Server
*
* @license     MIT
*
* @author      Steven Velozo <steven@velozo.com>
*/

var Chai = require("chai");
var Expect = Chai.expect;
var Assert = Chai.assert;

var libSuperTest = require('supertest');

var _MockSettings = (
{
	Product: 'MockOratorRequestLogging',
	APIServerPort: 8085,
	Profiling: (
		{
			// Tracelog is just log-based request timing encapsulation.
			TraceLog: true,
			RequestLog: true
		}),
		UncaughtExceptionHook: function(pRequest, pResponse, pRoute, pError) { console.log('Uncaught Exception Hook Triggered: '+pError); pResponse.send(pError); pResponse.end(); }
});

suite
(
	'Orator',
	function()
	{
		var _Orator;

		setup
		(
			function()
			{
				_Orator = require('../source/Orator.js').new(_MockSettings);
			}
		);

		suite
		(
			'Request Logging Server Start',
			function()
			{
				test
				(
					'simple routes should work',
					function(fDone)
					{
						_Orator.webServer.get (
							'/PINGOLo',
							function (pRequest, pResponse, fNext)
							{
								pResponse.send('Loggo');
								fNext();
							}
						);
						_Orator.webServer.get (
							'/PINataGOLo',
							async function (pRequest, pResponse)
							{
								return Promise.reject("Something absolutely dire has occurred.");
							}
						);
						_Orator.startWebServer();
						libSuperTest('http://localhost:8085/')
						.get('PINGOLo')
						.end(
							function (pError, pResponse)
							{
								if (pError)
								{
									console.log('Error on Logfile Results: '+JSON.stringify(pError));
									Expect('Logged Request Error').to.equal('Nothing');
								}
								else
								{
									Expect(pResponse.text)
										.to.contain('Loggo');
								}
								libSuperTest('http://localhost:8085/')
								.get('PINataGOLo')
								.end(
									function (pError, pResponse)
									{
										if (pError)
										{
											console.log('Error on Logfile Results: '+JSON.stringify(pError));
											Expect('Logged Request Error').to.equal('Nothing');
										}
										else
										{
											Expect(pResponse.text)
												.to.contain('dire');
										}
										// Next uncaught exception should be passed through without logging the stack trace
										_Orator.settings.LogStackTraces = false;
										fDone();
									}
								);
							}
						);
					}
				);
				test
				(
					'rejected promises should throw properly.',
					function(fDone)
					{
						libSuperTest('http://localhost:8085/')
						.get('PINataGOLo')
						.end(
							function (pError, pResponse)
							{
								if (pError)
								{
									console.log('Error on Logfile Results: '+JSON.stringify(pError));
									Expect('Logged Request Error').to.equal('Nothing');
								}
								else
								{
									Expect(pResponse.text)
										.to.contain('dire');
								}
								fDone();
							}
						);
					}
				);
			}
		);
	}
);


text:
using System;

namespace Neemo.Web.Models
{
    public class OrderHistoryView
    {
        public OrderView[] Orders { get; set; }
    }

    public class OrderView
    {
        public int OrderId { get; set; }
        public string Username { get; set; }
        public decimal TotalAmount { get; set; }
        public DateTime CreatedDateTime { get; set; }
        public OrderLineItemView[] OrderLineItems { get; set; }
    }

    public class OrderLineItemView
    {
        public int ProductId { get; set; }
        public int Quantity { get; set; }
        public decimal UnitPrice { get; set; }
        public decimal TotalValue { get; set; }
        public decimal TaxTotal { get; set; }
        public DateTime CreatedDateTime { get; set; }
        public string ProductName { get; set; }
    }
}


text:
"""
Copies configuration files to the destination host and applies appropriate
ownership and permissions.
"""

import argparse
import logging
import os
import shutil
import errno
import pwd
import grp
import subprocess

HOSTCLASS_FILE_PATH = "/opt/wgen/etc/hostclass"
METADATA_FILE_NAME = "acfg.metadata"

def copy_tree(source, destination, dryrun=False):
    """Copies a file tree rooted at source to destination.
    Files that contain '~' are only copied if string after ~ matches hostclass and files
    not containing '~' are only copied if a hostclass specific version does not exist.

    This reads the hostclass from a hostclass file located at HOSTCLASS_FILE_PATH. If no
    such file exists, this raises an exception. The files will also be renamed, stripping ~
    and hostclass string after it. Permissions and file ownership are applied from
    source/METADATA_FILE_NAME, if it exists.

    :param source:  the source tree root
    :param destination:  The destination tree root
    :param dryrun:  If this is true copy_tree() will log as normal but not actually copy anything.
    :raise HostclassFileNotFound: if no hostclass file was found
    """
    if os.path.exists(HOSTCLASS_FILE_PATH):
        with open(HOSTCLASS_FILE_PATH) as hostclass_file:
            hostclass = hostclass_file.readline().strip()
            _copy_files(source, destination, hostclass, dryrun)
            _apply_metadata(source, hostclass, dryrun)
    else:
        raise HostclassFileNotFound()

def _copy_files(source, destination, hostclass, dryrun=False):
    # TODO Break this into smaller functions
    # pylint: disable=R0914
    magicsuffix = "~{0}".format(hostclass)

    for path, dirnames, filenames in os.walk(source):
        destpath = os.path.join(destination, os.path.relpath(path, source))

        for dirname in dirnames:
            spath = os.path.join(path, dirname)
            dpath = os.path.join(destpath, dirname)
            logging.info("make directory %s", dpath)
            if not dryrun:
                if not os.path.isdir(dpath):
                    os.makedirs(dpath)
                shutil.copystat(spath, dpath)

        sources = set()
        destinations = set()
        files = []

        # Add the host specific files first
        for filename in [f for f in filenames if f.endswith(magicsuffix)]:
            src = os.path.join(path, filename)
            dst = os.path.join(destpath, filename[0:-len(magicsuffix)])
            sources |= set([src])
            destinations |= set([dst])
            files += [(src, dst)]

        # Add generic files if they don't overwrite host specific files
        for filename in [f for f in filenames if "~" not in f]:
            src = os.path.join(path, filename)
            dst = os.path.join(destpath, filename)
            if dst not in destinations:
                sources |= set([src])
                destinations |= set([dst])
                files += [(src, dst)]

        # Tell user what is being skipped
        for filename in filenames:
            src_file = os.path.join(path, filename)
            if src_file not in sources:
                logging.info("skipping: %s", os.path.realpath(src_file))

        # Tell user what is being copied, copy unless this is a dry run
        for (spath, dpath) in files:
            logging.info("copying %s to %s", os.path.realpath(spath), dpath)
            if not dryrun:
                shutil.copy(spath, dpath)

def _apply_metadata(source, hostclass, dryrun=False):
    # Pylint thinks this function has too many local variables
    # pylint: disable=R0914
    metadata_file_path = os.path.join(source, METADATA_FILE_NAME)
    if not os.path.exists(metadata_file_path):
        logging.warning("Metadata file not found: %s, no permissions to apply.", metadata_file_path)
        return

    magicsuffix = "~{0}".format(hostclass)

    with open(metadata_file_path, 'r') as metadata_file:
        for line in metadata_file.readlines():
            file_metadata = line.partition('#')[0].strip()  # ignore comments and blank lines
            if not file_metadata:
                continue
            try:
                filename, permissions, owner, group = file_metadata.split()
            except Exception:
                raise ValueError("Not enough values to unpack on line: {0}".format(file_metadata))

            if "~" in filename:
                if filename.endswith(magicsuffix):
                    filename = filename[0:-len(magicsuffix)]
                else:
                    logging.info("skipping permissions: %s", filename)
                    continue

            if not os.path.exists(filename):
                logging.warning("skipping permissions (file not found): %s", filename)
                continue

            logging.info("setting ownership of %s to %s:%s", filename, owner, group)
            if not dryrun:
                uid, gid = get_or_create_ids(owner, group)
                os.chown(filename, uid, gid)

            logging.info("setting permissions of %s to %s", filename, permissions)
            if not dryrun:
                os.chmod(filename, int(permissions, 8))

class HostclassFileNotFound(EnvironmentError):
    """
    An exception indicating that the hostclass file couldn't be found.
    """
    def __init__(self):
        super(HostclassFileNotFound, self).__init__(
            errno.ENOENT,
            "Couldn't find hostclass file {0}".format(HOSTCLASS_FILE_PATH))

def get_or_create_ids(username, groupname):
    """
    Get the UID and GID for a user and group, creating the user and group if necessary.
    Users are created with no login shell: if they need a shell, downstream init scripts
    should update it.
    """
    try:
        gid = grp.getgrnam(groupname).gr_gid
    except KeyError:
        logging.info("Creating group %s", groupname)
        subprocess.call(['/usr/sbin/groupadd', '-f', groupname])
        gid = grp.getgrnam(groupname).gr_gid
    try:
        uid = pwd.getpwnam(username).pw_uid
    except KeyError:
        logging.info("Creating user %s", username)
        subprocess.call(['/usr/sbin/adduser',
                         '--system',
                         '--gid', str(gid),
                         '--shell', '/sbin/nologin',
                         username])
        uid = pwd.getpwnam(username).pw_uid
    return uid, gid

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="""
    Tool for copying trees of files. Files that contain '~' are only copied if
    string after ~ matches hostclass. The files will also be renamed,
    stripping ~ and hostclass string after it. Permissions and file ownership
    are applied from /metadata.txt at the root of the tree.
    """)
    parser.add_argument("source", help="Source location overlay directory")
    parser.add_argument("destination", help="Destination of where to overlay source directory over")
    parser.add_argument('--dry', action='store_const', const=True, default=False, help='Dry run only')

    logger = logging.getLogger('')
    logger.setLevel(logging.INFO)

    args = parser.parse_args()
    copy_tree(args.source, args.destination, args.dry)


text:
if (( ${INSTALL_JDK_DEVEL} )); then
  echo 'Installing JDK with compiler and tools'
  install_application "openjdk-7-jdk" "java-1.7.0-openjdk-devel"
else
  if (( ${INSTALL_JRE} )); then
    echo 'Installing minimal JRE'
    install_application "openjdk-7-jre-headless" "java-1.7.0-openjdk"
  fi
fi


text:
<?php

namespace Tracks;

use Rhumsaa\Uuid\Uuid;
use Tracks\Storage\StorageInterface;

class Track implements TrackInterface {

    public $id;

    public $ts;

    public $te;

    public $ms;

    private $msTs;

    private $msTe;

    public $bucket;

    public $host;

    public $memory;

    public $tags = [];

    public $payload = [];

    public $pid = null;

    /** @var StorageInterface */
    private static $client;

    /** @var string key */
    private static $key = 'tracks';

    /**
     * @param string $bucket
     * @param array $payload
     * @param null|string $pid
     */
    public function __construct($bucket, $payload = [], $unique_pid = NULL)
    {
        $this->id = Uuid::uuid4()->toString();
        $this->bucket = $bucket;
        $this->host = (string) (\gethostname() . '_' . \getmypid());

        if($unique_pid) {
            $this->pid = $unique_pid;
        }
    }

    /**
     * @param StorageInterface $client
     */
    public static function setClient(StorageInterface $client)
    {
        self::$client = $client;
    }

    /**
     * @param $bucket
     * @param array $payload
     * @param null $pid
     * @return Track
     */
    public static function create($bucket, $payload = [], $pid = NULL) {
        return new Track($bucket, $payload, $pid);
    }

    /**
     * @return $this
     */
    public function start()
    {
        list($this->ts, $this->msTs) = $this->getTime();
        return $this;
    }

    /**
     * @return $this
     */
    public function stop()
    {
        list($this->te, $this->msTe) = $this->getTime();
        $this->memory = \memory_get_usage(true);
        $this->ms = intval(($this->msTe - $this->msTs) * 1000000);
        return $this;
    }

    public function addPayload($payload)
    {
        $this->payload[] = $payload;
        return $this;
    }

    private function getTime()
    {
        $d = new \DateTime();
        return [(string)  $d->format('Y-m-d\TH:i:s.u\0\0O'), microtime(true)];
    }

    public function getId()
    {
        return $this->id;
    }

    public function setTags(array $tags = [])
    {
        $this->tags = $tags;
    }

    public function addTag($string = '')
    {
        $this->tags[] = $string;
    }

    public function send()
    {
        try {
            self::$client->send(self::$key, $this);
        } catch(\Exception $e) {
            return ['success' => false, 'error' => $e->getMessage()];
        }

        return TRUE;
    }

}


text:
package org.opencds.cqf.cql.engine.execution;

import org.cqframework.cql.elm.execution.Library;
import org.cqframework.cql.elm.execution.VersionedIdentifier;

public interface LibraryLoader {
    Library load(VersionedIdentifier libraryIdentifier);
}


text:
var BSync = new function()
{

  /******* Privates *********/
  /**
   * Native js md5 implementation. Written by by Luigi Galli - LG@4e71.org - http://faultylabs.com
   * Modified by Clay Gulick - clay@ratiosoftware.com - http://ratiosoftware.com
   */
  var md5 = function(data) {

    // convert number to (unsigned) 32 bit hex, zero filled string
    function to_zerofilled_hex(n) {
        var t1 = (n >>> 0).toString(16)
        return "00000000".substr(0, 8 - t1.length) + t1
    }

    // convert array of chars to array of bytes
    function chars_to_bytes(ac) {
        var retval = []
        for (var i = 0; i < ac.length; i++) {
            retval = retval.concat(str_to_bytes(ac[i]))
        }
        return retval
    }

    // convert a 64 bit unsigned number to array of bytes. Little endian
    function int64_to_bytes(num) {
        var retval = []
        for (var i = 0; i < 8; i++) {
            retval.push(num & 0xFF)
            num = num >>> 8
        }
        return retval
    }

    //  32 bit left-rotation
    function rol(num, places) {
        return ((num << places) & 0xFFFFFFFF) | (num >>> (32 - places))
    }

    // The 4 MD5 functions
    function fF(b, c, d) {
        return (b & c) | (~b & d)
    }

    function fG(b, c, d) {
        return (d & b) | (~d & c)
    }

    function fH(b, c, d) {
        return b ^ c ^ d
    }

    function fI(b, c, d) {
        return c ^ (b | ~d)
    }

    // pick 4 bytes at specified offset. Little-endian is assumed
    function bytes_to_int32(arr, off) {
        return (arr[off + 3] << 24) | (arr[off + 2] << 16) | (arr[off + 1] << 8) | (arr[off])
    }

    /*
    Conver string to array of bytes in UTF-8 encoding
    See:
    http://www.dangrossman.info/2007/05/25/handling-utf-8-in-javascript-php-and-non-utf8-databases/
    http://stackoverflow.com/questions/1240408/reading-bytes-from-a-javascript-string
    How about a String.getBytes(<ENCODING>) for Javascript!? Isn't it time to add it?
    */
    function str_to_bytes(str) {
        var retval = [ ]
        for (var i = 0; i < str.length; i++)
            if (str.charCodeAt(i) <= 0x7F) {
                retval.push(str.charCodeAt(i))
            } else {
                var tmp = encodeURIComponent(str.charAt(i)).substr(1).split('%')
                for (var j = 0; j < tmp.length; j++) {
                    retval.push(parseInt(tmp[j], 0x10))
                }
            }
        return retval
    }

    // convert the 4 32-bit buffers to a 128 bit hex string. (Little-endian is assumed)
    function int128le_to_hex(a, b, c, d) {
        var ra = ""
        var t = 0
        var ta = 0
        for (var i = 3; i >= 0; i--) {
            ta = arguments[i]
            t = (ta & 0xFF)
            ta = ta >>> 8
            t = t << 8
            t = t | (ta & 0xFF)
            ta = ta >>> 8
            t = t << 8
            t = t | (ta & 0xFF)
            ta = ta >>> 8
            t = t << 8
            t = t | ta
            ra = ra + to_zerofilled_hex(t)
        }
        return ra
    }

    // conversion from typed byte array to plain javascript array
    function typed_to_plain(tarr) {
        var retval = new Array(tarr.length)
        for (var i = 0; i < tarr.length; i++) {
            retval[i] = tarr[i]
        }
        return retval
    }

    // check input data type and perform conversions if needed
    var databytes = null
    // String
    var type_mismatch = null
    if (typeof data == 'string') {
        // convert string to array bytes
        databytes = str_to_bytes(data)
    } else if (data.constructor == Array) {
        if (data.length === 0) {
            // if it's empty, just assume array of bytes
            databytes = data
        } else if (typeof data[0] == 'string') {
            databytes = chars_to_bytes(data)
        } else if (typeof data[0] == 'number') {
            databytes = data
        } else {
            type_mismatch = typeof data[0]
        }
    } else if (typeof ArrayBuffer != 'undefined') {
        if (data instanceof ArrayBuffer) {
            databytes = typed_to_plain(new Uint8Array(data))
        } else if ((data instanceof Uint8Array) || (data instanceof Int8Array)) {
            databytes = typed_to_plain(data)
        } else if ((data instanceof Uint32Array) || (data instanceof Int32Array) ||
               (data instanceof Uint16Array) || (data instanceof Int16Array) ||
               (data instanceof Float32Array) || (data instanceof Float64Array)
         ) {
            databytes = typed_to_plain(new Uint8Array(data.buffer))
        } else {
            type_mismatch = typeof data
        }
    } else {
        type_mismatch = typeof data
    }

    if (type_mismatch) {
        alert('MD5 type mismatch, cannot process ' + type_mismatch)
    }

    function _add(n1, n2) {
        return 0x0FFFFFFFF & (n1 + n2)
    }

    return do_digest()

    function do_digest() {

        // function update partial state for each run
        function updateRun(nf, sin32, dw32, b32) {
            var temp = d
            d = c
            c = b
            //b = b + rol(a + (nf + (sin32 + dw32)), b32)
            b = 0x0FFFFFFFF & (b +
                rol(
                    0x0FFFFFFFF & (a +
                        (0x0FFFFFFFF & (nf + (0x0FFFFFFFF & (sin32 + dw32))))
                    ), b32
                )
            )
            a = temp
        }

        // save original length
        var org_len = databytes.length

        // first append the "1" + 7x "0"
        databytes.push(0x80)

        // determine required amount of padding
        var tail = databytes.length % 64
        // no room for msg length?
        if (tail > 56) {
            // pad to next 512 bit block
            for (var i = 0; i < (64 - tail); i++) {
                databytes.push(0x0)
            }
            tail = databytes.length % 64
        }
        for (i = 0; i < (56 - tail); i++) {
            databytes.push(0x0)
        }
        // message length in bits mod 512 should now be 448
        // append 64 bit, little-endian original msg length (in *bits*!)
        databytes = databytes.concat(int64_to_bytes(org_len * 8))

        // initialize 4x32 bit state
        var h0 = 0x67452301
        var h1 = 0xEFCDAB89
        var h2 = 0x98BADCFE
        var h3 = 0x10325476

        // temp buffers
        var a = 0, b = 0, c = 0, d = 0

        // Digest message
        for (i = 0; i < databytes.length / 64; i++) {
            // initialize run
            a = h0
            b = h1
            c = h2
            d = h3

            var ptr = i * 64

            // do 64 runs
            updateRun(fF(b, c, d), 0xd76aa478, bytes_to_int32(databytes, ptr), 7)
            updateRun(fF(b, c, d), 0xe8c7b756, bytes_to_int32(databytes, ptr + 4), 12)
            updateRun(fF(b, c, d), 0x242070db, bytes_to_int32(databytes, ptr + 8), 17)
            updateRun(fF(b, c, d), 0xc1bdceee, bytes_to_int32(databytes, ptr + 12), 22)
            updateRun(fF(b, c, d), 0xf57c0faf, bytes_to_int32(databytes, ptr + 16), 7)
            updateRun(fF(b, c, d), 0x4787c62a, bytes_to_int32(databytes, ptr + 20), 12)
            updateRun(fF(b, c, d), 0xa8304613, bytes_to_int32(databytes, ptr + 24), 17)
            updateRun(fF(b, c, d), 0xfd469501, bytes_to_int32(databytes, ptr + 28), 22)
            updateRun(fF(b, c, d), 0x698098d8, bytes_to_int32(databytes, ptr + 32), 7)
            updateRun(fF(b, c, d), 0x8b44f7af, bytes_to_int32(databytes, ptr + 36), 12)
            updateRun(fF(b, c, d), 0xffff5bb1, bytes_to_int32(databytes, ptr + 40), 17)
            updateRun(fF(b, c, d), 0x895cd7be, bytes_to_int32(databytes, ptr + 44), 22)
            updateRun(fF(b, c, d), 0x6b901122, bytes_to_int32(databytes, ptr + 48), 7)
            updateRun(fF(b, c, d), 0xfd987193, bytes_to_int32(databytes, ptr + 52), 12)
            updateRun(fF(b, c, d), 0xa679438e, bytes_to_int32(databytes, ptr + 56), 17)
            updateRun(fF(b, c, d), 0x49b40821, bytes_to_int32(databytes, ptr + 60), 22)
            updateRun(fG(b, c, d), 0xf61e2562, bytes_to_int32(databytes, ptr + 4), 5)
            updateRun(fG(b, c, d), 0xc040b340, bytes_to_int32(databytes, ptr + 24), 9)
            updateRun(fG(b, c, d), 0x265e5a51, bytes_to_int32(databytes, ptr + 44), 14)
            updateRun(fG(b, c, d), 0xe9b6c7aa, bytes_to_int32(databytes, ptr), 20)
            updateRun(fG(b, c, d), 0xd62f105d, bytes_to_int32(databytes, ptr + 20), 5)
            updateRun(fG(b, c, d), 0x2441453, bytes_to_int32(databytes, ptr + 40), 9)
            updateRun(fG(b, c, d), 0xd8a1e681, bytes_to_int32(databytes, ptr + 60), 14)
            updateRun(fG(b, c, d), 0xe7d3fbc8, bytes_to_int32(databytes, ptr + 16), 20)
            updateRun(fG(b, c, d), 0x21e1cde6, bytes_to_int32(databytes, ptr + 36), 5)
            updateRun(fG(b, c, d), 0xc33707d6, bytes_to_int32(databytes, ptr + 56), 9)
            updateRun(fG(b, c, d), 0xf4d50d87, bytes_to_int32(databytes, ptr + 12), 14)
            updateRun(fG(b, c, d), 0x455a14ed, bytes_to_int32(databytes, ptr + 32), 20)
            updateRun(fG(b, c, d), 0xa9e3e905, bytes_to_int32(databytes, ptr + 52), 5)
            updateRun(fG(b, c, d), 0xfcefa3f8, bytes_to_int32(databytes, ptr + 8), 9)
            updateRun(fG(b, c, d), 0x676f02d9, bytes_to_int32(databytes, ptr + 28), 14)
            updateRun(fG(b, c, d), 0x8d2a4c8a, bytes_to_int32(databytes, ptr + 48), 20)
            updateRun(fH(b, c, d), 0xfffa3942, bytes_to_int32(databytes, ptr + 20), 4)
            updateRun(fH(b, c, d), 0x8771f681, bytes_to_int32(databytes, ptr + 32), 11)
            updateRun(fH(b, c, d), 0x6d9d6122, bytes_to_int32(databytes, ptr + 44), 16)
            updateRun(fH(b, c, d), 0xfde5380c, bytes_to_int32(databytes, ptr + 56), 23)
            updateRun(fH(b, c, d), 0xa4beea44, bytes_to_int32(databytes, ptr + 4), 4)
            updateRun(fH(b, c, d), 0x4bdecfa9, bytes_to_int32(databytes, ptr + 16), 11)
            updateRun(fH(b, c, d), 0xf6bb4b60, bytes_to_int32(databytes, ptr + 28), 16)
            updateRun(fH(b, c, d), 0xbebfbc70, bytes_to_int32(databytes, ptr + 40), 23)
            updateRun(fH(b, c, d), 0x289b7ec6, bytes_to_int32(databytes, ptr + 52), 4)
            updateRun(fH(b, c, d), 0xeaa127fa, bytes_to_int32(databytes, ptr), 11)
            updateRun(fH(b, c, d), 0xd4ef3085, bytes_to_int32(databytes, ptr + 12), 16)
            updateRun(fH(b, c, d), 0x4881d05, bytes_to_int32(databytes, ptr + 24), 23)
            updateRun(fH(b, c, d), 0xd9d4d039, bytes_to_int32(databytes, ptr + 36), 4)
            updateRun(fH(b, c, d), 0xe6db99e5, bytes_to_int32(databytes, ptr + 48), 11)
            updateRun(fH(b, c, d), 0x1fa27cf8, bytes_to_int32(databytes, ptr + 60), 16)
            updateRun(fH(b, c, d), 0xc4ac5665, bytes_to_int32(databytes, ptr + 8), 23)
            updateRun(fI(b, c, d), 0xf4292244, bytes_to_int32(databytes, ptr), 6)
            updateRun(fI(b, c, d), 0x432aff97, bytes_to_int32(databytes, ptr + 28), 10)
            updateRun(fI(b, c, d), 0xab9423a7, bytes_to_int32(databytes, ptr + 56), 15)
            updateRun(fI(b, c, d), 0xfc93a039, bytes_to_int32(databytes, ptr + 20), 21)
            updateRun(fI(b, c, d), 0xffeff47d, bytes_to_int32(databytes, ptr + 40), 15)
            updateRun(fI(b, c, d), 0x85845dd1, bytes_to_int32(databytes, ptr + 4), 21)
            updateRun(fI(b, c, d), 0x6fa87e4f, bytes_to_int32(databytes, ptr + 32), 6)
            updateRun(fI(b, c, d), 0xfe2ce6e0, bytes_to_int32(databytes, ptr + 60), 10)
            updateRun(fI(b, c, d), 0xa3014314, bytes_to_int32(databytes, ptr + 24), 15)
            updateRun(fI(b, c, d), 0x4e0811a1, bytes_to_int32(databytes, ptr + 52), 21)
            updateRun(fI(b, c, d), 0xf7537e82, bytes_to_int32(databytes, ptr + 16), 6)
            updateRun(fI(b, c, d), 0xbd3af235, bytes_to_int32(databytes, ptr + 44), 10)
            updateRun(fI(b, c, d), 0x2ad7d2bb, bytes_to_int32(databytes, ptr + 8), 15)
            updateRun(fI(b, c, d), 0xeb86d391, bytes_to_int32(databytes, ptr + 36), 21)

            // update buffers
            h0 = _add(h0, a)
            h1 = _add(h1, b)
            h2 = _add(h2, c)
            h3 = _add(h3, d)
        }
        // Done! Convert buffers to 128 bit (LE)
        //return int128le_to_hex(h3, h2, h1, h0).toUpperCase()
        return [h0,h1,h2,h3];
    }
  }
  /* ---- end md5 section ---- */

  /**
   * Create a fast 16 bit hash of a 32bit number. Just using a simple mod 2^16 for this for now.
   * TODO: Evaluate the distribution of adler32 to see if simple modulus is appropriate as a hashing function, or wheter 2^16 should be replaced with a prime
   */
  function hash16(num)
  {
    return num % 65536;
  }

  /**
   * Create a 32 bit checksum for the block, based on the adler-32 checksum, with M as 2^16
   * Used to feed the rollingChecksum function, so returns the broken out pieces that are required for fast calc (since there's no reason to do pointless
   * bit manipulation, we just cache the parts, like {a: ..., b: ..., checksum: ... }.
   *
   * Offset is the start, and end is the last byte for the block to be calculated. end - offset should equal the blockSize - 1
   *
   * Data should be a Uint8Array
   *
   * TODO: according to wikipedia, the zlib compression library has a much more efficient implementation of adler. To speed this up, it might be worth investigating whether that can be used here.
   */
  function adler32(offset, end, data)
  {
    var i=0;
    var a=0;
    var b=0;

    //adjust the end to make sure we don't exceed the extents of the data.
    if(end >= data.length)
      end = data.length - 1;

    for(i=offset; i <= end; i++)
    {
      a += data[i];
      b += a;
    }

    a %= 65536; //65536 = 2^16, used for M in the tridgell equation
    b %= 65536;

    return {a: a, b: b, checksum: ((b << 16) | a) >>> 0 };

  }

  /**
   * Performs a very fast rolling checksum for incremental searching using Tridgell's modification of adler-32 for rolling checksum
   * Returns an object suitable for use in additional calls to rollingChecksum, same as the adler32 function. This needs to be called with an offset of at least 1!
   * It is the responsibility of the called to make sure we don't exceed the bounds of the data, i.e. end MUST be less than data.length
   */
  function rollingChecksum(adlerInfo, offset, end, data)
  {
    var temp = data[offset - 1]; //this is the first byte used in the previous iteration
    var a = (adlerInfo.a - temp + data[end]) % 65536;
    var b = (adlerInfo.b - ((end - offset + 1) * temp) + a) % 65536;
    return {a: a, b: b, checksum: (b << 16) | a };
  }

  /**
   * This is a function born of annoyance. You can't create a Uint32Array at a non 4 byte boundary. So this is necessary to read
   * a 32bit int from an arbitrary location. Lame.
   *
   * BTW: This assumes everything to be little endian.
   */
  function readInt32(uint8View, offset)
  {
    return (uint8View[offset] | uint8View[++offset] << 8 | uint8View[++offset] << 16 | uint8View[++offset] << 24) >>> 0;
  }

  /**
   * Create a document that contains all of the checksum information for each block in the destination data. Everything is little endian
   * Document structure:
   * First 4 bytes = block size
   * Next 4 bytes = number of blocks
   * Repeat for number of blocks:
   *   4 bytes, adler32 checksum
   *   16 bytes, md5 checksum
   *
   */
  function createChecksumDocument(blockSize, data)
  {
    var numBlocks = Math.ceil(data.byteLength / blockSize);
    var i=0;
    var docLength = ( numBlocks * //the number of blocks times
                      ( 4 +       //the 4 bytes for the adler32 plus
                        16) +     //the 16 bytes for the md5
                      4 +         //plus 4 bytes for block size
                      4);         //plus 4 bytes for the number of blocks

    var doc = new ArrayBuffer(docLength);
    var dataView = new Uint8Array(data);
    var bufferView = new Uint32Array(doc);
    var offset = 2;
    var chunkSize = 5; //each chunk is 4 bytes for adler32 and 16 bytes for md5. for Uint32Array view, this is 20 bytes, or 5 4-byte uints

    bufferView[0] = blockSize;
    bufferView[1] = numBlocks;

    //spin through the data and create checksums for each block
    for(i=0; i < numBlocks; i++)
    {
      var start = i * blockSize;
      var end = (i * blockSize) + blockSize;

      //calculate the adler32 checksum
      bufferView[offset] = adler32(start, end - 1, dataView).checksum;
      offset++;

      //calculate the full md5 checksum
      var chunkLength = blockSize;
      if((start + blockSize) > data.byteLength)
        chunkLength = data.byteLength - start;

      var md5sum = md5(new Uint8Array(data, start, chunkLength));
      for(var j=0; j < 4; j++) bufferView[offset++] = md5sum[j];

    }

    return doc;

  }

  /**
   * Parse the checksum document into a hash table
   *
   * The hash table will have 2^16 entries. Each entry will point to an array that has the following strucutre:
   * [
   *  [ [blockIndex, adler32sum, md5sum],[blockIndex, adler32sum, md5sum],... ]
   *  [ [blockIndex, adler32sum, md5sum],[blockIndex, adler32sum, md5sum],... ]
   *  ...
   * ]
   */
  function parseChecksumDocument(checksumDocument)
  {
    var ret = [];
    var i=0;
    var view = new Uint32Array(checksumDocument);
    var blockIndex = 1; //blockIndex is 1 based, not zero based
    var numBlocks = view[1];
    var row;
    var hash;

    //each chunk in the document is 20 bytes long. 32 bit view indexes 4 bytes, so increment by 5.
    for(i = 2; i <= view.length - 5; i += 5)
    {
      checksumInfo = [
             blockIndex, //the index of the block
             view[i], //the adler32sum
             [view[i+1],view[i+2],view[i+3],view[i+4]] //the md5sum
            ];
      hash = hash16(checksumInfo[1]);
      if(!ret[hash]) ret[hash] = [];
      ret[hash].push(checksumInfo);
      blockIndex++;
    }

    if(numBlocks != (blockIndex - 1))
    {
      throw "Error parsing checksum document. Document states the number of blocks is: " + numBlocks + " however, " + blockIndex - 1 + " blocks were discovered";
    }

    return ret;

  }

  /**
   * Create a patch document that contains all the information needed to bring the destination data into synchronization with the source data.
   *
   * The patch document looks like this: (little Endian)
   * 4 bytes - blockSize
   * 4 bytes - number of patches
   * 4 bytes - number of matched blocks
   * For each matched block:
   *   4 bytes - the index of the matched block
   * For each patch:
   *   4 bytes - last matching block index. NOTE: This is 1 based index! Zero indicates beginning of file, NOT the first block
   *   4 bytes - patch size
   *   n bytes - new data
   */
  function createPatchDocument(checksumDocument, data)
  {
    function appendBuffer( buffer1, buffer2 ) {
      var tmp = new Uint8Array( buffer1.byteLength + buffer2.byteLength );
      tmp.set( new Uint8Array( buffer1 ), 0 );
      tmp.set( new Uint8Array( buffer2 ), buffer1.byteLength );
      return tmp.buffer;
    }

    /**
     * First, check to see if there's a match on the 16 bit hash
     * Then, look through all the entries in the hashtable row for an adler 32 match.
     * Finally, do a strong md5 comparison
     */
    function checkMatch(adlerInfo, hashTable, block)
    {
      var hash = hash16(adlerInfo.checksum);
      if(!(hashTable[hash])) return false;
      var row = hashTable[hash];
      var i=0;
      var matchedIndex=0;

      for(i=0; i<row.length; i++)
      {
        //compare adler32sum
        if(row[i][1] != adlerInfo.checksum) continue;
        //do strong comparison
        md5sum1 = md5(block);
        md5sum1 = new Uint32Array([md5sum1[0],md5sum1[1],md5sum1[2],md5sum1[3]]); //convert to unsigned 32
        md5sum2 = row[i][2];
        if(
            md5sum1[0] == md5sum2[0] &&
            md5sum1[1] == md5sum2[1] &&
            md5sum1[2] == md5sum2[2] &&
            md5sum1[3] == md5sum2[3]
          )
          return row[i][0]; //match found, return the matched block index

      }

      return false;

    }

    var checksumDocumentView = new Uint32Array(checksumDocument);
    var blockSize = checksumDocumentView[0];
    var numBlocks = checksumDocumentView[1];
    var numPatches = 0;

    var patchDocument = new ArrayBuffer(12);
    var patch;
    var patches = new ArrayBuffer(0);
    var i=0;

    var hashTable = parseChecksumDocument(checksumDocument);
    var endOffset = data.byteLength - blockSize;
    var adlerInfo = null;
    var lastMatchIndex = 0;
    var currentPatch = new ArrayBuffer(1000);
    var currentPatchUint8 = new Uint8Array(currentPatch);
    var currentPatchSize = 0;
    var dataUint8 = new Uint8Array(data);
    var matchedBlocks = new ArrayBuffer(1000);
    var matchedBlocksUint32 = new Uint32Array(matchedBlocks);
    var matchCount = 0;

    for(;;)
    {
      var chunkSize = 0;
      //determine the size of the next data chuck to evaluate. Default to blockSize, but clamp to end of data
      if((i + blockSize) > data.byteLength)
      {
        chunkSize = data.byteLength - i;
        adlerInfo=null; //need to reset this because the rolling checksum doesn't work correctly on a final non-aligned block
      }
      else
        chunkSize = blockSize;

      if(adlerInfo)
        adlerInfo = rollingChecksum(adlerInfo, i, i + chunkSize - 1, dataUint8);
      else
        adlerInfo = adler32(i, i + chunkSize - 1, dataUint8);

      var matchedBlock = checkMatch(adlerInfo, hashTable, new Uint8Array(data,i,chunkSize));
      if(matchedBlock)
      {
        //if we have a match, do the following:
        //1) add the matched block index to our tracking buffer
        //2) check to see if there's a current patch. If so, add it to the patch document.
        //3) jump forward blockSize bytes and continue
        matchedBlocksUint32[matchCount] = matchedBlock;
        matchCount++;
        //check to see if we need more memory for the matched blocks
        if(matchCount >= matchedBlocksUint32.length)
        {
          matchedBlocks = appendBuffer(matchedBlocks, new ArrayBuffer(1000));
          matchedBlocksUint32 = new Uint32Array(matchedBlocks);
        }
        if(currentPatchSize > 0)
        {
          //create the patch and append it to the patches buffer
          patch = new ArrayBuffer(4 + 4); //4 for last match index, 4 for patch size
          var patchUint32 = new Uint32Array(patch,0,2);
          patchUint32[0] = lastMatchIndex;
          patchUint32[1] = currentPatchSize;
          patch = appendBuffer(patch,currentPatch.slice(0,currentPatchSize));
          patches = appendBuffer(patches, patch);
          currentPatch = new ArrayBuffer(1000);
          currentPatchUint8 = new Uint8Array(currentPatch);
          currentPatchSize = 0;
          numPatches++;
        }
        lastMatchIndex = matchedBlock;
        i+=blockSize;
        if(i >= dataUint8.length -1 ) break;
        adlerInfo=null;
        continue;
      }
      else
      {
        //while we don't have a block match, append bytes to the current patch
        currentPatchUint8[currentPatchSize] = dataUint8[i];
        currentPatchSize++;
        if(currentPatchSize >= currentPatch.byteLength)
        {
          //allocate another 1000 bytes
          currentPatch = appendBuffer(currentPatch, new ArrayBuffer(1000));
          currentPatchUint8 = new Uint8Array(currentPatch);
        }
      }
      if((i) >= dataUint8.length -1) break;
      i++;
    } //end for each byte in the data
    if(currentPatchSize > 0)
    {
      //create the patch and append it to the patches buffer
      patch = new ArrayBuffer(4 + 4); //4 for last match index, 4 for patch size
      var patchUint32 = new Uint32Array(patch,0,2);
      patchUint32[0] = lastMatchIndex;
      patchUint32[1] = currentPatchSize;
      patch = appendBuffer(patch,currentPatch.slice(0,currentPatchSize));
      patches = appendBuffer(patches, patch);
      numPatches++;
    }

    var patchDocumentView32 = new Uint32Array(patchDocument);
    patchDocumentView32[0] = blockSize;
    patchDocumentView32[1] = numPatches;
    patchDocumentView32[2] = matchCount;
    patchDocument = appendBuffer(patchDocument, matchedBlocks.slice(0,matchCount * 4));
    patchDocument = appendBuffer(patchDocument, patches);

    var patchDocumentView32 = new Uint32Array(patchDocument,0,matchCount + 3);
    var patchDocumentView8 = new Uint8Array(patchDocument);

    return patchDocument;
  }

  /**
   * Apply the patch to the destination data, making it into a duplicate of the source data
   * Due to the inability to modify the size of ArrayBuffers once they have been allocated, this function
   * will return a new ArrayBuffer with the update file data. Note that this will consume a good bit of extra memory.
   */
  function applyPatch(patchDocument, data)
  {
    function appendBlock( buffer, blockUint8) {
      var tmp = new Uint8Array( buffer.byteLength + blockUint8.length);
      tmp.set( new Uint8Array( buffer ), 0 );
      tmp.set( blockUint8, buffer.byteLength );
      return tmp.buffer;
    }

    var patchDocumentView32 = new Uint32Array(patchDocument,0,3);
    var blockSize = patchDocumentView32[0];
    var patchCount = patchDocumentView32[1];
    var matchCount = patchDocumentView32[2];
    var matchedBlockView32 = new Uint32Array(patchDocument,12,matchCount);
    var i=0;
    var j=0;

    //first, let's deal with the simple case where we fully match. This is just an optimization for the unchanged file case.
    //to determine this, the number of matches must exactly equal ceil of data / blockSize, and num patches must be zero
    //additionally, the matched block indexes must start with 1 and be in order. This is to deal with the extreme edge case of a block being relocated
    //on an exact block boundary
    if(patchCount == 0)
      if(Math.ceil(data.byteLength / blockSize) == matchCount)
        for(i = 1; i <= matchCount; i++)
          if(matchedBlockView32[i-1] != i) { break; }
    if((i - 1) == matchCount) return data; //exact match

    //there was a modification. We need to construct the new document.
    //the way this works is as follows:
    //1) for each patch, get the last index of the matching block
    //2) loop through the matchedBlocks, appending blocks up to the index from step 1
    //3) append the patch at that point
    //4) after all patches have been applied, continue to loop through the matchedBlocks appending each one in order
    var offset = 12 + (matchCount * 4); //offset to the start of the patches
    var lastMatchingBlockIndex=0;
    var patchSize=0;
    var patchView8;
    var matchIndex=0; //the index into the matching blocks array
    var blockIndex=0; //the index of the block in the matching blocks array
    var ret = new ArrayBuffer(0);
    var patchDocumentView8 = new Uint8Array(patchDocument);
    var chunkSize=0;
    for(i=0; i< patchCount; i++)
    {
      lastMatchingBlockIndex = readInt32(patchDocumentView8,offset);
      patchSize = readInt32(patchDocumentView8,offset + 4);
      patchView8 = new Uint8Array(patchDocument, offset + 8, patchSize);
      offset = offset + 8 + patchSize;

      for(;matchIndex < matchedBlockView32.length; matchIndex++)
      {
        blockIndex = matchedBlockView32[matchIndex];
        if(blockIndex > lastMatchingBlockIndex) break;
        if((blockIndex * blockSize) > data.byteLength)
          chunkSize = data.byteLength % blockSize;
        else chunkSize = blockSize;
        ret = appendBlock(ret, new Uint8Array(data, (blockIndex-1) * blockSize, chunkSize));
      }

      ret = appendBlock(ret, patchView8);
    }

    //we're done with all the patches, add the remaining blocks
    for(;matchIndex < matchedBlockView32.length; matchIndex++)
    {
      blockIndex = matchedBlockView32[matchIndex];
      if((blockIndex * blockSize) > data.byteLength)
        chunkSize = data.byteLength % blockSize;
      else chunkSize = blockSize;
      ret = appendBlock(ret, new Uint8Array(data, (blockIndex-1) * blockSize, chunkSize));
    }

    return ret;
  }

  /******** Public API ***********/
  this.createChecksumDocument = createChecksumDocument;
  this.createPatchDocument = createPatchDocument;
  this.applyPatch = applyPatch;
  this.util = {md5: md5, adler32: adler32, rollingChecksum: rollingChecksum, readInt32: readInt32}; //mostly exposing these for the purposes of unit tests, but hey, if they are useful to someone, have at it!
};

if(((typeof require) != "undefined") &&
   ((typeof module) != "undefined") &&
   ((typeof module.exports) != "undefined"))
    module.exports = BSync;


text:
package org.huahinframework.tools.util;

import java.io.Serializable;

/**
 *
 */
public class SearchEngine implements Serializable {
    private static final long serialVersionUID = 1L;

    private String path;
    private String query;

    public SearchEngine() {
    }

    public SearchEngine(String path, String query) {
        this.path = path;
        this.query = query;
    }

    /**
     * @return the path
     */
    public String getPath() {
        return path;
    }

    /**
     * @param path the path to set
     */
    public void setPath(String path) {
        this.path = path;
    }

    /**
     * @return the query
     */
    public String getQuery() {
        return query;
    }

    /**
     * @param query the query to set
     */
    public void setQuery(String query) {
        this.query = query;
    }
}


text:
function ft_omri_pipeline(cfg)

% FT_OMRI_PIPELINE implements an online fMRI pre-processing pipeline
%
% Use as
%   ft_omri_pipeline(cfg)
% where cfg is a structure with configuration settings.
%
% Configuration options are
%   cfg.input            = FieldTrip buffer containing raw scans (default 'buffer://localhost:1972')
%   cfg.output           = where to write processed scans to     (default 'buffer://localhost:1973')
%   cfg.numDummy         = how many scans to ignore initially    (default 0)
%   cfg.smoothFWHM       = kernel width in mm (Full Width Half Maximum) for smoothing (default = 0 => no smoothing)
%   cfg.correctMotion 	 = flag indicating whether to correct motion artifacts (default = 1 = yes)
%   cfg.correctSliceTime = flag indicating whether to correct slice timing (default = 1 = yes)

% Copyright (C) 2010, Stefan Klanke
%
% This file is part of FieldTrip, see http://www.ru.nl/neuroimaging/fieldtrip
% for the documentation and details.
%
%    FieldTrip is free software: you can redistribute it and/or modify
%    it under the terms of the GNU General Public License as published by
%    the Free Software Foundation, either version 3 of the License, or
%    (at your option) any later version.
%
%    FieldTrip is distributed in the hope that it will be useful,
%    but WITHOUT ANY WARRANTY; without even the implied warranty of
%    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%    GNU General Public License for more details.
%
%    You should have received a copy of the GNU General Public License
%    along with FieldTrip. If not, see <http://www.gnu.org/licenses/>.
%
% $Id: ft_omri_pipeline.m 8143 2013-05-23 13:24:12Z roboos $

ft_defaults
ft_hastoolbox('spm8', 1);

if nargin < 1
	cfg = [];
end

if ~isfield(cfg, 'input')
	cfg.input = 'buffer://localhost:1972';
end

if ~isfield(cfg, 'output')
	cfg.output = 'buffer://localhost:1973';
end

if ~isfield(cfg, 'numDummy')
	cfg.numDummy = 0;			% number of dummy scans to drop
end

if ~isfield(cfg, 'smoothFWHM')
	cfg.smoothFWHM = 0;
end

if ~isfield(cfg, 'correctMotion')
	cfg.correctMotion = 1;
end

if ~isfield(cfg, 'correctSliceTime')
	cfg.correctSliceTime = 1;
end

if ~isfield(cfg, 'whichEcho')
	cfg.whichEcho = 1;
else
	if cfg.whichEcho < 1
		error '"whichEcho" configuration field must be >= 1';
	end
end

% prepare "ready" event data structure
evr = [];
evr.type = 'scan';
evr.value = 'ready';
evr.offset = 0;
evr.duration = 0;
evr.sample = 0;

history = struct('S',[], 'RRM', [], 'motion', []);

numTrial = 0;

% Loop this forever (until user cancels)
while 1
	clear ft_read_header
	% start by reading the header from the realtime buffer
	while 1
		try
			hdr = ft_read_header(cfg.input);
			break;
		catch
			disp(lasterror);
			disp('Waiting for header');
			pause(0.5);
		end
	end

	% Ok, we got the header, try to make sense out of it
	S = ft_omri_info_from_header(hdr);
	if isempty(S)
		warning('No protocol information found!')
		% restart loop
		pause(0.5);
		continue;
	end

	if cfg.whichEcho > S.numEchos
		warning('Selected echo number exceeds the number of echos in the protocol.');
		grabEcho = S.numEchos;
		fprintf(1,'Will grab echo #%i of %i\n', grabEcho, S.numEchos);
	else
		grabEcho = 1;
	end

	% Prepare smoothing kernels based on configuration and voxel size
	if cfg.smoothFWHM > 0
		[smKernX, smKernY, smKernZ, smOff] = ft_omri_smoothing_kernel(cfg.smoothFWHM, S.voxdim);
		smKern = convn(smKernX'*smKernY, reshape(smKernZ, 1, 1, length(smKernZ)));
	else
		smKernX = [];
		smKernY = [];
		smKernZ = [];
		smKern  = [];
		smOff   = [0 0 0];
	end

	niftiOut = [];
	niftiOut.dim = S.voxels;
	niftiOut.pixdim = S.voxdim;
	niftiOut.slice_duration = S.TR / S.vz;
	niftiOut.srow_x = S.mat0(1,:);
	niftiOut.srow_y = S.mat0(2,:);
	niftiOut.srow_z = S.mat0(3,:);

	hdrOut = [];
	hdrOut.nSamples = 0;
	hdrOut.Fs = hdr.Fs;
	if cfg.correctMotion
		hdrOut.nChans = prod(S.voxels) + 6;
	else
		hdrOut.nChans = prod(S.voxels);
	end
	hdrOut.nifti_1 = niftiOut; %encode_nifti1(niftiOut);

	ft_write_data(cfg.output, single([]), 'header', hdrOut);

	% reset motion estimates
	motEst = [];

	% store current info structure in history
	numTrial  = numTrial + 1;
	history(numTrial).S = S;
	disp(S)

	% Wait for numDummy scans (and drop them)
	fprintf(1,'Waiting for %i dummy samples to come in...\n', cfg.numDummy);
	while 1
		threshold = struct('nsamples', cfg.numDummy * S.numEchos);
		newNum = ft_poll_buffer(cfg.input, threshold, 500);
		if newNum.nsamples >= cfg.numDummy*S.numEchos
		   break
		end
		pause(0.01);
	end

	fprintf(1,'Starting to process\n');
	numTotal  = cfg.numDummy * S.numEchos;
	numProper = 0;

	% Loop this as long as the experiment runs with the same protocol (= data keeps coming in)
	while 1
		% determine number of samples available in buffer / wait for more than numTotal
		threshold.nsamples = numTotal + S.numEchos - 1;
		newNum = ft_poll_buffer(cfg.input, threshold, 500);

		if newNum.nsamples < numTotal
			% scanning seems to have stopped - re-read header to continue with next trial
			break;
		end
		if newNum.nsamples < numTotal + S.numEchos
			% timeout -- go back to start of (inner) loop
		    continue;
		end

		% this is necessary for ft_read_data
		hdr.nSamples = newNum.nsamples;

		index = (cfg.numDummy + numProper) * S.numEchos + grabEcho;
		fprintf('\nTrying to read %i. proper scan at sample index %d\n', numProper+1, index);
		GrabSampleT = tic;

		try
			% read data from buffer (only the last scan)
			dat = ft_read_data(cfg.input, 'header', hdr, 'begsample', index, 'endsample', index);
		catch
			warning('Problems reading data - going back to poll operation...');
			continue;
		end

		numProper = numProper + 1;
		numTotal  = numTotal + S.numEchos;

		rawScan = single(reshape(dat, S.voxels));

		%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
		% motion correction
		%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
		if cfg.correctMotion
			doneHere = 0;
			if numProper == 1
				RRM = [];
				for i=1:length(history)
					if isequal(history(i).S, S)
						fprintf(1,'Will realign scans to reference model from trial %i...\n', i);
						% protocol the same => re-use realignment reference
						RRM = history(i).RRM;
						break;
					end
				end

				% none found - setup new one
				if isempty(RRM)
					flags = struct('mat', S.mat0);
					fprintf(1,'Setting up first num-dummy scan as reference volume...\n');
					RRM = ft_omri_align_init(rawScan, flags);
					history(numTrial).RRM = RRM;
					curSixDof = zeros(1,6);
					motEst = zeros(1,6);
					procScan = single(rawScan);
					doneHere = 1;
				end
			end

			if ~doneHere
				fprintf('%-30s','Registration...');
				tic;
				[RRM, M, Mabs, procScan] = ft_omri_align_scan(RRM, rawScan);
				toc
				curSixDof = hom2six(M);
				motEst = [motEst; curSixDof.*[1 1 1 180/pi 180/pi 180/pi]];
			end
		else
			procScan = single(rawScan);
			motEst = [motEst; zeros(1,6)];
		end

		%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
		% slice timing correction
		%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
		if cfg.correctSliceTime
			if numProper == 1
				fprintf(1,'Initialising slice-time correction model...\n');
				STM = ft_omri_slice_time_init(procScan, S.TR, S.deltaT);
			else
				fprintf('%-30s','Slice time correction...');
				tic;
				[STM, procScan] = ft_omri_slice_time_apply(STM, procScan);
				toc
			end
		end

		%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
		% smoothing
		%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
		if cfg.smoothFWHM > 0
			fprintf('%-30s','Smoothing...');
			tic;
			% MATLAB convolution
			%Vsm = convn(procScan,smKern);
			%procScan = Vsm((1+smOff(1)):(end-smOff(1)), (1+smOff(2)):(end-smOff(2)), (1+smOff(3)):(end-smOff(3)));

			% specialised MEX file
			procScan = ft_omri_smooth_volume(single(procScan), smKernX, smKernY, smKernZ);

			toc
		end
		%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
		% done with pre-processing, write output
		%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

		if cfg.correctMotion
			procSample = [single(procScan(:)) ; single(curSixDof')];
		else
			procSample = single(procScan(:));
		end

		ft_write_data(cfg.output, procSample, 'header', hdrOut, 'append', true);

		%evr.sample = numProper;
		%ft_write_event(cfg.output, evr);

		fprintf('Done -- total time = %f\n', toc(GrabSampleT));

		subplot(4,1,1);
		plot(motEst(:,1:3));
		subplot(4,1,2);
		plot(motEst(:,4:6));

		subplot(4,1,3);
		slcImg = reshape(dat, [S.vx	S.vy*S.vz]);
		imagesc(slcImg);
		colormap(gray);

		subplot(4,1,4);
		slcImg = reshape(procScan, [S.vx	S.vy*S.vz]);
		imagesc(slcImg);
		colormap(gray);

		% force Matlab to update the figure
		drawnow
	end % while true
end


text:
require "rubocop"
require_relative "has_sigil"

module RuboCop
  module Cop
    module Sorbet
      # This cop makes the Sorbet `true` sigil mandatory in all files.
      class TrueSigil < HasSigil
        def minimum_strictness
          "true"
        end
      end
    end
  end
end


text:
=head1 LICENSE

Copyright [1999-2014] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute

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.

=cut

=head1 CONTACT

 Please email comments or questions to the public Ensembl
 developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.

 Questions may also be sent to the Ensembl help desk at
 <http://www.ensembl.org/Help/Contact>.

=cut

# Ensembl module for Bio::EnsEMBL::Variation::IndividualGenotype
#
#

=head1 NAME

Bio::EnsEMBL::Variation::IndividualGenotype- Module representing the genotype
of a single individual at a single position

=head1 SYNOPSIS

    print $genotype->variation()->name(), "\n";
    print $genotype->allele1(), '/', $genotype->allele2(), "\n";
    print $genotype->individual()->name(), "\n";

=head1 DESCRIPTION

This is a class representing the genotype of a single diploid individual at
a specific position

=head1 METHODS

=cut

use strict;
use warnings;

package Bio::EnsEMBL::Variation::IndividualGenotypeFeature;

use Bio::EnsEMBL::Variation::IndividualGenotype;
use Bio::EnsEMBL::Feature;
use Bio::EnsEMBL::Utils::Argument qw(rearrange);
use Bio::EnsEMBL::Utils::Exception qw(throw deprecate warning);

use vars qw(@ISA);

@ISA = qw(Bio::EnsEMBL::Variation::IndividualGenotype Bio::EnsEMBL::Feature);

=head2 new

  Arg [-adaptor] :
    Bio::EnsEMBL::Variation::DBSQL::IndividualAdaptor
  Arg [-START] :
    see superclass constructor
  Arg [-END] :
    see superclass constructor
  Arg [-STRAND] :
    see superclass constructor
  Arg [-SLICE] :
    see superclass constructor
  Arg [-allele1] :
    string - One of the two alleles defining this genotype
  Arg [-allele2] :
    string - One of the two alleles defining this genotype
  Arg [-variation] :
    Bio::EnsEMBL::Variation::Variation - The variation associated with this
    genotype
  Arg [-individual] :
    Bio::EnsEMBL::Individual - The individual this genotype is for.
  Example    : $ind_genotype = Bio:EnsEMBL::Variation::IndividualGenotype->new(
					-start      => 100,
					-end        => 100,
					-strand     => 1,
					-slice      => $slice,
					-genotype   => ['A','T'],
					-variation  => $variation,
					-individual => $ind
				);
  Description: Constructor.  Instantiates an IndividualGenotype object.
  Returntype : Bio::EnsEMBL::Variation::IndividualGenotype
  Exceptions : throw on bad argument
  Caller     : general
  Status     : Stable

=cut

sub new {
	my $caller = shift;
	my $class = ref($caller) || $caller;

	my $self = $class->SUPER::new(@_);

	my ($adaptor, $allele1, $allele2, $var, $var_id, $ind) =
	rearrange([qw(adaptor genotype variation _variation_id individual)],@_);

	if(defined($var) && (!ref($var) || !$var->isa('Bio::EnsEMBL::Variation::Variation'))) {
		throw("Bio::EnsEMBL::Variation::Variation argument expected");
	}

	if(defined($ind) && (!ref($ind) || !$ind->isa('Bio::EnsEMBL::Variation::Individual'))) {
		throw("Bio::EnsEMBL::Variation::Individual argument expected");
	}

	$self->{'adaptor'} = $adaptor;
	$self->{'allele1'} = $allele1;
	$self->{'allele2'} = $allele2;
	$self->{'individual'} = $ind;
	$self->{'variation'} = $var;
	$self->{'_variation_id'} = $var_id;

	return $self;
}

1;


text:
class CreateServices < ActiveRecord::Migration[5.0]
  def change
    enable_extension "hstore"
    create_table :services do |t|
      t.string :image
      t.string :container_id
      t.hstore :environment_variables, default: {}
      t.integer :port

      t.timestamps
    end
  end
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Cat. Lich. Univers. 2: 640 (1923)

#### Original name
Thelotrema subterebrans Nyl.

### Remarks
null