text:
import Visibility from 'visibilityjs';
import * as types from './mutation_types';
import { isProjectImportable } from '../utils';
import {
  convertObjectPropsToCamelCase,
  normalizeHeaders,
  parseIntPagination,
} from '~/lib/utils/common_utils';
import Poll from '~/lib/utils/poll';
import { visitUrl, objectToQuery } from '~/lib/utils/url_utility';
import { deprecatedCreateFlash as createFlash } from '~/flash';
import { s__, sprintf } from '~/locale';
import axios from '~/lib/utils/axios_utils';

let eTagPoll;

const hasRedirectInError = e => e?.response?.data?.error?.redirect;
const redirectToUrlInError = e => visitUrl(e.response.data.error.redirect);
const pathWithParams = ({ path, ...params }) => {
  const filteredParams = Object.fromEntries(
    Object.entries(params).filter(([, value]) => value !== ''),
  );
  const queryString = objectToQuery(filteredParams);
  return queryString ? `${path}?${queryString}` : path;
};

const isRequired = () => {
  // eslint-disable-next-line @gitlab/require-i18n-strings
  throw new Error('param is required');
};

const clearJobsEtagPoll = () => {
  eTagPoll = null;
};

const stopJobsPolling = () => {
  if (eTagPoll) eTagPoll.stop();
};

const restartJobsPolling = () => {
  if (eTagPoll) eTagPoll.restart();
};

const setFilter = ({ commit }, filter) => commit(types.SET_FILTER, filter);

const setImportTarget = ({ commit }, { repoId, importTarget }) =>
  commit(types.SET_IMPORT_TARGET, { repoId, importTarget });

const importAll = ({ state, dispatch }) => {
  return Promise.all(
    state.repositories
      .filter(isProjectImportable)
      .map(r => dispatch('fetchImport', r.importSource.id)),
  );
};

const fetchReposFactory = ({ reposPath = isRequired(), hasPagination }) => ({
  state,
  dispatch,
  commit,
}) => {
  dispatch('stopJobsPolling');
  commit(types.REQUEST_REPOS);

  const { provider, filter } = state;

  return axios
    .get(
      pathWithParams({
        path: reposPath,
        filter,
        page: hasPagination ? state.pageInfo.page.toString() : '',
      }),
    )
    .then(({ data, headers }) => {
      const normalizedHeaders = normalizeHeaders(headers);

      if ('X-PAGE' in normalizedHeaders) {
        commit(types.SET_PAGE_INFO, parseIntPagination(normalizedHeaders));
      }

      commit(types.RECEIVE_REPOS_SUCCESS, convertObjectPropsToCamelCase(data, { deep: true }));
    })
    .then(() => dispatch('fetchJobs'))
    .catch(e => {
      if (hasRedirectInError(e)) {
        redirectToUrlInError(e);
      } else {
        createFlash(
          sprintf(s__('ImportProjects|Requesting your %{provider} repositories failed'), {
            provider,
          }),
        );

        commit(types.RECEIVE_REPOS_ERROR);
      }
    });
};

const fetchImportFactory = (importPath = isRequired()) => ({ state, commit, getters }, repoId) => {
  const { ciCdOnly } = state;
  const importTarget = getters.getImportTarget(repoId);

  commit(types.REQUEST_IMPORT, { repoId, importTarget });

  const { newName, targetNamespace } = importTarget;
  return axios
    .post(importPath, {
      repo_id: repoId,
      ci_cd_only: ciCdOnly,
      new_name: newName,
      target_namespace: targetNamespace,
    })
    .then(({ data }) => {
      commit(types.RECEIVE_IMPORT_SUCCESS, {
        importedProject: convertObjectPropsToCamelCase(data, { deep: true }),
        repoId,
      });
    })
    .catch(e => {
      const serverErrorMessage = e?.response?.data?.errors;
      const flashMessage = serverErrorMessage
        ? sprintf(
            s__('ImportProjects|Importing the project failed: %{reason}'),
            {
              reason: serverErrorMessage,
            },
            false,
          )
        : s__('ImportProjects|Importing the project failed');

      createFlash(flashMessage);

      commit(types.RECEIVE_IMPORT_ERROR, repoId);
    });
};

export const fetchJobsFactory = (jobsPath = isRequired()) => ({ state, commit, dispatch }) => {
  const { filter } = state;

  if (eTagPoll) {
    stopJobsPolling();
    clearJobsEtagPoll();
  }

  eTagPoll = new Poll({
    resource: {
      fetchJobs: () => axios.get(pathWithParams({ path: jobsPath, filter })),
    },
    method: 'fetchJobs',
    successCallback: ({ data }) =>
      commit(types.RECEIVE_JOBS_SUCCESS, convertObjectPropsToCamelCase(data, { deep: true })),
    errorCallback: e => {
      if (hasRedirectInError(e)) {
        redirectToUrlInError(e);
      } else {
        createFlash(s__('ImportProjects|Update of imported projects with realtime changes failed'));
      }
    },
    data: { filter },
  });

  if (!Visibility.hidden()) {
    eTagPoll.makeRequest();
  }

  Visibility.change(() => {
    if (!Visibility.hidden()) {
      dispatch('restartJobsPolling');
    } else {
      dispatch('stopJobsPolling');
    }
  });
};

const fetchNamespacesFactory = (namespacesPath = isRequired()) => ({ commit }) => {
  commit(types.REQUEST_NAMESPACES);
  axios
    .get(namespacesPath)
    .then(({ data }) =>
      commit(types.RECEIVE_NAMESPACES_SUCCESS, convertObjectPropsToCamelCase(data, { deep: true })),
    )
    .catch(() => {
      createFlash(s__('ImportProjects|Requesting namespaces failed'));

      commit(types.RECEIVE_NAMESPACES_ERROR);
    });
};

const setPage = ({ state, commit, dispatch }, page) => {
  if (page === state.pageInfo.page) {
    return null;
  }

  commit(types.SET_PAGE, page);
  return dispatch('fetchRepos');
};

export default ({ endpoints = isRequired(), hasPagination }) => ({
  clearJobsEtagPoll,
  stopJobsPolling,
  restartJobsPolling,
  setFilter,
  setImportTarget,
  importAll,
  setPage,
  fetchRepos: fetchReposFactory({ reposPath: endpoints.reposPath, hasPagination }),
  fetchImport: fetchImportFactory(endpoints.importPath),
  fetchJobs: fetchJobsFactory(endpoints.jobsPath),
  fetchNamespaces: fetchNamespacesFactory(endpoints.namespacesPath),
});


text:
|          |                        |
| -------- | ---------------------- |
| title    | Summingbird            |
| status   | 10                     |
| section  | High level Programming |
| keywords | High level Programming |

Summingbird can be described as

> ``a library that lets you write MapReduce programs that look like
> native Scala or Java collection transformations and execute them on
> a number of well-known distributed MapReduce platforms, including
> Storm and Scalding'' [@summingbirdgit].

Summingbird is open-source and is a
domain-specific Scala implemented
language [@boykin2014summingbird]. It combines online and batch
MapReduce computations into one
framework [@boykin2014summingbird]. It utilizes the platforms
Hadoop for batch and Storm for online process
execution [@boykin2014summingbird]. The open-source Hadoop
implementation of MapReduce is a tool which those responsible for data
management use to handle problems related to big
data [@boykin2014summingbird]. Summingbird uses an algebraic
structure called a commutative semigroup to perform aggregations of
both batch and online processes [@boykin2014summingbird]. A
commutative semigroup is a particular type of semigroup

> ``where the associated binary operation is also commutative'' [@boykin2014summingbird].

The types of data that
Summingbird takes as inputs are streams and
snapshots [@boykin2014summingbird]. The types of data Summingbird
jobs generate are called stores and
sinks [@boykin2014summingbird]. Stores are

> ``an abstract model of a key-value store''

while sinks are unaggregated tuples from a
producer [@boykin2014summingbird]. Summingbird aims to simplify
the process of both batch and online analytics by exploiting

> ``the formal properties of algebraic structures''

to integrate the various
modes of distributed processing [@boykin2014summingbird].

redpajama_set_name: RedPajamaGithub


text:
#ifndef _SOCKET_IO_H
#define _SOCKET_IO_H

#include <ndb_global.h>

#include <NdbTCP.h>

#include <NdbMutex.h>

#ifdef  __cplusplus
extern "C" {
#endif

  int read_socket(NDB_SOCKET_TYPE, int timeout_ms, char *, int len);

  int readln_socket(NDB_SOCKET_TYPE socket, int timeout_millis, int *time,
                    char * buf, int buflen, NdbMutex *mutex);

  int write_socket(NDB_SOCKET_TYPE, int timeout_ms, int *time,
                   const char[], int len);

  int print_socket(NDB_SOCKET_TYPE, int timeout_ms, int *time,
                   const char *, ...);
  int println_socket(NDB_SOCKET_TYPE, int timeout_ms, int *time,
                     const char *, ...);
  int vprint_socket(NDB_SOCKET_TYPE, int timeout_ms, int *time,
                    const char *, va_list);
  int vprintln_socket(NDB_SOCKET_TYPE, int timeout_ms, int *time,
                      const char *, va_list);

#ifdef  __cplusplus
}
#endif

#endif


text:
package core;

import "log"
import "sync"

type VirtualUser struct {
  name string
  scenario *Scenario
}

func NewVirtualUser(name string, scenario *Scenario) *VirtualUser {
  return &VirtualUser{ name: name, scenario: scenario }
}

func (vu *VirtualUser) Init(log *log.Logger) error {
  log.Println("--> VirtualUser::Init()")
  // TODO
  log.Println("<-- VirtualUser::Init()")
  return nil
}

func (vu *VirtualUser) Run(log *log.Logger, wg *sync.WaitGroup, start <-chan int, stepsToController chan<- StepIteration, scenarioToController chan<- ScenarioIteration) error {
  log.Println("--> VirtualUser::Run()")

  // Make sure we notify we are done when this method is finished
  defer wg.Done()

  // Wait for the signal to start
  log.Println("Waiting for the signal to start")
  <- start
  log.Println("GOOOOOO !")

  for {
    err := vu.scenario.Do(log, vu, stepsToController, scenarioToController);
    if (err != nil) {
      log.Printf("Scenario ended with error %v, ", err)

    }
  }
  log.Println("<-- VirtualUser::Run()")
  return nil
}


text:
package org.apache.s4.comm.topology;

import org.I0Itec.zkclient.exception.ZkMarshallingError;
import org.I0Itec.zkclient.serialize.ZkSerializer;

import com.google.common.base.Preconditions;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
/**
 *
 * Utility to serialize/deserialize data in ZK. <br/>
 * Using Json format and Gson library.
 * TODO: Explore other libraries like jackson much richer features.
 * Gson needs no-arg constructor to work with without additional work
 */
public class ZNRecordSerializer implements ZkSerializer {

    @Override
    public byte[] serialize(Object data) throws ZkMarshallingError {
        if (data != null) {
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            String json = gson.toJson(data);
            if (json != null) {
                return json.getBytes();
            }
        }
        return new byte[0];
    }

    @Override
    public Object deserialize(byte[] bytes) throws ZkMarshallingError {
        ZNRecord record = null;
        if (bytes != null) {
            Gson gson = new Gson();
            record = gson.fromJson(new String(bytes), ZNRecord.class);
        }
        return record;
    }

}


text:
/*
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

using System;
namespace biz.ritter.javapi.util
{

    /**
     * A {@code Set} is a data structure which does not allow duplicate elements.
     *
     * @since 1.2
     */
    public interface Set<E> : Collection<E> {

        /*
         * Searches this set for all objects in the specified collection.
         *
         * @param collection
         *            the collection of objects.
         * @return {@code true} if all objects in the specified collection are
         *         elements of this set, {@code false} otherwise.
         *
        bool containsAll(Collection<E> collection);
        */
        /*
         * Compares the specified object to this set, and returns true if they
         * represent the same object using a class specific comparison.
         * Equality for a set means that both sets have the same size and the same
         * elements.
         *
         * @param object
         *            the object to compare with this object.
         * @return boolean {@code true} if the object is the same as this object,
         *         and {@code false} if it is different from this object.
         * @see #hashCode
         *
        bool equals(Object obj);

        /*
         * Returns the hash code for this set. Two set which are equal must return
         * the same value.
         *
         * @return the hash code of this set.
         *
         * @see #equals
         *
        int hashCode();

        /*
         * Adds the specified object to this set. The set is not modified if it
         * already contains the object.
         *
         * @param object
         *            the object to add.
         * @return {@code true} if this set is modified, {@code false} otherwise.
         * @throws UnsupportedOperationException
         *             when adding to this set is not supported.
         * @throws ClassCastException
         *             when the class of the object is inappropriate for this set.
         * @throws IllegalArgumentException
         *             when the object cannot be added to this set.
         *
        bool add(E obj);

        /*
         * Adds the objects in the specified collection which do not exist yet in
         * this set.
         *
         * @param collection
         *            the collection of objects.
         * @return {@code true} if this set is modified, {@code false} otherwise.
         * @throws UnsupportedOperationException
         *             when adding to this set is not supported.
         * @throws ClassCastException
         *             when the class of an object is inappropriate for this set.
         * @throws IllegalArgumentException
         *             when an object cannot be added to this set.
         *
        bool addAll(Collection<E> collection);

        /*
         * Removes all elements from this set, leaving it empty.
         *
         * @throws UnsupportedOperationException
         *             when removing from this set is not supported.
         * @see #isEmpty
         * @see #size
         *
        void clear();

        /*
         * Searches this set for the specified object.
         *
         * @param object
         *            the object to search for.
         * @return {@code true} if object is an element of this set, {@code false}
         *         otherwise.
         *
        bool contains(Object obj);

        /*
         * Returns true if this set has no elements.
         *
         * @return {@code true} if this set has no elements, {@code false}
         *         otherwise.
         * @see #size
         *
        bool isEmpty();

        /*
         * Returns an iterator on the elements of this set. The elements are
         * unordered.
         *
         * @return an iterator on the elements of this set.
         * @see Iterator
         *
        Iterator<E> iterator();

        /*
         * Removes the specified object from this set.
         *
         * @param object
         *            the object to remove.
         * @return {@code true} if this set was modified, {@code false} otherwise.
         * @throws UnsupportedOperationException
         *             when removing from this set is not supported.
         *
        bool remove(Object obj);

        /*
         * Returns the number of elements in this set.
         *
         * @return the number of elements in this set.
         *
        int size();

        /*
         * Returns an array containing all elements contained in this set.
         *
         * @return an array of the elements from this set.
         *
        Object[] toArray();

        /*
         * Returns an array containing all elements contained in this set. If the
         * specified array is large enough to hold the elements, the specified array
         * is used, otherwise an array of the same type is created. If the specified
         * array is used and is larger than this set, the array element following
         * the collection elements is set to null.
         *
         * @param array
         *            the array.
         * @return an array of the elements from this set.
         * @throws ArrayStoreException
         *             when the type of an element in this set cannot be stored in
         *             the type of the specified array.
         * @see Collection#toArray(Object[])
         *
        T[] toArray<T>(T[] array);
         */

        /*
         * Removes all objects in the specified collection from this set.
         *
         * @param collection
         *            the collection of objects to remove.
         * @return {@code true} if this set was modified, {@code false} otherwise.
         * @throws UnsupportedOperationException
         *             when removing from this set is not supported.
         *
        bool removeAll(Collection<E> collection);
        */

        /*
         * Removes all objects from this set that are not contained in the specified
         * collection.
         *
         * @param collection
         *            the collection of objects to retain.
         * @return {@code true} if this set was modified, {@code false} otherwise.
         * @throws UnsupportedOperationException
         *             when removing from this set is not supported.
         *
        bool retainAll(Collection<E> collection);
        */
    }
}


text:
//
//  KMAlertView.m
//  KM_Kit
//
//  Created by KM on 2017/6/13.
//  Copyright © 2017年 KM. All rights reserved.
//

#import "KMAlertView.h"

#define KM_Btn_Tag (888)
#define TableViewFooterHeight (0.1)

@interface UIView (KMAlertView_corners)

-(void)kmAlertView_setRoundedCorners:(UIRectCorner)corners radius:(CGFloat)radius;

@end

@implementation UIView (KMAlertView_corners)

-(void)kmAlertView_setRoundedCorners:(UIRectCorner)corners radius:(CGFloat)radius {
    CGRect rect = self.bounds;
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:rect
                                                   byRoundingCorners:corners
                                                         cornerRadii:CGSizeMake(radius, radius)];
    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.frame = rect;
    maskLayer.path = maskPath.CGPath;
    self.layer.mask = maskLayer;
}

@end

#pragma mark - KMHighLightButton
@interface KMHighLightButton : UIButton

@property (nonatomic, strong) KMAlertStyleButton * buttonStyle;

@end

@implementation KMHighLightButton

- (void)setHighlighted:(BOOL)highlighted {
    [super setHighlighted:highlighted];

    if (!self.buttonStyle.highlightBackgroundColor) { return; }

    self.backgroundColor = highlighted ? self.buttonStyle.highlightBackgroundColor : self.buttonStyle.backgroundColor;
}

//Getter
-(KMAlertStyleButton *)buttonStyle{
    if (!_buttonStyle) {
        _buttonStyle = [KMAlertStyleButton new];
    }
    return _buttonStyle;
}

@end

#pragma mark - KMAlertButtonCell

@interface KMAlertButtonCell : UITableViewCell

@property (nonatomic, strong) KMAlertStyleButton * buttonStyle;

@property (nonatomic, strong) KMHighLightButton * alertButton;

+(NSString *)alertCellId;

@end

@implementation KMAlertButtonCell

-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        self.backgroundColor = [UIColor clearColor];
        [self.contentView addSubview:self.alertButton];
    }
    return self;
}

-(void)layoutSubviews{
    [super layoutSubviews];
    self.alertButton.frame = self.contentView.bounds;
}

+(NSString *)alertCellId{
    return NSStringFromClass([self class]);
}

#pragma mark - Setter
-(void)setButtonStyle:(KMAlertStyleButton *)buttonStyle{
    _buttonStyle = buttonStyle;

    self.alertButton.buttonStyle = buttonStyle;
    [self.alertButton setTitle:buttonStyle.text forState:UIControlStateNormal];
    [self.alertButton setTitleColor:buttonStyle.textColor forState:UIControlStateNormal];
    [self.alertButton setTitleColor:buttonStyle.highlightTextColor forState:UIControlStateHighlighted];
    self.alertButton.titleLabel.font = buttonStyle.font;
    self.alertButton.backgroundColor = buttonStyle.backgroundColor;
}
#pragma mark - Getter
-(KMHighLightButton *)alertButton{
    if (!_alertButton) {
        _alertButton = [KMHighLightButton buttonWithType:UIButtonTypeCustom];
    }
    return _alertButton;
}
@end

#pragma mark - KMAlertView
@interface KMAlertView ()<UITableViewDelegate, UITableViewDataSource>

//View

@property (nonatomic, strong) UIView * contentView;

@property (nonatomic, strong) UIView * backgroundView;

@property (nonatomic, strong) UILabel * titleLabel;

@property (nonatomic, strong) UILabel * messageLabel;

@property (nonatomic, strong) UIScrollView * textContainer;
//标题容器
@property (nonatomic, strong) UIView * titleContainer;
//消息容器
@property (nonatomic, strong) UIView * messageContainer;
//按钮容器
@property (nonatomic, strong) UITableView * buttonContainer;
//高斯模糊
@property (nonatomic, strong) UIVisualEffectView *blurView;

@property (nonatomic, strong) UIView * shadowView;

//ButtonTitle
@property (nonatomic, copy) NSArray * buttonTitles;

//ContentFrame
@property (nonatomic, assign) CGRect alertContentFrame;

//CallBackBlock
@property (nonatomic, copy) KMAlertViewCallBackBlock callBack;

//AlertStyle
@property (nonatomic, strong) KMAlertStyle * style;
@end

@implementation KMAlertView

#pragma mark - Quick Init
/** Quick Init With Title */
+(instancetype)showAlertWithTitle:(NSString *)title{
    return [self showAlertWithTitle:title
                            message:nil
                      callBackBlock:nil];
}

/** Quick Init With Message */
+(instancetype)showAlertWithMessage:(NSString *)message{
    return [self showAlertWithTitle:nil
                            message:message
                      callBackBlock:nil];
}

/** Quick Init With Title + Message + CallBack */
+(instancetype)showAlertWithTitle:(NSString *)title
                          message:(NSString *)message
                    callBackBlock:(KMAlertViewCallBackBlock)callBack{
    return [self showAlertWithTitle:title
                            message:message
                       buttonTitles:@[@"确定"]
                      callBackBlock:callBack];

}

/** Quick Init With Title + Message + ButtonTitles + CallBack */
+(instancetype)showAlertWithTitle:(NSString *)title message:(NSString *)message buttonTitles:(NSArray<NSString *> *)buttonTitles callBackBlock:(KMAlertViewCallBackBlock)callBack{
    return [self showAlertWithStyleConfigBlock:^KMAlertStyle *(KMAlertStyle *alertStyle) {
                alertStyle.title.text = title;
                alertStyle.message.text = message;
                [alertStyle setupButtonsWithTitles:buttonTitles];
                return alertStyle;
            } callBackBlock:callBack];
}

/** Quick Init With ButtonTitles + AlertStyleConfig + CallBack */
+(instancetype)showAlertWithButtonTitles:(NSArray<NSString *> *)buttonTitles
                        styleConfigBlock:(AlertStyleConfig)alertStyleConfig
                           callBackBlock:(KMAlertViewCallBackBlock)callBack{
    return [self showAlertWithStyleConfigBlock:^KMAlertStyle *(KMAlertStyle *alertStyle) {
        alertStyle = alertStyleConfig ? alertStyleConfig(alertStyle) : alertStyle;
        [alertStyle setupButtonsWithTitles:buttonTitles];
        return alertStyle;
    } callBackBlock:callBack];
}

/** Quick Init With AlertStyleConfig + CallBack */
+(instancetype)showAlertWithStyleConfigBlock:(AlertStyleConfig)alertStyleConfig callBackBlock:(KMAlertViewCallBackBlock)callBack{
    KMAlertView *alertView = [KMAlertView new];
    alertView.style = alertStyleConfig ? alertStyleConfig(alertView.style) : alertView.style;
    alertView.callBack = [callBack copy];
    [alertView showAlertView];
    return alertView;
}

#pragma mark - initialize

- (instancetype)init
{
    self = [super init];
    if (self) {
        CGRect screenBounds = [UIScreen mainScreen].bounds;
        self.frame = screenBounds;
        self.backgroundColor = [UIColor clearColor];
        [self addSubviews];
    }
    return self;
}

-(void)willMoveToSuperview:(UIView *)newSuperview{
    [super willMoveToSuperview:newSuperview];
    if (newSuperview == nil) return;

    [self configBackground];                    //配置背景

    [self setupTextContentFrame];               //设置文字内容大小

    [self setupTextContentAttribute];           //设置文字属性

    [self.buttonContainer reloadData];

    if (self.style.buttons.count == 2){         //两个按钮
        [self setupTwoButtonFrame];
    }

    [self setupContentViewFrame];               //设置ContentView大小

    [self configShadow];                        //设置阴影

    //显示前对 TableView 的设置
    if (self.buttonContainer.contentSize.height > self.buttonContainer.frame.size.height + TableViewFooterHeight) {
        self.buttonContainer.scrollEnabled = YES;
    }else{
        self.buttonContainer.scrollEnabled = NO;
    }

    CGFloat margin = (self.style.alertView.width - self.style.separator.horizontalWidth) / 2.0;
    self.buttonContainer.layoutMargins = UIEdgeInsetsZero;
    self.buttonContainer.preservesSuperviewLayoutMargins = NO;
    self.buttonContainer.separatorColor = self.style.separator.horizontalColor;
    self.buttonContainer.separatorInset = UIEdgeInsetsMake(0, margin, 0, margin);
}

#pragma mark - Add Subviews
-(void)addSubviews{
    self.backgroundView.frame = self.bounds;

    [self addSubview:self.backgroundView];

    [self addSubview:self.shadowView];

    [self.shadowView addSubview:self.contentView];

    [self.contentView addSubview:self.textContainer];
    [self.contentView addSubview:self.buttonContainer];

    [self.textContainer addSubview:self.titleContainer];
    [self.textContainer addSubview:self.messageContainer];

    [self.titleContainer addSubview:self.titleLabel];
    [self.messageContainer addSubview:self.messageLabel];
}

#pragma mark - HorizontalLine
/**
 文字和按钮之间的横线
 */
-(void)addHorizontalLine{
    UIView *horizontalLine = [UIView new];
    horizontalLine.frame = CGRectMake(
                                      (CGRectGetWidth(_alertContentFrame) - _style.separator.horizontalWidth)/2.0,
                                      CGRectGetMaxY(_textContainer.frame),
                                      _style.separator.horizontalWidth,
                                      _style.separator.mainHorizontalHeight
                                      );
    horizontalLine.backgroundColor = _style.separator.horizontalColor;

    [_contentView addSubview:horizontalLine];
}

#pragma mark -
#pragma mark Config Background
/**
 背景的配置
 */
-(void)configBackground{

    if (_style.background.blur) {
        UIVisualEffect *blurEffect = [UIBlurEffect effectWithStyle:self.style.background.blurStyle];
        _blurView = [[UIVisualEffectView alloc]initWithEffect:blurEffect];
        _blurView.frame = _backgroundView.bounds;
        [_backgroundView addSubview:_blurView];
        _backgroundView.backgroundColor = [_style.background.color colorWithAlphaComponent:_style.background.alpha];
    }else{
        _backgroundView.backgroundColor = [_style.background.color colorWithAlphaComponent:_style.background.alpha];
    }
}

#pragma mark - Config Shadow
-(void)configShadow{
    if (self.style.shadow.isShadow) {
        _shadowView.layer.masksToBounds = NO;
        _shadowView.layer.shadowColor = _style.shadow.shadowColor.CGColor;
        _shadowView.layer.shadowRadius = _style.shadow.shadowRadius;
        _shadowView.layer.shadowOpacity = _style.shadow.shadowOpacity;
        _shadowView.layer.shadowOffset = _style.shadow.shadowOffset;
    }

    _shadowView.frame = _alertContentFrame;
    _contentView.frame = _shadowView.bounds;
    [_contentView kmAlertView_setRoundedCorners:UIRectCornerAllCorners
                                         radius:_style.alertView.cornerRadius];
}

#pragma mark -
#pragma mark TextContent Frame
/**
 文字内容 Frame
 */
-(void)setupTextContentFrame{

    _titleLabel.text = _style.title.text;
    _titleLabel.font = _style.title.font;
    _titleLabel.textColor = _style.title.textColor;

    _messageLabel.text = _style.message.text;
    _messageLabel.font = _style.message.font;
    _messageLabel.textColor = _style.message.textColor;

    CGFloat titleW = _style.alertView.width - _style.title.insets.left
                                                - _style.title.insets.right;

    CGSize titleTextSize = [_style.title.text boundingRectWithSize:CGSizeMake(titleW, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:_style.title.font} context:nil].size;

    CGFloat titleTextH = titleTextSize.height;
    CGFloat titleH = 0;

    if (titleTextH > 0) {
       titleTextH = (titleTextH < _style.title.minHeight ? _style.title.minHeight : titleTextH);
       titleH = titleTextH + _style.title.insets.top
                           + _style.title.insets.bottom;
    }

    CGFloat messageW = _style.alertView.width - _style.message.insets.left
                                                  - _style.message.insets.right;

    CGSize messageTextSize = [_style.message.text boundingRectWithSize:CGSizeMake(messageW, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:_style.message.font} context:nil].size;

    CGFloat messageTextH = messageTextSize.height;
    CGFloat messageH = 0;
    if (messageTextH > 0) {
        messageTextH = (messageTextH < _style.message.minHeight ? _style.message.minHeight : messageTextH);
        messageH = messageTextH + (titleTextH > 0 ? 0 : _style.message.insets.top)
                                + _style.message.insets.bottom;
    }

    CGFloat titleLabelX = _style.title.insets.left;
    CGFloat titleLabelY = _style.title.insets.top;
    CGFloat titleLabelW = titleW;
    CGFloat titleLabelH = titleTextH;

    _titleLabel.frame = CGRectMake(
                                       titleLabelX,
                                       titleLabelY,
                                       titleLabelW,
                                       titleLabelH
                                       );

    CGFloat messageLabelX = _style.message.insets.left;
    CGFloat messageLabelY = titleLabelH > 0 ? 0 : _style.message.insets.top;
    CGFloat messageLabelW = messageW;
    CGFloat messageLabelH = messageTextH;

    _messageLabel.frame = CGRectMake(
                                       messageLabelX,
                                       messageLabelY,
                                       messageLabelW,
                                       messageLabelH
                                       );

    CGFloat titleContainerX = 0;
    CGFloat titleContainerY = 0;
    CGFloat titleContainerW = _style.alertView.width;
    CGFloat titleContainerH = titleH;
    _titleContainer.frame = CGRectMake(
                                           titleContainerX,
                                           titleContainerY,
                                           titleContainerW,
                                           titleContainerH
                                           );
    CGFloat messageContainerX = 0;
    CGFloat messageContainerY = 0 + titleContainerH;
    CGFloat messageContainerW = _style.alertView.width;
    CGFloat messageContainerH = messageH;
    _messageContainer.frame = CGRectMake(
                                           messageContainerX,
                                           messageContainerY,
                                           messageContainerW,
                                           messageContainerH
                                           );

    CGFloat textContainerH = CGRectGetHeight(_titleContainer.frame) + CGRectGetHeight(_messageContainer.frame);

    _textContainer.contentSize = CGSizeMake(
                                                _style.alertView.width,
                                                textContainerH
                                                );
}
#pragma mark TextContent Attribute
/**
 配置文字属性
 */
-(void)setupTextContentAttribute{
    _titleLabel.textAlignment = _style.title.textAlignment;

    _messageLabel.textAlignment = _style.message.textAlignment;

    _titleContainer.backgroundColor = _style.title.backgroundColor;

    _messageContainer.backgroundColor = _style.message.backgroundColor;

    _contentView.backgroundColor = _style.alertView.backgroundColor;
}

#pragma mark -
#pragma mark ContentView Frame
/**
 计算 ContentView Frame
 */
-(void)setupContentViewFrame{

    CGFloat textContainerX = 0;
    CGFloat textContainerY = 0;
    CGFloat textContainerW = _style.alertView.width;
    CGFloat textContainerH = _textContainer.contentSize.height;

    CGFloat maxContnetH = [UIScreen mainScreen].bounds.size.height
    - _style.alertView.minInsets.top
    - _style.alertView.minInsets.bottom;

    CGFloat maxTextContainerH = 0;

    if (_style.buttons.count == 1 || _style.buttons.count == 2) {       //一个按钮 两个按钮

        KMAlertStyleButton *buttonStyle = [_style.buttons firstObject];
        maxTextContainerH = maxContnetH - buttonStyle.height;

    }else if (_style.buttons.count != 0){                                   //多个按钮

        maxTextContainerH = maxContnetH - _style.alertView.multipleButtonMinHeight;

    }else{                                                                      //没有按钮

        maxTextContainerH = maxContnetH;

    }
    textContainerH = textContainerH > maxTextContainerH ? maxTextContainerH : textContainerH;

    _textContainer.frame = CGRectMake(
                                          textContainerX,
                                          textContainerY,
                                          textContainerW,
                                          textContainerH
                                          );

    CGFloat buttonContainerX = 0;
    CGFloat buttonContainerY = CGRectGetMaxY(_textContainer.frame);
    CGFloat buttonContainerW = _style.alertView.width;
    CGFloat buttonContainerH = 0;

    if (_style.buttons.count == 1 || _style.buttons.count == 2) {       //一个按钮 两个按钮

        KMAlertStyleButton *buttonStyle = [_style.buttons firstObject];
        buttonContainerH = buttonStyle.height;

    }else if (_style.buttons.count != 0){                                   //多个按钮

        if (textContainerH + _buttonContainer.contentSize.height > maxContnetH) {
            buttonContainerH = maxContnetH - textContainerH;
        }else{
            buttonContainerH = _buttonContainer.contentSize.height;
        }

    }else{                                                                      //没有按钮
        buttonContainerH = 0;
    }

    if (buttonContainerH) {
        buttonContainerY += _style.separator.mainHorizontalHeight;
    }

    _buttonContainer.frame = CGRectMake(
                                            buttonContainerX,
                                            buttonContainerY,
                                            buttonContainerW,
                                            buttonContainerH
                                            );

    CGFloat contentViewX = ([UIScreen mainScreen].bounds.size.width - _style.alertView.width)/2.0;
    CGFloat contentViewH = CGRectGetMaxY(_buttonContainer.frame);
    CGFloat contentViewY = ([UIScreen mainScreen].bounds.size.height / 2.0) - (contentViewH / 2.0);
    CGFloat contentViewW = _style.alertView.width;

    _alertContentFrame = CGRectMake(
                                        contentViewX,
                                        contentViewY,
                                        contentViewW,
                                        contentViewH
                                        );;
    if (buttonContainerH) {
        [self addHorizontalLine];
    }
}

#pragma mark -
#pragma mark Config Button

#pragma mark  两个按钮
/**
 两个按钮时的配置
 */
-(void)setupTwoButtonFrame{

    CGFloat buttonY = 0;
    CGFloat buttonW = (_style.alertView.width - 0.5) / 2.0;

    for (int i = 0; i < _style.buttons.count; i ++) {

        KMAlertStyleButton *buttonStyle = [_style.buttons objectAtIndex:i];

        KMHighLightButton *button = [KMHighLightButton buttonWithType:UIButtonTypeCustom];
        button.tag = KM_Btn_Tag + i;
        button.buttonStyle = buttonStyle;

        [button setTitle:buttonStyle.text forState:UIControlStateNormal];
        [button setTitleColor:buttonStyle.textColor forState:UIControlStateNormal];
        [button setTitleColor:buttonStyle.highlightTextColor forState:UIControlStateHighlighted];
        button.titleLabel.font = buttonStyle.font;
        button.backgroundColor = buttonStyle.backgroundColor;

        [button addTarget:self
                      action:@selector(buttonClickEvent:)
            forControlEvents:UIControlEventTouchUpInside];

        CGFloat buttonX = i * (buttonW + 0.5);
        CGFloat buttonH = buttonStyle.height;

        button.frame = CGRectMake(
                                  buttonX,
                                  buttonY,
                                  buttonW,
                                  buttonH
                                  );
        [_buttonContainer addSubview:button];

        if(i == 0){
            UIView *verticalLineView = [UIView new];
            verticalLineView.frame = CGRectMake(
                                                CGRectGetWidth(button.frame),
                                                0,
                                                0.5,
                                                buttonH
                                                );
            verticalLineView.backgroundColor = _style.separator.verticalColor;
            [_buttonContainer addSubview:verticalLineView];
        }
    }

    KMAlertStyleButton *buttonStyle = [_style.buttons firstObject];
    _buttonContainer.contentSize = CGSizeMake(_style.alertView.width, buttonStyle.height);
}

#pragma mark -
#pragma mark ShowAlertView
/**
 显示前的动画设置
 */
-(void)configBeforeShowAlert{
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    [keyWindow addSubview:self];

    if (_style.background.isBlur) {
        _blurView.backgroundColor = [_style.background.color colorWithAlphaComponent:0];
    }else{
       _backgroundView.backgroundColor = [_style.background.color colorWithAlphaComponent:0];
    }

    switch (_style.animate.inType) {
        case KMAlertViewAnimateInTypeScale:{
            _shadowView.transform = CGAffineTransformMakeScale(0.6, 0.6);
        }
            break;
        case KMAlertViewAnimateInTypeTop:{
            _shadowView.frame = CGRectMake(
                                            _alertContentFrame.origin.x,
                                            0 - _alertContentFrame.size.height - 15,
                                            _alertContentFrame.size.width,
                                            _alertContentFrame.size.height
                                            );
        }
            break;
        case KMAlertViewAnimateInTypeLeft:{
            _shadowView.frame = CGRectMake(
                                            0 - _alertContentFrame.size.width - 15,
                                            _alertContentFrame.origin.y,
                                            _alertContentFrame.size.width,
                                            _alertContentFrame.size.height
                                            );
        }
            break;
        case KMAlertViewAnimateInTypeBottom:{
            _shadowView.frame = CGRectMake(
                                            _alertContentFrame.origin.x,
                                            self.frame.size.height + _alertContentFrame.size.height + 15,
                                            _alertContentFrame.size.width,
                                            _alertContentFrame.size.height
                                            );
        }
            break;
        case KMAlertViewAnimateInTypeRight:{
            _shadowView.frame = CGRectMake(
                                            self.frame.size.width + _alertContentFrame.size.width + 15,
                                            _alertContentFrame.origin.y,
                                            _alertContentFrame.size.width,
                                            _alertContentFrame.size.height
                                            );
        }
            break;
        case KMAlertViewAnimateInTypeAngle:{
            _shadowView.frame = CGRectMake(
                                            _alertContentFrame.origin.x,
                                            0 - _alertContentFrame.size.height - 15,
                                            _alertContentFrame.size.width,
                                            _alertContentFrame.size.height
                                            );
            _shadowView.transform = CGAffineTransformMakeRotation(_style.animate.angle * (M_PI / 180));
        }
            break;

        default:
            break;
    }
}

/**
 显示动画设置
 */
-(void)configAfterShowAlert{
    if (_style.background.isBlur) {
        _blurView.backgroundColor = [_style.background.color colorWithAlphaComponent:0];
    }else{
        _backgroundView.backgroundColor = [_style.background.color colorWithAlphaComponent:_style.background.alpha];
    }

    _shadowView.transform = CGAffineTransformIdentity;

    if (_style.animate.inType == KMAlertViewAnimateInTypeScale) {

    }else{
        _shadowView.frame = CGRectMake(
                                        _alertContentFrame.origin.x,
                                        _alertContentFrame.origin.y,
                                        _alertContentFrame.size.width,
                                        _alertContentFrame.size.height
                                        );
    }
}

/**
 显示Alert
 */
-(void)showAlertView{

    [self configBeforeShowAlert];

    if (_style.animate.isBounce) {
        [UIView animateWithDuration:_style.animate.animateInDuration delay:0 usingSpringWithDamping:_style.animate.springDamping initialSpringVelocity:_style.animate.springVelocity options:UIViewAnimationOptionCurveEaseInOut animations:^{
            [self configAfterShowAlert];
        } completion:^(BOOL finished) {

        }];
    }else{
        [UIView animateWithDuration:_style.animate.animateInDuration delay:0.0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            [self configAfterShowAlert];
        } completion:^(BOOL finished) {

        }];
    }
}

#pragma mark -
#pragma mark HideAlertView
/**
 隐藏时如果 Bounce = YES
 */
-(void)configBounceWithHideAlert{
    switch (_style.animate.outType) {
        case KMAlertViewAnimateOutTypeTop:{
            _shadowView.frame = CGRectMake(
                                            _alertContentFrame.origin.x,
                                            _alertContentFrame.origin.y + 7.5,
                                            _alertContentFrame.size.width,
                                            _alertContentFrame.size.height
                                            );
        }
            break;
        case KMAlertViewAnimateOutTypeLeft:{

            _shadowView.frame = CGRectMake(
                                            _alertContentFrame.origin.x + 7.5,
                                            _alertContentFrame.origin.y,
                                            _alertContentFrame.size.width,
                                            _alertContentFrame.size.height
                                            );

        }
            break;
        case KMAlertViewAnimateOutTypeBottom:{
            _shadowView.frame = CGRectMake(
                                            _alertContentFrame.origin.x,
                                            _alertContentFrame.origin.y - 7.5,
                                            _alertContentFrame.size.width,
                                            _alertContentFrame.size.height
                                            );
        }
            break;
        case KMAlertViewAnimateOutTypeRight:{
            _shadowView.frame = CGRectMake(
                                            _alertContentFrame.origin.x - 7.5,
                                            _alertContentFrame.origin.y,
                                            _alertContentFrame.size.width,
                                            _alertContentFrame.size.height
                                            );
        }
            break;
        default:
            break;
    }
}

-(void)configBeforeHideAlert{

}

/**
 隐藏动画设置
 */
-(void)configAfterHideAlert{
    _shadowView.alpha = 0;
    _backgroundView.backgroundColor = [_style.background.color colorWithAlphaComponent:0.15];
    switch (_style.animate.outType) {
        case KMAlertViewAnimateOutTypeTop:{
            _shadowView.frame = CGRectMake(
                                            _alertContentFrame.origin.x,
                                            0 - _alertContentFrame.size.height - 15,
                                            _alertContentFrame.size.width,
                                            _alertContentFrame.size.height
                                            );
        }
            break;
        case KMAlertViewAnimateOutTypeLeft:{
            _shadowView.frame = CGRectMake(
                                            0 - _alertContentFrame.size.width - 15,
                                            _alertContentFrame.origin.y,
                                            _alertContentFrame.size.width,
                                            _alertContentFrame.size.height
                                            );
        }
            break;
        case KMAlertViewAnimateOutTypeBottom:{
            _shadowView.frame = CGRectMake(
                                            _alertContentFrame.origin.x,
                                            self.frame.size.height + _alertContentFrame.size.height + 15,
                                            _alertContentFrame.size.width,
                                            _alertContentFrame.size.height
                                            );
        }
            break;
        case KMAlertViewAnimateOutTypeRight:{
            _shadowView.frame = CGRectMake(
                                            self.frame.size.width + _alertContentFrame.size.width + 15,
                                            _alertContentFrame.origin.y,
                                            _alertContentFrame.size.width,
                                            _alertContentFrame.size.height
                                            );
        }
            break;
        case KMAlertViewAnimateOutTypeAngle:{
            _shadowView.frame = CGRectMake(
                                            _alertContentFrame.origin.x,
                                            self.frame.size.height + _alertContentFrame.size.height + 15,
                                            _alertContentFrame.size.width,
                                            _alertContentFrame.size.height
                                            );
            _shadowView.transform = CGAffineTransformMakeRotation(_style.animate.angle);
        }
            break;

        default:
            break;
    }
}

/**
 隐藏Alert

 @param completion 回调
 */
- (void)hideAlertWithCompletion:(void(^)(void))completion{

    [UIView animateWithDuration:_style.animate.animateOutDuration delay:0.0 options:UIViewAnimationOptionCurveEaseInOut animations:^{

        if (_style.animate.outType == KMAlertViewAnimateOutTypeScale) {
            _shadowView.transform = CGAffineTransformMakeScale(0.6, 0.6);
            [self configAfterHideAlert];
        }else{
            if (_style.animate.isBounce) {
                [self configBounceWithHideAlert];
            }else{
                [self configAfterHideAlert];
            }
        }
    } completion:^(BOOL finished) {
        if (_style.animate.outType == KMAlertViewAnimateOutTypeScale) {
            completion ? completion() : nil;
            [self removeFromSuperview];
        }else{
            if (_style.animate.isBounce) {
                [UIView animateWithDuration:_style.animate.animateOutDuration animations:^{
                    [self configAfterHideAlert];
                } completion:^(BOOL finished) {
                    completion ? completion() : nil;
                    [self removeFromSuperview];
                }];
            }else{
                completion ? completion() : nil;
                [self removeFromSuperview];
            }
        }
    }];
}

#pragma mark -
#pragma mark Tap Background
/**
 点击背景
 */
-(void)tapBackgroundView{
    if (_style.background.isDismissWhenTouchBackground) {
        [self hideAlertWithCompletion:nil];
    }
}
#pragma mark -
#pragma mark Dismiss
/**
 外部调用的隐藏Alert

 @param completion 回调
 */
-(void)dismissWithCompletion:(void (^)(void))completion{
    [self hideAlertWithCompletion:completion];
}

/**
 Alert按钮点击
 */
#pragma mark - Button Event
-(void)buttonClickEvent:(UIButton *)button{

    NSInteger index = button.tag - KM_Btn_Tag;

    self.callBack ? self.callBack(index, [self.style.buttons objectAtIndex:index].text) : nil;
    [self hideAlertWithCompletion:nil];
}

#pragma mark - TableViwe Delegate && DataSouce

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
   KMAlertStyleButton *buttonStyle = [_style.buttons objectAtIndex:indexPath.row];
    return buttonStyle.height;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (_style.buttons.count == 2) {
        return 0;
    }
    return _style.buttons.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    KMAlertButtonCell *cell = [tableView dequeueReusableCellWithIdentifier:[KMAlertButtonCell alertCellId]];

    KMAlertStyleButton *buttonStyle = [_style.buttons objectAtIndex:indexPath.row];
    cell.buttonStyle = buttonStyle;
    cell.alertButton.tag = indexPath.row + KM_Btn_Tag;
    [cell.alertButton addTarget:self action:@selector(buttonClickEvent:) forControlEvents:UIControlEventTouchUpInside];
    cell.layoutMargins = UIEdgeInsetsZero;
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return TableViewFooterHeight;
}

#pragma mark - Getter
-(UIView *)backgroundView{
    if (!_backgroundView) {
        _backgroundView = [[UIView alloc]init];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self
                                                                             action:@selector(tapBackgroundView)];
        [_backgroundView addGestureRecognizer:tap];
    }
    return _backgroundView;
}
-(UIView *)shadowView{
    if (!_shadowView) {
        _shadowView = [[UIView alloc]init];
    }
    return _shadowView;
}
-(UIView *)contentView{
    if (!_contentView) {
        _contentView = [[UIView alloc]init];
    }
    return _contentView;
}

-(UIScrollView *)textContainer{
    if (!_textContainer) {
        _textContainer = [[UIScrollView alloc]init];
        _textContainer.backgroundColor = [UIColor clearColor];
    }
    return _textContainer;
}
-(UIView *)titleContainer{
    if (!_titleContainer) {
        _titleContainer = [[UIView alloc]init];
    }
    return _titleContainer;
}

-(UIView *)messageContainer{
    if (!_messageContainer) {
        _messageContainer = [[UIView alloc]init];
    }
    return _messageContainer;
}
-(UITableView *)buttonContainer{
    if (!_buttonContainer) {
        _buttonContainer = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        _buttonContainer.delegate = self;
        _buttonContainer.dataSource = self;
        _buttonContainer.backgroundColor = [UIColor clearColor];
        _buttonContainer.tableFooterView = [UIView new];
        [_buttonContainer registerClass:[KMAlertButtonCell class] forCellReuseIdentifier:[KMAlertButtonCell alertCellId]];
    }
    return _buttonContainer;
}
-(UILabel *)titleLabel{
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc]init];
        _titleLabel.numberOfLines = 0;
    }
    return _titleLabel;
}
-(UILabel *)messageLabel{
    if (!_messageLabel) {
        _messageLabel = [[UILabel alloc]init];
        _messageLabel.numberOfLines = 0;
    }
    return _messageLabel;
}

-(KMAlertStyle *)style{
    if (!_style) {
        _style = [KMAlertStyle new];
    }
    return _style;
}
@end


text:
class GURL;

#if defined(USE_AURA)
namespace aura {
namespace test {
class AuraTestHelper;
}
}
#endif

namespace content {
class NavigationController;
class WebContents;
}

// Base class for browser based unit tests. BrowserWithTestWindowTest creates a
// Browser with a TestingProfile and TestBrowserWindow. To add a tab use
// AddTab. For example, the following adds a tab and navigates to
// two URLs that target the TestTabContents:
//
//   // Add a new tab and navigate it. This will be at index 0.
//   AddTab(browser(), GURL("http://foo/1"));
//   NavigationController* controller =
//       &browser()->tab_strip_model()->GetTabContentsAt(0)->GetController();
//
//   // Navigate somewhere else.
//   GURL url2("http://foo/2");
//   NavigateAndCommit(controller, url2);
//
//   // This is equivalent to the above, and lets you test pending navigations.
//   browser()->OpenURL(OpenURLParams(
//       GURL("http://foo/2"), GURL(), CURRENT_TAB,
//       content::PAGE_TRANSITION_TYPED, false));
//   CommitPendingLoad(controller);
//
// Subclasses must invoke BrowserWithTestWindowTest::SetUp as it is responsible
// for creating the various objects of this class.
class BrowserWithTestWindowTest : public testing::Test {
 public:
  BrowserWithTestWindowTest();
  virtual ~BrowserWithTestWindowTest();

  virtual void SetUp() OVERRIDE;
  virtual void TearDown() OVERRIDE;

 protected:
  TestBrowserWindow* window() const { return window_.get(); }
  void set_window(TestBrowserWindow* window) {
    window_.reset(window);
  }

  Browser* browser() const { return browser_.get(); }
  void set_browser(Browser* browser) {
    browser_.reset(browser);
  }

  TestingProfile* profile() const { return profile_.get(); }
  void set_profile(TestingProfile* profile);

  MessageLoop* message_loop() { return &ui_loop_; }

  // Adds a tab to |browser| with the given URL and commits the load.
  // This is a convenience function. The new tab will be added at index 0.
  void AddTab(Browser* browser, const GURL& url);

  // Commits the pending load on the given controller. It will keep the
  // URL of the pending load. If there is no pending load, this does nothing.
  void CommitPendingLoad(content::NavigationController* controller);

  // Creates a pending navigation on the given navigation controller to the
  // given URL with the default parameters and the commits the load with a page
  // ID one larger than any seen. This emulates what happens on a new
  // navigation.
  void NavigateAndCommit(content::NavigationController* controller,
                         const GURL& url);

  // Navigates the current tab. This is a wrapper around NavigateAndCommit.
  void NavigateAndCommitActiveTab(const GURL& url);

 protected:
  // Destroys the browser, window, and profile created by this class. This is
  // invoked from the destructor.
  void DestroyBrowserAndProfile();

  // Creates the profile used by this test. The caller owns the return value.
  virtual TestingProfile* CreateProfile();

 private:
  // We need to create a MessageLoop, otherwise a bunch of things fails.
  MessageLoopForUI ui_loop_;
  content::TestBrowserThread ui_thread_;
  content::TestBrowserThread db_thread_;
  content::TestBrowserThread file_thread_;
  content::TestBrowserThread file_user_blocking_thread_;

  scoped_ptr<TestingProfile> profile_;
  scoped_ptr<TestBrowserWindow> window_;
  scoped_ptr<Browser> browser_;

  // The existence of this object enables tests via
  // RenderViewHostTester.
  content::RenderViewHostTestEnabler rvh_test_enabler_;

#if defined(USE_AURA)
  scoped_ptr<aura::test::AuraTestHelper> aura_test_helper_;
#endif

#if defined(OS_WIN)
  ui::ScopedOleInitializer ole_initializer_;
#endif

  DISALLOW_COPY_AND_ASSIGN(BrowserWithTestWindowTest);
};

#endif  // CHROME_TEST_BASE_BROWSER_WITH_TEST_WINDOW_TEST_H_


text:
package java.awt.event;

import java.util.EventListener;

/**
 * The listener interface for receiving keyboard focus events on
 * a component.
 * The class that is interested in processing a focus event
 * either implements this interface (and all the methods it
 * contains) or extends the abstract {@code FocusAdapter} class
 * (overriding only the methods of interest).
 * The listener object created from that class is then registered with a
 * component using the component's {@code addFocusListener}
 * method. When the component gains or loses the keyboard focus,
 * the relevant method in the listener object
 * is invoked, and the {@code FocusEvent} is passed to it.
 *
 * @see FocusAdapter
 * @see FocusEvent
 * @see Tutorial: Writing a Focus Listener
 *
 * @author Carl Quinn
 * @since 1.1
 */
public interface FocusListener extends EventListener {

    /**
     * Invoked when a component gains the keyboard focus.
     * @param e the event to be processed
     */
    public void focusGained(FocusEvent e);

    /**
     * Invoked when a component loses the keyboard focus.
     * @param e the event to be processed
     */
    public void focusLost(FocusEvent e);
}


text:
package com.francelabs.datafari.alerts;
/**
 *
 * This class is used to launch the alerts (if they are activated) at Datafari's start.
 * Also avoid cumulating scheduled task on reloading Datafari (useful only in development environment)
 * @author Alexis Karassev
 *
 */

import java.io.IOException;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import org.apache.log4j.Logger;
@WebListener
public class StartAlertsListener implements ServletContextListener {
	private final static Logger LOGGER = Logger.getLogger(StartAlertsListener.class
			.getName());
	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		AlertsManager.getInstance().turnOff();
	}

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		try {
			AlertsManager.getInstance().turnOn();
		} catch (IOException e) {
			LOGGER.error("Error while turning on the alerts during instantiation, StartAlertsListener", e);
		}
	}
}


text:
Core::Core(ILogger *pLogger){
	m_pLogger = pLogger;
	m_nWidth = 1280;
	m_nHeight = 720;
	m_nFramerate = 10;
	m_nPort = 31001;

	// init input streams
	m_pInputStreamCommands = new InputStreamCommands(this);
	m_pRenderStream = new RenderStream(this);
	m_pOutputStream = new OutputStream(this);

	m_pRenderStream->setInputStream(m_pInputStreamCommands);
	m_pRenderStream->setOutputStream(m_pOutputStream);

};

QImage * Core::createFrame(){
	QMutexLocker lock(&m_mtxFrames);
	QImage *pFrame = new QImage(QSize(width(),height()), QImage::Format_RGB32);
	pFrame->fill(QColor(0x303030));
	m_vFrames.push_back(pFrame);
	return pFrame;
};

QImage * Core::lastFrame(){
	QMutexLocker lock(&m_mtxFrames);
	if(m_vFrames.size() == 0){
		QImage *pFrame = new QImage(QSize(width(),height()), QImage::Format_RGB32);
		pFrame->fill(QColor(0x303030));
		m_vFrames.push_back(pFrame);
	}
	return m_vFrames.last();
};

void Core::pushFrames(){
	QMutexLocker lock(&m_mtxFrames);
	for(int i = 0; i < m_vFrames.size(); i++){
		m_pOutputStream->addFrame(m_vFrames[i]);
	}
	m_vFrames.clear();
};

ILogger *Core::logger(){
	return m_pLogger;
};

int Core::port(){
	return m_nPort;
};

int Core::width(){
	return m_nWidth;
};

int Core::height(){
	return m_nHeight;
}

int Core::framerate(){
	return m_nFramerate;
};

void Core::start(){
	m_pInputStreamCommands->start(port());
	m_pOutputStream->start();
	m_pRenderStream->start();
}


text:
<all
  id = ID
  maxOccurs = 1 : 1
  minOccurs = (0 | 1) : 1
  {any attributes with non-schema namespace . . .}>
  Content: (annotation?, element*)
</all>


text:
package org.apache.ofbiz.widget.model;

import java.util.List;

import org.apache.ofbiz.base.util.Debug;
import org.apache.ofbiz.base.util.UtilXml;
import org.apache.ofbiz.entity.model.ModelReader;
import org.apache.ofbiz.service.DispatchContext;
import org.w3c.dom.Element;

/**
 * Models the <grid> element.
 *
 * @see widget-form.xsd
 */
@SuppressWarnings("serial")
public class ModelGrid extends ModelForm {

    /*
     * ----------------------------------------------------------------------- *
     *                     DEVELOPERS PLEASE READ
     * ----------------------------------------------------------------------- *
     *
     * This model is intended to be a read-only data structure that represents
     * an XML element. Outside of object construction, the class should not
     * have any behaviors. All behavior should be contained in model visitors.
     *
     * Instances of this class will be shared by multiple threads - therefore
     * it is immutable. DO NOT CHANGE THE OBJECT'S STATE AT RUN TIME!
     *
     */

    public static final String module = ModelGrid.class.getName();

    /** XML Constructor */
    public ModelGrid(Element formElement, String formLocation, ModelReader entityModelReader, DispatchContext dispatchContext) {
        super(formElement, formLocation, entityModelReader, dispatchContext, "list");
    }

    @Override
    public void accept(ModelWidgetVisitor visitor) throws Exception {
        visitor.visit(this);
    }

    protected ModelForm getParentModel(Element gridElement, ModelReader entityModelReader, DispatchContext dispatchContext) {
        ModelForm parentModel = null;
        String parentResource = gridElement.getAttribute("extends-resource");
        String parentGrid = gridElement.getAttribute("extends");
        if (!parentGrid.isEmpty()) {
            // check if we have a resource name
            if (!parentResource.isEmpty()) {
                try {
                    parentModel = GridFactory.getGridFromLocation(parentResource, parentGrid, entityModelReader, dispatchContext);
                } catch (Exception e) {
                    Debug.logError(e, "Failed to load parent grid definition '" + parentGrid + "' at resource '" + parentResource
                            + "'", module);
                }
            } else if (!parentGrid.equals(gridElement.getAttribute("name"))) {
                // try to find a grid definition in the same file
                Element rootElement = gridElement.getOwnerDocument().getDocumentElement();
                List<? extends Element> gridElements = UtilXml.childElementList(rootElement, "grid");
                if (gridElements.isEmpty()) {
                    // Backwards compatibility - look for form definitions
                    gridElements = UtilXml.childElementList(rootElement, "form");
                }
                for (Element parentElement : gridElements) {
                    if (parentElement.getAttribute("name").equals(parentGrid)) {
                        parentModel = GridFactory.createModelGrid(parentElement, entityModelReader, dispatchContext,
                                parentResource, parentGrid);
                        break;
                    }
                }
                if (parentModel == null) {
                    Debug.logError("Failed to find parent grid definition '" + parentGrid + "' in same document.", module);
                }
            } else {
                Debug.logError("Recursive grid definition found for '" + gridElement.getAttribute("name") + ".'", module);
            }
        }
        return parentModel;
    }
}


text:
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.photo_picker;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.IntDef;
import androidx.recyclerview.widget.RecyclerView.Adapter;
import androidx.recyclerview.widget.RecyclerView.ViewHolder;

import org.chromium.chrome.R;

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

/**
 * A data adapter for the Photo Picker.
 */
public class PickerAdapter extends Adapter<ViewHolder> {
    // The possible types of actions required during decoding.
    @IntDef({DecodeActions.NO_ACTION, DecodeActions.FROM_CACHE, DecodeActions.DECODE})
    @Retention(RetentionPolicy.SOURCE)
    public @interface DecodeActions {
        int NO_ACTION = 0; // Gallery/Camera tile: No action.
        int FROM_CACHE = 1; // Image already decoded.
        int DECODE = 2; // Image needed to be decoded.
    }

    // The category view to use to show the images.
    private PickerCategoryView mCategoryView;

    // How many times the (high-res) cache was useful.
    @DecodeActions
    private int mCacheHits;

    // How many times a decoding was requested.
    @DecodeActions
    private int mDecodeRequests;

    /**
     * The PickerAdapter constructor.
     * @param categoryView The category view to use to show the images.
     */
    public PickerAdapter(PickerCategoryView categoryView) {
        mCategoryView = categoryView;
    }

    // RecyclerView.Adapter:

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                                .inflate(R.layout.photo_picker_bitmap_view, parent, false);
        PickerBitmapView bitmapView = (PickerBitmapView) itemView;
        bitmapView.setCategoryView(mCategoryView);
        return new PickerBitmapViewHolder(bitmapView);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        if (holder instanceof PickerBitmapViewHolder) {
            PickerBitmapViewHolder myHolder = (PickerBitmapViewHolder) holder;
            @DecodeActions
            int result = myHolder.displayItem(mCategoryView, position);
            if (result == DecodeActions.FROM_CACHE) {
                mCacheHits++;
            } else if (result == DecodeActions.DECODE) {
                mDecodeRequests++;
            }
        }
    }

    @Override
    public int getItemCount() {
        return mCategoryView.getPickerBitmaps().size();
    }

    /** Returns the number of times the cache supplied a bitmap. */
    public int getCacheHitCount() {
        return mCacheHits;
    }

    /** Returns the number of decode requests (cache-misses). */
    public int getDecodeRequestCount() {
        return mDecodeRequests;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Formatting;
using IBM.WatsonDeveloperCloud.Http.Filters;

namespace IBM.WatsonDeveloperCloud.Http
{
    public interface IClient : IDisposable
    {
        HttpClient BaseClient { get; }

        MediaTypeFormatterCollection Formatters { get; }

        List<IHttpFilter> Filters { get; }

        IClient WithAuthentication(string userName, string password);

        IRequest DeleteAsync(string resource);

        IRequest GetAsync(string resource);

        IRequest PostAsync(string resource);

        IRequest PostAsync<TBody>(string resource, TBody body);

        IRequest PutAsync(string resource);

        IRequest PutAsync<TBody>(string resource, TBody body);

        IRequest SendAsync(HttpMethod method, string resource);

        IRequest SendAsync(HttpRequestMessage message);
    }
}


text:
void Host_init();

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

extern PDMessageFuncs g_serviceMessageFuncs;
extern PDDialogFuncs g_dialogFuncs;


text:
<?php include('form.php'); ?>

The requested URL does not exist.


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Can. J. Bot. 46(3): 204 (1968)

#### Original name
Oidiodendron periconioides Morrall, 1968

### Remarks
null


text:
Houston Miller / @HueyTheDM / linkedin.com/in/houston-miller

  * Noticed similarities between D&D and software dev
  * What D&D has taught
    * Yes, and...
      * Trying new things
      * Working with other developers
    * Know when to speak up
      * You've been down the path before
      * Perfectionism
      * Premature optimization
    * When to keep quiet
      * Pair programming
      * Self-teaching moments
      * Nitpicking
    * Teamwork / Problem Solving
    * Communication through story telling
      * Underexplaining
      * Overexplaining
      * Missing out on important details
      * Re-explain things back to the customer
        * Clearly and concisely
  * Hobbies can influence your career (and vice versa)
    * Use to your advantage


text:
共有四种样式 `success`、`info`、`warning`、`error`。

```html
<template>
  <div class="alert-style">
    <avAlert type="success">Success Text</avAlert>
    <avAlert type="info">Info Text</avAlert>
    <avAlert type="warning">Warning Text</avAlert>
    <avAlert type="error">Error Text</avAlert>
  </div>
</template>

<script>
  import { avAlert } from 'antd-vue'

  export default {
    name: 'alert-style',
    components: { avAlert }
  }
</script>
```


text:
package org.apache.shindig.gadgets.http;

import com.google.common.base.Charsets;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shindig.common.util.CharsetUtil;
import org.apache.shindig.common.util.DateUtil;
import org.apache.shindig.gadgets.GadgetException;
import org.apache.shindig.gadgets.parse.GadgetHtmlParser;
import org.apache.shindig.gadgets.rewrite.MutableContent;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentFragment;

import java.nio.charset.Charset;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * Constructs HttpResponse objects.
 */
public class HttpResponseBuilder extends MutableContent {
  private int httpStatusCode = HttpResponse.SC_OK;
  private final Multimap<String, String> headers = HttpResponse.newHeaderMultimap();
  private final Map<String, String> metadata = Maps.newHashMap();

  // Stores the HttpResponse object, if any, from which this Builder is constructed.
  // This allows us to avoid creating a new HttpResponse in create() when no changes
  // have been made.
  private HttpResponse responseObj;
  private int responseObjNumChanges;

  public HttpResponseBuilder(GadgetHtmlParser parser, HttpResponse response) {
    super(parser, response);
    if (response != null) {
      httpStatusCode = response.getHttpStatusCode();
      headers.putAll(response.getHeaders());
      metadata.putAll(response.getMetadata());
    } else {
      setResponse(null);
    }
    responseObj = response;
    responseObjNumChanges = getNumChanges();
  }

  public HttpResponseBuilder() {
    this(unsupportedParser(), null);
  }

  public HttpResponseBuilder(HttpResponseBuilder builder) {
    this(unsupportedParser(), builder.create());
  }

  public HttpResponseBuilder(HttpResponse response) {
    this(unsupportedParser(), response);
  }

  /**
   * @return A new HttpResponse.
   */
  public HttpResponse create() {
    if (getNumChanges() != responseObjNumChanges || responseObj == null) {
      // Short-circuit the creation process: no need to create a
      // new (immutable) HttpResponse object when no modifications occurred.
      responseObj = new HttpResponse(this);
      responseObjNumChanges = getNumChanges();
    }
    return responseObj;
  }

  /**
   * @param body The response string.  Converted to UTF-8 bytes and copied when set.
   */
  public HttpResponseBuilder setResponseString(String body) {
    setContentBytes(CharsetUtil.getUtf8Bytes(body), Charsets.UTF_8);
    return this;
  }

  public HttpResponseBuilder setEncoding(Charset charset) {
    Collection<String> values = headers.get("Content-Type");
    if (!values.isEmpty()) {
      String contentType = values.iterator().next();
      StringBuilder newContentTypeBuilder = new StringBuilder("");
      // Remove previously set charset:
      String[] parts = StringUtils.split(contentType, ';');
      for (String part : parts) {
        if (!part.contains("charset=")) {
          if (newContentTypeBuilder.length() > 0) {
            newContentTypeBuilder.append("; ");
          }
          newContentTypeBuilder.append(part);
        }
      }
      if (charset != null) {
        if (newContentTypeBuilder.length() > 0) {
          newContentTypeBuilder.append("; ");
        }
        newContentTypeBuilder.append("charset=").append(charset.name());
      }
      values.clear();
      String newContentType = newContentTypeBuilder.toString();
      values.add(newContentType);
      if (!(values.size() == 1 && !contentType.equals(newContentType))) {
        incrementNumChanges();
      }
    }
    return this;
  }

  /**
   * @param responseBytes The response body. Copied when set.
   */
  public HttpResponseBuilder setResponse(byte[] responseBytes) {
    if (responseBytes == null) {
      responseBytes = ArrayUtils.EMPTY_BYTE_ARRAY;
    }
    byte[] newBytes = new byte[responseBytes.length];
    System.arraycopy(responseBytes, 0, newBytes, 0, responseBytes.length);
    setContentBytes(newBytes);
    return this;
  }

  /**
   * @param responseBytes The response body. Not copied when set.
   */
  public HttpResponseBuilder setResponseNoCopy(byte[] responseBytes) {
    if (responseBytes == null) {
      responseBytes = ArrayUtils.EMPTY_BYTE_ARRAY;
    }
    setContentBytes(responseBytes);
    return this;
  }

  public HttpResponseBuilder setHttpStatusCode(int httpStatusCode) {
    if (this.httpStatusCode != httpStatusCode) {
      this.httpStatusCode = httpStatusCode;
      incrementNumChanges();
    }
    return this;
  }

  public HttpResponseBuilder clearAllHeaders() {
    incrementNumChanges();
    headers.clear();
    return this;
  }

  public HttpResponseBuilder addHeader(String name, String value) {
    if (name != null) {
      headers.put(name, value);
      incrementNumChanges();
    }
    return this;
  }

  public HttpResponseBuilder setHeader(String name, String value) {
    if (name != null) {
      headers.replaceValues(name, Lists.newArrayList(value));
      incrementNumChanges();
    }
    return this;
  }

  public String getHeader(String name) {
    if (name != null && headers.containsKey(name)) {
      return headers.get(name).iterator().next();
    }
    return null;
  }

  public HttpResponseBuilder addHeaders(Map<String, String> headers) {
    for (Map.Entry<String,String> entry : headers.entrySet()) {
      this.headers.put(entry.getKey(), entry.getValue());
      incrementNumChanges();
    }
    return this;
  }

  public HttpResponseBuilder addAllHeaders(Map<String, ? extends List<String>> headers) {
    for (Map.Entry<String,? extends List<String>> entry : headers.entrySet()) {
      this.headers.putAll(entry.getKey(), entry.getValue());
      incrementNumChanges();
    }
    return this;
  }

  public Collection<String> removeHeader(String name) {
    Collection<String> ret = headers.removeAll(name);
    if (ret != null) {
      incrementNumChanges();
    }
    return ret;
  }

  public HttpResponseBuilder setCacheTtl(int cacheTtl) {
    headers.removeAll("Pragma");
    headers.removeAll("Expires");
    headers.replaceValues("Cache-Control", ImmutableList.of("public,max-age=" + cacheTtl));
    incrementNumChanges();
    return this;
  }

  public HttpResponseBuilder setExpirationTime(long expirationTime) {
    headers.removeAll("Cache-Control");
    headers.removeAll("Pragma");
    headers.put("Expires", DateUtil.formatRfc1123Date(expirationTime));
    incrementNumChanges();
    return this;
  }

  /**
   * Sets cache-control headers indicating the response is not cacheable.
   */
  private final List<String> NO_CACHE_HEADER = ImmutableList.of("no-cache");
  public HttpResponseBuilder setStrictNoCache() {
    headers.replaceValues("Cache-Control", NO_CACHE_HEADER);
    headers.replaceValues("Pragma", NO_CACHE_HEADER);
    headers.removeAll("Expires");
    incrementNumChanges();
    return this;
  }

  public HttpResponseBuilder setMetadata(String key, String value) {
    metadata.put(key, value);
    incrementNumChanges();
    return this;
  }

  public HttpResponseBuilder setMetadata(Map<String, String> metadata) {
    this.metadata.putAll(metadata);
    incrementNumChanges();
    return this;
  }

  public int getContentLength() {
    return getResponse().length;
  }

  Multimap<String, String> getHeaders() {
    return headers;
  }

  Map<String, String> getMetadata() {
    return metadata;
  }

  byte[] getResponse() {
    // Supported to avoid copying data unnecessarily.
    return getRawContentBytes();
  }

  public int getHttpStatusCode() {
    return httpStatusCode;
  }

  /**
   * Ensures that, when setting content bytes, the bytes' encoding is reflected
   * in the current Content-Type header.
   * Note, this method does NOT override existing Content-Type values if newEncoding is null.
   * This allows charset to be set by header only, along with a byte array -- a very typical,
   * and important, pattern when creating an HttpResponse in an HttpFetcher.
   */
  @Override
  protected void setContentBytesState(byte[] newBytes, Charset newEncoding) {
    super.setContentBytesState(newBytes, newEncoding);

    // Set the new encoding of the raw bytes, in order to ensure that
    // Content-Type headers are in sync w/ the content's encoding.
    if (newEncoding != null) setEncoding(newEncoding);
  }

  private static GadgetHtmlParser unsupportedParser() {
    return new GadgetHtmlParser(null) {
      @Override
      protected Document parseDomImpl(String source) throws GadgetException {
        throw new UnsupportedOperationException("Using HttpResponseBuilder in non-rewriting context");
      }

      @Override
      protected DocumentFragment parseFragmentImpl(String source)
          throws GadgetException {
        throw new UnsupportedOperationException("Using HttpResponseBuilder in non-rewriting context");
      }
    };
  }
}


text:
/*
 *
 * App constants
 *
 */

export const FREEZE_APP = 'app/App/FREEZE_APP';
export const LOAD_PLUGIN = 'app/App/LOAD_PLUGIN';
export const PLUGIN_LOADED = 'app/App/PLUGIN_LOADED';
export const PLUGIN_DELETED = 'app/App/PLUGIN_DELETED';
export const UNFREEZE_APP = 'app/App/UNFREEZE_APP';
export const UNSET_HAS_USERS_PLUGIN = 'app/App/UNSET_HAS_USERS_PLUGIN';
export const UPDATE_PLUGIN = 'app/App/UPDATE_PLUGIN';


text:
package net.catchpole.silicone.lang;

//   Copyright 2014 catchpole.net
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

import java.util.Iterator;

public class SingleIterator<T> implements Iterator<T> {
    private T value;
    private boolean hasNext = true;

    public SingleIterator(T value) {
        this.value = value;

    }

    @Override
    public boolean hasNext() {
        return hasNext;
    }

    @Override
    public T next() {
        hasNext = false;
        return value;
    }

    @Override
    public void remove() {
    }
}


text:
package io.datarouter.joblet;

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

import io.datarouter.joblet.enums.JobletStatus;
import io.datarouter.joblet.setting.DatarouterJobletSettingRoot;
import io.datarouter.joblet.storage.jobletrequest.DatarouterJobletRequestDao;
import io.datarouter.joblet.storage.jobletrequest.JobletRequest;
import io.datarouter.joblet.storage.jobletrequest.JobletRequestKey;
import io.datarouter.joblet.type.JobletType;
import io.datarouter.model.field.imp.StringEncodedField;
import io.datarouter.model.field.imp.StringField;
import io.datarouter.model.field.imp.comparable.BooleanField;
import io.datarouter.storage.node.type.physical.PhysicalNode;
import io.datarouter.storage.sql.Sql;

@Singleton
public class JobletRequestSqlBuilder{

	private static final StringEncodedField<JobletStatus> STATUS_CREATED_FIELD = new StringEncodedField<>(
			JobletRequest.FieldKeys.status, JobletStatus.CREATED);
	private static final StringEncodedField<JobletStatus> STATUS_RUNNING_FIELD = new StringEncodedField<>(
			JobletRequest.FieldKeys.status, JobletStatus.RUNNING);
	private static final BooleanField RESTARTABLE_FIELD = new BooleanField(JobletRequest.FieldKeys.restartable, true);

	private final DatarouterJobletSettingRoot datarouterJobletSettingRoot;
	private final DatarouterJobletRequestDao jobletRequestDao;

	private final String tableName;

	@Inject
	public JobletRequestSqlBuilder(
			DatarouterJobletSettingRoot datarouterJobletSettingRoot,
			DatarouterJobletRequestDao jobletRequestDao){
		this.datarouterJobletSettingRoot = datarouterJobletSettingRoot;
		this.jobletRequestDao = jobletRequestDao;
		PhysicalNode<?,?,?> physicalNode = jobletRequestDao.getPhysicalNode();
		this.tableName = physicalNode.getFieldInfo().getTableName();
	}

	public Sql<?,?,?> makeReserveJobletRequest(Sql<?,?,?> sql, JobletType<?> jobletType, String reservedBy){
		StringField reservedByField = new StringField(JobletRequest.FieldKeys.reservedBy, reservedBy);
		sql.addUpdateClause(tableName);
		sql.appendSqlNameValue(reservedByField, true);
		appendWhereClause(sql, jobletType);
		return sql;
	}

	public Sql<?,?,?> makeGetJobletRequest(Sql<?,?,?> sql, JobletType<?> jobletType){
		sql.addSelectFromClause(tableName, jobletRequestDao.getPhysicalNode().getFieldInfo().getFields());
		appendWhereClause(sql, jobletType);
		sql.append(" for update");//lock the row
		return sql;
	}

	private Sql<?,?,?> appendWhereClause(Sql<?,?,?> sql, JobletType<?> jobletType){
		sql.append(" where ");
		appendTypeClause(sql, jobletType);
		sql.append(" and ");
		appendStatusClause(sql);
		sql.append(" limit 1");
		return sql;
	}

	private void appendTypeClause(Sql<?,?,?> sql, JobletType<?> jobletType){
		StringField typeField = new StringField(JobletRequestKey.FieldKeys.type, jobletType.getPersistentString());
		sql.appendSqlNameValue(typeField, true);
	}

	private void appendStatusClause(Sql<?,?,?> sql){
		sql.append(" (")
				.appendSqlNameValue(STATUS_CREATED_FIELD, true)
				.append(" or ");
		appendStatusTimedOutClause(sql);
		sql.append(") ");
	}

	private void appendStatusTimedOutClause(Sql<?,?,?> sql){
		sql.append("(")
				.appendSqlNameValue(STATUS_RUNNING_FIELD, true)
				.append(" and ")
				.append(JobletRequest.FieldKeys.reservedAt.getColumnName())
				.append(" < ")
				.append(computeReservedBeforeMs().toString())
				.append(" and ")
				.appendSqlNameValue(RESTARTABLE_FIELD, true)
				.append(")");
	}

	private Long computeReservedBeforeMs(){
		return System.currentTimeMillis() - datarouterJobletSettingRoot.jobletTimeout.get().toMillis();
	}

}


text:
import { Model, BasicModel, ObjectModel, ArrayModel, FunctionModel, MapModel, SetModel, Any } from "../src/index"

export {
	Model,
	BasicModel,
	ObjectModel,
	ArrayModel,
	FunctionModel,
	MapModel,
	SetModel,
	Any
}


text:
include_recipe 'build-cookbook::_handler'

# Check the syntax on the cookbooks in cookbooks/
include_recipe 'delivery-truck::syntax'

execute 'syntax' do
  command "find . -name \\*.rb -exec ruby -c {} \\;"
  cwd node['delivery_builder']['repo']
  environment({
    "PATH" => '/opt/chefdk/embedded/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games'
  })
  user node['delivery_builder']['build_user']
end


text:
package consulo.roots.types;

import com.intellij.openapi.roots.OrderRootType;
import javax.annotation.Nonnull;

/**
 * @author VISTALL
 * @since 17.08.14
 */
public class DocumentationOrderRootType extends OrderRootType {
  @Nonnull
  public static DocumentationOrderRootType getInstance() {
    return getOrderRootType(DocumentationOrderRootType.class);
  }

  public DocumentationOrderRootType() {
    super("documentation");
  }
}


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

<TITLE>
IndexJoinPlan
</TITLE>

<META NAME="date" CONTENT="2008-07-30">

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

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

simpledb.index.query

Class IndexJoinPlan

java.lang.Object
  simpledb.index.query.IndexJoinPlan

All Implemented Interfaces:
Plan

public class IndexJoinPlan
extends java.lang.Object
implements Plan

The Plan class corresponding to the indexjoin
 relational algebra operator.

Author:

Edward Sciore

Constructor Summary

IndexJoinPlan(Plan p1,
              Plan p2,
              IndexInfo ii,
              java.lang.String joinfield,
              Transaction tx)

          Implements the join operator,
 using the specified LHS and RHS plans.

Method Summary

 int
blocksAccessed()

          Estimates the number of block accesses to compute the join.

 int
distinctValues(java.lang.String fldname)

          Estimates the number of distinct values for the
 specified field.

 Scan
open()

          Opens an indexjoin scan for this query

 int
recordsOutput()

          Estimates the number of output records in the join.

 Schema
schema()

          Returns the schema of the index join.

Methods inherited from class java.lang.Object

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

Constructor Detail

IndexJoinPlan

public IndexJoinPlan(Plan p1,
                     Plan p2,
                     IndexInfo ii,
                     java.lang.String joinfield,
                     Transaction tx)

Implements the join operator,
 using the specified LHS and RHS plans.

Parameters:
p1 - the left-hand plan
p2 - the right-hand plan
ii - information about the right-hand index
joinfield - the left-hand field used for joining
tx - the calling transaction

Method Detail

open

public Scan open()

Opens an indexjoin scan for this query

Specified by:
open in interface Plan

Returns:
a scan
See Also:
Plan.open()

blocksAccessed

public int blocksAccessed()

Estimates the number of block accesses to compute the join.
 The formula is:

 B(indexjoin(p1,p2,idx)) = B(p1) + R(p1)*B(idx)
       + R(indexjoin(p1,p2,idx)

Specified by:
blocksAccessed in interface Plan

Returns:
the estimated number of block accesses
See Also:
Plan.blocksAccessed()

recordsOutput

public int recordsOutput()

Estimates the number of output records in the join.
 The formula is:

 R(indexjoin(p1,p2,idx)) = R(p1)*R(idx)

Specified by:
recordsOutput in interface Plan

Returns:
the estimated number of output records
See Also:
Plan.recordsOutput()

distinctValues

public int distinctValues(java.lang.String fldname)

Estimates the number of distinct values for the
 specified field.

Specified by:
distinctValues in interface Plan

Parameters:
fldname - the name of a field

Returns:
the estimated number of distinct field values in the output
See Also:
Plan.distinctValues(java.lang.String)

schema

public Schema schema()

Returns the schema of the index join.

Specified by:
schema in interface Plan

Returns:
the query's schema
See Also:
Plan.schema()

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
#ifndef RMLUI_SHELL_INPUT_H
#define RMLUI_SHELL_INPUT_H

#include <RmlUi/Core/Input.h>
#include <RmlUi/Core/Types.h>

class Input
{
public:
	/// Sets the context to send input events to.
	/// @param[in] context The context to send input events to.
	static void SetContext(Rml::Context* context);
	/// Returns the character code for a key identifer / key modifier combination.
	/// @param[in] key_identifier The key to generate a character code for.
	/// @param[in] key_modifier_state The configuration of the key modifiers.
	/// @return The character code.
	static Rml::Character GetCharacterCode(Rml::Input::KeyIdentifier key_identifier, int key_modifier_state);

protected:
	static Rml::Context* context;
};

#endif