text:
package com.beiing.library;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import static android.widget.LinearLayout.HORIZONTAL;

/**
 * Created by chenliu on 2017/3/9.<br/>
 * 描述:
 * </br>
 */

public class MultipleMenu extends RelativeLayout implements View.OnClickListener {

    /**
     * tab所在layout
     */
    private LinearLayout tabHolderView;

    /**
     * menu所在layout
     */
    private FrameLayout menuHolderView;

    /**
     * tabHolderView下划线
     */
    private View underLineView;

    /**
     * 菜单下部阴影
     */
    private View maskView;

    /**
     * 属性
     */
    private Config config;

    /**
     * tab集合
     */
    private List<View> tabList;

    /**
     * menu: tabtitle和对应view
     */
    private List<MenuPage> menuPages;

    private final static int INVALID_POSITION = -1;

    /**
     * 当前打开的菜单位置
     */
    private int currentPosition = INVALID_POSITION;

    private Animation iconOutAnimation;
    private Animation iconInAnimation;
    private Animation menuOutAnimation;
    private Animation menuInAnimation;

    private static final int GRAVITY_TOP = 0;
    private static final int GRAVITY_BOTTOM = 1;

    public MultipleMenu(Context context) {
        this(context, null, 0);
    }

    public MultipleMenu(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MultipleMenu(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        initAttrs(context, attrs);

        initView(context);

        initAnimation(context);
    }

    private void initAttrs(Context context, @Nullable AttributeSet attrs) {
        config = new Config();
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MultipleMenu);
        try {
            config.tabHolderHeight = ta.getDimensionPixelSize(R.styleable.MultipleMenu_mm_tabHolderHeight, dp2px(48));
            config.tabHolderColor = ta.getColor(R.styleable.MultipleMenu_mm_tabHolderColor, 0xffffffff);
            config.underLineHeight = ta.getDimensionPixelSize(R.styleable.MultipleMenu_mm_underLineHeight, dp2px(0.6f));
            config.underLineColor = ta.getColor(R.styleable.MultipleMenu_mm_underLineColor, 0xffe0e0e0);
            config.tabTitleDefaultColor = ta.getColor(R.styleable.MultipleMenu_mm_tabTitleDefaultColor, 0xff252525);
            config.tabTitletSelectedColor = ta.getColor(R.styleable.MultipleMenu_mm_tabTitletSelectedColor, 0xff5da6f0);
            config.tabTitleDefaultSize = ta.getDimensionPixelSize(R.styleable.MultipleMenu_mm_tabTitleDefaultSize, 14);
            config.tabTitleSelectedSize = ta.getDimensionPixelSize(R.styleable.MultipleMenu_mm_tabTitleSelectedSize, 14);
            config.tabIconDefault = ta.getResourceId(R.styleable.MultipleMenu_mm_tabIconDefault, R.mipmap.tab_icon_default);
            config.tabIconSelected = ta.getResourceId(R.styleable.MultipleMenu_mm_tabIconSelected, R.mipmap.tab_icon_selected);
            config.tabIconLeftmargin = ta.getDimensionPixelSize(R.styleable.MultipleMenu_mm_tabIconLeftmargin, dp2px(6));
            config.dividerWidth = ta.getDimensionPixelSize(R.styleable.MultipleMenu_mm_dividerWidth, dp2px(0.6f));
            config.dividerTopmargin = ta.getDimensionPixelSize(R.styleable.MultipleMenu_mm_dividerTopmargin, dp2px(8));
            config.dividerBottommargin = ta.getDimensionPixelSize(R.styleable.MultipleMenu_mm_dividerBottommargin, dp2px(8));
            config.dividerColor = ta.getColor(R.styleable.MultipleMenu_mm_dividerColor, 0xffe0e0e0);
            config.maskColor = ta.getColor(R.styleable.MultipleMenu_mm_maskColor, 0x40000000);
            config.tabGravity = ta.getInteger(R.styleable.MultipleMenu_mm_tabGravity, GRAVITY_TOP);
            config.menuAnimateIn = ta.getResourceId(R.styleable.MultipleMenu_mm_menuAnimateIn, R.anim.scale_in_from_top);
            config.menuAnimateOut = ta.getResourceId(R.styleable.MultipleMenu_mm_menuAnimateOut, R.anim.scale_out_fom_top);
        } finally {
            ta.recycle();
        }
    }

    private void initView(Context context) {
        //初始化view
        tabHolderView = new LinearLayout(context);
        tabHolderView.setId(R.id.mm_tabholder_id);
        LayoutParams tabHolderParams = new LayoutParams(LayoutParams.MATCH_PARENT, config.tabHolderHeight);
        tabHolderParams.addRule(config.tabGravity == GRAVITY_TOP ? RelativeLayout.ALIGN_PARENT_TOP :RelativeLayout.ALIGN_PARENT_BOTTOM);
        tabHolderView.setLayoutParams(tabHolderParams);
        tabHolderView.setOrientation(HORIZONTAL);
        tabHolderView.setGravity(Gravity.CENTER);
        tabHolderView.setBackgroundColor(config.tabHolderColor);

        underLineView = new View(context);
        underLineView.setId(R.id.mm_underline_id);
        LayoutParams underLineParams = new LayoutParams(LayoutParams.MATCH_PARENT, config.underLineHeight);
        underLineParams.addRule(config.tabGravity == GRAVITY_TOP ? RelativeLayout.BELOW : RelativeLayout.ABOVE, R.id.mm_tabholder_id);
        underLineView.setLayoutParams(underLineParams);
        underLineView.setBackgroundColor(config.underLineColor);

        menuHolderView = new FrameLayout(context);
        LayoutParams menuHolderParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        menuHolderParams.addRule(config.tabGravity == GRAVITY_TOP ? RelativeLayout.BELOW : RelativeLayout.ABOVE, R.id.mm_underline_id);
        menuHolderView.setLayoutParams(menuHolderParams);

        maskView = new View(context);
        maskView.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        maskView.setBackgroundColor(config.maskColor);
        maskView.setOnClickListener(this);
        addView(maskView);

        //添加view
        addView(tabHolderView);
        addView(underLineView);
        addView(menuHolderView);
    }

    private void initAnimation(Context context) {
        iconInAnimation = AnimationUtils.loadAnimation(context, R.anim.rotate_up);
        iconOutAnimation = AnimationUtils.loadAnimation(context, R.anim.rotate_down);
        menuInAnimation = AnimationUtils.loadAnimation(context, config.menuAnimateIn);
        menuOutAnimation = AnimationUtils.loadAnimation(context, config.menuAnimateOut);
    }

    public void setMultipleMenu(List<MenuPage> menuPages){
        if(menuPages.isEmpty()) return;

        this.menuPages = menuPages;
        tabList = new ArrayList<>(menuPages.size());

        LayoutInflater inflater = LayoutInflater.from(getContext());
        for (int i = 0, size = menuPages.size(); i < size; i++) {
            MenuPage mp = menuPages.get(i);
            addTab(mp.getMenuTitle(), inflater, i);
            if(i != size - 1){
                addDivider();
            }
            addMenuView(mp.getMenuView());
        }

        maskView.setVisibility(GONE);
        menuHolderView.setVisibility(GONE);
    }

    /**
     * 添加tab菜单
     * @param menuTitle
     * @param inflater
     * @param position
     */
    private void addTab(String menuTitle, LayoutInflater inflater, int position) {
        View itemTab = inflater.inflate(R.layout.item_tab_layout, tabHolderView, false);
        ItemTabHolder itemTabHolder = new ItemTabHolder(itemTab, position);
        itemTabHolder.setTitleText(menuTitle)
                .setTitleTextSize(config.tabTitleDefaultSize)
                .setTitleTextColor(config.tabTitleDefaultColor)
                .setIconResource(config.tabIconDefault);
        final LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        lp.leftMargin = config.tabIconLeftmargin;
        itemTabHolder.tvIcon.setLayoutParams(lp);
        itemTab.setTag(itemTabHolder);
        itemTab.setOnClickListener(this);
        tabHolderView.addView(itemTab);
        tabList.add(itemTab);
    }

    /**
     * 添加tab菜单间隔线
     */
    private void addDivider() {
        View view = new View(getContext());
        final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(config.dividerWidth, LinearLayout.LayoutParams.MATCH_PARENT);
        params.topMargin = config.dividerTopmargin;
        params.bottomMargin = config.dividerBottommargin;
        view.setLayoutParams(params);
        view.setBackgroundColor(config.dividerColor);
        tabHolderView.addView(view);
    }

    /**
     * 添加单页菜单
     * @param menuView
     */
    private void addMenuView(View menuView) {
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.gravity = config.tabGravity == GRAVITY_TOP ? Gravity.TOP : Gravity.BOTTOM;
        menuView.setLayoutParams(params);
        menuView.setVisibility(GONE);
        menuHolderView.addView(menuView);
    }

    @Override
    public void onClick(View v) {
        if(v == maskView){
            closeMenu();
        } else {
            switchMenu(v);
        }
    }

    /**
     * 关闭菜单
     */
    public void closeMenu() {
        if(currentPosition != INVALID_POSITION){
            //tab状态改变
            View itemTab = tabList.get(currentPosition);
            ItemTabHolder itemHolder = (ItemTabHolder) itemTab.getTag();
            if (itemHolder != null) {
                itemHolder.setTitleTextSize(config.tabTitleDefaultSize)
                            .setTitleTextColor(config.tabTitleDefaultColor)
                            .setIconResource(config.tabIconDefault);

                //icon动画
                itemHolder.tvIcon.startAnimation(iconOutAnimation);
            }

            //动画退出
            final View menuView = menuHolderView.getChildAt(currentPosition);
            menuOutAnimation.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {

                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    menuView.setVisibility(GONE);
                    maskView.setVisibility(GONE);
                    menuHolderView.setVisibility(GONE);
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });

            menuHolderView.startAnimation(menuOutAnimation);
            currentPosition = INVALID_POSITION;
            changeMaskView(1f, 0);
        }

    }

    /**
     * 打开指定位置menu
     * @param position
     */
    private void openMenu(int position) {
        View itemTab = tabList.get(position);
        ItemTabHolder itemHolder = (ItemTabHolder) itemTab.getTag();
        if (itemHolder != null) {
            itemHolder.setTitleTextSize(config.tabTitleSelectedSize)
                    .setTitleTextColor(config.tabTitletSelectedColor)
                    .setIconResource(config.tabIconSelected);

            //icon动画
            itemHolder.tvIcon.startAnimation(iconInAnimation);
        }

        for (MenuPage page :
                menuPages) {
            page.getMenuView().setVisibility(GONE);
        }

        //动画进入
        menuHolderView.setVisibility(VISIBLE);
        maskView.setVisibility(VISIBLE);
        menuHolderView.getChildAt(position).setVisibility(VISIBLE);
        menuHolderView.startAnimation(menuInAnimation);
        currentPosition = position;

        changeMaskView(0, 1f);
    }

    private void changeMaskView(float alpha1, float alpha2) {
        ValueAnimator valueAnimator = ObjectAnimator.ofFloat(alpha1, alpha2).setDuration(menuInAnimation.getDuration());
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                maskView.setAlpha((Float) animation.getAnimatedValue());
            }
        });
        valueAnimator.start();
    }

    /**
     * 切换menu
     * @param selectV
     */
    private void switchMenu(View selectV){
        ItemTabHolder itemHolder = (ItemTabHolder) selectV.getTag();
        if(itemHolder.position == currentPosition){
            closeMenu();
        } else {
            closeMenu();
            openMenu(itemHolder.position);
        }
    }

    public void setTabTitle(String text){
        if(currentPosition != INVALID_POSITION){
            setTbaTitle(currentPosition, text);
        }
    }

    public void setTbaTitle(int position, String text){
        if(position >= 0 && position < tabList.size()){
            View itemTab = tabList.get(currentPosition);
            ItemTabHolder itemHolder = (ItemTabHolder) itemTab.getTag();
            if (itemHolder != null) {
                itemHolder.setTitleText(text);
            }
        } else {
            throw new IndexOutOfBoundsException();
        }
    }

    public int dp2px(float value) {
        DisplayMetrics dm = getResources().getDisplayMetrics();
        return (int) (TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, dm) + 0.5);
    }

    private class Config{
        /**
         * tab所在layout高度,必填
         */
        int tabHolderHeight;

        /**
         * tablayout背景色
         */
        int tabHolderColor;

        /**
         * tablayout底部线条
         */
        int underLineHeight;

        /**
         * tablayout底部线条颜色
         */
        int underLineColor;

        /**
         * tabtitle默认颜色
         */
        int tabTitleDefaultColor;

        /**
         * tabtitle选中颜色
         */
        int tabTitletSelectedColor;

        /**
         * tab默认字体大小
         */
        int tabTitleDefaultSize;

        /**
         * tab选中大小
         */
        int tabTitleSelectedSize;

        /**
         * tab未选中时icon
         */
        int tabIconDefault;

        /**
         * tab选中时icon
         */
        int tabIconSelected;

        /**
         * icon左边距
         */
        int tabIconLeftmargin;

        /**
         * tab 间隔线宽度
         */
        int dividerWidth;

        /**
         * tab 间隔线上边距
         */
        int dividerTopmargin;

        /**
         * tab 间隔线下边距
         */
        int dividerBottommargin;

        /**
         * tab 间隔线颜色
         */
        int dividerColor;

        /**
         * 阴影颜色
         */
        int maskColor;

        /**
         * menu进入动画
         */
        int menuAnimateIn;

        /**
         * menu退出动画
         */
        int menuAnimateOut;

        /**
         * tabholder显示位置:top  or  bottom
         */
        private int tabGravity;
    }

    public static class MenuPage{
        private String menuTitle;
        private View menuView;

        public MenuPage(String menuTitle, View menuView) {
            this.menuTitle = menuTitle;
            this.menuView = menuView;
        }

        public MenuPage() {
        }

        public String getMenuTitle() {
            return menuTitle;
        }

        public void setMenuTitle(String menuTitle) {
            this.menuTitle = menuTitle;
        }

        public View getMenuView() {
            return menuView;
        }

        public void setMenuView(View menuView) {
            this.menuView = menuView;
        }
    }

    private class ItemTabHolder{
        TextView tvTitle;
        ImageView tvIcon;
        int position;

        ItemTabHolder(View layout, int position){
            tvTitle = (TextView) layout.findViewById(R.id.tv_tab_title);
            tvIcon = (ImageView) layout.findViewById(R.id.iv_tab_icon);
            this.position = position;
        }

        ItemTabHolder setTitleText(String text){
            tvTitle.setText(text);
            return this;
        }

        ItemTabHolder setTitleTextColor(int color){
            tvTitle.setTextColor(color);
            return this;
        }

        ItemTabHolder setTitleTextSize(int size){
            tvTitle.setTextSize(TypedValue.COMPLEX_UNIT_PX, size);
            return this;
        }

        ItemTabHolder setIconResource(int res){
            tvIcon.setImageResource(res);
            return this;
        }

    }

}


text:
phpunit --process-isolation --filter testBalanceIsInitiallyZero BankAccountTest ../_files/BankAccountTest.php
--FILE--
<?php
$_SERVER['argv'][1] = '--no-configuration';
$_SERVER['argv'][2] = '--process-isolation';
$_SERVER['argv'][3] = '--filter';
$_SERVER['argv'][4] = 'testBalanceIsInitiallyZero';
$_SERVER['argv'][5] = 'BankAccountTest';
$_SERVER['argv'][6] = dirname(__FILE__).'/../_files/BankAccountTest.php';

require_once dirname(dirname(dirname(__FILE__))) . '/PHPUnit/Autoload.php';
PHPUnit_TextUI_Command::main();
?>
--EXPECTF--
PHPUnit %s by Sebastian Bergmann.

.

Time: %i %s, Memory: %sMb

OK (1 test, 1 assertion)

redpajama_set_name: RedPajamaGithub


text:
    Arrival Condition

Seat

			<input value="na" type="checkbox">Seat not installed

			<input class="arrival-seat-row1 arrival-seat-col2" name="arrival-seat-pos" value="1" type="radio">
			<input class="arrival-seat-row1 arrival-seat-col3" name="arrival-seat-pos" value="2" type="radio">
			<input class="arrival-seat-row2 arrival-seat-col1" name="arrival-seat-pos" value="3" type="radio">
			<input class="arrival-seat-row2 arrival-seat-col2" name="arrival-seat-pos" value="4" type="radio">
			<input class="arrival-seat-row2 arrival-seat-col3" name="arrival-seat-pos" value="5" type="radio">
			<input class="arrival-seat-row3 arrival-seat-col1" name="arrival-seat-pos" value="6" type="radio">
			<input class="arrival-seat-row3 arrival-seat-col2" name="arrival-seat-pos" value="7" type="radio">
			<input class="arrival-seat-row3 arrival-seat-col3" name="arrival-seat-pos" value="8" type="radio">

			<input value="ff" type="radio">Forward Facing
			<select>
				<option value="Unknown" selected>---</option>
				<option value="ca">Correct Angle</option>
				<option value="or" >Over Reclined</option>
				<option value="tu">Too Upright</option>
			</select>

			<input value="rf" type="radio" checked="checked">Rear Facing
			<select>
				<option value="Unknown" selected>---</option>
				<option value="ca">Correct Angle</option>
				<option value="or" >Over Reclined</option>
				<option value="tu">Too Upright</option>
			</select>

			<input value="b" type="radio">Booster

			<input value="snug" type="checkbox">Handle Position Correct (infant only)

Harness/Belt Fit

			Child in seat:

			<input value="Yes" type="radio" checked="checked">Yes
			<input value="No" type="radio">No

			Harness snug:

			<input value="Yes" type="radio">Yes
			<input value="No" type="radio">No
			<input value="Unknown" type="radio" checked="checked">Unknown

			Correct slots:

			<input value="Yes" type="radio">Yes
			<input value="No" type="radio">No
			<input value="Unknown" type="radio" checked="checked">Unknown

			Straps flat:

			<input value="Yes" type="radio">Yes
			<input value="No" type="radio">No
			<input value="Unknown" type="radio" checked="checked">Unknown

			Chest clip at armpits:

			<input value="Yes" type="radio">Yes
			<input value="No" type="radio">No
			<input value="Unknown" type="radio" checked="checked">Unknown

			Correct fit (booster):

			<input value="Yes" type="radio">Yes
			<input value="No" type="radio">No
			<input value="Unknown" type="radio" checked="checked">Unknown

Tether

			Choose:
			<select>
				<option value="Unknown" selected="">...</option>
				<option value="na">N/A</option>
				<option value="ac">Attached, correct anchor</option>
				<option value="ai">Attached, incorrect anchor</option>
				<option value="no">Not attached, anchor available</option>
				<option value="nn">Not attached, no anchor available</option>
				<option value="nl">Not attached, loose/dangling</option>
			</select>

			Routed Correctly:

			<input value="Yes" type="radio">Yes
			<input value="No" type="radio">No
			<input value="Unknown" type="radio" checked="checked">Unknown

			Tight:

			<input value="Yes" type="radio">Yes
			<input value="No" type="radio">No
			<input value="Unknown" type="radio" checked="checked">Unknown

Seat Belt System/UAS

			Installed with:
			<select>
				<option value="Unknown" selected>---</option>
				<option value="seatbelt">Seatbelt</option>
				<option value="uas">UAS</option>
				<option value="both" >Both</option>
			</select>

			 Seatbelt System:
			<select>
				<option value="eas" selected>ELR/ALR switchable</option>
				<option value="elr">ELR</option>
				<option value="alr">ALR</option>
				<option value="ll" >Locking latchplate</option>
				<option value="cl">Cinchable latchplate</option>
			</select>

			Belt Type:
			<select>
				<option value="ls" selected>Lap/shoulder belts</option>
				<option value="lo">Lap belt only</option>
			</select>

			Routed correctly:

			<input value="Yes" type="radio">Yes
			<input value="No" type="radio" checked="checked">No

			Tight (less than 1" movement):

			<input value="Yes" type="radio">Yes
			<input value="No" type="radio" checked="checked">No

			Seat belt locked:

			<input value="Yes" type="radio">Yes
			<input value="No" type="radio" checked="checked">No

			Locking clip used:
			<select>
				<option value="Unknown" selected="Unknown">Choose...</option>
				<option value="yc">Yes, used correctly</option>
				<option value="yi">Yes, used incorrectly</option>
				<option value="nr" >No, but required</option>
				<option value="nn">No, not necessary</option>
			</select>

			Restraint lock offs used:
			<select>
				<option value="Unknown" selected>Choose...</option>
				<option value="na">Not Applicable</option>
				<option value="yc">Yes, used correctly</option>
				<option value="yi">Yes, used incorrectly</option>
				<option value="nr" >No, but required</option>
				<option value="nn">No, not required</option>
			</select>


text:
cask 'musaicfm' do
  version '1.1.4'
  sha256 '1f3b1b52b18be3c012a7646d66b694bb77cdc705a887820e333d94a74ed1bd77'

  url "https://github.com/docterd/MusaicFM/releases/download/#{version}/MusaicFM.saver.zip"
  appcast 'https://github.com/docterd/MusaicFM/releases.atom'
  name 'MusaicFM Screensaver'
  homepage 'https://github.com/docterd/MusaicFM'

  screen_saver 'MusaicFM.saver'
end


text:
package com.phpdragon.jms;

import com.phpdragon.jms.mq.MqSender;
import com.phpdragon.jms.task.SendTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class App {

    public static final String DEFAULT_CONFIG_LOCATION = "/spring-context.xml";

    @Autowired
    private MqSender mqSender;

    /**
     * 程序入口
     *
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        ApplicationContext context = new ClassPathXmlApplicationContext(DEFAULT_CONFIG_LOCATION);
        App application = (App) context.getBean("app");
        application.run(args);
    }

    public void run(String[] args) {
        Thread thread = new Thread(new SendTask(mqSender));
        thread.start();
    }
}


text:
/**
 * output example:
 *
My-Custom-Header: custom_header_content
Content-Type: multipart/related; boundary="MultipartistBoundary5769293611663"
Content-Length: number_of_bytes_in_entire_request_body

--MultipartistBoundary5769293611663
Content-Type: application/json; charset=UTF-8

<PART-CONTENT>

--MultipartistBoundary5769293611663
Content-Type: image/jpeg

<JPEG data>

--MultipartistBoundary5769293611663--
 *
 */

import { Readable } from 'stream';
import debug from 'debug';

const PADDING = '--';
const CRLF = '\r\n';
const CRLF_BUFFER = Buffer.from(CRLF);

const dbg = debug('multipartist');

export default class Multipartist extends Readable {

  chunks = [];
  contentLengthKnown = true;

  _currentStream = null;

  _holdByEmpty = false;
  _aboutToFlush = 0;  // 0=no, 1=flushing, 2=flushed

  constructor(type = 'form-data', { endOnEmpty, ...options } = {}) {
    super(options);
    this.type = type;
    this.endOnEmpty = endOnEmpty !== false;
    this.boundary = boundary();
    this.ending = ending(this.boundary);
    this.contentLength = this.ending.length;
    dbg('generated boundary %s', this.boundary);
    dbg('generated ending %s', this.ending.toString());
  }

  append(content, length, headers) {
    if (typeof length != 'number') {
      headers = length;
      length = null;
    }

    headers = { ...headers };

    dbg('part headers %O', headers);

    if (content instanceof Readable) {
      content.pause();
      if (!length) {
        this.contentLengthKnown = false;
      }
      dbg('part content: Readable, length = %d', length);
    } else if (typeof content == 'string') {
      content = Buffer.from(content);
      length = content.length;
      dbg('part content: String -> Buffer, length = %d', length);
    } else if (Buffer.isBuffer(content)) {
      length = content.length;
      dbg('part content: Buffer, length = %d', length);
    } else {
      throw new Error('Content of part must be a Readable, String or Buffer');
    }

    const header = leading(this.boundary, headers);

    this.contentLength += header.length + CRLF_BUFFER.length;
    this.contentLength += length + CRLF_BUFFER.length;

    this.chunks.push(header);
    this.chunks.push(CRLF_BUFFER);
    this.chunks.push(content);
    this.chunks.push(CRLF_BUFFER);

    if (this._holdByEmpty) {
      dbg('_read() is hold, calling it to resume');
      this._holdByEmpty = false;
      this._read();
    }
  }

  headers(additions) {
    const headers = {
      'Content-Type': `multipart/${this.type}; boundary="${this.boundary}"`,
    };

    if (this.contentLengthKnown && this.endOnEmpty) {
      headers['Content-Length'] = `${this.contentLength}`;
    }

    dbg('generated headers %O', headers);
    dbg('additional headers %O', additions);

    return {
      ...headers,
      ...additions,
    };
  }

  flush() {
    dbg('about to flush');
    this._aboutToFlush = 1;
    if (this._holdByEmpty) {
      dbg('_read() is hold, calling it to flush');
      this._holdByEmpty = false;
      this._read();
    }
  }

  _read() {
    if (this._currentStream) {
      this._readStream();
      return;
    }

    if (this.chunks.length == 0) {
      if (this.endOnEmpty) {
        dbg('ending by empty');
        this.push(this.ending);
        this.push(null);
        return;
      } else {
        switch (this._aboutToFlush) {
          case 0: // not flush
            dbg('empty, hold on _read()');
            this._holdByEmpty = true;
            return;
          case 1: // about to flushing
            dbg('ending by flush');
            this._aboutToFlush = 2;
            this.push(this.ending);
            this.push(null);
            return;
          case 2: // flushed
            dbg('since flush push() twice. dont care~');
            return;
        }
      }
    }

    const chunk = this.chunks.shift();
    if (chunk instanceof Readable) {
      dbg('start streaming');
      this._startStream(chunk);
    } else {
      dbg('push chunk: %d', chunk.length);
      this.push(chunk);
    }
  }

  _startStream(stream) {
    this._currentStream = stream;

    stream.on('readable', () => {
      this._readStream();
    });

    stream.on('end', () => {
      dbg('stream end');
      this._currentStream = null;
      this._read();
    });
  }

  _readStream() {
    const stream = this._currentStream;
    const chunk = stream.read();
    if (chunk != null) {
      this.push(chunk);
    }
  }

}

function boundary() {
  var boundary = '--------------------------';

  for (let i = 0; i < 25; i++) {
    boundary += Math.floor(Math.random() * 10).toString(16);
  }

  return boundary;
}

function leading(boundary, headers) {
  var leading = [`${PADDING}${boundary}`];

  Object.keys(headers).forEach(function (key) {
    leading.push(`${key}: ${headers[key]}`);
  });

  return Buffer.from(`${leading.join(CRLF)}${CRLF}`);
}

function ending(boundary) {
  return Buffer.from(`${PADDING}${boundary}${PADDING}${CRLF}`);
}


text:
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User

#from timebank.currency.models import Currency

class Theme(models.Model):
    name = models.CharField(max_length=255)
    def __unicode__(self):
        return self.name

class Service(models.Model):
    created_date  = models.DateTimeField(auto_now_add=True,editable=False,default=None,null=True,blank=True)
    changed  = models.DateTimeField(auto_now=True,editable=False,default=None,null=True,blank=True)
    owner = models.ForeignKey(User)
    published = models.BooleanField()
    auth = models.IntegerField(default=0,choices=((-1,_('Inappropriate')),
                                                  (0,_('New')),
                                                  (1,_('Authorized')),
                                                  (2,_('Edited')),
                                                  ))
    theme=models.ForeignKey(Theme)
    title = models.CharField(max_length=255)
    description = models.TextField(null=True,blank=True)
    minutes = models.IntegerField(default=60,null=True,blank=True)
    min_minutes = models.IntegerField(default=30,null=True,blank=True)
    max_minutes = models.IntegerField(default=90,null=True,blank=True)
    location = models.CharField(max_length=255,null=True,blank=True)
    #currency = models.ForeignKey(Currency,null=True,blank=True)
    cost = models.IntegerField(default=1,null=True,blank=True)
    def __unicode__(self):
        return "%s:%s"%(self.theme, self.title)

    #class Meta:
        #abstract= True
        #ordering = ['weight','id']
        #db_table = 'mockup_content_item'
        #app_label = "services"


text:
+----------+-------------------+
| hr1420   | R Documentation   |
+----------+-------------------+

An example data for Manhattan plot with annotation
--------------------------------------------------

Description
~~~~~~~~~~~

This example contains p values for a list of SNPs wtih information on
chromosome, position and gene symnol.

In the reference below, seven established SNPs are in light blue, 14 new
SNPs in dark blue and those failed to replicate in red. The paper size
is set to 189 width x 189/2 height (mm) and 1200 dpi resolution. The
font is Verdana. See ``mhtplot2`` for all the details.

Usage
~~~~~

::

    data(hr1420)

Format
~~~~~~

A data frame

Source
~~~~~~

Dr Marcel den Hoed at the MRC Epidemiology Unit

References
~~~~~~~~~~

de Hoed M et al. (2013) Heart rate-associated loci and their effects on
cardiac conduction and rhythm disorders. Nature Genetics


text:
<?php

class oracle_timeout
{
	private $mode = '';

	public function set_mode($mode)
	{
		$this->mode = $mode;
	}

	public function process()
	{
		if ( $this->init() )
        {

            return $this->display();
        }
        return false;
	}

	private function init()
	{
		// cette carte ne sert qu'à afficher la page de timeout et à calculer les scores si besoin
		return true;
	}

	private function display()
	{
		include('./views/oracle.timeout.html');
        return true;
	}
}

?>


text:
package org.apache.horn.examples;

import java.io.IOException;

import org.apache.hama.HamaConfiguration;
import org.apache.horn.core.Constants.TrainingMethod;
import org.apache.horn.core.HornJob;
import org.apache.horn.core.RecurrentLayeredNeuralNetwork;
import org.apache.horn.funcs.CrossEntropy;
import org.apache.horn.funcs.SoftMax;
import org.apache.horn.funcs.Tanh;

public class MnistRecurrentMultiLayerPerceptron {

  public static HornJob createJob(HamaConfiguration conf, String modelPath,
      String inputPath, float learningRate, float momemtumWeight,
      float regularizationWeight, int features, int hu, int labels,
      int stepSize, int numOutCells, int miniBatch, int maxIteration)
          throws IOException, InstantiationException, IllegalAccessException {

    boolean isRecurrent = (stepSize == 1 ? false: true);

    HornJob job = new HornJob(
        conf, RecurrentLayeredNeuralNetwork.class, MnistRecurrentMultiLayerPerceptron.class);
    job.setTrainingSetPath(inputPath);
    job.setModelPath(modelPath);

    job.setMaxIteration(maxIteration);
    job.setLearningRate(learningRate);
    job.setMomentumWeight(momemtumWeight);
    job.setRegularizationWeight(regularizationWeight);

    job.setConvergenceCheckInterval(10);
    job.setBatchSize(miniBatch);
    job.setRecurrentStepSize(stepSize);

    job.setTrainingMethod(TrainingMethod.GRADIENT_DESCENT);

    job.inputLayer(features, 1.0f); // droprate
    job.addLayer(hu, Tanh.class, RecurrentDropoutNeuron.class, isRecurrent);
    job.outputLayer(labels, SoftMax.class, RecurrentDropoutNeuron.class, numOutCells);

    job.setCostFunction(CrossEntropy.class);

    return job;
  }

  public static void main(String[] args) throws IOException,
      InterruptedException, ClassNotFoundException,
      NumberFormatException, InstantiationException, IllegalAccessException {

    if (args.length < 9) {
      System.out.println("Usage: <MODEL_PATH> <INPUT_PATH> "
          + "<LEARNING_RATE> <MOMEMTUM_WEIGHT> <REGULARIZATION_WEIGHT> "
          + "<FEATURE_DIMENSION> <HIDDEN_UNITS> <LABEL_DIMENSION> "
          + "<STEP_SIZE> <NUM_OUTPUTCELLS> <BATCH_SIZE> <MAX_ITERATION>");
      System.out.println("E.g. MnistRecurrentMultiLayerPerceptron"
          + " ./model_rnn mnist.seq 0.01 0.9 0.0005 196 200 10 4 1 10 12000");
      System.exit(-1);
    }

    HornJob rnn = createJob(new HamaConfiguration(), args[0], args[1],
        Float.parseFloat(args[2]), Float.parseFloat(args[3]),
        Float.parseFloat(args[4]), Integer.parseInt(args[5]),
        Integer.parseInt(args[6]), Integer.parseInt(args[7]),
        Integer.parseInt(args[8]), Integer.parseInt(args[9]),
        Integer.parseInt(args[10]), Integer.parseInt(args[11]));

    long startTime = System.currentTimeMillis();
    if (rnn.waitForCompletion(true)) {
      System.out.println("Optimization Finished! "
          + (System.currentTimeMillis() - startTime) / 1000.0 + " seconds");
    }
  }
}


text:
package org.github.evenjn.plaintext;

import java.util.Comparator;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringWithNumberComparator implements
		Comparator<String> {

	public static final String digitsGroup = "([0-9]{0,10})";

	/**
	 * @param pattern
	 *          A pattern that identifies a single subgroup, and the subgroup is a
	 *          sequence of digits (StringWithNumberComparator.digitsGroup).
	 */
	public static Comparator<String> nu( Pattern pattern ) {
		return new StringWithNumberComparator( pattern );
	}

	private Pattern pattern;

	private StringWithNumberComparator(Pattern pattern) {
		this.pattern = pattern;
	}

	private int extractInt( String s ) {
		Matcher matcher1 = pattern.matcher( s );
		if ( !matcher1.matches( ) ) {
			throw new IllegalArgumentException( );
		}
		String digits1 = matcher1.group( 1 );
		int i1 = Integer.parseInt( digits1 );
		return i1;
	}

	private static Optional<Integer> compareNullFirst( Object o1, Object o2 ) {
		if ( o1 == null ) {
			if ( o2 == null )
				return Optional.of( 0 );
			return Optional.of( Integer.valueOf( -1 ) );
		}
		if ( o2 == null )
			return Optional.of( Integer.valueOf( 1 ) );
		return Optional.empty( );
	}

	@Override
	public int compare( String o1, String o2 ) {
		Optional<Integer> compareNullFirst = compareNullFirst( o1, o2 );
		if ( compareNullFirst.isPresent( ) ) {
			return compareNullFirst.get( );
		}
		return Integer.compare( extractInt( o1 ), extractInt( o2 ) );
	}

}


text:
package latexstudio.editor.pdf;

import java.io.File;
import java.io.IOException;
import latexstudio.editor.util.ApplicationUtils;
import org.apache.commons.io.IOUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;

/**
 * This class allows all kind of operations on the PDF files.
 * @author Sebastian
 */
public final class PDFService {

    private static PDDocument inputPDF;
    private static final String PDF_PATH = ApplicationUtils.getTempPDFFile();

    private PDFService() {
    }

    public static int getTotalPDFPages(){
        int pages = 0;

        File pdfFile = null;
        try {
            pdfFile = new File(PDF_PATH);
            if (pdfFile.exists()) {
                inputPDF = PDDocument.load(pdfFile);
                pages = inputPDF.getNumberOfPages();
            }
        } catch (IOException ex) {
            // fallback to finally
        } finally {
            closeDocument();
        }

        return pages;
    }

    public static PDDocument getPDDocument() {
        PDPage page = null;

        File pdfFile = null;
        try {
            pdfFile = new File(PDF_PATH);
            if (pdfFile.exists()) {
                inputPDF = PDDocument.load(pdfFile);
            }
        } catch (IOException ex) {
            closeDocument();
        }

        return inputPDF;
    }

    public static void closeDocument() {
        if (inputPDF != null) {
            IOUtils.closeQuietly(inputPDF);
        }
    }
}


text:
Review.delete_all
Movie.delete_all

movie1 = Movie.create!(title: "Arrival of a Train", gross: 100.00, release_date: "Apr 1 1896", mpaa_rating: "G", description: "RELEASED MORE THAN 5 YEARS AGO: first movie ever made was by the Lumiere Brothers")

movie2 = Movie.create!(title: "The Second Best Science Fiction Movie Ever Made", gross: 2000.00, release_date: "Jan 1 2010", mpaa_rating: "G", description: "RELEASED LESS THAN 5 YEARS AGO: Many years ago, eight of our astronauts were abducted and brought to another planet.")

movie3 = Movie.create!(title: "Brazil", gross: 280000.00, release_date: "Jun 6 1988", mpaa_rating: "R", description: "one of Terry Gilliam's best movies, can you believe Robert DiNero is in it too?")

movie1.reviews.create!(comment: "this movie is amazing!", star_rating: 4, reviewer_name: "Alexander the great")
movie1.reviews.create!(comment: "yep, pretty ground breaking stuff", star_rating: 3, reviewer_name: "John Doe")
movie2.reviews.create!(comment: "I'm not a fan of science Fiction!", star_rating: 2, reviewer_name: "Jayne Cobb")
movie3.reviews.create!(comment: "Best and most bizarre movie ever", star_rating: 5, reviewer_name: "Mr Tuttle")


text:
const randomButtonElement = document.getElementById('randomize');
const randomUserElement = document.getElementById('user');
const errorElement = document.getElementById('error');

randomButtonElement.onclick = function () {
    makeGetRequest('https://api.github.com/users',
        function (request) {
            let data;
            try {
                data = JSON.parse(request)
            } catch (err) {
                showError(new Error('Ошибка при чтении из json'));
            }
            if (data) {
                let user = data[Math.floor(Math.random() * data.length)];
                loadImage(user.avatar_url, function() {
                    hideError();
                    drawUser(user);
                }, showError);
            }
        }, showError);
};

function makeGetRequest(url, successCallback, errorCallback) {
    let xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.onreadystatechange = function () {
        if (xhr.readyState != 4) return;

        if (xhr.status != 200) {
            var error = new Error('Ошибка ' + xhr.status);
            error.code = xhr.statusText;
            errorCallback(error);
        } else {
            successCallback(xhr.responseText);
        }

    };

    xhr.send();
}

function showError(err) {
    errorElement.textContent = err;
    errorElement.classList.remove('hidden');
    randomUserElement.classList.add('hidden');
}

function hideError() {
    errorElement.classList.add('hidden');
    randomUserElement.classList.remove('hidden');
}

function loadImage(imageUrl, successCallback, errorCallback) {
    let img = new Image();

    img.onload = function () {
        successCallback(img);
    };

    img.onerror = function () {
        errorCallback(new Error('Что-то пошло не так'));
    };
    img.src = imageUrl;
}

function drawUser(data) {
    let img = randomUserElement.querySelector('img');
    let link = randomUserElement.querySelector('a');
    img.src = data.avatar_url;
    img.alt = data.login;
    link.href = data.html_url;
    link.textContent = data.login;
}


text:
package main

import (
	"flag"

	"otremblay.com/jkl"
)

type AttachCmd struct {
	args    []string
	file    string
	taskKey string
}

func NewAttachCmd(args []string) (*AttachCmd, error) {
	ccmd := &AttachCmd{}
	f := flag.NewFlagSet("x", flag.ExitOnError)
	f.Parse(args)
	if len(f.Args()) < 2 {
		return nil, ErrNotEnoughArgs
	}
	ccmd.taskKey = f.Arg(0)
	ccmd.file = f.Arg(1)
	return ccmd, nil
}

func (ecmd *AttachCmd) Attach() error {
	return jkl.Attach(ecmd.taskKey, ecmd.file)
}

func (ecmd *AttachCmd) Run() error {
	return ecmd.Attach()
}


text:
<?php

class testRuleAppliesToParentReferencedUnusedPrivateMethod extends stdClass
{
    private static function foo()
    {

    }

    public function  __construct()
    {
        parent::foo();
    }
}


text:
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/uio.h>
#include <unistd.h>
#if H2O_USE_KTLS
#include <linux/tls.h>
#endif
#include "cloexec.h"
#include "h2o/linklist.h"

#if !defined(H2O_USE_ACCEPT4)
#ifdef __linux__
#if defined(__ANDROID__) && __ANDROID_API__ < 21
#define H2O_USE_ACCEPT4 0
#else
#define H2O_USE_ACCEPT4 1
#endif
#elif __FreeBSD__ >= 10
#define H2O_USE_ACCEPT4 1
#else
#define H2O_USE_ACCEPT4 0
#endif
#endif

struct st_h2o_evloop_socket_t {
    h2o_socket_t super;
    int fd;
    int _flags;
    h2o_evloop_t *loop;
    size_t max_read_size;
    struct st_h2o_evloop_socket_t *_next_pending;
    struct st_h2o_evloop_socket_t *_next_statechanged;
    struct {
        uint64_t prev_loop;
        uint64_t cur_loop;
        uint64_t cur_run_count;
    } bytes_written;
    /**
     * vector to be sent (or vec.callbacks is NULL when not used)
     */
    h2o_sendvec_t sendvec;
};

static void link_to_pending(struct st_h2o_evloop_socket_t *sock);
static void link_to_statechanged(struct st_h2o_evloop_socket_t *sock);
static void write_pending(struct st_h2o_evloop_socket_t *sock);
static h2o_evloop_t *create_evloop(size_t sz);
static void update_now(h2o_evloop_t *loop);
static int32_t adjust_max_wait(h2o_evloop_t *loop, int32_t max_wait);

/* functions to be defined in the backends */
static int evloop_do_proceed(h2o_evloop_t *loop, int32_t max_wait);
static void evloop_do_dispose(h2o_evloop_t *loop);
static void evloop_do_on_socket_create(struct st_h2o_evloop_socket_t *sock);
static int evloop_do_on_socket_close(struct st_h2o_evloop_socket_t *sock);
static void evloop_do_on_socket_export(struct st_h2o_evloop_socket_t *sock);

#if H2O_USE_POLL || H2O_USE_EPOLL || H2O_USE_KQUEUE
/* explicitly specified */
#else
#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
#define H2O_USE_KQUEUE 1
#elif defined(__linux)
#define H2O_USE_EPOLL 1
#if defined(SO_ZEROCOPY) && defined(SO_EE_ORIGIN_ZEROCOPY)
#define H2O_USE_MSG_ZEROCOPY 1
#endif
#else
#define H2O_USE_POLL 1
#endif
#endif
#if !defined(H2O_USE_MSG_ZEROCOPY)
#define H2O_USE_MSG_ZEROCOPY 0
#endif

#if H2O_USE_POLL
#include "evloop/poll.c.h"
#elif H2O_USE_EPOLL
#include "evloop/epoll.c.h"
#elif H2O_USE_KQUEUE
#include "evloop/kqueue.c.h"
#else
#error "poller not specified"
#endif

size_t h2o_evloop_socket_max_read_size = 1024 * 1024; /* by default, we read up to 1MB at once */
size_t h2o_evloop_socket_max_write_size = 1024 * 1024; /* by default, we write up to 1MB at once */

void link_to_pending(struct st_h2o_evloop_socket_t *sock)
{
    if (sock->_next_pending == sock) {
        struct st_h2o_evloop_socket_t **slot = (sock->_flags & H2O_SOCKET_FLAG_IS_ACCEPTED_CONNECTION) != 0
                                                   ? &sock->loop->_pending_as_server
                                                   : &sock->loop->_pending_as_client;
        sock->_next_pending = *slot;
        *slot = sock;
    }
}

void link_to_statechanged(struct st_h2o_evloop_socket_t *sock)
{
    if (sock->_next_statechanged == sock) {
        sock->_next_statechanged = NULL;
        *sock->loop->_statechanged.tail_ref = sock;
        sock->loop->_statechanged.tail_ref = &sock->_next_statechanged;
    }
}

static const char *on_read_core(int fd, h2o_buffer_t **input, size_t max_bytes)
{
    ssize_t read_so_far = 0;

    while (1) {
        ssize_t rret;
        h2o_iovec_t buf = h2o_buffer_try_reserve(input, max_bytes < 4096 ? max_bytes : 4096);
        if (buf.base == NULL) {
            /* memory allocation failed */
            return h2o_socket_error_out_of_memory;
        }
        size_t read_size = buf.len <= INT_MAX / 2 ? buf.len : INT_MAX / 2 + 1;
        if (read_size > max_bytes)
            read_size = max_bytes;
        while ((rret = read(fd, buf.base, read_size)) == -1 && errno == EINTR)
            ;
        if (rret == -1) {
            if (errno == EAGAIN)
                break;
            else
                return h2o_socket_error_io;
        } else if (rret == 0) {
            if (read_so_far == 0)
                return h2o_socket_error_closed; /* TODO notify close */
            break;
        }
        (*input)->size += rret;
        if (buf.len != rret)
            break;
        read_so_far += rret;
        if (read_so_far >= max_bytes)
            break;
    }
    return NULL;
}

static size_t write_vecs(struct st_h2o_evloop_socket_t *sock, h2o_iovec_t **bufs, size_t *bufcnt, int sendmsg_flags)
{
    ssize_t wret;

    while (*bufcnt != 0) {
        /* write */
        int iovcnt = *bufcnt < IOV_MAX ? (int)*bufcnt : IOV_MAX;
        struct msghdr msg;
        do {
            msg = (struct msghdr){.msg_iov = (struct iovec *)*bufs, .msg_iovlen = iovcnt};
        } while ((wret = sendmsg(sock->fd, &msg, sendmsg_flags)) == -1 && errno == EINTR);
        SOCKET_PROBE(WRITEV, &sock->super, wret);

        if (wret == -1)
            return errno == EAGAIN ? 0 : SIZE_MAX;

        /* adjust the buffer, doing the write once again only if all IOV_MAX buffers being supplied were fully written */
        while ((*bufs)->len <= wret) {
            wret -= (*bufs)->len;
            ++*bufs;
            --*bufcnt;
            if (*bufcnt == 0) {
                assert(wret == 0);
                return 0;
            }
        }
        if (wret != 0) {
            return wret;
        } else if (iovcnt < IOV_MAX) {
            return 0;
        }
    }

    return 0;
}

static size_t write_core(struct st_h2o_evloop_socket_t *sock, h2o_iovec_t **bufs, size_t *bufcnt)
{
    if (sock->super.ssl == NULL || sock->super.ssl->offload == H2O_SOCKET_SSL_OFFLOAD_ON) {
        if (sock->super.ssl != NULL)
            assert(!has_pending_ssl_bytes(sock->super.ssl));
        return write_vecs(sock, bufs, bufcnt, 0);
    }

    /* SSL: flatten given vector if that has not been done yet; `*bufs` is guaranteed to have one slot available at the end; see
     * `do_write_with_sendvec`, `init_write_buf`. */
    if (sock->sendvec.callbacks != NULL) {
        size_t veclen = flatten_sendvec(&sock->super, &sock->sendvec);
        if (veclen == SIZE_MAX)
            return SIZE_MAX;
        sock->sendvec.callbacks = NULL;
        (*bufs)[(*bufcnt)++] = h2o_iovec_init(sock->super._write_buf.flattened, veclen);
    }

    /* continue encrypting and writing, until we run out of data */
    size_t first_buf_written = 0;
    while (1) {
        /* write bytes already encrypted, if any */
        if (has_pending_ssl_bytes(sock->super.ssl)) {
            h2o_iovec_t encbuf = h2o_iovec_init(sock->super.ssl->output.buf.base + sock->super.ssl->output.pending_off,
                                                sock->super.ssl->output.buf.off - sock->super.ssl->output.pending_off);
            h2o_iovec_t *encbufs = &encbuf;
            size_t encbufcnt = 1, enc_written;
            int sendmsg_flags = 0;
#if H2O_USE_MSG_ZEROCOPY
            /* Use zero copy if amount of data to be written is no less than 4KB, and if the memory can be returned to
             * `h2o_socket_zerocopy_buffer_allocator`. Latter is a short-cut. It is only under exceptional conditions (e.g., TLS
             * stack adding a post-handshake message) that we'd see the buffer grow to a size that cannot be returned to the
             * recycling allocator.
             * Even though https://www.kernel.org/doc/html/v5.17/networking/msg_zerocopy.html recommends 10KB, 4KB has been chosen
             * as the threshold, because we are likely to be using the non-temporal aesgcm engine and tx-nocache-copy, in which case
             * copying sendmsg is going to be more costly than what the kernel documentation assumes. In a synthetic benchmark,
             * changing from 16KB to 4KB increased the throughput by ~10%. */
            if (sock->super.ssl->output.allocated_for_zerocopy && encbuf.len >= 4096 &&
                sock->super.ssl->output.buf.capacity == h2o_socket_zerocopy_buffer_allocator.conf->memsize)
                sendmsg_flags = MSG_ZEROCOPY;
#endif
            if ((enc_written = write_vecs(sock, &encbufs, &encbufcnt, sendmsg_flags)) == SIZE_MAX) {
                dispose_ssl_output_buffer(sock->super.ssl);
                return SIZE_MAX;
            }
            if (sendmsg_flags != 0 && (encbufcnt == 0 || enc_written > 0)) {
                zerocopy_buffers_push(sock->super._zerocopy, sock->super.ssl->output.buf.base);
                if (!sock->super.ssl->output.zerocopy_owned) {
                    sock->super.ssl->output.zerocopy_owned = 1;
                    ++h2o_socket_num_zerocopy_buffers_inflight;
                }
            }
            /* if write is incomplete, record the advance and bail out */
            if (encbufcnt != 0) {
                sock->super.ssl->output.pending_off += enc_written;
                break;
            }
            /* succeeded in writing all the encrypted data; free the buffer */
            dispose_ssl_output_buffer(sock->super.ssl);
        }
        /* bail out if complete */
        if (*bufcnt == 0 && sock->sendvec.callbacks == NULL)
            break;
        /* convert more cleartext to TLS records if possible, or bail out on fatal error */
        if ((first_buf_written = generate_tls_records(&sock->super, bufs, bufcnt, first_buf_written)) == SIZE_MAX)
            break;
        /* as an optimization, if we have a flattened vector, release memory as soon as they have been encrypted */
        if (*bufcnt == 0 && sock->super._write_buf.flattened != NULL) {
            h2o_mem_free_recycle(&h2o_socket_ssl_buffer_allocator, sock->super._write_buf.flattened);
            sock->super._write_buf.flattened = NULL;
        }
    }

    return first_buf_written;
}

/**
 * Sends contents of sendvec, and returns if operation has been successful, either completely or partially. Upon completion,
 * `sendvec.vec.callbacks` is reset to NULL.
 */
static int sendvec_core(struct st_h2o_evloop_socket_t *sock)
{
    size_t bytes_sent;

    assert(sock->sendvec.len != 0);

    /* send, and return an error if failed */
    if ((bytes_sent = sock->sendvec.callbacks->send_(&sock->sendvec, sock->fd, sock->sendvec.len)) == SIZE_MAX)
        return 0;

    /* update offset, and return if we are not done yet */
    if (sock->sendvec.len != 0)
        return 1;

    /* operation complete; mark as such */
    sock->sendvec.callbacks = NULL;
    return 1;
}

void write_pending(struct st_h2o_evloop_socket_t *sock)
{
    assert(sock->super._cb.write != NULL);

    /* write from buffer, if we have anything */
    int ssl_needs_flatten = sock->sendvec.callbacks != NULL && sock->super.ssl != NULL
#if H2O_USE_KTLS
        && sock->super.ssl->offload != H2O_SOCKET_SSL_OFFLOAD_ON
#endif
    ;
    if (sock->super._write_buf.cnt != 0 || has_pending_ssl_bytes(sock->super.ssl) || ssl_needs_flatten) {
        size_t first_buf_written;
        if ((first_buf_written = write_core(sock, &sock->super._write_buf.bufs, &sock->super._write_buf.cnt)) != SIZE_MAX) {
            /* return if there's still pending data, adjusting buf[0] if necessary */
            if (sock->super._write_buf.cnt != 0) {
                sock->super._write_buf.bufs[0].base += first_buf_written;
                sock->super._write_buf.bufs[0].len -= first_buf_written;
                return;
            } else if (has_pending_ssl_bytes(sock->super.ssl)) {
                return;
            }
        }
    }

    /* either completed or failed */
    dispose_write_buf(&sock->super);

    /* send the vector, if we have one and if all buffered writes are complete */
    if (sock->sendvec.callbacks != NULL && sock->super._write_buf.cnt == 0 && !has_pending_ssl_bytes(sock->super.ssl)) {
        /* send, and upon partial send, return without changing state for another round */
        if (sendvec_core(sock) && sock->sendvec.callbacks != NULL)
            return;
    }

    /* operation completed or failed, schedule notification */
    SOCKET_PROBE(WRITE_COMPLETE, &sock->super, sock->super._write_buf.cnt == 0 && !has_pending_ssl_bytes(sock->super.ssl));
    sock->bytes_written.cur_loop = sock->super.bytes_written;
    sock->_flags |= H2O_SOCKET_FLAG_IS_WRITE_NOTIFY;
    link_to_pending(sock);
    link_to_statechanged(sock); /* might need to disable the write polling */
}

static void read_on_ready(struct st_h2o_evloop_socket_t *sock)
{
    const char *err = 0;
    size_t prev_size = sock->super.input->size;

    if ((sock->_flags & H2O_SOCKET_FLAG_DONT_READ) != 0)
        goto Notify;

    if ((err = on_read_core(sock->fd, sock->super.ssl == NULL ? &sock->super.input : &sock->super.ssl->input.encrypted,
                            sock->max_read_size)) != NULL)
        goto Notify;

    if (sock->super.ssl != NULL && sock->super.ssl->handshake.cb == NULL)
        err = decode_ssl_input(&sock->super);

Notify:
    /* the application may get notified even if no new data is avaiable.  The
     * behavior is intentional; it is designed as such so that the applications
     * can update their timeout counters when a partial SSL record arrives.
     */
    sock->super.bytes_read += sock->super.input->size - prev_size;
    sock->super._cb.read(&sock->super, err);
}

void do_dispose_socket(h2o_socket_t *_sock)
{
    struct st_h2o_evloop_socket_t *sock = (struct st_h2o_evloop_socket_t *)_sock;

    dispose_write_buf(&sock->super);

    sock->_flags = H2O_SOCKET_FLAG_IS_DISPOSED | (sock->_flags & H2O_SOCKET_FLAG__EPOLL_IS_REGISTERED);

    /* Give backends chance to do the necessary cleanup, as well as giving them chance to switch to their own disposal method; e.g.,
     * shutdown(SHUT_RDWR) with delays to reclaim all zero copy buffers. */
    if (evloop_do_on_socket_close(sock))
        return;

    /* immediate close */
    if (sock->fd != -1) {
        close(sock->fd);
        sock->fd = -1;
    }
    link_to_statechanged(sock);
}

void report_early_write_error(h2o_socket_t *_sock)
{
    struct st_h2o_evloop_socket_t *sock = (struct st_h2o_evloop_socket_t *)_sock;

    /* fill in _wreq.bufs with fake data to indicate error */
    sock->super._write_buf.bufs = sock->super._write_buf.smallbufs;
    sock->super._write_buf.cnt = 1;
    *sock->super._write_buf.bufs = h2o_iovec_init(H2O_STRLIT("deadbeef"));
    sock->_flags |= H2O_SOCKET_FLAG_IS_WRITE_NOTIFY;
    link_to_pending(sock);
}

void do_write(h2o_socket_t *_sock, h2o_iovec_t *bufs, size_t bufcnt)
{
    struct st_h2o_evloop_socket_t *sock = (struct st_h2o_evloop_socket_t *)_sock;
    size_t first_buf_written;

    /* Don't write too much; if more than 1MB have been already written in the current invocation of `h2o_evloop_run`, wait until
     * the event loop notifies us that the socket is writable. */
    if (sock->bytes_written.cur_run_count != sock->loop->run_count) {
        sock->bytes_written.prev_loop = sock->bytes_written.cur_loop;
        sock->bytes_written.cur_run_count = sock->loop->run_count;
    } else if (sock->bytes_written.cur_loop - sock->bytes_written.prev_loop >= h2o_evloop_socket_max_write_size) {
        init_write_buf(&sock->super, bufs, bufcnt, 0);
        goto Schedule_Write;
    }

    /* try to write now */
    if ((first_buf_written = write_core(sock, &bufs, &bufcnt)) == SIZE_MAX) {
        report_early_write_error(&sock->super);
        return;
    }
    if (bufcnt == 0 && !has_pending_ssl_bytes(sock->super.ssl)) {
        /* write complete, schedule the callback */
        if (sock->super._write_buf.flattened != NULL) {
            h2o_mem_free_recycle(&h2o_socket_ssl_buffer_allocator, sock->super._write_buf.flattened);
            sock->super._write_buf.flattened = NULL;
        }
        if (sock->sendvec.callbacks != NULL) {
            if (!sendvec_core(sock)) {
                report_early_write_error(&sock->super);
                return;
            }
            if (sock->sendvec.callbacks != NULL)
                goto Schedule_Write;
        }
        sock->bytes_written.cur_loop = sock->super.bytes_written;
        sock->_flags |= H2O_SOCKET_FLAG_IS_WRITE_NOTIFY;
        link_to_pending(sock);
        return;
    }

    /* setup the buffer to send pending data */
    init_write_buf(&sock->super, bufs, bufcnt, first_buf_written);

Schedule_Write:
    link_to_statechanged(sock);
}

static int can_tls_offload(h2o_socket_t *sock)
{
#if H2O_USE_KTLS
    if (sock->ssl->offload != H2O_SOCKET_SSL_OFFLOAD_NONE && sock->ssl->ptls != NULL) {
        ptls_cipher_suite_t *cipher = ptls_get_cipher(sock->ssl->ptls);
        switch (cipher->id) {
        case PTLS_CIPHER_SUITE_AES_128_GCM_SHA256:
        case PTLS_CIPHER_SUITE_AES_256_GCM_SHA384:
            return 1;
        default:
            break;
        }
    }
#endif

    return 0;
}

#if H2O_USE_KTLS
static void switch_to_ktls(struct st_h2o_evloop_socket_t *sock)
{
    assert(sock->super.ssl->offload == H2O_SOCKET_SSL_OFFLOAD_TBD);

    /* Postpone the decision, when we are still in the early stages of the connection, as we want to use userspace TLS for
     * generating small TLS records. TODO: integrate with TLS record size calculation logic. */
    if (sock->super.bytes_written < 65536)
        return;

    /* load the key to the kernel */
    struct {
        uint8_t key[PTLS_MAX_SECRET_SIZE];
        uint8_t iv[PTLS_MAX_DIGEST_SIZE];
        uint64_t seq;
        union {
            struct tls12_crypto_info_aes_gcm_128 aesgcm128;
            struct tls12_crypto_info_aes_gcm_256 aesgcm256;
        } tx_params;
        size_t tx_params_size;
    } keys;

    /* at the moment, only TLS/1.3 connections using aes-gcm is supported */
    if (sock->super.ssl->ptls == NULL)
        goto Fail;
    ptls_cipher_suite_t *cipher = ptls_get_cipher(sock->super.ssl->ptls);
    switch (cipher->id) {
    case PTLS_CIPHER_SUITE_AES_128_GCM_SHA256:
    case PTLS_CIPHER_SUITE_AES_256_GCM_SHA384:
        break;
    default:
        goto Fail;
    }
    if (ptls_get_traffic_keys(sock->super.ssl->ptls, 1, keys.key, keys.iv, &keys.seq) != 0)
        goto Fail;
    keys.seq = htobe64(keys.seq); /* converted to big endian ASAP */

#define SETUP_TX_PARAMS(target, type)                                                                                \
    do {                                                                                \
        keys.tx_params.target.info.version = TLS_1_3_VERSION;                                                                      \
        keys.tx_params.target.info.cipher_type = type;                                                                             \
        H2O_BUILD_ASSERT(sizeof(keys.tx_params.target.key) == cipher->aead->key_size);                                             \
        memcpy(keys.tx_params.target.key, keys.key, cipher->aead->key_size);                                                       \
        H2O_BUILD_ASSERT(cipher->aead->iv_size == 12);                                                                             \
        H2O_BUILD_ASSERT(sizeof(keys.tx_params.target.salt) == 4);                                                                 \
        memcpy(keys.tx_params.target.salt, keys.iv, 4);                                                                            \
        H2O_BUILD_ASSERT(sizeof(keys.tx_params.target.iv) == 8);                                                                   \
        memcpy(keys.tx_params.target.iv, keys.iv + 4, 8);                                                                          \
        H2O_BUILD_ASSERT(sizeof(keys.tx_params.target.rec_seq) == sizeof(keys.seq));                                               \
        memcpy(keys.tx_params.target.rec_seq, &keys.seq, sizeof(keys.seq));                                                        \
        keys.tx_params_size = sizeof(keys.tx_params.target);                                                                       \
    } while (0)
    switch (cipher->id) {
    case PTLS_CIPHER_SUITE_AES_128_GCM_SHA256:
        SETUP_TX_PARAMS(aesgcm128, TLS_CIPHER_AES_GCM_128);
        break;
    case PTLS_CIPHER_SUITE_AES_256_GCM_SHA384:
        SETUP_TX_PARAMS(aesgcm256, TLS_CIPHER_AES_GCM_256);
        break;
    default:
        goto Fail;
    }
#undef SETUP_TX_PARAMS

    /* set to kernel */
    if (setsockopt(sock->fd, SOL_TCP, TCP_ULP, "tls", sizeof("tls")) != 0)
        goto Fail;
    if (setsockopt(sock->fd, SOL_TLS, TLS_TX, &keys.tx_params, keys.tx_params_size) != 0)
        goto Fail;
    sock->super.ssl->offload = H2O_SOCKET_SSL_OFFLOAD_ON;

Exit:
    ptls_clear_memory(&keys, sizeof(keys));
    return;

Fail:
    sock->super.ssl->offload = H2O_SOCKET_SSL_OFFLOAD_NONE;
    goto Exit;
}
#endif

/**
 * `bufs` should be an array capable of storing `bufcnt + 1` objects, as we will be flattening `sendvec` at the end of `bufs` before
 * encryption; see `write_core`.
 */
static int do_write_with_sendvec(h2o_socket_t *_sock, h2o_iovec_t *bufs, size_t bufcnt, h2o_sendvec_t *sendvec)
{
    struct st_h2o_evloop_socket_t *sock = (struct st_h2o_evloop_socket_t *)_sock;

    assert(sendvec->callbacks->read_ != NULL);
    assert(sock->sendvec.callbacks == NULL);

    /* If userspace TLS is used, rely on `read_` which is a mandatory callback. Otherwise, rely on `send_` if it is available. */
    if (sock->super.ssl != NULL) {
#if H2O_USE_KTLS
        if (sock->super.ssl->offload == H2O_SOCKET_SSL_OFFLOAD_TBD)
            switch_to_ktls(sock);
        if (sock->super.ssl->offload == H2O_SOCKET_SSL_OFFLOAD_ON && sendvec->callbacks->send_ == NULL)
            return 0;
#endif
    } else {
        if (sendvec->callbacks->send_ == NULL)
            return 0;
    }

    /* handling writes with sendvec, here */
    sock->sendvec = *sendvec;
    do_write(&sock->super, bufs, bufcnt);

    return 1;
}

int h2o_socket_get_fd(h2o_socket_t *_sock)
{
    struct st_h2o_evloop_socket_t *sock = (struct st_h2o_evloop_socket_t *)_sock;
    return sock->fd;
}

void do_read_start(h2o_socket_t *_sock)
{
    struct st_h2o_evloop_socket_t *sock = (struct st_h2o_evloop_socket_t *)_sock;

    link_to_statechanged(sock);
}

void do_read_stop(h2o_socket_t *_sock)
{
    struct st_h2o_evloop_socket_t *sock = (struct st_h2o_evloop_socket_t *)_sock;

    sock->_flags &= ~H2O_SOCKET_FLAG_IS_READ_READY;
    link_to_statechanged(sock);
}

void h2o_socket_dont_read(h2o_socket_t *_sock, int dont_read)
{
    struct st_h2o_evloop_socket_t *sock = (struct st_h2o_evloop_socket_t *)_sock;

    if (dont_read) {
        sock->_flags |= H2O_SOCKET_FLAG_DONT_READ;
    } else {
        sock->_flags &= ~H2O_SOCKET_FLAG_DONT_READ;
    }
}

int do_export(h2o_socket_t *_sock, h2o_socket_export_t *info)
{
    struct st_h2o_evloop_socket_t *sock = (void *)_sock;

    assert((sock->_flags & H2O_SOCKET_FLAG_IS_DISPOSED) == 0);
    evloop_do_on_socket_export(sock);
    sock->_flags = H2O_SOCKET_FLAG_IS_DISPOSED | (sock->_flags & H2O_SOCKET_FLAG__EPOLL_IS_REGISTERED);

    info->fd = sock->fd;
    sock->fd = -1;

    return 0;
}

h2o_socket_t *do_import(h2o_loop_t *loop, h2o_socket_export_t *info)
{
    return h2o_evloop_socket_create(loop, info->fd, 0);
}

h2o_loop_t *h2o_socket_get_loop(h2o_socket_t *_sock)
{
    struct st_h2o_evloop_socket_t *sock = (void *)_sock;
    return sock->loop;
}

socklen_t get_sockname_uncached(h2o_socket_t *_sock, struct sockaddr *sa)
{
    struct st_h2o_evloop_socket_t *sock = (void *)_sock;
    socklen_t len = sizeof(struct sockaddr_storage);
    if (getsockname(sock->fd, sa, &len) != 0)
        return 0;
    return len;
}

socklen_t get_peername_uncached(h2o_socket_t *_sock, struct sockaddr *sa)
{
    struct st_h2o_evloop_socket_t *sock = (void *)_sock;
    socklen_t len = sizeof(struct sockaddr_storage);
    if (getpeername(sock->fd, sa, &len) != 0)
        return 0;
    return len;
}

static struct st_h2o_evloop_socket_t *create_socket(h2o_evloop_t *loop, int fd, int flags)
{
    struct st_h2o_evloop_socket_t *sock;

    sock = h2o_mem_alloc(sizeof(*sock));
    memset(sock, 0, sizeof(*sock));
    h2o_buffer_init(&sock->super.input, &h2o_socket_buffer_prototype);
    sock->loop = loop;
    sock->fd = fd;
    sock->_flags = flags;
    sock->max_read_size = h2o_evloop_socket_max_read_size; /* by default, we read up to 1MB at once */
    sock->_next_pending = sock;
    sock->_next_statechanged = sock;

    evloop_do_on_socket_create(sock);

    return sock;
}

/**
 * Sets TCP_NODELAY if the given file descriptor is likely to be a TCP socket. The intent of this function isto reduce number of
 * unnecessary system calls. Therefore, we skip setting TCP_NODELAY when it is certain that the socket is not a TCP socket,
 * otherwise call setsockopt.
 */
static void set_nodelay_if_likely_tcp(int fd, struct sockaddr *sa)
{
    if (sa != NULL && !(sa->sa_family == AF_INET || sa->sa_family == AF_INET6))
        return;

    int on = 1;
    setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on));
}

h2o_socket_t *h2o_evloop_socket_create(h2o_evloop_t *loop, int fd, int flags)
{
    /* It is the reponsibility of the event loop to modify the properties of a socket for its use (e.g., set O_NONBLOCK). */
    fcntl(fd, F_SETFL, O_NONBLOCK);
    set_nodelay_if_likely_tcp(fd, NULL);

    return &create_socket(loop, fd, flags)->super;
}

h2o_socket_t *h2o_evloop_socket_accept(h2o_socket_t *_listener)
{
    struct st_h2o_evloop_socket_t *listener = (struct st_h2o_evloop_socket_t *)_listener;
    int fd;
    h2o_socket_t *sock;

    /* cache the remote address, if we know that we are going to use the value (in h2o_socket_ebpf_lookup_flags) */
#if H2O_USE_EBPF_MAP
    struct {
        struct sockaddr_storage storage;
        socklen_t len;
    } _peeraddr;
    _peeraddr.len = sizeof(_peeraddr.storage);
    struct sockaddr_storage *peeraddr = &_peeraddr.storage;
    socklen_t *peeraddrlen = &_peeraddr.len;
#else
    struct sockaddr_storage *peeraddr = NULL;
    socklen_t *peeraddrlen = NULL;
#endif

#if H2O_USE_ACCEPT4
    /* the anticipation here is that a socket returned by `accept4` will inherit the TCP_NODELAY flag from the listening socket */
    if ((fd = accept4(listener->fd, (struct sockaddr *)peeraddr, peeraddrlen, SOCK_NONBLOCK | SOCK_CLOEXEC)) == -1)
        return NULL;
    sock = &create_socket(listener->loop, fd, H2O_SOCKET_FLAG_IS_ACCEPTED_CONNECTION)->super;
#else
    if ((fd = cloexec_accept(listener->fd, (struct sockaddr *)peeraddr, peeraddrlen)) == -1)
        return NULL;
    fcntl(fd, F_SETFL, O_NONBLOCK);
    sock = &create_socket(listener->loop, fd, H2O_SOCKET_FLAG_IS_ACCEPTED_CONNECTION)->super;
#endif
    set_nodelay_if_likely_tcp(fd, (struct sockaddr *)peeraddr);

    if (peeraddr != NULL && *peeraddrlen <= sizeof(*peeraddr))
        h2o_socket_setpeername(sock, (struct sockaddr *)peeraddr, *peeraddrlen);
    uint64_t flags = h2o_socket_ebpf_lookup_flags(listener->loop, h2o_socket_ebpf_init_key, sock);
    if ((flags & H2O_EBPF_FLAGS_SKIP_TRACING_BIT) != 0)
        sock->_skip_tracing = 1;
    return sock;
}

h2o_socket_t *h2o_socket_connect(h2o_loop_t *loop, struct sockaddr *addr, socklen_t addrlen, h2o_socket_cb cb, const char **err)
{
    int fd, connect_ret;
    struct st_h2o_evloop_socket_t *sock;

    if ((fd = cloexec_socket(addr->sa_family, SOCK_STREAM, 0)) == -1) {
        if (err != NULL) {
            *err = h2o_socket_error_socket_fail;
        }
        return NULL;
    }
    fcntl(fd, F_SETFL, O_NONBLOCK);

    if (!((connect_ret = connect(fd, addr, addrlen)) == 0 || errno == EINPROGRESS)) {
        if (err != NULL)
            *err = h2o_socket_get_error_string(errno, h2o_socket_error_conn_fail);
        close(fd);
        return NULL;
    }

    sock = create_socket(loop, fd, H2O_SOCKET_FLAG_IS_CONNECTING);
    set_nodelay_if_likely_tcp(fd, addr);

    if (connect_ret == 0) {
        /* connection has been established synchronously; notify the fact without going back to epoll */
        sock->_flags |= H2O_SOCKET_FLAG_IS_WRITE_NOTIFY | H2O_SOCKET_FLAG_IS_CONNECTING_CONNECTED;
        sock->super._cb.write = cb;
        link_to_pending(sock);
    } else {
        h2o_socket_notify_write(&sock->super, cb);
    }
    return &sock->super;
}

void h2o_evloop_socket_set_max_read_size(h2o_socket_t *_sock, size_t max_size)
{
    struct st_h2o_evloop_socket_t *sock = (void *)_sock;
    sock->max_read_size = max_size;
}

h2o_evloop_t *create_evloop(size_t sz)
{
    h2o_evloop_t *loop = h2o_mem_alloc(sz);

    memset(loop, 0, sz);
    loop->_statechanged.tail_ref = &loop->_statechanged.head;
    update_now(loop);
    /* 3 levels * 32-slots => 1 second goes into 2nd, becomes O(N) above approx. 31 seconds */
    loop->_timeouts = h2o_timerwheel_create(3, loop->_now_millisec);

    return loop;
}

void update_now(h2o_evloop_t *loop)
{
    gettimeofday(&loop->_tv_at, NULL);
    loop->_now_nanosec = ((uint64_t)loop->_tv_at.tv_sec * 1000000 + loop->_tv_at.tv_usec) * 1000;
    loop->_now_millisec = loop->_now_nanosec / 1000000;
}

int32_t adjust_max_wait(h2o_evloop_t *loop, int32_t max_wait)
{
    uint64_t wake_at = h2o_timerwheel_get_wake_at(loop->_timeouts);

    update_now(loop);

    if (wake_at <= loop->_now_millisec) {
        max_wait = 0;
    } else {
        uint64_t delta = wake_at - loop->_now_millisec;
        if (delta < max_wait)
            max_wait = (int32_t)delta;
    }

    return max_wait;
}

void h2o_socket_notify_write(h2o_socket_t *_sock, h2o_socket_cb cb)
{
    struct st_h2o_evloop_socket_t *sock = (struct st_h2o_evloop_socket_t *)_sock;
    assert(sock->super._cb.write == NULL);
    assert(sock->super._write_buf.cnt == 0);
    assert(!has_pending_ssl_bytes(sock->super.ssl));

    sock->super._cb.write = cb;
    link_to_statechanged(sock);
}

static void run_socket(struct st_h2o_evloop_socket_t *sock)
{
    if ((sock->_flags & H2O_SOCKET_FLAG_IS_DISPOSED) != 0) {
        /* is freed in updatestates phase */
        return;
    }

    if ((sock->_flags & H2O_SOCKET_FLAG_IS_READ_READY) != 0) {
        sock->_flags &= ~H2O_SOCKET_FLAG_IS_READ_READY;
        read_on_ready(sock);
    }

    if ((sock->_flags & H2O_SOCKET_FLAG_IS_WRITE_NOTIFY) != 0) {
        const char *err = NULL;
        assert(sock->super._cb.write != NULL);
        sock->_flags &= ~H2O_SOCKET_FLAG_IS_WRITE_NOTIFY;
        if (sock->super._write_buf.cnt != 0 || has_pending_ssl_bytes(sock->super.ssl) || sock->sendvec.callbacks != NULL) {
            /* error */
            err = h2o_socket_error_io;
            sock->super._write_buf.cnt = 0;
            if (has_pending_ssl_bytes(sock->super.ssl))
                dispose_ssl_output_buffer(sock->super.ssl);
            sock->sendvec.callbacks = NULL;
        } else if ((sock->_flags & H2O_SOCKET_FLAG_IS_CONNECTING) != 0) {
            /* completion of connect; determine error if we do not know whether the connection has been successfully estabilshed */
            if ((sock->_flags & H2O_SOCKET_FLAG_IS_CONNECTING_CONNECTED) == 0) {
                int so_err = 0;
                socklen_t l = sizeof(so_err);
                so_err = 0;
                if (getsockopt(sock->fd, SOL_SOCKET, SO_ERROR, &so_err, &l) != 0 || so_err != 0)
                    err = h2o_socket_get_error_string(so_err, h2o_socket_error_conn_fail);
            }
            sock->_flags &= ~(H2O_SOCKET_FLAG_IS_CONNECTING | H2O_SOCKET_FLAG_IS_CONNECTING_CONNECTED);
        }
        on_write_complete(&sock->super, err);
    }
}

static void run_pending(h2o_evloop_t *loop)
{
    struct st_h2o_evloop_socket_t *sock;

    while (loop->_pending_as_server != NULL || loop->_pending_as_client != NULL) {
        while ((sock = loop->_pending_as_client) != NULL) {
            loop->_pending_as_client = sock->_next_pending;
            sock->_next_pending = sock;
            run_socket(sock);
        }
        if ((sock = loop->_pending_as_server) != NULL) {
            loop->_pending_as_server = sock->_next_pending;
            sock->_next_pending = sock;
            run_socket(sock);
        }
    }
}

void h2o_evloop_destroy(h2o_evloop_t *loop)
{
    struct st_h2o_evloop_socket_t *sock;

    /* timeouts are governed by the application and MUST be destroyed prior to destroying the loop */
    assert(h2o_timerwheel_get_wake_at(loop->_timeouts) == UINT64_MAX);

    /* dispose all socket */
    while ((sock = loop->_pending_as_client) != NULL) {
        loop->_pending_as_client = sock->_next_pending;
        sock->_next_pending = sock;
        h2o_socket_close((h2o_socket_t *)sock);
    }
    while ((sock = loop->_pending_as_server) != NULL) {
        loop->_pending_as_server = sock->_next_pending;
        sock->_next_pending = sock;
        h2o_socket_close((h2o_socket_t *)sock);
    }

    /* now all socket are disposedand and placed in linked list statechanged
     * we can freeing memory in cycle by next_statechanged,
     */
    while ((sock = loop->_statechanged.head) != NULL) {
        loop->_statechanged.head = sock->_next_statechanged;
        free(sock);
    }

    /* dispose backend-specific data */
    evloop_do_dispose(loop);

    /* lastly we need to free loop memory */
    h2o_timerwheel_destroy(loop->_timeouts);
    free(loop);
}

int h2o_evloop_run(h2o_evloop_t *loop, int32_t max_wait)
{
    ++loop->run_count;

    /* update socket states, poll, set readable flags, perform pending writes */
    if (evloop_do_proceed(loop, max_wait) != 0)
        return -1;

    /* run the pending callbacks */
    run_pending(loop);

    /* run the expired timers at the same time invoking pending callbacks for every timer callback. This is an locality
     * optimization; handles things like timeout -> write -> on_write_complete for each object. */
    while (1) {
        h2o_linklist_t expired;
        h2o_linklist_init_anchor(&expired);
        h2o_timerwheel_get_expired(loop->_timeouts, loop->_now_millisec, &expired);
        if (h2o_linklist_is_empty(&expired))
            break;
        do {
            h2o_timerwheel_entry_t *timer = H2O_STRUCT_FROM_MEMBER(h2o_timerwheel_entry_t, _link, expired.next);
            h2o_linklist_unlink(&timer->_link);
            timer->cb(timer);
            run_pending(loop);
        } while (!h2o_linklist_is_empty(&expired));
    }

    assert(loop->_pending_as_client == NULL);
    assert(loop->_pending_as_server == NULL);

    if (h2o_sliding_counter_is_running(&loop->exec_time_nanosec_counter)) {
        update_now(loop);
        h2o_sliding_counter_stop(&loop->exec_time_nanosec_counter, loop->_now_nanosec);
    }

    return 0;
}


text:
#import "PBXBookmark.h"

@interface PBXBookmark (PBXUserInterfaceAdditions)
- (BOOL)openInSeparateApplication;
- (unsigned long long)currentTimestampForFileReference:(id)arg1;
- (id)groupTreeDisplayName;
- (void)updateToCurrentTimestamp;
- (void)updateToTimestamp:(unsigned long long)arg1 andResetTimestamp:(BOOL)arg2;
- (void)breakFileChangeCoalescing;
- (unsigned long long)currentFileTimestamp;
- (BOOL)isEqualRespectingSelection:(id)arg1;
- (BOOL)isSimpleBookmark;
- (id)fileDocumentLoadIfNeeded:(BOOL)arg1;
@end


text:
(function (Date, undefined) {

    var moment,
        round = Math.round,
        languages = {},
        isNode = (typeof window === 'undefined' && typeof module !== 'undefined'),
        paramsToParse = 'months|monthsShort|weekdays|weekdaysShort|relativeTime|ordinal'.split('|'),
        i,
        shortcuts = 'Month|Date|Hours|Minutes|Seconds'.split('|');

    // left zero fill a number
    // see http://jsperf.com/left-zero-filling for performance comparison
    function leftZeroFill(number, targetLength) {
        var output = number + '';
        while (output.length < targetLength) {
            output = '0' + output;
        }
        return output;
    }

    // helper function for _.addTime and _.subtractTime
    function dateAddRemove(date, _input, adding, val) {
        var isString = (typeof _input === 'string'),
            input = isString ? {} : _input,
            ms, M, currentDate;
        if (isString && val) {
            input[_input] = val;
        }
        ms = (input.ms || input.milliseconds || 0) +
            (input.s || input.seconds || 0) * 1e3 + // 1000
            (input.m || input.minutes || 0) * 6e4 + // 1000 * 60
            (input.h || input.hours || 0) * 36e5 + // 1000 * 60 * 60
            (input.d || input.days || 0) * 864e5 + // 1000 * 60 * 60 * 24
            (input.w || input.weeks || 0) * 6048e5; // 1000 * 60 * 60 * 24 * 7
        M = (input.M || input.months || 0) +
            (input.y || input.years || 0) * 12;
        if (ms) {
            date.setMilliseconds(date.getMilliseconds() + ms * adding);
        }
        if (M) {
            currentDate = date.getDate();
            date.setDate(1);
            date.setMonth(date.getMonth() + M * adding);
            date.setDate(Math.min(new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate(), currentDate));
        }
        return date;
    }

    // check if is an array
    function isArray(input) {
        return Object.prototype.toString.call(input) === '[object Array]';
    }

    // convert an array to a date.
    // the array should mirror the parameters below
    // note: all values past the year are optional and will default to the lowest possible value.
    // [year, month, day , hour, minute, second, millisecond]
    function dateFromArray(input) {
        return new Date(input[0], input[1] || 0, input[2] || 1, input[3] || 0, input[4] || 0, input[5] || 0, input[6] || 0);
    }

    // format date using native date object
    function formatDate(date, inputString) {
        var currentMonth = date.getMonth(),
            currentDate = date.getDate(),
            currentYear = date.getFullYear(),
            currentDay = date.getDay(),
            currentHours = date.getHours(),
            currentMinutes = date.getMinutes(),
            currentSeconds = date.getSeconds(),
            charactersToReplace = /(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|dddd?|do?|w[o|w]?|YYYY|YY|a|A|hh?|HH?|mm?|ss?|zz?)/g,
            nonuppercaseLetters = /[^A-Z]/g,
            timezoneRegex = /\([A-Za-z ]+\)|:[0-9]{2} [A-Z]{3} /g;
        // check if the character is a format
        // return formatted string or non string.
        //
        // uses switch/case instead of an object of named functions (like http://phpjs.org/functions/date:380)
        // for minification and performance
        // see http://jsperf.com/object-of-functions-vs-switch for performance comparison
        function replaceFunction(input) {
            // create a couple variables to be used later inside one of the cases.
            var a, b;
            switch (input) {
                // MONTH
            case 'M' :
                return currentMonth + 1;
            case 'Mo' :
                return (currentMonth + 1) + moment.ordinal(currentMonth + 1);
            case 'MM' :
                return leftZeroFill(currentMonth + 1, 2);
            case 'MMM' :
                return moment.monthsShort[currentMonth];
            case 'MMMM' :
                return moment.months[currentMonth];
            // DAY OF MONTH
            case 'D' :
                return currentDate;
            case 'Do' :
                return currentDate + moment.ordinal(currentDate);
            case 'DD' :
                return leftZeroFill(currentDate, 2);
            // DAY OF YEAR
            case 'DDD' :
                a = new Date(currentYear, currentMonth, currentDate);
                b = new Date(currentYear, 0, 1);
                return ~~ (((a - b) / 864e5) + 1.5);
            case 'DDDo' :
                a = replaceFunction('DDD');
                return a + moment.ordinal(a);
            case 'DDDD' :
                return leftZeroFill(replaceFunction('DDD'), 3);
            // WEEKDAY
            case 'd' :
                return currentDay;
            case 'do' :
                return currentDay + moment.ordinal(currentDay);
            case 'ddd' :
                return moment.weekdaysShort[currentDay];
            case 'dddd' :
                return moment.weekdays[currentDay];
            // WEEK OF YEAR
            case 'w' :
                a = new Date(currentYear, currentMonth, currentDate - currentDay + 5);
                b = new Date(a.getFullYear(), 0, 4);
                return ~~ ((a - b) / 864e5 / 7 + 1.5);
            case 'wo' :
                a = replaceFunction('w');
                return a + moment.ordinal(a);
            case 'ww' :
                return leftZeroFill(replaceFunction('w'), 2);
            // YEAR
            case 'YY' :
                return (currentYear + '').slice(-2);
            case 'YYYY' :
                return currentYear;
            // AM / PM
            case 'a' :
                return currentHours > 11 ? 'pm' : 'am';
            case 'A' :
                return currentHours > 11 ? 'PM' : 'AM';
            // 24 HOUR
            case 'H' :
                return currentHours;
            case 'HH' :
                return leftZeroFill(currentHours, 2);
            // 12 HOUR
            case 'h' :
                return currentHours % 12 || 12;
            case 'hh' :
                return leftZeroFill(currentHours % 12 || 12, 2);
            // MINUTE
            case 'm' :
                return currentMinutes;
            case 'mm' :
                return leftZeroFill(currentMinutes, 2);
            // SECOND
            case 's' :
                return currentSeconds;
            case 'ss' :
                return leftZeroFill(currentSeconds, 2);
            // TIMEZONE
            case 'zz' :
                // depreciating 'zz' fall through to 'z'
            case 'z' :
                return (date.toString().match(timezoneRegex) || [''])[0].replace(nonuppercaseLetters, '');
            // DEFAULT
            default :
                return input.replace("\\", "");
            }
        }
        return inputString.replace(charactersToReplace, replaceFunction);
    }

    // date from string and format string
    function makeDateFromStringAndFormat(string, format) {
        var inArray = [0],
            charactersToPutInArray = /[0-9a-zA-Z]+/g,
            inputParts = string.match(charactersToPutInArray),
            formatParts = format.match(charactersToPutInArray),
            i,
            isPm;

        // function to convert string input to date
        function addTime(format, input) {
            switch (format) {
            // MONTH
            case 'M' :
                // fall through to MM
            case 'MM' :
                inArray[1] = ~~input - 1;
                break;
            // DAY OF MONTH
            case 'D' :
                // fall through to DDDD
            case 'DD' :
                // fall through to DDDD
            case 'DDD' :
                // fall through to DDDD
            case 'DDDD' :
                inArray[2] = ~~input;
                break;
            // YEAR
            case 'YY' :
                input = ~~input;
                inArray[0] = input + (input > 70 ? 1900 : 2000);
                break;
            case 'YYYY' :
                inArray[0] = ~~input;
                break;
            // AM / PM
            case 'a' :
                // fall through to A
            case 'A' :
                isPm = (input.toLowerCase() === 'pm');
                break;
            // 24 HOUR
            case 'H' :
                // fall through to hh
            case 'HH' :
                // fall through to hh
            case 'h' :
                // fall through to hh
            case 'hh' :
                inArray[3] = ~~input;
                break;
            // MINUTE
            case 'm' :
                // fall through to mm
            case 'mm' :
                inArray[4] = ~~input;
                break;
            // SECOND
            case 's' :
                // fall through to ss
            case 'ss' :
                inArray[5] = ~~input;
                break;
            }
        }
        for (i = 0; i < formatParts.length; i++) {
            addTime(formatParts[i], inputParts[i]);
        }
        // handle am pm
        if (isPm && inArray[3] < 12) {
            inArray[3] += 12;
        }
        return dateFromArray(inArray);
    }

    // compare two arrays, return the number of differences
    function compareArrays(array1, array2) {
        var len = Math.min(array1.length, array2.length),
            lengthDiff = Math.abs(array1.length - array2.length),
            diffs = 0,
            i;
        for (i = 0; i < len; i++) {
            if (~~array1[i] !== ~~array2[i]) {
                diffs++;
            }
        }
        return diffs + lengthDiff;
    }

    // date from string and array of format strings
    function makeDateFromStringAndArray(string, formats) {
        var output,
            charactersToPutInArray = /[0-9a-zA-Z]+/g,
            inputParts = string.match(charactersToPutInArray),
            scores = [],
            scoreToBeat = 99,
            i,
            curDate,
            curScore;
        for (i = 0; i < formats.length; i++) {
            curDate = makeDateFromStringAndFormat(string, formats[i]);
            curScore = compareArrays(inputParts, formatDate(curDate, formats[i]).match(charactersToPutInArray));
            if (curScore < scoreToBeat) {
                scoreToBeat = curScore;
                output = curDate;
            }
        }
        return output;
    }

    // Moment prototype object
    function Moment(date) {
        this._d = date;
    }

    moment = function (input, format) {
        var date;
        // parse UnderscoreDate object
        if (input && input._d instanceof Date) {
            date = input._d;
        // parse string and format
        } else if (format) {
            if (isArray(format)) {
                date = makeDateFromStringAndArray(input, format);
            } else {
                date = makeDateFromStringAndFormat(input, format);
            }
        // parse everything else
        } else {
            date = input === undefined ? new Date() :
                input instanceof Date ? input :
                isArray(input) ? dateFromArray(input) :
                new Date(input);
        }
        return new Moment(date);
    };

    // language switching and caching
    moment.lang = function (key, values) {
        var i, param, req;
        if (values) {
            languages[key] = values;
        }
        if (languages[key]) {
            for (i = 0; i < paramsToParse.length; i++) {
                param = paramsToParse[i];
                moment[param] = languages[key][param] || moment[param];
            }
        } else {
            if (isNode) {
                req = require('./lang/' + key);
                moment.lang(key, req);
            }
        }
    };

    // set default language
    moment.lang('en', {
        months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"),
        monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),
        weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),
        weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),
        relativeTime : {
            future : "in %s",
            past : "%s ago",
            s : "seconds",
            m : "a minute",
            mm : "%d minutes",
            h : "an hour",
            hh : "%d hours",
            d : "a day",
            dd : "%d days",
            M : "a month",
            MM : "%d months",
            y : "a year",
            yy : "%d years"
        },
        ordinal : function (number) {
            var b = number % 10;
            return (~~ (number % 100 / 10) === 1) ? 'th' :
                (b === 1) ? 'st' :
                (b === 2) ? 'nd' :
                (b === 3) ? 'rd' : 'th';
        }
    });

    // helper function for _date.from() and _date.fromNow()
    function substituteTimeAgo(string, number) {
        return moment.relativeTime[string].replace(/%d/i, number || 1);
    }

    function relativeTime(milliseconds) {
        var seconds = Math.abs(milliseconds) / 1000,
            minutes = seconds / 60,
            hours = minutes / 60,
            days = hours / 24,
            years = days / 365;
        return seconds < 45 && substituteTimeAgo('s', round(seconds)) ||
            round(minutes) === 1 && substituteTimeAgo('m') ||
            minutes < 45 && substituteTimeAgo('mm', round(minutes)) ||
            round(hours) === 1 && substituteTimeAgo('h') ||
            hours < 22 && substituteTimeAgo('hh', round(hours)) ||
            round(days) === 1 && substituteTimeAgo('d') ||
            days < 25 && substituteTimeAgo('dd', round(days)) ||
            days < 45 && substituteTimeAgo('M') ||
            days < 345 && substituteTimeAgo('MM', round(days / 30)) ||
            round(years) === 1 && substituteTimeAgo('y') ||
            substituteTimeAgo('yy', round(years));
    }

    // shortcut for prototype
    moment.fn = Moment.prototype = {

        valueOf : function () {
            return +this._d;
        },

        native : function () {
            return this._d;
        },

        format : function (inputString) {
            return formatDate(this._d, inputString);
        },

        add : function (input, val) {
            this._d = dateAddRemove(this._d, input, 1, val);
            return this;
        },

        subtract : function (input, val) {
            this._d = dateAddRemove(this._d, input, -1, val);
            return this;
        },

        diff : function (input, format) {
            return this._d - moment(input, format)._d;
        },

        from : function (time, withoutSuffix) {
            var difference = this.diff(time),
                string = difference < 0 ? moment.relativeTime.past : moment.relativeTime.future,
                output = relativeTime(difference);
            return withoutSuffix ? output : string.replace(/%s/i, output);
        },

        fromNow : function (withoutSuffix) {
            return this.from(moment(), withoutSuffix);
        },

        isLeapYear : function () {
            var year = this._d.getFullYear();
            return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
        }
    };

    // helper for adding shortcuts
    function makeShortcut(name, key) {
        moment.fn[name] = function (input) {
            if (input) {
                this._d['set' + key](input);
                return this;
            } else {
                return this._d['get' + key]();
            }
        };
    }

    // loop through and add shortcuts
    for (i = 0; i < shortcuts.length; i ++) {
        makeShortcut(shortcuts[i].toLowerCase(), shortcuts[i]);
    }

    // add shortcut for year (uses different syntax than the getter/setter 'year' == 'FullYear')
    makeShortcut('year', 'FullYear');

    // add shortcut for day (no setter)
    moment.fn.day = function () {
        return this._d.getDay();
    };

    // CommonJS module is defined
    if (isNode) {
        module.exports = moment;
    } else {
        this.moment = moment;
    }

})(Date);


text:
pysal.explore.giddy.markov.homogeneity
======================================

.. currentmodule:: pysal.explore.giddy.markov

.. autofunction:: homogeneity


text:
/**
 * @class SocketMessageDelegate
 *
 * @author darryl.west@raincitysoftware.com
 * @created 2016-09-26
 */
const should = require('chai').should(),
    dash = require('lodash' ),
    MockLogger = require('simple-node-logger' ).mocks.MockLogger,
    SocketMessageDelegate = require('../../lib/delegates/SocketMessageDelegate');

describe('SocketMessageDelegate', function() {
    'use strict';

    const MockSocket = function(err) {
        const mock = this;

        this.messages = [];

        this.send = function(wrapper, callback) {
            mock.messages.push( wrapper );
            callback( err, wrapper.mid );
        };
    };

    const createOptions = function() {
        const opts = {};
        opts.log = MockLogger.createLogger('SocketMessageDelegate');

        return opts;
    };

    describe('#instance', function() {
        const delegate = new SocketMessageDelegate( createOptions() ),
            methods = [
                'sendSocketMessage',
                'createRequestWrapper',
                'createMessageId',
                'createResponseWrapper',
                'createFailedWrapper',
                'getMessageCount',
                'getOrigin'
            ];

        it('should create instance of SocketMessageDelegate', function() {
            should.exist( delegate );
            delegate.should.be.instanceof( SocketMessageDelegate );
            delegate.getMessageCount().should.equal( 0 );
            should.exist( delegate.getOrigin() );
        });

        it('should have all known methods by size and type', function() {
            dash.functionsIn( delegate ).length.should.equal( methods.length );
            methods.forEach(function(method) {
                delegate[ method ].should.be.a( 'function' );
            });
        });
    });

    describe('sendSocketMessage', function() {
        const delegate = new SocketMessageDelegate( createOptions() ),
            mockSocket = new MockSocket();

        it('should send the wrapped message and return the message id', done => {
            const msg = delegate.createRequestWrapper();
            const callback = function(err, id) {
                should.not.exist( err );
                should.exist( id );

                id.should.equal( msg.mid );

                done();
            };

            delegate.sendSocketMessage( mockSocket, msg, callback );
        });
    });

    describe('createMessageId', function() {
        const delegate = new SocketMessageDelegate( createOptions() );

        it('should return a generated message id', function() {
            const m1 = delegate.createMessageId();

            should.exist( m1 );
            m1.length.should.equal( 26 );
            delegate.getMessageCount().should.equal( 1 );

            const m2 = delegate.createMessageId();
            m2.should.not.equal( m1 );
            delegate.getMessageCount().should.equal( 2 );
        });
    });

    describe('#getters', function() {
        const delegate = new SocketMessageDelegate( createOptions() );

        it('should return the origin', function() {
            const origin = delegate.getOrigin();

            should.exist( origin );
            origin.length.should.equal( 9 );
        });

        it('should return the message count', function() {
            delegate.getMessageCount().should.equal( 0 );
            delegate.createRequestWrapper();
            delegate.getMessageCount().should.equal( 1 );
            delegate.createRequestWrapper();
            delegate.getMessageCount().should.equal( 2 );
        });
    });

    describe('#wrappers', function() {
        const delegate = new SocketMessageDelegate( createOptions() );

        it('should return a standard request wrapper', function() {
            const wrapper = delegate.createRequestWrapper();
            should.exist( wrapper );
            should.exist( wrapper.mid );
            should.exist( wrapper.ts );
            Object.keys( wrapper ).length.should.equal( 2 );
        });

        it('should return a standard response wrapper', function() {
            const wrapper = delegate.createResponseWrapper('1234');
            should.exist( wrapper );
            wrapper.mid.should.equal( '1234' );
            should.exist( wrapper.ts );
            wrapper.status.should.equal( 'ok' );
        });

        it('should return a standard failed wrapper', function() {
            const wrapper = delegate.createFailedWrapper('1234');
            should.exist( wrapper );
            wrapper.mid.should.equal( '1234' );
            should.exist( wrapper.ts );
            wrapper.status.should.equal( 'failed' );
        });

        it('should return a standard failed wrapper with reason', function() {
            const wrapper = delegate.createFailedWrapper('1234', 'because');
            should.exist( wrapper );
            wrapper.mid.should.equal( '1234' );
            should.exist( wrapper.ts );
            wrapper.status.should.equal( 'failed' );
            wrapper.reason.should.equal( 'because' );
        });
    });
});


text:
ACCEPTED

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

#### Published in
in Worapong, Strobel, Ford, Li, Baird & Hess, Mycotaxon 79: 71 (2001)

#### Original name
Muscodor albus Worapong, Strobel & W.M. Hess, 2001

### Remarks
null


text:
package ca.wbac.rxreader.domain;

public interface RssFetcher {
    Feed fetch(String href) throws Exception;
}