text:
package org.kaazing.gateway.transport;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

import org.apache.mina.core.filterchain.IoFilterAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.core.write.WriteRequest;

public abstract class AbstractInboundEventFilter extends IoFilterAdapter {

    private final TypedAttributeKey<Queue<InboundEvent>> inboundEventsKey =
                        new TypedAttributeKey<>(getClass(), "inboundEvents");

    @Override
    public void sessionCreated(NextFilter nextFilter, IoSession session) throws Exception {
        Queue<InboundEvent> inboundEvents = inboundEventsKey.get(session);
        if (inboundEvents != null) {
            inboundEvents.add(new SessionCreatedEvent());
        }
        else {
            super.sessionCreated(nextFilter, session);
        }
    }

    @Override
    public void sessionOpened(NextFilter nextFilter, IoSession session) throws Exception {
        Queue<InboundEvent> inboundEvents = inboundEventsKey.get(session);
        if (inboundEvents != null) {
            inboundEvents.add(new SessionOpenedEvent());
        }
        else {
            super.sessionOpened(nextFilter, session);
        }
    }

    @Override
    public void sessionIdle(NextFilter nextFilter, IoSession session, IdleStatus status) throws Exception {
        // note: *always* propagate session idle
        super.sessionIdle(nextFilter, session, status);
    }

    @Override
    public void exceptionCaught(NextFilter nextFilter, IoSession session, Throwable cause) throws Exception {
        // note: *always* propagate exception caught
        super.exceptionCaught(nextFilter, session, cause);
    }

    @Override
    public void messageReceived(NextFilter nextFilter, IoSession session, Object message) throws Exception {
        Queue<InboundEvent> inboundEvents = inboundEventsKey.get(session);
        if (inboundEvents != null) {
            inboundEvents.add(new MessageReceivedEvent(message));
        }
        else {
            super.messageReceived(nextFilter, session, message);
        }
    }

    @Override
    public void messageSent(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) throws Exception {
        Queue<InboundEvent> inboundEvents = inboundEventsKey.get(session);
        if (inboundEvents != null) {
            inboundEvents.add(new MessageSentEvent(writeRequest));
        }
        else {
            super.messageSent(nextFilter, session, writeRequest);
        }
    }

    @Override
    public void sessionClosed(NextFilter nextFilter, IoSession session) throws Exception {
        Queue<InboundEvent> inboundEvents = inboundEventsKey.get(session);
        if (inboundEvents != null) {
            inboundEvents.add(new SessionClosedEvent());
        }
        else {
            super.sessionClosed(nextFilter, session);
        }
    }

    protected Queue<InboundEvent> suspendInboundEvents(NextFilter nextFilter, IoSession session) throws Exception {
        Queue<InboundEvent> inboundEvents = inboundEventsKey.get(session);
        if (inboundEvents == null) {
            Queue<InboundEvent> newInboundEvents = new ConcurrentLinkedQueue<>();
            inboundEvents = inboundEventsKey.setIfAbsent(session, newInboundEvents);
            if (inboundEvents == null) {
                inboundEvents = newInboundEvents;
            }
        }
        return inboundEvents;
    }

    protected void flushInboundEvents(NextFilter nextFilter, IoSession session) throws Exception {
        Queue<InboundEvent> inboundEvents = inboundEventsKey.remove(session);
        if (inboundEvents != null) {
            for (InboundEvent inboundEvent : inboundEvents) {
                inboundEvent.flush(nextFilter, session);
            }
        }
    }

    private static abstract class InboundEvent {
        public abstract void flush(NextFilter nextFilter, IoSession session);
    }

    private static final class SessionCreatedEvent extends InboundEvent {
        @Override
        public void flush(NextFilter nextFilter, IoSession session) {
            nextFilter.sessionCreated(session);
        }
    }

    private static final class SessionOpenedEvent extends InboundEvent {
        @Override
        public void flush(NextFilter nextFilter, IoSession session) {
            nextFilter.sessionOpened(session);
        }
    }

    private static final class MessageReceivedEvent extends InboundEvent {
        private final Object message;

        public MessageReceivedEvent(Object message) {
            this.message = message;
        }

        @Override
        public void flush(NextFilter nextFilter, IoSession session) {
            nextFilter.messageReceived(session, message);
        }
    }

    private static final class MessageSentEvent extends InboundEvent {
        private final WriteRequest writeRequest;

        public MessageSentEvent(WriteRequest writeRequest) {
            this.writeRequest = writeRequest;
        }

        @Override
        public void flush(NextFilter nextFilter, IoSession session) {
            nextFilter.messageSent(session, writeRequest);
        }
    }

    private static final class SessionClosedEvent extends InboundEvent {
        @Override
        public void flush(NextFilter nextFilter, IoSession session) {
            nextFilter.sessionClosed(session);
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Database\Factories;

use App\Models\LocationType;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\Factory;

class LocationTypeFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = LocationType::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'name' => $this->faker->word,
            'created_at' => Carbon::now(),
            'updated_at' => Carbon::now()
        ];
    }
}


text:
{-# LANGUAGE Trustworthy #-}
-----------------------------------------------------------------------------
-- |
-- Module      :  Control.Arrow
-- Copyright   :  (c) Ross Paterson 2002
-- License     :  BSD-style (see the LICENSE file in the distribution)
--
-- Maintainer  :  libraries@haskell.org
-- Stability   :  provisional
-- Portability :  portable
--
-- Basic arrow definitions, based on
--  * /Generalising Monads to Arrows/, by John Hughes,
--    /Science of Computer Programming/ 37, pp67-111, May 2000.
-- plus a couple of definitions ('returnA' and 'loop') from
--  * /A New Notation for Arrows/, by Ross Paterson, in /ICFP 2001/,
--    Firenze, Italy, pp229-240.
-- These papers and more information on arrows can be found at
-- <http://www.haskell.org/arrows/>.

module Control.Arrow (
    -- * Arrows
    Arrow(..), Kleisli(..),
    -- ** Derived combinators
    returnA,
    (^>>), (>>^),
    (>>>), (<<<), -- reexported
    -- ** Right-to-left variants
    (<<^), (^<<),
    -- * Monoid operations
    ArrowZero(..), ArrowPlus(..),
    -- * Conditionals
    ArrowChoice(..),
    -- * Arrow application
    ArrowApply(..), ArrowMonad(..), leftApp,
    -- * Feedback
    ArrowLoop(..)
    ) where

import Prelude hiding (id,(.))

import Control.Monad
import Control.Monad.Fix
import Control.Category

infixr 5 <+>
infixr 3 ***
infixr 3 &&&
infixr 2 +++
infixr 2 |||
infixr 1 ^>>, >>^
infixr 1 ^<<, <<^

-- | The basic arrow class.
--
-- Minimal complete definition: 'arr' and 'first', satisfying the laws
--
--  * @'arr' id = 'id'@
--
--  * @'arr' (f >>> g) = 'arr' f >>> 'arr' g@
--
--  * @'first' ('arr' f) = 'arr' ('first' f)@
--
--  * @'first' (f >>> g) = 'first' f >>> 'first' g@
--
--  * @'first' f >>> 'arr' 'fst' = 'arr' 'fst' >>> f@
--
--  * @'first' f >>> 'arr' ('id' *** g) = 'arr' ('id' *** g) >>> 'first' f@
--
--  * @'first' ('first' f) >>> 'arr' 'assoc' = 'arr' 'assoc' >>> 'first' f@
--
-- where
--
-- > assoc ((a,b),c) = (a,(b,c))
--
-- The other combinators have sensible default definitions,
-- which may be overridden for efficiency.

class Category a => Arrow a where

    -- | Lift a function to an arrow.
    arr :: (b -> c) -> a b c

    -- | Send the first component of the input through the argument
    --   arrow, and copy the rest unchanged to the output.
    first :: a b c -> a (b,d) (c,d)

    -- | A mirror image of 'first'.
    --
    --   The default definition may be overridden with a more efficient
    --   version if desired.
    second :: a b c -> a (d,b) (d,c)
    second f = arr swap >>> first f >>> arr swap
      where
        swap :: (x,y) -> (y,x)
        swap ~(x,y) = (y,x)

    -- | Split the input between the two argument arrows and combine
    --   their output.  Note that this is in general not a functor.
    --
    --   The default definition may be overridden with a more efficient
    --   version if desired.
    (***) :: a b c -> a b' c' -> a (b,b') (c,c')
    f *** g = first f >>> second g

    -- | Fanout: send the input to both argument arrows and combine
    --   their output.
    --
    --   The default definition may be overridden with a more efficient
    --   version if desired.
    (&&&) :: a b c -> a b c' -> a b (c,c')
    f &&& g = arr (\b -> (b,b)) >>> f *** g

{-# RULES
"compose/arr"   forall f g .
                (arr f) . (arr g) = arr (f . g)
"first/arr"     forall f .
                first (arr f) = arr (first f)
"second/arr"    forall f .
                second (arr f) = arr (second f)
"product/arr"   forall f g .
                arr f *** arr g = arr (f *** g)
"fanout/arr"    forall f g .
                arr f &&& arr g = arr (f &&& g)
"compose/first" forall f g .
                (first f) . (first g) = first (f . g)
"compose/second" forall f g .
                (second f) . (second g) = second (f . g)
 #-}

-- Ordinary functions are arrows.

instance Arrow (->) where
    arr f = f
    first f = f *** id
    second f = id *** f
--  (f *** g) ~(x,y) = (f x, g y)
--  sorry, although the above defn is fully H'98, nhc98 can't parse it.
    (***) f g ~(x,y) = (f x, g y)

-- | Kleisli arrows of a monad.
newtype Kleisli m a b = Kleisli { runKleisli :: a -> m b }

instance Monad m => Category (Kleisli m) where
    id = Kleisli return
    (Kleisli f) . (Kleisli g) = Kleisli (\b -> g b >>= f)

instance Monad m => Arrow (Kleisli m) where
    arr f = Kleisli (return . f)
    first (Kleisli f) = Kleisli (\ ~(b,d) -> f b >>= \c -> return (c,d))
    second (Kleisli f) = Kleisli (\ ~(d,b) -> f b >>= \c -> return (d,c))

-- | The identity arrow, which plays the role of 'return' in arrow notation.
returnA :: Arrow a => a b b
returnA = arr id

-- | Precomposition with a pure function.
(^>>) :: Arrow a => (b -> c) -> a c d -> a b d
f ^>> a = arr f >>> a

-- | Postcomposition with a pure function.
(>>^) :: Arrow a => a b c -> (c -> d) -> a b d
a >>^ f = a >>> arr f

-- | Precomposition with a pure function (right-to-left variant).
(<<^) :: Arrow a => a c d -> (b -> c) -> a b d
a <<^ f = a <<< arr f

-- | Postcomposition with a pure function (right-to-left variant).
(^<<) :: Arrow a => (c -> d) -> a b c -> a b d
f ^<< a = arr f <<< a

class Arrow a => ArrowZero a where
    zeroArrow :: a b c

instance MonadPlus m => ArrowZero (Kleisli m) where
    zeroArrow = Kleisli (\_ -> mzero)

-- | A monoid on arrows.
class ArrowZero a => ArrowPlus a where
    -- | An associative operation with identity 'zeroArrow'.
    (<+>) :: a b c -> a b c -> a b c

instance MonadPlus m => ArrowPlus (Kleisli m) where
    Kleisli f <+> Kleisli g = Kleisli (\x -> f x `mplus` g x)

-- | Choice, for arrows that support it.  This class underlies the
-- @if@ and @case@ constructs in arrow notation.
-- Minimal complete definition: 'left', satisfying the laws
--
--  * @'left' ('arr' f) = 'arr' ('left' f)@
--
--  * @'left' (f >>> g) = 'left' f >>> 'left' g@
--
--  * @f >>> 'arr' 'Left' = 'arr' 'Left' >>> 'left' f@
--
--  * @'left' f >>> 'arr' ('id' +++ g) = 'arr' ('id' +++ g) >>> 'left' f@
--
--  * @'left' ('left' f) >>> 'arr' 'assocsum' = 'arr' 'assocsum' >>> 'left' f@
--
-- where
--
-- > assocsum (Left (Left x)) = Left x
-- > assocsum (Left (Right y)) = Right (Left y)
-- > assocsum (Right z) = Right (Right z)
--
-- The other combinators have sensible default definitions, which may
-- be overridden for efficiency.

class Arrow a => ArrowChoice a where

    -- | Feed marked inputs through the argument arrow, passing the
    --   rest through unchanged to the output.
    left :: a b c -> a (Either b d) (Either c d)

    -- | A mirror image of 'left'.
    --
    --   The default definition may be overridden with a more efficient
    --   version if desired.
    right :: a b c -> a (Either d b) (Either d c)
    right f = arr mirror >>> left f >>> arr mirror
      where
        mirror :: Either x y -> Either y x
        mirror (Left x) = Right x
        mirror (Right y) = Left y

    -- | Split the input between the two argument arrows, retagging
    --   and merging their outputs.
    --   Note that this is in general not a functor.
    --
    --   The default definition may be overridden with a more efficient
    --   version if desired.
    (+++) :: a b c -> a b' c' -> a (Either b b') (Either c c')
    f +++ g = left f >>> right g

    -- | Fanin: Split the input between the two argument arrows and
    --   merge their outputs.
    --
    --   The default definition may be overridden with a more efficient
    --   version if desired.
    (|||) :: a b d -> a c d -> a (Either b c) d
    f ||| g = f +++ g >>> arr untag
      where
        untag (Left x) = x
        untag (Right y) = y

{-# RULES
"left/arr"      forall f .
                left (arr f) = arr (left f)
"right/arr"     forall f .
                right (arr f) = arr (right f)
"sum/arr"       forall f g .
                arr f +++ arr g = arr (f +++ g)
"fanin/arr"     forall f g .
                arr f ||| arr g = arr (f ||| g)
"compose/left"  forall f g .
                left f . left g = left (f . g)
"compose/right" forall f g .
                right f . right g = right (f . g)
 #-}

instance ArrowChoice (->) where
    left f = f +++ id
    right f = id +++ f
    f +++ g = (Left . f) ||| (Right . g)
    (|||) = either

instance Monad m => ArrowChoice (Kleisli m) where
    left f = f +++ arr id
    right f = arr id +++ f
    f +++ g = (f >>> arr Left) ||| (g >>> arr Right)
    Kleisli f ||| Kleisli g = Kleisli (either f g)

-- | Some arrows allow application of arrow inputs to other inputs.
-- Instances should satisfy the following laws:
--
--  * @'first' ('arr' (\\x -> 'arr' (\\y -> (x,y)))) >>> 'app' = 'id'@
--
--  * @'first' ('arr' (g >>>)) >>> 'app' = 'second' g >>> 'app'@
--
--  * @'first' ('arr' (>>> h)) >>> 'app' = 'app' >>> h@
--
-- Such arrows are equivalent to monads (see 'ArrowMonad').

class Arrow a => ArrowApply a where
    app :: a (a b c, b) c

instance ArrowApply (->) where
    app (f,x) = f x

instance Monad m => ArrowApply (Kleisli m) where
    app = Kleisli (\(Kleisli f, x) -> f x)

-- | The 'ArrowApply' class is equivalent to 'Monad': any monad gives rise
--   to a 'Kleisli' arrow, and any instance of 'ArrowApply' defines a monad.

newtype ArrowMonad a b = ArrowMonad (a () b)

instance Arrow a => Functor (ArrowMonad a) where
    fmap f (ArrowMonad m) = ArrowMonad $ m >>> arr f

instance ArrowApply a => Monad (ArrowMonad a) where
    return x = ArrowMonad (arr (\_ -> x))
    ArrowMonad m >>= f = ArrowMonad $
        m >>> arr (\x -> let ArrowMonad h = f x in (h, ())) >>> app

instance (ArrowApply a, ArrowPlus a) => MonadPlus (ArrowMonad a) where
   mzero = ArrowMonad zeroArrow
   ArrowMonad x `mplus` ArrowMonad y = ArrowMonad (x <+> y)

-- | Any instance of 'ArrowApply' can be made into an instance of
--   'ArrowChoice' by defining 'left' = 'leftApp'.

leftApp :: ArrowApply a => a b c -> a (Either b d) (Either c d)
leftApp f = arr ((\b -> (arr (\() -> b) >>> f >>> arr Left, ())) |||
             (\d -> (arr (\() -> d) >>> arr Right, ()))) >>> app

-- | The 'loop' operator expresses computations in which an output value
-- is fed back as input, although the computation occurs only once.
-- It underlies the @rec@ value recursion construct in arrow notation.
-- 'loop' should satisfy the following laws:
--
-- [/extension/]
--      @'loop' ('arr' f) = 'arr' (\\ b -> 'fst' ('fix' (\\ (c,d) -> f (b,d))))@
--
-- [/left tightening/]
--      @'loop' ('first' h >>> f) = h >>> 'loop' f@
--
-- [/right tightening/]
--      @'loop' (f >>> 'first' h) = 'loop' f >>> h@
--
-- [/sliding/]
--      @'loop' (f >>> 'arr' ('id' *** k)) = 'loop' ('arr' ('id' *** k) >>> f)@
--
-- [/vanishing/]
--      @'loop' ('loop' f) = 'loop' ('arr' unassoc >>> f >>> 'arr' assoc)@
--
-- [/superposing/]
--      @'second' ('loop' f) = 'loop' ('arr' assoc >>> 'second' f >>> 'arr' unassoc)@
--
-- where
--
-- > assoc ((a,b),c) = (a,(b,c))
-- > unassoc (a,(b,c)) = ((a,b),c)
--
class Arrow a => ArrowLoop a where
    loop :: a (b,d) (c,d) -> a b c

instance ArrowLoop (->) where
    loop f b = let (c,d) = f (b,d) in c

-- | Beware that for many monads (those for which the '>>=' operation
-- is strict) this instance will /not/ satisfy the right-tightening law
-- required by the 'ArrowLoop' class.
instance MonadFix m => ArrowLoop (Kleisli m) where
    loop (Kleisli f) = Kleisli (liftM fst . mfix . f')
      where f' x y = f (x, snd y)


text:
[See html formatted version](https://huasofoundries.github.io/google-maps-documentation/Marker.html)

Marker class
------------

google.maps.Marker class

This class extends [MVCObject](MVCObject.md).

Constructor

[Marker](#Marker.constructor)

Marker(\[opts\])

**Parameters:**

*   opts (optional):  [MarkerOptions](MarkerOptions.md)

Creates a marker with the options specified. If a map is specified, the marker is added to the map upon construction. Note that the position must be set for the marker to display.

Methods

[getAnimation](#Marker.getAnimation)

getAnimation()

**Parameters:**  None

**Return Value:**  [Animation](Animation.md)

[getClickable](#Marker.getClickable)

getClickable()

**Parameters:**  None

**Return Value:**  boolean

[getCursor](#Marker.getCursor)

getCursor()

**Parameters:**  None

**Return Value:**  string

[getDraggable](#Marker.getDraggable)

getDraggable()

**Parameters:**  None

**Return Value:**  boolean

[getIcon](#Marker.getIcon)

getIcon()

**Parameters:**  None

**Return Value:**  string|[Icon](Icon.md)|[Symbol](Symbol.md)

[getLabel](#Marker.getLabel)

getLabel()

**Parameters:**  None

**Return Value:**  [MarkerLabel](MarkerLabel.md)

[getMap](#Marker.getMap)

getMap()

**Parameters:**  None

**Return Value:**  [Map](Map.md)|[StreetViewPanorama](StreetViewPanorama.md)

[getOpacity](#Marker.getOpacity)

getOpacity()

**Parameters:**  None

**Return Value:**  number

[getPosition](#Marker.getPosition)

getPosition()

**Parameters:**  None

**Return Value:**  [LatLng](LatLng.md)

[getShape](#Marker.getShape)

getShape()

**Parameters:**  None

**Return Value:**  [MarkerShape](MarkerShape.md)

[getTitle](#Marker.getTitle)

getTitle()

**Parameters:**  None

**Return Value:**  string

[getVisible](#Marker.getVisible)

getVisible()

**Parameters:**  None

**Return Value:**  boolean

[getZIndex](#Marker.getZIndex)

getZIndex()

**Parameters:**  None

**Return Value:**  number

[setAnimation](#Marker.setAnimation)

setAnimation(animation)

**Parameters:**

*   animation:  [Animation](Animation.md)

**Return Value:**  None

Start an animation. Any ongoing animation will be cancelled. Currently supported animations are: BOUNCE, DROP. Passing in null will cause any animation to stop.

[setClickable](#Marker.setClickable)

setClickable(flag)

**Parameters:**

*   flag:  boolean

**Return Value:**  None

[setCursor](#Marker.setCursor)

setCursor(cursor)

**Parameters:**

*   cursor:  string

**Return Value:**  None

[setDraggable](#Marker.setDraggable)

setDraggable(flag)

**Parameters:**

*   flag:  boolean

**Return Value:**  None

[setIcon](#Marker.setIcon)

setIcon(icon)

**Parameters:**

*   icon:  string|[Icon](Icon.md)|[Symbol](Symbol.md)

**Return Value:**  None

[setLabel](#Marker.setLabel)

setLabel(label)

**Parameters:**

*   label:  string|[MarkerLabel](MarkerLabel.md)

**Return Value:**  None

[setMap](#Marker.setMap)

setMap(map)

**Parameters:**

*   map:  [Map](Map.md)|[StreetViewPanorama](StreetViewPanorama.md)

**Return Value:**  None

Renders the marker on the specified map or panorama. If map is set to null, the marker will be removed.

[setOpacity](#Marker.setOpacity)

setOpacity(opacity)

**Parameters:**

*   opacity:  number

**Return Value:**  None

[setOptions](#Marker.setOptions)

setOptions(options)

**Parameters:**

*   options:  [MarkerOptions](MarkerOptions.md)

**Return Value:**  None

[setPosition](#Marker.setPosition)

setPosition(latlng)

**Parameters:**

*   latlng:  [LatLng](LatLng.md)|[LatLngLiteral](LatLngLiteral.md)

**Return Value:**  None

[setShape](#Marker.setShape)

setShape(shape)

**Parameters:**

*   shape:  [MarkerShape](MarkerShape.md)

**Return Value:**  None

[setTitle](#Marker.setTitle)

setTitle(title)

**Parameters:**

*   title:  string

**Return Value:**  None

[setVisible](#Marker.setVisible)

setVisible(visible)

**Parameters:**

*   visible:  boolean

**Return Value:**  None

[setZIndex](#Marker.setZIndex)

setZIndex(zIndex)

**Parameters:**

*   zIndex:  number

**Return Value:**  None

Constants

[MAX\_ZINDEX](#Marker.MAX_ZINDEX)

The maximum default z-index that the API will assign to a marker. You may set a higher z-index to bring a marker to the front.

Events

[animation\_changed](#Marker.animation_changed)

function()

**Arguments:**  None

This event is fired when the marker's animation property changes.

[click](#Marker.click)

function(event)

**Arguments:**

*   event:  [MouseEvent](MouseEvent.md)

This event is fired when the marker icon was clicked.

[clickable\_changed](#Marker.clickable_changed)

function()

**Arguments:**  None

This event is fired when the marker's clickable property changes.

[cursor\_changed](#Marker.cursor_changed)

function()

**Arguments:**  None

This event is fired when the marker's cursor property changes.

[dblclick](#Marker.dblclick)

function(event)

**Arguments:**

*   event:  [MouseEvent](MouseEvent.md)

This event is fired when the marker icon was double clicked.

[drag](#Marker.drag)

function(event)

**Arguments:**

*   event:  [MouseEvent](MouseEvent.md)

This event is repeatedly fired while the user drags the marker.

[dragend](#Marker.dragend)

function(event)

**Arguments:**

*   event:  [MouseEvent](MouseEvent.md)

This event is fired when the user stops dragging the marker.

[draggable\_changed](#Marker.draggable_changed)

function()

**Arguments:**  None

This event is fired when the marker's draggable property changes.

[dragstart](#Marker.dragstart)

function(event)

**Arguments:**

*   event:  [MouseEvent](MouseEvent.md)

This event is fired when the user starts dragging the marker.

[flat\_changed](#Marker.flat_changed)

function()

**Arguments:**  None

This event is fired when the marker's flat property changes.

[icon\_changed](#Marker.icon_changed)

function()

**Arguments:**  None

This event is fired when the marker icon property changes.

[mousedown](#Marker.mousedown)

function(event)

**Arguments:**

*   event:  [MouseEvent](MouseEvent.md)

This event is fired for a mousedown on the marker.

[mouseout](#Marker.mouseout)

function(event)

**Arguments:**

*   event:  [MouseEvent](MouseEvent.md)

This event is fired when the mouse leaves the area of the marker icon.

[mouseover](#Marker.mouseover)

function(event)

**Arguments:**

*   event:  [MouseEvent](MouseEvent.md)

This event is fired when the mouse enters the area of the marker icon.

[mouseup](#Marker.mouseup)

function(event)

**Arguments:**

*   event:  [MouseEvent](MouseEvent.md)

This event is fired for a mouseup on the marker.

[position\_changed](#Marker.position_changed)

function()

**Arguments:**  None

This event is fired when the marker position property changes.

[rightclick](#Marker.rightclick)

function(event)

**Arguments:**

*   event:  [MouseEvent](MouseEvent.md)

This event is fired for a rightclick on the marker.

[shape\_changed](#Marker.shape_changed)

function()

**Arguments:**  None

This event is fired when the marker's shape property changes.

[title\_changed](#Marker.title_changed)

function()

**Arguments:**  None

This event is fired when the marker title property changes.

[visible\_changed](#Marker.visible_changed)

function()

**Arguments:**  None

This event is fired when the marker's visible property changes.

[zindex\_changed](#Marker.zindex_changed)

function()

**Arguments:**  None

This event is fired when the marker's zIndex property changes.


text:
package com.fox.sp.util;

import java.sql.ResultSet;

public interface Wrapper<T> {
	public T getObject(ResultSet rs);
}


text:
package mvm.rya.camel.cbsail;

import org.apache.camel.Exchange;
import org.apache.camel.impl.DefaultProducer;
import org.openrdf.model.Statement;
import org.openrdf.query.*;
import org.openrdf.query.resultio.sparqlxml.SPARQLResultsXMLWriter;
import org.openrdf.repository.RepositoryConnection;
import org.openrdf.repository.RepositoryException;
import org.openrdf.rio.RDFHandlerException;

import java.io.ByteArrayOutputStream;
import java.util.*;

import static mvm.rya.api.RdfCloudTripleStoreConfiguration.*;
import static mvm.rya.camel.cbsail.CbSailComponent.SPARQL_QUERY_PROP;
import static mvm.rya.camel.cbsail.CbSailComponent.valueFactory;

/**
 */
public class CbSailProducer extends DefaultProducer {

    private RepositoryConnection connection;

    private CbSailEndpoint.CbSailOutput queryOutput = CbSailEndpoint.CbSailOutput.BINARY;

    public CbSailProducer(CbSailEndpoint endpoint) {
        super(endpoint);
    }

    @Override
    public void process(final Exchange exchange) throws Exception {
        //If a query is set in the header or uri, use it
        Collection<String> queries = new ArrayList<String>();
        Collection tmp = exchange.getIn().getHeader(SPARQL_QUERY_PROP, Collection.class);
        if (tmp != null) {
            queries = tmp;
        } else {
            String query = exchange.getIn().getHeader(SPARQL_QUERY_PROP, String.class);
            if (query != null) {
                queries.add(query);
            }
        }

        if (queries.size() > 0)
            sparqlQuery(exchange, queries);
        else
            inputTriples(exchange);
    }

    protected void inputTriples(Exchange exchange) throws RepositoryException {
        Object body = exchange.getIn().getBody();
        if (body instanceof Statement) {
            //save statement
            inputStatement((Statement) body);
        } else if (body instanceof List) {
            //save list of statements
            List lst = (List) body;
            for (Object obj : lst) {
                if (obj instanceof Statement)
                    inputStatement((Statement) obj);
            }
        }
        connection.commit();
        exchange.getOut().setBody(Boolean.TRUE);
    }

    protected void inputStatement(Statement stmt) throws RepositoryException {
        connection.add(stmt.getSubject(), stmt.getPredicate(), stmt.getObject());
    }

    protected void sparqlQuery(Exchange exchange, Collection<String> queries) throws RepositoryException, MalformedQueryException, QueryEvaluationException, TupleQueryResultHandlerException, RDFHandlerException {

        List list = new ArrayList();
        for (String query : queries) {

//            Long startTime = exchange.getIn().getHeader(START_TIME_QUERY_PROP, Long.class);
//            Long ttl = exchange.getIn().getHeader(TTL_QUERY_PROP, Long.class);
            String auth = exchange.getIn().getHeader(CONF_QUERY_AUTH, String.class);
            Boolean infer = exchange.getIn().getHeader(CONF_INFER, Boolean.class);

            Object output = performSelect(query, auth, infer);
            if (queries.size() == 1) {
                exchange.getOut().setBody(output);
                return;
            } else
                list.add(output);

        }
        exchange.getOut().setBody(list);
    }

    protected Object performSelect(String query, String auth, Boolean infer) throws RepositoryException, MalformedQueryException, QueryEvaluationException, TupleQueryResultHandlerException {
        TupleQuery tupleQuery = connection.prepareTupleQuery(
                QueryLanguage.SPARQL, query);
        if (auth != null && auth.length() > 0)
            tupleQuery.setBinding(CONF_QUERY_AUTH, valueFactory.createLiteral(auth));
        if (infer != null)
            tupleQuery.setBinding(CONF_INFER, valueFactory.createLiteral(infer));
        if (CbSailEndpoint.CbSailOutput.BINARY.equals(queryOutput)) {
            final List listOutput = new ArrayList();
            TupleQueryResultHandlerBase handler = new TupleQueryResultHandlerBase() {
                @Override
                public void handleSolution(BindingSet bindingSet) throws TupleQueryResultHandlerException {
                    Map<String, String> map = new HashMap<String, String>();
                    for (String s : bindingSet.getBindingNames()) {
                        map.put(s, bindingSet.getBinding(s).getValue().stringValue());
                    }
                    listOutput.add(map);
                }
            };
            tupleQuery.evaluate(handler);
            return listOutput;
        } else if (CbSailEndpoint.CbSailOutput.XML.equals(queryOutput)) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            SPARQLResultsXMLWriter sparqlWriter = new SPARQLResultsXMLWriter(baos);
            tupleQuery.evaluate(sparqlWriter);
            return new String(baos.toByteArray());
        } else {
            throw new IllegalArgumentException("Query Output[" + queryOutput + "] is not recognized");
        }
    }

//    protected Object performConstruct(String query, Long ttl, Long startTime) throws RepositoryException, MalformedQueryException, QueryEvaluationException, TupleQueryResultHandlerException, RDFHandlerException {
//        GraphQuery tupleQuery = connection.prepareGraphQuery(
//                QueryLanguage.SPARQL, query);
//        if (ttl != null && ttl > 0)
//            tupleQuery.setBinding("ttl", valueFactory.createLiteral(ttl));
//        if (startTime != null && startTime > 0)
//            tupleQuery.setBinding("startTime", valueFactory.createLiteral(startTime));
//        if (CbSailEndpoint.CbSailOutput.BINARY.equals(queryOutput)) {
//            throw new IllegalArgumentException("In Graph Construct mode, cannot return Java object");
//        } else if (CbSailEndpoint.CbSailOutput.XML.equals(queryOutput)) {
//            ByteArrayOutputStream baos = new ByteArrayOutputStream();
//            RDFXMLWriter rdfWriter = new RDFXMLWriter(baos);
//            tupleQuery.evaluate(rdfWriter);
//            return new String(baos.toByteArray());
//        } else {
//            throw new IllegalArgumentException("Query Output[" + queryOutput + "] is not recognized");
//        }
//    }

    @Override
    protected void doStart() throws Exception {
        CbSailEndpoint cbSailEndpoint = (CbSailEndpoint) getEndpoint();
        connection = cbSailEndpoint.getSailRepository().getConnection();
    }

    @Override
    protected void doStop() throws Exception {
        connection.close();
    }
}


text:
// ASM: a very small and fast Java bytecode manipulation framework
// Copyright (c) 2000-2011 INRIA, France Telecom
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
// 3. Neither the name of the copyright holders nor the names of its
//    contributors may be used to endorse or promote products derived from
//    this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
package org.objectweb.asm.tree;

import java.util.Map;
import org.objectweb.asm.Handle;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;

/**
 * A node that represents an invokedynamic instruction.
 *
 * @author Remi Forax
 */
public class InvokeDynamicInsnNode extends AbstractInsnNode {

  /** The method's name. */
  public String name;

  /** The method's descriptor (see {@link org.objectweb.asm.Type}). */
  public String desc;

  /** The bootstrap method. */
  public Handle bsm;

  /** The bootstrap method constant arguments. */
  public Object[] bsmArgs;

  /**
   * Constructs a new {@link InvokeDynamicInsnNode}.
   *
   * @param name the method's name.
   * @param descriptor the method's descriptor (see {@link org.objectweb.asm.Type}).
   * @param bootstrapMethodHandle the bootstrap method.
   * @param bootstrapMethodArguments the bootstrap method constant arguments. Each argument must be
   *     an {@link Integer}, {@link Float}, {@link Long}, {@link Double}, {@link String}, {@link
   *     org.objectweb.asm.Type} or {@link Handle} value. This method is allowed to modify the
   *     content of the array so a caller should expect that this array may change.
   */
  public InvokeDynamicInsnNode(
      final String name,
      final String descriptor,
      final Handle bootstrapMethodHandle,
      final Object... bootstrapMethodArguments) { // NOPMD(ArrayIsStoredDirectly): public field.
    super(Opcodes.INVOKEDYNAMIC);
    this.name = name;
    this.desc = descriptor;
    this.bsm = bootstrapMethodHandle;
    this.bsmArgs = bootstrapMethodArguments;
  }

  @Override
  public int getType() {
    return INVOKE_DYNAMIC_INSN;
  }

  @Override
  public void accept(final MethodVisitor methodVisitor) {
    methodVisitor.visitInvokeDynamicInsn(name, desc, bsm, bsmArgs);
    acceptAnnotations(methodVisitor);
  }

  @Override
  public AbstractInsnNode clone(final Map<LabelNode, LabelNode> clonedLabels) {
    return new InvokeDynamicInsnNode(name, desc, bsm, bsmArgs).cloneAnnotations(this);
  }
}


text:
WatiN
=====

Web Application Testing In .NET

WatiN

WatiN.org


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

<title>Uses of Interface org.apache.cassandra.cql3.Term.Raw (apache-cassandra API)</title>
<meta name="date" content="2015-08-28">
<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
org.apache.cassandra.cql3.Term.Raw

Packages that use Term.Raw

Package
Description

org.apache.cassandra.cql3

org.apache.cassandra.cql3.functions

org.apache.cassandra.cql3.statements

Uses of Term.Raw in org.apache.cassandra.cql3

Subinterfaces of Term.Raw in org.apache.cassandra.cql3

Modifier and Type
Interface and Description

static interface
Term.MultiColumnRaw

Classes in org.apache.cassandra.cql3 that implement Term.Raw

Modifier and Type
Class and Description

static class
AbstractMarker.INRaw

A raw placeholder for multiple values of the same type for a single column.

static class
AbstractMarker.Raw

A parsed, but non prepared, bind marker.

static class
Constants.Literal

static class
Lists.Literal

static class
Maps.Literal

static class
Sets.Literal

static class
Tuples.INRaw

A raw marker for an IN list of tuples, like "SELECT ...

static class
Tuples.Literal

A raw, literal tuple.

static class
Tuples.Raw

A raw placeholder for a tuple of values for different multiple columns, each of which may have a different type.

class
TypeCast

static class
UserTypes.Literal

Fields in org.apache.cassandra.cql3 declared as Term.Raw

Modifier and Type
Field and Description

static Term.Raw
Constants.NULL_LITERAL

Term.Raw
Attributes.Raw.timestamp

Term.Raw
Attributes.Raw.timeToLive

Fields in org.apache.cassandra.cql3 with type parameters of type Term.Raw

Modifier and Type
Field and Description

java.util.List<Pair<Term.Raw,Term.Raw>>
Maps.Literal.entries

java.util.List<Pair<Term.Raw,Term.Raw>>
Maps.Literal.entries

java.util.Map<ColumnIdentifier,Term.Raw>
UserTypes.Literal.entries

Methods in org.apache.cassandra.cql3 that return Term.Raw

Modifier and Type
Method and Description

Term.Raw
SingleColumnRelation.getMapKey()

protected abstract Term.Raw
Json.Prepared.getRawTermForColumn(ColumnDefinition def)

Methods in org.apache.cassandra.cql3 with parameters of type Term.Raw

Modifier and Type
Method and Description

static ColumnCondition.Raw
ColumnCondition.Raw.collectionCondition(Term.Raw value,
                   Term.Raw collectionElement,
                   Operator op)

A condition on a collection element.

static ColumnCondition.Raw
ColumnCondition.Raw.collectionInCondition(Term.Raw collectionElement,
                     AbstractMarker.INRaw inMarker)

An IN condition on a collection element with a single marker.

static ColumnCondition.Raw
ColumnCondition.Raw.collectionInCondition(Term.Raw collectionElement,
                     java.util.List<Term.Raw> inValues)

An IN condition on a collection element.

static ColumnCondition.Raw
ColumnCondition.Raw.simpleCondition(Term.Raw value,
               Operator op)

A condition on a column.

protected Term
MultiColumnRelation.toTerm(java.util.List<? extends ColumnSpecification> receivers,
      Term.Raw raw,
      java.lang.String keyspace,
      VariableSpecifications boundNames)

protected abstract Term
Relation.toTerm(java.util.List<? extends ColumnSpecification> receivers,
      Term.Raw raw,
      java.lang.String keyspace,
      VariableSpecifications boundNames)

Converts the specified Raw into a Term.

protected Term
SingleColumnRelation.toTerm(java.util.List<? extends ColumnSpecification> receivers,
      Term.Raw raw,
      java.lang.String keyspace,
      VariableSpecifications boundNames)

protected Term
TokenRelation.toTerm(java.util.List<? extends ColumnSpecification> receivers,
      Term.Raw raw,
      java.lang.String keyspace,
      VariableSpecifications boundNames)

Method parameters in org.apache.cassandra.cql3 with type arguments of type Term.Raw

Modifier and Type
Method and Description

static ColumnCondition.Raw
ColumnCondition.Raw.collectionInCondition(Term.Raw collectionElement,
                     java.util.List<Term.Raw> inValues)

An IN condition on a collection element.

static SingleColumnRelation
SingleColumnRelation.createInRelation(ColumnIdentifier.Raw entity,
                java.util.List<Term.Raw> inValues)

static ColumnCondition.Raw
ColumnCondition.Raw.simpleInCondition(java.util.List<Term.Raw> inValues)

An IN condition on a column.

protected java.util.List<Term>
Relation.toTerms(java.util.List<? extends ColumnSpecification> receivers,
       java.util.List<? extends Term.Raw> raws,
       java.lang.String keyspace,
       VariableSpecifications boundNames)

Converts the specified Raw terms into a Terms.

Constructors in org.apache.cassandra.cql3 with parameters of type Term.Raw

Constructor and Description

Addition(Term.Raw value)

ElementDeletion(ColumnIdentifier.Raw id,
               Term.Raw element)

Prepend(Term.Raw value)

SetElement(Term.Raw selector,
          Term.Raw value)

SetValue(Term.Raw value)

SingleColumnRelation(ColumnIdentifier.Raw entity,
                    Operator type,
                    Term.Raw value)

Creates a new relation.

SingleColumnRelation(ColumnIdentifier.Raw entity,
                    Term.Raw mapKey,
                    Operator type,
                    Term.Raw value)

Creates a new relation.

Substraction(Term.Raw value)

TokenRelation(java.util.List<ColumnIdentifier.Raw> entities,
             Operator type,
             Term.Raw value)

TypeCast(CQL3Type.Raw type,
        Term.Raw term)

Constructor parameters in org.apache.cassandra.cql3 with type arguments of type Term.Raw

Constructor and Description

Literal(java.util.List<Pair<Term.Raw,Term.Raw>> entries)

Literal(java.util.List<Pair<Term.Raw,Term.Raw>> entries)

Literal(java.util.List<Term.Raw> elements)

Literal(java.util.List<Term.Raw> elements)

Literal(java.util.List<Term.Raw> elements)

Literal(java.util.Map<ColumnIdentifier,Term.Raw> entries)

Uses of Term.Raw in org.apache.cassandra.cql3.functions

Classes in org.apache.cassandra.cql3.functions that implement Term.Raw

Modifier and Type
Class and Description

static class
FunctionCall.Raw

Constructor parameters in org.apache.cassandra.cql3.functions with type arguments of type Term.Raw

Constructor and Description

Raw(FunctionName name,
   java.util.List<Term.Raw> terms)

Uses of Term.Raw in org.apache.cassandra.cql3.statements

Constructors in org.apache.cassandra.cql3.statements with parameters of type Term.Raw

Constructor and Description

CreateAggregateStatement(FunctionName functionName,
                        java.util.List<CQL3Type.Raw> argRawTypes,
                        java.lang.String stateFunc,
                        CQL3Type.Raw stateType,
                        java.lang.String finalFunc,
                        Term.Raw ival,
                        boolean orReplace,
                        boolean ifNotExists)

RawStatement(CFName cfName,
            SelectStatement.Parameters parameters,
            java.util.List<RawSelector> selectClause,
            java.util.List<Relation> whereClause,
            Term.Raw limit)

Constructor parameters in org.apache.cassandra.cql3.statements with type arguments of type Term.Raw

Constructor and Description

ParsedInsert(CFName name,
            Attributes.Raw attrs,
            java.util.List<ColumnIdentifier.Raw> columnNames,
            java.util.List<Term.Raw> columnValues,
            boolean ifNotExists)

A parsed INSERT statement.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2015 The Apache Software Foundation


text:
package org.camunda.connect.httpclient.impl;

import org.camunda.connect.httpclient.HttpConnector;
import org.camunda.connect.httpclient.HttpConnectorProvider;

public class HttpConnectorProviderImpl implements HttpConnectorProvider {

  public String getConnectorId() {
    return HttpConnector.ID;
  }

  public HttpConnector createConnectorInstance() {
    return new HttpConnectorImpl(HttpConnector.ID);
  }

}


text:
<?php
/**
 * Class WooCommerce Product Importer
 *
 * Import products into WooCommerce: add images, variations, categories, upsells, crosssells
 *
 * @class       WooCommerce_Product_Importer
 * @version     1.2.3
 * @author      Etienne Tremel
 * Last Update: 23/01/2014
 */
if ( ! class_exists( 'WooCommerce_Product_Importer' ) ) {
    class WooCommerce_Product_Importer {

        public $errors;

        function __construct() {
            $this->errors = new WP_Error();
        }

        /**
         * ADD PRODUCT
         *
         * Add product to WooCommerce, if product exist (SKU already used), return product id
         *
         * Check $default_args for datas
         * You can add custom field by adding new row into metas, ie:
         * $args = array( ..., 'metas'   => array( ... 'my-custom-meta-key' => 'value', ... ) )
         *
         * @access public
         * @param  array     Product details
         * @return integer   Product ID
         */
        public function add_product( $args, $update_if_sku_exist = false ) {
            global $wpdb;

            $current_user = wp_get_current_user();

            $default_args = array(
                'user_id'            => '',
                'name'               => '',
                'slug'               => '',
                'status'             => 'publish',
                'description'        => '',
                'excerpt'            => '',
                'tags'               => array(),
                'images'             => array(),
                'categories'         => array(),
                'fetch_image_type'   => 'remote', // Remote url (ext), by IDs or Title (already in DB)
                'type'               => 'simple',
                'metas'              => array(
                    '_sku'                      => '',
                    '_regular_price'            => '',
                    '_sale_price'               => '',
                    '_sale_price_dates_from'    => '',
                    '_sale_price_dates_to'      => '',
                    '_manage_stock'             => 'yes',
                    '_sold_individually'        => '',
                    '_stock'                    => '',
                    '_visibility'               => 'visible',
                    '_tax_status'               => '',
                    '_tax_class'                => '',
                    '_featured'                 => 'no',
                    '_backorders'               => 'no',
                    '_virtual'                  => 'no',
                    '_downloadable'             => 'no',
                    '_height'                   => '',
                    '_length'                   => '',
                    '_weight'                   => '',
                    '_width'                    => '',
                    '_thumbnail_id'             => null,
                    '_purchase_note'            => '',
                    '_product_attributes'       => array()
                )
            );
            $args = self::parse_args_r( $args, $default_args );

            if ( empty( $args['user_id'] ) )
                $args['user_id'] = $current_user->ID;

            if ( empty( $args['metas']['_sku'] ) )
                return $this->errors->add( 'product', 'SKU is missing' );

            if ( empty( $args['slug'] ) )
                $args['slug'] = $args['name'];

            // Check if the product is already in the DB
            $product_id_in_db = $this->product_exist( $args['metas']['_sku'] );

            // Prepare post before insertion
            $product = array(
                'post_author'       => $args['user_id'],
                'post_title'        => $args['name'],
                'post_name'         => sanitize_title( $args['slug'] ),
                'post_status'       => $args['status'],
                'comment_status'    => 'closed',
                'ping_status'       => 'closed',
                'post_content'      => $args['description'],
                'post_excerpt'      => $args['excerpt'],
                'post_type'         => 'product'
            );

            // If product exist in DB, update
            if ( $update_if_sku_exist && $product_id_in_db ) {
                $product['ID'] = $product_id_in_db;
                $product_id = wp_update_post( $product );
            } else {
                $product_id = wp_insert_post( $product, true );
            }

            if ( ! $product_id )
                return $product_id;

            // Set stock status
            if ( is_numeric( $args['metas']['_stock'] ) && $args['metas']['_stock'] === 0 )
                $args['metas']['_stock_status'] = 'outofstock';
            else
                $args['metas']['_stock_status'] = 'instock';

            $args['metas']['_price'] = $args['metas']['_regular_price'];

            // Set metas:
            foreach ( $args['metas'] as $key => $value )
                if ( $value != null || ( is_array( $value ) && count( $value ) > 0 ) )
                    update_post_meta( $product_id, $key, $value );

            // Set tags
            wp_set_object_terms( $product_id, array_map( 'trim', $args['tags'] ), 'product_tag' );

            // Set product as simple
            wp_set_object_terms( $product_id, $args['type'], 'product_type' );

            // Add images
            self::add_image_to_product( $product_id, $args['images'], $args['fetch_image_type'] );

            // Associate to category
            self::add_product_to_category( $product_id, $args['categories'] );

            return $product_id;
        }

        /**
         * DELETE PRODUCT
         *
         * Delete product and all its data
         *
         * Move product with ID = 25 to the trash
         * delete_product( 'product_id=25' )
         *
         * Delete definitively a product with SKU = 00012ES
         * delete_product( 'sku=00012ES', true )
         *
         * @access  public
         * @param   array     $args            Check $default_args for datas
         *          boolean   $force_delete    Whether to bypass trash and force deletion
         * @return  boolean                    Return true if product has been deleted, false if not
         */
        public function delete_product( $args, $force_delete = false ) {
            global $wpdb;

            $default_args = array(
                'sku'           => null,
                'product_id'    => null
            );

            $args = wp_parse_args( $args, $default_args );
            extract( $args, EXTR_SKIP );

            // Check if product exist
            if ( $sku )
                $product_id = $this->product_exist( $sku );

            if ( ! $product_id || is_null( $product_id ) )
                return false;

            // Delete post meta
            if ( $force_delete ) {
                $post_meta = get_post_custom( $product_id );

                if ( $post_meta )
                    foreach ( $post_meta as $key => $value )
                        delete_post_meta( $product_id, $key );
            }

            wp_delete_post( $product_id, $force_delete );

            return true;
        }

        /**
         * ADD IMAGE TO PRODUCT
         *
         * Add image to a specific product. Image can be present fetched from a remote server or already in the DB
         *
         * Fetch via remote server:
         * add_image_to_product( 12, array( 'http://remote.com/image-1.jpg', 'http://remote.com/image-1.jpg' ) );
         *
         * Image already in DB, association via title:
         * add_image_to_product( 12, array( 'image-1', 'image-2' ) );
         *
         * Image already in DB, association via ID:
         * add_image_to_product( 12, array( 4, 5 ) );
         *
         * @access public
         * @param  integer   $product_id    Product ID
         *         array     $images        Image list to associate with defined product. First element in array is the featured image.
         *         string    $fetch         Default: remote
         *                                  - 'remote':  image downloaded from a remote server
         *                                  - 'title':   image is already in DB, make association via Attachment Title
         *                                  - 'id':      image is already in DB, make association via Attachment ID
         * @return integer   Product ID
         */
        public function add_image_to_product( $product_id, $images = array(), $fetch = 'remote' ) {

            // Clean array:
            $images = array_values( array_filter( $images ) );

            $image_ids = array();

            $previous_image_name = '';

            foreach ( $images as $index => $image ) {
                switch ( $fetch ) {
                    case 'remote':
                        // Define image name
                        $name = apply_filters( 'woocommerce-product-importer-image-name', preg_replace( '/\.[^.]+$/', '', basename( $image ) ), $image, $product_id, $images, $previous_image_name );

                        // If name not defined, make one:
                        if ( $name == '' )
                            $name = get_the_title( $product_id );

                        // Append index to the end of the name if multiple images with same name
                        if ( $name == $previous_image_name )
                            $name .= '_' . $index;

                        $previous_image_name = $name;

                        $slug = sanitize_title( $name );

                        // Check if image is in DB
                        $attachment_in_db = get_page_by_title( $slug, 'OBJECT', 'attachment' );
                        $attachment_in_db = apply_filters( 'woocommerce-product-importer-image-in-db', $attachment_in_db, $name );

                        // Is attachment already in DB?
                        if ( $attachment_in_db ) {

                            // push attachment ID
                            $image_ids[] = $attachment_in_db->ID;

                        } else {

                            $get = wp_remote_get( $image, array( 'timeout'  => 60 ) );
                            $type = wp_remote_retrieve_header( $get, 'content-type' );

                            if ( ! $type ) {
                                $this->errors->add( 'add_image_to_product', 'Mime type not found: ' . $image );
                                continue;
                            }

                            $mime_types = array(
                                'image/jpg'     => 'jpg',
                                'image/jpeg'    => 'jpg',
                                'image/gif'     => 'gif',
                                'image/png'     => 'png'
                            );

                            if ( isset( $mime_types[ $type ] ) ) {
                                $extension = $mime_types[ $type ];
                            } else {
                                $this->errors->add( 'add_image_to_product', 'Mime type ' . $type . ' invalid: ' . $image );
                                continue;
                            }

                            $uploaded = wp_upload_bits( $slug . '.' . $extension, null, wp_remote_retrieve_body( $get ) );

                            if ( $uploaded['error'] ) {
                                $this->errors->add( 'add_image_to_product', $uploaded['error'] . ' Image:' . $image );
                                continue;
                            }

                            $attachment = array(
                                'guid'              => $uploaded['url'],
                                'post_title'        => $slug,
                                'post_mime_type'    => $type
                            );
                            $attach_id = wp_insert_attachment( $attachment, $uploaded['file'], $product_id );

                            if ( ! function_exists( 'wp_generate_attachment_metadata' ) )
                                require_once( ABSPATH . 'wp-admin/includes/image.php' );

                            $attach_data = wp_generate_attachment_metadata( $attach_id, $uploaded['file'] );
                            wp_update_attachment_metadata( $attach_id, $attach_data );

                            $image_ids[] = $attach_id;

                        }
                        break;

                    case 'title':
                        $image_name = preg_replace( '/([^.]+)\.(jpg|gif|png|bmp|tga)/', '$1', $image );
                        if ( ! is_null( $image_name ) ) {
                            $db_image = get_page_by_title( $image_name, OBJECT, 'attachment' );
                            if ( ! is_null( $db_image ) ) {
                                // Set featured image
                                if ( 0 == $index )
                                    set_post_thumbnail( $product_id, $db_image->ID );

                                $image_ids[] = $db_image->ID;
                            } else {
                                $this->errors->add( 'add_image_to_product', 'Image missing in DB' );
                                continue;
                            }
                        }
                        break;

                    case 'id':
                        $image_ids[] = $image;
                        break;
                }
            }

            // Set featured image & product image gallery
            if ( count( $image_ids ) > 0 ) {
                set_post_thumbnail( $product_id, $image_ids[0] );

                // Associate images as gallery
                update_post_meta( $product_id, '_product_image_gallery', implode( ',', $image_ids ) );
            }
        }

        /**
         * ADD PRODUCT TO CATEGORY
         *
         * Create the category with parents if not defined
         *
         * Usage with single category:
         * add_product_to_category( 12, 'My category name' );
         *
         * Usage with multiple categories:
         * add_product_to_category( 12, array(
         *     'My first category',
         *     'My second category'
         * ) );
         *
         * Usage with hierarchical categories:
         * add_product_to_category( 12, array(
         *     array(
         *         'My category',
         *         'My sub category',
         *         'My sub sub category'
         *     )
         * ) );
         *
         * @access public
         * @param  integer   $product_id    Product ID
         *         array     $categories    Category
         * @return void
         */

        public function add_product_to_category( $product_id, $categories ) {

            $category_in = array();

            // Temporarily disable terms count updates
            wp_defer_term_counting( true );

            // Check if single
            if ( ! is_array( $categories ) )
                $categories = array( $category );

            // Multiple
            foreach( $categories as $category ) {
                if ( is_array( $category ) ) {
                    // Hierarchical
                    $parent = 0;
                    foreach ( $category as $sub_category ) {

                        if ( is_numeric( $sub_category ) )
                            $category_id = $sub_category;
                        else
                            $category_id = self::add_category( array(
                                'name'      => $sub_category,
                                'parent'    => $parent
                            ) );

                        if ( ! is_wp_error( $category_id ) ) {
                            $parent = $category_id;
                            $category_in[] = $category_id;
                        }
                    }
                } else {
                    // Single category
                    if ( is_numeric( $category ) )
                        $category_id = $category;
                    else
                        $category_id = self::add_category( array(
                            'name'  => $category
                        ) );

                    if ( ! is_wp_error( $category_id ) )
                        $category_in[] = $category_id;
                }
            }

            if ( ! count( $category_in ) )
                return;

            // Make sure the terms IDs is integers:
            $category_in = array_map( 'intval', $category_in );
            $category_in = array_unique( $category_in );

            // Set categories id to Product
            wp_set_object_terms( $product_id, $category_in, 'product_cat' );

            // check out http://wordpress.stackexchange.com/questions/24498/wp-insert-term-parent-child-problem
            delete_option( 'product_cat_children' );

            // Re-enable terms count updates
            wp_defer_term_counting( false );

            // Update number of post associated to the category:
            wp_update_term_count_now( $category_in, 'product_cat' );
        }

        /**
         * ADD VARIATION TO PRODUCT
         *
         * Usage:
         *   add_variation_to_product( 12, array(
         *       'name'   => Color',
         *       'values' => array(
         *           'Blue'  => array(
         *               '_sku'              => 'P678',
         *               '_manage_stock'     => 'yes',
         *               '_regular_price'    => '20.00',
         *               '_sale_price'       => '12.00',
         *               '_visibility'       => 'visible',
         *               '_tax_status'       => 'taxable',
         *               '_backorders'       => 'no',
         *               '_virtual'          => 'no',
         *               '_downloadable'     => 'no',
         *               '_stock'            => '',
         *               '_weight'           => '',
         *               '_length'           => '',
         *               '_width'            => '',
         *               '_height'           => '',
         *               '_thumbnail_id'     => ''
         *           ),
         *           'Red'   => array(
         *               '_sku'              => 'P679',
         *               '_manage_stock'     => 'yes',
         *               '_regular_price'    => '20.00',
         *               '_sale_price'       => '12.00',
         *               '_visibility'       => 'visible',
         *               '_tax_status'       => 'taxable',
         *               '_backorders'       => 'no',
         *               '_virtual'          => 'no',
         *               '_downloadable'     => 'no',
         *               '_stock'            => '',
         *               '_weight'           => '',
         *               '_length'           => '',
         *               '_width'            => '',
         *               '_height'           => '',
         *               '_thumbnail_id'     => ''
         *           )
         *   ) );
         *
         * @access public
         * @param  integer   $product_id    Product ID
         *         array     $args          List of variations
         * @return void
         */
        public function add_variation_to_product( $product_id, $args ) {

            $default = array(
                'name'      => '',
                'values'    => array()
            );

            $args = wp_parse_args( $args, $default );

            $taxonomy = 'pa_' . sanitize_title_with_dashes( $args['name'] );

            // Clear existing values
            wp_set_object_terms( $product_id, NULL, $taxonomy );

            // Explode attributes and remove first and last white space
            $attributes_ids = array();

            // Fetch post to duplicate
            $post_to_duplicate = get_post( $product_id );

            $variation = array(
                'post_author'       => $post_to_duplicate->post_author,
                'post_title'        => $post_to_duplicate->post_title,
                'post_name'         => $post_to_duplicate->post_name,
                'post_status'       => $post_to_duplicate->post_status,
                'comment_status'    => $post_to_duplicate->comment_status,
                'ping_status'       => $post_to_duplicate->ping_status,
                'post_content'      => $post_to_duplicate->post_content,
                'post_excerpt'      => $post_to_duplicate->post_excerpt,
                'post_type'         => 'product_variation',
                'post_parent'       => $product_id
            );

            $default_metas = array(
                '_sku'              => null,
                '_regular_price'    => null,
                '_sale_price'       => null,
                '_manage_stock'     => null,
                '_stock'            => null,
                '_regular_price'    => null,
                '_visibility'       => null,
                '_tax_status'       => null,
                '_backorders'       => null,
                '_virtual'          => null,
                '_downloadable'     => null,
                '_thumbnail_id'     => null,
                '_weight'           => null,
                '_length'           => null,
                '_width'            => null,
                '_height'           => null,
                '_thumbnail_id'     => null
            );

            foreach ( $args['values'] as $variation_name => $metas ) {

                // Define new variation name:
                $variation['post_name'] .= sanitize_title( $variation_name );

                // If product exist get ID, or insert
                $variation_id = wp_insert_post( $variation );

                /* DUPLICATE PRODUCT META */
                global $wpdb;

                // Fetch product meta
                $product_meta = $wpdb->get_results( $wpdb->prepare( "SELECT meta_key, meta_value FROM $wpdb->postmeta WHERE post_id = %d", $product_id ) );

                // If metas exist
                if ( sizeof( $product_meta ) > 0 ) {

                    $metas = wp_parse_args( $metas, $default_metas );

                    // Update metas
                    foreach ( $product_meta as $col )
                        if ( in_array( $col->meta_key, $metas ) && $metas->meta_value != null )
                            update_post_meta( $variation_id, $col->meta_key, $col->meta_value );

                    // Set new attribute to post
                    update_post_meta( $variation_id, 'attribute_' . $taxonomy, sanitize_title( $variation_name ) );
                }

                $attribute = term_exists( $variation_name, $taxonomy );

                // Check attribute taxonomie exist
                if ( ! is_array( $attribute ) ) {
                    $args = array(
                        'slug'  => sanitize_title( $variation_name )
                    );
                    $attribute = wp_insert_term( $term, $taxonomy, $args );
                }

                //Set attribute to duplicated product
                wp_set_object_terms( $variation_id, (int)$attribute['term_id'], $taxonomy, true );

                $attributes_ids[] = $attribute['term_id'];
            }

            // Make sure the terms IDs is integers:
            $attributes_ids = array_map( 'intval', $attributes_ids );
            $attributes_ids = array_unique( $attributes_ids );

            // Make product as variable
            wp_set_object_terms( $product_id, 'variable', 'product_type' );
            wp_set_object_terms( $product_id, $attributes_ids, $taxonomy, true );

            //Set attribute to product
            $post_meta = get_post_meta( $product_id, '_product_attributes', false );
            $post_meta[ $taxonomy ] = array(
                'name'          => $taxonomy,
                'position'      => 0,
                'is_variation'  => 1,
                'is_taxonomy'   => 1,
                'is_visible'    => 1
            );
            update_post_meta( $product_id, '_product_attributes', $post_meta );
        }

        /**
         * ADD CATEGORY
         *
         * Add a new category into WooCommerce, if the category already exist return Category ID
         *
         * @access public
         * @param  array     $args    Category parameters
         * @return integer            Category ID
         */
        public function add_category( $args ) {

            $default = array(
                'name'             => '',
                'slug'             => '',
                'parent'           => 0,
                'meta_title'       => '',
                'meta_keywords'    => '',
                'meta_description' => '',
                'description'      => ''
            );

            $args = wp_parse_args( $args, $default );

            if ( empty( $args['name'] ) )
                return false;

            if ( empty( $args['slug'] ) )
                $args['slug'] = sanitize_title( $args['name'] );

            $category = term_exists( $args['name'], 'product_cat' );

            if ( ! is_array( $category ) )
                $category = wp_insert_term( $args['name'], 'product_cat', array(
                    'parent'        => $args['parent'],
                    'description'   => $args['description'],
                    'slug'          => $args['slug']
                ) );

            if ( ! is_wp_error( $category ) )
                return $category['term_id'];
        }

        /**
         * ASSOCIATE UPSELLS VIA SKU
         *
         * Associate to a product a list of upsells via their SKU Code
         *
         * @access public
         * @param  integer     $product_id    Product ID
         *         array       $upsell_skus   List of upsells SKU Code
         * @return void
         */
        public function associate_upsell_sku( $product_id, $upsell_skus = array() ) {
            global $wpdb;
            $upsell_ids = array();

            foreach ( $upsell_skus as $upsell_sku ) {

                $upsell_id = $this->product_exist( $upsell_sku );

                if ( $upsell_id )
                    $upsell_ids[] = $upsell_id;
            }

            // Update DB
            update_post_meta( $product_id, '_upsell_ids', $upsell_ids );
        }

        /**
         * ASSOCIATE CROSSSELLS VIA SKU
         *
         * Associate to a product a list of crosssells via their SKU Code
         *
         * @access public
         * @param  integer     $product_id    Product ID
         *         array       $upsell_skus   List of crosssell SKU Code
         * @return void
         */
        public function associate_crosssell_sku( $product_id, $crosssell_skus = array() ) {
            global $wpdb;
            $crosssell_ids = array();

            foreach ( $crosssell_skus as $crosssell_sku ) {
                $crosssell_id = $this->product_exist( $crosssell_sku );

                if ( $crosssell_id )
                    $crosssell_ids[] = $crosssell_id;
            }

            // Update DB
            update_post_meta( $product_id, '_crosssell_ids', $crosssell_ids );
        }

        /**
         * PRODUCT EXIST
         *
         * Check in the DB if a product has already a given SKU code
         *
         * @access public
         * @param  string   $sku            SKU code
         * @return mixed    $product_id     Return product ID if exist, false if not
         */
        public function product_exist( $sku ) {
            global $wpdb;
            $product_id = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value= %s LIMIT 1", $sku ) );

            return $product_id;
        }

        /**
         * Recursive version of wp_parse_args()
         *
         * @access private
         */
        private function parse_args_r( &$a, $b ) {
            $a = (array) $a;
            $b = (array) $b;
            $r = $b;

            foreach ( $a as $k => &$v ) {
                if ( is_array( $v ) && isset( $r[ $k ] ) ) {
                    $r[ $k ] = self::parse_args_r( $v, $r[ $k ] );
                } else {
                    $r[ $k ] = $v;
                }
            }

            return $r;
        }
    }
}
?>


text:
#include "HTMLButtonElementImp.h"

#include "one_at_a_time.hpp"

constexpr auto Intern = &one_at_a_time::hash<char16_t>;

#include "HTMLUtil.h"

namespace org
{
namespace w3c
{
namespace dom
{
namespace bootstrap
{

void HTMLButtonElementImp::handleMutation(events::MutationEvent mutation)
{
    std::u16string value = mutation.getNewValue();

    switch (Intern(mutation.getAttrName().c_str())) {
    case Intern(u"disabled"):
        if (mutation.getAttrChange() != events::MutationEvent::REMOVAL)
            tabIndex = -1;
        else if (!toInteger(getAttribute(u"tabindex"), tabIndex))
            tabIndex = 0;
        break;
    case Intern(u"tabindex"):
        if (!getDisabled() && !toInteger(value, tabIndex))
            tabIndex = 0;
        break;
    default:
        HTMLFormControlImp::handleMutation(mutation);
        break;
    }
}

}
}
}
}


text: export * from './alternative.class';


text:
@implementation DRYBlockResponder {
    ResultBlock _resultBlock;
    ErrorBlock _errorBlock;
    StatusBlock _statusBlock;
}

- (id)initWithResultBlock:(ResultBlock)resultBlock andErrorBlock:(ErrorBlock)errorBlock {
    self = [super init];
    if (self) {
        _resultBlock = [resultBlock copy];
        _errorBlock = [errorBlock copy];
    }
    return self;
}

- (id)initWithResultBlock:(ResultBlock)resultBlock andErrorBlock:(ErrorBlock)errorBlock andStatusBlock:(StatusBlock)statusBlock {
    self = [self initWithResultBlock:resultBlock andErrorBlock:errorBlock];
    if (self) {
        _statusBlock = [statusBlock copy];
    }
    return self;
}

- (void)handleResult:(id)result {
    [self _executeBlockOnAppropriateQueue:^{
        _resultBlock(result);
    }];
}

- (void)handleError:(NSError *)error {
    [self _executeBlockOnAppropriateQueue:^{
        _errorBlock(error);
    }];
}

- (void)handleStatus:(NSUInteger)status withUserInfo:(NSDictionary *)userInfo {
    if (_statusBlock) {
        [self _executeBlockOnAppropriateQueue:^{
            _statusBlock(status, userInfo);
        }];
    }
}

- (void)_executeBlockOnAppropriateQueue:(void (^)())blockToCall {
    if ([self _completionShouldHappenOnMainThread]) {
        blockToCall();
    } else {
        dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
            blockToCall();
        });
    }
}

- (BOOL) _completionShouldHappenOnMainThread {
    return  [NSThread isMainThread] && (self.completionQueue == dispatch_get_main_queue() || self.completionQueue == nil);
}

@end


text:
package gov.healthit.chpl.app;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.naming.spi.InitialContextFactory;
import javax.naming.spi.InitialContextFactoryBuilder;

class LocalContext extends InitialContext implements InitialContextFactoryBuilder, InitialContextFactory {

	Map<Object,Object> dataSources;

	LocalContext() throws NamingException {
		super();
		dataSources = new HashMap<Object,Object>();
	}

	public void addDataSource(String name, String connectionString, String username, String password) {
		this.
		dataSources.put(name, new LocalDataSource(connectionString,username,password));
	}

	public InitialContextFactory createInitialContextFactory(
			Hashtable<?, ?> hsh) throws NamingException {
		dataSources.putAll(hsh);
		return this;
	}

	public Context getInitialContext(Hashtable<?, ?> arg0)
			throws NamingException {
		return this;
	}

	@Override
	public Object lookup(String name) throws NamingException {
		Object ret = dataSources.get(name);
		return (ret != null) ? ret : super.lookup(name);
	}
}


text:
<?php

namespace Sylius\Bundle\FixturesBundle\DataFixtures\ORM;

use Doctrine\Common\Persistence\ObjectManager;
use Sylius\Bundle\FixturesBundle\DataFixtures\DataFixture;
use Sylius\Component\Core\Model\TaxRateInterface;
use Sylius\Component\Taxation\Model\TaxCategoryInterface;

/**
 * Basic taxation fixtures.
 *
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
class LoadTaxationData extends DataFixture
{
    /**
     * {@inheritdoc}
     */
    public function load(ObjectManager $manager)
    {
        $taxableGoods = $this->createTaxCategory('Taxable goods', 'Default taxation category');

        $manager->persist($taxableGoods);
        $manager->flush();

        $taxRate = $this->createTaxRate('EU VAT', 'EU', 0.23);
        $taxRate->setCategory($taxableGoods);

        $manager->persist($taxRate);
        $manager->flush();

        $taxableGoods->addRate($this->createTaxRate('US Sales Tax', 'USA', 0.08));
        $taxRate->setCategory($taxableGoods);

        $manager->persist($taxRate);
        $manager->flush();

        $taxableGoods->addRate($this->createTaxRate('No tax', 'Rest of World', 0.00));
        $taxRate->setCategory($taxableGoods);

        $manager->persist($taxRate);
        $manager->flush();
    }

    /**
     * {@inheritdoc}
     */
    public function getOrder()
    {
        return 3;
    }

    /**
     * Create tax category.
     *
     * @param string $name
     * @param string $description
     *
     * @return TaxCategoryInterface
     */
    protected function createTaxCategory($name, $description)
    {
        /* @var $category TaxCategoryInterface */
        $category = $this->getTaxCategoryRepository()->createNew();
        $category->setName($name);
        $category->setDescription($description);

        $this->setReference('Sylius.TaxCategory.'.$name, $category);

        return $category;
    }

    /**
     * Create tax rate.
     *
     * @param string  $name
     * @param string  $zoneName
     * @param float   $amount
     * @param Boolean $includedInPrice
     * @param string  $calculator
     *
     * @return TaxRateInterface
     */
    protected function createTaxRate($name, $zoneName, $amount, $includedInPrice = false, $calculator = 'default')
    {
        /* @var $rate TaxRateInterface */
        $rate = $this->getTaxRateRepository()->createNew();
        $rate->setName($name);
        $rate->setZone($this->getZoneByName($zoneName));
        $rate->setAmount($amount);
        $rate->setIncludedInPrice($includedInPrice);
        $rate->setCalculator($calculator);

        $this->setReference('Sylius.TaxRate.'.$name, $rate);

        return $rate;
    }
}


text:
describe("Test du payerService", function() {

	var mockPaiement = {user_id: "1",panier:{id :1,libelle:"Produit 1",prix :150,quantite:3},paiement: { numero: "numero1",date_validite: {month: 4,year: 2016},crypto: 103},prix_total: 450,type_paiement: "CB"};
	var mockPaiement2 = {user_id:"1",panier:{id :1,libelle:"Produit 1",prix :150,quantite:2},prix_total:300,type_paiement : "Chèque"};
	var totalPrix = 0;

    beforeEach(function() {
		module("ecMobileApp.magasin");
	});

    it("Set le prix total du panier", inject(function(payerService) {
		payerService.setTotalPrix(300);
		expect(payerService.getTotalPrix()).toEqual(300);

    }));

	it("Obtenir le prix total du panier", inject(function(payerService) {
        spyOn(payerService, "getTotalPrix").and.returnValue(payerService.totalPrix);
    }));

});


text:
package com.netflix.governator;

import javax.inject.Inject;
import javax.inject.Singleton;

import com.google.inject.AbstractModule;

/**
 * When installed ShutdownHookModule will link a JVM shutdown hook to
 * LifecycleManager so that calling System.exit() will shutdown
 * it down.
 *
 * <pre>
 * {@code
 *    Governator.createInjector(new LifecycleModule(), new ShutdownHookModule());
 * }
 * </pre>
 */
public final class ShutdownHookModule extends AbstractModule {
    @Singleton
    public static class SystemShutdownHook extends Thread {
        @Inject
        public SystemShutdownHook(final LifecycleShutdownSignal shutdown) {
            Runtime.getRuntime().addShutdownHook(new Thread() {
                @Override
                public void run() {
                    shutdown.signal();
                }
            });
        }
    }

    @Override
    protected void configure() {
        bind(SystemShutdownHook.class).asEagerSingleton();
    }

    @Override
    public boolean equals(Object obj) {
        return getClass().equals(obj.getClass());
    }

    @Override
    public int hashCode() {
        return getClass().hashCode();
    }

    @Override
    public String toString() {
        return "ShutdownHookModule[]";
    }

}


text:
namespace netlib
{
	typedef std::function<void(UINT, LPARAM, WPARAM)> message_handler_t;

	NETLIB_API bool register_message_handler(int _msg, message_handler_t const& _hdlr);
	NETLIB_API void remove_message_handler(int _msg);

	NETLIB_API HANDLE completion_port();
}


text:
<?php

namespace Headplan\Events;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class Listeners implements EventSubscriberInterface
{
    private static $event;

    public function __construct($event)
    {
        $this->setEvent($event);
    }

    private function setEvent($event)
    {
        if (is_string($event)) {
            self::$event = [ $event => 'onEvent'];
        } elseif (is_string($event[0])) {
            self::$event = [ $event[0] => [
                'onEvent',
                isset($event[1]) ? $event[1] : 0
            ]];
        }
    }

    public static function getSubscribedEvents()
    {
        return self::$event;
    }
}


text:
package org.springframework.cloud.netflix.zuul.filters.post;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.lang.reflect.UndeclaredThrowableException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

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

import com.netflix.zuul.constants.ZuulHeaders;
import com.netflix.zuul.context.Debug;
import com.netflix.zuul.context.RequestContext;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;
import org.springframework.http.HttpStatus;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.web.util.WebUtils;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.X_ZUUL_DEBUG_HEADER;

/**
 * @author Spencer Gibb
 */
public class SendResponseFilterTests {

	@Before
	public void setTestRequestcontext() {
		RequestContext context = new RequestContext();
		context.setRequest(new MockHttpServletRequest());
		context.setResponse(new MockHttpServletResponse());
		context.setResponseGZipped(false);

		RequestContext.testSetCurrentContext(context);
	}

	@After
	public void reset() {
		RequestContext.getCurrentContext().clear();
	}

	@Test
	public void runsNormally() throws Exception {
		String characterEncoding = null;
		String content = "hello";
		runFilter(characterEncoding, content, false);
	}

	@Test
	public void useServlet31Works() {
		assertThat(new SendResponseFilter().isUseServlet31()).isTrue();
	}

	@Test
	public void characterEncodingNotOverridden() throws Exception {
		String characterEncoding = "UTF-16";
		String content = "\u00a5";
		runFilter(characterEncoding, content, true);
	}

	@Test
	public void runWithDebugHeader() throws Exception {
		ZuulProperties properties = new ZuulProperties();
		properties.setIncludeDebugHeader(true);

		SendResponseFilter filter = createFilter(properties, "hello", null,
				new MockHttpServletResponse(), false);
		Debug.addRoutingDebug("test");
		filter.run();

		String debugHeader = RequestContext.getCurrentContext().getResponse()
				.getHeader(X_ZUUL_DEBUG_HEADER);
		assertThat(debugHeader).as("wrong debug header").isEqualTo("[[[test]]]");
	}

	/*
	 * GZip NOT requested and NOT a GZip response -> Content-Length forwarded asis
	 */
	@Test
	public void runWithOriginContentLength() throws Exception {
		ZuulProperties properties = new ZuulProperties();
		properties.setSetContentLength(true);

		SendResponseFilter filter = createFilter(properties, "hello", null,
				new MockHttpServletResponse(), false);
		RequestContext.getCurrentContext().setOriginContentLength(6L); // for test
		RequestContext.getCurrentContext().setResponseGZipped(false);
		filter.run();

		String contentLength = RequestContext.getCurrentContext().getResponse()
				.getHeader("Content-Length");
		assertThat(contentLength).as("wrong origin content length").isEqualTo("6");
	}

	/*
	 * Unknown encoding requested and NOT a GZip response -> Content-Length forwarded asis
	 */
	@Test
	public void runWithOriginContentLength_content_encoding_header() throws Exception {
		ZuulProperties properties = new ZuulProperties();
		properties.setSetContentLength(true);

		SendResponseFilter filter = createFilter(properties, "hello", null,
				new MockHttpServletResponse(), false);
		RequestContext.getCurrentContext().addZuulResponseHeader("Content-Encoding",
				"unknown");
		RequestContext.getCurrentContext().setOriginContentLength(6L); // for test
		RequestContext.getCurrentContext().setResponseGZipped(false);
		filter.run();

		MockHttpServletResponse response = (MockHttpServletResponse) RequestContext
				.getCurrentContext().getResponse();
		assertThat(response.getHeader("Content-Length")).as("wrong origin content length")
				.isEqualTo("6");
		assertThat(response.getHeader("Content-Encoding")).isEqualTo("unknown");
	}

	/*
	 * GZip requested and GZip response -> Content-Length forwarded asis, response
	 * compressed
	 */
	@Test
	public void runWithOriginContentLength_gzipRequested_gzipResponse() throws Exception {
		ZuulProperties properties = new ZuulProperties();
		properties.setSetContentLength(true);

		SendResponseFilter filter = new SendResponseFilter(properties);

		byte[] gzipData = gzipData("hello");

		RequestContext.getCurrentContext().setOriginContentLength((long) gzipData.length); // for
		// test
		RequestContext.getCurrentContext().setResponseGZipped(true);
		RequestContext.getCurrentContext()
				.setResponseDataStream(new ByteArrayInputStream(gzipData));
		((MockHttpServletRequest) RequestContext.getCurrentContext().getRequest())
				.addHeader(ZuulHeaders.ACCEPT_ENCODING, "gzip");

		filter.run();

		MockHttpServletResponse response = (MockHttpServletResponse) RequestContext
				.getCurrentContext().getResponse();
		assertThat(response.getHeader("Content-Length"))
				.isEqualTo(Integer.toString(gzipData.length));
		assertThat(response.getHeader("Content-Encoding")).isEqualTo("gzip");
		assertThat(response.getContentAsByteArray()).isEqualTo(gzipData);

		BufferedReader reader = new BufferedReader(
				new InputStreamReader(new GZIPInputStream(
						new ByteArrayInputStream(response.getContentAsByteArray()))));
		assertThat(reader.readLine()).isEqualTo("hello");
	}

	/*
	 * GZip NOT requested and GZip response -> Content-Length discarded and response
	 * uncompressed
	 */
	@Test
	public void runWithOriginContentLength_gzipNotRequested_gzipResponse()
			throws Exception {
		ZuulProperties properties = new ZuulProperties();
		properties.setSetContentLength(true);

		SendResponseFilter filter = new SendResponseFilter(properties);

		byte[] gzipData = gzipData("hello");

		RequestContext.getCurrentContext().setOriginContentLength((long) gzipData.length); // for
		// test
		RequestContext.getCurrentContext().setResponseGZipped(true);
		RequestContext.getCurrentContext()
				.setResponseDataStream(new ByteArrayInputStream(gzipData));

		filter.run();

		MockHttpServletResponse response = (MockHttpServletResponse) RequestContext
				.getCurrentContext().getResponse();
		assertThat(response.getHeader("Content-Length")).isNull();
		assertThat(response.getHeader("Content-Encoding")).isNull();
		assertThat(response.getContentAsString()).as("wrong content").isEqualTo("hello");
	}

	/*
	 * GZip NOT requested and GZip response -> Content-Length discarded and response
	 * uncompressed
	 */
	@Test
	public void runWithOriginContentLength_gzipNotRequested_gzipResponse_content_encoding_header()
			throws Exception {
		ZuulProperties properties = new ZuulProperties();
		properties.setSetContentLength(true);

		SendResponseFilter filter = new SendResponseFilter(properties);

		byte[] gzipData = gzipData("hello");

		RequestContext.getCurrentContext().addZuulResponseHeader("Content-Encoding",
				"gzip");
		RequestContext.getCurrentContext().setOriginContentLength((long) gzipData.length); // for
																							// test
		RequestContext.getCurrentContext().setResponseGZipped(true);
		RequestContext.getCurrentContext()
				.setResponseDataStream(new ByteArrayInputStream(gzipData));

		filter.run();

		MockHttpServletResponse response = (MockHttpServletResponse) RequestContext
				.getCurrentContext().getResponse();
		assertThat(response.getHeader("Content-Length")).isNull();
		assertThat(response.getHeader("Content-Encoding")).isNull();
		assertThat(response.getContentAsString()).as("wrong content").isEqualTo("hello");
	}

	/*
	 * Origin sends a non gzip response with Content-Encoding: gzip Request does not
	 * support GZIP -> filter fails to uncompress and send stream "asis". Content-Length
	 * is NOT preserved.
	 */
	@Test
	public void invalidGzipResponseFromOrigin() throws Exception {
		ZuulProperties properties = new ZuulProperties();
		properties.setSetContentLength(true);

		SendResponseFilter filter = new SendResponseFilter(properties);

		byte[] gzipData = "hello".getBytes();

		RequestContext.getCurrentContext().setOriginContentLength((long) gzipData.length); // for
		// test
		RequestContext.getCurrentContext().setResponseGZipped(true); // say it is GZipped
		// although not
		// the case
		RequestContext.getCurrentContext()
				.setResponseDataStream(new ByteArrayInputStream(gzipData));

		filter.run();

		MockHttpServletResponse response = (MockHttpServletResponse) RequestContext
				.getCurrentContext().getResponse();
		assertThat(response.getHeader("Content-Length")).isNull();
		assertThat(response.getHeader("Content-Encoding")).isNull();
		assertThat(response.getContentAsString()).as("wrong content").isEqualTo("hello"); // response
		// sent
		// "asis"
	}

	/*
	 * Empty response from origin with Content-Encoding: gzip Request does not support
	 * GZIP -> filter should not fail in decoding the *empty* response stream
	 */
	@Test
	public void emptyGzipResponseFromOrigin() throws Exception {
		ZuulProperties properties = new ZuulProperties();
		properties.setSetContentLength(true);

		SendResponseFilter filter = new SendResponseFilter(properties);

		byte[] gzipData = new byte[] {};

		RequestContext.getCurrentContext().setResponseGZipped(true);
		RequestContext.getCurrentContext()
				.setResponseDataStream(new ByteArrayInputStream(gzipData));

		filter.run();

		MockHttpServletResponse response = (MockHttpServletResponse) RequestContext
				.getCurrentContext().getResponse();
		assertThat(response.getHeader("Content-Length")).isNull();
		assertThat(response.getHeader("Content-Encoding")).isNull();
		assertThat(response.getContentAsByteArray()).isEqualTo(gzipData);
	}

	@Test
	public void closeResponseOutputStreamError() throws Exception {
		HttpServletResponse response = mock(HttpServletResponse.class);
		InputStream mockStream = spy(
				new ByteArrayInputStream("Hello\n".getBytes("UTF-8")));

		RequestContext context = new RequestContext();
		context.setRequest(new MockHttpServletRequest());
		context.setResponse(response);
		context.setResponseDataStream(mockStream);
		context.setResponseGZipped(false);
		Closeable zuulResponse = mock(Closeable.class);
		context.set("zuulResponse", zuulResponse);
		RequestContext.testSetCurrentContext(context);

		SendResponseFilter filter = new SendResponseFilter();

		ServletOutputStream zuuloutputstream = mock(ServletOutputStream.class);
		doThrow(new IOException("Response to client closed")).when(zuuloutputstream)
				.write(isA(byte[].class), anyInt(), anyInt());

		when(response.getOutputStream()).thenReturn(zuuloutputstream);

		try {
			filter.run();
		}
		catch (UndeclaredThrowableException ex) {
			assertThat(ex.getUndeclaredThrowable().getMessage())
					.isEqualTo("Response to client closed");
		}

		verify(zuulResponse).close();
		verify(mockStream).close();
	}

	@Test
	public void testCloseResponseDataStream() throws Exception {
		HttpServletResponse response = mock(HttpServletResponse.class);
		InputStream mockStream = spy(
				new ByteArrayInputStream("Hello\n".getBytes("UTF-8")));

		RequestContext context = new RequestContext();
		context.setRequest(new MockHttpServletRequest());
		context.setResponse(response);
		context.setResponseDataStream(mockStream);
		context.setResponseGZipped(false);
		Closeable zuulResponse = mock(Closeable.class);
		context.set("zuulResponse", zuulResponse);
		RequestContext.testSetCurrentContext(context);

		when(response.getOutputStream()).thenReturn(mock(ServletOutputStream.class));

		SendResponseFilter filter = new SendResponseFilter();

		filter.run();

		verify(mockStream).close();
	}

	private void runFilter(String characterEncoding, String content,
			boolean streamContent) throws Exception {
		MockHttpServletResponse response = new MockHttpServletResponse();
		SendResponseFilter filter = createFilter(content, characterEncoding, response,
				streamContent);
		assertThat(filter.shouldFilter()).as("shouldFilter returned false").isTrue();
		filter.run();
		String encoding = RequestContext.getCurrentContext().getResponse()
				.getCharacterEncoding();
		String expectedEncoding = characterEncoding != null ? characterEncoding
				: WebUtils.DEFAULT_CHARACTER_ENCODING;
		assertThat(encoding).as("wrong character encoding").isEqualTo(expectedEncoding);
		assertThat(response.getContentAsString()).as("wrong content").isEqualTo(content);
	}

	private SendResponseFilter createFilter(String content, String characterEncoding,
			MockHttpServletResponse response, boolean streamContent) throws Exception {
		return createFilter(new ZuulProperties(), content, characterEncoding, response,
				streamContent);
	}

	private SendResponseFilter createFilter(ZuulProperties properties, String content,
			String characterEncoding, MockHttpServletResponse response,
			boolean streamContent) throws Exception {
		HttpServletRequest request = new MockHttpServletRequest();
		RequestContext context = new RequestContext();
		context.setRequest(request);
		context.setResponse(response);

		if (characterEncoding != null) {
			response.setCharacterEncoding(characterEncoding);
		}

		if (streamContent) {
			context.setResponseDataStream(
					new ByteArrayInputStream(content.getBytes(characterEncoding)));
		}
		else {
			context.setResponseBody(content);
		}

		context.setResponseGZipped(false);
		context.set("error.status_code", HttpStatus.NOT_FOUND.value());
		RequestContext.testSetCurrentContext(context);
		SendResponseFilter filter = new SendResponseFilter(properties);
		return filter;
	}

	private byte[] gzipData(String content) throws IOException {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		PrintWriter gzip = new PrintWriter(new GZIPOutputStream(bos));
		gzip.print(content);
		gzip.flush();
		gzip.close();

		return bos.toByteArray();
	}

}


text:
//package tt.dao.business.impl;
//
//import org.bouncycastle.asn1.isismtt.x509.Restriction;
//import org.hibernate.Criteria;
//import org.hibernate.criterion.Order;
//import org.hibernate.criterion.Restrictions;
//import org.springframework.stereotype.Repository;
//import tt.dao.business.UserDaoI;
//import tt.dao.impl.BaseDaoImpl;
//import tt.model.business.User;
//
//import java.util.List;
//
///**
// * Created by taotao on 2016/9/23.
// */
//@Repository("userDao")
//public class UserDaoImpl extends BaseDaoImpl<User> implements UserDaoI {
//    @Override
//    public List<User> list( String name, Integer page, Integer pageSize,Integer dept_id) {
//        Criteria criteria = getCriteria(page,pageSize,dept_id)
//                .add(Restrictions.eq("dept_id",dept_id)).addOrder(Order.asc("id"));
//        if(name!=null&&!name.trim().isEmpty()){
//            criteria.add(Restrictions.like("name","%"+name+"%"));
//        }
////        if(page!=null&&pageSize!=null){
////            criteria.setFirstResult((page-1)*pageSize);
////            criteria.setMaxResults(pageSize);
////        }
//        return criteria.list();
//    }
//}


text:
var parent = require('../../../actual/array/virtual/reduce');

module.exports = parent;


text:
using System;

using NUnit.Framework;

namespace ZXing.DataMatrix.Encoder
{
    /// <summary>
    /// Tests for the ECC200 error correction.
    /// </summary>
    [TestFixture]
    public sealed class ErrorCorrectionTests
    {
        [Test]
        public void testRS()
        {
            //Sample from Annexe R in ISO/IEC 16022:2000(E)
            char[] cw = { (char)142, (char)164, (char)186 };
            SymbolInfo symbolInfo = SymbolInfo.lookup(3);
            String s = ErrorCorrection.encodeECC200(String.Join("", cw), symbolInfo);
            Assert.AreEqual("142 164 186 114 25 5 88 102", HighLevelEncodeTests.visualize(s));

            //"A" encoded (ASCII encoding + 2 padding characters)
            cw = new char[] { (char)66, (char)129, (char)70 };
            s = ErrorCorrection.encodeECC200(String.Join("", cw), symbolInfo);
            Assert.AreEqual("66 129 70 138 234 82 82 95", HighLevelEncodeTests.visualize(s));
        }
    }
}


text:
package ch.epfl.bbp.triechar;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Serializable;

/**
 * Trie implementation to store strings (multiple occurences allowed) and
 * retrieve the frequency (count) of a word.
 *
 * @author renaud.richardet@epfl.ch
 */
public class TrieCnt implements Serializable {
    private static final long serialVersionUID = 1L;

    private TrieNodeCnt root;
    private boolean caseSensitive;

    public TrieCnt() {
        this(false);
    }

    public TrieCnt(boolean caseSensitive) {
        this.caseSensitive = caseSensitive;
        root = new TrieNodeCnt();
    }

    public void addWord(String word) {
        if (!caseSensitive)
            word = word.toLowerCase();
        root.addWord(word.toCharArray());
    }

    /** @return the frequency of that word in the trie */
    public int getWord(String word) {
        if (!caseSensitive)
            word = word.toLowerCase();
        return root.getWord(word.toCharArray());
    }

    /** one entry per line. word first, then tab, then frequency */
    public void toFrequencyFile(String filePath) throws IOException {
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(filePath), "UTF-8"));
        for (TrieNodeCnt child : root.children.values()) {
            child.writeFrequencies(writer, new char[0]);// recursive
        }
        writer.close();
    }
}