text:
package com.hippo.nimingban.widget;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hippo.easyrecyclerview.EasyRecyclerView;
import com.hippo.easyrecyclerview.FastScroller;
import com.hippo.easyrecyclerview.HandlerDrawable;
import com.hippo.easyrecyclerview.LayoutManagerUtils;
import com.hippo.effect.ViewTransition;
import com.hippo.nimingban.R;
import com.hippo.refreshlayout.RefreshLayout;
import com.hippo.util.ExceptionUtils;
import com.hippo.widget.ProgressView;
import com.hippo.yorozuya.IntIdGenerator;
import com.hippo.yorozuya.IntList;
import com.hippo.yorozuya.LayoutUtils;
import com.hippo.yorozuya.ResourcesUtils;
import com.hippo.yorozuya.Say;

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

public class ContentLayout extends FrameLayout {

    private static final String TAG = ContentLayout.class.getSimpleName();

    private ProgressView mProgressView;
    private ViewGroup mTipView;
    private ViewGroup mContentView;

    private RefreshLayout mRefreshLayout;
    private EasyRecyclerView mRecyclerView;
    private FastScroller mFastScroller;
    private View mImageView;
    private TextView mTextView;

    private int mRecyclerViewOriginTop;
    private int mRecyclerViewOriginBottom;

    public ContentLayout(Context context) {
        super(context);
        init(context);
    }

    public ContentLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public ContentLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        LayoutInflater.from(context).inflate(R.layout.widget_content_layout, this);

        mProgressView = (ProgressView) findViewById(R.id.progress);
        mTipView = (ViewGroup) findViewById(R.id.tip);
        mContentView = (ViewGroup) findViewById(R.id.content_view);

        mRefreshLayout = (RefreshLayout) mContentView.findViewById(R.id.refresh_layout);
        mFastScroller = (FastScroller) mContentView.findViewById(R.id.fast_scroller);
        mRecyclerView = (EasyRecyclerView) mRefreshLayout.findViewById(R.id.recycler_view);
        mImageView = mTipView.getChildAt(0);
        mTextView = (TextView) mTipView.getChildAt(1);

        mFastScroller.attachToRecyclerView(mRecyclerView);
        HandlerDrawable drawable = new HandlerDrawable();
        drawable.setColor(ResourcesUtils.getAttrColor(context, R.attr.colorAccent));
        mFastScroller.setHandlerDrawable(drawable);

        mRefreshLayout.setHeaderColorSchemeResources(
                R.color.loading_indicator_red,
                R.color.loading_indicator_purple,
                R.color.loading_indicator_blue,
                R.color.loading_indicator_cyan,
                R.color.loading_indicator_green,
                R.color.loading_indicator_yellow);
        mRefreshLayout.setFooterColorSchemeResources(
                R.color.loading_indicator_red,
                R.color.loading_indicator_blue,
                R.color.loading_indicator_green,
                R.color.loading_indicator_orange);
        mRefreshLayout.setHeaderProgressBackgroundColorSchemeColor(ResourcesUtils.getAttrColor(context, R.attr.colorPure));

        mRecyclerViewOriginTop = mRecyclerView.getPaddingTop();
        mRecyclerViewOriginBottom = mRecyclerView.getPaddingBottom();
    }

    public EasyRecyclerView getRecyclerView() {
        return mRecyclerView;
    }

    public void setHelper(ContentHelper helper) {
        helper.init(this);
    }

    public void showFastScroll() {
        if (!mFastScroller.isAttached()) {
            mFastScroller.attachToRecyclerView(mRecyclerView);
        }
    }

    public void hideFastScroll() {
        mFastScroller.detachedFromRecyclerView();
    }

    public void setFitPaddingTop(int fitPaddingTop) {
        // RecyclerView
        mRecyclerView.setPadding(mRecyclerView.getPaddingLeft(), mRecyclerViewOriginTop + fitPaddingTop, mRecyclerView.getPaddingRight(), mRecyclerView.getPaddingBottom());
        // RefreshLayout
        mRefreshLayout.setProgressViewOffset(false, fitPaddingTop, fitPaddingTop + LayoutUtils.dp2pix(getContext(), 32)); // TODO
    }

    public void setFitPaddingBottom(int fitPaddingBottom) {
        // RecyclerView
        mRecyclerView.setPadding(mRecyclerView.getPaddingLeft(),
                mRecyclerView.getPaddingTop(), mRecyclerView.getPaddingRight(),
                mRecyclerViewOriginBottom + fitPaddingBottom);
    }

    public abstract static class ContentHelper<E> {

        private static final String TAG = ContentHelper.class.getSimpleName();

        public static final int TYPE_REFRESH = 0;
        public static final int TYPE_PRE_PAGE = 1;
        public static final int TYPE_PRE_PAGE_KEEP_POS = 2;
        public static final int TYPE_NEXT_PAGE = 3;
        public static final int TYPE_NEXT_PAGE_KEEP_POS = 4;
        public static final int TYPE_SOMEWHERE = 5;
        public static final int TYPE_REFRESH_PAGE = 6;

        public static final int REFRESH_TYPE_HEADER = 0;
        public static final int REFRESH_TYPE_FOOTER = 1;
        public static final int REFRESH_TYPE_PROGRESS_VIEW = 2;

        private ProgressView mProgressView;
        private ViewGroup mTipView;
        private ViewGroup mContentView;

        private RefreshLayout mRefreshLayout;
        private EasyRecyclerView mRecyclerView;
        private View mImageView;
        private TextView mTextView;

        private ViewTransition mViewTransition;

        /**
         * Store data
         */
        private List<E> mData = new ArrayList<>();

        /**
         * Generate task id
         */
        private IntIdGenerator mIdGenerator = new IntIdGenerator();

        /**
         * Store the page divider index
         *
         * For example, the data contain page 3, page 4, page 5,
         * page 3 size is 7, page 4 size is 8, page 5 size is 9,
         * so mPageDivider contain 7, 15, 24.
         */
        private IntList mPageDivider = new IntList();

        /**
         * The first page in mData
         */
        private int mStartPage;

        /**
         * The last page + 1 in mData
         */
        private int mEndPage;

        /**
         * The available page count.
         */
        private int mPages;

        private int mCurrentTaskId;
        private int mCurrentTaskType;
        private int mCurrentTaskPage;

        private int mNextPageScrollSize;

        private String mEmptyString = "No hint";

        private RecyclerView.OnScrollListener mOnScrollListener = new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                if (!mRefreshLayout.isRefreshing() && mRefreshLayout.isAlmostBottom() && mEndPage < mPages) {
                    // Get next page
                    mRefreshLayout.setFooterRefreshing(true);
                    mOnRefreshListener.onFooterRefresh();
                }
            }
        };

        private RefreshLayout.OnRefreshListener mOnRefreshListener = new RefreshLayout.OnRefreshListener() {
            @Override
            public void onHeaderRefresh() {
                if (mStartPage > 0) {
                    mCurrentTaskId = mIdGenerator.nextId();
                    mCurrentTaskType = TYPE_PRE_PAGE_KEEP_POS;
                    mCurrentTaskPage = mStartPage - 1;
                    getPageData(mCurrentTaskId, mCurrentTaskType, mCurrentTaskPage);
                } else {
                    doRefresh();
                }
            }

            @Override
            public void onFooterRefresh() {
                if (mEndPage < mPages) {
                    // Get next page
                    mCurrentTaskId = mIdGenerator.nextId();
                    mCurrentTaskType = TYPE_NEXT_PAGE_KEEP_POS;
                    mCurrentTaskPage = mEndPage;
                    getPageData(mCurrentTaskId, mCurrentTaskType, mCurrentTaskPage);
                } else if (mEndPage == mPages) {
                    // Refresh last page
                    mCurrentTaskId = mIdGenerator.nextId();
                    mCurrentTaskType = TYPE_REFRESH_PAGE;
                    mCurrentTaskPage = mEndPage - 1;
                    getPageData(mCurrentTaskId, mCurrentTaskType, mCurrentTaskPage);
                } else {
                    Log.e(TAG, "Try to footer refresh, but mEndPage = " + mEndPage + ", mPages = " + mPages);
                }
            }
        };

        private final LayoutManagerUtils.OnScrollToPositionListener mOnScrollToPositionListener =
                new LayoutManagerUtils.OnScrollToPositionListener() {
                    @Override
                    public void onScrollToPosition(int position) {
                        ContentHelper.this.onScrollToPosition();
                    }
                };

        private void init(ContentLayout contentLayout) {
            mNextPageScrollSize = LayoutUtils.dp2pix(contentLayout.getContext(), 48);

            mProgressView = contentLayout.mProgressView;
            mTipView = contentLayout.mTipView;
            mContentView = contentLayout.mContentView;

            mRefreshLayout = contentLayout.mRefreshLayout;
            mRecyclerView = contentLayout.mRecyclerView;
            mImageView = contentLayout.mImageView;
            mTextView = contentLayout.mTextView;

            mViewTransition = new ViewTransition(mContentView, mProgressView, mTipView);
            mViewTransition.showView(2, false);

            mRecyclerView.addOnScrollListener(mOnScrollListener);
            mRefreshLayout.setOnRefreshListener(mOnRefreshListener);

            mTipView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    refresh();
                }
            });
        }

        /**
         * Call {@link #onGetPageData(int, List)} when get data
         *
         * @param taskId task id
         * @param page the page to get
         */
        protected abstract void getPageData(int taskId, int type, int page);

        protected abstract Context getContext();

        protected abstract void notifyDataSetChanged();

        protected abstract void notifyItemRangeRemoved(int positionStart, int itemCount);

        protected abstract void notifyItemRangeInserted(int positionStart, int itemCount);

        protected void onScrollToPosition() {
        }

        protected void onShowProgress() {
        }

        protected void onShowText() {
        }

        public void setEnable(boolean enable) {
            mRefreshLayout.setEnabled(enable);
        }

        public void setEmptyString(String str) {
            mEmptyString = str;
        }

        /**
         * @throws IndexOutOfBoundsException
         *                if {@code location < 0 || location >= size()}
         */
        public E getDataAt(int location) {
            return mData.get(location);
        }

        public int size() {
            return mData.size();
        }

        public void setPages(int pages) {
            // TODO what it pages > mEndPage
            mPages = pages;
        }

        public int getPages() {
            return mPages;
        }

        public void addAt(int index, E data) {
            mData.add(index, data);

            for (int i = 0, n = mPageDivider.size(); i < n; i++) {
                int divider = mPageDivider.get(i);
                if (index < divider) {
                    mPageDivider.set(i, divider + 1);
                }
            }

            notifyItemRangeInserted(index, 1);
        }

        public void removeAt(int index) {
            mData.remove(index);

            for (int i = 0, n = mPageDivider.size(); i < n; i++) {
                int divider = mPageDivider.get(i);
                if (index < divider) {
                    mPageDivider.set(i, divider - 1);
                }
            }

            notifyItemRangeRemoved(index, 1);
        }

        public void onGetEmptyData(int taskId) {
            if (mCurrentTaskId != taskId) {
                return;
            }

            switch (mCurrentTaskType) {
                case TYPE_REFRESH:
                case TYPE_SOMEWHERE:
                    showText(mEmptyString);
                    break;
                case TYPE_NEXT_PAGE:
                case TYPE_NEXT_PAGE_KEEP_POS:
                    // Last page ?
                    break;
                case TYPE_PRE_PAGE:
                case TYPE_PRE_PAGE_KEEP_POS:
                case TYPE_REFRESH_PAGE:
                    // TODO
                    break;
            }

            mRefreshLayout.setHeaderRefreshing(false);
            mRefreshLayout.setFooterRefreshing(false);
        }

        public void onGetPageData(int taskId, List<E> data) {
            if (mCurrentTaskId == taskId) {
                showContent();

                int dataSize;
                switch (mCurrentTaskType) {
                    case TYPE_REFRESH:
                        mStartPage = 0;
                        mEndPage = 1;
                        mPageDivider.clear();
                        mPageDivider.add(data.size());

                        mData.clear();
                        mData.addAll(data);
                        notifyDataSetChanged();

                        mRecyclerView.stopScroll();
                        LayoutManagerUtils.scrollToPositionWithOffset(mRecyclerView.getLayoutManager(), 0, 0);
                        onScrollToPosition();
                        break;
                    case TYPE_PRE_PAGE:
                    case TYPE_PRE_PAGE_KEEP_POS:
                        mData.addAll(0, data);
                        notifyItemRangeInserted(0, data.size());

                        dataSize = data.size();
                        for (int i = 0, n = mPageDivider.size(); i < n; i++) {
                            mPageDivider.set(i, mPageDivider.get(i) + dataSize);
                        }
                        mPageDivider.add(0, dataSize);

                        mStartPage--;
                        // assert mStartPage >= 0
                        if (mCurrentTaskType == TYPE_PRE_PAGE_KEEP_POS) {
                            mRecyclerView.stopScroll();
                            LayoutManagerUtils.scrollToPositionProperly(mRecyclerView.getLayoutManager(), getContext(),
                                    dataSize - 1, mOnScrollToPositionListener);
                        } else {
                            mRecyclerView.stopScroll();
                            LayoutManagerUtils.scrollToPositionWithOffset(mRecyclerView.getLayoutManager(), 0, 0);
                            onScrollToPosition();
                        }
                        break;
                    case TYPE_NEXT_PAGE:
                    case TYPE_NEXT_PAGE_KEEP_POS:
                        dataSize = data.size();
                        int oldDataSize = mData.size();
                        mData.addAll(data);
                        notifyItemRangeInserted(oldDataSize, dataSize);

                        mPageDivider.add(oldDataSize + dataSize);

                        mEndPage++;
                        if (mCurrentTaskType == TYPE_NEXT_PAGE_KEEP_POS) {
                            mRecyclerView.stopScroll();
                            mRecyclerView.smoothScrollBy(0, mNextPageScrollSize);
                            onScrollToPosition();
                        } else {
                            mRecyclerView.stopScroll();
                            LayoutManagerUtils.scrollToPositionWithOffset(mRecyclerView.getLayoutManager(), oldDataSize, 0);
                            onScrollToPosition();
                        }
                        break;
                    case TYPE_SOMEWHERE:
                        mData.clear();
                        mData.addAll(data);
                        notifyDataSetChanged();

                        mStartPage = mCurrentTaskPage;
                        mEndPage = mCurrentTaskPage + 1;

                        mPageDivider.clear();
                        mPageDivider.add(data.size());

                        mRecyclerView.stopScroll();
                        LayoutManagerUtils.scrollToPositionWithOffset(mRecyclerView.getLayoutManager(), 0, 0);
                        onScrollToPosition();
                        break;
                    case TYPE_REFRESH_PAGE:
                        if (mCurrentTaskPage < mStartPage || mCurrentTaskPage >= mEndPage) {
                            Log.e(TAG, "TYPE_REFRESH_PAGE, but mCurrentTaskPage = " + mCurrentTaskPage +
                                    ", mStartPage = " + mStartPage + ", mEndPage = " + mEndPage);
                            break;
                        }

                        int oldIndexStart = mCurrentTaskPage == mStartPage ? 0 : mPageDivider.get(mCurrentTaskPage - mStartPage - 1);
                        int oldIndexEnd = mPageDivider.get(mCurrentTaskPage - mStartPage);
                        mData.subList(oldIndexStart, oldIndexEnd).clear();
                        int newIndexStart = oldIndexStart;
                        int newIndexEnd = newIndexStart + data.size();
                        mData.addAll(oldIndexStart, data);
                        notifyDataSetChanged();

                        for (int i = mCurrentTaskPage - mStartPage, n = mPageDivider.size(); i < n; i++) {
                            mPageDivider.set(i, mPageDivider.get(i) - oldIndexEnd + newIndexEnd);
                        }

                        if (newIndexEnd > oldIndexEnd && newIndexEnd > 0) {
                            mRecyclerView.stopScroll();
                            LayoutManagerUtils.scrollToPositionWithOffset(mRecyclerView.getLayoutManager(), newIndexEnd - 1, 0);
                            onScrollToPosition();
                        }
                        break;
                }
            }

            mRefreshLayout.setHeaderRefreshing(false);
            mRefreshLayout.setFooterRefreshing(false);
        }

        public void onGetExpection(int taskId, Exception e) {
            if (mCurrentTaskId == taskId) {
                if (e != null) {
                    e.printStackTrace();
                }

                mRefreshLayout.setHeaderRefreshing(false);
                mRefreshLayout.setFooterRefreshing(false);
                Say.d(TAG, "Get page data failed " + e.getClass().getName() + " " + e.getMessage());
                String readableError = ExceptionUtils.getReadableString(getContext(), e);
                String reason = ExceptionUtils.getReasonString(getContext(), e);
                if (reason != null) {
                    readableError += '\n' + reason;
                }
                if (mViewTransition.getShownViewIndex() == 0) {
                    Toast.makeText(getContext(), readableError, Toast.LENGTH_SHORT).show();
                } else {
                    showText(readableError);
                }
            }
        }

        public void showContent() {
            mViewTransition.showView(0);
        }

        private boolean isContentShowning() {
            return mViewTransition.getShownViewIndex() == 0;
        }

        public void showProgressBar() {
            mViewTransition.showView(1, false);
        }

        public void showProgressBar(boolean animation) {
            if (mViewTransition.showView(1, animation)) {
                onShowProgress();
            }
        }

        public void showText(CharSequence text) {
            mTextView.setText(text);
            if (mViewTransition.showView(2)) {
                onShowText();
            }
        }

        public void showEmptyString() {
            showText(mEmptyString);
        }

        /**
         * Be carefull
         */
        public void doGetData(int type, int page, int refreshType) {
            switch (refreshType) {
                default:
                case REFRESH_TYPE_HEADER:
                    showContent();
                    mRefreshLayout.setFooterRefreshing(false);
                    mRefreshLayout.setHeaderRefreshing(true);
                    break;
                case REFRESH_TYPE_FOOTER:
                    showContent();
                    mRefreshLayout.setHeaderRefreshing(false);
                    mRefreshLayout.setFooterRefreshing(true);
                    break;
                case REFRESH_TYPE_PROGRESS_VIEW:
                    showProgressBar();
                    mRefreshLayout.setHeaderRefreshing(false);
                    mRefreshLayout.setFooterRefreshing(false);
                    break;
            }

            mCurrentTaskId = mIdGenerator.nextId();
            mCurrentTaskType = type;
            mCurrentTaskPage = page;
            getPageData(mCurrentTaskId, mCurrentTaskType, mCurrentTaskPage);
        }

        private void doRefresh() {
            mCurrentTaskId = mIdGenerator.nextId();
            mCurrentTaskType = TYPE_REFRESH;
            mCurrentTaskPage = 0;
            getPageData(mCurrentTaskId, mCurrentTaskType, mCurrentTaskPage);
        }

        /**
         * Lisk {@link #refresh()}, but no animation when show progress bar
         */
        public void firstRefresh() {
            showProgressBar(false);
            doRefresh();
        }

        /**
         * Show progress bar first, than do refresh
         */
        public void refresh() {
            showProgressBar();
            doRefresh();
        }

        private void cancelCurrentTask() {
            mCurrentTaskId = mIdGenerator.nextId();
            mRefreshLayout.setHeaderRefreshing(false);
            mRefreshLayout.setFooterRefreshing(false);
        }

        private int getPageStart(int page) {
            if (mStartPage == page) {
                return 0;
            } else {
                return mPageDivider.get(page - mStartPage - 1);
            }
        }

        private int getPageEnd(int page) {
            return mPageDivider.get(page - mStartPage);
        }

        private int getPageForPosition(int position) {
            if (position < 0) {
                return -1;
            }

            IntList pageDivider = mPageDivider;
            for (int i = 0, n = pageDivider.size(); i < n; i++) {
                if (position < pageDivider.get(i)) {
                    return i + mStartPage;
                }
            }

            return -1;
        }

        public int getPageForTop() {
            return getPageForPosition(LayoutManagerUtils.getFirstVisibleItemPosition(mRecyclerView.getLayoutManager()));
        }

        public int getPageForBottom() {
            return getPageForPosition(LayoutManagerUtils.getLastVisibleItemPosition(mRecyclerView.getLayoutManager()));
        }

        public boolean canGoTo() {
            return isContentShowning();
        }

        /**
         * Check range first!
         *
         * @param page the targe page
         * @throws IndexOutOfBoundsException
         */
        public void goTo(int page) throws IndexOutOfBoundsException {
            if (page < 0 || page >= mPages) {
                throw new IndexOutOfBoundsException("Page count is " + mPages + ", page is " + page);
            } else if (page >= mStartPage && page < mEndPage) {
                cancelCurrentTask();

                int position = getPageStart(page);
                mRecyclerView.stopScroll();
                LayoutManagerUtils.scrollToPositionWithOffset(mRecyclerView.getLayoutManager(), position, 0);
                onScrollToPosition();
            } else if (page == mStartPage - 1) {
                mRefreshLayout.setFooterRefreshing(false);
                mRefreshLayout.setHeaderRefreshing(true);

                mCurrentTaskId = mIdGenerator.nextId();
                mCurrentTaskType = TYPE_PRE_PAGE;
                mCurrentTaskPage = page;
                getPageData(mCurrentTaskId, mCurrentTaskType, mCurrentTaskPage);
            } else if (page == mEndPage) {
                mRefreshLayout.setHeaderRefreshing(false);
                mRefreshLayout.setFooterRefreshing(true);

                mCurrentTaskId = mIdGenerator.nextId();
                mCurrentTaskType = TYPE_NEXT_PAGE;
                mCurrentTaskPage = page;
                getPageData(mCurrentTaskId, mCurrentTaskType, mCurrentTaskPage);
            } else {
                mRefreshLayout.setFooterRefreshing(false);
                mRefreshLayout.setHeaderRefreshing(true);

                mCurrentTaskId = mIdGenerator.nextId();
                mCurrentTaskType = TYPE_SOMEWHERE;
                mCurrentTaskPage = page;
                getPageData(mCurrentTaskId, mCurrentTaskType, mCurrentTaskPage);
            }
        }
    }
}


text:
require('normalize.css/normalize.css');
require('styles/App.scss');

import React from 'react';
import ReactDOM from 'react-dom';
//获取图片相关的数据
var imageDatas = require('../data/imageData.json');
//利用自执行函数,将图片名信息转成图片URL路径信息
imageDatas = (function getImageURL(imageDatasArr) {
  for (var i = 0, j = imageDatasArr.length; i < j; i++) {
    var singleImageData = imageDatasArr[i];

    singleImageData.imageURL = require('../images/' + singleImageData.fileName);

    imageDatasArr[i] = singleImageData;
  }
  return imageDatasArr;
})(imageDatas);
//封装函数,获取区间内的一个随机值
function getRangeRandom(low, high) {
  return Math.ceil(Math.random() * (high - low) + low);
}
//获取0~30之间的一个任意正负值
function get30DegRandom() {
  return ((Math.random() > 0.5 ? '' : '-') + Math.ceil(Math.random() * 30));
}

/*
组件
 */
var ImgFigure = React.createClass({

  /*
  imgFigure的点击处理函数
   */
  handleClick: function(e) {
    if (this.props.arrange.isCenter) {
      this.props.inverse();
    } else {
      this.props.center();
    }

    e.stopPropagation();
    e.preventDefault();

  },
  render: function() {

    var styleObj = {};

    //如果props属性中指定了这张图片的信息,则使用
    if (this.props.arrange.pos) {
      styleObj = this.props.arrange.pos;
    }
    //如果图片的旋转角度有值并且不为0,添加旋转角度
    if (this.props.arrange.rotate) {
      (['MozTransform', 'msTransform', 'WebkitTransform', 'transform']).forEach(function(value) {
        styleObj['transform'] = 'rotate(' + this.props.arrange.rotate + 'deg)';
      }.bind(this));

    }

    if (this.props.arrange.isCenter) {
      styleObj.zIndex = 11;
    }

    var imgFigureClassName = 'img-figure';
    imgFigureClassName += this.props.arrange.isInverse ? ' is-inverse' : '';
    return (

{this.props.data.title}

      {this.props.data.desc}

    )
  }
});

/*控制组件*/

var ControllerUnit = React.createClass({

  handleClick: function(e) {
    //如果点击的是当前正在选中态的按钮,则翻转图片,否则将图片居中
    if (this.props.arrange.isCenter) {
      this.props.inverse();
    } else {
      this.props.center();
    }
    e.preventDefault();
    e.stopPropagation();
  },
  render: function() {
    var controllerUnitClassName = 'controller-unit';

    //如果对应的是居中的图片,显示控制按钮的居中状态
    if (this.props.arrange.isCenter) {
      controllerUnitClassName += ' is-center';
      if (this.props.arrange.isInverse) {
        controllerUnitClassName += ' is-inverse';
      }

    }
    return (

    );

  }
});

/*
组件
 */

var AppComponent = React.createClass({

  //舞台控制图片位置区域的分布
  Constant: {
    centerPos: {
      left: 0,
      right: 0
    },
    hPosRange: { //水平方向的取值范围
      leftSecX: [0, 0],
      rightSecX: [0, 0],
      y: [0, 0]
    },
    vPosRange: { //垂直方向的取值范围
      x: [0, 0],
      topY: [0, 0]
    }
  },

  /*
  翻转图片
  @param index 输入当前被执行inverse操作的图片对应的图片信息数组的index值
  @return{Function} 这是一个闭包函数,其内return一个真正待被执行的函数
   */
  inverse: function(index) {
    return function() {
      var imgsArrangeArr = this.state.imgsArrangeArr;

      imgsArrangeArr[index].isInverse = !imgsArrangeArr[index].isInverse;

      this.setState({
        imgsArrangeArr: imgsArrangeArr
      });
    }.bind(this);
  },

  /* 重新布局所有图片*/
  rearrange: function(centerIndex) {
    var imgsArrangeArr = this.state.imgsArrangeArr,
      Constant = this.Constant,
      centerPos = Constant.centerPos,
      hPosRange = Constant.hPosRange,
      vPosRange = Constant.vPosRange,
      hPosRangeLeftSecX = hPosRange.leftSecX,
      hPosRangeRightSecx = hPosRange.rightSecX,
      hPosRangeY = hPosRange.y,
      vPosRangeTopY = vPosRange.topY,
      vPosRangeX = vPosRange.x,

      imgsArrangeTopArr = [],

      topImgNum = Math.floor(Math.random() * 2), //排布上方的图片个数
      topImgSpliceIndex = 0,

      imgsArrangeCenterArr = imgsArrangeArr.splice(centerIndex, 1);
    //首先居中centerIndex图片,居中的centerIndex图片不需要旋转
    imgsArrangeCenterArr[0] = {
      pos: centerPos,
      rotate: 0,
      isCenter: true
    };

    //取出要布局上侧的图片的状态信息
    topImgSpliceIndex = Math.ceil(Math.random() * (imgsArrangeArr.length - topImgNum));
    imgsArrangeTopArr = imgsArrangeArr.splice(topImgSpliceIndex, topImgNum);

    //布局位于上侧的图片
    imgsArrangeTopArr.forEach(function(value, index) {
      imgsArrangeTopArr[index] = {
        pos: {
          top: getRangeRandom(vPosRangeTopY[0], vPosRangeTopY[1]),
          left: getRangeRandom(vPosRangeX[0], vPosRangeX[1])
        },
        rotate: get30DegRandom(),
        isCenter: false

      };
    });
    //布局左右两侧的图片
    for (var i = 0, j = imgsArrangeArr.length, k = j / 2; i < j; i++) {
      var hPosRangeLORX = null;
      //前半部分布局左边,右半部分布局右边
      if (i < k) {
        hPosRangeLORX = hPosRangeLeftSecX;
      } else {
        hPosRangeLORX = hPosRangeRightSecx;
      }
      imgsArrangeArr[i] = {
        pos: {
          top: getRangeRandom(hPosRangeY[0], hPosRangeY[1]),
          left: getRangeRandom(hPosRangeLORX[0], hPosRangeLORX[1])
        },
        rotate: get30DegRandom(),
        isCenter: false

      };
    }

    if (imgsArrangeTopArr && imgsArrangeTopArr[0]) {
      imgsArrangeArr.splice(topImgSpliceIndex, 0, imgsArrangeTopArr[0]);
    }

    imgsArrangeArr.splice(centerIndex, 0, imgsArrangeCenterArr[0]);

    this.setState({
      imgsArrangeArr: imgsArrangeArr
    });
  },

  /*利用rearrange 函数,居中对应index的图片
   */
  center: function(index) {
    return function() {
      this.rearrange(index);
    }.bind(this);
  },

  getInitialState: function() {
    return {
      imgsArrangeArr: [
        /*{
                pos:{
                  left:'0',
                  top:'0'
                },
                rotate:0 ,  //旋转角度
                isInverse:false , //图片正反面
                isCenter:false
              }*/
      ]
    };
  },

  //组件加载以后,为每张图片计算其位置的范围
  componentDidMount: function() {
    //首先拿到舞台大小
    var stageDOM = ReactDOM.findDOMNode(this.refs.stage),
      stageW = stageDOM.scrollWidth,
      stageH = stageDOM.scrollHeight,
      halfStageW = Math.ceil(stageW / 2),
      halfStageH = Math.ceil(stageH / 2);
    //拿到一个imageFigure的大小
    var imgFigureDOM = ReactDOM.findDOMNode(this.refs.imgFigure0),
      imgW = imgFigureDOM.scrollWidth,
      imgH = imgFigureDOM.scrollHeight,
      halfImgW = Math.ceil(imgW / 2),
      halfImgH = Math.ceil(imgH / 2);

    //计算中心图片的位置点
    this.Constant.centerPos = {
      left: halfStageW - halfImgW,
      top: halfStageH - halfImgH
    };
    //计算左右侧 图片排布取值范围
    this.Constant.hPosRange.leftSecX[0] = -halfImgW;
    this.Constant.hPosRange.leftSecX[1] = halfStageW - halfImgW * 3;
    this.Constant.hPosRange.rightSecX[0] = halfStageW + halfImgW;
    this.Constant.hPosRange.rightSecX[1] = stageW - halfImgW;
    this.Constant.hPosRange.y[0] = -halfImgH;
    this.Constant.hPosRange.y[1] = stageH - halfImgH;
    //计算上册区域图片排布范围
    this.Constant.vPosRange.topY[0] = -halfImgH;
    this.Constant.vPosRange.topY[1] = halfStageH - halfImgH * 3;
    this.Constant.vPosRange.x[0] = halfStageW - imgW;
    this.Constant.vPosRange.x[1] = halfStageW;

    this.rearrange(0);
  },
  render: function() {

    var controllerUnits = [],
      imgFigures = [];
    imageDatas.forEach(function(value, index) {
      if (!this.state.imgsArrangeArr[index]) {
        this.state.imgsArrangeArr[index] = {
          pos: {
            left: 0,
            top: 0
          },
          rotate: 0,
          isInverse: false,
          isCenter: false
        };
      }
      imgFigures.push(<ImgFigure key={index} data={value} ref={'imgFigure'+index} arrange={this.state.imgsArrangeArr[index]} inverse={this.inverse(index)} center={this.center(index)}/>);
      controllerUnits.push(<ControllerUnit key={index} arrange={this.state.imgsArrangeArr[index]} inverse={this.inverse(index)} center={this.center(index)}/>);
    }.bind(this));

    return (

      {imgFigures}

      {controllerUnits}

    );
  }
});

//AppComponent.defaultProps = {};

export default AppComponent;

redpajama_set_name: RedPajamaGithub


text:
import sqlite3
import time
import threading
import SimpleHTTPServer, SocketServer
import urlparse
import json
import psapi

RunWebServer = False

class MyHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def do_GET(self):
        parsedParams = urlparse.urlparse(self.path)
        queryParsed = urlparse.parse_qs(parsedParams.query)
        params = parsedParams.path.split("&")

        jsonp = ""
        if len(params) > 1:
            callback = params[1].split("=")
            if callback[0] == "callback":
                jsonp = callback[1]

        pathlist = params[0].split("/")

        if len(pathlist) > 0:
            if pathlist[1] == "data":
                self.processJsonRequest(queryParsed, pathlist[2:], jsonp)
                return
        # Default to serve up a local file
        self.path = "http/" + self.path
        SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self);

    def processJsonRequest(self, query, pathlist, jsonp):
        if len(pathlist) < 1:
            self.wfile.write("{}");     # Error: path has nothing after /data
        else:
            jsonData = psapi.ExecCommand({'cmd':'getobject', 'path':pathlist})
            self.sendJsonAscii(jsonData, jsonp)
        self.wfile.close();

    def sendJsonAscii(self, jsonData, jsonp):
        self.send_response(200)
        self.send_header('Content-Type', 'text/javascript; charset=utf-8')
        self.end_headers()
        if not len(jsonp) == 0:
            self.wfile.write(jsonp + '({"query":')
        self.wfile.write(json.dumps(jsonData))
        if not len(jsonp) == 0:
            self.wfile.write("})")

Handler = MyHandler

def WebServerMain():
    PORT = 80
    global httpd
    httpd = SocketServer.ThreadingTCPServer(("", PORT), Handler)
    httpd.timeout = 1
    print "Serving at port", PORT
    while RunWebServer:
        httpd.serve_forever()

def WebServerOpen():
    global RunWebServer
    RunWebServer = True
    global WebServerThread
    WebServerThread = threading.Thread(target=WebServerMain)
    WebServerThread.start()

def WebServerClose():
    print "Closing web server"
    global RunWebServer
    global httpd
    RunWebServer = False
    httpd.shutdown()
    WebServerThread.join()
    print "Done"

WebServerOpen()
try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    print "KeyboardInterrupt"
WebServerClose()


text:
title: Disable Your Google Account History to Keep Your Privacy
date: 2014-11-13 11:40:38 +0100
excerpt: If you are interested in keeping your privacy and use Google products it's highly recommended to disable your Google account history.
categories: Web
tags: [Google, Privacy]
permalink: /disable-google-account-history-keep-privacy
layout: post
---
If you are interested in keeping your privacy and use Google products it's a good idea to disable your [Google account history](https://myaccount.google.com/activitycontrols). To view your history you have to be logged-in.

On the account history page you are able to view and disable several histories Google is automatically keeping. These histories allow Google to tailor their ad displays to better suit your interests. As a result you get _more relevant_ ads displayed while surfing the web.

While this sounds not bad, these histories are actually a track record of your behavior. If you value your privacy it's recommended to minimize any tracking. All of this data is shared within Google i.e. your search behavior is linked to your YouTube behavior. Here are some direct links for viewing your histories. All of them are also on your [Google account history](https://myaccount.google.com/activitycontrols).

## [Google Search History](https://history.google.com/history)

All your searches you did while using Google's search engine are displayed here. This can easily add up to a lot of information because people are googling a lot.

## [Google Location History](https://maps.google.de/locationhistory/b/0/)

This is your location history which shows all physical locations you have been at while using location-enabled Google products like Google Now, Goggle Maps or other Google sites which use the location of your web browser.

## [YouTube Search History](https://www.youtube.com/feed/history/search_history)

YouTube's search history doesn't have much user-value because the watch history is much more useful. So disabling won't hurt much.

## [YouTube Watch History](https://www.youtube.com/feed/history)

While YouTube's watch history has some value to find this particular video from last week which you want to show to somebody but don't remember the name you might want to disable this if you are privacy-sensitive.

## [Settings for Interest-Based Ads](https://adssettings.google.com/authenticated)

This is the core of Google's ad display technology. If you don't want Google to know about your interests and habits to create a huge personal profile about you it's time to turn it off. You don't have any control about future applications of this data and might not like the consequences.

__I recommend to first delete all histories and then disable all of them, especially location and interest-based ads. You don't lose much value and all products work perfectly without these.__

## But Google Still Stores this Information

Disabling histories in your Google account will not prevent Google from gathering and storing this information and using it for internal purposes. It also does not change the fact that any information gathered and stored by Google could be sought by law enforcement.

__With histories enabled, Google will keep these records indefinitely; with it disabled, they will be partially anonymized after 18 months.__

All of this can change for the worse if Google changes it's [privacy policy](https://www.google.com/policies/privacy/) again.


text:
/**
 * @class FeedViewer.FeedInfo
 * @extends Ext.tab.Panel
 *
 * A container class for showing a series of feed details
 *
 * @constructor
 * Create a new Feed Info
 * @param {Object} config The config object
 */
Ext.define('FeedViewer.FeedInfo', {

    extend: 'Ext.tab.Panel',
    alias: 'widget.feedinfo',

    maxTabWidth: 230,
    border: false,

    initComponent: function() {
        this.tabBar = {
            border: true
        };

        this.callParent();
    },

    /**
     * Add a new feed
     * @param {String} title The title of the feed
     * @param {String} url The url of the feed
     */
    addFeed: function(title, url){
        var active = this.items.first();
        if (!active) {
            active = this.add({
                xtype: 'feeddetail',
                title: title,
                url: url,
                closable: false,
                listeners: {
                    scope: this,
                    opentab: this.onTabOpen,
                    openall: this.onOpenAll,
                    rowdblclick: this.onRowDblClick
                }
            });
        } else {
            active.loadFeed(url);
            active.tab.setText(title);
        }
        this.setActiveTab(active);
    },

    /**
     * Listens for a new tab request
     * @private
     * @param {FeedViewer.FeedPost} post The post
     * @param {Ext.data.Model} rec The model instance
     */
    onTabOpen: function(post, rec){
        var items = [],
            item,
            title;

        if (Ext.isArray(rec)) {
            Ext.each(rec, function(rec) {
                title = rec.get('title');
                if (!this.getTabByTitle(title)) {
                    items.push({
                        inTab: true,
                        xtype: 'feedpost',
                        title: title,
                        closable: true,
                        data: rec.data,
                        active: rec
                    });
                }
            }, this);
            this.add(items);
        }
        else if (rec) {
            title = rec.get('title');
            item = this.getTabByTitle(title);
            if (!item) {
                item = this.add({
                    inTab: true,
                    xtype: 'feedpost',
                    title: title,
                    closable: true,
                    data: rec.data,
                    active: rec
                });
            }
            this.setActiveTab(item);
        }
    },

    /**
     * Find a tab by title
     * @param {String} title The title of the tab
     * @return {Ext.Component} The panel matching the title. null if not found.
     */
    getTabByTitle: function(title) {
        var index = this.items.findIndex('title', title);
        return (index < 0) ? null : this.items.getAt(index);
    },

    /**
     * Listens for a row dblclick
     * @private
     * @param {FeedViewer.Detail} info The detail
     * @param {Ext.data.Model} rec The model instance
     */
    onRowDblClick: function(info, rec){
        this.onTabOpen(null, rec);
    },

    /**
     * Listens for the open all click
     * @private
     * @param {FeedViewer.FeedDetail} detail
     */
    onOpenAll: function(detail){
        this.onTabOpen(null, detail.getFeedData());
    }
});


text:
export declare function backwards<T>(array: T[], callback: (el: T) => any): void;
export declare function each<T>(array: T[], callback: (el: T) => any): void;
export declare function safeEach<T>(array: T[], callback: (el: T) => any): void;
export declare function remove<T>(array: T[], item: T): void;
export declare function nullify<T>(array: T[], item: T): void;
export declare function compact<T>(array: T[]): void;
export interface Constructor {
    (): void;
}
export declare function extend(Klass: Constructor, OtherKlass: Constructor): Constructor;
export interface NumericMap<V> {
    [key: number]: V;
}
export interface StringMap<V> {
    [key: string]: V;
}


text:
HTTPLIB_OPEN_NAMESPACE

namespace detail {

template<class BufferedReadStream, class Handler>
struct async_read_response_op {
    BufferedReadStream &stream;
    read_options_t options;
    Handler handler;

    http_response_parser_t parser;

    async_read_response_op(BufferedReadStream &stream,
                           read_options_t options,
                           Handler handler) :
        stream(stream),
        options(options),
        handler(std::move(handler))
    {
        parser.set_options(options.parsing);
    }

    void start() {
        if (stream.buffer().size() != 0) {
            consume_buffer();

            if (parser.done()) {
                stream.stream().get_io_service().post(std::move(*this));
                return;
            }
        }

        start_async_read();
    }

    void operator()() {
        assert(parser.done());

        if (parser.error()) {
            handler(parser.error(), http_response_t());
        } else {
            handler(boost::system::error_code(), parser.response());
        }
    }

    void operator()(boost::system::error_code ec, std::size_t transferred) {
        if (transferred > 0) {
            stream.buffer().commit(transferred);
        }

        if (stream.buffer().size() != 0) {
            consume_buffer();

            if (parser.done()) {
                (*this)();
                return;
            }
        }

        if (ec) {
            handler(ec, http_response_t());
            return;
        }

        start_async_read();
    }

    friend void *asio_handler_allocate(std::size_t size, async_read_response_op *context) {
        using boost::asio::asio_handler_allocate;
        return asio_handler_allocate(size, &context->handler);
    }

    friend void asio_handler_deallocate(void *pointer, std::size_t size, async_read_response_op *context) {
        using boost::asio::asio_handler_deallocate;
        asio_handler_deallocate(pointer, size, &context->handler);
    }

    friend bool asio_handler_is_continuation(async_read_response_op *context) {
        using boost::asio::asio_handler_is_continuation;
        return asio_handler_is_continuation(&context->handler);
    }

    template<class Callable>
    friend void asio_handler_invoke(Callable &function, async_read_response_op *context) {
        using boost::asio::asio_handler_invoke;
        asio_handler_invoke(function, &context->handler);
    }

    template<class Callable>
    friend void asio_handler_invoke(const Callable &function, async_read_response_op *context) {
        using boost::asio::asio_handler_invoke;
        asio_handler_invoke(function, &context->handler);
    }

private:
    void consume_buffer() {
        if (stream.buffer().size() == 0) {
            return;
        }

        auto buffers = stream.buffer().data();

        for (const auto &buf: buffers) {
            auto const_buffer = boost::asio::const_buffer(buf);

            while (boost::asio::buffer_size(const_buffer) > 0) {
                size_t parsed = parser.parse(boost::asio::buffer_cast<const char *>(const_buffer),
                                             boost::asio::buffer_size(const_buffer));

                const_buffer = boost::asio::const_buffer(
                    boost::asio::buffer_cast<const char *>(const_buffer) + parsed,
                    boost::asio::buffer_size(const_buffer) - parsed
                );

                stream.buffer().consume(parsed);

                if (parser.done()) {
                    return;
                }
            }
        }
    }

    void start_async_read() {
        stream.stream().async_read_some(
            stream.buffer().prepare(options.read_buffer_size),
            std::move(*this)
        );
    }
};

} // namespace detail

template<class BufferedReadStream, class Handler>
typename boost::asio::async_result<
    typename boost::asio::handler_type<Handler, void(boost::system::error_code, const http_response_t&)>::type
>::type
async_read_response(BufferedReadStream &stream, read_options_t options, Handler handler) {
    using handler_t = typename boost::asio::handler_type<Handler, void(boost::system::error_code, const http_response_t&)>::type;
    using op_t = detail::async_read_response_op<BufferedReadStream, handler_t>;

    handler_t concrete_handler = std::move(handler);
    boost::asio::async_result<handler_t> result(concrete_handler);
    op_t op(stream, options, std::move(concrete_handler));

    op.start();

    return result.get();
}

template<class BufferedReadStream, class Handler>
typename boost::asio::async_result<
    typename boost::asio::handler_type<Handler, void(boost::system::error_code, const http_response_t&)>::type
>::type
async_read_response(BufferedReadStream &stream, Handler handler) {
    return async_read_response(stream, {}, std::move(handler));
}

template<class BufferedReadStream>
http_response_t read_response(BufferedReadStream &stream,
                              read_options_t options,
                              boost::system::error_code &ec)
{
    http_response_parser_t parser;
    parser.set_options(options.parsing);

    while (true) {
        auto buffers = stream.buffer().data();

        for (const auto &buffer: buffers) {
            if (boost::asio::buffer_size(buffer) == 0) {
                continue;
            }

            std::size_t parsed = parser.parse(boost::asio::buffer_cast<const char *>(buffer),
                                              boost::asio::buffer_size(buffer));

            stream.buffer().consume(parsed);

            if (parser.done()) {
                if (parser.error()) {
                    ec = parser.error();
                    return {};
                } else {
                    return parser.response();
                }
            }
        }

        boost::system::error_code read_error;

        std::size_t transferred = stream.stream().read_some(
            stream.buffer().prepare(options.read_buffer_size),
            read_error
        );

        stream.buffer().commit(transferred);

        if (transferred == 0 && read_error) {
            ec = read_error;
            return {};
        }
    }
};

template<class BufferedReadStream>
http_response_t read_response(BufferedReadStream &stream, boost::system::error_code &ec) {
    return read_response(stream, read_options_t(), ec);
}

template<class BufferedReadStream>
http_response_t read_response(BufferedReadStream &stream, read_options_t options) {
    boost::system::error_code ec;
    http_response_t result = read_response(stream, std::move(options), ec);

    if (ec) {
        throw boost::system::system_error(ec);
    }

    return result;
}

template<class BufferedReadStream>
http_response_t read_response(BufferedReadStream &stream) {
    return read_response(stream, read_options_t());
}

HTTPLIB_CLOSE_NAMESPACE


text:
using namespace std;

bool isAnagram(QString, QString );

int main(int argc, char *argv[])
{
    QTextStream qin(stdin);
    QTextStream qout(stdout);

    // Output 'Hello World' to the console.
    qout << "Hello World!" << endl;

    // Return an array of the first 100 numbers that are divisible by 3 and 5.
    for(int i = 0; i <= 100; ++i)
    {
        if(i % 3 == 0 && i % 5 == 0)
            qout << i << endl;
    }

    // Create a program that verifies if a word is an anagram of another word.
    isAnagram("test", "test");

    // Create a program that removes a specificed letter from a word.
    qout << "Please input a word:" << endl;
    QString targetWord;
    qin >> targetWord;

    qout << endl << "Input a letter to be removed the word you just entered: " << endl;
    QString targetLetter;
    qin >> targetLetter;
    qout << targetWord.replace(targetLetter, "") << endl;

    // Sum all the elements of an array
    array<int, 100> numbers;
    int sum = 0;
    numbers.fill(10);
    for(unsigned int i = 0; i < numbers.size(); ++i)
    {
        sum += numbers[i];
    }
    qout << "Sum of " << numbers.size() << " numbers: " << sum << endl;

    // BONUS: Implement a bubble-sort.

    return 0;
}

bool isAnagram(QString word1, QString word2) {
    QTextStream qout(stdout);

    if(word1.size() != word2.size())
        return false;

    map<QChar, int> characters;
    for(QChar c : word1)
        ++characters[c];

    for(QChar c : word2)
        --characters[c];

    map<QChar, int>::iterator p;
    for(p = characters.cbegin(); p != characters.end(); ++p) {
        p->first;
    }

    return true;
}


text:
package com.webfirmframework.wffweb.server.page;

import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.locks.StampedLock;

/**
 * @since 12.0.0-beta.4
 */
final class TokenWrapper {

    final StampedLock lock = new StampedLock();

    private volatile String value;

    private volatile long updatedTimeMillis;

    private volatile int updatedId;

    final String key;

    TokenWrapper(final String key) {
        this.key = key;
    }

    /**
     * To set token pass token or token bytes. To remove token pass token and
     * orTokenBytes as null.
     *
     * @param value
     * @param orTokenBytes
     * @param writeTime
     * @param updatedId
     * @return
     */
    boolean setTokenAndWriteTime(final String value, final byte[] orTokenBytes, final long writeTime,
            final int updatedId) {
        return setTokenAndWriteTime(value, orTokenBytes, writeTime, updatedId, null, null);
    }

    boolean setTokenAndWriteTime(final String value, final byte[] orTokenBytes, final long writeTime,
            final int updatedId, final String key, final Map<String, TokenWrapper> tokenWrapperByKey) {
        if (writeTime >= updatedTimeMillis) {
            if (writeTime > updatedTimeMillis || (writeTime == updatedTimeMillis && updatedId > this.updatedId)) {
                if (orTokenBytes != null) {
                    this.value = new String(orTokenBytes, StandardCharsets.UTF_8);
                } else {
                    this.value = value;
                }
                if (value == null && orTokenBytes == null && tokenWrapperByKey != null && key != null) {
                    tokenWrapperByKey.remove(key);
                }
                updatedTimeMillis = writeTime;
                this.updatedId = updatedId;
                return true;
            }

        }
        return false;
    }

    public String getValue() {
        return value;
    }

    public long getUpdatedTimeMillis() {
        return updatedTimeMillis;
    }
}


text:
<?php

// Include PQLite library
require_once 'PQLite/PQLite.php';

class WP_Scraper {

}


text: export * from './sum-by';


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.Shared.Extensions;

namespace Microsoft.CodeAnalysis.InitializeParameter
{
    internal abstract partial class AbstractInitializeParameterCodeRefactoringProvider<
        TParameterSyntax,
        TStatementSyntax,
        TExpressionSyntax> : CodeRefactoringProvider
        where TParameterSyntax : SyntaxNode
        where TStatementSyntax : SyntaxNode
        where TExpressionSyntax : SyntaxNode
    {
        protected abstract bool IsFunctionDeclaration(SyntaxNode node);
        protected abstract bool IsImplicitConversion(Compilation compilation, ITypeSymbol source, ITypeSymbol destination);

        protected abstract SyntaxNode GetBody(SyntaxNode functionDeclaration);
        protected abstract SyntaxNode GetTypeBlock(SyntaxNode node);

        protected abstract void InsertStatement(
            SyntaxEditor editor, SyntaxNode functionDeclaration, IMethodSymbol method,
            SyntaxNode statementToAddAfterOpt, TStatementSyntax statement);

        protected abstract Task<ImmutableArray<CodeAction>> GetRefactoringsAsync(
            Document document, IParameterSymbol parameter, SyntaxNode functionDeclaration, IMethodSymbol method,
            IBlockOperation blockStatementOpt, CancellationToken cancellationToken);

        public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
        {
            var position = context.Span.Start;
            var document = context.Document;
            var cancellationToken = context.CancellationToken;

            var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
            var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            var token = root.FindToken(position);
            var parameterNode = GetParameterNode(token, position);
            if (parameterNode == null)
            {
                return;
            }

            // Only offered when there isn't a selection, or the selection exactly selects
            // a parameter name.
            var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
            if (!context.Span.IsEmpty)
            {
                var parameterName = syntaxFacts.GetNameOfParameter(parameterNode);
                if (parameterName == null || parameterName.Value.Span != context.Span)
                {
                    return;
                }
            }

            var functionDeclaration = parameterNode.FirstAncestorOrSelf<SyntaxNode>(IsFunctionDeclaration);
            if (functionDeclaration == null)
            {
                return;
            }

            var parameterDefault = syntaxFacts.GetDefaultOfParameter(parameterNode);

            // Don't offer inside the "=initializer" of a parameter
            if (parameterDefault?.Span.Contains(position) == true)
            {
                return;
            }

            var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            // we can't just call GetDeclaredSymbol on functionDeclaration because it could an anonymous function,
            // so first we have to get the parameter symbol and then its containing method symbol
            var parameter = (IParameterSymbol)semanticModel.GetDeclaredSymbol(parameterNode, cancellationToken);
            if (parameter == null || parameter.Name == "")
            {
                return;
            }

            var method = (IMethodSymbol)parameter.ContainingSymbol;
            if (method.IsAbstract ||
                method.IsExtern ||
                method.PartialImplementationPart != null ||
                method.ContainingType.TypeKind == TypeKind.Interface)
            {
                return;
            }

            if (CanOfferRefactoring(functionDeclaration, semanticModel, syntaxFacts, cancellationToken, out var blockStatementOpt))
            {
                // Ok.  Looks like a reasonable parameter to analyze.  Defer to subclass to
                // actually determine if there are any viable refactorings here.
                context.RegisterRefactorings(await GetRefactoringsAsync(
                    document, parameter, functionDeclaration, method, blockStatementOpt, cancellationToken).ConfigureAwait(false));
            }
        }

        private bool CanOfferRefactoring(SyntaxNode functionDeclaration, SemanticModel semanticModel, ISyntaxFactsService syntaxFacts, CancellationToken cancellationToken, out IBlockOperation blockStatementOpt)
        {
            blockStatementOpt = null;

            var functionBody = GetBody(functionDeclaration);
            if (functionBody == null)
            {
                // We support initializing parameters, even when the containing member doesn't have a
                // body. This is useful for when the user is typing a new constructor and hasn't written
                // the body yet.
                return true;
            }

            // In order to get the block operation for the body of an anonymous function, we need to
            // get it via `IAnonymousFunctionOperation.Body` instead of getting it directly from the body syntax.
            var operation = semanticModel.GetOperation(
                syntaxFacts.IsAnonymousFunction(functionDeclaration) ? functionDeclaration : functionBody,
                cancellationToken);

            if (operation == null)
            {
                return false;
            }

            switch (operation.Kind)
            {
                case OperationKind.AnonymousFunction:
                    blockStatementOpt = ((IAnonymousFunctionOperation)operation).Body;
                    break;
                case OperationKind.Block:
                    blockStatementOpt = (IBlockOperation)operation;
                    break;
                default:
                    return false;
            }

            return true;
        }

        private TParameterSyntax GetParameterNode(SyntaxToken token, int position)
        {
            var parameterNode = token.Parent?.FirstAncestorOrSelf<TParameterSyntax>();
            if (parameterNode != null)
            {
                return parameterNode;
            }

            // We may be on the comma of a param list.  Try the position before us.
            token = token.GetPreviousToken();
            if (position == token.FullSpan.End)
            {
                return token.Parent?.FirstAncestorOrSelf<TParameterSyntax>();
            }

            return null;
        }

        protected static bool IsParameterReference(IOperation operation, IParameterSymbol parameter)
            => UnwrapImplicitConversion(operation) is IParameterReferenceOperation parameterReference &&
               parameter.Equals(parameterReference.Parameter);

        protected static IOperation UnwrapImplicitConversion(IOperation operation)
            => operation is IConversionOperation conversion && conversion.IsImplicit
                ? conversion.Operand
                : operation;

        protected static bool ContainsParameterReference(
            SemanticModel semanticModel,
            IOperation condition,
            IParameterSymbol parameter,
            CancellationToken cancellationToken)
        {
            foreach (var child in condition.Syntax.DescendantNodes().OfType<TExpressionSyntax>())
            {
                var childOperation = semanticModel.GetOperation(child, cancellationToken);
                if (IsParameterReference(childOperation, parameter))
                {
                    return true;
                }
            }

            return false;
        }

        protected static bool IsFieldOrPropertyAssignment(IOperation statement, INamedTypeSymbol containingType, out IAssignmentOperation assignmentExpression)
            => IsFieldOrPropertyAssignment(statement, containingType, out assignmentExpression, out var fieldOrProperty);

        protected static bool IsFieldOrPropertyAssignment(
            IOperation statement, INamedTypeSymbol containingType,
            out IAssignmentOperation assignmentExpression, out ISymbol fieldOrProperty)
        {
            if (statement is IExpressionStatementOperation expressionStatement)
            {
                assignmentExpression = expressionStatement.Operation as IAssignmentOperation;
                return IsFieldOrPropertyReference(assignmentExpression?.Target, containingType, out fieldOrProperty);
            }

            fieldOrProperty = null;
            assignmentExpression = null;
            return false;
        }

        protected static bool IsFieldOrPropertyReference(IOperation operation, INamedTypeSymbol containingType)
            => IsFieldOrPropertyAssignment(operation, containingType, out var fieldOrProperty);

        protected static bool IsFieldOrPropertyReference(
            IOperation operation, INamedTypeSymbol containingType, out ISymbol fieldOrProperty)
        {
            if (operation is IMemberReferenceOperation memberReference &&
                memberReference.Member.ContainingType.Equals(containingType))
            {
                if (memberReference.Member is IFieldSymbol ||
                    memberReference.Member is IPropertySymbol)
                {
                    fieldOrProperty = memberReference.Member;
                    return true;
                }
            }

            fieldOrProperty = null;
            return false;
        }

        protected class MyCodeAction : CodeAction.DocumentChangeAction
        {
            public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument)
                : base(title, createChangedDocument)
            {
            }
        }
    }
}


text:
package sharded

import (
	"flag"
	"fmt"
	"os"
	"os/exec"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"

	"vitess.io/vitess/go/test/endtoend/cluster"
	"vitess.io/vitess/go/vt/log"
)

var (
	clusterInstance *cluster.LocalProcessCluster
	hostname        = "localhost"
	keyspaceName    = "ks"
	cell            = "zone1"
	sqlSchema       = `
		create table vt_select_test (
		id bigint not null,
		msg varchar(64),
		primary key (id)
		) Engine=InnoDB
		`
	sqlSchemaReverse = `
		create table vt_select_test (
		msg varchar(64),
		id bigint not null,
		primary key (id)
		) Engine=InnoDB
		`
	vSchema = `
		{
		  "sharded": true,
		  "vindexes": {
			"hash_index": {
			  "type": "hash"
			}
		  },
		  "tables": {
			"vt_select_test": {
			   "column_vindexes": [
				{
				  "column": "id",
				  "name": "hash_index"
				}
			  ]
			}
		  }
		}
	`
)

func TestMain(m *testing.M) {
	defer cluster.PanicHandler(nil)
	flag.Parse()

	exitcode, err := func() (int, error) {
		clusterInstance = cluster.NewCluster(cell, hostname)
		defer clusterInstance.Teardown()

		// Start topo server
		if err := clusterInstance.StartTopo(); err != nil {
			return 1, err
		}
		if err := clusterInstance.VtctlProcess.CreateKeyspace(keyspaceName); err != nil {
			return 1, err
		}

		initCluster([]string{"-80", "80-"}, 2)

		return m.Run(), nil
	}()
	if err != nil {
		fmt.Printf("%v\n", err)
		os.Exit(1)
	} else {
		os.Exit(exitcode)
	}

}

func TestShardedKeyspace(t *testing.T) {
	defer cluster.PanicHandler(t)
	shard1 := clusterInstance.Keyspaces[0].Shards[0]
	shard2 := clusterInstance.Keyspaces[0].Shards[1]

	shard1Primary := shard1.Vttablets[0]
	shard2Primary := shard2.Vttablets[0]
	err := clusterInstance.VtctlclientProcess.InitializeShard(keyspaceName, shard1.Name, cell, shard1Primary.TabletUID)
	require.Nil(t, err)
	err = clusterInstance.VtctlclientProcess.InitializeShard(keyspaceName, shard2.Name, cell, shard2Primary.TabletUID)
	require.Nil(t, err)

	// apply the schema on the first shard through vtctl, so all tablets
	// are the same.
	//apply the schema on the second shard.
	_, err = shard1Primary.VttabletProcess.QueryTablet(sqlSchema, keyspaceName, true)
	require.Nil(t, err)

	_, err = shard2Primary.VttabletProcess.QueryTablet(sqlSchemaReverse, keyspaceName, true)
	require.Nil(t, err)

	if err = clusterInstance.VtctlclientProcess.ApplyVSchema(keyspaceName, vSchema); err != nil {
		log.Error(err.Error())
		return
	}

	reloadSchemas(t,
		shard1Primary.Alias,
		shard1.Vttablets[1].Alias,
		shard2Primary.Alias,
		shard2.Vttablets[1].Alias)

	_ = clusterInstance.VtctlclientProcess.ExecuteCommand("SetReadWrite", shard1Primary.Alias)
	_ = clusterInstance.VtctlclientProcess.ExecuteCommand("SetReadWrite", shard2Primary.Alias)

	_, _ = shard1Primary.VttabletProcess.QueryTablet("insert into vt_select_test (id, msg) values (1, 'test 1')", keyspaceName, true)
	_, _ = shard2Primary.VttabletProcess.QueryTablet("insert into vt_select_test (id, msg) values (10, 'test 10')", keyspaceName, true)

	err = clusterInstance.VtctlclientProcess.ExecuteCommand("Validate", "--", "--ping-tablets")
	require.Nil(t, err)

	rows, err := shard1Primary.VttabletProcess.QueryTablet("select id, msg from vt_select_test order by id", keyspaceName, true)
	require.Nil(t, err)
	assert.Equal(t, `[[INT64(1) VARCHAR("test 1")]]`, fmt.Sprintf("%v", rows.Rows))

	err = clusterInstance.VtctlclientProcess.ExecuteCommand("ValidateSchemaShard", fmt.Sprintf("%s/%s", keyspaceName, shard1.Name))
	require.Nil(t, err)

	err = clusterInstance.VtctlclientProcess.ExecuteCommand("ValidateSchemaShard", fmt.Sprintf("%s/%s", keyspaceName, shard1.Name))
	require.Nil(t, err)

	output, err := clusterInstance.VtctlclientProcess.ExecuteCommandWithOutput("ValidateSchemaKeyspace", keyspaceName)
	require.Error(t, err)
	// We should assert that there is a schema difference and that both the shard primaries are involved in it.
	// However, we cannot assert in which order the two primaries will occur since the underlying function does not guarantee that
	// We could have an output here like `schemas differ ... shard1Primary ... differs from: shard2Primary ...` or `schemas differ ... shard2Primary ... differs from: shard1Primary ...`
	assert.Contains(t, output, "schemas differ on table vt_select_test:")
	assert.Contains(t, output, shard1Primary.Alias+": CREATE TABLE")
	assert.Contains(t, output, shard2Primary.Alias+": CREATE TABLE")

	err = clusterInstance.VtctlclientProcess.ExecuteCommand("ValidateVersionShard", fmt.Sprintf("%s/%s", keyspaceName, shard1.Name))
	require.Nil(t, err)
	err = clusterInstance.VtctlclientProcess.ExecuteCommand("GetPermissions", shard1.Vttablets[1].Alias)
	require.Nil(t, err)
	err = clusterInstance.VtctlclientProcess.ExecuteCommand("ValidatePermissionsShard", fmt.Sprintf("%s/%s", keyspaceName, shard1.Name))
	require.Nil(t, err)
	err = clusterInstance.VtctlclientProcess.ExecuteCommand("ValidatePermissionsKeyspace", keyspaceName)
	require.Nil(t, err)

	rows, err = shard1Primary.VttabletProcess.QueryTablet("select id, msg from vt_select_test order by id", keyspaceName, true)
	require.Nil(t, err)
	assert.Equal(t, `[[INT64(1) VARCHAR("test 1")]]`, fmt.Sprintf("%v", rows.Rows))

	rows, err = shard2Primary.VttabletProcess.QueryTablet("select id, msg from vt_select_test order by id", keyspaceName, true)
	require.Nil(t, err)
	assert.Equal(t, `[[INT64(10) VARCHAR("test 10")]]`, fmt.Sprintf("%v", rows.Rows))
}

func reloadSchemas(t *testing.T, aliases ...string) {
	for _, alias := range aliases {
		if err := clusterInstance.VtctlclientProcess.ExecuteCommand("ReloadSchema", alias); err != nil {
			assert.Fail(t, "Unable to reload schema")
		}

	}
}

func initCluster(shardNames []string, totalTabletsRequired int) {
	keyspace := cluster.Keyspace{
		Name: keyspaceName,
	}
	for _, shardName := range shardNames {
		shard := &cluster.Shard{
			Name: shardName,
		}

		var mysqlCtlProcessList []*exec.Cmd

		for i := 0; i < totalTabletsRequired; i++ {
			// instantiate vttablet object with reserved ports
			tabletUID := clusterInstance.GetAndReserveTabletUID()
			tablet := &cluster.Vttablet{
				TabletUID: tabletUID,
				HTTPPort:  clusterInstance.GetAndReservePort(),
				GrpcPort:  clusterInstance.GetAndReservePort(),
				MySQLPort: clusterInstance.GetAndReservePort(),
				Alias:     fmt.Sprintf("%s-%010d", clusterInstance.Cell, tabletUID),
			}
			if i == 0 { // Make the first one as primary
				tablet.Type = "primary"
			}
			// Start Mysqlctl process
			tablet.MysqlctlProcess = *cluster.MysqlCtlProcessInstance(tablet.TabletUID, tablet.MySQLPort, clusterInstance.TmpDirectory)
			proc, err := tablet.MysqlctlProcess.StartProcess()
			if err != nil {
				return
			}
			mysqlCtlProcessList = append(mysqlCtlProcessList, proc)

			// start vttablet process
			tablet.VttabletProcess = cluster.VttabletProcessInstance(
				tablet.HTTPPort,
				tablet.GrpcPort,
				tablet.TabletUID,
				clusterInstance.Cell,
				shardName,
				keyspaceName,
				clusterInstance.VtctldProcess.Port,
				tablet.Type,
				clusterInstance.TopoProcess.Port,
				clusterInstance.Hostname,
				clusterInstance.TmpDirectory,
				clusterInstance.VtTabletExtraArgs,
				clusterInstance.EnableSemiSync,
				clusterInstance.DefaultCharset)
			tablet.Alias = tablet.VttabletProcess.TabletPath

			shard.Vttablets = append(shard.Vttablets, tablet)
		}
		for _, proc := range mysqlCtlProcessList {
			if err := proc.Wait(); err != nil {
				return
			}
		}

		for _, tablet := range shard.Vttablets {
			log.Info(fmt.Sprintf("Starting vttablet for tablet uid %d, grpc port %d", tablet.TabletUID, tablet.GrpcPort))

			if err := tablet.VttabletProcess.Setup(); err != nil {
				log.Error(err.Error())
				return
			}
		}

		keyspace.Shards = append(keyspace.Shards, *shard)
	}
	clusterInstance.Keyspaces = append(clusterInstance.Keyspaces, keyspace)
}


text:
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.xdebugger.impl;

import com.intellij.AppTopics;
import com.intellij.codeInsight.hint.LineTooltipRenderer;
import com.intellij.codeInsight.hint.TooltipController;
import com.intellij.codeInsight.hint.TooltipGroup;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.ExecutionManager;
import com.intellij.execution.Executor;
import com.intellij.execution.executors.DefaultDebugExecutor;
import com.intellij.execution.process.ProcessHandler;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.execution.ui.ExecutionConsole;
import com.intellij.execution.ui.RunContentDescriptor;
import com.intellij.execution.ui.RunContentManager;
import com.intellij.execution.ui.RunContentWithExecutorListener;
import com.intellij.idea.ActionsBundle;
import com.intellij.notification.NotificationGroup;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import com.intellij.openapi.components.StoragePathMacros;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.event.EditorMouseEvent;
import com.intellij.openapi.editor.event.EditorMouseEventArea;
import com.intellij.openapi.editor.event.EditorMouseListener;
import com.intellij.openapi.editor.event.EditorMouseMotionListener;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.editor.ex.util.EditorUtil;
import com.intellij.openapi.editor.impl.EditorImpl;
import com.intellij.openapi.editor.markup.GutterIconRenderer;
import com.intellij.openapi.editor.markup.RangeHighlighter;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.fileEditor.FileDocumentManagerListener;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.FileEditorManagerListener;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.Balloon;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.IdeGlassPaneUtil;
import com.intellij.openapi.wm.ToolWindowId;
import com.intellij.ui.HintHint;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.util.messages.MessageBus;
import com.intellij.util.messages.MessageBusConnection;
import com.intellij.util.ui.UIUtil;
import com.intellij.xdebugger.*;
import com.intellij.xdebugger.breakpoints.XBreakpoint;
import com.intellij.xdebugger.breakpoints.XBreakpointListener;
import com.intellij.xdebugger.breakpoints.XLineBreakpoint;
import com.intellij.xdebugger.impl.actions.XDebuggerActions;
import com.intellij.xdebugger.impl.breakpoints.XBreakpointBase;
import com.intellij.xdebugger.impl.breakpoints.XBreakpointManagerImpl;
import com.intellij.xdebugger.impl.evaluate.quick.common.ValueLookupManager;
import com.intellij.xdebugger.impl.settings.XDebuggerSettingManagerImpl;
import com.intellij.xdebugger.impl.ui.DebuggerUIUtil;
import com.intellij.xdebugger.impl.ui.ExecutionPointHighlighter;
import com.intellij.xdebugger.impl.ui.XDebugSessionTab;
import com.intellij.xdebugger.ui.DebuggerColors;
import one.util.streamex.StreamEx;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author nik
 */
@State(name = "XDebuggerManager", storages = @Storage(StoragePathMacros.WORKSPACE_FILE))
public class XDebuggerManagerImpl extends XDebuggerManager implements PersistentStateComponent<XDebuggerState> {
  public static final NotificationGroup NOTIFICATION_GROUP =
    NotificationGroup.toolWindowGroup("Debugger messages", ToolWindowId.DEBUG, false);

  private final Project myProject;
  private final XBreakpointManagerImpl myBreakpointManager;
  private final XDebuggerWatchesManager myWatchesManager;
  private final ExecutionPointHighlighter myExecutionPointHighlighter;
  private final Map<ProcessHandler, XDebugSessionImpl> mySessions = Collections.synchronizedMap(new LinkedHashMap<>());
  private final AtomicReference<XDebugSessionImpl> myActiveSession = new AtomicReference<>();

  private XDebuggerState myState = new XDebuggerState();

  public XDebuggerManagerImpl(final Project project, MessageBus messageBus) {
    myProject = project;
    myBreakpointManager = new XBreakpointManagerImpl(project, this);
    myWatchesManager = new XDebuggerWatchesManager();
    myExecutionPointHighlighter = new ExecutionPointHighlighter(project);

    MessageBusConnection messageBusConnection = messageBus.connect();
    messageBusConnection.subscribe(AppTopics.FILE_DOCUMENT_SYNC, new FileDocumentManagerListener() {
      @Override
      public void fileContentLoaded(@NotNull VirtualFile file, @NotNull Document document) {
        updateExecutionPoint(file, true);
      }

      @Override
      public void fileContentReloaded(@NotNull VirtualFile file, @NotNull Document document) {
        updateExecutionPoint(file, true);
      }
    });
    messageBusConnection.subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, new FileEditorManagerListener() {
      @Override
      public void fileOpened(@NotNull FileEditorManager source, @NotNull VirtualFile file) {
        updateExecutionPoint(file, false);
      }
    });
    messageBusConnection.subscribe(XBreakpointListener.TOPIC, new XBreakpointListener<XBreakpoint<?>>() {
      @Override
      public void breakpointChanged(@NotNull XBreakpoint<?> breakpoint) {
        if (!(breakpoint instanceof XLineBreakpoint)) {
          final XDebugSessionImpl session = getCurrentSession();
          if (session != null && breakpoint.equals(session.getActiveNonLineBreakpoint())) {
            final XBreakpointBase breakpointBase = (XBreakpointBase)breakpoint;
            breakpointBase.clearIcon();
            myExecutionPointHighlighter.updateGutterIcon(breakpointBase.createGutterIconRenderer());
          }
        }
      }

      @Override
      public void breakpointRemoved(@NotNull XBreakpoint<?> breakpoint) {
        XDebugSessionImpl session = getCurrentSession();
        if (session != null && breakpoint == session.getActiveNonLineBreakpoint()) {
          myExecutionPointHighlighter.updateGutterIcon(null);
        }
      }
    });

    messageBusConnection.subscribe(RunContentManager.TOPIC, new RunContentWithExecutorListener() {
      @Override
      public void contentSelected(@Nullable RunContentDescriptor descriptor, @NotNull Executor executor) {
        if (descriptor != null && executor.equals(DefaultDebugExecutor.getDebugExecutorInstance())) {
          XDebugSessionImpl session = mySessions.get(descriptor.getProcessHandler());
          if (session != null) {
            session.activateSession();
          }
          else {
            setCurrentSession(null);
          }
        }
      }

      @Override
      public void contentRemoved(@Nullable RunContentDescriptor descriptor, @NotNull Executor executor) {
        if (descriptor != null && executor.equals(DefaultDebugExecutor.getDebugExecutorInstance())) {
          mySessions.remove(descriptor.getProcessHandler());
        }
      }
    });

    DebuggerEditorListener listener = new DebuggerEditorListener();
    EditorFactory.getInstance().getEventMulticaster().addEditorMouseMotionListener(listener, myProject);
    EditorFactory.getInstance().getEventMulticaster().addEditorMouseListener(listener, myProject);
  }

  private void updateExecutionPoint(@NotNull VirtualFile file, boolean navigate) {
    if (file.equals(myExecutionPointHighlighter.getCurrentFile())) {
      myExecutionPointHighlighter.update(navigate);
    }
  }

  void updateExecutionPoint(GutterIconRenderer renderer) {
    myExecutionPointHighlighter.updateGutterIcon(renderer);
  }

  @Override
  @NotNull
  public XBreakpointManagerImpl getBreakpointManager() {
    return myBreakpointManager;
  }

  public XDebuggerWatchesManager getWatchesManager() {
    return myWatchesManager;
  }

  public Project getProject() {
    return myProject;
  }

  @Override
  @NotNull
  public XDebugSession startSession(@NotNull ExecutionEnvironment environment, @NotNull XDebugProcessStarter processStarter) throws ExecutionException {
    return startSession(environment.getContentToReuse(), processStarter, new XDebugSessionImpl(environment, this));
  }

  @Override
  @NotNull
  public XDebugSession startSessionAndShowTab(@NotNull String sessionName, @Nullable RunContentDescriptor contentToReuse,
                                              @NotNull XDebugProcessStarter starter) throws ExecutionException {
    return startSessionAndShowTab(sessionName, contentToReuse, false, starter);
  }

  @NotNull
  @Override
  public XDebugSession startSessionAndShowTab(@NotNull String sessionName, @Nullable RunContentDescriptor contentToReuse,
                                              boolean showToolWindowOnSuspendOnly,
                                              @NotNull XDebugProcessStarter starter) throws ExecutionException {
    return startSessionAndShowTab(sessionName, null, contentToReuse, showToolWindowOnSuspendOnly, starter);
  }

  @NotNull
  @Override
  public XDebugSession startSessionAndShowTab(@NotNull String sessionName,
                                              Icon icon,
                                              @Nullable RunContentDescriptor contentToReuse,
                                              boolean showToolWindowOnSuspendOnly,
                                              @NotNull XDebugProcessStarter starter) throws ExecutionException {
    XDebugSessionImpl session = startSession(contentToReuse, starter,
      new XDebugSessionImpl(null, this, sessionName, icon, showToolWindowOnSuspendOnly, contentToReuse));

    if (!showToolWindowOnSuspendOnly) {
      session.showSessionTab();
    }
    ProcessHandler handler = session.getDebugProcess().getProcessHandler();
    handler.startNotify();
    return session;
  }

  private XDebugSessionImpl startSession(@Nullable RunContentDescriptor contentToReuse,
                                         @NotNull XDebugProcessStarter processStarter,
                                         @NotNull XDebugSessionImpl session) throws ExecutionException {
    XDebugProcess process = processStarter.start(session);
    myProject.getMessageBus().syncPublisher(TOPIC).processStarted(process);

    // Perform custom configuration of session data for XDebugProcessConfiguratorStarter classes
    if (processStarter instanceof XDebugProcessConfiguratorStarter) {
      session.activateSession();
      ((XDebugProcessConfiguratorStarter)processStarter).configure(session.getSessionData());
    }

    session.init(process, contentToReuse);

    mySessions.put(session.getDebugProcess().getProcessHandler(), session);

    return session;
  }

  void removeSession(@NotNull final XDebugSessionImpl session) {
    XDebugSessionTab sessionTab = session.getSessionTab();
    mySessions.remove(session.getDebugProcess().getProcessHandler());
    if (sessionTab != null &&
        !myProject.isDisposed() &&
        !ApplicationManager.getApplication().isUnitTestMode() &&
        XDebuggerSettingManagerImpl.getInstanceImpl().getGeneralSettings().isHideDebuggerOnProcessTermination()) {
      ExecutionManager.getInstance(myProject).getContentManager().hideRunContent(DefaultDebugExecutor.getDebugExecutorInstance(),
                                                                                sessionTab.getRunContentDescriptor());
    }
    if (myActiveSession.compareAndSet(session, null)) {
      onActiveSessionChanged(session, null);
    }
  }

  void updateExecutionPoint(@Nullable XSourcePosition position, boolean nonTopFrame, @Nullable GutterIconRenderer gutterIconRenderer) {
    if (position != null) {
      myExecutionPointHighlighter.show(position, nonTopFrame, gutterIconRenderer);
    }
    else {
      myExecutionPointHighlighter.hide();
    }
  }

  private void onActiveSessionChanged(@Nullable XDebugSession previousSession, @Nullable XDebugSession currentSession) {
    myBreakpointManager.getLineBreakpointManager().queueAllBreakpointsUpdate();
    ApplicationManager.getApplication().invokeLater(() -> {
      ValueLookupManager.getInstance(myProject).hideHint();
      DebuggerUIUtil.repaintCurrentEditor(myProject); // to update inline debugger data
    }, myProject.getDisposed());
    if (!myProject.isDisposed()) {
      myProject.getMessageBus().syncPublisher(TOPIC).currentSessionChanged(previousSession, currentSession);
    }
  }

  @Override
  @NotNull
  public XDebugSession[] getDebugSessions() {
    // ConcurrentHashMap.values().toArray(new T[0]) guaranteed to return array with no nulls
    return mySessions.values().toArray(new XDebugSessionImpl[0]);
  }

  @Override
  @Nullable
  public XDebugSession getDebugSession(@NotNull ExecutionConsole executionConsole) {
    synchronized (mySessions) {
      for (final XDebugSessionImpl debuggerSession : mySessions.values()) {
        XDebugSessionTab sessionTab = debuggerSession.getSessionTab();
        if (sessionTab != null) {
          RunContentDescriptor contentDescriptor = sessionTab.getRunContentDescriptor();
          if (contentDescriptor != null && executionConsole == contentDescriptor.getExecutionConsole()) {
            return debuggerSession;
          }
        }
      }
    }
    return null;
  }

  @NotNull
  @Override
  public <T extends XDebugProcess> List<? extends T> getDebugProcesses(Class<T> processClass) {
    synchronized (mySessions) {
      return StreamEx.of(mySessions.values()).map(XDebugSessionImpl::getDebugProcess).select(processClass).toList();
    }
  }

  @Override
  @Nullable
  public XDebugSessionImpl getCurrentSession() {
    return myActiveSession.get();
  }

  void setCurrentSession(@Nullable XDebugSessionImpl session) {
    XDebugSessionImpl previousSession = myActiveSession.getAndSet(session);
    boolean sessionChanged = previousSession != session;
    if (sessionChanged) {
      if (session != null) {
        XDebugSessionTab tab = session.getSessionTab();
        if (tab != null) {
          tab.select();
        }
      }
      else {
        myExecutionPointHighlighter.hide();
      }
      onActiveSessionChanged(previousSession, session);
    }
  }

  @Override
  public XDebuggerState getState() {
    XDebuggerState state = myState;
    myBreakpointManager.saveState(state.getBreakpointManagerState());
    myWatchesManager.saveState(state.getWatchesManagerState());
    return state;
  }

  public boolean isFullLineHighlighter() {
    return myExecutionPointHighlighter.isFullLineHighlighter();
  }

  @Override
  public void loadState(@NotNull XDebuggerState state) {
    myState = state;
    myBreakpointManager.loadState(state.getBreakpointManagerState());
    myWatchesManager.loadState(state.getWatchesManagerState());
  }

  public void showExecutionPosition() {
    myExecutionPointHighlighter.navigateTo();
  }

  private static final TooltipGroup RUN_TO_CURSOR_TOOLTIP_GROUP = new TooltipGroup("RUN_TO_CURSOR_TOOLTIP_GROUP", 0);

  private class DebuggerEditorListener implements EditorMouseMotionListener, EditorMouseListener {
    RangeHighlighter myCurrentHighlighter;

    boolean isEnabled(@NotNull EditorMouseEvent e) {
      Editor editor = e.getEditor();
      if (e.getArea() != EditorMouseEventArea.LINE_NUMBERS_AREA ||
          editor.getProject() != myProject ||
          !EditorUtil.isRealFileEditor(editor) ||
          !XDebuggerSettingManagerImpl.getInstanceImpl().getGeneralSettings().isRunToCursorGestureEnabled()) {
        return false;
      }
      XDebugSessionImpl session = getCurrentSession();
      return session != null && session.isPaused() && !session.isReadOnly();
    }

    @Override
    public void mouseMoved(@NotNull EditorMouseEvent e) {
      if (!isEnabled(e)) {
        removeHighlighter(e);
        return;
      }
      removeHighlighter(e);

      int lineNumber = getLineNumber(e);
      if (lineNumber < 0) {
        return;
      }

      TextAttributes attributes = EditorColorsManager.getInstance().getGlobalScheme().getAttributes(DebuggerColors.NOT_TOP_FRAME_ATTRIBUTES);
      Editor editor = e.getEditor();
      myCurrentHighlighter = editor.getMarkupModel().addLineHighlighter(lineNumber,
                                                                        DebuggerColors.EXECUTION_LINE_HIGHLIGHTERLAYER,
                                                                        attributes);

      HintHint hint = new HintHint(e.getMouseEvent()).setAwtTooltip(true).setPreferredPosition(Balloon.Position.above);
      String text = UIUtil.removeMnemonic(ActionsBundle.actionText(XDebuggerActions.RUN_TO_CURSOR));
      TooltipController.getInstance()
        .showTooltipByMouseMove(editor, new RelativePoint(e.getMouseEvent()), new LineTooltipRenderer(text, new Object[]{text}), false,
                                RUN_TO_CURSOR_TOOLTIP_GROUP, hint);

      IdeGlassPaneUtil.find(e.getMouseEvent().getComponent()).setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR), this);
    }

    @Override
    public void mouseExited(@NotNull EditorMouseEvent e) {
      removeHighlighter(e);
    }

    private void removeHighlighter(@NotNull EditorMouseEvent e) {
      if (myCurrentHighlighter != null) {
        myCurrentHighlighter.dispose();
        TooltipController.getInstance().cancelTooltip(RUN_TO_CURSOR_TOOLTIP_GROUP, e.getMouseEvent(), true);
        IdeGlassPaneUtil.find(e.getMouseEvent().getComponent()).setCursor(null, this);
        myCurrentHighlighter = null;
      }
    }

    private int getLineNumber(EditorMouseEvent event) {
      Editor editor = event.getEditor();
      int line = editor.yToVisualLine(event.getMouseEvent().getY());
      if (line >= ((EditorImpl)editor).getVisibleLineCount()) {
        return -1;
      }
      int offset = ((EditorImpl)editor).visualLineStartOffset(line);
      int lineStartOffset = EditorUtil.getNotFoldedLineStartOffset(editor, offset);
      return editor.getDocument().getLineNumber(lineStartOffset);
    }

    @Override
    public void mousePressed(@NotNull EditorMouseEvent e) {
      if (e.getMouseEvent().getButton() == MouseEvent.BUTTON1 && isEnabled(e)) {
        int lineNumber = getLineNumber(e);
        XDebugSessionImpl session = getCurrentSession();
        if (session != null && lineNumber >= 0) {
          session.runToPosition(XSourcePositionImpl.create(((EditorEx)e.getEditor()).getVirtualFile(), lineNumber), false);
          e.consume();
        }
      }
    }
  }
}


text:
package com.jlj.service;

import java.util.List;

import com.jlj.model.Bigwheel;

public interface IBigwheelService {

	List<Bigwheel> queryList(String publicaccount);

	int getTotalCount(String publicaccount);

	void add(Bigwheel bigwheel);

	void delete(Bigwheel bigwheel);

	Bigwheel loadById(int id);

	void update(Bigwheel bigwheel);

}


text:
"""Support for Plex media server monitoring."""
import logging

from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity import Entity

from .const import (
    CONF_SERVER_IDENTIFIER,
    DISPATCHERS,
    DOMAIN as PLEX_DOMAIN,
    NAME_FORMAT,
    PLEX_UPDATE_SENSOR_SIGNAL,
    SERVERS,
)

_LOGGER = logging.getLogger(__name__)

async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
    """Set up the Plex sensor platform.

    Deprecated.
    """
    pass

async def async_setup_entry(hass, config_entry, async_add_entities):
    """Set up Plex sensor from a config entry."""
    server_id = config_entry.data[CONF_SERVER_IDENTIFIER]
    plexserver = hass.data[PLEX_DOMAIN][SERVERS][server_id]
    sensor = PlexSensor(plexserver)
    async_add_entities([sensor])

class PlexSensor(Entity):
    """Representation of a Plex now playing sensor."""

    def __init__(self, plex_server):
        """Initialize the sensor."""
        self.sessions = []
        self._state = None
        self._now_playing = []
        self._server = plex_server
        self._name = NAME_FORMAT.format(plex_server.friendly_name)
        self._unique_id = f"sensor-{plex_server.machine_identifier}"

    async def async_added_to_hass(self):
        """Run when about to be added to hass."""
        server_id = self._server.machine_identifier
        unsub = async_dispatcher_connect(
            self.hass,
            PLEX_UPDATE_SENSOR_SIGNAL.format(server_id),
            self.async_refresh_sensor,
        )
        self.hass.data[PLEX_DOMAIN][DISPATCHERS][server_id].append(unsub)

    @callback
    def async_refresh_sensor(self, sessions):
        """Set instance object and trigger an entity state update."""
        self.sessions = sessions
        self.async_schedule_update_ha_state(True)

    @property
    def name(self):
        """Return the name of the sensor."""
        return self._name

    @property
    def unique_id(self):
        """Return the id of this plex client."""
        return self._unique_id

    @property
    def should_poll(self):
        """Return True if entity has to be polled for state."""
        return False

    @property
    def state(self):
        """Return the state of the sensor."""
        return self._state

    @property
    def unit_of_measurement(self):
        """Return the unit this state is expressed in."""
        return "Watching"

    @property
    def device_state_attributes(self):
        """Return the state attributes."""
        return {content[0]: content[1] for content in self._now_playing}

    def update(self):
        """Update method for Plex sensor."""
        _LOGGER.debug("Refreshing sensor [%s]", self.unique_id)
        now_playing = []
        for sess in self.sessions:
            user = sess.usernames[0]
            device = sess.players[0].title
            now_playing_user = f"{user} - {device}"
            now_playing_title = ""

            if sess.TYPE == "episode":
                # example:
                # "Supernatural (2005) - S01 · E13 - Route 666"
                season_title = sess.grandparentTitle
                if sess.show().year is not None:
                    season_title += " ({0})".format(sess.show().year)
                season_episode = "S{0}".format(sess.parentIndex)
                if sess.index is not None:
                    season_episode += f" · E{sess.index}"
                episode_title = sess.title
                now_playing_title = "{0} - {1} - {2}".format(
                    season_title, season_episode, episode_title
                )
            elif sess.TYPE == "track":
                # example:
                # "Billy Talent - Afraid of Heights - Afraid of Heights"
                track_artist = sess.grandparentTitle
                track_album = sess.parentTitle
                track_title = sess.title
                now_playing_title = "{0} - {1} - {2}".format(
                    track_artist, track_album, track_title
                )
            else:
                # example:
                # "picture_of_last_summer_camp (2015)"
                # "The Incredible Hulk (2008)"
                now_playing_title = sess.title
                if sess.year is not None:
                    now_playing_title += f" ({sess.year})"

            now_playing.append((now_playing_user, now_playing_title))
        self._state = len(self.sessions)
        self._now_playing = now_playing


text:
import numpy as np
import re
from src.utilities.data_utils import *
from src.utilities.metrics import *

class KeywordSearch(object):
    '''[summary]

    [description]
    '''
    def __init__(self, keywords=['caption']):
        super(KeywordSearch, self).__init__()
        self._keywords = keywords

    @property
    def keywords(self):
        return self._keywords

    @keywords.setter
    def keywords(self, keywords=[]):
        self._keywords = keywords

    def test(self, path_X, path_y=None):
        return accuracy_score_f1(self, path_X, path_y)

    def predict(self, X, padding=False):
        '''[summary]

        [description]

        Args:
            X: [description]
            keywords: [description]

        Returns:
            [description]
            [type]
        '''

        pattern = r'|'.join(self.keywords)
        is_matched =  X['caption'].str.contains(pattern, flags=re.IGNORECASE)
        #TODO: change the word spray to something smarter
        #as if we spray the neighboring points around the matched point
        if padding:
            is_matched_padded = is_matched.copy()
            PADDING = 18 # 3 minutes (plus/minus i)
            for i, row in is_matched.iteritems():
                if row:
                    start = i - PADDING if i > PADDING else 0
                    end = i + PADDING
                    is_matched_padded[start:end] = True

            is_matched = is_matched_padded
        return is_matched