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

<TITLE>
Button (2013 FRC Java API)
</TITLE>

<META NAME="date" CONTENT="2013-01-03">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

"
2013 FRC Java API
"

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

edu.wpi.first.wpilibj.buttons

Class Button

java.lang.Object
  edu.wpi.first.wpilibj.buttons.Trigger
      edu.wpi.first.wpilibj.buttons.Button

All Implemented Interfaces:
Sendable

Direct Known Subclasses:
DigitalIOButton, InternalButton, JoystickButton, NetworkButton

public abstract class Button
extends Trigger

This class provides an easy way to link commands to OI inputs.

 It is very easy to link a button to a command.  For instance, you could
 link the trigger button of a joystick to a "score" command.

 This class represents a subclass of Trigger that is specifically aimed at
 buttons on an operator interface as a common use case of the more generalized
 Trigger objects. This is a simple wrapper around Trigger with the method names
 renamed to fit the Button object use.

Author:

brad

Nested Class Summary

Nested classes/interfaces inherited from class edu.wpi.first.wpilibj.buttons.Trigger

Trigger.ButtonScheduler

Constructor Summary

Button()

Method Summary

 void
whenPressed(Command command)

          Starts the given command whenever the button is newly pressed.

 void
whenReleased(Command command)

          Starts the command when the button is released

 void
whileHeld(Command command)

          Constantly starts the given command while the button is held.

Methods inherited from class edu.wpi.first.wpilibj.buttons.Trigger

get, getSmartDashboardType, getTable, initTable, whenActive, whenInactive, whileActive

Methods inherited from class java.lang.Object

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

Constructor Detail

Button

public Button()

Method Detail

whenPressed

public void whenPressed(Command command)

Starts the given command whenever the button is newly pressed.

Parameters:
command - the command to start

whileHeld

public void whileHeld(Command command)

Constantly starts the given command while the button is held.

 Command.start() will be called repeatedly while the button is held,
 and will be canceled when the button is released.

Parameters:
command - the command to start

whenReleased

public void whenReleased(Command command)

Starts the command when the button is released

Parameters:
command - the command to start

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

"
2013 FRC Java API
"

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

"For updated information see the Java FRC site"


text:
package tifmo

package dcstree {

	abstract class WordBase {
		def isStopWord: Boolean
		def isNamedEntity: Boolean
	}
}

redpajama_set_name: RedPajamaGithub


text:
@interface ParseHelper : NSObject

+ (PlayerScore *) getPlayerScore;
+ (void) savePlayerScore:(PlayerScore *)playerScore;
+ (void) savePlayerScoreName:(NSString *)name;
+ (void) getTopTenPlayerScoresWithBlock:(void(^)(NSArray *playerScoreArray))block;

@end


text:
@interface POIObject : NSObject

@property (strong, nonatomic) NSString *venueID;
@property (strong, nonatomic) NSString *name;
@property (strong, nonatomic) NSString *address;
@property (strong, nonatomic) NSNumber *distance;
@property (strong, nonatomic) NSString *imageURL;
@property (strong, nonatomic) NSNumber *rating;
@property (strong, nonatomic) NSNumber *likes;
@property (strong, nonatomic) NSNumber *checkins;
@property (strong, nonatomic) NSMutableArray *tags;
@property (strong, nonatomic) NSString *price;

- (POIObject *) initWithObject:(NSDictionary *) obj;

@end


text:
// <copyright file="NavigationService.cs" company="Colin C. Williams">
// Copyright (c) Colin C. Williams. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>

namespace ColinCWilliams.CSharpNavigationService
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Windows.UI.Xaml.Controls;

    /// <summary>
    /// A navigation service which facilitates Frame navigation and suspension
    /// with passing of complex types.
    /// </summary>
    public class NavigationService : INavigationService
    {
        private static readonly List<NavigationService> NavigationServices = new List<NavigationService>();
        private static readonly ISuspensionManager SuspensionManager = new SuspensionManager();

        private readonly INavigationContextService contextService;
        private readonly WeakReference<Frame> rootFrame;
        private readonly string name;

        /// <summary>
        /// Initializes a new instance of the <see cref="NavigationService"/> class.
        /// </summary>
        /// <param name="frame">The Frame to use for navigation.</param>
        /// <param name="contextService">The context service to use for storing and retrieving Navigation Contexts during navigation.</param>
        internal NavigationService(Frame frame, INavigationContextService contextService)
        {
            if (frame == null)
            {
                throw new ArgumentNullException(nameof(frame));
            }

            if (contextService == null)
            {
                throw new ArgumentNullException(nameof(contextService));
            }

            this.contextService = contextService;
            this.rootFrame = new WeakReference<Frame>(frame);
            this.name = frame.Name;
            this.PageStates = new Dictionary<string, PageState>();
        }

        /// <summary>
        /// Gets a value indicating whether calling <see cref="GoBack" /> will success.
        /// </summary>
        /// <returns>True if back navigation can occur, false otherwise.</returns>
        public bool CanGoBack => this.RootFrame.CanGoBack;

        /// <summary>
        /// Gets a value indicating whether calling <see cref="GoForward" /> will success.
        /// </summary>
        /// <returns>True if forward navigation can occur, false otherwise.</returns>
        public bool CanGoForward => this.RootFrame.CanGoForward;

        /// <summary>
        /// Gets the states for the individual pages this Navigation Service has seen.
        /// </summary>
        internal Dictionary<string, PageState> PageStates { get; private set; }

        /// <summary>
        /// Gets the context service associated with this NavigationService.
        /// </summary>
        internal INavigationContextService ContextService
        {
            get { return this.contextService; }
        }

        /// <summary>
        /// Gets the root frame for the navigation service.
        /// </summary>
        internal Frame RootFrame
        {
            get
            {
                Frame frame = this.GetFrameSafe();
                if (frame == null)
                {
                    throw new InvalidOperationException("NavigationService still in use after Frame has been garbage collected.");
                }

                return frame;
            }
        }

        /// <summary>
        /// Gets the name of this NavigationService.
        /// </summary>
        internal string Name
        {
            get
            {
                if (this.GetFrameSafe().Name != this.name)
                {
                    throw new InvalidOperationException("Frame's name changed after this NavigationService was constructed.");
                }

                return this.name;
            }
        }

        /// <summary>
        /// Creates a new NavigationService for a Frame, registering the frame and NavigationService
        /// for future retrieval and registering the frame with the NavigationContextService.
        /// </summary>
        /// <param name="frame">The frame to register.</param>
        /// <param name="defaultPage">The default page to navigate to if there is no state to restore.</param>
        /// <param name="defaultNavigationContext">The navigation context to provide on navigation to defaultPage.</param>
        /// <param name="restoreState">True to attempt to restore previously saved state, false to just navigate to defaultPage
        ///     without attempting to restore state.</param>
        /// <returns>The NavigationService for the registered frame.</returns>
        public static INavigationService RegisterFrame(Frame frame, Type defaultPage, NavigationContextBase defaultNavigationContext = null, bool restoreState = true)
        {
            if (frame == null)
            {
                throw new ArgumentNullException(nameof(frame));
            }

            if (defaultPage == null)
            {
                throw new ArgumentNullException(nameof(defaultPage));
            }

            if (GetNavigationService(frame) != null)
            {
                throw new InvalidOperationException("Frame already associated with a NavigationService.");
            }

            // Clean up references before adding a new one.
            RemoveFrame();

            NavigationService navigationService = new NavigationService(frame, new NavigationContextService());

            // Ensure navigationService is fully registered before restoring state
            // or navigating so that it can be accessed by PageBase.
            NavigationServices.Add(navigationService);

            if (restoreState)
            {
                // This triggers NavigatedTo on PageBase if there is state restored.
                navigationService.RestoreState();
            }

            // If state wasn't restored, navigate to a default page to populate the Frame.
            if (navigationService.RootFrame.Content == null)
            {
                navigationService.Navigate(defaultPage, defaultNavigationContext);
            }

            return navigationService;
        }

        /// <summary>
        /// Unregisters a Frame and its NavigationService, removing all references to both the
        /// frame and navigation service. Unregisters the frame from the NavigationContextService.
        /// </summary>
        /// <param name="frame">The frame to unregister.</param>
        public static void UnregisterFrame(Frame frame)
        {
            if (frame == null)
            {
                throw new ArgumentNullException(nameof(frame));
            }

            RemoveFrame(frame);
        }

        /// <summary>
        /// Retrieves the NavigationService for a registered Frame.
        /// </summary>
        /// <param name="frame">The Frame to get the NavigationService for.</param>
        /// <returns>The NavigationService for the provided frame.</returns>
        public static INavigationService GetNavigationService(Frame frame)
        {
            if (frame == null)
            {
                throw new ArgumentNullException(nameof(frame));
            }

            return NavigationServices.FirstOrDefault(x => x.RootFrame == frame);
        }

        /// <summary>
        /// Saves the current navigation state in preparation for
        /// app suspension.
        /// </summary>
        /// <returns>The task for this operation.</returns>
        public static async Task SaveStateAsync()
        {
            // Clean up NavigationServices so we don't save the state of services with no Frame.
            RemoveFrame();

            // Save state to disk.
            await SuspensionManager.SaveAsync(NavigationServices);
        }

        /// <summary>
        /// Restores the current navigation state from disk.
        /// </summary>
        /// <returns>The task for this operation.</returns>
        public static async Task RestoreStateAsync()
        {
            await SuspensionManager.RestoreAsync();
        }

        /// <summary>
        /// Adds the provided types to a known type list so that they
        /// can be serialized when <see cref="SaveStateAsync" /> is called.
        /// </summary>
        /// <param name="types">The known types to add.</param>
        public static void AddKnownTypes(List<Type> types)
        {
            if (types != null)
            {
                foreach (Type type in types)
                {
                    SuspensionManager.AddKnownType(type);
                }
            }
        }

        /// <summary>
        /// Navigate to the specified page with the provided context.
        /// </summary>
        /// <param name="pageType">The type of page to navigate to.</param>
        /// <param name="context">The context that should be provided to the page after navigation.</param>
        public void Navigate(Type pageType, NavigationContextBase context = null)
        {
            if (pageType == null)
            {
                throw new ArgumentNullException(nameof(pageType));
            }

            if (context != null && !SuspensionManager.KnownTypes.Contains(context.GetType()))
            {
                throw new ArgumentException(
                    "Cannot navigate with a context that has not been registered as a Known Type. Use NavigationService.AddKnownTypes to register this context type before use.",
                    "context");
            }

            object parameter = null;

            if (context != null)
            {
                parameter = this.contextService.Add(context);
            }

            this.RootFrame.Navigate(pageType, parameter);
        }

        /// <summary>
        /// Navigate back a page in the back stack.
        /// </summary>
        public void GoBack()
        {
            if (this.CanGoBack)
            {
                this.RootFrame.GoBack();
            }
        }

        /// <summary>
        /// Navigate forward a page in the forward stack.
        /// </summary>
        public void GoForward()
        {
            if (this.CanGoForward)
            {
                this.RootFrame.GoForward();
            }
        }

        /// <summary>
        /// Saves the state of this NavigationService.
        /// </summary>
        /// <returns>The saved state.</returns>
        internal FrameState SaveState()
        {
            return new FrameState()
            {
                Navigation = this.RootFrame.GetNavigationState(),
                ContextService = this.ContextService.SaveState(),
                PageStates = this.PageStates
            };
        }

        /// <summary>
        /// Removes the NavigationService for the provided frame and cleans up any NavigationServices where their
        /// Frame has been garbage collected.
        /// </summary>
        /// <param name="frame">The frame to remove or null to just clean up invalid WeakReferences.</param>
        private static void RemoveFrame(Frame frame = null)
        {
            IEnumerable<NavigationService> servicesToRemove = NavigationServices.Where(x => x.GetFrameSafe() == null || x.GetFrameSafe() == frame);
            foreach (NavigationService service in servicesToRemove.ToList())
            {
                SuspensionManager.DeleteState(service.Name);
                NavigationServices.Remove(service);
            }
        }

        /// <summary>
        /// Restores the state of this Navigation Service from the <see cref="SuspensionManager"/>.
        /// </summary>
        private void RestoreState()
        {
            FrameState state = SuspensionManager.GetState(this.Name);

            if (state != null)
            {
                this.ContextService.RestoreState(state.ContextService);
                this.PageStates = state.PageStates;

                // SetNavigationState last so that everything else is restored.
                // This triggers OnNavigatedTo call for the page.
                this.RootFrame.SetNavigationState(state.Navigation);
            }
        }

        /// <summary>
        /// Attempts to get the Frame from the weak reference.
        /// </summary>
        /// <returns>The frame or null if the Frame was garbage collected.</returns>
        private Frame GetFrameSafe()
        {
            Frame frame = null;
            this.rootFrame.TryGetTarget(out frame);

            return frame;
        }
    }
}


text:
#ifndef _FABRIC_EXCEPTION_H
#define _FABRIC_EXCEPTION_H

#include <stdarg.h>
#include <stdio.h>
#include <Fabric/Base/Util/SimpleString.h>

namespace Fabric
{
  class Exception
  {
  public:

    Exception( size_t length, char const *data )
      : m_desc( data, length )
    {
    }

    Exception( const char *format, ... )
    {
      char buffer[4096];
      va_list argList;
      va_start( argList, format );
      vsnprintf( buffer, 4096, format, argList );
      va_end( argList );
      m_desc = buffer;
    }

    Exception( Util::SimpleString const &desc )
      : m_desc( desc )
    {
    }

    Exception( Exception const &that )
      : m_desc( that.m_desc )
    {
    }

    Exception &operator =( Exception const &that )
    {
      m_desc = that.m_desc;
      return *this;
    }

    virtual ~Exception()
    {
    }

    Util::SimpleString const &getDesc() const
    {
      return m_desc;
    }

    operator Util::SimpleString() const
    {
      return m_desc;
    }

    operator char const *() const
    {
      return m_desc.getCString();
    }

    char const *getData() const
    {
      return m_desc.getData();
    }

    size_t getLength() const
    {
      return m_desc.getLength();
    }

  private:

    Util::SimpleString m_desc;
  };

  inline Exception operator +( Util::SimpleString const &left, Exception const &right )
  {
    return left + right.getDesc();
  }

  inline Exception operator +( const char *left, Exception const &right )
  {
    return left + right.getDesc();
  }

  inline Exception operator +( Exception const &left, Util::SimpleString const &right )
  {
    return left.getDesc() + right;
  }

  inline Exception operator +( Exception const &left, const char *right )
  {
    return left.getDesc() + right;
  }
};

#endif //_FABRIC_EXCEPTION_H


text:
import click
from PIL import Image
from utils.misc import get_file_list
from utils.fs import remove_file

@click.command()
@click.argument('path', type=click.Path(exists=True))
@click.argument('condition')
@click.option('-t', '--test', is_flag=True, help='test only')
def remove_if(path, condition, test):
    count = 0
    for f in get_file_list(path):
        img = Image.open(f)
        w, h = img.size
        img.close()
        if eval(condition):
            count += 1
            print (f)
            if not test:
                remove_file(f, False)
    print count, 'file(s)'

if __name__ == '__main__':
    remove_if()


text:
package org.elasticsearch.cluster.routing.allocation.decider;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.cluster.routing.RecoverySource;
import org.elasticsearch.cluster.routing.RoutingNode;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.cluster.routing.UnassignedInfo;
import org.elasticsearch.cluster.routing.allocation.RoutingAllocation;
import org.elasticsearch.common.settings.ClusterSettings;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Setting.Property;
import org.elasticsearch.common.settings.Settings;

import static org.elasticsearch.cluster.routing.allocation.decider.Decision.THROTTLE;
import static org.elasticsearch.cluster.routing.allocation.decider.Decision.YES;

/**
 * {@link ThrottlingAllocationDecider} controls the recovery process per node in
 * the cluster. It exposes two settings via the cluster update API that allow
 * changes in real-time:
 *

 *
{@code cluster.routing.allocation.node_initial_primaries_recoveries} -
 * restricts the number of initial primary shard recovery operations on a single
 * node. The default is {@code 4}

 *
{@code cluster.routing.allocation.node_concurrent_recoveries} -
 * restricts the number of total concurrent shards initializing on a single node. The
 * default is {@code 2}

 *

 *

 * If one of the above thresholds is exceeded per node this allocation decider
 * will return {@link Decision#THROTTLE} as a hit to upstream logic to throttle
 * the allocation process to prevent overloading nodes due to too many concurrent recovery
 * processes.
 */
public class ThrottlingAllocationDecider extends AllocationDecider {

    private static final Logger LOGGER = LogManager.getLogger(ThrottlingAllocationDecider.class);

    public static final int DEFAULT_CLUSTER_ROUTING_ALLOCATION_NODE_CONCURRENT_RECOVERIES = 2;
    public static final int DEFAULT_CLUSTER_ROUTING_ALLOCATION_NODE_INITIAL_PRIMARIES_RECOVERIES = 4;
    public static final String NAME = "throttling";
    public static final Setting<Integer> CLUSTER_ROUTING_ALLOCATION_NODE_CONCURRENT_RECOVERIES_SETTING =
        new Setting<>("cluster.routing.allocation.node_concurrent_recoveries",
            Integer.toString(DEFAULT_CLUSTER_ROUTING_ALLOCATION_NODE_CONCURRENT_RECOVERIES),
            (s) -> Setting.parseInt(s, 0, "cluster.routing.allocation.node_concurrent_recoveries"),
            Property.Dynamic, Property.NodeScope);
    public static final Setting<Integer> CLUSTER_ROUTING_ALLOCATION_NODE_INITIAL_PRIMARIES_RECOVERIES_SETTING =
        Setting.intSetting("cluster.routing.allocation.node_initial_primaries_recoveries",
            DEFAULT_CLUSTER_ROUTING_ALLOCATION_NODE_INITIAL_PRIMARIES_RECOVERIES, 0,
            Property.Dynamic, Property.NodeScope);
    public static final Setting<Integer> CLUSTER_ROUTING_ALLOCATION_NODE_CONCURRENT_INCOMING_RECOVERIES_SETTING =
        new Setting<>("cluster.routing.allocation.node_concurrent_incoming_recoveries",
            CLUSTER_ROUTING_ALLOCATION_NODE_CONCURRENT_RECOVERIES_SETTING::getRaw,
            (s) -> Setting.parseInt(s, 0, "cluster.routing.allocation.node_concurrent_incoming_recoveries"),
            Property.Dynamic, Property.NodeScope);
    public static final Setting<Integer> CLUSTER_ROUTING_ALLOCATION_NODE_CONCURRENT_OUTGOING_RECOVERIES_SETTING =
        new Setting<>("cluster.routing.allocation.node_concurrent_outgoing_recoveries",
            CLUSTER_ROUTING_ALLOCATION_NODE_CONCURRENT_RECOVERIES_SETTING::getRaw,
            (s) -> Setting.parseInt(s, 0, "cluster.routing.allocation.node_concurrent_outgoing_recoveries"),
            Property.Dynamic, Property.NodeScope);

    private volatile int primariesInitialRecoveries;
    private volatile int concurrentIncomingRecoveries;
    private volatile int concurrentOutgoingRecoveries;

    public ThrottlingAllocationDecider(Settings settings, ClusterSettings clusterSettings) {
        this.primariesInitialRecoveries = CLUSTER_ROUTING_ALLOCATION_NODE_INITIAL_PRIMARIES_RECOVERIES_SETTING.get(settings);
        concurrentIncomingRecoveries = CLUSTER_ROUTING_ALLOCATION_NODE_CONCURRENT_INCOMING_RECOVERIES_SETTING.get(settings);
        concurrentOutgoingRecoveries = CLUSTER_ROUTING_ALLOCATION_NODE_CONCURRENT_OUTGOING_RECOVERIES_SETTING.get(settings);

        clusterSettings.addSettingsUpdateConsumer(CLUSTER_ROUTING_ALLOCATION_NODE_INITIAL_PRIMARIES_RECOVERIES_SETTING,
                this::setPrimariesInitialRecoveries);
        clusterSettings.addSettingsUpdateConsumer(CLUSTER_ROUTING_ALLOCATION_NODE_CONCURRENT_INCOMING_RECOVERIES_SETTING,
                this::setConcurrentIncomingRecoverries);
        clusterSettings.addSettingsUpdateConsumer(CLUSTER_ROUTING_ALLOCATION_NODE_CONCURRENT_OUTGOING_RECOVERIES_SETTING,
                this::setConcurrentOutgoingRecoverries);

        LOGGER.debug("using node_concurrent_outgoing_recoveries [{}], node_concurrent_incoming_recoveries [{}], " +
                        "node_initial_primaries_recoveries [{}]",
                concurrentOutgoingRecoveries, concurrentIncomingRecoveries, primariesInitialRecoveries);
    }

    private void setConcurrentIncomingRecoverries(int concurrentIncomingRecoveries) {
        this.concurrentIncomingRecoveries = concurrentIncomingRecoveries;
    }

    private void setConcurrentOutgoingRecoverries(int concurrentOutgoingRecoveries) {
        this.concurrentOutgoingRecoveries = concurrentOutgoingRecoveries;
    }

    private void setPrimariesInitialRecoveries(int primariesInitialRecoveries) {
        this.primariesInitialRecoveries = primariesInitialRecoveries;
    }

    @Override
    public Decision canAllocate(ShardRouting shardRouting, RoutingNode node, RoutingAllocation allocation) {
        if (shardRouting.primary() && shardRouting.unassigned()) {
            assert initializingShard(shardRouting, node.nodeId()).recoverySource().getType() != RecoverySource.Type.PEER;
            // primary is unassigned, means we are going to do recovery from store, snapshot or local shards
            // count *just the primaries* currently doing recovery on the node and check against primariesInitialRecoveries

            int primariesInRecovery = 0;
            for (ShardRouting shard : node) {
                // when a primary shard is INITIALIZING, it can be because of *initial recovery* or *relocation from another node*
                // we only count initial recoveries here, so we need to make sure that relocating node is null
                if (shard.initializing() && shard.primary() && shard.relocatingNodeId() == null) {
                    primariesInRecovery++;
                }
            }
            if (primariesInRecovery >= primariesInitialRecoveries) {
                // TODO: Should index creation not be throttled for primary shards?
                return allocation.decision(THROTTLE, NAME,
                    "reached the limit of ongoing initial primary recoveries [%d], cluster setting [%s=%d]",
                    primariesInRecovery, CLUSTER_ROUTING_ALLOCATION_NODE_INITIAL_PRIMARIES_RECOVERIES_SETTING.getKey(),
                    primariesInitialRecoveries);
            } else {
                return allocation.decision(YES, NAME, "below primary recovery limit of [%d]", primariesInitialRecoveries);
            }
        } else {
            // Peer recovery
            assert initializingShard(shardRouting, node.nodeId()).recoverySource().getType() == RecoverySource.Type.PEER;

            // Allocating a shard to this node will increase the incoming recoveries
            int currentInRecoveries = allocation.routingNodes().getIncomingRecoveries(node.nodeId());
            if (currentInRecoveries >= concurrentIncomingRecoveries) {
                return allocation.decision(THROTTLE, NAME,
                    "reached the limit of incoming shard recoveries [%d], cluster setting [%s=%d] (can also be set via [%s])",
                    currentInRecoveries, CLUSTER_ROUTING_ALLOCATION_NODE_CONCURRENT_INCOMING_RECOVERIES_SETTING.getKey(),
                    concurrentIncomingRecoveries,
                    CLUSTER_ROUTING_ALLOCATION_NODE_CONCURRENT_RECOVERIES_SETTING.getKey());
            } else {
                // search for corresponding recovery source (= primary shard) and check number of outgoing recoveries on that node
                ShardRouting primaryShard = allocation.routingNodes().activePrimary(shardRouting.shardId());
                if (primaryShard == null) {
                    return allocation.decision(Decision.NO, NAME, "primary shard for this replica is not yet active");
                }
                int primaryNodeOutRecoveries = allocation.routingNodes().getOutgoingRecoveries(primaryShard.currentNodeId());
                if (primaryNodeOutRecoveries >= concurrentOutgoingRecoveries) {
                    return allocation.decision(THROTTLE, NAME,
                        "reached the limit of outgoing shard recoveries [%d] on the node [%s] which holds the primary, " +
                        "cluster setting [%s=%d] (can also be set via [%s])",
                        primaryNodeOutRecoveries, primaryShard.currentNodeId(),
                        CLUSTER_ROUTING_ALLOCATION_NODE_CONCURRENT_OUTGOING_RECOVERIES_SETTING.getKey(),
                        concurrentOutgoingRecoveries,
                        CLUSTER_ROUTING_ALLOCATION_NODE_CONCURRENT_RECOVERIES_SETTING.getKey());
                } else {
                    return allocation.decision(YES, NAME, "below shard recovery limit of outgoing: [%d < %d] incoming: [%d < %d]",
                        primaryNodeOutRecoveries,
                        concurrentOutgoingRecoveries,
                        currentInRecoveries,
                        concurrentIncomingRecoveries);
                }
            }
        }
    }

    /**
     * The shard routing passed to {@link #canAllocate(ShardRouting, RoutingNode, RoutingAllocation)} is not the initializing shard to this
     * node but:
     * - the unassigned shard routing in case if we want to assign an unassigned shard to this node.
     * - the initializing shard routing if we want to assign the initializing shard to this node instead
     * - the started shard routing in case if we want to check if we can relocate to this node.
     * - the relocating shard routing if we want to relocate to this node now instead.
     *
     * This method returns the corresponding initializing shard that would be allocated to this node.
     */
    private ShardRouting initializingShard(ShardRouting shardRouting, String currentNodeId) {
        final ShardRouting initializingShard;
        if (shardRouting.unassigned()) {
            initializingShard = shardRouting.initialize(currentNodeId, null, ShardRouting.UNAVAILABLE_EXPECTED_SHARD_SIZE);
        } else if (shardRouting.initializing()) {
            UnassignedInfo unassignedInfo = shardRouting.unassignedInfo();
            if (unassignedInfo == null) {
                // unassigned shards must have unassignedInfo (initializing shards might not)
                unassignedInfo = new UnassignedInfo(UnassignedInfo.Reason.ALLOCATION_FAILED, "fake");
            }
            initializingShard = shardRouting.moveToUnassigned(unassignedInfo)
                .initialize(currentNodeId, null, ShardRouting.UNAVAILABLE_EXPECTED_SHARD_SIZE);
        } else if (shardRouting.relocating()) {
            initializingShard = shardRouting.cancelRelocation()
                .relocate(currentNodeId, ShardRouting.UNAVAILABLE_EXPECTED_SHARD_SIZE)
                .getTargetRelocatingShard();
        } else {
            assert shardRouting.started();
            initializingShard = shardRouting.relocate(currentNodeId, ShardRouting.UNAVAILABLE_EXPECTED_SHARD_SIZE)
                .getTargetRelocatingShard();
        }
        assert initializingShard.initializing();
        return initializingShard;
    }
}


text:
package com.iclojure.jline.console.completer;

import com.iclojure.jline.console.ConsoleReader;

import java.io.IOException;
import java.util.List;

/**
 * Handler for dealing with candidates for tab-completion.
 *
 * @author Marc Prud'hommeaux
 * @author Jason Dillon
 * @since 2.3
 */
public interface CompletionHandler
{
    boolean complete(ConsoleReader reader, List<CharSequence> candidates, int position) throws IOException;
}


text:
using Tibia.Constants;
using Tibia.Objects;

namespace Tibia.Packets.Pipes
{
    public class RemoveTextPacket : PipePacket
    {
        public string TextName { get; set; }

        public RemoveTextPacket(Client client)
            : base(client)
        {
            Type = PipePacketType.RemoveText;
        }

        public override bool ParseMessage(NetworkMessage msg, PacketDestination destination)
        {
            if (msg.GetByte() != (byte)PipePacketType.RemoveText)
                return false;

            Type = PipePacketType.RemoveText;
            TextName = msg.GetString();

            return true;
        }

        public override byte[] ToByteArray()
        {
            NetworkMessage msg = NetworkMessage.CreateUnencrypted(Client, 3 + TextName.Length);
            msg.AddByte((byte)Type);

            msg.AddString(TextName);

            return msg.Data;
        }

        public static bool Send(Objects.Client client, string textName)
        {
            RemoveTextPacket p = new RemoveTextPacket(client);
            p.TextName = textName;
            return p.Send();
        }

    }
}


text:
package metadata

func dropPrivileges() (err error) {
	return nil
}


text:
class Comment < ActiveRecord::Base
  include ActsAsCommentable.CommentBase
end


text:
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>
    <predicate lemma="grunt">
        <note>
            Frames file for 'grunt' based on sentences in brown.  Verbnet entry
        </note>

        <roleset id="grunt.02" vncls="37.3" name="speak gruntingly">
            <roles>
                <role n="0"  descr="speaker">
                    <vnrole vncls="37.3" vntheta="Agent"/>
                </role>
                <role n="1"  descr="utterance">
                    <vnrole vncls="37.3" vntheta="Topic"/>
                </role>
                <role n="2"  descr="listener">
                    <vnrole vncls="37.3" vntheta="Recipient"/>
                </role>
            </roles>

            <example name="intransitive, as an animal">
                <inflection person="ns" tense="past" aspect="ns" voice="active" form="full"/>
                <text>
                    ...and the men grunted and followed, pushing Lester to the side
                    where he back against the wall with the sleeve of his jacket
                    raised before his eyesto shut out the light.
                </text>
                <arg n="0"        >the men</arg>
                <rel              >grunted</rel>
                <arg n="m" f="ADV">pushing Lester to the side
                    where he back against the wall with the sleeve of his jacket
                    raised before his eyesto shut out the light
                </arg>
            </example>

            <example name="utterance, sorta">
                <inflection person="ns" tense="past" aspect="ns" voice="active" form="full"/>
                <text>
                    He grunted a sort of ``yes'' answer.
                </text>
                <arg n="0"        >He</arg>
                <rel              >grunted</rel>
                <arg n="1"        >a sort of ``yes'' answer</arg>
            </example>

            <example name="with listener">
                <inflection person="ns" tense="ns" aspect="ns" voice="active" form="full"/>
                <text>
                    Sometimes he would grunt softly to some invisible onlooker beside him.
                </text>
                <arg n="m" f="TMP">Sometimes</arg>
                <arg n="0"        >he</arg>
                <arg n="m" f="MOD">would</arg>
                <rel              >grunt</rel>
                <arg n="m" f="MNR">softly</arg>
                <arg n="2">to some invisible onlooker beside him</arg>
            </example>

            <example name="a proper utterance">
                <inflection person="ns" tense="past" aspect="ns" voice="active" form="full"/>
                <text>
                    [``It does'',]-1 Shayne grunted *trace*-1 sourly, still able to taste
                    her mouth on his in the Green Jungle parking lot.
                </text>
                <arg n="0"        >Shayne</arg>
                <rel              >grunted</rel>
                <arg n="1"        >*trace*</arg>
                <arg n="m" f="MNR">sourly</arg>
                <arg n="m" f="ADV">still able to taste her mouth on his in the Green
                    Jungle parking lot
                </arg>
            </example>

            <note>
                Ah, romance!
            </note>

        </roleset>
    </predicate>
</frameset>


text:
layout: default
title: Sign-up
description:
---

Voeg hier spelers toe

		<form>
			<input type="text" placeholder="Speler #1">
			<input type="text" placeholder="Speler #2">
			<input type="text" placeholder="Speler #3">
			<input type="button" value="Speler +1" id="addPlayer">
		</form>
		<button>Start spel</button>


text:
#ifndef MXNET_OPERATOR_RNN_INL_H_
#define MXNET_OPERATOR_RNN_INL_H_

#include <dmlc/logging.h>
#include <dmlc/parameter.h>
#include <mxnet/operator.h>
#include <algorithm>
#include <map>
#include <vector>
#include <string>
#include <utility>
#include "./operator_common.h"

namespace mxnet {
namespace op {

namespace rnn_enum {
  enum RNNOpInputs {kData, kParams, kState, kStateCell};
  enum RNNOpOutputs {kOut, kStateOut, kStateCellOut};
  enum RNNModeType {kRnnRelu, kRnnTanh, kLstm, kGru};
  enum RNNOpResource {kTempSpace};
}

// A utility function to calculate input size
inline int rnn_single_param_size(int inputSize,
                                int hiddenSize,
                                int mode) {
  int size = hiddenSize * (hiddenSize + inputSize + 2);
  // Different RNN's have different num weights
  switch (mode) {
    case rnn_enum::kRnnRelu:
      size *= 1;
      break;
    case rnn_enum::kRnnTanh:
      size *= 1;
      break;
    case rnn_enum::kLstm:
      size *= 4;
      break;
    case rnn_enum::kGru:
      size *= 3;
      break;
  }
  return size;
}

inline int rnn_param_size(int layerNum,
                          int inputSize,
                          int hiddenSize,
                          bool bidirectional,
                          int mode) {
  // get size of first layer
  int size = rnn_single_param_size(inputSize, hiddenSize, mode);
  // get size of remaining layers
  if (bidirectional) {
    size += (layerNum - 1) * rnn_single_param_size(2 * hiddenSize, hiddenSize, mode);
    size *= 2;
  } else {
    size += (layerNum - 1) * rnn_single_param_size(hiddenSize, hiddenSize, mode);
  }
  return size;
}

struct RNNParam : public dmlc::Parameter<RNNParam> {
  uint32_t state_size;
  uint32_t num_layers;
  bool bidirectional, state_outputs;
  int mode;
  float p, pkeep_;
  int seq_length_, batch_size_, input_size_;
  bool lstm_q_;  // whether type is lstm

  DMLC_DECLARE_PARAMETER(RNNParam) {
    DMLC_DECLARE_FIELD(state_size)
    .describe("size of the state for each layer");

    DMLC_DECLARE_FIELD(num_layers)
    .describe("number of stacked layers");

    DMLC_DECLARE_FIELD(bidirectional).set_default(false)
    .describe("whether to use bidirectional recurrent layers");

    DMLC_DECLARE_FIELD(mode)
    .add_enum("rnn_relu", rnn_enum::kRnnRelu)
    .add_enum("rnn_tanh", rnn_enum::kRnnTanh)
    .add_enum("lstm", rnn_enum::kLstm)
    .add_enum("gru", rnn_enum::kGru)
    .describe("the type of RNN to compute");

    DMLC_DECLARE_FIELD(p).set_default(0.)
    .set_range(0, 1)
    .describe("Dropout probability, fraction of the input that gets dropped out at training time");

    DMLC_DECLARE_FIELD(state_outputs).set_default(false)
    .describe("Whether to have the states as symbol outputs.");
  }
};

template<typename xpu, typename DType>
class RNNOp : public Operator {
 public:
  explicit RNNOp(RNNParam p) {
  }

  virtual void Forward(const OpContext &ctx,
                       const std::vector<TBlob> &in_data,
                       const std::vector<OpReqType> &req,
                       const std::vector<TBlob> &out_data,
                       const std::vector<TBlob> &aux_args) {
    using namespace mshadow;
    using namespace mshadow::expr;
    // TODO(sbodenstein): add MShadow implementation
  }

  virtual void Backward(const OpContext &ctx,
                        const std::vector<TBlob> &out_grad,
                        const std::vector<TBlob> &in_data,
                        const std::vector<TBlob> &out_data,
                        const std::vector<OpReqType> &req,
                        const std::vector<TBlob> &in_grad,
                        const std::vector<TBlob> &aux_args) {
    using namespace mshadow;
    using namespace mshadow::expr;
    // TODO(sbodenstein): add MShadow implementation
  }

 private:
  RNNParam param_;
};  // class RNNOp

template<typename xpu>
Operator* CreateOp(RNNParam param, int dtype);

#if DMLC_USE_CXX11
class RNNProp : public OperatorProperty {
 public:
  std::vector<std::string> ListArguments() const override {
    if (param_.mode == rnn_enum::kLstm) {
      return {"data", "parameters", "state", "state_cell"};
    } else {
      return {"data", "parameters", "state"};
    }
  }

  std::vector<std::string> ListOutputs() const override {
    std::vector<std::string> outputs = {"output"};
    if (!param_.state_outputs)
      return outputs;
    else
      outputs.push_back("state");
    if (param_.mode == rnn_enum::kLstm)
      outputs.push_back("state_cell");
    return outputs;
  }

  int NumOutputs() const override {
    int mode_num = (param_.mode == rnn_enum::kLstm) ? 2 : 1;
    int num_outputs = param_.state_outputs ? (mode_num + 1) : 1;
    return num_outputs;
  }

  void Init(const std::vector<std::pair<std::string, std::string> >& kwargs) override {
    param_.Init(kwargs);
  }

  std::map<std::string, std::string> GetParams() const override {
    return param_.__DICT__();
  }

  bool InferShape(std::vector<TShape> *in_shape,
                  std::vector<TShape> *out_shape,
                  std::vector<TShape> *aux_shape) const override {
    using namespace mshadow;
    if (param_.mode == rnn_enum::kLstm) {
      CHECK_EQ(in_shape->size(), 4U) << "Input:[data, parameters, state, cell_state]";
    } else {
      CHECK_EQ(in_shape->size(), 3U) << "Input:[data, parameters, state]";
    }
    const TShape &dshape = (*in_shape)[rnn_enum::kData];
    if (dshape.ndim() ==  0) return false;
    CHECK_EQ(dshape.ndim(), 3U) \
        << "Input data should be rank-3 tensor of dim [sequence length, batch size, input size]";
    // data: [sequence len, batch, input dimension]
    int batch_size = dshape[1];
    int input_size = dshape[2];
    int numDirections = param_.bidirectional ? 2 : 1;
    int total_layers = numDirections * param_.num_layers;  // double for bidirectional
    SHAPE_ASSIGN_CHECK(*in_shape,
                       rnn_enum::kState,
                       Shape3(total_layers, batch_size, param_.state_size));
    if (param_.mode == rnn_enum::kLstm)
      SHAPE_ASSIGN_CHECK(*in_shape,
                        rnn_enum::kStateCell,
                        Shape3(total_layers, batch_size, param_.state_size));

    // calculate parameter vector length
    int param_size = rnn_param_size(param_.num_layers,
                                    input_size,
                                    param_.state_size,
                                    param_.bidirectional,
                                    param_.mode);
    SHAPE_ASSIGN_CHECK(*in_shape, rnn_enum::kParams, Shape1(param_size));

    out_shape->clear();
    // output: [sequence len, batch, output size]
    TShape oshape = dshape;
    oshape[2] = numDirections * param_.state_size;
    out_shape->push_back(oshape);
    if (!param_.state_outputs) {
      return true;
    } else {
      // outStateShape: [layer_num, batch, state size]
      TShape outStateShape = dshape;
      outStateShape[0] = total_layers;
      outStateShape[1] = batch_size;
      outStateShape[2] = param_.state_size;
      out_shape->push_back(outStateShape);
      // Deal with lstm cell state
      if (param_.mode == rnn_enum::kLstm)
        out_shape->push_back(outStateShape);
      return true;
    }
  }

  bool InferType(std::vector<int> *in_type,
                 std::vector<int> *out_type,
                 std::vector<int> *aux_type) const override {
    CHECK_GE(in_type->size(), 1U);
    int dtype = (*in_type)[0];
    CHECK_NE(dtype, -1) << "First input must have specified type";
    for (index_t i = 0; i < in_type->size(); ++i) {
      if ((*in_type)[i] == -1) {
        (*in_type)[i] = dtype;
      } else {
        CHECK_EQ((*in_type)[i], dtype) << "This layer requires uniform type. "
                                       << "Expected " << dtype << " v.s. given "
                                       << (*in_type)[i] << " at " << ListArguments()[i];
      }
    }
    out_type->clear();
    out_type->push_back(dtype);
    if (!param_.state_outputs) {
      return true;
    } else {
      out_type->push_back(dtype);
      // Deal with lstm cell state
      if (param_.mode == rnn_enum::kLstm)
        out_type->push_back(dtype);
      return true;
    }
  }

  OperatorProperty* Copy() const override {
    auto ptr = new RNNProp();
    ptr->param_ = param_;
    return ptr;
  }

  std::string TypeString() const override {
    return "RNN";
  }

  std::vector<int> DeclareBackwardDependency(
    const std::vector<int> &out_grad,
    const std::vector<int> &in_data,
    const std::vector<int> &out_data) const override {
    std::vector<int> dep = {in_data[rnn_enum::kData], in_data[rnn_enum::kParams],
        in_data[rnn_enum::kState], out_data[rnn_enum::kOut], out_grad[rnn_enum::kOut]};

    if (param_.state_outputs) {
      dep.push_back(out_data[rnn_enum::kStateOut]);
      dep.push_back(out_grad[rnn_enum::kStateOut]);
    }

    if (param_.mode == rnn_enum::kLstm) {
      dep.push_back(in_data[rnn_enum::kStateCell]);
      if (param_.state_outputs) {
        dep.push_back(out_data[rnn_enum::kStateCellOut]);
        dep.push_back(out_grad[rnn_enum::kStateCellOut]);
      }
    }
    return dep;
  }

  std::vector<ResourceRequest> ForwardResource(
      const std::vector<TShape> &in_shape) const override {
    return {ResourceRequest::kTempSpace};
  }

  std::vector<ResourceRequest> BackwardResource(
      const std::vector<TShape> &in_shape) const override {
    return {ResourceRequest::kTempSpace};
  }

  Operator* CreateOperator(Context ctx) const override {
    LOG(FATAL) << "Not Implemented";
    return NULL;
  }

  Operator* CreateOperatorEx(Context ctx, std::vector<TShape> *in_shape,
                             std::vector<int> *in_type) const override;

 private:
  RNNParam param_;
};  // class RNNProp
#endif  // DMLC_USE_CXX11
}  // namespace op
}  // namespace mxnet
#endif  // MXNET_OPERATOR_RNN_INL_H_


text:
import time

def _tail_print(e):
    print("%s %s %s" % (e.resource_status, e.resource_type, e.event_id))

def get_events(conn, stackname):
    """Get the events in batches and return in chronological order"""
    next = None
    event_list = []
    while 1:
        events = conn.describe_stack_events(stackname, next)
        event_list.append(events)
        if events.next_token is None:
            break
        next = events.next_token
        time.sleep(1)
    return reversed(sum(event_list, []))

def tail(conn, stack_name, log_func=_tail_print, sleep_time=5,
         include_initial=True):
    """Show and then tail the event log"""
    # First dump the full list of events in chronological order and keep
    # track of the events we've seen already
    seen = set()
    initial_events = get_events(conn, stack_name)
    for e in initial_events:
        if include_initial:
            log_func(e)
        seen.add(e.event_id)

    # Now keep looping through and dump the new events
    while 1:
        events = get_events(conn, stack_name)
        for e in events:
            if e.event_id not in seen:
                log_func(e)
                seen.add(e.event_id)
        time.sleep(sleep_time)


text:
import * as Rx from "rx";
import * as QUnit from "qunitjs";
import {integrationModule} from "../../integration-test-helpers/integration-test-helpers";
import {UserStorage} from "../../remote-storage/user-storage";
import {
  testObjects,
  testHandlerSync
} from "../../integration-test-helpers/integration-test-helpers";
import {MasterScheduleStorage} from "../../remote-storage/master-schedule-storage";
import {EvernoteClientRx} from "../../evernote-client-rx/evernote-client-rx";
import {EvernoteSyncService} from "../../evernote-mediators/evernote-sync-service";
import {tap} from "../../utils/obj";
import {Evernote} from "evernote";
import {GetMcdsService} from "../get-mcds-service";
import {
  GetMcdsRequest, GetMcdsResponse, PutMcdsRequest,
  PutMcdsResponse
} from "../../api/api-models";
import {PutMcdsService} from "../put-mcds-service";
import {Note, Term, Cloze} from "../../study-model/note-model";

integrationModule("get-put-mcds-service");

function encloseInEnml(body:string) {
  return `<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">
<en-note style="margin:20px">${body}</en-note>`
}

QUnit.test(`
  thing
`, (assert) => {
  var userStorage = new UserStorage(testObjects.db);
  var scheduleStorage = new MasterScheduleStorage(testObjects.db);
  var evernoteClient = new EvernoteClientRx(testObjects.testServer.config.evernoteConfig, undefined, true);
  var userClient = evernoteClient.forUser(testObjects.user);
  var syncService = new EvernoteSyncService(userStorage, evernoteClient, scheduleStorage);
  var getService = new GetMcdsService(evernoteClient, scheduleStorage,
    syncService, testObjects.testServer.timeProvider());
  var putService = new PutMcdsService(evernoteClient, scheduleStorage);
  var getRequest = new GetMcdsRequest();
  var getResponse = new GetMcdsResponse();
  var putRequest = new PutMcdsRequest();
  var putResponse = new PutMcdsResponse();
  var user$ = Rx.Observable.just(testObjects.user);

  var note = new Note();
  putRequest.notes.push(note);

  var term = new Term();
  note.terms.push(term);

  note.text = "This would\n\nbe some note contents\n<For reference>."
  term.marker = "1";
  term.original = "original 1";
  term.details = "Some details would\ngo here\n\n\nand be <escaped> safely.";

  term = new Term();
  note.terms.push(term);

  term.marker = "2";
  term.original = "original 2";
  term.details = "Some more details here";
  term.hint = "hint here";

  var cloze = new Cloze();
  term.clozes.push(cloze);

  cloze.segment = "segment1";
  cloze.schedule.dueAtMinutes = 7483912;
  cloze.schedule.intervalMinutes = 38271;
  cloze.schedule.isNew = true;
  cloze.schedule.lastAnsweredMinutes = 5637114;

  cloze = new Cloze();
  term.clozes.push(cloze);

  cloze.schedule = null;
  cloze.segment = "segment2";

  var noteOneGuid = "";
  var noteTwoGuid = "";
  var noteOneVersion = 0;

  syncService.findOrCreateStudyBook(testObjects.user).flatMap(([guid, updateSequence]) => {
    testObjects.user.studyBook.guid = guid;
    testObjects.user.studyBook.syncVersion = updateSequence;

    return userClient.createNote(tap(new Evernote.Note)(note => {
      note.content = encloseInEnml("Content");
      note.notebookGuid = guid;
      note.title = "Test Note";
    })).doOnNext(note => {
      noteOneGuid = note.guid;
      noteOneVersion = note.updateSequenceNum;
    }).flatMap(() => {
      return userClient.createNote(tap(new Evernote.Note)(note => {
        note.content = encloseInEnml("Content");
        note.notebookGuid = guid;
        note.title = "Test Note";
      })).doOnNext(note => {
        noteTwoGuid = note.guid;
      });
    })
  }).flatMap(() => {
    getRequest.ignoreIds = [noteTwoGuid];
    note.id = noteOneGuid;

    return putService.handle(putRequest, putResponse, user$)
      .ignoreElements()
      .toArray()
      .doOnCompleted(() => {
        assert.deepEqual(putResponse.completedIds, [noteOneGuid]);
      }).doOnCompleted(assert.async());
  }).flatMap(() => {
    return getService.handle(getRequest, getResponse, user$).ignoreElements().toArray();
  }).doOnCompleted(() => {
    assert.equal(getResponse.notes.length, 1);

    var responseNote = getResponse.notes[0];
    assert.equal(responseNote.text, "This would\nbe some note contents\n<For reference>.");
    assert.equal(responseNote.id, note.id);
    assert.equal(responseNote.terms.length, 2);
    assert.ok(responseNote.version > noteOneVersion);

    assert.deepEqual(JSON.parse(JSON.stringify(responseNote.terms[0])), {
      "original": "original 1",
      "marker": "1",
      "details": "",
      "hint": "",
      "imageIds": [],
      "clozes": []
    });

    assert.deepEqual(JSON.parse(JSON.stringify(responseNote.terms[1])), {
      "original": "original 2",
      "marker": "2",
      "details": "",
      "hint": "hint here",
      "imageIds": [],
      "clozes": [{
        "segment": "segment1",
        "schedule": {
          "dueAtMinutes": 7483912,
          "lastAnsweredMinutes": 5637114,
          "intervalMinutes": 38271,
          "isNew": true
        }
      }, {
        "segment": "segment2",
        "schedule": {
          "dueAtMinutes": 420,
          "lastAnsweredMinutes": 0,
          "intervalMinutes": 0,
          "isNew": true
        }
      }]
    });

    assert.equal(responseNote.toString(),
      "This would\nbe some note contents\n<For reference>.\n\n[1] original 1\n\n[2] original 2\n? hint here\n-- segment1 new true due 03-25-1984 03:52 interval PT637H51M last 09-19-1980 15:54\n-- segment2 new true due 01-01-1970 07:00 interval P0D last 01-01-1970 00:00");
  }).catch((e) => {
    console.error(e);
    assert.ok(false, e + "");
    return Rx.Observable.just(null);
  }).finally(assert.async()).subscribe();
});


text:
#ifndef _DDEML_H
#define _DDEML_H
#pragma GCC system_header
#include <_mingw.h>

#ifdef __cplusplus
extern "C" {
#endif

#define EXPENTRY	CALLBACK
#define CP_WINANSI	1004
#define CP_WINUNICODE	1200
#define XTYPF_NOBLOCK	2
#define XTYPF_NODATA	4
#define XTYPF_ACKREQ	8
#define XCLASS_MASK	0xFC00
#define XCLASS_BOOL	0x1000
#define XCLASS_DATA	0x2000
#define XCLASS_FLAGS	0x4000
#define XCLASS_NOTIFICATION	0x8000
#define XST_NULL	0
#define XST_INCOMPLETE	1
#define XST_CONNECTED	2
#define XST_INIT1	3
#define XST_INIT2	4
#define XST_REQSENT	5
#define XST_DATARCVD	6
#define XST_POKESENT	7
#define XST_POKEACKRCVD	8
#define XST_EXECSENT	9
#define XST_EXECACKRCVD	10
#define XST_ADVSENT 11
#define XST_UNADVSENT 12
#define XST_ADVACKRCVD 13
#define XST_UNADVACKRCVD 14
#define XST_ADVDATASENT 15
#define XST_ADVDATAACKRCVD 16
#define XTYP_ERROR	(XCLASS_NOTIFICATION|XTYPF_NOBLOCK)
#define XTYP_ADVDATA	(16|XCLASS_FLAGS)
#define XTYP_ADVREQ	(32|XCLASS_DATA|XTYPF_NOBLOCK)
#define XTYP_ADVSTART	(0x30|XCLASS_BOOL)
#define XTYP_ADVSTOP	(0x0040|XCLASS_NOTIFICATION)
#define XTYP_EXECUTE	(0x0050|XCLASS_FLAGS)
#define XTYP_CONNECT	(0x0060|XCLASS_BOOL|XTYPF_NOBLOCK)
#define XTYP_CONNECT_CONFIRM	(0x0070|XCLASS_NOTIFICATION|XTYPF_NOBLOCK)
#define XTYP_XACT_COMPLETE	(0x0080|XCLASS_NOTIFICATION)
#define XTYP_POKE	(0x0090|XCLASS_FLAGS)
#define XTYP_REGISTER	(0x00A0|XCLASS_NOTIFICATION|XTYPF_NOBLOCK)
#define XTYP_REQUEST	(0x00B0|XCLASS_DATA)
#define XTYP_DISCONNECT	(0x00C0|XCLASS_NOTIFICATION|XTYPF_NOBLOCK)
#define XTYP_UNREGISTER	(0x00D0|XCLASS_NOTIFICATION|XTYPF_NOBLOCK)
#define XTYP_WILDCONNECT	(0x00E0|XCLASS_DATA|XTYPF_NOBLOCK)
#define XTYP_MASK	0xF0
#define XTYP_SHIFT	4
#define TIMEOUT_ASYNC	0xFFFFFFFF
#define QID_SYNC	0xFFFFFFFF
#define ST_CONNECTED	1
#define ST_ADVISE	2
#define ST_ISLOCAL	4
#define ST_BLOCKED	8
#define ST_CLIENT	16
#define ST_TERMINATED	32
#define ST_INLIST	64
#define ST_BLOCKNEXT	128
#define ST_ISSELF	256
#define CADV_LATEACK 0xFFFF
#define DMLERR_NO_ERROR	0
#define DMLERR_FIRST	0x4000
#define DMLERR_ADVACKTIMEOUT	0x4000
#define DMLERR_BUSY	0x4001
#define DMLERR_DATAACKTIMEOUT	0x4002
#define DMLERR_DLL_NOT_INITIALIZED	0x4003
#define	DMLERR_DLL_USAGE	0x4004
#define DMLERR_EXECACKTIMEOUT	0x4005
#define DMLERR_INVALIDPARAMETER	0x4006
#define DMLERR_LOW_MEMORY	0x4007
#define DMLERR_MEMORY_ERROR	0x4008
#define DMLERR_NOTPROCESSED	0x4009
#define DMLERR_NO_CONV_ESTABLISHED	0x400a
#define DMLERR_POKEACKTIMEOUT	0x400b
#define DMLERR_POSTMSG_FAILED	0x400c
#define DMLERR_REENTRANCY	0x400d
#define DMLERR_SERVER_DIED	0x400e
#define DMLERR_SYS_ERROR	0x400f
#define DMLERR_UNADVACKTIMEOUT	0x4010
#define DMLERR_UNFOUND_QUEUE_ID	0x4011
#define DMLERR_LAST	0x4011
#define DDE_FACK	0x8000
#define DDE_FBUSY	0x4000
#define DDE_FDEFERUPD	0x4000
#define DDE_FACKREQ	0x8000
#define DDE_FRELEASE	0x2000
#define DDE_FREQUESTED	0x1000
#define DDE_FAPPSTATUS	0x00ff
#define DDE_FNOTPROCESSED	0
#define DDE_FACKRESERVED	(~(DDE_FACK|DDE_FBUSY|DDE_FAPPSTATUS))
#define DDE_FADVRESERVED	(~(DDE_FACKREQ|DDE_FDEFERUPD))
#define DDE_FDATRESERVED	(~(DDE_FACKREQ|DDE_FRELEASE|DDE_FREQUESTED))
#define DDE_FPOKRESERVED	(~DDE_FRELEASE)
#define MSGF_DDEMGR	0x8001
#define CBR_BLOCK	((HDDEDATA)0xffffffff)
#define CBF_FAIL_SELFCONNECTIONS	0x1000
#define CBF_FAIL_CONNECTIONS	0x2000
#define CBF_FAIL_ADVISES	0x4000
#define CBF_FAIL_EXECUTES	0x8000
#define CBF_FAIL_POKES	0x10000
#define CBF_FAIL_REQUESTS	0x20000
#define CBF_FAIL_ALLSVRXACTIONS	0x3f000
#define CBF_SKIP_CONNECT_CONFIRMS	0x40000
#define CBF_SKIP_REGISTRATIONS	0x80000
#define CBF_SKIP_UNREGISTRATIONS	0x100000
#define CBF_SKIP_DISCONNECTS	0x200000
#define CBF_SKIP_ALLNOTIFICATIONS	0x3c0000
#define APPCMD_CLIENTONLY	0x10L
#define APPCMD_FILTERINITS	0x20L
#define APPCMD_MASK	0xFF0L
#define APPCLASS_STANDARD	0
#define APPCLASS_MASK	0xFL
#define EC_ENABLEALL	0
#define EC_ENABLEONE	ST_BLOCKNEXT
#define EC_DISABLE	ST_BLOCKED
#define EC_QUERYWAITING	2
#define DNS_REGISTER	1
#define DNS_UNREGISTER	2
#define DNS_FILTERON	4
#define DNS_FILTEROFF	8
#define HDATA_APPOWNED	1
#define MAX_MONITORS	4
#define APPCLASS_MONITOR	1L
#define XTYP_MONITOR	(XCLASS_NOTIFICATION|XTYPF_NOBLOCK|0xF0)
#define MF_HSZ_INFO	0x1000000
#define MF_SENDMSGS	0x2000000
#define MF_POSTMSGS	0x4000000
#define MF_CALLBACKS	0x8000000
#define MF_ERRORS	0x10000000
#define MF_LINKS	0x20000000
#define MF_CONV	0x40000000
#define MF_MASK 0xFF000000
#define MH_CREATE	1
#define MH_KEEP	2
#define MH_DELETE	3
#define MH_CLEANUP	4

DECLARE_HANDLE(HCONVLIST);
DECLARE_HANDLE(HCONV);
DECLARE_HANDLE(HSZ);
DECLARE_HANDLE(HDDEDATA);
typedef HDDEDATA CALLBACK FNCALLBACK(UINT,UINT,HCONV,HSZ,HSZ,HDDEDATA,DWORD,DWORD);
typedef HDDEDATA(CALLBACK *PFNCALLBACK)(UINT,UINT,HCONV,HSZ,HSZ,HDDEDATA,DWORD,DWORD);
typedef struct tagHSZPAIR {
	HSZ	hszSvc;
	HSZ	hszTopic;
} HSZPAIR, *PHSZPAIR;
typedef struct tagCONVCONTEXT {
	UINT	cb;
	UINT	wFlags;
	UINT	wCountryID;
	int	iCodePage;
	DWORD	dwLangID;
	DWORD	dwSecurity;
	SECURITY_QUALITY_OF_SERVICE qos;
} CONVCONTEXT,*PCONVCONTEXT;
typedef struct tagCONVINFO {
	DWORD	cb;
	DWORD	hUser;
	HCONV	hConvPartner;
	HSZ	hszSvcPartner;
	HSZ	hszServiceReq;
	HSZ	hszTopic;
	HSZ	hszItem;
	UINT	wFmt;
	UINT	wType;
	UINT	wStatus;
	UINT	wConvst;
	UINT	wLastError;
	HCONVLIST	hConvList;
	CONVCONTEXT ConvCtxt;
	HWND	hwnd;
	HWND	hwndPartner;
} CONVINFO,*PCONVINFO;
typedef struct tagDDEML_MSG_HOOK_DATA {
	UINT	uiLo;
	UINT	uiHi;
	DWORD	cbData;
	DWORD	Data[8];
} DDEML_MSG_HOOK_DATA;
typedef struct tagMONHSZSTRUCT {
	UINT	cb;
	BOOL	fsAction;
	DWORD	dwTime;
	HSZ	hsz;
	HANDLE	hTask;
	TCHAR	str[1];
} MONHSZSTRUCT, *PMONHSZSTRUCT;
typedef struct tagMONLINKSTRUCT {
	UINT	cb;
	DWORD	dwTime;
	HANDLE	hTask;
	BOOL	fEstablished;
	BOOL	fNoData;
	HSZ	hszSvc;
	HSZ	hszTopic;
	HSZ	hszItem;
	UINT	wFmt;
	BOOL	fServer;
	HCONV	hConvServer;
	HCONV	hConvClient;
} MONLINKSTRUCT, *PMONLINKSTRUCT;
typedef struct tagMONCONVSTRUCT {
	UINT	cb;
	BOOL	fConnect;
	DWORD	dwTime;
	HANDLE	hTask;
	HSZ	hszSvc;
	HSZ	hszTopic;
	HCONV	hConvClient;
	HCONV	hConvServer;
} MONCONVSTRUCT, *PMONCONVSTRUCT;
typedef struct tagMONCBSTRUCT {
	UINT	cb;
	DWORD	dwTime;
	HANDLE	hTask;
	DWORD	dwRet;
	UINT	wType;
	UINT	wFmt;
	HCONV	hConv;
	HSZ	hsz1;
	HSZ	hsz2;
	HDDEDATA	hData;
	ULONG_PTR	dwData1;
	ULONG_PTR	dwData2;
	CONVCONTEXT	cc;
	DWORD	cbData;
	DWORD	Data[8];
} MONCBSTRUCT, *PMONCBSTRUCT;
typedef struct tagMONERRSTRUCT {
	UINT	cb;
	UINT	wLastError;
	DWORD	dwTime;
	HANDLE	hTask;
} MONERRSTRUCT, *PMONERRSTRUCT;
typedef struct tagMONMSGSTRUCT {
	UINT	cb;
	HWND	hwndTo;
	DWORD	dwTime;
	HANDLE	hTask;
	UINT	wMsg;
	WPARAM	wParam;
	LPARAM	lParam;
	DDEML_MSG_HOOK_DATA dmhd;
} MONMSGSTRUCT, *PMONMSGSTRUCT;

BOOL WINAPI DdeAbandonTransaction(DWORD,HCONV,DWORD);
PBYTE WINAPI DdeAccessData(HDDEDATA,PDWORD);
HDDEDATA WINAPI DdeAddData(HDDEDATA,PBYTE,DWORD,DWORD);
HDDEDATA WINAPI DdeClientTransaction(PBYTE,DWORD,HCONV,HSZ,UINT,UINT,DWORD,PDWORD);
int WINAPI DdeCmpStringHandles(HSZ,HSZ);
HCONV WINAPI DdeConnect(DWORD,HSZ,HSZ,PCONVCONTEXT);
HCONVLIST WINAPI DdeConnectList(DWORD,HSZ,HSZ,HCONVLIST,PCONVCONTEXT);
HDDEDATA WINAPI DdeCreateDataHandle(DWORD,PBYTE,DWORD,DWORD,HSZ,UINT,UINT);
HSZ WINAPI DdeCreateStringHandleA(DWORD,LPCSTR,int);
HSZ WINAPI DdeCreateStringHandleW(DWORD,LPCWSTR,int);
BOOL WINAPI DdeDisconnect(HCONV);
BOOL WINAPI DdeDisconnectList(HCONVLIST);
BOOL WINAPI DdeEnableCallback(DWORD,HCONV,UINT);
BOOL WINAPI DdeFreeDataHandle(HDDEDATA);
BOOL WINAPI DdeFreeStringHandle(DWORD,HSZ);
DWORD WINAPI DdeGetData(HDDEDATA,PBYTE,DWORD,DWORD);
UINT WINAPI DdeGetLastError(DWORD);
BOOL WINAPI DdeImpersonateClient(HCONV);
UINT WINAPI DdeInitializeA(PDWORD,PFNCALLBACK,DWORD,DWORD);
UINT WINAPI DdeInitializeW(PDWORD,PFNCALLBACK,DWORD,DWORD);
BOOL WINAPI DdeKeepStringHandle(DWORD,HSZ);
HDDEDATA WINAPI DdeNameService(DWORD,HSZ,HSZ,UINT);
BOOL WINAPI DdePostAdvise(DWORD,HSZ,HSZ);
UINT WINAPI DdeQueryConvInfo(HCONV,DWORD,PCONVINFO);
HCONV WINAPI DdeQueryNextServer(HCONVLIST,HCONV);
DWORD WINAPI DdeQueryStringA(DWORD,HSZ,LPSTR,DWORD,int);
DWORD WINAPI DdeQueryStringW(DWORD,HSZ,LPWSTR,DWORD,int);
HCONV WINAPI DdeReconnect(HCONV);
BOOL WINAPI DdeSetUserHandle(HCONV,DWORD,DWORD);
BOOL WINAPI DdeUnaccessData(HDDEDATA);
BOOL WINAPI DdeUninitialize(DWORD);

#define SZDDESYS_TOPIC	__STR("System")
#define SZDDESYS_ITEM_TOPICS	__STR("Topics")
#define SZDDESYS_ITEM_SYSITEMS	__STR("SysItems")
#define SZDDESYS_ITEM_RTNMSG	__STR("ReturnMessage")
#define SZDDESYS_ITEM_STATUS	__STR("Status")
#define SZDDESYS_ITEM_FORMATS	__STR("Formats")
#define SZDDESYS_ITEM_HELP	__STR("Help")
#define SZDDE_ITEM_ITEMLIST	__STR("TopicItemList")
#define DdeCreateStringHandle __AW(DdeCreateStringHandle)
#define DdeInitialize __AW(DdeInitialize)
#define DdeQueryString __AW(DdeQueryString)

#ifdef __cplusplus
}
#endif
#endif /* _DDEML_H */


text:
require_relative '../spec_helper'

describe 'drain', type: :integration do
  let(:deployment_name) { 'simple' }

  with_reset_sandbox_before_each

  describe 'static drain' do
    before do
      cloud_config_hash = Bosh::Spec::NewDeployments.simple_cloud_config

      manifest_hash = Bosh::Spec::NewDeployments.simple_manifest_with_instance_groups
      manifest_hash['releases'].first['version'] = 'latest'
      manifest_hash['instance_groups'][0]['instances'] = 1

      deploy_from_scratch(cloud_config_hash: cloud_config_hash, manifest_hash: manifest_hash)

      manifest_hash['instance_groups'][0]['persistent_disk'] = 100
      manifest_hash['instance_groups'].first['jobs'].first['properties'] ||= {}
      manifest_hash['instance_groups'].first['jobs'].first['properties']['test_property'] = 0
      deploy_simple_manifest(manifest_hash: manifest_hash)
    end

    it 'runs the drain script on a job if drain script is present' do
      drain_log = director.instance('foobar', '0').read_file('drain-test.log')
      expect(drain_log).to eq("job_shutdown hash_unchanged\n1\n")
    end

    it 'sets BOSH_JOB_STATE and BOSH_JOB_NEXT_STATE env vars with changed values' do
      drain_log = director.instance('foobar', '0').read_file('drain-job-state.log')
      expect(drain_log).to include('BOSH_JOB_STATE={"persistent_disk":0}')
      expect(drain_log).to include('BOSH_JOB_NEXT_STATE={"persistent_disk":100}')
    end
  end

  describe 'dynamic drain' do
    before do
      cloud_config_hash = Bosh::Spec::NewDeployments.simple_cloud_config

      manifest_hash = Bosh::Spec::NewDeployments.simple_manifest_with_instance_groups
      manifest_hash['releases'].first['version'] = 'latest'
      manifest_hash['instance_groups'][0]['instances'] = 1
      manifest_hash['instance_groups'].first['jobs'].first['properties'] ||= {}
      manifest_hash['instance_groups'].first['jobs'].first['properties']['drain_type'] = 'dynamic'

      deploy_from_scratch(cloud_config_hash: cloud_config_hash, manifest_hash: manifest_hash)

      manifest_hash['instance_groups'].first['jobs'].first['properties']['test_property'] = 0
      deploy_simple_manifest(manifest_hash: manifest_hash)
    end

    it 'retries after the appropriate amount of time' do
      drain_log = director.instance('foobar', '0').read_file('drain-test.log')
      drain_times = drain_log.split.map(&:to_i)
      expect(drain_times.size).to eq(3)
      expect(drain_times[1] - drain_times[0]).to be >= 3
      expect(drain_times[2] - drain_times[1]).to be >= 2
    end
  end

  context 'when skip-drain flag is not provided' do
    before do
      deploy_from_scratch(manifest_hash: Bosh::Spec::NewDeployments.simple_manifest_with_instance_groups, cloud_config_hash: Bosh::Spec::NewDeployments.simple_cloud_config)
      director.instances.each do |instance|
        expect(File).not_to exist( instance.file_path('drain-test.log'))
      end
    end

    def drain_file
      director.instance('foobar', '0').file_path('drain-test.log')
    end

    it 'runs drain script for recreate' do
      drain_path_before_recreate = drain_file
      bosh_runner.run('recreate foobar/0', deployment_name: deployment_name)
      expect(File).to exist(drain_path_before_recreate)
    end

    it 'runs drain script for stop' do
      bosh_runner.run('stop foobar/0', deployment_name: deployment_name)
      expect(File).to exist(drain_file)
    end

    it 'runs drain script for restart' do
      bosh_runner.run('restart foobar/0', deployment_name: deployment_name)
      expect(File).to exist(drain_file)
    end

    it 'runs drain scripts for change state of the deployment' do
      bosh_runner.run('stop', deployment_name: deployment_name)
      director.instances.each do |instance|
        expect(File).to exist( instance.file_path('drain-test.log'))
      end
    end

    it 'runs drain scripts for change state of the job' do
      bosh_runner.run('restart foobar', deployment_name: deployment_name)
      director.instances.each do |instance|
        expect(File).to exist( instance.file_path('drain-test.log'))
      end
    end
  end

  context 'when skip-drain flag is provided' do
    let(:manifest_with_drain) do
      manifest_hash = Bosh::Spec::NewDeployments.simple_manifest_with_instance_groups
      manifest_hash['instance_groups'][0]['instances'] = 1
      manifest_hash['instance_groups'].first['jobs'].first['properties'] = { 'test_property' => 'drained' }
      manifest_hash
    end

    before do
      deploy_from_scratch(manifest_hash: manifest_with_drain, cloud_config_hash: Bosh::Spec::NewDeployments.simple_cloud_config)
    end

    def drain_file
      director.instance('foobar', '0').file_path('drain-test.log')
    end

    it 'does not run drain script for recreate' do
      drain_path_before_recreate = drain_file
      bosh_runner.run('recreate foobar/0 --skip-drain', deployment_name: deployment_name)
      expect(File).not_to exist(drain_path_before_recreate)
    end

    it 'does not run drain script for stop' do
      bosh_runner.run('stop foobar/0 --skip-drain', deployment_name: deployment_name)
      expect(File).not_to exist(drain_file)
    end

    it 'does not run drain script for restart' do
      bosh_runner.run('restart foobar/0 --skip-drain', deployment_name: deployment_name)
      expect(File).not_to exist(drain_file)
    end

    context 'with multiple deployment instance groups' do
      let(:manifest_with_drain) do
        manifest_hash = Bosh::Spec::NewDeployments.simple_manifest_with_instance_groups
        manifest_hash['instance_groups'][0]['instances'] = 1
        manifest_hash['instance_groups'].first['jobs'].first['properties'] = { 'test_property' => 'drained' }
        manifest_hash['instance_groups'] << Bosh::Spec::NewDeployments.simple_instance_group(name: 'second', instances: 1)
        manifest_hash['instance_groups'] << Bosh::Spec::NewDeployments.simple_instance_group(name: 'third', instances: 1)
        manifest_hash
      end

      it 'skips drain for specified instance_groups' do
        foobar_drain_file = director.instance('foobar', '0').file_path('drain-test.log')
        second_drain_file = director.instance('second', '0').file_path('drain-test.log')
        third_drain_file = director.instance('third', '0').file_path('drain-test.log')

        deploy_simple_manifest(manifest_hash: manifest_with_drain, recreate: true, skip_drain: ['second', 'third'])
        expect(File).not_to exist(second_drain_file)
        expect(File).not_to exist(third_drain_file)
        expect(File.read(foobar_drain_file)).to include('drained')
      end

      it 'skips drain for all instance_groups' do
        foobar_drain_file = director.instance('foobar', '0').file_path('drain-test.log')
        second_drain_file = director.instance('second', '0').file_path('drain-test.log')

        deploy_simple_manifest(manifest_hash: manifest_with_drain, recreate: true, skip_drain: true)
        expect(File).not_to exist(foobar_drain_file)
        expect(File).not_to exist(second_drain_file)
      end

      it 'does not run drain scripts for change state of the specified job' do
        bosh_runner.run('stop --skip-drain foobar', deployment_name: deployment_name)
        foobar_drain_file = director.instance('foobar', '0').file_path('drain-test.log')
        expect(File).not_to exist(foobar_drain_file)
      end

      it 'does not run drain scripts for change state of the deployment' do
        bosh_runner.run('stop --skip-drain', deployment_name: deployment_name)
        director.instances.each do |instance|
          expect(File).not_to exist( instance.file_path('drain-test.log'))
        end
      end
    end
  end

  context 'with one deployment instance group having colocated jobs, some of which have drain scripts' do
    let(:manifest_with_colocated_drainable_release_jobs) do
      Bosh::Spec::NewDeployments.test_release_manifest_with_stemcell.merge(
          'instance_groups' => [
              Bosh::Spec::NewDeployments.instance_group_with_many_jobs(
                  name: 'colocated',
                  jobs: [
                      {'name' => 'job_1_with_pre_start_script', 'release' => 'bosh-release'},
                      {'name' => 'foobar', 'release' => 'bosh-release'},
                      {'name' => 'has_drain_script', 'release' => 'bosh-release'},
                  ],
                  instances: 1,
              )
          ],
          'properties' => {
              'test_property' => 'multi-drain',
              'drain_type' => 'static',
          }
      )
    end

    it 'runs drain for jobs that have drain script' do
      deploy_from_scratch(manifest_hash: manifest_with_colocated_drainable_release_jobs, cloud_config_hash: Bosh::Spec::NewDeployments.simple_cloud_config)

      foobar_drain_log = director.instance('colocated', '0').file_path('drain-test.log')
      second_drain_log = director.instance('colocated', '0').file_path('has_drain_script_drain.log')

      deploy_simple_manifest(manifest_hash: manifest_with_colocated_drainable_release_jobs, recreate: true)

      expect(File).to exist(foobar_drain_log)
      expect(File.read(foobar_drain_log)).to include('multi-drain')

      expect(File).to exist(second_drain_log)
      expect(File.read(second_drain_log)).to include('multi-drain')
    end
  end
end


text:
using Newtonsoft.Json;

namespace Kondor.Data.ApiModels
{
    public class TelegramApiResponseModel
    {
        [JsonProperty("ok")]
        public bool Ok { get; set; }

        [JsonProperty("result")]
        public object Result { get; set; }
    }
}


text:
namespace LiteCppDB
{
	void LiteEngine::BeginTrans() noexcept
	{
	}

	bool LiteEngine::Commit() noexcept
	{
		return false;
	}

	void LiteEngine::Rollback() noexcept
	{
	}
}


text:
layout: post
date:	2008-01-25 06:35:00
title:  Patterns
tags: [archived-posts]
categories: archives
permalink: /:categories/:year/:month/:day/:title/
---
I got to liking the shapes of images, after I looked at the photographs of <LJ user="deepsan">, who has been  posting the images of his trips lately, after a long gap.

I went out today to see if I could snap some pics of the cardinals, but what I got was ....

<lj-cut text="plus two">

and

</lj-cut>

I realize that I have been learning about different aspects of photography, and images, from different people...there's still so much to learn. I am not gadget- or technically-oriented, and  it's very slow going...


text:
import { NativeModulesProxy } from 'expo-modules-core';
export default NativeModulesProxy.ExpoAmplitude || {};
//# sourceMappingURL=ExpoAmplitude.js.map


text:
module ODBCExt

  # ------------------------------------------------------------------------
  # Mandatory methods
  #

  # #last_insert_id must be implemented for any database which returns
  # false from #prefetch_primary_key?
  def last_insert_id(table, sequence_name, stmt = nil)
     @logger.unknown("ODBCAdapter#last_insert_id>") if @trace
    select_value("select @@IDENTITY", 'last_insert_id')
  end

  # ------------------------------------------------------------------------
  # Optional methods
  #
  # These are supplied for a DBMS only if necessary.
  # ODBCAdapter tests for optional methods using Object#respond_to?

  # Pre action for ODBCAdapter#insert
  def pre_insert(sql, name, pk, id_value, sequence_name)
    @iiTable = get_table_name(sql)
    @iiCol = get_autounique_column(@iiTable)
    @iiEnabled = false

    if @iiCol != nil
      if query_contains_autounique_col(sql, @iiCol)
        begin
          @connection.do(enable_identity_insert(@iiTable, true))
          @iiEnabled = true
        rescue Exception => e
          raise ActiveRecordError, "IDENTITY_INSERT could not be turned on"
        end
      end
    end
  end

  # Post action for ODBCAdapter#insert
  def post_insert(sql, name, pk, id_value, sequence_name)
    if @iiEnabled
      begin
        @connection.do(enable_identity_insert(@iiTable, false))
      rescue Exception => e
        raise ActiveRecordError, "IDENTITY_INSERT could not be turned off"
      end
    end
  end

  # ------------------------------------------------------------------------
  # Method redefinitions
  #
  # DBMS specific methods which override the default implementation
  # provided by the ODBCAdapter core.

   def get_table_name(sql)
    if sql =~ /^\s*insert\s+into\s+([^\(\s]+)\s*|^\s*update\s+([^\(\s]+)\s*/i
      $1
    elsif sql =~ /from\s+([^\(\s]+)\s*/i
      $1
    else
      nil
    end	end

    def get_autounique_column(table_name)
    @table_columns = {} unless @table_columns
    @table_columns[table_name] = columns(table_name) if @table_columns[table_name] == nil
    @table_columns[table_name].each do |col|
      return col.name if col.auto_unique?
    end

    return nil
  end

  def query_contains_autounique_col(sql, col)
    sql =~ /(\[#{col}\])|("#{col}")/
  end

  def enable_identity_insert(table_name, enable = true)
    if has_autounique_column(table_name)
    	"SET IDENTITY_INSERT #{table_name} #{enable ? 'ON' : 'OFF'}"
    end
  end

  def has_autounique_column(table_name)
    !get_autounique_column(table_name).nil?
  end

end # module


text:
import * as minimatch from "minimatch";
import { CancellationToken, DocumentFormattingEditProvider, DocumentSelector, FormattingOptions, languages, OnTypeFormattingEditProvider, Position, Range, TextDocument, TextEdit, window, workspace } from "vscode";
import * as as from "../../shared/analysis_server_types";
import { IAmDisposable, Logger } from "../../shared/interfaces";
import { disposeAll } from "../../shared/utils";
import { fsPath } from "../../shared/utils/fs";
import { Context } from "../../shared/vscode/workspace";
import { DasAnalyzerClient } from "../analysis/analyzer_das";
import { config } from "../config";

export class DartFormattingEditProvider implements DocumentFormattingEditProvider, OnTypeFormattingEditProvider, IAmDisposable {
	constructor(private readonly logger: Logger, private readonly analyzer: DasAnalyzerClient, private readonly context: Context) {
		workspace.onDidChangeConfiguration((e) => {
			if (e.affectsConfiguration("dart.enableSdkFormatter")) {
				if (config.enableSdkFormatter)
					this.registerAllFormatters();
				else
					this.unregisterAllFormatters();
			}
		});
	}

	private readonly registeredFormatters: IAmDisposable[] = [];
	private readonly formatterRegisterFuncs: Array<() => void> = [];

	public registerDocumentFormatter(filter: DocumentSelector): void {
		this.registerFormatter(() => languages.registerDocumentFormattingEditProvider(filter, this));
	}

	public registerTypingFormatter(filter: DocumentSelector, firstTriggerCharacter: string, ...moreTriggerCharacters: string[]): void {
		this.registerFormatter(() => languages.registerOnTypeFormattingEditProvider(filter, this, firstTriggerCharacter, ...moreTriggerCharacters));
	}

	private registerFormatter(reg: () => IAmDisposable) {
		const registerAndTrack = () => this.registeredFormatters.push(reg());
		// Register the formatter immediately if enabled.
		if (config.enableSdkFormatter)
			registerAndTrack();

		// Add it to our list so we can re-register later..
		this.formatterRegisterFuncs.push(registerAndTrack);
	}

	private registerAllFormatters() {
		for (const formatterReg of this.formatterRegisterFuncs) {
			formatterReg();
		}
	}

	private unregisterAllFormatters() {
		disposeAll(this.registeredFormatters);
	}

	public async provideDocumentFormattingEdits(document: TextDocument, options: FormattingOptions, token: CancellationToken): Promise<TextEdit[] | undefined> {
		try {
			return await this.doFormat(document, true); // await is important for catch to work.
		} catch {
			if (!this.context.hasWarnedAboutFormatterSyntaxLimitation) {
				this.context.hasWarnedAboutFormatterSyntaxLimitation = true;
				window.showInformationMessage("The Dart formatter will not run if the file has syntax errors");
			}
			return undefined;
		}
	}

	public async provideOnTypeFormattingEdits(document: TextDocument, position: Position, ch: string, options: FormattingOptions, token: CancellationToken): Promise<TextEdit[] | undefined> {
		try {
			return await this.doFormat(document, false);
		} catch {
			return undefined;
		}
	}

	private async doFormat(document: TextDocument, doLogError = true): Promise<TextEdit[] | undefined> {
		if (!this.shouldFormat(document))
			return undefined;
		try {
			const resp = await this.analyzer.editFormat({
				file: fsPath(document.uri),
				lineLength: config.for(document.uri).lineLength,
				selectionLength: 0,
				selectionOffset: 0,
			});
			if (resp.edits.length === 0)
				return undefined;
			else
				return resp.edits.map((e) => this.convertData(document, e));
		} catch (e) {
			if (doLogError)
				this.logger.error(e);
			throw e;
		}
	}

	private shouldFormat(document: TextDocument): boolean {
		if (!document || !document.uri || document.uri.scheme !== "file")
			return false;

		const resourceConf = config.for(document.uri);
		const path = fsPath(document.uri);

		return undefined === resourceConf.doNotFormat.find((p) => minimatch(path, p, { dot: true }));
	}

	private convertData(document: TextDocument, edit: as.SourceEdit): TextEdit {
		return new TextEdit(
			new Range(document.positionAt(edit.offset), document.positionAt(edit.offset + edit.length)),
			edit.replacement,
		);
	}

	public dispose() {
		this.unregisterAllFormatters();
	}
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using StreamJsonRpc;

namespace Microsoft.CodeAnalysis.LanguageServer
{
    internal interface ILanguageServerFactory
    {
        public ILanguageServerTarget Create(
            JsonRpc jsonRpc,
            ICapabilitiesProvider capabilitiesProvider,
            ILspLogger logger);
    }
}


text:
import Controller from './lib/Controller';
import nunjucks from 'nunjucks';

function getName(context) {
  // default values
  let name = {
    fname: 'Rick',
    lname: 'Sanchez'
  };
  // split path params
  let nameParts = context.params.name ? context.params.name.split('/') : [];

  // order of precedence
  // 1. path param
  // 2. query param
  // 3. default value
  name.fname = (nameParts[0] || context.query.fname) ||
    name.fname;
  name.lname = (nameParts[1] || context.query.lname) ||
    name.lname;

  return name;
}

export default class HelloController extends Controller {

  index(application, request, reply, callback) {
    this.context.cookie.set('random', '_' + (Math.floor(Math.random() * 1000) + 1), { path: '/' });
    this.context.data = { random: Math.floor(Math.random() * 1000) + 1 };
    callback(null);
  }

  toString(callback) {
    // this can be handled more eloquently using Object.assign
    // but we are not including for the sake of simplicity
    let context = getName(this.context);
    context.data = this.context.data;

    nunjucks.render('hello.html', context, (err, html) => {
      if (err) {
        return callback(err, null);
      }

      callback(null, html);
    });
  }

  attach(el) {
    console.log(this.context.data.random);
    this.clickHandler = el.addEventListener('click', function (e) {
      console.log(e.currentTarget);
    }, false);
  }

}


text:
namespace onnxruntime {
namespace cuda {

class CumSum final : public CudaKernel {
 public:
  explicit CumSum(const OpKernelInfo& info) : CudaKernel(info) {
    // Process exclusive attribute
    int64_t exclusive = 0;
    auto status = info.GetAttr("exclusive", &exclusive);
    if (status.IsOK()) {
      if (exclusive == 1 || exclusive == 0) {
        exclusive_ = (exclusive == 1);
      } else {
        ORT_ENFORCE("attribute exclusive can only be 0 or 1");
      }
    }

    // Process reverse attribute
    int64_t reverse = 0;
    status = info.GetAttr("reverse", &reverse);
    if (status.IsOK()) {
      if (reverse == 1 || reverse == 0) {
        reverse_ = (reverse == 1);
      } else {
        ORT_ENFORCE("attribute reverse can only be 0 or 1");
      }
    }
  }

  ~CumSum() = default;

  Status ComputeInternal(OpKernelContext* ctx) const override;

 private:
  bool exclusive_ = false;
  bool reverse_ = false;
};

}  // namespace cuda
}  // namespace onnxruntime


text:
<?php

use app\components\widgets\Alert;
use app\modules\admin\Module;
use yii\helpers\ArrayHelper;
use yii\bootstrap\Nav;
use yii\bootstrap\NavBar;
use yii\widgets\Breadcrumbs;

/* @var $this \yii\web\View */
/* @var $content string */

/** @var \yii\web\Controller $context */
$context = $this->context;

if (isset($this->params['breadcrumbs'])) {
    $panelBreadcrumbs = [['label' => Module::t('module', 'ADMIN'), 'url' => ['/admin/default/index']]];
    $breadcrumbs = $this->params['breadcrumbs'];
} else {
    $panelBreadcrumbs = [Module::t('module', 'ADMIN')];
    $breadcrumbs = [];
}
?>
<?php $this->beginContent('@app/views/layouts/layout.php'); ?>

<?php
NavBar::begin([
    'brandLabel' => Yii::$app->name,
    'brandUrl' => Yii::$app->homeUrl,
    'options' => [
        'class' => 'navbar-inverse navbar-fixed-top',
    ],
]);
echo Nav::widget([
    'options' => ['class' => 'navbar-nav navbar-right'],
    'activateParents' => true,
    'items' => array_filter([
        ['label' => Yii::t('app', 'NAV_ADMIN'), 'url' => ['/admin/default/index']],
        ['label' => Yii::t('app', 'NAV_ADMIN_USERS'), 'url' => ['/admin/users/default/index'], 'active' => $context->module->id == 'users'],
        ['label' => Yii::t('app', 'NAV_LOGOUT'), 'url' => ['/user/default/logout'], 'linkOptions' => ['data-method' => 'post']]
    ]),
]);
NavBar::end();
?>

<div class="container">
    <?= Breadcrumbs::widget([
        'links' => ArrayHelper::merge($panelBreadcrumbs, $breadcrumbs),
    ]) ?>
    <?= Alert::widget() ?>
    <?= $content ?>
</div>

<?php $this->endContent(); ?>


text:
'use strict';

module.exports = function(grunt) {

  var path = require('path');

  var SourceMapConsumer = require('source-map').SourceMapConsumer;
  var SourceMapGenerator = require('source-map').SourceMapGenerator;
  var SourceNode = require('source-map').SourceNode;

  // source map file of input
  var sourceMaps = [];

  grunt.registerMultiTask('concat_sourcemap', 'Concatenate files and generate a source map.', function() {
    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options({
      separator: grunt.util.linefeed,
      sourceRoot: '',
      sourcesContent: false
    });

    // Iterate over all src-dest file pairs.
    this.files.forEach(function(f) {

      var sourceNode = new SourceNode();

      // Warn on and remove invalid source files (if nonull was set).
      var filepaths = f.src.filter(function(filepath) {
        if (!grunt.file.exists(filepath)) {
          grunt.log.warn('Source file "' + filepath + '" not found.');
          return false;
        } else {
          return true;
        }
      });

      // Concatenate files with using SourceNode.
      var i, l, j, m;
      for (i = 0, l = filepaths.length; i < l; i++) {
        // Read file source.
        var filename = filepaths[i];
        var src = grunt.file.read(filename);
        var childNodeChunks = src.split('\n');
        for (j = 0, m = childNodeChunks.length - 1; j < m; j++) {
          childNodeChunks[j] += '\n';
        }
        childNodeChunks.map(function(line) {
          if (/\/\/[@#]\s+sourceMappingURL=(.+)/.test(line) || /\/\*#\s+sourceMappingURL=([^\s]+)\s+\*\//.test(line)) {
            var sourceMapPath = filename.replace(/[^\/]*$/, RegExp.$1);
            var sourceMap = JSON.parse(grunt.file.read(sourceMapPath));

            // The source map generated by sass 3.3.0.rc.1 seems to be wrong format.
            if (typeof sourceMap.version === 'string') {
              sourceMap.version = parseInt(sourceMap.version, 10);
            }
            if (typeof sourceMap.names === 'undefined') {
              sourceMap.names = [];
            }

            sourceMap.file = filename;
            var sourceRoot = path.resolve(path.dirname(filename), (sourceMap.sourceRoot || ''));
            sourceMap.sources = sourceMap.sources.map(function(source){
              return path.relative(process.cwd(), path.join(sourceRoot, source));
            });
            delete sourceMap.sourceRoot;
            sourceMaps.push(sourceMap);
            return line.replace(/[@#]\s+sourceMappingURL=[\w\.]+/, '');
          }
          return line;
        }).forEach(function(line, j){
          sourceNode.add(new SourceNode(j + 1, 0, filename, line));
        });
        sourceNode.add(options.separator);
        if(options.sourcesContent) {
          sourceNode.setSourceContent(filename, src);
        }
      }

      var mapfilepath = f.dest.split('/').pop() + '.map';
      if (/\.css$/.test(f.dest)) {
        sourceNode.add('/*# sourceMappingURL=' + mapfilepath + ' */');
      } else {
        sourceNode.add('//# sourceMappingURL=' + mapfilepath);
      }

      var code_map = sourceNode.toStringWithSourceMap({
        file: f.dest,
        sourceRoot: options.sourceRoot
      });

      // Write the destination file.
      grunt.file.write(f.dest, code_map.code);

      // Write the source map file.
      var generator = SourceMapGenerator.fromSourceMap(new SourceMapConsumer(code_map.map.toJSON()));
      sourceMaps.forEach(function(sourceMap){
        generator.applySourceMap(new SourceMapConsumer(sourceMap));
      });
      var newSourceMap = generator.toJSON();
      newSourceMap.file = path.basename(newSourceMap.file);
      grunt.file.write(f.dest + '.map', JSON.stringify(newSourceMap, null, '  '));

      // Print a success message.
      grunt.log.writeln('File "' + f.dest + '" created.');
    });
  });

};


text:
namespace {

namespace cast_crypto = ::cast_certificate;

// Parses |pem_data| for a PEM block of |pem_type|.
// Returns true if a |pem_type| block is found, storing the decoded result in
// |der_output|.
bool GetDERFromPEM(const std::string& pem_data,
                   const std::string& pem_type,
                   std::vector<uint8_t>* der_output) {
  std::vector<std::string> headers;
  headers.push_back(pem_type);
  net::PEMTokenizer pem_tokenizer(pem_data, headers);
  if (!pem_tokenizer.GetNext()) {
    return false;
  }

  der_output->assign(pem_tokenizer.data().begin(), pem_tokenizer.data().end());
  return true;
}

}  // namespace

namespace networking_private_crypto {

bool VerifyCredentials(
    const std::string& certificate,
    const std::vector<std::string>& intermediate_certificates,
    const std::string& signature,
    const std::string& data,
    const std::string& connected_mac) {
  base::Time now = base::Time::Now();
  return VerifyCredentialsAtTime(certificate, intermediate_certificates,
                                 signature, data, connected_mac, now);
}

bool VerifyCredentialsAtTime(
    const std::string& certificate,
    const std::vector<std::string>& intermediate_certificates,
    const std::string& signature,
    const std::string& data,
    const std::string& connected_mac,
    const base::Time& time) {
  static const char kErrorPrefix[] = "Device verification failed. ";

  std::vector<std::string> headers;
  headers.push_back("CERTIFICATE");

  // Convert certificate from PEM to raw DER
  net::PEMTokenizer pem_tokenizer(certificate, headers);
  if (!pem_tokenizer.GetNext()) {
    LOG(ERROR) << kErrorPrefix << "Failed to parse device certificate.";
    return false;
  }

  // |certs| is a vector with the DER for all the certificates.
  std::vector<std::string> certs;
  certs.push_back(pem_tokenizer.data());

  // Convert intermediate certificates from PEM to raw DER
  for (size_t idx = 0; idx < intermediate_certificates.size(); ++idx) {
    net::PEMTokenizer ica_pem_tokenizer(intermediate_certificates[idx],
                                        headers);
    if (ica_pem_tokenizer.GetNext()) {
      certs.push_back(ica_pem_tokenizer.data());
    } else {
      LOG(WARNING) << "Failed to parse intermediate certificates.";
    }
  }

  // Note that the device certificate's policy is not enforced here. The goal
  // is simply to verify that the device belongs to the Cast ecosystem.
  cast_crypto::CastDeviceCertPolicy unused_policy;

  std::unique_ptr<cast_crypto::CertVerificationContext> verification_context;
  if (!cast_crypto::VerifyDeviceCert(certs, time, &verification_context,
                                     &unused_policy, nullptr,
                                     cast_crypto::CRLPolicy::CRL_OPTIONAL)) {
    LOG(ERROR) << kErrorPrefix << "Failed verifying cast device cert";
    return false;
  }

  // Check that the device listed in the certificate is correct.
  // Something like evt_e161 001a11ffacdf
  std::string common_name = verification_context->GetCommonName();
  std::string translated_mac;
  base::RemoveChars(connected_mac, ":", &translated_mac);
  if (!base::EndsWith(common_name, translated_mac,
                      base::CompareCase::INSENSITIVE_ASCII)) {
    LOG(ERROR) << kErrorPrefix << "MAC addresses don't match.";
    return false;
  }

  // Use the public key from verified certificate to verify |signature| over
  // |data|.
  if (!verification_context->VerifySignatureOverData(signature, data)) {
    LOG(ERROR) << kErrorPrefix
               << "Failed verifying signature using cast device cert";
    return false;
  }
  return true;
}

bool EncryptByteString(const std::vector<uint8_t>& pub_key_der,
                       const std::string& data,
                       std::vector<uint8_t>* encrypted_output) {
  crypto::EnsureOpenSSLInit();
  crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);

  bssl::UniquePtr<RSA> rsa(
      RSA_public_key_from_bytes(pub_key_der.data(), pub_key_der.size()));
  if (!rsa || RSA_size(rsa.get()) == 0) {
    LOG(ERROR) << "Failed to parse public key";
    return false;
  }

  encrypted_output->resize(RSA_size(rsa.get()));
  int encrypted_length = RSA_public_encrypt(
      data.size(), reinterpret_cast<const uint8_t*>(data.data()),
      encrypted_output->data(), rsa.get(), RSA_PKCS1_PADDING);
  if (encrypted_length < 0) {
    LOG(ERROR) << "Error during decryption";
    return false;
  }
  encrypted_output->resize(encrypted_length);
  return true;
}

bool DecryptByteString(const std::string& private_key_pem,
                       const std::vector<uint8_t>& encrypted_data,
                       std::string* decrypted_output) {
  crypto::EnsureOpenSSLInit();
  crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);

  std::vector<uint8_t> private_key_data;
  if (!GetDERFromPEM(private_key_pem, "PRIVATE KEY", &private_key_data)) {
    LOG(ERROR) << "Failed to parse private key PEM.";
    return false;
  }
  std::unique_ptr<crypto::RSAPrivateKey> private_key(
      crypto::RSAPrivateKey::CreateFromPrivateKeyInfo(private_key_data));
  if (!private_key || !private_key->key()) {
    LOG(ERROR) << "Failed to parse private key DER.";
    return false;
  }

  RSA* rsa = EVP_PKEY_get0_RSA(private_key->key());
  if (!rsa || RSA_size(rsa) == 0) {
    LOG(ERROR) << "Failed to get RSA key.";
    return false;
  }

  uint8_t* output = reinterpret_cast<uint8_t*>(
      base::WriteInto(decrypted_output, RSA_size(rsa) + 1));
  int output_length =
      RSA_private_decrypt(encrypted_data.size(), &encrypted_data[0], output,
                          rsa, RSA_PKCS1_PADDING);
  if (output_length < 0) {
    LOG(ERROR) << "Error during decryption.";
    return false;
  }
  decrypted_output->resize(output_length);
  return true;
}

}  // namespace networking_private_crypto


text:
'use strict';

var AbstractMappedTypes = require('./abstract_mapped_types');

/**
 * This class extends the Types interface to provide the MongoDB types
 * supported by JHipster.
 */
var MongoDBTypes = module.exports = function() {
  this.types = {
    String: [ 'required', 'minlength', 'maxlength', 'pattern' ],
    Integer: [ 'required', 'min', 'max' ],
    Long: [ 'required', 'min', 'max' ],
    BigDecimal: [ 'required', 'min', 'max' ],
    LocalDate: [ 'required' ],
    ZonedDateTime: [ 'required' ],
    Boolean: [ 'required' ],
    Enum : [ 'required' ],
    Blob: [ 'required', 'minbytes', 'maxbytes' ],
    AnyBlob: [ 'required', 'minbytes', 'maxbytes' ],
    ImageBlob: [ 'required', 'minbytes', 'maxbytes' ],
    Float: [ 'required', 'min', 'max' ],
    Double: [ 'required', 'min', 'max' ]
  };
};

// inheritance stuff
MongoDBTypes.prototype = Object.create(AbstractMappedTypes.prototype);
MongoDBTypes.prototype.constructor = AbstractMappedTypes;


text:
Color Enhancement
=================

.. _evaluate:

Evaluate Expression
-------------------

.. versionadded:: 0.4.1

Pixel channels can be manipulated by applying an arithmetic, relational, or
logical expression. See :const:`~wand.image.EVALUATE_OPS` for a list of valid
operations.

For example, when given image :file:`enhancement.jpg`:

.. image:: ../_images/enhancement.jpg
     :alt: Chicago River

We can reduce the amount of data in the blue channel by applying the
right-shift binary operator, and increase data in the right channel with
left-shift operator::

    from wand.image import Image

    with Image(filename='enhancement.jpg') as img:
        # B >> 1
        img.evaluate(operator='rightshift', value=1, channel='blue')
        # R << 1
        img.evaluate(operator='leftshift', value=1, channel='red')

.. image:: ../_images/enhancement-evaluate.jpg
     :alt: Chicago River - Evaluated right shift

.. _function:

Function Expression
-------------------

.. versionadded:: 0.4.1

Similar to :meth:`~wand.image.BaseImage.evaluate()`,
:meth:`~wand.image.BaseImage.function()` applies a multi-argument function to
pixel channels. See :const:`~wand.image.FUNCTION_TYPES` for a list of available
function formulas.

For example, when given image :file:`enhancement.jpg`:

.. image:: ../_images/enhancement.jpg
     :alt: Chicago River

We can apply a **Sinusoid** function with the following::

    from wand.image import Image

    with Image(filename='enhancement.jpg') as img:
        frequency = 3
        phase_shift = -90
        amplitude = 0.2
        bias = 0.7
        img.function('sinusoid', [frequency, phase_shift, amplitude, bias])

.. image:: ../_images/enhancement-function.jpg
     :alt: Chicago River - Sinusoid function

.. _gamma:

Gamma
-----

.. versionadded:: 0.4.1

Gamma correction allows you to adjust the luminance of an image. Resulting
pixels are defined as ``pixel^(1/gamma)``. The value of ``gamma`` is
typically between 0.8 & 2.3 range, and value of 1.0 will not affect the
resulting image.

The :meth:`~wand.image.Image.level()` method can also adjust ``gamma`` value.

For example, when given image :file:`enhancement.jpg`:

.. image:: ../_images/enhancement.jpg
     :alt: Chicago River

We can step through 4 pre-configured gamma correction values with the following::

    from wand.image import Image

    with Image(filename='enhancement.jpg') as img_src:
        for Y in [0.8, 0.9, 1.33, 1.66]:
            with Image(img_src) as img_cpy:
                img_cpy.gamma(Y)

.. image:: ../_images/enhancement-gamma.jpg
     :alt: Chicago River - Gamma Correction

.. _level:

Level
-----

.. versionadded:: 0.4.1

Black & white boundaries of an image can be controlled with
:meth:`~wand.image.Image.level()` method. Similar to the
:meth:`~wand.image.Image.gamma()` method, mid-point levels can be adjusted with
the ``gamma`` keyword argument.

The ``black`` and ``white`` point arguments are expecting values between 0.0 &
1.0 which represent percentages.

For example, when given image :file:`enhancement.jpg`:

.. image:: ../_images/enhancement.jpg
     :alt: Chicago River

We can adjust the level range between 20% & 90% with slight mid-range increase::

    from wand.image import Image

    with Image(filename='enhancement.jpg') as img:
        img.level(0.2, 0.9, gamma=1.1)
        img.save(filename='enhancement-level.jpg')

.. image:: ../_images/enhancement-level.jpg
     :alt: Chicago River - Level Adjustment