text:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:fitsSystemWindows="true">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="56dp"
        android:paddingLeft="24dp"
        android:paddingRight="24dp">

        <ImageView
            android:src="@drawable/logo_campus"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="24dp"
            android:layout_gravity="center_horizontal" />

        <!-- Email Label -->
        <android.support.design.widget.TextInputLayout
            android:id="@+id/input_login"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:errorEnabled="true"
            android:layout_marginTop="8dp"
            android:layout_marginBottom="8dp">

            <EditText android:id="@+id/edit_text_login"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textEmailAddress"
                android:hint="Логін" />

        </android.support.design.widget.TextInputLayout>

        <!--  Password Label -->
        <android.support.design.widget.TextInputLayout
            android:id="@+id/input_password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            app:errorEnabled="true"
            android:layout_marginBottom="8dp">

            <EditText android:id="@+id/edit_text_password"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textPassword"
                android:hint="Пароль"/>

        </android.support.design.widget.TextInputLayout>

        <android.support.v7.widget.AppCompatButton
            android:id="@+id/button_login"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="24dp"
            android:layout_marginBottom="24dp"
            android:padding="12dp"
            android:text="Вхід"/>

        <!--<TextView android:id="@+id/text_view_forget_password"-->
            <!--android:layout_width="match_parent"-->
            <!--android:layout_height="wrap_content"-->
            <!--android:layout_marginBottom="24dp"-->
            <!--android:text="Забули пароль?"-->
            <!--android:gravity="center"-->
            <!--android:textSize="16sp"/>-->

        </LinearLayout>
</ScrollView>


text:
"""
iLO Deploy Driver(s) and supporting methods.
"""

from oslo_config import cfg
from oslo_log import log as logging

from ironic.common import boot_devices
from ironic.common import exception
from ironic.common.i18n import _
from ironic.common.i18n import _LW
from ironic.common import states
from ironic.conductor import task_manager
from ironic.conductor import utils as manager_utils
from ironic.drivers.modules import agent
from ironic.drivers.modules import deploy_utils
from ironic.drivers.modules.ilo import boot as ilo_boot
from ironic.drivers.modules.ilo import common as ilo_common
from ironic.drivers.modules import iscsi_deploy
from ironic.drivers.modules import pxe

LOG = logging.getLogger(__name__)

CONF = cfg.CONF

clean_opts = [
    cfg.IntOpt('clean_priority_erase_devices',
               help=_('Priority for erase devices clean step. If unset, '
                      'it defaults to 10. If set to 0, the step will be '
                      'disabled and will not run during cleaning.'))
]

CONF.import_opt('pxe_append_params', 'ironic.drivers.modules.iscsi_deploy',
                group='pxe')
CONF.import_opt('swift_ilo_container', 'ironic.drivers.modules.ilo.common',
                group='ilo')
CONF.register_opts(clean_opts, group='ilo')

def _prepare_agent_vmedia_boot(task):
    """Ejects virtual media devices and prepares for vmedia boot."""
    # Eject all virtual media devices, as we are going to use them
    # during deploy.
    ilo_common.eject_vmedia_devices(task)

    deploy_ramdisk_opts = deploy_utils.build_agent_options(task.node)
    deploy_iso = task.node.driver_info['ilo_deploy_iso']
    ilo_common.setup_vmedia(task, deploy_iso, deploy_ramdisk_opts)
    manager_utils.node_power_action(task, states.REBOOT)

def _disable_secure_boot(task):
    """Disables secure boot on node, if secure boot is enabled on node.

    This method checks if secure boot is enabled on node. If enabled, it
    disables same and returns True.

    :param task: a TaskManager instance containing the node to act on.
    :returns: It returns True, if secure boot was successfully disabled on
              the node.
              It returns False, if secure boot on node is in disabled state
              or if secure boot feature is not supported by the node.
    :raises: IloOperationError, if some operation on iLO failed.
    """
    cur_sec_state = False
    try:
        cur_sec_state = ilo_common.get_secure_boot_mode(task)
    except exception.IloOperationNotSupported:
        LOG.debug('Secure boot mode is not supported for node %s',
                  task.node.uuid)
        return False

    if cur_sec_state:
        LOG.debug('Disabling secure boot for node %s', task.node.uuid)
        ilo_common.set_secure_boot_mode(task, False)
        return True
    return False

def _prepare_node_for_deploy(task):
    """Common preparatory steps for all iLO drivers.

    This method performs common preparatory steps required for all drivers.
    1. Power off node
    2. Disables secure boot, if it is in enabled state.
    3. Updates boot_mode capability to 'uefi' if secure boot is requested.
    4. Changes boot mode of the node if secure boot is disabled currently.

    :param task: a TaskManager instance containing the node to act on.
    :raises: IloOperationError, if some operation on iLO failed.
    """
    manager_utils.node_power_action(task, states.POWER_OFF)

    # Boot mode can be changed only if secure boot is in disabled state.
    # secure boot and boot mode cannot be changed together.
    change_boot_mode = True

    # Disable secure boot on the node if it is in enabled state.
    if _disable_secure_boot(task):
        change_boot_mode = False

    if change_boot_mode:
        ilo_common.update_boot_mode(task)
    else:
        # Need to update boot mode that will be used during deploy, if one is
        # not provided.
        # Since secure boot was disabled, we are in 'uefi' boot mode.
        if deploy_utils.get_boot_mode_for_deploy(task.node) is None:
            instance_info = task.node.instance_info
            instance_info['deploy_boot_mode'] = 'uefi'
            task.node.instance_info = instance_info
            task.node.save()

def _disable_secure_boot_if_supported(task):
    """Disables secure boot on node, does not throw if its not supported.

    :param task: a TaskManager instance containing the node to act on.
    :raises: IloOperationError, if some operation on iLO failed.
    """
    try:
        ilo_common.update_secure_boot_mode(task, False)
    # We need to handle IloOperationNotSupported exception so that if
    # the user has incorrectly specified the Node capability
    # 'secure_boot' to a node that does not have that capability and
    # attempted deploy. Handling this exception here, will help the
    # user to tear down such a Node.
    except exception.IloOperationNotSupported:
        LOG.warning(_LW('Secure boot mode is not supported for node %s'),
                    task.node.uuid)

class IloVirtualMediaIscsiDeploy(iscsi_deploy.ISCSIDeploy):

    def get_properties(self):
        return {}

    @task_manager.require_exclusive_lock
    def tear_down(self, task):
        """Tear down a previous deployment on the task's node.

        Power off the node. All actual clean-up is done in the clean_up()
        method which should be called separately.

        :param task: a TaskManager instance containing the node to act on.
        :returns: deploy state DELETED.
        :raises: IloOperationError, if some operation on iLO failed.
        """

        manager_utils.node_power_action(task, states.POWER_OFF)
        _disable_secure_boot_if_supported(task)
        return super(IloVirtualMediaIscsiDeploy, self).tear_down(task)

    def prepare(self, task):
        """Prepare the deployment environment for this task's node.

        :param task: a TaskManager instance containing the node to act on.
        :raises: IloOperationError, if some operation on iLO failed.
        """
        if task.node.provision_state != states.ACTIVE:
            _prepare_node_for_deploy(task)

        super(IloVirtualMediaIscsiDeploy, self).prepare(task)

    def prepare_cleaning(self, task):
        """Boot into the agent to prepare for cleaning.

        :param task: a TaskManager object containing the node
        :returns: states.CLEANWAIT to signify an asynchronous prepare.
        :raises NodeCleaningFailure: if the previous cleaning ports cannot
            be removed or if new cleaning ports cannot be created
        :raises: IloOperationError, if some operation on iLO failed.
        """
        # Powering off the Node before initiating boot for node cleaning.
        # If node is in system POST, setting boot device fails.
        manager_utils.node_power_action(task, states.POWER_OFF)
        return super(IloVirtualMediaIscsiDeploy, self).prepare_cleaning(task)

class IloVirtualMediaAgentDeploy(agent.AgentDeploy):
    """Interface for deploy-related actions."""

    def get_properties(self):
        """Return the properties of the interface.

        :returns: dictionary of <property name>:<property description> entries.
        """
        return ilo_boot.COMMON_PROPERTIES

    @task_manager.require_exclusive_lock
    def tear_down(self, task):
        """Tear down a previous deployment on the task's node.

        :param task: a TaskManager instance.
        :returns: states.DELETED
        :raises: IloOperationError, if some operation on iLO failed.
        """
        manager_utils.node_power_action(task, states.POWER_OFF)
        _disable_secure_boot_if_supported(task)
        return super(IloVirtualMediaAgentDeploy, self).tear_down(task)

    def prepare(self, task):
        """Prepare the deployment environment for this node.

        :param task: a TaskManager instance.
        :raises: IloOperationError, if some operation on iLO failed.
        """
        if task.node.provision_state != states.ACTIVE:
            _prepare_node_for_deploy(task)

        super(IloVirtualMediaAgentDeploy, self).prepare(task)

    def prepare_cleaning(self, task):
        """Boot into the agent to prepare for cleaning.

        :param task: a TaskManager object containing the node
        :returns: states.CLEANWAIT to signify an asynchronous prepare.
        :raises NodeCleaningFailure: if the previous cleaning ports cannot
            be removed or if new cleaning ports cannot be created
        :raises: IloOperationError, if some operation on iLO failed.
        """
        # Powering off the Node before initiating boot for node cleaning.
        # If node is in system POST, setting boot device fails.
        manager_utils.node_power_action(task, states.POWER_OFF)
        return super(IloVirtualMediaAgentDeploy, self).prepare_cleaning(task)

    def get_clean_steps(self, task):
        """Get the list of clean steps from the agent.

        :param task: a TaskManager object containing the node
        :raises NodeCleaningFailure: if the clean steps are not yet
            available (cached), for example, when a node has just been
            enrolled and has not been cleaned yet.
        :returns: A list of clean step dictionaries
        """

        # TODO(stendulker): All drivers use CONF.deploy.erase_devices_priority
        # agent_ilo driver should also use the same. Defect has been filed for
        # the same.
        # https://bugs.launchpad.net/ironic/+bug/1515871
        new_priorities = {
            'erase_devices': CONF.ilo.clean_priority_erase_devices,
        }
        return deploy_utils.agent_get_clean_steps(
            task, interface='deploy',
            override_priorities=new_priorities)

class IloPXEDeploy(iscsi_deploy.ISCSIDeploy):

    def prepare(self, task):
        """Prepare the deployment environment for this task's node.

        If the node's 'capabilities' property includes a boot_mode, that
        boot mode will be applied for the node. Otherwise, the existing
        boot mode of the node is used in the node's 'capabilities' property.

        PXEDeploys' prepare method is then called, to prepare the deploy
        environment for the node

        :param task: a TaskManager instance containing the node to act on.
        :raises: IloOperationError, if some operation on iLO failed.
        :raises: InvalidParameterValue, if some information is invalid.
        """
        if task.node.provision_state != states.ACTIVE:
            _prepare_node_for_deploy(task)

            # Check if 'boot_option' is compatible with 'boot_mode' and image.
            # Whole disk image deploy is not supported in UEFI boot mode if
            # 'boot_option' is not 'local'.
            # If boot_mode is not set in the node properties/capabilities then
            # PXEDeploy.validate() would pass.
            # Boot mode gets updated in prepare stage. It is possible that the
            # deploy boot mode is 'uefi' after call to update_boot_mode().
            # Hence a re-check is required here.
            pxe.validate_boot_option_for_uefi(task.node)

        super(IloPXEDeploy, self).prepare(task)

    def deploy(self, task):
        """Start deployment of the task's node.

        This method sets the boot device to 'NETWORK' and then calls
        PXEDeploy's deploy method to deploy on the given node.

        :param task: a TaskManager instance containing the node to act on.
        :returns: deploy state DEPLOYWAIT.
        """
        manager_utils.node_set_boot_device(task, boot_devices.PXE)
        return super(IloPXEDeploy, self).deploy(task)

    @task_manager.require_exclusive_lock
    def tear_down(self, task):
        """Tear down a previous deployment on the task's node.

        :param task: a TaskManager instance.
        :returns: states.DELETED
        """
        # Powering off the Node before disabling secure boot. If the node is
        # is in POST, disable secure boot will fail.
        manager_utils.node_power_action(task, states.POWER_OFF)
        _disable_secure_boot_if_supported(task)
        return super(IloPXEDeploy, self).tear_down(task)

    def prepare_cleaning(self, task):
        """Boot into the agent to prepare for cleaning.

        :param task: a TaskManager object containing the node
        :returns: states.CLEANWAIT to signify an asynchronous prepare.
        :raises NodeCleaningFailure: if the previous cleaning ports cannot
            be removed or if new cleaning ports cannot be created
        :raises: IloOperationError, if some operation on iLO failed.
        """
        # Powering off the Node before initiating boot for node cleaning.
        # If node is in system POST, setting boot device fails.
        manager_utils.node_power_action(task, states.POWER_OFF)
        return super(IloPXEDeploy, self).prepare_cleaning(task)

redpajama_set_name: RedPajamaGithub


text:
{{ user.name }}

watchlist

new search

sign out


text:
(function(module){
    'use strict';

    module.factory('Auth', ['$http', '$q', '$rootScope', 'Conf',
        function($http, $q, $root, $conf){
            var key = 'auth_user';
            var _user = null;

            function register(userInfo) {
                var deferred = $q.defer();

                $http.post('/api/users', userInfo)
                    .then(function(resp){
                        $root.$broadcast('auth:login', resp.data);
                        deferred.resolve(resp.data);
                    }, function(resp){
                        deferred.reject(resp.data, resp.status);
                    });

                return deferred.promise;
            }

            function login(email, password) {
                var deferred = $q.defer();

                $http.post('/login', {
                    email: email,
                    password: password
                }).then(function(result){
                    $root.$broadcast('auth:login', result.data);
                    deferred.resolve(result.data);
                }, function(resp){
                    deferred.reject(resp.data, resp.status);
                });

                return deferred.promise;
            }

            function logout() {
                var deferred = $q.defer();

                $http.post('/logout')
                    .then(function(){
                        $root.$broadcast('auth:logout');
                        deferred.resolve();
                    });

                return deferred.promise;
            }

            function setState(user) {
                $conf.set(key, true);
                _user = user;
            }

            function invalidate() {
                $conf.clear(key);
                _user = null;
            }

            // log info persistence
            (function init(){
                if ($conf.get(key)) {
                    $http.get("api/users")
                        .then(function(result){
                            setState(result.data);
                        })
                        .catch(invalidate);
                }

                $root.$on('auth:login', function(_, user){
                    setState(user);
                });

                $root.$on('auth:logout', invalidate);

                $root.$on('monitor:unauthorized', invalidate);

                $root.$on('comment:add', function(){
                    if (_user) {
                        ++_user.commentCount;
                    }
                });

                $root.$on('blog:add', function(){
                    if (_user) {
                        ++_user.blogCount;
                    }
                });

                $root.$on('blog:delete', function(){
                    if (_user) {
                        --_user.blogCount;
                    }
                });
            })();

            return {
                register: register,
                login: login,
                logout: logout,
                invalidate: invalidate,
                user: function() {
                    return _user;
                },
                hasLogin: function() {
                    return !!_user;
                },
                update: function(user) {
                    _user = user;
                }
            };
        }
    ]);
})(angular.module('service.auth', ['service.conf']));


text:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>

        <item name="android:windowBackground">@drawable/activity_background</item>
        <item name="android:buttonStyle">@style/AllButtons</item>
    </style>

    <style name="AllButtons">
        <item name="android:background">@drawable/button</item>
        <item name="android:minWidth">@dimen/calc_button_min_width</item>
        <item name="android:minHeight">@dimen/calc_button_min_height</item>
    </style>

    <!-- custom -> -->

    <dimen name="calc_button_min_width">50dp</dimen>
    <dimen name="calc_button_min_height">40dp</dimen>
    <dimen name="calc_button_margin">10dp</dimen>

    <!-- calc buttons -->
    <style name="CalcButton">
        <item name="android:minWidth">@dimen/calc_button_min_width</item>
        <item name="android:minHeight">@dimen/calc_button_min_height</item>
        <item name="android:background">@drawable/calc_button</item>
        <item name="android:gravity">center</item>
        <item name="android:layout_margin">@dimen/calc_button_margin</item>
    </style>

    <!-- extra calc buttons -->
    <style name="CalcExtraButton" parent="CalcButton">
        <item name="android:background">@drawable/calc_button_extra</item>
    </style>

    <style name="CalcDisplayTextAppearance" parent="TextAppearance.AppCompat">
        <item name="android:textColor">#0F0</item>
        <item name="android:textStyle">italic</item>
    </style>

</resources>


text:
@interface SomeOtherComponent : NSObject <ESComponent>

@end


text:
var settings = {
	browsersStatsPage: 'http://www.w3schools.com/browsers/browsers_stats.asp',
	browserBasePage: 'http://useragentstring.com/pages/%s/',
	browserCountLimit: 30,
	browsersType: ['Chrome', 'Internet Explorer', 'Firefox', 'Safari', 'Opera']
}

module.exports = settings


text:
package controlP5;

import processing.core.PApplet;
import processing.core.PFont;
import processing.core.PGraphics;

public class Icon extends Controller< Icon > {

	protected boolean isPressed;
	protected boolean isOn = false;
	public static int autoWidth = 69;
	public static int autoHeight = 19;
	protected int activateBy = RELEASE;
	protected boolean isSwitch = false;
	protected int roundedCorners = 0;
	protected boolean isFill = true;
	protected boolean isStroke = false;
	protected float scl = 1;
	protected int[] fontIcons = new int[] { -1 , -1 , -1 , -1 };
	protected boolean isHideBackground = true;
	protected float strokeWeight = 1;
	protected float scalePressed = 1.0f;
	protected float scaleReleased = 1.0f;

	public Icon( ControlP5 theControlP5 , String theName ) {
		this( theControlP5 , theControlP5.getDefaultTab( ) , theName , 0 , 0 , 0 , autoWidth , autoHeight );
		theControlP5.register( theControlP5.papplet , theName , this );
	}

	protected Icon( ControlP5 theControlP5 , ControllerGroup< ? > theParent , String theName , float theDefaultValue , int theX , int theY , int theWidth , int theHeight ) {
		super( theControlP5 , theParent , theName , theX , theY , theWidth , theHeight );
		_myValue = theDefaultValue;
		_myCaptionLabel.align( CENTER , CENTER );
	}

	@Override protected void onEnter( ) {
		isActive = true;
	}

	@Override protected void onLeave( ) {
		isActive = false;
		setIsInside( false );
	}

	/**
	 * @exclude
	 */
	@Override @ControlP5.Invisible public void mousePressed( ) {
		isActive = getIsInside( );
		isPressed = true;
		if ( activateBy == PRESSED ) {
			activate( );
		}
		scl = scalePressed;
	}

	/**
	 * @exclude
	 */
	@Override @ControlP5.Invisible public void mouseReleased( ) {
		isPressed = false;
		if ( activateBy == RELEASE ) {
			activate( );
		}
		isActive = false;
		scl = scaleReleased;
	}

	/**
	 * A Icon can be activated by a mouse PRESSED or mouse
	 * RELEASE. Default value is RELEASE.
	 */
	public Icon activateBy( int theValue ) {
		if ( theValue == PRESS ) {
			activateBy = PRESS;
		} else {
			activateBy = RELEASE;
		}
		return this;
	}

	protected void activate( ) {
		if ( isActive ) {
			isActive = false;
			isOn = !isOn;
			setValue( _myValue );
		}
	}

	@Override @ControlP5.Invisible public void mouseReleasedOutside( ) {
		mouseReleased( );
	}

	@Override public Icon setValue( float theValue ) {
		_myValue = theValue;
		broadcast( FLOAT );
		return this;
	}

	@Override public Icon update( ) {
		return setValue( _myValue );
	}

	/**
	 * Turns an icon into a switch.
	 */
	public Icon setSwitch( boolean theFlag ) {
		isSwitch = theFlag;
		if ( isSwitch ) {
			_myBroadcastType = BOOLEAN;
		} else {
			_myBroadcastType = FLOAT;
		}
		return this;
	}

	/**
	 * If the Icon acts as a switch, setOn will turn on
	 * the switch. Use
	 * {@link controlP5.Icon#setSwitch(boolean) setSwitch}
	 * to turn a Icon into a Switch.
	 */
	public Icon setOn( ) {
		if ( isSwitch ) {
			isOn = false;
			isActive = true;
			activate( );
		}
		return this;
	}

	/**
	 * If the Icon acts as a switch, setOff will turn off
	 * the switch. Use
	 * {@link controlP5.Icon#setSwitch(boolean) setSwitch}
	 * to turn a Icon into a Switch.
	 */
	public Icon setOff( ) {
		if ( isSwitch ) {
			isOn = true;
			isActive = true;
			activate( );
		}
		return this;
	}

	public boolean isOn( ) {
		return isOn;
	}

	public boolean isSwitch( ) {
		return isSwitch;
	}

	public boolean isPressed( ) {
		return isPressed;
	}

	/**
	 * Returns true or false and indicates the switch state
	 * of the Icon. {@link setSwitch(boolean) setSwitch}
	 * should have been set before.
	 */
	public boolean getBooleanValue( ) {
		return isOn;
	}

	public Icon setRoundedCorners( int theRadius ) {
		roundedCorners = theRadius;
		return this;
	}

	public Icon setFontIconSize( int theSize ) {
		_myCaptionLabel.setSize( theSize );
		return this;
	}

	public Icon setFont( PFont thePFont ) {
		_myCaptionLabel.setFont( thePFont );
		return this;
	}

	public Icon setFont( PFont thePFont , int theSize ) {
		_myCaptionLabel.setFont( thePFont );
		setFontIconSize( theSize );
		return this;
	}

	public Icon setFontIndex( int theIndex ) {
		_myCaptionLabel.set( "" + ( char ) theIndex );
		return this;
	}

	public Icon setStroke( boolean theBoolean ) {
		isStroke = theBoolean;
		return this;
	}

	public Icon setStrokeWeight( float theStrokeWeight ) {
		strokeWeight = theStrokeWeight;
		return this;
	}

	public Icon setFill( boolean theBoolean ) {
		isFill = theBoolean;
		return this;
	}

	public Icon setFontIcons( int theStateOff , int theStateOn ) {
		setFontIcon( theStateOn , ACTIVE );
		setFontIcon( theStateOff , DEFAULT );
		return this;
	}

	public Icon setFontIconOn( int theStateOn ) {
		setFontIcon( theStateOn , ACTIVE );
		return this;
	}

	public Icon setFontIconOff( int theStateOff ) {
		setFontIcon( theStateOff , DEFAULT );
		return this;
	}

	public Icon setFontIcons( int ... theIds ) {
		if ( theIds.length < 3 || theIds.length > 4 ) {
			return this;
		}
		setFontIcon( theIds[ 0 ] , DEFAULT );
		setFontIcon( theIds[ 1 ] , OVER );
		setFontIcon( theIds[ 2 ] , ACTIVE );
		setFontIcon( theIds.length == 3 ? theIds[ 2 ] : theIds[ 3 ] , HIGHLIGHT );
		return this;
	}

	public Icon setFontIcon( int theId ) {
		return setFontIcon( theId , DEFAULT );
	}

	public int getFontIcon( int theState ) {
		if ( theState >= 0 && theState < 4 ) {
			return fontIcons[ theState ];
		} else {
			return fontIcons[ DEFAULT ];
		}
	}

	/**
	 * @param theImage
	 * @param theState use Controller.DEFAULT (background) Controller.OVER (foreground) Controller.ACTIVE (active)
	 */
	public Icon setFontIcon( int theId , int theState ) {
		fontIcons[ theState ] = theId;
		updateDisplayMode( DEFAULT );
		return this;
	}

	public Icon hideBackground( ) {
		isHideBackground = true;
		return this;
	}

	public Icon showBackground( ) {
		isHideBackground = false;
		return this;
	}

	public Icon setScale( float theScalePressed , float theScaleReleased ) {
		scalePressed = theScalePressed;
		scaleReleased = theScaleReleased;
		return this;
	}

	@Override @ControlP5.Invisible public Icon updateDisplayMode( int theMode ) {
		return updateViewMode( theMode );
	}

	/**
	 * @exclude
	 */
	@ControlP5.Invisible public Icon updateViewMode( int theMode ) {
		_myDisplayMode = theMode;
		switch ( theMode ) {
		case ( DEFAULT ):
			_myControllerView = new IconView( );
			break;
		case ( IMAGE ):
			_myControllerView = new IconImageView( );
			break;
		case ( CUSTOM ):
		default:
			break;

		}
		return this;
	}

	private class IconView implements ControllerView< Icon > {

		public void display( PGraphics theGraphics , Icon theController ) {

			if ( !isHideBackground ) {
				if ( isStroke ) {
					theGraphics.stroke( color.getBackground( ) );
					theGraphics.strokeWeight( strokeWeight );
				} else {
					theGraphics.noStroke( );
				}

				if ( isFill ) {
					theGraphics.fill( color.getBackground( ) );
				} else {
					theGraphics.noFill( );
				}
			}

			float w_half = getWidth( ) / 2;
			float h_half = getHeight( ) / 2;
			theGraphics.translate( w_half , h_half );
			theGraphics.scale( scl );

			if ( !isHideBackground ) {
				if ( roundedCorners == 0 ) {
					theGraphics.rect( -w_half , -h_half , getWidth( ) , getHeight( ) );
				} else if ( roundedCorners == -1 ) {
					theGraphics.ellipseMode(PApplet.CORNER);
					theGraphics.ellipse( -w_half , -h_half , getWidth( ) , getHeight( ) );
				} else {
					theGraphics.rect( -w_half , -h_half , getWidth( ) , getHeight( ) , roundedCorners , roundedCorners , roundedCorners , roundedCorners );
				}
			}

			if ( isSwitch ) {
				if ( !isOn ) {
					setFontIndex( getFontIcon( ACTIVE ) );
				} else {
					setFontIndex( getFontIcon( DEFAULT ) );
				}
			} else {
				setFontIndex( getFontIcon( DEFAULT ) );
			}
			_myCaptionLabel.setColor( isOn && isSwitch || isPressed && !isSwitch ? color.getActive( ) : color.getForeground( ) );
			_myCaptionLabel.draw( theGraphics , -( int ) w_half , -( int ) ( h_half * 1.05f ) , theController );

		}
	}

	private class IconImageView implements ControllerView< Icon > {

		public void display( PGraphics theGraphics , Icon theController ) {

			float w_half = getWidth( ) / 2;
			float h_half = getHeight( ) / 2;
			theGraphics.translate( w_half , h_half );
			theGraphics.scale( scl );

			if ( isOn && isSwitch ) {
				theGraphics.image( ( availableImages[ HIGHLIGHT ] == true ) ? images[ HIGHLIGHT ] : images[ DEFAULT ] , -w_half , -h_half );
				return;
			}
			if ( getIsInside( ) ) {
				if ( isPressed ) {
					theGraphics.image( ( availableImages[ ACTIVE ] == true ) ? images[ ACTIVE ] : images[ DEFAULT ] , -w_half , -h_half );
				} else {
					theGraphics.image( ( availableImages[ OVER ] == true ) ? images[ OVER ] : images[ DEFAULT ] , -w_half , -h_half );
				}
			} else {
				theGraphics.image( images[ DEFAULT ] , -w_half , -h_half );
			}
		}
	}

	@Override public String getInfo( ) {
		return "type:\tIcon\n" + super.getInfo( );
	}

	@Override public String toString( ) {
		return super.toString( ) + " [ " + getValue( ) + " ] " + "Icon" + " (" + this.getClass( ).getSuperclass( ) + ")";
	}
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="bower_components/qunit/qunit/qunit.css" />
    <title>Jashboard Test Suite</title>


text:
from rosie.core.classifiers import InvalidCnpjCpfClassifier

CLASSIFIERS = {
    'invalid_cnpj_cpf': InvalidCnpjCpfClassifier,
}

UNIQUE_IDS = None


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Halcyon.HAL.Attributes;
using Threax.AspNetCore.Halcyon.Ext;
using Threax.AspNetCore.Models;

namespace Test.Database
{
    public partial class ValueEntity
    {
        //You can add your own customizations here. These will not be overwritten by the model generator.
        //See ValueEntity.Generated for the generated code
    }
}


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Interface net.sourceforge.pmd.lang.java.symboltable.TypedNameDeclaration (PMD Java 5.5.1 API)</title>
<meta name="date" content="2016-07-27">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
net.sourceforge.pmd.lang.java.symboltable.TypedNameDeclaration

Packages that use TypedNameDeclaration

Package
Description

net.sourceforge.pmd.lang.java.symboltable

net.sourceforge.pmd.lang.java.typeresolution

Uses of TypedNameDeclaration in net.sourceforge.pmd.lang.java.symboltable

Classes in net.sourceforge.pmd.lang.java.symboltable that implement TypedNameDeclaration

Modifier and Type
Class and Description

class
ClassNameDeclaration

class
SimpleTypedNameDeclaration

Just stores a type image and a actual type.

class
VariableNameDeclaration

Uses of TypedNameDeclaration in net.sourceforge.pmd.lang.java.typeresolution

Methods in net.sourceforge.pmd.lang.java.typeresolution with parameters of type TypedNameDeclaration

Modifier and Type
Method and Description

static boolean
TypeHelper.isA(TypedNameDeclaration vnd,
   Class<?> clazz)

static boolean
TypeHelper.isEither(TypedNameDeclaration vnd,
        Class<?> class1,
        Class<?> class2)

static boolean
TypeHelper.isNeither(TypedNameDeclaration vnd,
         Class<?> class1,
         Class<?> class2)

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2002–2016 InfoEther. All rights reserved.


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.03.23 at 01:49:06 PM CET
//

package org.sdmx.resources.sdmxml.schemas.v2_0.registry;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 * The QueryRegistrationRequest is used to query the contents of a registry for data sets and metadata sets. The QueryRegistrationRequest specifies whether the result set should include metadata sets, data sets, or both with the QueryType element. The constraints which characterize the search - including reference period, are contained in teh Constraints within the child object references.
 *
 *
Java class for QueryRegistrationRequestType complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="QueryRegistrationRequestType">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="QueryType" type="{http://www.SDMX.org/resources/SDMXML/schemas/v2_0/registry}QueryTypeType"/>
 *         <choice>
 *           <element name="ProvisionAgreementRef" type="{http://www.SDMX.org/resources/SDMXML/schemas/v2_0/registry}ProvisionAgreementRefType"/>
 *           <element name="DataflowRef" type="{http://www.SDMX.org/resources/SDMXML/schemas/v2_0/registry}DataflowRefType"/>
 *           <element name="MetadataflowRef" type="{http://www.SDMX.org/resources/SDMXML/schemas/v2_0/registry}MetadataflowRefType"/>
 *           <element name="DataProviderRef" type="{http://www.SDMX.org/resources/SDMXML/schemas/v2_0/registry}DataProviderRefType"/>
 *         </choice>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "QueryRegistrationRequestType", propOrder = {
    "queryType",
    "provisionAgreementRef",
    "dataflowRef",
    "metadataflowRef",
    "dataProviderRef"
})
public class QueryRegistrationRequestType {

    @XmlElement(name = "QueryType", required = true)
    protected QueryTypeType queryType;
    @XmlElement(name = "ProvisionAgreementRef")
    protected ProvisionAgreementRefType provisionAgreementRef;
    @XmlElement(name = "DataflowRef")
    protected DataflowRefType dataflowRef;
    @XmlElement(name = "MetadataflowRef")
    protected MetadataflowRefType metadataflowRef;
    @XmlElement(name = "DataProviderRef")
    protected DataProviderRefType dataProviderRef;

    /**
     * Gets the value of the queryType property.
     *
     * @return
     *     possible object is
     *     {@link QueryTypeType }
     *
     */
    public QueryTypeType getQueryType() {
        return queryType;
    }

    /**
     * Sets the value of the queryType property.
     *
     * @param value
     *     allowed object is
     *     {@link QueryTypeType }
     *
     */
    public void setQueryType(QueryTypeType value) {
        this.queryType = value;
    }

    /**
     * Gets the value of the provisionAgreementRef property.
     *
     * @return
     *     possible object is
     *     {@link ProvisionAgreementRefType }
     *
     */
    public ProvisionAgreementRefType getProvisionAgreementRef() {
        return provisionAgreementRef;
    }

    /**
     * Sets the value of the provisionAgreementRef property.
     *
     * @param value
     *     allowed object is
     *     {@link ProvisionAgreementRefType }
     *
     */
    public void setProvisionAgreementRef(ProvisionAgreementRefType value) {
        this.provisionAgreementRef = value;
    }

    /**
     * Gets the value of the dataflowRef property.
     *
     * @return
     *     possible object is
     *     {@link DataflowRefType }
     *
     */
    public DataflowRefType getDataflowRef() {
        return dataflowRef;
    }

    /**
     * Sets the value of the dataflowRef property.
     *
     * @param value
     *     allowed object is
     *     {@link DataflowRefType }
     *
     */
    public void setDataflowRef(DataflowRefType value) {
        this.dataflowRef = value;
    }

    /**
     * Gets the value of the metadataflowRef property.
     *
     * @return
     *     possible object is
     *     {@link MetadataflowRefType }
     *
     */
    public MetadataflowRefType getMetadataflowRef() {
        return metadataflowRef;
    }

    /**
     * Sets the value of the metadataflowRef property.
     *
     * @param value
     *     allowed object is
     *     {@link MetadataflowRefType }
     *
     */
    public void setMetadataflowRef(MetadataflowRefType value) {
        this.metadataflowRef = value;
    }

    /**
     * Gets the value of the dataProviderRef property.
     *
     * @return
     *     possible object is
     *     {@link DataProviderRefType }
     *
     */
    public DataProviderRefType getDataProviderRef() {
        return dataProviderRef;
    }

    /**
     * Sets the value of the dataProviderRef property.
     *
     * @param value
     *     allowed object is
     *     {@link DataProviderRefType }
     *
     */
    public void setDataProviderRef(DataProviderRefType value) {
        this.dataProviderRef = value;
    }

}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Utilitaire;

import Entite.Equipe;
import Entite.Match;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

/**
 *
 * @author jeoffrey
 */
public class Match_DAO {

    public static void CreerMatch(Match match,Connection connection ) throws Exception
{

   Statement stmt = null;

    try
    {

    stmt = connection.createStatement();

  stmt.executeUpdate("Insert Into matchs(Match_lib_team1,Match_res_team1,Match_res_team2,Match_lib_team2,Match_typ,Match_info_tn,Equipe_Equ_id) Values('"
          + match.getMatch_lib_equ1() + "', '"
          + match.getMatch_res_equ1() +"',"
          + match.getMatch_res_equ2()+","
          + match.getMatch_lib_equ2()+","
          + match.getMatch_type()+","
          + match.getMatch_info_tn()+","
          + match.getEquipe_id().getEqu_id()+")");

     ResultSet res =  stmt.executeQuery("SELECT MAX(Match_id) FROM matchs");
       if(res.next())
       {

           int id = res.getInt(1);
           match.setMatch_id(id);
       }

        System.out.println("Insertion réusssite " );

    } catch(Exception ex){ex.printStackTrace();}

    finally
    {
        if (stmt != null)
        {
            try
            {
                stmt.close();
            }catch( SQLException ex){

            }
        }
    }

}

    public static void ModifMatch(Match match,Connection connection ) throws Exception
{

     Statement stmt = null;
    try
    {
      stmt = connection.createStatement();
      stmt.executeUpdate("UPDATE matchs "
      + "SET Match_lib_team1 ='"+ match.getMatch_lib_equ1()
      + "', Match_res_team1 ='" + match.getMatch_res_equ1()
      +"', Match_res_team2 =" + match.getMatch_res_equ2()
      +"', Match_lib_team2 =" + match.getMatch_lib_equ2()
      +"', Match_typ      =" + match.getMatch_type()
      +"', Match_info_tn =" + match.getMatch_info_tn()
      +"', Equipe_Equ_id =" + match.getEquipe_id().getEqu_id()
      +" where Match_id = " + match.getMatch_id());

      } catch(Exception ex){ex.printStackTrace();}

    finally
    {
        if (stmt != null)
        {
            try
            {
                stmt.close();
            }catch( SQLException ex){

            }
        }
    }

}

    public static void DeleteMatch(Match match,Connection connection )throws Exception
{

     Statement stmt = null;
     try
    {
      stmt = connection.createStatement();
      stmt.executeUpdate("DELETE matchs "+
      "Where Match_id = " + match.getMatch_id());

      } catch(Exception ex){ex.printStackTrace();}

    finally
    {
        if (stmt != null)
        {
            try
            {
                stmt.close();
            }catch( SQLException ex){

            }
        }
    }

}

    public static ArrayList<Match> ListerMatch(Connection connection)
{

    Statement stmt = null;

    ArrayList<Match> listMatch = new ArrayList();
    try
    {
    stmt = connection.createStatement();
    ResultSet rs = stmt.executeQuery("Select Match_id,Match_lib_team1,Match_res_team1,Match_res_team2,Match_lib_team2,match_date,Match_typ,Match_info_tn,Equipe_Equ_id FROM matchs;");

    while(rs.next())
            {
                int id = rs.getInt("Match_id");
                String libEqu1Match = rs.getString("Match_lib_team1");
                String resEqu1 = rs.getString("Match_res_team1");
                String resEqu2 = rs.getString("Match_res_team2");
                String libEqu2Match = rs.getString("Match_lib_team2");
                java.sql.Timestamp date_match = rs.getTimestamp("match_date");
                String matchType = rs.getString("Match_typ");
                String matchInfo = rs.getString("Match_info_tn");
                   int EquipId = rs.getInt("Equipe_Equ_id");

                   Equipe equipe = Equipe_DAO.TrouverEquipe(connection, EquipId);

                // rentrer DATE
                Match match = new Match(libEqu1Match,libEqu2Match,date_match,resEqu1,resEqu2,matchType,matchInfo,equipe);

                listMatch.add(match);
            }

    } catch(Exception ex){ex.printStackTrace();}

    finally
    {
        if (stmt != null)
        {
            try
            {
                stmt.close();
            }catch( SQLException ex){

            }
        }

    }
return listMatch;
}
}


text:
UCLASS()
class UMatineeTrackEventHelper : public UInterpTrackHelper
{
	GENERATED_UCLASS_BODY()

	void OnAddKeyTextEntry(const FText& ChosenText, ETextCommit::Type CommitInfo, IMatineeBase* Matinee, UInterpTrack* Track);

public:

	// UInterpTrackHelper interface

	virtual	bool PreCreateKeyframe( UInterpTrack *Track, float KeyTime ) const override;
	virtual void  PostCreateKeyframe( UInterpTrack *Track, int32 KeyIndex ) const override;
};


text:
module MagicBeans
	class Id < ActiveRecord::Base

		self.primary_key = "id"

		belongs_to :resource, polymorphic: true

	end
end


text:
package mediautil.image.jpeg.maker;

import java.io.IOException;
import java.io.OutputStream;

import mediautil.image.jpeg.Exif;
import mediautil.image.jpeg.IFD;
import mediautil.image.jpeg.IFDParsingException;

/**
 * This is the interface that all MakerNote handlers have to follow : read and write must be supported
 *
 * Two implementations exist for now :
 * BlockMakerNoteHandler which considers the notes as a block of Raw Data
 *  According to http://www.exif.org/samples.html , this is the format used by Kodak and Ricoh
 *  This is also the handler used for processing of unknown MakerNotes
 *
 * IDFMakerNoteHandler which considers the notes as an IFD structure and is able to read it and write it with accurate offset handling
 *  According to http://www.exif.org/samples.html , this is the format used by Canon, Fujifilm, Nikon, Nikon, Olympus and Sanyo
 *
 */
public interface MakerNoteHandler {
    void load(Exif exif, IFD ifd, int tag, int type, int offset, int count, int typelen) throws IFDParsingException;

    void save(OutputStream out, Exif exif, IFD ifd1) throws IOException;
}


text:
package com.alibaba.json.bvt.parser.deser;

import java.util.Hashtable;

import junit.framework.TestCase;

import org.junit.Assert;

import com.alibaba.fastjson.JSON;

public class HashtableFieldTest extends TestCase {

    public void test_null() throws Exception {
        Entity value = JSON.parseObject("{value:null}", Entity.class);
        Assert.assertNull(value.getValue());
    }

    public void test_empty() throws Exception {
        Entity value = JSON.parseObject("{value:{}}", Entity.class);
        Assert.assertEquals(0, value.getValue().size());
    }

    public void test_null_2() throws Exception {
        Entity value = JSON.parseObject("{\"value\":null}", Entity.class);
        Assert.assertNull(value.getValue());
    }

    public void test_empty_a() throws Exception {
        A value = JSON.parseObject("{value:{\"@type\":\"java.util.Hashtable\"}}", A.class);
        Assert.assertEquals(0, ((Hashtable)value.getValue()).size());
    }

    private static class Entity {

        private Hashtable value;

        public Hashtable getValue() {
            return value;
        }

        public void setValue(Hashtable value) {
            this.value = value;
        }
    }

    private static class A {

        private Object value;

        public Object getValue() {
            return value;
        }

        public void setValue(Object value) {
            this.value = value;
        }
    }
}


text:
ALTER TABLE SecurityPerson ADD

	CONSTRAINT FK_SecurityPerson_PersonID
	FOREIGN KEY (PersonID)
	REFERENCES Person (PersonID),

	CONSTRAINT FK_SecurityPerson_RoleID
	FOREIGN KEY (RoleID)
	REFERENCES SecurityRole (RoleID)


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Dvorak on A Place to Remember</title>
    <link>https://renodesper.com/tags/dvorak/</link>
    <description>Recent content in Dvorak on A Place to Remember</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en</language>
    <lastBuildDate>Sun, 18 Jan 2015 00:00:00 +0000</lastBuildDate>

	<atom:link href="https://renodesper.com/tags/dvorak/index.xml" rel="self" type="application/rss+xml" />

    <item>
      <title>dvorak programmer's time</title>
      <link>https://renodesper.com/blog/2015-01-18-dvorak-programmers-time/</link>
      <pubDate>Sun, 18 Jan 2015 00:00:00 +0000</pubDate>

      <guid>https://renodesper.com/blog/2015-01-18-dvorak-programmers-time/</guid>
      <description>Jadi begini, beberapa hari belakangan ini saya sedang menikmati belajar menggunakan layout dvorak programmer. Keycode untuk layout tersebut adalah dvp. Jujur saja, sangat sulit untuk menggunakan layout tersebut terlebih lagi jika kita sudah terbiasa menggunakan qwerty. Terkadang jadi jemari saya kembali ke tempat dimana huruf tersebut berada di qwerty. Ini yang saya lakukan agar saya tidak terganggu dengan tampilan keyword qwerty yang ada di laptop saya: dvorak workaround</description>
    </item>

  </channel>
</rss>


text:
function contains (array, value) {
  return array.indexOf(value) >= 0;
}

function filterAvailableDigits (allDigits, availableDigits) {
  allDigits.forEach(item => {
    item.active = contains(availableDigits, item.value);
  });
  return allDigits;
}

export function getDigit (allDigits, number) {
  return allDigits
          .filter(digit => digit.value === number)
          .reduce((old, item) => {
            return item;
          }, {});
}

export function convertToNumber (number) {
  return Number(number);
}

export function filteredDigits (index, digits, time) {
  let timeIntegers = time.map(convertToNumber);

  if (index === 0) {
    if (timeIntegers[1] > 3) {
      return filterAvailableDigits(digits, [0, 1]);
    }
    return filterAvailableDigits(digits, [0, 1, 2]);
  }
  if (index === 1) {
    if (timeIntegers[0] === 2) {
      return filterAvailableDigits(digits, [0, 1, 2, 3]);
    }
    return filterAvailableDigits(digits, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
  }
  if (index === 2) {
    return filterAvailableDigits(digits, [0, 1, 2, 3, 4, 5]);
  }
  if (index === 3) {
    return filterAvailableDigits(digits, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
  }
}

export function activeNumbers (numbers) {
  return numbers
          .filter(digit => digit.active)
          .map(item => item.value);
}


text:
package com.rubix.util;

import java.util.concurrent.atomic.AtomicInteger;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.rubix.constant.CubeConstants;

@Scope("prototype")
@Component
public class CubeCheckerServiceManager {

    private final int total;

    private final AtomicInteger counter = new AtomicInteger();

    public CubeCheckerServiceManager() {
        this.total = CubeConstants.TOTAL_NR_OF_COMBINATIONS;
    }

    public CubeCheckerServiceManager(final int total) {
        this.total = total;
    }

    public boolean checkFinished() {
        System.out.println(counter.incrementAndGet());
        return counter.get() == total;
        // return counter.incrementAndGet() == total;
    }
}


text:
package org.takes.facets.auth.codecs;

/**
 * Decoding exception.
 *
 * @since 0.5
 */
public final class DecodingException extends RuntimeException {

    /**
     * Serialization marker.
     */
    private static final long serialVersionUID = 0x7529FA781EDA1479L;

    /**
     * Public ctor.
     * @param cause The cause of it
     */
    DecodingException(final String cause) {
        super(cause);
    }

    /**
     * Public ctor.
     * @param cause The cause of it
     */
    DecodingException(final Throwable cause) {
        super(cause);
    }

}


text:
import { behavior } from './behavior';
import { observeProps } from './props';
export function observe(vantOptions, options) {
    const { watch, computed } = vantOptions;
    options.behaviors.push(behavior);
    if (watch) {
        const props = options.properties || {};
        Object.keys(watch).forEach(key => {
            if (key in props) {
                let prop = props[key];
                if (prop === null || !('type' in prop)) {
                    prop = { type: prop };
                }
                prop.observer = watch[key];
                props[key] = prop;
            }
        });
        options.properties = props;
    }
    if (computed) {
        options.methods = options.methods || {};
        options.methods.$options = () => vantOptions;
        if (options.properties) {
            observeProps(options.properties);
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<arquillian xmlns="http://jboss.org/schema/arquillian"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://jboss.org/schema/arquillian http://jboss.org/schema/arquillian/arquillian_1_0.xsd">

  <container qualifier="container" default="true">
    <configuration>
      <property name="chameleonTarget">wildfly:9.0.0.Final:managed</property>
    </configuration>
  </container>

  <extension qualifier="webdriver">
    <property name="browser">firefox</property>
  </extension>

</arquillian>


text:
using System;
using System.Net;
using Independentsoft.Exchange;

namespace Sample
{
    class Program
    {
        static void Main(string[] args)
        {
            NetworkCredential credential = new NetworkCredential("username", "password");
            Service service = new Service("https://myserver/ews/Exchange.asmx", credential);

            try
            {
                IsGreaterThanOrEqualTo restriction1 = new IsGreaterThanOrEqualTo(FolderPropertyPath.CreationTime, DateTime.Today);
                IsLessThan restriction2 = new IsLessThan(FolderPropertyPath.CreationTime, DateTime.Today.AddDays(1));
                And restriction3 = new And(restriction1, restriction2);

                FindFolderResponse findFolderResponse = service.FindFolder(StandardFolder.MailboxRoot, FolderPropertyPath.AllPropertyPaths, restriction3, FolderQueryTraversal.Deep);

                for (int i = 0; i < findFolderResponse.Folders.Count; i++)
                {
                    Console.WriteLine(findFolderResponse.Folders[i].DisplayName);
                    Console.WriteLine(findFolderResponse.Folders[i].FolderClass);
                    Console.WriteLine(findFolderResponse.Folders[i].CreationTime);
                    Console.WriteLine(findFolderResponse.Folders[i].FolderId);
                    Console.WriteLine("----------------------------------------------------------");
                }

                Console.Read();
            }
            catch (ServiceRequestException ex)
            {
                Console.WriteLine("Error: " + ex.Message);
                Console.WriteLine("Error: " + ex.XmlMessage);
                Console.Read();
            }
            catch (WebException ex)
            {
                Console.WriteLine("Error: " + ex.Message);
                Console.Read();
            }
        }
    }
}


text:
package eu.motogymkhana.server.model;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;

import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

@Entity
@Table(name = "registrations")
public class Registration {

	public static final String ID = "_id";
	public static final String SEASON = "season";
	public static final String COUNTRY = "country";
	public static final String RIDER = "rider";
	public static final String NUMBER = "number";
	private static final String REGISTERED = "registered";
	private static final String BIB = "bib";
	private static final String DAY_RIDER = "day_rider";

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@JsonIgnore
	private int _id;

	@JsonProperty(SEASON)
	@Column(name = SEASON)
	protected int season;

	@JsonProperty(COUNTRY)
	@Column(name = COUNTRY)
	protected Country country;

	@JsonProperty(NUMBER)
	@Column(name = NUMBER)
	protected int number;

	@JsonProperty(BIB)
	@Column(name = BIB)
	protected Bib bib;

	@JsonProperty(DAY_RIDER)
	@Column(name = DAY_RIDER)
	protected boolean dayRider;

	@JsonBackReference
	@ManyToOne(cascade = CascadeType.ALL)
	protected Rider rider;

	@JsonProperty(REGISTERED)
	@Column(name = REGISTERED)
	protected boolean registered;

	public Registration() {

	}

	public Registration(Rider rider, Country country, int season, int startNumber, Bib bib) {
		this.rider = rider;
		this.country = country;
		this.season = season;
		this.number = startNumber;
		this.bib = bib;
	}

	public Country getCountry() {
		return country;
	}

	public int getSeason() {
		return season;
	}

	public boolean isRegistered() {
		return registered;
	}

	public Rider getRider() {
		return rider;
	}

	public String toString() {
		return _id + " " + country.name() + " " + season + " " + number + " rider id "
				+ (rider != null ? Integer.toString(rider.get_id()) : "null");
	}

	public void setRider(Rider rider) {
		this.rider = rider;
	}

	public int get_id() {
		return _id;
	}

	public void setDayRider(boolean dayRider) {
		this.dayRider = dayRider;
	}

	public boolean isDayRider() {
		return dayRider;
	}

	public void setRegistered(boolean registered) {
		this.registered = registered;
	}

	public void set_id(int id) {
		this._id = id;
	}

	public Bib getBib() {
		return bib;
	}

	public void setBib(Bib bib) {
		this.bib = bib;
	}

	public void setRiderNumber(int riderNumber) {
		this.number = riderNumber;
	}

	public int getNumber() {
		return number;
	}
}


text: export * from './my-gallery.component';


text:
<?php
defined('WYSIJA') or die('Restricted access');

class WYSIJA_control_front_confirm extends WYSIJA_control_front{
    var $model='user';
    var $view='confirm';

    function WYSIJA_control_front_confirm(){
        parent::WYSIJA_control_front();
    }

    function _testKeyuser(){
        $this->helperUser=WYSIJA::get('user','helper');

        $this->userData=$this->helperUser->checkUserKey();
        add_action('init',array($this,'testsession'));

        if(!$this->userData){
            $this->title=__('Page does not exist.',WYSIJA);
            $this->subtitle=__('Please verify your link to this page.',WYSIJA);
            return false;
        }
        return true;
    }

    /**
     * confirm subscription page
     * return boolean
     */
    function subscribe(){
        $helper_user = WYSIJA::get('user','helper');
        if(!isset($_REQUEST['demo'])){
            $helper_user->confirm_user();

            if(!empty($helper_user->title))    $this->title = $helper_user->title;
            if(!empty($helper_user->subtitle))    $this->optional_subtitle = $helper_user->subtitle;
        }else{
            $model_config=WYSIJA::get('config','model');

            // we need to call the translation otherwise it will not be loaded and translated
            $model_config->add_translated_default();

            $this->title = sprintf($model_config->getValue('subscribed_title'), 'demo');
            $this->optional_subtitle=$model_config->getValue('subscribed_subtitle');
        }

        return true;
    }

    function unsubscribe(){
        $model_config=WYSIJA::get('config','model');

        // we need to call the translation otherwise it will not be loaded and translated
        $model_config->add_translated_default();

        $this->title = $model_config->getValue('unsubscribed_title');
        if(!isset($model_config->values['unsubscribed_title'])) $this->title = __("You've unsubscribed!",WYSIJA);

        $this->optional_subtitle = $model_config->getValue('unsubscribed_subtitle');
        if(!isset($model_config->values['unsubscribed_subtitle'])) $this->optional_subtitle = __("Great, you'll never hear from us again!",WYSIJA);

        $wysija_key = '';
        if(isset( $_GET['wysija-key'] )){
            $wysija_key = $_GET['wysija-key'];
        }
        $undo_paramsurl = array(
             'wysija-page' => 1,
             'controller' => 'confirm',
             'action' => 'undounsubscribe',
             'wysija-key' => $wysija_key
             );

        if(! isset($_GET['demo']) ){
            if($this->_testKeyuser()){
                $statusint=(int)$this->userData['details']['status'];
                if( ($model_config->getValue('confirm_dbleoptin') && $statusint>0) || (!$model_config->getValue('confirm_dbleoptin') && $statusint>=0)){
                    $listids=$this->helperUser->unsubscribe($this->userData['details']['user_id']);
                    $this->helperUser->uid=$this->userData['details']['user_id'];
                    if($model_config->getValue('emails_notified') && $model_config->getValue('emails_notified_when_unsub'))    $this->helperUser->_notify($this->userData['details']['email'],false,$listids);
                }else{
                    $this->title=__('You are already unsubscribed.',WYSIJA);
                    return false;
                }
            }
        }else{
            $undo_paramsurl['demo'] = 1;
        }

        $link_undo = WYSIJA::get_permalink($model_config->getValue('unsubscribe_page'),$undo_paramsurl);

        $this->undo_unsubscribe = str_replace(
                array('[link]','[/link]'),
                array('',''),
                '
'.__('You made a mistake? [link]Undo unsubscribe[/link].',WYSIJA)).'
';
        return true;
    }

    function undounsubscribe(){
        $model_config=WYSIJA::get('config','model');

        // we need to call the translation otherwise it will not be loaded and translated
        $model_config->add_translated_default();

        $this->title =__("You've been subscribed!",WYSIJA);
        $user_object = false;
        if(!isset($_REQUEST['demo'])){
            if($this->_testKeyuser()){
                $user_object = (object)$this->userData['details'];
                $this->helperUser->undounsubscribe($this->userData['details']['user_id']);
            }
        }

        //manage subcription link
        if(($model_config->getValue('manage_subscriptions'))){
            $helper_user = WYSIJA::get('config','helper');
            $model_user = WYSIJA::get('user','model');
            $editsubscriptiontxt = $model_config->getValue('manage_subscriptions_linkname');
            if(empty($editsubscriptiontxt)) $editsubscriptiontxt =__('Edit your subscription',WYSIJA);
            $this->subtitle = '
'.$model_user->getEditsubLink($user_object,false,'').'.
';
        }
        return true;
    }

    function subscriptions(){
        $data=array();

        //get the user_id out of the params passed
        if($this->_testKeyuser()){

            $data['user']=$this->userData;
            //get the list of user
            $model_list=WYSIJA::get('list','model');
            $model_list->orderBy('ordering','ASC');
            $data['list']=$model_list->get(array('list_id','name','description'),array('is_enabled'=>true,'is_public'=>true));

            $this->title=sprintf(__('Edit your subscriber profile: %1$s',WYSIJA),$data['user']['details']['email']);

            $this->subtitle=$this->viewObj->subscriptions($data);

            return true;
        }

    }

    function resend(){
        $this->title='The link you clicked has expired';

        $this->subtitle=$this->viewObj->resend();
    }

    function resendconfirm(){
        //make sure the user has the right to access this action
        if($this->requireSecurity()){
            //resend email
            $helper_mailer=WYSIJA::get('mailer','helper');
            $helper_mailer->sendOne((int)$_REQUEST['email_id'],(int)$_REQUEST['user_id']);
            $this->title='Please check your inbox!';

            $this->subtitle='
A new email with working links has been sent to you.
';
        }
    }

    function save(){

        //get the user_id out of the params passed */
        if($this->_testKeyuser()){
            //update the general details */
            $userid=$_REQUEST['wysija']['user']['user_id'];
            unset($_REQUEST['wysija']['user']['user_id']);
            $model_config=WYSIJA::get('config','model');
            // we need to call the translation otherwise it will not be loaded and translated
            $model_config->add_translated_default();
            $this->helperUser->uid=$userid;
            //if the status changed we might need to send notifications */
            if((int)$_REQUEST['wysija']['user']['status'] !=(int)$this->userData['details']['status']){
                if($_REQUEST['wysija']['user']['status']>0){
                    if($model_config->getValue('emails_notified_when_sub'))    $this->helperUser->_notify($this->userData['details']['email']);
                }else{
                    if($model_config->getValue('emails_notified_when_unsub'))    $this->helperUser->_notify($this->userData['details']['email'],false);
                }
            }

            //check whether the email address has changed if so then we should make sure that the new address doesnt exists already
            if(isset($_REQUEST['wysija']['user']['email'])){
                $_REQUEST['wysija']['user']['email']=trim($_REQUEST['wysija']['user']['email']);
                if($this->userData['details']['email']!=$_REQUEST['wysija']['user']['email']){
                    $this->modelObj->reset();
                    $result=$this->modelObj->getOne(false,array('email'=>$_REQUEST['wysija']['user']['email']));
                    if($result){
                        $this->error(sprintf(__('Email %1$s already exists.',WYSIJA),$_REQUEST['wysija']['user']['email']),1);
                        unset($_REQUEST['wysija']['user']['email']);
                    }
                }
            }

            $this->modelObj->update($_REQUEST['wysija']['user'],array('user_id'=>$userid));
            $id=$userid;

            $hUser=WYSIJA::get('user','helper');
            //update the list subscriptions */
           //run the unsubscribe process if needed
            if((int)$_REQUEST['wysija']['user']['status']==-1){
                $hUser->unsubscribe($id);
            }

            //update subscriptions */
            $modelUL=WYSIJA::get('user_list','model');
            $modelUL->backSave=true;
            /* list of core list */
            $modelLIST=WYSIJA::get('list','model');

	    // Using "like" condition in order to force sql query to OR (instead of AND). It'll be incorrct if status contains other values than 0/1.
            $results=$modelLIST->get(array('list_id'),array('like' => array('is_enabled'=>0, 'is_public' => 0)));
            $static_listids=array();
            foreach($results as $res){
                $static_listids[]=$res['list_id'];
            }

            //0 - get current lists of the user
            $userlists=$modelUL->get(array('list_id','unsub_date'),array('user_id'=>$id));

            $oldlistids=$new_list_ids=array();
            foreach($userlists as $listdata)    $oldlistids[$listdata['list_id']]=$listdata['unsub_date'];

            $config=WYSIJA::get('config','model');
            $dbloptin=$config->getValue('confirm_dbleoptin');
            //1 - insert new user_list
            if(isset($_POST['wysija']['user_list']['list_id']) && $_POST['wysija']['user_list']['list_id']){
                $modelUL->reset();
                $modelUL->update(array('sub_date'=>time()),array('user_id'=>$id));
                foreach($_POST['wysija']['user_list']['list_id'] as $list_id){
                    //if the list is not already recorded for the user then we will need to insert it
                    if(!isset($oldlistids[$list_id])){
                        $modelUL->reset();
                        $new_list_ids[]=$list_id;
                        $dataul=array('user_id'=>$id,'list_id'=>$list_id,'sub_date'=>time());
                        //if double optin is on then we want to send a confirmation email for newly added subscription
                        if($dbloptin){
                            unset($dataul['sub_date']);
                            $modelUL->nohook=true;
                        }
                        $modelUL->insert($dataul);
                    //if the list is recorded already then let's check the status, if it is an unsubed one then we update it
                    }else{
                        if($oldlistids[$list_id]>0){
                            $modelUL->reset();
                            $modelUL->update(array('unsub_date'=>0,'sub_date'=>time()),array('user_id'=>$id,'list_id'=>$list_id));
                        }
                        //$alreadysubscribelistids[]=$list_id;
                    }
                }
            }

            //if a confirmation email needs to be sent then we send it

            if($dbloptin && !empty($new_list_ids)){
                $send_confirmation = true;
                $send_confirmation = apply_filters('mpoet_confirm_new_list_subscriptions_page', $send_confirmation);

                if($send_confirmation === true){
                    $hUser->sendConfirmationEmail($id,true,$new_list_ids);
                }else{
                    // this case has been made so that when subscribers add themselves to a
                    // list through the edit your subscription form they don't receive a confirmation email they already confirmed.
                    // so they receive also the autorespo,nders correspondign to that list immediately.
                    $helper_user = WYSIJA::get('user','helper');
                    $_REQUEST['wysiconf'] = base64_encode(serialize($new_list_ids));
                    $helper_user->confirm_user();
                }
            }

            // list ids
            $list_ids = !empty($_POST['wysija']['user_list']['list_id']) ? $_POST['wysija']['user_list']['list_id'] : array();
            if(is_array($list_ids) === false) $list_ids = array();

            $notEqual = array_merge($static_listids, $list_ids);

            //delete the lists from which you've removed yourself
            $condiFirst = array('notequal'=>array('list_id'=> $notEqual), 'equal' => array('user_id' => $id, 'unsub_date' => 0));
            $modelUL=WYSIJA::get('user_list','model');
            $modelUL->update(array('unsub_date'=>time()),$condiFirst);
            $modelUL->reset();

            /*
            Custom Fields.
            */
            if (isset($_POST['wysija']['field'])) {
              WJ_FieldHandler::handle_all(
                $_POST['wysija']['field'], $id
              );
            }

            $this->notice(__('Newsletter profile has been updated.',WYSIJA));
            $this->subscriptions();

            //reset post otherwise wordpress will not recognise the post !!!
            $_POST=array();
        }
        return true;
    }
}


text:
layout: talks
title: Async PHP requests & reactive responses
subtitle: Fast CGI Client
tags: [FastCGI, PHP FPM, PHP, talk, OSS]
permalink: /talks/async-php-request-and-reactive-responses-phpugdd.html
slug: talks
---

Talk at [PHP USERGROUP DRESDEN, Dresden, Germany](http://phpug-dresden.org)

### Slides on [Speaker Deck](https://speakerdeck.com/hollodotme)

<script async class="speakerdeck-embed" data-id="a96ceefda84240f184e3caeab61eb1fe" data-ratio="1.77777777777778" src="//speakerdeck.com/assets/embed.js"></script>


text:
<?php
/**
 * G_View_Helper_HtmlLink
 * Generate HTML links (...)
 * @author Harmen Janssen | grrr.nl
 * @modifiedby $LastChangedBy: $
 * @version $Revision: $
 * @package Garp
 * @subpackage Helper
 * @lastmodified $Date: $
 */
class G_View_Helper_HtmlLink extends Zend_View_Helper_HtmlElement {
	/**
	 * Return a HTML  tag
	 * @param Array|String $url The url to link to (e.g. ),
	 * 							or an array with values matching Zend_View_Helper_Url::url().
	 * @param String $label The link label (e.g. $label)
	 * @param Array $attributes More attributes
	 * @param Boolean $escape Wether to escape attributes and label
	 * @return String
	 */
	public function htmlLink($url, $label, array $attributes = array(), $escape = true) {
		if (is_array($url)) {
			$url = call_user_func_array(array($this->view, 'url'), $url);
		} elseif ($url instanceof Garp_Util_RoutedUrl) {
			$url = (string)$url;
		} else {
			$urlAttribs = parse_url($url);
			if (empty($urlAttribs['scheme']) && substr($url, 0, 2) !== '//') {
				$url = $this->view->baseUrl($url);
			}
		}
		$attributes['href'] = $url;
		$label = $escape ? $this->view->escape($label) : $label;
		$html = '_htmlAttribs($attributes).'>'.$label.'';
		return $html;
	}
}


text:
You're given an array `a` with numbers. Write an algorithm that checks if there are any two entries in the array that add up to a given number `k`. In other words, is there any `a[i] + a[j] == k`?

There are a variety of solutions to this problem (some better than others) but I quite like the following.

**Note**: This particular algorithm requires that the array is sorted, so if the array isn't sorted yet (usually it won't be), you need to sort it first. The time complexity of the algorithm itself is **O(n)** but if you have to sort first, the total time complexity becomes **O(n log n)**. Slightly worse but still quite acceptable.

Here is the code in Swift:

```swift
func twoSumProblem(a: [Int], k: Int) -> ((Int, Int))? {
  var i = 0
  var j = a.count - 1

  while i < j {
    let sum = a[i] + a[j]
    if sum == k {
      return (i, j)
    } else if sum < k {
      ++i
    } else {
      --j
    }
  }
  return nil
}
```

The `twoSumProblem()` function takes as parameters the array `a` with the numbers, which it assumes is sorted, and `k`, the sum we're looking for. If there are two numbers that add up to `k`, the function returns a tuple containing their array indices. If not, it returns `nil`.

To test it, copy the code into a playground and add the following:

```swift
let a = [2, 3, 4, 4, 7, 8, 9, 10, 12, 14, 21, 22, 100]
if let (i, j) = twoSumProblem(a, k: 33) {
  a[i] + a[j]  // 33
}
```

This returns the tuple `(8, 10)` because `a[8] = 12` and `a[10] = 21`, and together they add up to `33`.

So how does this algorithm work? It takes advantage of the array being sorted. That's true for many algorithms, by the way. If you first sort the data, it's often easier to perform your calculations.

In the example, the sorted array is:

	[ 2, 3, 4, 4, 7, 8, 9, 10, 12, 14, 21, 22, 100 ]

The algorithm uses the two variables `i` and `j` to point to the beginning and end of the array, respectively. Then it increments `i` and decrements `j` until the two meet. While it's doing this, it checks whether `a[i]` and `a[j]` add up to `k`.

Let's step through this. Initially, we have:

	[ 2, 3, 4, 4, 7, 8, 9, 10, 12, 14, 21, 22, 100 ]
      i                                        j

The sum of these two is `2 + 100 = 102`. That's obviously too much, since `k = 33` in this example. There is no way that `100` will ever be part of the answer, so decrement `j`.

We have:

	[ 2, 3, 4, 4, 7, 8, 9, 10, 12, 14, 21, 22, 100 ]
      i                                    j

The sum is `2 + 22 = 24`. Now the sum is too small. We can safely conclude at this point that the number `2` will never be part of the answer. The largest number on the right is `22`, so we at least need `11` on the left to make `33`. Anything less than `11` is not going to cut it. (This is why we sorted the array!)

So, `2` is out and we increment `i` to look at the next small number.

	[ 2, 3, 4, 4, 7, 8, 9, 10, 12, 14, 21, 22, 100 ]
         i                                 j

The sum is `3 + 22 = 25`. Still too small, so increment `i` again.

	[ 2, 3, 4, 4, 7, 8, 9, 10, 12, 14, 21, 22, 100 ]
            i                              j

In fact, we have to increment `i` a few more times, until we get to `12`:

	[ 2, 3, 4, 4, 7, 8, 9, 10, 12, 14, 21, 22, 100 ]
                               i           j

Now the sum is `12 + 22 = 34`. It's too high, which means we need to decrement `j`. This gives:

	[ 2, 3, 4, 4, 7, 8, 9, 10, 12, 14, 21, 22, 100 ]
                               i       j

And finally, we have the answer: `12 + 21 = 33`. Yay!

It's possible, of course, that there are no values for `a[i] + a[j]` that sum to `k`. In that case, eventually `i` and `j` will point at the same number. Then we can conclude that no answer exists and we return `nil`.

I'm quite enamored by this little algorithm. It shows that with some basic preprocessing on the input data -- sorting it from low to high -- you can turn a tricky problem into a very simple and beautiful algorithm.

*Written by Matthijs Hollemans*


text:
<!DOCTYPE html>

<title>MessageService_mms_sendMessage_successCallback_TypeMismatch</title>
<meta charset="utf-8"/>


text:
// © 2017 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html

#include "unicode/utypes.h"

#if !UCONFIG_NO_FORMATTING

#include "umutex.h"
#include "ucln_cmn.h"
#include "ucln_in.h"
#include "number_modifiers.h"

using namespace icu;
using namespace icu::number;
using namespace icu::number::impl;

namespace {

// TODO: This is copied from simpleformatter.cpp
const int32_t ARG_NUM_LIMIT = 0x100;

// These are the default currency spacing UnicodeSets in CLDR.
// Pre-compute them for performance.
// The Java unit test testCurrencySpacingPatternStability() will start failing if these change in CLDR.
icu::UInitOnce gDefaultCurrencySpacingInitOnce = U_INITONCE_INITIALIZER;

UnicodeSet *UNISET_DIGIT = nullptr;
UnicodeSet *UNISET_NOTS = nullptr;

UBool U_CALLCONV cleanupDefaultCurrencySpacing() {
    delete UNISET_DIGIT;
    UNISET_DIGIT = nullptr;
    delete UNISET_NOTS;
    UNISET_NOTS = nullptr;
    gDefaultCurrencySpacingInitOnce.reset();
    return TRUE;
}

void U_CALLCONV initDefaultCurrencySpacing(UErrorCode &status) {
    ucln_i18n_registerCleanup(UCLN_I18N_CURRENCY_SPACING, cleanupDefaultCurrencySpacing);
    UNISET_DIGIT = new UnicodeSet(UnicodeString(u"[:digit:]"), status);
    UNISET_NOTS = new UnicodeSet(UnicodeString(u"[:^S:]"), status);
    if (UNISET_DIGIT == nullptr || UNISET_NOTS == nullptr) {
        status = U_MEMORY_ALLOCATION_ERROR;
        return;
    }
    UNISET_DIGIT->freeze();
    UNISET_NOTS->freeze();
}

}  // namespace

Modifier::~Modifier() = default;

Modifier::Parameters::Parameters()
        : obj(nullptr) {}

Modifier::Parameters::Parameters(
    const ModifierStore* _obj, Signum _signum, StandardPlural::Form _plural)
        : obj(_obj), signum(_signum), plural(_plural) {}

ModifierStore::~ModifierStore() = default;

AdoptingModifierStore::~AdoptingModifierStore()  {
    for (const Modifier *mod : mods) {
        delete mod;
    }
}

int32_t ConstantAffixModifier::apply(FormattedStringBuilder &output, int leftIndex, int rightIndex,
                                     UErrorCode &status) const {
    // Insert the suffix first since inserting the prefix will change the rightIndex
    int length = output.insert(rightIndex, fSuffix, fField, status);
    length += output.insert(leftIndex, fPrefix, fField, status);
    return length;
}

int32_t ConstantAffixModifier::getPrefixLength() const {
    return fPrefix.length();
}

int32_t ConstantAffixModifier::getCodePointCount() const {
    return fPrefix.countChar32() + fSuffix.countChar32();
}

bool ConstantAffixModifier::isStrong() const {
    return fStrong;
}

bool ConstantAffixModifier::containsField(Field field) const {
    (void)field;
    // This method is not currently used.
    UPRV_UNREACHABLE;
}

void ConstantAffixModifier::getParameters(Parameters& output) const {
    (void)output;
    // This method is not currently used.
    UPRV_UNREACHABLE;
}

bool ConstantAffixModifier::semanticallyEquivalent(const Modifier& other) const {
    auto* _other = dynamic_cast<const ConstantAffixModifier*>(&other);
    if (_other == nullptr) {
        return false;
    }
    return fPrefix == _other->fPrefix
        && fSuffix == _other->fSuffix
        && fField == _other->fField
        && fStrong == _other->fStrong;
}

SimpleModifier::SimpleModifier(const SimpleFormatter &simpleFormatter, Field field, bool strong)
        : SimpleModifier(simpleFormatter, field, strong, {}) {}

SimpleModifier::SimpleModifier(const SimpleFormatter &simpleFormatter, Field field, bool strong,
                               const Modifier::Parameters parameters)
        : fCompiledPattern(simpleFormatter.compiledPattern), fField(field), fStrong(strong),
          fParameters(parameters) {
    int32_t argLimit = SimpleFormatter::getArgumentLimit(
            fCompiledPattern.getBuffer(), fCompiledPattern.length());
    if (argLimit == 0) {
        // No arguments in compiled pattern
        fPrefixLength = fCompiledPattern.charAt(1) - ARG_NUM_LIMIT;
        U_ASSERT(2 + fPrefixLength == fCompiledPattern.length());
        // Set suffixOffset = -1 to indicate no arguments in compiled pattern.
        fSuffixOffset = -1;
        fSuffixLength = 0;
    } else {
        U_ASSERT(argLimit == 1);
        if (fCompiledPattern.charAt(1) != 0) {
            // Found prefix
            fPrefixLength = fCompiledPattern.charAt(1) - ARG_NUM_LIMIT;
            fSuffixOffset = 3 + fPrefixLength;
        } else {
            // No prefix
            fPrefixLength = 0;
            fSuffixOffset = 2;
        }
        if (3 + fPrefixLength < fCompiledPattern.length()) {
            // Found suffix
            fSuffixLength = fCompiledPattern.charAt(fSuffixOffset) - ARG_NUM_LIMIT;
        } else {
            // No suffix
            fSuffixLength = 0;
        }
    }
}

SimpleModifier::SimpleModifier()
        : fField(kUndefinedField), fStrong(false), fPrefixLength(0), fSuffixLength(0) {
}

int32_t SimpleModifier::apply(FormattedStringBuilder &output, int leftIndex, int rightIndex,
                              UErrorCode &status) const {
    return formatAsPrefixSuffix(output, leftIndex, rightIndex, status);
}

int32_t SimpleModifier::getPrefixLength() const {
    return fPrefixLength;
}

int32_t SimpleModifier::getCodePointCount() const {
    int32_t count = 0;
    if (fPrefixLength > 0) {
        count += fCompiledPattern.countChar32(2, fPrefixLength);
    }
    if (fSuffixLength > 0) {
        count += fCompiledPattern.countChar32(1 + fSuffixOffset, fSuffixLength);
    }
    return count;
}

bool SimpleModifier::isStrong() const {
    return fStrong;
}

bool SimpleModifier::containsField(Field field) const {
    (void)field;
    // This method is not currently used.
    UPRV_UNREACHABLE;
}

void SimpleModifier::getParameters(Parameters& output) const {
    output = fParameters;
}

bool SimpleModifier::semanticallyEquivalent(const Modifier& other) const {
    auto* _other = dynamic_cast<const SimpleModifier*>(&other);
    if (_other == nullptr) {
        return false;
    }
    if (fParameters.obj != nullptr) {
        return fParameters.obj == _other->fParameters.obj;
    }
    return fCompiledPattern == _other->fCompiledPattern
        && fField == _other->fField
        && fStrong == _other->fStrong;
}

int32_t
SimpleModifier::formatAsPrefixSuffix(FormattedStringBuilder &result, int32_t startIndex, int32_t endIndex,
                                     UErrorCode &status) const {
    if (fSuffixOffset == -1 && fPrefixLength + fSuffixLength > 0) {
        // There is no argument for the inner number; overwrite the entire segment with our string.
        return result.splice(startIndex, endIndex, fCompiledPattern, 2, 2 + fPrefixLength, fField, status);
    } else {
        if (fPrefixLength > 0) {
            result.insert(startIndex, fCompiledPattern, 2, 2 + fPrefixLength, fField, status);
        }
        if (fSuffixLength > 0) {
            result.insert(
                    endIndex + fPrefixLength,
                    fCompiledPattern,
                    1 + fSuffixOffset,
                    1 + fSuffixOffset + fSuffixLength,
                    fField,
                    status);
        }
        return fPrefixLength + fSuffixLength;
    }
}

int32_t
SimpleModifier::formatTwoArgPattern(const SimpleFormatter& compiled, FormattedStringBuilder& result,
                                    int32_t index, int32_t* outPrefixLength, int32_t* outSuffixLength,
                                    Field field, UErrorCode& status) {
    const UnicodeString& compiledPattern = compiled.compiledPattern;
    int32_t argLimit = SimpleFormatter::getArgumentLimit(
            compiledPattern.getBuffer(), compiledPattern.length());
    if (argLimit != 2) {
        status = U_INTERNAL_PROGRAM_ERROR;
        return 0;
    }
    int32_t offset = 1; // offset into compiledPattern
    int32_t length = 0; // chars added to result

    int32_t prefixLength = compiledPattern.charAt(offset);
    offset++;
    if (prefixLength < ARG_NUM_LIMIT) {
        // No prefix
        prefixLength = 0;
    } else {
        prefixLength -= ARG_NUM_LIMIT;
        result.insert(index + length, compiledPattern, offset, offset + prefixLength, field, status);
        offset += prefixLength;
        length += prefixLength;
        offset++;
    }

    int32_t infixLength = compiledPattern.charAt(offset);
    offset++;
    if (infixLength < ARG_NUM_LIMIT) {
        // No infix
        infixLength = 0;
    } else {
        infixLength -= ARG_NUM_LIMIT;
        result.insert(index + length, compiledPattern, offset, offset + infixLength, field, status);
        offset += infixLength;
        length += infixLength;
        offset++;
    }

    int32_t suffixLength;
    if (offset == compiledPattern.length()) {
        // No suffix
        suffixLength = 0;
    } else {
        suffixLength = compiledPattern.charAt(offset) -  ARG_NUM_LIMIT;
        offset++;
        result.insert(index + length, compiledPattern, offset, offset + suffixLength, field, status);
        length += suffixLength;
    }

    *outPrefixLength = prefixLength;
    *outSuffixLength = suffixLength;

    return length;
}

int32_t ConstantMultiFieldModifier::apply(FormattedStringBuilder &output, int leftIndex, int rightIndex,
                                          UErrorCode &status) const {
    int32_t length = output.insert(leftIndex, fPrefix, status);
    if (fOverwrite) {
        length += output.splice(
            leftIndex + length,
            rightIndex + length,
            UnicodeString(), 0, 0,
            kUndefinedField, status);
    }
    length += output.insert(rightIndex + length, fSuffix, status);
    return length;
}

int32_t ConstantMultiFieldModifier::getPrefixLength() const {
    return fPrefix.length();
}

int32_t ConstantMultiFieldModifier::getCodePointCount() const {
    return fPrefix.codePointCount() + fSuffix.codePointCount();
}

bool ConstantMultiFieldModifier::isStrong() const {
    return fStrong;
}

bool ConstantMultiFieldModifier::containsField(Field field) const {
    return fPrefix.containsField(field) || fSuffix.containsField(field);
}

void ConstantMultiFieldModifier::getParameters(Parameters& output) const {
    output = fParameters;
}

bool ConstantMultiFieldModifier::semanticallyEquivalent(const Modifier& other) const {
    auto* _other = dynamic_cast<const ConstantMultiFieldModifier*>(&other);
    if (_other == nullptr) {
        return false;
    }
    if (fParameters.obj != nullptr) {
        return fParameters.obj == _other->fParameters.obj;
    }
    return fPrefix.contentEquals(_other->fPrefix)
        && fSuffix.contentEquals(_other->fSuffix)
        && fOverwrite == _other->fOverwrite
        && fStrong == _other->fStrong;
}

CurrencySpacingEnabledModifier::CurrencySpacingEnabledModifier(const FormattedStringBuilder &prefix,
                                                               const FormattedStringBuilder &suffix,
                                                               bool overwrite,
                                                               bool strong,
                                                               const DecimalFormatSymbols &symbols,
                                                               UErrorCode &status)
        : ConstantMultiFieldModifier(prefix, suffix, overwrite, strong) {
    // Check for currency spacing. Do not build the UnicodeSets unless there is
    // a currency code point at a boundary.
    if (prefix.length() > 0 && prefix.fieldAt(prefix.length() - 1) == Field(UFIELD_CATEGORY_NUMBER, UNUM_CURRENCY_FIELD)) {
        int prefixCp = prefix.getLastCodePoint();
        UnicodeSet prefixUnicodeSet = getUnicodeSet(symbols, IN_CURRENCY, PREFIX, status);
        if (prefixUnicodeSet.contains(prefixCp)) {
            fAfterPrefixUnicodeSet = getUnicodeSet(symbols, IN_NUMBER, PREFIX, status);
            fAfterPrefixUnicodeSet.freeze();
            fAfterPrefixInsert = getInsertString(symbols, PREFIX, status);
        } else {
            fAfterPrefixUnicodeSet.setToBogus();
            fAfterPrefixInsert.setToBogus();
        }
    } else {
        fAfterPrefixUnicodeSet.setToBogus();
        fAfterPrefixInsert.setToBogus();
    }
    if (suffix.length() > 0 && suffix.fieldAt(0) == Field(UFIELD_CATEGORY_NUMBER, UNUM_CURRENCY_FIELD)) {
        int suffixCp = suffix.getFirstCodePoint();
        UnicodeSet suffixUnicodeSet = getUnicodeSet(symbols, IN_CURRENCY, SUFFIX, status);
        if (suffixUnicodeSet.contains(suffixCp)) {
            fBeforeSuffixUnicodeSet = getUnicodeSet(symbols, IN_NUMBER, SUFFIX, status);
            fBeforeSuffixUnicodeSet.freeze();
            fBeforeSuffixInsert = getInsertString(symbols, SUFFIX, status);
        } else {
            fBeforeSuffixUnicodeSet.setToBogus();
            fBeforeSuffixInsert.setToBogus();
        }
    } else {
        fBeforeSuffixUnicodeSet.setToBogus();
        fBeforeSuffixInsert.setToBogus();
    }
}

int32_t CurrencySpacingEnabledModifier::apply(FormattedStringBuilder &output, int leftIndex, int rightIndex,
                                              UErrorCode &status) const {
    // Currency spacing logic
    int length = 0;
    if (rightIndex - leftIndex > 0 && !fAfterPrefixUnicodeSet.isBogus() &&
        fAfterPrefixUnicodeSet.contains(output.codePointAt(leftIndex))) {
        // TODO: Should we use the CURRENCY field here?
        length += output.insert(
            leftIndex,
            fAfterPrefixInsert,
            kUndefinedField,
            status);
    }
    if (rightIndex - leftIndex > 0 && !fBeforeSuffixUnicodeSet.isBogus() &&
        fBeforeSuffixUnicodeSet.contains(output.codePointBefore(rightIndex))) {
        // TODO: Should we use the CURRENCY field here?
        length += output.insert(
            rightIndex + length,
            fBeforeSuffixInsert,
            kUndefinedField,
            status);
    }

    // Call super for the remaining logic
    length += ConstantMultiFieldModifier::apply(output, leftIndex, rightIndex + length, status);
    return length;
}

int32_t
CurrencySpacingEnabledModifier::applyCurrencySpacing(FormattedStringBuilder &output, int32_t prefixStart,
                                                     int32_t prefixLen, int32_t suffixStart,
                                                     int32_t suffixLen,
                                                     const DecimalFormatSymbols &symbols,
                                                     UErrorCode &status) {
    int length = 0;
    bool hasPrefix = (prefixLen > 0);
    bool hasSuffix = (suffixLen > 0);
    bool hasNumber = (suffixStart - prefixStart - prefixLen > 0); // could be empty string
    if (hasPrefix && hasNumber) {
        length += applyCurrencySpacingAffix(output, prefixStart + prefixLen, PREFIX, symbols, status);
    }
    if (hasSuffix && hasNumber) {
        length += applyCurrencySpacingAffix(output, suffixStart + length, SUFFIX, symbols, status);
    }
    return length;
}

int32_t
CurrencySpacingEnabledModifier::applyCurrencySpacingAffix(FormattedStringBuilder &output, int32_t index,
                                                          EAffix affix,
                                                          const DecimalFormatSymbols &symbols,
                                                          UErrorCode &status) {
    // NOTE: For prefix, output.fieldAt(index-1) gets the last field type in the prefix.
    // This works even if the last code point in the prefix is 2 code units because the
    // field value gets populated to both indices in the field array.
    Field affixField = (affix == PREFIX) ? output.fieldAt(index - 1) : output.fieldAt(index);
    if (affixField != Field(UFIELD_CATEGORY_NUMBER, UNUM_CURRENCY_FIELD)) {
        return 0;
    }
    int affixCp = (affix == PREFIX) ? output.codePointBefore(index) : output.codePointAt(index);
    UnicodeSet affixUniset = getUnicodeSet(symbols, IN_CURRENCY, affix, status);
    if (!affixUniset.contains(affixCp)) {
        return 0;
    }
    int numberCp = (affix == PREFIX) ? output.codePointAt(index) : output.codePointBefore(index);
    UnicodeSet numberUniset = getUnicodeSet(symbols, IN_NUMBER, affix, status);
    if (!numberUniset.contains(numberCp)) {
        return 0;
    }
    UnicodeString spacingString = getInsertString(symbols, affix, status);

    // NOTE: This next line *inserts* the spacing string, triggering an arraycopy.
    // It would be more efficient if this could be done before affixes were attached,
    // so that it could be prepended/appended instead of inserted.
    // However, the build code path is more efficient, and this is the most natural
    // place to put currency spacing in the non-build code path.
    // TODO: Should we use the CURRENCY field here?
    return output.insert(index, spacingString, kUndefinedField, status);
}

UnicodeSet
CurrencySpacingEnabledModifier::getUnicodeSet(const DecimalFormatSymbols &symbols, EPosition position,
                                              EAffix affix, UErrorCode &status) {
    // Ensure the static defaults are initialized:
    umtx_initOnce(gDefaultCurrencySpacingInitOnce, &initDefaultCurrencySpacing, status);
    if (U_FAILURE(status)) {
        return UnicodeSet();
    }

    const UnicodeString& pattern = symbols.getPatternForCurrencySpacing(
            position == IN_CURRENCY ? UNUM_CURRENCY_MATCH : UNUM_CURRENCY_SURROUNDING_MATCH,
            affix == SUFFIX,
            status);
    if (pattern.compare(u"[:digit:]", -1) == 0) {
        return *UNISET_DIGIT;
    } else if (pattern.compare(u"[:^S:]", -1) == 0) {
        return *UNISET_NOTS;
    } else {
        return UnicodeSet(pattern, status);
    }
}

UnicodeString
CurrencySpacingEnabledModifier::getInsertString(const DecimalFormatSymbols &symbols, EAffix affix,
                                                UErrorCode &status) {
    return symbols.getPatternForCurrencySpacing(UNUM_CURRENCY_INSERT, affix == SUFFIX, status);
}

#endif /* #if !UCONFIG_NO_FORMATTING */