text:
/**
 * @file
 * Declares the integer type.
 */
#pragma once

#include <boost/functional/hash.hpp>
#include <boost/variant.hpp>
#include <limits>
#include <cstdint>
#include <ostream>
#include <functional>

namespace puppet { namespace runtime { namespace types {

    /**
     * Represents the Puppet Integer[from, to] type.
     */
    struct integer
    {
        /**
         * Constructs an integer type.
         * @param from The "from" type parameter.
         * @param to The "to" type parameter.
         */
        explicit integer(int64_t from = std::numeric_limits<int64_t>::min(), int64_t to = std::numeric_limits<int64_t>::max());

        /**
         * Gets the "from" type parameter.
         * @return Returns the "from" type parameter.
         */
        int64_t from() const;

        /**
         * Gets the "to" type parameter.
         * @return Returns the "to" type parameter.
         */
        int64_t to() const;

        /**
         * Gets the name of the type.
         * @return Returns the name of the type (i.e. Integer).
         */
        static const char* name();

        /**
         * Determines if the range is enumerable.
         * @return Returns whether or not the range is enumerable.
         */
        bool enumerable() const;

        /**
         * Calls the given callback for each integer in the range.
         * @param callback The callback to call.
         */
        void each(std::function<bool(int64_t, int64_t)> const& callback) const;

        /**
         * Determines if the given value is an instance of this type.
         * @tparam Value The type of the runtime value.
         * @param value The value to determine if it is an instance of this type. This value will never be a variable.
         * @return Returns true if the given value is an instance of this type or false if not.
         */
        template <typename Value>
        bool is_instance(Value const& value) const
        {
            auto ptr = boost::get<int64_t>(&value);
            if (!ptr) {
                return false;
            }
            return _to < _from ? (*ptr >= _to && *ptr <= _from) : (*ptr >= _from && *ptr <= _to);
        }

        /**
         * Determines if the given type is a specialization (i.e. more specific) of this type.
         * @tparam Type The type of runtime type.
         * @param other The other type to check for specialization.
         * @return Returns true if the other type is a specialization or false if not.
         */
        template <typename Type>
        bool is_specialization(Type const& other) const
        {
            // Check for an Integer with a range inside of this type's range
            auto ptr = boost::get<integer>(&other);
            if (!ptr) {
                return false;
            }
            // Check for equality
            if (ptr->from() == _from && ptr->to() == _to) {
                return false;
            }
            return std::min(ptr->from(), ptr->to()) >= std::min(_from, _to) &&
                   std::max(ptr->from(), ptr->to()) <= std::max(_from, _to);
        }

     private:
        int64_t _from;
        int64_t _to;
    };

    /**
     * Stream insertion operator for integer type.
     * @param os The output stream to write the type to.
     * @param type The type to write.
     * @return Returns the given output stream.
     */
    std::ostream& operator<<(std::ostream& os, integer const& type);

    /**
     * Equality operator for integer.
     * @param left The left type to compare.
     * @param right The right type to compare.
     * @return Returns true if the two types are equal or false if not.
     */
    bool operator==(integer const& left, integer const& right);

}}}  // puppet::runtime::types

namespace boost {
    /**
     * Hash specialization for Integer type.
     */
    template <>
    struct hash<puppet::runtime::types::integer>
    {
        /**
         * Hashes the Integer type.
         * @param type The type to hash.
         * @return Returns the hash value for the type.
         */
        size_t operator()(puppet::runtime::types::integer const& type) const
        {
            size_t seed = 0;
            hash_combine(seed, puppet::runtime::types::integer::name());
            hash_combine(seed, type.from());
            hash_combine(seed, type.to());
            return seed;
        }
    };
}


text:
<?php

namespace Agile\NimbleBoardBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Sprint
 *
 * @ORM\Table(name="sprints")
 * @ORM\Entity
 */
class Sprint
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var integer
     *
     * @Assert\NotBlank(message="sprint.number.not_blank")
     * @ORM\Column(name="number", type="integer")
     */
    private $number;

    /**
     * @var integer
     *
     * @Assert\NotBlank(message="sprint.week.not_blank")
     * @Assert\Range(min="1", max="52")
     * @ORM\Column(name="week", type="integer")
     */
    private $week;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="createdAt", type="datetime")
     */
    private $createdAt;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="updatedAt", type="datetime")
     */
    private $updatedAt;

    /**
     * @var Project $project
     *
     * @ORM\ManyToOne(targetEntity="Project", inversedBy="sprints")
     */
    private $project;

    /**
     * @var $stories
     *
     * @ORM\OneToMany(targetEntity="Story", mappedBy="sprint")
     */
    private $stories;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set number
     *
     * @param integer $number
     * @return Sprint
     */
    public function setNumber($number)
    {
        $this->number = $number;

        return $this;
    }

    /**
     * Get number
     *
     * @return integer
     */
    public function getNumber()
    {
        return $this->number;
    }

    /**
     * Set week
     *
     * @param integer $week
     * @return Sprint
     */
    public function setWeek($week)
    {
        $this->week = $week;

        return $this;
    }

    /**
     * Get week
     *
     * @return integer
     */
    public function getWeek()
    {
        return $this->week;
    }

    /**
     * Set createdAt
     *
     * @param \DateTime $createdAt
     * @return Sprint
     */
    public function setCreatedAt($createdAt)
    {
        $this->createdAt = $createdAt;

        return $this;
    }

    /**
     * Get createdAt
     *
     * @return \DateTime
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * Set updatedAt
     *
     * @param \DateTime $updatedAt
     * @return Sprint
     */
    public function setUpdatedAt($updatedAt)
    {
        $this->updatedAt = $updatedAt;

        return $this;
    }

    /**
     * Get updatedAt
     *
     * @return \DateTime
     */
    public function getUpdatedAt()
    {
        return $this->updatedAt;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.deidentifier.arx.framework.check.groupify;

import org.deidentifier.arx.framework.check.distribution.Distribution;

/**
 * Implements an equivalence class.
 *
 * @author Fabian Prasser
 * @author Florian Kohlmayer
 */
public class HashGroupifyEntry {

    /** The number of elements in this class. Excluding elements from the public table.*/
    public int               count        = 0;

    /** The number of elements in this class. Including elements from the public table */
    public int               pcount       = 0;

    /** The hashcode of this class. */
    public final int         hashcode;

    /** The key of this class. */
    public final int[]       key;

    /** The next element in this bucket. */
    public HashGroupifyEntry next         = null;

    /** The overall next element in original order. */
    public HashGroupifyEntry nextOrdered  = null;

    /** The index of the representative row. */
    public int               representative = -1;

    /** Is this class not an outlier?. */
    public boolean           isNotOutlier = false;

    /** Frequency set for other attributes *. */
    public Distribution[]    distributions;

    /**
     * Creates a new entry.
     *
     * @param key
     *            the key
     * @param hash
     *            the hash
     */
    public HashGroupifyEntry(final int[] key, final int hash) {
        hashcode = hash;
        this.key = key;
    }
}


text:
describe('A test module', function() {
  it('should work', function() {
    expect(1).toBe(1);
  });
});


text:
require 'bundler/setup'
require 'minitest/spec'
require 'minitest/autorun'
require 'active_record'
require 'active_record/deprecated_finders'

ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')

ActiveRecord::Schema.verbose = false
ActiveRecord::Schema.define do
  create_table :posts do |t|
    t.string :title
    t.string :category
  end

  create_table :comments do |t|
    t.string :title
    t.references :post
  end

  create_table :appointments do |t|
    t.integer :physician_id
    t.integer :patient_id
    t.string :week_day
    t.string :status
  end

  create_table :physicians do |t|
    t.string :name
  end

  create_table :patients do |t|
    t.string :name
  end
end

class Post < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  def self.lol
    "lol"
  end
end

class Appointment < ActiveRecord::Base
  belongs_to :physician
  belongs_to :patient
end

class Patient < ActiveRecord::Base
  def self.find_by_custom_name
    []
  end
end

class Physician < ActiveRecord::Base
  has_many :appointments
  has_many :patients, through: :appointments
end

require 'active_support/testing/deprecation'
ActiveSupport::Deprecation.debug = true

class MiniTest::Spec
  include ActiveSupport::Testing::Deprecation
end


text:
var gulp = require('gulp');
var paths = require('../paths');
var browserSync = require('browser-sync');
var fs = require('fs');

// outputs changes to files to the console
function reportChange(event){
  console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
}

// this task wil watch for changes
// to js, html, and css files and call the
// reportChange method. Also, by depending on the
// serve task, it will instantiate a browserSync session
var tsConfig = JSON.parse(fs.readFileSync(paths.tsConfig, 'utf8'));
gulp.task('watch', ['serve'], function() {
  gulp.watch(tsConfig.include, ['build-ts', browserSync.reload]).on('change', reportChange);
  gulp.watch(paths.source, ['build-system', browserSync.reload]).on('change', reportChange);
  gulp.watch(paths.html, ['build-html', browserSync.reload]).on('change', reportChange);
  gulp.watch(paths.style, browserSync.reload).on('change', reportChange);
});


text:
/*************************************************************************/
/*  navigation_obstacle_2d.h                                             */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#ifndef NAVIGATION_OBSTACLE_2D_H
#define NAVIGATION_OBSTACLE_2D_H

#include "scene/main/node.h"

class Navigation2D;

class NavigationObstacle2D : public Node {
	GDCLASS(NavigationObstacle2D, Node);

	Navigation2D *navigation = nullptr;

	RID agent;

protected:
	static void _bind_methods();
	void _notification(int p_what);

public:
	NavigationObstacle2D();
	virtual ~NavigationObstacle2D();

	void set_navigation(Navigation2D *p_nav);
	const Navigation2D *get_navigation() const {
		return navigation;
	}

	void set_navigation_node(Node *p_nav);
	Node *get_navigation_node() const;

	RID get_rid() const {
		return agent;
	}

	virtual String get_configuration_warning() const override;

private:
	void update_agent_shape();
};

#endif


text:
package at.ac.tuwien.service.impl.semantic.simple;

import java.util.Set;

/**
 * provides natural language processing services like POS tagging, Chunking and tokenizing
 */
@FunctionalInterface
interface NLPService {

    /**
     * Returns all chunks of natural language units
     * which are good for lookup
     *
     * @param term with phrase to process
     * @return a list of all suitable candidates for lookup
     */
    Set<String> getCandidates(String term);

}


text:
.class public final Landroid/service/voice/VoiceInteractionSession$Insets;
.super Ljava/lang/Object;
.source "VoiceInteractionSession.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/service/voice/VoiceInteractionSession;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x19
    name = "Insets"
.end annotation

# static fields
.field public static final TOUCHABLE_INSETS_CONTENT:I = 0x1

.field public static final TOUCHABLE_INSETS_FRAME:I = 0x0

.field public static final TOUCHABLE_INSETS_REGION:I = 0x3

# instance fields
.field public final contentInsets:Landroid/graphics/Rect;

.field public touchableInsets:I

.field public final touchableRegion:Landroid/graphics/Region;

# direct methods
.method public constructor <init>()V
    .locals 1

    .prologue
    .line 866
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 875
    new-instance v0, Landroid/graphics/Rect;

    invoke-direct {v0}, Landroid/graphics/Rect;-><init>()V

    iput-object v0, p0, Landroid/service/voice/VoiceInteractionSession$Insets;->contentInsets:Landroid/graphics/Rect;

    .line 882
    new-instance v0, Landroid/graphics/Region;

    invoke-direct {v0}, Landroid/graphics/Region;-><init>()V

    iput-object v0, p0, Landroid/service/voice/VoiceInteractionSession$Insets;->touchableRegion:Landroid/graphics/Region;

    .line 866
    return-void
.end method


text:
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.ui;

import android.os.Bundle;
import android.os.CancellationSignal;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;

import org.chromium.base.ApiCompatibilityUtils;
import org.chromium.base.Callback;
import org.chromium.base.CallbackController;
import org.chromium.base.TraceEvent;
import org.chromium.base.metrics.RecordUserAction;
import org.chromium.base.supplier.ObservableSupplier;
import org.chromium.base.supplier.ObservableSupplierImpl;
import org.chromium.base.supplier.Supplier;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.ActivityTabProvider;
import org.chromium.chrome.browser.ChromeActionModeHandler;
import org.chromium.chrome.browser.ChromeActivity;
import org.chromium.chrome.browser.TabThemeColorProvider;
import org.chromium.chrome.browser.bookmarks.BookmarkBridge;
import org.chromium.chrome.browser.compositor.bottombar.OverlayPanel;
import org.chromium.chrome.browser.compositor.bottombar.OverlayPanelManager;
import org.chromium.chrome.browser.compositor.layouts.EmptyOverviewModeObserver;
import org.chromium.chrome.browser.compositor.layouts.LayoutManager;
import org.chromium.chrome.browser.compositor.layouts.OverviewModeBehavior;
import org.chromium.chrome.browser.directactions.DirectActionInitializer;
import org.chromium.chrome.browser.feature_engagement.TrackerFactory;
import org.chromium.chrome.browser.findinpage.FindToolbarManager;
import org.chromium.chrome.browser.findinpage.FindToolbarObserver;
import org.chromium.chrome.browser.flags.ActivityType;
import org.chromium.chrome.browser.identity_disc.IdentityDiscController;
import org.chromium.chrome.browser.lifecycle.Destroyable;
import org.chromium.chrome.browser.lifecycle.InflationObserver;
import org.chromium.chrome.browser.metrics.UkmRecorder;
import org.chromium.chrome.browser.omnibox.geo.GeolocationHeader;
import org.chromium.chrome.browser.paint_preview.PaintPreviewTabHelper;
import org.chromium.chrome.browser.profiles.Profile;
import org.chromium.chrome.browser.search_engines.TemplateUrlServiceFactory;
import org.chromium.chrome.browser.share.ShareButtonController;
import org.chromium.chrome.browser.share.ShareDelegate;
import org.chromium.chrome.browser.share.ShareUtils;
import org.chromium.chrome.browser.tab.AccessibilityVisibilityHandler;
import org.chromium.chrome.browser.tab.Tab;
import org.chromium.chrome.browser.tab.TabLaunchType;
import org.chromium.chrome.browser.tabmodel.TabModelSelector;
import org.chromium.chrome.browser.toolbar.ButtonDataProvider;
import org.chromium.chrome.browser.toolbar.ToolbarManager;
import org.chromium.chrome.browser.toolbar.top.ToolbarActionModeCallback;
import org.chromium.chrome.browser.toolbar.top.ToolbarControlContainer;
import org.chromium.chrome.browser.ui.appmenu.AppMenuBlocker;
import org.chromium.chrome.browser.ui.appmenu.AppMenuCoordinator;
import org.chromium.chrome.browser.ui.appmenu.AppMenuCoordinatorFactory;
import org.chromium.chrome.browser.ui.messages.snackbar.SnackbarManager;
import org.chromium.chrome.browser.ui.system.StatusBarColorController;
import org.chromium.chrome.browser.vr.VrModuleProvider;
import org.chromium.chrome.browser.widget.ScrimView;
import org.chromium.chrome.browser.widget.bottomsheet.BottomSheetController;
import org.chromium.components.browser_ui.widget.MenuOrKeyboardActionController;
import org.chromium.components.browser_ui.widget.scrim.ScrimCoordinator;
import org.chromium.components.feature_engagement.EventConstants;
import org.chromium.content_public.browser.ActionModeCallbackHelper;
import org.chromium.content_public.browser.LoadUrlParams;
import org.chromium.ui.base.DeviceFormFactor;
import org.chromium.ui.base.PageTransition;
import org.chromium.ui.modaldialog.ModalDialogManager.ModalDialogManagerObserver;
import org.chromium.ui.modelutil.PropertyModel;
import org.chromium.ui.vr.VrModeObserver;

import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

/**
 * The root UI coordinator. This class will eventually be responsible for inflating and managing
 * lifecycle of the main UI components.
 *
 * The specific things this component will manage and how it will hook into Chrome*Activity are
 * still being discussed See https://crbug.com/931496.
 */
public class RootUiCoordinator
        implements Destroyable, InflationObserver,
                   MenuOrKeyboardActionController.MenuOrKeyboardActionHandler, AppMenuBlocker {
    protected ChromeActivity mActivity;
    protected @Nullable AppMenuCoordinator mAppMenuCoordinator;
    private final MenuOrKeyboardActionController mMenuOrKeyboardActionController;
    private final TabObscuringHandler mTabObscuringHandler;
    private final AccessibilityVisibilityHandler mAccessibilityVisibilityHandler;

    private ActivityTabProvider mActivityTabProvider;
    private ObservableSupplier<ShareDelegate> mShareDelegateSupplier;

    protected @Nullable FindToolbarManager mFindToolbarManager;
    private @Nullable FindToolbarObserver mFindToolbarObserver;

    private Callback<LayoutManager> mLayoutManagerSupplierCallback;
    private OverlayPanelManager mOverlayPanelManager;
    private OverlayPanelManager.OverlayPanelManagerObserver mOverlayPanelManagerObserver;

    private Callback<OverviewModeBehavior> mOverviewModeBehaviorSupplierCallback;
    private OverviewModeBehavior mOverviewModeBehavior;
    private OverviewModeBehavior.OverviewModeObserver mOverviewModeObserver;

    /** A means of providing the theme color to different features. */
    private TabThemeColorProvider mTabThemeColorProvider;
    @Nullable
    private Callback<Boolean> mOnOmniboxFocusChangedListener;
    protected ToolbarManager mToolbarManager;
    protected Supplier<Boolean> mCanAnimateBrowserControls;
    private ModalDialogManagerObserver mModalDialogManagerObserver;

    private VrModeObserver mVrModeObserver;

    private BottomSheetManager mBottomSheetManager;
    private BottomSheetController mBottomSheetController;
    private SnackbarManager mBottomSheetSnackbarManager;

    private ScrimView mScrimView;
    private ScrimCoordinator mScrimCoordinator;
    private DirectActionInitializer mDirectActionInitializer;
    private List<ButtonDataProvider> mButtonDataProviders;
    private IdentityDiscController mIdentityDiscController;
    private ChromeActionModeHandler mChromeActionModeHandler;
    private ToolbarActionModeCallback mActionModeControllerCallback;
    private ObservableSupplierImpl<Boolean> mOmniboxFocusStateSupplier =
            new ObservableSupplierImpl<>();
    protected final ObservableSupplier<Profile> mProfileSupplier;
    private final ObservableSupplier<BookmarkBridge> mBookmarkBridgeSupplier;
    protected final CallbackController mCallbackController;

    /**
     * Create a new {@link RootUiCoordinator} for the given activity.
     * @param activity The containing {@link ChromeActivity}. TODO(https://crbug.com/931496):
     *         Remove this in favor of passing in direct dependencies.
     * @param onOmniboxFocusChangedListener Callback<Boolean> callback to invoke when Omnibox focus
     *         changes.
     * @param shareDelegateSupplier Supplies {@link ShareDelegate} object.
     * @param tabProvider The {@link ActivityTabProvider} to get current tab of the activity.
     * @param profileSupplier Supplier of the currently applicable profile.
     * @param bookmarkBridgeSupplier Supplier of the bookmark bridge for the current profile.
     */
    public RootUiCoordinator(ChromeActivity activity,
            @Nullable Callback<Boolean> onOmniboxFocusChangedListener,
            ObservableSupplier<ShareDelegate> shareDelegateSupplier,
            ActivityTabProvider tabProvider, ObservableSupplier<Profile> profileSupplier,
            ObservableSupplier<BookmarkBridge> bookmarkBridgeSupplier) {
        mCallbackController = new CallbackController();
        mActivity = activity;
        mOnOmniboxFocusChangedListener = onOmniboxFocusChangedListener;
        mActivity.getLifecycleDispatcher().register(this);

        mMenuOrKeyboardActionController = mActivity.getMenuOrKeyboardActionController();
        mMenuOrKeyboardActionController.registerMenuOrKeyboardActionHandler(this);
        mActivityTabProvider = tabProvider;

        mLayoutManagerSupplierCallback = this::onLayoutManagerAvailable;
        mActivity.getLayoutManagerSupplier().addObserver(mLayoutManagerSupplierCallback);

        mShareDelegateSupplier = shareDelegateSupplier;
        mTabObscuringHandler = new TabObscuringHandler();
        mAccessibilityVisibilityHandler = new AccessibilityVisibilityHandler(
                activity.getLifecycleDispatcher(), mActivityTabProvider, mTabObscuringHandler);
        mProfileSupplier = profileSupplier;
        mBookmarkBridgeSupplier = bookmarkBridgeSupplier;

        mOmniboxFocusStateSupplier.set(false);

        initOverviewModeSupplierObserver();
    }

    // TODO(pnoland, crbug.com/865801): remove this in favor of wiring it directly.
    public ToolbarManager getToolbarManager() {
        return mToolbarManager;
    }

    @Override
    public void destroy() {
        mCallbackController.destroy();
        mMenuOrKeyboardActionController.unregisterMenuOrKeyboardActionHandler(this);

        mActivity.getLayoutManagerSupplier().removeObserver(mLayoutManagerSupplierCallback);

        if (mOverlayPanelManager != null) {
            mOverlayPanelManager.removeObserver(mOverlayPanelManagerObserver);
        }

        if (mActivity.getOverviewModeBehaviorSupplier() != null) {
            mActivity.getOverviewModeBehaviorSupplier().removeObserver(
                    mOverviewModeBehaviorSupplierCallback);
        }
        if (mOverviewModeBehavior != null) {
            mOverviewModeBehavior.removeOverviewModeObserver(mOverviewModeObserver);
        }
        if (mToolbarManager != null) {
            mToolbarManager.destroy();
            mToolbarManager = null;
        }
        if (mAppMenuCoordinator != null) {
            mAppMenuCoordinator.unregisterAppMenuBlocker(this);
            mAppMenuCoordinator.unregisterAppMenuBlocker(mActivity);
            mAppMenuCoordinator.destroy();
        }

        if (mTabThemeColorProvider != null) {
            mTabThemeColorProvider.destroy();
            mTabThemeColorProvider = null;
        }

        if (mFindToolbarManager != null) mFindToolbarManager.removeObserver(mFindToolbarObserver);

        if (mVrModeObserver != null) VrModuleProvider.unregisterVrModeObserver(mVrModeObserver);

        if (mModalDialogManagerObserver != null && mActivity.getModalDialogManager() != null) {
            mActivity.getModalDialogManager().removeObserver(mModalDialogManagerObserver);
        }

        if (mBottomSheetManager != null) mBottomSheetManager.destroy();
        if (mBottomSheetController != null) mBottomSheetController.destroy();

        if (mButtonDataProviders != null) {
            for (ButtonDataProvider provider : mButtonDataProviders) {
                provider.destroy();
            }

            mButtonDataProviders = null;
        }

        if (mScrimCoordinator != null) mScrimCoordinator.destroy();
        mScrimCoordinator = null;

        mActivity = null;
    }

    @Override
    public void onPreInflationStartup() {
        initializeBottomSheetController();
    }

    @Override
    public void onPostInflationStartup() {
        ViewGroup coordinator = mActivity.findViewById(R.id.coordinator);
        StatusBarColorController statusBarColorController = mActivity.getStatusBarColorController();
        mScrimView = new ScrimView(mActivity,
                statusBarColorController.getStatusBarScrimDelegate(), coordinator);
        mScrimCoordinator = new ScrimCoordinator(mActivity,
                (fraction) -> statusBarColorController
                        .getStatusBarScrimDelegate()
                        .setStatusBarScrimFraction(fraction),
                coordinator,
                ApiCompatibilityUtils.getColor(coordinator.getResources(),
                        R.color.omnibox_focused_fading_background_color));

        mTabThemeColorProvider = new TabThemeColorProvider(mActivity);
        mTabThemeColorProvider.setActivityTabProvider(mActivity.getActivityTabProvider());

        initFindToolbarManager();
        initializeToolbar();
        initAppMenu();
        initDirectActionInitializer();
        if (mAppMenuCoordinator != null) {
            mToolbarManager.onAppMenuInitialized(mAppMenuCoordinator);
            mModalDialogManagerObserver = new ModalDialogManagerObserver() {
                @Override
                public void onDialogShown(PropertyModel model) {
                    mAppMenuCoordinator.getAppMenuHandler().hideAppMenu();
                }

                @Override
                public void onDialogHidden(PropertyModel model) {}
            };
            mActivity.getModalDialogManager().addObserver(mModalDialogManagerObserver);
        }
        mChromeActionModeHandler = new ChromeActionModeHandler(mActivity.getActivityTabProvider(),
                mToolbarManager::onActionBarVisibilityChanged, (searchText) -> {
                    TabModelSelector selector = mActivity.getTabModelSelector();
                    if (selector == null) return;

                    String query = ActionModeCallbackHelper.sanitizeQuery(
                            searchText, ActionModeCallbackHelper.MAX_SEARCH_QUERY_LENGTH);
                    if (TextUtils.isEmpty(query)) return;

                    Tab tab = mActivity.getActivityTabProvider().get();
                    TrackerFactory
                            .getTrackerForProfile(Profile.fromWebContents(tab.getWebContents()))
                            .notifyEvent(EventConstants.WEB_SEARCH_PERFORMED);

                    selector.openNewTab(generateUrlParamsForSearch(tab, query),
                            TabLaunchType.FROM_LONGPRESS_FOREGROUND, tab, tab.isIncognito());
                });
        mVrModeObserver = new VrModeObserver() {
            @Override
            public void onEnterVr() {
                mFindToolbarManager.hideToolbar();
            }

            @Override
            public void onExitVr() {}
        };
        VrModuleProvider.registerVrModeObserver(mVrModeObserver);
    }

    /**
     * Generate the LoadUrlParams necessary to load the specified search query.
     */
    private static LoadUrlParams generateUrlParamsForSearch(Tab tab, String query) {
        String url = TemplateUrlServiceFactory.get().getUrlForSearchQuery(query);
        String headers = GeolocationHeader.getGeoHeader(url, tab);

        LoadUrlParams loadUrlParams = new LoadUrlParams(url);
        loadUrlParams.setVerbatimHeaders(headers);
        loadUrlParams.setTransitionType(PageTransition.GENERATED);
        return loadUrlParams;
    }

    /**
     * Triggered when the share menu item is selected.
     * This creates and shows a share intent picker dialog or starts a share intent directly.
     * @param shareDirectly Whether it should share directly with the activity that was most
     *                      recently used to share.
     * @param isIncognito Whether currentTab is incognito.
     */
    @VisibleForTesting
    public void onShareMenuItemSelected(final boolean shareDirectly, final boolean isIncognito) {
        ShareDelegate shareDelegate = mShareDelegateSupplier.get();
        Tab tab = mActivityTabProvider.get();

        if (shareDelegate == null || tab == null) return;

        shareDelegate.share(tab, shareDirectly);
    }

    // MenuOrKeyboardActionHandler implementation

    @Override
    public boolean handleMenuOrKeyboardAction(int id, boolean fromMenu) {
        if (id == R.id.show_menu && mAppMenuCoordinator != null) {
            mAppMenuCoordinator.showAppMenuForKeyboardEvent();
            return true;
        } else if (id == R.id.find_in_page_id) {
            if (mFindToolbarManager == null) return false;

            mFindToolbarManager.showToolbar();

            Tab tab = mActivityTabProvider.get();
            if (fromMenu) {
                RecordUserAction.record("MobileMenuFindInPage");
                new UkmRecorder.Bridge().recordEventWithBooleanMetric(
                        tab.getWebContents(), "MobileMenu.FindInPage", "HasOccurred");
            } else {
                RecordUserAction.record("MobileShortcutFindInPage");
            }
            return true;
        } else if (id == R.id.share_menu_id || id == R.id.direct_share_menu_id) {
            onShareMenuItemSelected(id == R.id.direct_share_menu_id,
                    mActivity.getTabModelSelector().isIncognitoSelected());
        } else if (id == R.id.paint_preview_show_id) {
            Tab tab = mActivityTabProvider.get();
            PaintPreviewTabHelper paintPreviewTabHelper = PaintPreviewTabHelper.get(tab);
            paintPreviewTabHelper.showPaintPreviewDemo();
        }

        return false;
    }

    // AppMenuBlocker implementation

    @Override
    public boolean canShowAppMenu() {
        // TODO(https:crbug.com/931496): Eventually the ContextualSearchManager,
        // EphemeralTabCoordinator, and FindToolbarManager will all be owned by this class.

        // Do not show the menu if Contextual Search panel is opened.
        if (mActivity.getContextualSearchManager() != null
                && mActivity.getContextualSearchManager().isSearchPanelOpened()) {
            return false;
        }

        // Do not show the menu if we are in find in page view.
        if (mFindToolbarManager != null && mFindToolbarManager.isShowing()
                && !DeviceFormFactor.isNonMultiDisplayContextOnTablet(mActivity)) {
            return false;
        }

        return true;
    }

    /**
     * Performs a direct action.
     *
     * @param actionId Name of the direct action to perform.
     * @param arguments Arguments for this action.
     * @param cancellationSignal Signal used to cancel a direct action from the caller.
     * @param callback Callback to run when the action is done.
     */
    public void onPerformDirectAction(String actionId, Bundle arguments,
            CancellationSignal cancellationSignal, Consumer<Bundle> callback) {
        if (mDirectActionInitializer == null) return;
        mDirectActionInitializer.onPerformDirectAction(
                actionId, arguments, cancellationSignal, callback);
    }

    /**
     * Lists direct actions supported.
     *
     * Returns a list of direct actions supported by the Activity associated with this
     * RootUiCoordinator.
     *
     * @param cancellationSignal Signal used to cancel a direct action from the caller.
     * @param callback Callback to run when the action is done.
     */
    public void onGetDirectActions(CancellationSignal cancellationSignal, Consumer callback) {
        if (mDirectActionInitializer == null) return;
        mDirectActionInitializer.onGetDirectActions(cancellationSignal, callback);
    }

    // Protected class methods

    protected void onLayoutManagerAvailable(LayoutManager layoutManager) {
        if (mOverlayPanelManager != null) {
            mOverlayPanelManager.removeObserver(mOverlayPanelManagerObserver);
        }
        mOverlayPanelManager = layoutManager.getOverlayPanelManager();

        if (mOverlayPanelManagerObserver == null) {
            mOverlayPanelManagerObserver = new OverlayPanelManager.OverlayPanelManagerObserver() {
                @Override
                public void onOverlayPanelShown() {
                    if (mFindToolbarManager != null) {
                        mFindToolbarManager.hideToolbar(false);
                    }
                }

                @Override
                public void onOverlayPanelHidden() {}
            };
        }

        mOverlayPanelManager.addObserver(mOverlayPanelManagerObserver);
    }

    /**
     * Constructs {@link ToolbarManager} and the handler necessary for controlling the menu on the
     * {@link Toolbar}.
     */
    protected void initializeToolbar() {
        try (TraceEvent te = TraceEvent.scoped("RootUiCoordinator.initializeToolbar")) {
            final View controlContainer = mActivity.findViewById(R.id.control_container);
            assert controlContainer != null;
            ToolbarControlContainer toolbarContainer = (ToolbarControlContainer) controlContainer;
            Callback<Boolean> urlFocusChangedCallback = hasFocus -> {
                if (mOnOmniboxFocusChangedListener != null) {
                    mOnOmniboxFocusChangedListener.onResult(hasFocus);
                }
                mOmniboxFocusStateSupplier.set(hasFocus);
            };

            ObservableSupplierImpl<Boolean> bottomToolbarVisibilitySupplier =
                    new ObservableSupplierImpl<>();
            bottomToolbarVisibilitySupplier.set(false);

            mIdentityDiscController = new IdentityDiscController(
                    mActivity, mActivity.getLifecycleDispatcher(), bottomToolbarVisibilitySupplier);
            ShareButtonController shareButtonController = new ShareButtonController(mActivity,
                    mActivityTabProvider, mShareDelegateSupplier, new ShareUtils(),
                    bottomToolbarVisibilitySupplier, mActivity.getLifecycleDispatcher());
            mButtonDataProviders = Arrays.asList(mIdentityDiscController, shareButtonController);
            mActionModeControllerCallback = new ToolbarActionModeCallback();
            mToolbarManager = new ToolbarManager(mActivity, mActivity.getFullscreenManager(),
                    toolbarContainer, mActivity.getCompositorViewHolder().getInvalidator(),
                    urlFocusChangedCallback, mTabThemeColorProvider, mTabObscuringHandler,
                    mShareDelegateSupplier, bottomToolbarVisibilitySupplier,
                    mIdentityDiscController, mButtonDataProviders, mActivityTabProvider,
                    mScrimCoordinator, mActionModeControllerCallback, mFindToolbarManager,
                    mProfileSupplier, mBookmarkBridgeSupplier, mCanAnimateBrowserControls);
            if (!mActivity.supportsAppMenu()) {
                mToolbarManager.getToolbar().disableMenuButton();
            }
        }
    }

    // Private class methods

    private void initOverviewModeSupplierObserver() {
        if (mActivity.getOverviewModeBehaviorSupplier() != null) {
            mOverviewModeBehaviorSupplierCallback = overviewModeBehavior -> {
                if (mOverviewModeBehavior != null) {
                    mOverviewModeBehavior.removeOverviewModeObserver(mOverviewModeObserver);
                }

                mOverviewModeBehavior = overviewModeBehavior;

                if (mOverviewModeObserver == null) {
                    mOverviewModeObserver = new EmptyOverviewModeObserver() {
                        @Override
                        public void onOverviewModeStartedShowing(boolean showToolbar) {
                            if (mFindToolbarManager != null) mFindToolbarManager.hideToolbar();
                            hideAppMenu();
                        }

                        @Override
                        public void onOverviewModeFinishedShowing() {
                            // Ideally we wouldn't allow the app menu to show while animating the
                            // overview mode. This is hard to track, however, because in some
                            // instances #onOverviewModeStartedShowing is called after
                            // #onOverviewModeFinishedShowing (see https://crbug.com/969047).
                            // Once that bug is fixed, we can remove this call to hide in favor of
                            // disallowing app menu shows during animation. Alternatively, we
                            // could expose a way to query whether an animation is in progress.
                            hideAppMenu();
                        }

                        @Override
                        public void onOverviewModeStartedHiding(
                                boolean showToolbar, boolean delayAnimation) {
                            hideAppMenu();
                        }

                        @Override
                        public void onOverviewModeFinishedHiding() {
                            hideAppMenu();
                        }
                    };
                }
                mOverviewModeBehavior.addOverviewModeObserver(mOverviewModeObserver);
            };
            mActivity.getOverviewModeBehaviorSupplier().addObserver(
                    mOverviewModeBehaviorSupplierCallback);
        }
    }

    private void initAppMenu() {
        // TODO(https://crbug.com/931496): Revisit this as part of the broader
        // discussion around activity-specific UI customizations.
        if (mActivity.supportsAppMenu()) {
            mAppMenuCoordinator = AppMenuCoordinatorFactory.createAppMenuCoordinator(mActivity,
                    mActivity.getLifecycleDispatcher(), mToolbarManager, mActivity,
                    mActivity.getWindow().getDecorView(),
                    mActivity.getWindow().getDecorView().findViewById(R.id.menu_anchor_stub));

            mAppMenuCoordinator.registerAppMenuBlocker(this);
            mAppMenuCoordinator.registerAppMenuBlocker(mActivity);
        }
    }

    private void hideAppMenu() {
        if (mAppMenuCoordinator != null) mAppMenuCoordinator.getAppMenuHandler().hideAppMenu();
    }

    private void initFindToolbarManager() {
        if (!mActivity.supportsFindInPage()) return;

        int stubId = R.id.find_toolbar_stub;
        if (DeviceFormFactor.isNonMultiDisplayContextOnTablet(mActivity)) {
            stubId = R.id.find_toolbar_tablet_stub;
        }
        mFindToolbarManager = new FindToolbarManager(mActivity.findViewById(stubId),
                mActivity.getTabModelSelector(), mActivity.getWindowAndroid(),
                mActionModeControllerCallback);

        mFindToolbarObserver = new FindToolbarObserver() {
            @Override
            public void onFindToolbarShown() {
                RootUiCoordinator.this.onFindToolbarShown();
            }

            @Override
            public void onFindToolbarHidden() {}
        };

        mFindToolbarManager.addObserver(mFindToolbarObserver);
    }

    /**
     * Called when the find in page toolbar is shown. Sub-classes may override to manage
     * cross-feature interaction, e.g. hide other features when this feature is shown.
     */
    protected void onFindToolbarShown() {
        if (mActivity.getContextualSearchManager() != null) {
            mActivity.getContextualSearchManager().hideContextualSearch(
                    OverlayPanel.StateChangeReason.UNKNOWN);
        }
    }

    /**
     * Initialize the {@link BottomSheetController}. The view for this component is not created
     * until content is requested in the sheet.
     */
    private void initializeBottomSheetController() {
        Supplier<View> sheetViewSupplier = () -> {
            ViewGroup coordinator = mActivity.findViewById(R.id.coordinator);
            mActivity.getLayoutInflater().inflate(R.layout.bottom_sheet, coordinator);

            View sheet = coordinator.findViewById(R.id.bottom_sheet);

            mBottomSheetSnackbarManager = new SnackbarManager(mActivity,
                    sheet.findViewById(R.id.bottom_sheet_snackbar_container),
                    mActivity.getWindowAndroid());

            return sheet;
        };

        Supplier<OverlayPanelManager> panelManagerSupplier = ()
                -> mActivity.getCompositorViewHolder().getLayoutManager().getOverlayPanelManager();

        mBottomSheetController =
                new BottomSheetController(mActivity.getLifecycleDispatcher(), mActivityTabProvider,
                        () -> mScrimCoordinator, sheetViewSupplier, panelManagerSupplier,
                        mActivity.getFullscreenManager(), mActivity.getWindow(),
                        mActivity.getWindowAndroid().getKeyboardDelegate(),
                        mOmniboxFocusStateSupplier);

        mBottomSheetManager = new BottomSheetManager(mBottomSheetController, mActivityTabProvider,
                mActivity::getModalDialogManager, this::getBottomSheetSnackbarManager,
                mTabObscuringHandler);
    }

    /**
     * TODO(jinsukkim): remove/hide this in favor of wiring it directly.
     * @return {@link TabObscuringHandler} object.
     */
    public TabObscuringHandler getTabObscuringHandler() {
        return mTabObscuringHandler;
    }

    /** @return The {@link BottomSheetController} for this activity. */
    public BottomSheetController getBottomSheetController() {
        return mBottomSheetController;
    }

    /** @return The root coordinator / activity's primary scrim. */
    public ScrimView getScrim() {
        return mScrimView;
    }

    /** @return The {@link SnackbarManager} for the {@link BottomSheetController}. */
    public SnackbarManager getBottomSheetSnackbarManager() {
        return mBottomSheetSnackbarManager;
    }

    private void initDirectActionInitializer() {
        @ActivityType
        int activityType = mActivity.getActivityType();
        TabModelSelector tabModelSelector = mActivity.getTabModelSelector();
        mDirectActionInitializer = new DirectActionInitializer(mActivity, activityType, mActivity,
                mActivity::onBackPressed, tabModelSelector, mFindToolbarManager,
                mActivity.getBottomSheetController(), mActivity.getFullscreenManager(),
                mActivity.getCompositorViewHolder(), mActivity.getActivityTabProvider(),
                mScrimView);
        mActivity.getLifecycleDispatcher().register(mDirectActionInitializer);
    }

    // Testing methods

    @VisibleForTesting
    public AppMenuCoordinator getAppMenuCoordinatorForTesting() {
        return mAppMenuCoordinator;
    }

    @VisibleForTesting
    public ScrimCoordinator getScrimCoordinatorForTesting() {
        return mScrimCoordinator;
    }
}


text:
require 'multi_json'

class PageToken
  class SavedSearch
    def self.parse(token, json)
      new(token, MultiJson.decode(json))
    end

    attr_reader :token, :limit, :order, :search, :last_id

    def initialize(token, attrs = {})
      @token   = token
      @limit   = attrs.fetch('limit')
      @order   = attrs.fetch('order').to_sym
      @search  = attrs.fetch('search')
      @last_id = attrs['last_id']
    end

    def asc?
      order == :asc
    end

    def desc?
      order == :desc
    end
  end
end


text:
package net.ucanaccess.jdbc;

import java.sql.SQLException;

public class InsertResultSet extends AbstractExecute {
	protected InsertResultSet(UcanaccessResultSet resultSet) {
		super(resultSet);
	}

	public void execute() throws SQLException {
		executeBase();
	}

	@Override
	public Object executeWrapped() throws SQLException {
    	super.getWrappedResultSet().insertRow();
		return true;
	}
}


text:
Some stream use cases may require retrying of requests after a failure response.  squbs provides a `Retry` Akka Streams
stage to add a retry capability to streams that need to add retries for any failing requests.

### Dependency

Add the following dependency to your `build.sbt` or scala build file:

```
"org.squbs" %% "squbs-ext" % squbsVersion
```

### Usage

The retry stage functionality is provided via a `BidiFlow` that can be connected to flows via the `join` operator.  The
retry `BidiFlow` will perform some specified maximum number of retries of any failures from downstream. A failure is
determined by either a passed in failure decider function or a Failure, if a failure decider function is not supplied.

If all the retried attempts fail then the last failure for that request is emitted.  The retry stage requires a
`Context` to be carried around for each element.  This is needed to _uniquely
identify_ each element.  Please see [Context to Unique Id
Mapping](#context-to-unique-id-mapping) section for more details.

##### Scala

```scala
val retry = Retry[String, String, Long](max = 10)
val flow = Flow[(String, Long)].map { case (s, ctx) => (findAnEnglishWordThatStartWith(s), ctx) }

Source("a" :: "b" :: "c" :: Nil)
  .zipWithIndex
  .via(retry.join(flow))
  .runWith(Sink.foreach(println))
```

##### Java

```java
final BidiFlow<Pair<String, Long>,
                Pair<String, Long>,
                Pair<Try<String>, Long>,
                Pair<Try<String>, Long>, NotUsed> retry = Retry.create(2);

final Flow<Pair<String, Long>, Pair<Try<String>, Long>, NotUsed> flow =
        Flow.<Pair<String, Long>>create()
                .map(p -> Pair.create(findAnEnglishWordThatStartsWith.apply(p.first()), p.second()));

Source.from(Arrays.asList("a", "b", "c"))
        .zipWithIndex()
        .via(retry.join(flow))
        .runWith(Sink.foreach(System.out::println), mat);
```

#### Context to Unique Id Mapping

The `Context` type itself might be used as a unique id.  However, in many scenarios, `Context` contains more than the
unique id itself or the unique id might be retrieved as a mapping from the `Context`.  squbs allows different options to
provide a unique id:

   * `Context` itself is a type that can be used as a unique id, e.g., `Int`, `Long`, `java.util.UUID`
   * `Context` extends `UniqueId.Provider` and implements `def uniqueId`
   * `Context` is wrapped with `UniqueId.Envelope`
   * `Context` is mapped to a unique id by calling a function

With the first three options, a unique id can be retrieved directly through the context.

For the last option, `Retry` allows a function to be passed in through `RetrySettings`.

###### Scala

```scala
case class MyContext(s: String, id: Long)

val settings =
  RetrySettings[String, String, MyContext](maxRetries = 3)
    .withUniqueIdMapper(context => context.id)

val retry = Retry(settings)
```

###### Java

```java
class MyContext {
    private String s;
    private long id;

    public MyContext(String s, long id) {
        this.s = s;
        this.id = id;
    }

    public long id() {
        return id;
    }
}

final RetrySettings settings =
        RetrySettings.<String, String, MyContext>create(3)
                .withUniqueIdMapper(ctx -> ctx.id());

final BidiFlow<Pair<String, MyContext>,
               Pair<String, MyContext>,
               Pair<Try<String>, MyContext>,
               Pair<Try<String>, MyContext>, NotUsed> retry = Retry.create(settings);
```

##### Important note

As mentioned earlier, a `RetryStage` uses the `Context` to identify elements that should be retried.  If the downstream
modifies the `Context` such that it can no longer be used to uniquely identify elements, the tracked elements will never
be removed, essentially becoming a memory leak.  Furthermore, those elements will never be retried, and it is likely the
flow will unable to materialize a value.  Consequently, it is **very** important to understand the concepts above and to
make sure the downstream does not adversely affect them.

#### Failure decider

By default, any `Failure` from the joined `Flow` is considered a failure for retry purposes.  However, the `Retry` stage
also accepts an optional `failureDecider` parameter, via `RetrySettings`, to more finely control what elements from the
joined `Flow` should actually be treated as failures that should be retried.

##### Scala

A function of type `Try[Out] => Boolean` can be provided to `RetrySettings` via the `withFailureDecider` call. Below is
an example where, along with any `Failure` message, a response with failing http status code is also considered a
failure:

```scala
val failureDecider = (tryResponse: Try[HttpResponse]) => tryResponse.isFailure || tryResponse.get.status.isFailure

val settings =
  RetrySettings[HttpRequest, HttpResponse, MyContext](max = 3)
    .withFailureDecider(failureDecider)

val retry = Retry(settings)

```

##### Java

A `Function<Try<Out>, Boolean>` can be provided to `RetrySettings` via the `withFailureDecider` call.  Below is an
example where, along with any `Failure` message, a `Success` of `HttpResponse` with status code `400` and above is also
considered a failure:

```java
final Function<Try<HttpResponse>, Boolean> failureDecider =
        tryResponse -> tryResponse.isFailure() || tryResponse.get().status().isFailure();

final RetrySettings settings =
        RetrySettings.<HttpRequest, HttpResponse, MyContext>create(1)
                .withFailureDecider(failureDecider);

final BidiFlow<Pair<HttpRequest, MyContext>,
               Pair<HttpRequest, MyContext>,
               Pair<Try<HttpResponse>, MyContext>,
               Pair<Try<HttpResponse>, MyContext>, NotUsed> retry = Retry.create(settings);

```

#### Retries with a delay duration

By default, any failures pulled from the joined `Flow` are immediately attempted to be retried.  However, the `Retry`
stage also accepts an optional delay `Duration` parameter to add a timed delay between each subsequent retry attempt.
This duration is the minimum delay duration from when a failure is pulled from the joined flow to when it is
re-attempted (pushed) again to the joined flow.  For example, to create a `Retry` stage that delays 200 milliseconds
during retries:

##### Scala

```scala
val settings = RetrySettings[String, String, Context](max = 3).withDelay(1 second)

val retry = Retry(settings)
```

##### Java

```java
final RetrySettings settings =
        RetrySettings.<String, String, Context>create(3)
                .withDelay(Duration.create("200 millis"));

final BidiFlow<Pair<String, Context>,
               Pair<String, Context>,
               Pair<Try<String>, Context>,
               Pair<Try<String>, Context>, NotUsed> retry = Retry.create(settings);

```

##### Exponential backoff
An optional exponential backoff factor can also be specified to increase the delay duration on each subsequent retry
attempt (up to a maximum delay duration).  In the following examples, the first failure of any element will be retried
after a delay of 200ms, and then any second attempt will be retried after 800ms.  In general the retry delay duration
will continue to increase using the formula `delay * N ^ exponentialBackOff` (where N is the retry number).

###### Scala

```scala
val settings =
  RetrySettings[String, String, Context](max = 3)
    .withDelay(200 millis)
    .withExponentialBackoff(2)

val retry = Retry(settings)
```

###### Java

```java
final RetrySettings settings =
        RetrySettings.create<String, String, Context>.create(3)
                .withDelay(Duration.create("200 millis"))
                .withExponentialBackoff(2.0);

final BidiFlow<Pair<String, Context>,
               Pair<String, Context>,
               Pair<Try<String>, Context>,
               Pair<Try<String>, Context>, NotUsed> retry = Retry.create(settings);

```

##### Maximum delay
An optional maximum delay duration can also be specified to provide an upper bound on the exponential backoff delay
duration.  If no maximum delay is specified the exponential backoff will continue to increase the retry delay duration
until the number of maxRetries.

###### Scala

```scala
val settings =
  RetrySettings[String, String, Context](max = 3)
    .withDelay(200 millis)
    .withExponentialBackoff(2)
    .withMaxDelay(400 millis)

val retry = Retry(settings)
```

###### Java

```java
final RetrySettings settings =
        RetrySettings.create<String, String, Context>.create(3)
                .withDelay(Duration.create("200 millis"))
                .withExponentialBackoff(2.0)
                withMaxDelay(Duration.create("400 millis"));

final BidiFlow<Pair<String, Context>,
               Pair<String, Context>,
               Pair<Try<String>, Context>,
               Pair<Try<String>, Context>, NotUsed> retry = Retry.create(settings);
```

##### Configuring the threshold for backpressure

If the joined flow keeps returning failures, `Retry` starts back pressuring when the elements waiting to be retried
reaches to a certain threshold.  By default, the threshold is equal to the internal buffer size of `Retry` Akka Stream
`GraphStage` (please see [Akka Stream
Attributes](https://doc.akka.io/docs/akka/current/stream/stream-composition.html#attributes)).  The threshold can be
made independent of internal buffer size by calling `withMaxWaitingRetries`:

##### Scala

```scala
val settings = RetrySettings[String, String, Context](max = 3).withMaxWaitingRetries(50)

val retry = Retry(settings)
```

##### Java

```java
final RetrySettings settings =
        RetrySettings.<String, String, Context>create(3)
                .withMaxWaitingRetries(50)

final BidiFlow<Pair<String, Context>,
               Pair<String, Context>,
               Pair<Try<String>, Context>,
               Pair<Try<String>, Context>, NotUsed> retry = Retry.create(settings);
```

#### Metrics

`Retry` supports Codahale counters for state and failure/success rate of elements passing through it.  Metrics can be
enabled by calling `withMetrics` with a name and an actor system.

The following counters are provided:

  * Count of all retry elements ("<name>.retry-count")
  * Count of all failed elements ("<name>.failed-count")
  * Count of all successful elements ("<name>.success-count")
  * Current size of the retry registry
  * Current size of the retry queue

##### Scala

```scala
val settings = RetrySettings[String, String, Context](max = 3)
  .withMetrics("myRetry") // Takes implicit ActorSystem

val retry = Retry(settings)
```

##### Java

```java
final RetrySettings settings =
        RetrySettings.<String, String, Context>create(3)
                .withMetrics("myRetry", system)

final BidiFlow<Pair<String, Context>,
               Pair<String, Context>,
               Pair<Try<String>, Context>,
               Pair<Try<String>, Context>, NotUsed> retry = Retry.create(settings);
```


text:
'''persistant storage of state data

We need some way to keep track of Tasks that are being worked on,
the state of items etc. It would be even cooler if that data was
to hang around when the process was gone.
'''

try: import pymongo
except: pass	# allow import where noone is using the MongoStore

import config
import random

class MongoStore(object):
	'''persistant mongodb store'''

	def __init__(self):
		self.connection = pymongo.Connection(config.mongodb_server,config.mongodb_port)
		self.db = self.connection[config.mongodb_database]
	def get_tasks(self):
		return [name for name in self.db.collection_names() if 'system.' not in name]
	def new_task(self, uuid, items, metadata=None):
		if metadata == None: metadata = {}
		metadata['uuid'] = uuid
		metadata['metadata'] = True
		self.db[uuid].create_index('name')
		self.db[uuid].create_index('metadata')
		self.db[uuid].insert(items)
		self.db[uuid].insert(metadata)
	def _noid(self, item):
		if item is None or '_id' not in item: return item
		del item['_id']
		return item
	def item(self, uuid, name):
		'''get a specific item for a task'''
		return self._noid( self.db[uuid].find_one({'name': name}) )
	def items(self, uuid):
		'''get all the items for a task'''
		# ALL THE THINGS!
		return [self._noid(item) for item in self.db[uuid].find({'name': {'$exists': True},'metadata': {'$exists': False}})]
	def metadata(self, uuid):
		'''get metadata for a task'''
		metadata = self.db[uuid].find_one({'metadata': {'$exists': True}})
		return self._noid(metadata)
	def update_item(self, uuid, name, updatedict, existingstate={}):
		'''updates an item similar to dict.update()

		if 'existingdict' is supplied, the update will only succeed if
		the items in existingdict match what is in the item already

		returns the contents of the item after the attempt is made.
		It is up to the caller to check if the update worked or failed.
		'''
		matchon = dict(existingstate)
		matchon['name'] = name
		self.db[uuid].update(matchon, {'$set': updatedict})
		return self.item(uuid, name)
	def update_metadata(self, uuid, updatedict, existingstate={}):
		'''updates a metadata similar to dict.update()

		if 'existingdict' is supplied, the update will only succeed if
		the items in existingdict match what is in the metadata already

		returns the contents of the metadata after the attempt is made.
		It is up to the caller to check if the update worked or failed.
		'''
		matchon = dict(existingstate)
		matchon['metadata'] = {'$exists': True}
		self.db[uuid].update(matchon, {'$set': updatedict})
		return self.metadata(uuid)
	def delete_task(self, uuid):
		'''delete a task, all it's items, and all it's metadata

		This is not recoverable.
		'''
		self.db[uuid].drop()

# Define the default Store here
Store = MongoStore


text:
@interface MOBProjectionEPSG4254 : MOBProjection

@end


text:
require "spec_helper"

RSpec.describe SpreeShopifyImporter::Connections::Shop, type: :model do
  subject { described_class }

  before { authenticate_with_shopify }

  describe "#call", vcr: { cassette_name: "shopify/shop/call" } do
    it "find shop settings in Shopify" do
      expect(subject.new.call.name).to eq "Spree Shopify Importer Test Store"
    end
  end
end


text:
#include "formatters/create_smartSchema.h"
namespace test {
namespace components {
namespace formatters {

using namespace ns_smart_device_link::ns_json_handler::strings;
using namespace ns_smart_device_link::ns_json_handler::formatters;
using namespace ns_smart_device_link::ns_smart_objects;

template <>
const EnumConversionHelper<FunctionIDTest::eType>::EnumToCStringMap
    EnumConversionHelper<test::components::formatters::FunctionIDTest::eType>::
        enum_to_cstring_map_ = EnumConversionHelper<
            test::components::formatters::FunctionIDTest::eType>::
            InitEnumToCStringMap();

template <>
const EnumConversionHelper<FunctionIDTest::eType>::CStringToEnumMap
    EnumConversionHelper<test::components::formatters::FunctionIDTest::eType>::
        cstring_to_enum_map_ = EnumConversionHelper<
            test::components::formatters::FunctionIDTest::eType>::
            InitCStringToEnumMap();

template <>
const char* const
    EnumConversionHelper<FunctionIDTest::eType>::cstring_values_[] = {
        "RegisterAppInterface",
        "UnregisterAppInterface",
        "SetGlobalProperties"};

template <>
const FunctionIDTest::eType
    EnumConversionHelper<FunctionIDTest::eType>::enum_values_[] = {
        test::components::formatters::FunctionIDTest::RegisterAppInterface,
        test::components::formatters::FunctionIDTest::UnregisterAppInterface,
        test::components::formatters::FunctionIDTest::SetGlobalProperties};

template <>
const EnumConversionHelper<Language::eType>::EnumToCStringMap
    EnumConversionHelper<
        test::components::formatters::Language::eType>::enum_to_cstring_map_ =
        EnumConversionHelper<test::components::formatters::Language::eType>::
            InitEnumToCStringMap();

template <>
const EnumConversionHelper<Language::eType>::CStringToEnumMap
    EnumConversionHelper<
        test::components::formatters::Language::eType>::cstring_to_enum_map_ =
        EnumConversionHelper<test::components::formatters::Language::eType>::
            InitCStringToEnumMap();

template <>
const char* const EnumConversionHelper<Language::eType>::cstring_values_[] = {
    "EN_EU", "RU_RU"};

template <>
const Language::eType EnumConversionHelper<Language::eType>::enum_values_[] = {
    test::components::formatters::Language::EN_EU,
    test::components::formatters::Language::RU_RU};

template <>
const EnumConversionHelper<SpeechCapabilities::eType>::EnumToCStringMap
    EnumConversionHelper<test::components::formatters::SpeechCapabilities::
                             eType>::enum_to_cstring_map_ =
        EnumConversionHelper<test::components::formatters::SpeechCapabilities::
                                 eType>::InitEnumToCStringMap();

template <>
const EnumConversionHelper<SpeechCapabilities::eType>::CStringToEnumMap
    EnumConversionHelper<test::components::formatters::SpeechCapabilities::
                             eType>::cstring_to_enum_map_ =
        EnumConversionHelper<test::components::formatters::SpeechCapabilities::
                                 eType>::InitCStringToEnumMap();

template <>
const char* const
    EnumConversionHelper<SpeechCapabilities::eType>::cstring_values_[] = {
        "SC_TEXT"};

template <>
const SpeechCapabilities::eType
    EnumConversionHelper<SpeechCapabilities::eType>::enum_values_[] = {
        test::components::formatters::SpeechCapabilities::SC_TEXT};

template <>
const EnumConversionHelper<AppTypeTest::eType>::EnumToCStringMap
    EnumConversionHelper<test::components::formatters::AppTypeTest::eType>::
        enum_to_cstring_map_ = EnumConversionHelper<
            test::components::formatters::AppTypeTest::eType>::
            InitEnumToCStringMap();

template <>
const EnumConversionHelper<AppTypeTest::eType>::CStringToEnumMap
    EnumConversionHelper<test::components::formatters::AppTypeTest::eType>::
        cstring_to_enum_map_ = EnumConversionHelper<
            test::components::formatters::AppTypeTest::eType>::
            InitCStringToEnumMap();

template <>
const char* const EnumConversionHelper<AppTypeTest::eType>::cstring_values_[] =
    {"SYSTEM", "MEDIA"};

template <>
const AppTypeTest::eType
    EnumConversionHelper<AppTypeTest::eType>::enum_values_[] = {
        test::components::formatters::AppTypeTest::SYSTEM,
        test::components::formatters::AppTypeTest::MEDIA,
};

#ifdef BUILD_TESTS
// cppcheck-suppress unusedFunction //Used in unit tests
CSmartSchema initObjectSchema() {
  std::set<TestType::eType> resultCode_allowedEnumSubsetValues;
  resultCode_allowedEnumSubsetValues.insert(
      TestType::APPLICATION_NOT_REGISTERED);
  resultCode_allowedEnumSubsetValues.insert(TestType::SUCCESS);
  resultCode_allowedEnumSubsetValues.insert(
      TestType::TOO_MANY_PENDING_REQUESTS);
  resultCode_allowedEnumSubsetValues.insert(TestType::REJECTED);
  resultCode_allowedEnumSubsetValues.insert(TestType::INVALID_DATA);
  resultCode_allowedEnumSubsetValues.insert(TestType::OUT_OF_MEMORY);
  resultCode_allowedEnumSubsetValues.insert(TestType::ABORTED);
  resultCode_allowedEnumSubsetValues.insert(TestType::USER_DISALLOWED);
  resultCode_allowedEnumSubsetValues.insert(TestType::GENERIC_ERROR);
  resultCode_allowedEnumSubsetValues.insert(TestType::DISALLOWED);

  // Possible functions in this test scheme
  std::set<FunctionIDTest::eType> functionId_allowedEnumSubsetValues;
  functionId_allowedEnumSubsetValues.insert(
      FunctionIDTest::RegisterAppInterface);
  functionId_allowedEnumSubsetValues.insert(
      FunctionIDTest::UnregisterAppInterface);
  functionId_allowedEnumSubsetValues.insert(
      FunctionIDTest::SetGlobalProperties);

  // Possible message types
  std::set<MessageTypeTest::eType> messageType_allowedEnumSubsetValues;
  messageType_allowedEnumSubsetValues.insert(MessageTypeTest::request);
  messageType_allowedEnumSubsetValues.insert(MessageTypeTest::response);
  messageType_allowedEnumSubsetValues.insert(MessageTypeTest::notification);

  // Create result item
  ISchemaItemPtr success_SchemaItem =
      CBoolSchemaItem::create(TSchemaItemParameter<bool>());
  ISchemaItemPtr resultCode_SchemaItem =
      TEnumSchemaItem<TestType::eType>::create(
          resultCode_allowedEnumSubsetValues,
          TSchemaItemParameter<TestType::eType>());

  // Create info value with min 0 length and max 1000
  ISchemaItemPtr info_SchemaItem =
      CStringSchemaItem::create(TSchemaItemParameter<size_t>(0),
                                TSchemaItemParameter<size_t>(1000),
                                TSchemaItemParameter<std::string>());

  ISchemaItemPtr tryAgainTime_SchemaItem =
      TNumberSchemaItem<int>::create(TSchemaItemParameter<int>(0),
                                     TSchemaItemParameter<int>(2000000000),
                                     TSchemaItemParameter<int>());

  // Map of parameters
  std::map<std::string, SMember> schemaMembersMap;

  schemaMembersMap["success"] = SMember(success_SchemaItem, false);
  schemaMembersMap["resultCode"] = SMember(resultCode_SchemaItem, false);
  schemaMembersMap["info"] = SMember(info_SchemaItem, false);
  schemaMembersMap["tryAgainTime"] = SMember(tryAgainTime_SchemaItem, false);

  std::map<std::string, SMember> paramsMembersMap;
  paramsMembersMap[S_FUNCTION_ID] =
      SMember(TEnumSchemaItem<FunctionIDTest::eType>::create(
                  functionId_allowedEnumSubsetValues),
              true);
  paramsMembersMap[S_MESSAGE_TYPE] =
      SMember(TEnumSchemaItem<MessageTypeTest::eType>::create(
                  messageType_allowedEnumSubsetValues),
              true);
  paramsMembersMap[S_CORRELATION_ID] =
      SMember(TNumberSchemaItem<int>::create(), true);
  paramsMembersMap[S_PROTOCOL_VERSION] =
      SMember(TNumberSchemaItem<int>::create(TSchemaItemParameter<int>(1),
                                             TSchemaItemParameter<int>(2)),
              true);
  paramsMembersMap[S_PROTOCOL_TYPE] =
      SMember(TNumberSchemaItem<int>::create(), true);

  std::map<std::string, SMember> rootMembersMap;
  rootMembersMap[S_MSG_PARAMS] =
      SMember(CObjectSchemaItem::create(schemaMembersMap), true);
  rootMembersMap[S_PARAMS] =
      SMember(CObjectSchemaItem::create(paramsMembersMap), true);
  return CSmartSchema(CObjectSchemaItem::create(rootMembersMap));
};

// cppcheck-suppress unusedFunction //Used in unit tests
CSmartSchema initSchemaForMetaFormatter() {
  std::set<TestType::eType> resultCode_allowedEnumSubsetValues;
  resultCode_allowedEnumSubsetValues.insert(
      TestType::APPLICATION_NOT_REGISTERED);
  resultCode_allowedEnumSubsetValues.insert(TestType::SUCCESS);
  resultCode_allowedEnumSubsetValues.insert(
      TestType::TOO_MANY_PENDING_REQUESTS);
  resultCode_allowedEnumSubsetValues.insert(TestType::REJECTED);
  resultCode_allowedEnumSubsetValues.insert(TestType::INVALID_DATA);
  resultCode_allowedEnumSubsetValues.insert(TestType::OUT_OF_MEMORY);
  resultCode_allowedEnumSubsetValues.insert(TestType::ABORTED);
  resultCode_allowedEnumSubsetValues.insert(TestType::USER_DISALLOWED);
  resultCode_allowedEnumSubsetValues.insert(TestType::GENERIC_ERROR);
  resultCode_allowedEnumSubsetValues.insert(TestType::DISALLOWED);

  // Possible functions in this test scheme
  std::set<FunctionIDTest::eType> functionId_allowedEnumSubsetValues;
  functionId_allowedEnumSubsetValues.insert(
      FunctionIDTest::RegisterAppInterface);
  functionId_allowedEnumSubsetValues.insert(
      FunctionIDTest::UnregisterAppInterface);
  functionId_allowedEnumSubsetValues.insert(
      FunctionIDTest::SetGlobalProperties);

  std::set<Language::eType> languageDesired_allowedEnumSubsetValues;
  languageDesired_allowedEnumSubsetValues.insert(Language::RU_RU);
  languageDesired_allowedEnumSubsetValues.insert(Language::EN_EU);

  std::set<AppTypeTest::eType> appType_allowedEnumSubsetValues;
  appType_allowedEnumSubsetValues.insert(AppTypeTest::SYSTEM);
  appType_allowedEnumSubsetValues.insert(AppTypeTest::MEDIA);

  std::set<SpeechCapabilities::eType>
      speechCapabilities_allowedEnumSubsetValues;
  speechCapabilities_allowedEnumSubsetValues.insert(
      SpeechCapabilities::SC_TEXT);

  // Possible message types
  std::set<MessageTypeTest::eType> messageType_allowedEnumSubsetValues;
  messageType_allowedEnumSubsetValues.insert(MessageTypeTest::request);
  messageType_allowedEnumSubsetValues.insert(MessageTypeTest::response);
  messageType_allowedEnumSubsetValues.insert(MessageTypeTest::notification);

  // Create param items
  ISchemaItemPtr appID_SchemaItem =
      CStringSchemaItem::create(TSchemaItemParameter<size_t>(0),
                                TSchemaItemParameter<size_t>(1000),
                                TSchemaItemParameter<std::string>());
  ISchemaItemPtr appName_SchemaItem =
      CStringSchemaItem::create(TSchemaItemParameter<size_t>(0),
                                TSchemaItemParameter<size_t>(1000),
                                TSchemaItemParameter<std::string>());
  ISchemaItemPtr isMediaApplication_SchemaItem =
      CBoolSchemaItem::create(TSchemaItemParameter<bool>());
  ISchemaItemPtr ngnMediaScreenAppName_SchemaItem =
      CStringSchemaItem::create(TSchemaItemParameter<size_t>(0),
                                TSchemaItemParameter<size_t>(1000),
                                TSchemaItemParameter<std::string>());

  ISchemaItemPtr ttsNameItem_SchemaItem =
      CStringSchemaItem::create(TSchemaItemParameter<size_t>(0),
                                TSchemaItemParameter<size_t>(1000),
                                TSchemaItemParameter<std::string>());

  ISchemaItemPtr ttstype_SchemaItem =
      TEnumSchemaItem<SpeechCapabilities::eType>::create(
          speechCapabilities_allowedEnumSubsetValues,
          TSchemaItemParameter<SpeechCapabilities::eType>());

  std::map<std::string, SMember> ttsMap;
  ttsMap["text"] = SMember(ttsNameItem_SchemaItem, false);
  ttsMap["type"] = SMember(ttstype_SchemaItem, false);
  ;

  ISchemaItemPtr hmiDisplayLanguageDesired_SchemaItem =
      TEnumSchemaItem<Language::eType>::create(
          languageDesired_allowedEnumSubsetValues,
          TSchemaItemParameter<Language::eType>());

  ISchemaItemPtr languageDesired_SchemaItem =
      TEnumSchemaItem<Language::eType>::create(
          languageDesired_allowedEnumSubsetValues,
          TSchemaItemParameter<Language::eType>());

  ISchemaItemPtr vrElementSchemaItem =
      CStringSchemaItem::create(TSchemaItemParameter<size_t>(0),
                                TSchemaItemParameter<size_t>(1000),
                                TSchemaItemParameter<std::string>());

  ISchemaItemPtr appTypeElementSchemaItem =
      TEnumSchemaItem<AppTypeTest::eType>::create(
          appType_allowedEnumSubsetValues,
          TSchemaItemParameter<AppTypeTest::eType>());

  ISchemaItemPtr ttsElementSchemaItem = CObjectSchemaItem::create(ttsMap);

  ISchemaItemPtr ttsName_SchemaItem =
      CArraySchemaItem::create(ttsElementSchemaItem,
                               TSchemaItemParameter<size_t>(0),
                               TSchemaItemParameter<size_t>(1000));

  ISchemaItemPtr vrSynonyms_SchemaItem =
      CArraySchemaItem::create(vrElementSchemaItem,
                               TSchemaItemParameter<size_t>(0),
                               TSchemaItemParameter<size_t>(1000));

  ISchemaItemPtr appType_SchemaItem =
      CArraySchemaItem::create(appTypeElementSchemaItem,
                               TSchemaItemParameter<size_t>(0),
                               TSchemaItemParameter<size_t>(1000));

  ISchemaItemPtr majorVersion_SchemaItem = TNumberSchemaItem<int>::create();
  ISchemaItemPtr minorVersion_SchemaItem = TNumberSchemaItem<int>::create();
  ISchemaItemPtr patchVersion_SchemaItem = TNumberSchemaItem<int>::create();

  // Creation map for syncMsgVersion
  std::map<std::string, SMember> schemaSyncMsgVersionMap;
  schemaSyncMsgVersionMap["majorVersion"] =
      SMember(majorVersion_SchemaItem, false);
  schemaSyncMsgVersionMap["minorVersion"] =
      SMember(minorVersion_SchemaItem, false);
  schemaSyncMsgVersionMap["patchVersion"] =
      SMember(patchVersion_SchemaItem, false);
  ;

  // Map of parameters
  std::map<std::string, SMember> schemaMembersMap;

  schemaMembersMap["appID"] = SMember(appID_SchemaItem, false);
  schemaMembersMap["appName"] = SMember(appName_SchemaItem, false);
  schemaMembersMap["appType"] = SMember(appType_SchemaItem, false);
  schemaMembersMap["hmiDisplayLanguageDesired"] =
      SMember(hmiDisplayLanguageDesired_SchemaItem, false);
  schemaMembersMap["isMediaApplication"] =
      SMember(isMediaApplication_SchemaItem, false);
  schemaMembersMap["languageDesired"] =
      SMember(languageDesired_SchemaItem, false);
  schemaMembersMap["ngnMediaScreenAppName"] =
      SMember(ngnMediaScreenAppName_SchemaItem, false);
  schemaMembersMap["syncMsgVersion"] =
      SMember(CObjectSchemaItem::create(schemaSyncMsgVersionMap), false);
  schemaMembersMap["ttsName"] = SMember(ttsName_SchemaItem, false);
  schemaMembersMap["vrSynonyms"] = SMember(vrSynonyms_SchemaItem, false);

  std::map<std::string, SMember> paramsMembersMap;
  paramsMembersMap[S_FUNCTION_ID] =
      SMember(TEnumSchemaItem<FunctionIDTest::eType>::create(
                  functionId_allowedEnumSubsetValues),
              true);
  paramsMembersMap[S_MESSAGE_TYPE] =
      SMember(TEnumSchemaItem<MessageTypeTest::eType>::create(
                  messageType_allowedEnumSubsetValues),
              true);
  paramsMembersMap[S_CORRELATION_ID] =
      SMember(TNumberSchemaItem<int>::create(), true);
  paramsMembersMap[S_PROTOCOL_VERSION] =
      SMember(TNumberSchemaItem<int>::create(TSchemaItemParameter<int>(1),
                                             TSchemaItemParameter<int>(2)),
              true);
  paramsMembersMap[S_PROTOCOL_TYPE] =
      SMember(TNumberSchemaItem<int>::create(), true);

  std::map<std::string, SMember> rootMembersMap;
  rootMembersMap[S_MSG_PARAMS] =
      SMember(CObjectSchemaItem::create(schemaMembersMap), true);
  rootMembersMap[S_PARAMS] =
      SMember(CObjectSchemaItem::create(paramsMembersMap), true);
  return CSmartSchema(CObjectSchemaItem::create(rootMembersMap));
};
#endif  // BUILD_TESTS

}  // namespace formatters
}  // namespace components
}  // namespace test


text:
package com.qihoo360.replugin;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;

import com.qihoo360.replugin.helper.LogDebug;
import com.qihoo360.replugin.i.IPluginManager;
import com.qihoo360.replugin.library.BuildConfig;

import static com.qihoo360.replugin.helper.LogDebug.TAG;

/**
 * 对框架暴露的一些通用的接口。
 * <p>
 * 注意:插件框架内部使用,外界请不要调用。
 *
 * @author RePlugin Team
 */
public class RePluginInternal {

    public static final boolean FOR_DEV = BuildConfig.DEBUG;

    /**
     * @param activity
     * @param newBase
     * @return 为Activity构造一个base Context
     * @hide 内部方法,插件框架使用
     * 插件的Activity创建成功后通过此方法获取其base context
     */
    public static Context createActivityContext(Activity activity, Context newBase) {
        if (!RePluginFramework.mHostInitialized) {
            return newBase;
        }

        try {
            return (Context) ProxyRePluginInternalVar.createActivityContext.call(null, activity, newBase);
        } catch (Exception e) {
            if (LogDebug.LOG) {
                e.printStackTrace();
            }
        }

        return null;
    }

    /**
     * @param activity
     * @param savedInstanceState
     * @hide 内部方法,插件框架使用
     * 插件的Activity的onCreate调用前调用此方法
     */
    public static void handleActivityCreateBefore(Activity activity, Bundle savedInstanceState) {
        if (!RePluginFramework.mHostInitialized) {
            return;
        }

        ProxyRePluginInternalVar.handleActivityCreateBefore.call(null, activity, savedInstanceState);
    }

    /**
     * @param activity
     * @param savedInstanceState
     * @hide 内部方法,插件框架使用
     * 插件的Activity的onCreate调用后调用此方法
     */
    public static void handleActivityCreate(Activity activity, Bundle savedInstanceState) {
        if (!RePluginFramework.mHostInitialized) {
            return;
        }

        ProxyRePluginInternalVar.handleActivityCreate.call(null, activity, savedInstanceState);
    }

    /**
     * @param activity
     * @hide 内部方法,插件框架使用
     * 插件的Activity的onDestroy调用后调用此方法
     */
    public static void handleActivityDestroy(Activity activity) {
        if (!RePluginFramework.mHostInitialized) {
            return;
        }

        ProxyRePluginInternalVar.handleActivityDestroy.call(null, activity);
    }

    /**
     * @param activity
     * @param savedInstanceState
     * @hide 内部方法,插件框架使用
     * 插件的Activity的onRestoreInstanceState调用后调用此方法
     */
    public static void handleRestoreInstanceState(Activity activity, Bundle savedInstanceState) {
        if (!RePluginFramework.mHostInitialized) {
            return;
        }

        ProxyRePluginInternalVar.handleRestoreInstanceState.call(null, activity, savedInstanceState);
    }

    /**
     * @param activity Activity上下文
     * @param intent
     * @return 插件机制层是否成功,例如没有插件存在、没有合适的Activity坑
     * @hide 内部方法,插件框架使用
     * 启动一个插件中的activity
     * 通过Extra参数IPluginManager.KEY_COMPATIBLE,IPluginManager.KEY_PLUGIN,IPluginManager.KEY_ACTIVITY,IPluginManager.KEY_PROCESS控制
     */
    public static boolean startActivity(Activity activity, Intent intent) {
        if (!RePluginFramework.mHostInitialized) {
            return false;
        }

        try {
            Object obj = ProxyRePluginInternalVar.startActivity.call(null, activity, intent);
            if (obj != null) {
                return (Boolean) obj;
            }
        } catch (Exception e) {
            if (LogDebug.LOG) {
                e.printStackTrace();
            }
        }

        return false;
    }

    /**
     * @param activity Activity上下文
     * @param intent
     * @return 插件机制层是否成功,例如没有插件存在、没有合适的Activity坑
     * Added by liupo
     * @hide 内部方法,插件框架使用
     * 启动一个插件中的activity
     * 通过Extra参数IPluginManager.KEY_COMPATIBLE,IPluginManager.KEY_PLUGIN,IPluginManager.KEY_ACTIVITY,IPluginManager.KEY_PROCESS控制
     */
    public static boolean startActivityForResult(Activity activity, Intent intent, int requestCode) {
        return startActivityForResult(activity, intent, requestCode, null);
    }

    /**
     * @param activity Activity上下文
     * @param intent
     * @return 插件机制层是否成功,例如没有插件存在、没有合适的Activity坑
     * Added by Jiongxuan Zhang
     * @hide 内部方法,插件框架使用
     * 启动一个插件中的activity
     * 通过Extra参数IPluginManager.KEY_COMPATIBLE,IPluginManager.KEY_PLUGIN,IPluginManager.KEY_ACTIVITY,IPluginManager.KEY_PROCESS控制
     */
    public static boolean startActivityForResult(Activity activity, Intent intent, int requestCode, Bundle options) {
        if (!RePluginFramework.mHostInitialized) {
            return false;
        }

        try {
            Object obj = ProxyRePluginInternalVar.startActivityForResult.call(null, activity, intent, requestCode, options);
            if (obj != null) {
                return (Boolean) obj;
            }
        } catch (Exception e) {
            if (LogDebug.LOG) {
                e.printStackTrace();
            }
        }

        // replugin-host-lib 版本小于 2.1.3 时
        return startActivityForResultCompat(activity, intent, requestCode, options);
    }

    /**
     * 如果 replugin-host-lib 版本小于 2.1.3,使用此 compat 方法。
     */
    private static boolean startActivityForResultCompat(Activity activity, Intent intent, int requestCode, Bundle options) {
        String plugin = getPluginName(activity, intent);

        if (LogDebug.LOG) {
            LogDebug.d(TAG, "start activity with startActivityForResult: intent=" + intent);
        }

        if (TextUtils.isEmpty(plugin)) {
            return false;
        }

        ComponentName cn = intent.getComponent();
        if (cn == null) {
            return false;
        }
        String name = cn.getClassName();

        ComponentName cnNew = loadPluginActivity(intent, plugin, name, IPluginManager.PROCESS_AUTO);
        if (cnNew == null) {
            return false;
        }

        intent.setComponent(cnNew);

        if (Build.VERSION.SDK_INT >= 16) {
            activity.startActivityForResult(intent, requestCode, options);
        } else {
            activity.startActivityForResult(intent, requestCode);
        }
        return true;
    }

    /**
     * 加载插件Activity,在startActivity之前调用
     *
     * @param intent
     * @param plugin  插件名
     * @param target  目标Service名,如果传null,则取获取到的第一个
     * @param process 是否在指定进程中启动
     * @return
     */
    public static ComponentName loadPluginActivity(Intent intent, String plugin, String target, int process) {
        if (!RePluginFramework.mHostInitialized) {
            return null;
        }

        try {
            return (ComponentName) ProxyRePluginInternalVar.loadPluginActivity.call(null, intent, plugin, target, process);
        } catch (Exception e) {
            if (LogDebug.LOG) {
                e.printStackTrace();
            }
        }

        return null;
    }

    /**
     * 获取插件名称
     */
    private static String getPluginName(Activity activity, Intent intent) {
        String plugin = "";
        if (intent.getComponent() != null) {
            plugin = intent.getComponent().getPackageName();
        }
        // 如果 plugin 是包名,则说明启动的是本插件。
        if (TextUtils.isEmpty(plugin) || plugin.contains(".")) {
            plugin = RePlugin.fetchPluginNameByClassLoader(activity.getClassLoader());
        }
        // 否则是其它插件
        return plugin;
    }

    static class ProxyRePluginInternalVar {

        private static MethodInvoker createActivityContext;

        private static MethodInvoker handleActivityCreateBefore;

        private static MethodInvoker handleActivityCreate;

        private static MethodInvoker handleActivityDestroy;

        private static MethodInvoker handleRestoreInstanceState;

        private static MethodInvoker startActivity;

        private static MethodInvoker startActivityForResult;

        private static MethodInvoker loadPluginActivity;

        static void initLocked(final ClassLoader classLoader) {

            final String factory2 = "com.qihoo360.i.Factory2";
            final String factory = "com.qihoo360.i.Factory";

            // 初始化Factory2相关方法
            createActivityContext = new MethodInvoker(classLoader, factory2, "createActivityContext", new Class<?>[]{Activity.class, Context.class});
            handleActivityCreateBefore = new MethodInvoker(classLoader, factory2, "handleActivityCreateBefore", new Class<?>[]{Activity.class, Bundle.class});
            handleActivityCreate = new MethodInvoker(classLoader, factory2, "handleActivityCreate", new Class<?>[]{Activity.class, Bundle.class});
            handleActivityDestroy = new MethodInvoker(classLoader, factory2, "handleActivityDestroy", new Class<?>[]{Activity.class});
            handleRestoreInstanceState = new MethodInvoker(classLoader, factory2, "handleRestoreInstanceState", new Class<?>[]{Activity.class, Bundle.class});
            startActivity = new MethodInvoker(classLoader, factory2, "startActivity", new Class<?>[]{Activity.class, Intent.class});
            startActivityForResult = new MethodInvoker(classLoader, factory2, "startActivityForResult", new Class<?>[]{Activity.class, Intent.class, int.class, Bundle.class});

            // 初始化Factory相关方法
            loadPluginActivity = new MethodInvoker(classLoader, factory, "loadPluginActivity", new Class<?>[]{Intent.class, String.class, String.class, int.class});
        }
    }
}


text:
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';

import AppContainer from './container';
import store from './store';

var appRootElement = document.createElement('div');
document.body.appendChild(appRootElement);

render(
  <Provider store={store}>
    <AppContainer />
  </Provider>,
  appRootElement
);


text:
//
//  Generated by the J2ObjC translator.  DO NOT EDIT!
//  source: android/libcore/luni/src/main/java/java/security/cert/X509Extension.java
//

#ifndef _JavaSecurityCertX509Extension_H_
#define _JavaSecurityCertX509Extension_H_

#include "J2ObjC_header.h"

@class IOSByteArray;
@protocol JavaUtilSet;

/*!
 @brief The interface specifying an X.509 Certificate or CRL extension.
 */
@protocol JavaSecurityCertX509Extension < NSObject, JavaObject >

/*!
 @brief Returns the set of OIDs of the extension(s) marked as CRITICAL, that this
 implementation manages.
 @return the set of extension OIDs marked as CRITIAL, an empty set if none
 are marked as CRITICAL, or null if no extensions are
 present.
 */
- (id<JavaUtilSet>)getCriticalExtensionOIDs;

/*!
 @brief Returns the extension value as DER-encoded OCTET string for the specified
 OID.
 @param oid
 the object identifier to get the extension value for.
 @return the extension value as DER-encoded OCTET string, or null
 if no extension for the specified OID can be found.
 */
- (IOSByteArray *)getExtensionValueWithNSString:(NSString *)oid;

/*!
 @brief Returns the set of OIDs of the extension(s) marked as NON-CRITICAL, that
 this implementation manages.
 @return the set of extension OIDs marked as NON-CRITIAL, an empty set if
 none are marked as NON-.CRITICAL, or null if no
 extensions are present.
 */
- (id<JavaUtilSet>)getNonCriticalExtensionOIDs;

/*!
 @brief Returns whether this instance has an extension marked as CRITICAL that it
 cannot support.
 @return true if an unsupported CRITICAL extension is present,
 false otherwise.
 */
- (jboolean)hasUnsupportedCriticalExtension;

@end

J2OBJC_EMPTY_STATIC_INIT(JavaSecurityCertX509Extension)

J2OBJC_TYPE_LITERAL_HEADER(JavaSecurityCertX509Extension)

#endif // _JavaSecurityCertX509Extension_H_


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

{% block content %}

Config

    <form method="POST">
        <input name='nonce' type='hidden' value="{{ nonce }}">

            CTF Name:
            <input id='ctf_name' name='ctf_name' type='text' placeholder="CTF Name" {% if ctf_name is defined and ctf_name != None %}value="{{ ctf_name }}"{% endif %}>

            Mailgun API Key:
            <input id='mg_api_key' name='mg_api_key' type='text' placeholder="Mailgun API Key" {% if mg_api_key is defined and mg_api_key != None %}value="{{ mg_api_key }}"{% endif %}>

            Digital Ocean API Key:
            <input id='do_api_key' name='do_api_key' type='text' placeholder="Digital Ocean API Key" {% if do_api_key is defined and do_api_key != None %}value="{{ do_api_key }}"{% endif %}>

            Start Date:
            <input id='start' name='start' type='text' placeholder="Start Date (UTC timestamp)" {% if start is defined and start != None %}value="{{ start }}"{% endif %}>

            End Date:
            <input id='end' name='end' type='text' placeholder="End Date (UTC timestamp)" {% if end is defined and end != None %}value="{{ end }}"{% endif %}>

            <input id="view_challenges_unregistered" name="view_challenges_unregistered" type="checkbox" {% if view_challenges_unregistered %}checked{% endif %}>
            Unregistered users can view challenges

            <input id="prevent_registration" name="prevent_registration" type="checkbox" {% if prevent_registration %}checked{% endif %}>
            Prevent public registration

        <button class="radius" type='submit'>Update</button>
    </form>

{% endblock %}

{% block scripts %}
{% endblock %}


text:
import React, { PropTypes } from 'react'
import { Router } from 'dva/router'
import App from './routes/app'

const cached = {}
const registerModel = (app, model) => {
  if (!cached[model.namespace]) {
    app.model(model)
    cached[model.namespace] = 1
  }
}

const Routers = function ({ history, app }) {
  const routes = [
    {
      path: '/',
      component: App,
      getIndexRoute (nextState, cb) {
        require.ensure([], require => {
          registerModel(app, require('./models/sys_func'))
          cb(null, require('./page/sys/func'))
        }, 'sys/func')
      },
      childRoutes: [
        {
          path: 'sys/func',
          name: 'sys/func',
          getComponent (nextState, cb) {
            require.ensure([], require => {
              registerModel(app, require('./models/sys_func'))
              cb(null, require('./page/sys/func'))
            }, 'sys/func')
          },
        },{
          path: 'sys/account',
          name: 'sys/account',
          getComponent (nextState, cb) {
            require.ensure([], require => {
              cb(null, require('./page/sys/account'))
            }, 'sys/account')
          },
        },{
          path: 'sys/role',
          name: 'sys/role',
          getComponent (nextState, cb) {
            require.ensure([], require => {
              cb(null, require('./page/sys/role'))
            }, 'sys/role')
          },
        },{
          path: 'hrm/department',
          name: 'hrm/department',
          getComponent (nextState, cb) {
            require.ensure([], require => {
              cb(null, require('./page/hrm/department'))
            }, 'hrm/department')
          },
        },{
          path: 'hrm/employee',
          name: 'hrm/employee',
          getComponent (nextState, cb) {
            require.ensure([], require => {
              cb(null, require('./page/hrm/employee'))
            }, 'hrm/employee')
          },
        },{
          path: 'hrm/train',
          name: 'hrm/train',
          getComponent (nextState, cb) {
            require.ensure([], require => {
              cb(null, require('./page/hrm/train'))
            }, 'hrm/train')
          },
        },{
          path: '*',
          name: 'error',
          getComponent (nextState, cb) {
            require.ensure([], require => {
              cb(null, require('./routes/error'))
            }, 'error')
          },
        },
      ],
    },
  ]

  return <Router history={history} routes={routes} />
}

Routers.propTypes = {
  history: PropTypes.object,
  app: PropTypes.object,
}

export default Routers


text:
package fr.pilato.elasticsearch.crawler.fs.framework.bulk;

import java.util.ArrayList;
import java.util.List;

public abstract class FsCrawlerBulkRequest<T extends FsCrawlerOperation<T>> {

    private final List<T> operations = new ArrayList<>();

    public int numberOfActions() {
        return operations.size();
    }

    public void add(T request) {
        operations.add(request);
    }

    public List<T> getOperations() {
        return operations;
    }
}


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

<recipeml version="0.5">
  <recipe>
    <head>
      <title>Baby Bok Choy with Mushrooms and Tofu</title>
      <categories>
        <cat>Stir-fry</cat>
        <cat>Vegetable</cat>
        <cat>Country liv</cat></categories>
      <yield>4</yield></head>
    <ingredients>
      <ing-div>
        <title/>
        <ing>
          <amt>
            <qty>1</qty>
            <unit>pound</unit></amt>
          <item>Firm tofu; drained</item></ing>
        <ing>
          <amt>
            <qty>2</qty>
            <unit>tablespoons</unit></amt>
          <item>Cornstarch</item></ing>
        <ing>
          <amt>
            <qty>3</qty>
            <unit>tablespoons</unit></amt>
          <item>Vegetable oil</item></ing>
        <ing>
          <amt>
            <qty>1/2</qty>
            <unit>cups</unit></amt>
          <item>Vegetable broth</item></ing>
        <ing>
          <amt>
            <qty>6</qty>
            <unit>slices</unit></amt>
          <item>Fresh ginger root; sliced</item></ing>
        <ing>
          <amt>
            <qty>8</qty>
            <unit/></amt>
          <item>Baby bok choy; halved lengthwise</item></ing></ing-div>
      <ing-div>
        <title>SAUCE</title>
        <ing>
          <amt>
            <qty>1/2</qty>
            <unit>cups</unit></amt>
          <item>Vegetable broth</item></ing>
        <ing>
          <amt>
            <qty>1/4</qty>
            <unit>cups</unit></amt>
          <item>Oyster sauce</item></ing>
        <ing>
          <amt>
            <qty>2</qty>
            <unit>tablespoons</unit></amt>
          <item>Soy sauce; low sodium</item></ing>
        <ing>
          <amt>
            <qty>2</qty>
            <unit>teaspoons</unit></amt>
          <item>Cornstarch</item></ing>
        <ing>
          <amt>
            <qty>2</qty>
            <unit>teaspoons</unit></amt>
          <item>Sugar</item></ing>
        <ing>
          <amt>
            <qty>2</qty>
            <unit>teaspoons</unit></amt>
          <item>Sesame oil</item></ing>
        <ing>
          <amt>
            <qty>1/2</qty>
            <unit>pounds</unit></amt>
          <item>Medium size shiitake mushroom; stems removed</item></ing></ing-div>
      <ing-div>
        <title>OPTIONAL TOPPING</title>
        <ing>
          <amt>
            <qty>1</qty>
            <unit>small</unit></amt>
          <item>Green onion; diagonally sliced</item></ing></ing-div></ingredients>
    <directions>
      <step>  On paper towels, pat tofu dry on all sides. Cut tofu crosswise into
  1/2-inch thick slices. On small plate, place cornstarch.

  Heat nonstick wok or large skillet over medium heat until hot. Add 2
  tablespoons oil and swirl to coat pan. One at a time, dip tofu slices into
  cornstarch to coat cut surfaces and place in wok. Fry until well browned on
  one side--about 5 minutes . Turn tofu slices and fry other sides until well
  borwned. Transfer tofu to center of large serving platter; cover with foil
  and keep warm.

  Add broth and gingerroot to wok and heat to boiling. Add bok choy; cover
  and cook until tender and most of broth evaporates--about 5 minutes.

  Meanwhile, prepare Sauce. In small bowl, combine vegetable broth,
  oyster-flavored sauce, soy sauce, cornstarch, sugar and sesame oil.

  With slotted spoon or pancake turner, remove bok choy and place, cut sides
  down, around rim of platter with tofu; cover and keep warm. Discard ginger
  slices and any remaining broth.

  Reheat wok over high heat until hot. Add remaining 1 tablespoon oil and the
  mushrooms. Stir-fry mushrooms until softened--about 3 minutes. Restir Sauce
  and pour over mushrooms; cook, stirring constantly, until thickened and
  bubbly. Transfer mushrooms from Sauce and place over tofu. Pour Sauce over
  all. Garnish with green onions, if desired.

  Recipe by: Country Living (March 1998)

  Posted to recipelu-digest by "Nesb2@aol.com" <Nesb2@aol.com> on Mar 22,
  1998

</step></directions></recipe></recipeml>


text:
package ninja.metrics;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * An annotation for marking a controller method to be Metered for metrics
 * collection.
 *
 * A meter measures the rate of events over time (e.g., "requests per second").
 * In addition to the mean rate, meters also track 1-, 5-, and 15-minute moving averages.
 *
 * If no name is specified, the controller classname and method name are used.
 *
 * @author James Moger
 */

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Metered {

    String value() default "";

}


text:
package com.apollo;

public interface Behavior
{
	public abstract Engine getEngine();

	public abstract void setOwner(Entity owner);

	public abstract Entity getOwner();

	public abstract Class<? extends Behavior> getType();

	public abstract void initialize();

	public abstract void update(float delta);

	public abstract <T extends Behavior> T getBehaviorFromOwner(Class<T> family);

	public abstract void uninitialize();

}