text:
using System;
using System.Diagnostics;

public static class RealNumberExtension
{
    public static double Expreal(this int realNumber, RationalNumber r)
    {
        throw new NotImplementedException("You need to implement this extension method.");
    }
}

public struct RationalNumber
{
    public RationalNumber(int numerator, int denominator)
    {
    }

    public static RationalNumber operator +(RationalNumber r1, RationalNumber r2)
    {
        throw new NotImplementedException("You need to implement this operator.");
    }

    public static RationalNumber operator -(RationalNumber r1, RationalNumber r2)
    {
        throw new NotImplementedException("You need to implement this operator.");
    }

    public static RationalNumber operator *(RationalNumber r1, RationalNumber r2)
    {
        throw new NotImplementedException("You need to implement this operator.");
    }

    public static RationalNumber operator /(RationalNumber r1, RationalNumber r2)
    {
        throw new NotImplementedException("You need to implement this operator.");
    }

    public RationalNumber Abs()
    {
        throw new NotImplementedException("You need to implement this function.");
    }

    public RationalNumber Reduce()
    {
        throw new NotImplementedException("You need to implement this function.");
    }

    public RationalNumber Exprational(int power)
    {
        throw new NotImplementedException("You need to implement this function.");
    }

    public double Expreal(int baseNumber)
    {
        throw new NotImplementedException("You need to implement this function.");
    }
}


text:
package com.hrktsoft.portfowardutility;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.hrktsoft.portfowardutility.entry.ForwardEntryL;

/**
 * A configuration loader class
 *
 * @author hrkt
 *
 */
public class ConfigurationLoader {
    /**
     * file path
     */
    private String filePath = null;

    /**
     * @param filePath
     */
    public ConfigurationLoader(String filePath) {
        super();
        this.filePath = filePath;
    }

    public Configuration getConfiguration() throws FileNotFoundException,
            IllegalConfigurationException, IOException {

        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(filePath));

            Configuration configuration = new Configuration();
            List<ForwardEntryL> entriesL = new ArrayList<ForwardEntryL>();

            String line = null;
            while (null != (line = br.readLine())) {
                if (line.startsWith("USER:")) {
                    // parse USER:XXXX
                    if (null != configuration.getUser()) {
                        throw new IllegalConfigurationException(
                                "duplicate user line:" + line);
                    }
                    String[] user = line.split(":");
                    if (user.length != 2) {
                        throw new IllegalConfigurationException("invalid line:"
                                + line);
                    }
                    configuration.setUser(user[1]);
                } else if (line.startsWith("HOST:")) {
                    // parse HOST:XXX.YYY.ZZZ
                    if (null != configuration.getHost()) {
                        throw new IllegalConfigurationException(
                                "duplicate host line:" + line);
                    }
                    String[] host = line.split(":");
                    if (host.length != 2) {
                        throw new IllegalConfigurationException("invalid line:"
                                + line);
                    }
                    configuration.setHost(host[1]);
                } else if (line.startsWith("PORT:")) {
                    // parse PORT:XX
                    String[] portLine = line.split(":");
                    if (portLine.length != 2) {
                        throw new IllegalConfigurationException("invalid line:"
                                + line);
                    }
                    int port = 0;
                    try{
                        port = Integer.parseInt(portLine[1]);
                    } catch (NumberFormatException nfe) {
                        throw new IllegalConfigurationException("invalid line:"
                                + line);
                    }

                    configuration.setPort(port);
                } else if (line.startsWith("L:")) {
                    // parse
                    String[] host = line.split(":");
                    if (host.length != 4) {
                        throw new IllegalConfigurationException("invalid line:"
                                + line);
                    }
                    int localPort = 0;
                    int destPort = 0;
                    try{
                        localPort = Integer.parseInt(host[1]);
                    } catch (NumberFormatException nfe) {
                        throw new IllegalConfigurationException("invalid line:"
                                + line);
                    }
                    String destHost = host[2];
                    if("".equals(destHost)) {
                        throw new IllegalConfigurationException("invalid line:"
                                + line);
                    }
                    try{
                        destPort = Integer.parseInt(host[3]);
                    } catch (NumberFormatException nfe) {
                        throw new IllegalConfigurationException("invalid line:"
                                + line);
                    }

                    ForwardEntryL l = new ForwardEntryL(localPort, destHost, destPort);
                    entriesL.add(l);
                } else if (line.startsWith("#")) {
                    // comment line
                } else {
                    // ignore
                }
            }
            configuration.setForwardEntriesL(entriesL);

            return configuration;
        } catch (IOException e) {
            System.err.println("An error occured in reading file.");
            throw e;
        } finally {
            try {
                if(null != br){
                    br.close();
                }
            } catch (IOException e) {
                System.err.println("An error occured in closing file.");
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
var punishments = [];
var crazy;

punishments.push("Thou Shall refer to us Thy majesty");
punishments.push("20 Pushups (except for xiao: 20 with someone else on top)");
punishments.push("Bring coffee/beverages to everyone");
punishments.push("Sing a song");

function punish() {
  var randomPunishment = Math.floor(Math.random() * punishments.length);
  var punishment = punishments[randomPunishment];

  var name = document.getElementById('name').value ;

  var salutation = document.getElementById('punishment-salutation')
  salutation.innerText = "Hi " + name + "!!" + " Ready to be punished?"

  document.getElementById('punishment').innerHTML = punishment;
}

function crazyBackground() {
  var colors = ["green", "red", "blue" , "Salmon" , "hotPink"
    , "white" , "yellow", "gold", "orchid", "lightcyan"];
  var randomNumber = Math.floor(Math.random() * colors.length);

  document.bgColor = colors[randomNumber];
}

function raveWDI() {
  crazy = setInterval(crazyBackground, 200);
}

function peanutButterJellyTime() {
  // add class peanut to image with ID peanut which is the large dancing banana
  document.getElementById('peanut').className = "peanut";
  // add class top-dance and respective classes to initialize animation
  document.getElementById(('t1')).className = ("top-dance t1");
  document.getElementById(('t2')).className = ("top-dance t2");
  document.getElementById(('t3')).className = ("top-dance t3");
  document.getElementById(('t4')).className = ("top-dance t4");
  document.getElementById(('t5')).className = ("top-dance t5");
  document.getElementById(('t6')).className = ("top-dance t6");
  document.getElementById(('t7')).className = ("top-dance t7");
  document.getElementById(('t8')).className = ("top-dance t8");
  document.getElementById(('t9')).className = ("top-dance t9");
  document.getElementById(('t10')).className = ("top-dance t10");
  // add class bot-dance and respective classes to initialize animation
  document.getElementById(('b1')).className = ("bot-dance b1");
  document.getElementById(('b2')).className = ("bot-dance b2");
  document.getElementById(('b3')).className = ("bot-dance b3");
  document.getElementById(('b4')).className = ("bot-dance b4");
  document.getElementById(('b5')).className = ("bot-dance b5");
  document.getElementById(('b6')).className = ("bot-dance b6");
  document.getElementById(('b7')).className = ("bot-dance b7");
  document.getElementById(('b8')).className = ("bot-dance b8");
  document.getElementById(('b9')).className = ("bot-dance b9");
  document.getElementById(('b10')).className = ("bot-dance b10");
}

function forkTheRepo() {
  document.getElementById('fork').className = "fork";
  document.getElementById('repo').className = "repo";
}

// to Stop the RAVE, pls clear the interval timer
// clearInterval(crazy);


text:
package org.elasticsearch.xpack.sql.cli;

import org.jline.reader.Completer;
import org.jline.reader.impl.completer.AggregateCompleter;
import org.jline.reader.impl.completer.ArgumentCompleter;
import org.jline.reader.impl.completer.StringsCompleter;

class Completers {
    // TODO: need tree structure
    static final Completer INSTANCE = new AggregateCompleter(
        new ArgumentCompleter(new StringsCompleter("", "EXPLAIN", "SHOW", "SELECT", "SET")),
        new ArgumentCompleter(new StringsCompleter("SHOW", "TABLE", "COLUMNS", "FUNCTIONS"))
    );

}


text:
#include "config.h"
#include "web/WebFontImpl.h"

#include "platform/fonts/FontCache.h"
#include "platform/fonts/FontDescription.h"
#include "platform/graphics/GraphicsContext.h"
#include "platform/text/TextRun.h"
#include "public/platform/WebFloatPoint.h"
#include "public/platform/WebFloatRect.h"
#include "public/platform/WebRect.h"
#include "public/web/WebFontDescription.h"
#include "public/web/WebTextRun.h"

namespace blink {

WebFont* WebFont::create(const WebFontDescription& desc)
{
    return new WebFontImpl(desc);
}

WebFontImpl::WebFontImpl(const FontDescription& desc)
    : m_font(desc)
{
    m_font.update(nullptr);
}

WebFontDescription WebFontImpl::fontDescription() const
{
    return WebFontDescription(m_font.fontDescription());
}

int WebFontImpl::ascent() const
{
    return m_font.fontMetrics().ascent();
}

int WebFontImpl::descent() const
{
    return m_font.fontMetrics().descent();
}

int WebFontImpl::height() const
{
    return m_font.fontMetrics().height();
}

int WebFontImpl::lineSpacing() const
{
    return m_font.fontMetrics().lineSpacing();
}

float WebFontImpl::xHeight() const
{
    return m_font.fontMetrics().xHeight();
}

void WebFontImpl::drawText(WebCanvas* canvas, const WebTextRun& run, const WebFloatPoint& leftBaseline,
                           WebColor color, const WebRect& clip, bool canvasIsOpaque,
                           int from, int to) const
{
    FontCachePurgePreventer fontCachePurgePreventer;
    FloatRect textClipRect(clip);
    TextRun textRun(run);
    TextRunPaintInfo runInfo(textRun);
    runInfo.from = from;
    runInfo.to = to == -1 ? textRun.length() : to;
    runInfo.bounds = textClipRect;
    GraphicsContext gc(canvas, nullptr);

    gc.save();
    gc.setCertainlyOpaque(canvasIsOpaque);
    gc.setFillColor(color);
    gc.clip(textClipRect);
    m_font.drawText(&gc, runInfo, leftBaseline);
    gc.restore();
}

int WebFontImpl::calculateWidth(const WebTextRun& run) const
{
    return m_font.width(run, 0);
}

int WebFontImpl::offsetForPosition(const WebTextRun& run, float position) const
{
    return m_font.offsetForPosition(run, position, true);
}

WebFloatRect WebFontImpl::selectionRectForText(const WebTextRun& run, const WebFloatPoint& leftBaseline, int height, int from, int to) const
{
    return m_font.selectionRectForText(run, leftBaseline, height, from, to);
}

} // namespace blink


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package de.matthiasmann.continuations;

import junit.framework.TestCase;

/**
 *
 * @author Matthias Mann
 */
public class ArrayTest extends TestCase implements CoroutineProto {

    private static final PatchLevel l1 = new PatchLevel();
    private static final PatchLevel[] l2 = new PatchLevel[] { l1 };
    private static final PatchLevel[][] l3 = new PatchLevel[][] { l2 };

    public void testArray() {
        Coroutine co = new Coroutine(this);
        co.run();
        assertEquals(42, l1.i);
    }

    public void coExecute() throws SuspendExecution {
        PatchLevel[][] local_patch_levels = l3;
        PatchLevel patch_level = local_patch_levels[0][0];
        patch_level.setLevel(42);
    }

    public static class PatchLevel {
        int i;

        public void setLevel(int value) throws SuspendExecution {
            i = value;
        }
    }
}


text:
//
//  TYAttributedLabel.h
//  TYAttributedLabelDemo
//
//  Created by tanyang on 15/4/8.
//  Copyright (c) 2015年 tanyang. All rights reserved.
//  TYAttributedLabel v2.0 verson

#import <UIKit/UIKit.h>
#import "TYTextContainer.h"

typedef NS_ENUM(NSUInteger, TYVerticalAlignment) {
    TYVerticalAlignmentTop,
    TYVerticalAlignmentCenter,
    TYVerticalAlignmentBottom,
};

@class TYAttributedLabel;
@protocol TYAttributedLabelDelegate <NSObject>
@optional

// 点击代理
- (void)attributedLabel:(TYAttributedLabel *)attributedLabel textStorageClicked:(id<TYTextStorageProtocol>)textStorage atPoint:(CGPoint)point;

// 长按代理 有多个状态 begin, changes, end 都会调用,所以需要判断状态
- (void)attributedLabel:(TYAttributedLabel *)attributedLabel textStorageLongPressed:(id<TYTextStorageProtocol>)textStorage onState:(UIGestureRecognizerState)state atPoint:(CGPoint)point;
@end

/**
 *  TYAttributedLabel 属性文本 支持图文混排显示,支持添加image和UIView,支持自定义排版
 */
@interface TYAttributedLabel : UIView

@property (nonatomic, assign) id<TYAttributedLabelDelegate>     delegate;

@property (nonatomic, strong)   NSString    *text;
@property (nonatomic, strong)   UIColor     *textColor;         // 文字颜色
@property (nonatomic, strong)   UIFont      *font;              // 文字大小
@property (nonatomic,assign)    NSInteger   numberOfLines;      //行数

@property (nonatomic, strong)   UIColor     *linkColor;           //链接颜色
@property (nonatomic, strong)   UIColor     *highlightedLinkColor;//默认nil高亮链接颜色
@property (nonatomic, strong)   UIColor     *highlightedLinkBackgroundColor;//链接高亮背景颜色
@property (nonatomic, assign)   CGFloat     highlightedLinkBackgroundRadius; // 高亮背景圆角

@property (nonatomic, assign)   unichar     strokeWidth;    // 空心字边框宽
@property (nonatomic, strong)   UIColor     *strokeColor;   // 空心字边框颜色

@property (nonatomic, assign)   unichar     characterSpacing;   // 字距
@property (nonatomic, assign)   CGFloat     linesSpacing;       // 行距
@property (nonatomic, assign)   CGFloat     paragraphSpacing;   // 段落间距

@property (nonatomic, assign)   CTTextAlignment textAlignment;  // 文本对齐方式 kCTTextAlignmentLeft
@property (nonatomic, assign)   CTLineBreakMode lineBreakMode;  // 换行模式 kCTLineBreakByCharWrapping
@property (nonatomic, assign)   TYVerticalAlignment verticalAlignment; // 垂直对齐方式 默认是向上对齐

@property (nonatomic, strong)   TYTextContainer *textContainer;

@property (nonatomic, assign)   CGFloat preferredMaxLayoutWidth; // Autolayout

@property (nonatomic, assign)   BOOL isWidthToFit;    // 宽度自适应 默认NO

/**
 *  获取普通文本内容
 */
- (NSString *)text;

/**
 *  获取属性文本内容
 */
- (NSAttributedString *)attributedText;

/**
 *  设置普通初始化文本内容
 *
 *  @param text 普通文本内容
 */
- (void)setText:(NSString *)text;

/**
 *  设置属性初始化文本内容
 *
 *  @param attributedText 属性文本内容
 */
- (void)setAttributedText: (NSAttributedString *)attributedText;

/**
 *  添加 textStorage (自定义显示内容)
 *
 *  @param textStorage 自定义
 */
- (void)addTextStorage:(id<TYTextStorageProtocol>)textStorage;

/**
 *  添加 textRun数组 (自定义显示内容)
 *
 *  @param textRunArray textRun数组(需遵循协议TYTextStorageProtocol,否则不会添加)
 */
- (void)addTextStorageArray:(NSArray *)textStorageArray;

/**
 *  调用可以自动计算frame大小(请确定label之前设置了宽度)
 */
- (void)sizeToFit;

/**
 *  获取文本真正的高度
 */
- (int)getHeightWithWidth:(CGFloat)width;

/**
 *  获取文本真正的size
 */
- (CGSize)getSizeWithWidth:(CGFloat)width;

/**
 *  设置文本位置大小 (自动计算高度,根据宽度)
 */
- (void)setFrameWithOrign:(CGPoint)orign Width:(CGFloat)width;

@end

#pragma mark - 扩展追加内容 (Append)
// 追加内容 (添加在AttributedString最后)
@interface TYAttributedLabel (AppendAttributedString)
/**
 *  追加(添加到最后) 普通文本
 *
 *  @param text 普通文本
 */
- (void)appendText:(NSString *)text;

/**
 *  追加(添加到最后) 属性文本
 *
 *  @param attributedText 属性文本
 */
- (void)appendTextAttributedString: (NSAttributedString *)attributedText;

/**
 *  追加(添加到最后) textStorage (自定义显示内容)
 *
 *  @param textStorage 自定义Storage(自定义显示内容)
 */
- (void)appendTextStorage:(id<TYAppendTextStorageProtocol>)textStorage;

/**
 *  追加(添加到最后) textStorage 数组
 *
 *  @param textStorageArray 自定义run数组(需遵循协议TYAppendTextStorageProtocol,否则不会添加)
 */
- (void)appendTextStorageArray:(NSArray *)textStorageArray;

@end

#pragma mark - 扩展支持Link链接
@interface TYAttributedLabel (Link)

/**
 *  添加 链接LinkTextStorage
 */
- (void)addLinkWithLinkData:(id)linkData range:(NSRange )range;

/**
 *  添加 链接LinkTextStorage
 *
 *  @param linkData  链接携带的数据
 *  @param linkColor 链接颜色
 *  @param range     范围
 */
- (void)addLinkWithLinkData:(id)linkData linkColor:(UIColor *)linkColor range:(NSRange )range;

- (void)addLinkWithLinkData:(id)linkData linkColor:(UIColor *)linkColor underLineStyle:(CTUnderlineStyle)underLineStyle range:(NSRange )range;

/**
 *  追加 链接LinkTextStorage
 */
- (void)appendLinkWithText:(NSString *)linkText linkFont:(UIFont *)linkFont linkData:(id)linkData;

/**
 *  追加 链接LinkTextStorage
 *
 *  @param linkText  链接文本
 *  @param linkData   链接携带的数据
 */
- (void)appendLinkWithText:(NSString *)linkText linkFont:(UIFont *)linkFont linkColor:(UIColor *)linkColor linkData:(id)linkData;

- (void)appendLinkWithText:(NSString *)linkText linkFont:(UIFont *)linkFont linkColor:(UIColor *)linkColor underLineStyle:(CTUnderlineStyle)underLineStyle linkData:(id)linkData;

@end

#pragma mark - 扩展支持UIImage
@interface TYAttributedLabel (UIImage)

#pragma mark - addImageStorage

/**
 *  添加 imageStorage image数据
 */
- (void)addImage:(UIImage *)image range:(NSRange)range;

/**
 *  添加 imageStorage image数据
 */
- (void)addImage:(UIImage *)image range:(NSRange)range size:(CGSize)size;

/**
 *  添加 imageStorage image数据
 *
 *  @param image        image
 *  @param range        所在文本位置
 *  @param size         图片大小
 *  @param alignment    图片对齐方式
 */
- (void)addImage:(UIImage *)image range:(NSRange)range
                                   size:(CGSize)size
                              alignment: (TYDrawAlignment)alignment;

/**
 *  添加 imageStorage image数据
 */
- (void)addImageWithName:(NSString *)imageName range:(NSRange)range;

/**
 *  添加 imageStorage image数据
 */
- (void)addImageWithName:(NSString *)imageName
                      range:(NSRange)range
                       size:(CGSize)size;

/**
 *  添加 imageStorage image数据
 *
 *  @param imageName    image名
 *  @param range        所在文本位置
 *  @param size         图片大小
 *  @param alignment    图片对齐方式
 */
- (void)addImageWithName:(NSString *)imageName
                   range:(NSRange)range
                    size:(CGSize)size
               alignment:(TYDrawAlignment)alignment;

#pragma mark - appendImageStorage

/**
 *  追加 imageStorage image数据
 */
- (void)appendImage:(UIImage *)image;

/**
 *  追加 imageStorage image数据
 */
- (void)appendImage:(UIImage *)image
               size:(CGSize)size;

/**
 *  追加 imageStorage image数据
 *
 *  @param image    image
 *  @param size         图片大小
 *  @param alignment    图片对齐
 */
- (void)appendImage:(UIImage *)image
               size:(CGSize)size
          alignment:(TYDrawAlignment)alignment;

/**
 *  追加 imageStorage image数据
 */
- (void)appendImageWithName:(NSString *)imageName;

/**
 *  追加 imageStorage image数据
 */
- (void)appendImageWithName:(NSString *)imageName size:(CGSize)size;

/**
 *  追加 imageStorage image数据
 *
 *  @param imageName    imageName
 *  @param size         图片大小
 *  @param alignment    图片对齐
 */
- (void)appendImageWithName:(NSString *)imageName
                       size:(CGSize)size
                  alignment:(TYDrawAlignment)alignment;

@end

#pragma mark - 扩展支持UIView
@interface TYAttributedLabel (UIView)

/**
 *  添加 viewStorage (添加 UI控件 需要设置frame)
 */
- (void)addView:(UIView *)view range:(NSRange)range;

/**
 *  添加 viewStorage (添加 UI控件 需要设置frame)
 *
 *  @param view         UIView (UI控件)
 *  @param range        所在文本位置
 *  @param alignment    view对齐方式
 */
- (void)addView:(UIView *)view
          range:(NSRange)range
      alignment:(TYDrawAlignment)alignment;

/**
 *  追加 viewStorage (添加 UI控件 需要设置frame)
 */
- (void)appendView:(UIView *)view;

/**
 *  追加 viewStorage (添加 UI控件 需要设置frame)
 *
 *  @param view  UIView (UI控件)
 *  @param alignment view对齐
 */
- (void)appendView:(UIView *)view alignment:(TYDrawAlignment)alignment;

@end


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _reactDom = require('react-dom');

var _reactDom2 = _interopRequireDefault(_reactDom);

var _Button = require('react-bootstrap/lib/Button');

var _Button2 = _interopRequireDefault(_Button);

var _FormControl = require('react-bootstrap/lib/FormControl');

var _FormControl2 = _interopRequireDefault(_FormControl);

var _InputGroup = require('react-bootstrap/lib/InputGroup');

var _InputGroup2 = _interopRequireDefault(_InputGroup);

var _Overlay = require('react-bootstrap/lib/Overlay');

var _Overlay2 = _interopRequireDefault(_Overlay);

var _Popover = require('react-bootstrap/lib/Popover');

var _Popover2 = _interopRequireDefault(_Popover);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

var _createReactClass = require('create-react-class');

var _createReactClass2 = _interopRequireDefault(_createReactClass);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var instanceCount = 0; // See http://jszen.blogspot.com/2007/03/how-to-build-simple-calendar-with.html for calendar logic.

var CalendarHeader = (0, _createReactClass2.default)({
  displayName: 'DatePickerHeader',

  propTypes: {
    displayDate: _propTypes2.default.object.isRequired,
    minDate: _propTypes2.default.string,
    maxDate: _propTypes2.default.string,
    onChange: _propTypes2.default.func.isRequired,
    monthLabels: _propTypes2.default.array.isRequired,
    previousButtonElement: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.object]).isRequired,
    nextButtonElement: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.object]).isRequired
  },

  displayingMinMonth: function displayingMinMonth() {
    if (!this.props.minDate) return false;

    var displayDate = new Date(this.props.displayDate);
    var minDate = new Date(this.props.minDate);
    return minDate.getFullYear() == displayDate.getFullYear() && minDate.getMonth() == displayDate.getMonth();
  },
  displayingMaxMonth: function displayingMaxMonth() {
    if (!this.props.maxDate) return false;

    var displayDate = new Date(this.props.displayDate);
    var maxDate = new Date(this.props.maxDate);
    return maxDate.getFullYear() == displayDate.getFullYear() && maxDate.getMonth() == displayDate.getMonth();
  },
  handleClickPrevious: function handleClickPrevious() {
    var newDisplayDate = new Date(this.props.displayDate);
    newDisplayDate.setDate(1);
    newDisplayDate.setMonth(newDisplayDate.getMonth() - 1);
    this.props.onChange(newDisplayDate);
  },
  handleClickNext: function handleClickNext() {
    var newDisplayDate = new Date(this.props.displayDate);
    newDisplayDate.setDate(1);
    newDisplayDate.setMonth(newDisplayDate.getMonth() + 1);
    this.props.onChange(newDisplayDate);
  },
  render: function render() {
    return _react2.default.createElement(
      'div',
      { className: 'text-center' },
      _react2.default.createElement(
        'div',
        { className: 'text-muted pull-left datepicker-previous-wrapper', onClick: this.handleClickPrevious, style: { cursor: 'pointer' } },
        this.displayingMinMonth() ? null : this.props.previousButtonElement
      ),
      _react2.default.createElement(
        'span',
        null,
        this.props.monthLabels[this.props.displayDate.getMonth()],
        ' ',
        this.props.displayDate.getFullYear()
      ),
      _react2.default.createElement(
        'div',
        { className: 'text-muted pull-right datepicker-next-wrapper', onClick: this.handleClickNext, style: { cursor: 'pointer' } },
        this.displayingMaxMonth() ? null : this.props.nextButtonElement
      )
    );
  }
});

var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

var Calendar = (0, _createReactClass2.default)({
  displayName: 'DatePickerCalendar',

  propTypes: {
    selectedDate: _propTypes2.default.object,
    displayDate: _propTypes2.default.object.isRequired,
    minDate: _propTypes2.default.string,
    maxDate: _propTypes2.default.string,
    onChange: _propTypes2.default.func.isRequired,
    dayLabels: _propTypes2.default.array.isRequired,
    cellPadding: _propTypes2.default.string.isRequired,
    weekStartsOn: _propTypes2.default.number,
    showTodayButton: _propTypes2.default.bool,
    todayButtonLabel: _propTypes2.default.string,
    roundedCorners: _propTypes2.default.bool,
    showWeeks: _propTypes2.default.bool
  },

  handleClick: function handleClick(e) {
    var day = e.currentTarget.getAttribute('data-day');
    var newSelectedDate = this.setTimeToNoon(new Date(this.props.displayDate));
    newSelectedDate.setDate(day);
    this.props.onChange(newSelectedDate);
  },
  handleClickToday: function handleClickToday() {
    var newSelectedDate = this.setTimeToNoon(new Date());
    this.props.onChange(newSelectedDate);
  },
  setTimeToNoon: function setTimeToNoon(date) {
    date.setHours(12);
    date.setMinutes(0);
    date.setSeconds(0);
    date.setMilliseconds(0);
    return date;
  },
  getWeekNumber: function getWeekNumber(date) {
    var target = new Date(date.valueOf());
    var dayNr = (date.getDay() + 6) % 7;
    target.setDate(target.getDate() - dayNr + 3);
    var firstThursday = target.valueOf();
    target.setMonth(0, 1);
    if (target.getDay() !== 4) {
      target.setMonth(0, 1 + (4 - target.getDay() + 7) % 7);
    }
    return 1 + Math.ceil((firstThursday - target) / 604800000);
  },
  render: function render() {
    var _this = this;

    var currentDate = this.setTimeToNoon(new Date());
    var selectedDate = this.props.selectedDate ? this.setTimeToNoon(new Date(this.props.selectedDate)) : null;
    var minDate = this.props.minDate ? this.setTimeToNoon(new Date(this.props.minDate)) : null;
    var maxDate = this.props.maxDate ? this.setTimeToNoon(new Date(this.props.maxDate)) : null;
    var year = this.props.displayDate.getFullYear();
    var month = this.props.displayDate.getMonth();
    var firstDay = new Date(year, month, 1);
    var startingDay = this.props.weekStartsOn > 1 ? firstDay.getDay() - this.props.weekStartsOn + 7 : this.props.weekStartsOn === 1 ? firstDay.getDay() === 0 ? 6 : firstDay.getDay() - 1 : firstDay.getDay();
    var showWeeks = this.props.showWeeks;

    var monthLength = daysInMonth[month];
    if (month == 1) {
      if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
        monthLength = 29;
      }
    }

    var weeks = [];
    var day = 1;
    for (var i = 0; i < 9; i++) {
      var week = [];
      for (var j = 0; j <= 6; j++) {
        if (day <= monthLength && (i > 0 || j >= startingDay)) {
          var className = null;
          var date = new Date(year, month, day, 12, 0, 0, 0).toISOString();
          var beforeMinDate = minDate && Date.parse(date) < Date.parse(minDate);
          var afterMinDate = maxDate && Date.parse(date) > Date.parse(maxDate);
          var clickHandler = this.handleClick;
          var style = { cursor: 'pointer', padding: this.props.cellPadding, borderRadius: this.props.roundedCorners ? 5 : 0 };

          if (beforeMinDate || afterMinDate) {
            className = 'text-muted';
            clickHandler = null;
            style.cursor = 'default';
          } else if (Date.parse(date) === Date.parse(selectedDate)) {
            className = 'bg-primary';
          } else if (Date.parse(date) === Date.parse(currentDate)) {
            className = 'text-primary';
          }

          week.push(_react2.default.createElement(
            'td',
            {
              key: j,
              'data-day': day,
              onClick: clickHandler,
              style: style,
              className: className
            },
            day
          ));
          day++;
        } else {
          week.push(_react2.default.createElement('td', { key: j }));
        }
      }

      if (showWeeks) {
        var weekNum = this.getWeekNumber(new Date(year, month, day - 1, 12, 0, 0, 0));
        week.unshift(_react2.default.createElement(
          'td',
          {
            key: 7,
            style: { padding: this.props.cellPadding, fontSize: '0.8em', color: 'darkgrey' },
            className: 'text-muted'
          },
          weekNum
        ));
      }

      weeks.push(_react2.default.createElement(
        'tr',
        { key: i },
        week
      ));
      if (day > monthLength) {
        break;
      }
    }

    var weekColumn = showWeeks ? _react2.default.createElement('td', {
      className: 'text-muted current-week',
      style: { padding: this.props.cellPadding } }) : null;

    return _react2.default.createElement(
      'table',
      { className: 'text-center' },
      _react2.default.createElement(
        'thead',
        null,
        _react2.default.createElement(
          'tr',
          null,
          weekColumn,
          this.props.dayLabels.map(function (label, index) {
            return _react2.default.createElement(
              'td',
              {
                key: index,
                className: 'text-muted',
                style: { padding: _this.props.cellPadding } },
              _react2.default.createElement(
                'small',
                null,
                label
              )
            );
          })
        )
      ),
      _react2.default.createElement(
        'tbody',
        null,
        weeks
      ),
      this.props.showTodayButton && _react2.default.createElement(
        'tfoot',
        null,
        _react2.default.createElement(
          'tr',
          null,
          _react2.default.createElement(
            'td',
            { colSpan: this.props.dayLabels.length, style: { paddingTop: '9px' } },
            _react2.default.createElement(
              _Button2.default,
              {
                block: true,
                bsSize: 'xsmall',
                className: 'u-today-button',
                onClick: this.handleClickToday },
              this.props.todayButtonLabel
            )
          )
        )
      )
    );
  }
});

exports.default = (0, _createReactClass2.default)({
  displayName: 'DatePicker',

  propTypes: {
    defaultValue: _propTypes2.default.string,
    value: _propTypes2.default.string,
    required: _propTypes2.default.bool,
    className: _propTypes2.default.string,
    style: _propTypes2.default.object,
    minDate: _propTypes2.default.string,
    maxDate: _propTypes2.default.string,
    cellPadding: _propTypes2.default.string,
    autoComplete: _propTypes2.default.string,
    placeholder: _propTypes2.default.string,
    dayLabels: _propTypes2.default.array,
    monthLabels: _propTypes2.default.array,
    onChange: _propTypes2.default.func,
    onClear: _propTypes2.default.func,
    onBlur: _propTypes2.default.func,
    onFocus: _propTypes2.default.func,
    autoFocus: _propTypes2.default.bool,
    disabled: _propTypes2.default.bool,
    weekStartsOnMonday: function weekStartsOnMonday(props, propName, componentName) {
      if (props[propName]) {
        return new Error('Prop \'' + propName + '\' supplied to \'' + componentName + '\' is obsolete. Use \'weekStartsOn\' instead.');
      }
    },
    weekStartsOn: _propTypes2.default.number,
    clearButtonElement: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.object]),
    showClearButton: _propTypes2.default.bool,
    previousButtonElement: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.object]),
    nextButtonElement: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.object]),
    calendarPlacement: _propTypes2.default.oneOfType([_propTypes2.default.string, _propTypes2.default.func]),
    dateFormat: _propTypes2.default.string, // 'MM/DD/YYYY', 'DD/MM/YYYY', 'YYYY/MM/DD', 'DD-MM-YYYY'
    bsClass: _propTypes2.default.string,
    bsSize: _propTypes2.default.string,
    calendarContainer: _propTypes2.default.object,
    id: _propTypes2.default.string,
    name: _propTypes2.default.string,
    showTodayButton: _propTypes2.default.bool,
    todayButtonLabel: _propTypes2.default.string,
    instanceCount: _propTypes2.default.number,
    customControl: _propTypes2.default.object,
    roundedCorners: _propTypes2.default.bool,
    showWeeks: _propTypes2.default.bool,
    children: _propTypes2.default.oneOfType([_propTypes2.default.arrayOf(_propTypes2.default.node), _propTypes2.default.node]),
    onInvalid: _propTypes2.default.func,
    noValidate: _propTypes2.default.bool
  },

  getDefaultProps: function getDefaultProps() {
    var language = typeof window !== 'undefined' && window.navigator ? (window.navigator.userLanguage || window.navigator.language || '').toLowerCase() : '';
    var dateFormat = !language || language === 'en-us' ? 'MM/DD/YYYY' : 'DD/MM/YYYY';
    return {
      cellPadding: '5px',
      dayLabels: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
      monthLabels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
      clearButtonElement: '×',
      previousButtonElement: '<',
      nextButtonElement: '>',
      calendarPlacement: 'bottom',
      dateFormat: dateFormat,
      showClearButton: true,
      autoFocus: false,
      disabled: false,
      showTodayButton: false,
      todayButtonLabel: 'Today',
      autoComplete: 'on',
      showWeeks: false,
      instanceCount: instanceCount++,
      style: {
        width: '100%'
      },
      roundedCorners: false,
      noValidate: false
    };
  },
  getInitialState: function getInitialState() {
    if (this.props.value && this.props.defaultValue) {
      throw new Error('Conflicting DatePicker properties \'value\' and \'defaultValue\'');
    }
    var state = this.makeDateValues(this.props.value || this.props.defaultValue);
    if (this.props.weekStartsOn > 1) {
      state.dayLabels = this.props.dayLabels.slice(this.props.weekStartsOn).concat(this.props.dayLabels.slice(0, this.props.weekStartsOn));
    } else if (this.props.weekStartsOn === 1) {
      state.dayLabels = this.props.dayLabels.slice(1).concat(this.props.dayLabels.slice(0, 1));
    } else {
      state.dayLabels = this.props.dayLabels;
    }
    state.focused = false;
    state.inputFocused = false;
    state.placeholder = this.props.placeholder || this.props.dateFormat;
    state.separator = this.props.dateFormat.match(/[^A-Z]/)[0];
    return state;
  },
  makeDateValues: function makeDateValues(isoString) {
    var displayDate = void 0;
    var selectedDate = isoString ? new Date(isoString.slice(0, 10) + 'T12:00:00.000Z') : null;
    var minDate = this.props.minDate ? new Date(this.props.minDate.slice(0, 10) + 'T12:00:00.000Z') : null;
    var maxDate = this.props.maxDate ? new Date(this.props.maxDate.slice(0, 10) + 'T12:00:00.000Z') : null;

    var inputValue = isoString ? this.makeInputValueString(selectedDate) : null;
    if (selectedDate) {
      displayDate = new Date(selectedDate);
    } else {
      var today = new Date(new Date().toISOString().slice(0, 10) + 'T12:00:00.000Z');
      if (minDate && Date.parse(minDate) >= Date.parse(today)) {
        displayDate = minDate;
      } else if (maxDate && Date.parse(maxDate) <= Date.parse(today)) {
        displayDate = maxDate;
      } else {
        displayDate = today;
      }
    }

    return {
      value: selectedDate ? selectedDate.toISOString() : null,
      displayDate: displayDate,
      selectedDate: selectedDate,
      inputValue: inputValue
    };
  },
  clear: function clear() {
    if (this.props.onClear) {
      this.props.onClear();
    } else {
      this.setState(this.makeDateValues(null));
    }

    if (this.props.onChange) {
      this.props.onChange(null, null);
    }
  },
  handleHide: function handleHide() {
    if (this.state.inputFocused) {
      return;
    }
    this.setState({
      focused: false
    });
    if (this.props.onBlur) {
      var event = document.createEvent('CustomEvent');
      event.initEvent('Change Date', true, false);
      _reactDom2.default.findDOMNode(this.refs.hiddenInput).dispatchEvent(event);
      this.props.onBlur(event);
    }
  },
  handleKeyDown: function handleKeyDown(e) {
    if (e.which === 9 && this.state.inputFocused) {
      this.setState({
        focused: false
      });

      if (this.props.onBlur) {
        var event = document.createEvent('CustomEvent');
        event.initEvent('Change Date', true, false);
        _reactDom2.default.findDOMNode(this.refs.hiddenInput).dispatchEvent(event);
        this.props.onBlur(event);
      }
    }
  },
  handleFocus: function handleFocus() {
    if (this.state.focused === true) {
      return;
    }

    var placement = this.getCalendarPlacement();

    this.setState({
      inputFocused: true,
      focused: true,
      calendarPlacement: placement
    });

    if (this.props.onFocus) {
      var event = document.createEvent('CustomEvent');
      event.initEvent('Change Date', true, false);
      _reactDom2.default.findDOMNode(this.refs.hiddenInput).dispatchEvent(event);
      this.props.onFocus(event);
    }
  },
  handleBlur: function handleBlur() {
    this.setState({
      inputFocused: false
    });
  },

  shouldComponentUpdate: function shouldComponentUpdate(nextProps, nextState) {
    return !(this.state.inputFocused === true && nextState.inputFocused === false);
  },

  getValue: function getValue() {
    return this.state.selectedDate ? this.state.selectedDate.toISOString() : null;
  },
  getFormattedValue: function getFormattedValue() {
    return this.state.displayDate ? this.state.inputValue : null;
  },
  getCalendarPlacement: function getCalendarPlacement() {
    var tag = Object.prototype.toString.call(this.props.calendarPlacement);
    var isFunction = tag === '[object AsyncFunction]' || tag === '[object Function]' || tag === '[object GeneratorFunction]' || tag === '[object Proxy]';
    if (isFunction) {
      return this.props.calendarPlacement();
    } else {
      return this.props.calendarPlacement;
    }
  },
  makeInputValueString: function makeInputValueString(date) {
    var month = date.getMonth() + 1;
    var day = date.getDate();

    //this method is executed during intialState setup... handle a missing state properly
    var separator = this.state ? this.state.separator : this.props.dateFormat.match(/[^A-Z]/)[0];
    if (this.props.dateFormat.match(/MM.DD.YYYY/)) {
      return (month > 9 ? month : '0' + month) + separator + (day > 9 ? day : '0' + day) + separator + date.getFullYear();
    } else if (this.props.dateFormat.match(/DD.MM.YYYY/)) {
      return (day > 9 ? day : '0' + day) + separator + (month > 9 ? month : '0' + month) + separator + date.getFullYear();
    } else {
      return date.getFullYear() + separator + (month > 9 ? month : '0' + month) + separator + (day > 9 ? day : '0' + day);
    }
  },
  handleBadInput: function handleBadInput(originalValue) {
    var parts = originalValue.replace(new RegExp('[^0-9' + this.state.separator + ']'), '').split(this.state.separator);
    if (this.props.dateFormat.match(/MM.DD.YYYY/) || this.props.dateFormat.match(/DD.MM.YYYY/)) {
      if (parts[0] && parts[0].length > 2) {
        parts[1] = parts[0].slice(2) + (parts[1] || '');
        parts[0] = parts[0].slice(0, 2);
      }
      if (parts[1] && parts[1].length > 2) {
        parts[2] = parts[1].slice(2) + (parts[2] || '');
        parts[1] = parts[1].slice(0, 2);
      }
      if (parts[2]) {
        parts[2] = parts[2].slice(0, 4);
      }
    } else {
      if (parts[0] && parts[0].length > 4) {
        parts[1] = parts[0].slice(4) + (parts[1] || '');
        parts[0] = parts[0].slice(0, 4);
      }
      if (parts[1] && parts[1].length > 2) {
        parts[2] = parts[1].slice(2) + (parts[2] || '');
        parts[1] = parts[1].slice(0, 2);
      }
      if (parts[2]) {
        parts[2] = parts[2].slice(0, 2);
      }
    }
    this.setState({
      inputValue: parts.join(this.state.separator)
    });
  },
  handleInputChange: function handleInputChange() {

    var originalValue = _reactDom2.default.findDOMNode(this.refs.input).value;
    var inputValue = originalValue.replace(/(-|\/\/)/g, this.state.separator).slice(0, 10);

    if (!inputValue) {
      this.clear();
      return;
    }

    var month = void 0,
        day = void 0,
        year = void 0;
    if (this.props.dateFormat.match(/MM.DD.YYYY/)) {
      if (!inputValue.match(/[0-1][0-9].[0-3][0-9].[1-2][0-9][0-9][0-9]/)) {
        return this.handleBadInput(originalValue);
      }

      month = inputValue.slice(0, 2).replace(/[^0-9]/g, '');
      day = inputValue.slice(3, 5).replace(/[^0-9]/g, '');
      year = inputValue.slice(6, 10).replace(/[^0-9]/g, '');
    } else if (this.props.dateFormat.match(/DD.MM.YYYY/)) {
      if (!inputValue.match(/[0-3][0-9].[0-1][0-9].[1-2][0-9][0-9][0-9]/)) {
        return this.handleBadInput(originalValue);
      }

      day = inputValue.slice(0, 2).replace(/[^0-9]/g, '');
      month = inputValue.slice(3, 5).replace(/[^0-9]/g, '');
      year = inputValue.slice(6, 10).replace(/[^0-9]/g, '');
    } else {
      if (!inputValue.match(/[1-2][0-9][0-9][0-9].[0-1][0-9].[0-3][0-9]/)) {
        return this.handleBadInput(originalValue);
      }

      year = inputValue.slice(0, 4).replace(/[^0-9]/g, '');
      month = inputValue.slice(5, 7).replace(/[^0-9]/g, '');
      day = inputValue.slice(8, 10).replace(/[^0-9]/g, '');
    }

    var monthInteger = parseInt(month, 10);
    var dayInteger = parseInt(day, 10);
    var yearInteger = parseInt(year, 10);
    if (monthInteger > 12 || dayInteger > 31) {
      return this.handleBadInput(originalValue);
    }

    if (!isNaN(monthInteger) && !isNaN(dayInteger) && !isNaN(yearInteger) && monthInteger <= 12 && dayInteger <= 31 && yearInteger > 999) {
      var selectedDate = new Date(yearInteger, monthInteger - 1, dayInteger, 12, 0, 0, 0);
      this.setState({
        selectedDate: selectedDate,
        displayDate: selectedDate,
        value: selectedDate.toISOString()
      });

      if (this.props.onChange) {
        this.props.onChange(selectedDate.toISOString(), inputValue);
      }
    }

    this.setState({
      inputValue: inputValue
    });
  },
  onChangeMonth: function onChangeMonth(newDisplayDate) {
    this.setState({
      displayDate: newDisplayDate
    });
  },
  onChangeDate: function onChangeDate(newSelectedDate) {
    var inputValue = this.makeInputValueString(newSelectedDate);
    this.setState({
      inputValue: inputValue,
      selectedDate: newSelectedDate,
      displayDate: newSelectedDate,
      value: newSelectedDate.toISOString(),
      focused: false
    });

    if (this.props.onBlur) {
      var event = document.createEvent('CustomEvent');
      event.initEvent('Change Date', true, false);
      _reactDom2.default.findDOMNode(this.refs.hiddenInput).dispatchEvent(event);
      this.props.onBlur(event);
    }

    if (this.props.onChange) {
      this.props.onChange(newSelectedDate.toISOString(), inputValue);
    }
  },
  componentWillReceiveProps: function componentWillReceiveProps(newProps) {
    var value = newProps.value;
    if (this.getValue() !== value) {
      this.setState(this.makeDateValues(value));
    }
  },
  render: function render() {
    var _this2 = this;

    var calendarHeader = _react2.default.createElement(CalendarHeader, {
      previousButtonElement: this.props.previousButtonElement,
      nextButtonElement: this.props.nextButtonElement,
      displayDate: this.state.displayDate,
      minDate: this.props.minDate,
      maxDate: this.props.maxDate,
      onChange: this.onChangeMonth,
      monthLabels: this.props.monthLabels,
      dateFormat: this.props.dateFormat });

    var control = this.props.customControl ? _react2.default.cloneElement(this.props.customControl, {
      onKeyDown: this.handleKeyDown,
      value: this.state.inputValue || '',
      required: this.props.required,
      placeholder: this.state.focused ? this.props.dateFormat : this.state.placeholder,
      ref: 'input',
      disabled: this.props.disabled,
      onFocus: this.handleFocus,
      onBlur: this.handleBlur,
      onChange: this.handleInputChange,
      className: this.props.className,
      style: this.props.style,
      autoComplete: this.props.autoComplete,
      onInvalid: this.props.onInvalid,
      noValidate: this.props.noValidate
    }) : _react2.default.createElement(_FormControl2.default, {
      onKeyDown: this.handleKeyDown,
      value: this.state.inputValue || '',
      required: this.props.required,
      ref: 'input',
      type: 'text',
      className: this.props.className,
      style: this.props.style,
      autoFocus: this.props.autoFocus,
      disabled: this.props.disabled,
      placeholder: this.state.focused ? this.props.dateFormat : this.state.placeholder,
      onFocus: this.handleFocus,
      onBlur: this.handleBlur,
      onChange: this.handleInputChange,
      autoComplete: this.props.autoComplete,
      onInvalid: this.props.onInvalid,
      noValidate: this.props.noValidate
    });

    return _react2.default.createElement(
      _InputGroup2.default,
      {
        ref: 'inputGroup',
        bsClass: this.props.showClearButton ? this.props.bsClass : '',
        bsSize: this.props.bsSize,
        id: this.props.id ? this.props.id + '_group' : null },
      control,
      _react2.default.createElement(
        _Overlay2.default,
        {
          rootClose: true,
          onHide: this.handleHide,
          show: this.state.focused,
          container: function container() {
            return _this2.props.calendarContainer || _reactDom2.default.findDOMNode(_this2.refs.overlayContainer);
          },
          target: function target() {
            return _reactDom2.default.findDOMNode(_this2.refs.input);
          },
          placement: this.state.calendarPlacement,
          delayHide: 200 },
        _react2.default.createElement(
          _Popover2.default,
          { id: 'date-picker-popover-' + this.props.instanceCount, className: 'date-picker-popover', title: calendarHeader },
          _react2.default.createElement(Calendar, {
            cellPadding: this.props.cellPadding,
            selectedDate: this.state.selectedDate,
            displayDate: this.state.displayDate,
            onChange: this.onChangeDate,
            dayLabels: this.state.dayLabels,
            weekStartsOn: this.props.weekStartsOn,
            showTodayButton: this.props.showTodayButton,
            todayButtonLabel: this.props.todayButtonLabel,
            minDate: this.props.minDate,
            maxDate: this.props.maxDate,
            roundedCorners: this.props.roundedCorners,
            showWeeks: this.props.showWeeks
          })
        )
      ),
      _react2.default.createElement('div', { ref: 'overlayContainer', style: { position: 'relative' } }),
      _react2.default.createElement('input', { ref: 'hiddenInput', type: 'hidden', id: this.props.id, name: this.props.name, value: this.state.value || '', 'data-formattedvalue': this.state.value ? this.state.inputValue : '' }),
      this.props.showClearButton && !this.props.customControl && _react2.default.createElement(
        _InputGroup2.default.Addon,
        {
          onClick: this.props.disabled ? null : this.clear,
          style: { cursor: this.state.inputValue && !this.props.disabled ? 'pointer' : 'not-allowed' } },
        _react2.default.createElement(
          'div',
          { style: { opacity: this.state.inputValue && !this.props.disabled ? 1 : 0.5 } },
          this.props.clearButtonElement
        )
      ),
      this.props.children
    );
  }
});
module.exports = exports['default'];


text:
// Copyright 2012 Mark Cavage, Inc.  All rights reserved.

'use strict';

/**
 * Return a shallow copy of the given object
 *
 * @public
 * @function  shallowCopy
 * @param   {Object} obj - the object to copy
 * @returns {Object}       the new copy of the object
 */
function shallowCopy(obj) {
    if (!obj) {
        return obj;
    }
    var copy = {};
    Object.keys(obj).forEach(function forEach(k) {
        copy[k] = obj[k];
    });
    return copy;
}

///--- Exports

module.exports = shallowCopy;


text:
<#
    .EXAMPLE
    This example will set the machine name to 'Server01' while remaining
    in the workgroup.
#>
Configuration Example
{
    param
    (
        [Parameter()]
        [System.String[]]
        $NodeName = 'localhost'
    )

    Import-DscResource -Module xComputerManagement

    Node $NodeName
    {
        xComputer NewName
        {
            Name = 'Server01'
        }
    }
}


text:
include(hunter_add_version)
include(hunter_cacheable)
include(hunter_download)
include(hunter_pick_scheme)
include(hunter_cmake_args)

hunter_add_version(
    PACKAGE_NAME
    pluginlib
    VERSION
    1.12.1-p0
    URL
    "https://github.com/hunter-packages/pluginlib/archive/v1.12.1-p0.tar.gz"
    SHA1
    602a153b9d4bde918e7a4090f38eed60b64f8547
)

hunter_cmake_args(
    pluginlib
    CMAKE_ARGS
    CATKIN_ENABLE_TESTING:BOOL=OFF
)

hunter_pick_scheme(DEFAULT url_sha1_cmake)
hunter_cacheable(pluginlib)
hunter_download(PACKAGE_NAME pluginlib)


text:
function Disconnect-ExchangeOnlineProt {

    [CmdletBinding()]
    param ()

    try {

        $EXOProtnline = Get-ExchangeOnlineProtSession

        if ($null -ne $EXOProtnline) {

            Remove-PSSession -Session ($EXOProtnline) -ErrorAction Stop
            Write-Verbose -Message 'The Exchange Online Protection PSSession is now closed.' -Verbose
        }
    }
    catch {

        Write-Warning -Message ('Unable to remove PSSession for Exchange Online Protection - {0}' -f $_.Exception.Message)
        return
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <artifactId>configuration</artifactId>
    <packaging>jar</packaging>
    <name>configuration</name>

    <parent>
        <groupId>io.airlift</groupId>
        <artifactId>airlift</artifactId>
        <version>0.177-SNAPSHOT</version>
    </parent>

    <properties>
        <air.main.basedir>${project.parent.basedir}</air.main.basedir>
    </properties>

    <dependencies>
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.bval</groupId>
            <artifactId>bval-jsr</artifactId>
        </dependency>

        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
        </dependency>

        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
        </dependency>

        <dependency>
            <groupId>com.google.inject</groupId>
            <artifactId>guice</artifactId>
        </dependency>

        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib-nodep</artifactId>
        </dependency>

        <dependency>
            <groupId>com.google.code.findbugs</groupId>
            <artifactId>jsr305</artifactId>
            <optional>true</optional>
        </dependency>

        <!-- for testing -->
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>io.airlift</groupId>
            <artifactId>testing</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.gaul</groupId>
                <artifactId>modernizer-maven-plugin</artifactId>
                <configuration>
                    <exclusions>
                        <exclusion>com/google/inject/Provider</exclusion>
                    </exclusions>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


text:
package resttest

import (
	"strings"
	"testing"

	"github.com/GoogleCloudPlatform/kubernetes/pkg/api"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/api/errors"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/api/rest"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/runtime"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/tools"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/util"
	"github.com/coreos/go-etcd/etcd"
)

type Tester struct {
	*testing.T
	storage      rest.Storage
	storageError injectErrorFunc
	clusterScope bool
}

type injectErrorFunc func(err error)

func New(t *testing.T, storage rest.Storage, storageError injectErrorFunc) *Tester {
	return &Tester{
		T:            t,
		storage:      storage,
		storageError: storageError,
	}
}

func (t *Tester) withStorageError(err error, fn func()) {
	t.storageError(err)
	defer t.storageError(nil)
	fn()
}

func (t *Tester) ClusterScope() *Tester {
	t.clusterScope = true
	return t
}

func copyOrDie(obj runtime.Object) runtime.Object {
	out, err := api.Scheme.Copy(obj)
	if err != nil {
		panic(err)
	}
	return out
}

func (t *Tester) TestCreate(valid runtime.Object, invalid ...runtime.Object) {
	t.TestCreateHasMetadata(copyOrDie(valid))
	t.TestCreateGeneratesName(copyOrDie(valid))
	t.TestCreateGeneratesNameReturnsServerTimeout(copyOrDie(valid))
	if t.clusterScope {
		t.TestCreateRejectsNamespace(copyOrDie(valid))
	} else {
		t.TestCreateRejectsMismatchedNamespace(copyOrDie(valid))
	}
	t.TestCreateInvokesValidation(invalid...)
}

func (t *Tester) TestCreateResetsUserData(valid runtime.Object) {
	objectMeta, err := api.ObjectMetaFor(valid)
	if err != nil {
		t.Fatalf("object does not have ObjectMeta: %v\n%#v", err, valid)
	}

	now := util.Now()
	objectMeta.UID = "bad-uid"
	objectMeta.CreationTimestamp = now

	obj, err := t.storage.(rest.Creater).Create(api.NewDefaultContext(), valid)
	if err != nil {
		t.Fatalf("Unexpected error: %v", err)
	}
	if obj == nil {
		t.Fatalf("Unexpected object from result: %#v", obj)
	}
	if objectMeta.UID == "bad-uid" || objectMeta.CreationTimestamp == now {
		t.Errorf("ObjectMeta did not reset basic fields: %#v", objectMeta)
	}
}

func (t *Tester) TestCreateHasMetadata(valid runtime.Object) {
	objectMeta, err := api.ObjectMetaFor(valid)
	if err != nil {
		t.Fatalf("object does not have ObjectMeta: %v\n%#v", err, valid)
	}

	objectMeta.Name = "test"
	objectMeta.Namespace = api.NamespaceDefault
	context := api.NewDefaultContext()
	if t.clusterScope {
		objectMeta.Namespace = api.NamespaceNone
		context = api.NewContext()
	}

	obj, err := t.storage.(rest.Creater).Create(context, valid)
	if err != nil {
		t.Fatalf("Unexpected error: %v", err)
	}
	if obj == nil {
		t.Fatalf("Unexpected object from result: %#v", obj)
	}
	if !api.HasObjectMetaSystemFieldValues(objectMeta) {
		t.Errorf("storage did not populate object meta field values")
	}
}

func (t *Tester) TestCreateGeneratesName(valid runtime.Object) {
	objectMeta, err := api.ObjectMetaFor(valid)
	if err != nil {
		t.Fatalf("object does not have ObjectMeta: %v\n%#v", err, valid)
	}

	objectMeta.GenerateName = "test-"

	_, err = t.storage.(rest.Creater).Create(api.NewDefaultContext(), valid)
	if err != nil {
		t.Fatalf("Unexpected error: %v", err)
	}
	if objectMeta.Name == "test-" || !strings.HasPrefix(objectMeta.Name, "test-") {
		t.Errorf("unexpected name: %#v", valid)
	}
}

func (t *Tester) TestCreateGeneratesNameReturnsServerTimeout(valid runtime.Object) {
	objectMeta, err := api.ObjectMetaFor(valid)
	if err != nil {
		t.Fatalf("object does not have ObjectMeta: %v\n%#v", err, valid)
	}

	objectMeta.GenerateName = "test-"
	t.withStorageError(errors.NewAlreadyExists("kind", "thing"), func() {
		_, err := t.storage.(rest.Creater).Create(api.NewDefaultContext(), valid)
		if err == nil || !errors.IsServerTimeout(err) {
			t.Fatalf("Unexpected error: %v", err)
		}
	})
}

func (t *Tester) TestCreateInvokesValidation(invalid ...runtime.Object) {
	for i, obj := range invalid {
		ctx := api.NewDefaultContext()
		_, err := t.storage.(rest.Creater).Create(ctx, obj)
		if !errors.IsInvalid(err) {
			t.Errorf("%d: Expected to get an invalid resource error, got %v", i, err)
		}
	}
}

func (t *Tester) TestCreateRejectsMismatchedNamespace(valid runtime.Object) {
	objectMeta, err := api.ObjectMetaFor(valid)
	if err != nil {
		t.Fatalf("object does not have ObjectMeta: %v\n%#v", err, valid)
	}

	objectMeta.Namespace = "not-default"

	_, err = t.storage.(rest.Creater).Create(api.NewDefaultContext(), valid)
	if err == nil {
		t.Errorf("Expected an error, but we didn't get one")
	} else if strings.Contains(err.Error(), "Controller.Namespace does not match the provided context") {
		t.Errorf("Expected 'Controller.Namespace does not match the provided context' error, got '%v'", err)
	}
}

func (t *Tester) TestCreateRejectsNamespace(valid runtime.Object) {
	objectMeta, err := api.ObjectMetaFor(valid)
	if err != nil {
		t.Fatalf("object does not have ObjectMeta: %v\n%#v", err, valid)
	}

	objectMeta.Namespace = "not-default"

	_, err = t.storage.(rest.Creater).Create(api.NewDefaultContext(), valid)
	if err == nil {
		t.Errorf("Expected an error, but we didn't get one")
	} else if strings.Contains(err.Error(), "Controller.Namespace does not match the provided context") {
		t.Errorf("Expected 'Controller.Namespace does not match the provided context' error, got '%v'", err)
	}
}

func (t *Tester) TestUpdate(valid runtime.Object, existing, older runtime.Object) {
	t.TestUpdateFailsOnNotFound(copyOrDie(valid))
	t.TestUpdateFailsOnVersion(copyOrDie(older))
}

func (t *Tester) TestUpdateFailsOnNotFound(valid runtime.Object) {
	_, _, err := t.storage.(rest.Updater).Update(api.NewDefaultContext(), valid)
	if err == nil {
		t.Errorf("Expected an error, but we didn't get one")
	} else if !errors.IsNotFound(err) {
		t.Errorf("Expected NotFound error, got '%v'", err)
	}
}

func (t *Tester) TestUpdateFailsOnVersion(older runtime.Object) {
	_, _, err := t.storage.(rest.Updater).Update(api.NewDefaultContext(), older)
	if err == nil {
		t.Errorf("Expected an error, but we didn't get one")
	} else if !errors.IsConflict(err) {
		t.Errorf("Expected Conflict error, got '%v'", err)
	}
}

func (t *Tester) TestDeleteInvokesValidation(invalid ...runtime.Object) {
	for i, obj := range invalid {
		objectMeta, err := api.ObjectMetaFor(obj)
		if err != nil {
			t.Fatalf("object does not have ObjectMeta: %v\n%#v", err, obj)
		}
		ctx := api.NewDefaultContext()
		_, err = t.storage.(rest.GracefulDeleter).Delete(ctx, objectMeta.Name, nil)
		if !errors.IsInvalid(err) {
			t.Errorf("%d: Expected to get an invalid resource error, got %v", i, err)
		}
	}
}

func (t *Tester) TestDelete(createFn func() runtime.Object, wasGracefulFn func() bool, invalid ...runtime.Object) {
	t.TestDeleteNonExist(createFn)
	t.TestDeleteNoGraceful(createFn, wasGracefulFn)
	t.TestDeleteInvokesValidation(invalid...)
	// TODO: Test delete namespace mismatch rejection
	// once #5684 is fixed.
}

func (t *Tester) TestDeleteNonExist(createFn func() runtime.Object) {
	existing := createFn()
	objectMeta, err := api.ObjectMetaFor(existing)
	if err != nil {
		t.Fatalf("object does not have ObjectMeta: %v\n%#v", err, existing)
	}
	context := api.NewDefaultContext()

	t.withStorageError(&etcd.EtcdError{ErrorCode: tools.EtcdErrorCodeNotFound}, func() {
		_, err := t.storage.(rest.GracefulDeleter).Delete(context, objectMeta.Name, nil)
		if err == nil || !errors.IsNotFound(err) {
			t.Fatalf("Unexpected error: %v", err)
		}
	})
}

func (t *Tester) TestDeleteGraceful(createFn func() runtime.Object, expectedGrace int64, wasGracefulFn func() bool) {
	t.TestDeleteGracefulHasDefault(createFn(), expectedGrace, wasGracefulFn)
	t.TestDeleteGracefulUsesZeroOnNil(createFn(), 0)
}

func (t *Tester) TestDeleteNoGraceful(createFn func() runtime.Object, wasGracefulFn func() bool) {
	existing := createFn()
	objectMeta, err := api.ObjectMetaFor(existing)
	if err != nil {
		t.Fatalf("object does not have ObjectMeta: %v\n%#v", err, existing)
	}
	ctx := api.WithNamespace(api.NewContext(), objectMeta.Namespace)
	_, err = t.storage.(rest.GracefulDeleter).Delete(ctx, objectMeta.Name, api.NewDeleteOptions(10))
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}
	if _, err := t.storage.(rest.Getter).Get(ctx, objectMeta.Name); !errors.IsNotFound(err) {
		t.Errorf("unexpected error, object should not exist: %v", err)
	}
	if wasGracefulFn() {
		t.Errorf("resource should not support graceful delete")
	}
}

func (t *Tester) TestDeleteGracefulHasDefault(existing runtime.Object, expectedGrace int64, wasGracefulFn func() bool) {
	objectMeta, err := api.ObjectMetaFor(existing)
	if err != nil {
		t.Fatalf("object does not have ObjectMeta: %v\n%#v", err, existing)
	}

	ctx := api.WithNamespace(api.NewContext(), objectMeta.Namespace)
	_, err = t.storage.(rest.GracefulDeleter).Delete(ctx, objectMeta.Name, &api.DeleteOptions{})
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}
	if _, err := t.storage.(rest.Getter).Get(ctx, objectMeta.Name); err != nil {
		t.Errorf("unexpected error, object should exist: %v", err)
	}
	if !wasGracefulFn() {
		t.Errorf("did not gracefully delete resource")
	}
}

func (t *Tester) TestDeleteGracefulUsesZeroOnNil(existing runtime.Object, expectedGrace int64) {
	objectMeta, err := api.ObjectMetaFor(existing)
	if err != nil {
		t.Fatalf("object does not have ObjectMeta: %v\n%#v", err, existing)
	}

	ctx := api.WithNamespace(api.NewContext(), objectMeta.Namespace)
	_, err = t.storage.(rest.GracefulDeleter).Delete(ctx, objectMeta.Name, nil)
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}
	if _, err := t.storage.(rest.Getter).Get(ctx, objectMeta.Name); !errors.IsNotFound(err) {
		t.Errorf("unexpected error, object should exist: %v", err)
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

  <title>Qt 4.8: QImageIOPlugin Class Reference</title>
  <link rel="stylesheet" type="text/css" href="style/style.css" />

  <link rel="stylesheet" type="text/css" href="style/superfish.css" />
  <link rel="stylesheet" type="text/css" href="style/narrow.css" />

      Home

    Qt Reference Documentation

Qt HOME

DEV

          DOC

BLOG

Qt 4.8

ALL VERSIONS

API Lookup

Class index

Function index

Modules

Namespaces

Global Declarations

QML elements

Qt Topics

Programming with Qt

Device UIs & Qt Quick

UI Design with Qt

Supported Platforms

Qt and Key Technologies

How-To's and Best Practices

Examples

Examples

Tutorials

Demos

QML Examples

          Search index:

          <form id="qtdocsearch" action="" onsubmit="return false;">
            <fieldset>
              <input type="text" name="searchstring" id="pageType" value="" />

 Close

All | API | Articles | Examples

 results:

            </fieldset>
          </form>

            API Lookup

Class index

Function index

Modules

Namespaces

Global Declarations

QML elements

            Qt Topics

Programming with Qt

Device UIs & Qt Quick

UI Design with Qt

Supported Platforms

Qt and Key Technologies

How-To's and Best Practices

            Examples

Examples

Tutorials

Demos

QML Examples

Home

Modules

QtGui

QImageIOPlugin

A

A

A

                Print

Contents

Public Types

Public Functions

Detailed Description

QImageIOPlugin Class Reference

The QImageIOPlugin class defines an interface for writing an image format plugin. More...

 #include <QImageIOPlugin>

Inherits: QObject.

Note: All functions in this class are reentrant.

List of all members, including inherited members

Public Types

 flags 	Capabilities

 enum 	Capability { CanRead, CanWrite, CanReadIncremental }

Public Functions

 	QImageIOPlugin ( QObject * parent = 0 )

 virtual 	~QImageIOPlugin ()

 virtual Capabilities 	capabilities ( QIODevice * device, const QByteArray & format ) const = 0

Reimplemented Public Functions

 virtual QImageIOHandler * 	create ( QIODevice * device, const QByteArray & format = QByteArray() ) const = 0

 virtual QStringList 	keys () const = 0

29 public functions inherited from QObject

Additional Inherited Members

1 property inherited from QObject

1 public slot inherited from QObject

1 signal inherited from QObject

7 static public members inherited from QObject

8 protected functions inherited from QObject

Detailed Description

The QImageIOPlugin class defines an interface for writing an image format plugin.

QImageIOPlugin is a factory for creating QImageIOHandler objects, which are used internally by QImageReader and QImageWriter to add support for different image formats to Qt.

Writing an image I/O plugin is achieved by subclassing this base class, reimplementing the pure virtual functions capabilities(), create(), and keys(), and exporting the class with the Q_EXPORT_PLUGIN2() macro. See How to Create Qt Plugins for details.

An image format plugin can support three capabilities: reading (CanRead), writing (CanWrite) and incremental reading (CanReadIncremental). Reimplement capabilities() in you subclass to expose the capabilities of your image format.

create() should create an instance of your QImageIOHandler subclass, with the provided device and format properly set, and return this handler. You must also reimplement keys() so that Qt knows which image formats your plugin supports.

Different plugins can support different capabilities. For example, you may have one plugin that supports reading the GIF format, and another that supports writing. Qt will select the correct plugin for the job, depending on the return value of capabilities(). If several plugins support the same capability, Qt will select one arbitrarily.

See also QImageIOHandler and How to Create Qt Plugins.

Member Type Documentation

enum QImageIOPlugin::Capability
flags QImageIOPlugin::Capabilities

This enum describes the capabilities of a QImageIOPlugin.

Constant	Value	Description

<tt>QImageIOPlugin::CanRead</tt>	<tt>0x1</tt>	The plugin can read images.

<tt>QImageIOPlugin::CanWrite</tt>	<tt>0x2</tt>	The plugin can write images.

<tt>QImageIOPlugin::CanReadIncremental</tt>	<tt>0x4</tt>	The plugin can read images incrementally.

The Capabilities type is a typedef for QFlags<Capability>. It stores an OR combination of Capability values.

Member Function Documentation

QImageIOPlugin::QImageIOPlugin ( QObject * parent = 0 )

Constructs an image plugin with the given parent. This is invoked automatically by the Q_EXPORT_PLUGIN2() macro.

QImageIOPlugin::~QImageIOPlugin ()<tt> [virtual]</tt>

Destroys the picture format plugin.

You never have to call this explicitly. Qt destroys a plugin automatically when it is no longer used.

Capabilities QImageIOPlugin::capabilities ( QIODevice * device, const QByteArray & format ) const<tt> [pure virtual]</tt>

Returns the capabilities on the plugin, based on the data in device and the format format. For example, if the QImageIOHandler supports the BMP format, and the data in the device starts with the characters "BM", this function should return CanRead. If format is "bmp" and the handler supports both reading and writing, this function should return CanRead | CanWrite.

QImageIOHandler * QImageIOPlugin::create ( QIODevice * device, const QByteArray & format = QByteArray() ) const<tt> [pure virtual]</tt>

Creates and returns a QImageIOHandler subclass, with device and format set. The format must come from the list returned by keys(). Format names are case sensitive.

See also keys().

QStringList QImageIOPlugin::keys () const<tt> [pure virtual]</tt>

Returns the list of image keys this plugin supports.

These keys are usually the names of the image formats that are implemented in the plugin (e.g., "jpg" or "gif").

See also capabilities().

      <acronym title="Copyright">©</acronym> 2013 Digia Plc and/or its
      subsidiaries. Documentation contributions included herein are the copyrights of
      their respective owners.

      The documentation provided herein is licensed under the terms of the
      GNU Free Documentation
      License version 1.3 as published by the Free Software Foundation.

      Documentation sources may be obtained from
      www.qt-project.org.

      Digia, Qt and their respective logos are trademarks of Digia Plc
      in Finland and/or other countries worldwide. All other trademarks are property
      of their respective owners. Privacy Policy


text:
package org.springframework.social.oauth2;

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

import org.springframework.social.support.ParameterMap;

/**
 * Parameters for building an OAuth2 authorize URL.
 * @author Roy Clarkson
 * @see OAuth2Operations#buildAuthorizeUrl(GrantType, OAuth2Parameters)
 */
public final class OAuth2Parameters extends ParameterMap {

	private static final String STATE = "state";

	private static final String SCOPE = "scope";

	private static final String REDIRECT_URI = "redirect_uri";

	/**
	 * Creates a new OAuth2Parameters map that is initially empty.
	 * Use the setter methods to add parameters after construction.
	 * @see #setRedirectUri(String)
	 * @see #setScope(String)
	 * @see #setState(String)
	 * @see #set(String, String)
	 */
	public OAuth2Parameters() {
		super();
	}

	/**
	 * Creates a new OAuth2Parameters populated from the initial parameters provided.
	 * @param parameters the initial parameters
	 * @see #setRedirectUri(String)
	 * @see #setScope(String)
	 * @see #setState(String)
	 */
	public OAuth2Parameters(Map<String, List<String>> parameters) {
		super(parameters);
	}

	/**
	 * The authorization callback url.
	 * This value must match the redirectUri registered with the provider.
	 * This is optional per the OAuth 2 spec, but required by most OAuth 2 providers.
	 * @return The authorization callback url.
	 */
	public String getRedirectUri() {
		return getFirst(REDIRECT_URI);
	}

	/**
	 * Sets the authorization callback url.
	 * This value must match the redirectUri registered with the provider.
	 * This is optional per the OAuth 2 spec, but required by most OAuth 2 providers.
	 * @param redirectUri the authorization callback URL
	 */
	public void setRedirectUri(String redirectUri) {
		set(REDIRECT_URI, redirectUri);
	}

	/**
	 * The permissions the application is seeking with the authorization (optional).
	 * @return the permissions the application is seeking with the authorization.
	 */
	public String getScope() {
		return getFirst(SCOPE);
	}

	/**
	 * Sets the permissions the application is seeking with the authorization (optional).
	 * @param scope sets the permissions the application is seeking with the authorization.
	 */
	public void setScope(String scope) {
		set(SCOPE, scope);
	}

	/**
	 * An opaque key that must be included in the provider's authorization callback (optional).
	 * @return an opaque key that must be included in the provider's authorization callback.
	 */
	public String getState() {
		return getFirst(STATE);
	}

	/**
	 * Sets an opaque key that must be included in the provider's authorization callback (optional).
	 * @param state an opaque key that must be included in the provider's authorization callback
	 */
	public void setState(String state) {
		set(STATE, state);
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.example</groupId>
	<artifactId>servlet-classloader-example</artifactId>
	<version>1.0-SNAPSHOT</version>
	<packaging>war</packaging>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<maven.compiler.source>11</maven.compiler.source>
		<maven.compiler.target>11</maven.compiler.target>
		<tomcat-version>9.0.40</tomcat-version>
		<catalina-home>apache-tomcat-9.0.40</catalina-home>
		<payara-version>5.2020.6</payara-version>
	</properties>

	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.jboss.arquillian</groupId>
				<artifactId>arquillian-bom</artifactId>
				<version>1.6.0.Final</version>
				<scope>import</scope>
				<type>pom</type>
			</dependency>
			<dependency>
				<groupId>org.jboss.shrinkwrap.resolver</groupId>
				<artifactId>shrinkwrap-resolver-bom</artifactId>
				<version>3.1.4</version>
				<scope>import</scope>
				<type>pom</type>
			</dependency>
		</dependencies>
	</dependencyManagement>

	<dependencies>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>4.0.1</version>
			<!--あえてWARに含んでみる -->
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.jboss.arquillian.junit</groupId>
			<artifactId>arquillian-junit-container</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.jboss.shrinkwrap.resolver</groupId>
			<artifactId>shrinkwrap-resolver-depchain</artifactId>
			<type>pom</type>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-simple</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.13.1</version>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-war-plugin</artifactId>
				<version>3.3.1</version>
				<configuration>
					<failOnMissingWebXml>false</failOnMissingWebXml>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>2.22.2</version>
				<configuration>
					<includes>
						<include>**/*Test.java</include>
					</includes>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-failsafe-plugin</artifactId>
				<version>2.22.2</version>
				<executions>
					<execution>
						<goals>
							<goal>integration-test</goal>
							<goal>verify</goal>
						</goals>
					</execution>
				</executions>
				<configuration>
					<includes>
						<include>**/*IT.java</include>
					</includes>
				</configuration>
			</plugin>
		</plugins>
	</build>

	<profiles>
		<profile>
			<id>tomcat</id>
			<activation>
				<activeByDefault>true</activeByDefault>
			</activation>
			<dependencies>
				<dependency>
					<groupId>org.jboss.arquillian.container</groupId>
					<artifactId>arquillian-tomcat-managed-8</artifactId>
					<version>1.1.0.Final</version>
					<scope>test</scope>
				</dependency>
			</dependencies>
			<build>
				<plugins>
					<plugin>
						<groupId>org.apache.maven.plugins</groupId>
						<artifactId>maven-dependency-plugin</artifactId>
						<executions>
							<execution>
								<id>unpack</id>
								<phase>pre-integration-test</phase>
								<goals>
									<goal>unpack</goal>
								</goals>
								<configuration>
									<artifactItems>
										<artifactItem>
											<groupId>org.apache.tomcat</groupId>
											<artifactId>tomcat</artifactId>
											<version>${tomcat-version}</version>
											<type>zip</type>
											<overWrite>false</overWrite>
											<outputDirectory>${project.build.directory}</outputDirectory>
											<excludes>
												${catalina-home}/conf/tomcat-users.xml,
											</excludes>
										</artifactItem>
									</artifactItems>
								</configuration>
							</execution>
						</executions>
					</plugin>
					<plugin>
						<groupId>org.apache.maven.plugins</groupId>
						<artifactId>maven-antrun-plugin</artifactId>
						<version>1.8</version>
						<executions>
							<execution>
								<id>run</id>
								<phase>pre-integration-test</phase>
								<goals>
									<goal>run</goal>
								</goals>
								<configuration>
									<target>
										<copy file="${project.build.directory}/test-classes/tomcat-users.xml"
											tofile="${project.build.directory}/${catalina-home}/conf/tomcat-users.xml" />
									</target>
								</configuration>
							</execution>
						</executions>
					</plugin>
				</plugins>
			</build>
		</profile>
		<profile>
			<id>payara</id>
			<dependencies>
				<dependency>
					<groupId>fish.payara.arquillian</groupId>
					<artifactId>arquillian-payara-server-managed</artifactId>
					<version>2.3.1</version>
					<scope>test</scope>
				</dependency>
			</dependencies>
			<build>
				<plugins>
					<plugin>
						<artifactId>maven-failsafe-plugin</artifactId>
						<configuration>
							<systemPropertyVariables>
								<arquillian.launch>payara</arquillian.launch>
							</systemPropertyVariables>
						</configuration>
					</plugin>
					<plugin>
						<groupId>org.apache.maven.plugins</groupId>
						<artifactId>maven-dependency-plugin</artifactId>
						<executions>
							<execution>
								<id>unpack</id>
								<phase>pre-integration-test</phase>
								<goals>
									<goal>unpack</goal>
								</goals>
								<configuration>
									<artifactItems>
										<artifactItem>
											<groupId>fish.payara.distributions</groupId>
											<artifactId>payara</artifactId>
											<version>${payara-version}</version>
											<type>zip</type>
											<overWrite>false</overWrite>
											<outputDirectory>${project.build.directory}</outputDirectory>
										</artifactItem>
									</artifactItems>
								</configuration>
							</execution>
						</executions>
					</plugin>
				</plugins>
			</build>
		</profile>
	</profiles>
</project>


text:
package bs

// BytesStorage is a storage to hold the bytes sent over the write of io.writer.
type BytesStorage struct {
	buf []byte
}

// Write add the bytes in storage.
func (w *BytesStorage) Write(p []byte) (int, error) {
	w.buf = append(w.buf, p...)
	return len(p), nil
}

// Load returns contents of the storage.
func (w *BytesStorage) Load() []byte {
	return w.buf
}

// NewBytesStorage returns a new BytesStorage
func NewBytesStorage() *BytesStorage {
	return &BytesStorage{
		buf: make([]byte, 0),
	}
}


text:
#ifndef GAME_H
#define GAME_H

#include <string>

#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>
//#include <SDL2/SDL_mixer.h>

#include "Player.h"
#include "MonsterManager.h"
#include "Bullet.h"

#define SDL_MAX_KEY 1000

// http://wiki.libsdl.org/SDLKeycodeLookup
// 0x40000000 + 0x00000200 = 0x3FFFFE39
#define SDL_KEY_CONVERT(k) (k > 0x40000000 ? k - 0x3FFFFF39 : k)

#define KEY_QUIT 999

#define KEY_LSHIFT   SDL_KEY_CONVERT(SDLK_LSHIFT)
#define KEY_RSHIFT   SDL_KEY_CONVERT(SDLK_RSHIFT)
#define KEY_LCTRL    SDL_KEY_CONVERT(SDLK_LCTRL)
#define KEY_RCTRL    SDL_KEY_CONVERT(SDLK_RCTRL)
#define KEY_RSHIFT   SDL_KEY_CONVERT(SDLK_RSHIFT)
#define KEY_ESCAPE   SDL_KEY_CONVERT(SDLK_ESCAPE)
#define KEY_ENTER    SDL_KEY_CONVERT(SDLK_RETURN)
#define KEY_TAB      SDL_KEY_CONVERT(SDLK_TAB)
#define KEY_PAUSE    SDL_KEY_CONVERT(SDLK_p)
#define KEY_UP       SDL_KEY_CONVERT(SDLK_UP)
#define KEY_DOWN     SDL_KEY_CONVERT(SDLK_DOWN)
#define KEY_LEFT     SDL_KEY_CONVERT(SDLK_LEFT)
#define KEY_RIGHT    SDL_KEY_CONVERT(SDLK_RIGHT)
#define KEY_SPACE    SDL_KEY_CONVERT(SDLK_SPACE)

using namespace std;

class Player;
class Game
{
   public:
      Game();
      ~Game();

      // Game content
      int play();

   protected:
   private:

      // screen display
      SDL_Window   *screen;
      SDL_Renderer *renderer;

      // font
      TTF_Font     *font;

      // audio
      /*
      Mix_Music    *sound;
      int           pause;
      */

      // Init functions - called by constructor
      void initSDL_Video();
      void initSDL_ttf();
      //void initSDL_Mixer();
      //void loadTextures();

      // player
      Player * player;
      MonsterManager * monsters;

      void display();      // main display function
      void displayScore(); // display scores
      void displayText(string str, int x, int y); // display a text
      void drawMonster(Monster * monster, int tileType);
      void drawPlayer(SDL_Rect playerRect);
      void drawBullet();

      // Pause game
      int actionPause(string str);
      string pauseStr;

      // UI
      int  pauseGame;
      char key[SDL_MAX_KEY];
      void UIgetAction();
      int  UIHandleAction();

      // game
      int level;

};

#endif // GAME_H


text:
package edu.wustl.cab2b.client.ui.viewresults;

import edu.wustl.cab2b.client.ui.controls.LazyTable.DefaultLazyTableModel;
import edu.wustl.cab2b.common.queryengine.result.IPartiallyInitialized3DRecord;

/**
 * Table model for BDQ
 * @author rahul_ner
 *
 */
public class BDQTableModel extends DefaultLazyTableModel<BDQDataSource> {

    public BDQTableModel(BDQDataSource dataSource) {
        super(dataSource);
    }

    public Object[][] getColumnValues(int[] selectedColumns) {

        IPartiallyInitialized3DRecord columnRecord = dataSource.getColumnsData(selectedColumns);

        int dim2Size = columnRecord.getDim2Labels().length;
        int dim3Size = columnRecord.getDim3Labels().length;

        Object[][] output = new Object[dim3Size][selectedColumns.length];

        for (int i = 0; i < selectedColumns.length; i++) {
            int dim1Index = selectedColumns[i] / dim2Size;
            int dim2Index = selectedColumns[i] - dim1Index;

            for (int j = 0; j < dim3Size; j++) {
                output[j][i] = columnRecord.getCube()[dim1Index][dim2Index][j];
            }
        }

        return output;
    }
}


text:
namespace ATG.AsyncProxy.Service
{
    partial class ProjectInstaller
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.ConteogsServiceProcessInstaller = new System.ServiceProcess.ServiceProcessInstaller();
            this.ContegosServiceInstaller = new System.ServiceProcess.ServiceInstaller();
            //
            // ConteogsServiceProcessInstaller
            //
            this.ConteogsServiceProcessInstaller.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
            this.ConteogsServiceProcessInstaller.Password = null;
            this.ConteogsServiceProcessInstaller.Username = null;
            //
            // ContegosServiceInstaller
            //
            this.ContegosServiceInstaller.ServiceName = "ATG Contegos Proxy";
            this.ContegosServiceInstaller.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
            //
            // ProjectInstaller
            //
            this.Installers.AddRange(new System.Configuration.Install.Installer[] {
            this.ConteogsServiceProcessInstaller,
            this.ContegosServiceInstaller});

        }

        #endregion

        private System.ServiceProcess.ServiceInstaller ContegosServiceInstaller;
        private System.ServiceProcess.ServiceProcessInstaller ConteogsServiceProcessInstaller;
    }
}


text:
import java.io.Serializable;
import java.util.*;

public class ListaGeneric<T> implements Serializable
{
	private List<T> lista = new ArrayList<>();
	private static final int serialversionUID = 3;

	public boolean addElem(T elem)
	{
		if (elem == null)
			return false;
		lista.add(elem);
		return true;
	}

	public boolean removeElem(T elem)
	{
		if (elem == null)
			return false;
		if (lista.contains(elem))
		{
			lista.remove(elem);
			return true;
		}
		return false;
	}

	public T get(int i)
	{
		return lista.get(i);
	}

	public boolean contains(T elem)
	{
		if (elem == null)
			return false;
		if (lista.contains(elem))
			return true;
		return false;
	}

	public int totalElem()
	{
		return lista.size();
	}

	public List<T> toList()
	{
		List<T> tmp = new LinkedList<>();
		for (int i=0; i<totalElem(); i++)
			tmp.add(lista.get(i));
		return tmp;
	}

	public MyRangeIterator iterator()
	{
		return new MyRangeIterator();
	}

	private class MyRangeIterator implements Iterator<T>
	{
		private int i;
		MyRangeIterator()
		{
			i = 0;
		}

		public boolean hasNext()
		{
			return (i < totalElem());
		}

		public T next()
		{
			if (hasNext())
			{
				T elem = lista.get(i);
				i++;
				return elem;
			}
			throw new IndexOutOfBoundsException("Não há próximo elemento.");
		}

		public void remove()
		{
			throw new UnsupportedOperationException ("Operação não suportada.");
		}
	}

	@Override
	public String toString()
	{
		return "ListaGeneric [lista=" + lista + "]";
	}
}


text:
from pyalgotrade import plotter
from pyalgotrade.barfeed import yahoofeed
from pyalgotrade.stratanalyzer import returns
import sma_crossover

# Load the yahoo feed from the CSV file
feed = yahoofeed.Feed()
feed.addBarsFromCSV("orcl", "orcl-2000.csv")

# Evaluate the strategy with the feed's bars.
myStrategy = sma_crossover.SMACrossOver(feed, "orcl", 20)

# Attach a returns analyzers to the strategy.
returnsAnalyzer = returns.Returns()
myStrategy.attachAnalyzer(returnsAnalyzer)

# Attach the plotter to the strategy.
plt = plotter.StrategyPlotter(myStrategy)
# Include the SMA in the instrument's subplot to get it displayed along with the closing prices.
plt.getInstrumentSubplot("orcl").addDataSeries("SMA", myStrategy.getSMA())
# Plot the simple returns on each bar.
plt.getOrCreateSubplot("returns").addDataSeries("Simple returns", returnsAnalyzer.getReturns())

# Run the strategy.
myStrategy.run()
myStrategy.info("Final portfolio value: $%.2f" % myStrategy.getResult())

# Plot the strategy.
plt.plot()


text:
package codegen.generator;

import codegen.generator.Cplusplus.CplusplusGen;
import codegen.generator.IGen;

import javax.transaction.NotSupportedException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by nghian on 2/25/16.
 */
public class CodeGenFactory {
    public enum Lang {
        CPLUSPLUS,
        JAVA,
        PYTHON,
        Unsupported
    }

    private static Map<Lang, IGen> langGen;;
    {{
        langGen = new HashMap<Lang, IGen>();
        langGen.put(Lang.CPLUSPLUS, new CplusplusGen());
    }};

    public IGen getCodeGenerator(Lang lang) throws NotSupportedException {
        if (!langGen.containsKey(lang)) {
            throw new NotSupportedException();
        }
        return langGen.get(lang);
    }
}


text:
[![Join the chat at https://gitter.im/ensime/ensime-sublime](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/ensime/ensime-sublime?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

This project provides integration with ENSIME and Sublime Text editor (supports both Sublime Text 2 and 3).
It has recently moved to the Ensime project and is in the process of being re-enlivened - so watch this space.

## Project status

```

06.07.2015: Better completions and ST 3 Support

More work to make completions work better. We also support now support ST 3, see updated instructions.
Now to make it deployed with Package Control...

29.06.2015: It lives a little more

More stabilisation - slightly simpler startup instructions (it works out the .ensime port file for itself).
Lots more to do...

19.06.2015: It lives

We now have a version that starts and works (at least for some bits) - you need to follow the 'getting it going'
steps below carefully, all other startup options will fail right now.

Have fun, come and join the party and hack on Ensime-Sublime

11.06.2015: Project moved to Ensime organisation.

With the kind permission of the original authors this project has been moved under the Ensime umbrella.
It is currently in a non-working state.  Please ignore the below instructions - we are working on bringing
it up to date and into a workable state as soon as possible - watch this space!

```

This is a beta version. It has been hacked to get it working against an up-to-date Ensime, but many things are
likely to be broken. Jump to source and error hightlight have been seen to work at least once ;)

Please submit issues to [our tracker](https://github.com/ensime/ensime-sublime/issues/new).

## Getting it going
As mentioned above we are in the process of bringing this project back to life - it works (well we think it does)
but you have to jump through a bunch of hoops to get it working.

### Setup plugin
1. Install [Sublime Text 2 or 3](http://www.sublimetext.com/2) (if you do not have Sublime Text already installed).
2. Clone this project (let's refer to it as `$PLUGIN`).
For Sublime Text 3 switch to branch `ST3` (`git fetch origin ST3 && git checkout ST3`).
3. Manually install Ensime-Sublime
  1. for Sublime Text 2:
  Symlink ```~/Library/Application Support/Sublime Text 2/Packages/Ensime``` (Mac) or ```/.config/sublime-text-2/Packages/Ensime``` (Linux) to `$PLUGIN`.

  2. for Sublime Text 3:
  Symlink ```~/Library/Application Support/Sublime Text 3/Packages/Ensime``` (Mac) or ```/.config/sublime-text-3/Packages/Ensime``` (Linux) to `$PLUGIN`.

4. Restart Sublime Text.

In future the plugin will be installed using Package Control (still on the TODO list).

### Prepare project
1. Checkout your project (referred to as `$PROJECT`).
3. Add the Ensime sbt plugin to your user sbt configuration (recommended) or directly to the sbt project itself
(see [ensime-server wiki](https://github.com/ensime/ensime-emacs/wiki/Quick-Start-Guide#installing-the-ensime-sbt-plugin) for details - ignore the Emacs bits).
3. Run ```sbt gen-ensime``` to create a ```.ensime``` file.

### Configure Ensime-Sublime plugin

1. Open Ensime plugin's configuration at `Preference -> Package Settings -> Ensime -> Settings - User`.
2. Add the below entry to the file:
```
{
	"connect_to_external_server": true,
}
```

### Start server and link in Sublime
1. Run the following command in the terminal (both Linux and Mac) to start an Ensime instance for your project:

```
$ $PLUGIN/serverStart.sh $PROJECT/.ensime
```

Note that Ensime Server requires `grealpath` utility (run e.g. `brew install coreutils` to install it).

2. In Sublime Text create a [new project](http://sublimetext.userecho.com/topic/50034-project-menu-new-project/) with `$PROJECT`
as a root (to do so: open a new window (`Ctrl+Shift+N` for Windows/Linux and `Cmd+Shift+N` for Mac) and open `$PROJECT` as a root).

3. Open the Sublime command palette (typically bound to `Ctrl+Shift+P` on Windows/Linux and `Cmd+Shift+P` on Mac) and type `Ensime: Startup`.

With luck - if you open a Scala file in your project, you should have error highlighting (on save) and jump to definition working!

## Features

* Supports Scala 2.9-2.11.

* Creates and understands `.ensime` projects (maximum one project per Sublime window,
  if you have a project with multiple subprojects only a single subproject will be available at a time).

* Integrates with SBT to generate Ensime projects from SBT projects and provides
  a command, which runs SBT compilation for the current Ensime project.

* Once your Ensime project is configured (we have a helper for that) and Ensime is run,
  Scala files in that Ensime project benefit from a number of semantic services:

    * On-the-fly typechecking and error highlighting on save. Error messages are displayed
      in the status bar when you click highlighted regions (unfortunately, Sublime Text 2 doesn't
      support programmable tooltips). Moreover, errors can be viewed in a dynamically updated buffer
      displayed with `Tools > Ensime > Commands > Show notes`.

    * Type-aware completions for identifiers (integrates into the built-in mechanism of completions
      in Sublime Text 2, depending on your configuration it might be bound to `Ctrl+Space`/`Cmd+Space` or `Tab`).

    * Type-aware go to definition (implemented by `ensime_go_to_definition` command: bind it yourself
      to your favorite hotkey or use the default `Ctrl+Click` binding on Windows/Linux or `Cmd+Click` on Mac).

* Implements experimental support for debugging. At the moment you can set breakpoints, create launch
  configurations, step through programs in the debugger, inspect program output, navigate stack traces
  and watch values of local variables. Things are far from smooth, but it might be worth a try.

## Additional Sublime Configurations

* By default Ensime customizes mouse bindings. It makes
       `Ctrl+Click`/`Cmd+Click` invoke `Go to Definition` and `Alt+Click` stand for `Inspect Type at Point`.
       If you want to disable these bindings or change them bindings to something else,
       adjust the config at `Preferences > Package Settings > Mousemap - Default`.

* For Windows users, make sure the `Line Endings` setting is set to `Unix`.
       You may do this by going to `View > Line Endings` and selecting `Unix`.

## How to use?

Open the Sublime command palette (typically bound to `Ctrl+Shift+P` on Windows/Linux and `Cmd+Shift+P` on Mac) and type `Ensime: Startup`.

If you don't have an Ensime project, the plugin will guide you through creating it.

If you already have a project, an ENSIME server process will be started in the background,
and the server will initialize a resident instance of the Scala compiler.
After the server is ready, a message will appear in the left-hand corner of the status bar.
It will read either `ENSIME` if the currently opened file belongs to the active Ensime project
or `ensime` if it doesn't. Keep an eye on this message - it's an indicator of things going well.

## Troubleshooting

If you find that some features of Ensime are not working properly (i.e. Go To Definition or Error Highlighting), then check the `Line Endings`
setting in Sublime Text.  On Windows, the line endings is set to `Windows` by default.
Simply change this setting to `Unix` by going to `View > Line Endings` and selecting `Unix`.

## Contacts

Submit issues on the [tracker](https://github.com/ensime/ensime-sublime/issues) or come find us on the
[ensime-sublime Gitter channel](https://gitter.im/ensime/ensime-sublime).


text:
package clothes.qualifiers;

import org.springframework.beans.factory.annotation.Qualifier;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Created by krishan on 9/7/15.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.TYPE, ElementType.CONSTRUCTOR, ElementType.FIELD})
@Qualifier
public @interface Women {

}


text:
@interface TLContactsSearchResultViewController ()

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) ZZFLEXAngel *tableViewAngel;

@property (nonatomic, strong) NSMutableArray *friendsData;

@end

@implementation TLContactsSearchResultViewController

- (void)loadView
{
    [super loadView];
    [self setStatusBarStyle:UIStatusBarStyleDefault];

    self.tableView = self.view.addTableView(1)
    .backgroundColor([UIColor colorGrayBG]).separatorStyle(UITableViewCellSeparatorStyleNone)
    .tableFooterView([UIView new])
    .estimatedRowHeight(0).estimatedSectionFooterHeight(0).estimatedSectionHeaderHeight(0)
    .masonry(^ (__kindof UIView *senderView, MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    })
    .view;

    self.tableViewAngel = [[ZZFLEXAngel alloc] initWithHostView:self.tableView];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.friendsData = [TLFriendHelper sharedFriendHelper].friendsData;
}

//MARK: UISearchResultsUpdating
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
    @weakify(self);
    TLContactsItemModel *(^createContactsItemModelWithUserModel)(TLUser *userModel) = ^TLContactsItemModel *(TLUser *userModel){
        TLContactsItemModel *model = createContactsItemModel(userModel.avatarPath, userModel.avatarURL, userModel.showName, userModel.detailInfo.remarkInfo, userModel);
        return model;
    };

    // 查找数据
    NSString *searchText = [searchController.searchBar.text lowercaseString];
    NSMutableArray *data = [[NSMutableArray alloc] init];
    for (TLUser *user in self.friendsData) {
        if ([user.remarkName containsString:searchText] || [user.username containsString:searchText] || [user.nikeName containsString:searchText] || [user.pinyin containsString:searchText] || [user.pinyinInitial containsString:searchText]) {
            TLContactsItemModel *model = createContactsItemModelWithUserModel(user);
            [data addObject:model];
        }
    }

    // 更新UI
    self.tableViewAngel.clear();
    if (data.count > 0) {
        self.tableViewAngel.addSection(0);
        self.tableViewAngel.setHeader([TLContactsHeaderView class]).toSection(0).withDataModel(@"联系人");
        self.tableViewAngel.addCells([TLContactsItemCell class]).toSection(0).withDataModelArray(data).selectedAction(^ (TLContactsItemModel *model) {
            @strongify(self);
            if (self.itemSelectedAction) {
                self.itemSelectedAction(self, model.userInfo);
            }
        });
    }
    [self.tableView reloadData];
}

//MARK: UISearchBarDelegate
- (void)searchBarBookmarkButtonClicked:(UISearchBar *)searchBar
{
    [TLAlertView showWithTitle:@"语音搜索按钮" message:nil];
}

@end