text:
#include <stdio.h>
#include <string>

#include "EOSWeb.h"
#include "EOSLuaRuntime.h"

extern "C"
    {
    #include "lua.h"
    #include "lauxlib.h"
    #include "lualib.h"

    // -----------------------------------------------------------------------------
    // -----------------------------------------------------------------------------
    //
    // Module manifest structure. Developer must edit just the #define values below.
    //
    #define _MODULE_NAME            "web"
    #define _MODULE_VERSION         "0.1"
    #define _MODULE_DATE		    "November 09, 2012"
    #define _MODULE_DESC_SHORT      "somewhat powered web module for EOS Scripting Environment"
    #define _MODULE_DESC_LONG       ""
    #define _MODULE_AUTHOR_NAME     "EOS Scripting Team"
    #define _MODULE_AUTHOR_WEBSITE  "http://sourceforge.net/projects/eos-scripting/ | http://alex9978.blogspot.it/"
    //
    // -----------------------------------------------------------------------------
    // -----------------------------------------------------------------------------

    // utility functions -----------------------------------------------------
    // end utility functions -------------------------------------------------

    // ====================== COMMON REQUIRED FUNCTIONS ============================
    // -----------------------------------------------------------------------------

    static int moduleCleanup(lua_State* luaRuntime)
        {
        /*
         * insert here code for resources cleanup
         * on module unload (automatically done by kernel on close)
         */
        EOSLuaRuntime::getInstance()->logInfoMessage("[eos."_MODULE_NAME"] Shutting down...");
        //
        return 0;
        }

    // ====================== CUSTOM MODULE FUNCTIONS ==============================

    static int moduleInitialize(lua_State* luaRuntime)
        {
        bool done = false;
        //if(EOSLuaRuntime::checkLuaParameters(_MODULE_NAME, "initialize", 1))
            done = EOSWeb::getInstance()->initialize();
        //
        lua_pushboolean(luaRuntime, done);
        return 1;
        }

    /*- @function eos.audio.update
     *  @brief updates audio module status (at this time, this module does not need to be updated in order to work, however use it in order to guarantee future compatibility)
     *  @return updated (boolean) true or false
     */
    static int moduleUpdate(lua_State* luaRuntime)
        {
        bool done = true;
        EOSWeb::getInstance()->update();
        //
        lua_pushboolean(luaRuntime, done);
        return 1;
        }

    // -----------------------------------------------------------------------------

    /*- @function eos.web.load
	 *  @brief loads an image from file, and returns an EOSbject cointaining the pointer to the decoded image pixel buffer
	 *  @param imageFileName filename of the image to load
	 *  @return loadedImage an EOSbject cointaining the pointer to the decoded image pixel buffer
	 */
	static int load(lua_State* luaRuntime)
		{
		void* userdata = NULL;
		//
		if(EOSLuaRuntime::checkLuaParameters("eos."_MODULE_NAME, "eos."_MODULE_NAME"load", 1))
			{
			userdata = EOSWeb::getInstance()->load_webpage(luaL_checkstring(luaRuntime, 1));
			}
		//
		lua_pushlightuserdata(luaRuntime, userdata);
		return 1;
		}

    // -----------------------------------------------------------------------------
    // ========================== END LIBRARY FUNCTIONS ============================

    // ======================== LUA FUNCTIONS REGISTRATION =========================

    // ==== Here we declare an array with all functions and their respective names.
    // ==== This array has elements of type luaL_reg, which is a structure with
    // ==== two fields: a string and a function pointer.

    const struct luaL_reg fn_table_module [] = {
        {"cleanup", moduleCleanup},
        {"initialize", moduleInitialize},
        {NULL, NULL} // <-- end-of-table sentinel
        };

    const struct luaL_reg fn_table_main [] = {
        {"update", moduleUpdate},
        {"load", load},
        {NULL, NULL} // <-- end-of-table sentinel
        };

    // ==== Finally, we declare a main (initialization) function, using luaL_openlib:

    int _INIT_(lua_State* luaRuntime)
        {
        EOSLuaRuntime::getInstance()->setRuntime(luaRuntime);
        //
        // Never touch the manifest structure code below!
        EOSLuaRuntime::getInstance()->executeLuaChunk(
                  "eos."_MODULE_NAME" = {}\
                 eos.module._new = eos."_MODULE_NAME"\
                 eos.module._new.module                        = {}\
                 eos.module._new.module.info                   = {}\
                 eos.module._new.module.info.name              = '"_MODULE_NAME".eosmodule'\
                 eos.module._new.module.info.tableName         = 'eos."_MODULE_NAME"'\
                 eos.module._new.module.info.version           = '"_MODULE_VERSION"'\
                 eos.module._new.module.info.date              = '"_MODULE_DATE"'\
                 eos.module._new.module.info.description       = {}\
                 eos.module._new.module.info.description.short = '"_MODULE_DESC_SHORT"'\
                 eos.module._new.module.info.description.long  = '"_MODULE_DESC_LONG"'\
                 eos.module._new.module.info.author            = {}\
                 eos.module._new.module.info.author.name       = '"_MODULE_AUTHOR_NAME"'\
                 eos.module._new.module.info.author.website    = '"_MODULE_AUTHOR_WEBSITE"'\
                 eos.module._new.module.reservedFunctions         = {}\
                 eos.module._new.module.reservedFunctions.init    = ''\
                 eos.module._new.module.reservedFunctions.cleanup = 'eos."_MODULE_NAME".module.cleanup'\
                ");

        // registers "eos.*.module" functions
        luaL_register(luaRuntime, "eos."_MODULE_NAME".module", fn_table_module);

        // registers main functions
        luaL_register(luaRuntime, "eos."_MODULE_NAME, fn_table_main);

        //
        //
        return 1;
        }

    // -----------------------------------------------------------------------------

    } // extern "C" closure


text:
using System;
using System.Collections.Generic;

namespace Nuxleus.WebService {

    public struct PutObjectRequest : IRequest {

        String m_requestBody;

        #region IRequest Members

        public KeyValuePair<string, string>[] Headers {
            get {
                return
                    new KeyValuePair<string, string>[] {
                        //new KeyValuePair<string,string>("SOAPAction", LabelAttribute.FromMember(RequestType)),
                    };
            }
        }

        public Uri RequestUri { get; set; }

        public RequestType RequestType {
            get {
                return RequestType.PUT;
            }
        }

        public String RequestMessage {
            get {
                return m_requestBody;
            }
            set {
                m_requestBody = value;
            }
        }

        #endregion
    }
}

redpajama_set_name: RedPajamaGithub


text:
/**
 * @module PreloadJS
 */

// namespace:
this.createjs = this.createjs || {};

(function () {
	"use strict";

	// constructor
	/**
	 * An {{#crossLink "AbstractRequest"}}{{/crossLink}} that loads HTML tags, such as images and scripts.
	 * @class TagRequest
	 * @param {LoadItem} loadItem
	 * @param {HTMLElement} tag
	 * @param {String} srcAttribute The tag attribute that specifies the source, such as "src", "href", etc.
	 */
	function TagRequest(loadItem, tag, srcAttribute) {
		this.AbstractRequest_constructor(loadItem);

		// protected properties
		/**
		 * The HTML tag instance that is used to load.
		 * @property _tag
		 * @type {HTMLElement}
		 * @protected
		 */
		this._tag = tag;

		/**
		 * The tag attribute that specifies the source, such as "src", "href", etc.
		 * @property _tagSrcAttribute
		 * @type {String}
		 * @protected
		 */
		this._tagSrcAttribute = srcAttribute;

		/**
		 * A method closure used for handling the tag load event.
		 * @property _loadedHandler
		 * @type {Function}
		 * @private
		 */
		this._loadedHandler = createjs.proxy(this._handleTagComplete, this);

		/**
		 * Determines if the element was added to the DOM automatically by PreloadJS, so it can be cleaned up after.
		 * @property _addedToDOM
		 * @type {Boolean}
		 * @private
		 */
		this._addedToDOM = false;

		/**
		 * Determines what the tags initial style.visibility was, so we can set it correctly after a load.
		 *
		 * @type {null}
		 * @private
		 */
		this._startTagVisibility = null;
	};

	var p = createjs.extend(TagRequest, createjs.AbstractRequest);

	// public methods
	p.load = function () {
		this._tag.onload = createjs.proxy(this._handleTagComplete, this);
		this._tag.onreadystatechange = createjs.proxy(this._handleReadyStateChange, this);
		this._tag.onerror = createjs.proxy(this._handleError, this);

		var evt = new createjs.Event("initialize");
		evt.loader = this._tag;

		this.dispatchEvent(evt);

		this._hideTag();

		this._loadTimeout = setTimeout(createjs.proxy(this._handleTimeout, this), this._item.loadTimeout);

		this._tag[this._tagSrcAttribute] = this._item.src;

		// wdg:: Append the tag AFTER setting the src, or SVG loading on iOS will fail.
		if (this._tag.parentNode == null) {
			createjs.DomUtils.appendToBody(this._tag);
			this._addedToDOM = true;
		}
	};

	p.destroy = function() {
		this._clean();
		this._tag = null;

		this.AbstractRequest_destroy();
	};

	// private methods
	/**
	 * Handle the readyStateChange event from a tag. We need this in place of the `onload` callback (mainly SCRIPT
	 * and LINK tags), but other cases may exist.
	 * @method _handleReadyStateChange
	 * @private
	 */
	p._handleReadyStateChange = function () {
		clearTimeout(this._loadTimeout);
		// This is strictly for tags in browsers that do not support onload.
		var tag = this._tag;

		// Complete is for old IE support.
		if (tag.readyState == "loaded" || tag.readyState == "complete") {
			this._handleTagComplete();
		}
	};

	/**
	 * Handle any error events from the tag.
	 * @method _handleError
	 * @protected
	 */
	p._handleError = function() {
		this._clean();
		this.dispatchEvent("error");
	};

	/**
	 * Handle the tag's onload callback.
	 * @method _handleTagComplete
	 * @private
	 */
	p._handleTagComplete = function () {
		this._rawResult = this._tag;
		this._result = this.resultFormatter && this.resultFormatter(this) || this._rawResult;

		this._clean();
		this._showTag();

		this.dispatchEvent("complete");
	};

	/**
	 * The tag request has not loaded within the time specified in loadTimeout.
	 * @method _handleError
	 * @param {Object} event The XHR error event.
	 * @private
	 */
	p._handleTimeout = function () {
		this._clean();
		this.dispatchEvent(new createjs.Event("timeout"));
	};

	/**
	 * Remove event listeners, but don't destroy the request object
	 * @method _clean
	 * @private
	 */
	p._clean = function() {
		this._tag.onload = null;
		this._tag.onreadystatechange = null;
		this._tag.onerror = null;
		if (this._addedToDOM && this._tag.parentNode != null) {
			this._tag.parentNode.removeChild(this._tag);
		}
		clearTimeout(this._loadTimeout);
	};

	p._hideTag = function() {
		this._startTagVisibility = this._tag.style.visibility;
		this._tag.style.visibility = "hidden";
	};

	p._showTag = function() {
		this._tag.style.visibility = this._startTagVisibility;
	};

	/**
	 * Handle a stalled audio event. The main place this happens is with HTMLAudio in Chrome when playing back audio
	 * that is already in a load, but not complete.
	 * @method _handleStalled
	 * @private
	 */
	p._handleStalled = function () {
		//Ignore, let the timeout take care of it. Sometimes its not really stopped.
	};

	createjs.TagRequest = createjs.promote(TagRequest, "AbstractRequest");

}());


text:
/// jpeg loader, (C) crow_riot 2013

#include "imagelib.h"
#include "imagelib_priv.h"

#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <jpeglib.h>
#include <jerror.h>

/// stackoverflow <3
/// http://stackoverflow.com/questions/5280756/libjpeg-ver-6b-jpeg-stdio-src-vs-jpeg-mem-src

/* Read JPEG image from a memory segment */
static void init_source (j_decompress_ptr cinfo) {}
static boolean fill_input_buffer (j_decompress_ptr cinfo)
{
    ERREXIT(cinfo, JERR_INPUT_EMPTY);
    return TRUE;
}
static void skip_input_data (j_decompress_ptr cinfo, long num_bytes)
{
    struct jpeg_source_mgr* src = (struct jpeg_source_mgr*) cinfo->src;

    if (num_bytes > 0) {
        src->next_input_byte += (size_t) num_bytes;
        src->bytes_in_buffer -= (size_t) num_bytes;
    }
}
static void term_source (j_decompress_ptr cinfo) {}
static void jpeg_mem_src (j_decompress_ptr cinfo, void* buffer, long nbytes)
{
    struct jpeg_source_mgr* src;

    if (cinfo->src == NULL) {   /* first time for this JPEG object? */
        cinfo->src = (struct jpeg_source_mgr *)
            (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
            sizeof(struct jpeg_source_mgr));
    }

    src = (struct jpeg_source_mgr*) cinfo->src;
    src->init_source = init_source;
    src->fill_input_buffer = fill_input_buffer;
    src->skip_input_data = skip_input_data;
    src->resync_to_restart = jpeg_resync_to_restart; /* use default method */
    src->term_source = term_source;
    src->bytes_in_buffer = nbytes;
    src->next_input_byte = (JOCTET*)buffer;
}

image_t* imagelib_load_jpeg_from_mem(char* buf, size_t size, const imageloadersettings_t settings)
{
    struct jpeg_decompress_struct cinfo;
    struct jpeg_error_mgr jerr;
    JSAMPLE *buffer;
    int x;

    cinfo.err = jpeg_std_error(&jerr);

    jpeg_create_decompress(&cinfo);

    //jpeg_stdio_src(&cinfo,fp);
    jpeg_mem_src(&cinfo,buf,size);

    if (jpeg_read_header(&cinfo,1)!=JPEG_HEADER_OK) {
        return NULL;
    }
    if(!jpeg_start_decompress(&cinfo)) {
        return NULL;
    }
    if (cinfo.output_components!=3) {
        jpeg_finish_decompress(&cinfo);
        jpeg_destroy_decompress(&cinfo);
        return NULL;
    }
    int stride = cinfo.output_width * cinfo.output_components;

    image_t *image = malloc(sizeof(image_t));

    image->width = cinfo.output_width;
    image->height = cinfo.output_height;

    if (settings.forcergba) {
        image->bpp = 4;
    } else {
        image->bpp = cinfo.output_components;
    }

    buffer = malloc(stride * sizeof(JSAMPLE));
    image->data = malloc(sizeof(unsigned char)*image->width*image->height*image->bpp);
    int ro = settings.swaprb ? 2 : 0;
    int bo = settings.swaprb ? 0 : 2;

    while (cinfo.output_scanline<cinfo.output_height){
        jpeg_read_scanlines(&cinfo,&buffer,1);

        unsigned char* trg = image->data + image->width*image->bpp*cinfo.output_scanline;
        if (settings.forcergba) {
            for (x=0; x<cinfo.output_width;x++) {
                int tx = x<<2;
                int sx = x*cinfo.output_components;

                trg[tx+0] = buffer[sx+ro];
                trg[tx+1] = buffer[sx+1];
                trg[tx+2] = buffer[sx+bo];
                trg[tx+3] = settings.alpha;
            }
        }
        else {
            for (x=0; x<cinfo.output_width;x++) {
                int tx = x<<2;
                int sx = x*cinfo.output_components;

                trg[tx+0] = buffer[sx+ro];
                trg[tx+1] = buffer[sx+1];
                trg[tx+2] = buffer[sx+bo];
            }
        }
    }

    jpeg_finish_decompress(&cinfo);

    jpeg_destroy_decompress(&cinfo);

    return image;
}


text:
import urllib, hashlib, sys, os
from optparse import OptionParser

class AppURLopener(urllib.FancyURLopener):
    version ="Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en-US; rv:1.8.0.7) Gecko/20060909 Firefox/1.5.0.7"

    def prompt_user_passwd(self, host, realm):
        raise Exception()
urllib._urlopener = AppURLopener()

def file_md5(file):
    m = hashlib.md5()
    m.update(open(dest).read())
    return m.hexdigest()

def main():
    parser = OptionParser(usage="usage: %prog URI dest [md5sum]", prog=sys.argv[0])
    options, args = parser.parse_args()
    md5sum = None

    if len(args)==2:
        uri, dest = args
    elif len(args)==3:
        uri, dest, md5 = args
    else:
        parser.error("Wrong arguments")

    fresh = False
    if not os.path.exists(dest):
        print "Downloading from %s to %s..."%(uri, dest),
        sys.stdout.flush()
        urllib.urlretrieve(uri, dest)
        print "done"
        fresh = True

    if md5sum:
        print "Computing md5sum on downloaded file",
        sys.stdout.flush()
        checksum = md5_file(dest)
        print "done"

        if checksum!=md5sum:
            if not fresh:
                print "Checksum mismatch (%s != %s), re-downloading file %s"%(checksum, md5sum, dest),
                sys.stdout.flush()
                os.remove(dest)
                urllib.urlretrieve(uri, dest)
                print "done"

                print "Computing md5sum on downloaded file",
                sys.stdout.flush()
                checksum = md5_file(dest)
                print "done"

                if checksum!=md5sum:
                    print "ERROR, checksum mismatch (%s != %s) on %d",(checksum, md5sum, dest)
                    return 1
    return 0

if __name__ == '__main__':
    try:
        sys.exit(main())
    except Exception as e:
        print "ERROR, ",e
        sys.exit(1)


text:
@interface ABI43_0_0EXCamera ()

@property (nonatomic, weak) id<ABI43_0_0EXFileSystemInterface> fileSystem;
@property (nonatomic, weak) ABI43_0_0EXModuleRegistry *moduleRegistry;
@property (nonatomic, strong) id<ABI43_0_0EXFaceDetectorManagerInterface> faceDetectorManager;
@property (nonatomic, strong) id<ABI43_0_0EXBarCodeScannerInterface> barCodeScanner;
@property (nonatomic, weak) id<ABI43_0_0EXPermissionsInterface> permissionsManager;
@property (nonatomic, weak) id<ABI43_0_0EXAppLifecycleService> lifecycleManager;

@property (nonatomic, assign, getter=isSessionPaused) BOOL paused;
@property (nonatomic, assign) BOOL isValidVideoOptions;

@property (nonatomic, strong) NSDictionary *photoCaptureOptions;
@property (nonatomic, strong) ABI43_0_0EXPromiseResolveBlock photoCapturedResolve;
@property (nonatomic, strong) ABI43_0_0EXPromiseRejectBlock photoCapturedReject;

@property (nonatomic, strong) ABI43_0_0EXPromiseResolveBlock videoRecordedResolve;
@property (nonatomic, strong) ABI43_0_0EXPromiseRejectBlock videoRecordedReject;

@property (nonatomic, copy) ABI43_0_0EXDirectEventBlock onCameraReady;
@property (nonatomic, copy) ABI43_0_0EXDirectEventBlock onMountError;
@property (nonatomic, copy) ABI43_0_0EXDirectEventBlock onPictureSaved;

@property (nonatomic, copy) ABI43_0_0EXDirectEventBlock onBarCodeScanned;
@property (nonatomic, copy) ABI43_0_0EXDirectEventBlock onFacesDetected;

@end

@implementation ABI43_0_0EXCamera

static NSDictionary *defaultFaceDetectorOptions = nil;

- (id)initWithModuleRegistry:(ABI43_0_0EXModuleRegistry *)moduleRegistry
{
  if ((self = [super init])) {
    _moduleRegistry = moduleRegistry;
    _session = [AVCaptureSession new];
    _sessionQueue = dispatch_queue_create("cameraQueue", DISPATCH_QUEUE_SERIAL);
    _faceDetectorManager = [self createFaceDetectorManager];
    _barCodeScanner = [self createBarCodeScanner];
    _lifecycleManager = [moduleRegistry getModuleImplementingProtocol:@protocol(ABI43_0_0EXAppLifecycleService)];
    _fileSystem = [moduleRegistry getModuleImplementingProtocol:@protocol(ABI43_0_0EXFileSystemInterface)];
    _permissionsManager = [moduleRegistry getModuleImplementingProtocol:@protocol(ABI43_0_0EXPermissionsInterface)];
#if !(TARGET_IPHONE_SIMULATOR)
    _previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:_session];
    _previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    _previewLayer.needsDisplayOnBoundsChange = YES;
#endif
    _paused = NO;
    _isValidVideoOptions = YES;
    _pictureSize = AVCaptureSessionPresetHigh;
    [self changePreviewOrientation:[UIApplication sharedApplication].statusBarOrientation];
    [self initializeCaptureSessionInput];
    [self startSession];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(orientationChanged:)
                                                 name:UIDeviceOrientationDidChangeNotification
                                               object:nil];
    [_lifecycleManager registerAppLifecycleListener:self];
  }
  return self;
}

- (void)dealloc
{
  // In very rare case ABI43_0_0EXCamera might be unmounted (and thus deallocated) after starting taking a photo,
  // but still before callbacks from AVCapturePhotoCaptureDelegate are fired (that means before results from taking a photo are handled).
  // This scenario leads to a state when AVCapturePhotoCaptureDelegate is `nil` and
  // neither self.photoCapturedResolve nor self.photoCapturedResolve is called.
  // To prevent hanging promise let's reject here.
  if (_photoCapturedReject) {
    _photoCapturedReject(@"E_IMAGE_CAPTURE_FAILED", @"Camera unmounted during taking photo process.", nil);
  }
}

- (void)onReady:(NSDictionary *)event
{
  if (_onCameraReady) {
    _onCameraReady(nil);
  }
}

- (void)onMountingError:(NSDictionary *)event
{
  if (_onMountError) {
    _onMountError(event);
  }
}

- (void)onBarCodeScanned:(NSDictionary *)event
{
  if (_onBarCodeScanned) {
    _onBarCodeScanned(event);
  }
}

- (void)onPictureSaved:(NSDictionary *)event
{
  if (_onPictureSaved) {
    _onPictureSaved(event);
  }
}

- (void)layoutSubviews
{
  [super layoutSubviews];
  _previewLayer.frame = self.bounds;
  [self setBackgroundColor:[UIColor blackColor]];
  [self.layer insertSublayer:_previewLayer atIndex:0];
}

- (void)removeFromSuperview
{
  [_lifecycleManager unregisterAppLifecycleListener:self];
  [self stopSession];
  [super removeFromSuperview];
  [[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil];
}

- (void)updateType
{
  ABI43_0_0EX_WEAKIFY(self);
  dispatch_async(_sessionQueue, ^{
    ABI43_0_0EX_ENSURE_STRONGIFY(self);
    [self initializeCaptureSessionInput];
    if (!self.session.isRunning) {
      [self startSession];
    }
  });
}

- (void)updateFlashMode
{
  AVCaptureDevice *device = [_videoCaptureDeviceInput device];
  NSError *error = nil;

  if (_flashMode == ABI43_0_0EXCameraFlashModeTorch) {
    if (![device hasTorch]) {
      return;
    }

    if (![device lockForConfiguration:&error]) {
      if (error) {
        ABI43_0_0EXLogInfo(@"%s: %@", __func__, error);
      }
      return;
    }

    if ([device hasTorch] && [device isTorchModeSupported:AVCaptureTorchModeOn]) {
      if ([device lockForConfiguration:&error]) {
        [device setTorchMode:AVCaptureTorchModeOn];
        [device unlockForConfiguration];
      } else {
        if (error) {
          ABI43_0_0EXLogInfo(@"%s: %@", __func__, error);
        }
      }
    }
  } else {
    if (![device hasFlash]) {
      return;
    }

    if (![device lockForConfiguration:&error]) {
      if (error) {
        ABI43_0_0EXLogInfo(@"%s: %@", __func__, error);
      }
      return;
    }

    if ([device hasFlash])
    {
      if ([device lockForConfiguration:&error]) {
        if ([device isTorchModeSupported:AVCaptureTorchModeOff]) {
          [device setTorchMode:AVCaptureTorchModeOff];
        }
        [device unlockForConfiguration];
      } else {
        if (error) {
          ABI43_0_0EXLogInfo(@"%s: %@", __func__, error);
        }
      }
    }
  }

  [device unlockForConfiguration];
}

- (void)updateFocusMode
{
  AVCaptureDevice *device = [_videoCaptureDeviceInput device];
  NSError *error = nil;

  if (![device lockForConfiguration:&error]) {
    if (error) {
      ABI43_0_0EXLogInfo(@"%s: %@", __func__, error);
    }
    return;
  }

  if ([device isFocusModeSupported:_autoFocus]) {
    if ([device lockForConfiguration:&error]) {
      [device setFocusMode:_autoFocus];
    } else {
      if (error) {
        ABI43_0_0EXLogInfo(@"%s: %@", __func__, error);
      }
    }
  }

  [device unlockForConfiguration];
}

- (void)updateFocusDepth
{
  AVCaptureDevice *device = [_videoCaptureDeviceInput device];
  NSError *error = nil;

  if (device == nil || device.focusMode != ABI43_0_0EXCameraAutoFocusOff) {
    return;
  }

  if ([device isLockingFocusWithCustomLensPositionSupported]) {
    if (![device lockForConfiguration:&error]) {
      if (error) {
        ABI43_0_0EXLogInfo(@"%s: %@", __func__, error);
      }
      return;
    }

    ABI43_0_0EX_WEAKIFY(device);
    [device setFocusModeLockedWithLensPosition:_focusDepth completionHandler:^(CMTime syncTime) {
      ABI43_0_0EX_ENSURE_STRONGIFY(device);
      [device unlockForConfiguration];
    }];
    return;
  }

  ABI43_0_0EXLogInfo(@"%s: Setting focusDepth isn't supported for this camera device", __func__);
  return;
}

- (void)updateZoom {
  AVCaptureDevice *device = [_videoCaptureDeviceInput device];
  NSError *error = nil;

  if (![device lockForConfiguration:&error]) {
    if (error) {
      ABI43_0_0EXLogInfo(@"%s: %@", __func__, error);
    }
    return;
  }

  device.videoZoomFactor = (device.activeFormat.videoMaxZoomFactor - 1.0) * _zoom + 1.0;

  [device unlockForConfiguration];
}

- (void)updateWhiteBalance
{
  AVCaptureDevice *device = [_videoCaptureDeviceInput device];
  NSError *error = nil;

  if (![device lockForConfiguration:&error]) {
    if (error) {
      ABI43_0_0EXLogInfo(@"%s: %@", __func__, error);
    }
    return;
  }

  if (_whiteBalance == ABI43_0_0EXCameraWhiteBalanceAuto) {
    [device setWhiteBalanceMode:AVCaptureWhiteBalanceModeContinuousAutoWhiteBalance];
    [device unlockForConfiguration];
  } else {
    AVCaptureWhiteBalanceTemperatureAndTintValues temperatureAndTint = {
      .temperature = [ABI43_0_0EXCameraUtils temperatureForWhiteBalance:_whiteBalance],
      .tint = 0,
    };
    AVCaptureWhiteBalanceGains rgbGains = [device deviceWhiteBalanceGainsForTemperatureAndTintValues:temperatureAndTint];
    if ([device lockForConfiguration:&error]) {
      ABI43_0_0EX_WEAKIFY(device);
      [device setWhiteBalanceModeLockedWithDeviceWhiteBalanceGains:rgbGains completionHandler:^(CMTime syncTime) {
        ABI43_0_0EX_ENSURE_STRONGIFY(device);
        [device unlockForConfiguration];
      }];
    } else {
      if (error) {
        ABI43_0_0EXLogInfo(@"%s: %@", __func__, error);
      }
    }
  }

  [device unlockForConfiguration];
}

- (void)updatePictureSize
{
  [self updateSessionPreset:_pictureSize];
}

- (void)setIsScanningBarCodes:(BOOL)barCodeScanning
{
  if (_barCodeScanner) {
    [_barCodeScanner setIsEnabled:barCodeScanning];
  } else if (barCodeScanning) {
    ABI43_0_0EXLogError(@"BarCodeScanner module not found. Make sure `expo-barcode-scanner` is installed and linked correctly.");
  }
}

- (void)setBarCodeScannerSettings:(NSDictionary *)settings
{
  if (_barCodeScanner) {
    [_barCodeScanner setSettings:settings];
  }
}

- (void)setIsDetectingFaces:(BOOL)faceDetecting
{
  if (_faceDetectorManager) {
    [_faceDetectorManager setIsEnabled:faceDetecting];
  } else if (faceDetecting) {
    ABI43_0_0EXLogError(@"FaceDetector module not found. Make sure `expo-face-detector` is installed and linked correctly.");
  }
}

- (void)updateFaceDetectorSettings:(NSDictionary *)settings
{
  if (_faceDetectorManager) {
    [_faceDetectorManager updateSettings:settings];
  }
}

- (void)takePicture:(NSDictionary *)options resolve:(ABI43_0_0EXPromiseResolveBlock)resolve reject:(ABI43_0_0EXPromiseRejectBlock)reject
{
  if (_photoCapturedResolve) {
    reject(@"E_ANOTHER_CAPTURE", @"Another photo capture is already being processed. Await the first call.", nil);
    return;
  }
  if (!_photoOutput) {
    reject(@"E_IMAGE_CAPTURE_FAILED", @"Camera is not ready yet. Wait for 'onCameraReady' callback.", nil);
    return;
  }
  AVCaptureConnection *connection = [_photoOutput connectionWithMediaType:AVMediaTypeVideo];
  [connection setVideoOrientation:[ABI43_0_0EXCameraUtils videoOrientationForDeviceOrientation:[[UIDevice currentDevice] orientation]]];

  _photoCapturedReject = reject;
  _photoCapturedResolve = resolve;
  _photoCaptureOptions = options;

  AVCapturePhotoSettings *outputSettings = [AVCapturePhotoSettings photoSettingsWithFormat:@{AVVideoCodecKey : AVVideoCodecJPEG}];
  outputSettings.highResolutionPhotoEnabled = YES;
  AVCaptureFlashMode requestedFlashMode = AVCaptureFlashModeOff;
  switch (_flashMode) {
    case ABI43_0_0EXCameraFlashModeOff:
      requestedFlashMode = AVCaptureFlashModeOff;
      break;
    case ABI43_0_0EXCameraFlashModeAuto:
      requestedFlashMode = AVCaptureFlashModeAuto;
      break;
    case ABI43_0_0EXCameraFlashModeOn:
    case ABI43_0_0EXCameraFlashModeTorch:
      requestedFlashMode = AVCaptureFlashModeOn;
      break;
  }
  if ([[_photoOutput supportedFlashModes] containsObject:@(requestedFlashMode)]) {
    outputSettings.flashMode = requestedFlashMode;
  }
  [_photoOutput capturePhotoWithSettings:outputSettings delegate:self];
}

- (void)captureOutput:(AVCapturePhotoOutput *)output
didFinishProcessingPhotoSampleBuffer:(CMSampleBufferRef)photoSampleBuffer
previewPhotoSampleBuffer:(CMSampleBufferRef)previewPhotoSampleBuffer
     resolvedSettings:(AVCaptureResolvedPhotoSettings *)resolvedSettings
      bracketSettings:(AVCaptureBracketedStillImageSettings *)bracketSettings
                error:(NSError *)error
{
  NSDictionary *options = _photoCaptureOptions;
  ABI43_0_0EXPromiseRejectBlock reject = _photoCapturedReject;
  ABI43_0_0EXPromiseResolveBlock resolve = _photoCapturedResolve;
  _photoCapturedResolve = nil;
  _photoCapturedReject = nil;
  _photoCaptureOptions = nil;

  if (error || !photoSampleBuffer) {
    reject(@"E_IMAGE_CAPTURE_FAILED", @"Image could not be captured", error);
    return;
  }

  if (!self.fileSystem) {
    reject(@"E_IMAGE_CAPTURE_FAILED", @"No file system module", nil);
    return;
  }

  NSData *imageData = [AVCapturePhotoOutput JPEGPhotoDataRepresentationForJPEGSampleBuffer:photoSampleBuffer previewPhotoSampleBuffer:previewPhotoSampleBuffer];

  CGImageSourceRef sourceCGIImageRef = CGImageSourceCreateWithData((CFDataRef) imageData, NULL);
  NSDictionary *sourceMetadata = (__bridge NSDictionary *) CGImageSourceCopyPropertiesAtIndex(sourceCGIImageRef, 0, NULL);
  [self handleCapturedImageData:imageData metadata:sourceMetadata options:options resolver:resolve reject:reject];
  CFRelease(sourceCGIImageRef);
}

- (void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhoto:(AVCapturePhoto *)photo error:(NSError *)error
{
  NSDictionary *options = _photoCaptureOptions;
  ABI43_0_0EXPromiseRejectBlock reject = _photoCapturedReject;
  ABI43_0_0EXPromiseResolveBlock resolve = _photoCapturedResolve;
  _photoCapturedResolve = nil;
  _photoCapturedReject = nil;
  _photoCaptureOptions = nil;

  if (error || !photo) {
    reject(@"E_IMAGE_CAPTURE_FAILED", @"Image could not be captured", error);
    return;
  }

  if (!self.fileSystem) {
    reject(@"E_IMAGE_CAPTURE_FAILED", @"No file system module", nil);
    return;
  }

  NSData *imageData = [photo fileDataRepresentation];
  [self handleCapturedImageData:imageData metadata:photo.metadata options:options resolver:resolve reject:reject];
}

- (void)handleCapturedImageData:(NSData *)imageData metadata:(NSDictionary *)metadata options:(NSDictionary *)options resolver:(ABI43_0_0EXPromiseResolveBlock)resolve reject:(ABI43_0_0EXPromiseRejectBlock)reject
{
  UIImage *takenImage = [UIImage imageWithData:imageData];
  BOOL useFastMode = [options[@"fastMode"] boolValue];
  if (useFastMode) {
    resolve(nil);
  }

  CGSize previewSize;
  if (UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation])) {
    previewSize = CGSizeMake(self.previewLayer.frame.size.height, self.previewLayer.frame.size.width);
  } else {
    previewSize = CGSizeMake(self.previewLayer.frame.size.width, self.previewLayer.frame.size.height);
  }

  CGImageRef takenCGImage = takenImage.CGImage;
  CGRect cropRect = CGRectMake(0, 0, CGImageGetWidth(takenCGImage), CGImageGetHeight(takenCGImage));
  CGRect croppedSize = AVMakeRectWithAspectRatioInsideRect(previewSize, cropRect);
  takenImage = [ABI43_0_0EXCameraUtils cropImage:takenImage toRect:croppedSize];

  NSString *path = [self.fileSystem generatePathInDirectory:[self.fileSystem.cachesDirectory stringByAppendingPathComponent:@"Camera"] withExtension:@".jpg"];
  float width = takenImage.size.width;
  float height = takenImage.size.height;
  NSData *processedImageData = nil;
  float quality = [options[@"quality"] floatValue];

  NSMutableDictionary *response = [[NSMutableDictionary alloc] init];
  if ([options[@"exif"] boolValue]) {
    NSMutableDictionary *updatedExif = [ABI43_0_0EXCameraUtils updateExifMetadata:metadata[(NSString *)kCGImagePropertyExifDictionary] withAdditionalData:@{ @"Orientation": @([ABI43_0_0EXCameraUtils exportImageOrientation:takenImage.imageOrientation]) }];
    updatedExif[(NSString *)kCGImagePropertyExifPixelYDimension] = @(width);
    updatedExif[(NSString *)kCGImagePropertyExifPixelXDimension] = @(height);
    response[@"exif"] = updatedExif;

    NSMutableDictionary *updatedMetadata = [metadata mutableCopy];
    updatedMetadata[(NSString *)kCGImagePropertyExifDictionary] = updatedExif;

    // UIImage does not contain metadata information. We need to add them to CGImage manually.
    processedImageData = [ABI43_0_0EXCameraUtils dataFromImage:takenImage withMetadata:updatedMetadata imageQuality:quality];
  } else {
    processedImageData = UIImageJPEGRepresentation(takenImage, quality);
  }

  if (!processedImageData) {
    return reject(@"E_IMAGE_SAVE_FAILED", @"Could not save the image.", nil);
  }

  response[@"uri"] = [ABI43_0_0EXCameraUtils writeImage:processedImageData toPath:path];
  response[@"width"] = @(width);
  response[@"height"] = @(height);

  if ([options[@"base64"] boolValue]) {
    response[@"base64"] = [processedImageData base64EncodedStringWithOptions:0];
  }

  if ([options[@"fastMode"] boolValue]) {
    [self onPictureSaved:@{@"data": response, @"id": options[@"id"]}];
  } else {
    resolve(response);
  }
}

- (void)record:(NSDictionary *)options resolve:(ABI43_0_0EXPromiseResolveBlock)resolve reject:(ABI43_0_0EXPromiseRejectBlock)reject
{
  if (_movieFileOutput == nil) {
    // At the time of writing AVCaptureMovieFileOutput and AVCaptureVideoDataOutput (> GMVDataOutput)
    // cannot coexist on the same AVSession (see: https://stackoverflow.com/a/4986032/1123156).
    // We stop face detection here and restart it in when AVCaptureMovieFileOutput finishes recording.
    if (_faceDetectorManager) {
      [_faceDetectorManager stopFaceDetection];
    }
    [self setupMovieFileCapture];
  }

  if (_movieFileOutput != nil && !_movieFileOutput.isRecording && _videoRecordedResolve == nil && _videoRecordedReject == nil) {
    bool shouldBeMuted = options[@"mute"] && [options[@"mute"] boolValue];
    [self updateSessionAudioIsMuted:shouldBeMuted];

    AVCaptureConnection *connection = [_movieFileOutput connectionWithMediaType:AVMediaTypeVideo];
    // TODO: Add support for videoStabilizationMode (right now it is not only read, never written to)
    if (connection.isVideoStabilizationSupported == NO) {
      ABI43_0_0EXLogWarn(@"%s: Video Stabilization is not supported on this device.", __func__);
    } else {
      [connection setPreferredVideoStabilizationMode:self.videoStabilizationMode];
    }
    [connection setVideoOrientation:[ABI43_0_0EXCameraUtils videoOrientationForDeviceOrientation:[[UIDevice currentDevice] orientation]]];

    AVCaptureSessionPreset preset;
    if (options[@"quality"]) {
      ABI43_0_0EXCameraVideoResolution resolution = [options[@"quality"] integerValue];
      preset = [ABI43_0_0EXCameraUtils captureSessionPresetForVideoResolution:resolution];
    } else if ([self.session.sessionPreset isEqual:AVCaptureSessionPresetPhoto]) {
      preset = AVCaptureSessionPresetHigh;
    }

    if (preset != nil) {
      [self updateSessionPreset:preset];
    }

    [self setVideoOptions:options forConnection:connection onReject:reject];

    bool canBeMirrored = connection.isVideoMirroringSupported;
    bool shouldBeMirrored = options[@"mirror"] && [options[@"mirror"] boolValue];
    if (canBeMirrored && shouldBeMirrored) {
      [connection setVideoMirrored:shouldBeMirrored];
    }

    ABI43_0_0EX_WEAKIFY(self);
    dispatch_async(self.sessionQueue, ^{
      ABI43_0_0EX_STRONGIFY(self);
      // it is possible that the session has been invalidated at this point
      // for example, the video codec option is invalid and so this call has already rejected
      if (!self.isValidVideoOptions) {
        return;
      }

      if (!self) {
        reject(@"E_IMAGE_SAVE_FAILED", @"Camera view has been unmounted.", nil);
        return;
      }
      if (!self.fileSystem) {
        reject(@"E_IMAGE_SAVE_FAILED", @"No file system module", nil);
        return;
      }
      NSString *directory = [self.fileSystem.cachesDirectory stringByAppendingPathComponent:@"Camera"];
      NSString *path = [self.fileSystem generatePathInDirectory:directory withExtension:@".mov"];
      NSURL *outputURL = [[NSURL alloc] initFileURLWithPath:path];
      [self.movieFileOutput startRecordingToOutputFileURL:outputURL recordingDelegate:self];
      self.videoRecordedResolve = resolve;
      self.videoRecordedReject = reject;
    });
  }
}

// Video options are set in an async block to prevent the possible race condition outlined here:
// https://github.com/react-native-camera/react-native-camera/pull/2694
- (void)setVideoOptions:(NSDictionary *)options forConnection:(AVCaptureConnection *)connection onReject:(ABI43_0_0EXPromiseRejectBlock)reject
{
  ABI43_0_0EX_WEAKIFY(self);
  dispatch_async(_sessionQueue, ^{
    ABI43_0_0EX_STRONGIFY(self);
    // Reset validation flag
    self.isValidVideoOptions = YES;

    if (options[@"maxDuration"]) {
      Float64 maxDuration = [options[@"maxDuration"] floatValue];
      self.movieFileOutput.maxRecordedDuration = CMTimeMakeWithSeconds(maxDuration, 30);
    }

    if (options[@"maxFileSize"]) {
      self.movieFileOutput.maxRecordedFileSize = [options[@"maxFileSize"] integerValue];
    }

    if (options[@"codec"]) {
      AVVideoCodecType videoCodecType = [ABI43_0_0EXCameraUtils videoCodecForType: [options[@"codec"] integerValue]];

      if ([self.movieFileOutput.availableVideoCodecTypes containsObject:videoCodecType]) {
        [self.movieFileOutput setOutputSettings: @{AVVideoCodecKey: videoCodecType} forConnection: connection];
        self.videoCodecType = videoCodecType;
      } else {
        if ([videoCodecType isEqualToString: @"VIDEO_CODEC_UNKNOWN"]) {
          videoCodecType = options[@"codec"];
        }
        NSString *videoCodecErrorMessage = [NSString stringWithFormat: @"Video Codec '%@' is not supported on this device", videoCodecType];
        reject(@"E_RECORDING_FAILED", videoCodecErrorMessage, nil);

        [self cleanupMovieFileCapture];
        self.videoRecordedResolve = nil;
        self.videoRecordedReject = nil;
        self.isValidVideoOptions = NO;
      }
    }

  });
}

- (void)maybeStartFaceDetection:(BOOL)mirrored {
  if (self.faceDetectorManager) {
    AVCaptureConnection *connection = [self.photoOutput connectionWithMediaType:AVMediaTypeVideo];
    [connection setVideoOrientation:[ABI43_0_0EXCameraUtils videoOrientationForDeviceOrientation:[[UIDevice currentDevice] orientation]]];
    [self.faceDetectorManager maybeStartFaceDetectionOnSession:self.session withPreviewLayer:self.previewLayer mirrored:mirrored];
  }
}

- (void)setPresetCamera:(NSInteger)presetCamera
{
  _presetCamera = presetCamera;
  [self.faceDetectorManager updateMirrored:_presetCamera!=1];
}

- (void)stopRecording
{
  [_movieFileOutput stopRecording];
}

- (void)resumePreview
{
  [[_previewLayer connection] setEnabled:YES];
}

- (void)pausePreview
{
  [[_previewLayer connection] setEnabled:NO];
}

- (void)startSession
{
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunreachable-code"
#if TARGET_IPHONE_SIMULATOR
  return;
#endif
  if (![_permissionsManager hasGrantedPermissionUsingRequesterClass:[ABI43_0_0EXCameraCameraPermissionRequester class]]) {
    [self onMountingError:@{@"message": @"Camera permissions not granted - component could not be rendered."}];
    return;
  }
  ABI43_0_0EX_WEAKIFY(self);
  dispatch_async(_sessionQueue, ^{
    ABI43_0_0EX_ENSURE_STRONGIFY(self);

    if (self.presetCamera == AVCaptureDevicePositionUnspecified) {
      return;
    }

    AVCapturePhotoOutput *photoOutput = [AVCapturePhotoOutput new];
    photoOutput.highResolutionCaptureEnabled = YES;
    photoOutput.livePhotoCaptureEnabled = NO;
    if ([self.session canAddOutput:photoOutput]) {
      [self.session addOutput:photoOutput];
      self.photoOutput = photoOutput;
    }

    [self setRuntimeErrorHandlingObserver:
     [[NSNotificationCenter defaultCenter] addObserverForName:AVCaptureSessionRuntimeErrorNotification object:self.session queue:nil usingBlock:^(NSNotification *note) {
      ABI43_0_0EX_ENSURE_STRONGIFY(self);
      dispatch_async(self.sessionQueue, ^{
        ABI43_0_0EX_ENSURE_STRONGIFY(self)
        // Manually restarting the session since it must
        // have been stopped due to an error.
        [self.session startRunning];
        [self ensureSessionConfiguration];
        [self onReady:nil];
      });
    }]];

    // when BarCodeScanner is enabled since the beginning of camera component lifecycle,
    // some race condition occurs in reconfiguration and barcodes aren't scanned at all
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 50 * NSEC_PER_USEC), self.sessionQueue, ^{
      ABI43_0_0EX_ENSURE_STRONGIFY(self);
      [self maybeStartFaceDetection:self.presetCamera!=1];
      if (self.barCodeScanner) {
        [self.barCodeScanner maybeStartBarCodeScanning];
      }

      [self.session startRunning];
      [self ensureSessionConfiguration];
      [self onReady:nil];
    });
  });
#pragma clang diagnostic pop
}

- (void)stopSession
{
#if TARGET_IPHONE_SIMULATOR
  return;
#endif
  ABI43_0_0EX_WEAKIFY(self);
  dispatch_async(_sessionQueue, ^{
    ABI43_0_0EX_ENSURE_STRONGIFY(self);

    if (self.faceDetectorManager) {
      [self.faceDetectorManager stopFaceDetection];
    }
    if (self.barCodeScanner) {
      [self.barCodeScanner stopBarCodeScanning];
    }
    [self.previewLayer removeFromSuperlayer];
    [self.session commitConfiguration];
    [self.session stopRunning];
    for (AVCaptureInput *input in self.session.inputs) {
      [self.session removeInput:input];
    }

    for (AVCaptureOutput *output in self.session.outputs) {
      [self.session removeOutput:output];
    }
  });
}

- (void)initializeCaptureSessionInput
{
  if (_videoCaptureDeviceInput.device.position == _presetCamera) {
    return;
  }

  __block UIInterfaceOrientation interfaceOrientation;
  [ABI43_0_0EXUtilities performSynchronouslyOnMainThread:^{
    interfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
  }];
  AVCaptureVideoOrientation orientation = [ABI43_0_0EXCameraUtils videoOrientationForInterfaceOrientation:interfaceOrientation];

  ABI43_0_0EX_WEAKIFY(self);
  dispatch_async(_sessionQueue, ^{
    ABI43_0_0EX_ENSURE_STRONGIFY(self);

    [self.session beginConfiguration];

    NSError *error = nil;
    AVCaptureDevice *captureDevice = [ABI43_0_0EXCameraUtils deviceWithMediaType:AVMediaTypeVideo preferringPosition:self.presetCamera];
    AVCaptureDeviceInput *captureDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];

    if (error || captureDeviceInput == nil) {
      NSString *errorMessage = @"Camera could not be started - ";
      if (error) {
        errorMessage = [errorMessage stringByAppendingString:[error description]];
      } else {
        errorMessage = [errorMessage stringByAppendingString:@"there's no captureDeviceInput available"];
      }
      [self onMountingError:@{@"message": errorMessage}];
      return;
    }

    [self.session removeInput:self.videoCaptureDeviceInput];
    if ([self.session canAddInput:captureDeviceInput]) {
      [self.session addInput:captureDeviceInput];

      self.videoCaptureDeviceInput = captureDeviceInput;
      [self updateZoom];
      [self updateFocusMode];
      [self updateFocusDepth];
      [self updateWhiteBalance];
      [self.previewLayer.connection setVideoOrientation:orientation];
    }

    [self.session commitConfiguration];
  });
}

// Some configuration need to be applied on session after it's started
// - torchMode: https://stackoverflow.com/a/53666293/4337317
- (void)ensureSessionConfiguration
{
  ABI43_0_0EX_WEAKIFY(self);
  dispatch_async(_sessionQueue, ^{
    ABI43_0_0EX_ENSURE_STRONGIFY(self);
    [self updateFlashMode];
  });
}

#pragma mark - internal

- (void)updateSessionPreset:(AVCaptureSessionPreset)preset
{
#if !(TARGET_IPHONE_SIMULATOR)
  if (preset) {
    ABI43_0_0EX_WEAKIFY(self);
    dispatch_async(_sessionQueue, ^{
      ABI43_0_0EX_ENSURE_STRONGIFY(self);
      [self.session beginConfiguration];
      if ([self.session canSetSessionPreset:preset]) {
        self.session.sessionPreset = preset;
      }
      [self.session commitConfiguration];
    });
  }
#endif
}

- (void)updateSessionAudioIsMuted:(BOOL)isMuted
{
  ABI43_0_0EX_WEAKIFY(self);
  dispatch_async(_sessionQueue, ^{
    ABI43_0_0EX_ENSURE_STRONGIFY(self);
    [self.session beginConfiguration];

    for (AVCaptureDeviceInput* input in [self.session inputs]) {
      if ([input.device hasMediaType:AVMediaTypeAudio]) {
        if (isMuted) {
          [self.session removeInput:input];
        }
        [self.session commitConfiguration];
        return;
      }
    }

    if (!isMuted) {
      NSError *error = nil;

      AVCaptureDevice *audioCaptureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
      AVCaptureDeviceInput *audioDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:audioCaptureDevice error:&error];

      if (error || audioDeviceInput == nil) {
        ABI43_0_0EXLogInfo(@"%s: %@", __func__, error);
        return;
      }

      if ([self.session canAddInput:audioDeviceInput]) {
        [self.session addInput:audioDeviceInput];
      }
    }

    [self.session commitConfiguration];
  });
}

- (void)onAppForegrounded
{
  if (![_session isRunning] && [self isSessionPaused]) {
    _paused = NO;
    ABI43_0_0EX_WEAKIFY(self);
    dispatch_async(_sessionQueue, ^{
      ABI43_0_0EX_ENSURE_STRONGIFY(self);
      [self.session startRunning];
      [self ensureSessionConfiguration];
    });
  }
}

- (void)onAppBackgrounded
{
  if ([_session isRunning] && ![self isSessionPaused]) {
    _paused = YES;
    ABI43_0_0EX_WEAKIFY(self);
    dispatch_async(_sessionQueue, ^{
      ABI43_0_0EX_ENSURE_STRONGIFY(self);
      [self.session stopRunning];
    });
  }
}

- (void)orientationChanged:(NSNotification *)notification
{
  UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
  [self changePreviewOrientation:orientation];
}

- (void)changePreviewOrientation:(UIInterfaceOrientation)orientation
{
  ABI43_0_0EX_WEAKIFY(self);
  AVCaptureVideoOrientation videoOrientation = [ABI43_0_0EXCameraUtils videoOrientationForInterfaceOrientation:orientation];
  [ABI43_0_0EXUtilities performSynchronouslyOnMainThread:^{
    ABI43_0_0EX_ENSURE_STRONGIFY(self);
    if (self.previewLayer.connection.isVideoOrientationSupported) {
      [self.previewLayer.connection setVideoOrientation:videoOrientation];
    }
  }];
}

# pragma mark - AVCaptureMovieFileOutput

- (void)setupMovieFileCapture
{
  AVCaptureMovieFileOutput *movieFileOutput = [[AVCaptureMovieFileOutput alloc] init];

  if ([_session canAddOutput:movieFileOutput]) {
    [_session addOutput:movieFileOutput];
    _movieFileOutput = movieFileOutput;
  }
}

- (void)cleanupMovieFileCapture
{
  if ([_session.outputs containsObject:_movieFileOutput]) {
    [_session removeOutput:_movieFileOutput];
    _movieFileOutput = nil;
  }
}

- (void)captureOutput:(AVCaptureFileOutput *)captureOutput didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray *)connections error:(NSError *)error
{
  BOOL success = YES;
  if ([error code] != noErr) {
    NSNumber *value = [[error userInfo] objectForKey:AVErrorRecordingSuccessfullyFinishedKey];
    if (value) {
      success = [value boolValue];
    }
  }
  if (success && _videoRecordedResolve != nil) {
    _videoRecordedResolve(@{ @"uri": outputFileURL.absoluteString });
  } else if (_videoRecordedReject != nil) {
    _videoRecordedReject(@"E_RECORDING_FAILED", @"An error occurred while recording a video.", error);
  }
  _videoRecordedResolve = nil;
  _videoRecordedReject = nil;
  _videoCodecType = nil;

  [self cleanupMovieFileCapture];
  // If face detection has been running prior to recording to file
  // we reenable it here (see comment in -record).
  [self maybeStartFaceDetection:false];

  if (_session.sessionPreset != _pictureSize) {
    [self updateSessionPreset:_pictureSize];
  }
}

# pragma mark - Face detector

- (id)createFaceDetectorManager
{
  id<ABI43_0_0EXFaceDetectorManagerProviderInterface> faceDetectorProvider = [_moduleRegistry getModuleImplementingProtocol:@protocol(ABI43_0_0EXFaceDetectorManagerProviderInterface)];

  if (faceDetectorProvider) {
    id<ABI43_0_0EXFaceDetectorManagerInterface> faceDetector = [faceDetectorProvider createFaceDetectorManager];
    if (faceDetector) {
      ABI43_0_0EX_WEAKIFY(self);
      [faceDetector setOnFacesDetected:^(NSArray<NSDictionary *> *faces) {
        ABI43_0_0EX_ENSURE_STRONGIFY(self);
        if (self.onFacesDetected) {
          self.onFacesDetected(@{
                                 @"type": @"face",
                                 @"faces": faces
                                 });
        }
      }];
      [faceDetector setSessionQueue:_sessionQueue];
    }
    return faceDetector;
  }
  return nil;
}

# pragma mark - BarCode scanner

- (id)createBarCodeScanner
{
  id<ABI43_0_0EXBarCodeScannerProviderInterface> barCodeScannerProvider = [_moduleRegistry getModuleImplementingProtocol:@protocol(ABI43_0_0EXBarCodeScannerProviderInterface)];
  if (barCodeScannerProvider) {
    id<ABI43_0_0EXBarCodeScannerInterface> barCodeScanner = [barCodeScannerProvider createBarCodeScanner];
    if (barCodeScanner) {
      ABI43_0_0EX_WEAKIFY(self);
      [barCodeScanner setSession:_session];
      [barCodeScanner setSessionQueue:_sessionQueue];
      [barCodeScanner setOnBarCodeScanned:^(NSDictionary *body) {
        ABI43_0_0EX_ENSURE_STRONGIFY(self);
        [self onBarCodeScanned:body];
      }];
    }
    return barCodeScanner;
  }
  return nil;
}

@end


text:
define({
  "configText": "Angi konfigurasjonstekst:",
  "generalSettings": {
    "tabTitle": "Generelle innstillinger",
    "measurementUnitLabel": "Måleenhet",
    "currencyLabel": "Målesymbol",
    "roundCostLabel": "Avrundet kostnad",
    "projectOutputSettings": "Innstillinger for prosjektutdata",
    "typeOfProjectAreaLabel": "Type prosjektområde",
    "bufferDistanceLabel": "Bufferavstand",
    "csvReportExportLabel": "Tillat at bruker eksporterer rapport for prosjektet",
    "editReportSettingsBtnTooltip": "Rediger rapportinnstillinger",
    "roundCostValues": {
      "twoDecimalPoint": "To desimaler",
      "nearestWholeNumber": "Nærmeste hele tall",
      "nearestTen": "Nærmeste tier",
      "nearestHundred": "Nærmeste hundrer",
      "nearestThousand": "Nærmeste tusener",
      "nearestTenThousands": "Nærmeste titusener"
    },
    "reportSettings": {
      "reportSettingsPopupTitle": "Rapportinnstillinger",
      "reportNameLabel": "Rapportnavn (valgfritt):",
      "checkboxLabel": "Vis",
      "layerTitle": "Tittel",
      "columnLabel": "Etikett",
      "duplicateMsg": "Dupliser etikett"
    },
    "projectAreaType": {
      "outline": "Omriss",
      "buffer": "Lag buffer"
    },
    "errorMessages": {
      "currency": "Ugyldig valutaenhet",
      "bufferDistance": "Ugyldig bufferavstand",
      "outOfRangebufferDistance": "Verdien må være større enn 0 og mindre enn eller lik 100"
    }
  },
  "projectSettings": {
    "tabTitle": "Prosjektinnstillinger",
    "costingGeometrySectionTitle": "Definer geografi for kostnadsberegning (valgfritt)",
    "costingGeometrySectionNote": "Merk: Konfigurasjon av dette laget gjør det mulig for brukeren å angi kostnadsligninger for geoobjektmaler basert på geografi.",
    "projectTableSectionTitle": "Mulighet for å lagre / laste inn prosjektinnstillinger (valgfritt)",
    "projectTableSectionNote": "Merk: Konfigurasjon av alle tabeller og lag gjør det mulig for brukeren å lagre / laste inn prosjekter for senere bruk.",
    "costingGeometryLayerLabel": "Geometrilag for kostnadsberegning",
    "fieldLabelGeography": "Felt-til-etikett-geografi",
    "projectAssetsTableLabel": "Tabell over prosjektressurser",
    "projectMultiplierTableLabel": "Tabell over multiplikator for tilleggskostnad for prosjekt",
    "projectLayerLabel": "Prosjektlag",
    "configureFieldsLabel": "Konfigurer felt",
    "fieldDescriptionHeaderTitle": "Feltbeskrivelse",
    "layerFieldsHeaderTitle": "Lagfelt",
    "selectLabel": "Velg",
    "errorMessages": {
      "duplicateLayerSelection": "${layerName} er allerede valgt",
      "invalidConfiguration": "Velg ${fieldsString}"
    },
    "costingGeometryHelp": "
Polygonlag med følgende betingelser vises:

\tLaget må ha en spørringsfunksjon

\tLaget må ha et GlobalID-felt

",
    "fieldToLabelGeographyHelp": "
Strengen og de numeriske feltene for det valgte geometrilaget for kostnadsberegning vises i rullegardinlisten Felt-til-etikett-geografi.
",
    "projectAssetsTableHelp": "
Tabell(er) med følgende betingelser vises:

Tabellen må ha redigeringsfunksjoner, nærmere bestemt Opprett, Slett og Oppdater

Tabellen må ha seks felt med nøyaktig navn og datatype:

\tAssetGUID (GUID-typefelt)

\tCostEquation (strengtypefelt)

\tScenario (strengtypefelt)

\tTemplateName (strengtypefelt)

    GeographyGUID (GUID-typefelt)

\tProjectGUID (GUID-typefelt)

",
    "projectMultiplierTableHelp": "
Tabell(er) med følgende betingelser vises:

Tabellen må ha redigeringsfunksjoner, nærmere bestemt Opprett, Slett og Oppdater

Tabellen må ha fem felt med nøyaktig navn og datatype:

\tDescription (strengtypefelt)

\tType (strengtypefelt)

\tValue (Float/Double-typefelt)

\tCostindex (heltallstypefelt)

   \tProjectGUID (GUID-typefelt))

",
    "projectLayerHelp": "
Polygonlag med følgende betingelser vises:

Laget må ha redigeringsfunksjoner, nærmere bestemt Opprett, Slett og Oppdater

Laget må ha fem felt med nøyaktig navn og datatype:

ProjectName (strengtypefelt)

Description (strengtypefelt)

Totalassetcost (Float/Double-typefelt)

Grossprojectcost (Float/Double-typefelt)

GlobalID (GlobalID-typefelt)

",
    "pointLayerCentroidLabel": "Punktlagets tyngdepunkt",
    "selectRelatedPointLayerDefaultOption": "Velg",
    "pointLayerHintText": "
Punktlag med følgende vilkår vises:

\tLaget må ha et Prosjekt-ID-felt (av GUID-type)

\tLaget må ha redigeringsfunksjonene Opprett, Slett og Oppdater

"
  },
  "layerSettings": {
    "tabTitle": "Laginnstillinger",
    "layerNameHeaderTitle": "Lagnavn",
    "layerNameHeaderTooltip": "Liste over lag i kartet",
    "EditableLayerHeaderTitle": "Redigerbar",
    "EditableLayerHeaderTooltip": "Inkluder laget og malene i miniprogrammet for kostnadsberegning",
    "SelectableLayerHeaderTitle": "Kan velges",
    "SelectableLayerHeaderTooltip": "Geometrien fra geoobjektet kan brukes til å generere et nytt kostnadselement",
    "fieldPickerHeaderTitle": "Prosjekt-ID (valgfritt)",
    "fieldPickerHeaderTooltip": "Valgfritt felt (for strengtypen) for lagring av Prosjekt-ID i",
    "selectLabel": "Velg",
    "noAssetLayersAvailable": "Finner ingen ressurslag i valgt webkart",
    "disableEditableCheckboxTooltip": "Dette laget har ikke redigeringsfunksjoner",
    "missingCapabilitiesMsg": "Laget mangler følgende funksjoner:",
    "missingGlobalIdMsg": "Laget mangler feltet GlobalId.",
    "create": "Opprett",
    "update": "Oppdater",
    "deleteColumnLabel": "Slett",
    "attributeSettingHeaderTitle": "Attributtinnstillinger",
    "addFieldLabelTitle": "Legg til attributter",
    "layerAttributesHeaderTitle": "Lagattributter",
    "projectLayerAttributesHeaderTitle": "Prosjektlagattributter",
    "attributeSettingsPopupTitle": "Innstillinger for lagattributter"
  },
  "costingInfo": {
    "tabTitle": "Kostnadsberegningsinformasjon",
    "proposedMainsLabel": "Foreslått hovedledning",
    "addCostingTemplateLabel": "Legg til kostnadsberegningsmal",
    "manageScenariosTitle": "Administrer scenarioer",
    "featureTemplateTitle": "Geoobjektmal",
    "costEquationTitle": "Kostnadsligning",
    "geographyTitle": "Geografi",
    "scenarioTitle": "Scenario",
    "actionTitle": "Handlinger",
    "scenarioNameLabel": "Scenarionavn",
    "addBtnLabel": "Legg til",
    "srNoLabel": "Nei.",
    "deleteLabel": "Slett",
    "duplicateScenarioName": "Dupliser scenarionavn",
    "hintText": "
Tips: Bruk følgende nøkkelord

{TOTALCOUNT}: Bruker det totale antallet av samme type ressurs i en geografi

{MEASURE}: Bruker lengde for linjeressurs og areal for polygonressurs

{TOTALMEASURE}: Bruker den samlede lengden for linjeressursen og det samlede arealet for polygonressursen av samme type i en geografi

Du kan bruke funksjoner som:

Math.abs(-100)

Math.floor({TOTALMEASURE})

Rediger kostnadsligningen ut fra prosjektbehovene dine.",
    "noneValue": "Ingen",
    "requiredCostEquation": "Ugyldig kostnadsligning for ${layerName} : ${templateName}",
    "duplicateTemplateMessage": "Duplisert maloppføring finnes for ${layerName} : ${templateName}",
    "defaultEquationRequired": "Standardligning kreves for ${layerName} : ${templateName}",
    "validCostEquationMessage": "Angi en gyldig kostnadsligning",
    "costEquationHelpText": "Rediger kostnadsligningen ut fra prosjektbehovene dine",
    "scenarioHelpText": "Velg scenario ut fra prosjektbehovene dine",
    "copyRowTitle": "Kopier rad",
    "noTemplateAvailable": "Legg til minst én mal for ${layerName}",
    "manageScenarioLabel": "Administrer scenario",
    "noLayerMessage": "Angi minst ett lag i ${tabName}",
    "noEditableLayersAvailable": "Lag(ene) skal merkes som redigerbare i fanen med laginnstillinger",
    "updateProjectCostCheckboxLabel": "Oppdater prosjektets beregninger",
    "updateProjectCostEquationHint": "Tips: Dette gjør det mulig for brukeren å oppdatere kostnadsberegninger som allerede er lagt til eksisterende prosjekter, med de nye beregningene som er utført nedenfor på basis av geoobjektmalen, geografien og scenarioet. Hvis kombinasjonen ikke blir funnet, settes den til standard kostnadsberegning, dvs. at geografi og scenario settes til Ingen. Hvis geoobjektmalen er fjernet, settes kostnaden til 0."
  },
  "statisticsSettings": {
    "tabTitle": "Tilleggsinnstillinger",
    "addStatisticsLabel": "Legg til statistikk",
    "fieldNameTitle": "Felt",
    "statisticsTitle": "Etikett",
    "addNewStatisticsText": "Legg til ny statistikk",
    "deleteStatisticsText": "Slett statistikk",
    "moveStatisticsUpText": "Flytt statistikk opp",
    "moveStatisticsDownText": "Flytt statistikk ned",
    "selectDeselectAllTitle": "Merk alle"
  },
  "projectCostSettings": {
    "addProjectCostLabel": "Legg til ytterligere prosjektkostnader",
    "additionalCostValueColumnHeader": "Verdi",
    "invalidProjectCostMessage": "Ugyldig oppføring for prosjektkostnad",
    "additionalCostLabelColumnHeader": "Etikett",
    "additionalCostTypeColumnHeader": "Type"
  },
  "statisticsType": {
    "countLabel": "Antall",
    "averageLabel": "Gjennomsnitt",
    "maxLabel": "Maksimum",
    "minLabel": "Minimum",
    "summationLabel": "Summering",
    "areaLabel": "Areal",
    "lengthLabel": "Lengde"
  }
});


text:
begin
  gem "sorbet-runtime"
  return
rescue Gem::LoadError
end

module T
  class << self
    def absurd(value); end
    def all(type_a, type_b, *types); end
    def any(type_a, type_b, *types); end
    def attached_class; end
    def class_of(klass); end
    def enum(values); end
    def nilable(type); end
    def noreturn; end
    def self_type; end
    def type_alias(type=nil, &_blk); end
    def type_parameter(name); end
    def untyped; end

    def assert_type!(value, _type, _checked: true)
      value
    end

    def cast(value, _type, _checked: true)
      value
    end

    def let(value, _type, _checked: true)
      value
    end

    def must(arg, _msg = nil)
      arg
    end

    def proc
      T::Proc.new
    end

    def reveal_type(value)
      value
    end

    def unsafe(value)
      value
    end
  end

  module Sig
    def sig(arg0=nil, &blk); end
  end

  module Helpers
    def abstract!;  end
    def interface!; end
    def final!; end
    def sealed!; end
    def mixes_in_class_methods(mod); end
  end

  module Generic
    include T::Helpers

    def type_parameters(*params); end
    def type_member(variance=:invariant, fixed: nil, lower: nil, upper: BasicObject); end
    def type_template(variance=:invariant, fixed: nil, lower: nil, upper: BasicObject); end

    def [](*types)
      self
    end
  end

  module Array
    def self.[](type); end
  end

  Boolean = Object.new.freeze

  module Configuration
    def self.call_validation_error_handler(signature, opts); end
    def self.call_validation_error_handler=(value); end
    def self.default_checked_level=(default_checked_level); end
    def self.enable_checking_for_sigs_marked_checked_tests; end
    def self.enable_final_checks_on_hooks; end
    def self.enable_legacy_t_enum_migration_mode; end
    def self.reset_final_checks_on_hooks; end
    def self.hard_assert_handler(str, extra); end
    def self.hard_assert_handler=(value); end
    def self.inline_type_error_handler(error); end
    def self.inline_type_error_handler=(value); end
    def self.log_info_handler(str, extra); end
    def self.log_info_handler=(value); end
    def self.scalar_types; end
    def self.scalar_types=(values); end
    def self.sealed_violation_whitelist; end
    def self.sealed_violation_whitelist=(sealed_violation_whitelist); end
    def self.sig_builder_error_handler(error, location); end
    def self.sig_builder_error_handler=(value); end
    def self.sig_validation_error_handler(error, opts); end
    def self.sig_validation_error_handler=(value); end
    def self.soft_assert_handler(str, extra); end
    def self.soft_assert_handler=(value); end
  end

  module Enumerable
    def self.[](type); end
  end

  module Enumerator
    def self.[](type); end
  end

  module Hash
    def self.[](keys, values); end
  end

  class Proc
    def bind(*_)
      self
    end

    def params(*_param)
      self
    end

    def void
      self
    end

    def returns(_type)
      self
    end
  end

  module Range
    def self.[](type); end
  end

  module Set
    def self.[](type); end
  end
end


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

import java.math.*;

import javax.annotation.Generated;

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

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

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

    public MetricsSummary unmarshall(JsonUnmarshallerContext context) throws Exception {
        MetricsSummary metricsSummary = new MetricsSummary();

        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 null;
        }

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

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("MeteredLinesOfCodeCount", targetDepth)) {
                    context.nextToken();
                    metricsSummary.setMeteredLinesOfCodeCount(context.getUnmarshaller(Long.class).unmarshall(context));
                }
                if (context.testExpression("SuppressedLinesOfCodeCount", targetDepth)) {
                    context.nextToken();
                    metricsSummary.setSuppressedLinesOfCodeCount(context.getUnmarshaller(Long.class).unmarshall(context));
                }
                if (context.testExpression("FindingsCount", targetDepth)) {
                    context.nextToken();
                    metricsSummary.setFindingsCount(context.getUnmarshaller(Long.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 metricsSummary;
    }

    private static MetricsSummaryJsonUnmarshaller instance;

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


text:
def main():
    say('Pentaho Report Test Framework Development Setup Helper')

    say('Trying to run Java... ')
    if run('java -version'):
        say('OK!')
    else:
        fail('java', 'not found. Must be in PATH. Java is needed to run Gradle.')
        say('No java.')

    say('Trying to run Gradle... ')
    gradle = get_for_os('gradle')
    if run('%s -v' % gradle):
        say('OK!')
    else:
        fail(gradle, 'not found. Must be in PATH. Gradle is needed to build.')
        say('No maven.')

    pdiPath = ""
    if promptYesNo('Should I look for PDI at %s? [Y/n]: ' % get_for_os('pdi')) == 'yes':
        pdiPath = get_for_os('pdi')
    else:
        while pdiPath == "":
            pdiPath = prompt('Ok, where? ')

    panPath = os.path.join(pdiPath, get_for_os('pan_script'))
    if os.path.exists(panPath):
        say('OK!')
    else:
        fail('pdi', '%s not found. PDI is needed to run tests.' % panPath)
        say('No pdi.')

    if 'pdi' not in failed:
        say('Trying to run Pan... ')
        if run('%s -version' % panPath, badExitCode=True):
            say('OK!')
        else:
            fail('pdi', 'Couldn''t run Pan, necessary for tests.')
            say('Didn''t work.')

    if 'pdi' in failed:
        say('PDI wasn''t found, skipped check for Pentaho Reporting Output plugin.')
        fail('pdi', 'Pentaho Reporting Output plugin not found, but is needed to run tests.')

    if 'pdi' not in failed:
        say('Looking for Pentaho Reporting Output plugin...')
        outputPluginPath = os.path.join(pdiPath, 'plugins', 'pentaho-reporting-plugin.jar')
        if os.path.exists(outputPluginPath):
            say('OK!')
        else:
            fail('pdi', '%s not found.' % outputPluginPath)

    if 'pdi' not in failed:
        say('Looking for Mifos i18n bundles...')
        i18nBundlePath = os.path.join(pdiPath, 'org', 'mifos', 'bi', 'reports')
        if os.path.exists(i18nBundlePath):
            say('OK!')
        else:
            fail('pdi', '%s not found, but is needed to run tests.' % i18nBundlePath)

    userHome = os.getenv('USERPROFILE') or os.getenv('HOME')
    prestoSettings = os.path.join(userHome, '.presto')
    if 'pdi' not in failed:
        if os.path.exists(prestoSettings) and promptYesNo('%s exists. Overwrite? [Y/n]: ' % prestoSettings) == 'yes' \
                or not os.path.exists(prestoSettings):
            say('Storing local settings...')
            prestoSettingsFd = open(prestoSettings, 'w')
            print >> prestoSettingsFd, 'pdiPath=%s' % pdiPath
            prestoSettingsFd.close()
            say('Wrote %s' % prestoSettings)

    if 'pdi' not in failed:
        dbSettingsFile = os.path.join(pdiPath, 'simple-jndi', 'jdbc.properties')
        say('')
        say('Be sure to configure your database connections in %s' % dbSettingsFile)
        say('SourceDB must be a Mifos OLTP database, DestinationDB must be a Mifos BI data warehouse.')
        say('Mysql connection URL must include useUnicode=true&characterEncoding=UTF-8.')

    say('')
    say('DONE.')
    say('')
    if failed:
        say('THERE WERE ERRORS. Fix the following, then try again:')
        for msg in failmsgs:
            say(msg)
    else:
        say('Ready to test Pentaho reports! Build using "gradle build".')

import os
import re
import subprocess

default_locations = {
    'pdi': {
        'nt' : os.path.join('Program Files', 'Pentaho Data Integration'),
        'posix': os.path.join('/', 'opt', 'pentaho', 'data-integration'),
    },
    'pan_script': {
        'nt' : 'pan.bat',
        'posix': 'pan.sh',
    },
    'gradle': {
        'nt' : 'gradle.bat',
        'posix': 'gradle',
    },
}
failed = []
failmsgs = []

def format_string_for_user(msg):
    return '*** ' + msg

def get_for_os(program_nickname):
    return default_locations[program_nickname][os.name]

def say(msg):
    'Tell the user something.'
    print format_string_for_user(msg)

def prompt(msg):
    'Ask for user input.'
    answer = raw_input(format_string_for_user(msg))
    return answer

def promptYesNo(msg):
    'Ask for yes/no response'
    answer = raw_input(format_string_for_user(msg))
    if answer == '' or re.match('y', answer, re.IGNORECASE):
        return 'yes'
    else:
        return 'no'

def fail(what, why):
    failmsg = what + ' FAIL: ' + why
    failmsgs.append(failmsg)
    failed.append(what)

def run(cmd, badExitCode=False):
    'Run an external command.'
    exit_status = 1
    try:
        exit_status = subprocess.call(cmd.split())
    except OSError as e:
        say("%s" % e)
        return False
    if exit_status == 0 or badExitCode:
        return True
    else:
        return False

if __name__ == '__main__':
    main()


text:
using namespace theoria ;
using namespace util ;

static CommandLine*  __CommandLine = nullptr ;

CommandLine::CommandLine(int argc, const char*argv[], bool allowMissingConfig)
{
    //The first one constructed is the global instance
    if (!__CommandLine)
        __CommandLine = this ;

    if (argc < 1)
        throw RUNTIME_ERROR("theoria requires at least a config file arg") ;

    //First optional settings which may be terminated with --
    int iSetting = 0 ;
    while(iSetting < argc && strcmp(argv[iSetting], "--") != 0 && argv[iSetting] == strstr(argv[iSetting], "--")) {
        const char * setting = argv[iSetting++]+2 ;
        const char * value = "true" ;
        if (iSetting < argc && strncmp(argv[iSetting], "--", 2) != 0)
            value = argv[iSetting++] ;
        _settings[setting] = value ;
    }
    if (iSetting < argc && strcmp(argv[iSetting], "--") == 0)
        ++iSetting ;

    if (iSetting >= argc) {
        if (hasSetting("help") || allowMissingConfig)
            return ;
        throw RUNTIME_ERROR("Missing config file");
    }

    //Next the config file which is mandatory
    std::string config_file(argv[iSetting++]) ;
    if (!allowMissingConfig) {
        FILE* f = fopen(config_file.c_str(), "r") ;
        if (!f)
            throw RUNTIME_ERROR("theoria could not open config %s", config_file.c_str()) ;
        fclose(f) ;
    }
    _configFileName = config_file ;

    //Next optional user settings which may be terminated with --
    while(iSetting < argc && strcmp(argv[iSetting], "--") != 0 && argv[iSetting] == strstr(argv[iSetting], "--")) {
        const char * setting = argv[iSetting++]+2 ;
        const char * value = "true" ;
        if (iSetting < argc && strncmp(argv[iSetting], "--", 2) != 0)
            value = argv[iSetting++] ;
        if (hasSetting(setting))
            throw RUNTIME_ERROR("User setting duplicates existing setting: %s", setting) ;
        _settings[setting] = value ;
    }

    iSetting++ ; //eat potential trailing --
    if (iSetting >= argc)
        return ;

    //Variables
    const char * pEq = nullptr ;
    while(iSetting < argc && (pEq = strstr(argv[iSetting], "=")) != nullptr) {
        const char * p = argv[iSetting++] ;
        std::string name(p, pEq-p) ;
        std::string value(pEq+1) ;
        if ( name[0] == '_' || ('A' <= name[0] && name[0] <= 'Z') || ('a' <= name[0] && name[0] <= 'z') ) {
            _variables[name] = value ;
        }
        else {
            throw RUNTIME_ERROR("theoria variables must start with '_' or alpha: [%s] is illegal" , name.c_str()) ;
        }
    }

    if (iSetting < argc) {
        throw RUNTIME_ERROR("theoria found unexpected parameters starting with %s", argv[iSetting]) ;
    }
}

const CommandLine& CommandLine::instance()
{
    //yes death will be swift if used before main initializes!
    return *__CommandLine ;
}

const char * CommandLine::variableAsPtr(const std::string& name) const noexcept
{
    auto iter = findVar(name) ;
    if (iter != endVars())
        return iter->second.c_str() ;
    return nullptr ;
}

const std::string& CommandLine::variableAsStr(const std::string& name, const std::string& def) const
{
    auto iter = findVar(name) ;
    if (iter != _variables.cend())
        return iter->second ;
    return def ;
}

int64_t CommandLine::variableAsInt(const std::string& name, int64_t def) const
{
    return convertToInt(findVar(name) , endVars(), "variable", name, def) ;
}

double CommandLine::variableAsDbl(const std::string& name, double def) const
{
    return convertToDbl(findVar(name) , endVars(), "variable", name, def) ;
}

bool CommandLine::variableAsBool(const std::string& name, bool def) const
{
    return convertToBool(findVar(name) , endVars(), "variable", name, def) ;
}

void CommandLine::reset()
{
    __CommandLine = nullptr ;
}

const char * CommandLine::settingAsPtr(const std::string& name) const noexcept
{
    auto iter = findSetting(name) ;
    if (iter != endSettings())
        return iter->second.c_str() ;
    return nullptr ;
}

const std::string& CommandLine::settingAsStr(const std::string& name, const std::string& def) const
{
    auto iter = findSetting(name) ;
    if (iter != endSettings())
        return iter->second ;
    return def ;
}

int64_t CommandLine::settingAsInt(const std::string& name, int64_t def) const
{
    return convertToInt(findSetting(name), endSettings(), "setting", name, def) ;
}

bool CommandLine::settingAsBool(const std::string& name, bool def) const
{
    return convertToBool(findSetting(name), endSettings(), "setting", name, def) ;
}

double CommandLine::settingAsDbl(const std::string& name, double def) const
{
    return convertToDbl(findSetting(name), endSettings(), "setting", name, def) ;
}


text:
// Copyright (c) Microsoft. All rights reserved.

using IoTCoreDefaultApp.Utils;
using System;
using System.Globalization;
using Windows.Networking.Connectivity;
using Windows.Storage;
using Windows.System;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;

namespace IoTCoreDefaultApp
{
    public sealed partial class MainPage : Page
    {
        public static MainPage Current;
        private CoreDispatcher MainPageDispatcher;
        private DispatcherTimer timer;
        private ConnectedDevicePresenter connectedDevicePresenter;

        public CoreDispatcher UIThreadDispatcher
        {
            get
            {
                return MainPageDispatcher;
            }

            set
            {
                MainPageDispatcher = value;
            }
        }

        public MainPage()
        {
            this.InitializeComponent();

            // This is a static public property that allows downstream pages to get a handle to the MainPage instance
            // in order to call methods that are in this class.
            Current = this;

            MainPageDispatcher = Window.Current.Dispatcher;

            NetworkInformation.NetworkStatusChanged += NetworkInformation_NetworkStatusChanged;

            this.NavigationCacheMode = NavigationCacheMode.Enabled;

            var languageManager = LanguageManager.GetInstance();
            languageManager.PropertyChanged += (sender, e) =>
            {
                // If the language manager updates the
                // language, the current content needs to
                // be reloaded.
                if (e.PropertyName == "Item[]")
                {
                    Dispatcher.RunAsync(CoreDispatcherPriority.Low, () => { UpdateDateTime(); });
                }
            };

            this.DataContext = languageManager;

            this.Loaded += (sender, e) =>
            {
                UpdateBoardInfo();
                UpdateNetworkInfo();
                UpdateDateTime();
                UpdateConnectedDevices();

                timer = new DispatcherTimer();
                timer.Tick += timer_Tick;
                timer.Interval = TimeSpan.FromSeconds(10);
                timer.Start();
            };
            this.Unloaded += (sender, e) =>
            {
                timer.Stop();
                timer = null;
            };
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (!ApplicationData.Current.LocalSettings.Values.ContainsKey(Constants.HasDoneOOBEKey))
            {
                ApplicationData.Current.LocalSettings.Values[Constants.HasDoneOOBEKey] = Constants.HasDoneOOBEValue;
            }

            base.OnNavigatedTo(e);
        }

        private async void NetworkInformation_NetworkStatusChanged(object sender)
        {
            await MainPageDispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
            {
                UpdateNetworkInfo();
            });
        }

        private void timer_Tick(object sender, object e)
        {
            UpdateDateTime();
        }

        private void UpdateBoardInfo()
        {
            BoardName.Text = DeviceInfoPresenter.GetBoardName();
            BoardImage.Source = new BitmapImage(DeviceInfoPresenter.GetBoardImageUri());

            ulong version = 0;
            if (!ulong.TryParse(Windows.System.Profile.AnalyticsInfo.VersionInfo.DeviceFamilyVersion, out version))
            {
                var loader = new Windows.ApplicationModel.Resources.ResourceLoader();
                OSVersion.Text = loader.GetString("OSVersionNotAvailable");
            }
            else
            {
                OSVersion.Text = String.Format(CultureInfo.InvariantCulture,"{0}.{1}.{2}.{3}",
                    (version & 0xFFFF000000000000) >> 48,
                    (version & 0x0000FFFF00000000) >> 32,
                    (version & 0x00000000FFFF0000) >> 16,
                    version & 0x000000000000FFFF);
            }
        }

        private void UpdateDateTime()
        {
            // Using DateTime.Now is simpler, but the time zone is cached. So, we use a native method insead.
            SYSTEMTIME localTime;
            NativeTimeMethods.GetLocalTime(out localTime);

            DateTime t = localTime.ToDateTime();
            CurrentTime.Text = t.ToString("t", CultureInfo.CurrentCulture) + Environment.NewLine + t.ToString("d", CultureInfo.CurrentCulture);
        }

        private async void UpdateNetworkInfo()
        {
            this.DeviceName.Text = DeviceInfoPresenter.GetDeviceName();
            this.IPAddress1.Text = NetworkPresenter.GetCurrentIpv4Address();
            this.NetworkName1.Text = NetworkPresenter.GetCurrentNetworkName();
            this.NetworkInfo.ItemsSource = await NetworkPresenter.GetNetworkInformation();
        }

        private void UpdateConnectedDevices()
        {
            connectedDevicePresenter = new ConnectedDevicePresenter(MainPageDispatcher);
            this.ConnectedDevices.ItemsSource = connectedDevicePresenter.GetConnectedDevices();
        }

        private void ShutdownButton_Clicked(object sender, RoutedEventArgs e)
        {
            ShutdownDropdown.IsOpen = true;
        }

        private void SettingsButton_Clicked(object sender, RoutedEventArgs e)
        {
            NavigationUtils.NavigateToScreen(typeof(Settings));
        }

        private void Tutorials_Clicked(object sender, RoutedEventArgs e)
        {
            NavigationUtils.NavigateToScreen(typeof(TutorialMainPage));
        }

        private void ShutdownHelper(ShutdownKind kind)
        {
            ShutdownManager.BeginShutdown(kind, TimeSpan.FromSeconds(0.5));
        }

        private void ShutdownListView_ItemClick(object sender, ItemClickEventArgs e)
        {
            var item = e.ClickedItem as FrameworkElement;
            if (item == null)
            {
                return;
            }
            switch (item.Name)
            {
                case "ShutdownOption":
                    ShutdownHelper(ShutdownKind.Shutdown);
                    break;
                case "RestartOption":
                    ShutdownHelper(ShutdownKind.Restart);
                    break;
            }
        }

        private void ShutdownDropdown_Opened(object sender, object e)
        {
            var w = ShutdownListView.ActualWidth;
            if (w == 0)
            {
                // trick to recalculate the size of the dropdown
                ShutdownDropdown.IsOpen = false;
                ShutdownDropdown.IsOpen = true;
            }
            var offset = -(ShutdownListView.ActualWidth - ShutdownButton.ActualWidth);
            ShutdownDropdown.HorizontalOffset = offset;
        }
    }
}


text:
{% extends "pretixcontrol/items/base.html" %}
{% load i18n %}
{% load bootstrap3 %}
{% load eventsignal %}
{% block title %}{% blocktrans with name=quota.name %}Quota: {{ name }}{% endblocktrans %}{% endblock %}
{% block inside %}

        {% blocktrans with name=quota.name %}Quota: {{ name }}{% endblocktrans %}
        {% if request.eventperm.can_change_items %}

                {% trans "Edit quota" %}

        {% endif %}

            <legend>{% trans "Usage overview" %}</legend>

            <legend>{% trans "Availability calculation" %}</legend>

{% trans "Total quota" %}

                    {% if quota.size == None %}{% trans "Infinite" %}{% else %}{{ quota.size }}{% endif %}

            {% for row in quota_table_rows %}

{{ row.label }}

 – {{ row.value }}

            {% endfor %}

{% trans "Current availability" %}

                    {% if quota.size == None %}{% trans "Infinite" %}{% else %}{{ avail.1 }}{% endif %}

            {% if quota_overbooked > 0 %}

                    {% blocktrans trimmed with num=quota_overbooked %}
                        This quota is currently overbooked by {{ num }} tickets.
                    {% endblocktrans %}

            {% endif %}
            {% if has_ignore_vouchers %}

                    {% blocktrans trimmed %}
                        Your event contains vouchers that affect products covered by this quota and that
                        allow a user to buy products even if this quota is sold out.
                    {% endblocktrans %}

            {% endif %}

                        {% trans "Quota history" %}

                {% include "pretixcontrol/includes/logs.html" with obj=quota %}

    {% eventsignal request.event "pretix.control.signals.quota_detail_html" quota=quota %}
{% endblock %}


text:
'use strict';

module.exports = function(app) {

	app.middleware = {};

	// The order here is important.
	require('./security')(app);
	require('./parsers')(app);
	require('./template')(app);
	require('./static')(app);
	require('./session')(app);
	require('./auth')(app);
};


text:
package functions.clean

import com.hankcs.hanlp.HanLP
import config.paramconf.{HasOutputCol, HasInputCol}
import functions.MySchemaUtils
import functions.clean.chinese.BCConvert
import org.apache.spark.ml.Transformer
import org.apache.spark.ml.param.{IntParam, Param, ParamMap}
import org.apache.spark.ml.util.{DefaultParamsReadable, DefaultParamsWritable, Identifiable}
import org.apache.spark.sql.functions.{col, udf}
import org.apache.spark.sql.types.{StringType, StructType}
import org.apache.spark.sql.{DataFrame, Dataset}

/**
  * Created by yhao on 2017/3/14.
  */
class Cleaner(val uid: String) extends Transformer with HasInputCol with HasOutputCol with DefaultParamsWritable {

  def this() = this(Identifiable.randomUID("clean"))

  /** @group setParam */
  def setInputCol(value: String): this.type = set(inputCol, value)

  /** @group setParam */
  def setOutputCol(value: String): this.type = set(outputCol, value)

  /**
    * 繁简转换, 可选输入有: 'f2j'(繁体转换为简体), 'j2f'(简体转换为繁体)
    * @group param
    */
  val fanjan: Param[String] = new Param[String](this, "fanjan", "words from fan to jan or from jan to fan")

  /** @group setParam */
  def setFanJian(value: String): this.type = {
    val fanjianSet = Set("f2j", "j2f")
    require(fanjianSet.contains(value), "繁简参数错误!")
    set(fanjan, value)
  }

  /** @group getParam */
  def getFanJian: String = $(fanjan)

  /**
    * 是否全角转半角, 可选输入有: 'q2b'(全角转半角), 'b2q'(半角转全角)
    * @group param
    */
  val quanban: Param[String] = new Param[String](this, "q2b", "from SBC case to DBC case")

  /** @group setParam */
  def setQuanBan(value: String): this.type = {
    val quanbanSet = Set("q2b", "b2q")
    require(quanbanSet.contains(value), "全半角参数错误!")
    set(quanban, value)
  }

  /** @group getParam */
  def getQuanBan: String = $(quanban)

  /**
    * 最短行长度,大于等于0,默认1以便返回非空字符串
    * @group param
    */
  val minLineLen: IntParam = new IntParam(this, "minLineLen", "minimum line length (>= 0)")

  /** @group setParam */
  def setMinLineLen(value: Int): this.type = {
    require(value >= 0, "最短行长度必须大于等于0")
    set(minLineLen, value)
  }

  /** @group getParam */
  def getMinLineLen: Int = $(minLineLen)

  /**
    * 设置默认参数
    */
  setDefault(fanjan -> "f2j", quanban -> "q2b", minLineLen -> 1)

  override def transform(dataset: Dataset[_]): DataFrame = {
    val outputSchema = transformSchema(dataset.schema, logging = true)

    val cleanFunc = udf {line: String =>
      var cleaned = ""
      getFanJian match {
        case "f2j" => cleaned = HanLP.convertToSimplifiedChinese(line)
        case "j2f" => cleaned = HanLP.convertToTraditionalChinese(line)
        case _ => cleaned = line
      }

      getQuanBan match {
        case "q2b" => cleaned = BCConvert.qj2bj(cleaned)
        case "b2q" => cleaned = BCConvert.bj2qj(cleaned)
        case _ => cleaned = cleaned
      }

      cleaned
    }

    val metadata = outputSchema($(outputCol)).metadata
    dataset.select(col("*"), cleanFunc(col($(inputCol))).as($(outputCol), metadata)).filter{record =>
      val outputIndex = record.fieldIndex($(outputCol))
      record.getString(outputIndex).length >= getMinLineLen
    }
  }

  override def copy(extra: ParamMap): Transformer = defaultCopy(extra)

  override def transformSchema(schema: StructType): StructType = {
    val inputType = schema($(inputCol)).dataType
    require(inputType.typeName.equals(StringType.typeName),
      s"Input type must be StringType but got $inputType.")
    MySchemaUtils.appendColumn(schema, $(outputCol), inputType, schema($(inputCol)).nullable)
  }
}

object Cleaner extends DefaultParamsReadable[Cleaner] {
  override def load(path: String): Cleaner = super.load(path)
}


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

import java.util.Collections;
import java.util.List;

import docking.widgets.OptionDialog;
import ghidra.app.cmd.memory.DeleteBlockCmd;
import ghidra.framework.cmd.Command;
import ghidra.framework.model.DomainObject;
import ghidra.framework.plugintool.PluginTool;
import ghidra.framework.store.LockException;
import ghidra.program.model.address.*;
import ghidra.program.model.listing.*;
import ghidra.program.model.mem.*;
import ghidra.util.Msg;
import ghidra.util.exception.*;

/**
 * Helper class to make changes to memory blocks.
 */
class MemoryMapManager {

	private Program program;
	private MemoryMapPlugin plugin;
	private PluginTool tool;

	MemoryMapManager(MemoryMapPlugin plugin) {
		this.plugin = plugin;
		tool = plugin.getTool();
	}

	/**
	 * Split the block by creating the new block at newStart address.
	 * @param block block to split
	 * @param newStart start address of new block
	 * @param newBlockName new block name
	 * @return boolean true if the split was successful.
	 */
	void splitBlock(MemoryBlock block, Address newStart, String newBlockName) {

		SplitBlockCmd cmd = new SplitBlockCmd(block, newStart, newBlockName);
		if (!tool.execute(cmd, program)) {
			Msg.showError(getClass(), plugin.getMemoryMapProvider().getComponent(),
				"Split Block Failed", cmd.getStatusMsg());
		}
	}

	/**
	 * Callback for merging blocks of memory
	 */
	void mergeBlocks(List<MemoryBlock> blocks) {
		// need to order by start address
		Collections.sort(blocks, (b1, b2) -> b1.getStart().compareTo(b2.getStart()));
		if (!goodBlocks(blocks)) {
			return;
		}

		MergeBlocksCmd cmd = new MergeBlocksCmd(blocks);
		if (!tool.execute(cmd, program)) {
			Msg.showError(getClass(), plugin.getMemoryMapProvider().getComponent(),
				"Merge Blocks Failed", cmd.getStatusMsg());
		}
	}

	private void renameFragment(Address start, String name) {

		Listing listing = program.getListing();
		String[] treeNames = listing.getTreeNames();
		for (String treeName : treeNames) {
			boolean duplicate = false;
			int index = 0;

			ProgramFragment frag = listing.getFragment(treeName, start);
			do {
				try {
					frag.setName("Frag" + index + "-" + name);
					duplicate = false;
				}
				catch (DuplicateNameException exc) {
					duplicate = true;
				}
				index++;
			}
			while (duplicate);
		}
	}

	private boolean goodBlocks(List<MemoryBlock> blocks) {
		// check that blocks are contigous (no other blocks in between)
		//    throw error if blocks in between
		Class<?> bc = null;
		long space_size = 0;
		for (int i = 0; i < (blocks.size() - 1); i++) {
			MemoryBlock blockA = blocks.get(i);
			MemoryBlock blockB = blocks.get(i + 1);
			if (bc == null) {
				bc = blockA.getClass();
			}
			if (bc != blockA.getClass() || bc != blockB.getClass()) {
				Msg.showError(this, plugin.getMemoryMapProvider().getComponent(),
					"Merge Blocks Failed",
					"Can't merge blocks because all block types are not the same");
				return false;
			}

			// make sure that the block after the first block is the second block
			Address nextStart = blockA.getEnd();
			AddressSpace space = nextStart.getAddressSpace();
			if (space.isOverlaySpace()) {
				Msg.showError(this, plugin.getMemoryMapProvider().getComponent(),
					"Merge Blocks Failed", "Can't merge overlay blocks");
				return false;
			}

			Address blockBstart = blockB.getStart();
			if (!space.isSuccessor(nextStart, blockBstart)) {
				try {
					Address a = nextStart.addNoWrap(1);
					MemoryBlock b = program.getMemory().getBlock(a);
					if (b != null) {
						Msg.showError(this, plugin.getMemoryMapProvider().getComponent(),
							"Merge Blocks Failed",
							"Can't merge blocks because they are not contiguous");
						return false;
					}
					else if (blockA.getType() == MemoryBlockType.BIT_MAPPED) {
						Msg.showError(this, plugin.getMemoryMapProvider().getComponent(),
							"Merge Blocks Failed",
							"Can't merge Bit Memory Blocks because they do not\n" +
								"have successive block end and block start addresses.");
						return false;
					}

				}
				catch (AddressOverflowException e) {
				}
			}

			try {
				space_size += blockBstart.subtract(blockA.getEnd());
			}
			catch (IllegalArgumentException e) {
				Msg.showError(this, plugin.getMemoryMapProvider().getComponent(),
					"Merge Blocks Failed", e.getMessage(), e);
				return false;
			}
		}

		// check that this won't create a large area between the address spaces
		if (space_size > 4 * 1024 * 1024) {
			int option = OptionDialog.showOptionDialog(plugin.getMemoryMapProvider().getComponent(),
				"Merge Memory Blocks",
				"Merging these blocks will create " + space_size / 1024 +
					"K extra bytes in memory.\n" +
					"Do you really want to merge the selected Memory Block(s)?",
				"Merge Blocks", OptionDialog.QUESTION_MESSAGE);
			if (option == 0) {
				return false;
			}
		}
		return true;
	}

	void setProgram(Program program) {
		this.program = program;
	}

	/**
	 * Delete the list of memory blocks.
	 */
	void deleteBlocks(final List<MemoryBlock> blocks) {

		if (blocks == null || blocks.size() <= 0) {
			return;
		}

		StringBuffer blockNames = new StringBuffer();
		AddressSet set = new AddressSet();
		for (int i = 0; i < blocks.size(); i++) {
			MemoryBlock block = blocks.get(i);
			blockNames.append(block.getName());
			if (i < blocks.size() - 1) {
				blockNames.append(", ");
			}
			set.addRange(block.getStart(), block.getEnd());
		}
		String msg =
			"Do you really want to delete the Memory Block(s)\n" + "   " + blockNames + "  ?";
		Listing listing = program.getListing();
		InstructionIterator iter = listing.getInstructions(set, true);

		if (iter.hasNext()) {
			msg = "Code Units exist in selected block(s).\n" + "Do you want to continue?";
		}
		else {
			DataIterator dIter = listing.getDefinedData(set, true);
			if (dIter.hasNext()) {
				msg = "Code Units exist in selected block(s).\n" + "Do you want to continue?";
			}
		}

		int option = -1;

		option = OptionDialog.showOptionDialog(plugin.getMemoryMapProvider().getComponent(),
			"Delete Memory Block?", msg, "Yes", OptionDialog.QUESTION_MESSAGE);

		if (option == OptionDialog.CANCEL_OPTION) {
			return;
		}

		Address[] addresses = new Address[blocks.size()];
		for (int i = 0; i < blocks.size(); i++) {
			MemoryBlock block = blocks.get(i);
			addresses[i] = block.getStart();
		}
		DeleteBlockCmd cmd = new DeleteBlockCmd(addresses, command -> {
			// don't care
		});

		tool.executeBackgroundCommand(cmd, program);
	}

	private class SplitBlockCmd implements Command {

		private MemoryBlock block;
		private Address newStart;
		private String newBlockName;
		private String msg;

		SplitBlockCmd(MemoryBlock block, Address newStart, String newBlockName) {
			this.block = block;
			this.newStart = newStart;
			this.newBlockName = newBlockName;
		}

		@Override
		public boolean applyTo(DomainObject obj) {
			Program p = (Program) obj;
			Memory memory = p.getMemory();

			if (!p.hasExclusiveAccess()) {
				msg = "Exclusive access required";
				return false;
			}

			try {
				memory.split(block, newStart);
			}
			catch (MemoryBlockException e) {
				msg = e.getMessage();
				return false;
			}
			catch (IllegalArgumentException e) {
				msg = e.getMessage();
				return false;
			}
			catch (NotFoundException e) {
				msg = e.getMessage();
				return false;
			}
			catch (LockException e) {
				msg = e.getMessage();
				return false;
			}
			MemoryBlock newBlock = memory.getBlock(newStart);
			try {
				newBlock.setName(newBlockName);
			}
			catch (LockException e) {
				msg = e.getMessage();
				return false;
			}
			return true;
		}

		@Override
		public String getName() {
			return "Split Memory Block";
		}

		@Override
		public String getStatusMsg() {
			return msg;
		}
	}

	private class MergeBlocksCmd implements Command {

		private String msg;
		private List<MemoryBlock> blocks;

		MergeBlocksCmd(List<MemoryBlock> blocks) {
			this.blocks = blocks;
		}

		@Override
		public boolean applyTo(DomainObject obj) {
			Program p = (Program) obj;
			Memory mem = p.getMemory();
			Address min = null;
			Address max = null;

			if (!allBlocksInSameSpace()) {
				msg = "All memory block must be in the same address space.";
				return false;
			}

			for (MemoryBlock nextBlock : blocks) {
				if (min == null || nextBlock.getStart().compareTo(min) < 0) {
					min = nextBlock.getStart();
				}
				if (max == null || nextBlock.getEnd().compareTo(max) > 0) {
					max = nextBlock.getEnd();
				}
			}

			if (max == null) {
				return false;
			}

			long size = max.subtract(min) + 1;
			if (size <= 0 || size > Integer.MAX_VALUE) {
				msg = "Resulting Memory Block would be too large.";
				return false;
			}

			try {

				// start with first block
				MemoryBlock bigBlock = blocks.get(0);

				// for each block after
				for (int i = 1; i < blocks.size(); i++) {
					//   get block after
					MemoryBlock nextBlock = blocks.get(i);

					//   create new block for gap in between first block
					Address start = bigBlock.getEnd();
					start = start.addNoWrap(1);
					long length = nextBlock.getStart().subtract(start);
					if (length != 0) {
						MemoryBlock newBlock;
						if (bigBlock.isInitialized()) {
							newBlock = mem.createInitializedBlock(bigBlock.getName(), start, length,
								(byte) 0, null, false);
							newBlock.setRead(bigBlock.isRead());
							newBlock.setWrite(bigBlock.isWrite());
							newBlock.setExecute(bigBlock.isExecute());
							newBlock.setVolatile(bigBlock.isVolatile());
							newBlock.setSourceName("Resized Memory Block");
						}
						else {
							newBlock = mem.createUninitializedBlock(bigBlock.getName(), start,
								(int) length, false);
						}
						newBlock.setComment(bigBlock.getComment());
						//   join block with gap block
						bigBlock = mem.join(bigBlock, newBlock);
					}

					//  Rename the fragment based on the first block
					renameFragment(start, bigBlock.getName());

					//   join block with block after
					bigBlock = mem.join(bigBlock, nextBlock);
				}
				return true;

			}
			catch (RollbackException e) {
				throw e;
			}
			catch (Exception e) {
				msg = e.getMessage();
				if (msg == null) {
					msg = "Error merging blocks: " + e;
				}
			}
			catch (OutOfMemoryError e) {
				msg = "Not enough memory to merge blocks";
			}
			throw new RollbackException(msg);
		}

		private boolean allBlocksInSameSpace() {
			AddressSpace lastSpace = null;
			for (MemoryBlock block : blocks) {
				Address start = block.getStart();
				AddressSpace space = start.getAddressSpace();
				if (lastSpace != null && !lastSpace.equals(space)) {
					return false;
				}
				lastSpace = space;
			}
			return true;
		}

		@Override
		public String getName() {
			return "Merge Memory Blocks";
		}

		@Override
		public String getStatusMsg() {
			return msg;
		}
	}
}


text:
package org.ihtsdo.rvf.validation.log;

public interface ValidationLogFactory {

	ValidationLog getValidationLog(Class<?> subject);

}