text:
package com.amazonaws.services.appstream.model.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.appstream.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * Fleet JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class FleetJsonUnmarshaller implements Unmarshaller<Fleet, JsonUnmarshallerContext> {

    public Fleet unmarshall(JsonUnmarshallerContext context) throws Exception {
        Fleet fleet = new Fleet();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return null;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("Arn", targetDepth)) {
                    context.nextToken();
                    fleet.setArn(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("Name", targetDepth)) {
                    context.nextToken();
                    fleet.setName(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("DisplayName", targetDepth)) {
                    context.nextToken();
                    fleet.setDisplayName(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("Description", targetDepth)) {
                    context.nextToken();
                    fleet.setDescription(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("ImageName", targetDepth)) {
                    context.nextToken();
                    fleet.setImageName(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("ImageArn", targetDepth)) {
                    context.nextToken();
                    fleet.setImageArn(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("InstanceType", targetDepth)) {
                    context.nextToken();
                    fleet.setInstanceType(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("FleetType", targetDepth)) {
                    context.nextToken();
                    fleet.setFleetType(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("ComputeCapacityStatus", targetDepth)) {
                    context.nextToken();
                    fleet.setComputeCapacityStatus(ComputeCapacityStatusJsonUnmarshaller.getInstance().unmarshall(context));
                }
                if (context.testExpression("MaxUserDurationInSeconds", targetDepth)) {
                    context.nextToken();
                    fleet.setMaxUserDurationInSeconds(context.getUnmarshaller(Integer.class).unmarshall(context));
                }
                if (context.testExpression("DisconnectTimeoutInSeconds", targetDepth)) {
                    context.nextToken();
                    fleet.setDisconnectTimeoutInSeconds(context.getUnmarshaller(Integer.class).unmarshall(context));
                }
                if (context.testExpression("State", targetDepth)) {
                    context.nextToken();
                    fleet.setState(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("VpcConfig", targetDepth)) {
                    context.nextToken();
                    fleet.setVpcConfig(VpcConfigJsonUnmarshaller.getInstance().unmarshall(context));
                }
                if (context.testExpression("CreatedTime", targetDepth)) {
                    context.nextToken();
                    fleet.setCreatedTime(DateJsonUnmarshallerFactory.getInstance("unixTimestamp").unmarshall(context));
                }
                if (context.testExpression("FleetErrors", targetDepth)) {
                    context.nextToken();
                    fleet.setFleetErrors(new ListUnmarshaller<FleetError>(FleetErrorJsonUnmarshaller.getInstance()).unmarshall(context));
                }
                if (context.testExpression("EnableDefaultInternetAccess", targetDepth)) {
                    context.nextToken();
                    fleet.setEnableDefaultInternetAccess(context.getUnmarshaller(Boolean.class).unmarshall(context));
                }
                if (context.testExpression("DomainJoinInfo", targetDepth)) {
                    context.nextToken();
                    fleet.setDomainJoinInfo(DomainJoinInfoJsonUnmarshaller.getInstance().unmarshall(context));
                }
                if (context.testExpression("IdleDisconnectTimeoutInSeconds", targetDepth)) {
                    context.nextToken();
                    fleet.setIdleDisconnectTimeoutInSeconds(context.getUnmarshaller(Integer.class).unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return fleet;
    }

    private static FleetJsonUnmarshaller instance;

    public static FleetJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new FleetJsonUnmarshaller();
        return instance;
    }
}


text:
export DISPLAY=:0
xrandr --output HDMI1 --mode 720x480 --rate 60

redpajama_set_name: RedPajamaGithub


text:
import defaultEnv from 'ember-htmlbars/env';
import discoverKnownHelpers from 'ember-htmlbars/system/discover-known-helpers';

export default function RenderEnv(options) {
  this.lifecycleHooks = options.lifecycleHooks || [];
  this.renderedViews = options.renderedViews || [];
  this.renderedNodes = options.renderedNodes || {};
  this.hasParentOutlet = options.hasParentOutlet || false;

  this.view = options.view;
  this.outletState = options.outletState;
  this.container = options.container;
  this.renderer = options.renderer;
  this.dom = options.dom;
  this.knownHelpers = options.knownHelpers || discoverKnownHelpers(options.container);

  this.hooks = defaultEnv.hooks;
  this.helpers = defaultEnv.helpers;
  this.useFragmentCache = defaultEnv.useFragmentCache;
}

RenderEnv.build = function(view) {
  return new RenderEnv({
    view: view,
    outletState: view.outletState,
    container: view.container,
    renderer: view.renderer,
    dom: view.renderer._dom
  });
};

RenderEnv.prototype.childWithView = function(view) {
  return new RenderEnv({
    view: view,
    outletState: this.outletState,
    container: this.container,
    renderer: this.renderer,
    dom: this.dom,
    lifecycleHooks: this.lifecycleHooks,
    renderedViews: this.renderedViews,
    renderedNodes: this.renderedNodes,
    hasParentOutlet: this.hasParentOutlet,
    knownHelpers: this.knownHelpers
  });
};

RenderEnv.prototype.childWithOutletState = function(outletState, hasParentOutlet=this.hasParentOutlet) {
  return new RenderEnv({
    view: this.view,
    outletState: outletState,
    container: this.container,
    renderer: this.renderer,
    dom: this.dom,
    lifecycleHooks: this.lifecycleHooks,
    renderedViews: this.renderedViews,
    renderedNodes: this.renderedNodes,
    hasParentOutlet: hasParentOutlet,
    knownHelpers: this.knownHelpers
  });
};


text:
import React from 'react';
import PropTypes from 'prop-types';
import { DragLayer as LibDragLayer } from 'react-dnd';
import * as styles from './styles';
import { DragContext } from 'components/DragContainer';
import identity from 'lodash.identity';

/**
 * Renders a generic layer for drawing dragged items from draggable
 * components.
 */
class DragLayer extends React.Component {
  static propTypes = {
    /**
     * Provided by DragGroupItem via drag context.
     * Contains details needed to render an item preview
     */
    item: PropTypes.shape({
      children: PropTypes.node,
      dimensions: PropTypes.shape({
        width: PropTypes.number,
        height: PropTypes.number,
      }),
    }),
    /**
     * Provided by
     * Offset values for the position of the dragged preview
     * item
     */
    clientOffset: PropTypes.object,

    /**
     * Override the presentational component which renders the full-screen
     * overlay
     */
    Overlay: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
    /**
     * Override the presentational component which positions and sizes
     * the preview element
     */
    PreviewContainer: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
  };

  static defaultProps = {
    item: null,
    clientOffset: null,
    Overlay: styles.Overlay,
    PreviewContainer: styles.DragItemPreviewContainer,
  };

  static styles = styles;

  renderPreviewContent = () => {
    const { item } = this.props;

    return (
      item.children &&
      React.Children.map(
        item.children,
        child =>
          child
            ? React.cloneElement(child, { wrapDragHandle: identity })
            : null,
      )
    );
  };

  render() {
    const {
      item,
      clientOffset,
      Overlay,
      PreviewContainer,
      Cutout,
      ...rest
    } = this.props;

    if (!item || !clientOffset) {
      return <Overlay {...rest} />;
    }

    const previewPositionStyles = {
      transform: `translate(${clientOffset.x}px, ${clientOffset.y}px)`,
      width: item.dimensions ? item.dimensions.width + 'px' : '0px',
      height: item.dimensions ? item.dimensions.height + 'px' : '0px',
    };

    return (
      <DragContext.Provider value={{ wrapDragHandle: identity }}>
        <Overlay {...rest}>
          <div style={previewPositionStyles}>
            <PreviewContainer>{this.renderPreviewContent()}</PreviewContainer>
          </div>
        </Overlay>
      </DragContext.Provider>
    );
  }
}

const collect = monitor => ({
  item: monitor.getItem(),
  clientOffset: monitor.getClientOffset(),
});

export default LibDragLayer(collect)(DragLayer);


text:
class NoiseObject;

class Player : public GameObject
{
public:
	Player(void);
	~Player(void);

	void InputUpdate();
	void SetCameraTargetWindow(WindowWizard* window);
	Controller controller;

	void CheckGroundCollision(NoiseObject n);

	virtual CameraModule* GetCamera();
	virtual Rigidbody* GetRigidbody();
	virtual Mesh* GetMesh();
	virtual Controller* GetController();

private:
	bool flying;

	CameraModule camera;
	CameraController camController;
	Rigidbody rigidbody;

};


text:
package sarama

import (
	"context"
	"errors"
	"fmt"
	"sort"
	"sync"
	"time"
)

// ErrClosedConsumerGroup is the error returned when a method is called on a consumer group that has been closed.
var ErrClosedConsumerGroup = errors.New("kafka: tried to use a consumer group that was closed")

// ConsumerGroup is responsible for dividing up processing of topics and partitions
// over a collection of processes (the members of the consumer group).
type ConsumerGroup interface {
	// Consume joins a cluster of consumers for a given list of topics and
	// starts a blocking ConsumerGroupSession through the ConsumerGroupHandler.
	//
	// The life-cycle of a session is represented by the following steps:
	//
	// 1. The consumers join the group (as explained in https://kafka.apache.org/documentation/#intro_consumers)
	//    and is assigned their "fair share" of partitions, aka 'claims'.
	// 2. Before processing starts, the handler's Setup() hook is called to notify the user
	//    of the claims and allow any necessary preparation or alteration of state.
	// 3. For each of the assigned claims the handler's ConsumeClaim() function is then called
	//    in a separate goroutine which requires it to be thread-safe. Any state must be carefully protected
	//    from concurrent reads/writes.
	// 4. The session will persist until one of the ConsumeClaim() functions exits. This can be either when the
	//    parent context is cancelled or when a server-side rebalance cycle is initiated.
	// 5. Once all the ConsumeClaim() loops have exited, the handler's Cleanup() hook is called
	//    to allow the user to perform any final tasks before a rebalance.
	// 6. Finally, marked offsets are committed one last time before claims are released.
	//
	// Please note, that once a rebalance is triggered, sessions must be completed within
	// Config.Consumer.Group.Rebalance.Timeout. This means that ConsumeClaim() functions must exit
	// as quickly as possible to allow time for Cleanup() and the final offset commit. If the timeout
	// is exceeded, the consumer will be removed from the group by Kafka, which will cause offset
	// commit failures.
	Consume(ctx context.Context, topics []string, handler ConsumerGroupHandler) error

	// Errors returns a read channel of errors that occurred during the consumer life-cycle.
	// By default, errors are logged and not returned over this channel.
	// If you want to implement any custom error handling, set your config's
	// Consumer.Return.Errors setting to true, and read from this channel.
	Errors() <-chan error

	// Close stops the ConsumerGroup and detaches any running sessions. It is required to call
	// this function before the object passes out of scope, as it will otherwise leak memory.
	Close() error
}

type consumerGroup struct {
	client    Client
	ownClient bool

	config   *Config
	consumer Consumer
	groupID  string
	memberID string
	errors   chan error

	lock      sync.Mutex
	closed    chan none
	closeOnce sync.Once
}

// NewConsumerGroup creates a new consumer group the given broker addresses and configuration.
func NewConsumerGroup(addrs []string, groupID string, config *Config) (ConsumerGroup, error) {
	client, err := NewClient(addrs, config)
	if err != nil {
		return nil, err
	}

	c, err := NewConsumerGroupFromClient(groupID, client)
	if err != nil {
		_ = client.Close()
		return nil, err
	}

	c.(*consumerGroup).ownClient = true
	return c, nil
}

// NewConsumerGroupFromClient creates a new consumer group using the given client. It is still
// necessary to call Close() on the underlying client when shutting down this consumer.
// PLEASE NOTE: consumer groups can only re-use but not share clients.
func NewConsumerGroupFromClient(groupID string, client Client) (ConsumerGroup, error) {
	config := client.Config()
	if !config.Version.IsAtLeast(V0_10_2_0) {
		return nil, ConfigurationError("consumer groups require Version to be >= V0_10_2_0")
	}

	consumer, err := NewConsumerFromClient(client)
	if err != nil {
		return nil, err
	}

	return &consumerGroup{
		client:   client,
		consumer: consumer,
		config:   config,
		groupID:  groupID,
		errors:   make(chan error, config.ChannelBufferSize),
		closed:   make(chan none),
	}, nil
}

// Errors implements ConsumerGroup.
func (c *consumerGroup) Errors() <-chan error { return c.errors }

// Close implements ConsumerGroup.
func (c *consumerGroup) Close() (err error) {
	c.closeOnce.Do(func() {
		close(c.closed)

		c.lock.Lock()
		defer c.lock.Unlock()

		// leave group
		if e := c.leave(); e != nil {
			err = e
		}

		// drain errors
		go func() {
			close(c.errors)
		}()
		for e := range c.errors {
			err = e
		}

		if c.ownClient {
			if e := c.client.Close(); e != nil {
				err = e
			}
		}
	})
	return
}

// Consume implements ConsumerGroup.
func (c *consumerGroup) Consume(ctx context.Context, topics []string, handler ConsumerGroupHandler) error {
	// Ensure group is not closed
	select {
	case <-c.closed:
		return ErrClosedConsumerGroup
	default:
	}

	c.lock.Lock()
	defer c.lock.Unlock()

	// Quick exit when no topics are provided
	if len(topics) == 0 {
		return fmt.Errorf("no topics provided")
	}

	// Refresh metadata for requested topics
	if err := c.client.RefreshMetadata(topics...); err != nil {
		return err
	}

	// Get coordinator
	coordinator, err := c.client.Coordinator(c.groupID)
	if err != nil {
		return err
	}

	// Init session
	sess, err := c.newSession(ctx, coordinator, topics, handler, c.config.Consumer.Group.Rebalance.Retry.Max)
	if err == ErrClosedClient {
		return ErrClosedConsumerGroup
	} else if err != nil {
		return err
	}

	// Wait for session exit signal
	<-sess.ctx.Done()

	// Gracefully release session claims
	return sess.release(true)
}

func (c *consumerGroup) newSession(ctx context.Context, coordinator *Broker, topics []string, handler ConsumerGroupHandler, retries int) (*consumerGroupSession, error) {
	// Join consumer group
	join, err := c.joinGroupRequest(coordinator, topics)
	if err != nil {
		_ = coordinator.Close()
		return nil, err
	}
	switch join.Err {
	case ErrNoError:
		c.memberID = join.MemberId
	case ErrUnknownMemberId, ErrIllegalGeneration: // reset member ID and retry immediately
		c.memberID = ""
		return c.newSession(ctx, coordinator, topics, handler, retries)
	case ErrRebalanceInProgress: // retry after backoff
		if retries <= 0 {
			return nil, join.Err
		}

		select {
		case <-c.closed:
			return nil, ErrClosedConsumerGroup
		case <-time.After(c.config.Consumer.Group.Rebalance.Retry.Backoff):
		}

		return c.newSession(ctx, coordinator, topics, handler, retries-1)
	default:
		return nil, join.Err
	}

	// Prepare distribution plan if we joined as the leader
	var plan BalanceStrategyPlan
	if join.LeaderId == join.MemberId {
		members, err := join.GetMembers()
		if err != nil {
			return nil, err
		}

		plan, err = c.balance(members)
		if err != nil {
			return nil, err
		}
	}

	// Sync consumer group
	sync, err := c.syncGroupRequest(coordinator, plan, join.GenerationId)
	if err != nil {
		_ = coordinator.Close()
		return nil, err
	}
	switch sync.Err {
	case ErrNoError:
	case ErrUnknownMemberId, ErrIllegalGeneration: // reset member ID and retry immediately
		c.memberID = ""
		return c.newSession(ctx, coordinator, topics, handler, retries)
	case ErrRebalanceInProgress: // retry after backoff
		if retries <= 0 {
			return nil, sync.Err
		}

		select {
		case <-c.closed:
			return nil, ErrClosedConsumerGroup
		case <-time.After(c.config.Consumer.Group.Rebalance.Retry.Backoff):
		}

		return c.newSession(ctx, coordinator, topics, handler, retries-1)
	default:
		return nil, sync.Err
	}

	// Retrieve and sort claims
	var claims map[string][]int32
	if len(sync.MemberAssignment) > 0 {
		members, err := sync.GetMemberAssignment()
		if err != nil {
			return nil, err
		}
		claims = members.Topics

		for _, partitions := range claims {
			sort.Sort(int32Slice(partitions))
		}
	}

	return newConsumerGroupSession(ctx, c, claims, join.MemberId, join.GenerationId, handler)
}

func (c *consumerGroup) joinGroupRequest(coordinator *Broker, topics []string) (*JoinGroupResponse, error) {
	req := &JoinGroupRequest{
		GroupId:        c.groupID,
		MemberId:       c.memberID,
		SessionTimeout: int32(c.config.Consumer.Group.Session.Timeout / time.Millisecond),
		ProtocolType:   "consumer",
	}
	if c.config.Version.IsAtLeast(V0_10_1_0) {
		req.Version = 1
		req.RebalanceTimeout = int32(c.config.Consumer.Group.Rebalance.Timeout / time.Millisecond)
	}

	meta := &ConsumerGroupMemberMetadata{
		Topics:   topics,
		UserData: c.config.Consumer.Group.Member.UserData,
	}
	strategy := c.config.Consumer.Group.Rebalance.Strategy
	if err := req.AddGroupProtocolMetadata(strategy.Name(), meta); err != nil {
		return nil, err
	}

	return coordinator.JoinGroup(req)
}

func (c *consumerGroup) syncGroupRequest(coordinator *Broker, plan BalanceStrategyPlan, generationID int32) (*SyncGroupResponse, error) {
	req := &SyncGroupRequest{
		GroupId:      c.groupID,
		MemberId:     c.memberID,
		GenerationId: generationID,
	}
	for memberID, topics := range plan {
		err := req.AddGroupAssignmentMember(memberID, &ConsumerGroupMemberAssignment{
			Topics: topics,
		})
		if err != nil {
			return nil, err
		}
	}
	return coordinator.SyncGroup(req)
}

func (c *consumerGroup) heartbeatRequest(coordinator *Broker, memberID string, generationID int32) (*HeartbeatResponse, error) {
	req := &HeartbeatRequest{
		GroupId:      c.groupID,
		MemberId:     memberID,
		GenerationId: generationID,
	}

	return coordinator.Heartbeat(req)
}

func (c *consumerGroup) balance(members map[string]ConsumerGroupMemberMetadata) (BalanceStrategyPlan, error) {
	topics := make(map[string][]int32)
	for _, meta := range members {
		for _, topic := range meta.Topics {
			topics[topic] = nil
		}
	}

	for topic := range topics {
		partitions, err := c.client.Partitions(topic)
		if err != nil {
			return nil, err
		}
		topics[topic] = partitions
	}

	strategy := c.config.Consumer.Group.Rebalance.Strategy
	return strategy.Plan(members, topics)
}

// Leaves the cluster, called by Close, protected by lock.
func (c *consumerGroup) leave() error {
	if c.memberID == "" {
		return nil
	}

	coordinator, err := c.client.Coordinator(c.groupID)
	if err != nil {
		return err
	}

	resp, err := coordinator.LeaveGroup(&LeaveGroupRequest{
		GroupId:  c.groupID,
		MemberId: c.memberID,
	})
	if err != nil {
		_ = coordinator.Close()
		return err
	}

	// Unset memberID
	c.memberID = ""

	// Check response
	switch resp.Err {
	case ErrRebalanceInProgress, ErrUnknownMemberId, ErrNoError:
		return nil
	default:
		return resp.Err
	}
}

func (c *consumerGroup) handleError(err error, topic string, partition int32) {
	select {
	case <-c.closed:
		return
	default:
	}

	if _, ok := err.(*ConsumerError); !ok && topic != "" && partition > -1 {
		err = &ConsumerError{
			Topic:     topic,
			Partition: partition,
			Err:       err,
		}
	}

	if c.config.Consumer.Return.Errors {
		select {
		case c.errors <- err:
		default:
		}
	} else {
		Logger.Println(err)
	}
}

// --------------------------------------------------------------------

// ConsumerGroupSession represents a consumer group member session.
type ConsumerGroupSession interface {
	// Claims returns information about the claimed partitions by topic.
	Claims() map[string][]int32

	// MemberID returns the cluster member ID.
	MemberID() string

	// GenerationID returns the current generation ID.
	GenerationID() int32

	// MarkOffset marks the provided offset, alongside a metadata string
	// that represents the state of the partition consumer at that point in time. The
	// metadata string can be used by another consumer to restore that state, so it
	// can resume consumption.
	//
	// To follow upstream conventions, you are expected to mark the offset of the
	// next message to read, not the last message read. Thus, when calling `MarkOffset`
	// you should typically add one to the offset of the last consumed message.
	//
	// Note: calling MarkOffset does not necessarily commit the offset to the backend
	// store immediately for efficiency reasons, and it may never be committed if
	// your application crashes. This means that you may end up processing the same
	// message twice, and your processing should ideally be idempotent.
	MarkOffset(topic string, partition int32, offset int64, metadata string)

	// ResetOffset resets to the provided offset, alongside a metadata string that
	// represents the state of the partition consumer at that point in time. Reset
	// acts as a counterpart to MarkOffset, the difference being that it allows to
	// reset an offset to an earlier or smaller value, where MarkOffset only
	// allows incrementing the offset. cf MarkOffset for more details.
	ResetOffset(topic string, partition int32, offset int64, metadata string)

	// MarkMessage marks a message as consumed.
	MarkMessage(msg *ConsumerMessage, metadata string)

	// Context returns the session context.
	Context() context.Context
}

type consumerGroupSession struct {
	parent       *consumerGroup
	memberID     string
	generationID int32
	handler      ConsumerGroupHandler

	claims  map[string][]int32
	offsets *offsetManager
	ctx     context.Context
	cancel  func()

	waitGroup       sync.WaitGroup
	releaseOnce     sync.Once
	hbDying, hbDead chan none
}

func newConsumerGroupSession(ctx context.Context, parent *consumerGroup, claims map[string][]int32, memberID string, generationID int32, handler ConsumerGroupHandler) (*consumerGroupSession, error) {
	// init offset manager
	offsets, err := newOffsetManagerFromClient(parent.groupID, memberID, generationID, parent.client)
	if err != nil {
		return nil, err
	}

	// init context
	ctx, cancel := context.WithCancel(ctx)

	// init session
	sess := &consumerGroupSession{
		parent:       parent,
		memberID:     memberID,
		generationID: generationID,
		handler:      handler,
		offsets:      offsets,
		claims:       claims,
		ctx:          ctx,
		cancel:       cancel,
		hbDying:      make(chan none),
		hbDead:       make(chan none),
	}

	// start heartbeat loop
	go sess.heartbeatLoop()

	// create a POM for each claim
	for topic, partitions := range claims {
		for _, partition := range partitions {
			pom, err := offsets.ManagePartition(topic, partition)
			if err != nil {
				_ = sess.release(false)
				return nil, err
			}

			// handle POM errors
			go func(topic string, partition int32) {
				for err := range pom.Errors() {
					sess.parent.handleError(err, topic, partition)
				}
			}(topic, partition)
		}
	}

	// perform setup
	if err := handler.Setup(sess); err != nil {
		_ = sess.release(true)
		return nil, err
	}

	// start consuming
	for topic, partitions := range claims {
		for _, partition := range partitions {
			sess.waitGroup.Add(1)

			go func(topic string, partition int32) {
				defer sess.waitGroup.Done()

				// cancel the as session as soon as the first
				// goroutine exits
				defer sess.cancel()

				// consume a single topic/partition, blocking
				sess.consume(topic, partition)
			}(topic, partition)
		}
	}
	return sess, nil
}

func (s *consumerGroupSession) Claims() map[string][]int32 { return s.claims }
func (s *consumerGroupSession) MemberID() string           { return s.memberID }
func (s *consumerGroupSession) GenerationID() int32        { return s.generationID }

func (s *consumerGroupSession) MarkOffset(topic string, partition int32, offset int64, metadata string) {
	if pom := s.offsets.findPOM(topic, partition); pom != nil {
		pom.MarkOffset(offset, metadata)
	}
}

func (s *consumerGroupSession) ResetOffset(topic string, partition int32, offset int64, metadata string) {
	if pom := s.offsets.findPOM(topic, partition); pom != nil {
		pom.ResetOffset(offset, metadata)
	}
}

func (s *consumerGroupSession) MarkMessage(msg *ConsumerMessage, metadata string) {
	s.MarkOffset(msg.Topic, msg.Partition, msg.Offset+1, metadata)
}

func (s *consumerGroupSession) Context() context.Context {
	return s.ctx
}

func (s *consumerGroupSession) consume(topic string, partition int32) {
	// quick exit if rebalance is due
	select {
	case <-s.ctx.Done():
		return
	case <-s.parent.closed:
		return
	default:
	}

	// get next offset
	offset := s.parent.config.Consumer.Offsets.Initial
	if pom := s.offsets.findPOM(topic, partition); pom != nil {
		offset, _ = pom.NextOffset()
	}

	// create new claim
	claim, err := newConsumerGroupClaim(s, topic, partition, offset)
	if err != nil {
		s.parent.handleError(err, topic, partition)
		return
	}

	// handle errors
	go func() {
		for err := range claim.Errors() {
			s.parent.handleError(err, topic, partition)
		}
	}()

	// trigger close when session is done
	go func() {
		select {
		case <-s.ctx.Done():
		case <-s.parent.closed:
		}
		claim.AsyncClose()
	}()

	// start processing
	if err := s.handler.ConsumeClaim(s, claim); err != nil {
		s.parent.handleError(err, topic, partition)
	}

	// ensure consumer is closed & drained
	claim.AsyncClose()
	for _, err := range claim.waitClosed() {
		s.parent.handleError(err, topic, partition)
	}
}

func (s *consumerGroupSession) release(withCleanup bool) (err error) {
	// signal release, stop heartbeat
	s.cancel()

	// wait for consumers to exit
	s.waitGroup.Wait()

	// perform release
	s.releaseOnce.Do(func() {
		if withCleanup {
			if e := s.handler.Cleanup(s); e != nil {
				s.parent.handleError(err, "", -1)
				err = e
			}
		}

		if e := s.offsets.Close(); e != nil {
			err = e
		}

		close(s.hbDying)
		<-s.hbDead
	})

	return
}

func (s *consumerGroupSession) heartbeatLoop() {
	defer close(s.hbDead)
	defer s.cancel() // trigger the end of the session on exit

	pause := time.NewTicker(s.parent.config.Consumer.Group.Heartbeat.Interval)
	defer pause.Stop()

	retries := s.parent.config.Metadata.Retry.Max
	for {
		coordinator, err := s.parent.client.Coordinator(s.parent.groupID)
		if err != nil {
			if retries <= 0 {
				s.parent.handleError(err, "", -1)
				return
			}

			select {
			case <-s.hbDying:
				return
			case <-time.After(s.parent.config.Metadata.Retry.Backoff):
				retries--
			}
			continue
		}

		resp, err := s.parent.heartbeatRequest(coordinator, s.memberID, s.generationID)
		if err != nil {
			_ = coordinator.Close()

			if retries <= 0 {
				s.parent.handleError(err, "", -1)
				return
			}

			retries--
			continue
		}

		switch resp.Err {
		case ErrNoError:
			retries = s.parent.config.Metadata.Retry.Max
		case ErrRebalanceInProgress, ErrUnknownMemberId, ErrIllegalGeneration:
			return
		default:
			s.parent.handleError(err, "", -1)
			return
		}

		select {
		case <-pause.C:
		case <-s.hbDying:
			return
		}
	}
}

// --------------------------------------------------------------------

// ConsumerGroupHandler instances are used to handle individual topic/partition claims.
// It also provides hooks for your consumer group session life-cycle and allow you to
// trigger logic before or after the consume loop(s).
//
// PLEASE NOTE that handlers are likely be called from several goroutines concurrently,
// ensure that all state is safely protected against race conditions.
type ConsumerGroupHandler interface {
	// Setup is run at the beginning of a new session, before ConsumeClaim.
	Setup(ConsumerGroupSession) error

	// Cleanup is run at the end of a session, once all ConsumeClaim goroutines have exited
	// but before the offsets are committed for the very last time.
	Cleanup(ConsumerGroupSession) error

	// ConsumeClaim must start a consumer loop of ConsumerGroupClaim's Messages().
	// Once the Messages() channel is closed, the Handler must finish its processing
	// loop and exit.
	ConsumeClaim(ConsumerGroupSession, ConsumerGroupClaim) error
}

// ConsumerGroupClaim processes Kafka messages from a given topic and partition within a consumer group.
type ConsumerGroupClaim interface {
	// Topic returns the consumed topic name.
	Topic() string

	// Partition returns the consumed partition.
	Partition() int32

	// InitialOffset returns the initial offset that was used as a starting point for this claim.
	InitialOffset() int64

	// HighWaterMarkOffset returns the high water mark offset of the partition,
	// i.e. the offset that will be used for the next message that will be produced.
	// You can use this to determine how far behind the processing is.
	HighWaterMarkOffset() int64

	// Messages returns the read channel for the messages that are returned by
	// the broker. The messages channel will be closed when a new rebalance cycle
	// is due. You must finish processing and mark offsets within
	// Config.Consumer.Group.Session.Timeout before the topic/partition is eventually
	// re-assigned to another group member.
	Messages() <-chan *ConsumerMessage
}

type consumerGroupClaim struct {
	topic     string
	partition int32
	offset    int64
	PartitionConsumer
}

func newConsumerGroupClaim(sess *consumerGroupSession, topic string, partition int32, offset int64) (*consumerGroupClaim, error) {
	pcm, err := sess.parent.consumer.ConsumePartition(topic, partition, offset)
	if err == ErrOffsetOutOfRange {
		offset = sess.parent.config.Consumer.Offsets.Initial
		pcm, err = sess.parent.consumer.ConsumePartition(topic, partition, offset)
	}
	if err != nil {
		return nil, err
	}

	go func() {
		for err := range pcm.Errors() {
			sess.parent.handleError(err, topic, partition)
		}
	}()

	return &consumerGroupClaim{
		topic:             topic,
		partition:         partition,
		offset:            offset,
		PartitionConsumer: pcm,
	}, nil
}

func (c *consumerGroupClaim) Topic() string        { return c.topic }
func (c *consumerGroupClaim) Partition() int32     { return c.partition }
func (c *consumerGroupClaim) InitialOffset() int64 { return c.offset }

// Drains messages and errors, ensures the claim is fully closed.
func (c *consumerGroupClaim) waitClosed() (errs ConsumerErrors) {
	go func() {
		for range c.Messages() {
		}
	}()

	for err := range c.Errors() {
		errs = append(errs, err)
	}
	return
}


text:
import { Component } from '@angular/core';
import { ViewController, AlertController, NavParams } from 'ionic-angular';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'add-post',
  templateUrl: 'addPost.html'
})
export class AddPostPage {

  addPost: FormGroup;
  currentUser: string;

  constructor(public viewCtrl: ViewController, public formBuilder: FormBuilder,
    public alertCtrl: AlertController, public navParams: NavParams) {
    this.addPost = formBuilder.group({
      message: ['', Validators.compose([Validators.required])]
    });
  }

  ionViewDidLoad() {
    this.currentUser = this.navParams.get('userName');
    console.log('modal sees user: ' + this.currentUser)
  }

  addNewPost() {
    if (!this.addPost.valid){
        let validAlert = this.alertCtrl.create({
          message: "Please enter a message",
          buttons: [
            {
              text: "Ok",
              role: 'cancel',
              handler: () => {

              }
            }
          ]
        });
        validAlert.present();
      } else {
        // let timestamp = firebase.database.ServerValue.TIMESTAMP
        let d = new Date();
        let dateArray = d.toString().split(' ');
        let time = dateArray[4].slice(0, -3);
        let timestamp = time + ', ' + dateArray[0] + ' ' + dateArray[2]
        let data = {
           name : this.currentUser,
           message: this.addPost.value.message,
           timestamp: timestamp,
           uri: 'none'
        };
        this.viewCtrl.dismiss(data);
    }
  }

  deleteLast() {
    let data = {
      deleteLast: true
    }
    this.viewCtrl.dismiss(data);
  }

  dismiss() {
  this.viewCtrl.dismiss();
  }

}


text:
require 'spec_helper'

RSpec.describe NullUser do
  let(:null_user) { NullUser.new }
  describe "#id" do
    it "should return nil" do
      expect(null_user.id).to eq(nil)
    end
  end

  describe "#email" do
    it "should return an empty string" do
      expect(null_user.email).to eq("")
    end
  end

  describe "#authenticate" do
    it "should return false" do
      expect(null_user.authenticate "" ).to be_falsey
    end
  end

  describe "#has_role?" do
    it "should return false" do
      expect(null_user.has_role? :admin ).to be_falsey
    end
  end

  describe "#generate_password_reset" do
    it "should return false" do
      expect(null_user.generate_password_reset).to be_falsey
    end
  end

  describe "find_module_history" do
    it "should return NullUserModuleHistory" do
      expect(null_user.find_module_history(module_id: 1)).to be_an_instance_of(NullUserModuleHistory)
    end
  end

  describe "module_histories" do
    it "should return NullUserModuleHistory" do
      expect(null_user.module_histories).to be_an_instance_of(NullUserModuleHistory)
    end
  end
end


text:
using Newtonsoft.Json;

namespace CompaniesHouse.Tests.ResourceBuilders
{
    public class Charges
    {
        [JsonProperty("Etag")]
        public string Etag { get; set; }

        [JsonProperty("items")]
        public Charge[] Items { get; set; }

        [JsonProperty("part_satisfied_count")]
        public int? PartSatisfiedCount { get; set; }

        [JsonProperty("satisfied_count")]
        public int? SatisfiedCount { get; set; }

        [JsonProperty("total_count")]
        public int? TotalCount { get; set; }

        [JsonProperty("unfiletered_count")]
        public int? UnfileteredCount { get; set; }
    }
}


text:
namespace gameplay
{

void luaRegister_Curve();

}

#endif


text:
<code_scheme name="IS24Android">
    <option name="USE_SAME_INDENTS" value="true" />
    <option name="IGNORE_SAME_INDENTS_FOR_LANGUAGES" value="true" />
    <option name="OTHER_INDENT_OPTIONS">
        <value>
            <option name="INDENT_SIZE" value="2" />
            <option name="CONTINUATION_INDENT_SIZE" value="4" />
            <option name="TAB_SIZE" value="2" />
            <option name="USE_TAB_CHARACTER" value="false" />
            <option name="SMART_TABS" value="false" />
            <option name="LABEL_INDENT_SIZE" value="0" />
            <option name="LABEL_INDENT_ABSOLUTE" value="false" />
            <option name="USE_RELATIVE_INDENTS" value="false" />
        </value>
    </option>
    <option name="CLASS_COUNT_TO_USE_IMPORT_ON_DEMAND" value="999" />
    <option name="NAMES_COUNT_TO_USE_IMPORT_ON_DEMAND" value="999" />
    <option name="PACKAGES_TO_USE_IMPORT_ON_DEMAND">
        <value />
    </option>
    <option name="IMPORT_LAYOUT_TABLE">
        <value>
            <package name="" withSubpackages="true" static="false" />
            <emptyLine />
            <package name="" withSubpackages="true" static="true" />
        </value>
    </option>
    <option name="RIGHT_MARGIN" value="160" />
    <option name="JD_ALIGN_PARAM_COMMENTS" value="false" />
    <option name="JD_ALIGN_EXCEPTION_COMMENTS" value="false" />
    <option name="JD_P_AT_EMPTY_LINES" value="false" />
    <option name="JD_DO_NOT_WRAP_ONE_LINE_COMMENTS" value="true" />
    <option name="JD_KEEP_EMPTY_PARAMETER" value="false" />
    <option name="JD_KEEP_EMPTY_RETURN" value="false" />
    <option name="JD_PRESERVE_LINE_FEEDS" value="true" />
    <option name="LINE_COMMENT_AT_FIRST_COLUMN" value="false" />
    <option name="BLOCK_COMMENT_AT_FIRST_COLUMN" value="false" />
    <option name="KEEP_LINE_BREAKS" value="false" />
    <option name="KEEP_FIRST_COLUMN_COMMENT" value="false" />
    <option name="KEEP_BLANK_LINES_IN_DECLARATIONS" value="1" />
    <option name="KEEP_BLANK_LINES_IN_CODE" value="1" />
    <option name="KEEP_BLANK_LINES_BEFORE_RBRACE" value="0" />
    <option name="ALIGN_MULTILINE_PARAMETERS" value="false" />
    <option name="ALIGN_MULTILINE_FOR" value="false" />
    <option name="SPACE_BEFORE_ARRAY_INITIALIZER_LBRACE" value="true" />
    <option name="CALL_PARAMETERS_WRAP" value="1" />
    <option name="METHOD_PARAMETERS_WRAP" value="1" />
    <option name="RESOURCE_LIST_WRAP" value="1" />
    <option name="EXTENDS_LIST_WRAP" value="1" />
    <option name="THROWS_LIST_WRAP" value="1" />
    <option name="EXTENDS_KEYWORD_WRAP" value="1" />
    <option name="THROWS_KEYWORD_WRAP" value="1" />
    <option name="METHOD_CALL_CHAIN_WRAP" value="5" />
    <option name="BINARY_OPERATION_WRAP" value="5" />
    <option name="BINARY_OPERATION_SIGN_ON_NEXT_LINE" value="true" />
    <option name="TERNARY_OPERATION_WRAP" value="1" />
    <option name="TERNARY_OPERATION_SIGNS_ON_NEXT_LINE" value="true" />
    <option name="FOR_STATEMENT_WRAP" value="1" />
    <option name="ARRAY_INITIALIZER_WRAP" value="1" />
    <option name="ASSIGNMENT_WRAP" value="1" />
    <option name="WRAP_COMMENTS" value="true" />
    <option name="ASSERT_STATEMENT_WRAP" value="1" />
    <option name="IF_BRACE_FORCE" value="1" />
    <option name="DOWHILE_BRACE_FORCE" value="1" />
    <option name="WHILE_BRACE_FORCE" value="1" />
    <option name="METHOD_ANNOTATION_WRAP" value="1" />
    <option name="CLASS_ANNOTATION_WRAP" value="1" />
    <option name="FIELD_ANNOTATION_WRAP" value="1" />
    <option name="PARAMETER_ANNOTATION_WRAP" value="1" />
    <option name="VARIABLE_ANNOTATION_WRAP" value="1" />
    <option name="ENUM_CONSTANTS_WRAP" value="1" />
    <AndroidXmlCodeStyleSettings>
        <option name="USE_CUSTOM_SETTINGS" value="true" />
        <option name="MANIFEST_SETTINGS">
            <value>
                <option name="INSERT_LINE_BREAK_BEFORE_FIRST_ATTRIBUTE" value="false" />
            </value>
        </option>
    </AndroidXmlCodeStyleSettings>
    <JavaCodeStyleSettings>
        <option name="DO_NOT_WRAP_AFTER_SINGLE_ANNOTATION" value="true" />
        <option name="CLASS_NAMES_IN_JAVADOC" value="3" />
    </JavaCodeStyleSettings>
    <Objective-C-extensions>
        <option name="GENERATE_INSTANCE_VARIABLES_FOR_PROPERTIES" value="ASK" />
        <option name="RELEASE_STYLE" value="IVAR" />
        <option name="TYPE_QUALIFIERS_PLACEMENT" value="BEFORE" />
        <file>
            <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Import" />
            <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Macro" />
            <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Typedef" />
            <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Enum" />
            <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Constant" />
            <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Global" />
            <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Struct" />
            <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="FunctionPredecl" />
            <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Function" />
        </file>
        <class>
            <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Property" />
            <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Synthesize" />
            <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="InitMethod" />
            <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="StaticMethod" />
            <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="InstanceMethod" />
            <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="DeallocMethod" />
        </class>
        <extensions>
            <pair source="cpp" header="h" />
            <pair source="c" header="h" />
        </extensions>
    </Objective-C-extensions>
    <XML>
        <option name="XML_KEEP_LINE_BREAKS" value="false" />
        <option name="XML_ALIGN_ATTRIBUTES" value="false" />
        <option name="XML_LEGACY_SETTINGS_IMPORTED" value="true" />
    </XML>
    <ADDITIONAL_INDENT_OPTIONS fileType="php">
        <option name="INDENT_SIZE" value="2" />
        <option name="CONTINUATION_INDENT_SIZE" value="4" />
        <option name="TAB_SIZE" value="2" />
    </ADDITIONAL_INDENT_OPTIONS>
    <ADDITIONAL_INDENT_OPTIONS fileType="scala">
        <option name="INDENT_SIZE" value="2" />
        <option name="CONTINUATION_INDENT_SIZE" value="2" />
        <option name="TAB_SIZE" value="2" />
    </ADDITIONAL_INDENT_OPTIONS>
    <codeStyleSettings language="CSS">
        <indentOptions>
            <option name="INDENT_SIZE" value="2" />
            <option name="CONTINUATION_INDENT_SIZE" value="4" />
            <option name="TAB_SIZE" value="2" />
        </indentOptions>
    </codeStyleSettings>
    <codeStyleSettings language="CoffeeScript">
        <option name="KEEP_LINE_BREAKS" value="false" />
        <option name="KEEP_FIRST_COLUMN_COMMENT" value="false" />
        <option name="KEEP_BLANK_LINES_IN_CODE" value="1" />
        <option name="ALIGN_MULTILINE_PARAMETERS" value="false" />
        <option name="METHOD_PARAMETERS_WRAP" value="1" />
        <option name="PARENT_SETTINGS_INSTALLED" value="true" />
    </codeStyleSettings>
    <codeStyleSettings language="Groovy">
        <option name="KEEP_LINE_BREAKS" value="true"/>
        <option name="KEEP_FIRST_COLUMN_COMMENT" value="false" />
        <option name="KEEP_BLANK_LINES_IN_DECLARATIONS" value="1" />
        <option name="KEEP_BLANK_LINES_IN_CODE" value="1" />
        <option name="KEEP_BLANK_LINES_BEFORE_RBRACE" value="0" />
        <option name="ALIGN_MULTILINE_PARAMETERS" value="false" />
        <option name="ALIGN_MULTILINE_FOR" value="false" />
        <option name="CALL_PARAMETERS_WRAP" value="1" />
        <option name="METHOD_PARAMETERS_WRAP" value="1" />
        <option name="EXTENDS_LIST_WRAP" value="1" />
        <option name="THROWS_LIST_WRAP" value="1" />
        <option name="EXTENDS_KEYWORD_WRAP" value="1" />
        <option name="THROWS_KEYWORD_WRAP" value="1" />
        <option name="METHOD_CALL_CHAIN_WRAP" value="5" />
        <option name="BINARY_OPERATION_WRAP" value="5" />
        <option name="TERNARY_OPERATION_WRAP" value="1" />
        <option name="FOR_STATEMENT_WRAP" value="1" />
        <option name="ASSIGNMENT_WRAP" value="1" />
        <option name="ASSERT_STATEMENT_WRAP" value="1" />
        <option name="IF_BRACE_FORCE" value="1" />
        <option name="WHILE_BRACE_FORCE" value="1" />
        <option name="METHOD_ANNOTATION_WRAP" value="1" />
        <option name="CLASS_ANNOTATION_WRAP" value="1" />
        <option name="FIELD_ANNOTATION_WRAP" value="1" />
        <option name="PARAMETER_ANNOTATION_WRAP" value="1" />
        <option name="VARIABLE_ANNOTATION_WRAP" value="1" />
        <option name="PARENT_SETTINGS_INSTALLED" value="true" />
        <indentOptions>
            <option name="INDENT_SIZE" value="2" />
            <option name="CONTINUATION_INDENT_SIZE" value="4" />
            <option name="TAB_SIZE" value="2" />
        </indentOptions>
    </codeStyleSettings>
    <codeStyleSettings language="JAVA">
        <option name="LINE_COMMENT_AT_FIRST_COLUMN" value="false" />
        <option name="BLOCK_COMMENT_AT_FIRST_COLUMN" value="false" />
        <option name="KEEP_FIRST_COLUMN_COMMENT" value="false" />
        <option name="KEEP_BLANK_LINES_IN_DECLARATIONS" value="1" />
        <option name="KEEP_BLANK_LINES_IN_CODE" value="1" />
        <option name="KEEP_BLANK_LINES_BEFORE_RBRACE" value="1" />
        <option name="BLANK_LINES_AROUND_METHOD_IN_INTERFACE" value="0" />
        <option name="BLANK_LINES_AFTER_CLASS_HEADER" value="1" />
        <option name="ALIGN_MULTILINE_PARAMETERS" value="false" />
        <option name="ALIGN_MULTILINE_FOR" value="false" />
        <option name="SPACE_WITHIN_ARRAY_INITIALIZER_BRACES" value="true" />
        <option name="SPACE_BEFORE_ARRAY_INITIALIZER_LBRACE" value="true" />
        <option name="CALL_PARAMETERS_WRAP" value="1" />
        <option name="METHOD_PARAMETERS_WRAP" value="1" />
        <option name="RESOURCE_LIST_WRAP" value="1" />
        <option name="EXTENDS_LIST_WRAP" value="1" />
        <option name="THROWS_LIST_WRAP" value="1" />
        <option name="EXTENDS_KEYWORD_WRAP" value="1" />
        <option name="THROWS_KEYWORD_WRAP" value="1" />
        <option name="METHOD_CALL_CHAIN_WRAP" value="5" />
        <option name="BINARY_OPERATION_WRAP" value="5" />
        <option name="BINARY_OPERATION_SIGN_ON_NEXT_LINE" value="true" />
        <option name="TERNARY_OPERATION_WRAP" value="1" />
        <option name="TERNARY_OPERATION_SIGNS_ON_NEXT_LINE" value="true" />
        <option name="KEEP_SIMPLE_CLASSES_IN_ONE_LINE" value="true" />
        <option name="FOR_STATEMENT_WRAP" value="1" />
        <option name="ARRAY_INITIALIZER_WRAP" value="1" />
        <option name="ARRAY_INITIALIZER_LBRACE_ON_NEXT_LINE" value="true" />
        <option name="ARRAY_INITIALIZER_RBRACE_ON_NEXT_LINE" value="true" />
        <option name="ASSIGNMENT_WRAP" value="1" />
        <option name="ASSERT_STATEMENT_WRAP" value="1" />
        <option name="IF_BRACE_FORCE" value="3" />
        <option name="DOWHILE_BRACE_FORCE" value="1" />
        <option name="WHILE_BRACE_FORCE" value="1" />
        <option name="FIELD_ANNOTATION_WRAP" value="1" />
        <option name="PARAMETER_ANNOTATION_WRAP" value="1" />
        <option name="VARIABLE_ANNOTATION_WRAP" value="1" />
        <option name="ENUM_CONSTANTS_WRAP" value="2" />
        <option name="PARENT_SETTINGS_INSTALLED" value="true" />
        <indentOptions>
            <option name="INDENT_SIZE" value="2" />
            <option name="CONTINUATION_INDENT_SIZE" value="4" />
            <option name="TAB_SIZE" value="2" />
        </indentOptions>
    </codeStyleSettings>
    <codeStyleSettings language="JSON">
        <option name="KEEP_LINE_BREAKS" value="false" />
        <option name="KEEP_BLANK_LINES_IN_CODE" value="1" />
        <option name="PARENT_SETTINGS_INSTALLED" value="true" />
    </codeStyleSettings>
    <codeStyleSettings language="JavaScript">
        <option name="KEEP_LINE_BREAKS" value="false" />
        <option name="KEEP_FIRST_COLUMN_COMMENT" value="false" />
        <option name="KEEP_BLANK_LINES_IN_CODE" value="1" />
        <option name="ALIGN_MULTILINE_PARAMETERS" value="false" />
        <option name="ALIGN_MULTILINE_FOR" value="false" />
        <option name="CALL_PARAMETERS_WRAP" value="1" />
        <option name="METHOD_PARAMETERS_WRAP" value="1" />
        <option name="BINARY_OPERATION_WRAP" value="5" />
        <option name="BINARY_OPERATION_SIGN_ON_NEXT_LINE" value="true" />
        <option name="TERNARY_OPERATION_WRAP" value="1" />
        <option name="TERNARY_OPERATION_SIGNS_ON_NEXT_LINE" value="true" />
        <option name="FOR_STATEMENT_WRAP" value="1" />
        <option name="ARRAY_INITIALIZER_WRAP" value="1" />
        <option name="ASSIGNMENT_WRAP" value="1" />
        <option name="IF_BRACE_FORCE" value="1" />
        <option name="DOWHILE_BRACE_FORCE" value="1" />
        <option name="WHILE_BRACE_FORCE" value="1" />
        <option name="PARENT_SETTINGS_INSTALLED" value="true" />
        <indentOptions>
            <option name="INDENT_SIZE" value="2" />
            <option name="TAB_SIZE" value="2" />
        </indentOptions>
    </codeStyleSettings>
    <codeStyleSettings language="SQL">
        <option name="KEEP_BLANK_LINES_IN_CODE" value="1" />
        <option name="PARENT_SETTINGS_INSTALLED" value="true" />
    </codeStyleSettings>
    <codeStyleSettings language="TypeScript">
        <option name="KEEP_LINE_BREAKS" value="false" />
        <option name="KEEP_FIRST_COLUMN_COMMENT" value="false" />
        <option name="KEEP_BLANK_LINES_IN_CODE" value="1" />
        <option name="ALIGN_MULTILINE_PARAMETERS" value="false" />
        <option name="ALIGN_MULTILINE_FOR" value="false" />
        <option name="CALL_PARAMETERS_WRAP" value="1" />
        <option name="METHOD_PARAMETERS_WRAP" value="1" />
        <option name="EXTENDS_LIST_WRAP" value="1" />
        <option name="EXTENDS_KEYWORD_WRAP" value="1" />
        <option name="BINARY_OPERATION_WRAP" value="5" />
        <option name="BINARY_OPERATION_SIGN_ON_NEXT_LINE" value="true" />
        <option name="TERNARY_OPERATION_WRAP" value="1" />
        <option name="TERNARY_OPERATION_SIGNS_ON_NEXT_LINE" value="true" />
        <option name="FOR_STATEMENT_WRAP" value="1" />
        <option name="ARRAY_INITIALIZER_WRAP" value="1" />
        <option name="ASSIGNMENT_WRAP" value="1" />
        <option name="WRAP_COMMENTS" value="true" />
        <option name="IF_BRACE_FORCE" value="1" />
        <option name="DOWHILE_BRACE_FORCE" value="1" />
        <option name="WHILE_BRACE_FORCE" value="1" />
        <option name="PARENT_SETTINGS_INSTALLED" value="true" />
    </codeStyleSettings>
    <codeStyleSettings language="XML">
        <indentOptions>
            <option name="INDENT_SIZE" value="2" />
            <option name="CONTINUATION_INDENT_SIZE" value="4" />
            <option name="TAB_SIZE" value="2" />
        </indentOptions>
        <arrangement>
            <rules>
                <sectionView>
                    <rule>
                        <match>
                            <NAME>xmlns:android</NAME>
                        </match>
                    </rule>
                </sectionView>
                <sectionView>
                    <rule>
                        <match>
                            <NAME>xmlns:.*</NAME>
                        </match>
                    </rule>
                </sectionView>
                <sectionView>
                    <rule>
                        <match>
                            <NAME>style</NAME>
                        </match>
                    </rule>
                </sectionView>
                <sectionView>
                    <rule>
                        <match>
                            <AND>
                                <NAME>id</NAME>
                                <XML_NAMESPACE>android</XML_NAMESPACE>
                            </AND>
                        </match>
                    </rule>
                </sectionView>
            </rules>
        </arrangement>
    </codeStyleSettings>
</code_scheme>


text:
package com.updateimpact.report;

public class DependencyId {
    private final String groupId;
    private final String artifactId;
    private final String version;
    private final String type;
    private final String classifier;

    public DependencyId(String groupId, String artifactId, String version, String type, String classifier) {
        this.groupId = groupId;
        this.artifactId = artifactId;
        this.version = version;
        this.type = type;
        this.classifier = classifier;
    }

    public String getGroupId() {
        return groupId;
    }

    public String getArtifactId() {
        return artifactId;
    }

    public String getVersion() {
        return version;
    }

    public String getType() {
        return type;
    }

    public String getClassifier() {
        return classifier;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        DependencyId that = (DependencyId) o;

        if (groupId != null ? !groupId.equals(that.groupId) : that.groupId != null) return false;
        if (artifactId != null ? !artifactId.equals(that.artifactId) : that.artifactId != null) return false;
        if (version != null ? !version.equals(that.version) : that.version != null) return false;
        if (type != null ? !type.equals(that.type) : that.type != null) return false;
        if (classifier != null ? !classifier.equals(that.classifier) : that.classifier != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = groupId != null ? groupId.hashCode() : 0;
        result = 31 * result + (artifactId != null ? artifactId.hashCode() : 0);
        result = 31 * result + (version != null ? version.hashCode() : 0);
        result = 31 * result + (type != null ? type.hashCode() : 0);
        result = 31 * result + (classifier != null ? classifier.hashCode() : 0);
        return result;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(groupId).append(":").append(artifactId).append(":").append(version);
        if (type != null) sb.append(":").append(type);
        if (classifier != null) sb.append(":").append(classifier);
        return sb.toString();
    }
}


text:
package akka.persistence.hbase.journal

import akka.persistence.PersistenceSettings
import java.util.concurrent.atomic.AtomicReference
import org.hbase.async.HBaseClient

object HBaseClientFactory {

  /** based on the docs, there should always be only one instance, reused even if we had more tables */
  private val client = new AtomicReference[HBaseClient]()
  implicit def int2short(intVal: Int) = java.lang.Short.parseShort(intVal.toString)

  /** Always returns the same client */
  def getClient(config: PluginPersistenceSettings, persistenceSettings: PersistenceSettings): HBaseClient = {
    client.compareAndSet(null, new HBaseClient(config.zookeeperQuorum))

    // since we will be forcing a flush anyway after each batch, let's not make asyncbase flush more than it needs to.
    // for example, we tell akka "200", but asyncbase was set to "20", so it would flush way more often than we'd expect it to.
    // by setting the internal flushing to max(...), we're manually in hold of doing the flushing at the rigth moment.
    //    val maxBatchSize = List(
    //      persistenceSettings.journal.maxMessageBatchSize,
    //      persistenceSettings.journal.maxConfirmationBatchSize,
    //      persistenceSettings.journal.maxDeletionBatchSize
    //    ).max.toShort
    val hbaseClient = client.get()
    // set Flush Interval to 0 to disable the batch flush, will flush instantly
    hbaseClient.setFlushInterval(config.clientFlushInterval)
    hbaseClient
  }

  def shutDown() {
    if (client.get() != null) {
      val hbaseClient = client.get()
      client set null
      try {
        hbaseClient.shutdown()
      } catch {
        case e: Exception => System.err.println(s"Caught Exception in hbaseClient shutdown : ${e.getMessage}")
      }
    }
  }

}


text:
package keymap

import (
	"github.com/hajimehoshi/ebiten"
)

// GamepadBtnMap is a bi-directional map connecting gamepad buttons and actions.
type GamepadBtnMap struct {
	btnToAct map[ebiten.GamepadButton]Action
	actToBtn map[Action]ebiten.GamepadButton
}

// NewGamepadBtnMap returns a new, initialized GamepadBtnMap.
func NewGamepadBtnMap() *GamepadBtnMap {
	return &GamepadBtnMap{
		btnToAct: map[ebiten.GamepadButton]Action{},
		actToBtn: map[Action]ebiten.GamepadButton{},
	}
}

// Set associates the given button and action with each other.
func (gm *GamepadBtnMap) Set(b ebiten.GamepadButton, a Action) {
	oldA, oldAok := gm.btnToAct[b]
	oldB, oldBok := gm.actToBtn[a]
	if oldAok {
		delete(gm.actToBtn, oldA)
	}
	if oldBok {
		delete(gm.btnToAct, oldB)
	}

	gm.btnToAct[b] = a
	gm.actToBtn[a] = b
}

// GetButton returns the button associated with the action.
func (gm *GamepadBtnMap) GetButton(a Action) (b ebiten.GamepadButton, ok bool) {
	b, ok = gm.actToBtn[a]
	return
}

// GetAction returns the action associated with the button.
func (gm *GamepadBtnMap) GetAction(b ebiten.GamepadButton) (a Action, ok bool) {
	a, ok = gm.btnToAct[b]
	return
}

// DelButton removes the button and its associated action.
func (gm *GamepadBtnMap) DelButton(b ebiten.GamepadButton) {
	if a, ok := gm.btnToAct[b]; ok {
		delete(gm.btnToAct, b)
		delete(gm.actToBtn, a)
	}
}

// DelAction removes the action and its associated button.
func (gm *GamepadBtnMap) DelAction(a Action) {
	if b, ok := gm.actToBtn[a]; ok {
		delete(gm.actToBtn, a)
		delete(gm.btnToAct, b)
	}
}

// Buttons returns a slice containing all buttons currently in the map.
func (gm *GamepadBtnMap) Buttons() []ebiten.GamepadButton {
	s := make([]ebiten.GamepadButton, 0, len(gm.btnToAct))
	for b := range gm.btnToAct {
		s = append(s, b)
	}
	return s
}

// Actions returns a slice containing all actions currently in the map.
func (gm *GamepadBtnMap) Actions() []Action {
	s := make([]Action, 0, len(gm.actToBtn))
	for a := range gm.actToBtn {
		s = append(s, a)
	}
	return s
}


text:
title: 'What to do'
published: true
date: '11-12-2015 17:49'
summary:
    enabled: '1'
    format: short
taxonomy:
    tag:
        - General
    category:
        - blog
---

Sat at the airport for around four hours -- it seemed preferable to wandering around town in the rain with a suitcase -- I'm taking a pause from reading _The Economist_ to think about what else I could be doing. The fact is, when I travel I don't often make good use of the downtime involved. Well, I make use of it, but not productive use. So, I'll read more of a magazine than I might otherwise and listen to more podcasts, but there's always the nagging guilt that I could be doing something else.

===

It isn't the lack of online access. I could have more of that, for a price. But I've already checked my emails and the social sites that mean something to me, and skipping from site to site online is not actually productive.

More than that, it is a lack of things that I could do when on the road. I've got a couple of ongoing projects -- cleaning up my image files and transferring my main site from one content management system to another -- that I certainly could do. But they're stuck on the desktop machine at home. I have, sometimes, used DropBox to transfer projects to the portable machine so I can work on them while I'm away from home, but neither of those really lends itself to that approach.

OK, now I've used this little bit of downtime to write a post about how to use downtime; very meta. Longer term, though, I think I really need to ensure that I have with me something not too demanding that I could do while on the road.


text:
'use strict';

function _typeof(obj) { return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj; }

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

(function () {
  'use strict';

  /* Module constants. */

  var TRIGGER_KEY_CODES = [13 /*Enter*/, 32 /*Space*/];
  var ROLE_BUTTON_TAGS = ['a', 'div', 'figure', 'p', 'pre', 'blockquote', 'img', 'ins', 'del', 'output', 'span', 'summary'];

  /* Module variables. */
  var moduleName = 'Metsu';
  var instances = {};
  var defaultOptions = {};
  var isIos = navigator.userAgent.match(/iPad|iPhone/i);
  var sanitize = /[^a-z0-9_-]/gi;
  var uid = 0;

  /* Module default options. */
  defaultOptions = {
    triggers: null,
    defaultState: null,
    globalClose: false,
    independent: false,
    noSelfClosing: false,
    beforeCallback: null,
    afterCallback: null,
    /*triggerSelector: '.js-metsu__trigger',
    triggerSelectorContext: true,
    labelSelector: null,
    labelSelectorContext: true,
    contentSelector: '.js-metsu__content',
    contentSelectorContext: true,*/
    contentClass: 'is-open',
    triggerClass: 'is-active',
    /*openedLabel: null,
    closedLabel: null,
    toggleProperties: ['height'],
    toggleOptions: {
      duration: 0
    }*/
    toggleCss: true
  };

  /**
   * Module Constructor.
   *
   * @param {object} options
   *   Instance specific options.
   */
  function Metsu(content, options) {
    var data;

    // Check data.
    if (!content) {
      throw new Error('The content option is mandatory.');
    }
    this.content = this.getElements(content);
    if (!(this.content instanceof Element)) {
      throw new Error('The content is not a valid DOM element.');
    }

    // Merge specific and default options.
    this.options = {};
    this.merge(this.options, defaultOptions);
    this.merge(this.options, options);

    // Data initialization.
    this.setup();

    // Save instances (after setup).
    if (!instances[this.options.group]) {
      instances[this.options.group] = {};
    }
    instances[this.options.group][this.uid] = this;

    // Event binding and default initialization.
    this.bind();
    this.init();
  }

  /**
   * Setup module.
   * e.g. Get DOM elements, setup data...
   */
  Metsu.prototype.setup = function () {
    this.listeners = new Map();
    this.uid = ++uid;

    this.setupDataOptions();

    // Sanitize group name.
    if (this.options.group) {
      this.options.group = this.options.group.toString().replace(sanitize, '');
    }

    // Parse JSON options.
    /*if (typeof this.options.toggleProperties === 'string') {
      this.options.toggleProperties = JSON.parse(this.options.toggleProperties);
    }
     if (typeof this.options.toggleOptions === 'string') {
      this.options.toggleOptions = JSON.parse(this.options.toggleOptions);
    }*/

    // Get trigger elements.
    this.triggers = this.getElements(this.options.triggers);
    if (!(this.triggers instanceof Array)) {
      this.triggers = [this.triggers];
    }

    // Get labels elements.
    /*if (this.options.labelSelector) {
      if (this.options.labelSelectorContext) {
        this.$labels = $(this.options.labelSelector, this.$element);
      } else {
        this.$labels = $(this.options.labelSelector);
      }
    } else {
      this.$labels = this.$triggers;
    }*/

    // Get callbacks.
    this.options.beforeCallback = this.getCallback(this.options.beforeCallback);
    this.options.afterCallback = this.getCallback(this.options.afterCallback);
  };

  /**
   * Setup module specific data.
   * e.g. Get DOM elements, setup data...
   */
  Metsu.prototype.setupDataOptions = function () {
    this.forEach(this.content.dataset, (function (value, index) {
      if (index in defaultOptions) {
        this.options[index] = value;
      }
    }).bind(this));
  };

  /**
   * Bind events.
   */
  Metsu.prototype.bind = function () {
    var eventName = isIos && this.options.globalClose ? 'touchstart' : 'click';
    var elements = this.triggers.concat([this.content]);

    // Bind custom events on all elements.
    this.on(elements, 'destroy', this.destroy.bind(this));
    this.on(elements, 'toggle', this.proxy(this.toggle, this, null));
    this.on(elements, 'close', this.proxy(this.toggle, this, false));
    this.on(elements, 'open', this.proxy(this.toggle, this, true));
    /*this.on(elements, 'isOpen', function() {
      return this.isOpen;
    }.bind(this));*/

    // Bind native events on triggers.
    this.on(this.triggers, eventName, (function (event) {
      var source = event.mozInputSource;
      event.preventDefault();
      if (!source || source !== MouseEvent.MOZ_SOURCE_KEYBOARD) {
        this.toggle(null, event);
      }
    }).bind(this));
    this.on(this.triggers, 'keydown', (function (event) {
      if (TRIGGER_KEY_CODES.indexOf(event.keyCode) !== -1) {
        event.preventDefault();
        this.toggle(null, event);
      }
    }).bind(this));

    // Bind native events on content (avoid triggers click event).
    this.on(this.content, eventName, function (event) {
      event.stopPropagation();
    });
  };

  /**
   * Initialize default module state.
   */
  Metsu.prototype.init = function () {

    // Initialize triggers IDs.
    this.tid = [];
    this.triggers.forEach(this.proxy(this.initId, this, this.tid, 'metsu__trigger'));

    // Initialize contents IDs.
    this.cid = [];
    this.initId(this.cid, 'metsu__content', this.content);

    // Initialize triggers attributes.
    this.triggers.forEach((function (el) {
      var ariaControls = this.attr(el, 'aria-controls') || '';
      ariaControls = ariaControls.split(' ').concat(this.cid);
      this.attr(el, 'aria-controls', ariaControls.join(' '));

      if (!this.attr(el, 'role') && ROLE_BUTTON_TAGS.indexOf(el.tagName.toLowerCase()) !== -1) {
        this.attr(el, 'role', 'button');
      }

      if (!this.attr(el, 'tabindex')) {
        this.attr(el, 'tabindex', '0');
      }
    }).bind(this));

    // Default module state.
    if (['open', 'close'].indexOf(this.options.defaultState) !== -1) {
      this.content.dispatchEvent(this.options.defaultState);
    } else {
      this.isOpen = this.isVisible();
      this.update();
    }
  };

  /**
   * Toggle content.
   *
   * @param {boolean} state
   *   The state of the wanted display.
   * @param {Event} event
   *   The event object.
   */
  Metsu.prototype.toggle = function (state, event) {
    event.stopPropagation();

    if (typeof state !== 'boolean') {
      state = !this.isOpen;
    }

    this.currentTrigger = null;
    if (this.triggers.indexOf(event.currentTarget) !== -1) {
      this.currentTrigger = event.currentTarget;
    }

    if (!this.options.beforeCallback || typeof this.options.beforeCallback === 'function' && this.options.beforeCallback(event)) {
      if (state) {
        this.open();
      } else if (!this.options.noSelfClosing) {
        this.close();
      }
    }
  };

  /**
   * Open content.
   */
  Metsu.prototype.open = function () {
    if (this.isOpen !== true) {
      this.isOpen = true;
      this.do();
      this.closeAll(true);
      if (this.options.globalClose) {
        this.on(document, isIos ? 'touchstart' : 'click', this.proxy(this.closeAll, this, false), this.uid);
      }
    }
  };

  /**
   * Close content.
   */
  Metsu.prototype.close = function () {
    if (this.isOpen !== false) {
      this.isOpen = false;
      this.do();
      this.off(document, isIos ? 'touchstart' : 'click', this.uid);
    }
  };

  /**
   * Close all binded instances.
   *
   * @param {boolean} butItself
   *   Close all but itself or not.
   */
  Metsu.prototype.closeAll = function (butItself) {
    if (!this.options.independent) {
      this.forEach(instances[this.options.group], (function (instance, uid) {
        if (Number(uid) !== this.uid) {
          instance.close();
        }
      }).bind(this));
    }

    if (!butItself) {
      this.close();
    }
  };

  /**
   * Perform toggle action.
   */
  Metsu.prototype.do = function () {
    // var toggleProperties = {};
    // var action = this.isOpen ? 'show' : 'hide';

    this.update();

    if (this.options.toggleCss) {
      if (this.isOpen) {
        this.content.style.display = 'block';
      } else {
        this.content.style.display = 'none';
      }
    }

    if (this.options.afterCallback && typeof this.options.afterCallback === 'function') {
      this.options.afterCallback();
    }

    /*this.options.toggleProperties.forEach(function(value) {
      toggleProperties[value] = action;
    });
     this.$contents.stop().animate(
      toggleProperties,
      this.options.toggleOptions
    );*/
  };

  /**
   * Update classes and aria data.
   */
  Metsu.prototype.update = function () {
    if (this.isOpen) {
      this.addClass(this.content, this.options.contentClass);
      this.attr(this.content, 'aria-hidden', false);
      this.attr(this.triggers, 'aria-expanded', true);
      if (this.currentTrigger) {
        this.addClass(this.currentTrigger, this.options.triggerClass);
      } else {
        this.addClass(this.triggers, this.options.triggerClass);
      }

      /*if (typeof this.options.openedLabel === 'string') {
        this.$labels.html(this.options.openedLabel);
      }*/
    } else {
        this.removeClass(this.content, this.options.contentClass);
        this.attr(this.content, 'aria-hidden', true);
        this.attr(this.triggers, 'aria-expanded', false);
        this.removeClass(this.triggers, this.options.triggerClass);
        /*if (typeof this.options.closedLabel === 'string') {
          this.$labels.html(this.options.closedLabel);
        }*/
      }
  };

  /**
   * Destroy events.
   */
  Metsu.prototype.destroy = function () {
    delete this.content.dataset[moduleName];
    this.off(this.content);
    this.off(this.triggers);
    this.off(this.document);
  };

  /**
   * Is content visible ?
   *
   * @return {boolean}
   *   Visible or not.
   */
  Metsu.prototype.isVisible = function () {
    return this.content.offsetWidth > 0 || this.content.offsetHeight > 0 || this.content.getClientRects().length > 0;
  };

  /**
   * Helper for object iteration.
   *
   * @param {Object} object
   *   Target object.
   * @param {Function} callback
   *   Callback function.
   */
  Metsu.prototype.forEach = function (object, callback) {
    for (var i in object) {
      if (object.hasOwnProperty(i)) {
        callback(object[i], i);
      }
    }
  };

  /**
   * Merge target object with source object.
   *
   * @param {Object} target
   *   Target object.
   * @param {Object} source
   *   Source object.
   * @return {Object}
   *   The merged target.
   */
  Metsu.prototype.merge = function (target, source) {
    this.forEach(source, (function (value, index) {
      target[index] = value;
    }).bind(this));
    return target;
  };

  /**
   * Get elements from given input.
   *
   * @param {mixed} elements
   *   Input element representation.
   * @return {Element}
   *   DOM elements.
   */
  Metsu.prototype.getElements = function (elements) {
    if (typeof elements === 'string') {
      elements = document.querySelectorAll(elements);
    }
    if (elements instanceof NodeList) {
      elements = [].concat(_toConsumableArray(elements));
    }
    return elements;
  };

  /**
   * Get callback function.
   *
   * @param {mixed} callback
   *   Input callback.
   * @return {Function}
   *   Callback function.
   */
  Metsu.prototype.getCallback = function (callback) {
    if (typeof callback === 'string' && window[callback] && typeof window[callback] === 'function') {
      var _callback = window[_callback];
      _callback = _callback.bind(this);
    } else if (typeof callback === 'function') {
      callback = callback.bind(this);
    }
    return callback;
  };

  /**
   * Bind event listener.
   *
   * @param {Element|Array} element
   *   Element or array of elements.
   * @param {string} eventName
   *   Event name.
   * @param {Function} callback
   *   Callback function.
   * @param {string} namespace
   *   Event namespace.
   */
  Metsu.prototype.on = function (element, eventName, callback, namespace) {
    if (element instanceof Element || element instanceof Window || element instanceof Document) {
      this.registerListener(element, eventName, callback, namespace);
      element.addEventListener(eventName, callback);
    } else {
      this.forEach(element, (function (el) {
        this.on(el, eventName, callback, namespace);
      }).bind(this));
    }
  };

  /**
   * Remove event listener.
   *
   * @param {Element|Array} element
   *   Element or array of elements.
   * @param {string} eventName
   *   Event name.
   * @param {string} namespace
   *   Event namespace.
   */
  Metsu.prototype.off = function (element, eventName, namespace) {
    var listeners, callbacks;
    if (element instanceof Element || element instanceof Window || element instanceof Document) {
      listeners = this.listeners.get(element);
      if (listeners && eventName && listeners[eventName]) {
        if (namespace) {
          this.removeListener(element, eventName, namespace);
        } else {
          callbacks = listeners[eventName].callbacks;
          this.forEach(callbacks, (function (callback, namespace) {
            this.removeListener(element, eventName, namespace);
          }).bind(this));
        }
      } else if (listeners && typeof eventName === 'undefined') {
        this.forEach(listeners, (function (eventListeners, eventName) {
          callbacks = eventListeners.callbacks;
          this.forEach(callbacks, (function (callback, namespace) {
            this.removeListener(element, eventName, namespace);
          }).bind(this));
        }).bind(this));
      }
    } else {
      this.forEach(element, (function (el) {
        this.off(el, eventName, namespace);
      }).bind(this));
    }
  };

  /**
   * Register event listener.
   *
   * @param {Element|Array} element
   *   Element or array of elements.
   * @param {string} eventName
   *   Event name.
   * @param {Function} callback
   *   Callback function.
   * @param {string} namespace
   *   Event namespace.
   */
  Metsu.prototype.registerListener = function (element, eventName, callback, namespace) {
    var listeners;
    if (element instanceof Element || element instanceof Window || element instanceof Document) {
      listeners = this.listeners.get(element);
      if (!listeners) {
        listeners = {};
        this.listeners.set(element, listeners);
      }
      if (!listeners[eventName]) {
        listeners[eventName] = {
          callbacks: {},
          next: 0
        };
      }
      if (!namespace) {
        do {
          namespace = listeners[eventName].next++;
        } while (listeners[eventName].callbacks[namespace]);
      }
      listeners[eventName].callbacks[namespace] = callback;
    } else {
      this.forEach(element, (function (el) {
        this.registerListener(el, eventName, callback, namespace);
      }).bind(this));
    }
  };

  /**
   * Remove event listener.
   *
   * @param {Element|Array} element
   *   Element or array of elements.
   * @param {string} eventName
   *   Event name.
   * @param {Function} callback
   *   Callback function.
   * @param {string} namespace
   *   Event namespace.
   */
  Metsu.prototype.removeListener = function (element, eventName, namespace) {
    var callback;
    var listeners = this.listeners.get(element);
    if (listeners[eventName] && listeners[eventName].callbacks[namespace]) {
      callback = listeners[eventName].callbacks[namespace];
      element.removeEventListener(eventName, callback);
      delete listeners[eventName].callbacks[namespace];
    }
  };

  /**
   * Returns function with specific context and arguments.
   *
   * @param {Function} callback
   *   Callback function.
   * @param {Object} context
   *   Context object.
   * @return {Function}
   *   "Proxied" callback.
   */
  Metsu.prototype.proxy = function (callback, context) {
    for (var _len = arguments.length, contextArgs = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
      contextArgs[_key - 2] = arguments[_key];
    }

    return function () {
      for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
        args[_key2] = arguments[_key2];
      }

      return callback.apply(context, contextArgs.concat(args));
    };
  };

  /**
   * Initialize element id.
   *
   * @param {Array} ids
   *   Array of ids.
   * @param {string} prefix
   *   Id prefix.
   * @param {Element} element
   *   DOM element.
   * @param {number} index
   *   Id index.
   * @return {Array}
   *   Array of ids containing the newly created id.
   */
  Metsu.prototype.initId = function (ids, prefix, element) {
    var index = arguments.length <= 3 || arguments[3] === undefined ? 0 : arguments[3];

    ids[index] = element.id;
    if (!ids[index]) {
      ids[index] = prefix + '-' + this.uid + '-' + index;
      element.id = ids[index];
    }
    return ids;
  };

  /**
   * Add class for a DOM element.
   *
   * @param {Mixed} element
   *   Element or array of elements.
   * @param {string} htmlClass
   *   The class to add.
   */
  Metsu.prototype.addClass = function (element, htmlClass) {
    var htmlClasses;
    if (element instanceof Element) {
      htmlClasses = element.getAttribute('class') || '';
      if (htmlClasses.indexOf(htmlClass) === -1) {
        htmlClasses = htmlClasses.split(' ');
        htmlClasses.push(htmlClass);
        element.setAttribute('class', htmlClasses.join(' '));
      }
    } else {
      this.forEach(element, (function (el) {
        this.addClass(el, htmlClass);
      }).bind(this));
    }
  };

  /**
   * Remove class for a DOM element.
   *
   * @param {Mixed} element
   *   Element or array of elements.
   * @param {string} htmlClass
   *   The class to add.
   */
  Metsu.prototype.removeClass = function (element, htmlClass) {
    var htmlClasses, index;
    if (element instanceof Element) {
      htmlClasses = element.getAttribute('class') || '';
      htmlClasses = htmlClasses.split(' ');
      while ((index = htmlClasses.indexOf(htmlClass)) !== -1) {
        delete htmlClasses[index];
      }
      element.setAttribute('class', htmlClasses.join(' ').replace(/\s+/, ' ').trim());
    } else {
      this.forEach(element, (function (el) {
        this.removeClass(el, htmlClass);
      }).bind(this));
    }
  };

  /**
   * Set or get attribute for a DOM element.
   *
   * @param {Mixed} element
   *   Element or array of elements.
   * @param {string} htmlClass
   *   The class to add.
   */
  Metsu.prototype.attr = function (element, attribute, value) {
    if (element instanceof Element) {
      if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) !== undefined) {
        element.setAttribute(attribute, value);
      } else {
        return element.getAttribute(attribute);
      }
    } else {
      if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) !== undefined) {
        this.forEach(element, (function (el) {
          this.attr(el, attribute, value);
        }).bind(this));
      } else {
        return this.attr(element[0], attribute);
      }
    }
  };

  /* Expose module. */
  window[moduleName] = Metsu;
})();


text:
package com.pizza.jackson;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.pizza.model.OrderStatus;

public class OrderStatusJacksonSerializer extends JsonSerializer<OrderStatus> {

	@Override
	public void serialize(OrderStatus status, JsonGenerator generator, SerializerProvider provider)
			throws IOException, JsonProcessingException {

	    generator.writeStartObject();
	    generator.writeFieldName("id");
	    generator.writeString(status.toString());
	    generator.writeFieldName("pretty");
	    generator.writeString(status.getPretty());
	    generator.writeEndObject();
	}

}


text:
package org.springframework.social.google.api.tasks;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.springframework.http.HttpMethod.DELETE;
import static org.springframework.http.HttpMethod.GET;
import static org.springframework.http.HttpMethod.POST;
import static org.springframework.http.HttpMethod.PUT;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.*;

import java.util.Date;

import org.junit.Test;
import org.springframework.social.google.api.AbstractGoogleApiTest;
import org.springframework.social.google.api.tasks.Task;
import org.springframework.social.google.api.tasks.TaskList;
import org.springframework.social.google.api.tasks.TaskListsPage;
import org.springframework.social.google.api.tasks.TaskStatus;
import org.springframework.social.google.api.tasks.TasksPage;

public class TaskTemplateTest extends AbstractGoogleApiTest {

	private static final String DEFAULT = "@default";

	private static final String FIRST_TASK_LIST_ID = "MTY1OTA3NzU4OTQyMFAzMjM0MDc6MDow";
	private static final String FIRST_TASK_LIST_TITLE = "First Task List";

	private static final String SECOND_TASK_LIST_ID = "MTY1OTA2NzU4OSQyMDAzMjM0MDc6NjI7MDQ0NjgwOjA";
	private static final String SECONDS_TASK_LIST_TITLE = "Seconds Task List";

	private static final String COMPLETED_TASK_ID = "MTY1OTA2NxR4OTQyMDAzMjM0CDc6MDox";
	private static final String COMPLETED_TASK_TITLE = "Completed Task";
	private static final Date COMPLETED_TASK_UPDATED = date("2010-02-02T04:05:06.000Z");
	private static final String COMPLETED_TASK_POSITION = "00000000002147483647";
	private static final Date COMPLETED_TASK_DUE = date("2011-01-10T00:00:00.000Z");
	private static final Date COMPLETED_TASK_COMPLETED = date("2011-01-01T01:01:01.000Z");

	private static final String ACTIVE_TASK_ID = "MTY1OTA2NzU4OTQyMQAzMjM0MDc6MDo4GTI5NjMfMTc";
	private static final String ACTIVE_TASK_TITLE = "Active Task";
	private static final String ACTIVE_TASK_NOTES = "Task notes";
	private static final Date ACTIVE_TASK_UPDATED = date("2010-01-01T01:02:03.000Z");
	private static final String ACTIVE_TASK_POSITION = "00000000003221225471";
	private static final Date ACTIVE_TASK_DUE = date("2012-02-02T00:00:00.000Z");

	@Test
	public void getTasklistsPage() {
		mockServer
				.expect(requestTo("https://www.googleapis.com/tasks/v1/users/@me/lists"))
				.andExpect(method(GET))
				.andRespond(
						withSuccess(jsonResource("tasklists"), APPLICATION_JSON));
		TaskListsPage page = google.taskOperations().getTaskLists(null);
		assertTaskListsPage(page);
	}

	@Test
	public void getDefaultTaskList() {
		mockServer
				.expect(requestTo("https://www.googleapis.com/tasks/v1/users/@me/lists/@default"))
				.andExpect(method(GET))
				.andRespond(
						withSuccess(jsonResource("tasklist"), APPLICATION_JSON));
		TaskList taskList = google.taskOperations().getTaskList(DEFAULT);
		assertFirstTaskList(taskList);
	}

	@Test
	public void getTaskListById() {
		mockServer
				.expect(requestTo("https://www.googleapis.com/tasks/v1/users/@me/lists/MTY1OTA3NzU4OTQyMFAzMjM0MDc6MDow"))
				.andExpect(method(GET))
				.andRespond(
						withSuccess(jsonResource("tasklist"), APPLICATION_JSON));
		TaskList taskList = google.taskOperations().getTaskList(
				FIRST_TASK_LIST_ID);
		assertFirstTaskList(taskList);
	}

	@Test
	public void createTaskList() {
		mockServer
				.expect(requestTo("https://www.googleapis.com/tasks/v1/users/@me/lists"))
				.andExpect(method(POST))
				.andRespond(
						withSuccess(jsonResource("tasklist"), APPLICATION_JSON));
		TaskList taskList = google.taskOperations().saveTaskList(
				new TaskList(FIRST_TASK_LIST_TITLE));
		assertFirstTaskList(taskList);
	}

	@Test
	public void updateTaskList() {
		mockServer
				.expect(requestTo("https://www.googleapis.com/tasks/v1/users/@me/lists/MTY1OTA3NzU4OTQyMFAzMjM0MDc6MDow"))
				.andExpect(method(PUT))
				.andRespond(
						withSuccess(jsonResource("tasklist"), APPLICATION_JSON));
		TaskList taskList = google.taskOperations().saveTaskList(
				new TaskList(FIRST_TASK_LIST_ID, FIRST_TASK_LIST_TITLE));
		assertFirstTaskList(taskList);
	}

	@Test
	public void deleteTaskList() {
		mockServer
				.expect(requestTo("https://www.googleapis.com/tasks/v1/users/@me/lists/MTY1OTA3NzU4OTQyMFAzMjM0MDc6MDow"))
				.andExpect(method(DELETE)).andRespond(withNoContent());
		google.taskOperations().deleteTaskList(
				"MTY1OTA3NzU4OTQyMFAzMjM0MDc6MDow");
	}

	@Test
	public void getTasksInDefaultList() {
		mockServer
				.expect(requestTo("https://www.googleapis.com/tasks/v1/lists/@default/tasks?maxResults=100"))
				.andExpect(method(GET))
				.andRespond(
						withSuccess(jsonResource("tasks"), APPLICATION_JSON));
		TasksPage page = google.taskOperations().getTasks();
		assertTasksPage(page);
	}

	@Test
	public void getTasksByListId() {
		mockServer
				.expect(requestTo("https://www.googleapis.com/tasks/v1/lists/MTY1OTA3NzU4OTQyMFAzMjM0MDc6MDow/tasks"))
				.andExpect(method(GET))
				.andRespond(
						withSuccess(jsonResource("tasks"), APPLICATION_JSON));
		TasksPage page = google.taskOperations().getTasks(FIRST_TASK_LIST_ID,
				null);
		assertTasksPage(page);
	}

	@Test
	public void getTaskFromDefaultListById() {
		mockServer
				.expect(requestTo("https://www.googleapis.com/tasks/v1/lists/@default/tasks/MTY1OTA2NzU4OTQyMQAzMjM0MDc6MDo4GTI5NjMfMTc"))
				.andExpect(method(GET))
				.andRespond(withSuccess(jsonResource("task"), APPLICATION_JSON));
		Task task = google.taskOperations().getTask(ACTIVE_TASK_ID);
		assertActiveTask(task);
	}

	@Test
	public void getTaskByIds() {
		mockServer
				.expect(requestTo("https://www.googleapis.com/tasks/v1/lists/MTY1OTA3NzU4OTQyMFAzMjM0MDc6MDow/tasks/MTY1OTA2NzU4OTQyMQAzMjM0MDc6MDo4GTI5NjMfMTc"))
				.andExpect(method(GET))
				.andRespond(withSuccess(jsonResource("task"), APPLICATION_JSON));
		Task task = google.taskOperations().getTask(FIRST_TASK_LIST_ID,
				ACTIVE_TASK_ID);
		assertActiveTask(task);
	}

	@Test
	public void createTask() {
		mockServer
				.expect(requestTo("https://www.googleapis.com/tasks/v1/lists/@default/tasks"))
				.andExpect(method(POST))
				.andRespond(withSuccess(jsonResource("task"), APPLICATION_JSON));
		Task task = google.taskOperations()
				.saveTask(
						new Task(ACTIVE_TASK_TITLE, ACTIVE_TASK_NOTES,
								ACTIVE_TASK_DUE));
		assertActiveTask(task);
	}

	@Test
	public void updateTask() {
		mockServer
				.expect(requestTo("https://www.googleapis.com/tasks/v1/lists/@default/tasks/MTY1OTA2NzU4OTQyMQAzMjM0MDc6MDo4GTI5NjMfMTc"))
				.andExpect(method(PUT))
				.andRespond(withSuccess(jsonResource("task"), APPLICATION_JSON));
		Task task = google.taskOperations().saveTask(
				new Task(ACTIVE_TASK_ID, ACTIVE_TASK_TITLE, ACTIVE_TASK_NOTES,
						ACTIVE_TASK_DUE, null));
		assertActiveTask(task);
	}

	@Test
	public void deleteTask() {
		mockServer
				.expect(requestTo("https://www.googleapis.com/tasks/v1/lists/@default/tasks/MTY1OTA2NzU4OTQyMQAzMjM0MDc6MDo4GTI5NjMfMTc"))
				.andExpect(method(DELETE)).andRespond(withNoContent());
		google.taskOperations().deleteTask(ACTIVE_TASK_ID);
	}

	private void assertTaskListsPage(TaskListsPage page) {
		assertNotNull(page);
		assertEquals(2, page.getItems().size());
		assertNull(page.getNextPageToken());
		assertFirstTaskList(page.getItems().get(0));
		assertSecondTaskList(page.getItems().get(1));
	}

	private void assertFirstTaskList(TaskList taskList) {
		assertNotNull(taskList);
		assertEquals(FIRST_TASK_LIST_ID, taskList.getId());
		assertEquals(FIRST_TASK_LIST_TITLE, taskList.getTitle());
	}

	private void assertSecondTaskList(TaskList taskList) {
		assertNotNull(taskList);
		assertEquals(SECOND_TASK_LIST_ID, taskList.getId());
		assertEquals(SECONDS_TASK_LIST_TITLE, taskList.getTitle());
	}

	private void assertTasksPage(TasksPage page) {
		assertNotNull(page);
		assertEquals(2, page.getItems().size());
		assertNull(page.getNextPageToken());
		assertCompletedTask(page.getItems().get(0));
		assertActiveTask(page.getItems().get(1));
	}

	private void assertCompletedTask(Task task) {
		assertNotNull(task);
		assertEquals(COMPLETED_TASK_ID, task.getId());
		assertEquals(COMPLETED_TASK_TITLE, task.getTitle());
		assertEquals(COMPLETED_TASK_POSITION, task.getPosition());
		assertEquals(TaskStatus.COMPLETED, task.getStatus());
		assertEquals(COMPLETED_TASK_DUE, task.getDue());
		assertEquals(COMPLETED_TASK_UPDATED, task.getUpdated());
		assertEquals(COMPLETED_TASK_COMPLETED, task.getCompleted());
	}

	private void assertActiveTask(Task task) {
		assertNotNull(task);
		assertEquals(ACTIVE_TASK_ID, task.getId());
		assertEquals(ACTIVE_TASK_TITLE, task.getTitle());
		assertEquals(ACTIVE_TASK_NOTES, task.getNotes());
		assertEquals(ACTIVE_TASK_POSITION, task.getPosition());
		assertEquals(TaskStatus.NEEDS_ACTION, task.getStatus());
		assertEquals(ACTIVE_TASK_DUE, task.getDue());
		assertEquals(ACTIVE_TASK_UPDATED, task.getUpdated());
		assertNull(task.getCompleted());
	}
}


text:
import * as React from 'react';
import PropTypes from 'prop-types';
import IconButton from '@material-ui/core/IconButton';
import InputAdornment from '@material-ui/core/InputAdornment';
import { useUtils } from './hooks/useUtils';
import CalendarIcon from '../svg-icons/Calendar';
import { useMaskedInput } from './hooks/useMaskedInput';
import { DateInputProps } from './PureDateInput';
import { getTextFieldAriaText } from './text-field-helper';

export const KeyboardDateInput = React.forwardRef(function KeyboardDateInput(
  props: DateInputProps,
  ref: React.Ref<HTMLDivElement>,
) {
  const {
    components = {},
    disableOpenPicker,
    getOpenDialogAriaText = getTextFieldAriaText,
    InputAdornmentProps,
    InputProps,
    inputRef,
    openPicker,
    OpenPickerButtonProps,
    renderInput,
    ...other
  } = props;
  const utils = useUtils();
  const textFieldProps = useMaskedInput(other);
  const adornmentPosition = InputAdornmentProps?.position || 'end';
  const OpenPickerIcon = components.OpenPickerIcon || CalendarIcon;

  return renderInput({
    ref,
    inputRef,
    ...textFieldProps,
    InputProps: {
      ...InputProps,
      [`${adornmentPosition}Adornment`]: disableOpenPicker ? undefined : (
        <InputAdornment position={adornmentPosition} {...InputAdornmentProps}>
          <IconButton
            edge={adornmentPosition}
            data-mui-test="open-picker-from-keyboard"
            disabled={other.disabled || other.readOnly}
            aria-label={getOpenDialogAriaText(other.rawValue, utils)}
            {...OpenPickerButtonProps}
            onClick={openPicker}
          >
            <OpenPickerIcon />
          </IconButton>
        </InputAdornment>
      ),
    },
  });
});

KeyboardDateInput.propTypes = {
  acceptRegex: PropTypes.instanceOf(RegExp),
  getOpenDialogAriaText: PropTypes.func,
  mask: PropTypes.string,
  OpenPickerButtonProps: PropTypes.object,
  renderInput: PropTypes.func.isRequired,
  rifmFormatter: PropTypes.func,
};

export default KeyboardDateInput;


text:
<script type="text/javascript">
  var Settings = {
    scope           : '<?php echo sfConfig::get('app_facebook_app_scope'); ?>',
    authUser        : '<?php echo url_for('@authUser'); ?>',
    homepage        : '<?php echo url_for('@homepage', true); ?>',
    logout          : '<?php echo url_for('@sf_guard_signout'); ?>'
  };
</script>


text:
<?php

declare(strict_types=1);

namespace Core23\PiwikBundle\Connection;

use Core23\PiwikBundle\Exception\PiwikException;
use Http\Client\HttpClient;
use Http\Message\MessageFactory;

final class PiwikConnection implements ConnectionInterface
{
    /**
     * @var HttpClient
     */
    private $client;

    /**
     * @var MessageFactory
     */
    private $messageFactory;

    /**
     * @var string
     */
    private $apiUrl;

    /**
     * Initialize client.
     *
     * @param HttpClient     $client
     * @param MessageFactory $messageFactory
     * @param string         $apiUrl         base API URL
     */
    public function __construct(HttpClient $client, MessageFactory $messageFactory, string $apiUrl)
    {
        $this->apiUrl         = $apiUrl;
        $this->client         = $client;
        $this->messageFactory = $messageFactory;
    }

    /**
     * {@inheritdoc}
     */
    public function send(array $params = []): string
    {
        $params['module'] = 'API';

        $url      = $this->apiUrl.'?'.$this->getUrlParamString($params);
        $request  = $this->messageFactory->createRequest('GET', $url);
        $response = $this->client->sendRequest($request);

        if (200 !== $response->getStatusCode()) {
            throw new PiwikException(sprintf('"%s" returned an invalid status code: "%s"', $url, $response->getStatusCode()));
        }

        return $response->getBody()->getContents();
    }

    /**
     * Converts a set of parameters to a query string.
     *
     * @param array $params
     *
     * @return string query string
     */
    private function getUrlParamString(array $params): string
    {
        $query = [];
        foreach ($params as $key => $val) {
            if (is_array($val)) {
                $val = implode(',', $val);
            } elseif ($val instanceof \DateTime) {
                $val = $val->format('Y-m-d');
            } elseif (is_bool($val)) {
                if ($val) {
                    $val = 1;
                } else {
                    continue;
                }
            } else {
                $val = urlencode((string) $val);
            }
            $query[] = $key.'='.$val;
        }

        return implode('&', $query);
    }
}


text:
@implementation DomainModule

- (NSDictionary*)domainIPData{
    return @{@"api.imemo8.com":@"218.244.140.1"};
}

@end


text:
package io.scigraph.lucene;

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

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.core.StopAnalyzer;
import org.apache.lucene.analysis.core.StopFilter;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.util.CharArraySet;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.Query;
import org.apache.lucene.util.Version;

import com.google.common.base.Joiner;
import com.google.common.collect.Lists;

public class LuceneUtils {

  public static final String EXACT_SUFFIX = "_EXACT";

  /***
   * @return The current Lucene version in use across the application
   */
  public static Version getVersion() {
    return Version.LUCENE_5_5_0;
  }

  public static final CharArraySet caseSensitiveStopSet;

  static {
    List<String> stopWords = Lists.newArrayList();
    for (Iterator<?> stopWord = StopAnalyzer.ENGLISH_STOP_WORDS_SET.iterator(); stopWord.hasNext();) {
      String word = new String((char[]) stopWord.next());
      stopWords.add(word);
      stopWords.add(Character.toUpperCase(word.charAt(0)) + word.substring(1).toLowerCase());
    }
    caseSensitiveStopSet = StopFilter.makeStopSet(stopWords, false);
  }

  public static boolean isStopword(String word) {
    for (Iterator<?> stopWord = StopAnalyzer.ENGLISH_STOP_WORDS_SET.iterator(); stopWord.hasNext();) {
      String stopword = new String((char[]) stopWord.next());
      if (stopword.equalsIgnoreCase(word)) {
        return true;
      }
    }
    return false;
  }

  public static boolean isAllStopwords(List<String> words) {
    for (String word : words) {
      if (!isStopword(word)) {
        return false;
      }
    }
    return true;
  }

  public static Query getBoostedQuery(QueryParser parser, String queryString, float boost)
      throws ParseException {
    Query query = parser.parse(queryString);
    query.setBoost(boost);
    return query;
  }

  public static String getTokenization(Analyzer analyzer, String term) {
    List<String> ret = getTokenization(analyzer, (CharSequence) term);
    return Joiner.on(", ").join(ret);
  }

  public static List<String> getTokenization(Analyzer analyzer, CharSequence term) {
    List<String> ret = Lists.newArrayList();

    try {
      TokenStream stream = analyzer.tokenStream("", new StringReader(term.toString()));
      CharTermAttribute token = stream.getAttribute(CharTermAttribute.class);
      stream.reset();
      while (stream.incrementToken()) {
        ret.add(token.toString());
      }
      stream.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return ret;
  }

}