text:
const GET_USER = new Promise((resolve, reject) => {
    firebase.auth().onAuthStateChanged(function (user) {
        let currentUser = firebase.auth().currentUser;

        if (currentUser) {
            resolve(currentUser);
        } else {
            let provider = new firebase.auth.GoogleAuthProvider();

            firebase.auth().signInWithPopup(provider).then(function (result) {
                resolve(result.user);
            });
        }
    });
})


text:
package com.github;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

import com.wordnik.swagger.annotations.ApiModel;
import com.wordnik.swagger.annotations.ApiModelProperty;

@XmlRootElement(name = "version")
@XmlAccessorType(XmlAccessType.FIELD)
@ApiModel(value = "A pet is a person's best friend" )
public class Container {

	@XmlElement
	@ApiModelProperty(value = "name", required=true)
	private String name;
	@XmlElement
	@ApiModelProperty(value = "value", required=true)
	private String value;

	public Container() {
	}

	public Container(String name, String value) {
		this.name = name;
		this.value = value;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}

}

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) 2012 Ecma International.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
es5id: 15.2.3.2-1
description: Object.getPrototypeOf returns Number.prototype if 'O' is a number
---*/

assert.sameValue(Object.getPrototypeOf(0), Number.prototype, 'Object.getPrototypeOf(0)');


text:
namespace Shuttle.Core.Infrastructure
{
    public interface IRegisterEventBefore
    {
        void Register<TPipelineEvent>() where TPipelineEvent : IPipelineEvent, new();
        void Register(IPipelineEvent pipelineEventToRegister);
    }
}


text:
namespace RGM
{

/// Read xml file
class XMLData
{
public:
    struct XMLNode {
        XMLNode();
        XMLNode(char* _name, char* _value);

        ~XMLNode();

        XMLNode* Clone();

        void SetName(char* _name);
        void SetValue(char* _value);
        void SetChildren(std::vector<XMLNode*>& _children);
        void AddChild(XMLNode* pNode);

        char* _name;
        char* _value;
        int _childCount;
        XMLNode* _parent;
        XMLNode** _children;
    };

    XMLData();

    void Clear();

    void ReadFromFile(std::string fileName, std::string firstNodeName);
    void ReadFromString(char* str, std::string firstNodeName);
    void WriteToFile(std::string fileName);

    XMLNode* GetNode(std::string path);
    XMLNode* GetNode(std::string path, XMLNode* pNode);
    XMLNode* GetRootNode();

    XMLNode* FindFirst(std::string path, std::string childName, std::string childValue);
    XMLNode* FindFirst(std::string path, std::string childName, std::string field, std::string query);
    XMLNode* FindFirst(std::string basePath, std::string childName, std::string field1, std::string query1, std::string field2, std::string query2);

    std::vector<XMLNode *> GetNodes(const std::string& path);
    std::vector<XMLNode *> GetNodes(const std::string& path, XMLNode* pNode);

    std::string GetNodeName(XMLNode* pNode);
    std::string GetString(std::string path);
    int GetInt(std::string path);
    float GetFloat(std::string path);
    bool GetBoolean(std::string path);

    std::string GetString(XMLNode* pNode);
    int   GetInt(XMLNode* pNode);
    float GetFloat(XMLNode* pNode);
    bool  GetBoolean(XMLNode* pNode);

    std::string GetString(std::string path, XMLNode* pNode);
    int   GetInt(std::string path, XMLNode* pNode);
    float GetFloat(std::string path, XMLNode* pNode);
    bool  GetBoolean(std::string path, XMLNode* pNode);

    void RemoveNode(XMLNode* pNode);
    void InsertNode(XMLNode* pParent, XMLNode* pNode);

private:
    XMLNode* ReadNode(rapidxml::xml_node<>* node);
    void     WriteNode(XMLNode* node, std::ofstream& ofs);

    XMLNode* _pRootNode;
};

} // namespace RGM

#endif // RGM_XMLREADER_HPP_


text:
ChromeWebRtcLogMessageDelegate::ChromeWebRtcLogMessageDelegate(
    const scoped_refptr<base::MessageLoopProxy>& io_message_loop,
    WebRtcLoggingMessageFilter* message_filter)
    : io_message_loop_(io_message_loop),
      message_filter_(message_filter) {
  content::InitWebRtcLoggingDelegate(this);
}

ChromeWebRtcLogMessageDelegate::~ChromeWebRtcLogMessageDelegate() {
  DCHECK(CalledOnValidThread());
}

void ChromeWebRtcLogMessageDelegate::LogMessage(const std::string& message) {
  if (!CalledOnValidThread()) {
    io_message_loop_->PostTask(
        FROM_HERE, base::Bind(
            &ChromeWebRtcLogMessageDelegate::LogMessage,
            base::Unretained(this),
            message));
    return;
  }

  if (circular_buffer_) {
    circular_buffer_->Write(message.c_str(), message.length());
    const char eol = '\n';
    circular_buffer_->Write(&eol, 1);
  }
}

void ChromeWebRtcLogMessageDelegate::OnFilterRemoved() {
  DCHECK(CalledOnValidThread());
  message_filter_ = NULL;
}

void ChromeWebRtcLogMessageDelegate::OnStartLogging(
    base::SharedMemoryHandle handle,
    uint32 length) {
  DCHECK(CalledOnValidThread());
  DCHECK(!shared_memory_ && !circular_buffer_);

  shared_memory_.reset(new base::SharedMemory(handle, false));
  CHECK(shared_memory_->Map(length));
  circular_buffer_.reset(
      new PartialCircularBuffer(shared_memory_->memory(),
                                length,
                                length / 2,
                                true));

  content::InitWebRtcLogging();
}

void ChromeWebRtcLogMessageDelegate::OnStopLogging() {
  DCHECK(CalledOnValidThread());
  DCHECK(shared_memory_ && circular_buffer_);

  circular_buffer_.reset(NULL);
  shared_memory_.reset(NULL);
  if (message_filter_)
    message_filter_->LoggingStopped();
}


text:
<?php

namespace Yoda\EventBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class EventType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name')
            ->add('time', 'datetime')
            ->add('location')
            ->add('details')
        ;
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Yoda\EventBundle\Entity\Event'
        ));
    }
}


text:
package com.amazonaws.services.simplesystemsmanagement.model.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.simplesystemsmanagement.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * UpdateMaintenanceWindowResult JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class UpdateMaintenanceWindowResultJsonUnmarshaller implements Unmarshaller<UpdateMaintenanceWindowResult, JsonUnmarshallerContext> {

    public UpdateMaintenanceWindowResult unmarshall(JsonUnmarshallerContext context) throws Exception {
        UpdateMaintenanceWindowResult updateMaintenanceWindowResult = new UpdateMaintenanceWindowResult();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return updateMaintenanceWindowResult;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("WindowId", targetDepth)) {
                    context.nextToken();
                    updateMaintenanceWindowResult.setWindowId(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("Name", targetDepth)) {
                    context.nextToken();
                    updateMaintenanceWindowResult.setName(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("Schedule", targetDepth)) {
                    context.nextToken();
                    updateMaintenanceWindowResult.setSchedule(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("Duration", targetDepth)) {
                    context.nextToken();
                    updateMaintenanceWindowResult.setDuration(context.getUnmarshaller(Integer.class).unmarshall(context));
                }
                if (context.testExpression("Cutoff", targetDepth)) {
                    context.nextToken();
                    updateMaintenanceWindowResult.setCutoff(context.getUnmarshaller(Integer.class).unmarshall(context));
                }
                if (context.testExpression("AllowUnassociatedTargets", targetDepth)) {
                    context.nextToken();
                    updateMaintenanceWindowResult.setAllowUnassociatedTargets(context.getUnmarshaller(Boolean.class).unmarshall(context));
                }
                if (context.testExpression("Enabled", targetDepth)) {
                    context.nextToken();
                    updateMaintenanceWindowResult.setEnabled(context.getUnmarshaller(Boolean.class).unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return updateMaintenanceWindowResult;
    }

    private static UpdateMaintenanceWindowResultJsonUnmarshaller instance;

    public static UpdateMaintenanceWindowResultJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new UpdateMaintenanceWindowResultJsonUnmarshaller();
        return instance;
    }
}


text:
var Game = Game || {};

Game.About = function (game) {};

Game.About.prototype = (function () {
    var teamMembersText = {},
        teamMembers = [
            { nickname: 'dentia', participated: 'participated' },
            { nickname: 'alara.kalama', participated: 'participated' },
            { nickname: 'Stev3n', participated: 'participated' },
            { nickname: 'Rodoteia.Yordanova', participated: 'participated' },
            { nickname: 'Bizuuu', participated: 'participated' },
            { nickname: 'ahansb', participated: 'participated' },
            { nickname: 'Boyan1912', participated: 'notParticipated' }
        ],
        music;

    function getRandom (max) {
        return Math.floor((Math.random() * max) + 1);
    }

    function addTeamMember (member) {
        var x = getRandom(CONST.game.world.width - 200),
            y = getRandom(CONST.game.world.height - 100);
        teamMembersText[member] = this.game.add.bitmapText(x, y, member.participated, member.nickname, 70);
        teamMembersText[member].inputEnabled = true;
        teamMembersText[member].input.enableDrag();
    }

    function loadMembers () {
        for(var ind = 0, len = teamMembers.length; ind < len; ind += 1){
            addTeamMember(teamMembers[ind]);
        }
    }

    var about = {
        preload: function () {
            this.game.load.image('github', 'imgs/github.png');
            this.game.load.image('menu', 'imgs/smallerMenu.png');
            this.game.load.bitmapFont('participated', 'fonts/greenBitmap_noStroke.png', 'fonts/greenBitmap_noStroke.fnt');
            this.game.load.bitmapFont('notParticipated', 'fonts/redBitmap_noStroke.png', 'fonts/redBitmap_noStroke.fnt');
            this.game.load.audio('helpMenuMusic', ['audio/menuHelpTheme.mp3']);
        },
        create: function () {
            music = this.game.add.audio('helpMenuMusic');
            music.play();
            this.game.add.button(5, 5, 'github', this.redirectToGithub, this.game, 1, 0, 2);
            this.game.add.button(350, 540, 'menu', this.returnToMenu, this.game, 1, 0, 2);

            loadMembers();
        },
        redirectToGithub: function(){
            console.log('github');
            window.open("https://github.com/RoseWaterRickey", "_blank");
        },
        returnToMenu: function () {
            music.stop();
            this.state.start('Menu');
        }
    };

    return about;
}());


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace De.Osthus.Ambeth.Appendable
{
    public class StreamWriterAppendable : IAppendable
    {
        protected StreamWriter streamWriter;

        public StreamWriterAppendable(StreamWriter streamWriter)
        {
            this.streamWriter = streamWriter;
        }

        public IAppendable Append(String value)
        {
            streamWriter.Write(value);
            return this;
        }

        public IAppendable Append(char value)
        {
            streamWriter.Write(value);
            return this;
        }
    }
}


text:
extern "C" {

static void wxSocket_Motif_Input(XtPointer data, int *WXUNUSED(fid),
                                 XtInputId *WXUNUSED(id))
{
    wxFDIOHandler * const handler = static_cast<wxFDIOHandler *>(data);

    handler->OnReadWaiting();
}

static void wxSocket_Motif_Output(XtPointer data, int *WXUNUSED(fid),
                                  XtInputId *WXUNUSED(id))
{
    wxFDIOHandler * const handler = static_cast<wxFDIOHandler *>(data);

    handler->OnWriteWaiting();
}

}

class MotifFDIOManager : public wxFDIOManager
{
public:
    virtual int AddInput(wxFDIOHandler *handler, int fd, Direction d)
    {
        return XtAppAddInput
               (
                    wxGetAppContext(),
                    fd,
                    (XtPointer)(d == OUTPUT ? XtInputWriteMask
                                            : XtInputReadMask),
                    d == OUTPUT ? wxSocket_Motif_Output
                                : wxSocket_Motif_Input,
                    handler
               );
    }

    virtual void
    RemoveInput(wxFDIOHandler* WXUNUSED(handler), int fd, Direction WXUNUSED(d))
    {
        XtRemoveInput(fd);
    }
};

wxFDIOManager *wxGUIAppTraits::GetFDIOManager()
{
    static MotifFDIOManager s_manager;
    return &s_manager;
}

#endif // wxUSE_SOCKETS


text:
"""
Usage:
  python shell.py <access_token_file>

Description:
  Starts a shell with a `user` object
  This makes it easier to start playing
  with the Flickr API.
"""
from __future__ import print_function

import flickr_api
import sys
import warnings

try:
    import IPython
except ImportError:
    """Not making iPython a dependency because
    this sample module is not core functionality.
    """
    ipython_required = 'iPython is required; pip install ipython.' \
        '\n  Run "pip install ipython" before using this sample module.'
    warnings.warn(ipython_required)

def main():
    """Start shell with `user` object
    """
    ACCESS_TOKEN = sys.argv[1]
    flickr_api.set_auth_handler(ACCESS_TOKEN)

    user_namespace = {
        'flickr_api': flickr_api,
        'user': flickr_api.test.login()}

    # iPython uses `sys.argv`
    # so we're resetting it
    sys.argv = sys.argv[:1]

    IPython.start_ipython(user_ns=user_namespace)

if __name__ == '__main__':
    if len(sys.argv) > 1:
        main()
    else:
        print (__doc__)


text:
https://github.com/kward/shunit2

This release contains bug fixes and enhancements. It is the first release since moving to GitHub. Users can now clone the latest version at any time.

See the `CHANGES-2.1.md` file for a full list of changes.

## New Features

Colorized output, based on popular demand. shUnit2 output is now colorized based on the result of the asserts.

## Changes and Enhancements

With the move to GitHub, the shUnit2 unit tests are run on every commit using the [Travis CI][TravisCI] continuous integration framework. Additionally, all code is run through [ShellCheck](http:/www.shellcheck.net/) on every commit.

[TravisCI]: https://travis-ci.org/kward/shunit2

Shell commands in shUnit2 are prefixed with '\' so that they can be stubbed in tests.

## Bug Fixes

shUnit2 no longer exits with an 'OK' result if there were syntax errors due to incorrect usage of the assert commands.

## Deprecated Features

None.

## Known Bugs and Issues

Zsh requires the `shwordsplit` option to be set. See the documentation for examples of how to do this.

Line numbers in assert messages do not work properly with BASH 2.x.

The Bourne shell of Solaris, BASH 2.x, and Zsh 3.0.x do not properly catch the
SIGTERM signal. As such, shell interpreter failures due to such things as
unbound variables cannot be caught. (See `shunit_test_misc.sh`)

## Tested Platforms

Continuous integration testing is provided by
[Travis CI](https://travis-ci.org/).

https://travis-ci.org/github/kward/shunit2

Tested OSes:

- Linux
- macOS

Tested shells:

- /bin/sh
- ash
- bash
- dash
- ksh
- pdksh
- zsh


text:
	<button class="menutoggle" id="menutoggle"></button>

			X1 Marketing Library
			X1 Services
			X1 Info
			X1 Home

				Successful Marketing Ideas

                Marketing Reading Suggestions
				Marketing Videos
                Effective Marketing Ingredients                X1 Lunch & Learn Events

                X1 Picks

                X1 Newsletter

            				Direct Marketing Strategy

				Copy Writing, Design & Branding
			Photography & Video
Printing & Direct Mail
                Fulfilment
				Web-2-Promotion
                Multipurpose Marketing Products
                Promotional Items

				Contacts
                Testimonials

                X1 Design Gallery

				Article of the Month
				Video of the Month
				Quote of the Month


text:
{-# OPTIONS_GHC -Wall                      #-}
{-# OPTIONS_GHC -fno-warn-name-shadowing   #-}
{-# OPTIONS_GHC -fno-warn-type-defaults    #-}
{-# OPTIONS_GHC -fno-warn-unused-do-bind   #-}
{-# OPTIONS_GHC -fno-warn-missing-methods  #-}
{-# OPTIONS_GHC -fno-warn-orphans          #-}

{-# LANGUAGE DataKinds                  #-}
{-# LANGUAGE DeriveDataTypeable         #-}
{-# LANGUAGE FlexibleContexts           #-}
{-# LANGUAGE FlexibleInstances          #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE KindSignatures             #-}
{-# LANGUAGE MultiParamTypeClasses      #-}
{-# LANGUAGE Rank2Types                 #-}
{-# LANGUAGE RankNTypes                 #-}
{-# LANGUAGE ScopedTypeVariables        #-}
{-# LANGUAGE StandaloneDeriving         #-}
{-# LANGUAGE TypeFamilies               #-}
{-# LANGUAGE TypeOperators              #-}
{-# LANGUAGE UndecidableInstances       #-}
{-# LANGUAGE MagicHash                  #-}

module Main (main) where

import Test.HUnit hiding (Test)
import Test.QuickCheck hiding ((.&.))
import Test.Framework ( Test, defaultMain )
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Test.Framework.Providers.HUnit
import Data.Word.N
import Data.Word.N.Util
import Data.Bits
import Data.Binary.Get
import Data.Binary.Put
import qualified Data.ByteString.Lazy as LZ

import GHC.TypeLits
import Data.Word

-- Most of these properties come from the package 'largeword' (on hackage).
-- This is because that package and this one expose pretty much the same api.

encode' :: (8 :|: n) => W n -> LZ.ByteString
encode' = disassembleR (runPut . putWord8 . (fromIntegral :: W 8 -> Word8))

decode' :: (8 :|: n) => LZ.ByteString -> W n
decode' = runGet (assembleR (fmap (fromIntegral :: Word8 -> W 8) getWord8))

instance (8 :|: n) => Arbitrary (W n) where
   arbitrary = assembleL $ fmap (fromIntegral :: (Word8 -> W 8)) arbitrary

pShiftRightShiftLeft :: W 128 -> Bool
pShiftRightShiftLeft x = shiftR (shiftL x 1) 1 == x .&. (fromInteger ((2^127) - 1))

u1 :: Assertion
u1 = shiftR (18446744073709551616  :: W 128) 64  @?= 1

pQuotRem :: W 256 -> Bool
pQuotRem x = rx == fromInteger ry
  where
    (_qx, rx) = quotRem x 16
    (_qy, ry) = quotRem ((fromIntegral x) :: Integer) 16

encodeDecode :: (8 :|: n) => W n -> Bool
encodeDecode word = decode' encoded == word
  where
    encoded = encode' word
    {-# NOINLINE encoded #-}

correctEncoding :: Assertion
correctEncoding = (decode' . LZ.pack)
    [0,0,0,0,0,0,0,0,50,89,125,125,237,119,73,240
        ,217,12,178,101,235,8,44,221,50,122,244,125,115,181,239,78]
    @?=
    (1234567891234567891234567812345678123456781234567812345678 :: W 256)

pRotateLeftRight :: W 256 -> Bool
pRotateLeftRight x = rotate (rotate x 8) (-8) == x

pRepeatedShift :: Int -> Property
pRepeatedShift n =
  (n >= 0) && (n <= 1024) ==>
  (((iterate (`shift` 8) (1::W 192))!!n) == shift (1::W 192) (n*8))

pRepeatedShift' :: Int -> Property
pRepeatedShift' n =
  (n >= 0) && (n <= 1024) ==>
  (((iterate (`shift` 8) a)!!n) == shift a (n*8))
  where a :: W 192
        a = 0x0123456789ABCDEFFEDCBA98765432100011223344556677

pRepeatedShift160 :: Int -> Property
pRepeatedShift160 n =
  (n >= 0) && (n <= 1024) ==>
  (((iterate (`shift` 8) (1::W 160))!!n) == shift (1::W 160) (n*8))

u2 :: Assertion
u2 = (2 :: W (256 + 128)) ^ 254 @?=
     (fromInteger (2 :: Integer) ^ 254)

u3 :: Assertion
u3 = rotate (rotate ((2^255) :: W 256) (1)) (-1) @?=
     ((2^255) :: W 256)

u4 :: Assertion
u4 = shift (0x0123456789ABCDEFFEDCBA98765432100011223344556677 :: W 192) 80 @?=
           (0xBA9876543210001122334455667700000000000000000000 :: W 192)

u5 :: Assertion
u5 = shift (0x112233445566778899AABBCC :: W 96) 40 @?=
           (0x66778899AABBCC0000000000 :: W 96)

u6 :: Assertion
u6 = rotate ((2^95) :: W 96) (1) @?= 1

tests :: [Test]
tests =
    [ testProperty "largeword shift left then right" pShiftRightShiftLeft
    , testProperty "largeword quotRem by 16" pQuotRem
    , testProperty "largeword rotate left then right" pRotateLeftRight
    , testProperty "largeword repeated shift vs single shift" pRepeatedShift
    , testProperty "largeword repeated shift vs single shift" pRepeatedShift'
    , testProperty "largeword repeated shift vs single shift" pRepeatedShift160
    , testCase "largeword shift 2^64 by 2^64" u1
    , testCase "largeword exponentiation 2^254" u2
    , testCase "largeword rotation by 1" u3
    , testCase "largeword shift by 80" u4
    , testCase "largeword shift by 40" u5
    , testCase "largeword rotate by 1" u6
    , testCase "big-endian encoding" correctEncoding
    , testProperty "Word96 encode/decode loop"  (encodeDecode::W 96 -> Bool)
    , testProperty "Word128 encode/decode loop" (encodeDecode::W 128 -> Bool)
    , testProperty "Word160 encode/decode loop" (encodeDecode::W 160 -> Bool)
    , testProperty "Word192 encode/decode loop" (encodeDecode::W 192 -> Bool)
    , testProperty "Word224 encode/decode loop" (encodeDecode::W 224 -> Bool)
    , testProperty "Word256 encode/decode loop" (encodeDecode::W 256 -> Bool)
      ]

main :: IO ()
main = defaultMain tests


text:
<?php /* $Id$ */
$text = 'I am the very model of a modern major general, I\'ve information vegetable, animal, and mineral.';

$fp = fopen('php://stdout', 'w');
stream_filter_append($fp, 'zlib.deflate', STREAM_FILTER_WRITE);
stream_filter_append($fp, 'convert.base64-encode', STREAM_FILTER_WRITE);
fwrite($fp, $text);
fclose($fp);

?>


text:
const {promisify} = require('util');
const fs = require('fs');
const path = require('path');
const del = require('del');
const imageminJpegtran = require('imagemin-jpegtran');
const imageminWebp = require('imagemin-webp');
const imageminSvgo = require('imagemin-svgo');
const isJpg = require('is-jpg');
const makeDir = require('make-dir');
const tempy = require('tempy');
const test = require('ava');
const imagemin = require('.');

const readFile = promisify(fs.readFile);
const writeFile = promisify(fs.writeFile);

test('optimize a file', async t => {
	const buffer = await readFile(path.join(__dirname, 'fixture.jpg'));
	const files = await imagemin(['fixture.jpg'], {
		plugins: [imageminJpegtran()]
	});

	t.is(files[0].destinationPath, undefined);
	t.true(files[0].data.length < buffer.length);
	t.true(isJpg(files[0].data));
});

test('optimize a buffer', async t => {
	const buffer = await readFile(path.join(__dirname, 'fixture.jpg'));
	const data = await imagemin.buffer(buffer, {
		plugins: [imageminJpegtran()]
	});

	t.true(data.length < buffer.length);
	t.true(isJpg(data));
});

test('output error on corrupt images', async t => {
	await t.throwsAsync(imagemin(['fixture-corrupt.jpg'], {
		plugins: [imageminJpegtran()]
	}), {message: /Corrupt JPEG data/});
});

test('throw on wrong input', async t => {
	await t.throwsAsync(imagemin('foo'), {message: /Expected an `Array`, got `string`/});
	await t.throwsAsync(imagemin.buffer('foo'), {message: /Expected a `Buffer`, got `string`/});
});

test('return original file if no plugins are defined', async t => {
	const buffer = await readFile(path.join(__dirname, 'fixture.jpg'));
	const files = await imagemin(['fixture.jpg']);

	t.is(files[0].destinationPath, undefined);
	t.deepEqual(files[0].data, buffer);
	t.true(isJpg(files[0].data));
});

test('return original buffer if no plugins are defined', async t => {
	const buffer = await readFile(path.join(__dirname, 'fixture.jpg'));
	const data = await imagemin.buffer(buffer);

	t.deepEqual(data, buffer);
	t.true(isJpg(data));
});

test('return processed buffer even it is a bad optimization', async t => {
	const buffer = await readFile(path.join(__dirname, 'fixture.svg'));
	t.false(buffer.includes('http://www.w3.org/2000/svg'));

	const data = await imagemin.buffer(buffer, {
		plugins: [
			imageminSvgo({
				plugins: [{
					addAttributesToSVGElement: {
						attributes: [{
							xmlns: 'http://www.w3.org/2000/svg'
						}]
					}
				}]
			})
		]
	});

	t.true(data.includes('xmlns="http://www.w3.org/2000/svg"'));
	t.true(data.length > buffer.length);
});

test('output at the specified location', async t => {
	const temporary = tempy.directory();
	const destinationTemporary = tempy.directory();
	const buffer = await readFile(path.join(__dirname, 'fixture.jpg'));

	await makeDir(temporary);
	await writeFile(path.join(temporary, 'fixture.jpg'), buffer);

	const files = await imagemin(['fixture.jpg', `${temporary}/*.jpg`], {
		destination: destinationTemporary,
		plugins: [imageminJpegtran()]
	});

	t.true(fs.existsSync(files[0].destinationPath));
	t.true(fs.existsSync(files[1].destinationPath));

	await del([temporary, destinationTemporary], {force: true});
});

test('set webp ext', async t => {
	const temporary = tempy.file();
	const files = await imagemin(['fixture.jpg'], {
		destination: temporary,
		plugins: [imageminWebp()]
	});

	t.is(path.extname(files[0].destinationPath), '.webp');
	await del(temporary, {force: true});
});

test('ignores junk files', async t => {
	const temporary = tempy.directory();
	const destinationTemporary = tempy.directory();
	const buffer = await readFile(path.join(__dirname, 'fixture.jpg'));

	await makeDir(temporary);
	await writeFile(path.join(temporary, '.DS_Store'), '');
	await writeFile(path.join(temporary, 'Thumbs.db'), '');
	await writeFile(path.join(temporary, 'fixture.jpg'), buffer);

	await t.notThrowsAsync(imagemin([`${temporary}/*`], {
		destination: destinationTemporary,
		plugins: [imageminJpegtran()]
	}));

	t.true(fs.existsSync(path.join(destinationTemporary, 'fixture.jpg')));
	t.false(fs.existsSync(path.join(destinationTemporary, '.DS_Store')));
	t.false(fs.existsSync(path.join(destinationTemporary, 'Thumbs.db')));

	await del([temporary, destinationTemporary], {force: true});
});

test('glob option', async t => {
	const files = await imagemin(['fixture.jpg'], {
		glob: false,
		plugins: [imageminJpegtran()]
	});

	t.true(isJpg(files[0].data));
});


text:
module.exports = function (chai, util) {

  /*!
   * Chai dependencies.
   */

  var Assertion = chai.Assertion
    , flag = util.flag;

  /*!
   * Module export.
   */

  /**
   * ### assert(expression, message)
   *
   * Write your own test expressions.
   *
   *     assert('foo' !== 'bar', 'foo is not bar');
   *     assert(Array.isArray([]), 'empty arrays are arrays');
   *
   * @param {Mixed} expression to test for truthiness
   * @param {String} message to display on error
   * @name assert
   * @api public
   */

  var assert = chai.assert = function (express, errmsg) {
    var test = new Assertion(null);
    test.assert(
        express
      , errmsg
      , '[ negation message unavailable ]'
    );
  };

  /**
   * ### .fail(actual, expected, [message], [operator])
   *
   * Throw a failure. Node.js `assert` module-compatible.
   *
   * @name fail
   * @param {Mixed} actual
   * @param {Mixed} expected
   * @param {String} message
   * @param {String} operator
   * @api public
   */

  assert.fail = function (actual, expected, message, operator) {
    throw new chai.AssertionError({
        actual: actual
      , expected: expected
      , message: message
      , operator: operator
      , stackStartFunction: assert.fail
    });
  };

  /**
   * ### .ok(object, [message])
   *
   * Asserts that `object` is truthy.
   *
   *     assert.ok('everything', 'everything is ok');
   *     assert.ok(false, 'this will fail');
   *
   * @name ok
   * @param {Mixed} object to test
   * @param {String} message
   * @api public
   */

  assert.ok = function (val, msg) {
    new Assertion(val, msg).is.ok;
  };

  /**
   * ### .equal(actual, expected, [message])
   *
   * Asserts non-strict equality (`==`) of `actual` and `expected`.
   *
   *     assert.equal(3, '3', '== coerces values to strings');
   *
   * @name equal
   * @param {Mixed} actual
   * @param {Mixed} expected
   * @param {String} message
   * @api public
   */

  assert.equal = function (act, exp, msg) {
    var test = new Assertion(act, msg);

    test.assert(
        exp == flag(test, 'object')
      , 'expected #{this} to equal #{exp}'
      , 'expected #{this} to not equal #{act}'
      , exp
      , act
    );
  };

  /**
   * ### .notEqual(actual, expected, [message])
   *
   * Asserts non-strict inequality (`!=`) of `actual` and `expected`.
   *
   *     assert.notEqual(3, 4, 'these numbers are not equal');
   *
   * @name notEqual
   * @param {Mixed} actual
   * @param {Mixed} expected
   * @param {String} message
   * @api public
   */

  assert.notEqual = function (act, exp, msg) {
    var test = new Assertion(act, msg);

    test.assert(
        exp != flag(test, 'object')
      , 'expected #{this} to not equal #{exp}'
      , 'expected #{this} to equal #{act}'
      , exp
      , act
    );
  };

  /**
   * ### .strictEqual(actual, expected, [message])
   *
   * Asserts strict equality (`===`) of `actual` and `expected`.
   *
   *     assert.strictEqual(true, true, 'these booleans are strictly equal');
   *
   * @name strictEqual
   * @param {Mixed} actual
   * @param {Mixed} expected
   * @param {String} message
   * @api public
   */

  assert.strictEqual = function (act, exp, msg) {
    new Assertion(act, msg).to.equal(exp);
  };

  /**
   * ### .notStrictEqual(actual, expected, [message])
   *
   * Asserts strict inequality (`!==`) of `actual` and `expected`.
   *
   *     assert.notStrictEqual(3, '3', 'no coercion for strict equality');
   *
   * @name notStrictEqual
   * @param {Mixed} actual
   * @param {Mixed} expected
   * @param {String} message
   * @api public
   */

  assert.notStrictEqual = function (act, exp, msg) {
    new Assertion(act, msg).to.not.equal(exp);
  };

  /**
   * ### .deepEqual(actual, expected, [message])
   *
   * Asserts that `actual` is deeply equal to `expected`.
   *
   *     assert.deepEqual({ tea: 'green' }, { tea: 'green' });
   *
   * @name deepEqual
   * @param {Mixed} actual
   * @param {Mixed} expected
   * @param {String} message
   * @api public
   */

  assert.deepEqual = function (act, exp, msg) {
    new Assertion(act, msg).to.eql(exp);
  };

  /**
   * ### .notDeepEqual(actual, expected, [message])
   *
   * Assert that `actual` is not deeply equal to `expected`.
   *
   *     assert.notDeepEqual({ tea: 'green' }, { tea: 'jasmine' });
   *
   * @name notDeepEqual
   * @param {Mixed} actual
   * @param {Mixed} expected
   * @param {String} message
   * @api public
   */

  assert.notDeepEqual = function (act, exp, msg) {
    new Assertion(act, msg).to.not.eql(exp);
  };

  /**
   * ### .isTrue(value, [message])
   *
   * Asserts that `value` is true.
   *
   *     var teaServed = true;
   *     assert.isTrue(teaServed, 'the tea has been served');
   *
   * @name isTrue
   * @param {Mixed} value
   * @param {String} message
   * @api public
   */

  assert.isTrue = function (val, msg) {
    new Assertion(val, msg).is['true'];
  };

  /**
   * ### .isFalse(value, [message])
   *
   * Asserts that `value` is false.
   *
   *     var teaServed = false;
   *     assert.isFalse(teaServed, 'no tea yet? hmm...');
   *
   * @name isFalse
   * @param {Mixed} value
   * @param {String} message
   * @api public
   */

  assert.isFalse = function (val, msg) {
    new Assertion(val, msg).is['false'];
  };

  /**
   * ### .isNull(value, [message])
   *
   * Asserts that `value` is null.
   *
   *     assert.isNull(err, 'there was no error');
   *
   * @name isNull
   * @param {Mixed} value
   * @param {String} message
   * @api public
   */

  assert.isNull = function (val, msg) {
    new Assertion(val, msg).to.equal(null);
  };

  /**
   * ### .isNotNull(value, [message])
   *
   * Asserts that `value` is not null.
   *
   *     var tea = 'tasty chai';
   *     assert.isNotNull(tea, 'great, time for tea!');
   *
   * @name isNotNull
   * @param {Mixed} value
   * @param {String} message
   * @api public
   */

  assert.isNotNull = function (val, msg) {
    new Assertion(val, msg).to.not.equal(null);
  };

  /**
   * ### .isUndefined(value, [message])
   *
   * Asserts that `value` is `undefined`.
   *
   *     var tea;
   *     assert.isUndefined(tea, 'no tea defined');
   *
   * @name isUndefined
   * @param {Mixed} value
   * @param {String} message
   * @api public
   */

  assert.isUndefined = function (val, msg) {
    new Assertion(val, msg).to.equal(undefined);
  };

  /**
   * ### .isDefined(value, [message])
   *
   * Asserts that `value` is not `undefined`.
   *
   *     var tea = 'cup of chai';
   *     assert.isDefined(tea, 'tea has been defined');
   *
   * @name isUndefined
   * @param {Mixed} value
   * @param {String} message
   * @api public
   */

  assert.isDefined = function (val, msg) {
    new Assertion(val, msg).to.not.equal(undefined);
  };

  /**
   * ### .isFunction(value, [message])
   *
   * Asserts that `value` is a function.
   *
   *     function serveTea() { return 'cup of tea'; };
   *     assert.isFunction(serveTea, 'great, we can have tea now');
   *
   * @name isFunction
   * @param {Mixed} value
   * @param {String} message
   * @api public
   */

  assert.isFunction = function (val, msg) {
    new Assertion(val, msg).to.be.a('function');
  };

  /**
   * ### .isNotFunction(value, [message])
   *
   * Asserts that `value` is _not_ a function.
   *
   *     var serveTea = [ 'heat', 'pour', 'sip' ];
   *     assert.isNotFunction(serveTea, 'great, we have listed the steps');
   *
   * @name isNotFunction
   * @param {Mixed} value
   * @param {String} message
   * @api public
   */

  assert.isNotFunction = function (val, msg) {
    new Assertion(val, msg).to.not.be.a('function');
  };

  /**
   * ### .isObject(value, [message])
   *
   * Asserts that `value` is an object (as revealed by
   * `Object.prototype.toString`).
   *
   *     var selection = { name: 'Chai', serve: 'with spices' };
   *     assert.isObject(selection, 'tea selection is an object');
   *
   * @name isObject
   * @param {Mixed} value
   * @param {String} message
   * @api public
   */

  assert.isObject = function (val, msg) {
    new Assertion(val, msg).to.be.a('object');
  };

  /**
   * ### .isNotObject(value, [message])
   *
   * Asserts that `value` is _not_ an object.
   *
   *     var selection = 'chai'
   *     assert.isObject(selection, 'tea selection is not an object');
   *     assert.isObject(null, 'null is not an object');
   *
   * @name isNotObject
   * @param {Mixed} value
   * @param {String} message
   * @api public
   */

  assert.isNotObject = function (val, msg) {
    new Assertion(val, msg).to.not.be.a('object');
  };

  /**
   * ### .isArray(value, [message])
   *
   * Asserts that `value` is an array.
   *
   *     var menu = [ 'green', 'chai', 'oolong' ];
   *     assert.isArray(menu, 'what kind of tea do we want?');
   *
   * @name isArray
   * @param {Mixed} value
   * @param {String} message
   * @api public
   */

  assert.isArray = function (val, msg) {
    new Assertion(val, msg).to.be.an('array');
  };

  /**
   * ### .isNotArray(value, [message])
   *
   * Asserts that `value` is _not_ an array.
   *
   *     var menu = 'green|chai|oolong';
   *     assert.isNotArray(menu, 'what kind of tea do we want?');
   *
   * @name isNotArray
   * @param {Mixed} value
   * @param {String} message
   * @api public
   */

  assert.isNotArray = function (val, msg) {
    new Assertion(val, msg).to.not.be.an('array');
  };

  /**
   * ### .isString(value, [message])
   *
   * Asserts that `value` is a string.
   *
   *     var teaOrder = 'chai';
   *     assert.isString(teaOrder, 'order placed');
   *
   * @name isString
   * @param {Mixed} value
   * @param {String} message
   * @api public
   */

  assert.isString = function (val, msg) {
    new Assertion(val, msg).to.be.a('string');
  };

  /**
   * ### .isNotString(value, [message])
   *
   * Asserts that `value` is _not_ a string.
   *
   *     var teaOrder = 4;
   *     assert.isNotString(teaOrder, 'order placed');
   *
   * @name isNotString
   * @param {Mixed} value
   * @param {String} message
   * @api public
   */

  assert.isNotString = function (val, msg) {
    new Assertion(val, msg).to.not.be.a('string');
  };

  /**
   * ### .isNumber(value, [message])
   *
   * Asserts that `value` is a number.
   *
   *     var cups = 2;
   *     assert.isNumber(cups, 'how many cups');
   *
   * @name isNumber
   * @param {Number} value
   * @param {String} message
   * @api public
   */

  assert.isNumber = function (val, msg) {
    new Assertion(val, msg).to.be.a('number');
  };

  /**
   * ### .isNotNumber(value, [message])
   *
   * Asserts that `value` is _not_ a number.
   *
   *     var cups = '2 cups please';
   *     assert.isNotNumber(cups, 'how many cups');
   *
   * @name isNotNumber
   * @param {Mixed} value
   * @param {String} message
   * @api public
   */

  assert.isNotNumber = function (val, msg) {
    new Assertion(val, msg).to.not.be.a('number');
  };

  /**
   * ### .isBoolean(value, [message])
   *
   * Asserts that `value` is a boolean.
   *
   *     var teaReady = true
   *       , teaServed = false;
   *
   *     assert.isBoolean(teaReady, 'is the tea ready');
   *     assert.isBoolean(teaServed, 'has tea been served');
   *
   * @name isBoolean
   * @param {Mixed} value
   * @param {String} message
   * @api public
   */

  assert.isBoolean = function (val, msg) {
    new Assertion(val, msg).to.be.a('boolean');
  };

  /**
   * ### .isNotBoolean(value, [message])
   *
   * Asserts that `value` is _not_ a boolean.
   *
   *     var teaReady = 'yep'
   *       , teaServed = 'nope';
   *
   *     assert.isNotBoolean(teaReady, 'is the tea ready');
   *     assert.isNotBoolean(teaServed, 'has tea been served');
   *
   * @name isNotBoolean
   * @param {Mixed} value
   * @param {String} message
   * @api public
   */

  assert.isNotBoolean = function (val, msg) {
    new Assertion(val, msg).to.not.be.a('boolean');
  };

  /**
   * ### .typeOf(value, name, [message])
   *
   * Asserts that `value`'s type is `name`, as determined by
   * `Object.prototype.toString`.
   *
   *     assert.typeOf({ tea: 'chai' }, 'object', 'we have an object');
   *     assert.typeOf(['chai', 'jasmine'], 'array', 'we have an array');
   *     assert.typeOf('tea', 'string', 'we have a string');
   *     assert.typeOf(/tea/, 'regexp', 'we have a regular expression');
   *     assert.typeOf(null, 'null', 'we have a null');
   *     assert.typeOf(undefined, 'undefined', 'we have an undefined');
   *
   * @name typeOf
   * @param {Mixed} value
   * @param {String} name
   * @param {String} message
   * @api public
   */

  assert.typeOf = function (val, type, msg) {
    new Assertion(val, msg).to.be.a(type);
  };

  /**
   * ### .notTypeOf(value, name, [message])
   *
   * Asserts that `value`'s type is _not_ `name`, as determined by
   * `Object.prototype.toString`.
   *
   *     assert.notTypeOf('tea', 'number', 'strings are not numbers');
   *
   * @name notTypeOf
   * @param {Mixed} value
   * @param {String} typeof name
   * @param {String} message
   * @api public
   */

  assert.notTypeOf = function (val, type, msg) {
    new Assertion(val, msg).to.not.be.a(type);
  };

  /**
   * ### .instanceOf(object, constructor, [message])
   *
   * Asserts that `value` is an instance of `constructor`.
   *
   *     var Tea = function (name) { this.name = name; }
   *       , chai = new Tea('chai');
   *
   *     assert.instanceOf(chai, Tea, 'chai is an instance of tea');
   *
   * @name instanceOf
   * @param {Object} object
   * @param {Constructor} constructor
   * @param {String} message
   * @api public
   */

  assert.instanceOf = function (val, type, msg) {
    new Assertion(val, msg).to.be.instanceOf(type);
  };

  /**
   * ### .notInstanceOf(object, constructor, [message])
   *
   * Asserts `value` is not an instance of `constructor`.
   *
   *     var Tea = function (name) { this.name = name; }
   *       , chai = new String('chai');
   *
   *     assert.notInstanceOf(chai, Tea, 'chai is not an instance of tea');
   *
   * @name notInstanceOf
   * @param {Object} object
   * @param {Constructor} constructor
   * @param {String} message
   * @api public
   */

  assert.notInstanceOf = function (val, type, msg) {
    new Assertion(val, msg).to.not.be.instanceOf(type);
  };

  /**
   * ### .include(haystack, needle, [message])
   *
   * Asserts that `haystack` includes `needle`. Works
   * for strings and arrays.
   *
   *     assert.include('foobar', 'bar', 'foobar contains string "bar"');
   *     assert.include([ 1, 2, 3 ], 3, 'array contains value');
   *
   * @name include
   * @param {Array|String} haystack
   * @param {Mixed} needle
   * @param {String} message
   * @api public
   */

  assert.include = function (exp, inc, msg) {
    var obj = new Assertion(exp, msg);

    if (Array.isArray(exp)) {
      obj.to.include(inc);
    } else if ('string' === typeof exp) {
      obj.to.contain.string(inc);
    } else {
      throw new chai.AssertionError({
          message: 'expected an array or string'
        , stackStartFunction: assert.include
      });
    }
  };

  /**
   * ### .notInclude(haystack, needle, [message])
   *
   * Asserts that `haystack` does not include `needle`. Works
   * for strings and arrays.
   *i
   *     assert.notInclude('foobar', 'baz', 'string not include substring');
   *     assert.notInclude([ 1, 2, 3 ], 4, 'array not include contain value');
   *
   * @name notInclude
   * @param {Array|String} haystack
   * @param {Mixed} needle
   * @param {String} message
   * @api public
   */

  assert.notInclude = function (exp, inc, msg) {
    var obj = new Assertion(exp, msg);

    if (Array.isArray(exp)) {
      obj.to.not.include(inc);
    } else if ('string' === typeof exp) {
      obj.to.not.contain.string(inc);
    } else {
      throw new chai.AssertionError({
          message: 'expected an array or string'
        , stackStartFunction: assert.include
      });
    }
  };

  /**
   * ### .match(value, regexp, [message])
   *
   * Asserts that `value` matches the regular expression `regexp`.
   *
   *     assert.match('foobar', /^foo/, 'regexp matches');
   *
   * @name match
   * @param {Mixed} value
   * @param {RegExp} regexp
   * @param {String} message
   * @api public
   */

  assert.match = function (exp, re, msg) {
    new Assertion(exp, msg).to.match(re);
  };

  /**
   * ### .notMatch(value, regexp, [message])
   *
   * Asserts that `value` does not match the regular expression `regexp`.
   *
   *     assert.notMatch('foobar', /^foo/, 'regexp does not match');
   *
   * @name notMatch
   * @param {Mixed} value
   * @param {RegExp} regexp
   * @param {String} message
   * @api public
   */

  assert.notMatch = function (exp, re, msg) {
    new Assertion(exp, msg).to.not.match(re);
  };

  /**
   * ### .property(object, property, [message])
   *
   * Asserts that `object` has a property named by `property`.
   *
   *     assert.property({ tea: { green: 'matcha' }}, 'tea');
   *
   * @name property
   * @param {Object} object
   * @param {String} property
   * @param {String} message
   * @api public
   */

  assert.property = function (obj, prop, msg) {
    new Assertion(obj, msg).to.have.property(prop);
  };

  /**
   * ### .notProperty(object, property, [message])
   *
   * Asserts that `object` does _not_ have a property named by `property`.
   *
   *     assert.notProperty({ tea: { green: 'matcha' }}, 'coffee');
   *
   * @name notProperty
   * @param {Object} object
   * @param {String} property
   * @param {String} message
   * @api public
   */

  assert.notProperty = function (obj, prop, msg) {
    new Assertion(obj, msg).to.not.have.property(prop);
  };

  /**
   * ### .deepProperty(object, property, [message])
   *
   * Asserts that `object` has a property named by `property`, which can be a
   * string using dot- and bracket-notation for deep reference.
   *
   *     assert.deepProperty({ tea: { green: 'matcha' }}, 'tea.green');
   *
   * @name deepProperty
   * @param {Object} object
   * @param {String} property
   * @param {String} message
   * @api public
   */

  assert.deepProperty = function (obj, prop, msg) {
    new Assertion(obj, msg).to.have.deep.property(prop);
  };

  /**
   * ### .notDeepProperty(object, property, [message])
   *
   * Asserts that `object` does _not_ have a property named by `property`, which
   * can be a string using dot- and bracket-notation for deep reference.
   *
   *     assert.notDeepProperty({ tea: { green: 'matcha' }}, 'tea.oolong');
   *
   * @name notDeepProperty
   * @param {Object} object
   * @param {String} property
   * @param {String} message
   * @api public
   */

  assert.notDeepProperty = function (obj, prop, msg) {
    new Assertion(obj, msg).to.not.have.deep.property(prop);
  };

  /**
   * ### .propertyVal(object, property, value, [message])
   *
   * Asserts that `object` has a property named by `property` with value given
   * by `value`.
   *
   *     assert.propertyVal({ tea: 'is good' }, 'tea', 'is good');
   *
   * @name propertyVal
   * @param {Object} object
   * @param {String} property
   * @param {Mixed} value
   * @param {String} message
   * @api public
   */

  assert.propertyVal = function (obj, prop, val, msg) {
    new Assertion(obj, msg).to.have.property(prop, val);
  };

  /**
   * ### .propertyNotVal(object, property, value, [message])
   *
   * Asserts that `object` has a property named by `property`, but with a value
   * different from that given by `value`.
   *
   *     assert.propertyNotVal({ tea: 'is good' }, 'tea', 'is bad');
   *
   * @name propertyNotVal
   * @param {Object} object
   * @param {String} property
   * @param {Mixed} value
   * @param {String} message
   * @api public
   */

  assert.propertyNotVal = function (obj, prop, val, msg) {
    new Assertion(obj, msg).to.not.have.property(prop, val);
  };

  /**
   * ### .deepPropertyVal(object, property, value, [message])
   *
   * Asserts that `object` has a property named by `property` with value given
   * by `value`. `property` can use dot- and bracket-notation for deep
   * reference.
   *
   *     assert.deepPropertyVal({ tea: { green: 'matcha' }}, 'tea.green', 'matcha');
   *
   * @name deepPropertyVal
   * @param {Object} object
   * @param {String} property
   * @param {Mixed} value
   * @param {String} message
   * @api public
   */

  assert.deepPropertyVal = function (obj, prop, val, msg) {
    new Assertion(obj, msg).to.have.deep.property(prop, val);
  };

  /**
   * ### .deepPropertyNotVal(object, property, value, [message])
   *
   * Asserts that `object` has a property named by `property`, but with a value
   * different from that given by `value`. `property` can use dot- and
   * bracket-notation for deep reference.
   *
   *     assert.deepPropertyNotVal({ tea: { green: 'matcha' }}, 'tea.green', 'konacha');
   *
   * @name deepPropertyNotVal
   * @param {Object} object
   * @param {String} property
   * @param {Mixed} value
   * @param {String} message
   * @api public
   */

  assert.deepPropertyNotVal = function (obj, prop, val, msg) {
    new Assertion(obj, msg).to.not.have.deep.property(prop, val);
  };

  /**
   * ### .lengthOf(object, length, [message])
   *
   * Asserts that `object` has a `length` property with the expected value.
   *
   *     assert.lengthOf([1,2,3], 3, 'array has length of 3');
   *     assert.lengthOf('foobar', 5, 'string has length of 6');
   *
   * @name lengthOf
   * @param {Mixed} object
   * @param {Number} length
   * @param {String} message
   * @api public
   */

  assert.lengthOf = function (exp, len, msg) {
    new Assertion(exp, msg).to.have.length(len);
  };

  /**
   * ### .throws(function, [constructor/string/regexp], [string/regexp], [message])
   *
   * Asserts that `function` will throw an error that is an instance of
   * `constructor`, or alternately that it will throw an error with message
   * matching `regexp`.
   *
   *     assert.throw(fn, 'function throws a reference error');
   *     assert.throw(fn, /function throws a reference error/);
   *     assert.throw(fn, ReferenceError);
   *     assert.throw(fn, ReferenceError, 'function throws a reference error');
   *     assert.throw(fn, ReferenceError, /function throws a reference error/);
   *
   * @name throws
   * @alias throw
   * @alias Throw
   * @param {Function} function
   * @param {ErrorConstructor} constructor
   * @param {RegExp} regexp
   * @param {String} message
   * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types
   * @api public
   */

  assert.Throw = function (fn, errt, errs, msg) {
    if ('string' === typeof errt || errt instanceof RegExp) {
      errs = errt;
      errt = null;
    }

    new Assertion(fn, msg).to.Throw(errt, errs);
  };

  /**
   * ### .doesNotThrow(function, [constructor/regexp], [message])
   *
   * Asserts that `function` will _not_ throw an error that is an instance of
   * `constructor`, or alternately that it will not throw an error with message
   * matching `regexp`.
   *
   *     assert.doesNotThrow(fn, Error, 'function does not throw');
   *
   * @name doesNotThrow
   * @param {Function} function
   * @param {ErrorConstructor} constructor
   * @param {RegExp} regexp
   * @param {String} message
   * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types
   * @api public
   */

  assert.doesNotThrow = function (fn, type, msg) {
    if ('string' === typeof type) {
      msg = type;
      type = null;
    }

    new Assertion(fn, msg).to.not.Throw(type);
  };

  /**
   * ### .operator(val1, operator, val2, [message])
   *
   * Compares two values using `operator`.
   *
   *     assert.operator(1, '<', 2, 'everything is ok');
   *     assert.operator(1, '>', 2, 'this will fail');
   *
   * @name operator
   * @param {Mixed} val1
   * @param {String} operator
   * @param {Mixed} val2
   * @param {String} message
   * @api public
   */

  assert.operator = function (val, operator, val2, msg) {
    if (!~['==', '===', '>', '>=', '<', '<=', '!=', '!=='].indexOf(operator)) {
      throw new Error('Invalid operator "' + operator + '"');
    }
    var test = new Assertion(eval(val + operator + val2), msg);
    test.assert(
        true === flag(test, 'object')
      , 'expected ' + util.inspect(val) + ' to be ' + operator + ' ' + util.inspect(val2)
      , 'expected ' + util.inspect(val) + ' to not be ' + operator + ' ' + util.inspect(val2) );
  };

  /**
   * ### .closeTo(actual, expected, delta, [message])
   *
   * Asserts that the target is equal `expected`, to within a +/- `delta` range.
   *
   *     assert.closeTo(1.5, 1, 0.5, 'numbers are close');
   *
   * @name closeTo
   * @param {Number} actual
   * @param {Number} expected
   * @param {Number} delta
   * @param {String} message
   * @api public
   */

  assert.closeTo = function (act, exp, delta, msg) {
    new Assertion(act, msg).to.be.closeTo(exp, delta);
  };

  /**
   * ### .sameMembers(set1, set2, [message])
   *
   * Asserts that `set1` and `set2` have the same members.
   * Order is not taken into account.
   *
   *     assert.sameMembers([ 1, 2, 3 ], [ 2, 1, 3 ], 'same members');
   *
   * @name sameMembers
   * @param {Array} superset
   * @param {Array} subset
   * @param {String} message
   * @api public
   */

  assert.sameMembers = function (set1, set2, msg) {
    new Assertion(set1, msg).to.have.same.members(set2);
  }

  /**
   * ### .includeMembers(superset, subset, [message])
   *
   * Asserts that `subset` is included in `superset`.
   * Order is not taken into account.
   *
   *     assert.includeMembers([ 1, 2, 3 ], [ 2, 1 ], 'include members');
   *
   * @name includeMembers
   * @param {Array} superset
   * @param {Array} subset
   * @param {String} message
   * @api public
   */

  assert.includeMembers = function (superset, subset, msg) {
    new Assertion(superset, msg).to.include.members(subset);
  }

  /*!
   * Undocumented / untested
   */

  assert.ifError = function (val, msg) {
    new Assertion(val, msg).to.not.be.ok;
  };

  /*!
   * Aliases.
   */

  (function alias(name, as){
    assert[as] = assert[name];
    return alias;
  })
  ('Throw', 'throw')
  ('Throw', 'throws');
};


text:
export class video {
    public size: number;
    public id: number;

    constructor(id: number, size: number) {
        this.id = id;
        this.size = size;
    }
}


text:
require 'quick_travel/init_from_hash'

module QuickTravel
  class Service
    include QuickTravel::InitFromHash
  end
end


text:
<?php

if(version_compare(PHP_VERSION, '5.1.0', '<')) {
    exit('Your current PHP version is: ' . PHP_VERSION . '. Haxe/PHP generates code for version 5.1.0 or later');
} else if(version_compare(PHP_VERSION, '5.4.0', '<')) {
	trigger_error('Your current PHP version is: ' . PHP_VERSION . '. Code generated by Haxe/PHP might not work for versions < 5.4.0', E_USER_WARNING);
}
;
require_once dirname(__FILE__).'/lib/php/Boot.class.php';

Main::main();

?>


text:
{% extends "base.html" %}

{% block content %}

Obrigado pela sua submissão. Poderá encontrá-la aqui enquanto aguarda aprovação.

{% endblock %}


text:
namespace parquet {
namespace encryption {

std::shared_ptr<KmsClient> KeyToolkit::GetKmsClient(
    const KmsConnectionConfig& kms_connection_config, double cache_entry_lifetime_ms) {
  if (kms_client_factory_ == NULL) {
    throw ParquetException("No KmsClientFactory is registered.");
  }
  auto kms_client_per_kms_instance_cache =
      kms_client_cache_per_token().GetOrCreateInternalCache(
          kms_connection_config.key_access_token(), cache_entry_lifetime_ms);

  return kms_client_per_kms_instance_cache->GetOrInsert(
      kms_connection_config.kms_instance_id, [this, kms_connection_config]() {
        return this->kms_client_factory_->CreateKmsClient(kms_connection_config);
      });
}

// Flush any caches that are tied to the (compromised) access_token
void KeyToolkit::RemoveCacheEntriesForToken(const std::string& access_token) {
  kms_client_cache_per_token().Remove(access_token);
  kek_write_cache_per_token().Remove(access_token);
  kek_read_cache_per_token().Remove(access_token);
}

void KeyToolkit::RemoveCacheEntriesForAllTokens() {
  kms_client_cache_per_token().Clear();
  kek_write_cache_per_token().Clear();
  kek_read_cache_per_token().Clear();
}

}  // namespace encryption
}  // namespace parquet


text:
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/fs.h>
#include <linux/mtd/mtd.h>
#include <linux/rbtree.h>
#include <linux/crc32.h>
#include <linux/slab.h>
#include <linux/pagemap.h>
#include "nodelist.h"

static void jffs2_obsolete_node_frag(struct jffs2_sb_info *c,
				     struct jffs2_node_frag *this);

void jffs2_add_fd_to_list(struct jffs2_sb_info *c, struct jffs2_full_dirent *new, struct jffs2_full_dirent **list)
{
	struct jffs2_full_dirent **prev = list;

	dbg_dentlist("add dirent \"%s\", ino #%u\n", new->name, new->ino);

	while ((*prev) && (*prev)->nhash <= new->nhash) {
		if ((*prev)->nhash == new->nhash && !strcmp((*prev)->name, new->name)) {
			/* Duplicate. Free one */
			if (new->version < (*prev)->version) {
				dbg_dentlist("Eep! Marking new dirent node is obsolete, old is \"%s\", ino #%u\n",
					(*prev)->name, (*prev)->ino);
				jffs2_mark_node_obsolete(c, new->raw);
				jffs2_free_full_dirent(new);
			} else {
				dbg_dentlist("marking old dirent \"%s\", ino #%u bsolete\n",
					(*prev)->name, (*prev)->ino);
				new->next = (*prev)->next;
				jffs2_mark_node_obsolete(c, ((*prev)->raw));
				jffs2_free_full_dirent(*prev);
				*prev = new;
			}
			return;
		}
		prev = &((*prev)->next);
	}
	new->next = *prev;
	*prev = new;
}

void jffs2_truncate_fragtree(struct jffs2_sb_info *c, struct rb_root *list, uint32_t size)
{
	struct jffs2_node_frag *frag = jffs2_lookup_node_frag(list, size);

	dbg_fragtree("truncating fragtree to 0x%08x bytes\n", size);

	/* We know frag->ofs <= size. That's what lookup does for us */
	if (frag && frag->ofs != size) {
		if (frag->ofs+frag->size > size) {
			frag->size = size - frag->ofs;
		}
		frag = frag_next(frag);
	}
	while (frag && frag->ofs >= size) {
		struct jffs2_node_frag *next = frag_next(frag);

		frag_erase(frag, list);
		jffs2_obsolete_node_frag(c, frag);
		frag = next;
	}

	if (size == 0)
		return;

	/*
	 * If the last fragment starts at the RAM page boundary, it is
	 * REF_PRISTINE irrespective of its size.
	 */
	frag = frag_last(list);
	if (frag->node && (frag->ofs & (PAGE_CACHE_SIZE - 1)) == 0) {
		dbg_fragtree2("marking the last fragment 0x%08x-0x%08x REF_PRISTINE.\n",
			frag->ofs, frag->ofs + frag->size);
		frag->node->raw->flash_offset = ref_offset(frag->node->raw) | REF_PRISTINE;
	}
}

static void jffs2_obsolete_node_frag(struct jffs2_sb_info *c,
				     struct jffs2_node_frag *this)
{
	if (this->node) {
		this->node->frags--;
		if (!this->node->frags) {
			/* The node has no valid frags left. It's totally obsoleted */
			dbg_fragtree2("marking old node @0x%08x (0x%04x-0x%04x) obsolete\n",
				ref_offset(this->node->raw), this->node->ofs, this->node->ofs+this->node->size);
			jffs2_mark_node_obsolete(c, this->node->raw);
			jffs2_free_full_dnode(this->node);
		} else {
			dbg_fragtree2("marking old node @0x%08x (0x%04x-0x%04x) REF_NORMAL. frags is %d\n",
				ref_offset(this->node->raw), this->node->ofs, this->node->ofs+this->node->size, this->node->frags);
			mark_ref_normal(this->node->raw);
		}

	}
	jffs2_free_node_frag(this);
}

static void jffs2_fragtree_insert(struct jffs2_node_frag *newfrag, struct jffs2_node_frag *base)
{
	struct rb_node *parent = &base->rb;
	struct rb_node **link = &parent;

	dbg_fragtree2("insert frag (0x%04x-0x%04x)\n", newfrag->ofs, newfrag->ofs + newfrag->size);

	while (*link) {
		parent = *link;
		base = rb_entry(parent, struct jffs2_node_frag, rb);

		if (newfrag->ofs > base->ofs)
			link = &base->rb.rb_right;
		else if (newfrag->ofs < base->ofs)
			link = &base->rb.rb_left;
		else {
			JFFS2_ERROR("duplicate frag at %08x (%p,%p)\n", newfrag->ofs, newfrag, base);
			BUG();
		}
	}

	rb_link_node(&newfrag->rb, &base->rb, link);
}

/*
 * Allocate and initializes a new fragment.
 */
static struct jffs2_node_frag * new_fragment(struct jffs2_full_dnode *fn, uint32_t ofs, uint32_t size)
{
	struct jffs2_node_frag *newfrag;

	newfrag = jffs2_alloc_node_frag();
	if (likely(newfrag)) {
		newfrag->ofs = ofs;
		newfrag->size = size;
		newfrag->node = fn;
	} else {
		JFFS2_ERROR("cannot allocate a jffs2_node_frag object\n");
	}

	return newfrag;
}

/*
 * Called when there is no overlapping fragment exist. Inserts a hole before the new
 * fragment and inserts the new fragment to the fragtree.
 */
static int no_overlapping_node(struct jffs2_sb_info *c, struct rb_root *root,
		 	       struct jffs2_node_frag *newfrag,
			       struct jffs2_node_frag *this, uint32_t lastend)
{
	if (lastend < newfrag->node->ofs) {
		/* put a hole in before the new fragment */
		struct jffs2_node_frag *holefrag;

		holefrag= new_fragment(NULL, lastend, newfrag->node->ofs - lastend);
		if (unlikely(!holefrag)) {
			jffs2_free_node_frag(newfrag);
			return -ENOMEM;
		}

		if (this) {
			/* By definition, the 'this' node has no right-hand child,
			   because there are no frags with offset greater than it.
			   So that's where we want to put the hole */
			dbg_fragtree2("add hole frag %#04x-%#04x on the right of the new frag.\n",
				holefrag->ofs, holefrag->ofs + holefrag->size);
			rb_link_node(&holefrag->rb, &this->rb, &this->rb.rb_right);
		} else {
			dbg_fragtree2("Add hole frag %#04x-%#04x to the root of the tree.\n",
				holefrag->ofs, holefrag->ofs + holefrag->size);
			rb_link_node(&holefrag->rb, NULL, &root->rb_node);
		}
		rb_insert_color(&holefrag->rb, root);
		this = holefrag;
	}

	if (this) {
		/* By definition, the 'this' node has no right-hand child,
		   because there are no frags with offset greater than it.
		   So that's where we want to put new fragment */
		dbg_fragtree2("add the new node at the right\n");
		rb_link_node(&newfrag->rb, &this->rb, &this->rb.rb_right);
	} else {
		dbg_fragtree2("insert the new node at the root of the tree\n");
		rb_link_node(&newfrag->rb, NULL, &root->rb_node);
	}
	rb_insert_color(&newfrag->rb, root);

	return 0;
}

/* Doesn't set inode->i_size */
static int jffs2_add_frag_to_fragtree(struct jffs2_sb_info *c, struct rb_root *root, struct jffs2_node_frag *newfrag)
{
	struct jffs2_node_frag *this;
	uint32_t lastend;

	/* Skip all the nodes which are completed before this one starts */
	this = jffs2_lookup_node_frag(root, newfrag->node->ofs);

	if (this) {
		dbg_fragtree2("lookup gave frag 0x%04x-0x%04x; phys 0x%08x (*%p)\n",
			  this->ofs, this->ofs+this->size, this->node?(ref_offset(this->node->raw)):0xffffffff, this);
		lastend = this->ofs + this->size;
	} else {
		dbg_fragtree2("lookup gave no frag\n");
		lastend = 0;
	}

	/* See if we ran off the end of the fragtree */
	if (lastend <= newfrag->ofs) {
		/* We did */

		/* Check if 'this' node was on the same page as the new node.
		   If so, both 'this' and the new node get marked REF_NORMAL so
		   the GC can take a look.
		*/
		if (lastend && (lastend-1) >> PAGE_CACHE_SHIFT == newfrag->ofs >> PAGE_CACHE_SHIFT) {
			if (this->node)
				mark_ref_normal(this->node->raw);
			mark_ref_normal(newfrag->node->raw);
		}

		return no_overlapping_node(c, root, newfrag, this, lastend);
	}

	if (this->node)
		dbg_fragtree2("dealing with frag %u-%u, phys %#08x(%d).\n",
		this->ofs, this->ofs + this->size,
		ref_offset(this->node->raw), ref_flags(this->node->raw));
	else
		dbg_fragtree2("dealing with hole frag %u-%u.\n",
		this->ofs, this->ofs + this->size);

	/* OK. 'this' is pointing at the first frag that newfrag->ofs at least partially obsoletes,
	 * - i.e. newfrag->ofs < this->ofs+this->size && newfrag->ofs >= this->ofs
	 */
	if (newfrag->ofs > this->ofs) {
		/* This node isn't completely obsoleted. The start of it remains valid */

		/* Mark the new node and the partially covered node REF_NORMAL -- let
		   the GC take a look at them */
		mark_ref_normal(newfrag->node->raw);
		if (this->node)
			mark_ref_normal(this->node->raw);

		if (this->ofs + this->size > newfrag->ofs + newfrag->size) {
			/* The new node splits 'this' frag into two */
			struct jffs2_node_frag *newfrag2;

			if (this->node)
				dbg_fragtree2("split old frag 0x%04x-0x%04x, phys 0x%08x\n",
					this->ofs, this->ofs+this->size, ref_offset(this->node->raw));
			else
				dbg_fragtree2("split old hole frag 0x%04x-0x%04x\n",
					this->ofs, this->ofs+this->size);

			/* New second frag pointing to this's node */
			newfrag2 = new_fragment(this->node, newfrag->ofs + newfrag->size,
						this->ofs + this->size - newfrag->ofs - newfrag->size);
			if (unlikely(!newfrag2))
				return -ENOMEM;
			if (this->node)
				this->node->frags++;

			/* Adjust size of original 'this' */
			this->size = newfrag->ofs - this->ofs;

			/* Now, we know there's no node with offset
			   greater than this->ofs but smaller than
			   newfrag2->ofs or newfrag->ofs, for obvious
			   reasons. So we can do a tree insert from
			   'this' to insert newfrag, and a tree insert
			   from newfrag to insert newfrag2. */
			jffs2_fragtree_insert(newfrag, this);
			rb_insert_color(&newfrag->rb, root);

			jffs2_fragtree_insert(newfrag2, newfrag);
			rb_insert_color(&newfrag2->rb, root);

			return 0;
		}
		/* New node just reduces 'this' frag in size, doesn't split it */
		this->size = newfrag->ofs - this->ofs;

		/* Again, we know it lives down here in the tree */
		jffs2_fragtree_insert(newfrag, this);
		rb_insert_color(&newfrag->rb, root);
	} else {
		/* New frag starts at the same point as 'this' used to. Replace
		   it in the tree without doing a delete and insertion */
		dbg_fragtree2("inserting newfrag (*%p),%d-%d in before 'this' (*%p),%d-%d\n",
			  newfrag, newfrag->ofs, newfrag->ofs+newfrag->size, this, this->ofs, this->ofs+this->size);

		rb_replace_node(&this->rb, &newfrag->rb, root);

		if (newfrag->ofs + newfrag->size >= this->ofs+this->size) {
			dbg_fragtree2("obsoleting node frag %p (%x-%x)\n", this, this->ofs, this->ofs+this->size);
			jffs2_obsolete_node_frag(c, this);
		} else {
			this->ofs += newfrag->size;
			this->size -= newfrag->size;

			jffs2_fragtree_insert(this, newfrag);
			rb_insert_color(&this->rb, root);
			return 0;
		}
	}
	/* OK, now we have newfrag added in the correct place in the tree, but
	   frag_next(newfrag) may be a fragment which is overlapped by it
	*/
	while ((this = frag_next(newfrag)) && newfrag->ofs + newfrag->size >= this->ofs + this->size) {
		/* 'this' frag is obsoleted completely. */
		dbg_fragtree2("obsoleting node frag %p (%x-%x) and removing from tree\n",
			this, this->ofs, this->ofs+this->size);
		rb_erase(&this->rb, root);
		jffs2_obsolete_node_frag(c, this);
	}
	/* Now we're pointing at the first frag which isn't totally obsoleted by
	   the new frag */

	if (!this || newfrag->ofs + newfrag->size == this->ofs)
		return 0;

	/* Still some overlap but we don't need to move it in the tree */
	this->size = (this->ofs + this->size) - (newfrag->ofs + newfrag->size);
	this->ofs = newfrag->ofs + newfrag->size;

	/* And mark them REF_NORMAL so the GC takes a look at them */
	if (this->node)
		mark_ref_normal(this->node->raw);
	mark_ref_normal(newfrag->node->raw);

	return 0;
}

/*
 * Given an inode, probably with existing tree of fragments, add the new node
 * to the fragment tree.
 */
int jffs2_add_full_dnode_to_inode(struct jffs2_sb_info *c, struct jffs2_inode_info *f, struct jffs2_full_dnode *fn)
{
	int ret;
	struct jffs2_node_frag *newfrag;

	if (unlikely(!fn->size))
		return 0;

	newfrag = new_fragment(fn, fn->ofs, fn->size);
	if (unlikely(!newfrag))
		return -ENOMEM;
	newfrag->node->frags = 1;

	dbg_fragtree("adding node %#04x-%#04x @0x%08x on flash, newfrag *%p\n",
		  fn->ofs, fn->ofs+fn->size, ref_offset(fn->raw), newfrag);

	ret = jffs2_add_frag_to_fragtree(c, &f->fragtree, newfrag);
	if (unlikely(ret))
		return ret;

	/* If we now share a page with other nodes, mark either previous
	   or next node REF_NORMAL, as appropriate.  */
	if (newfrag->ofs & (PAGE_CACHE_SIZE-1)) {
		struct jffs2_node_frag *prev = frag_prev(newfrag);

		mark_ref_normal(fn->raw);
		/* If we don't start at zero there's _always_ a previous */
		if (prev->node)
			mark_ref_normal(prev->node->raw);
	}

	if ((newfrag->ofs+newfrag->size) & (PAGE_CACHE_SIZE-1)) {
		struct jffs2_node_frag *next = frag_next(newfrag);

		if (next) {
			mark_ref_normal(fn->raw);
			if (next->node)
				mark_ref_normal(next->node->raw);
		}
	}
	jffs2_dbg_fragtree_paranoia_check_nolock(f);

	return 0;
}

/*
 * Check the data CRC of the node.
 *
 * Returns: 0 if the data CRC is correct;
 * 	    1 - if incorrect;
 *	    error code if an error occured.
 */
static int check_node_data(struct jffs2_sb_info *c, struct jffs2_tmp_dnode_info *tn)
{
	struct jffs2_raw_node_ref *ref = tn->fn->raw;
	int err = 0, pointed = 0;
	struct jffs2_eraseblock *jeb;
	unsigned char *buffer;
	uint32_t crc, ofs, len;
	size_t retlen;

	BUG_ON(tn->csize == 0);

	if (!jffs2_is_writebuffered(c))
		goto adj_acc;

	/* Calculate how many bytes were already checked */
	ofs = ref_offset(ref) + sizeof(struct jffs2_raw_inode);
	len = ofs % c->wbuf_pagesize;
	if (likely(len))
		len = c->wbuf_pagesize - len;

	if (len >= tn->csize) {
		dbg_readinode("no need to check node at %#08x, data length %u, data starts at %#08x - it has already been checked.\n",
			ref_offset(ref), tn->csize, ofs);
		goto adj_acc;
	}

	ofs += len;
	len = tn->csize - len;

	dbg_readinode("check node at %#08x, data length %u, partial CRC %#08x, correct CRC %#08x, data starts at %#08x, start checking from %#08x - %u bytes.\n",
		ref_offset(ref), tn->csize, tn->partial_crc, tn->data_crc, ofs - len, ofs, len);

#ifndef __ECOS
	/* TODO: instead, incapsulate point() stuff to jffs2_flash_read(),
	 * adding and jffs2_flash_read_end() interface. */
	if (c->mtd->point) {
		err = c->mtd->point(c->mtd, ofs, len, &retlen, &buffer);
		if (!err && retlen < tn->csize) {
			JFFS2_WARNING("MTD point returned len too short: %zu instead of %u.\n", retlen, tn->csize);
			c->mtd->unpoint(c->mtd, buffer, ofs, len);
		} else if (err)
			JFFS2_WARNING("MTD point failed: error code %d.\n", err);
		else
			pointed = 1; /* succefully pointed to device */
	}
#endif

	if (!pointed) {
		buffer = kmalloc(len, GFP_KERNEL);
		if (unlikely(!buffer))
			return -ENOMEM;

		/* TODO: this is very frequent pattern, make it a separate
		 * routine */
		err = jffs2_flash_read(c, ofs, len, &retlen, buffer);
		if (err) {
			JFFS2_ERROR("can not read %d bytes from 0x%08x, error code: %d.\n", len, ofs, err);
			goto free_out;
		}

		if (retlen != len) {
			JFFS2_ERROR("short read at %#08x: %zd instead of %d.\n", ofs, retlen, len);
			err = -EIO;
			goto free_out;
		}
	}

	/* Continue calculating CRC */
	crc = crc32(tn->partial_crc, buffer, len);
	if(!pointed)
		kfree(buffer);
#ifndef __ECOS
	else
		c->mtd->unpoint(c->mtd, buffer, ofs, len);
#endif

	if (crc != tn->data_crc) {
		JFFS2_NOTICE("wrong data CRC in data node at 0x%08x: read %#08x, calculated %#08x.\n",
			ofs, tn->data_crc, crc);
		return 1;
	}

adj_acc:
	jeb = &c->blocks[ref->flash_offset / c->sector_size];
	len = ref_totlen(c, jeb, ref);

	/*
	 * Mark the node as having been checked and fix the
	 * accounting accordingly.
	 */
	spin_lock(&c->erase_completion_lock);
	jeb->used_size += len;
	jeb->unchecked_size -= len;
	c->used_size += len;
	c->unchecked_size -= len;
	spin_unlock(&c->erase_completion_lock);

	return 0;

free_out:
	if(!pointed)
		kfree(buffer);
#ifndef __ECOS
	else
		c->mtd->unpoint(c->mtd, buffer, ofs, len);
#endif
	return err;
}

/*
 * Helper function for jffs2_add_older_frag_to_fragtree().
 *
 * Checks the node if we are in the checking stage.
 */
static int check_node(struct jffs2_sb_info *c, struct jffs2_inode_info *f, struct jffs2_tmp_dnode_info *tn)
{
	int ret;

	BUG_ON(ref_obsolete(tn->fn->raw));

	/* We only check the data CRC of unchecked nodes */
	if (ref_flags(tn->fn->raw) != REF_UNCHECKED)
		return 0;

	dbg_fragtree2("check node %#04x-%#04x, phys offs %#08x.\n",
		tn->fn->ofs, tn->fn->ofs + tn->fn->size, ref_offset(tn->fn->raw));

	ret = check_node_data(c, tn);
	if (unlikely(ret < 0)) {
		JFFS2_ERROR("check_node_data() returned error: %d.\n",
			ret);
	} else if (unlikely(ret > 0)) {
		dbg_fragtree2("CRC error, mark it obsolete.\n");
		jffs2_mark_node_obsolete(c, tn->fn->raw);
	}

	return ret;
}

/*
 * Helper function for jffs2_add_older_frag_to_fragtree().
 *
 * Called when the new fragment that is being inserted
 * splits a hole fragment.
 */
static int split_hole(struct jffs2_sb_info *c, struct rb_root *root,
		      struct jffs2_node_frag *newfrag, struct jffs2_node_frag *hole)
{
	dbg_fragtree2("fragment %#04x-%#04x splits the hole %#04x-%#04x\n",
		newfrag->ofs, newfrag->ofs + newfrag->size, hole->ofs, hole->ofs + hole->size);

	if (hole->ofs == newfrag->ofs) {
		/*
		 * Well, the new fragment actually starts at the same offset as
		 * the hole.
		 */
		if (hole->ofs + hole->size > newfrag->ofs + newfrag->size) {
			/*
			 * We replace the overlapped left part of the hole by
			 * the new node.
			 */

			dbg_fragtree2("insert fragment %#04x-%#04x and cut the left part of the hole\n",
				newfrag->ofs, newfrag->ofs + newfrag->size);
			rb_replace_node(&hole->rb, &newfrag->rb, root);

			hole->ofs += newfrag->size;
			hole->size -= newfrag->size;

			/*
			 * We know that 'hole' should be the right hand
			 * fragment.
			 */
			jffs2_fragtree_insert(hole, newfrag);
			rb_insert_color(&hole->rb, root);
		} else {
			/*
			 * Ah, the new fragment is of the same size as the hole.
			 * Relace the hole by it.
			 */
			dbg_fragtree2("insert fragment %#04x-%#04x and overwrite hole\n",
				newfrag->ofs, newfrag->ofs + newfrag->size);
			rb_replace_node(&hole->rb, &newfrag->rb, root);
			jffs2_free_node_frag(hole);
		}
	} else {
		/* The new fragment lefts some hole space at the left */

		struct jffs2_node_frag * newfrag2 = NULL;

		if (hole->ofs + hole->size > newfrag->ofs + newfrag->size) {
			/* The new frag also lefts some space at the right */
			newfrag2 = new_fragment(NULL, newfrag->ofs +
				newfrag->size, hole->ofs + hole->size
				- newfrag->ofs - newfrag->size);
			if (unlikely(!newfrag2)) {
				jffs2_free_node_frag(newfrag);
				return -ENOMEM;
			}
		}

		hole->size = newfrag->ofs - hole->ofs;
		dbg_fragtree2("left the hole %#04x-%#04x at the left and inserd fragment %#04x-%#04x\n",
			hole->ofs, hole->ofs + hole->size, newfrag->ofs, newfrag->ofs + newfrag->size);

		jffs2_fragtree_insert(newfrag, hole);
		rb_insert_color(&newfrag->rb, root);

		if (newfrag2) {
			dbg_fragtree2("left the hole %#04x-%#04x at the right\n",
				newfrag2->ofs, newfrag2->ofs + newfrag2->size);
			jffs2_fragtree_insert(newfrag2, newfrag);
			rb_insert_color(&newfrag2->rb, root);
		}
	}

	return 0;
}

/*
 * This function is used when we build inode. It expects the nodes are passed
 * in the decreasing version order. The whole point of this is to improve the
 * inodes checking on NAND: we check the nodes' data CRC only when they are not
 * obsoleted. Previously, add_frag_to_fragtree() function was used and
 * nodes were passed to it in the increasing version ordes and CRCs of all
 * nodes were checked.
 *
 * Note: tn->fn->size shouldn't be zero.
 *
 * Returns 0 if the node was inserted
 *         1 if it wasn't inserted (since it is obsolete)
 *         < 0 an if error occured
 */
int jffs2_add_older_frag_to_fragtree(struct jffs2_sb_info *c, struct jffs2_inode_info *f,
				     struct jffs2_tmp_dnode_info *tn)
{
	struct jffs2_node_frag *this, *newfrag;
	uint32_t lastend;
	struct jffs2_full_dnode *fn = tn->fn;
	struct rb_root *root = &f->fragtree;
	uint32_t fn_size = fn->size, fn_ofs = fn->ofs;
	int err, checked = 0;
	int ref_flag;

	dbg_fragtree("insert fragment %#04x-%#04x, ver %u\n", fn_ofs, fn_ofs + fn_size, tn->version);

	/* Skip all the nodes which are completed before this one starts */
	this = jffs2_lookup_node_frag(root, fn_ofs);
	if (this)
		dbg_fragtree2("'this' found %#04x-%#04x (%s)\n", this->ofs, this->ofs + this->size, this->node ? "data" : "hole");

	if (this)
		lastend = this->ofs + this->size;
	else
		lastend = 0;

	/* Detect the preliminary type of node */
	if (fn->size >= PAGE_CACHE_SIZE)
		ref_flag = REF_PRISTINE;
	else
		ref_flag = REF_NORMAL;

	/* See if we ran off the end of the root */
	if (lastend <= fn_ofs) {
		/* We did */

		/*
		 * We are going to insert the new node into the
		 * fragment tree, so check it.
		 */
		err = check_node(c, f, tn);
		if (err != 0)
			return err;

		fn->frags = 1;

		newfrag = new_fragment(fn, fn_ofs, fn_size);
		if (unlikely(!newfrag))
			return -ENOMEM;

		err = no_overlapping_node(c, root, newfrag, this, lastend);
		if (unlikely(err != 0)) {
			jffs2_free_node_frag(newfrag);
			return err;
		}

		goto out_ok;
	}

	fn->frags = 0;

	while (1) {
		/*
		 * Here we have:
		 * fn_ofs < this->ofs + this->size && fn_ofs >= this->ofs.
		 *
		 * Remember, 'this' has higher version, any non-hole node
		 * which is already in the fragtree is newer then the newly
		 * inserted.
		 */
		if (!this->node) {
			/*
			 * 'this' is the hole fragment, so at least the
			 * beginning of the new fragment is valid.
			 */

			/*
			 * We are going to insert the new node into the
			 * fragment tree, so check it.
			 */
			if (!checked) {
				err = check_node(c, f, tn);
				if (unlikely(err != 0))
					return err;
				checked = 1;
			}

			if (this->ofs + this->size >= fn_ofs + fn_size) {
				/* We split the hole on two parts */

				fn->frags += 1;
				newfrag = new_fragment(fn, fn_ofs, fn_size);
				if (unlikely(!newfrag))
					return -ENOMEM;

				err = split_hole(c, root, newfrag, this);
				if (unlikely(err))
					return err;
				goto out_ok;
			}

			/*
			 * The beginning of the new fragment is valid since it
			 * overlaps the hole node.
			 */

			ref_flag = REF_NORMAL;

			fn->frags += 1;
			newfrag = new_fragment(fn, fn_ofs,
					this->ofs + this->size - fn_ofs);
			if (unlikely(!newfrag))
				return -ENOMEM;

			if (fn_ofs == this->ofs) {
				/*
				 * The new node starts at the same offset as
				 * the hole and supersieds the hole.
				 */
				dbg_fragtree2("add the new fragment instead of hole %#04x-%#04x, refcnt %d\n",
					fn_ofs, fn_ofs + this->ofs + this->size - fn_ofs, fn->frags);

				rb_replace_node(&this->rb, &newfrag->rb, root);
				jffs2_free_node_frag(this);
			} else {
				/*
				 * The hole becomes shorter as its right part
				 * is supersieded by the new fragment.
				 */
				dbg_fragtree2("reduce size of hole %#04x-%#04x to %#04x-%#04x\n",
					this->ofs, this->ofs + this->size, this->ofs, this->ofs + this->size - newfrag->size);

				dbg_fragtree2("add new fragment %#04x-%#04x, refcnt %d\n", fn_ofs,
					fn_ofs + this->ofs + this->size - fn_ofs, fn->frags);

				this->size -= newfrag->size;
				jffs2_fragtree_insert(newfrag, this);
				rb_insert_color(&newfrag->rb, root);
			}

			fn_ofs += newfrag->size;
			fn_size -= newfrag->size;
			this = rb_entry(rb_next(&newfrag->rb),
					struct jffs2_node_frag, rb);

			dbg_fragtree2("switch to the next 'this' fragment: %#04x-%#04x %s\n",
				this->ofs, this->ofs + this->size, this->node ? "(data)" : "(hole)");
		}

		/*
		 * 'This' node is not the hole so it obsoletes the new fragment
		 * either fully or partially.
		 */
		if (this->ofs + this->size >= fn_ofs + fn_size) {
			/* The new node is obsolete, drop it */
			if (fn->frags == 0) {
				dbg_fragtree2("%#04x-%#04x is obsolete, mark it obsolete\n", fn_ofs, fn_ofs + fn_size);
				ref_flag = REF_OBSOLETE;
			}
			goto out_ok;
		} else {
			struct jffs2_node_frag *new_this;

			/* 'This' node obsoletes the beginning of the new node */
			dbg_fragtree2("the beginning %#04x-%#04x is obsolete\n", fn_ofs, this->ofs + this->size);

			ref_flag = REF_NORMAL;

			fn_size -= this->ofs + this->size - fn_ofs;
			fn_ofs = this->ofs + this->size;
			dbg_fragtree2("now considering %#04x-%#04x\n", fn_ofs, fn_ofs + fn_size);

			new_this = rb_entry(rb_next(&this->rb), struct jffs2_node_frag, rb);
			if (!new_this) {
				/*
				 * There is no next fragment. Add the rest of
				 * the new node as the right-hand child.
				 */
				if (!checked) {
					err = check_node(c, f, tn);
					if (unlikely(err != 0))
						return err;
					checked = 1;
				}

				fn->frags += 1;
				newfrag = new_fragment(fn, fn_ofs, fn_size);
				if (unlikely(!newfrag))
					return -ENOMEM;

				dbg_fragtree2("there are no more fragments, insert %#04x-%#04x\n",
					newfrag->ofs, newfrag->ofs + newfrag->size);
				rb_link_node(&newfrag->rb, &this->rb, &this->rb.rb_right);
				rb_insert_color(&newfrag->rb, root);
				goto out_ok;
			} else {
				this = new_this;
				dbg_fragtree2("switch to the next 'this' fragment: %#04x-%#04x %s\n",
					this->ofs, this->ofs + this->size, this->node ? "(data)" : "(hole)");
			}
		}
	}

out_ok:
	BUG_ON(fn->size < PAGE_CACHE_SIZE && ref_flag == REF_PRISTINE);

	if (ref_flag == REF_OBSOLETE) {
		dbg_fragtree2("the node is obsolete now\n");
		/* jffs2_mark_node_obsolete() will adjust space accounting */
		jffs2_mark_node_obsolete(c, fn->raw);
		return 1;
	}

	dbg_fragtree2("the node is \"%s\" now\n", ref_flag == REF_NORMAL ? "REF_NORMAL" : "REF_PRISTINE");

	/* Space accounting was adjusted at check_node_data() */
	spin_lock(&c->erase_completion_lock);
	fn->raw->flash_offset = ref_offset(fn->raw) | ref_flag;
	spin_unlock(&c->erase_completion_lock);

	return 0;
}

void jffs2_set_inocache_state(struct jffs2_sb_info *c, struct jffs2_inode_cache *ic, int state)
{
	spin_lock(&c->inocache_lock);
	ic->state = state;
	wake_up(&c->inocache_wq);
	spin_unlock(&c->inocache_lock);
}

/* During mount, this needs no locking. During normal operation, its
   callers want to do other stuff while still holding the inocache_lock.
   Rather than introducing special case get_ino_cache functions or
   callbacks, we just let the caller do the locking itself. */

struct jffs2_inode_cache *jffs2_get_ino_cache(struct jffs2_sb_info *c, uint32_t ino)
{
	struct jffs2_inode_cache *ret;

	ret = c->inocache_list[ino % INOCACHE_HASHSIZE];
	while (ret && ret->ino < ino) {
		ret = ret->next;
	}

	if (ret && ret->ino != ino)
		ret = NULL;

	return ret;
}

void jffs2_add_ino_cache (struct jffs2_sb_info *c, struct jffs2_inode_cache *new)
{
	struct jffs2_inode_cache **prev;

	spin_lock(&c->inocache_lock);
	if (!new->ino)
		new->ino = ++c->highest_ino;

	dbg_inocache("add %p (ino #%u)\n", new, new->ino);

	prev = &c->inocache_list[new->ino % INOCACHE_HASHSIZE];

	while ((*prev) && (*prev)->ino < new->ino) {
		prev = &(*prev)->next;
	}
	new->next = *prev;
	*prev = new;

	spin_unlock(&c->inocache_lock);
}

void jffs2_del_ino_cache(struct jffs2_sb_info *c, struct jffs2_inode_cache *old)
{
	struct jffs2_inode_cache **prev;

#ifdef CONFIG_JFFS2_FS_XATTR
	BUG_ON(old->xref);
#endif
	dbg_inocache("del %p (ino #%u)\n", old, old->ino);
	spin_lock(&c->inocache_lock);

	prev = &c->inocache_list[old->ino % INOCACHE_HASHSIZE];

	while ((*prev) && (*prev)->ino < old->ino) {
		prev = &(*prev)->next;
	}
	if ((*prev) == old) {
		*prev = old->next;
	}

	/* Free it now unless it's in READING or CLEARING state, which
	   are the transitions upon read_inode() and clear_inode(). The
	   rest of the time we know nobody else is looking at it, and
	   if it's held by read_inode() or clear_inode() they'll free it
	   for themselves. */
	if (old->state != INO_STATE_READING && old->state != INO_STATE_CLEARING)
		jffs2_free_inode_cache(old);

	spin_unlock(&c->inocache_lock);
}

void jffs2_free_ino_caches(struct jffs2_sb_info *c)
{
	int i;
	struct jffs2_inode_cache *this, *next;

	for (i=0; i<INOCACHE_HASHSIZE; i++) {
		this = c->inocache_list[i];
		while (this) {
			next = this->next;
			jffs2_xattr_free_inode(c, this);
			jffs2_free_inode_cache(this);
			this = next;
		}
		c->inocache_list[i] = NULL;
	}
}

void jffs2_free_raw_node_refs(struct jffs2_sb_info *c)
{
	int i;
	struct jffs2_raw_node_ref *this, *next;

	for (i=0; i<c->nr_blocks; i++) {
		this = c->blocks[i].first_node;
		while (this) {
			if (this[REFS_PER_BLOCK].flash_offset == REF_LINK_NODE)
				next = this[REFS_PER_BLOCK].next_in_ino;
			else
				next = NULL;

			jffs2_free_refblock(this);
			this = next;
		}
		c->blocks[i].first_node = c->blocks[i].last_node = NULL;
	}
}

struct jffs2_node_frag *jffs2_lookup_node_frag(struct rb_root *fragtree, uint32_t offset)
{
	/* The common case in lookup is that there will be a node
	   which precisely matches. So we go looking for that first */
	struct rb_node *next;
	struct jffs2_node_frag *prev = NULL;
	struct jffs2_node_frag *frag = NULL;

	dbg_fragtree2("root %p, offset %d\n", fragtree, offset);

	next = fragtree->rb_node;

	while(next) {
		frag = rb_entry(next, struct jffs2_node_frag, rb);

		if (frag->ofs + frag->size <= offset) {
			/* Remember the closest smaller match on the way down */
			if (!prev || frag->ofs > prev->ofs)
				prev = frag;
			next = frag->rb.rb_right;
		} else if (frag->ofs > offset) {
			next = frag->rb.rb_left;
		} else {
			return frag;
		}
	}

	/* Exact match not found. Go back up looking at each parent,
	   and return the closest smaller one */

	if (prev)
		dbg_fragtree2("no match. Returning frag %#04x-%#04x, closest previous\n",
			  prev->ofs, prev->ofs+prev->size);
	else
		dbg_fragtree2("returning NULL, empty fragtree\n");

	return prev;
}

/* Pass 'c' argument to indicate that nodes should be marked obsolete as
   they're killed. */
void jffs2_kill_fragtree(struct rb_root *root, struct jffs2_sb_info *c)
{
	struct jffs2_node_frag *frag;
	struct jffs2_node_frag *parent;

	if (!root->rb_node)
		return;

	dbg_fragtree("killing\n");

	frag = (rb_entry(root->rb_node, struct jffs2_node_frag, rb));
	while(frag) {
		if (frag->rb.rb_left) {
			frag = frag_left(frag);
			continue;
		}
		if (frag->rb.rb_right) {
			frag = frag_right(frag);
			continue;
		}

		if (frag->node && !(--frag->node->frags)) {
			/* Not a hole, and it's the final remaining frag
			   of this node. Free the node */
			if (c)
				jffs2_mark_node_obsolete(c, frag->node->raw);

			jffs2_free_full_dnode(frag->node);
		}
		parent = frag_parent(frag);
		if (parent) {
			if (frag_left(parent) == frag)
				parent->rb.rb_left = NULL;
			else
				parent->rb.rb_right = NULL;
		}

		jffs2_free_node_frag(frag);
		frag = parent;

		cond_resched();
	}
}

struct jffs2_raw_node_ref *jffs2_link_node_ref(struct jffs2_sb_info *c,
					       struct jffs2_eraseblock *jeb,
					       uint32_t ofs, uint32_t len,
					       struct jffs2_inode_cache *ic)
{
	struct jffs2_raw_node_ref *ref;

	BUG_ON(!jeb->allocated_refs);
	jeb->allocated_refs--;

	ref = jeb->last_node;

	dbg_noderef("Last node at %p is (%08x,%p)\n", ref, ref->flash_offset,
		    ref->next_in_ino);

	while (ref->flash_offset != REF_EMPTY_NODE) {
		if (ref->flash_offset == REF_LINK_NODE)
			ref = ref->next_in_ino;
		else
			ref++;
	}

	dbg_noderef("New ref is %p (%08x becomes %08x,%p) len 0x%x\n", ref,
		    ref->flash_offset, ofs, ref->next_in_ino, len);

	ref->flash_offset = ofs;

	if (!jeb->first_node) {
		jeb->first_node = ref;
		BUG_ON(ref_offset(ref) != jeb->offset);
	} else if (unlikely(ref_offset(ref) != jeb->offset + c->sector_size - jeb->free_size)) {
		uint32_t last_len = ref_totlen(c, jeb, jeb->last_node);

		JFFS2_ERROR("Adding new ref %p at (0x%08x-0x%08x) not immediately after previous (0x%08x-0x%08x)\n",
			    ref, ref_offset(ref), ref_offset(ref)+len,
			    ref_offset(jeb->last_node),
			    ref_offset(jeb->last_node)+last_len);
		BUG();
	}
	jeb->last_node = ref;

	if (ic) {
		ref->next_in_ino = ic->nodes;
		ic->nodes = ref;
	} else {
		ref->next_in_ino = NULL;
	}

	switch(ref_flags(ref)) {
	case REF_UNCHECKED:
		c->unchecked_size += len;
		jeb->unchecked_size += len;
		break;

	case REF_NORMAL:
	case REF_PRISTINE:
		c->used_size += len;
		jeb->used_size += len;
		break;

	case REF_OBSOLETE:
		c->dirty_size += len;
		jeb->dirty_size += len;
		break;
	}
	c->free_size -= len;
	jeb->free_size -= len;

#ifdef TEST_TOTLEN
	/* Set (and test) __totlen field... for now */
	ref->__totlen = len;
	ref_totlen(c, jeb, ref);
#endif
	return ref;
}

/* No locking, no reservation of 'ref'. Do not use on a live file system */
int jffs2_scan_dirty_space(struct jffs2_sb_info *c, struct jffs2_eraseblock *jeb,
			   uint32_t size)
{
	if (!size)
		return 0;
	if (unlikely(size > jeb->free_size)) {
		printk(KERN_CRIT "Dirty space 0x%x larger then free_size 0x%x (wasted 0x%x)\n",
		       size, jeb->free_size, jeb->wasted_size);
		BUG();
	}
	/* REF_EMPTY_NODE is !obsolete, so that works OK */
	if (jeb->last_node && ref_obsolete(jeb->last_node)) {
#ifdef TEST_TOTLEN
		jeb->last_node->__totlen += size;
#endif
		c->dirty_size += size;
		c->free_size -= size;
		jeb->dirty_size += size;
		jeb->free_size -= size;
	} else {
		uint32_t ofs = jeb->offset + c->sector_size - jeb->free_size;
		ofs |= REF_OBSOLETE;

		jffs2_link_node_ref(c, jeb, ofs, size, NULL);
	}

	return 0;
}

/* Calculate totlen from surrounding nodes or eraseblock */
static inline uint32_t __ref_totlen(struct jffs2_sb_info *c,
				    struct jffs2_eraseblock *jeb,
				    struct jffs2_raw_node_ref *ref)
{
	uint32_t ref_end;
	struct jffs2_raw_node_ref *next_ref = ref_next(ref);

	if (next_ref)
		ref_end = ref_offset(next_ref);
	else {
		if (!jeb)
			jeb = &c->blocks[ref->flash_offset / c->sector_size];

		/* Last node in block. Use free_space */
		if (unlikely(ref != jeb->last_node)) {
			printk(KERN_CRIT "ref %p @0x%08x is not jeb->last_node (%p @0x%08x)\n",
			       ref, ref_offset(ref), jeb->last_node, jeb->last_node?ref_offset(jeb->last_node):0);
			BUG();
		}
		ref_end = jeb->offset + c->sector_size - jeb->free_size;
	}
	return ref_end - ref_offset(ref);
}

uint32_t __jffs2_ref_totlen(struct jffs2_sb_info *c, struct jffs2_eraseblock *jeb,
			    struct jffs2_raw_node_ref *ref)
{
	uint32_t ret;

	ret = __ref_totlen(c, jeb, ref);

#ifdef TEST_TOTLEN
	if (unlikely(ret != ref->__totlen)) {
		if (!jeb)
			jeb = &c->blocks[ref->flash_offset / c->sector_size];

		printk(KERN_CRIT "Totlen for ref at %p (0x%08x-0x%08x) miscalculated as 0x%x instead of %x\n",
		       ref, ref_offset(ref), ref_offset(ref)+ref->__totlen,
		       ret, ref->__totlen);
		if (ref_next(ref)) {
			printk(KERN_CRIT "next %p (0x%08x-0x%08x)\n", ref_next(ref), ref_offset(ref_next(ref)),
			       ref_offset(ref_next(ref))+ref->__totlen);
		} else
			printk(KERN_CRIT "No next ref. jeb->last_node is %p\n", jeb->last_node);

		printk(KERN_CRIT "jeb->wasted_size %x, dirty_size %x, used_size %x, free_size %x\n", jeb->wasted_size, jeb->dirty_size, jeb->used_size, jeb->free_size);

#if defined(JFFS2_DBG_DUMPS) || defined(JFFS2_DBG_PARANOIA_CHECKS)
		__jffs2_dbg_dump_node_refs_nolock(c, jeb);
#endif

		WARN_ON(1);

		ret = ref->__totlen;
	}
#endif /* TEST_TOTLEN */
	return ret;
}


text:
package org.medipi.clinical;

import java.io.File;
import java.util.Date;
import java.util.Properties;
import org.medipi.clinical.logging.MediPiLogger;
import org.medipi.clinical.services.SSLClientHttpRequestFactory;
import org.medipi.clinical.utilities.Utilities;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

/**
 * Class bootstrap the Spring Boot Application
 *
 * This class calls all the configuration necessary to boot the concentrator It
 * should be called using one argument - location of the MediPiConcentrator
 * properties file
 *
 * @author rick@robinsonhq.com
 */
@SpringBootApplication
@EnableAutoConfiguration
@Configuration
@ComponentScan
@EnableScheduling
public class MediPiClinicalSbApplication implements CommandLineRunner {

    private static final String LOG = "medipi.log";
    // MediPi version Number
    private static final String MEDIPINAME = "MediPi Clinical";
    private static final String VERSION = "MediPiClinical_v1.0.5";
    private static final String VERSIONNAME = "PILOT-20170921-1";
    private final MediPiLogger logger = MediPiLogger.getInstance();

    @Autowired
    private SSLClientHttpRequestFactory requestFactory;
    /**
     * Run method inherited by the commandLineRunner. This method sets the
     * version, calls the properties and utilities classes and instantiates any
     * formats used in transaction of data from MediPi Patient units to the
     * Concentrator
     *
     * @param args from the call of the Spring Boot Application
     * @throws Exception
     */
    @Override
    public void run(String... args) throws Exception {
        String prop = null;
        if (args.length != 2) {
            System.exit(1);
        } else {
            prop = args[0];
        }        // set versioning and print to standard output
        String versionIdent = MEDIPINAME + " " + VERSION + "-" + VERSIONNAME + " starting at " + new Date();
        System.out.println(versionIdent);

        MediPiProperties mpp = MediPiProperties.getInstance();

        if (!mpp.setProperties(prop)) {
            System.out.println("FATAL: Properties file failed to load");
            System.exit(1);
        }

        Properties properties = mpp.getProperties();
        // initialise utilities which is accessible to all classes which have reference to MediPi.class
        Utilities utils = Utilities.getInstance();
        utils.setProperties(properties);

        //Set up logging
        String log = properties.getProperty(LOG);
        if (log == null || log.trim().equals("")) {
            System.out.println(log + " - MediPi log directory is not set");
            System.exit(1);
        } else if (new File(log).isDirectory()) {
            logger.setAppName("MEDIPI", log);
            logger.log(MediPiClinicalSbApplication.class.getName() + "startup", versionIdent);
        } else {
            System.out.println("FATAL: " + log + " - MediPi log directory is not a directory");
            System.exit(1);
        }

        requestFactory = new SSLClientHttpRequestFactory();

        System.out.println("ServletContextListener started");

    }

    /**
     * Bean to make available the MediPiLogger object
     *
     * @return instance of MediPiLogger singleton
     */
    @Bean
    public MediPiLogger mediPiLogger() {
        return MediPiLogger.getInstance();
    }

    /**
     * Bean to make available the utils object
     *
     * @return instance of utils singleton
     */
    @Bean
    public Utilities utils() {
        return Utilities.getInstance();
    }

    /**
     *
     * @param args
     */
    public static void main(String[] args) {
        SpringApplication.run(MediPiClinicalSbApplication.class, args);
    }

}


text:
local ffi = require('ffi')
local spi = require('pllj.spi').spi
local bit = require("bit")

local C = ffi.C;

local trigger_event = {
    when ={
        [tonumber(C.TRIGGER_EVENT_BEFORE)] = "before",
        [tonumber(C.TRIGGER_EVENT_AFTER)] = "after",
        [tonumber(C.TRIGGER_EVENT_INSTEAD)] = "instead",
    },
    operation = {
        [tonumber(C.TRIGGER_EVENT_INSERT)] = "insert",
        [tonumber(C.TRIGGER_EVENT_DELETE)] = "delete",
        [tonumber(C.TRIGGER_EVENT_UPDATE)] = "update",
        [tonumber(C.TRIGGER_EVENT_TRUNCATE)] = "truncate",
    }
}

local tuple_to_lua_table = require('pllj.tuple_ops').tuple_to_lua_table
local lua_table_to_tuple = require('pllj.tuple_ops').lua_table_to_tuple

local G_mt
if __untrusted__ then
    G_mt = {__index = _G }
else
    local env = require('pllj.env').env
    G_mt = {__index = env }
end

local private_key = {}
local private_key_changes = {}
local proxy_mt = {
    __index = function(self, key)
        return self[private_key][key]
    end,
    __newindex = function(self, key, value)
        self[private_key][private_key_changes] = true
        self[private_key][key] = value
    end,
}
local function track(t)
    local proxy = {}
    proxy[private_key] = t
    setmetatable(proxy, proxy_mt)
    return proxy
end

local function trigger_handler(func_struct, fcinfo)
    if func_struct.prorettype ~= C.TRIGGEROID then
        return error('wrong trigger function')
    end
    local tdata = ffi.cast('TriggerData*', fcinfo.context)
    local trigger_level = bit.band(tdata.tg_event, C.TRIGGER_EVENT_ROW) and "row" or "statement"
    local trigger_operation = trigger_event.operation[bit.band(tdata.tg_event, C.TRIGGER_EVENT_OPMASK)]
    local trigger_when = trigger_event.when[bit.band(tdata.tg_event, C.TRIGGER_EVENT_TIMINGMASK)]

    local relname = ffi.string(tdata.tg_relation.rd_rel.relname.data)
    local namespace = ffi.string(C.get_namespace_name(tdata.tg_relation.rd_rel.relnamespace))
    local relation_oid = tonumber(tdata.tg_relation.rd_id)

    local tupleDesc = tdata.tg_relation.rd_att
    local row = tuple_to_lua_table(tupleDesc, tdata.tg_trigtuple)
    local old_row
    if trigger_level == "row" and trigger_operation == "update" then
        old_row = row
        row = tuple_to_lua_table(tupleDesc, tdata.tg_newtuple)
    end

    local trigger_name = ffi.string(tdata.tg_trigger.tgname)

    local trigger = {
        level = trigger_level,
        operation = trigger_operation,
        when = trigger_when,
        name = trigger_name,
        old = old_row,
        row = track(row),
        relation = {
            namespace = namespace,
            name = relname,
            oid = relation_oid
        }
    }

    local newgt = {trigger = trigger}
    setmetatable(newgt, G_mt)
    setfenv(func_struct.func, newgt)
    func_struct.func()

    if trigger_level == "row" and trigger_when == "before" then

        if row[private_key_changes] then
            return true, C.SPI_copytuple(lua_table_to_tuple(tupleDesc, row))
        end

        return true, tdata.tg_trigtuple
    end

end

return {
    trigger_handler = trigger_handler
}