text:
package org.apache.commons.lang3;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.hamcrest.core.IsNull.nullValue;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.DynamicTest.dynamicTest;

import java.lang.reflect.UndeclaredThrowableException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.apache.commons.lang3.Functions.FailableConsumer;
import org.apache.commons.lang3.Functions.FailablePredicate;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestFactory;
import org.junit.jupiter.api.function.Executable;
import org.xml.sax.SAXException;

public class StreamsTest extends AbstractLangTest {

    @Test
    public void testSimpleStreamMap() {
        final List<String> input = Arrays.asList("1", "2", "3", "4", "5", "6");
        final List<Integer> output = Functions.stream(input).map(Integer::valueOf).collect(Collectors.toList());
        assertEquals(6, output.size());
        for (int i = 0;  i < 6;  i++) {
            assertEquals(i+1, output.get(i).intValue());
        }
    }

    @Test
    public void testSimpleStreamMapFailing() {
        final List<String> input = Arrays.asList("1", "2", "3", "4 ", "5", "6");
        final Executable testMethod = () -> Functions.stream(input).map(Integer::valueOf).collect(Collectors.toList());
        final NumberFormatException thrown = assertThrows(NumberFormatException.class, testMethod);
        assertEquals("For input string: \"4 \"", thrown.getMessage());
    }

    @Test
    public void testSimpleStreamForEach() {
        final List<String> input = Arrays.asList("1", "2", "3", "4", "5", "6");
        final List<Integer> output = new ArrayList<>();
        Functions.stream(input).forEach(s -> output.add(Integer.valueOf(s)));
        assertEquals(6, output.size());
        for (int i = 0;  i < 6;  i++) {
            assertEquals(i+1, output.get(i).intValue());
        }
    }

    @Test
    public void testToArray() {
        final String[] array = Arrays.asList("2", "3", "1").stream().collect(Streams.toArray(String.class));
        assertNotNull(array);
        assertEquals(3, array.length);
        assertEquals("2", array[0]);
        assertEquals("3", array[1]);
        assertEquals("1", array[2]);
    }

    protected <T extends Throwable> FailableConsumer<String, T> asIntConsumer(final T pThrowable) {
        return s -> {
            final int i = Integer.parseInt(s);
            if (i == 4) {
                throw pThrowable;
            }
        };
    }

    @TestFactory
    public Stream<DynamicTest> simpleStreamForEachFailing() {
        final List<String> input = Arrays.asList("1", "2", "3", "4", "5", "6");

        return Stream.of(

                dynamicTest("IllegalArgumentException", () -> {
                    final IllegalArgumentException ise = new IllegalArgumentException();
                    final Executable testMethod = () -> Functions.stream(input)
                            .forEach(asIntConsumer(ise));
                    final IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, testMethod);
                    assertThat(thrown.getMessage(), is(nullValue()));
                }),

                dynamicTest("OutOfMemoryError", () -> {
                    final OutOfMemoryError oome = new OutOfMemoryError();
                    final Executable oomeTestMethod = () -> Functions.stream(input)
                            .forEach(asIntConsumer(oome));
                    final OutOfMemoryError oomeThrown = assertThrows(OutOfMemoryError.class, oomeTestMethod);
                    assertThat(oomeThrown.getMessage(), is(nullValue()));
                }),

                dynamicTest("SAXException", () -> {
                    final SAXException se = new SAXException();
                    final Executable seTestMethod = () -> Functions.stream(input)
                            .forEach(asIntConsumer(se));
                    final UndeclaredThrowableException seThrown = assertThrows(UndeclaredThrowableException.class, seTestMethod);
                    assertAll(
                            () -> assertThat(seThrown.getMessage(), is(nullValue())),
                            () -> assertThat(seThrown.getCause(), is(equalTo(se)))
                    );
                })
        );
    }

    @Test
    public void testSimpleStreamFilter() {
        final List<String> input = Arrays.asList("1", "2", "3", "4", "5", "6");
        final List<Integer> output = Functions.stream(input)
                .map(Integer::valueOf)
                .filter(i -> (i.intValue() %2 == 0))
                .collect(Collectors.toList());
        assertEvenNumbers(output);
    }

    private void assertEvenNumbers(final List<Integer> output) {
        assertEquals(3, output.size());
        for (int i = 0;  i < 3;  i++) {
            assertEquals((i+1)*2, output.get(i).intValue());
        }
    }

    protected <T extends Throwable> FailablePredicate<Integer, T> asIntPredicate(final T pThrowable) {
        return i -> {
            if (i.intValue() == 5 && pThrowable != null) {
                throw pThrowable;
            }
            return i%2==0;
        };
    }

    @TestFactory
    public Stream<DynamicTest> simpleStreamFilterFailing() {
        final List<String> input = Arrays.asList("1", "2", "3", "4", "5", "6");
        final List<Integer> output = Functions.stream(input)
                .map(Integer::valueOf)
                .filter(asIntPredicate(null))
                .collect(Collectors.toList());
        assertEvenNumbers(output);

        return Stream.of(

                dynamicTest("IllegalArgumentException", () -> {
                    final IllegalArgumentException iae = new IllegalArgumentException("Invalid argument: " + 5);
                    final Executable testMethod = () -> Functions.stream(input)
                            .map(Integer::valueOf)
                            .filter(asIntPredicate(iae))
                            .collect(Collectors.toList());
                    final IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, testMethod);
                    assertThat(thrown.getMessage(), is(equalTo("Invalid argument: " + 5)));
                }),

                dynamicTest("OutOfMemoryError", () -> {
                    final OutOfMemoryError oome = new OutOfMemoryError();
                    final Executable testMethod = () -> Functions.stream(input)
                            .map(Integer::valueOf)
                            .filter(asIntPredicate(oome))
                            .collect(Collectors.toList());
                    final OutOfMemoryError thrown = assertThrows(OutOfMemoryError.class, testMethod);
                    assertThat(thrown.getMessage(), is(nullValue()));
                }),

                dynamicTest("SAXException", () -> {
                    final SAXException se = new SAXException();
                    final Executable testMethod = () -> Functions.stream(input)
                            .map(Integer::valueOf)
                            .filter(asIntPredicate(se))
                            .collect(Collectors.toList());
                    final UndeclaredThrowableException thrown = assertThrows(UndeclaredThrowableException.class, testMethod);
                    assertAll(
                            () -> assertThat(thrown.getMessage(), is(nullValue())),
                            () -> assertThat(thrown.getCause(), is(equalTo(se)))
                    );
                })
        );
    }

}


text:
.class Landroid/widget/CursorTreeAdapter$MyCursorHelper$MyDataSetObserver;
.super Landroid/database/DataSetObserver;
.source "CursorTreeAdapter.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/widget/CursorTreeAdapter$MyCursorHelper;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x2
    name = "MyDataSetObserver"
.end annotation

# instance fields
.field final synthetic this$1:Landroid/widget/CursorTreeAdapter$MyCursorHelper;

# direct methods
.method private constructor <init>(Landroid/widget/CursorTreeAdapter$MyCursorHelper;)V
    .locals 0
    .param p1, "this$1"    # Landroid/widget/CursorTreeAdapter$MyCursorHelper;

    .prologue
    .line 508
    iput-object p1, p0, Landroid/widget/CursorTreeAdapter$MyCursorHelper$MyDataSetObserver;->this$1:Landroid/widget/CursorTreeAdapter$MyCursorHelper;

    invoke-direct {p0}, Landroid/database/DataSetObserver;-><init>()V

    return-void
.end method

.method synthetic constructor <init>(Landroid/widget/CursorTreeAdapter$MyCursorHelper;Landroid/widget/CursorTreeAdapter$MyCursorHelper$MyDataSetObserver;)V
    .locals 0
    .param p1, "this$1"    # Landroid/widget/CursorTreeAdapter$MyCursorHelper;

    .prologue
    invoke-direct {p0, p1}, Landroid/widget/CursorTreeAdapter$MyCursorHelper$MyDataSetObserver;-><init>(Landroid/widget/CursorTreeAdapter$MyCursorHelper;)V

    return-void
.end method

# virtual methods
.method public onChanged()V
    .locals 2

    .prologue
    .line 511
    iget-object v0, p0, Landroid/widget/CursorTreeAdapter$MyCursorHelper$MyDataSetObserver;->this$1:Landroid/widget/CursorTreeAdapter$MyCursorHelper;

    const/4 v1, 0x1

    invoke-static {v0, v1}, Landroid/widget/CursorTreeAdapter$MyCursorHelper;->-set0(Landroid/widget/CursorTreeAdapter$MyCursorHelper;Z)Z

    .line 512
    iget-object v0, p0, Landroid/widget/CursorTreeAdapter$MyCursorHelper$MyDataSetObserver;->this$1:Landroid/widget/CursorTreeAdapter$MyCursorHelper;

    iget-object v0, v0, Landroid/widget/CursorTreeAdapter$MyCursorHelper;->this$0:Landroid/widget/CursorTreeAdapter;

    invoke-virtual {v0}, Landroid/widget/CursorTreeAdapter;->notifyDataSetChanged()V

    .line 510
    return-void
.end method

.method public onInvalidated()V
    .locals 2

    .prologue
    .line 517
    iget-object v0, p0, Landroid/widget/CursorTreeAdapter$MyCursorHelper$MyDataSetObserver;->this$1:Landroid/widget/CursorTreeAdapter$MyCursorHelper;

    const/4 v1, 0x0

    invoke-static {v0, v1}, Landroid/widget/CursorTreeAdapter$MyCursorHelper;->-set0(Landroid/widget/CursorTreeAdapter$MyCursorHelper;Z)Z

    .line 518
    iget-object v0, p0, Landroid/widget/CursorTreeAdapter$MyCursorHelper$MyDataSetObserver;->this$1:Landroid/widget/CursorTreeAdapter$MyCursorHelper;

    iget-object v0, v0, Landroid/widget/CursorTreeAdapter$MyCursorHelper;->this$0:Landroid/widget/CursorTreeAdapter;

    invoke-virtual {v0}, Landroid/widget/CursorTreeAdapter;->notifyDataSetInvalidated()V

    .line 516
    return-void
.end method

redpajama_set_name: RedPajamaGithub


text:
/**
 * @fileOverview Implements a popup component
 *
 * @author Frédéric MOULIS, JF CUNAT, Sylvain LALANDE
 */

define(['../../../../_amd/core'], function(wink)
{
	var byId = wink.byId;

	/**
	 * @class Popup is a singleton that allows to open a popup window with one (alert) or two buttons (confirm) or with a fully customizable content
	 * Options are available for each type of popup style
	 *
	 * @example
	 *
	 * var popup = new wink.ui.xy.Popup();
	 *
	 * document.body.appendChild(popup.getDomNode());
	 *
	 * popup.confirm(
	 * {
	 * 	msg: "Do you confirm ?",
	 * 	callbackOk: { context: window, method: 'confirmOk' },
	 * 	callbackCancel: { context: window, method: 'confirmCancel' }
	 * });
	 *
	 * @compatibility iOS2, iOS3, iOS4, iOS5, iOS6, Android 1.1, Android 1.5, Android 2.1, Android 2.2, Android 2.3, Android 3.0, Android 3.1, Android 4.0, Android 4.1.2, BlackBerry 6, BlackBerry 7, BB10, Bada 1.0, Windows Phone 7.5, Windows Phone 8
	 *
	 * @see Test page
	 * @see Test page (add to homescreen)
	 */
	wink.ui.xy.Popup = function()
	{
		if (wink.isUndefined(wink.ui.xy.Popup.singleton))
		{
			/**
			 * Unique identifier
			 *
			 * @property
			 * @type integer
			 */
			this.uId = 1;

			/**
			 * Indicates whether the Popup is displayed
			 *
			 * @property
			 * @type boolean
			 */
			this.displayed = false;

			this._domNode		= null;
			this._contentNode 	= null;
			this._btnsNode 		= null;
			this._arrowNode		= null;
			this._absolutePos	= false;
			this._nodeAsContent = false;
			this._contentParentNode = null;
			this._followScrollY = false;
			this._scrollHandler = null;
			this._popupClasses	= "";
			this._inTransition	= false;
			this._transitions	= {};

			this._initDom();
			this._initListeners();

			wink.ui.xy.Popup.singleton = this;
		}
		else
		{
			return wink.ui.xy.Popup.singleton;
		}
	};

	wink.ui.xy.Popup.prototype =
	{
		i18n: {},
		_DEFAULT_ARROW: "none",

		/**
		 * Returns the Popup dom node
		 *
		 * @returns {HTMLElement} The main dom node
		 */
		getDomNode: function()
		{
			return this._domNode;
		},
		/**
		 * Hides the Popup
		 */
		hide: function()
		{
			this._hide();
		},
		/**
		 * @deprecated This method is no longer needed
		 * @since 1.2.0
		 */
		preloadContent: function()
		{
			wink.log('[Popup] preloadContent is deprecated : this method is no longer needed');
			return;
		},
		/**
		 * Opens a 1-button popup with a message. calls a callback function if asked when the button is clicked
		 *
		 * @param {object} options The options object
		 * @param {string} options.msg The message to display
		 * @param {string} options.btn The text to display in the button. If nothing specified, the default translation is used
		 * @param {object|function} options.callback The callback to invoke when the user clicks on the button
		 * @param {boolean} options.borderRadius Indicates whether the popup must be displayed with border-radius style
		 * @param {integer} options.duration The duration of the display transition
		 * @param {boolean} options.followScrollY Allows to follow the scroll on y-axis
		 */
		alert: function(options)
		{
			if (this.displayed == true) {
				return;
			}
			var opt = options || {};
			this._initTemplate(this._DEFAULT_ARROW, opt.msg);

			var btnNode = document.createElement('div');
			wink.addClass(btnNode, "w_button w_radius pp_popup_btn pp_popup_alert w_bg_light");
			var btnNodeValue = wink.translate('alertOk', this);
			if (wink.isSet(opt.btn))
			{
				btnNodeValue = opt.btn;
			}
			btnNode.innerHTML = btnNodeValue;

			if (wink.isSet(opt.callback)) {
				btnNode.onclick = wink.bind(function(e) {
					this._invokeCallback(opt.callback);
				}, this);
			}
			this._btnsNode.appendChild(btnNode);

			this._setPopupStyle("pp_type_alert", opt);
			this._show();
		},
		/**
		 * Opens a 2-buttons popup with a message. calls a callback function if asked, depending on the clicked button
		 *
		 * @param {object} options The options object
		 * @param {string} options.msg The message to display
		 * @param {string} options.btnCancel The text to display in the "cancel" button. If nothing specified, the default translation is used
		 * @param {object|function} options.callbackCancel The callback to invoke when the user clicks on the 'cancel' button { context, method }
		 * @param {string} options.btnOk The text to display in the "ok" button. If nothing specified, the default translation is used
		 * @param {object|function} options.callbackOk The callback to invoke when the user clicks on the 'ok' button { context, method }
		 * @param {boolean} options.borderRadius Indicates whether the popup must be displayed with border-radius style
		 * @param {integer} options.duration The duration of the display transition
		 * @param {boolean} options.followScrollY Allows to follow the scroll on y-axis
		 */
		confirm: function(options)
		{
			if (this.displayed == true) {
				return;
			}
			var opt = options || {};
			this._initTemplate(this._DEFAULT_ARROW, opt.msg);

			var btnCancelNode = document.createElement('div');
			var btnOkNode = document.createElement('div');
			wink.addClass(btnCancelNode, "w_button w_radius pp_popup_btn pp_popup_confirm w_bg_light");
			wink.addClass(btnOkNode, "w_button w_radius pp_popup_btn pp_popup_confirm w_bg_light");

			var btnCancelValue = wink.translate('confirmCancel', this);
			if (wink.isSet(opt.btnCancel))
			{
				btnCancelValue = opt.btnCancel;
			}
			var btnOkValue = wink.translate('confirmOk', this);
			if (wink.isSet(opt.btnOk))
			{
				btnOkValue = opt.btnOk;
			}

			btnCancelNode.innerHTML = btnCancelValue;
			btnOkNode.innerHTML = btnOkValue;

			if (wink.isSet(opt.callbackCancel)) {
				btnCancelNode.onclick = wink.bind(function(e) {
					this._invokeCallback(opt.callbackCancel);
				}, this);
			}
			if (wink.isSet(opt.callbackOk)) {
				btnOkNode.onclick = wink.bind(function(e) {
					this._invokeCallback(opt.callbackOk);
				}, this);
			}
			this._btnsNode.appendChild(btnCancelNode);
			this._btnsNode.appendChild(btnOkNode);

			this._setPopupStyle("pp_type_confirm", opt);
			this._show();
		},
		/**
		 * Opens a fully customizable popup
		 *
		 * @param {object} options The options object
		 * @param {string|HTMLElement} options.content The HTML code of the content or a dom node
		 * @param {string} options.arrow The position of the arrow, if needed, values: "top", "bottom", "none" (default value)
		 * @param {integer|string} options.top The top position of the window
		 * @param {HTMLElement} options.targetNode The node pointed by the arrow (top is then ignored)
		 * @param {integer|string} options.arrowLeftPos The left-position of the arrow
		 * @param {boolean} options.borderRadius Indicates whether the popup must be displayed with border-radius style
		 * @param {integer} options.duration The duration of the display transition
		 * @param {boolean} options.followScrollY Allows to follow the scroll on y-axis
		 * @param {object|function} options.layerCallback The callback invoked when the user click on the layer, if not specified the default action is the popup hiding
		 */
		popup: function(options)
		{
			if (this.displayed == true) {
				return;
			}
			var opt = options || {};
			var arrowValue = this._DEFAULT_ARROW;
			var arrowLeftPos = "50px";

			if (wink.isSet(opt.arrowLeftPos)) {
				if (wink.isInteger(opt.arrowLeftPos)) {
					arrowLeftPos = opt.arrowLeftPos + "px";
				} else {
					arrowLeftPos = opt.arrowLeftPos;
				}
			}

			if (wink.isSet(opt.arrow)) {
				arrowValue 	= opt.arrow;
			}
			if (arrowValue != 'top' && arrowValue != 'bottom' && arrowValue != this._DEFAULT_ARROW) {
				wink.log('[Popup] popup() : bad arrow value (expected "top", "bottom" or "none")');
				return;
			}

			this._initTemplate(arrowValue, opt.content, arrowLeftPos);

			var topValue = "0px";
			if (wink.isSet(opt.targetNode)) {
				this._absolutePos = true;
				if (arrowValue == "bottom") {
					topValue = wink.getTopPosition(opt.targetNode) - this._domNode.offsetHeight - 10 + "px";
				} else if (arrowValue == "top") {
					topValue = wink.getTopPosition(opt.targetNode) + opt.targetNode.offsetHeight + 10 + "px";
				}
			} else if (wink.isSet(opt.top)) {
				this._absolutePos = true;
				if (wink.isInteger(opt.top)) {
					topValue = opt.top + "px";
				} else {
					topValue = opt.top;
				}
			}
			this._domNode.style.top = topValue;

			this._setPopupStyle("pp_type_popup", opt);

			// for browsers that do not support css gradient
			if(!wink.has('css-gradient'))
			{
				this._arrowNode.style['border'+((arrowValue == 'top') ? 'Bottom' : 'Top')+'Color'] = window.getComputedStyle(this._domNode)['background-color'];
			}

			this._show();

			if (wink.isSet(opt.layerCallback)) {
				wink.layer.onclick = function() {
					if (!this._inTransition) {
						wink.call(opt.layerCallback);
					}
				};
			} else {
				wink.layer.onclick = this._layerHandler;
			}
		},
		/**
		 * Initialize the popup template
		 *
		 * @param {string} arrowType The arrow type ("top", "bottom" or "none")
		 * @param {string|HTMLElement} content The content
		 * @param {string} arrowLeftPos The left-position of the arrow
		 */
		_initTemplate: function(arrowType, content, arrowLeftPos)
		{
			this._absolutePos = false;
			this._followScrollY = false;
			this._nodeAsContent = false;
            this._contentParentNode = null;
			this._popupClasses = "w_box w_window pp_popup pp_hidden w_bg_dark";
			if(wink.isString(content)){
              this._contentNode.innerHTML = content;
            }else{
              if (content && content.nodeType != undefined){
                this._nodeAsContent = true;
                this._contentParentNode = content.parentNode;
                this._contentNode.appendChild(content);
              }
            }
			this._btnsNode.innerHTML = "";
			this._arrowNode.className = "pp_popup_arrow pp_" + arrowType;
			this._arrowNode.style.left = arrowLeftPos;
			this._domNode.style.top = "0px";
		},
		/**
		 * Set the popup style
		 *
		 * @param {string} style The css class of the popup
		 * @param {object} opt The options
		 */
		_setPopupStyle: function(style, opt)
		{
			this._popupClasses += " " + style;
			if (opt.borderRadius !== false) {
				this._popupClasses += " w_radius";
			}
			this._domNode.className = this._popupClasses;

			if (wink.isSet(opt.followScrollY) && opt.followScrollY === true) {
				this._followScrollY = true;
			}

			this._updatePosition();

			var newOpDur = (opt.duration >= 0) ? opt.duration : 400;
			this._updateTransition(newOpDur, 0);
		},
		/**
		 * Updates the popup transitions
		 *
		 * @param {integer} opacityDuration The opacity duration
		 * @param {integer} topDuration The top duration
		 */
		_updateTransition: function(opacityDuration, topDuration)
		{
			var trsChanged = false;
			if (wink.isInteger(opacityDuration) && this._transitions.opacity != opacityDuration) {
				this._transitions.opacity = opacityDuration;
				trsChanged = true;
			}
			if (wink.isInteger(topDuration) && this._transitions.top != topDuration) {
				this._transitions.top = topDuration;
				trsChanged = true;
			}

			if (trsChanged) {
				var dr = this._transitions.opacity + "ms," + this._transitions.top + 'ms';
				wink.fx.applyTransition(this._domNode, 'opacity, transform', dr, '1ms,1ms', 'default,default');
				// WORKAROUND : the second delay must be 1ms instead of 0ms for iOS2
			}
		},
		/**
		 * Updates the popup position
		 */
		_updatePosition: function()
		{
			var y = 0;
			if (this._absolutePos == false) {
				y += ((window.innerHeight - this._domNode.offsetHeight) / 2) + window.pageYOffset;
			} else if (this._followScrollY) {
				y += window.pageYOffset;
			}
			wink.fx.translate(this._domNode, 0, y);
		},
		/**
		 * Initialize the DOM nodes
		 */
		_initDom: function()
		{
			this._domNode = document.createElement('div');
			this._contentNode = document.createElement('div');
			this._btnsNode = document.createElement('div');
			this._arrowNode	= document.createElement('div');

			wink.addClass(this._domNode, "pp_popup pp_hidden");
			wink.addClass(this._contentNode, "w_bloc");
			wink.addClass(this._arrowNode, "pp_popup_arrow none");

			this._domNode.appendChild(this._contentNode);
			this._domNode.appendChild(this._btnsNode);
			this._domNode.appendChild(this._arrowNode);

			this._domNode.style.opacity = 0;
			this._transitions.opacity = 0;
			this._transitions.top = 0;
		},
		/**
		 * Initialize listeners
		 */
		_initListeners: function()
		{
			this._scrollHandler = wink.bind(this._updatePosition, this);
			this._postShowHandler = wink.bind(this._postShow, this);
			this._postHideHandler = wink.bind(this._postHide, this);
			this._layerHandler = wink.bind(this._hide, this);
		},
		/**
		 * Shows the popup
		 */
		_show: function()
		{
			if (this.displayed == true || this._inTransition == true) {
				return;
			}
			this._inTransition = true;

			if (this._followScrollY == true) {
				window.addEventListener("scroll", this._scrollHandler, false);
			}
			wink.removeClass(this._domNode, "pp_hidden");

			wink.layer.update();
			wink.layer.show();

			if(wink.has('css-transition'))
			{
				wink.fx.onTransitionEnd(this._domNode, this._postShowHandler);
			} else
			{
				this._postShowHandler();
			}
			this._domNode.style.opacity = 1;
		},
		/**
		 * Post show management
		 */
		_postShow: function()
		{
			if (this._followScrollY == true) {
				this._updateTransition(this._transitions.opacity, 200);
			}
			this.displayed = true;
			this._inTransition = false;
		},
		/**
		 * Hides the popup
		 */
		_hide: function()
		{
			if (this.displayed == false || this._inTransition == true) {
				return;
			}
			this._inTransition = true;

			if (this._followScrollY == true) {
				window.removeEventListener("scroll", this._scrollHandler, false);
			}

			wink.layer.hide();
			wink.layer.onclick = null;

			if(wink.has('css-transition'))
			{
				wink.fx.onTransitionEnd(this._domNode, this._postHideHandler);
			} else
			{
				this._postHideHandler();
			}
			this._domNode.style.opacity = 0;
		},
		/**
		 * Post hide management
		 */
		_postHide: function()
		{
			wink.addClass(this._domNode, "pp_hidden");

			if (this._nodeAsContent){
              (this._contentParentNode || document.body).appendChild(this._contentNode.firstChild);
            }

			this._contentNode.innerHTML = "";

			this.displayed = false;
			this._inTransition = false;
		},
		/**
		 * Invokes the given callback
		 *
		 * @param {object|function} cb The callback to invoke
		 */
		_invokeCallback: function(cb)
		{
			if (this._inTransition == true || !wink.isSet(cb)) {
				return;
			}
			this._hide();
			wink.call(cb);
		}
	};

	return wink.ui.xy.Popup;
});


text:
package ru.job4j;

import org.junit.Test;
import static org.hamcrest.number.IsCloseTo.closeTo;
import static org.junit.Assert.assertThat;

/**
 *Test.
 *@author gkachalov
 *@since 13.01.2016
 *@version 1
 */
 public class PointTest {
	/**
	 * Number 1.0.
	 */
	private final double one = 1.0;
	/**
	 * Number 2.0.
	 */
	private final double two = 2.0;
	/**
	 * error Number 2.01.
	 */
	private final double error = 2.01;
	/**
	 *Test distanceTo метода расчета расстояния между точками.
	 */
	 @Test
	 public void testCalculationDistanceTo() {
		  Point pointA = new Point(one, one);
		  Point pointB = new Point(one, two);
		  assertThat(pointA.distanceTo(pointB), closeTo(two, error));
	 }
 }


text:
ACCEPTED

#### According to
Integrated Taxonomic Information System

#### Published in
W. J. Hooker, Niger Fl. 142. 1849

#### Original name
null

### Remarks
null


text:
import { extHostCustomer } from 'vs/workbench/api/electron-browser/extHostCustomers';
import { ILogService } from 'vs/platform/log/common/log';
import { Disposable } from 'vs/base/common/lifecycle';
import { IExtHostContext, ExtHostContext } from 'vs/workbench/api/node/extHost.protocol';

@extHostCustomer
export class MainThreadLogService extends Disposable {

	constructor(
		extHostContext: IExtHostContext,
		@ILogService logService: ILogService,
	) {
		super();
		this._register(logService.onDidChangeLogLevel(level => extHostContext.getProxy(ExtHostContext.ExtHostLogService).$setLevel(level)));
	}

}


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

			<title>Docs For Class AmfphpFlexMessaging</title>
			<link rel="stylesheet" href="../media/stylesheet.css" />
			<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'/>

Class AmfphpFlexMessaging

Description

					Description |
															Methods (details)

											Constants (details)

Support for flex messaging.

Flex doesn't use the basic packet system. When using a remote objct, first a CommandMessage is sent, expecting an AcknowledgeMessage in return.  Then a RemotingMessage is sent, expecting an AcknowledgeMessage in return.  In case of an error, an ErrorMessage is expected

author: Ariel Sommeria-Klein

			Located in /Amfphp/Plugins/AmfphpFlexMessaging/AmfphpFlexMessaging.php (line 26)

Class Constant Summary

			Description |
						Constants (details)
										|
									Methods (details)

					FIELD_MESSAGE_ID = 					 "messageId"

					FLEX_TYPE_ACKNOWLEDGE_MESSAGE = 					 'flex.messaging.messages.AcknowledgeMessage'

					FLEX_TYPE_COMMAND_MESSAGE = 					 'flex.messaging.messages.CommandMessage'

					FLEX_TYPE_ERROR_MESSAGE = 					 'flex.messaging.messages.ErrorMessage'

					FLEX_TYPE_REMOTING_MESSAGE = 					 'flex.messaging.messages.RemotingMessage'

Method Summary

			Description |
															Constants (details)

									Methods (details)

											AmfphpFlexMessaging
										__construct
											([ $config = null])

											array
										filterAmfExceptionHandler
											( $handler, Object $handler.)

											array
										filterAmfRequestMessageHandler
											( $handler,  $requestMessage, Object $handler.)

											Amfphp_Core_Amf_Packet
										generateErrorResponse
											( $exception)

											Amfphp_Core_Amf_Message
										handleRequestMessage
											( $requestMessage,  $serviceRouter)

Methods

			Description |
																		Constants (details)

										Methods (details)

		Constructor __construct (line 56)

constructor.

access: public

		AmfphpFlexMessaging

			__construct

					([ $config = null])

				array
				$config: optional key/value pairs in an associative array. Used to override default configuration values.

		filterAmfExceptionHandler (line 99)

access: public

		array

			filterAmfExceptionHandler

					( $handler, Object $handler.)

				Object
				$handler.: null at call. If the plugin takes over the handling of the request message,  it must set this to a proper handler for the message, probably itself.

				$handler

		filterAmfRequestMessageHandler (line 69)

access: public

		array

			filterAmfRequestMessageHandler

					( $handler,  $requestMessage, Object $handler.)

				Object
				$handler.: null at call. If the plugin takes over the handling of the request message,  it must set this to a proper handler for the message, probably itself.

				Amfphp_Core_Amf_Message
				$requestMessage: the request message

				$handler

		generateErrorResponse (line 144)

flex expects error messages formatted in a special way, using the ErrorMessage object.

access: public

		Amfphp_Core_Amf_Packet

			generateErrorResponse

					( $exception)

				Exception
				$exception

		handleRequestMessage (line 111)

handle the request message instead of letting the Amf Handler do it.

access: public

		Amfphp_Core_Amf_Message

			handleRequestMessage

					( $requestMessage,  $serviceRouter)

				Amfphp_Core_Amf_Message
				$requestMessage

				Amfphp_Core_Common_ServiceRouter
				$serviceRouter

Class Constants

			Description |
										Constants (details)

										|
									Methods (details)

			FIELD_MESSAGE_ID
			 =  "messageId"
			(line 32)

			FLEX_TYPE_ACKNOWLEDGE_MESSAGE
			 =  'flex.messaging.messages.AcknowledgeMessage'
			(line 29)

			FLEX_TYPE_COMMAND_MESSAGE
			 =  'flex.messaging.messages.CommandMessage'
			(line 27)

			FLEX_TYPE_ERROR_MESSAGE
			 =  'flex.messaging.messages.ErrorMessage'
			(line 30)

			FLEX_TYPE_REMOTING_MESSAGE
			 =  'flex.messaging.messages.RemotingMessage'
			(line 28)

		Documentation generated on Thu, 23 Jun 2011 13:03:05 +0200 by phpDocumentor 1.4.3


text:
import ViewNodeManager from 'ember-htmlbars/node-managers/view-node-manager';

QUnit.module('ember-htmlbars: node-managers - ViewNodeManager');

QUnit.test('create method should assert if component hasn\'t been found', assert => {
  assert.expect(1);

  let found = {
    component: null,
    layout: null
  };

  let path;

  expectAssertion(() => {
    ViewNodeManager.create(null, null, null, found, null, path);
  }, 'HTMLBars error: Could not find component named "' + path + '" (no component or template with that name was found)');
});

QUnit.test('create method shouldn\'t assert if `found.component` is truthy', assert => {
  assert.expect(1);

  let found = {
    component: {},
    layout: null
  };
  let attrs = {};
  let renderNode = {};

  let env = {
    renderer: {
      componentUpdateAttrs() {
        assert.ok('env.renderer.componentUpdateAttrs called');
      }
    }
  };

  ViewNodeManager.create(renderNode, env, attrs, found);
});

QUnit.test('create method shouldn\'t assert if `found.layout` is truthy', assert => {
  assert.expect(0);

  let found = {
    component: null,
    layout: true
  };

  ViewNodeManager.create(null, null, null, found);
});

QUnit.test('create method shouldn\'t assert if `path` is falsy and `contentTemplate` is truthy', assert => {
  assert.expect(0);

  let found = {
    component: null,
    layout: null
  };
  let path = null;
  let contentTemplate = true;

  ViewNodeManager.create(null, null, null, found, null, path, null, contentTemplate);
});


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<meta name="generator" content="JDiff v1.1.0">

<meta name="description" content="JDiff is a Javadoc doclet which generates an HTML report of all the packages, classes, constructors, methods, and fields which have been removed, added or changed in any way, including their documentation, when two APIs are compared.">
<meta name="keywords" content="diff, jdiff, javadiff, java diff, java difference, API difference, difference between two APIs, API diff, Javadoc, doclet">
<TITLE>
android.service.voice.VoiceInteractionSession
</TITLE>
<link href="../../../../assets/android-developer-docs.css" rel="stylesheet" type="text/css" />
<link href="../stylesheet-jdiff.css" rel="stylesheet" type="text/css" />

<nobr>Android Developers | Android.com</nobr>

        API Diff Specification

        To Level:
        23

        From Level:
        22

        Generated
        2015.08.14 14:28

        Statistics

Class android.service.voice.VoiceInteractionSession

Added interface android.content.ComponentCallbacks2.

Changed from abstract to non-abstract.

  Added Methods

  <nobr>void closeSystemDialogs()</nobr>

  <nobr>void dump(String,</nobr> FileDescriptor<nobr>,</nobr> PrintWriter<nobr>,</nobr> String[]<nobr><nobr>)</nobr>

  <nobr>Context getContext()</nobr>

  <nobr>int getDisabledShowContext()</nobr>

  <nobr>LayoutInflater getLayoutInflater()</nobr>

  <nobr>int getUserDisabledShowContext()</nobr>

  <nobr>Dialog getWindow()</nobr>

  <nobr>void hide()</nobr>

  <nobr>void onAssistStructureFailure(Throwable)</nobr>

  <nobr>void onBackPressed()</nobr>

  <nobr>void onCancelRequest(Request)</nobr>

  <nobr>void onComputeInsets(Insets)</nobr>

  <nobr>void onConfigurationChanged(Configuration)</nobr>

  <nobr>View onCreateContentView()</nobr>

  <nobr>boolean[] onGetSupportedCommands(String[])</nobr>

  <nobr>void onHandleAssist(Bundle,</nobr> AssistStructure<nobr>,</nobr> AssistContent<nobr><nobr>)</nobr>

  <nobr>void onHandleScreenshot(Bitmap)</nobr>

  <nobr>void onHide()</nobr>

  <nobr>void onLockscreenShown()</nobr>

  <nobr>void onLowMemory()</nobr>

  <nobr>void onRequestAbortVoice(AbortVoiceRequest)</nobr>

  <nobr>void onRequestCommand(CommandRequest)</nobr>

  <nobr>void onRequestCompleteVoice(CompleteVoiceRequest)</nobr>

  <nobr>void onRequestConfirmation(ConfirmationRequest)</nobr>

  <nobr>void onRequestPickOption(PickOptionRequest)</nobr>

  <nobr>void onShow(Bundle,</nobr> int<nobr><nobr>)</nobr>

  <nobr>void onTaskFinished(Intent,</nobr> int<nobr><nobr>)</nobr>

  <nobr>void onTaskStarted(Intent,</nobr> int<nobr><nobr>)</nobr>

  <nobr>void onTrimMemory(int)</nobr>

  <nobr>void setDisabledShowContext(int)</nobr>

  <nobr>void setKeepAwake(boolean)</nobr>

  <nobr>void setTheme(int)</nobr>

  <nobr>void show(Bundle,</nobr> int<nobr><nobr>)</nobr>

  <nobr>void startVoiceActivity(Intent)</nobr>

  Changed Methods

  <nobr>void onCreate()  </nobr>

Change in signature from Bundle to void.

  Added Fields

  <nobr>int SHOW_SOURCE_APPLICATION</nobr>

  <nobr>int SHOW_SOURCE_ASSIST_GESTURE</nobr>

  <nobr>int SHOW_WITH_ASSIST</nobr>

  <nobr>int SHOW_WITH_SCREENSHOT</nobr>

        Except as noted, this content is licensed under
         Creative Commons Attribution 2.5.
        For details and restrictions, see the Content License.

        Site Terms of Service -
        Privacy Policy -
        Brand Guidelines


text:
using namespace std;

bool exist[100];

void Permutation(int test[], int first, int last);
void PrintSubset(int test[], bool exist[], int last);
void Subset(int test[], bool exist[], int first, int last);

int main()
{
	int test[100];
	while(1)
	{
		cout << "Please input your array's size(0 to quit):\n";
		int length;
		cin >> length;
		if(length)
		{
			cout << "Please input " << length << " integer:\n";
			for(int index = 0; index < length; index++)
			{
				cin >> test[index];
			}
			cout << "Permutation:\n";
			Permutation(test, 0, length - 1);
			cout << "Subset:\n";
			Subset(test, exist, 0, length - 1);
		}
		else
		{
			break;
		}
	}

	return 0;
}

void Permutation(int test[], int first, int last)  // get the permutation of test[first, last]
{
	if(first == last)  // no need to swap element, so we get one permutation
	{
		for(int index = 0; index <= last; index++)
		{
			cout << test[index] << " ";
		}
		cout << endl;
	}
	else
	{
		for(int index = first; index <= last; index++)
		{
			swap(test[first], test[index]);  // exchange the first element with all elements one by one
			Permutation(test, first + 1, last);  // get the permutation of test[first + 1, last]
			swap(test[first], test[index]);  // recover the exchange
		}
	}
}

void Subset(int test[], bool exist[], int first, int last)  // get the subset of test[first, last]
{
	if(first == last)  // reach the end
	{
		exist[first] = true;  // the last element is in this subset
		PrintSubset(test, exist, last);  // get one subset
		exist[first] = false;
		PrintSubset(test, exist, last);
		return;
	}
	exist[first] = true;  // the first element is in this subset
	Subset(test, exist, first + 1, last);  // get the subset of test[first + 1, last]
	exist[first] = false;
	Subset(test, exist, first + 1, last);
}

void PrintSubset(int test[], bool exist[], int last)
{
	for(int index = 0; index <= last; index++)
	{
		if(exist[index])  // if  current element is in the subset, print it.
		{
			cout << test[index] << " ";
		}
	}
	cout << endl;
}


text:
import { Component, Input } from '@angular/core';

@Component({
  selector: 'wordlist',
  styleUrls: [ './wordlist.component.scss' ],
  templateUrl: './wordlist.component.html'
})
export class WordlistComponent {

  @Input('words') wordLists;
  @Input('sentences') relatedSentences;

  constructor () {}
}


text:
namespace v8 {
namespace internal {

template<class Type, class TypeHandle, class Region>
class Types {
 public:
  Types(Region* region, Isolate* isolate, v8::base::RandomNumberGenerator* rng)
      : region_(region), isolate_(isolate), rng_(rng) {
    #define DECLARE_TYPE(name, value) \
      name = Type::name(region);      \
      types.push_back(name);
    PROPER_BITSET_TYPE_LIST(DECLARE_TYPE)
    #undef DECLARE_TYPE

    SignedSmall = Type::SignedSmall(region);
    UnsignedSmall = Type::UnsignedSmall(region);

    object_map = isolate->factory()->NewMap(
        JS_OBJECT_TYPE, JSObject::kHeaderSize);
    array_map = isolate->factory()->NewMap(
        JS_ARRAY_TYPE, JSArray::kSize);
    number_map = isolate->factory()->NewMap(
        HEAP_NUMBER_TYPE, HeapNumber::kSize);
    uninitialized_map = isolate->factory()->uninitialized_map();
    ObjectClass = Type::Class(object_map, region);
    ArrayClass = Type::Class(array_map, region);
    NumberClass = Type::Class(number_map, region);
    UninitializedClass = Type::Class(uninitialized_map, region);

    maps.push_back(object_map);
    maps.push_back(array_map);
    maps.push_back(uninitialized_map);
    for (MapVector::iterator it = maps.begin(); it != maps.end(); ++it) {
      types.push_back(Type::Class(*it, region));
    }

    smi = handle(Smi::FromInt(666), isolate);
    signed32 = isolate->factory()->NewHeapNumber(0x40000000);
    object1 = isolate->factory()->NewJSObjectFromMap(object_map);
    object2 = isolate->factory()->NewJSObjectFromMap(object_map);
    array = isolate->factory()->NewJSArray(20);
    uninitialized = isolate->factory()->uninitialized_value();
    SmiConstant = Type::Constant(smi, region);
    Signed32Constant = Type::Constant(signed32, region);

    ObjectConstant1 = Type::Constant(object1, region);
    ObjectConstant2 = Type::Constant(object2, region);
    ArrayConstant = Type::Constant(array, region);
    UninitializedConstant = Type::Constant(uninitialized, region);

    values.push_back(smi);
    values.push_back(signed32);
    values.push_back(object1);
    values.push_back(object2);
    values.push_back(array);
    values.push_back(uninitialized);
    for (ValueVector::iterator it = values.begin(); it != values.end(); ++it) {
      types.push_back(Type::Constant(*it, region));
    }

    integers.push_back(isolate->factory()->NewNumber(-V8_INFINITY));
    integers.push_back(isolate->factory()->NewNumber(+V8_INFINITY));
    integers.push_back(isolate->factory()->NewNumber(-rng_->NextInt(10)));
    integers.push_back(isolate->factory()->NewNumber(+rng_->NextInt(10)));
    for (int i = 0; i < 10; ++i) {
      double x = rng_->NextInt();
      integers.push_back(isolate->factory()->NewNumber(x));
      x *= rng_->NextInt();
      if (!IsMinusZero(x)) integers.push_back(isolate->factory()->NewNumber(x));
    }

    Integer = Type::Range(-V8_INFINITY, +V8_INFINITY, region);

    NumberArray = Type::Array(Number, region);
    StringArray = Type::Array(String, region);
    AnyArray = Type::Array(Any, region);

    SignedFunction1 = Type::Function(SignedSmall, SignedSmall, region);
    NumberFunction1 = Type::Function(Number, Number, region);
    NumberFunction2 = Type::Function(Number, Number, Number, region);
    MethodFunction = Type::Function(String, Object, 0, region);

    for (int i = 0; i < 30; ++i) {
      types.push_back(Fuzz());
    }
  }

  Handle<i::Map> object_map;
  Handle<i::Map> array_map;
  Handle<i::Map> number_map;
  Handle<i::Map> uninitialized_map;

  Handle<i::Smi> smi;
  Handle<i::HeapNumber> signed32;
  Handle<i::JSObject> object1;
  Handle<i::JSObject> object2;
  Handle<i::JSArray> array;
  Handle<i::Oddball> uninitialized;

  #define DECLARE_TYPE(name, value) TypeHandle name;
  PROPER_BITSET_TYPE_LIST(DECLARE_TYPE)
  #undef DECLARE_TYPE

#define DECLARE_TYPE(name, value) TypeHandle Mask##name##ForTesting;
  MASK_BITSET_TYPE_LIST(DECLARE_TYPE)
#undef DECLARE_TYPE
  TypeHandle SignedSmall;
  TypeHandle UnsignedSmall;

  TypeHandle ObjectClass;
  TypeHandle ArrayClass;
  TypeHandle NumberClass;
  TypeHandle UninitializedClass;

  TypeHandle SmiConstant;
  TypeHandle Signed32Constant;
  TypeHandle ObjectConstant1;
  TypeHandle ObjectConstant2;
  TypeHandle ArrayConstant;
  TypeHandle UninitializedConstant;

  TypeHandle Integer;

  TypeHandle NumberArray;
  TypeHandle StringArray;
  TypeHandle AnyArray;

  TypeHandle SignedFunction1;
  TypeHandle NumberFunction1;
  TypeHandle NumberFunction2;
  TypeHandle MethodFunction;

  typedef std::vector<TypeHandle> TypeVector;
  typedef std::vector<Handle<i::Map> > MapVector;
  typedef std::vector<Handle<i::Object> > ValueVector;

  TypeVector types;
  MapVector maps;
  ValueVector values;
  ValueVector integers;  // "Integer" values used for range limits.

  TypeHandle Of(Handle<i::Object> value) {
    return Type::Of(value, region_);
  }

  TypeHandle NowOf(Handle<i::Object> value) {
    return Type::NowOf(value, region_);
  }

  TypeHandle Class(Handle<i::Map> map) {
    return Type::Class(map, region_);
  }

  TypeHandle Constant(Handle<i::Object> value) {
    return Type::Constant(value, region_);
  }

  TypeHandle Range(double min, double max) {
    return Type::Range(min, max, region_);
  }

  TypeHandle Context(TypeHandle outer) {
    return Type::Context(outer, region_);
  }

  TypeHandle Array1(TypeHandle element) {
    return Type::Array(element, region_);
  }

  TypeHandle Function0(TypeHandle result, TypeHandle receiver) {
    return Type::Function(result, receiver, 0, region_);
  }

  TypeHandle Function1(TypeHandle result, TypeHandle receiver, TypeHandle arg) {
    TypeHandle type = Type::Function(result, receiver, 1, region_);
    type->AsFunction()->InitParameter(0, arg);
    return type;
  }

  TypeHandle Function2(TypeHandle result, TypeHandle arg1, TypeHandle arg2) {
    return Type::Function(result, arg1, arg2, region_);
  }

  TypeHandle Union(TypeHandle t1, TypeHandle t2) {
    return Type::Union(t1, t2, region_);
  }

  TypeHandle Intersect(TypeHandle t1, TypeHandle t2) {
    return Type::Intersect(t1, t2, region_);
  }

  TypeHandle Representation(TypeHandle t) {
    return Type::Representation(t, region_);
  }

  // TypeHandle Semantic(TypeHandle t) { return Intersect(t,
  // MaskSemanticForTesting); }
  TypeHandle Semantic(TypeHandle t) { return Type::Semantic(t, region_); }

  template<class Type2, class TypeHandle2>
  TypeHandle Convert(TypeHandle2 t) {
    return Type::template Convert<Type2>(t, region_);
  }

  TypeHandle Random() {
    return types[rng_->NextInt(static_cast<int>(types.size()))];
  }

  TypeHandle Fuzz(int depth = 4) {
    switch (rng_->NextInt(depth == 0 ? 3 : 20)) {
      case 0: {  // bitset
        #define COUNT_BITSET_TYPES(type, value) + 1
        int n = 0 PROPER_BITSET_TYPE_LIST(COUNT_BITSET_TYPES);
        #undef COUNT_BITSET_TYPES
        // Pick a bunch of named bitsets and return their intersection.
        TypeHandle result = Type::Any(region_);
        for (int i = 0, m = 1 + rng_->NextInt(3); i < m; ++i) {
          int j = rng_->NextInt(n);
          #define PICK_BITSET_TYPE(type, value) \
            if (j-- == 0) { \
              TypeHandle tmp = Type::Intersect( \
                  result, Type::type(region_), region_); \
              if (tmp->Is(Type::None()) && i != 0) { \
                break; \
              } else { \
                result = tmp; \
                continue; \
              } \
            }
          PROPER_BITSET_TYPE_LIST(PICK_BITSET_TYPE)
          #undef PICK_BITSET_TYPE
        }
        return result;
      }
      case 1: {  // class
        int i = rng_->NextInt(static_cast<int>(maps.size()));
        return Type::Class(maps[i], region_);
      }
      case 2: {  // constant
        int i = rng_->NextInt(static_cast<int>(values.size()));
        return Type::Constant(values[i], region_);
      }
      case 3: {  // range
        int i = rng_->NextInt(static_cast<int>(integers.size()));
        int j = rng_->NextInt(static_cast<int>(integers.size()));
        double min = integers[i]->Number();
        double max = integers[j]->Number();
        if (min > max) std::swap(min, max);
        return Type::Range(min, max, region_);
      }
      case 4: {  // context
        int depth = rng_->NextInt(3);
        TypeHandle type = Type::Internal(region_);
        for (int i = 0; i < depth; ++i) type = Type::Context(type, region_);
        return type;
      }
      case 5: {  // array
        TypeHandle element = Fuzz(depth / 2);
        return Type::Array(element, region_);
      }
      case 6:
      case 7: {  // function
        TypeHandle result = Fuzz(depth / 2);
        TypeHandle receiver = Fuzz(depth / 2);
        int arity = rng_->NextInt(3);
        TypeHandle type = Type::Function(result, receiver, arity, region_);
        for (int i = 0; i < type->AsFunction()->Arity(); ++i) {
          TypeHandle parameter = Fuzz(depth / 2);
          type->AsFunction()->InitParameter(i, parameter);
        }
        return type;
      }
      case 8: {  // simd
        static const int num_simd_types =
            #define COUNT_SIMD_TYPE(NAME, Name, name, lane_count, lane_type) +1
            SIMD128_TYPES(COUNT_SIMD_TYPE);
            #undef COUNT_SIMD_TYPE
        TypeHandle (*simd_constructors[num_simd_types])(Isolate*, Region*) = {
          #define COUNT_SIMD_TYPE(NAME, Name, name, lane_count, lane_type) \
          &Type::Name,
          SIMD128_TYPES(COUNT_SIMD_TYPE)
          #undef COUNT_SIMD_TYPE
        };
        return simd_constructors[rng_->NextInt(num_simd_types)](
            isolate_, region_);
      }
      default: {  // union
        int n = rng_->NextInt(10);
        TypeHandle type = None;
        for (int i = 0; i < n; ++i) {
          TypeHandle operand = Fuzz(depth - 1);
          type = Type::Union(type, operand, region_);
        }
        return type;
      }
    }
    UNREACHABLE();
  }

  Region* region() { return region_; }

 private:
  Region* region_;
  Isolate* isolate_;
  v8::base::RandomNumberGenerator* rng_;
};

}  // namespace internal
}  // namespace v8

#endif


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using SignalR.Infrastructure;

namespace SignalR
{
    public abstract class Subscription : ISubscription, IDisposable
    {
        private readonly Func<MessageResult, Task<bool>> _callback;
        private readonly int _maxMessages;

        private readonly PerformanceCounter _subsTotalCounter;
        private readonly PerformanceCounter _subsCurrentCounter;
        private readonly PerformanceCounter _subsPerSecCounter;

        private int _disposed;

        private int _queued;
        private int _working;

        private bool Alive
        {
            get
            {
                return _disposed == 0;
            }
        }

        public string Identity { get; private set; }

        public HashSet<string> EventKeys { get; private set; }

        public int MaxMessages { get; set; }

        public Subscription(string identity, IEnumerable<string> eventKeys, Func<MessageResult, Task<bool>> callback, int maxMessages, IPerformanceCounterWriter counters)
        {
            Identity = identity;
            _callback = callback;
            _maxMessages = maxMessages;
            EventKeys = new HashSet<string>(eventKeys);
            MaxMessages = maxMessages;

            _subsTotalCounter = counters.GetCounter(PerformanceCounters.MessageBusSubscribersTotal);
            _subsCurrentCounter = counters.GetCounter(PerformanceCounters.MessageBusSubscribersCurrent);
            _subsPerSecCounter = counters.GetCounter(PerformanceCounters.MessageBusSubscribersPerSec);

            _subsTotalCounter.SafeIncrement();
            _subsCurrentCounter.SafeIncrement();
            _subsPerSecCounter.SafeIncrement();
        }

        public virtual Task<bool> Invoke(MessageResult result)
        {
            return _callback.Invoke(result);
        }

        public Task WorkAsync()
        {
            if (SetWorking())
            {
                var tcs = new TaskCompletionSource<object>();

                WorkImpl(tcs);

                // Fast Path
                if (tcs.Task.IsCompleted)
                {
                    UnsetWorking();
                    return tcs.Task;
                }

                return FinishAsync(tcs);
            }

            return TaskAsyncHelper.Empty;
        }

        public bool SetQueued()
        {
            return Interlocked.Exchange(ref _queued, 1) == 0;
        }

        public bool UnsetQueued()
        {
            return Interlocked.Exchange(ref _queued, 0) == 1;
        }

        private bool SetWorking()
        {
            return Interlocked.Exchange(ref _working, 1) == 0;
        }

        private bool UnsetWorking()
        {
            return Interlocked.Exchange(ref _working, 0) == 1;
        }

        private Task FinishAsync(TaskCompletionSource<object> tcs)
        {
            return tcs.Task.ContinueWith(task =>
            {
                UnsetWorking();

                if (task.IsFaulted)
                {
                    return TaskAsyncHelper.FromError(task.Exception);
                }

                return TaskAsyncHelper.Empty;
            }).FastUnwrap();
        }

        private void WorkImpl(TaskCompletionSource<object> taskCompletionSource)
        {
        Process:
            if (!Alive)
            {
                // If this subscription is dead then return immediately
                taskCompletionSource.TrySetResult(null);
                return;
            }

            int totalCount = 0;
            string nextCursor = null;
            var items = new List<ArraySegment<Message>>();
            object state = null;

            PerformWork(ref items, out nextCursor, ref totalCount, out state);

            if (Alive && items.Count > 0)
            {
                BeforeInvoke(state);

                var messageResult = new MessageResult(items, nextCursor, totalCount);
                Task<bool> callbackTask = Invoke(messageResult);

                if (callbackTask.IsCompleted)
                {
                    try
                    {
                        // Make sure exceptions propagate
                        callbackTask.Wait();

                        if (callbackTask.Result)
                        {
                            // Sync path
                            goto Process;
                        }
                        else
                        {
                            // If we're done pumping messages through to this subscription
                            // then dispose
                            Dispose();

                            // If the callback said it's done then stop
                            taskCompletionSource.TrySetResult(null);
                        }
                    }
                    catch (Exception ex)
                    {
                        taskCompletionSource.TrySetException(ex);
                    }
                }
                else
                {
                    WorkImplAsync(callbackTask, taskCompletionSource);
                }
            }
            else
            {
                taskCompletionSource.TrySetResult(null);
            }
        }

        protected virtual void BeforeInvoke(object state)
        {
        }

        protected abstract void PerformWork(ref List<ArraySegment<Message>> items, out string nextCursor, ref int totalCount, out object state);

        private void WorkImplAsync(Task<bool> callbackTask, TaskCompletionSource<object> taskCompletionSource)
        {
            // Async path
            callbackTask.ContinueWith(task =>
            {
                if (task.IsFaulted)
                {
                    taskCompletionSource.TrySetException(task.Exception);
                }
                else if (task.Result)
                {
                    WorkImpl(taskCompletionSource);
                }
                else
                {
                    // If we're done pumping messages through to this subscription
                    // then dispose
                    Dispose();

                    // If the callback said it's done then stop
                    taskCompletionSource.TrySetResult(null);
                }
            });
        }

        public virtual bool AddEvent(string key, Topic topic)
        {
            lock (EventKeys)
            {
                return EventKeys.Add(key);
            }
        }

        public virtual void RemoveEvent(string key)
        {
            lock (EventKeys)
            {
                EventKeys.Remove(key);
            }
        }

        public virtual void SetEventTopic(string key, Topic topic)
        {
            lock (EventKeys)
            {
                EventKeys.Add(key);
            }
        }

        public void Dispose()
        {
            // REVIEW: Should we make this block if there's pending work
            Interlocked.Exchange(ref _disposed, 1);

            _subsCurrentCounter.SafeDecrement();
            _subsPerSecCounter.SafeDecrement();
        }

        public abstract string GetCursor();

        public override int GetHashCode()
        {
            return Identity.GetHashCode();
        }

        public override bool Equals(object obj)
        {
            return Identity.Equals(((Subscription)obj).Identity);
        }
    }
}


text:
package com.quartzodev.buddybook;

import android.app.Activity;
import android.app.SearchManager;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.OpenableColumns;
import android.provider.SearchRecentSuggestions;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.crashlytics.android.Crashlytics;
import com.crashlytics.android.answers.Answers;
import com.firebase.ui.auth.AuthUI;
import com.firebase.ui.auth.ErrorCodes;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.common.api.CommonStatusCodes;
import com.google.android.gms.vision.barcode.Barcode;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.tabs.TabLayout;
import com.google.firebase.FirebaseApp;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.gson.Gson;
import com.mikepenz.aboutlibraries.Libs;
import com.mikepenz.aboutlibraries.LibsBuilder;
import com.quartzodev.data.Book;
import com.quartzodev.data.FirebaseDatabaseHelper;
import com.quartzodev.data.Folder;
import com.quartzodev.data.User;
import com.quartzodev.fragments.BookGridFragment;
import com.quartzodev.fragments.DetailActivityFragment;
import com.quartzodev.fragments.FolderListFragment;
import com.quartzodev.fragments.SearchResultFragment;
import com.quartzodev.fragments.ViewPagerFragment;
import com.quartzodev.provider.SuggestionProvider;
import com.quartzodev.ui.BarcodeCaptureActivity;
import com.quartzodev.utils.ConnectionUtils;
import com.quartzodev.utils.Constants;
import com.quartzodev.utils.DialogUtils;
import com.quartzodev.utils.ExportCSVUtil;
import com.quartzodev.utils.PathUtils;
import com.quartzodev.views.DynamicImageView;
import com.quartzodev.widgets.BuddyBookWidgetProvider;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.appcompat.widget.ShareActionProvider;
import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.app.ActivityOptionsCompat;
import androidx.core.view.GravityCompat;
import androidx.core.view.MenuItemCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import butterknife.BindView;
import butterknife.ButterKnife;
import hotchemi.android.rate.AppRate;
import hotchemi.android.rate.OnClickButtonListener;
import io.fabric.sdk.android.Fabric;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener,
        FolderListFragment.OnListFragmentInteractionListener,
        BookGridFragment.OnGridFragmentInteractionListener,
        SearchView.OnQueryTextListener,
        FirebaseDatabaseHelper.OnPaidOperationListener,
        DetailActivityFragment.OnDetailInteractionListener {

    private static final String TAG = MainActivity.class.getSimpleName();

    private static final int RC_BARCODE_CAPTURE = 2;
    private static final int RC_SIGN_IN = 5;
    private static final int RC_PICKFILE = 6;
    private static final int RC_INSERT_BOOK = 7;

    public static final String EXTRA_USER_ID = "userId";
    private static final String KEY_PARCELABLE_USER = "userKey";
    private static final String KEY_FOLDER_ID = "folderIdKey";
    private static final String KEY_CURRENT_QUERY = "queryKey";
    private static final String KEY_FLAG_SEARCH_OPEN = "flagSearchOpenKey";
    private static final int TOTAL_SEARCH_RESULT = 40;

    private final int NO_INTERNET = 1;
    private final int LOADING = 2;
    private final int READY = 3;

    @BindView(R.id.main_coordinator)
    CoordinatorLayout mCoordinatorLayout;
    @BindView(R.id.nav_view)
    NavigationView mNavigationView;
    @BindView(R.id.drawer_layout)
    DrawerLayout mDrawer;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.toolbar2)
    @Nullable
    Toolbar mToolbar2;
    @BindView(R.id.main_message)
    TextView mTextViewMessage;
    @BindView(R.id.fragment_main_container)
    FrameLayout mFrameLayoutContainer;
    @BindView(R.id.loading_container)
    RelativeLayout mLoadingContainer;
    @BindView(R.id.fab)
    FloatingActionButton mFab;
    @BindView(R.id.tabs)
    TabLayout mTabLayout;
    @BindView(R.id.main_progress_bar)
    ProgressBar mProgressBar;

    private User mUser;
    private Context mContext;

    //Authentication entities
    private FirebaseAuth mFirebaseAuth;
    private FirebaseDatabaseHelper mFirebaseDatabaseHelper;

    private String mFolderId;
    private String mFolderName;
    private SearchView mSearchView;
    private MenuItem mSearchItem;
    private String mCurrQuery;
    private boolean mFlagSeachBarOpen;
    private List<Folder> mFolderList;
    private String mFolderListComma;
    private SearchRecentSuggestions mSuggestions;
    private boolean mTwoPane;
    private Snackbar mSnackbarNoInternet;
    private SharedPreferences mPrefs;
    private LinearLayout mTabLinearLayoutLeft;
    private LinearLayout mTabLinearLayoutRight;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Fabric.with(this, new Crashlytics(), new Answers());

        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        setSupportActionBar(mToolbar);

        if (findViewById(R.id.detail_container) != null) {
            mTwoPane = true;
        }

        mContext = this;
        mPrefs = PreferenceManager.getDefaultSharedPreferences(this);

        //Auth
        FirebaseApp.initializeApp(getApplicationContext());
        mFirebaseAuth = FirebaseAuth.getInstance();
        mFirebaseDatabaseHelper = FirebaseDatabaseHelper.getInstance();
        mNavigationView.setNavigationItemSelectedListener(this);

        ActionBarDrawerToggle mActionBarDrawerToggle = new ActionBarDrawerToggle(
                this, mDrawer, mToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        mDrawer.addDrawerListener(mActionBarDrawerToggle);
        mActionBarDrawerToggle.syncState();

        mSuggestions = new SearchRecentSuggestions(this,
                SuggestionProvider.AUTHORITY, SuggestionProvider.MODE);

        if (savedInstanceState != null) {
            mUser = (User) savedInstanceState.get(KEY_PARCELABLE_USER);
            mFolderId = savedInstanceState.getString(KEY_FOLDER_ID);
        }

        setupFab();

        if (BuildConfig.FLAVOR.equals(Constants.FLAVOR_FREE)) initAdView();

        checkUserIsLoged();
    }

    private void checkUserIsLoged() {

        if (mFirebaseAuth.getCurrentUser() != null) {
            onSignedIn(mFirebaseAuth.getCurrentUser());
        } else {
            if (ConnectionUtils.isNetworkConnected(getApplication())) {
                launchLoginActivityResult();
            } else {
                showStatus(NO_INTERNET, null);
            }
        }
    }

    public void setupFab() {
        if (ConnectionUtils.isNetworkConnected(getApplication()) || FirebaseAuth.getInstance().getCurrentUser() != null) {
            mFab.show();
            mFab.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    // launch barcode activity.
                    Intent intent = new Intent(mContext, BarcodeCaptureActivity.class);
                    intent.putExtra(BarcodeCaptureActivity.AutoFocus, true); //Automatic focus
                    intent.putExtra(BarcodeCaptureActivity.UseFlash, false); //Flash false

                    startActivityForResult(intent, RC_BARCODE_CAPTURE);

                }
            });
        }
    }

    public FloatingActionButton getFab() {
        return mFab;
    }

    private void initAdView() {
        //Ad main
        AdView mAdView = findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);
    }

    public void onSignedIn(final FirebaseUser firebaseUser) {

        if (mUser == null || mUser.getUid().equals(firebaseUser.getUid())) {

            mUser = User.setupUserFirstTime(firebaseUser, mContext);

            mFirebaseDatabaseHelper.fetchUserById(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    updateUser(dataSnapshot);
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
        }
    }

    private void updateUser(DataSnapshot dataSnapshot) {

        if (mUser != null) {

            if (dataSnapshot.getValue() != null) {

                mFirebaseDatabaseHelper.updateUserLastActivity();
                loadFolderListFragment();
                Snackbar.make(mCoordinatorLayout, getText(R.string.success_sign_in), Snackbar.LENGTH_SHORT).show();

            } else {

                mFirebaseDatabaseHelper.insertUser(mUser, new DatabaseReference.CompletionListener() {
                    @Override
                    public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {

                        if (databaseError == null) {
                            mFirebaseDatabaseHelper.insertDefaulFolder(
                                    mContext.getResources().getString(R.string.tab_my_books), new DatabaseReference.CompletionListener() {
                                        @Override
                                        public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
                                            Snackbar.make(mCoordinatorLayout, getText(R.string.success_sign_in), Snackbar.LENGTH_SHORT).show();
                                            loadFolderListFragment();
                                        }
                                    });
                        }

                    }
                });

            }
        }
    }

    public void updateWidget() {
        Intent intent = new Intent(this, BuddyBookWidgetProvider.class);
        intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
        // Use an array and EXTRA_APPWIDGET_IDS instead of AppWidgetManager.EXTRA_APPWIDGET_ID,
        // since it seems the onUpdate() is only fired on that:
        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
        int appWidgetIds[] = appWidgetManager
                .getAppWidgetIds(new ComponentName(mContext, BuddyBookWidgetProvider.class));

        intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);

        sendBroadcast(intent);
    }

    public void doNothing(View view) {

    }

    private void loadProfileOnDrawer() {

        if (mUser != null) {

            LinearLayout linearLayout = (LinearLayout) mNavigationView.getHeaderView(0); //LinearLayout Index
            ImageView mImageViewProfile = linearLayout.findViewById(R.id.main_imageview_user_photo);
            TextView mTextViewUsername = linearLayout.findViewById(R.id.main_textview_username);
            TextView mTextViewTextEmail = linearLayout.findViewById(R.id.main_textview_user_email);

            mTextViewTextEmail.setText(mUser.getEmail());
            mTextViewUsername.setText(mUser.getUsername());

            GlideApp.with(this)
                    .load(mUser.getPhotoUrl())
                    .apply(RequestOptions.circleCropTransform())
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(mImageViewProfile);

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RC_SIGN_IN) {

            if (resultCode == ErrorCodes.UNKNOWN_ERROR) {
                AuthUI.getInstance().signOut(this);
            }

            if (resultCode == ErrorCodes.NO_NETWORK) {

                showStatus(NO_INTERNET, null);

            } else {
                checkUserIsLoged();
            }

        } else if (requestCode == RC_BARCODE_CAPTURE && resultCode == CommonStatusCodes.SUCCESS) {

            if (data != null) {

                Barcode barcode = data.getParcelableExtra(BarcodeCaptureActivity.BarcodeObject);

                Fragment searchFragment = SearchResultFragment.newInstance(null, barcode.displayValue, R.menu.menu_search_result);

                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                transaction.replace(R.id.fragment_main_container, searchFragment).commitAllowingStateLoss();

            }
        } else if (requestCode == RC_PICKFILE && resultCode == CommonStatusCodes.SUCCESS_CACHE) {
            Log.d(TAG, data.getDataString());

            try {

                Uri uri = data.getData();
                String mimeType = getContentResolver().getType(uri);

                Cursor returnCursor =
                        getContentResolver().query(uri, null, null, null, null);

                int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
                returnCursor.moveToFirst();

                Log.d(TAG, "mimeType: " + mimeType);
                Log.d(TAG, "nameView: " + returnCursor.getString(nameIndex));
                Log.d(TAG, "sizeView: " + returnCursor.getLong(sizeIndex));

                File file = new File(PathUtils.getPath(mContext, uri));

                Log.d(TAG, "File path: " + PathUtils.getPath(mContext, uri));
                Log.d(TAG, "File absolute path: " + PathUtils.getPath(mContext, uri));
                Log.d(TAG, "File exists? : " + file.exists());

            } catch (Exception e) {
                e.printStackTrace();
                Log.e(TAG, e.getMessage());
            }

        }
    }

    public void showStatus(int statusCode, String msg) {

        switch (statusCode) {
            case NO_INTERNET:

                mTextViewMessage.setVisibility(View.VISIBLE);
                mFrameLayoutContainer.setVisibility(View.GONE);
                mTextViewMessage.setText(getString(R.string.no_internet));

                mLoadingContainer.setVisibility(View.GONE);
                mFab.hide();
                mProgressBar.setVisibility(View.GONE);
                mDrawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
                mToolbar.setVisibility(View.GONE);
                //mTabLayout.setVisibility(View.GONE);

                final DatabaseReference connectedRef = FirebaseDatabase.getInstance().getReference(".info/connected");
                connectedRef.addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot snapshot) {
                        boolean connected = snapshot.getValue(Boolean.class);
                        if (connected) {
                            connectedRef.removeEventListener(this);
                            checkUserIsLoged();
                        }
                    }

                    @Override
                    public void onCancelled(DatabaseError error) {
                    }
                });

                break;
            case LOADING:

                mFrameLayoutContainer.setVisibility(View.GONE);

                mLoadingContainer.setVisibility(View.VISIBLE);
                mProgressBar.setVisibility(View.VISIBLE);
                mTextViewMessage.setVisibility(View.VISIBLE);
                mTextViewMessage.setText(msg);

                mFab.hide();
                mDrawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
                mToolbar.setVisibility(View.GONE);

                break;
            case READY:

                mTextViewMessage.setVisibility(View.GONE);
                mProgressBar.setVisibility(View.GONE);
                mFrameLayoutContainer.setVisibility(View.VISIBLE);
                mLoadingContainer.setVisibility(View.GONE);

                mFab.show();
                mDrawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
                mToolbar.setVisibility(View.VISIBLE);

                break;
        }

    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        if (savedInstanceState.containsKey(KEY_PARCELABLE_USER)) {
            mUser = (User) savedInstanceState.get(KEY_PARCELABLE_USER);
        }

        if (savedInstanceState.containsKey(KEY_FLAG_SEARCH_OPEN)) {
            mCurrQuery = savedInstanceState.getString(KEY_CURRENT_QUERY);
            mFlagSeachBarOpen = savedInstanceState.getBoolean(KEY_FLAG_SEARCH_OPEN);
        }

        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putParcelable(KEY_PARCELABLE_USER, mUser);
        outState.putString(KEY_FOLDER_ID, mFolderId);

        if (mSearchView != null && mSearchView.isEnabled()) {
            outState.putCharSequence(KEY_CURRENT_QUERY, mSearchView.getQuery().toString());
            outState.putBoolean(KEY_FLAG_SEARCH_OPEN, mSearchView.isShown());

        }
    }

    private void launchLoginActivityResult() {

        startActivityForResult(
                AuthUI.getInstance()
                        .createSignInIntentBuilder()
                        .setTheme(R.style.LoginTheme)
                        .setIsSmartLockEnabled(false)
                        .setAvailableProviders(
                                Arrays.asList(new AuthUI.IdpConfig.EmailBuilder().build(),
                                        new AuthUI.IdpConfig.GoogleBuilder().build()))
                        .build(),
                RC_SIGN_IN);

        overridePendingTransition(R.anim.fui_slide_in_right, R.anim.fui_slide_in_right);

    }

    @Override
    public void onBackPressed() {
        if (mDrawer.isDrawerOpen(GravityCompat.START)) {
            mDrawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    private void handleIntent(Intent intent) {

        if (intent.getAction() != null && intent.getAction().equals(Intent.ACTION_SEARCH)) {
            String query = intent.getStringExtra(SearchManager.QUERY);

            mSuggestions.saveRecentQuery(query, null);
            mSearchView.clearFocus();
            mSearchView.setQuery(query, true);
        }

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        handleIntent(intent);
    }

    public void setIntentShareMenu(Intent intent) {

        if (mToolbar2 != null) {
            MenuItem menushareItem = mToolbar2.getMenu().findItem(R.id.action_share);
            ShareActionProvider mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(menushareItem);
            menushareItem.setVisible(true);
            mShareActionProvider.setShareIntent(intent);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        if (mToolbar2 == null) {

            if (BuildConfig.FLAVOR.equals(Constants.FLAVOR_FREE)) {
                getMenuInflater().inflate(R.menu.main, menu);
            } else {
                getMenuInflater().inflate(R.menu.main_paid, menu);
            }

        } else {
            if (!mToolbar.getMenu().hasVisibleItems())
                mToolbar.inflateMenu(R.menu.main_toolbar1);

            if (!mToolbar2.getMenu().hasVisibleItems()) {
                if (BuildConfig.FLAVOR.equals(Constants.FLAVOR_FREE)) {
                    mToolbar2.inflateMenu(R.menu.main_toolbar2);
                } else {
                    mToolbar2.inflateMenu(R.menu.main_toolbar2_paid);
                }
            }
        }

        // Retrieve the SearchView and plug it into SearchManager
        //final SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
        mSearchItem = menu.findItem(R.id.action_search);
        mSearchView = (SearchView) MenuItemCompat.getActionView(mSearchItem);

        mSearchView.setOnSuggestionListener(new SearchView.OnSuggestionListener() {
            @Override
            public boolean onSuggestionSelect(int position) {

                return false;
            }

            @Override
            public boolean onSuggestionClick(int position) {

                return false;
            }
        });

        if (mFlagSeachBarOpen) {
            mSearchItem.expandActionView();
            mSearchView.setQuery(mCurrQuery, true);
            mSearchView.clearFocus();
        }

        SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);

        mSearchView.setOnQueryTextListener(this);

        mSearchView.setOnCloseListener(new SearchView.OnCloseListener() {
            @Override
            public boolean onClose() {
                return false;
            }
        });

        final String search_tag = "SEARCH_TAG";

        mSearchItem.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
            @Override
            public boolean onMenuItemActionExpand(MenuItem menuItem) {

                if (!ConnectionUtils.isNetworkConnected(mContext)) {
                    mSnackbarNoInternet = Snackbar.make(mCoordinatorLayout, R.string.no_internet_search, Snackbar.LENGTH_INDEFINITE);
                    mSnackbarNoInternet.show();
                }

                ViewPagerFragment fragment = ViewPagerFragment.newInstance(ViewPagerFragment.SEARCH_VIEW_PAGER, mFolderId, null, null);
                loadFragment(fragment, search_tag);

                return true;
            }

            @Override
            public boolean onMenuItemActionCollapse(MenuItem menuItem) {
                removeFragment(search_tag);

                if (mSnackbarNoInternet != null && mSnackbarNoInternet.isShown()) {
                    mSnackbarNoInternet.dismiss();
                }

                return true;
            }
        });

        ComponentName componentName = new ComponentName(mContext, MainActivity.class);

        mSearchView.setSearchableInfo(searchManager.getSearchableInfo(componentName));

        return true;

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        switch (id) {

            case R.id.action_sign_out:
                mUser = null;
                AuthUI.getInstance().signOut(this);
                clearFragmentBackStack();
                launchLoginActivityResult();

                return true;

            case R.id.action_clear_search:
                mSuggestions.clearHistory();
                Snackbar.make(mCoordinatorLayout, getString(R.string.search_clear), Snackbar.LENGTH_LONG).show();
                return true;

            case R.id.action_add_book:

                lauchInsertEditActivity(null);

                break;

            case R.id.action_about:
                new LibsBuilder()
                        .withActivityStyle(Libs.ActivityStyle.LIGHT_DARK_TOOLBAR)
                        .withAboutIconShown(true)
                        .withAboutVersionShown(true)
                        .start(this);
                break;
            case R.id.action_to_premium:

                DialogUtils.alertDialogUpgradePro(this);

                break;
            case R.id.action_sort:

                DialogUtils.alertDialogSortList(mContext, mCoordinatorLayout);

                break;
            case R.id.action_export_csv:

                showStatus(LOADING, getString(R.string.generating_csv));

                FirebaseDatabaseHelper.getInstance().findBookSearch(mFolderId, new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {

                        showStatus(READY, null);

                        List<Book> bookList = new ArrayList<>();

                        for (DataSnapshot child : dataSnapshot.getChildren()) {
                            Book book = child.getValue(Book.class);
                            bookList.add(book);
                        }

                        try {
                            ExportCSVUtil.writeWithCsvMapWriter(mFolderName == null ? getString(R.string.tab_my_books) : mFolderName, bookList, (Activity) mContext);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {
                        showStatus(READY, null);
                    }
                });

                break;
            default:
                break;
        }

        return super.onOptionsItemSelected(item);
    }

    public void lauchInsertEditActivity(String bookId) {

        Intent it = new Intent(mContext, com.quartzodev.inserteditbook.InsertEditBookActivity.class);

        if (bookId != null)
            it.putExtra(InsertEditBookActivity.ARG_BOOK_ID, bookId);

        it.putExtra(InsertEditBookActivity.ARG_FOLDER_NAME, mFolderName);
        it.putExtra(InsertEditBookActivity.ARG_FOLDER_ID, mFolderId);
        it.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivityForResult(it, RC_INSERT_BOOK);

    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void onLongClickListenerFolderListInteraction(final Folder folder) {

        DialogUtils.alertDialogDeleteFolder(mContext, folder, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mFirebaseDatabaseHelper.deleteFolder(folder.getId());
                onClickListenerFolderListInteraction(null);
                Snackbar.make(mCoordinatorLayout, getText(R.string.folder_deleted), Snackbar.LENGTH_SHORT).show();
            }
        });

    }

    @Override
    public void onClickListenerFolderListInteraction(Folder folder) {

        mDrawer.closeDrawer(GravityCompat.START);
        mFolderId = folder != null ? folder.getId() : null;
        if (mFolderId == null) {

            mToolbar.findViewById(R.id.toolbar_container).setVisibility(View.VISIBLE);
            mFolderName = getString(R.string.tab_my_books);
            loadMainViewPagerFragment();
            loadFragment(ViewPagerFragment.newInstance(ViewPagerFragment.MAIN_VIEW_PAGER,
                    mFolderId, null, null), null);

        } else {

            mToolbar.findViewById(R.id.toolbar_container).setVisibility(View.GONE);
            mFolderName = folder.getDescription();
            mToolbar.setTitle(mFolderName);

            if (folder.getBooks() != null) {
                mToolbar.setSubtitle(String.format(getString(R.string.number_of_books), folder.getBooks().size()));
            } else {
                mToolbar.setSubtitle(String.format(getString(R.string.number_of_books), 0));
            }

            loadFragment(BookGridFragment.newInstance(mFolderId, R.menu.menu_my_books), null);
        }
    }

    @Override
    public void onClickAddFolderListInteraction() {
        DialogUtils.alertDialogAddFolder(this,
                mFolderList,
                FirebaseDatabaseHelper.getInstance());
    }

    private void clearFragmentBackStack() {
        FragmentManager fm = getSupportFragmentManager();
        for (int i = 0; i < fm.getBackStackEntryCount(); ++i) {
            fm.popBackStack();
        }
    }

    //Comes first
    private void loadFolderListFragment() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.container_nav_header, new FolderListFragment());
        transaction.commitAllowingStateLoss();
    }

    //Second step
    private void loadApplication() {
        loadProfileOnDrawer();
        updateWidget();
        loadMainViewPagerFragment();
        setupRateApp();
        showStatus(READY, null);
    }

    public void setupRateApp() {
        AppRate.with(this)
                .setInstallDays(0) // default 10, 0 means install day.
                .setLaunchTimes(3) // default 10
                .setRemindInterval(2) // default 1
                .setShowLaterButton(true) // default true
                .setDebug(false) // default false
                .setOnClickButtonListener(new OnClickButtonListener() { // callback listener.
                    @Override
                    public void onClickButton(int which) {
                        Log.d(MainActivity.class.getName(), Integer.toString(which));
                    }
                })
                .monitor();

        // Show a dialog if meets conditions
        AppRate.showRateDialogIfMeetsConditions(this);
    }

    private void loadMainViewPagerFragment() {
        Fragment frag = getSupportFragmentManager().findFragmentById(R.id.fragment_main_container);

        if (frag == null) {
            loadFragment(ViewPagerFragment.newInstance(ViewPagerFragment.MAIN_VIEW_PAGER,
                    mFolderId, null, null), null);
        }
    }

    private void loadFragment(Fragment fragment, String tag) {

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        if (tag != null) {
            transaction.add(R.id.fragment_main_container, fragment, tag);
        } else {
            transaction.replace(R.id.fragment_main_container, fragment);
        }

        transaction.commitNow();
        checkTabLayout();
    }

    private void removeFragment(String tag) {
        Fragment fragment = getSupportFragmentManager().findFragmentByTag(tag);

        if (fragment != null) {
            getSupportFragmentManager().beginTransaction().remove(fragment).commitNow();
        }

        checkTabLayout();
    }

    public void checkTabLayout() {
        Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.fragment_main_container);

        if (currentFragment instanceof ViewPagerFragment) {
            mTabLayout.setVisibility(View.VISIBLE);
            mTabLayout.setupWithViewPager(((ViewPagerFragment) currentFragment).getViewPager());
            setupTabIcons(((ViewPagerFragment) currentFragment).getTypeFragment());
        } else {
            mTabLayout.setVisibility(View.GONE);
        }
    }

    //Gets fired when FolderListFragment is done
    @Override
    public void onFolderListIsAvailable(List<Folder> folderList, String folderListComma) {
        mFolderList = folderList;
        mFolderListComma = folderListComma;

        loadApplication();
    }

    @Override
    public void onClickListenerBookGridInteraction(String folderId, Book book, DynamicImageView imageView) {

        if (mTwoPane) {

            Gson gson = new Gson();
            DetailActivityFragment newFragment = DetailActivityFragment.newInstance(mUser.getUid(), book.getId(), folderId, mFolderListComma, gson.toJson(book));

            getSupportFragmentManager().popBackStackImmediate();
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.detail_container, newFragment).commitAllowingStateLoss();

        } else {

            Intent it = new Intent(this, DetailActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString(DetailActivity.ARG_BOOK_ID, book.getId());
            bundle.putString(DetailActivity.ARG_FOLDER_ID, folderId);
            bundle.putString(DetailActivity.ARG_USER_ID, mUser.getUid());
            bundle.putString(DetailActivity.ARG_FOLDER_LIST_ID, mFolderListComma);

            Gson gson = new Gson();
            bundle.putString(DetailActivity.ARG_BOOK_JSON, gson.toJson(book));

            it.putExtras(bundle);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                startActivity(it, ActivityOptionsCompat.makeSceneTransitionAnimation(MainActivity.this, imageView, imageView.getTransitionName()).toBundle());
            } else {
                startActivity(it);
            }

        }
    }

    private void showToolbar() {
        if (mToolbar.getParent() instanceof AppBarLayout) {
            ((AppBarLayout) mToolbar.getParent()).setExpanded(true, true);
        }
    }

    @Override
    public void onDeleteBookClickListener(final String mFolderId, final Book book) {

        mFirebaseDatabaseHelper.deleteBookFolder(mFolderId, book);

        showToolbar();

        Snackbar.make(mCoordinatorLayout, getString(R.string.book_deleted), Snackbar.LENGTH_LONG)
                .setAction(getString(R.string.redo), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mFirebaseDatabaseHelper.insertBookFolder(mFolderId, book, (MainActivity) mContext);
                    }
                }).show();
    }

    @Override
    public void onAddBookToFolderClickListener(final String folderId, final Book book) {

        DialogUtils.alertDialogListFolder(mContext, mFolderListComma, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                String unFormatted = mFolderListComma.split(",")[which];
                final String id = unFormatted.split("=")[1];
                String name = unFormatted.split("=")[0];

                Snackbar.make(mCoordinatorLayout, String.format(getString(R.string.added_to_folder), name), Snackbar.LENGTH_LONG)
                        .setAction(getString(R.string.redo), new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (!id.equals(folderId)) {
                                    mFirebaseDatabaseHelper.insertBookFolder(folderId, book, (MainActivity) mContext);
                                    mFirebaseDatabaseHelper.deleteBookFolder(id, book);
                                }
                            }
                        }).show();

                if (!id.equals(folderId)) {
                    mFirebaseDatabaseHelper.insertBookFolder(id, book, (MainActivity) mContext);
                    mFirebaseDatabaseHelper.deleteBookFolder(folderId, book);
                }

            }
        });
    }

    @Override
    public void onCopyBookToFolderClickListener(final String folderId, final Book book) {

        DialogUtils.alertDialogListFolder(mContext, mFolderListComma, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                String unFormatted = mFolderListComma.split(",")[which];
                final String id = unFormatted.split("=")[1];
                String name = unFormatted.split("=")[0];

                Snackbar.make(mCoordinatorLayout, String.format(getString(R.string.copied_to_folder), name), Snackbar.LENGTH_LONG)
                        .show();

                mFirebaseDatabaseHelper.insertBookFolder(id, book, (MainActivity) mContext);

            }
        });

    }

    @Override
    public void onLendBookClickListener(Book book, MenuItem menuItem) {
        DialogUtils.alertDialogLendBook(this, mCoordinatorLayout, mFirebaseDatabaseHelper, mUser.getUid(), mFolderId, book, menuItem);
    }

    @Override
    public void onReturnBookClickListener(Book book) {
        DialogUtils.alertDialogReturnBook(this, mFirebaseDatabaseHelper, mUser.getUid(), mFolderId, book);
    }

    @Override
    public void onEditListener(Book book) {
        lauchInsertEditActivity(book.getId());
    }

    @Override
    public boolean onQueryTextSubmit(String query) {

        if (query != null && !query.isEmpty()) {

            mSuggestions.saveRecentQuery(query, null);

            Fragment frag = getSupportFragmentManager().findFragmentById(R.id.fragment_main_container);

            if (frag instanceof ViewPagerFragment) {
                ((ViewPagerFragment) frag).executeSearch(query, TOTAL_SEARCH_RESULT);
            }

            mSearchView.clearFocus();
        }

        return true;

    }

    public void refreshCurrentFragment() {
        Fragment frag = getSupportFragmentManager().findFragmentById(R.id.fragment_main_container);

        if (frag instanceof BookGridFragment) {
            ((BookGridFragment) frag).refresh();
        } else if (frag instanceof ViewPagerFragment) {
            ((ViewPagerFragment) frag).refresh();
        }
    }

    @Override
    public boolean onQueryTextChange(String newText) {

        if (newText != null && !newText.isEmpty()) {
            Fragment frag = getSupportFragmentManager().findFragmentById(R.id.fragment_main_container);
            if (frag instanceof ViewPagerFragment) {
                ((ViewPagerFragment) frag).executeSearch(newText, TOTAL_SEARCH_RESULT);
            }

        }

        return false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        mPrefs.registerOnSharedPreferenceChangeListener(listener);
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();
    }

    /**
     * Makes sure to unregister the BroadcastReceiver when this activity is destroyed
     */
    @Override
    protected void onPause() {
        super.onPause();
        mPrefs.unregisterOnSharedPreferenceChangeListener(listener);
    }

    SharedPreferences.OnSharedPreferenceChangeListener listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
        public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
            if (key != null && !key.equals("com.facebook.appevents.SessionInfo.sessionEndTime")) {
                refreshCurrentFragment();
            }
        }
    };

    @Override
    public void onInsertBook(boolean success) {
        if (!success) {
            DialogUtils.alertDialogUpgradePro(this);
        }
    }

    @Override
    public void onInsertFolder(boolean success) {

        if (!success) {
            DialogUtils.alertDialogUpgradePro(this);
        }
    }

    public TabLayout getTabLayout() {
        return mTabLayout;
    }

    public void setupTabIcons(String typeFragment) {

        TabLayout.Tab tab1 = mTabLayout.getTabAt(0);
        TabLayout.Tab tab2 = mTabLayout.getTabAt(1);

        if (tab1 == null || mTabLinearLayoutLeft == null) {
            mTabLinearLayoutLeft = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
        }

        if (tab2 == null || mTabLinearLayoutRight == null) {
            mTabLinearLayoutRight = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
        }

        if (typeFragment.equals(ViewPagerFragment.MAIN_VIEW_PAGER)) {
            ((ImageView) mTabLinearLayoutLeft.findViewById(R.id.tab_icon)).setImageResource(R.drawable.ic_favorite_border);
            ((TextView) mTabLinearLayoutLeft.findViewById(R.id.tab_title)).setText(getString(R.string.tab_my_books));
        } else {
            ((ImageView) mTabLinearLayoutLeft.findViewById(R.id.tab_icon)).setImageResource(R.drawable.ic_action_globe);
            ((TextView) mTabLinearLayoutLeft.findViewById(R.id.tab_title)).setText(getString(R.string.tab_search_online));
        }

        mTabLayout.getTabAt(0).setCustomView(mTabLinearLayoutLeft);

        if (typeFragment.equals(ViewPagerFragment.MAIN_VIEW_PAGER)) {
            ((ImageView) mTabLinearLayoutRight.findViewById(R.id.tab_icon)).setImageResource(R.drawable.ic_library_books);
            ((TextView) mTabLinearLayoutRight.findViewById(R.id.tab_title)).setText(getString(R.string.tab_top_books));
        } else {
            ((ImageView) mTabLinearLayoutRight.findViewById(R.id.tab_icon)).setImageResource(R.drawable.ic_action_folder_closed);
            if (mFolderName != null) {
                ((TextView) mTabLinearLayoutRight.findViewById(R.id.tab_title)).setText(mFolderName);
            } else {
                ((TextView) mTabLinearLayoutRight.findViewById(R.id.tab_title)).setText(getString(R.string.tab_my_books));
            }
        }

        mTabLayout.getTabAt(1).setCustomView(mTabLinearLayoutRight);
    }

    @Override
    public void onLendBook(Book bookApi) {
        DialogUtils.alertDialogLendBook(this, mCoordinatorLayout, mFirebaseDatabaseHelper, mUser.getUid(), mFolderId, bookApi, null);
    }

    @Override
    public void onReturnBook(Book bookApi) {
        DialogUtils.alertDialogReturnBook(this, mFirebaseDatabaseHelper, mUser.getUid(), mFolderId, bookApi);
    }

}