text:
package com.android.email.activity.setup;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.FragmentManager;
import android.app.admin.DevicePolicyManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;

import com.android.email.Email;
import com.android.email.R;
import com.android.email.SecurityPolicy;
import com.android.email.activity.ActivityHelper;
import com.android.emailcommon.provider.Account;
import com.android.emailcommon.provider.HostAuth;
import com.android.emailcommon.utility.Utility;

/**
 * Psuedo-activity (no UI) to bootstrap the user up to a higher desired security level.  This
 * bootstrap requires the following steps.
 *
 * 1.  Confirm the account of interest has any security policies defined - exit early if not
 * 2.  If not actively administrating the device, ask Device Policy Manager to start that
 * 3.  When we are actively administrating, check current policies and see if they're sufficient
 * 4.  If not, set policies
 * 5.  If necessary, request for user to update device password
 * 6.  If necessary, request for user to activate device encryption
 */
public class AccountSecurity extends Activity {
    private static final String TAG = "Email/AccountSecurity";

    private static final String EXTRA_ACCOUNT_ID = "ACCOUNT_ID";
    private static final String EXTRA_SHOW_DIALOG = "SHOW_DIALOG";
    private static final String EXTRA_PASSWORD_EXPIRING = "EXPIRING";
    private static final String EXTRA_PASSWORD_EXPIRED = "EXPIRED";

    private static final int REQUEST_ENABLE = 1;
    private static final int REQUEST_PASSWORD = 2;
    private static final int REQUEST_ENCRYPTION = 3;

    private boolean mTriedAddAdministrator = false;
    private boolean mTriedSetPassword = false;
    private boolean mTriedSetEncryption = false;
    private Account mAccount;

    /**
     * Used for generating intent for this activity (which is intended to be launched
     * from a notification.)
     *
     * @param context Calling context for building the intent
     * @param accountId The account of interest
     * @param showDialog If true, a simple warning dialog will be shown before kicking off
     * the necessary system settings.  Should be true anywhere the context of the security settings
     * is not clear (e.g. any time after the account has been set up).
     * @return an Intent which can be used to view that account
     */
    public static Intent actionUpdateSecurityIntent(Context context, long accountId,
            boolean showDialog) {
        Intent intent = new Intent(context, AccountSecurity.class);
        intent.putExtra(EXTRA_ACCOUNT_ID, accountId);
        intent.putExtra(EXTRA_SHOW_DIALOG, showDialog);
        return intent;
    }

    /**
     * Used for generating intent for this activity (which is intended to be launched
     * from a notification.)  This is a special mode of this activity which exists only
     * to give the user a dialog (for context) about a device pin/password expiration event.
     */
    public static Intent actionDevicePasswordExpirationIntent(Context context, long accountId,
            boolean expired) {
        Intent intent = new Intent(context, AccountSecurity.class);
        intent.putExtra(EXTRA_ACCOUNT_ID, accountId);
        intent.putExtra(expired ? EXTRA_PASSWORD_EXPIRED : EXTRA_PASSWORD_EXPIRING, true);
        return intent;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityHelper.debugSetWindowFlags(this);

        Intent i = getIntent();
        final long accountId = i.getLongExtra(EXTRA_ACCOUNT_ID, -1);
        final boolean showDialog = i.getBooleanExtra(EXTRA_SHOW_DIALOG, false);
        final boolean passwordExpiring = i.getBooleanExtra(EXTRA_PASSWORD_EXPIRING, false);
        final boolean passwordExpired = i.getBooleanExtra(EXTRA_PASSWORD_EXPIRED, false);
        SecurityPolicy security = SecurityPolicy.getInstance(this);
        security.clearNotification();
        if (accountId == -1) {
            finish();
            return;
        }

        mAccount = Account.restoreAccountWithId(AccountSecurity.this, accountId);
        if (mAccount == null) {
            finish();
            return;
        }
        // Special handling for password expiration events
        if (passwordExpiring || passwordExpired) {
            FragmentManager fm = getFragmentManager();
            if (fm.findFragmentByTag("password_expiration") == null) {
                PasswordExpirationDialog dialog =
                    PasswordExpirationDialog.newInstance(mAccount.getDisplayName(),
                            passwordExpired);
                dialog.show(fm, "password_expiration");
            }
            return;
        }
        // Otherwise, handle normal security settings flow
        if (mAccount.mPolicyKey != 0) {
            // This account wants to control security
            if (showDialog) {
                // Show dialog first, unless already showing (e.g. after rotation)
                FragmentManager fm = getFragmentManager();
                if (fm.findFragmentByTag("security_needed") == null) {
                    SecurityNeededDialog dialog =
                        SecurityNeededDialog.newInstance(mAccount.getDisplayName());
                    dialog.show(fm, "security_needed");
                }
            } else {
                // Go directly to security settings
                tryAdvanceSecurity(mAccount);
            }
            return;
        }
        finish();
    }

    /**
     * After any of the activities return, try to advance to the "next step"
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        tryAdvanceSecurity(mAccount);
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * Walk the user through the required steps to become an active administrator and with
     * the requisite security settings for the given account.
     *
     * These steps will be repeated each time we return from a given attempt (e.g. asking the
     * user to choose a device pin/password).  In a typical activation, we may repeat these
     * steps a few times.  It may go as far as step 5 (password) or step 6 (encryption), but it
     * will terminate when step 2 (isActive()) succeeds.
     *
     * If at any point we do not advance beyond a given user step, (e.g. the user cancels
     * instead of setting a password) we simply repost the security notification, and exit.
     * We never want to loop here.
     */
    private void tryAdvanceSecurity(Account account) {
        SecurityPolicy security = SecurityPolicy.getInstance(this);
        // Step 1.  Check if we are an active device administrator, and stop here to activate
        if (!security.isActiveAdmin()) {
            if (mTriedAddAdministrator) {
                if (Email.DEBUG) {
                    Log.d(TAG, "Not active admin: repost notification");
                }
                repostNotification(account, security);
                finish();
            } else {
                mTriedAddAdministrator = true;
                // retrieve name of server for the format string
                HostAuth hostAuth = HostAuth.restoreHostAuthWithId(this, account.mHostAuthKeyRecv);
                if (hostAuth == null) {
                    if (Email.DEBUG) {
                        Log.d(TAG, "No HostAuth: repost notification");
                    }
                    repostNotification(account, security);
                    finish();
                } else {
                    if (Email.DEBUG) {
                        Log.d(TAG, "Not active admin: post initial notification");
                    }
                    // try to become active - must happen here in activity, to get result
                    Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
                    intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
                            security.getAdminComponent());
                    intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,
                            this.getString(R.string.account_security_policy_explanation_fmt,
                                    hostAuth.mAddress));
                    startActivityForResult(intent, REQUEST_ENABLE);
                }
            }
            return;
        }

        // Step 2.  Check if the current aggregate security policy is being satisfied by the
        // DevicePolicyManager (the current system security level).
        if (security.isActive(null)) {
            if (Email.DEBUG) {
                Log.d(TAG, "Security active; clear holds");
            }
            Account.clearSecurityHoldOnAllAccounts(this);
            security.clearNotification();
            finish();
            return;
        }

        // Step 3.  Try to assert the current aggregate security requirements with the system.
        security.setActivePolicies();

        // Step 4.  Recheck the security policy, and determine what changes are needed (if any)
        // to satisfy the requirements.
        int inactiveReasons = security.getInactiveReasons(null);

        // Step 5.  If password is needed, try to have the user set it
        if ((inactiveReasons & SecurityPolicy.INACTIVE_NEED_PASSWORD) != 0) {
            if (mTriedSetPassword) {
                if (Email.DEBUG) {
                    Log.d(TAG, "Password needed; repost notification");
                }
                repostNotification(account, security);
                finish();
            } else {
                if (Email.DEBUG) {
                    Log.d(TAG, "Password needed; request it via DPM");
                }
                mTriedSetPassword = true;
                // launch the activity to have the user set a new password.
                Intent intent = new Intent(DevicePolicyManager.ACTION_SET_NEW_PASSWORD);
                startActivityForResult(intent, REQUEST_PASSWORD);
            }
            return;
        }

        // Step 6.  If encryption is needed, try to have the user set it
        if ((inactiveReasons & SecurityPolicy.INACTIVE_NEED_ENCRYPTION) != 0) {
            if (mTriedSetEncryption) {
                if (Email.DEBUG) {
                    Log.d(TAG, "Encryption needed; repost notification");
                }
                repostNotification(account, security);
                finish();
            } else {
                if (Email.DEBUG) {
                    Log.d(TAG, "Encryption needed; request it via DPM");
                }
                mTriedSetEncryption = true;
                // launch the activity to start up encryption.
                Intent intent = new Intent(DevicePolicyManager.ACTION_START_ENCRYPTION);
                startActivityForResult(intent, REQUEST_ENCRYPTION);
            }
            return;
        }

        // Step 7.  No problems were found, so clear holds and exit
        if (Email.DEBUG) {
            Log.d(TAG, "Policies enforced; clear holds");
        }
        Account.clearSecurityHoldOnAllAccounts(this);
        security.clearNotification();
        finish();
    }

    /**
     * Mark an account as not-ready-for-sync and post a notification to bring the user back here
     * eventually.
     */
    private void repostNotification(final Account account, final SecurityPolicy security) {
        if (account == null) return;
        Utility.runAsync(new Runnable() {
            @Override
            public void run() {
                security.policiesRequired(account.mId);
            }
        });
    }

    /**
     * Dialog briefly shown in some cases, to indicate the user that a security update is needed.
     * If the user clicks OK, we proceed into the "tryAdvanceSecurity" flow.  If the user cancels,
     * we repost the notification and finish() the activity.
     */
    public static class SecurityNeededDialog extends DialogFragment
            implements DialogInterface.OnClickListener {
        private static final String BUNDLE_KEY_ACCOUNT_NAME = "account_name";

        /**
         * Create a new dialog.
         */
        public static SecurityNeededDialog newInstance(String accountName) {
            final SecurityNeededDialog dialog = new SecurityNeededDialog();
            Bundle b = new Bundle();
            b.putString(BUNDLE_KEY_ACCOUNT_NAME, accountName);
            dialog.setArguments(b);
            return dialog;
        }

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            final String accountName = getArguments().getString(BUNDLE_KEY_ACCOUNT_NAME);

            final Context context = getActivity();
            final Resources res = context.getResources();
            final AlertDialog.Builder b = new AlertDialog.Builder(context);
            b.setTitle(R.string.account_security_dialog_title);
            b.setIconAttribute(android.R.attr.alertDialogIcon);
            b.setMessage(res.getString(R.string.account_security_dialog_content_fmt, accountName));
            b.setPositiveButton(R.string.okay_action, this);
            b.setNegativeButton(R.string.cancel_action, this);
            if (Email.DEBUG) {
                Log.d(TAG, "Posting security needed dialog");
            }
            return b.create();
        }

        @Override
        public void onClick(DialogInterface dialog, int which) {
            dismiss();
            AccountSecurity activity = (AccountSecurity) getActivity();
            if (activity.mAccount == null) {
                // Clicked before activity fully restored - probably just monkey - exit quickly
                activity.finish();
                return;
            }
            switch (which) {
                case DialogInterface.BUTTON_POSITIVE:
                    if (Email.DEBUG) {
                        Log.d(TAG, "User accepts; advance to next step");
                    }
                    activity.tryAdvanceSecurity(activity.mAccount);
                    break;
                case DialogInterface.BUTTON_NEGATIVE:
                    if (Email.DEBUG) {
                        Log.d(TAG, "User declines; repost notification");
                    }
                    activity.repostNotification(
                            activity.mAccount, SecurityPolicy.getInstance(activity));
                    activity.finish();
                    break;
            }
        }
    }

    /**
     * Dialog briefly shown in some cases, to indicate the user that the PIN/Password is expiring
     * or has expired.  If the user clicks OK, we launch the password settings screen.
     */
    public static class PasswordExpirationDialog extends DialogFragment
            implements DialogInterface.OnClickListener {
        private static final String BUNDLE_KEY_ACCOUNT_NAME = "account_name";
        private static final String BUNDLE_KEY_EXPIRED = "expired";

        /**
         * Create a new dialog.
         */
        public static PasswordExpirationDialog newInstance(String accountName, boolean expired) {
            final PasswordExpirationDialog dialog = new PasswordExpirationDialog();
            Bundle b = new Bundle();
            b.putString(BUNDLE_KEY_ACCOUNT_NAME, accountName);
            b.putBoolean(BUNDLE_KEY_EXPIRED, expired);
            dialog.setArguments(b);
            return dialog;
        }

        /**
         * Note, this actually creates two slightly different dialogs (for expiring vs. expired)
         */
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            final String accountName = getArguments().getString(BUNDLE_KEY_ACCOUNT_NAME);
            final boolean expired = getArguments().getBoolean(BUNDLE_KEY_EXPIRED);
            final int titleId = expired
                    ? R.string.password_expired_dialog_title
                    : R.string.password_expire_warning_dialog_title;
            final int contentId = expired
                    ? R.string.password_expired_dialog_content_fmt
                    : R.string.password_expire_warning_dialog_content_fmt;

            final Context context = getActivity();
            final Resources res = context.getResources();
            final AlertDialog.Builder b = new AlertDialog.Builder(context);
            b.setTitle(titleId);
            b.setIconAttribute(android.R.attr.alertDialogIcon);
            b.setMessage(res.getString(contentId, accountName));
            b.setPositiveButton(R.string.okay_action, this);
            b.setNegativeButton(R.string.cancel_action, this);
            return b.create();
        }

        @Override
        public void onClick(DialogInterface dialog, int which) {
            dismiss();
            AccountSecurity activity = (AccountSecurity) getActivity();
            if (which == DialogInterface.BUTTON_POSITIVE) {
                Intent intent = new Intent(DevicePolicyManager.ACTION_SET_NEW_PASSWORD);
                activity.startActivity(intent);
            }
            activity.finish();
        }
    }
}


text:
require 'simplecov'

module SimpleCov::Configuration
  def clean_filters
    @filters = []
  end
end

SimpleCov.configure do
  clean_filters
  load_adapter 'test_frameworks'
end

ENV["COVERAGE"] && SimpleCov.start do
  add_filter "/.rvm/"
end
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))

require 'rspec'
require 'hello-gem'

require "cenit/collection/slack/build"
require 'cenit/client'

# Requires supporting files with custom matchers and macros, etc,
# in ./support/ and its subdirectories.
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f}

RSpec.configure do |config|

  # Infer an example group's spec type from the file location.
  config.infer_spec_type_from_file_location!

  config.mock_with :rspec
  config.color = true
end

redpajama_set_name: RedPajamaGithub


text:
from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.config import ConfigValidationError
from txircd.module_interface import Command, ICommand, IModuleData, ModuleData
from zope.interface import implements

class PassCommand(ModuleData, Command):
	implements(IPlugin, IModuleData, ICommand)

	name = "PassCommand"
	core = True
	forRegistered = False

	def actions(self):
		return [ ("register", 10, self.matchPassword) ]

	def userCommands(self):
		return [ ("PASS", 1, self) ]

	def verifyConfig(self, config):
		if "server_password" in config and not isinstance(config["server_password"], basestring):
			raise ConfigValidationError("server_password", "value must be a string")

	def parseParams(self, user, params, prefix, tags):
		if not params:
			user.sendSingleError("PassCmd", irc.ERR_NEEDMOREPARAMS, "PASS", "Not enough parameters")
			return None
		return {
			"password": params[0]
		}

	def execute(self, user, data):
		user.cache["password"] = data["password"]
		return True

	def matchPassword(self, user):
		try:
			serverPass = self.ircd.config["server_password"]
		except KeyError:
			return True
		if "password" not in user.cache or serverPass != user.cache["password"]:
			user.sendMessage("ERROR", "Closing Link: {}@{} [Access Denied]".format(user.ident, user.host()), to=None, prefix=None)
			return False
		return True

passCmd = PassCommand()


text:
package org.apereo.portal.io.xml.portlettype;

import java.util.Arrays;
import java.util.List;
import javax.xml.namespace.QName;
import org.apereo.portal.io.xml.AbstractPortalDataType;
import org.apereo.portal.io.xml.IExportAllPortalDataType;
import org.apereo.portal.io.xml.PortalDataKey;
import org.springframework.stereotype.Component;

@Component("portletTypePortalDataType")
public class PortletTypePortalDataType extends AbstractPortalDataType
        implements IExportAllPortalDataType {

    public static final int ORDER = 80;

    public static final QName PORTLET_TYPE_QNAME =
            new QName("https://source.jasig.org/schemas/uportal/io/portlet-type", "portlet-type");

    public static final PortalDataKey IMPORT_40_DATA_KEY =
            new PortalDataKey(PORTLET_TYPE_QNAME, null, "4.0");

    private static final List<PortalDataKey> PORTAL_DATA_KEYS = Arrays.asList(IMPORT_40_DATA_KEY);

    public PortletTypePortalDataType() {
        super(ORDER, PORTLET_TYPE_QNAME);
    }

    @Override
    public List<PortalDataKey> getDataKeyImportOrder() {
        return PORTAL_DATA_KEYS;
    }

    @Override
    public String getTitleCode() {
        return "Portlet Type";
    }

    @Override
    public String getDescriptionCode() {
        return "Types of portlets published in the portal";
    }
}


text:
import { rollup } from 'rollup';
import * as commonjs from 'rollup-plugin-commonjs';
import * as nodeResolve from 'rollup-plugin-node-resolve';
import * as typescript from 'rollup-plugin-typescript';
import { expect, assert } from 'chai';
import * as angular from '../../dist/rollup-plugin-angular.js';
import * as colors from 'colors';

process.chdir('test');

const bundle = () => {
  return rollup({
    entry: 'mochats/component.ts',
    plugins: [
      angular(),
      commonjs(),
      typescript({
        typescript: require('./../../node_modules/typescript')
      })
    ]
  });
}

describe('rollup-plugin-angular', () => {
  console.info(`-------------------`);
  console.info(colors.blue(`start test mocha:ts`));
  console.info(`-------------------`);
  beforeEach(() => {

  });
  it('should not have example-component.html file content loaded from comment', () => {
    return bundle()
      .then(bundle => {
        return bundle
          .generate({ format: 'iife', moduleName: 'component' })
          .then(generated => {
            assert.ok(generated.code);
            expect(generated.code.includes(`example-component.html content loaded`)).to.equal(false);
            return generated;
          });
      });
	});

  it('should have component.html file content loaded', () => {
    return bundle()
      .then(bundle => {
        return bundle
          .generate({ format: 'iife', moduleName: 'component' })
          .then(generated => {
            assert.ok(generated.code);
            expect(generated.code.includes(`component.html content loaded`)).to.equal(true);
            return generated;
          });
      });
	});
});


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Enum. pl. (Kjbenhavn) 2: 224 (1803)

#### Original name
Aecidium myrtilli Schumach., 1803

### Remarks
null


text:
package demo.account.domain;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import demo.account.action.*;
import demo.account.controller.AccountController;
import demo.account.event.AccountEvent;
import demo.domain.AbstractEntity;
import demo.domain.Aggregate;
import demo.domain.Command;
import demo.domain.Module;
import demo.order.domain.Order;
import demo.order.domain.Orders;
import org.springframework.hateoas.Link;

import javax.persistence.*;

import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;

@Entity
public class Account extends AbstractEntity<AccountEvent, Long> {

    @Id
    @GeneratedValue
    private Long id;

    private String firstName;
    private String lastName;
    private String email;

    @Enumerated(value = EnumType.STRING)
    private AccountStatus status;

    public Account() {
        status = AccountStatus.ACCOUNT_CREATED;
    }

    public Account(String firstName, String lastName, String email) {
        this();
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
    }

    @JsonProperty("accountId")
    @Override
    public Long getIdentity() {
        return this.id;
    }

    @Override
    public void setIdentity(Long id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public AccountStatus getStatus() {
        return status;
    }

    public void setStatus(AccountStatus status) {
        this.status = status;
    }

    @JsonIgnore
    public Orders getOrders() {
        return getAction(GetOrders.class)
                .apply(this);
    }

    @Command(method = "activate", controller = AccountController.class)
    public Account activate() {
        return getAction(ActivateAccount.class)
                .apply(this);
    }

    @Command(method = "archive", controller = AccountController.class)
    public Account archive() {
        return getAction(ArchiveAccount.class)
                .apply(this);
    }

    @Command(method = "confirm", controller = AccountController.class)
    public Account confirm() {
        return getAction(ConfirmAccount.class)
                .apply(this);
    }

    @Command(method = "suspend", controller = AccountController.class)
    public Account suspend() {
        return getAction(SuspendAccount.class)
                .apply(this);
    }

    @Command(method = "postOrder", controller = AccountController.class)
    public Order postOrder(Order order) {
        return getAction(PostOrder.class)
                .apply(this, order);
    }

    /**
     * Retrieves an instance of the {@link Module} for this instance
     *
     * @return the provider for this instance
     * @throws IllegalArgumentException if the application context is unavailable or the provider does not exist
     */
    @Override
    @SuppressWarnings("unchecked")
    public <T extends Module<A>, A extends Aggregate<AccountEvent, Long>> T getModule() throws
            IllegalArgumentException {
        AccountModule accountProvider = getModule(AccountModule.class);
        return (T) accountProvider;
    }

    /**
     * Returns the {@link Link} with a rel of {@link Link#REL_SELF}.
     */
    @Override
    public Link getId() {
        return linkTo(AccountController.class)
                .slash("accounts")
                .slash(getIdentity())
                .withSelfRel();
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", firstName='" + firstName + '\'' +
                ", lastName='" + lastName + '\'' +
                ", email='" + email + '\'' +
                ", status=" + status +
                "} " + super.toString();
    }
}


text:
[![npm version](https://badge.fury.io/js/react-selectize.svg)](https://badge.fury.io/js/react-selectize)
[![Build Status](https://travis-ci.org/furqanZafar/react-selectize.svg?branch=develop)](https://travis-ci.org/furqanZafar/react-selectize)
[![Coverage Status](https://coveralls.io/repos/furqanZafar/react-selectize/badge.svg?branch=develop&service=github)](https://coveralls.io/github/furqanZafar/react-selectize?branch=develop)

# React Selectize
`ReactSelectize` is a stateless Select component for ReactJS, that provides a platform for the more developer friendly `SimpleSelect` & `MultiSelect` components.

Both `SimpleSelect` & `MultiSelect` have been designed to work as drop in replacement for the built-in `React.DOM.Select` component.

styles & features inspired by [React Select](http://jedwatson.github.io/react-select/) & [Selectize](http://brianreavis.github.io/selectize.js/).

**DEMO / Examples**: [furqanZafar.github.io/react-selectize](http://furqanZafar.github.io/react-selectize/)

[![](http://i.imgsafe.co/rQmogzn.gif)](http://furqanZafar.github.io/react-selectize/)

- [Changelog](CHANGELOG.md) (last updated on 29th July 2017)
- [API Reference](API.md)

# Motivation
* existing components do not behave like built-in React.DOM.* components.
* existing components [synchronize props with state](http://facebook.github.io/react/tips/props-in-getInitialState-as-anti-pattern.html) an anti pattern, which makes them prone to bugs & difficult for contributers to push new features without breaking something else.
* more features.

## Features
* [Drop in replacement for React.DOM.Select](http://furqanzafar.github.io/react-selectize/#/?category=simple&example=drop-in-replacement-for-react.dom.select)
* [Customizable themes](http://furqanzafar.github.io/react-selectize/#/?category=simple&example=themes)
* Stateless, therefore extremely flexible & extensible
* Clean and compact API fully documented on GitHub
* [Multiselect support](http://furqanzafar.github.io/react-selectize/#/?category=multi&example=multi-select)
* [Option groups](http://furqanzafar.github.io/react-selectize/#/?category=multi&example=option-groups)
* [Custom filtering & option object](http://furqanzafar.github.io/react-selectize/#/?category=multi&example=custom-filtering-and-rendering)
* [Search highlighting](http://furqanzafar.github.io/react-selectize/#/?category=simple&example=search-highlighting)
* [Custom option & value rendering](http://furqanzafar.github.io/react-selectize/#/?category=simple&example=custom-option-and-value-rendering)
* [Animated dropdown](http://furqanzafar.github.io/react-selectize/#/?category=multi&example=animated-dropdown)
* [Remote data loading](http://furqanzafar.github.io/react-selectize/#/?category=simple&example=remote-options)
* [Tagging or item creation](http://furqanzafar.github.io/react-selectize/#/?category=multi&example=tags)
* [Restore on backspace](http://furqanzafar.github.io/react-selectize/#/?category=simple&example=restore-on-backspace)
* [Editable value](http://furqanzafar.github.io/react-selectize/#/?category=simple&example=editable-value)
* [Caret between items](http://furqanzafar.github.io/react-selectize/#/?category=multi&example=tags)
* [Customizable dropdown direction](http://furqanzafar.github.io/react-selectize/#/?category=multi&example=dropdown-direction)
* [Mark options as unselectable](http://furqanzafar.github.io/react-selectize/#/?category=simple&example=selectability)
* [Disable selected values](http://furqanzafar.github.io/react-selectize/#/?category=multi&example=disable-selected)
* [Absolute positioned overlay, "Tether"ed to the search field](http://furqanzafar.github.io/react-selectize/#/?category=multi&example=tether)

## Deps
* [tether](https://github.com/HubSpot/tether)

## Peer Deps
* create-react-class
* react
* react-dom
* react-transition-group
* react-dom-factories

## Install

* **npm:**
`npm install react-selectize`

your package.json must look like this
```
{
    "dependencies": {
        "react": "^16.0.0-beta.2",
        "react-addons-css-transition-group": "^15.6.0",
        "react-addons-shallow-compare": "^15.6.0",
        "react-dom": "^16.0.0-beta.2",
        "react-dom-factories": "^1.0.0",
        "react-selectize": "^3.0.1",
        "react-transition-group": "^1.1.2"
    }
}
```

to include the default styles add the following import statement to your stylus file:
`@import 'node_modules/react-selectize/themes/index.css'`

* **bower:**
`bower install https://unpkg.com/react-selectize@3.0.1/bower.zip`

* **1998 script tag:**
```html
<html>
 <head>
  <!-- PRELUDE -->
  <script src="http://www.preludels.com/prelude-browser-min.js" type="text/javascript" ></script>
  <script src="https://unpkg.com/prelude-extension@0.0.11/dist/index.min.js" type="text/javascript" ></script>

  <!-- REACT -->
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-with-addons.min.js"></script>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.min.js"></script>
  <script type="text/javascript" src="https://unpkg.com/react-dom-factories@1.0.0"></script>

  <!-- optional dependency (only required with using the tether prop) -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.1.1/js/tether.min.js" type="text/javascript" ></script>

  <!-- REACT SELECTIZE -->
  <script src="https://unpkg.com/react-selectize@3.0.1/dist/index.min.js" type="text/javascript" ></script>

  <!-- THEMES (default, bootstrap3, material) -->
  <link rel="stylesheet" href="https://unpkg.com/react-selectize@3.0.1/dist/index.min.css"/>

 </head>
 <body>
  <div id="mount-node"></div>
  <script type="text/javascript">
   ReactDOM.render(
    React.createElement(reactSelectize.SimpleSelect, {
     style: {width: 300},
     tether: true,
     placeholder: "Select fruit",
     options: [{label: "apple", value: "apple"}, {label: "banana", value: "banana"}]
    }),
    document.getElementById("mount-node")
   );
  </script>
 </body>
</html>
```

## Usage (jsx)
```jsx
import React, {Component} from 'react';
import {ReactSelectize, SimpleSelect, MultiSelect} from 'react-selectize';
.
.
.
<SimpleSelect placeholder="Select a fruit" onValueChange={value => alert(value)}>
  <option value = "apple">apple</option>
  <option value = "mango">mango</option>
  <option value = "orange">orange</option>
  <option value = "banana">banana</option>
</SimpleSelect>
.
.
.
// Note: options can be passed as props as well, for example
<MultiSelect
    placeholder = "Select fruits"
    options = {["apple", "mango", "orange", "banana"].map(
      fruit => ({label: fruit, value: fruit})
    )}
    onValuesChange = {value => alert(value)}
/>
```

## Usage (livescript)
```LiveScript
{create-factory}:React = require \react
{SimpleSelect, MultiSelect, ReactSelectize} = require \react-selectize
SimpleSelect = create-factory SimpleSelect
MultiSelect = create-factory MultiSelect
.
.
.
SimpleSelect do
    placeholder: 'Select a fruit'
    options: <[apple mango orange banana]> |> map ~> label: it, value: it
    on-value-change: (value) ~>
        alert value
.
.
.
MultiSelect do
    placeholder: 'Select fruits'
    options: <[apple mango orange banana]> |> map ~> label: it, value: it
    on-values-change: (values) ~>
        alert values
```

## Gotchas
* the default structure of an option object is `{label: String, value :: a}` where `a` implies that `value` property can be of any equatable type

* SimpleSelect notifies change via `onValueChange` prop whereas MultiSelect notifies change via `onValuesChange` prop

* the onValueChange callback for SimpleSelect is passed 1 parameter. the `selected option object` (instead of the value property of the option object)

* the onValuesChange callback for MultiSelect is passed 1 parameter an Array  of selected option objects (instead of a collection of the value properties or a comma separated string of value properties)

* both the SimpleSelect & MultiSelect will manage the `open`, `search`, `value` & `anchor` props using internal state, if they are not provided via props:
when passing `open`, `search`, `value` or `anchor` via props, you must update them on*Change (just like in the case of standard react html input components)
``` jsx
value = {state.selectedValue}
onValueChange = {function(value){
    self.setState({selectedValue: value});
}}
search = {state.search}
onSearchChange = {function(value){
    self.setState({search: value});
}}
```

* when using custom option object, you should implement the `uid` function which accepts an option object and returns a unique id, for example:
``` jsx
// assuming the type of our option object is:
// {firstName :: String, lastName :: String, age :: Int}
uid = {function(item){
    return item.firstName + item.lastName;
}}
```
the `uid` function is used internally for performance optimization.

## Development
* `npm install`
* `npm start`
* visit `localhost:8000`
* `npm test` , `npm run coverage` for unit tests & coverage
* for production build/test run `MINIFY=true gulp`


text:
namespace metaforce {
u16 CObjectReference::RemoveReference() {
  --x0_refCount;
  if (x0_refCount == 0) {
    if (x10_object)
      Unload();
    if (IsLoading())
      CancelLoad();
    if (xC_objectStore)
      xC_objectStore->ObjectUnreferenced(x4_objTag);
  }
  return x0_refCount;
}

CObjectReference::CObjectReference(IObjectStore& objStore, std::unique_ptr<IObj>&& obj, const SObjectTag& objTag,
                                   CVParamTransfer buildParams)
: x4_objTag(objTag), xC_objectStore(&objStore), x10_object(std::move(obj)), x14_params(std::move(buildParams)) {}
CObjectReference::CObjectReference(std::unique_ptr<IObj>&& obj) : x10_object(std::move(obj)) {}

void CObjectReference::Unlock() {
  --x2_lockCount;
  if (x2_lockCount)
    return;
  if (x10_object && xC_objectStore)
    Unload();
  else if (IsLoading())
    CancelLoad();
}

void CObjectReference::Lock() {
  ++x2_lockCount;
  if (!x10_object && !x3_loading) {
    IFactory& fac = xC_objectStore->GetFactory();
    fac.BuildAsync(x4_objTag, x14_params, &x10_object, this);
    x3_loading = !x10_object.operator bool();
  }
}

void CObjectReference::CancelLoad() {
  if (xC_objectStore && IsLoading()) {
    xC_objectStore->GetFactory().CancelBuild(x4_objTag);
    x3_loading = false;
  }
}

void CObjectReference::Unload() {
  x10_object.reset();
  x3_loading = false;
}

IObj* CObjectReference::GetObject() {
  if (!x10_object) {
    IFactory& factory = xC_objectStore->GetFactory();
    x10_object = factory.Build(x4_objTag, x14_params, this);
  }
  x3_loading = false;
  return x10_object.get();
}

CObjectReference::~CObjectReference() {
  if (x10_object)
    x10_object.reset();
  else if (x3_loading)
    xC_objectStore->GetFactory().CancelBuild(x4_objTag);
}

void CToken::RemoveRef() {
  if (x0_objRef && x0_objRef->RemoveReference() == 0) {
    std::default_delete<CObjectReference>()(x0_objRef);
    x0_objRef = nullptr;
  }
}

CToken::CToken(CObjectReference* obj) {
  x0_objRef = obj;
  ++x0_objRef->x0_refCount;
}

void CToken::Unlock() {
  if (x0_objRef && x4_lockHeld) {
    x0_objRef->Unlock();
    x4_lockHeld = false;
  }
}
void CToken::Lock() {
  if (x0_objRef && !x4_lockHeld) {
    x0_objRef->Lock();
    x4_lockHeld = true;
  }
}
bool CToken::IsLoaded() const {
  if (!x0_objRef || !x4_lockHeld)
    return false;
  return x0_objRef->IsLoaded();
}
IObj* CToken::GetObj() {
  if (!x0_objRef)
    return nullptr;
  Lock();
  return x0_objRef->GetObject();
}
CToken& CToken::operator=(const CToken& other) {
  Unlock();
  RemoveRef();
  x0_objRef = other.x0_objRef;
  if (x0_objRef) {
    ++x0_objRef->x0_refCount;
    if (other.x4_lockHeld)
      Lock();
  }
  return *this;
}
CToken& CToken::operator=(CToken&& other) noexcept {
  Unlock();
  RemoveRef();
  x0_objRef = other.x0_objRef;
  other.x0_objRef = nullptr;
  x4_lockHeld = other.x4_lockHeld;
  other.x4_lockHeld = false;
  return *this;
}
CToken::CToken(const CToken& other) : x0_objRef(other.x0_objRef) {
  if (x0_objRef) {
    ++x0_objRef->x0_refCount;
    if (other.x4_lockHeld)
      Lock();
  }
}
CToken::CToken(CToken&& other) noexcept : x0_objRef(other.x0_objRef), x4_lockHeld(other.x4_lockHeld) {
  other.x0_objRef = nullptr;
  other.x4_lockHeld = false;
}
CToken::CToken(IObj* obj) {
  x0_objRef = new CObjectReference(std::unique_ptr<IObj>(obj));
  ++x0_objRef->x0_refCount;
  Lock();
}
CToken::CToken(std::unique_ptr<IObj>&& obj) {
  x0_objRef = new CObjectReference(std::move(obj));
  ++x0_objRef->x0_refCount;
  Lock();
}
const SObjectTag* CToken::GetObjectTag() const {
  if (!x0_objRef)
    return nullptr;
  return &x0_objRef->GetObjectTag();
}
CToken::~CToken() {
  if (x0_objRef) {
    if (x4_lockHeld)
      x0_objRef->Unlock();
    RemoveRef();
  }
}

} // namespace metaforce


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

#include "components/viz/host/gpu_host_impl.h"

#include <utility>

#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/feature_list.h"
#include "base/metrics/histogram_macros.h"
#include "base/no_destructor.h"
#include "base/process/process_handle.h"
#include "base/strings/strcat.h"
#include "base/threading/thread_checker.h"
#include "base/trace_event/trace_event.h"
#include "base/values.h"
#include "build/build_config.h"
#include "components/viz/common/buildflags.h"
#include "components/viz/common/features.h"
#include "gpu/config/gpu_driver_bug_workaround_type.h"
#include "gpu/config/gpu_feature_info.h"
#include "gpu/config/gpu_finch_features.h"
#include "gpu/config/gpu_info.h"
#include "gpu/ipc/common/gpu_client_ids.h"
#include "gpu/ipc/host/gpu_disk_cache.h"
#include "mojo/public/cpp/bindings/sync_call_restrictions.h"
#include "ui/gfx/font_render_params.h"

#if BUILDFLAG(IS_ANDROID)
#include "base/android/build_info.h"
#endif

#if BUILDFLAG(IS_WIN)
#include "ui/gfx/win/rendering_window_manager.h"
#elif BUILDFLAG(IS_MAC)
#include "ui/accelerated_widget_mac/window_resize_helper_mac.h"
#endif

#if BUILDFLAG(IS_OZONE)
#include "ui/ozone/public/gpu_platform_support_host.h"
#include "ui/ozone/public/ozone_platform.h"
#endif

namespace viz {
namespace {

// A wrapper around gfx::FontRenderParams that checks it is set and accessed on
// the same thread.
class FontRenderParams {
 public:
  FontRenderParams(const FontRenderParams&) = delete;
  FontRenderParams& operator=(const FontRenderParams&) = delete;

  void Set(const gfx::FontRenderParams& params);
  void Reset();
  const absl::optional<gfx::FontRenderParams>& Get();

 private:
  friend class base::NoDestructor<FontRenderParams>;

  FontRenderParams();
  ~FontRenderParams();

  THREAD_CHECKER(thread_checker_);
  absl::optional<gfx::FontRenderParams> params_;
};

void FontRenderParams::Set(const gfx::FontRenderParams& params) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  params_ = params;
}

void FontRenderParams::Reset() {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  params_ = absl::nullopt;
}

const absl::optional<gfx::FontRenderParams>& FontRenderParams::Get() {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  return params_;
}

FontRenderParams::FontRenderParams() = default;

FontRenderParams::~FontRenderParams() {
  NOTREACHED();
}

FontRenderParams& GetFontRenderParams() {
  static base::NoDestructor<FontRenderParams> instance;
  return *instance;
}

}  // namespace

GpuHostImpl::InitParams::InitParams() = default;

GpuHostImpl::InitParams::InitParams(InitParams&&) = default;

GpuHostImpl::InitParams::~InitParams() = default;

GpuHostImpl::GpuHostImpl(Delegate* delegate,
                         mojo::PendingRemote<mojom::VizMain> viz_main,
                         InitParams params)
    : delegate_(delegate),
      viz_main_(std::move(viz_main)),
      params_(std::move(params)) {
  // Create a special GPU info collection service if the GPU process is used for
  // info collection only.
#if BUILDFLAG(IS_WIN)
  if (params_.info_collection_gpu_process) {
    viz_main_->CreateInfoCollectionGpuService(
        info_collection_gpu_service_remote_.BindNewPipeAndPassReceiver());
    return;
  }
#endif

  DCHECK(delegate_);

  mojo::PendingRemote<discardable_memory::mojom::DiscardableSharedMemoryManager>
      discardable_manager_remote;
  delegate_->BindDiscardableMemoryReceiver(
      discardable_manager_remote.InitWithNewPipeAndPassReceiver());

  DCHECK(GetFontRenderParams().Get());
  scoped_refptr<base::SequencedTaskRunner> task_runner = nullptr;
#if BUILDFLAG(IS_MAC)
  if (params_.main_thread_task_runner->BelongsToCurrentThread())
    task_runner = ui::WindowResizeHelperMac::Get()->task_runner();
#endif

#if BUILDFLAG(IS_ANDROID)
  viz_main_->SetHostProcessId(base::GetCurrentProcId());
#endif

  viz_main_->CreateGpuService(
      gpu_service_remote_.BindNewPipeAndPassReceiver(task_runner),
      gpu_host_receiver_.BindNewPipeAndPassRemote(task_runner),
      std::move(discardable_manager_remote), activity_flags_.CloneRegion(),
      GetFontRenderParams().Get()->subpixel_rendering);

#if BUILDFLAG(IS_OZONE)
  InitOzone();
#endif  // BUILDFLAG(IS_OZONE)
}

GpuHostImpl::~GpuHostImpl() {
  SendOutstandingReplies();
}

// static
void GpuHostImpl::InitFontRenderParams(const gfx::FontRenderParams& params) {
  DCHECK(!GetFontRenderParams().Get());
  GetFontRenderParams().Set(params);
}

// static
void GpuHostImpl::ResetFontRenderParams() {
  DCHECK(GetFontRenderParams().Get());
  GetFontRenderParams().Reset();
}

void GpuHostImpl::SetProcessId(base::ProcessId pid) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK_EQ(base::kNullProcessId, pid_);
  DCHECK_NE(base::kNullProcessId, pid);
  pid_ = pid;
}

void GpuHostImpl::OnProcessCrashed() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  // If the GPU process crashed while compiling a shader, we may have invalid
  // cached binaries. Completely clear the shader cache to force shader binaries
  // to be re-created.
  if (activity_flags_.IsFlagSet(
          gpu::ActivityFlagsBase::FLAG_LOADING_PROGRAM_BINARY)) {
    auto* gpu_disk_cache_factory = delegate_->GetGpuDiskCacheFactory();
    for (auto& [_, cache] : client_id_to_caches_) {
      // This call will temporarily extend the lifetime of the cache (kept
      // alive in the factory), and may drop loads of cached shader binaries if
      // it takes a while to complete. As we are intentionally dropping all
      // binaries, this behavior is fine.
      gpu_disk_cache_factory->ClearByCache(
          cache, base::Time(), base::Time::Max(), base::DoNothing());
    }
  }
}

void GpuHostImpl::AddConnectionErrorHandler(base::OnceClosure handler) {
  connection_error_handlers_.push_back(std::move(handler));
}

void GpuHostImpl::BlockLiveOffscreenContexts() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  std::set<GURL> urls(urls_with_live_offscreen_contexts_.begin(),
                      urls_with_live_offscreen_contexts_.end());
  delegate_->BlockDomainsFrom3DAPIs(urls, gpu::DomainGuilt::kUnknown);
}

void GpuHostImpl::ConnectFrameSinkManager(
    mojo::PendingReceiver<mojom::FrameSinkManager> receiver,
    mojo::PendingRemote<mojom::FrameSinkManagerClient> client,
    const DebugRendererSettings& debug_renderer_settings) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  TRACE_EVENT0("gpu", "GpuHostImpl::ConnectFrameSinkManager");

  mojom::FrameSinkManagerParamsPtr params =
      mojom::FrameSinkManagerParams::New();
  params->restart_id = params_.restart_id;
  params->use_activation_deadline =
      params_.deadline_to_synchronize_surfaces.has_value();
  params->activation_deadline_in_frames =
      params_.deadline_to_synchronize_surfaces.value_or(0u);
  params->frame_sink_manager = std::move(receiver);
  params->frame_sink_manager_client = std::move(client);
  params->debug_renderer_settings = debug_renderer_settings;
  viz_main_->CreateFrameSinkManager(std::move(params));
}

void GpuHostImpl::EstablishGpuChannel(int client_id,
                                      uint64_t client_tracing_id,
                                      bool is_gpu_host,
                                      bool sync,
                                      EstablishChannelCallback callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  TRACE_EVENT0("gpu", "GpuHostImpl::EstablishGpuChannel");

  shutdown_timeout_.Stop();

  // If GPU features are already blocklisted, no need to establish the channel.
  if (!delegate_->GpuAccessAllowed()) {
    DVLOG(1) << "GPU access blocked, refusing to open a GPU channel.";
    std::move(callback).Run(mojo::ScopedMessagePipeHandle(), gpu::GPUInfo(),
                            gpu::GpuFeatureInfo(),
                            EstablishChannelStatus::kGpuAccessDenied);
    return;
  }

  if (gpu::IsReservedClientId(client_id)) {
    // The display-compositor/GrShaderCache in the gpu process uses these
    // special client ids.
    std::move(callback).Run(mojo::ScopedMessagePipeHandle(), gpu::GPUInfo(),
                            gpu::GpuFeatureInfo(),
                            EstablishChannelStatus::kGpuAccessDenied);
    return;
  }

  channel_requests_[client_id] = std::move(callback);
  if (sync) {
    mojo::ScopedMessagePipeHandle channel_handle;
    gpu::GPUInfo gpu_info;
    gpu::GpuFeatureInfo gpu_feature_info;
    {
      mojo::SyncCallRestrictions::ScopedAllowSyncCall scoped_allow;
      gpu_service_remote_->EstablishGpuChannel(client_id, client_tracing_id,
                                               is_gpu_host, &channel_handle,
                                               &gpu_info, &gpu_feature_info);
    }
    OnChannelEstablished(client_id, true, std::move(channel_handle), gpu_info,
                         gpu_feature_info);
  } else {
    gpu_service_remote_->EstablishGpuChannel(
        client_id, client_tracing_id, is_gpu_host,
        base::BindOnce(&GpuHostImpl::OnChannelEstablished,
                       weak_ptr_factory_.GetWeakPtr(), client_id, false));
  }

  // The gpu host channel uses the same cache as the compositor client.
  if (is_gpu_host) {
    SetChannelDiskCacheHandle(client_id,
                              gpu::kDisplayCompositorGpuDiskCacheHandle);
  }
}

void GpuHostImpl::SetChannelClientPid(int client_id,
                                      base::ProcessId client_pid) {
  gpu_service_remote_->SetChannelClientPid(client_id, client_pid);
}

void GpuHostImpl::SetChannelDiskCacheHandle(
    int client_id,
    const gpu::GpuDiskCacheHandle& handle) {
  if (params_.disable_gpu_shader_disk_cache) {
    return;
  }

  scoped_refptr<gpu::GpuDiskCache> cache =
      delegate_->GetGpuDiskCacheFactory()->Get(handle);
  if (!cache) {
    // Create the cache if necessary and save a reference.
    cache = delegate_->GetGpuDiskCacheFactory()->Create(
        handle,
        base::BindRepeating(&GpuHostImpl::LoadedBlob,
                            weak_ptr_factory_.GetWeakPtr()),
        base::BindOnce(&GpuHostImpl::OnDiskCacheHandleDestoyed,
                       weak_ptr_factory_.GetWeakPtr()));
    if (!cache) {
      return;
    }
  }

  client_id_to_caches_.emplace(client_id, cache);
  gpu_service_remote_->SetChannelDiskCacheHandle(client_id, handle);
}

void GpuHostImpl::RemoveChannelDiskCacheHandles(int client_id) {
  // Release the handle, then release the cache.
  auto [start, end] = client_id_to_caches_.equal_range(client_id);
  for (auto it = start; it != end; ++it) {
    delegate_->GetGpuDiskCacheFactory()->ReleaseCacheHandle(it->second.get());
  }
  client_id_to_caches_.erase(client_id);
}

void GpuHostImpl::CloseChannel(int client_id) {
  gpu_service_remote_->CloseChannel(client_id);

  channel_requests_.erase(client_id);
}

#if BUILDFLAG(USE_VIZ_DEBUGGER)
void GpuHostImpl::FilterVisualDebugStream(base::Value json) {
  viz_main_->FilterDebugStream(std::move(json));
}

void GpuHostImpl::StartVisualDebugStream(
    base::RepeatingCallback<void(base::Value)> callback) {
  viz_debug_output_callback_ = std::move(callback);
  viz_main_->StartDebugStream(viz_debug_output_.BindNewPipeAndPassRemote());
}

void GpuHostImpl::StopVisualDebugStream() {
  viz_main_->StopDebugStream();
  viz_debug_output_.reset();
}
#endif

void GpuHostImpl::SendOutstandingReplies() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  for (auto& handler : connection_error_handlers_)
    std::move(handler).Run();
  connection_error_handlers_.clear();

  // Send empty channel handles for all EstablishChannel requests.
  for (auto& entry : channel_requests_) {
    std::move(entry.second)
        .Run(mojo::ScopedMessagePipeHandle(), gpu::GPUInfo(),
             gpu::GpuFeatureInfo(), EstablishChannelStatus::kGpuHostInvalid);
  }
  channel_requests_.clear();
}

void GpuHostImpl::BindInterface(const std::string& interface_name,
                                mojo::ScopedMessagePipeHandle interface_pipe) {
  delegate_->BindInterface(interface_name, std::move(interface_pipe));
}

mojom::GpuService* GpuHostImpl::gpu_service() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(gpu_service_remote_.is_bound());
  return gpu_service_remote_.get();
}

#if BUILDFLAG(IS_WIN)
mojom::InfoCollectionGpuService* GpuHostImpl::info_collection_gpu_service() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(info_collection_gpu_service_remote_.is_bound());
  return info_collection_gpu_service_remote_.get();
}
#endif

#if BUILDFLAG(IS_OZONE)

void GpuHostImpl::InitOzone() {
  // Ozone needs to send the primary DRM device to GPU service as early as
  // possible to ensure the latter always has a valid device.
  // https://crbug.com/608839
  //
  // The Ozone/Wayland requires mojo communication to be established to be
  // functional with a separate gpu process. Thus, using the PlatformProperties,
  // check if there is such a requirement.
  auto interface_binder = base::BindRepeating(&GpuHostImpl::BindInterface,
                                              weak_ptr_factory_.GetWeakPtr());
  auto terminate_callback = base::BindOnce(&GpuHostImpl::TerminateGpuProcess,
                                           weak_ptr_factory_.GetWeakPtr());

  ui::OzonePlatform::GetInstance()
      ->GetGpuPlatformSupportHost()
      ->OnGpuServiceLaunched(params_.restart_id, interface_binder,
                             std::move(terminate_callback));
}

void GpuHostImpl::TerminateGpuProcess(const std::string& message) {
  delegate_->TerminateGpuProcess(message);
}

#endif  // BUILDFLAG(IS_OZONE)

std::string GpuHostImpl::GetShaderPrefixKey() {
  if (shader_prefix_key_.empty()) {
    const gpu::GPUInfo& info = delegate_->GetGPUInfo();
    const gpu::GPUInfo::GPUDevice& active_gpu = info.active_gpu();

    shader_prefix_key_ = params_.product + "-" + info.gl_vendor + "-" +
                         info.gl_renderer + "-" + active_gpu.driver_version +
                         "-" + active_gpu.driver_vendor;

#if BUILDFLAG(IS_ANDROID)
    std::string build_fp =
        base::android::BuildInfo::GetInstance()->android_build_fp();
    shader_prefix_key_ += "-" + build_fp;
#endif
  }

  return shader_prefix_key_;
}

void GpuHostImpl::LoadedBlob(const gpu::GpuDiskCacheHandle& handle,
                             const std::string& key,
                             const std::string& data) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  TRACE_EVENT1("gpu", "GpuHostImpl::LoadedBlob", "handle_type",
               GetHandleType(handle));
  switch (gpu::GetHandleType(handle)) {
    case gpu::GpuDiskCacheType::kGlShaders: {
      std::string prefix = GetShaderPrefixKey();
      bool prefix_ok = !key.compare(0, prefix.length(), prefix);
      UMA_HISTOGRAM_BOOLEAN("GPU.ShaderLoadPrefixOK", prefix_ok);
      if (prefix_ok) {
        // Remove the prefix from the key before load.
        std::string key_no_prefix = key.substr(prefix.length() + 1);
        gpu_service_remote_->LoadedBlob(handle, key_no_prefix, data);
      }
      break;
    }
    case gpu::GpuDiskCacheType::kDawnWebGPU: {
      gpu_service_remote_->LoadedBlob(handle, key, data);
      break;
    }
  }
}

void GpuHostImpl::OnDiskCacheHandleDestoyed(
    const gpu::GpuDiskCacheHandle& handle) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  gpu_service_remote_->OnDiskCacheHandleDestoyed(handle);
}

void GpuHostImpl::OnChannelEstablished(
    int client_id,
    bool sync,
    mojo::ScopedMessagePipeHandle channel_handle,
    const gpu::GPUInfo& gpu_info,
    const gpu::GpuFeatureInfo& gpu_feature_info) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  TRACE_EVENT0("gpu", "GpuHostImpl::OnChannelEstablished");

  auto it = channel_requests_.find(client_id);
  if (it == channel_requests_.end())
    return;

  auto callback = std::move(it->second);
  channel_requests_.erase(it);

  // Currently if any of the GPU features are blocklisted, we don't establish a
  // GPU channel.
  if (channel_handle.is_valid() && !delegate_->GpuAccessAllowed()) {
    gpu_service_remote_->CloseChannel(client_id);
    std::move(callback).Run(mojo::ScopedMessagePipeHandle(), gpu::GPUInfo(),
                            gpu::GpuFeatureInfo(),
                            EstablishChannelStatus::kGpuAccessDenied);
    RecordLogMessage(logging::LOG_WARNING, "WARNING",
                     "Hardware acceleration is unavailable.");
    return;
  }

  // TODO(jam): always use GPUInfo & GpuFeatureInfo from the service once we
  // know there's no issue with the ProcessHostOnUI which is the only mode
  // that currently uses it. This is because in that mode the sync mojo call
  // in the caller means we won't get the async DidInitialize() call before
  // this point, so the delegate_ methods won't have the GPU info structs yet.
  if (sync) {
    std::move(callback).Run(std::move(channel_handle), gpu_info,
                            gpu_feature_info, EstablishChannelStatus::kSuccess);
  } else {
    std::move(callback).Run(std::move(channel_handle), delegate_->GetGPUInfo(),
                            delegate_->GetGpuFeatureInfo(),
                            EstablishChannelStatus::kSuccess);
  }
}

void GpuHostImpl::DidInitialize(
    const gpu::GPUInfo& gpu_info,
    const gpu::GpuFeatureInfo& gpu_feature_info,
    const absl::optional<gpu::GPUInfo>& gpu_info_for_hardware_gpu,
    const absl::optional<gpu::GpuFeatureInfo>&
        gpu_feature_info_for_hardware_gpu,
    const gfx::GpuExtraInfo& gpu_extra_info) {
  UMA_HISTOGRAM_BOOLEAN("GPU.GPUProcessInitialized", true);

  delegate_->DidInitialize(gpu_info, gpu_feature_info,
                           gpu_info_for_hardware_gpu,
                           gpu_feature_info_for_hardware_gpu, gpu_extra_info);

  if (!params_.disable_gpu_shader_disk_cache) {
    SetChannelDiskCacheHandle(gpu::kDisplayCompositorClientId,
                              gpu::kDisplayCompositorGpuDiskCacheHandle);
    SetChannelDiskCacheHandle(gpu::kGrShaderCacheClientId,
                              gpu::kGrShaderGpuDiskCacheHandle);
  }
}

void GpuHostImpl::DidFailInitialize() {
  UMA_HISTOGRAM_BOOLEAN("GPU.GPUProcessInitialized", false);
  delegate_->DidFailInitialize();
}

void GpuHostImpl::DidCreateContextSuccessfully() {
  delegate_->DidCreateContextSuccessfully();
}

void GpuHostImpl::DidCreateOffscreenContext(const GURL& url) {
  urls_with_live_offscreen_contexts_.insert(url);
}

void GpuHostImpl::DidDestroyOffscreenContext(const GURL& url) {
  // We only want to remove *one* of the entries in the multiset for this
  // particular URL, so can't use the erase method taking a key.
  auto candidate = urls_with_live_offscreen_contexts_.find(url);
  if (candidate != urls_with_live_offscreen_contexts_.end())
    urls_with_live_offscreen_contexts_.erase(candidate);
}

void GpuHostImpl::DidDestroyChannel(int32_t client_id) {
  TRACE_EVENT0("gpu", "GpuHostImpl::DidDestroyChannel");
  client_id_to_caches_.erase(client_id);
}

void GpuHostImpl::DidDestroyAllChannels() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  if (!channel_requests_.empty())
    return;
  constexpr base::TimeDelta kShutDownTimeout = base::Seconds(10);
  shutdown_timeout_.Start(FROM_HERE, kShutDownTimeout,
                          base::BindOnce(&GpuHostImpl::MaybeShutdownGpuProcess,
                                         base::Unretained(this)));
}

void GpuHostImpl::MaybeShutdownGpuProcess() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(channel_requests_.empty());
  delegate_->MaybeShutdownGpuProcess();
}

void GpuHostImpl::DidLoseContext(bool offscreen,
                                 gpu::error::ContextLostReason reason,
                                 const GURL& active_url) {
  // TODO(kbr): would be nice to see the "offscreen" flag too.
  TRACE_EVENT2("gpu", "GpuHostImpl::DidLoseContext", "reason", reason, "url",
               active_url.possibly_invalid_spec());

  if (active_url.is_empty()) {
    return;
  }

  gpu::DomainGuilt guilt = gpu::DomainGuilt::kUnknown;
  switch (reason) {
    case gpu::error::kGuilty:
      guilt = gpu::DomainGuilt::kKnown;
      break;
    // Treat most other error codes as though they had unknown provenance.
    // In practice this doesn't affect the user experience. A lost context
    // of either known or unknown guilt still causes user-level 3D APIs
    // (e.g. WebGL) to be blocked on that domain until the user manually
    // reenables them.
    case gpu::error::kUnknown:
    case gpu::error::kOutOfMemory:
    case gpu::error::kMakeCurrentFailed:
    case gpu::error::kGpuChannelLost:
    case gpu::error::kInvalidGpuMessage:
      break;
    case gpu::error::kInnocent:
      return;
  }

  std::set<GURL> urls{active_url};
  delegate_->BlockDomainsFrom3DAPIs(urls, guilt);
}

void GpuHostImpl::DisableGpuCompositing() {
  delegate_->DisableGpuCompositing();
}

void GpuHostImpl::GetIsolationKey(
    int32_t client_id,
    const blink::WebGPUExecutionContextToken& token,
    GetIsolationKeyCallback cb) {
  std::string isolation_key = delegate_->GetIsolationKey(client_id, token);
  std::move(cb).Run(isolation_key);
}

void GpuHostImpl::DidUpdateGPUInfo(const gpu::GPUInfo& gpu_info) {
  delegate_->DidUpdateGPUInfo(gpu_info);
}

#if BUILDFLAG(IS_WIN)
void GpuHostImpl::DidUpdateOverlayInfo(const gpu::OverlayInfo& overlay_info) {
  delegate_->DidUpdateOverlayInfo(overlay_info);
}

void GpuHostImpl::DidUpdateDXGIInfo(gfx::mojom::DXGIInfoPtr dxgi_info) {
  delegate_->DidUpdateDXGIInfo(std::move(dxgi_info));
}

void GpuHostImpl::AddChildWindow(gpu::SurfaceHandle parent_window,
                                 gpu::SurfaceHandle child_window) {
  if (pid_ != base::kNullProcessId) {
    gfx::RenderingWindowManager::GetInstance()->RegisterChild(
        parent_window, child_window, /*expected_child_process_id=*/pid_);
  }
}
#endif  // BUILDFLAG(IS_WIN)

void GpuHostImpl::StoreBlobToDisk(const gpu::GpuDiskCacheHandle& handle,
                                  const std::string& key,
                                  const std::string& blob) {
  scoped_refptr<gpu::GpuDiskCache> cache =
      delegate_->GetGpuDiskCacheFactory()->Get(handle);
  if (!cache) {
    return;
  }

  TRACE_EVENT1("gpu", "GpuHostImpl::StoreBlobToDisk", "handle_type",
               GetHandleType(handle));
  switch (GetHandleType(handle)) {
    case gpu::GpuDiskCacheType::kGlShaders: {
      std::string prefix = GetShaderPrefixKey();
      cache->Cache(base::StrCat({prefix, ":", key}), blob);
      break;
    }
    case gpu::GpuDiskCacheType::kDawnWebGPU: {
      cache->Cache(key, blob);
      break;
    }
  }
}

void GpuHostImpl::RecordLogMessage(int32_t severity,
                                   const std::string& header,
                                   const std::string& message) {
  delegate_->RecordLogMessage(severity, header, message);
}

#if BUILDFLAG(USE_VIZ_DEBUGGER)
void GpuHostImpl::LogFrame(base::Value frame_data) {
  if (!viz_debug_output_callback_.is_null())
    viz_debug_output_callback_.Run(std::move(frame_data));
}
#endif

}  // namespace viz


text:
<?php

namespace CP\Terms\DemoBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class CPTermsDemoBundle extends Bundle
{
    public function getParent()
    {
        return 'FOSUserBundle';
    }
}


text:
package com.github.kohanyirobert.sggc;

import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;

import java.util.List;

final class DefaultResponse implements Response {

  private final Status status;
  private final List<Result> results;

  DefaultResponse(Status status, List<Result> results) {
    Preconditions.checkNotNull(status, "null status");
    Preconditions.checkNotNull(results, "null results");
    this.status = status;
    this.results = ImmutableList.copyOf(results);
  }

  @Override
  public Status status() {
    return status;
  }

  @Override
  public List<Result> results() {
    return results;
  }

  @Override
  public int hashCode() {
    return Objects.hashCode(status(), results());
  }

  @Override
  public boolean equals(Object object) {
    if (object instanceof Response) {
      Response other = (Response) object;
      return status().equals(other.status())
          && results().equals(other.results());
    }
    return false;
  }

  @Override
  public String toString() {
    return Objects.toStringHelper(Response.class)
        .add("status", status())
        .add("results", results())
        .toString();
  }
}


text:
package org.axonframework.eventsourcing.eventstore.jdbc.statements;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.time.Instant;

/**
 * Writer interface for writing a formatted timestamp to a {@link PreparedStatement} during updates of the database.
 * Used in {@link AppendEventsStatementBuilder} and {@link AppendSnapshotStatementBuilder}.
 *
 * @author Trond Marius Øvstetun
 * @since 4.4
 */
@FunctionalInterface
public interface TimestampWriter {

    /**
     * Write a timestamp from a {@link Instant} to a data value suitable for the database scheme.
     *
     * @param preparedStatement the statement to update
     * @param position          the position of the timestamp parameter in the statement
     * @param timestamp         {@link Instant} to convert
     * @throws SQLException if modification of the statement fails
     */
    void writeTimestamp(PreparedStatement preparedStatement, int position, Instant timestamp) throws SQLException;
}


text:
<?php

$lLogin = new \GGN\Using('Connect/Login');

$Login = \GGN\Connect\Login\Invoke::Main(['app'=>$arguments]);

$isLogged = $Login->isLoggedApp();

return (is_array($isLogged))?$Login:false;

?>


text:
package htlcswitch

import (
	"github.com/lightningnetwork/lnd/channeldb"
	"github.com/lightningnetwork/lnd/htlcswitch/hop"
	"github.com/lightningnetwork/lnd/lnwire"
	"github.com/lightningnetwork/lnd/record"
)

// htlcPacket is a wrapper around htlc lnwire update, which adds additional
// information which is needed by this package.
type htlcPacket struct {
	// incomingChanID is the ID of the channel that we have received an incoming
	// HTLC on.
	incomingChanID lnwire.ShortChannelID

	// outgoingChanID is the ID of the channel that we have offered or will
	// offer an outgoing HTLC on.
	outgoingChanID lnwire.ShortChannelID

	// incomingHTLCID is the ID of the HTLC that we have received from the peer
	// on the incoming channel.
	incomingHTLCID uint64

	// outgoingHTLCID is the ID of the HTLC that we offered to the peer on the
	// outgoing channel.
	outgoingHTLCID uint64

	// sourceRef is used by forwarded htlcPackets to locate incoming Add
	// entry in a fwdpkg owned by the incoming link. This value can be nil
	// if there is no such entry, e.g. switch initiated payments.
	sourceRef *channeldb.AddRef

	// destRef is used to locate a settle/fail entry in the outgoing link's
	// fwdpkg. If sourceRef is non-nil, this reference should be to a
	// settle/fail in response to the sourceRef.
	destRef *channeldb.SettleFailRef

	// incomingAmount is the value in milli-satoshis that arrived on an
	// incoming link.
	incomingAmount lnwire.MilliSatoshi

	// amount is the value of the HTLC that is being created or modified.
	amount lnwire.MilliSatoshi

	// htlc lnwire message type of which depends on switch request type.
	htlc lnwire.Message

	// obfuscator contains the necessary state to allow the switch to wrap
	// any forwarded errors in an additional layer of encryption.
	obfuscator hop.ErrorEncrypter

	// localFailure is set to true if an HTLC fails for a local payment before
	// the first hop. In this case, the failure reason is simply encoded, not
	// encrypted with any shared secret.
	localFailure bool

	// linkFailure is non-nil for htlcs that fail at our node. This may
	// occur for our own payments which fail on the outgoing link,
	// or for forwards which fail in the switch or on the outgoing link.
	linkFailure *LinkError

	// convertedError is set to true if this is an HTLC fail that was
	// created using an UpdateFailMalformedHTLC from the remote party. If
	// this is true, then when forwarding this failure packet, we'll need
	// to wrap it as if we were the first hop if it's a multi-hop HTLC. If
	// it's a direct HTLC, then we'll decode the error as no encryption has
	// taken place.
	convertedError bool

	// hasSource is set to true if the incomingChanID and incomingHTLCID
	// fields of a forwarded fail packet are already set and do not need to
	// be looked up in the circuit map.
	hasSource bool

	// isResolution is set to true if this packet was actually an incoming
	// resolution message from an outside sub-system. We'll treat these as
	// if they emanated directly from the switch. As a result, we'll
	// encrypt all errors related to this packet as if we were the first
	// hop.
	isResolution bool

	// circuit holds a reference to an Add's circuit which is persisted in
	// the switch during successful forwarding.
	circuit *PaymentCircuit

	// incomingTimeout is the timeout that the incoming HTLC carried. This
	// is the timeout of the HTLC applied to the incoming link.
	incomingTimeout uint32

	// outgoingTimeout is the timeout of the proposed outgoing HTLC. This
	// will be extracted from the hop payload received by the incoming
	// link.
	outgoingTimeout uint32

	// customRecords are user-defined records in the custom type range that
	// were included in the payload.
	customRecords record.CustomSet

	// originalOutgoingChanID is used when sending back failure messages.
	// It is only used for forwarded Adds on option_scid_alias channels.
	// This is to avoid possible confusion if a payer uses the public SCID
	// but receives a channel_update with the alias SCID. Instead, the
	// payer should receive a channel_update with the public SCID.
	originalOutgoingChanID lnwire.ShortChannelID
}

// inKey returns the circuit key used to identify the incoming htlc.
func (p *htlcPacket) inKey() CircuitKey {
	return CircuitKey{
		ChanID: p.incomingChanID,
		HtlcID: p.incomingHTLCID,
	}
}

// outKey returns the circuit key used to identify the outgoing, forwarded htlc.
func (p *htlcPacket) outKey() CircuitKey {
	return CircuitKey{
		ChanID: p.outgoingChanID,
		HtlcID: p.outgoingHTLCID,
	}
}

// keystone returns a tuple containing the incoming and outgoing circuit keys.
func (p *htlcPacket) keystone() Keystone {
	return Keystone{
		InKey:  p.inKey(),
		OutKey: p.outKey(),
	}
}