text:
package engineer.spodin.algorithms.structures.heap;

import engineer.spodin.algorithms.Provider;
import engineer.spodin.algorithms.util.Iterables;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.util.Arrays;
import java.util.Comparator;
import java.util.function.Supplier;

import static org.hamcrest.Matchers.arrayContainingInAnyOrder;
import static org.junit.Assert.*;

@RunWith(Parameterized.class)
public class HeapTest {
    private static final Comparator<Integer> MAX_HEAP_COMPARATOR = Comparator.reverseOrder();
    private static final Comparator<Integer> MIN_HEAP_COMPARATOR = Comparator.naturalOrder();

    private static final Integer[] TEST_INPUT = {7, 8, 9, 5, 1, 15, 14, 16, 18, 19, 20};

    private final HeapTestEntry provider;

    public HeapTest(HeapTestEntry provider) {
        this.provider = provider;
    }

    private static class HeapTestEntry extends Provider<Heap<Integer>> {
        private final Comparator<Integer> comparator;

        HeapTestEntry(
                Supplier<Heap<Integer>> supplier,
                String description,
                Comparator<Integer> comparator
        ) {
            super(supplier, description);
            this.comparator = comparator;
        }

        @Override
        public Heap<Integer> get() {
            Heap<Integer> heap = super.get();
            Arrays.stream(TEST_INPUT).forEach(heap::push);
            return heap;
        }

        Integer[] expectedOutput() {
            Integer[] copy = Arrays.copyOf(TEST_INPUT, TEST_INPUT.length);
            Arrays.sort(copy, comparator);
            return copy;
        }
    }

    @Parameterized.Parameters(name = "{0}")
    public static Iterable<Object> implementations() {
        return Arrays.asList(
                new HeapTestEntry(
                        ArrayHeap::new,
                        "ArrayHeap (max, default comparator)",
                        MAX_HEAP_COMPARATOR
                ),
                new HeapTestEntry(
                        () -> new ArrayHeap<>(MAX_HEAP_COMPARATOR),
                        "ArrayHeap (max)",
                        MAX_HEAP_COMPARATOR
                ),
                new HeapTestEntry(
                        () -> new ArrayHeap<>(MIN_HEAP_COMPARATOR),
                        "ArrayHeap (min)",
                        MIN_HEAP_COMPARATOR
                )
        );
    }

    @Test
    public void popAndPeekFromEmptyHeapWouldReturnNull() {
        final Heap<Integer> heap = provider.get();

        while (!heap.isEmpty()) {
            heap.pop();
        }

        assertSize(heap, 0);
        assertNull(heap.peek());
        assertNull(heap.pop());
    }

    @Test
    public void pushingNullsWouldBeIgnored() {
        final Heap<Integer> heap = provider.get();
        int sizeBefore = heap.size();

        heap.push(null);
        heap.push(null);

        assertEquals(sizeBefore, heap.size());
    }

    @Test
    public void testIterationOrdering() {
        final Heap<Integer> heap = provider.get();

        Integer[] collected = Iterables.toStream(heap).toArray(Integer[]::new);

        assertSize(heap, collected.length);
        assertThat(collected, arrayContainingInAnyOrder(TEST_INPUT));
        assertArrayEquals(provider.expectedOutput(), collected);
    }

    @Test
    public void testPeekAndPop() {
        final Heap<Integer> heap = provider.get();

        Integer[] expected = provider.expectedOutput();

        for (int i = 0; i < expected.length; i++) {
            assertPeekAndPop(heap, expected[i]);
            assertSize(heap, expected.length - i - 1);
        }
    }

    private static void assertSize(Heap<?> heap, int expectedSize) {
        assertEquals(expectedSize, heap.size());
        assertEquals(heap.isEmpty(), expectedSize == 0);
    }

    private static <T extends Comparable<T>> void assertPeekAndPop(Heap<T> heap, T expected) {
        assertEquals(expected, heap.peek());
        assertEquals(expected, heap.pop());
    }
}

redpajama_set_name: RedPajamaGithub


text:
package registry

import (
	"errors"
	"net/http"
	"time"

	log "github.com/sirupsen/logrus"

	"github.com/kelda/kelda/db"
	"github.com/kelda/kelda/minion/docker"
	"sync"
)

/*
The registry submodule builds custom Dockerfiles. When a custom Dockerfile is
deployed in a blueprint (e.g.`new Container(new Image("name", "dk"))`), a couple
things happen:
1) On the leader, the engine reads the custom images from the Containers in the
blueprint, and writes them to the Image table.
2) The registry submodule builds the images in the Image table, and updates
their image ID with the ID of the built image.
3) The scheduler schedules containers for which the image has been built.
When scheduling Containers with custom images, it modifies the image to
be pointed at the registry running on the leader. A side effect of this is that
if the leader dies, the scheduler updates the image names in etcd, and the workers
restart containers running the custom image.
4) The workers pull and run the image just like any other image.
*/

// Run builds Docker images according to the Image table if the minion's Role is
// Master, and does nothing otherwise.
func Run(conn db.Conn, dk docker.Client) {
	if conn.MinionSelf().Role != db.Master {
		return
	}

	bootWait()
	for range conn.TriggerTick(30, db.ImageTable).C {
		syncImages(conn, dk)
	}
}

// syncImages checks the Image table for any images that have not yet been
// built, and builds them.
func syncImages(conn db.Conn, dk docker.Client) {
	var toBuild []db.Image
	conn.Txn(db.ImageTable).Run(func(view db.Database) error {
		toBuild = view.SelectFromImage(func(img db.Image) bool {
			return img.Status != db.Built
		})
		return nil
	})

	var wg sync.WaitGroup
	wg.Add(len(toBuild))
	sema := make(chan struct{}, 8)

	builder := func(img db.Image) {
		sema <- struct{}{}
		defer func() {
			writeImage(conn, img)
			<-sema
			wg.Done()
		}()

		img.Status = db.Building
		writeImage(conn, img)

		log.WithField("image", img.Name).Info("Building image...")
		id, err := updateRegistry(dk, img)
		if err != nil {
			img.Status = "" // Unset the building status.

			log.WithError(err).WithField("image", img.Name).
				Error("Failed to update registry")
			return
		}

		img.DockerID = id
		img.Status = db.Built

		log.WithField("image", img.Name).Info("Built image.")
	}

	for _, img := range toBuild {
		go builder(img)
	}
	wg.Wait()
}

func updateRegistry(dk docker.Client, img db.Image) (string, error) {
	registryImg := "localhost:5000/" + img.Name
	id, err := dk.Build(registryImg, img.Dockerfile, false)
	if err == nil {
		err = dk.Push("localhost:5000", registryImg)
	}
	return id, err
}

// writeImage updates the attributes of the image committed to the database that
// has the same Name and Dockerfile.
func writeImage(conn db.Conn, img db.Image) {
	err := conn.Txn(db.ImageTable).Run(
		func(view db.Database) error {
			dbImg, err := getImageHandle(view, img)
			if err == nil {
				img.ID = dbImg.ID
				view.Commit(img)
			}
			return err
		},
	)
	if err != nil {
		log.WithError(err).WithField("image", img).Warn("Failed to write image")
	}
}

func getImageHandle(view db.Database, ref db.Image) (db.Image, error) {
	matchingImages := view.SelectFromImage(func(img db.Image) bool {
		return img.Dockerfile == ref.Dockerfile && img.Name == ref.Name
	})
	switch len(matchingImages) {
	case 0:
		return db.Image{}, errors.New("no matching images")
	case 1:
		return matchingImages[0], nil
	default:
		return db.Image{}, errors.New("multiple matching images")
	}
}

// bootWait blocks until the registry is ready to be pushed to.
func bootWait() {
	for {
		_, err := http.Get("http://localhost:5000")
		if err != nil {
			log.WithError(err).Debug("Registry not up yet")
		} else {
			break
		}

		time.Sleep(500 * time.Millisecond)
	}
}


text:
define(["application-configuration"],function(app) {

    function chatController($rootScope, $scope,$compile, $routeParams, $location, $localStorage,api){

        $scope.user = api.current_user();
        $scope.userActions = [1,2,3,4,5,6,7,8,9,10];
        $scope.onlineUsers = [1,2,3,4,5,6,7,8,9,10];
        $scope.activeChats = [];

        $scope.openChat     = function(userId){
            if(!($scope.activeChats.indexOf(userId)>-1 && userId)){
                $scope.activeChats.push(userId);
                $scope.register_popup('user'+userId,'name'+userId)

            }
        };
        //this function can remove a array element.
         Array.remove = function(array, from, to) {
             var rest = array.slice((to || from) + 1 || array.length);
             array.length = from < 0 ? array.length + from : from;
             return array.push.apply(array, rest);
         };

         //this variable represents the total number of popups can be displayed according to the viewport width
         var total_popups = 0;

         //arrays of popups ids
         var popups = [];

         //this is used to close a popup
         $scope.close_popup = function(id)
         {
             for(var iii = 0; iii < popups.length; iii++)
             {
                 if(id == popups[iii])
                 {
                     Array.remove(popups, iii);

                     document.getElementById(id).style.display = "none";

                     calculate_popups();

                     return;
                 }
             }
         }

         //displays the popups. Displays based on the maximum number of popups that can be displayed on the current viewport width
         function display_popups()
         {
             var right = 320;
             var iii = 0;
             for(iii; iii < total_popups; iii++)
             {
                 if(popups[iii] != undefined)
                 {
                     var element = angular.element('#'+popups[iii]);
                     element.css("right", right + "px");
                     right = right + 320;
                     element.css("display","block");
                 }
             }

             for(var jjj = iii; jjj < popups.length; jjj++)
             {
                 var element = angular.element('#'+popups[jjj]);
                 element.css('display',"none");
             }
         }

         //creates markup for a new popup. Adds the id to popups array.
         $scope.register_popup = function(id, name)
         {

             for(var iii = 0; iii < popups.length; iii++)
             {
                 //already registered. Bring it to front.
                 if(id == popups[iii])
                 {
                     Array.remove(popups, iii);

                     popups.unshift(id);

                     calculate_popups();

                     return;
                 }
             }

             var element = '';

            angular.element('body').append($compile(element)($scope));

             popups.unshift(id);

             calculate_popups();

         };

         //calculate the total number of popups suitable and then populate the toatal_popups variable.
         function calculate_popups()
         {
             var width = window.innerWidth;
             if(width < 540)
             {
                 total_popups = 0;
             }
             else
             {
                 width = width - 320;
                 //320 is width of a single popup box
                 total_popups = parseInt(width/320);
             }

             display_popups();

         }
         console.log($scope);
        $scope.classname = 'slide-right';
    }
    app.register.controller("chatController", ['$rootScope', '$scope','$compile','$routeParams', '$location', '$localStorage','api',chatController]);

    app.register.directive('chatresize', function ($window) {
        return function (scope, element) {
            var w = angular.element($window);
            scope.getWindowDimensions = function () {
                return {
                    'h': w.height(),
                    'w': w.width()
                };
            };
            scope.$watch(scope.getWindowDimensions, function (newValue, oldValue) {

                scope.lastfeedStyle = function () {
                    return {
                        'height': (newValue.h/3.5) + 'px',
                        'overflow-y' : 'scroll'
                    };
                };
                scope.chatStyle = function(){
                    return {
                        'height': (newValue.h/1.6) + 'px',
                        'overflow-y' : 'scroll'
                    };
                };

            }, true);

            w.bind('resize', function () {
                scope.$apply();
            });
        }
    });

});


text:
(function(factory){

	// CommonJS/RequireJS and "native" compatibility
	if(typeof module !== "undefined" && typeof exports == "object") {
		// A commonJS/RequireJS environment
		if(typeof window != "undefined") {
			// Window and document exist, so return the factory's return value.
			module.exports = factory();
		} else {
			// Let the user give the factory a Window and Document.
			module.exports = factory;
		}
	} else {
		// Assume a traditional browser.
		window.Affix = factory();
	}

})(function(){

	//AFFIX DEFINITION
	var Affix = function(element,options) {
		this.element = typeof element === 'object' ? element : document.querySelector(element);
		this.options = {};
		this.options.target = options.target ? ((typeof(options.target) === 'object') ? options.target : document.querySelector(options.target)) : null; // target is an object
		this.options.offsetTop = options.offsetTop && options.offsetTop ? ( options.offsetTop === 'function' ? options.offsetTop() : parseInt(options.offsetTop,0) ) : 0; // offset option is an integer number or function to determine that number
		this.options.offsetBottom = options.offsetBottom && options.offsetBottom ? ( options.offsetBottom === 'function' ? options.offsetBottom() : parseInt(options.offsetBottom,0) ) : null;

		if (this.element && (this.options.target || this.options.offsetTop || this.options.offsetBottom ) ) { this.init(); }
	}

	//AFFIX METHODS
	Affix.prototype = {
		init: function () {
			this.affixed = false;
			this.affixedBottom = false;
			this.getPinOffsetTop = 0;
			this.getPinOffsetBottom = null;

			//actions
			this.checkPosition();
			this.updateAffix();
			this.scrollEvent();
			this.resizeEvent()
		},
		processOffsetTop: function () {
			if ( this.options.target !== null ) {
				return this.targetRect().top + this.scrollOffset();
			} else if ( this.options.offsetTop !== null ) {
				return this.options.offsetTop
			}
		},
		processOffsetBottom: function () {
			if ( this.options.offsetBottom !== null ) {
				var maxScroll = this.getMaxScroll();
				return maxScroll - this.elementHeight() - this.options.offsetBottom
			}
		},
		offsetTop: function () {
			return this.processOffsetTop()
		},
		offsetBottom: function () {
			return this.processOffsetBottom()
		},
		checkPosition: function () {
			this.getPinOffsetTop = this.offsetTop
			this.getPinOffsetBottom = this.offsetBottom
		},
		scrollOffset: function () {
			return window.pageYOffset || document.documentElement.scrollTop
		},
		pinTop: function () {
			if ( this.element.classList && !this.element.classList.contains('affix') ) this.element.classList.add('affix');
			this.affixed = true
		},
		unPinTop: function () {
			if ( this.element.classList && this.element.classList.contains('affix') ) this.element.classList.remove('affix');
			this.affixed = false
		},
		pinBottom: function () {
			if ( this.element.classList && !this.element.classList.contains('affix-bottom') ) this.element.classList.add('affix-bottom');
			this.affixedBottom = true
		},
		unPinBottom: function () {
			if ( this.element.classList && this.element.classList.contains('affix-bottom') ) this.element.classList.remove('affix-bottom');
			this.affixedBottom = false
		},

		updatePin: function () {
			if (this.affixed === false && (parseInt(this.offsetTop(),0) - parseInt(this.scrollOffset(),0) < 0)) {
				this.pinTop();
			} else if (this.affixed === true && (parseInt(this.scrollOffset(),0) <= parseInt(this.getPinOffsetTop(),0) )) {
				this.unPinTop()
			}

			if (this.affixedBottom === false && (parseInt(this.offsetBottom(),0) - parseInt(this.scrollOffset(),0) < 0)) {
				this.pinBottom();
			} else if (this.affixedBottom === true && (parseInt(this.scrollOffset(),0) <= parseInt(this.getPinOffsetBottom(),0) )) {
				this.unPinBottom()
			}
		},

		updateAffix : function () { // Unpin and check position again
			this.unPinTop();
			this.unPinBottom();
			this.checkPosition()

			this.updatePin() // If any case update values again
		},

		elementHeight : function(){
			return this.element.offsetHeight
		},

		targetRect : function(){
			return this.options.target.getBoundingClientRect()
		},

		getMaxScroll : function(){
			return Math.max( document.body.scrollHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight )
		},

		scrollEvent : function(){
			var self = this;
			window.addEventListener('scroll', affOnScroll = function() {
				self.updatePin()
			}, false);

		},
		resizeEvent : function(){
			var self = this;
			window.addEventListener('resize', affOnResize = function () {
				setTimeout(function(){
					self.updateAffix()
				},100);
			}, false);

		}
	};

	var Affixes = document.querySelectorAll('[data-spy="affix"]');
	[].forEach.call(Affixes, function (item) {
		var options = {};
			options.offsetTop		= item.getAttribute('data-offset-top');
			options.offsetBottom	= item.getAttribute('data-offset-bottom');
			options.target			= item.getAttribute('data-target');

		if ( item && (options.offsetTop !== null || options.offsetBottom !== null || options.target !== null) ) { //don't do anything unless we have something valid to pin
			return new Affix(item, options);
		}
	})

	return Affix;
});


text:
var chai = require('chai');
var expect = chai.expect;
var ThirdView = require('./views/thirdView');

describe('ThirdView Test', function() {
    describe('#init()', function() {
        it('should have init and render functions', function() {

            expect(ThirdView.init).to.be.a('function');
            expect(ThirdView.render).to.be.a('function');

        });
    });
});


text:
<?

	include_once("../../PeoplePods.php");

	$POD = new PeoplePod(array('lockdown'=>'adminuser','authSecret'=>@$_COOKIE['pp_auth']));
	$POD->changeTheme('admin');

	$mode = $_GET['mode'];

	if ($mode =='upload') {
		// someone just uploaded or modified an image

	} else if ($mode=='list') {

		$content = $POD->getContent(array('id'=>$_GET['docId']));

		?>

		<?
		// output an upload form
		$content->output('browser.upload');

		// output list of files
		$content->files()->output('browser.list','list_header','list_footer',null,'No files attached to this content.');
		?>

		<?
	} else if ($mode=='details') {

		$content = $POD->getContent(array('id'=>$_GET['docId']));
		$file = $content->files()->contains('id',$_GET['fileId']);
		$file->output('browser.details');

	}


text:
#include "internal.h"
#include <string.h>

/**
 * \file dhstate.h
 * \brief DHState interface
 */

/**
 * \file dhstate.c
 * \brief DHState implementation
 */

/**
 * \defgroup dhstate DHState API
 *
 * DHState objects are used to store the keypairs for the local party or
 * the public keys for remote parties.  Once the keys have been set,
 * noise_dhstate_calculate() can be used to perform a Diffie-Hellman
 * operation with two DHState objects.
 */
/**@{*/

/**
 * \typedef NoiseDHState
 * \brief Opaque object that represents a DHState.
 */

/**
 * \brief Creates a new DHState object by its algorithm identifier.
 *
 * \param state Points to the variable where to store the pointer to
 * the new DHState object.
 * \param id The algorithm identifier; NOISE_DH_CURVE25519,
 * NOISE_DH_CURVE448, etc.
 *
 * \return NOISE_ERROR_NONE on success.
 * \return NOISE_ERROR_INVALID_PARAM if \a state is NULL.
 * \return NOISE_ERROR_UNKNOWN_ID if \a id is unknown.
 * \return NOISE_ERROR_NO_MEMORY if there is insufficient memory to
 * allocate the new DHState object.
 *
 * \sa noise_dhstate_free(), noise_dhstate_new_by_name()
 */
int noise_dhstate_new_by_id(NoiseDHState **state, int id)
{
    /* The "state" argument must be non-NULL */
    if (!state)
        return NOISE_ERROR_INVALID_PARAM;

    /* Create the DHState object for the "id" */
    *state = 0;
    switch (id) {
    case NOISE_DH_CURVE25519:
        *state = noise_curve25519_new();
        break;

    case NOISE_DH_CURVE448:
        *state = noise_curve448_new();
        break;

    case NOISE_DH_NEWHOPE:
        *state = noise_newhope_new();
        break;

    default:
        return NOISE_ERROR_UNKNOWN_ID;
    }

    /* Bail out if insufficient memory */
    if (!(*state))
        return NOISE_ERROR_NO_MEMORY;

    /* Ready to go */
    return NOISE_ERROR_NONE;
}

/**
 * \brief Creates a new DHState object by its algorithm name.
 *
 * \param state Points to the variable where to store the pointer to
 * the new DHState object.
 * \param name The name of the Diffie-Hellman algorithm; e.g. "25519".
 * This string must be NUL-terminated.
 *
 * \return NOISE_ERROR_NONE on success.
 * \return NOISE_ERROR_INVALID_PARAM if \a state or \a name is NULL.
 * \return NOISE_ERROR_UNKNOWN_NAME if \a name is unknown.
 * \return NOISE_ERROR_NO_MEMORY if there is insufficient memory to
 * allocate the new DHState object.
 *
 * \sa noise_dhstate_free(), noise_dhstate_new_by_id()
 */
int noise_dhstate_new_by_name(NoiseDHState **state, const char *name)
{
    int id;

    /* The "state" and "name" arguments must be non-NULL */
    if (!state)
        return NOISE_ERROR_INVALID_PARAM;
    *state = 0;
    if (!name)
        return NOISE_ERROR_INVALID_PARAM;

    /* Map the name and create the corresponding object */
    id = noise_name_to_id(NOISE_DH_CATEGORY, name, strlen(name));
    if (id)
        return noise_dhstate_new_by_id(state, id);

    /* We don't know what this is */
    return NOISE_ERROR_UNKNOWN_NAME;
}

/**
 * \brief Frees a DHState object after destroying all sensitive material.
 *
 * \param state The DHState object to free.
 *
 * \return NOISE_ERROR_NONE on success.
 * \return NOISE_ERROR_INVALID_PARAM if \a state is NULL.
 *
 * \sa noise_dhstate_new_by_id(), noise_dhstate_new_by_name()
 */
int noise_dhstate_free(NoiseDHState *state)
{
    /* Bail out if no DH state */
    if (!state)
        return NOISE_ERROR_INVALID_PARAM;

    /* Call the backend-specific destroy function if necessary */
    if (state->destroy)
        (*(state->destroy))(state);

    /* Clean and free the memory */
    noise_free(state, state->size);
    return NOISE_ERROR_NONE;
}

/**
 * \brief Gets the algorithm identifier for a DHState object.
 *
 * \param state The DHState object.
 *
 * \return The algorithm identifier, or NOISE_DH_NONE if \a state is NULL.
 */
int noise_dhstate_get_dh_id(const NoiseDHState *state)
{
    return state ? state->dh_id : NOISE_DH_NONE;
}

/**
 * \brief Gets the length of the public key for a DHState object.
 *
 * \param state The DHState object.
 *
 * \return The size of the public key in bytes, or 0 if \a state is NULL.
 *
 * \sa noise_dhstate_get_private_key_length(),
 * noise_dhstate_get_shared_key_length()
 */
size_t noise_dhstate_get_public_key_length(const NoiseDHState *state)
{
    return state ? state->public_key_len : 0;
}

/**
 * \brief Gets the length of the private key for a DHState object.
 *
 * \param state The DHState object.
 *
 * \return The size of the private key in bytes, or 0 if \a state is NULL.
 *
 * \sa noise_dhstate_get_public_key_length(),
 * noise_dhstate_get_shared_key_length()
 */
size_t noise_dhstate_get_private_key_length(const NoiseDHState *state)
{
    return state ? state->private_key_len : 0;
}

/**
 * \brief Gets the length of the shared key for a DHState object.
 *
 * \param state The DHState object.
 *
 * \return The size of the shared key in bytes, or 0 if \a state is NULL.
 *
 * \sa noise_dhstate_get_public_key_length(),
 * noise_dhstate_get_private_key_length()
 */
size_t noise_dhstate_get_shared_key_length(const NoiseDHState *state)
{
    return state ? state->shared_key_len : 0;
}

/**
 * \brief Determine if a DHState object only supports ephemeral keys.
 *
 * \param state The DHState object.
 *
 * \return Non-zero if the DHState object only supports ephemeral keys,
 * or zero if the DHState object supports both static and ephemeral keys.
 *
 * Some algorithms like "NewHope" can only be used to generate
 * ephemeral keys during a session and have no support for long-term
 * static keys.
 */
int noise_dhstate_is_ephemeral_only(const NoiseDHState *state)
{
    return state ? state->ephemeral_only : 0;
}

/**
 * \brief Determine if a DHState object contains a keypair.
 *
 * \param state The DHState object.
 *
 * \return Returns 1 if \a state contains both a private key and a
 * public key.  Returns 0 if \a state is NULL or it only contains a
 * public key.
 *
 * \sa noise_dhstate_set_keypair(), noise_dhstate_has_public_key(),
 * noise_dhstate_clear_key()
 */
int noise_dhstate_has_keypair(const NoiseDHState *state)
{
    if (state)
        return state->key_type == NOISE_KEY_TYPE_KEYPAIR;
    else
        return 0;
}

/**
 * \brief Determine if a DHState object contains a public key.
 *
 * \param state The DHState object.
 *
 * \return Returns 1 if \a state contains a public key (and optionally a
 * private key).  Returns 0 if \a state is NULL or it does not contain a
 * public key.
 *
 * \sa noise_dhstate_set_keypair(), noise_dhstate_has_public_key(),
 * noise_dhstate_clear_key()
 */
int noise_dhstate_has_public_key(const NoiseDHState *state)
{
    if (state)
        return state->key_type != NOISE_KEY_TYPE_NO_KEY;
    else
        return 0;
}

/**
 * \brief Generates a new key pair within a DHState object.
 *
 * \param state The DHState object.
 *
 * \return NOISE_ERROR_NONE on success.
 * \return NOISE_ERROR_INVALID_PARAM if \a state is NULL.
 *
 * \note This function needs to generate random key material for the
 * private key, so the system random number generator must be properly
 * seeded before calling this function.
 *
 * \sa noise_dhstate_calculate(), noise_dhstate_set_keypair()
 */
int noise_dhstate_generate_keypair(NoiseDHState *state)
{
    int err;

    /* Validate the parameter */
    if (!state)
        return NOISE_ERROR_INVALID_PARAM;

    /* Generate the new keypair */
    err = (*(state->generate_keypair))(state, 0);
    if (err == NOISE_ERROR_NONE)
        state->key_type = NOISE_KEY_TYPE_KEYPAIR;
    return err;
}

/**
 * \brief Generates a new key pair within a DHState object that may depend
 * upon the parameters from another DHState object.
 *
 * \param state The DHState object.
 * \param other The other DHState object to obtain parameters from,
 * which may be NULL.
 *
 * \return NOISE_ERROR_NONE on success.
 * \return NOISE_ERROR_INVALID_PARAM if \a state or is NULL.
 * \return NOISE_ERROR_INVALID_PARAM if \a state and \a other
 * do not have the same algorithm identifier.
 * \return NOISE_ERROR_INVALID_STATE if dependent parameters are required
 * but \a other does not currently contain any.
 *
 * This function is intended for generating ephemeral keypairs for
 * algorithms like New Hope where the keypair for Bob depends upon
 * parameters that are transmitted in Alice's public key.  If the
 * algorithm does not require dependent parameters to generate the
 * keypair, \a other is ignored.
 *
 * \note This function needs to generate random key material for the
 * private key, so the system random number generator must be properly
 * seeded before calling this function.
 *
 * \sa noise_dhstate_calculate(), noise_dhstate_set_keypair()
 */
int noise_dhstate_generate_dependent_keypair
    (NoiseDHState *state, const NoiseDHState *other)
{
    int err;

    /* Validate the parameters */
    if (!state)
        return NOISE_ERROR_INVALID_PARAM;
    if (other && state->dh_id != other->dh_id)
        return NOISE_ERROR_INVALID_PARAM;

    /* Generate the new keypair */
    err = (*(state->generate_keypair))(state, other);
    if (err == NOISE_ERROR_NONE)
        state->key_type = NOISE_KEY_TYPE_KEYPAIR;
    return err;
}

/**
 * \brief Sets the keypair within a DHState object.
 *
 * \param state The DHState object.
 * \param private_key Points to the private key.
 * \param private_key_len The private key length in bytes.
 * \param public_key Points to the public key.
 * \param public_key_len The public key length in bytes.
 *
 * \return NOISE_ERROR on success.
 * \return NOISE_ERROR_INVALID_PARAM if \a state, \a private_key, or
 * \a public_key is NULL.
 * \return NOISE_ERROR_INVALID_LENGTH if either \a private_key_len or
 * \a public_key_len is incorrect for the algorithm.
 * \return NOISE_ERROR_INVALID_PRIVATE_KEY if \a private_key is not valid.
 * \return NOISE_ERROR_INVALID_PUBLIC_KEY if \a public_key is not valid.
 *
 * The algorithm may decide to defer NOISE_ERROR_INVALID_PRIVATE_KEY or
 * NOISE_ERROR_INVALID_PUBLIC_KEY to later when the keypair is actually
 * used during noise_dhstate_calculate().
 *
 * \sa noise_dhstate_get_keypair(), noise_dhstate_set_public_key(),
 * noise_dhstate_set_keypair_private()
 */
int noise_dhstate_set_keypair
    (NoiseDHState *state, const uint8_t *private_key, size_t private_key_len,
     const uint8_t *public_key, size_t public_key_len)
{
    int err;

    /* Validate the parameters */
    if (!state || !private_key || !public_key)
        return NOISE_ERROR_INVALID_PARAM;
    if (private_key_len != state->private_key_len)
        return NOISE_ERROR_INVALID_LENGTH;
    if (public_key_len != state->public_key_len)
        return NOISE_ERROR_INVALID_LENGTH;

    /* Set the keypair */
    err = (*(state->set_keypair))(state, private_key, public_key);
    if (err != NOISE_ERROR_NONE) {
        noise_dhstate_clear_key(state);
        return err;
    }
    state->key_type = NOISE_KEY_TYPE_KEYPAIR;
    return NOISE_ERROR_NONE;
}

/**
 * \brief Sets the keypair within a DHState object based on a private key only.
 *
 * \param state The DHState object.
 * \param private_key Points to the private key.
 * \param private_key_len The private key length in bytes.
 *
 * \return NOISE_ERROR on success.
 * \return NOISE_ERROR_INVALID_PARAM if \a state or \a private_key is NULL.
 * \return NOISE_ERROR_INVALID_LENGTH if either \a private_key_len is
 * incorrect for the algorithm.
 * \return NOISE_ERROR_INVALID_PRIVATE_KEY if \a private_key is not valid.
 * \return NOISE_ERROR_INVALID_PUBLIC_KEY if \a public_key that is derived
 * from the \a private_key is not valid.
 *
 * The algorithm may decide to defer NOISE_ERROR_INVALID_PRIVATE_KEY or
 * NOISE_ERROR_INVALID_PUBLIC_KEY to later when the keypair is actually
 * used during noise_dhstate_calculate().
 *
 * This function only takes the private key as an argument.  The public
 * key in the keypair is derived from the private key.
 *
 * \sa noise_dhstate_get_keypair(), noise_dhstate_set_public_key(),
 * noise_dhstate_set_keypair()
 */
int noise_dhstate_set_keypair_private
    (NoiseDHState *state, const uint8_t *private_key, size_t private_key_len)
{
    int err;

    /* Validate the parameters */
    if (!state || !private_key)
        return NOISE_ERROR_INVALID_PARAM;
    if (private_key_len != state->private_key_len)
        return NOISE_ERROR_INVALID_LENGTH;

    /* Set the private key and derive the public key from the private key */
    err = (*(state->set_keypair_private))(state, private_key);
    if (err != NOISE_ERROR_NONE) {
        noise_dhstate_clear_key(state);
        return err;
    }
    state->key_type = NOISE_KEY_TYPE_KEYPAIR;
    return NOISE_ERROR_NONE;
}

/**
 * \brief Gets the keypair from within a DHState object.
 *
 * \param state The DHState object.
 * \param private_key Points to the buffer to receive the private key.
 * \param private_key_len The private key buffer length in bytes.
 * \param public_key Points to the buffer to receive the public key.
 * \param public_key_len The public key buffer length in bytes.
 *
 * \return NOISE_ERROR on success.
 * \return NOISE_ERROR_INVALID_PARAM if \a state, \a private_key, or
 * \a public_key is NULL.
 * \return NOISE_ERROR_INVALID_LENGTH if either \a private_key_len or
 * \a public_key_len is incorrect for the algorithm.
 * \return NOISE_ERROR_INVALID_STATE if \a state does not contain a keypair.
 *
 * \sa noise_dhstate_set_keypair(), noise_dhstate_get_public_key()
 */
int noise_dhstate_get_keypair
    (const NoiseDHState *state, uint8_t *private_key, size_t private_key_len,
     uint8_t *public_key, size_t public_key_len)
{
    /* Validate the parameters */
    if (!state || !private_key || !public_key)
        return NOISE_ERROR_INVALID_PARAM;
    if (private_key_len != state->private_key_len)
        return NOISE_ERROR_INVALID_LENGTH;
    if (public_key_len != state->public_key_len)
        return NOISE_ERROR_INVALID_LENGTH;

    /* Is this actually a keypair? */
    if (state->key_type != NOISE_KEY_TYPE_KEYPAIR) {
        memset(private_key, 0, private_key_len);
        memset(public_key, 0, public_key_len);
        return NOISE_ERROR_INVALID_STATE;
    }

    /* Copy the keypair out */
    memcpy(private_key, state->private_key, private_key_len);
    memcpy(public_key, state->public_key, public_key_len);
    return NOISE_ERROR_NONE;
}

/**
 * \brief Sets the public key in a DHState object.
 *
 * \param state The DHState object.
 * \param public_key Points to the public key.
 * \param public_key_len The public key length in bytes.
 *
 * \return NOISE_ERROR_NONE on success.
 * \return NOISE_ERROR_INVALID_PARAM if \a state or \a public_key is NULL.
 * \return NOISE_ERROR_INVALID_LENGTH if \a public_key_len is incorrect
 * for the algorithm.
 * \return NOISE_ERROR_INVALID_PUBLIC_KEY if \a public_key is not valid
 * and it is not the special null value.
 *
 * After this function succeeds, the DHState will only contain a public key.
 * Any existing private key will be cleared.  Thus, this function is useful
 * to set the public key of a remote party.  Use noise_dhstate_set_keypair()
 * to set both the public and private key for the local party.
 *
 * The algorithm may decide to defer NOISE_ERROR_INVALID_PUBLIC_KEY to
 * later when the public key is actually used during noise_dhstate_calculate().
 *
 * \sa noise_dhstate_get_public_key(), noise_dhstate_set_keypair()
 */
int noise_dhstate_set_public_key
    (NoiseDHState *state, const uint8_t *public_key, size_t public_key_len)
{
    int is_null, err;

    /* Validate the parameters */
    if (!state || !public_key)
        return NOISE_ERROR_INVALID_PARAM;
    if (public_key_len != state->public_key_len)
        return NOISE_ERROR_INVALID_LENGTH;

    /* Validate the public key with the back end and then ignore the
       result if the public key is the special null value */
    is_null = state->nulls_allowed & noise_is_zero(public_key, public_key_len);
    err = (*(state->validate_public_key))(state, public_key);
    err &= (is_null - 1);
    if (err != NOISE_ERROR_NONE)
        return err;

    /* Copy the public key into place and clear the private key */
    memset(state->private_key, 0, state->private_key_len);
    memcpy(state->public_key, public_key, public_key_len);
    state->key_type = NOISE_KEY_TYPE_PUBLIC;
    return NOISE_ERROR_NONE;
}

/**
 * \brief Gets the public key value from a DHState object.
 *
 * \param state The DHState object.
 * \param public_key The buffer to receive the public key value.
 * \param public_key_len The public key length in bytes.
 *
 * \return NOISE_ERROR_NONE on success.
 * \return NOISE_ERROR_INVALID_PARAM if \a state or \a public_key is NULL.
 * \return NOISE_ERROR_INVALID_LENGTH if \a public_key_len is incorrect
 * for this algorithm.
 *
 * \sa noise_dhstate_set_public_key(), noise_dhstate_get_public_key_length()
 */
int noise_dhstate_get_public_key
    (const NoiseDHState *state, uint8_t *public_key, size_t public_key_len)
{
    /* Validate the parameters */
    if (!state || !public_key)
        return NOISE_ERROR_INVALID_PARAM;
    if (public_key_len != state->public_key_len)
        return NOISE_ERROR_INVALID_LENGTH;

    /* Copy the public key out */
    memcpy(public_key, state->public_key, public_key_len);
    return NOISE_ERROR_NONE;
}

/**
 * \brief Sets the public key in a DHState object to the special null value.
 *
 * \param state The DHState object.
 *
 * \return NOISE_ERROR_NONE on success.
 * \return NOISE_ERROR_INVALID_PARAM if \a state is NULL.
 * \return NOISE_ERROR_INVALID_PARAM if \a state does not support null
 * public keys.
 *
 * \sa noise_dhstate_is_null_public_key()
 */
int noise_dhstate_set_null_public_key(NoiseDHState *state)
{
    /* Validate the parameter */
    if (!state || !state->nulls_allowed)
        return NOISE_ERROR_INVALID_PARAM;

    /* Clear the key to all-zeroes */
    memset(state->public_key, 0, state->public_key_len);
    memset(state->private_key, 0, state->private_key_len);

    /* We have a public key but no private key */
    state->key_type = NOISE_KEY_TYPE_PUBLIC;
    return NOISE_ERROR_NONE;
}

/**
 * \brief Determine if the public key in a DHState object has the
 * special null value.
 *
 * \param state The DHState object.
 *
 * \return Returns non-zero if the public key within \a state is the
 * special null value; zero otherwise.
 *
 * \sa noise_dhstate_set_null_public_key()
 */
int noise_dhstate_is_null_public_key(const NoiseDHState *state)
{
    if (state && state->key_type != NOISE_KEY_TYPE_NO_KEY) {
        return state->nulls_allowed &&
               noise_is_zero(state->public_key, state->public_key_len);
    } else {
        return 0;
    }
}

/**
 * \brief Clears the key in a DHState object.
 *
 * \param state The DHState object.
 *
 * \return NOISE_ERROR_NONE on success.
 * \return NOISE_ERROR_INVALID_PARAM if \a state is NULL.
 *
 * \sa noise_dhstate_has_keypair(), noise_dhstate_has_public_key()
 */
int noise_dhstate_clear_key(NoiseDHState *state)
{
    /* Validate the parameter */
    if (!state)
        return NOISE_ERROR_INVALID_PARAM;

    /* Clear the key to all-zeroes */
    memset(state->public_key, 0, state->public_key_len);
    memset(state->private_key, 0, state->private_key_len);

    /* There is no key in the object now */
    state->key_type = NOISE_KEY_TYPE_NO_KEY;
    return NOISE_ERROR_NONE;
}

/**
 * \brief Conditional move of zero into a buffer in constant time.
 *
 * \param data The data buffer to fill with zeroes if the condition is true.
 * \param len The length of the \a data buffer in bytes.
 * \param condition Condition that is 1 to move zero into \a data, or
 * zero to leave the contents of \a data as-is.
 */
static void noise_cmove_zero(uint8_t *data, size_t len, int condition)
{
    /* Turn the condition into an all-zeroes or all-ones mask.
       If the condition is set, then we want all-zeroes in the mask.
       If the condition is not set, then we want all-ones in the mask. */
    uint8_t mask = ~((uint8_t)(-condition));

    /* AND the contents of the data buffer with the mask */
    while (len > 0) {
        *data++ &= mask;
        --len;
    }
}

/**
 * \brief Performs a Diffie-Hellman calculation.
 *
 * \param private_key_state Points to the DHState containing the private key.
 * \param public_key_state Points to the DHState containing the public key.
 * \param shared_key Points to the shared key on exit.
 * \param shared_key_len The length of the \a shared_key buffer in bytes.
 *
 * \return NOISE_ERROR_NONE on success.
 * \return NOISE_ERROR_INVALID_PARAM if \a private_key_state,
 * \a public_key_state, or \a shared_key is NULL.
 * \return NOISE_ERROR_INVALID_PARAM if \a private_key_state and
 * \a public_key_state do not have the same algorithm identifier.
 * \return NOISE_ERROR_INVALID_LENGTH if \a shared_key_len is not
 * correct for the algorithm.
 * \return NOISE_ERROR_INVALID_PRIVATE_KEY if \a private_key_state does not
 * contain a private key or the private key is invalid.
 * \return NOISE_ERROR_INVALID_PUBLIC_KEY if the public key in
 * \a public_key_state is invalid.
 *
 * If the input public key is the special null value, then the output
 * \a shared_key will also be the null value and NOISE_ERROR_NONE
 * will be returned.
 *
 * \sa noise_dhstate_generate_keypair()
 */
int noise_dhstate_calculate
    (const NoiseDHState *private_key_state,
     const NoiseDHState *public_key_state,
     uint8_t *shared_key, size_t shared_key_len)
{
    int is_null, err;

    /* Validate the parameters */
    if (!private_key_state || !public_key_state || !shared_key)
        return NOISE_ERROR_INVALID_PARAM;
    if (private_key_state->dh_id != public_key_state->dh_id)
        return NOISE_ERROR_INVALID_PARAM;
    if (shared_key_len != private_key_state->shared_key_len)
        return NOISE_ERROR_INVALID_LENGTH;
    if (private_key_state->key_type != NOISE_KEY_TYPE_KEYPAIR)
        return NOISE_ERROR_INVALID_PRIVATE_KEY;

    /* If the public key is null, then the output must be null too.
       We check for null now, but still perform the normal evaluation.
       At the end we will null out the result in constant time */
    is_null = public_key_state->nulls_allowed & noise_is_zero
        (public_key_state->public_key, public_key_state->public_key_len);

    /* Perform the calculation */
    err = (*(private_key_state->calculate))
        (private_key_state, public_key_state, shared_key);

    /* If the public key was null, then we need to set the shared key
       to null and replace any error we got from the back end with "none" */
    noise_cmove_zero(shared_key, shared_key_len, is_null);
    err &= (is_null - 1);
    return err;
}

/**
 * \brief Copies the keys from one DHState object to another.
 *
 * \param state The DHState to copy into.
 * \param from The DHState to copy from.
 *
 * \return NOISE_ERROR_NONE on success.
 * \return NOISE_ERROR_INVALID_PARAM if \a state or \a from is NULL.
 * \return NOISE_ERROR_NOT_APPLICABLE if \a from does not have the same
 * key type identifier as \a state.
 */
int noise_dhstate_copy(NoiseDHState *state, const NoiseDHState *from)
{
    int err;

    /* Validate the parameters */
    if (!state || !from)
        return NOISE_ERROR_INVALID_PARAM;
    if (state->dh_id != from->dh_id)
        return NOISE_ERROR_NOT_APPLICABLE;
    if (state == from)
        return NOISE_ERROR_NONE;

    /* Copy the key information across */
    err = (*(state->copy))(state, from, 0);
    if (err != NOISE_ERROR_NONE)
        return err;
    state->key_type = from->key_type;
    return err;
}

/**
 * \brief Formats the public key fingerprint for the key within a DHState.
 *
 * \param state The DHState object.
 * \param fingerprint_type The type of fingerprint to format,
 * NOISE_FINGERPRINT_BASIC or NOISE_FINGERPRINT_FULL.
 * \param buffer The buffer to write the fingerprint string to, including a
 * terminating NUL.
 * \param len The length of \a buffer in bytes.
 *
 * \return NOISE_ERROR_NONE on success.
 * \return NOISE_ERROR_INVALID_PARAM if \a state or \a buffer is NULL.
 * \return NOISE_ERROR_INVALID_PARAM if \a fingerprint_type is not a
 * supported fingerprint type.
 * \return NOISE_ERROR_INVALID_LENGTH if \a len is not large enough to
 * hold the entire fingerprint string.
 * \return NOISE_ERROR_INVALID_STATE if a public key has not been set
 * on \a state yet.
 *
 * Fingerprints are created by hashing the public key with SHA256 and
 * then formatting the value in hexadecimal with bytes separated by colons.
 * If the \a fingerprint_type is NOISE_FINGERPRINT_BASIC, then the SHA256
 * hash value is truncated to the first 16 bytes.  If the type is
 * NOISE_FINGERPRINT_FULL, then the entire 32 byte hash value is formatted.
 */
int noise_dhstate_format_fingerprint
    (const NoiseDHState *state, int fingerprint_type, char *buffer, size_t len)
{
    /* Validate the parameters */
    if (!buffer)
        return NOISE_ERROR_INVALID_PARAM;
    if (!len)
        return NOISE_ERROR_INVALID_LENGTH;
    *buffer = '\0'; /* In case we bail out with an error later */
    if (!state)
        return NOISE_ERROR_INVALID_PARAM;
    if (state->key_type == NOISE_KEY_TYPE_NO_KEY)
        return NOISE_ERROR_INVALID_STATE;

    /* Format the fingerprint */
    return noise_format_fingerprint
        (fingerprint_type, buffer, len,
         state->public_key, state->public_key_len);
}

/**
 * \brief Gets the role that a DHState object will play in a handshake.
 *
 * \param state The DHState object.
 *
 * \return The role, NOISE_ROLE_INITIATOR or NOISE_ROLE_RESPONDER, or zero
 * if the role has not been set yet.
 *
 * \sa noise_dhstate_set_role()
 */
int noise_dhstate_get_role(const NoiseDHState *state)
{
    return state ? state->role : 0;
}

/**
 * \brief Sets the role that a DHState object will play in a handshake.
 *
 * \param state The DHState object.
 * \param role The role, NOISE_ROLE_INITIATOR or NOISE_ROLE_RESPONDER, or zero
 * if the role is unspecified.
 *
 * \return NOISE_ERROR_NONE on success.
 * \return NOISE_ERROR_INVALID_PARAM if \a state is NULL.
 * \return NOISE_ERROR_INVALID_PARAM if \a role is not one of
 * NOISE_ROLE_INITIATOR, NOISE_ROLE_RESPONDER, or zero.
 *
 * This function is intended for use with algorithms that have a different
 * method for calculating public keys and shared secrets for the two parties
 * in a communication.  An example is the post-quantum SIDH algorithm where
 * "Alice" and "Bob" differ in the calculations they perform.
 *
 * To assist with supporting such algorithms, the HandshakeState labels
 * DHState objects as either initiator or responder depending upon who
 * owns that specific key.  The algorithm-specific back end can then use
 * the role information to determine which object it wants to treat as
 * "Alice" and which object should be treated as "Bob".
 *
 * \sa noise_dhstate_get_role()
 */
int noise_dhstate_set_role(NoiseDHState *state, int role)
{
    if (!state)
        return NOISE_ERROR_INVALID_PARAM;
    if (role != NOISE_ROLE_INITIATOR && role != NOISE_ROLE_RESPONDER && role)
        return NOISE_ERROR_INVALID_PARAM;
    state->role = role;
    if (state->change_role)
        (*(state->change_role))(state);
    return NOISE_ERROR_NONE;
}

/**@}*/


text:
using NMF.Collections.Generic;
using NMF.Collections.ObjectModel;
using NMF.Expressions;
using NMF.Expressions.Linq;
using NMF.Models;
using NMF.Models.Collections;
using NMF.Models.Expressions;
using NMF.Models.Meta;
using NMF.Models.Repository;
using NMF.Serialization;
using NMF.Utilities;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using TTC2017.SmartGrids.CIM;
using TTC2017.SmartGrids.CIM.IEC61968.Common;
using TTC2017.SmartGrids.CIM.IEC61970.Contingency;
using TTC2017.SmartGrids.CIM.IEC61970.Core;
using TTC2017.SmartGrids.CIM.IEC61970.Generation.Production;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.EnergyScheduling;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.Financial;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfERPSupport;
using TTC2017.SmartGrids.CIM.IEC61970.LoadModel;
using TTC2017.SmartGrids.CIM.IEC61970.Meas;
using TTC2017.SmartGrids.CIM.IEC61970.Wires;

namespace TTC2017.SmartGrids.CIM.IEC61970.Informative.MarketOperations
{

    public class SecurityConstraintSumConstraintTermsCollection : ObservableOppositeOrderedSet<ISecurityConstraintSum, IConstraintTerm>
    {

        public SecurityConstraintSumConstraintTermsCollection(ISecurityConstraintSum parent) :
                base(parent)
        {
        }

        private void OnItemDeleted(object sender, System.EventArgs e)
        {
            this.Remove(((IConstraintTerm)(sender)));
        }

        protected override void SetOpposite(IConstraintTerm item, ISecurityConstraintSum parent)
        {
            if ((parent != null))
            {
                item.Deleted += this.OnItemDeleted;
                item.SecurityConstraintSum = parent;
            }
            else
            {
                item.Deleted -= this.OnItemDeleted;
                if ((item.SecurityConstraintSum == this.Parent))
                {
                    item.SecurityConstraintSum = parent;
                }
            }
        }
    }
}


text:
This recipe is to build the complete set of packages to run and develop with QT5 and the Webengine.
Make sure you run them in the order outlined below.

### 1 Build core QT5 framework, Webengine, cross compilation tools:

 * ./buildall.sh cross
 * extract: libqt5all.deb, libqt5all-dev.deb, libqt5all-cross.deb, libqt5webengine.deb, liqt5webengine-dev.deb

### 2 Build QT5 framework with debug symbols:

 * ./qt5-build purge --yes
 * ./qt5-build compile qt5 cross debug --yes
 * ./qt5-build package qt5
 * extract: libqt5all-debug

```
 FIXME: debug build fails with message below.

parser.o tools/qdatetimeparser.cpp
tools/qdatetimeparser.cpp: In function 'QString unquote(const QStringRef&)':
tools/qdatetimeparser.cpp:342:1: internal compiler error: in push_minipool_fix, at config/arm/arm.c:14059
 }
  ^
  Please submit a full bug report,
```

### 3 Build QT5 RPi native compilation tools:

 * ./qt5-build purge --yes
 * ./qt5-build compile qt5 native release --core-tools --yes
 * ./qt5-build package native-tools
 * extract: libqt5all-native.deb


text:
package com.mentatlabs.nsa
package scalac
package dsl
package experimental

trait ScalacYClosureDSL
    extends ScalacExperimentalDSL {

  object Yclosure {
    val unary_- = new {
      def -(e: elim.type) = options.ScalacYClosureElim
    }
  }
}


text:
print("\27[31m SDL crushes with DCHECK. Some tests are commented. After resolving uncomment tests!\27[0m")
---------------------------------------------------------------------------------------------
-- CRQ: APPLINK-25085: [GENIVI] UI interface: SDL behavior in case HMI does not respond to
--                     IsReady_request or respond with "available" = false
--
-- Requirement(s): APPLINK-25064:[RegisterAppInterface] SDL behavior in case HMI does NOT
--                               respond to IsReady request
--                 APPLINK-25099:[UI Interface] HMI does NOT respond to IsReady and mobile
--                                app sends RPC that must be splitted
--                               => only checked RPCs: GetSupportedLanguages
--                                                     GetLanguage
--                                                     GetCapabilities
--                 APPLINK-25299:[HMI_API] UI.IsReady
---------------------------------------------------------------------------------------------

TestedInterface = "UI"
Test = require('user_modules/IsReady_Template/ATF_Interface_IsReady_missing_RAI_Template')

return Test


text:
module Houston
  module Slack
    module RtmEvent

      def react(emoji)
        message.add_reaction(emoji)
      end

      def responding
        channel.typing
      end

    end
  end
end


text:
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */

namespace UnitTests\BeanstalkTests\CommandTests\WatchTest;

use PHPUnit_Framework_TestCase;
use Beanstalk\Command\WatchTube;

class TestCases extends PHPUnit_Framework_TestCase
{

    public function testGetCommand()
    {
        $command = new WatchTube('tube-name');
        $this->assertEquals('watch tube-name', $command->getCommand());

        $command = new WatchTube('tube3r');
        $this->assertEquals('watch tube3r', $command->getCommand());
    }

    public function testCannotSetTubeNameLongerThan200Bytes()
    {
        $this->setExpectedException('\Beanstalk\Exception', '', \Beanstalk\Exception::TUBE_NAME_TOO_LONG);

        $tube = 'a-long-name-for-a-tube-that-is-completely-ridiculous-and-probably-would-not-happen-in-reality-but-we-have-to-test-for-it-anyways-just-in-case-someone-gets-the-crazy-idea-to-create-a-tube-name-like-this';
        $command = new WatchTube($tube);
    }

    public function testHasNoData()
    {
        $command = new WatchTube('tube');
        $this->assertFalse($command->getData());
    }

    public function testReturnsNoData()
    {
        $command = new WatchTube('tube');
        $this->assertFalse($command->returnsData());
    }

    public function testParseResponseOnSuccess()
    {
        $command = new WatchTube('tube');
        $this->assertEquals(2, $command->parseResponse('WATCHING 2'));

        $command = new WatchTube('tube2-name');
        $this->assertEquals(3, $command->parseResponse('WATCHING 3'));
    }

    public function testParseResponseOnSuccessReturnInteger()
    {
        $command = new WatchTube('tube');
        $this->assertInternalType('integer', $command->parseResponse('WATCHING 3'));
    }

    public function testParseResponseOnOtherErrors()
    {
        $this->setExpectedException('\Beanstalk\Exception', '', \Beanstalk\Exception::UNKNOWN);

        $command = new WatchTube('tube');
        $command->parseResponse('This is wack');
    }

}


text:
@implementation NSObject (MJCoding)

- (void)encode:(NSCoder *)encoder
{
    NSArray *ignoredCodingPropertyNames = [[self class] totalIgnoredCodingPropertyNames];

    [[self class] enumeratePropertiesWithBlock:^(MJProperty *property, BOOL *stop) {
        // 检测是否被忽略
        if ([ignoredCodingPropertyNames containsObject:property.name]) return;

        id value = [property valueFromObject:self];
        if (value == nil) return;
        [encoder encodeObject:value forKey:property.name];
    }];
}

- (void)decode:(NSCoder *)decoder
{
    NSArray *ignoredCodingPropertyNames = [[self class] totalIgnoredCodingPropertyNames];

    [[self class] enumeratePropertiesWithBlock:^(MJProperty *property, BOOL *stop) {
        // 检测是否被忽略
        if ([ignoredCodingPropertyNames containsObject:property.name]) return;

        id value = [decoder decodeObjectForKey:property.name];
        if (value == nil) return;
        [property setValue:value forObject:self];
    }];
}
@end


text:
package OpenXPKI::Server::Workflow::Validator::KeyGenerationParams;

use strict;
use warnings;
use base qw( OpenXPKI::Server::Workflow::Validator );
use Data::Dumper;
use OpenXPKI::Debug;
use OpenXPKI::Server::Context qw( CTX );
use Workflow::Exception qw( validation_error configuration_error );

sub _preset_args {
    return [ qw(cert_profile key_alg key_gen_params enc_alg) ];
}

sub _validate {

    ##! 1: 'start'
    my ( $self, $wf, $cert_profile, $key_alg, $key_gen_params, $enc_alg ) = @_;

    if (!$key_alg) {
        ##! 8: 'skip - no algorithm'
        return 1;
    }

    # might be serialized
    if (!ref $key_gen_params) {
        $key_gen_params = OpenXPKI::Serialization::Simple->new()->deserialize( $key_gen_params );
    }

    my $key_params = {};

    if ($key_alg eq 'rsa') {
        $key_params = { key_length =>  $key_gen_params->{KEY_LENGTH} };
    } elsif ($key_alg eq 'dsa') {
        $key_params = { key_length =>  $key_gen_params->{KEY_LENGTH} };
    } elsif ($key_alg eq 'ec') {
        $key_params = { key_length =>  '_any', curve_name => $key_gen_params->{CURVE_NAME} };
        # not yet defined
    } else {
        validation_error('I18N_OPENXPKI_UI_VALIDATOR_KEY_PARAM_ALGO_NOT_SUPPORTED');
    }

    ##! 16: "Alg: $key_alg"
    ##! 16: 'Params ' . Dumper $key_params

    # get the list of allowed algorithms from the config
    my $algs = CTX('api2')->get_key_algs( profile => $cert_profile, showall => 1 );

    ##! 32: 'Alg expected ' . Dumper $algs

    if (!grep(/\A$key_alg\z/, @{$algs})) {
        ##! 8: "KeyParam validation failed on algo $key_alg"
        CTX('log')->application()->error("KeyParam validation failed on algo $key_alg");

        validation_error('I18N_OPENXPKI_UI_VALIDATOR_KEY_PARAM_ALGO_NOT_ALLOWED');
    }

    my $params = CTX('api2')->get_key_params( profile => $cert_profile, alg => $key_alg, showall => 1 );

    ##! 32: 'Params expected ' . Dumper $params

    foreach my $param (keys %{$params}) {
        my $val = $key_params->{$param} || '';

        if ($val eq '_any') { next; }

        my @expect = @{$params->{$param}};
        ##! 32: "Validate param $param, $val, " . Dumper \@expect
        if (!grep(/$val/, @expect)) {
            ##! 32: 'Failed on ' . $val
            CTX('log')->application()->error("KeyParam validation failed on $param with value $val");

            validation_error("I18N_OPENXPKI_UI_VALIDATOR_KEY_PARAM_PARAM_NOT_ALLOWED ($param)");
        }
    }

    my $enc_algs = CTX('api2')->get_key_enc( profile => $cert_profile, showall => 1 );
    if ($enc_alg && !grep(/\A$enc_alg\z/, @{$enc_algs})) {
        ##! 32: 'Failed on ' . $enc_alg
        CTX('log')->application()->error("KeyParam validation failed on enc_alg with value $enc_alg");

        validation_error("I18N_OPENXPKI_UI_VALIDATOR_KEY_PARAM_PARAM_NOT_ALLOWED (enc_alg)");
    }

    ##! 1: 'Validation succeeded'
    CTX('log')->application()->debug("KeyParam validation succeeded");

    return 1;
}

1;

__END__

=head1 NAME

OpenXPKI::Server::Workflow::Validator::KeyGenerationParams

=head1 Description

Check if the key specification passed fits the requirements of the profile.

=head1 Configuration

  global_validate_key_param:
      class: OpenXPKI::Server::Workflow::Validator::KeyGenerationParams
      arg:
       - $cert_profile
       - $key_alg
       - $key_gen_params
       - $enc_alg

=head2 Arguments

=over

=item cert_profile

Name of the certificate profile

=item key_alg

The selected key algorithm

=item key_gen_params

Hash holding the key generation params, must fit the list given in the
profile definition.

=item enc_alg

The encryption algorithm, can be emtpy.

=back


text:
// ConcurrentQueueTest.cs
//
// Copyright (c) 2008 Jérémie "Garuma" Laval
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//

using System;
using System.Collections.Concurrent;
using System.Text;
using System.Threading;
using NUnit.Framework;
using Tests.Helpers;

namespace Tests.SystemTests.CollectionsTests.ConcurrentTests
{
    [TestFixture]
    public class ConcurrentQueueTests
    {
        public static ConcurrentQueue<int> Setup()
        {
            var queue = new ConcurrentQueue<int>();
            for (var i = 0; i < 10; i++)
            {
                queue.Enqueue(i);
            }

            return queue;
        }

        [Test]
        public void CountTestCase()
        {
            var queue = Setup();
            Assert.AreEqual(10, queue.Count, "#1");
            queue.TryPeek(out _);
            queue.TryDequeue(out _);
            queue.TryDequeue(out _);
            Assert.AreEqual(8, queue.Count, "#2");
        }

        [Test]
        public void EnumerateTestCase()
        {
            var queue = Setup();
            var s = string.Empty;
            var builder = new StringBuilder();
            builder.Append(s);
            foreach (var item in queue)
            {
                builder.Append(item);
            }

            s = builder.ToString();
            Assert.AreEqual("0123456789", s, "#1 : " + s);
        }

        [Test]
        [Category("LongRunning")]
        public void StressDequeueTestCase()
        {
            CollectionStressTestHelper.RemoveStressTest(new ConcurrentQueue<int>(), CheckOrderingType.InOrder);
        }

        [Test]
        [Category("LongRunning")]
        public void StressEnqueueTestCase()
        {
            CollectionStressTestHelper.AddStressTest(new ConcurrentQueue<int>());
        }

        [Test]
        [Category("LongRunning")]
        public void StressTryPeekTestCase()
        {
            ParallelTestHelper.Repeat
            (
                delegate
                {
                    var queue = new ConcurrentQueue<object>();
                    queue.Enqueue(new object());

                    const int threads = 10;
                    var threadCounter = 0;
                    var success = true;

                    ParallelTestHelper.ParallelStressTest
                    (
                        () =>
                        {
                            var threadId = Interlocked.Increment(ref threadCounter);
                            object temp;
                            if (threadId < threads)
                            {
                                while (queue.TryPeek(out temp))
                                {
                                    success &= temp != null;
                                }
                            }
                            else
                            {
                                queue.TryDequeue(out temp);
                            }
                        }, threads
                    );

                    Assert.IsTrue(success, "TryPeek returned unexpected null value.");
                }, 10
            );
        }

        [Test]
        public void ToArrayTest()
        {
            var queue = Setup();
            var array = queue.ToArray();
            var s = string.Empty;
            var builder = new StringBuilder();
            builder.Append(s);
            foreach (var i in array)
            {
                builder.Append(i);
            }

            s = builder.ToString();
            Assert.AreEqual("0123456789", s, "#1 : " + s);
            queue.CopyTo(array, 0);
            s = string.Empty;
            builder = new StringBuilder();
            builder.Append(s);
            foreach (var i in array)
            {
                builder.Append(i);
            }

            s = builder.ToString();
            Assert.AreEqual("0123456789", s, "#2 : " + s);
        }

        [Test]
        public void ToExistingArrayIndexOverflow()
        {
            var queue = Setup();
            Assert.Throws<ArgumentException>(() => queue.CopyTo(new int[3], 4));
        }

        [Test]
        public void ToExistingArrayNull()
        {
            var queue = Setup();
            Assert.Throws<ArgumentNullException>(() => queue.CopyTo(null, 0));
        }

        [Test]
        public void ToExistingArrayOutOfRange()
        {
            var queue = Setup();
            Assert.Throws<ArgumentOutOfRangeException>(() => queue.CopyTo(new int[3], -1));
        }

        [Test]
        public void ToExistingArrayOverflow()
        {
            var queue = Setup();
            Assert.Throws<ArgumentException>(() => queue.CopyTo(new int[3], 0));
        }

        [Test]
        public void TryDequeueEmptyTestCase()
        {
            var queue = new ConcurrentQueue<int>();
            queue.Enqueue(1);
            Assert.IsTrue(queue.TryDequeue(out _), "#1");
            Assert.IsFalse(queue.TryDequeue(out _), "#2");
            Assert.IsTrue(queue.IsEmpty, "#3");
        }

        [Test]
        public void TryDequeueReferenceTest()
        {
            var queue = new ConcurrentQueue<object>();
            var weakReference = AddObjectWeakReference(queue);
            DequeueIgnore(queue);
            ThreadEx.MemoryBarrier();
            GC.Collect();
            GC.WaitForPendingFinalizers();
            ThreadEx.MemoryBarrier();
            Assert.IsFalse(weakReference.IsAlive);
        }

        [Test]
        public void TryDequeueTestCase()
        {
            var queue = Setup();
            queue.TryPeek(out var value);
            Assert.AreEqual(0, value, "#1");
            Assert.IsTrue(queue.TryDequeue(out _), "#2");
            Assert.IsTrue(queue.TryDequeue(out value), "#3");
            Assert.AreEqual(1, value, "#4");
        }

        [Test]
        public void TryPeekTestCase()
        {
            var queue = Setup();
            queue.TryPeek(out var value);
            Assert.AreEqual(0, value, $"#1 : {value}");
            queue.TryDequeue(out value);
            Assert.AreEqual(0, value, $"#2 : {value}");
            queue.TryDequeue(out value);
            Assert.AreEqual(1, value, $"#3 : {value}");
            queue.TryPeek(out value);
            Assert.AreEqual(2, value, $"#4 : {value}");
            queue.TryPeek(out value);
            Assert.AreEqual(2, value, $"#5 : {value}");
        }

        private static WeakReference AddObjectWeakReference(ConcurrentQueue<object> queue)
        {
            var obj = new object();
            var weakReference = CreateWeakReference(obj);
            queue.Enqueue(obj);
            return weakReference;
        }

        private static WeakReference CreateWeakReference(object obj)
        {
            return new WeakReference(obj);
        }

        private static void DequeueIgnore(ConcurrentQueue<object> queue)
        {
            queue.TryDequeue(out _);
        }
    }
}


text:
module.exports.GATTIP = require('./gattip').GATTIP;
module.exports.C = require('./lib/constants').C;


text:
package mccity.heroes.skills.turret;

import com.herocraftonline.heroes.characters.Hero;
import com.herocraftonline.heroes.characters.skill.SkillConfigManager;
import com.herocraftonline.heroes.util.Messaging;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;

public class TurretManager implements Runnable {

    private final TurretMap turretMap;

    private final SkillTurret skill;
    private final TurretStorage turretStorage;

    private final PlayersAroundChecker playerChecker;

    private static final String PERM_BYPASS_PROTECTION = "skillturret.bypassprotection";

    public TurretManager(SkillTurret skill) {
        this.skill = skill;
        turretStorage = new TurretStorage(skill.plugin.getDataFolder());
        turretMap = new TurretMap();
        playerChecker = new PlayersAroundChecker(skill.plugin, 47);
    }

    private boolean isReplaceOldestOnLimitFor(Hero hero) {
        return SkillConfigManager.getUseSetting(hero, skill, "replace-oldest-on-limit", false);
    }

    public boolean canAddFor(Hero hero) {
        List<Turret> playerTurrets = turretMap.getByPlayer(hero.getPlayer());
        return (isReplaceOldestOnLimitFor(hero) || playerTurrets.size() < skill.maxTurretsFor(hero));
    }

    public int getTotalTurrets(Hero hero) {
        return turretMap.getByPlayer(hero.getPlayer()).size();
    }

    public boolean addFor(Hero hero, Block base) {
        List<Turret> playerTurrets = turretMap.getByPlayer(hero.getPlayer());

        boolean replace = false;
        if (playerTurrets.size() >= skill.maxTurretsFor(hero)) {
            if (isReplaceOldestOnLimitFor(hero)) {
                // remove oldest
                turretMap.removeByBase(playerTurrets.get(0).getBaseBlock());
                replace = true;
            } else {
                return false;
            }
        }

        turretMap.add(new Turret(hero, base, skill));
        if (replace) {
            Messaging.send(hero.getPlayer(), Messages.turretReplaced);
        }
        return true;
    }

    /**
     * @return cancel event ?
     */
    public boolean onDispenserDestroyed(Block dispenser, Player destroyer) {
        Turret turret = turretMap.getAt(dispenser);
        if (turret == null) return false;

        boolean isOwner = turret.getOwnerName().equals(destroyer.getName());

        if (isOwner || hasAccess(destroyer, turret)) {
            Turret destroyed = turretMap.removeByBase(dispenser);
            if (isOwner) {
                Messaging.send(destroyer, Messages.yourTurretDestroyed);
            } else {
                Messaging.send(destroyer, Messages.youDestroyOtherPlayerTurret, destroyed.getOwnerName());
                Utils.safeSend(destroyed.getOwnerName(), Messages.yourTurretDestroyedBy, destroyer.getName());
            }
            return false;
        } else {
            Messaging.send(destroyer, Messages.turretProtected);
            return true;
        }
    }

    /**
     * @return cancel event ?
     */
    public boolean onDispenserOpen(Block dispenser, Player player) {
        Turret turret = turretMap.getAt(dispenser);
        if (turret == null) return false;

        boolean isOwner = turret.getOwnerName().equals(player.getName());

        if (isOwner || hasAccess(player, turret)) {
            return false;
        } else {
            Messaging.send(player, Messages.turretProtected);
            return true;
        }
    }

    private boolean hasAccess(Player player, Turret turret) {
        return !turret.isProtected() || player.isOp() || player.hasPermission(PERM_BYPASS_PROTECTION);
    }

    public void removeAll(Hero hero) {
        turretMap.removeByPlayer(hero.getPlayer());
    }

    @Override
    public void run() {
        if (turretMap.size() == 0) return;
        List<Turret> forRemove = new ArrayList<Turret>();

        for (Turret curTurret : turretMap.getTurrets()) {
            if (curTurret.isAlive()) {
                if (curTurret.isChunkLoaded() && playerChecker.isAnyPlayerAround(curTurret.getBaseBlock().getLocation(), 60)) {
                    if (curTurret.checkBaseBlock()) {
                        curTurret.AITick();
                    } else {
                        forRemove.add(curTurret);
                    }
                }
            } else {
                forRemove.add(curTurret);
            }
        }

        for (Turret rTurret : forRemove) {
            turretMap.removeByBase(rTurret.getBaseBlock());
            Utils.safeSend(rTurret.getOwnerName(), Messages.yourTurretLostMagicPower);
        }
    }

    public void loadAll() {
        List<Turret> loaded = turretStorage.load();
        Utils.log(loaded.size() + " turrets loaded", Level.INFO);
        turretMap.setTurrets(loaded);
    }

    public void saveAll() {
        turretStorage.save(turretMap.getTurrets());
    }

    public void onPlayerJoin(Player player) {
        List<Turret> playerTurrets = turretMap.getByPlayer(player);
        if (!playerTurrets.isEmpty()) {
            Hero owner = Utils.getHero(player);
            for (Turret playerTurret : playerTurrets) {
                playerTurret.ownerJoined(owner);
            }
        }
    }

    public void onPlayerQuit(Player player) {
        List<Turret> playerTurrets = turretMap.getByPlayer(player);
        for (Turret playerTurret : playerTurrets) {
            playerTurret.ownerQuited();
        }
    }
}


text:
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Collections.Generic;
using Teaching.Skills.Core;

namespace Teaching.Skills.Models
{
    public class Indicator : Base
    {
        public Indicator()
        {
            Questions = new HashSet<Question>();
        }

        [JsonProperty("Description")]
        public string Description { get; set; }

        [JsonProperty("Questions")]
        public HashSet<Question> Questions { get; set; }
    }
}


text:
import { convUnit } from '../helpers';

export default border => {
    return [
        {
            prop: 'border-width',
            value: convUnit(border.thickness)
        },
        {
            prop: 'border-style',
            value: 'solid'
        },
        {
            prop: 'border-color',
            value: border.color.value
        }
    ];
};


text:
title: Albert Young, MD, MAS
author: albert_young
layout: author-bio
jobtitle: Medical Resident
bio: Henry Ford Health System
type: alumn
excerpt: "Albert was a 4th year Research Fellow and UCSF medical student interested in dermatology and machine learning in medicine. In the Keiser Lab he pursued a Yearlo"
header:
  teaser: /assets/images/people/bio-young.jpg
papers:
    - title: Stress testing reveals gaps in clinic readiness of image-based diagnostic artificial intelligence models
      excerpt: Young AT, Fernandez K, Pfau J, Reddy R, Cao NA, von Franque MY, Johal A, Wu BV, Wu RR, Chen JY, Fadadu RP, Vasquez JA, Tam A, Keiser MJ, Wei ML. __NPJ Digit Med__. 2021 Jan 21.
      link: "https://doi.org/10.1038/s41746-020-00380-6"

    - title: Artificial Intelligence in Dermatology- A Primer
      excerpt: Young AT, Xiong M, Pfau J, Keiser MJ, Wei ML. __J Invest Dermatol__. 2020 Aug.
      link: "https://doi.org/10.1016/j.jid.2020.02.026"

    - title: Robust Semantic Interpretability- Revisiting Concept Activation Vectors
      excerpt: Pfau J, Young AT, Wei J, Wei ML, Keiser MJ. __arXiv - ICML - WHI__. 2020 Jul 17.
      link: ""

    - title: Global Saliency- Aggregating Saliency Maps to Assess Dataset Artefact Bias
      excerpt: Pfau J, Young AT, Wei ML, Keiser MJ. __arXiv - NeurIPS ML4H__. 2019 Oct 16.
      link: ""

---


text:
package org.worshipsongs.helper;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Build;
import android.util.Log;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.worshipsongs.activity.NavigationDrawerActivity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @Author : Madasamy
 * @Version : 1.0
 */
public class DatabaseHelper extends SQLiteOpenHelper
{
    private static final int DATA_BASE_VERSION = 3;
    public static String dbPath = "";

    public static String dbName = "songs.sqlite";
    private SQLiteDatabase database;
    private final Context context;

    /**
     * Constructor
     * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
     *
     * @param context
     */
    public DatabaseHelper(Context context)
    {
        super(context, dbName, null, DATA_BASE_VERSION);
        this.context = context;
        this.dbPath = "/data/data/" + context.getApplicationContext().getPackageName() + "/databases/";
    }

    /**
     * Creates a empty database on the system and rewrites it with your own database.
     */
    public void createDataBase(String databasePath, boolean dropDatabase) throws IOException
    {
        Log.d(this.getClass().getName(), "Preparing to create database");
        if (dropDatabase) {
            context.deleteDatabase(dbName);
        }
        boolean dbExist = checkDataBase();
        if (dbExist) {
            //do nothing - database already exist
            Log.d(this.getClass().getName(), "Database " + dbName + " already exists");
        } else {
            Log.d(this.getClass().getName(), "Database " + dbName + " is not exists");
            //By calling this method and empty database will be created into the default system path
            //of your application so we are gonna be able to overwrite that database with our database.
            this.getReadableDatabase();
            this.close();
            try {
                copyDataBase(databasePath);
            } catch (Exception ex) {
                Log.e(this.getClass().getName(), "Error occurred while copy database " + ex);
            }
        }
    }

    /**
     * Check if the database already exist to avoid re-copying the file each time you open the application.
     *
     * @return true if it exists, false if it doesn't
     */
    public boolean checkDataBase()
    {
        try {
            return new File(dbPath, dbName).exists();
        } catch (Exception ex) {
            Log.e(this.getClass().getName(), "Error occurred while checking database" + ex);
            return false;
        }
    }

    /**
     * Copies your database from your local assets-folder to the just created empty database in the
     * system folder, from where it can be accessed and handled.
     * This is done by transfering bytestream.
     */
    public void copyDataBase(String databasePath) throws IOException
    {
        InputStream inputStream = null;
        // Open local db as the input stream
        if (StringUtils.isNotBlank(databasePath)) {
            inputStream = new FileInputStream(new File(databasePath));
        } else {
            inputStream = context.getAssets().open(dbName);
        }
        String outFileName = dbPath + dbName;
        OutputStream outputStream = new FileOutputStream(outFileName);
        // transfer bytes from the input file to the output file
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, length);
        }
        // Close the streams
        outputStream.flush();
        outputStream.close();
        inputStream.close();
    }

    public SQLiteDatabase openDataBase() throws SQLException
    {
        //Open the database
        String myPath = dbPath + dbName;
        database = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
        return database;
    }

    @Override
    public void onOpen(SQLiteDatabase db) {
        super.onOpen(db);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            db.disableWriteAheadLogging();
        }
    }

    @Override
    public synchronized void close()
    {
        if (database != null) {
            database.close();
        }
        SQLiteDatabase.releaseMemory();
        super.close();
    }

    public SQLiteDatabase getDatabase()
    {
        return database;
    }

    @Override
    public void onCreate(SQLiteDatabase db)
    {
        //Do nothing its read only database
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
        //Do nothing its read only database
    }

}