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

<title>State</title>
<meta name="date" content="2017-02-26">
<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 Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

kariminf.faris.philosophical

Class State

java.lang.Object

kariminf.faris.philosophical.Being

kariminf.faris.philosophical.State

public class State
extends Being

Having or state, condition (ἔχειν, echein, to have or be).
 The examples Aristotle gives indicate that he meant a condition of rest resulting
 from an affection (i.e. being acted on): 'shod', 'armed'. The term is, however,
 frequently taken to mean the determination arising from the physical accoutrements
 of an object: one's shoes, one's arms, etc. Traditionally, this category is also
 called a habitus (from Latin habere, to have).

Author:

Abdelkrime Aries (kariminfo0@gmail.com)

         Copyright (c) 2015-2017 Abdelkrime Aries

         Licensed under the Apache License, Version 2.0 (the "License");
         you may not use this file except in compliance with the License.
         You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

         Unless required by applicable law or agreed to in writing, software
         distributed under the License is distributed on an "AS IS" BASIS,
         WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
         See the License for the specific language governing permissions and
         limitations under the License.

Nested Class Summary

Nested Classes

Modifier and Type
Class and Description

static class
State.StateWrapper

Field Summary

Fields

Modifier and Type
Field and Description

(package private) kariminf.sentrep.univ.types.Relation.Relative
affectionType

private java.util.List<Action>
mainActions

private Action
stateAction

Constructor Summary

Constructors

Constructor and Description

State()

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

void
addMainAction(Action mainAction)

boolean
affectState(Action action,
           QuantSubstance owner,
           java.util.List<java.util.List<QuantSubstance>> relatives,
           kariminf.sentrep.univ.types.Relation.Relative affectionType)

void
generate(Generator gr)

java.util.List<Action>
getMainActions()

Action
getStateAction()

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

mainActions

private java.util.List<Action> mainActions

affectionType

kariminf.sentrep.univ.types.Relation.Relative affectionType

stateAction

private Action stateAction

Constructor Detail

State

public State()

Parameters:

mainAction -

Method Detail

addMainAction

public void addMainAction(Action mainAction)

affectState

public boolean affectState(Action action,
                           QuantSubstance owner,
                           java.util.List<java.util.List<QuantSubstance>> relatives,
                           kariminf.sentrep.univ.types.Relation.Relative affectionType)

Parameters:

action - the action which represents a state.
 This action must not have subjects or objects.

 Example: a car which is stopped on the road and have an old engine.
 The car have two states: "stopped" and "having old engine".

haver - The substance which have this state

relatives - The subjects or the objects that share this action with the haver.
 If the haver is a subject, the relatives are objects, and vis-versa.

affected - if SUBJECT then the haver is a subject, otherwise it is an object

Returns:

true if the affectation is successful

getMainActions

public java.util.List<Action> getMainActions()

getStateAction

public Action getStateAction()

Returns:

the stateAction

generate

public void generate(Generator gr)

Specified by:

generate in class Being

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
package reportsha

import (
	"encoding/json"
	"expvar"
	"fmt"
	"io/ioutil"
	"os"
	"sync"

	"github.com/signalfx/golib/v3/datapoint"
	"github.com/signalfx/golib/v3/log"
	"github.com/signalfx/golib/v3/logkey"
	"github.com/signalfx/golib/v3/sfxclient"
)

// SHA1Reporter reports a gauge to Client that is the commit SHA1 of the current image
type SHA1Reporter struct {
	RepoURL  string
	FileName string
	Logger   log.Logger
	Fi       fileInfo
	Tag      string
	oc       sync.Once
}

type fileInfo struct {
	Name    string `json:"name"`
	Version string `json:"version"`
	Builder string `json:"builder"`
	Commit  string `json:"commit"`
	Source  string
}

func load(fileName string) (fileInfo, error) {
	var fi fileInfo
	contents, err := ioutil.ReadFile(fileName)
	if err != nil {
		return fi, err
	}
	if err := json.Unmarshal(contents, &fi); err != nil {
		return fi, err
	}
	return fi, nil
}

func (s *SHA1Reporter) loadInfo() {
	s.oc.Do(func() {
		s.Tag = os.Getenv("DOCKER_TAG")
		fi, err := load(s.FileName)
		if err != nil {
			s.Logger.Log(log.Err, err, logkey.Name, s.FileName, "Cannot load file info!")
			return
		}
		fi.Source = fmt.Sprintf("%s/tree/%s", s.RepoURL, fi.Commit)
		s.Fi = fi
	})
}

// Var returns an expvar that is the build file info
func (s *SHA1Reporter) Var() expvar.Var {
	s.loadInfo()
	return expvar.Func(func() interface{} {
		return s.Fi
	})
}

// Datapoints returns a single datapoint that includes the commit sha loaded from a config file
func (s *SHA1Reporter) Datapoints() []*datapoint.Datapoint {
	s.loadInfo()
	dims := map[string]string{"commit": s.Fi.Commit}
	if len(s.Tag) > 0 {
		dims["dockerTag"] = s.Tag
	}
	return []*datapoint.Datapoint{
		sfxclient.Gauge("fileinfo_commit", dims, int64(1)),
	}
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using Azure.Core;

namespace Azure.ResourceManager.Storage.Models
{
    /// <summary> The parameters used when creating a storage account. </summary>
    public partial class StorageAccountCreateParameters
    {
        /// <summary> Initializes a new instance of StorageAccountCreateParameters. </summary>
        /// <param name="sku"> Required. Gets or sets the SKU name. </param>
        /// <param name="kind"> Required. Indicates the type of storage account. </param>
        /// <param name="location"> Required. Gets or sets the location of the resource. This will be one of the supported and registered Azure Geo Regions (e.g. West US, East US, Southeast Asia, etc.). The geo region of a resource cannot be changed once it is created, but if an identical geo region is specified on update, the request will succeed. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="sku"/> or <paramref name="location"/> is null. </exception>
        public StorageAccountCreateParameters(Sku sku, Kind kind, string location)
        {
            if (sku == null)
            {
                throw new ArgumentNullException(nameof(sku));
            }
            if (location == null)
            {
                throw new ArgumentNullException(nameof(location));
            }

            Sku = sku;
            Kind = kind;
            Location = location;
            Tags = new ChangeTrackingDictionary<string, string>();
        }

        /// <summary> Required. Gets or sets the SKU name. </summary>
        public Sku Sku { get; }
        /// <summary> Required. Indicates the type of storage account. </summary>
        public Kind Kind { get; }
        /// <summary> Required. Gets or sets the location of the resource. This will be one of the supported and registered Azure Geo Regions (e.g. West US, East US, Southeast Asia, etc.). The geo region of a resource cannot be changed once it is created, but if an identical geo region is specified on update, the request will succeed. </summary>
        public string Location { get; }
        /// <summary> Optional. Set the extended location of the resource. If not set, the storage account will be created in Azure main region. Otherwise it will be created in the specified extended location. </summary>
        public ExtendedLocation ExtendedLocation { get; set; }
        /// <summary> Gets or sets a list of key value pairs that describe the resource. These tags can be used for viewing and grouping this resource (across resource groups). A maximum of 15 tags can be provided for a resource. Each tag must have a key with a length no greater than 128 characters and a value with a length no greater than 256 characters. </summary>
        public IDictionary<string, string> Tags { get; }
        /// <summary> The identity of the resource. </summary>
        public Identity Identity { get; set; }
        /// <summary> SasPolicy assigned to the storage account. </summary>
        public SasPolicy SasPolicy { get; set; }
        /// <summary> KeyPolicy assigned to the storage account. </summary>
        public KeyPolicy KeyPolicy { get; set; }
        /// <summary> User domain assigned to the storage account. Name is the CNAME source. Only one custom domain is supported per storage account at this time. To clear the existing custom domain, use an empty string for the custom domain name property. </summary>
        public CustomDomain CustomDomain { get; set; }
        /// <summary> Not applicable. Azure Storage encryption is enabled for all storage accounts and cannot be disabled. </summary>
        public Encryption Encryption { get; set; }
        /// <summary> Network rule set. </summary>
        public NetworkRuleSet NetworkRuleSet { get; set; }
        /// <summary> Required for storage accounts where kind = BlobStorage. The access tier used for billing. </summary>
        public AccessTier? AccessTier { get; set; }
        /// <summary> Provides the identity based authentication settings for Azure Files. </summary>
        public AzureFilesIdentityBasedAuthentication AzureFilesIdentityBasedAuthentication { get; set; }
        /// <summary> Allows https traffic only to storage service if sets to true. The default value is true since API version 2019-04-01. </summary>
        public bool? EnableHttpsTrafficOnly { get; set; }
        /// <summary> Account HierarchicalNamespace enabled if sets to true. </summary>
        public bool? IsHnsEnabled { get; set; }
        /// <summary> Allow large file shares if sets to Enabled. It cannot be disabled once it is enabled. </summary>
        public LargeFileSharesState? LargeFileSharesState { get; set; }
        /// <summary> Maintains information about the network routing choice opted by the user for data transfer. </summary>
        public RoutingPreference RoutingPreference { get; set; }
        /// <summary> Allow or disallow public access to all blobs or containers in the storage account. The default interpretation is true for this property. </summary>
        public bool? AllowBlobPublicAccess { get; set; }
        /// <summary> Set the minimum TLS version to be permitted on requests to storage. The default interpretation is TLS 1.0 for this property. </summary>
        public MinimumTlsVersion? MinimumTlsVersion { get; set; }
        /// <summary> Indicates whether the storage account permits requests to be authorized with the account access key via Shared Key. If false, then all requests, including shared access signatures, must be authorized with Azure Active Directory (Azure AD). The default value is null, which is equivalent to true. </summary>
        public bool? AllowSharedKeyAccess { get; set; }
        /// <summary> NFS 3.0 protocol support enabled if set to true. </summary>
        public bool? EnableNfsV3 { get; set; }
        /// <summary> Allow or disallow cross AAD tenant object replication. The default interpretation is true for this property. </summary>
        public bool? AllowCrossTenantReplication { get; set; }
    }
}


text:
class NavigableHash < Hash

  def initialize(constructor = {}, &block)
    if block_given?
      yield self
    elsif constructor.is_a?(Hash)
      super()
      update(constructor)
    else
      super(constructor)
    end
  end

  alias_method :get_value, :[] unless method_defined?(:get_value)
  alias_method :set_value, :[]= unless method_defined?(:set_value)

  def ==(other_hash)
    to_hash == self.class.new(other_hash).to_hash
  end

  # Assigns a new value to the hash:
  #
  #   hash = NavigableHash.new
  #   hash[:key] = "value"
  #
  def []=(key, value)
    set_value convert_key(key), navigate(value)
  end

  alias :store :[]=

  def [](key)
    get_value convert_key(key)
  end

  # Removes a specified key from the hash.
  def delete(key)
    super(convert_key(key))
  end

  # Returns an exact copy of the hash.
  def dup
    self.class.new to_hash
  end

  # Same as <tt>Hash#fetch</tt> where the key passed as argument can be
  # either a string or a symbol:
  #
  #   counters = NavigableHash.new
  #   counters[:foo] = 1
  #
  #   counters.fetch("foo")          # => 1
  #   counters.fetch(:bar, 0)        # => 0
  #   counters.fetch(:bar) {|key| 0} # => 0
  #   counters.fetch(:zoo)           # => KeyError: key not found: "zoo"
  #
  def fetch(key, *extras)
    super(convert_key(key), *extras)
  end

  # Checks the hash for a key matching the argument passed in:
  #
  #   hash = NavigableHash.new
  #   hash["key"] = "value"
  #   hash.key? :key  # => true
  #   hash.key? "key" # => true
  #
  def key?(key)
    super(convert_key(key))
  end

  alias_method :include?, :key?
  alias_method :has_key?, :key?
  alias_method :member?, :key?

  # Merges the instantiated and the specified hashes together, giving precedence to the values from the second hash.
  # Does not overwrite the existing hash.
  def merge(hash)
    self.dup.update(hash)
  end

  def respond_to?(m, include_private = false)
    has_key?(m) || super
  end

  def to_hash
    reduce({}) do |hash, (key, value)|
      hash.merge key => convert_for_to_hash(value)
    end
  end

  # Updates the instantized hash with values from the second:
  #
  #   hash_1 = NavigableHash.new
  #   hash_1[:key] = "value"
  #
  #   hash_2 = NavigableHash.new
  #   hash_2[:key] = "New Value!"
  #
  #   hash_1.update(hash_2) # => {"key"=>"New Value!"}
  #
  def update(other_hash)
    other_hash.reduce(self) { |hash, (k, v)| hash[k] = navigate(v) ; hash }
  end

  alias_method :merge!, :update

  # Returns an array of the values at the specified indices:
  #
  #   hash = NavigableHash.new
  #   hash[:a] = "x"
  #   hash[:b] = "y"
  #   hash.values_at("a", "b") # => ["x", "y"]
  #
  def values_at(*indices)
    indices.collect {|key| self[convert_key(key)]}
  end

  protected :get_value, :set_value

  def convert_for_to_hash(value)
    case value
    when NavigableHash
      convert_navigable_hash_for_to_hash value
    when Array
      convert_array_for_to_hash value
    else
      convert_value_for_to_hash value
    end
  end

  def convert_key(key)
    key.kind_of?(Symbol) ? key.to_s : key
  end

  def convert_navigable_hash_for_to_hash(value)
    value.to_hash
  end

  def convert_array_for_to_hash(value)
    value.map { |item| convert_for_to_hash item }
  end

  def convert_value_for_to_hash(value)
    value
  end

  def navigate value
    case value
    when self.class
      value
    when Hash
      navigate_hash value
    when Array
      navigate_array value
    else
      navigate_value value
    end
  end

  def navigate_hash(value)
    self.class.new value
  end

  def navigate_array(value)
    value.map { |item| navigate item }
  end

  def navigate_value(value)
    value
  end

  def navigate_hash_from_block(key, &block)
    self[key] = self.class.new &block
  end

  private

  def set_and_cache_value(key, value)
    cache_getter! key
    self[key] = value
  end

  def get_and_cache_value(key)
    cache_getter! key
    self[key]
  end

  def cache_getter!(key)
    define_singleton_method(key) { self[key] } unless respond_to? key
  end

  def method_missing(m, *args, &block)
    m = m.to_s
    if m.chomp!('=') && args.count == 1
      set_and_cache_value(m, *args)
    elsif args.empty? && block_given?
      self.navigate_hash_from_block m, &block
    elsif args.empty?
      get_and_cache_value(m)
    else
      fail ArgumentError, "wrong number of arguments (#{args.count} for 0)"
    end
  end

end


text:
using System;
using UnityEngine;

namespace Vuforia
{
    static class VuforiaRuntimeInitialization
    {
        #region PRIVATE_METHODS

        /// <summary>
        /// Initialize platform before first scene is loaded
        /// </summary>
        [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
        private static void InitPlatform()
        {
            VuforiaUnity.SetAssetInitializationParameters();
            VuforiaRuntime.Instance.InitPlatform(CreateUnityPlayer());
        }

        /// <summary>
        /// Initialize Vuforia after first scene is loaded to make
        /// sure that the platform has already been initialized.
        /// This is only executed if delayed initialization is disabled
        /// in the Vuforia configuration.
        /// </summary>
        [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)]
        private static void InitVuforia()
        {
            if(!VuforiaConfiguration.Instance.Vuforia.DelayedInitialization)
            {
                VuforiaRuntime.Instance.InitVuforia();
            }
        }

        /// <summary>
        /// Create platform-specific unity player
        /// </summary>
        private static IUnityPlayer CreateUnityPlayer()
        {
            IUnityPlayer unityPlayer = new NullUnityPlayer();

            // instantiate the correct UnityPlayer for the current platform
            if (Application.platform == RuntimePlatform.Android)
                unityPlayer = new AndroidUnityPlayer();
            else if (Application.platform == RuntimePlatform.IPhonePlayer)
                unityPlayer = new IOSUnityPlayer();
            else if (VuforiaRuntimeUtilities.IsPlayMode())
                unityPlayer = new PlayModeUnityPlayer();
            else if (VuforiaRuntimeUtilities.IsWSARuntime())
            {
                unityPlayer = new WSAUnityPlayer();
            }

            return unityPlayer;
        }

        #endregion // PRIVATE_METHODS

    }
}


text:
define([
  'jquery',
  'underscore',
  'backbone'
], function ($, _, Backbone) {

  var KeyView = Backbone.View.extend({
    events: {
      'click': 'toggleSelect'
    },

    toggleSelect: function (event) {
      this.toggleClass(this.$el);

      var notes = $('.selected').map(function (index, note) {
        return parseInt(note.id);
      }).toArray();

      this.model.set('notes', notes);
    },

    toggleClass: function(element){
      var currentClass = element.attr('class');

      if (currentClass.indexOf('selected') === -1) {
        element.attr('class', currentClass + ' selected');
      } else {
        element.attr('class', currentClass.split(' selected')[0]);
      }
    }
  });

  return KeyView;
});


text:
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;

namespace Statman.Windows
{
    [TemplatePart(Type = typeof(Border), Name = "PART_WindowContent")]
    public class AnimatedWindow : GlassWindow
    {
        public Size OldSize
        {
            get { return (Size) GetValue(OldSizeProperty); }
            set { SetValue(OldSizeProperty, value); }
        }

        public Size NewSize
        {
            get { return (Size) GetValue(NewSizeProperty); }
            set { SetValue(NewSizeProperty, value); }
        }

        public static readonly DependencyProperty NewSizeProperty = DependencyProperty.Register("NewSize", typeof(Size), typeof(AnimatedWindow), new PropertyMetadata(new Size()));
        public static readonly DependencyProperty OldSizeProperty = DependencyProperty.Register("OldSize", typeof(Size), typeof(AnimatedWindow), new PropertyMetadata(new Size()));

        private Border m_Contents;

        private Storyboard m_SizeUpStoryboard;
        private Storyboard m_SizeDownStoryboard;

        static AnimatedWindow()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(AnimatedWindow), new FrameworkPropertyMetadata(typeof(AnimatedWindow)));
        }

        protected void OnLoaded()
        {
            m_SizeUpStoryboard = FindResource("SizeUp") as Storyboard;
            m_SizeDownStoryboard = FindResource("SizeDown") as Storyboard;

            Storyboard.SetTarget(m_SizeUpStoryboard, this);
            Storyboard.SetTarget(m_SizeDownStoryboard, this);
        }

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            m_Contents = GetChildControl<Border>("PART_WindowContent");
        }

        public void ApplyResizeAnimation()
        {
            var s_InitialPosition = new Point(Left, Top);

            Left = s_InitialPosition.X;
            Top = s_InitialPosition.Y;

            if (NewSize.Width > OldSize.Width || NewSize.Height > OldSize.Height)
            {
                (m_SizeUpStoryboard.Children[0] as DoubleAnimation).To = NewSize.Height;
                (m_SizeUpStoryboard.Children[1] as DoubleAnimation).To = NewSize.Width;

                m_SizeUpStoryboard.Begin();
            }
            else
            {
                (m_SizeDownStoryboard.Children[0] as DoubleAnimation).To = NewSize.Height;
                (m_SizeDownStoryboard.Children[1] as DoubleAnimation).To = NewSize.Width;

                m_SizeDownStoryboard.Begin();
            }
        }
    }
}


text:
class Hq::UsersController < Hq::ApplicationController
  include Activatable

  before_action :set_user, only: %i[show edit update destroy toggle_is_active]
  add_breadcrumb I18n.t('activerecord.models.users'), :hq_users_path

  def index
    @search = User.order(id: :desc).search(params[:q])
    @users = @search.result(distinct: true).paginate(page: params[:page])
    respond_with(@users)
  end

  def show
    add_breadcrumb @user.name, hq_user_path(@user)
    respond_with(@user)
  end

  def new
    add_breadcrumb t('view.tooltips.new'), new_hq_user_path
    @user = User.new
    respond_with(@user)
  end

  def edit
    add_breadcrumb @user.name, hq_user_path(@user)
    add_breadcrumb t('view.tooltips.edit'), edit_hq_user_path
  end

  def create
    @user = User.new(user_params)
    @user.save
    respond_with(:hq, @user)
  end

  def update
    @user.update(user_params)
    respond_with(:hq, @user)
  end

  def destroy
    @user.destroy
    respond_with(:hq, @user, location: request.referer)
  end

  def toggle_is_active
    activation_toggle(@user)
    respond_with(:hq, @user, location: request.referer)
  end

  private

  def set_user
    @user = User.find(params[:id])
  end

  def user_params
    params.require(:user).permit(:email, :name, :surname, :time_zone)
  end
end


text:
package org.springframework.boot.autoconfigure.data.r2dbc;

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

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate;
import org.springframework.boot.autoconfigure.r2dbc.R2dbcAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.convert.CustomConversions;
import org.springframework.data.r2dbc.convert.MappingR2dbcConverter;
import org.springframework.data.r2dbc.convert.R2dbcConverter;
import org.springframework.data.r2dbc.convert.R2dbcCustomConversions;
import org.springframework.data.r2dbc.core.R2dbcEntityTemplate;
import org.springframework.data.r2dbc.dialect.DialectResolver;
import org.springframework.data.r2dbc.dialect.R2dbcDialect;
import org.springframework.data.r2dbc.mapping.R2dbcMappingContext;
import org.springframework.data.relational.core.mapping.NamingStrategy;
import org.springframework.r2dbc.core.DatabaseClient;

/**
 * {@link EnableAutoConfiguration Auto-configuration} for {@link DatabaseClient}.
 *
 * @author Mark Paluch
 * @author Oliver Drotbohm
 * @since 2.3.0
 */
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ DatabaseClient.class, R2dbcEntityTemplate.class })
@ConditionalOnSingleCandidate(DatabaseClient.class)
@AutoConfigureAfter(R2dbcAutoConfiguration.class)
public class R2dbcDataAutoConfiguration {

	private final DatabaseClient databaseClient;

	private final R2dbcDialect dialect;

	public R2dbcDataAutoConfiguration(DatabaseClient databaseClient) {
		this.databaseClient = databaseClient;
		this.dialect = DialectResolver.getDialect(this.databaseClient.getConnectionFactory());
	}

	@Bean
	@ConditionalOnMissingBean
	public R2dbcEntityTemplate r2dbcEntityTemplate(R2dbcConverter r2dbcConverter) {
		return new R2dbcEntityTemplate(this.databaseClient, this.dialect, r2dbcConverter);
	}

	@Bean
	@ConditionalOnMissingBean
	public R2dbcMappingContext r2dbcMappingContext(ObjectProvider<NamingStrategy> namingStrategy,
			R2dbcCustomConversions r2dbcCustomConversions) {
		R2dbcMappingContext relationalMappingContext = new R2dbcMappingContext(
				namingStrategy.getIfAvailable(() -> NamingStrategy.INSTANCE));
		relationalMappingContext.setSimpleTypeHolder(r2dbcCustomConversions.getSimpleTypeHolder());
		return relationalMappingContext;
	}

	@Bean
	@ConditionalOnMissingBean
	public MappingR2dbcConverter r2dbcConverter(R2dbcMappingContext mappingContext,
			R2dbcCustomConversions r2dbcCustomConversions) {
		return new MappingR2dbcConverter(mappingContext, r2dbcCustomConversions);
	}

	@Bean
	@ConditionalOnMissingBean
	public R2dbcCustomConversions r2dbcCustomConversions() {
		List<Object> converters = new ArrayList<>(this.dialect.getConverters());
		converters.addAll(R2dbcCustomConversions.STORE_CONVERTERS);
		return new R2dbcCustomConversions(
				CustomConversions.StoreConversions.of(this.dialect.getSimpleTypeHolder(), converters),
				Collections.emptyList());
	}

}


text:
package lc.convertsortedlisttobinarysearchtree;

import java.util.List;
import java.util.Stack;

import lc.binarytreerightsightview.TreeNode;

public class Solution {
	// grab a paper and pen to hand-run it otherwise you never know what is going on.
    public TreeNode sortedListToBST(ListNode head) {
		// corner case
		if(head == null) return null;

		// first get the length of the list
		int size = 0;
		ListNode p = head;
		while(p != null) {
			p = p.next;
			size ++;
		}

		// handle the case where only one  node in the tree
		if(size == 1) return new TreeNode(head.val);
		else		  return helper(head, size / 2, size);
    }

	private TreeNode helper(ListNode head, int step, int size) {
		// handle the cases where there is only one node in the tree or
		// current node is a null node
		if(head == null) return null;
		else if(head.next == null) return new TreeNode(head.val);

		// compute the size of left subtree and right subtree to decide how to
		// halve the sub linkedlist sections
		// NOTE: -1 means taking the current node(mid) into consideration
		// this avoids the pitfall of incorrectly allocating pointers
		int leftSize = step; int rightSize = size - step - 1;
		// break the list section into three part: head...prev, mid, mid.next...null
		// which represent the left subtree, root and right subtree
		// note that currently we have at least two nodes in the list section
		ListNode prev = null;
		ListNode mid = head;
		for(int i = 0; i < step; i ++) {
			prev = mid;
			mid = mid.next;
		}
		// now we get prev and mid, then break the list
		if(prev != null) prev.next = null;
		TreeNode curr = new TreeNode(mid.val);
		curr.left = helper(head, leftSize / 2, leftSize);
		curr.right = helper(mid.next, rightSize / 2, rightSize);

		return curr;
	}

	public static void main(String [] args) {

		int [] nums = {-90,-84,-76,-72,-40,-34,-9,8,19,33,50,51,56,68,79,81};
		ListNode head = ListNode.genList(nums);

		Solution sol = new Solution();

		TreeNode root = sol.sortedListToBST(head);

		lc.binarytreelevelordertraversal.Solution testSol = new lc.binarytreelevelordertraversal.Solution();

		List<List<Integer>>re = testSol.levelOrder(root);

		for(List<Integer> l : re) {
			for(Integer i : l) System.out.print(i + " ");
			System.out.println();
		}
	}
}


text:
<?php

namespace Forms\Fields;

abstract class Field
{
    protected $name;

    protected $attributes;

    protected $value;

    protected $showLabel = true;

    public function __construct($name, $value = null, array $attributes = [])
    {
        $this->name = $name;
        $this->attributes = $attributes;
        $this->value = $value;
    }

    /**
     * Gets the value of value.
     *
     * @return mixed
     */
    public function getValue()
    {
        return $this->value;
    }

    /**
     * Sets the value of value.
     *
     * @param mixed $value the value
     *
     * @return self
     */
    public function setValue($value)
    {
        $this->value = $value;

        return $this;
    }

    /**
     * Gets the value of attributes.
     *
     * @return mixed
     */
    public function getAttributes()
    {
        return $this->attributes;
    }

    /**
     * Sets the value of attributes.
     *
     * @param mixed $attributes the attributes
     *
     * @return self
     */
    public function setAttributes($attributes)
    {
        $this->attributes = $attributes;

        return $this;
    }

    /**
     * Gets the value of name.
     *
     * @return mixed
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Sets the value of name.
     *
     * @param mixed $name the name
     *
     * @return self
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    protected function attributesAsString()
    {
        $str = '';

        foreach ($this->attributes as $name => $attr)
        {
            $str .= "{$name}=\"{$attr}\"";
        }

        return $str;
    }

    abstract public function render();

    /**
     * Gets the value of showLabel.
     *
     * @return mixed
     */
    public function getShowLabel()
    {
        return $this->showLabel;
    }

    /**
     * Sets the value of showLabel.
     *
     * @param mixed $showLabel the show label
     *
     * @return self
     */
    public function setShowLabel($showLabel)
    {
        $this->showLabel = $showLabel;

        return $this;
    }
}


text:
@interface Location:NSObject<NSCoding>

@property int location_id;
@property (nonatomic, strong) NSString * location_name;
@property (nonatomic, strong) NSString * center_name;
@property float latitude;
@property float longtitude;
-(void) setValueLocationID:(int)locationid withLocationName:(NSString *)locationname;
-(void) setLocationObject:(Location *)source;
@end


text:
using WebKit::WebArrayBuffer;
using WebKit::WebDocument;
using WebKit::WebString;
using WebKit::WebSocket;
using WebKit::WebURL;

namespace content {

PepperWebSocketHost::PepperWebSocketHost(
    RendererPpapiHost* host,
    PP_Instance instance,
    PP_Resource resource)
    : ResourceHost(host->GetPpapiHost(), instance, resource),
      renderer_ppapi_host_(host),
      connecting_(false),
      initiating_close_(false),
      accepting_close_(false),
      error_was_received_(false) {
}

PepperWebSocketHost::~PepperWebSocketHost() {
  if (websocket_)
    websocket_->disconnect();
}

int32_t PepperWebSocketHost::OnResourceMessageReceived(
    const IPC::Message& msg,
    ppapi::host::HostMessageContext* context) {
  IPC_BEGIN_MESSAGE_MAP(PepperWebSocketHost, msg)
    PPAPI_DISPATCH_HOST_RESOURCE_CALL(PpapiHostMsg_WebSocket_Connect,
                                      OnHostMsgConnect)
    PPAPI_DISPATCH_HOST_RESOURCE_CALL(PpapiHostMsg_WebSocket_Close,
                                      OnHostMsgClose)
    PPAPI_DISPATCH_HOST_RESOURCE_CALL(PpapiHostMsg_WebSocket_SendText,
                                      OnHostMsgSendText)
    PPAPI_DISPATCH_HOST_RESOURCE_CALL(PpapiHostMsg_WebSocket_SendBinary,
                                      OnHostMsgSendBinary)
    PPAPI_DISPATCH_HOST_RESOURCE_CALL(PpapiHostMsg_WebSocket_Fail,
                                      OnHostMsgFail)
  IPC_END_MESSAGE_MAP()
  return PP_ERROR_FAILED;
}

void PepperWebSocketHost::didConnect() {
  std::string protocol;
  if (websocket_)
    protocol = websocket_->subprotocol().utf8();
  connecting_ = false;
  connect_reply_.params.set_result(PP_OK);
  host()->SendReply(connect_reply_,
                    PpapiPluginMsg_WebSocket_ConnectReply(
                        url_,
                        protocol));
}

void PepperWebSocketHost::didReceiveMessage(const WebKit::WebString& message) {
  // Dispose packets after receiving an error.
  if (error_was_received_)
    return;

  // Send an IPC to transport received data.
  std::string string_message = message.utf8();
  host()->SendUnsolicitedReply(pp_resource(),
                               PpapiPluginMsg_WebSocket_ReceiveTextReply(
                                  string_message));
}

void PepperWebSocketHost::didReceiveArrayBuffer(
    const WebKit::WebArrayBuffer& binaryData) {
  // Dispose packets after receiving an error.
  if (error_was_received_)
    return;

  // Send an IPC to transport received data.
  uint8_t* data = static_cast<uint8_t*>(binaryData.data());
  std::vector<uint8_t> array_message(data, data + binaryData.byteLength());
  host()->SendUnsolicitedReply(pp_resource(),
                               PpapiPluginMsg_WebSocket_ReceiveBinaryReply(
                                  array_message));
}

void PepperWebSocketHost::didReceiveMessageError() {
  // Records the error, then stops receiving any frames after this error.
  // The error must be notified after all queued messages are read.
  error_was_received_ = true;

  // Send an IPC to report the error. After this IPC, ReceiveTextReply and
  // ReceiveBinaryReply IPC are not sent anymore because |error_was_received_|
  // blocks.
  host()->SendUnsolicitedReply(pp_resource(),
                               PpapiPluginMsg_WebSocket_ErrorReply());
}

void PepperWebSocketHost::didUpdateBufferedAmount(
    unsigned long buffered_amount) {
  // Send an IPC to update buffered amount.
  host()->SendUnsolicitedReply(pp_resource(),
                               PpapiPluginMsg_WebSocket_BufferedAmountReply(
                                  buffered_amount));
}

void PepperWebSocketHost::didStartClosingHandshake() {
  accepting_close_ = true;

  // Send an IPC to notice that server starts closing handshake.
  host()->SendUnsolicitedReply(pp_resource(),
                               PpapiPluginMsg_WebSocket_StateReply(
                                  PP_WEBSOCKETREADYSTATE_CLOSING));
}

void PepperWebSocketHost::didClose(unsigned long unhandled_buffered_amount,
                                   ClosingHandshakeCompletionStatus status,
                                   unsigned short code,
                                   const WebKit::WebString& reason) {
  if (connecting_) {
    connecting_ = false;
    connect_reply_.params.set_result(PP_ERROR_FAILED);
    host()->SendReply(
        connect_reply_,
        PpapiPluginMsg_WebSocket_ConnectReply(url_, std::string()));
  }

  // Set close_was_clean_.
  bool was_clean =
      (initiating_close_ || accepting_close_) &&
      !unhandled_buffered_amount &&
      status == WebSocketClient::ClosingHandshakeComplete;

  if (initiating_close_) {
    initiating_close_ = false;
    close_reply_.params.set_result(PP_OK);
    host()->SendReply(close_reply_, PpapiPluginMsg_WebSocket_CloseReply(
          unhandled_buffered_amount,
          was_clean,
          code,
          reason.utf8()));
  } else {
    accepting_close_ = false;
    host()->SendUnsolicitedReply(pp_resource(),
                                 PpapiPluginMsg_WebSocket_ClosedReply(
                                     unhandled_buffered_amount,
                                     was_clean,
                                     code,
                                     reason.utf8()));
  }

  // Disconnect.
  if (websocket_)
    websocket_->disconnect();
}

int32_t PepperWebSocketHost::OnHostMsgConnect(
    ppapi::host::HostMessageContext* context,
    const std::string& url,
    const std::vector<std::string>& protocols) {
  // Validate url and convert it to WebURL.
  GURL gurl(url);
  url_ = gurl.spec();
  if (!gurl.is_valid())
    return PP_ERROR_BADARGUMENT;
  if (!gurl.SchemeIs("ws") && !gurl.SchemeIs("wss"))
    return PP_ERROR_BADARGUMENT;
  if (gurl.has_ref())
    return PP_ERROR_BADARGUMENT;
  if (!net::IsPortAllowedByDefault(gurl.IntPort()))
    return PP_ERROR_BADARGUMENT;
  WebURL web_url(gurl);

  // Validate protocols.
  std::string protocol_string;
  for (std::vector<std::string>::const_iterator vector_it = protocols.begin();
       vector_it != protocols.end();
       ++vector_it) {

    // Check containing characters.
    for (std::string::const_iterator string_it = vector_it->begin();
        string_it != vector_it->end();
        ++string_it) {
      uint8_t character = *string_it;
      // WebSocket specification says "(Subprotocol string must consist of)
      // characters in the range U+0021 to U+007E not including separator
      // characters as defined in [RFC2616]."
      const uint8_t minimumProtocolCharacter = '!';  // U+0021.
      const uint8_t maximumProtocolCharacter = '~';  // U+007E.
      if (character < minimumProtocolCharacter ||
          character > maximumProtocolCharacter ||
          character == '"' || character == '(' || character == ')' ||
          character == ',' || character == '/' ||
          (character >= ':' && character <= '@') ||  // U+003A - U+0040
          (character >= '[' && character <= ']') ||  // U+005B - u+005D
          character == '{' || character == '}')
        return PP_ERROR_BADARGUMENT;
    }
    // Join protocols with the comma separator.
    if (vector_it != protocols.begin())
      protocol_string.append(",");
    protocol_string.append(*vector_it);
  }

  // Convert protocols to WebString.
  WebString web_protocols = WebString::fromUTF8(protocol_string);

  // Create WebKit::WebSocket object and connect.
  WebKit::WebPluginContainer* container =
      renderer_ppapi_host_->GetContainerForInstance(pp_instance());
  if (!container)
    return PP_ERROR_BADARGUMENT;
  // TODO(toyoshim) Remove following WebDocument object copy.
  WebDocument document = container->element().document();
  websocket_.reset(WebSocket::create(document, this));
  DCHECK(websocket_.get());
  if (!websocket_)
    return PP_ERROR_NOTSUPPORTED;

  // Set receiving binary object type.
  websocket_->setBinaryType(WebSocket::BinaryTypeArrayBuffer);
  websocket_->connect(web_url, web_protocols);

  connect_reply_ = context->MakeReplyMessageContext();
  connecting_ = true;
  return PP_OK_COMPLETIONPENDING;
}

int32_t PepperWebSocketHost::OnHostMsgClose(
    ppapi::host::HostMessageContext* context,
    int32_t code,
    const std::string& reason) {
  if (!websocket_)
    return PP_ERROR_FAILED;
  close_reply_ = context->MakeReplyMessageContext();
  initiating_close_ = true;
  WebString web_reason = WebString::fromUTF8(reason);
  websocket_->close(code, web_reason);
  return PP_OK_COMPLETIONPENDING;
}

int32_t PepperWebSocketHost::OnHostMsgSendText(
    ppapi::host::HostMessageContext* context,
    const std::string& message) {
  if (websocket_) {
    WebString web_message = WebString::fromUTF8(message);
    websocket_->sendText(web_message);
  }
  return PP_OK;
}

int32_t PepperWebSocketHost::OnHostMsgSendBinary(
    ppapi::host::HostMessageContext* context,
    const std::vector<uint8_t>& message) {
  if (websocket_.get() && !message.empty()) {
    WebArrayBuffer web_message = WebArrayBuffer::create(message.size(), 1);
    memcpy(web_message.data(), &message.front(), message.size());
    websocket_->sendArrayBuffer(web_message);
  }
  return PP_OK;
}

int32_t PepperWebSocketHost::OnHostMsgFail(
    ppapi::host::HostMessageContext* context,
    const std::string& message) {
  if (websocket_)
    websocket_->fail(WebString::fromUTF8(message));
  return PP_OK;
}

}  // namespace content


text:
<?php

namespace Guzzle\Tests\Service;

use Guzzle\Common\Cache\DoctrineCacheAdapter;
use Guzzle\Service\AbstractFactory;
use Guzzle\Service\Builder\JsonServiceBuilderFactory;
use Guzzle\Service\Exception\ServiceBuilderException;
use Guzzle\Service\Builder\ArrayServiceBuilderFactory;
use Doctrine\Common\Cache\ArrayCache;

/**
 * @covers Guzzle\Service\AbstractFactory
 */
class AbstractFactoryTest extends \Guzzle\Tests\GuzzleTestCase
{
    protected function getFactory()
    {
        return $this->getMockBuilder('Guzzle\Service\AbstractFactory')
            ->setMethods(array('getCacheTtlKey', 'throwException', 'getFactory'))
            ->getMockForAbstractClass();
    }

    public function testCachesArtifacts()
    {
        $jsonFile = __DIR__ . '/../TestData/test_service.json';

        $adapter = new DoctrineCacheAdapter(new ArrayCache());
        $factory = $this->getFactory();

        $factory->expects($this->once())
            ->method('getFactory')
            ->will($this->returnValue(new JsonServiceBuilderFactory(new ArrayServiceBuilderFactory())));

        // Create a service and add it to the cache
        $service = $factory->build($jsonFile, array(
            'cache.adapter' => $adapter
        ));

        // Ensure the cache key was set
        $this->assertTrue($adapter->contains('guzzle' . crc32($jsonFile)));

        // Grab the service from the cache
        $this->assertEquals($service, $factory->build($jsonFile, array(
            'cache.adapter' => $adapter
        )));
    }

    /**
     * @expectedException Guzzle\Service\Exception\ServiceBuilderException
     */
    public function testThrowsExceptionsWhenNoFactoryResolves()
    {
        $factory = $this->getFactory();
        $factory->expects($this->any())
            ->method('getFactory')
            ->will($this->returnValue(false));
        $factory->expects($this->any())
            ->method('throwException')
            ->will($this->throwException(new ServiceBuilderException()));

        $service = $factory->build('foo');
    }
}


text:
from alphatwirl.selection.factories.AnyFactory import AnyFactory
from alphatwirl.selection.modules.basic import All
from alphatwirl.selection.modules.basic import Any
from alphatwirl.selection.modules.LambdaStr import LambdaStr
import unittest

##__________________________________________________________________||
class Test_AnyFactory(unittest.TestCase):

    def test_obj(self):
        path_cfg_list = ("ev : ev.nJet[0] >= 2", "ev : ev.nMET[0] >= 200")
        kargs = dict(arg1 = 10, arg2 = 20, AnyClass = Any, LambdaStrClass = LambdaStr)
        obj = AnyFactory(path_cfg_list, name = 'test_any', **kargs)

##__________________________________________________________________||


text:
var rpc = require('./../lib/binrpc.js');

require('should');

describe('client server connection', function () {
    var rpcServer;
    var rpcClient;
    it('should raise an error if no connection can be established', function (done) {
        this.timeout(60000);
        var rpcClientNC = rpc.createClient({host: 'localhost', port: '2032'});
        rpcClientNC.methodCall('testNC', [1, 1.1, 'string', true, [1, 2, 3], {a: 'a', b: 'b'}], function (err, res) {
            if (err) {
                done()
            } else {
                done(new Error('no Error was thrown'));
            }
        });
    });
    it('should open a server without throwing an error', function () {
        rpcServer = rpc.createServer({host: '127.0.0.1', port: '2037'});
    });
    it('should create a client without error', function () {
        rpcClient = rpc.createClient({host: '127.0.0.1', port: '2037'});
    });
    it('should do nothing when shifting an empty queue', function () {
        rpcClient.queueShift();
    });
    it('should send a call to the server and receive empty string', function (done) {
        this.timeout(30000);
        rpcServer.on('test1', function (err, params, callback) {
            callback(null, '');
        });
        rpcClient.methodCall('test1', [''], function (err, res) {
            if (err) {
                done(err);
            } else if (res !== '') {
                done(new Error('received wrong response ' + res));
            } else {
                done();
            }
        });
    });
    it('should send a call with some params to the server and receive some params', function (done) {
        this.timeout(30000);
        rpcServer.on('test2', function (err, params, callback) {
            params.should.deepEqual([1, 1.1, 'string', true, [1, 2, 3], {a: 'a', b: 'b'}]);
            callback(null, [2, 2.2, 'string2', true, [3, 4, 5], {c: 'c', d: 'd'}]);
        });
        rpcClient.methodCall('test2', [1, 1.1, 'string', true, [1, 2, 3], {a: 'a', b: 'b'}], function (err, res) {
            if (err ) {
                done(err);
            } else {
                res.should.deepEqual([2, 2.2, 'string2', true, [3, 4, 5], {c: 'c', d: 'd'}]);
                done();
            }
        });
    });
    it('should send a unknown call with some params to the server and trigger a NotFound event', function (done) {
        this.timeout(30000);
        rpcServer.on('NotFound', function (method, params) {
            method.should.equal('test3');
            params.should.deepEqual([1, 1.1, 'string', true, [1, 2, 3], {a: 'a', b: 'b'}]);
            done();
        });
        rpcClient.methodCall('test3', [1, 1.1, 'string', true, [1, 2, 3], {a: 'a', b: 'b'}], function (err, res) {
            if (err) {
                done(err);
            }
        });
    });

    it('should fill up the queue', function (done) {
        this.timeout(60000);
        rpcServer.on('slow', function (err, params, callback) {
            setTimeout(function () {
                callback(null, '');
            }, 2000);
        });
        for (var i = 0; i < 110; i++) {
            rpcClient.methodCall('slow', [''], function (err, res) {});
        }
        rpcClient.methodCall('slow', [''], function (err, res) {
            err.toString().should.equal('Error: You are sending too fast');
            done(!err);
        });
    });

    it('should create a client twice without error', function () {
        var rpcClientTwice = rpc.createClient({host: 'localhost', port: '2033'});
        rpcClientTwice = rpc.createClient({host: 'localhost', port: '2033'});
    });

});


text:
require 'spec_helper'

describe WardenOauthProvider::TokenStrategy do

  before(:all) do
    @client_application = Factory.create(:client_application)
    @user = Factory(:user)
  end

  it "should allow to authenticate a token multiple times in a session" do

    class TestSession
      cattr_accessor :session
      def initialize(app)
        @app = app
      end

      def call(env)
        env['rack.session'] = TestSession.session
        @app.call(env)
      end
    end
    TestSession.session = {}

    session = TestSession

    # Step 1 - Request token
    auth_str_step1 = oauth_header({
      :realm                  => "MoneyBird",
      :oauth_consumer_key     => @client_application.key,
      :oauth_signature_method => "PLAINTEXT",
      :oauth_timestamp        => Time.now.to_i+1,
      :oauth_nonce            => Time.now.to_f+1,
      :oauth_callback         => "oob",
      :oauth_signature        => @client_application.secret + "%26"
    })
    env_step1 = env_with_params("/oauth/request_token", {}, {
      "HTTP_AUTHORIZATION" => auth_str_step1
    })
    response = setup_rack.call(env_step1)
    response.first.should == 200
    oauth_response = Hash[*response.last.first.split("&").collect { |v| v.split("=") }.flatten]
    oauth_request_token = oauth_response["oauth_token"]
    oauth_request_token_secret = oauth_response["oauth_token_secret"]

    # Step 2 - Authorize
    req = WardenOauthProvider::Token::Request.find_by_token(oauth_request_token)
    env_step2 = env_with_params("/oauth/authorize", {:oauth_token => oauth_request_token, :username => "John", :password => "testtest"}, {})
    response = setup_rack(nil, :session => session).call(env_step2)
    response.first.should == 302
    location = URI.parse(response[1]["Location"])
    oauth_response = Hash[*location.query.split("&").collect { |v| v.split("=") }.flatten]
    oauth_verifier = oauth_response["oauth_verifier"]

    # Step 3 - Access token
    auth_str_step3 = oauth_header({
      :realm => "MoneyBird",
      :oauth_consumer_key => @client_application.key,
      :oauth_token => oauth_request_token,
      :oauth_signature_method => "PLAINTEXT",
      :oauth_timestamp => Time.now.to_i+2,
      :oauth_nonce => Time.now.to_f+2,
      :oauth_verifier => oauth_verifier,
      :oauth_signature => @client_application.secret + "%26" + oauth_request_token_secret
    })
    env_step3 = env_with_params("/oauth/access_token", {}, {
      "HTTP_AUTHORIZATION" => auth_str_step3
    })
    response = setup_rack.call(env_step3)
    response.first.should == 200
    oauth_response = Hash[*response.last.first.split("&").collect { |v| v.split("=") }.flatten]
    oauth_access_token = oauth_response["oauth_token"]
    oauth_access_token_secret = oauth_response["oauth_token_secret"]

    # Step 4 - App request with access token
    auth_str_step4 = oauth_header({
      :realm => "MoneyBird",
      :oauth_consumer_key => @client_application.key,
      :oauth_token => oauth_access_token,
      :oauth_signature_method => "PLAINTEXT",
      :oauth_timestamp => Time.now.to_i+3,
      :oauth_nonce => Time.now.to_f+3,
      :oauth_signature => @client_application.secret + "%26" + oauth_access_token_secret
    })
    env_step4 = env_with_params("/invoices", {}, {
      "HTTP_AUTHORIZATION" => auth_str_step4
    })
    response = setup_rack.call(env_step4)
    response.first.should == 200

    # Step 1 - Request token
    auth_str_step1 = oauth_header({
      :realm                  => "MoneyBird",
      :oauth_consumer_key     => @client_application.key,
      :oauth_signature_method => "PLAINTEXT",
      :oauth_timestamp        => Time.now.to_i+1,
      :oauth_nonce            => Time.now.to_f+1,
      :oauth_callback         => "oob",
      :oauth_signature        => @client_application.secret + "%26"
    })
    env_step1 = env_with_params("/oauth/request_token", {}, {
      "HTTP_AUTHORIZATION" => auth_str_step1
    })
    response = setup_rack.call(env_step1)
    response.first.should == 200
    oauth_response = Hash[*response.last.first.split("&").collect { |v| v.split("=") }.flatten]
    oauth_request_token = oauth_response["oauth_token"]
    oauth_request_token_secret = oauth_response["oauth_token_secret"]

    # Step 2 - Authorize
    req = WardenOauthProvider::Token::Request.find_by_token(oauth_request_token)
    env_step2 = env_with_params("/oauth/authorize", {:oauth_token => oauth_request_token, :username => "John", :password => "testtest"}, {})
    response = setup_rack(nil, :session => session).call(env_step2)
    response.first.should == 302
    location = URI.parse(response[1]["Location"])
    oauth_response = Hash[*location.query.split("&").collect { |v| v.split("=") }.flatten]
    oauth_verifier = oauth_response["oauth_verifier"]

    # Step 3 - Access token
    auth_str_step3 = oauth_header({
      :realm => "MoneyBird",
      :oauth_consumer_key => @client_application.key,
      :oauth_token => oauth_request_token,
      :oauth_signature_method => "PLAINTEXT",
      :oauth_timestamp => Time.now.to_i+2,
      :oauth_nonce => Time.now.to_f+2,
      :oauth_verifier => oauth_verifier,
      :oauth_signature => @client_application.secret + "%26" + oauth_request_token_secret
    })
    env_step3 = env_with_params("/oauth/access_token", {}, {
      "HTTP_AUTHORIZATION" => auth_str_step3
    })
    response = setup_rack.call(env_step3)
    response.first.should == 200
    oauth_response = Hash[*response.last.first.split("&").collect { |v| v.split("=") }.flatten]
    oauth_access_token = oauth_response["oauth_token"]
    oauth_access_token_secret = oauth_response["oauth_token_secret"]

    # Step 4 - App request with access token
    auth_str_step4 = oauth_header({
      :realm => "MoneyBird",
      :oauth_consumer_key => @client_application.key,
      :oauth_token => oauth_access_token,
      :oauth_signature_method => "PLAINTEXT",
      :oauth_timestamp => Time.now.to_i+3,
      :oauth_nonce => Time.now.to_f+3,
      :oauth_signature => @client_application.secret + "%26" + oauth_access_token_secret
    })
    env_step4 = env_with_params("/invoices", {}, {
      "HTTP_AUTHORIZATION" => auth_str_step4
    })
    response = setup_rack.call(env_step4)
    response.first.should == 200

  end

end


text:
layout: doc_page
---

# Druid Firehoses

Firehoses are used in the [stream-pull](../ingestion/stream-pull.html) ingestion model. They are pluggable and thus the configuration schema can and will vary based on the `type` of the firehose.

| Field | Type | Description | Required |
|-------|------|-------------|----------|
| type | String | Specifies the type of firehose. Each value will have its own configuration schema, firehoses packaged with Druid are described below. | yes |

## Additional Firehoses

There are several firehoses readily available in Druid, some are meant for examples, others can be used directly in a production environment.

For additional firehoses, please see our [extensions list](../development/extensions.html).

#### LocalFirehose

This Firehose can be used to read the data from files on local disk.
It can be used for POCs to ingest data on disk.
A sample local firehose spec is shown below:

```json
{
    "type"    : "local",
    "filter"   : "*.csv",
    "baseDir"  : "/data/directory"
}
```

|property|description|required?|
|--------|-----------|---------|
|type|This should be "local".|yes|
|filter|A wildcard filter for files. See [here](http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/filefilter/WildcardFileFilter.html) for more information.|yes|
|baseDir|directory to search recursively for files to be ingested. |yes|

#### IngestSegmentFirehose

This Firehose can be used to read the data from existing druid segments.
It can be used ingest existing druid segments using a new schema and change the name, dimensions, metrics, rollup, etc. of the segment.
A sample ingest firehose spec is shown below -

```json
{
    "type"    : "ingestSegment",
    "dataSource"   : "wikipedia",
    "interval" : "2013-01-01/2013-01-02"
}
```

|property|description|required?|
|--------|-----------|---------|
|type|This should be "ingestSegment".|yes|
|dataSource|A String defining the data source to fetch rows from, very similar to a table in a relational database|yes|
|interval|A String representing ISO-8601 Interval. This defines the time range to fetch the data over.|yes|
|dimensions|The list of dimensions to select. If left empty, no dimensions are returned. If left null or not defined, all dimensions are returned. |no|
|metrics|The list of metrics to select. If left empty, no metrics are returned. If left null or not defined, all metrics are selected.|no|
|filter| See [Filters](../querying/filters.html)|yes|

#### CombiningFirehose

This firehose can be used to combine and merge data from a list of different firehoses.
This can be used to merge data from more than one firehose.

```json
{
    "type"  :   "combining",
    "delegates" : [ { firehose1 }, { firehose2 }, ..... ]
}
```

|property|description|required?|
|--------|-----------|---------|
|type|This should be "combining"|yes|
|delegates|list of firehoses to combine data from|yes|

#### EventReceiverFirehose

EventReceiverFirehoseFactory can be used to ingest events using an http endpoint.

```json
{
  "type": "receiver",
  "serviceName": "eventReceiverServiceName",
  "bufferSize": 10000
}
```
When using this firehose, events can be sent by submitting a POST request to the http endpoint:

`http://<peonHost>:<port>/druid/worker/v1/chat/<eventReceiverServiceName>/push-events/`

|property|description|required?|
|--------|-----------|---------|
|type|This should be "receiver"|yes|
|serviceName|name used to announce the event receiver service endpoint|yes|
|bufferSize| size of buffer used by firehose to store events|no default(100000)|

Shut down time for EventReceiverFirehose can be specified by submitting a POST request to

`http://<peonHost>:<port>/druid/worker/v1/chat/<eventReceiverServiceName>/shutdown?shutoffTime=<shutoffTime>`

If shutOffTime is not specified, the firehose shuts off immediately.

#### TimedShutoffFirehose

This can be used to start a firehose that will shut down at a specified time.
An example is shown below:

```json
{
    "type"  :   "timed",
    "shutoffTime": "2015-08-25T01:26:05.119Z",
    "delegate": {
          "type": "receiver",
          "serviceName": "eventReceiverServiceName",
          "bufferSize": 100000
     }
}
```

|property|description|required?|
|--------|-----------|---------|
|type|This should be "timed"|yes|
|shutoffTime|time at which the firehose should shut down, in ISO8601 format|yes|
|delegate|firehose to use|yes|


text:
package io.github.droidkaigi.confsched.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.like.LikeButton;
import com.like.OnLikeListener;

import org.parceler.Parcels;

import java.util.Collections;
import java.util.List;

import javax.inject.Inject;

import io.github.droidkaigi.confsched.R;
import io.github.droidkaigi.confsched.activity.ActivityNavigator;
import io.github.droidkaigi.confsched.dao.SessionDao;
import io.github.droidkaigi.confsched.databinding.FragmentSessionsTabBinding;
import io.github.droidkaigi.confsched.databinding.ItemSessionBinding;
import io.github.droidkaigi.confsched.model.Session;
import io.github.droidkaigi.confsched.util.AlarmUtil;
import io.github.droidkaigi.confsched.widget.ArrayRecyclerAdapter;
import io.github.droidkaigi.confsched.widget.BindingHolder;
import io.github.droidkaigi.confsched.widget.itemdecoration.SpaceItemDecoration;

public class SessionsTabFragment extends BaseFragment {

    protected static final String ARG_SESSIONS = "sessions";
    private static final int REQ_DETAIL = 1;

    @Inject
    SessionDao dao;
    @Inject
    ActivityNavigator activityNavigator;

    private SessionsAdapter adapter;
    private FragmentSessionsTabBinding binding;

    private List<Session> sessions;

    private SessionsFragment.OnChangeSessionListener onChangeSessionListener = sessions -> {/* no op */};

    @NonNull
    public static SessionsTabFragment newInstance(List<Session> sessions) {
        SessionsTabFragment fragment = new SessionsTabFragment();
        Bundle args = new Bundle();
        args.putParcelable(ARG_SESSIONS, Parcels.wrap(sessions));
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sessions = Parcels.unwrap(getArguments().getParcelable(ARG_SESSIONS));
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        getComponent().inject(this);
        if (context instanceof SessionsFragment.OnChangeSessionListener) {
            onChangeSessionListener = (SessionsFragment.OnChangeSessionListener) context;
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentSessionsTabBinding.inflate(inflater, container, false);
        bindData();
        return binding.getRoot();
    }

    private void bindData() {
        adapter = createAdapter();

        binding.recyclerView.setAdapter(adapter);
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        int spacing = getResources().getDimensionPixelSize(R.dimen.spacing_xsmall);
        binding.recyclerView.addItemDecoration(new SpaceItemDecoration(spacing));
        adapter.addAll(sessions);
    }

    protected SessionsAdapter createAdapter() {
        return new SessionsAdapter(getContext());
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQ_DETAIL:
                if (resultCode == Activity.RESULT_OK) {
                    Session session = Parcels.unwrap(data.getParcelableExtra(Session.class.getSimpleName()));
                    if (session != null) {
                        adapter.refresh(session);
                        onChangeSessionListener.onChangeSession(Collections.singletonList(session));
                    }
                }
                break;
        }
    }

    public void scrollUpToTop() {
        binding.recyclerView.smoothScrollToPosition(0);
    }

    protected class SessionsAdapter extends ArrayRecyclerAdapter<Session, BindingHolder<ItemSessionBinding>> {

        public SessionsAdapter(@NonNull Context context) {
            super(context);
        }

        protected void refresh(@NonNull Session session) {
            // TODO It may be heavy logic...
            for (int i = 0, count = adapter.getItemCount(); i < count; i++) {
                Session s = adapter.getItem(i);
                if (session.equals(s)) {
                    s.checked = session.checked;
                    adapter.notifyItemChanged(i);
                }
            }
        }

        @Override
        public BindingHolder<ItemSessionBinding> onCreateViewHolder(ViewGroup parent, int viewType) {
            return new BindingHolder<>(getContext(), parent, R.layout.item_session);
        }

        @Override
        public void onBindViewHolder(BindingHolder<ItemSessionBinding> holder, int position) {
            Session session = getItem(position);
            ItemSessionBinding binding = holder.binding;
            binding.setSession(session);

            if (position > 0 && position < getItemCount()) {
                Session prevSession = getItem(position - 1);
                if (prevSession.stime.getTime() == session.stime.getTime()) {
                    binding.txtStime.setVisibility(View.INVISIBLE);
                } else {
                    binding.txtStime.setVisibility(View.VISIBLE);
                }
            } else {
                binding.txtStime.setVisibility(View.VISIBLE);
            }

            binding.txtConflict.setVisibility(View.GONE);

            binding.btnStar.setOnLikeListener(new OnLikeListener() {
                @Override
                public void liked(LikeButton likeButton) {
                    session.checked = true;
                    final int pos = holder.getAdapterPosition();
                    if (pos != RecyclerView.NO_POSITION) {
                        onLikeChanged(session, pos);
                    }
                }

                @Override
                public void unLiked(LikeButton likeButton) {
                    session.checked = false;
                    final int pos = holder.getAdapterPosition();
                    if (pos != RecyclerView.NO_POSITION) {
                        onLikeChanged(session, pos);
                    }
                }
            });

            binding.cardView.setOnClickListener(v ->
                    activityNavigator.showSessionDetail(SessionsTabFragment.this, session, REQ_DETAIL));
        }

        protected void onLikeChanged(@NonNull Session session, int position) {
            dao.updateChecked(session);
            AlarmUtil.handleSessionAlarm(getContext(), session);
            onChangeSessionListener.onChangeSession(Collections.singletonList(session));
        }
    }

}


text:
define([
  'aeris/util',
  'aeris/model',
  'aeris/events',
  'backbone',
  'aeris/errors/invalidargumenterror'
], function(_, Model, Events, Backbone, InvalidArgumentError) {
  /**
   * Base collection class.
   *
   * @class Collection
   * @namespace aeris
   * @extends Backbone.Collection
   *
   * @param {Array.<aeris.Model>=} opt_models
   * @param {Object} opt_options
   * @param {Boolean=} opt_options.validate
   *        If set to true, will validate all models on instantiation.
   * @constructor
   */
  var Collection = function(opt_models, opt_options) {
    var options = _.extend({
      model: Model,
      validate: false,
      modelOptions: {}
    }, opt_options);

    if (opt_models && !_.isArray(opt_models)) {
      throw new InvalidArgumentError(opt_models + ' is not a valid array of models.');
    }

    /**
     * Options to pass on to
     * models created by this collection.
     *
     * @type {Object}
     * @protected
     * @property modelOptions_
     */
    this.modelOptions_ = options.modelOptions;

    Backbone.Collection.call(this, opt_models, options);
    Events.call(this);

    if (options.validate) {
      this.isValid();
    }

    /**
     * When any child model's attribute changes
     * @event change
     * @param {aeris.Model} model
     */

    /**
     * When any child model's attribute changes,
     * where [attribute] is the name of the attribute.
     *
     * @event change:[attribute]
     * @param {aeris.Model} model
     * @param {*} value
     */

    /**
     * When a model is added to the
     * {aeris.Collection}.
     *
     * @event add
     * @param {aeris.Model} model
     * @param {aeris.Collection} collection
     */

    /**
     * When a model is removed from the {aeris.Collection}.
     *
     * @event remove
     * @param {aeris.Model} model
     * @param {aeris.Collection} collection
     */
  };
  _.inherits(Collection, Backbone.Collection);
  _.extend(Collection.prototype, Events.prototype);

  /**
   * Runs validation on all collection models.
   *
   * @return {Boolean=} Returns false if any model fails validation.
   * @method isValid
   */
  Collection.prototype.isValid = function() {
    var isValid = true;
    this.each(function(model) {
      if (!model.isValid()) {
        isValid = false;
      }
    });

    return isValid;
  };

  /**
   * Retrieve a model from the collection
   * by id.
   *
   * @param {number|string} id
   * @return {aeris.Model}
   */

  /**
   * Retrieve a model from the collection
   * by index.
   *
   * @method at
   * @param {number} index
   * @return {aeris.Model}
   */

  /**
   * Pass modelOptions on to newly
   * created models.
   *
   * @override
   * @private
   * @method _prepareModel
   */
  Collection.prototype._prepareModel = function(attrs, opt_options) {
    var options = _.defaults(opt_options || {}, this.modelOptions_);

    return Backbone.Collection.prototype._prepareModel.call(this, attrs, options);
  };

  return _.expose(Collection, 'aeris.Collection');
});

/**
 * See http://backbonejs.org/#Collection for full
 * documentation. Provided here to provide documentation
 * for extending classes.
 *
 * @class Collection
 * @namespace Backbone
 */

/**
 * @protected
 * @method _prepareModel
 */

/**
 * @property model
 * @type {Function}
*/

/**
 * Add models to the collection.
 *
 * @method add
 * @param {Array.<Backbone.Model|Object>} models
 */

/**
 * Remove models from the collection.
 *
 * @method remove
 * @param {Array.<Backbone.Model>} models
 */

/**
 * Remove and replace all models in the collection.
 *
 * @method reset
 * @param {Array.<Backbone.Model|Object>=} opt_models
 */

/**
 * @protected
 * @method set
 */

/**
 * @method push
 * @protected
 */

/**
 * @method pop
 * @protected
 */

/**
 * @method shift
 * @protected
 */

/**
 * @method slice
 * @protected
 */

/**
 * The number of models in the collection.
 *
 * @property length
 */

/**
 * @protected
 * @method parse
 */


text:
/**
 * EntityBrokerImplTest.java - 2007 Jul 21, 2007 3:04:55 PM - entity-broker - AZ
 */

package org.sakaiproject.entitybroker.impl;

import java.util.List;
import java.util.Map;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.sakaiproject.entitybroker.dao.EntityBrokerDao;
import org.sakaiproject.entitybroker.impl.data.TestDataPreload;
import org.sakaiproject.entitybroker.mocks.data.TestData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;

/**
 * Testing the entitybroker implementation
 *
 * @author Aaron Zeckoski (azeckoski@gmail.com)
 */
@ContextConfiguration(locations={
		"/database-test.xml",
		"classpath:org/sakaiproject/entitybroker/spring-jdbc.xml" })
public class EntityMetaPropertiesServiceTest extends AbstractTransactionalJUnit4SpringContextTests {

   protected EntityMetaPropertiesService propertiesService;

   @Autowired
   @Qualifier("org.sakaiproject.entitybroker.dao.EntityBrokerDao")
   private EntityBrokerDao dao;
   private TestData td;
   @Autowired
   private TestDataPreload tdp;

   @Before
   public void onSetUp() throws Exception {
      // init the test data
      td = new TestData();

      // setup fake internal services
      ServiceTestManager tm = new ServiceTestManager(td, dao);

      // create and setup the object to be tested
      propertiesService = tm.entityMetaPropertiesService;
   }

   /**
    * ADD unit tests below here, use testMethod as the name of the unit test, Note that if a method
    * is overloaded you should include the arguments in the test name like so: testMethodClassInt
    * (for method(Class, int);
    */

   @Test
   public void testValidTestData() {
      // ensure the test data is setup the way we think
      Assert.assertNotNull(td);
      Assert.assertNotNull(tdp);

      // Assert.assertEquals(new Long(1), tdp.pNode1.getId());
   }

   /**
    * Test method for
    * {@link org.sakaiproject.entitybroker.impl.EntityBrokerImpl#findEntityRefs(java.lang.String[], java.lang.String[], java.lang.String[], boolean)}.
    */
   @Test
   public void testFindEntityRefs() {
      List<String> l = null;

      // test search with limit by prefix
      l = propertiesService.findEntityRefs(new String[] { TestData.PREFIX5 }, null, null, true);
      Assert.assertNotNull(l);
      Assert.assertEquals(2, l.size());
      Assert.assertTrue(l.contains(TestData.REF5));
      Assert.assertTrue(l.contains(TestData.REF5_2));

      // test search with limit by prefix (check that no results ok)
      l = propertiesService.findEntityRefs(new String[] { TestData.INVALID_REF }, null, null, true);
      Assert.assertNotNull(l);
      Assert.assertEquals(0, l.size());

      // test searching with multiple prefixes
      l = propertiesService.findEntityRefs(new String[] { TestData.PREFIX5, TestData.PREFIX1 }, null,
            null, true);
      Assert.assertNotNull(l);
      Assert.assertEquals(2, l.size());
      Assert.assertTrue(l.contains(TestData.REF5));
      Assert.assertTrue(l.contains(TestData.REF5_2));

      // test searching by names
      l = propertiesService.findEntityRefs(new String[] { TestData.PREFIX5 },
            new String[] { TestData.PROPERTY_NAME5A }, null, true);
      Assert.assertNotNull(l);
      Assert.assertEquals(1, l.size());
      Assert.assertTrue(l.contains(TestData.REF5));

      // test searching by invalid name (return no results)
      l = propertiesService.findEntityRefs(new String[] { TestData.PREFIX5 },
            new String[] { TestData.INVALID_REF }, null, true);
      Assert.assertNotNull(l);
      Assert.assertEquals(0, l.size());

      // test searching with multiple names
      l = propertiesService.findEntityRefs(new String[] { TestData.PREFIX5 }, new String[] {
            TestData.PROPERTY_NAME5A, TestData.PROPERTY_NAME5C }, null, true);
      Assert.assertNotNull(l);
      Assert.assertEquals(2, l.size());
      Assert.assertTrue(l.contains(TestData.REF5));
      Assert.assertTrue(l.contains(TestData.REF5_2));

      // test search limit by values (long exact match)
      l = propertiesService.findEntityRefs(new String[] { TestData.PREFIX5 },
            new String[] { TestData.PROPERTY_NAME5C }, new String[] { TestData.PROPERTY_VALUE5C },
            true);
      Assert.assertNotNull(l);
      Assert.assertEquals(1, l.size());
      Assert.assertTrue(l.contains(TestData.REF5_2));

      // test search limit by values (exact match)
      l = propertiesService.findEntityRefs(new String[] { TestData.PREFIX5 },
            new String[] { TestData.PROPERTY_NAME5B }, new String[] { TestData.PROPERTY_VALUE5B },
            true);
      Assert.assertNotNull(l);
      Assert.assertEquals(1, l.size());
      Assert.assertTrue(l.contains(TestData.REF5));

      // cannot have empty or null prefix
      try {
         l = propertiesService.findEntityRefs(new String[] {},
               new String[] { TestData.PROPERTY_NAME5A }, null, true);
         Assert.fail("Should have thrown exception");
      } catch (IllegalArgumentException e) {
         Assert.assertNotNull(e.getMessage());
      }

      try {
         l = propertiesService.findEntityRefs(null, new String[] { TestData.PROPERTY_NAME5A }, null,
               true);
         Assert.fail("Should have thrown exception");
      } catch (IllegalArgumentException e) {
         Assert.assertNotNull(e.getMessage());
      }

      // test search limit by values cannot have name null or empty
      try {
         l = propertiesService.findEntityRefs(new String[] { TestData.PREFIX5 }, new String[] {},
               new String[] { TestData.PROPERTY_VALUE5A }, true);
         Assert.fail("Should have thrown exception");
      } catch (IllegalArgumentException e) {
         Assert.assertNotNull(e.getMessage());
      }

      // test name and values arrays must match sizes
      try {
         l = propertiesService.findEntityRefs(new String[] { TestData.PREFIX5 }, new String[] {
               TestData.PROPERTY_NAME5A, TestData.PROPERTY_NAME5B },
               new String[] { TestData.PROPERTY_VALUE5A }, true);
         Assert.fail("Should have thrown exception");
      } catch (IllegalArgumentException e) {
         Assert.assertNotNull(e.getMessage());
      }

      // test search with all empty fields fail
      try {
         l = propertiesService.findEntityRefs(new String[] {}, new String[] {}, new String[] {}, false);
         Assert.fail("Should have thrown exception");
      } catch (IllegalArgumentException e) {
         Assert.assertNotNull(e.getMessage());
      }

   }

   /**
    * Test method for
    * {@link org.sakaiproject.entitybroker.impl.EntityBrokerImpl#getProperties(java.lang.String)}.
    */
   @Test
   public void testGetProperties() {
      Map<String, String> m = null;

      m = propertiesService.getProperties(TestData.REF5);
      Assert.assertNotNull(m);
      Assert.assertEquals(2, m.size());
      Assert.assertTrue(m.containsKey(TestData.PROPERTY_NAME5A));
      Assert.assertTrue(m.containsKey(TestData.PROPERTY_NAME5B));

      m = propertiesService.getProperties(TestData.REF5_2);
      Assert.assertNotNull(m);
      Assert.assertEquals(1, m.size());
      Assert.assertTrue(m.containsKey(TestData.PROPERTY_NAME5C));

      // ref with no properties should fetch none
      m = propertiesService.getProperties(TestData.REF1);
      Assert.assertNotNull(m);
      Assert.assertTrue(m.isEmpty());

      // make sure invalid ref causes failure
      try {
         m = propertiesService.getProperties(TestData.INVALID_REF);
         Assert.fail("Should have thrown exception");
      } catch (IllegalArgumentException e) {
         Assert.assertNotNull(e.getMessage());
      }

   }

   /**
    * Test method for
    * {@link org.sakaiproject.entitybroker.impl.EntityBrokerImpl#getPropertyValue(java.lang.String, java.lang.String)}.
    */
   @Test
   public void testGetPropertyValue() {
      String value = null;

      value = propertiesService.getPropertyValue(TestData.REF5, TestData.PROPERTY_NAME5A);
      Assert.assertNotNull(value);
      Assert.assertEquals(TestData.PROPERTY_VALUE5A, value);

      value = propertiesService.getPropertyValue(TestData.REF5, TestData.PROPERTY_NAME5B);
      Assert.assertNotNull(value);
      Assert.assertEquals(TestData.PROPERTY_VALUE5B, value);

      // test large value retrieval
      value = propertiesService.getPropertyValue(TestData.REF5_2, TestData.PROPERTY_NAME5C);
      Assert.assertNotNull(value);
      Assert.assertEquals(TestData.PROPERTY_VALUE5C, value);

      // nonexistent value property get retrieves null
      value = propertiesService.getPropertyValue(TestData.REF5, "XXXXXXXXXXXX");
      Assert.assertNull(value);

      // make sure invalid ref causes failure
      try {
         value = propertiesService.getPropertyValue(TestData.INVALID_REF, TestData.PROPERTY_NAME5A);
         Assert.fail("Should have thrown exception");
      } catch (IllegalArgumentException e) {
         Assert.assertNotNull(e.getMessage());
      }

      // null name causes failure
      try {
         value = propertiesService.getPropertyValue(TestData.REF5, null);
         Assert.fail("Should have thrown exception");
      } catch (IllegalArgumentException e) {
         Assert.assertNotNull(e.getMessage());
      }

      // empty name causes failure
      try {
         value = propertiesService.getPropertyValue(TestData.REF5, "");
         Assert.fail("Should have thrown exception");
      } catch (IllegalArgumentException e) {
         Assert.assertNotNull(e.getMessage());
      }

   }

   /**
    * Test method for
    * {@link org.sakaiproject.entitybroker.impl.EntityBrokerImpl#setPropertyValue(java.lang.String, java.lang.String, java.lang.String[])}.
    */
   @Test
   public void testSetPropertyValue() {
      String value = null;

      // check that we can save a new property on an entity
      propertiesService.setPropertyValue(TestData.REF5, "newNameAlpha", "newValueAlpha");
      value = propertiesService.getPropertyValue(TestData.REF5, "newNameAlpha");
      Assert.assertNotNull(value);
      Assert.assertEquals("newValueAlpha", value);

      // check that we can update an existing property on an entity
      propertiesService.setPropertyValue(TestData.REF5, TestData.PROPERTY_NAME5A, "AZnewValue");
      value = propertiesService.getPropertyValue(TestData.REF5, TestData.PROPERTY_NAME5A);
      Assert.assertNotNull(value);
      Assert.assertNotSame(TestData.PROPERTY_VALUE5A, value);
      Assert.assertEquals("AZnewValue", value);

      // check that we can remove a property on an entity
      propertiesService.setPropertyValue(TestData.REF5, "newNameAlpha", null);
      value = propertiesService.getPropertyValue(TestData.REF5, "newNameAlpha");
      Assert.assertNull(value);

      // check that we can remove all properties on an entity
      Map<String, String> m = propertiesService.getProperties(TestData.REF5);
      Assert.assertEquals(2, m.size());
      propertiesService.setPropertyValue(TestData.REF5, null, null);
      m = propertiesService.getProperties(TestData.REF5);
      Assert.assertEquals(0, m.size());

      // make sure invalid ref causes failure
      try {
         propertiesService.setPropertyValue(TestData.INVALID_REF, "newNameAlpha", "newValueAlpha");
         Assert.fail("Should have thrown exception");
      } catch (IllegalArgumentException e) {
         Assert.assertNotNull(e.getMessage());
      }

      // make sure invalid params cause failure
      try {
         propertiesService.setPropertyValue(TestData.REF1, null, "XXXXXXXXX");
         Assert.fail("Should have thrown exception");
      } catch (IllegalArgumentException e) {
         Assert.assertNotNull(e.getMessage());
      }

   }

}


text:
package com.app.admin.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.app.admin.model.Admin;
import com.app.admin.service.AdminService;
import com.app.session.AdminSession;
import com.app.util.Utility;

@Controller
public class AdminController {

	@Autowired
	private AdminService adminService;

	@Autowired
	private Utility utility;

	@RequestMapping(value = "/admin", method = RequestMethod.GET)
	public String AdminHome(Model model, HttpServletRequest req, HttpServletResponse res)
	{
		AdminSession session = (AdminSession) req.getSession().getAttribute("ADMIN_SESSION");

		if(session != null)
		{
			return "redirect:/admin/dashboard";
		}
		else
		{
			return "admin";
		}

	}

	@RequestMapping(value = "/admin/login", method = RequestMethod.POST)
	public String AdminLogin(Model model, HttpServletRequest req, HttpServletResponse res) throws Exception
	{
		String mobile = req.getParameter("mobile") == null ? "" : req.getParameter("mobile");
		String password = req.getParameter("password") == null ? "" : req.getParameter("password");
		password = utility.encrypt(password, "MD5", "UTF-8");

		if(!mobile.equals("") && !password.equals(""))
    	{
			Admin adminInfo = adminService.getAdminInfo(mobile,password);
			if(adminInfo != null)
			{
				AdminSession session = new AdminSession();
				session.setAdmin(adminInfo);
				session.setSessionId(req.getSession().getId());
				req.getSession(true).setAttribute("ADMIN_SESSION", session);
			}
			else
			{
				model.addAttribute("status", "failure");
	    		model.addAttribute("message", "Credentials not matching.");
			}
    	}
		else
		{
			model.addAttribute("status", "failure");
    		model.addAttribute("message", "All fields are required.");
		}

		return "redirect:/admin";
	}

	/* LOGOUT
	 * */
	@RequestMapping(value = "/admin/logout", method = RequestMethod.GET)
	public String Logout(Model model, HttpServletRequest req, HttpServletResponse res)
	{
		req.getSession().removeAttribute("ADMIN_SESSION");
		return "redirect:/admin";
	}

}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, user-scalable=no">
    <link rel="shortcut icon" href="../../assets/ax5favicon.ico" type="image/x-icon">
    <title>ax5ui / ax5ui-formatter : home</title>

    <link rel="stylesheet" type="text/css" href="../../assets/lib/prettify/skins/github.css">

    <link rel="stylesheet" type="text/css" href="../../assets/css/docs.css">

							/ ax5ui-formatter

Demo

API

                                    Star
                                    .

                                AX5UI

AX5UI

ax5core

ax5ui-mask

ax5ui-dialog

ax5ui-toast

ax5ui-modal

ax5ui-calendar

ax5ui-picker

ax5ui-formatter

ax5ui-menu

ax5ui-media-viewer

ax5ui-select

ax5ui-layout

ax5ui-combobox

ax5ui-autocomplete

ax5ui-binder

ax5ui-grid

ax5ui-uploader

ax5ui-docker

ax5ui-palette

axisj.com

AX5UI

ax5ui-formatter

					<button class="btn btn-lg btn-border white" onclick="location.href = 'https://github.com/ax5ui/ax5ui-formatter';">
						Get ax5formatter
					</button>

					<button class="btn btn-lg btn-border white" onclick="location.href = 'demo/index.html';">Demonstration
					</button>

ax5ui-formatter

"formatter" provides a set of pre-defined formats for various types of values.

Dependencies

jQuery 1.X+

ax5core

bootstrap

Install with bower

bower install ax5ui-formatter

bower is web front-end package manager.
When you install bower, it will be installed under the bower_components folder to resolve the plug-in dependencies.

(You can change the folder location. .bowerrc )

It is recommended that you install by using bower.
If you've never used bower, please refer to http://bower.io/#install-bower.

Install with npm

If you do not use bower, it also can be installed by using npm as an alternative.
In case of npm, which is the package manager for the front end, you need to solve the problem of plug-in dependencies.

npm install jquery
npm install ax5core
npm install ax5ui-formatter

After downloading the install file of npm, you will need to copy it to the location where you want to use as a resource for the project.
If the copy process is inconvenient, it also can be done easily by using gulp or grunt.

Download code

ax5core Github releases

ax5ui-formatter Github releases

Insert "ax5formatter" in HTML HEAD.

Folder location can be any for your project. However, please be sure to assign the right path in the project.

<link rel="stylesheet" type="text/css" href="https://cdn.rawgit.com/ax5ui/ax5ui-formatter/master/dist/ax5formatter.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.rawgit.com/ax5ui/ax5core/master/dist/ax5core.min.js"></script>
<script type="text/javascript" src="https://cdn.rawgit.com/ax5ui/ax5ui-formatter/master/dist/ax5formatter.min.js"></script>

CDN urls
This is a list of CDN urls for ax5ui-formatter. ax5ui offers the CDN services through rawgit.

https://cdn.rawgit.com/ax5ui/ax5ui-formatter/master/dist/ax5formatter.css
https://cdn.rawgit.com/ax5ui/ax5ui-formatter/master/dist/ax5formatter.js
https://cdn.rawgit.com/ax5ui/ax5ui-formatter/master/dist/ax5formatter.min.js

Basic Usage

<div class="form-group">
    <div class="input-group">
        <span class="input-group-addon">Money</span>
        <input name="1" type="text" class="form-control" placeholder="" data-ax5formatter="money" />
    </div>
</div>
<div class="form-group">
    <div class="input-group">
        <span class="input-group-addon">Date</span>
        <input name="3" type="text" class="form-control" placeholder="yyyy-mm-dd" data-ax5formatter="date" />
    </div>
</div>

$('[data-ax5formatter]').ax5formatter();

Preview

See Demonstration

If you have any questions, please refer to the following gitHub

Question

https://jsdev.kr/c/axisj/ax5ui

https://github.com/ax5ui/ax5ui-kernel/issues

                             AX5UI Package

                        'AX5UI' can be used with Bootstrap theme. The development of the distribution of the various UI plug-in.
                        When you click the link to move to AX5UI index page.

                             Get AXBoot

                        AXBoot makes it easy to build web applications with Java & HTML5
                        Repeatable and noise development process are resolved by AXBoot.

Code licensed

MIT

Mantained by

Thomas Jang, Brant and Team AXISJ

Templete design by

Jorwrney Kim

Copyright

Opensource Group AXISJ -
                        www.axisj.com

DNS

                        DNSEver


text:
import React from 'react'
import classnames from 'classnames'
import { Button } from '@blueprintjs/core'

import { msg } from 'common/i18n/i18n'
import { formatNumber } from 'common/util/TextUtil'

import './SelectionSummary.less'

export interface Props {
    className?: any
    selectedCount: number
    onClearSelection(): void
}

export default class SelectionSummary extends React.Component<Props> {

    render() {
        const { props } = this
        return (

                    {msg('SelectionSummary_selected', formatNumber(props.selectedCount))}

                <Button
                    icon='cross'
                    minimal={true}
                    title={msg('SelectionSummary_clearSelection')}
                    onClick={props.onClearSelection}
                />

        )
    }

}


text:
package kieker.analysis.generic.source;

import kieker.common.record.IMonitoringRecord;

import teetime.framework.OutputPort;

/**
 * Marker interface for composite stages used as source.
 *
 * @author Reiner Jung
 *
 * @since 1.15
 *
 */
public interface ISourceCompositeStage {

	/**
	 * get the output port of a source composite stage.
	 *
	 * @return the proper output port
	 * @since 1.15
	 */
	OutputPort<IMonitoringRecord> getOutputPort();
}