text:
package com.justwayward.reader.view.recyclerview;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.ColorRes;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.AdapterDataObserver;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.justwayward.reader.R;
import com.justwayward.reader.utils.NetworkUtils;
import com.justwayward.reader.view.recyclerview.adapter.RecyclerArrayAdapter;
import com.justwayward.reader.view.recyclerview.decoration.DividerDecoration;
import com.justwayward.reader.view.recyclerview.swipe.OnRefreshListener;
import com.justwayward.reader.view.recyclerview.swipe.SwipeRefreshLayout;

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

public class EasyRecyclerView extends FrameLayout {
    private Context mContext;

    public static final String TAG = "EasyRecyclerView";
    public static boolean DEBUG = false;
    protected RecyclerView mRecycler;
    protected TextView tipView;
    protected ViewGroup mProgressView;
    protected ViewGroup mEmptyView;
    protected ViewGroup mErrorView;
    private int mProgressId;
    private int mEmptyId;
    private int mErrorId;

    protected boolean mClipToPadding;
    protected int mPadding;
    protected int mPaddingTop;
    protected int mPaddingBottom;
    protected int mPaddingLeft;
    protected int mPaddingRight;
    protected int mScrollbarStyle;
    protected int mScrollbar;

    protected RecyclerView.OnScrollListener mInternalOnScrollListener;
    protected RecyclerView.OnScrollListener mExternalOnScrollListener;

    protected SwipeRefreshLayout mPtrLayout;
    protected OnRefreshListener mRefreshListener;

    public List<RecyclerView.ItemDecoration> decorations = new ArrayList<>();

    public SwipeRefreshLayout getSwipeToRefresh() {
        return mPtrLayout;
    }

    public RecyclerView getRecyclerView() {
        return mRecycler;
    }

    public EasyRecyclerView(Context context) {
        this(context, null);
    }

    public EasyRecyclerView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public EasyRecyclerView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mContext = context;
        if (attrs != null)
            initAttrs(attrs);
        initView();
    }

    protected void initAttrs(AttributeSet attrs) {
        TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.superrecyclerview);
        try {
            mClipToPadding = a.getBoolean(R.styleable.superrecyclerview_recyclerClipToPadding, false);
            mPadding = (int) a.getDimension(R.styleable.superrecyclerview_recyclerPadding, -1.0f);
            mPaddingTop = (int) a.getDimension(R.styleable.superrecyclerview_recyclerPaddingTop, 0.0f);
            mPaddingBottom = (int) a.getDimension(R.styleable.superrecyclerview_recyclerPaddingBottom, 0.0f);
            mPaddingLeft = (int) a.getDimension(R.styleable.superrecyclerview_recyclerPaddingLeft, 0.0f);
            mPaddingRight = (int) a.getDimension(R.styleable.superrecyclerview_recyclerPaddingRight, 0.0f);
            mScrollbarStyle = a.getInteger(R.styleable.superrecyclerview_scrollbarStyle, -1);
            mScrollbar = a.getInteger(R.styleable.superrecyclerview_scrollbars, -1);

            mEmptyId = a.getResourceId(R.styleable.superrecyclerview_layout_empty, 0);
            mProgressId = a.getResourceId(R.styleable.superrecyclerview_layout_progress, 0);
            mErrorId = a.getResourceId(R.styleable.superrecyclerview_layout_error, R.layout.common_net_error_view);
        } finally {
            a.recycle();
        }
    }

    private void initView() {
        if (isInEditMode()) {
            return;
        }
        //生成主View
        View v = LayoutInflater.from(getContext()).inflate(R.layout.common_recyclerview, this);
        mPtrLayout = (SwipeRefreshLayout) v.findViewById(R.id.ptr_layout);
        mPtrLayout.setEnabled(false);

        mProgressView = (ViewGroup) v.findViewById(R.id.progress);
        if (mProgressId != 0) LayoutInflater.from(getContext()).inflate(mProgressId, mProgressView);
        mEmptyView = (ViewGroup) v.findViewById(R.id.empty);
        if (mEmptyId != 0) LayoutInflater.from(getContext()).inflate(mEmptyId, mEmptyView);
        mErrorView = (ViewGroup) v.findViewById(R.id.error);
        if (mErrorId != 0) LayoutInflater.from(getContext()).inflate(mErrorId, mErrorView);
        initRecyclerView(v);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        return mPtrLayout.dispatchTouchEvent(ev);
    }

    /**
     * @param left
     * @param top
     * @param right
     * @param bottom
     */
    public void setRecyclerPadding(int left, int top, int right, int bottom) {
        this.mPaddingLeft = left;
        this.mPaddingTop = top;
        this.mPaddingRight = right;
        this.mPaddingBottom = bottom;
        mRecycler.setPadding(mPaddingLeft, mPaddingTop, mPaddingRight, mPaddingBottom);
    }

    public void setClipToPadding(boolean isClip) {
        mRecycler.setClipToPadding(isClip);
    }

    public void setEmptyView(View emptyView) {
        mEmptyView.removeAllViews();
        mEmptyView.addView(emptyView);
    }

    public void setProgressView(View progressView) {
        mProgressView.removeAllViews();
        mProgressView.addView(progressView);
    }

    public void setErrorView(View errorView) {
        mErrorView.removeAllViews();
        mErrorView.addView(errorView);
    }

    public void setEmptyView(int emptyView) {
        mEmptyView.removeAllViews();
        LayoutInflater.from(getContext()).inflate(emptyView, mEmptyView);
    }

    public void setProgressView(int progressView) {
        mProgressView.removeAllViews();
        LayoutInflater.from(getContext()).inflate(progressView, mProgressView);
    }

    public void setErrorView(int errorView) {
        mErrorView.removeAllViews();
        LayoutInflater.from(getContext()).inflate(errorView, mErrorView);
    }

    public void scrollToPosition(int position) {
        getRecyclerView().scrollToPosition(position);
    }

    /**
     * Implement this method to customize the AbsListView
     */
    protected void initRecyclerView(View view) {
        mRecycler = (RecyclerView) view.findViewById(android.R.id.list);
        tipView = (TextView) view.findViewById(R.id.tvTip);
        setItemAnimator(null);
        if (mRecycler != null) {
            mRecycler.setHasFixedSize(true);
            mRecycler.setClipToPadding(mClipToPadding);
            mInternalOnScrollListener = new RecyclerView.OnScrollListener() {

                @Override
                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);
                    if (mExternalOnScrollListener != null)
                        mExternalOnScrollListener.onScrolled(recyclerView, dx, dy);

                }

                @Override
                public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                    super.onScrollStateChanged(recyclerView, newState);
                    if (mExternalOnScrollListener != null)
                        mExternalOnScrollListener.onScrollStateChanged(recyclerView, newState);

                }
            };
            mRecycler.addOnScrollListener(mInternalOnScrollListener);

            if (mPadding != -1.0f) {
                mRecycler.setPadding(mPadding, mPadding, mPadding, mPadding);
            } else {
                mRecycler.setPadding(mPaddingLeft, mPaddingTop, mPaddingRight, mPaddingBottom);
            }
            if (mScrollbarStyle != -1) {
                mRecycler.setScrollBarStyle(mScrollbarStyle);
            }
            switch (mScrollbar) {
                case 0:
                    setVerticalScrollBarEnabled(false);
                    break;
                case 1:
                    setHorizontalScrollBarEnabled(false);
                    break;
                case 2:
                    setVerticalScrollBarEnabled(false);
                    setHorizontalScrollBarEnabled(false);
                    break;
            }
        }
    }

    @Override
    public void setVerticalScrollBarEnabled(boolean verticalScrollBarEnabled) {
        mRecycler.setVerticalScrollBarEnabled(verticalScrollBarEnabled);
    }

    @Override
    public void setHorizontalScrollBarEnabled(boolean horizontalScrollBarEnabled) {
        mRecycler.setHorizontalScrollBarEnabled(horizontalScrollBarEnabled);
    }

    /**
     * Set the layout manager to the recycler
     *
     * @param manager
     */
    public void setLayoutManager(RecyclerView.LayoutManager manager) {
        mRecycler.setLayoutManager(manager);
    }

    /**
     * Set the ItemDecoration to the recycler
     *
     * @param color
     * @param height
     * @param paddingLeft
     * @param paddingRight
     */
    public void setItemDecoration(int color, int height, int paddingLeft, int paddingRight) {
        DividerDecoration itemDecoration = new DividerDecoration(color, height, paddingLeft, paddingRight);
        itemDecoration.setDrawLastItem(false);
        decorations.add(itemDecoration);
        mRecycler.addItemDecoration(itemDecoration);
    }

    public static class EasyDataObserver extends AdapterDataObserver {
        private EasyRecyclerView recyclerView;

        public EasyDataObserver(EasyRecyclerView recyclerView) {
            this.recyclerView = recyclerView;
        }

        @Override
        public void onItemRangeChanged(int positionStart, int itemCount) {
            super.onItemRangeChanged(positionStart, itemCount);
            update();
        }

        @Override
        public void onItemRangeInserted(int positionStart, int itemCount) {
            super.onItemRangeInserted(positionStart, itemCount);
            update();
        }

        @Override
        public void onItemRangeRemoved(int positionStart, int itemCount) {
            super.onItemRangeRemoved(positionStart, itemCount);
            update();
        }

        @Override
        public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
            super.onItemRangeMoved(fromPosition, toPosition, itemCount);
            update();
        }

        @Override
        public void onChanged() {
            super.onChanged();
            update();
        }

        //自动更改Container的样式
        private void update() {
            log("update");
            int count;
            if (recyclerView.getAdapter() instanceof RecyclerArrayAdapter) {
                count = ((RecyclerArrayAdapter) recyclerView.getAdapter()).getCount();
            } else {
                count = recyclerView.getAdapter().getItemCount();
            }

            if (count == 0 && !NetworkUtils.isAvailable(recyclerView.getContext())) {
                recyclerView.showError();
                return;
            }

            if (count == 0 && ((RecyclerArrayAdapter) recyclerView.getAdapter()).getHeaderCount() == 0) {
                log("no data:" + "show empty");
                recyclerView.showEmpty();
            } else {
                log("has data");
                recyclerView.showRecycler();
            }
        }
    }

    /**
     * 设置适配器,关闭所有副view。展示recyclerView
     * 适配器有更新,自动关闭所有副view。根据条数判断是否展示EmptyView
     *
     * @param adapter
     */
    public void setAdapter(RecyclerView.Adapter adapter) {
        mRecycler.setAdapter(adapter);
        adapter.registerAdapterDataObserver(new EasyDataObserver(this));
        showRecycler();
    }

    /**
     * 设置适配器,关闭所有副view。展示进度条View
     * 适配器有更新,自动关闭所有副view。根据条数判断是否展示EmptyView
     *
     * @param adapter
     */
    public void setAdapterWithProgress(RecyclerView.Adapter adapter) {
        mRecycler.setAdapter(adapter);
        adapter.registerAdapterDataObserver(new EasyDataObserver(this));
        //只有Adapter为空时才显示ProgressView
        if (adapter instanceof RecyclerArrayAdapter) {
            if (((RecyclerArrayAdapter) adapter).getCount() == 0) {
                showProgress();
            } else {
                showRecycler();
            }
        } else {
            if (adapter.getItemCount() == 0) {
                showProgress();
            } else {
                showRecycler();
            }
        }
    }

    /**
     * Remove the adapter from the recycler
     */
    public void clear() {
        mRecycler.setAdapter(null);
    }

    private void hideAll() {
        mEmptyView.setVisibility(View.GONE);
        mProgressView.setVisibility(View.GONE);
        mErrorView.setVisibility(GONE);
//        mPtrLayout.setRefreshing(false);
        mRecycler.setVisibility(View.INVISIBLE);
    }

    public void showError() {
        log("showError");
        if (mErrorView.getChildCount() > 0) {
            hideAll();
            mErrorView.setVisibility(View.VISIBLE);
        } else {
            showRecycler();
        }

    }

    public void showEmpty() {
        log("showEmpty");
        if (mEmptyView.getChildCount() > 0) {
            hideAll();
            mEmptyView.setVisibility(View.VISIBLE);
        } else {
            showRecycler();
        }
    }

    public void showProgress() {
        log("showProgress");
        if (mProgressView.getChildCount() > 0) {
            hideAll();
            mProgressView.setVisibility(View.VISIBLE);
        } else {
            showRecycler();
        }
    }

    public void showRecycler() {
        log("showRecycler");
        hideAll();
        mRecycler.setVisibility(View.VISIBLE);
    }

    public void showTipViewAndDelayClose(String tip) {
        tipView.setText(tip);
        Animation mShowAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                -1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
        mShowAction.setDuration(500);
        tipView.startAnimation(mShowAction);
        tipView.setVisibility(View.VISIBLE);

        tipView.postDelayed(new Runnable() {
            @Override
            public void run() {
                Animation mHiddenAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF,
                        0.0f, Animation.RELATIVE_TO_SELF, 0.0f,
                        Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                        -1.0f);
                mHiddenAction.setDuration(500);
                tipView.startAnimation(mHiddenAction);
                tipView.setVisibility(View.GONE);
            }
        }, 2200);
    }

    public void showTipView(String tip) {
        tipView.setText(tip);
        Animation mShowAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                -1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
        mShowAction.setDuration(500);
        tipView.startAnimation(mShowAction);
        tipView.setVisibility(View.VISIBLE);
    }

    public void hideTipView(long delayMillis) {
        tipView.postDelayed(new Runnable() {
            @Override
            public void run() {
                Animation mHiddenAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF,
                        0.0f, Animation.RELATIVE_TO_SELF, 0.0f,
                        Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                        -1.0f);
                mHiddenAction.setDuration(500);
                tipView.startAnimation(mHiddenAction);
                tipView.setVisibility(View.GONE);
            }
        }, delayMillis);
    }

    public void setTipViewText(String tip) {
        if (!isTipViewVisible())
            showTipView(tip);
        else
            tipView.setText(tip);
    }

    public boolean isTipViewVisible() {
        return tipView.getVisibility() == View.VISIBLE;
    }

    /**
     * Set the listener when refresh is triggered and enable the SwipeRefreshLayout
     *
     * @param listener
     */
    public void setRefreshListener(OnRefreshListener listener) {
        mPtrLayout.setEnabled(true);
        mPtrLayout.setOnRefreshListener(listener);
        this.mRefreshListener = listener;
    }

    public void setRefreshing(final boolean isRefreshing) {
        mPtrLayout.post(new Runnable() {
            @Override
            public void run() {
                if (isRefreshing) { // 避免刷新的loadding和progressview 同时显示
                    mProgressView.setVisibility(View.GONE);
                }
                mPtrLayout.setRefreshing(isRefreshing);
            }
        });
    }

    public void setRefreshing(final boolean isRefreshing, final boolean isCallbackListener) {
        mPtrLayout.post(new Runnable() {
            @Override
            public void run() {
                mPtrLayout.setRefreshing(isRefreshing);
                if (isRefreshing && isCallbackListener && mRefreshListener != null) {
                    mRefreshListener.onRefresh();
                }
            }
        });
    }

    /**
     * Set the colors for the SwipeRefreshLayout states
     *
     * @param colRes
     */
    public void setRefreshingColorResources(@ColorRes int... colRes) {
        mPtrLayout.setColorSchemeResources(colRes);
    }

    /**
     * Set the colors for the SwipeRefreshLayout states
     *
     * @param col
     */
    public void setRefreshingColor(int... col) {
        mPtrLayout.setColorSchemeColors(col);
    }

    /**
     * Set the scroll listener for the recycler
     *
     * @param listener
     */
    public void setOnScrollListener(RecyclerView.OnScrollListener listener) {
        mExternalOnScrollListener = listener;
    }

    /**
     * Add the onItemTouchListener for the recycler
     *
     * @param listener
     */
    public void addOnItemTouchListener(RecyclerView.OnItemTouchListener listener) {
        mRecycler.addOnItemTouchListener(listener);
    }

    /**
     * Remove the onItemTouchListener for the recycler
     *
     * @param listener
     */
    public void removeOnItemTouchListener(RecyclerView.OnItemTouchListener listener) {
        mRecycler.removeOnItemTouchListener(listener);
    }

    /**
     * @return the recycler adapter
     */
    public RecyclerView.Adapter getAdapter() {
        return mRecycler.getAdapter();
    }

    public void setOnTouchListener(OnTouchListener listener) {
        mRecycler.setOnTouchListener(listener);
    }

    public void setItemAnimator(RecyclerView.ItemAnimator animator) {
        mRecycler.setItemAnimator(animator);
    }

    public void addItemDecoration(RecyclerView.ItemDecoration itemDecoration) {
        mRecycler.addItemDecoration(itemDecoration);
    }

    public void addItemDecoration(RecyclerView.ItemDecoration itemDecoration, int index) {
        mRecycler.addItemDecoration(itemDecoration, index);
    }

    public void removeItemDecoration(RecyclerView.ItemDecoration itemDecoration) {
        mRecycler.removeItemDecoration(itemDecoration);
    }

    public void removeAllItemDecoration() {
        for (RecyclerView.ItemDecoration decoration : decorations) {
            mRecycler.removeItemDecoration(decoration);
        }
    }

    /**
     * @return inflated error view or null
     */
    public View getErrorView() {
        if (mErrorView.getChildCount() > 0) return mErrorView.getChildAt(0);
        return null;
    }

    /**
     * @return inflated progress view or null
     */
    public View getProgressView() {
        if (mProgressView.getChildCount() > 0) return mProgressView.getChildAt(0);
        return null;
    }

    /**
     * @return inflated empty view or null
     */
    public View getEmptyView() {
        if (mEmptyView.getChildCount() > 0) return mEmptyView.getChildAt(0);
        return null;
    }

    private static void log(String content) {
        if (DEBUG) {
            Log.i(TAG, content);
        }
    }

}


text:
layout: article
title: "L'accessibilité est importante"
description: "L'accessibilité n'est pas une fonctionnalité."
introduction: "L'accessibilité n'est pas une fonctionnalité. Les utilisateurs malentendants ou malvoyants ne peuvent pas du tout bénéficier d'une vidéo si celle-ci ne contient pas de sous-titres ni de descriptions. Le temps que vous allez passer à ajouter ces éléments à la vidéo vous coûtera bien moins que de faire subir une expérience désagréable aux internautes. Faites en sorte de fournir au minimum une expérience de base accessible à tous."
article:
  written_on: 2014-04-16
  updated_on: 2014-04-29
  order: 4
collection: videos
authors:
  - samdutton
key-takeaways:
  add-a-video:
    - Utilisez l'élément vidéo pour importer, décoder et lire des contenus vidéos sur votre site.
    - Produisez des vidéos de plusieurs formats pour couvrir une gamme de plates-formes mobiles.
    - Définissez correctement la taille des vidéos. Veillez à ce qu'elles ne débordent pas de leurs contenants.
    - L'accessibilité est importante. Ajoutez l'élément de suivi en tant qu'élément enfant de l'élément vidéo.
remember:
  media-fragments :
    - L'API Media Fragments est compatible avec la plupart des plates-formes, à l'exception d'iOS.
    - Assurez-vous que les demandes de type 'Range' sont compatibles avec votre serveur. Elles sont activées par défaut sur la plupart des serveurs. Cependant, il arrive qu'elles soient désactivées sur certains services d'hébergement.
  dont-overflow:
    - Ne forcez pas la taille d'un élément générant un format d'image différent de celui de la vidéo d'origine. Les vidéos écrasées ou étirées donnent une mauvaise image du site.
  accessibility-matters:
    - L'élément de suivi est compatible avec Chrome pour Android, Safari pour iOS, ainsi que tous les navigateurs actuels pour ordinateur de bureau, sauf Firefox (voir caniuse.com/track). Plusieurs polyfills sont également disponibles. Nous vous recommandons d'utiliser l'Playr ou leCaptionator.
  construct-video-streams:
    - MSE est compatible avec Chrome et Opera sur Android, ainsi qu'avec Internet Explorer 11 et Chrome pour les ordinateurs de bureau. La compatibilité est également prévue pour Firefox.
  optimize:
    - Images
    - Optimiser l'efficacité du contenu
---

{% wrap content%}

{% include modules/toc.liquid %}

## Ajouter des sous-titres pour améliorer l'accessibilité

Pour améliorer l'accessibilité des médias sur mobile, ajoutez des sous-titres ou des descriptions à l'aide de l'élément de suivi.

{% include modules/remember.liquid title="Important" list=page.remember.accessibility-matters %}

Lorsque vous utilisez l'élément de suivi, les sous-titres ont l'apparence suivante :

##Ajouter un élément de suivi

Il est très facile d'ajouter des sous-titres à une vidéo. Il vous suffit d'ajouter un élément de suivi en tant qu'élément enfant de l'élément vidéo :

{% include_code _code/track.html track html %}

L'attribut d'élément de suivi `src` indique l'emplacement du fichier de suivi.

##Définir des sous-titres dans un fichier de suivi

Un fichier de suivi est composé de `signaux` chronométrés au format WebVTT :

    WEBVTT

    00:00.000 --> 00:04.000
     Un homme est assis sur une branche, utilisant un ordinateur portable.

    00:05.000 --> 00:08.000
     La branche casse et il commence à tomber.

    ...

{% include modules/nextarticle.liquid %}

{% endwrap %}

redpajama_set_name: RedPajamaGithub


text:
"""weight_scheduler

Revision ID: 1955efc66455
Revises: 35a0f3365720
Create Date: 2015-03-12 22:11:37.607390

"""

# revision identifiers, used by Alembic.
revision = '1955efc66455'
down_revision = '35a0f3365720'

from alembic import op
import sqlalchemy as sa

def upgrade():
    op.add_column('agents',
                  sa.Column('load', sa.Integer(),
                            server_default='0', nullable=False))


text:
package com.alexmiragall.wakepc.fragments;

import android.app.Fragment;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.alexmiragall.wakepc.R;
import com.alexmiragall.wakepc.adapters.BaseRecyclerAdapter;
import com.alexmiragall.wakepc.adapters.EventsClickListener;
import com.alexmiragall.wakepc.adapters.pcadapter.PCViewHolder;
import com.alexmiragall.wakepc.model.PC;
import com.alexmiragall.wakepc.presenters.WakePCPresenter;

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

import javax.inject.Inject;

import butterknife.InjectView;
import butterknife.OnClick;

/**
 * A simple {@link Fragment} subclass.
 */
public class WakePCFragment extends BaseFragment implements WakePCPresenter.View {
    @InjectView(R.id.fragment_wake_pc_recycler_view)
    RecyclerView recyclerView;
    @InjectView(R.id.fragment_wake_pc_empty_txt)
    TextView txtEmpty;

    @Inject
    WakePCPresenter wakePCPresenter;
    List<PC> pcsList = new ArrayList<>();

    private BaseRecyclerAdapter<PC, PCViewHolder> mAdapter;

    public WakePCFragment() {
        setHasOptionsMenu(true);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        menu.clear();
       // menu.add(0, 0, 0, "Add");
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == 0) {
        //    openEditionFragment(null, null);
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected int getFragmentLayout() {
        return R.layout.fragment_wake_pc;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        wakePCPresenter.setView(this);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mAdapter = new BaseRecyclerAdapter<PC, PCViewHolder>(pcsList, new PCViewHolder.Factory(new EventsClickListener() {
            @Override
            public void onItemClickListener(int position) {
                wakePCPresenter.editPC(position, pcsList.get(position));
            }

            @Override
            public void onItemSubViewClickListener(int position, int viewId, View view) {
                PC pc = pcsList.get(position);
                switch (viewId) {
                    case R.id.item_pc_power_btn:
                        wakePCPresenter.powerOnPC(pc);
                        break;
                    case R.id.item_pc_edit_btn:
                        wakePCPresenter.editPC(position, pc);
                        break;
                }
            }
        }));
        recyclerView.setAdapter(mAdapter);
    }

    @Override
    public void onResume() {
        super.onResume();
        wakePCPresenter.resume();
    }

    @Override
    public void openEditionFragment(Integer position, PC pc) {
        getFragmentManager().beginTransaction().replace(R.id.container, AddPCFragment.newInstance(position, pc)).addToBackStack(null).commit();
    }

    @Override
    public void updateListView(List<PC> pcs) {
        pcsList.clear();
        pcsList.addAll(pcs);
        mAdapter.notifyDataSetChanged();
    }

    @OnClick(R.id.fragment_wake_pc_add_btn)
    public void onClickAdd() {
        wakePCPresenter.editPC(null, null);
    }
}


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.

Imports System.Collections.Generic
Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax

Namespace Microsoft.CodeAnalysis.VisualBasic

    ''' <summary>
    ''' A region analysis walker that computes the set of variables for
    ''' which their assigned values flow out of the region.
    ''' A variable assigned inside is used outside if an analysis that
    ''' treats assignments in the region as un-assigning the variable would
    ''' cause "unassigned" errors outside the region.
    ''' </summary>
    Friend Class DataFlowsOutWalker
        Inherits AbstractRegionDataFlowPass

        Private ReadOnly _dataFlowsIn As ImmutableArray(Of ISymbol)
        Private ReadOnly _originalUnassigned As HashSet(Of Symbol)
        Private ReadOnly _dataFlowsOut As New HashSet(Of Symbol)()
#If DEBUG Then
        ' we'd like to ensure that only variables get returned in DataFlowsOut that were assigned to inside the region.
        Private ReadOnly _assignedInside As HashSet(Of Symbol) = New HashSet(Of Symbol)()
#End If

        Private Sub New(info As FlowAnalysisInfo, region As FlowAnalysisRegionInfo,
                unassignedVariables As HashSet(Of Symbol), originalUnassigned As HashSet(Of Symbol), dataFlowsIn As ImmutableArray(Of ISymbol))

            MyBase.New(info, region, unassignedVariables, trackUnassignments:=True, trackStructsWithIntrinsicTypedFields:=True)

            Me._dataFlowsIn = dataFlowsIn
            Me._originalUnassigned = originalUnassigned
        End Sub

        Friend Overloads Shared Function Analyze(info As FlowAnalysisInfo, region As FlowAnalysisRegionInfo,
                                                 unassignedVariables As HashSet(Of Symbol), dataFlowsIn As ImmutableArray(Of ISymbol)) As HashSet(Of Symbol)

            ' remove static locals from unassigned, otherwise they will never reach ReportUnassigned(...)
            Dim unassignedWithoutStatic As New HashSet(Of Symbol)
            For Each var In unassignedVariables
                If var.Kind <> SymbolKind.Local OrElse Not DirectCast(var, LocalSymbol).IsStatic Then
                    unassignedWithoutStatic.Add(var)
                End If
            Next

            Dim walker = New DataFlowsOutWalker(info, region, unassignedWithoutStatic, unassignedVariables, dataFlowsIn)
            Try
                Dim success = walker.Analyze
                Dim result = walker._dataFlowsOut
#If DEBUG Then
                ' Assert that DataFlowsOut only contains variables that were assigned to inside the region
                Debug.Assert(Not success OrElse Not result.Any(Function(variable) Not walker._assignedInside.Contains(variable)))
#End If

                Return If(success, result, New HashSet(Of Symbol)())
            Finally
                walker.Free()
            End Try
        End Function

        Protected Overrides Sub EnterRegion()
            ' to handle loops properly, we must assume that every variable (except static locals)
            ' that flows in is assigned at the beginning of the loop.  If it isn't, then it must
            ' be in a loop and flow out of the region in that loop (and into the region inside the loop).
            For Each variable As Symbol In _dataFlowsIn
                Dim slot As Integer = Me.GetOrCreateSlot(variable)
                If Not Me.State.IsAssigned(slot) AndAlso variable.Kind <> SymbolKind.RangeVariable AndAlso
                        (variable.Kind <> SymbolKind.Local OrElse Not DirectCast(variable, LocalSymbol).IsStatic) Then
                    _dataFlowsOut.Add(variable)
                End If
            Next

            MyBase.EnterRegion()
        End Sub

        Protected Overrides Sub Assign(node As BoundNode, value As BoundExpression, Optional assigned As Boolean = True)
            If IsInside Then

                If assigned Then
                    Dim symbol = GetNodeSymbol(node)
                    If symbol IsNot Nothing Then
#If DEBUG Then
                        _assignedInside.Add(symbol)
#End If
                    End If
                End If

                ' assignments inside the region are recorded as un-assignments
                assigned = False

                ' any reachable assignment to a ref or out parameter can
                ' be visible to the caller in the face of exceptions.
                If Me.State.Reachable Then
                    Select Case node.Kind

                        Case BoundKind.Parameter, BoundKind.MeReference
                            Dim expression = DirectCast(node, BoundExpression)
                            Dim slots As SlotCollection = MakeSlotsForExpression(expression)
                            Debug.Assert(slots.Count <= 1)

                            If slots.Count > 0 Then
                                Dim slot As Integer = slots(0)
                                If slot >= SlotKind.FirstAvailable Then

                                    Dim exprIdentifier = DirectCast(variableBySlot(slot).Symbol, ParameterSymbol)
                                    If exprIdentifier IsNot Nothing AndAlso exprIdentifier.IsByRef Then
                                        _dataFlowsOut.Add(exprIdentifier)
                                    End If
                                End If
                            End If

                        Case BoundKind.Local
                            Dim local = DirectCast(node, BoundLocal)
                            Dim locSymbol As LocalSymbol = local.LocalSymbol
                            If locSymbol.IsStatic AndAlso WasUsedBeforeAssignment(locSymbol) Then
                                Dim slots As SlotCollection = MakeSlotsForExpression(local)
                                Debug.Assert(slots.Count <= 1)

                                If slots.Count > 0 Then
                                    Dim slot As Integer = slots(0)
                                    If slot >= SlotKind.FirstAvailable Then
                                        Debug.Assert(locSymbol Is variableBySlot(slot).Symbol)
                                        _dataFlowsOut.Add(variableBySlot(slot).Symbol)
                                    End If
                                End If

                            End If

                    End Select
                End If
            End If

            MyBase.Assign(node, value, assigned)
        End Sub

        Protected Overrides Sub ReportUnassigned(local As Symbol,
                                                 node As SyntaxNode,
                                                 rwContext As ReadWriteContext,
                                                 Optional slot As Integer = SlotKind.NotTracked,
                                                 Optional boundFieldAccess As BoundFieldAccess = Nothing)

            Debug.Assert(local.Kind <> SymbolKind.Field OrElse boundFieldAccess IsNot Nothing)

            If Not _dataFlowsOut.Contains(local) AndAlso local.Kind <> SymbolKind.RangeVariable AndAlso Not IsInside Then
                If local.Kind = SymbolKind.Field Then
                    Dim sym As Symbol = GetNodeSymbol(boundFieldAccess)

                    ' Unreachable for AmbiguousLocalsPseudoSymbol: ambiguous implicit
                    ' receiver should not ever be considered unassigned
                    Debug.Assert(Not TypeOf sym Is AmbiguousLocalsPseudoSymbol)

                    If sym IsNot Nothing Then
                        _dataFlowsOut.Add(sym)
                    End If

                Else
                    _dataFlowsOut.Add(local)
                End If
            End If

            MyBase.ReportUnassigned(local, node, rwContext, slot, boundFieldAccess)
        End Sub

        Protected Overrides Sub ReportUnassignedByRefParameter(parameter As ParameterSymbol)
            _dataFlowsOut.Add(parameter)

            MyBase.ReportUnassignedByRefParameter(parameter)
        End Sub

        Protected Overrides Sub NoteWrite(variable As Symbol, value As BoundExpression)
            If Me.State.Reachable Then
                Dim isByRefParameter As Boolean = variable.Kind = SymbolKind.Parameter AndAlso DirectCast(variable, ParameterSymbol).IsByRef
                Dim isStaticLocal As Boolean = variable.Kind = SymbolKind.Local AndAlso DirectCast(variable, LocalSymbol).IsStatic

                If IsInside AndAlso (isByRefParameter OrElse isStaticLocal AndAlso WasUsedBeforeAssignment(variable)) Then
                    _dataFlowsOut.Add(variable)
#If DEBUG Then
                    _assignedInside.Add(variable)
#End If
                End If
            End If

            MyBase.NoteWrite(variable, value)
        End Sub

        Private Function WasUsedBeforeAssignment(sym As Symbol) As Boolean
            Return Me._originalUnassigned.Contains(sym)
        End Function

        Friend Overrides Sub AssignLocalOnDeclaration(local As LocalSymbol, node As BoundLocalDeclaration)
            If local.IsStatic Then
                ' We should pretend that all the static locals are
                ' initialized by previous method invocations
                Assign(node, node.InitializerOpt)
            Else
                MyBase.AssignLocalOnDeclaration(local, node)
            End If
        End Sub

    End Class

End Namespace


text:
package zipkin.storage.elasticsearch.http.integration;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import okhttp3.Call;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import org.junit.Before;
import org.junit.Test;
import zipkin.Annotation;
import zipkin.Span;
import zipkin.internal.Util;
import zipkin.internal.V2SpanConverter;
import zipkin.storage.elasticsearch.http.ElasticsearchHttpStorage;
import zipkin.storage.elasticsearch.http.InternalForTests;

import static org.assertj.core.api.Assertions.assertThat;
import static zipkin.Constants.SERVER_RECV;
import static zipkin.Constants.SERVER_SEND;
import static zipkin.TestObjects.DAY;
import static zipkin.TestObjects.TODAY;
import static zipkin.TestObjects.WEB_ENDPOINT;
import static zipkin.storage.elasticsearch.http.integration.LazyElasticsearchHttpStorage.INDEX;

abstract class ElasticsearchHttpSpanConsumerTest {
  // we assume that buckets use a simple daily format.
  SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

  ElasticsearchHttpSpanConsumerTest() {
    dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
  }

  /** Should maintain state between multiple calls within a test. */
  abstract ElasticsearchHttpStorage storage();

  /** Clears store between tests. */
  @Before
  public void clear() throws IOException {
    InternalForTests.clear(storage());
  }

  @Test
  public void spanGoesIntoADailyIndex_whenTimestampIsDerived() throws Exception {
    long twoDaysAgo = (TODAY - 2 * DAY);

    Span span = Span.builder().traceId(20L).id(20L).name("get")
      .addAnnotation(Annotation.create(twoDaysAgo * 1000, SERVER_RECV, WEB_ENDPOINT))
      .addAnnotation(Annotation.create(TODAY * 1000, SERVER_SEND, WEB_ENDPOINT))
      .build();

    accept(span);

    // make sure the span went into an index corresponding to its first annotation timestamp
    assertThat(findSpans(twoDaysAgo, span.traceId))
      .contains("\"hits\":{\"total\":1");
  }

  String findSpans(long endTs, long traceId) throws IOException {
    return new OkHttpClient().newCall(new Request.Builder().url(
      HttpUrl.parse(baseUrl()).newBuilder()
        .addPathSegment(INDEX + ":span-" + dateFormat.format(new Date(endTs)))
        .addPathSegment("_search")
        .addQueryParameter("q", "traceId:" + Util.toLowerHex(traceId)).build())
      .get().build()).execute().body().string();
  }

  @Test
  public void spanGoesIntoADailyIndex_whenTimestampIsExplicit() throws Exception {
    long twoDaysAgo = (TODAY - 2 * DAY);

    Span span = Span.builder().traceId(20L).id(20L).name("get")
      .timestamp(twoDaysAgo * 1000).build();

    accept(span);

    // make sure the span went into an index corresponding to its timestamp, not collection time
    assertThat(findSpans(twoDaysAgo, span.traceId))
      .contains("\"hits\":{\"total\":1");
  }

  @Test
  public void spanGoesIntoADailyIndex_fallsBackToTodayWhenNoTimestamps() throws Exception {
    Span span = Span.builder().traceId(20L).id(20L).name("get").build();

    accept(span);

    // make sure the span went into an index corresponding to collection time
    assertThat(findSpans(TODAY, span.traceId))
      .contains("\"hits\":{\"total\":1");
  }

  @Test
  public void searchByTimestampMillis() throws Exception {
    Span span = Span.builder().timestamp(TODAY * 1000).traceId(20L).id(20L).name("get").build();

    accept(span);

    Call searchRequest = new OkHttpClient().newCall(new Request.Builder().url(
      HttpUrl.parse(baseUrl()).newBuilder()
        .addPathSegment(INDEX + ":span-*")
        .addPathSegment("_search")
        .addQueryParameter("q", "timestamp_millis:" + TODAY).build())
      .get().tag("search-terms").build());

    assertThat(searchRequest.execute().body().string())
      .contains("\"hits\":{\"total\":1");
  }

  abstract String baseUrl();

  void accept(Span span) throws Exception {
    storage().spanConsumer().accept(V2SpanConverter.fromSpan(span)).execute();
  }
}


text:
function onblur_apfd20(){
	var x = document.getElementById("apfd2-0").value;
	if(x == 4 || x == 5){
		document.getElementById("visible_apfd2-0").style.visibility = "visible";
	}else{
		document.getElementById("visible_apfd2-0").style.visibility = "hidden";
		document.getElementById("dias2-0").value = "";
	}
}


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

import ghidra.program.model.address.Address;
import ghidra.program.model.address.AddressRange;

/**
 * A trace-property access shim for a specific property
 *
 * @see PcodeTraceAccess
 * @see PcodeTraceDataAccess
 *
 * @param <T> the type of the property's values
 */
public interface PcodeTracePropertyAccess<T> {
	/**
	 * Get the property's value at the given address
	 *
	 *

	 * This may search for the same property from other related data sources, e.g., from mapped
	 * static images.
	 *
	 * @param address the address
	 * @return the value, or null if not set
	 */
	T get(Address address);

	/**
	 * Set the property's value at the given address
	 *
	 *

	 * The value is affective for future snapshots up to but excluding the next snapshot where
	 * another value is set at the same address.
	 *
	 * @param address the address
	 * @param value the value to set
	 */
	void put(Address address, T value);

	/**
	 * Clear the property's value across a range
	 *
	 * @param range the range
	 */
	void clear(AddressRange range);
}


text:
package com.yeamanan.projecttwo.model.mission;

import com.yeamanan.projecttwo.model.Element;
import com.yeamanan.projecttwo.model.character.Abomination;
import com.yeamanan.projecttwo.model.character.Fatty;
import com.yeamanan.projecttwo.model.character.Runner;
import com.yeamanan.projecttwo.model.character.Walker;
import com.yeamanan.projecttwo.model.character.ZombieDog;
import com.yeamanan.projecttwo.model.token.Door;
import com.yeamanan.projecttwo.model.token.Exit;
import com.yeamanan.projecttwo.model.token.Noise;
import com.yeamanan.projecttwo.model.token.Objective;
import com.yeamanan.projecttwo.model.token.Pimpmobile;
import com.yeamanan.projecttwo.model.token.PoliceCar;
import com.yeamanan.projecttwo.model.token.Start;
import com.yeamanan.projecttwo.model.token.Spawn;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 * Zone class.
 *
 * @author Yeam Anan (<yeamanan|at|gmail|dot|com>)
 */
@XmlType(name = "Zone")
@XmlRootElement(name = "Zone")
@XmlAccessorType(XmlAccessType.FIELD)
public class Zone extends Element {

    /**
     * Id.
     */
    @XmlAttribute(name = "id", required = true)
    private int id;

    /**
     * X.
     */
    @XmlAttribute(name = "x", required = true)
    private double x;

    /**
     * Y.
     */
    @XmlAttribute(name = "y", required = true)
    private double y;

    /**
     * Width.
     */
    @XmlAttribute(name = "width", required = true)
    private double width;

    /**
     * Height.
     */
    @XmlAttribute(name = "height", required = true)
    private double height;

    /**
     * List of elements in the zone.
     */
    @XmlElementWrapper(name = "Elements", required = false)
    @XmlElements({
        @XmlElement(name = "Walker", type = Walker.class),
        @XmlElement(name = "Fatty", type = Fatty.class),
        @XmlElement(name = "Runner", type = Runner.class),
        @XmlElement(name = "Abomination", type = Abomination.class),
        @XmlElement(name = "ZombieDog", type = ZombieDog.class),
        @XmlElement(name = "Door", type = Door.class),
        @XmlElement(name = "Exit", type = Exit.class),
        @XmlElement(name = "Noise", type = Noise.class),
        @XmlElement(name = "Objective", type = Objective.class),
        @XmlElement(name = "Pimpmobile", type = Pimpmobile.class),
        @XmlElement(name = "PoliceCar", type = PoliceCar.class),
        @XmlElement(name = "Start", type = Start.class),
        @XmlElement(name = "Spawn", type = Spawn.class)
    })
    private List<Element> elements;

    /**
     * Constructor.
     */
    public Zone() {
        this.id = 0;
        this.x = 0.0d;
        this.y = 0.0d;
        this.width = 0.0d;
        this.height = 0.0d;
        this.elements = new ArrayList<>();
    }

    /**
     * getId() method.
     *
     * @return the id of the zone
     */
    public final int getId() {
        return this.id;
    }

    /**
     * setId() method.
     *
     * @param argId the new id of the zone
     */
    public final void setId(final int argId) {
        this.id = argId;
    }

    /**
     * getX() method.
     *
     * @return the x position of the zone
     */
    public final double getX() {
        return this.x;
    }

    /**
     * setX() method.
     *
     * @param argX the new x position of the zone
     */
    public final void setX(final double argX) {
        this.x = argX;
    }

    /**
     * getY() method.
     *
     * @return the y position of the zone
     */
    public final double getY() {
        return this.y;
    }

    /**
     * setY() method.
     *
     * @param argY the new y position of the zone
     */
    public final void setY(final double argY) {
        this.y = argY;
    }

    /**
     * getWidth() method.
     *
     * @return the width of the zone
     */
    public final double getWidth() {
        return this.width;
    }

    /**
     * setWidth() method.
     *
     * @param argWidth the new width of the zone
     */
    public final void setWidth(final double argWidth) {
        this.width = argWidth;
    }

    /**
     * getHeight() method.
     *
     * @return the height of the zone
     */
    public final double getHeight() {
        return this.height;
    }

    /**
     * setHeight() method.
     *
     * @param argHeight the new height of the zone
     */
    public final void setHeight(final double argHeight) {
        this.height = argHeight;
    }

    /**
     * getElements() method.
     *
     * @return a list of elements
     */
    public final List<Element> getElements() {
        return this.elements;
    }

    /**
     * setElements() method.
     *
     * @param argElements the new list of elements
     */
    public final void setElements(final List<Element> argElements) {
        this.elements = argElements;
    }

}


text:
'use strict';

var should = require('should');
var _ = require('lodash');

var Sudoku = require('../src/Sudoku');
var sut = new Sudoku();

describe('Main sudoku generator node module', function () {
    var sudokuPuzzle = sut.generate(9);

    describe('Solution property', function() {
        var solution = sudokuPuzzle.solution;

        it('should not have duplicate numbers in any row.', function () {
            for (var i = 0; i < solution.length; i++) {
                for (var j = 1; j <= 9; j++) {
                    validateNumberOccursOnlyOnceInArry(solution[i], j);
                }
            }
        });

        it('should not have duplicate numbers in any column', function () {
            for (var i = 0; i < 9; i++) {
                var column = getColumnAsArray(solution, i);

                for (var j = 1; j <= 9; j++) {
                    validateNumberOccursOnlyOnceInArry(column, j);
                }
            }
        });

        it('should not have duplicate numbers in any section', function () {
            for (var i = 0; i < 9; i++) {
                var sectionXIndex = (i % 3) * 3;
                var sectionYIndex = (Math.floor(i / 3)) * 3;

                var section = getSubMatrix(solution, sectionXIndex, sectionYIndex, 3, 3);
                for (var j = 1; j <= 9; j++) {
                    validateNumberOccursOnlyOnceInMatrix(section, j);
                }
            }
        });
    });

});

function countOccurrancesInArray(arry, itemToCount) {
    return _.filter(arry, function (item) {
        return item === itemToCount;
    }).length;
}

function validateNumberOccursOnlyOnceInArry(arry, numberToValidate) {
    var count = countOccurrancesInArray(arry, numberToValidate);
    should(count).be.exactly(1);
}

function validateNumberOccursOnlyOnceInMatrix(matrix, numberToValidate) {
    var count = 0;

    for (var i = 0; i < matrix.length; i++) {
        count += countOccurrancesInArray(matrix[i], numberToValidate);
    }
    should(count).be.exactly(1);
}

function getColumnAsArray(matrix, columnIndex) {
    var result = [];
    for (var i = 0; i < matrix.length; i++) {
        result.push(matrix[i][columnIndex]);
    }
    return result;
}

function getSubMatrix(matrix, xIndex, yIndex, width, height) {
    var result = [];

    for (var j = yIndex; j < yIndex + height; j++) {
        var row = [];

        for (var i = xIndex; i < xIndex + width; i++) {
            row.push(matrix[j][i]);
        }

        result.push(row);
    }

    return result;
}


text:
import Util from './Util';
import Renderer from './Renderer';
import InlineLexer from './InlineLexer';
import marked from './marked';

export default class Parser {
  /**
   * Constructor
   */
  constructor(options) {
    this.tokens = [];
    this.token = null;
    this.options = options || marked.defaults();
    this.options.renderer = this.options.renderer || new Renderer(this.options);
    this.renderer = this.options.renderer;
  }

  /**
   * Static Parse Method
   */
  static parse(src, options, renderer) {
    var parser = new Parser(options, renderer);
    return parser.parse(src);
  };

  /**
   * Parse Loop
   */
  parse(src) {
    this.inline = new InlineLexer(src.links, this.options, this.renderer);
    this.tokens = src.reverse();

    var out = [];
    while (this.next()) {
      out.push(this.tok());
    }

    return out;
  }

  /**
   * Next Token
   */
  next() {
    return this.token = this.tokens.pop();
  }

  /**
   * Preview Next Token
   */
  peek() {
    return this.tokens[this.tokens.length - 1] || 0;
  }

  /**
   * Parse Text Tokens
   */
  parseText() {
    var body = this.token.text;

    while (this.peek().type === 'text') {
      body += '\n' + this.next().text;
    }

    return this.inline.output(body);
  }

  /**
   * Parse Current Token
   */
  tok() {
    switch (this.token.type) {
      case 'space':
        {
          return '';
        }
      case 'hr':
        {
          return this.renderer.hr();
        }
      case 'heading':
        {
          return this.renderer.heading(this.inline.output(this.token.text), this.token.depth, this.token.text);
        }
      case 'code':
        {
          return this.renderer.code(this.token.text, this.token.lang, this.token.escaped);
        }
      case 'table':
        {
          var header = [],
            body = [],
            i,
            row,
            cell,
            flags,
            j;

          // header
          cell = [];
          for (i = 0; i < this.token.header.length; i++) {
            flags = {
              header: true,
              align: this.token.align[i]
            };
            cell.push(this.renderer.tablecell(this.inline.output(this.token.header[i]), {
              header: true,
              align: this.token.align[i]
            }));
          }
          header.push(this.renderer.tablerow(cell));

          for (i = 0; i < this.token.cells.length; i++) {
            row = this.token.cells[i];

            cell = [];
            for (j = 0; j < row.length; j++) {
              cell.push(this.renderer.tablecell(this.inline.output(row[j]), {
                header: false,
                align: this.token.align[j]
              }));
            }

            body.push(this.renderer.tablerow(cell));
          }
          return this.renderer.table(header, body);
        }
      case 'spoiler_start':
        {
          var body = [];

          while (this.next().type !== 'spoiler_end') {
            body.push(this.tok());
          }

          return this.renderer.spoiler(body);
        }
      case 'blockquote_start':
        {
          var body = [];

          while (this.next().type !== 'blockquote_end') {
            body.push(this.tok());
          }

          return this.renderer.blockquote(body);
        }
      case 'list_start':
        {
          var body = [],
            ordered = this.token.ordered;

          while (this.next().type !== 'list_end') {
            body.push(this.tok());
          }

          return this.renderer.list(body, ordered);
        }
      case 'list_item_start':
        {
          var body = [];

          while (this.next().type !== 'list_item_end') {
            body.push(this.token.type === 'text'
              ? this.parseText()
              : this.tok());
          }

          return this.renderer.listitem(body);
        }
      case 'loose_item_start':
        {
          var body = [];

          while (this.next().type !== 'list_item_end') {
            body.push(this.tok());
          }

          return this.renderer.listitem(body);
        }
      case 'html':
        {
          var html = !this.token.pre && !this.options.pedantic
            ? this.inline.output(this.token.text)
            : this.token.text;
          return this.renderer.html(html);
        }
      case 'paragraph':
        {
          return this.renderer.paragraph(this.inline.output(this.token.text));
        }
      case 'text':
        {
          return this.renderer.paragraph(this.parseText());
        }
    }
  }
}


text:
package srv

import (
	"encoding/json"
	"fmt"
	"io"
	"net"
	"strings"
	"sync"

	"github.com/gravitational/teleport/lib/defaults"
	"github.com/gravitational/teleport/lib/reversetunnel"
	"github.com/gravitational/teleport/lib/services"
	"github.com/gravitational/teleport/lib/sshutils"
	"github.com/gravitational/teleport/lib/utils"

	log "github.com/Sirupsen/logrus"
	"github.com/gravitational/trace"
	"golang.org/x/crypto/ssh"
)

// proxySubsys implements an SSH subsystem for proxying listening sockets from
// remote hosts to a proxy client (AKA port mapping)
type proxySubsys struct {
	srv       *Server
	host      string
	port      string
	namespace string
	siteName  string
	closeC    chan struct{}
	error     error
	closeOnce sync.Once
}

// parseProxySubsys looks at the requested subsystem name and returns a fully configured
// proxy subsystem
//
// proxy subsystem name can take the following forms:
//  "proxy:host:22"          - standard SSH request to connect to  host:22 on the 1st cluster
//  "proxy:@clustername"        - Teleport request to connect to an auth server for cluster with name 'clustername'
//  "proxy:host:22@clustername" - Teleport request to connect to host:22 on cluster 'clustername'
//  "proxy:host:22@namespace@clustername"
func parseProxySubsys(name string, srv *Server) (*proxySubsys, error) {
	log.Debugf("parse_proxy_subsys(%s)", name)
	var (
		siteName   string
		host       string
		port       string
		paramError = trace.BadParameter("invalid format for proxy request: '%v', expected 'proxy:host:port@site'", name)
	)
	const prefix = "proxy:"
	// get rid of 'proxy:' prefix:
	if strings.Index(name, prefix) != 0 {
		return nil, trace.Wrap(paramError)
	}
	name = strings.TrimPrefix(name, prefix)
	namespace := defaults.Namespace
	// find the site name in the argument:
	parts := strings.Split(name, "@")
	switch len(parts) {
	case 2:
		siteName = strings.Join(parts[1:], "@")
		name = parts[0]
	case 3:
		siteName = strings.Join(parts[2:], "@")
		namespace = parts[1]
		name = parts[0]
	}
	// find host & port in the arguments:
	host, port, err := net.SplitHostPort(name)
	if siteName == "" && err != nil {
		return nil, trace.Wrap(paramError)
	}
	// validate siteName
	if siteName != "" && srv.proxyTun != nil {
		_, err := srv.proxyTun.GetSite(siteName)
		if err != nil {
			return nil, trace.BadParameter("unknown site '%s'", siteName)
		}
	}

	return &proxySubsys{
		namespace: namespace,
		srv:       srv,
		host:      host,
		port:      port,
		siteName:  siteName,
		closeC:    make(chan struct{}),
	}, nil
}

func (t *proxySubsys) String() string {
	return fmt.Sprintf("proxySubsys(site=%s/%s, host=%s, port=%s)",
		t.namespace, t.siteName, t.host, t.port)
}

// start is called by Golang's ssh when it needs to engage this sybsystem (typically to establish
// a mapping connection between a client & remote node we're proxying to)
func (t *proxySubsys) start(sconn *ssh.ServerConn, ch ssh.Channel, req *ssh.Request, ctx *ctx) error {
	log.Debugf("[PROXY] subsystem(from: %v, to: %v)", sconn.RemoteAddr(), sconn.LocalAddr())
	var (
		site       reversetunnel.RemoteSite
		err        error
		tunnel     = t.srv.proxyTun
		clientAddr = sconn.RemoteAddr()
	)
	// get the site by name:
	if t.siteName != "" {
		site, err = tunnel.GetSite(t.siteName)
		if err != nil {
			log.Warn(err)
			return trace.Wrap(err)
		}
	}
	// connecting to a specific host:
	if t.host != "" {
		// no site given? use the 1st one:
		if site == nil {
			sites := tunnel.GetSites()
			if len(sites) == 0 {
				log.Errorf("[PROXY] not connected to any remote clusters")
				return trace.Errorf("no connected sites")
			}
			site = sites[0]
			log.Debugf("[PROXY] subsystem: cluster not specified. connecting to default='%s'", site.GetName())
		}
		return t.proxyToHost(site, clientAddr, ch)
	}
	// connect to a site's auth server:
	return t.proxyToSite(site, clientAddr, ch)
}

// proxyToSite establishes a proxy connection from the connected SSH client to the
// auth server of the requested remote site
func (t *proxySubsys) proxyToSite(
	site reversetunnel.RemoteSite, remoteAddr net.Addr, ch ssh.Channel) error {

	var (
		err  error
		conn net.Conn
	)
	siteClient, err := site.GetClient()
	if err != nil {
		return trace.Wrap(err)
	}
	authServers, err := siteClient.GetAuthServers()
	if err != nil {
		return trace.Wrap(err)
	}

	for _, authServer := range authServers {
		conn, err = site.Dial(remoteAddr,
			&utils.NetAddr{Addr: authServer.Addr, AddrNetwork: "tcp"})
		if err != nil {
			log.Error(err)
			continue
		}
		log.Infof("[PROXY] connected to auth server: %v", authServer.Addr)
		go func() {
			var err error
			defer func() {
				t.close(err)
			}()
			defer ch.Close()
			_, err = io.Copy(ch, conn)
		}()
		go func() {
			var err error
			defer func() {
				t.close(err)
			}()
			defer conn.Close()
			_, err = io.Copy(conn, ch)

		}()
		return nil
	}
	return err
}

// proxyToHost establishes a proxy connection from the connected SSH client to the
// requested remote node (t.host:t.port) via the given site
func (t *proxySubsys) proxyToHost(
	site reversetunnel.RemoteSite, remoteAddr net.Addr, ch ssh.Channel) error {
	//
	// first, lets fetch a list of servers at the given site. this allows us to
	// match the given "host name" against node configuration (their 'nodename' setting)
	//
	// but failing to fetch the list of servers is also OK, we'll use standard
	// network resolution (by IP or DNS)
	//
	var (
		servers []services.Server
		err     error
	)
	localDomain, _ := t.srv.authService.GetDomainName()
	// going to "local" CA? lets use the caching 'auth service' directly and avoid
	// hitting the reverse tunnel link (it can be offline if the CA is down)
	if site.GetName() == localDomain {
		servers, err = t.srv.authService.GetNodes(t.namespace)
		if err != nil {
			log.Warn(err)
		}
	} else {
		// "remote" CA? use a reverse tunnel to talk to it:
		siteClient, err := site.GetClient()
		if err != nil {
			log.Warn(err)
		} else {
			servers, err = siteClient.GetNodes(t.namespace)
			if err != nil {
				log.Warn(err)
			}
		}
	}
	// enumerate and try to find a server with a matching name
	serverAddr := net.JoinHostPort(t.host, t.port)
	var server *services.Server
	for i := range servers {
		ip, port, err := net.SplitHostPort(servers[i].Addr)
		if err != nil {
			return trace.Wrap(err)
		}

		// match either by hostname of ip, based on the match
		if (t.host == ip || t.host == servers[i].Hostname) && port == t.port {
			server = &servers[i]
			break
		}
	}
	if server != nil {
		serverAddr = server.Addr
	}

	// we must dial by server IP address because hostname
	// may not be actually DNS resolvable
	conn, err := site.Dial(
		remoteAddr,
		&utils.NetAddr{Addr: serverAddr, AddrNetwork: "tcp"})
	if err != nil {
		return trace.ConvertSystemError(err)
	}

	// this custom SSH handshake allows SSH proxy to relay the client's IP
	// address to the SSH erver:
	doHandshake(remoteAddr, ch, conn)

	go func() {
		var err error
		defer func() {
			t.close(err)
		}()
		defer ch.Close()
		_, err = io.Copy(ch, conn)
	}()
	go func() {
		var err error
		defer func() {
			t.close(err)
		}()
		defer conn.Close()
		_, err = io.Copy(conn, ch)

	}()
	return nil
}

func (t *proxySubsys) close(err error) {
	t.closeOnce.Do(func() {
		t.error = err
		close(t.closeC)
	})
}

func (t *proxySubsys) wait() error {
	<-t.closeC
	return t.error
}

// doHandshake allows a proxy server to send additional information (client IP)
// to an SSH server before establishing a bridge
func doHandshake(clientAddr net.Addr, clientConn io.ReadWriter, serverConn io.ReadWriter) {
	// on behalf of a client ask the server for it's version:
	var bytes [sshutils.MaxVersionStringBytes]byte
	n, err := serverConn.Read(bytes[:])
	if err != nil {
		log.Error(err)
		return
	}
	// is that a Teleport server?
	resp := bytes[:n]
	if strings.HasPrefix(string(resp), sshutils.SSHVersionPrefix) {
		// if we're connecting to a Teleport SSH server, send our own "handshake payload"
		// message, along with a client's IP:
		hp := &sshutils.HandshakePayload{
			ClientAddr: clientAddr.String(),
		}
		payloadJSON, err := json.Marshal(hp)
		if err != nil {
			log.Error(err)
		} else {
			n, err = serverConn.Write(
				[]byte(fmt.Sprintf("%s\n%s", sshutils.ProxyHelloSignature, payloadJSON)))
			if err != nil {
				log.Error(err)
			}
		}
	}
	// forwrd server's response to the client:
	n, err = clientConn.Write(resp)
	if err != nil {
		log.Error(err)
	}
}


text:
using SmoONE.Domain;
using SmoONE.Domain.IRepository;
using SmoONE.Infrastructure;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;

namespace SmoONE.Repository.Contact
{
   public  class ContactRepository: BaseRepository<SmoONE.Domain.Contact>,IContactRepository
    {
        // <summary>
        /// 仓储类的构造函数
        /// </summary>
        /// <param name="dbContext">数据库上下文</param>
        public ContactRepository(IDbContext dbContext)
            : base(dbContext)
        { }

        /// <summary>
        /// 根据ID返回联系人对象
        /// </summary>_entities.Where(x => x.C_CreateUser == UserID).OrderByDescending(o => o.C_ID ).AsNoTracking()
        /// <param name="ID">请假单ID</param>
        public IQueryable<SmoONE.Domain.Contact> GetByID(int ID)
        {
            return _entities.Where(x => x.C_ID == ID);
        }
        /// <summary>
        /// 根据创建用户ID返回联系人传输对象
        /// </summary>
        /// <param name="UserID">用户ID</param>
        public IQueryable<SmoONE.Domain.Contact> GetByCreateUsers(string UserID)
        {
            return _entities.Where(x => x.C_CreateUser == UserID).OrderByDescending(o => o.C_ID ).AsNoTracking();
        }
    }
}


text:
package com.sequenceiq.cloudbreak.service.clustertemplate;

import java.util.Set;

import javax.inject.Inject;
import javax.transaction.Transactional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.stereotype.Service;

import com.sequenceiq.cloudbreak.common.model.user.IdentityUser;
import com.sequenceiq.cloudbreak.common.model.user.IdentityUserRole;
import com.sequenceiq.cloudbreak.common.type.APIResourceType;
import com.sequenceiq.cloudbreak.controller.NotFoundException;
import com.sequenceiq.cloudbreak.domain.ClusterTemplate;
import com.sequenceiq.cloudbreak.repository.ClusterRepository;
import com.sequenceiq.cloudbreak.repository.ClusterTemplateRepository;
import com.sequenceiq.cloudbreak.service.AuthorizationService;
import com.sequenceiq.cloudbreak.service.DuplicateKeyValueException;

@Service
@Transactional
public class ClusterTemplateService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ClusterTemplateService.class);

    @Inject
    private ClusterTemplateRepository clusterTemplateRepository;

    @Inject
    private ClusterRepository clusterRepository;

    @Inject
    private AuthorizationService authorizationService;

    public Set<ClusterTemplate> retrievePrivateClusterTemplates(IdentityUser user) {
        return clusterTemplateRepository.findForUser(user.getUserId());
    }

    public Set<ClusterTemplate> retrieveAccountClusterTemplates(IdentityUser user) {
        if (user.getRoles().contains(IdentityUserRole.ADMIN)) {
            return clusterTemplateRepository.findAllInAccount(user.getAccount());
        } else {
            return clusterTemplateRepository.findPublicInAccountForUser(user.getUserId(), user.getAccount());
        }
    }

    @PostAuthorize("hasPermission(returnObject,'read')")
    public ClusterTemplate get(Long id) {
        ClusterTemplate clusterTemplate = clusterTemplateRepository.findOne(id);
        if (clusterTemplate == null) {
            throw new NotFoundException(String.format("ClusterTemplate '%s' not found.", id));
        }
        return clusterTemplate;
    }

    @PostAuthorize("hasPermission(returnObject,'read')")
    public ClusterTemplate getByName(String name, IdentityUser user) {
        ClusterTemplate clusterTemplate = clusterTemplateRepository.findByNameInAccount(name, user.getAccount(), user.getUsername());
        if (clusterTemplate == null) {
            throw new NotFoundException(String.format("Blueprint '%s' not found.", name));
        }
        return clusterTemplate;
    }

    @Transactional(Transactional.TxType.NEVER)
    public ClusterTemplate create(IdentityUser user, ClusterTemplate clusterTemplate) {
        LOGGER.debug("Creating clusterTemplate: [User: '{}', Account: '{}']", user.getUsername(), user.getAccount());
        ClusterTemplate savedClusterTemplate;
        clusterTemplate.setOwner(user.getUserId());
        clusterTemplate.setAccount(user.getAccount());
        try {
            savedClusterTemplate = clusterTemplateRepository.save(clusterTemplate);
        } catch (DataIntegrityViolationException ex) {
            throw new DuplicateKeyValueException(APIResourceType.CLUSTER_TEMPLATE, clusterTemplate.getName(), ex);
        }
        return savedClusterTemplate;
    }

    public void delete(Long id, IdentityUser user) {
        ClusterTemplate clusterTemplate = clusterTemplateRepository.findByIdInAccount(id, user.getAccount());
        if (clusterTemplate == null) {
            throw new NotFoundException(String.format("ClusterTemplate '%s' not found.", id));
        }
        delete(clusterTemplate);
    }

    public ClusterTemplate getPublicClusterTemplate(String name, IdentityUser user) {
        ClusterTemplate clusterTemplate = clusterTemplateRepository.findOneByName(name, user.getAccount());
        if (clusterTemplate == null) {
            throw new NotFoundException(String.format("ClusterTemplate '%s' not found.", name));
        }
        return clusterTemplate;
    }

    public ClusterTemplate getPrivateClusterTemplate(String name, IdentityUser user) {
        ClusterTemplate clusterTemplate = clusterTemplateRepository.findByNameInUser(name, user.getUserId());
        if (clusterTemplate == null) {
            throw new NotFoundException(String.format("ClusterTemplate '%s' not found.", name));
        }
        return clusterTemplate;
    }

    public void delete(String name, IdentityUser user) {
        ClusterTemplate clusterTemplate = clusterTemplateRepository.findByNameInAccount(name, user.getAccount(), user.getUserId());
        if (clusterTemplate == null) {
            throw new NotFoundException(String.format("ClusterTemplate '%s' not found.", name));
        }
        delete(clusterTemplate);
    }

    @Transactional(Transactional.TxType.NEVER)
    public Iterable<ClusterTemplate> save(Iterable<ClusterTemplate> entities) {
        return clusterTemplateRepository.save(entities);
    }

    private void delete(ClusterTemplate clusterTemplate) {
        authorizationService.hasWritePermission(clusterTemplate);
        clusterTemplateRepository.delete(clusterTemplate);
    }
}


text:
namespace Microsoft.Azure.Management.DataBox
{
  using System;
  using System.Collections.Generic;
  using System.Linq;

  internal static partial class SdkInfo
  {
      public static IEnumerable<Tuple<string, string, string>> ApiInfo_DataBoxManagementClient
      {
          get
          {
              return new Tuple<string, string, string>[]
              {
                new Tuple<string, string, string>("DataBox", "Jobs", "2021-08-01-preview"),
                new Tuple<string, string, string>("DataBox", "Mitigate", "2021-08-01-preview"),
                new Tuple<string, string, string>("DataBox", "Operations", "2021-08-01-preview"),
                new Tuple<string, string, string>("DataBox", "Service", "2021-08-01-preview"),
              }.AsEnumerable();
          }
      }
      // BEGIN: Code Generation Metadata Section
      public static readonly String AutoRestVersion = "v2";
      public static readonly String AutoRestBootStrapperVersion = "autorest@3.3.2";
      public static readonly String AutoRestCmdExecuted = "cmd.exe /c autorest.cmd https://github.com/Azure/azure-rest-api-specs/blob/master/specification/databox/resource-manager/readme.md --csharp --version=v2 --reflect-api-versions --csharp-sdks-folder=D:\\azure-sdk\\azure-sdk-for-net\\sdk";
      public static readonly String GithubForkName = "Azure";
      public static readonly String GithubBranchName = "master";
      public static readonly String GithubCommidId = "5ee7c98d2f778a2a3f867215eba5b13ddf139f6e";
      public static readonly String CodeGenerationErrors = "";
      public static readonly String GithubRepoName = "azure-rest-api-specs";
      // END: Code Generation Metadata Section
  }
}


text:
import argparse
import copy
import logging
import os
import sys

from datetime import datetime
from fn import _
from opentuner.driverbase import DriverBase
from opentuner.resultsdb.models import Configuration
from opentuner.resultsdb.models import DesiredResult
from opentuner.resultsdb.models import Result
from opentuner.resultsdb.models import BanditInfo
from opentuner.resultsdb.models import BanditSubTechnique
from opentuner.search import plugin
from opentuner.search import technique
from opentuner.search.bandittechniques import AUCBanditMetaTechnique

log = logging.getLogger(__name__)

argparser = argparse.ArgumentParser(add_help=False)
argparser.add_argument('--test-limit', type=int, default=5000,
                       help='stop tuning after given tests count')
argparser.add_argument('--stop-after', type=float,
                       help='stop tuning after given seconds')
argparser.add_argument('--parallelism', type=int, default=4,
                       help='how many tests to support at once')
argparser.add_argument('--pipelining', type=int, default=0,
                       help='how long a delay (in generations) before results are available')
argparser.add_argument('--bail-threshold', type=int, default=500,
                       help='abort if no requests have been made in X generations')
argparser.add_argument('--no-dups', action='store_true',
                       help='don\'t print out warnings for duplicate requests')
argparser.add_argument('--seed-configuration', action='append', default=[],
                       metavar='FILENAME', help="""
                           Start search at a given configuration.  Can be
                           specified multiple times.  Configurations are loaded
                           with ConfigurationManipulator.load_from_file()
                           and file format is detected from extension.""")

class SearchDriver(DriverBase):
  """
  controls the search process managing root_technique and creating
  DesiredResults
  """

  def __init__(self, manipulator, extra_seeds=None, **kwargs):
    super(SearchDriver, self).__init__(**kwargs)
    if extra_seeds is None:
      extra_seeds = []
    self.manipulator = manipulator
    self.wait_for_results = self.tuning_run_main.results_wait
    self.commit = self.tuning_run_main.commit

    self.generation = 0
    self.test_count = 0
    self.plugins = plugin.get_enabled(self.args)
    self.pending_result_callbacks = list()  # (DesiredResult, function) tuples
    # deepcopy is required to have multiple tuning runs in a single process
    if self.args.list_techniques:
      techniques, generators = technique.all_techniques()
      for t in techniques:
        print t.name
      sys.exit(0)

    if self.args.generate_bandit_technique:
      # generate a bandit
      self.root_technique = AUCBanditMetaTechnique.generate_technique(manipulator)
    else:
      self.root_technique = copy.deepcopy(technique.get_root(self.args))

    if isinstance(self.root_technique, AUCBanditMetaTechnique):
      self.session.flush()
      info = BanditInfo(tuning_run=self.tuning_run,
                        c=self.root_technique.bandit.C,
                        window=self.root_technique.bandit.window,)
      self.session.add(info)
      for t in self.root_technique.techniques:
        subtechnique = BanditSubTechnique(bandit_info=info,
                                          name=t.name)
        self.session.add(subtechnique)

    self.objective.set_driver(self)
    self.pending_config_ids = set()
    self.best_result = None

    for t in self.plugins:
      t.set_driver(self)
    self.root_technique.set_driver(self)
    self.seed_cfgs = list(extra_seeds)
    for cfg_filename in reversed(self.args.seed_configuration):
      if os.path.exists(cfg_filename):
        self.seed_cfgs.append(manipulator.load_from_file(cfg_filename))
      else:
        log.error('no such file for --seed-configuration %s', cfg_filename)

    self.plugins.sort(key=_.priority)

  def add_plugin(self, p):
    if p in self.plugins:
      return
    self.plugins.append(p)
    self.plugins.sort(key=_.priority)
    p.set_driver(self)

  def convergence_criteria(self):
    """returns true if the tuning process should stop"""
    if self.args.stop_after:
      elapsed = (datetime.now() - self.tuning_run.start_date)
      try:
        elapsed = elapsed.total_seconds()
      except:  # python 2.6
        elapsed = elapsed.days * 86400 + elapsed.seconds
      return elapsed > self.args.stop_after
    return self.test_count > self.args.test_limit

  def register_result_callback(self, desired_result, callback):
    if desired_result.result is not None:
      callback(desired_result.result)
    else:
      self.pending_result_callbacks.append((desired_result, callback))

  def result_callbacks(self):
    pending = self.pending_result_callbacks
    self.pending_result_callbacks = list()
    for dr, callback in pending:
      if dr.result is not None:
        callback(dr.result)
        continue
      elif self.generation - dr.generation > self.args.pipelining:
        # see if we can find a result
        results = self.results_query(config=dr.configuration).all()
        log.warning("Result callback %d (requestor=%s) pending for "
                    "%d generations %d results available",
                    dr.id, dr.requestor, self.generation - dr.generation,
                    len(results))
        if len(results):
          dr.result = results[0]
          callback(dr.result)
          continue
      # try again later
      self.pending_result_callbacks.append((dr, callback))

  def has_results(self, config):
    return self.results_query(config=config).count() > 0

  def run_generation_techniques(self):
    tests_this_generation = 0
    self.plugin_proxy.before_techniques()
    for z in xrange(self.args.parallelism):
      if self.seed_cfgs:
        config = self.get_configuration(self.seed_cfgs.pop())
        dr = DesiredResult(configuration=config,
                           requestor='seed',
                           generation=self.generation,
                           request_date=datetime.now(),
                           tuning_run=self.tuning_run)
      else:
        dr = self.root_technique.desired_result()
      if dr is None or dr is False:
        log.debug("no desired result, skipping to testing phase")
        break
      self.session.flush()  # populate configuration_id
      duplicates = (self.session.query(DesiredResult)
                    .filter_by(tuning_run=self.tuning_run,
                               configuration_id=dr.configuration_id)
                    .filter(DesiredResult.id != dr.id)
                    .order_by(DesiredResult.request_date)
                    .limit(1).all())
      self.session.add(dr)
      if len(duplicates):
        if not self.args.no_dups:
          log.warning("duplicate configuration request #%d %s/%s %s",
                      self.test_count,
                      dr.requestor,
                      duplicates[0].requestor,
                      'OLD' if duplicates[0].result else 'PENDING')
        self.session.flush()
        desired_result_id = dr.id

        def callback(result):
          dr = self.session.query(DesiredResult).get(desired_result_id)
          dr.result = result
          dr.state = 'COMPLETE'
          dr.start_date = datetime.now()

        self.register_result_callback(duplicates[0], callback)
      else:
        log.debug("desired result id=%d, cfg=%d", dr.id, dr.configuration_id)
        dr.state = 'REQUESTED'
      self.test_count += 1
      tests_this_generation += 1
    self.plugin_proxy.after_techniques()
    return tests_this_generation

  def process_new_results(self):
    for result in (self.results_query()
                       .filter_by(was_new_best=None)
                       .order_by(Result.collection_date)):
      self.plugin_proxy.on_result(result)
      if self.best_result is None:
        self.best_result = result
        result.was_new_best = True
      elif self.objective.lt(result, self.best_result):
        self.best_result = result
        result.was_new_best = True
        self.plugin_proxy.on_new_best_result(result)
      else:
        result.was_new_best = False
    self.result_callbacks()

  def run_generation_results(self, offset=0):
    self.commit()
    self.plugin_proxy.before_results_wait()
    self.wait_for_results(self.generation + offset)
    self.plugin_proxy.after_results_wait()
    self.process_new_results()

  @property
  def plugin_proxy(self):
    """
    forward any method calls on the returned object to all plugins
    """
    plugins = self.plugins

    class PluginProxy(object):
      def __getattr__(self, method_name):
        def plugin_method_proxy(*args, **kwargs):
          rv = []
          for plugin in plugins:
            rv.append(getattr(plugin, method_name)(*args, **kwargs))
          return filter(lambda x: x is not None, rv)

        return plugin_method_proxy

    return PluginProxy()

  def get_configuration(self, cfg):
    """called by SearchTechniques to create Configuration objects"""
    self.manipulator.normalize(cfg)
    hashv = self.manipulator.hash_config(cfg)
    config = Configuration.get(self.session,self.program, hashv, cfg)
    return config

  def main(self):
    self.plugin_proxy.set_driver(self)
    self.plugin_proxy.before_main()

    no_tests_generations = 0

    # prime pipeline with tests
    for z in xrange(self.args.pipelining):
      self.run_generation_techniques()
      self.generation += 1

    while not self.convergence_criteria():
      if self.run_generation_techniques() > 0:
        no_tests_generations = 0
      elif no_tests_generations <= self.args.bail_threshold:
        no_tests_generations += 1
      else:
        break
      self.run_generation_results(offset=-self.args.pipelining)
      self.generation += 1

    self.plugin_proxy.after_main()

  def external_main_begin(self):
    self.plugin_proxy.set_driver(self)
    self.plugin_proxy.before_main()

  def external_main_generation(self):
    if self.generation > 0:
      self.plugin_proxy.after_results_wait()
    self.process_new_results()
    self.run_generation_techniques()
    self.commit()
    self.plugin_proxy.before_results_wait()

  def external_main_end(self):
    self.plugin_proxy.after_main()


text:
package org.wso2.andes.amqp;

import org.wso2.andes.kernel.AndesMessage;
import org.wso2.andes.kernel.AndesMessageMetadata;

/**
 * This is a sub class of AndesMessage which contains AMQP protocol specific implementations
 */
public class AMQPMessage extends AndesMessage {

    public AMQPMessage(AndesMessageMetadata metadata) {
        super(metadata);
    }

}


text:
'use strict';

const EntityCollection = require('@frctl/core').entities.Collection;

module.exports = class ComponentCollection extends EntityCollection {
    constructor(config, items, parent) {
        super(config.name, config, items, parent);
    }

    find() {
        return this.source.find.apply(this, arguments);
    }

    components() {
        return super.entities();
    }

    variants() {
        return this.source.variants.apply(this, arguments);
    }
};


text:
Find Your Fracker

v0.1 of findyourfracker.org

This website uses json data, Google Maps, and the Sunlight API to look up voting records re: fracking for NC legislators. This is intended to be expanded nationally.

The site layout was built with Bootstrap. The prototype search was built by David Egen and resides at:

  search/

The intended production search rewritten in php resides at:

  search/location/location.htm

To use, go to http://sunlightfoundation.com/api/ for a Sunlight API key, and enter it at this file:

  includes/key.php

It may also be necessary to set URL permissions on the Sunlight account to allow lookup to function properly with their API.

Anyone interested in taking this project to the national level is welcome to take over the findyourfracker.org domain.  Just reach out to us.  As of htis writing, (20160226) the prototype search functions are functional for demonstration here:
http://www.findyourfracker.org/


text:
package guicomponents;

import java.awt.Point;
import java.awt.event.MouseEvent;

import processing.core.PApplet;

/**
 * The vertical slider component
 *
 * @author Peter Lager
 *
 */
public class GVertSlider extends GSlider {

	/**
	 * Create a vertical slider.
	 * Default values:
	 * 		Range 0-100
	 *      Initial value 50
	 * Use the setLimits method to customise these values.
	 *
	 * @param theApplet
	 * @param x
	 * @param y
	 * @param width
	 * @param height
	 */
	public GVertSlider(PApplet theApplet, int x, int y, int width, int height){
		super(theApplet, x, y, width, height);
		initThumbDetails();
		z = Z_SLIPPY;
	}

	/**
	 * Initialises the thumb details called by constructor
	 */
	protected void initThumbDetails(){
		thumbSize = Math.max(20, height / 20);
		thumbMin = thumbSize/2;
		thumbMax = height - thumbSize/2;
		thumbTargetPos = thumbPos;
	}

	/**
	 * Draw the slider
	 */
	public void draw(){
		if(!visible) return;

		winApp.pushStyle();
		winApp.style(G4P.g4pStyle);

		Point pos = new Point(0,0);
		calcAbsPosition(pos);

		winApp.noStroke();
		winApp.fill(localColor.sdrTrack);
		winApp.rect(pos.x, pos.y, width, height);
		winApp.fill(localColor.sdrThumb);
		winApp.rect(pos.x, pos.y + thumbPos - thumbSize/2, width, thumbSize);
		if(border != 0){
			winApp.strokeWeight(border);
			winApp.noFill();
			winApp.stroke(localColor.sdrBorder);
			winApp.rect(pos.x, pos.y, width, height);
		}
		winApp.popStyle();

	}

	/**
	 * If this slider is part of a combo box then hand focus back to
	 * the combo box
	 */
	protected void loseFocus(GComponent grabber){
		if(cursorIsOver == this)
			cursorIsOver = null;
		String pname = (parent == null) ? "" : parent.getClass().getSimpleName();
		if(pname.equalsIgnoreCase("GCombo")){
			focusIsWith = parent;
		}
		else
			focusIsWith = null;
	}

	/**
	 * All GUI components are registered for mouseEvents
	 */
	public void mouseEvent(MouseEvent event){
		if(!visible || !enabled) return;

		boolean mouseOver = isOver(winApp.mouseX, winApp.mouseY);
		if(mouseOver || focusIsWith == this)
			cursorIsOver = this;
		else if(cursorIsOver == this)
				cursorIsOver = null;

		switch(event.getID()){
		case MouseEvent.MOUSE_PRESSED:
			if(focusIsWith != this && mouseOver && z > focusObjectZ()){
				mdx = winApp.mouseX;
				mdy = winApp.mouseY;
				takeFocus();
			}
			break;
		case MouseEvent.MOUSE_CLICKED:
			if(focusIsWith == this){
				loseFocus(null);
				mdx = mdy = Integer.MAX_VALUE;
			}
			break;
		case MouseEvent.MOUSE_RELEASED:
			if(focusIsWith == this && mouseHasMoved(winApp.mouseX, winApp.mouseY)){
				loseFocus(null);
				mdx = mdy = Integer.MAX_VALUE;
			}
			break;
		case MouseEvent.MOUSE_DRAGGED:
			if(focusIsWith == this){
				isValueChanging = true;
				Point p = new Point(0,0);
				calcAbsPosition(p);
				thumbTargetPos = PApplet.constrain(winApp.mouseY - offset - p.y, thumbMin, thumbMax);
			}
			break;
		}
	}

	/**
	 * Determines whether the position ax, ay is over the thumb
	 * of this GPanel.
	 *
	 * @return true if mouse is over the panel tab else false
	 */
	public boolean isOver(int ax, int ay){
		Point p = new Point(0,0);
		calcAbsPosition(p);
		if(ax >= p.x && ax <= p.x + width && ay >= p.y + thumbPos - thumbSize/2 && ay <= p.y + thumbPos + thumbSize/2){
			offset = ay - (p.y + thumbPos);
			return true;
		}
		else
			return false;
	}
} // end of class


text:
package com.citypay.pan.search

import java.util.concurrent._

import com.citypay.pan.search.source.ScanSource
import com.citypay.pan.search.util.NamedThreadFactory

import scala.concurrent.ExecutionContext
import scala.util.control.NonFatal

/**
  * Defines the context for a search
  */
trait SearchContext {

  /**
    * @return a specification of searches used for level 1 searching. Level 1 searches are used against the core
    *         data in the file to attempt to locate a match. Once a match has been found its potential is realised
    *         by further review against a level 2 test which is expected to be higher detail of a bin range
    */
  def level1: List[PanSpec]

  /**
    * @return a level 2 list of specs, see [[level1]]
    */
  def level2: List[PanSpec] = level1

  /**
    * @return a list of strings which are false positive matches and should be ignored
    */
  def falsePositives: List[String] = Nil

  /**
    * @return a list of scan sources
    */
  def sources: List[ScanSource]

  /**
    * @return true if the search should stop when a single PAN is found, this may speed up searches to black list
    *         files for further analysis
    */
  def stopOnFirstMatch: Boolean

  /**
    * All possible distinct leading single byte values
    *
    */
  val leadingPanDigits: List[Byte] = level1.map(_.firstDigit.toString.getBytes.head).distinct

  /**
    * The calculated mimumum length of any pan based on the configured specs
    */
  val minimumLength: Int = level1.foldLeft(16)((i, s) => if (s.length < i) s.length else i)

  /**
    * The calculated maximum length of any pan based on the configured specs
    */
  val maximumLength: Int = level1.foldLeft(16)((i, s) => if (s.maxLength > i) s.maxLength else i)

  def config: ScannerConfig

  // run some sanity checks against the search context
  assume(level1.nonEmpty, "No level1 specs, cannot search")
  assume(level2.nonEmpty, "No level2 specs, cannot search")

}


text:
package mf.org.apache.xerces.impl.dtd;

import mf.org.apache.xerces.xni.parser.XMLDocumentFilter;

/**
 * Defines a DTD Validator filter to allow
 * components to query the DTD validator.
 *
 * @xerces.internal
 *
 * @author Elena Litani, IBM
 *
 * @version $Id: XMLDTDValidatorFilter.java 446755 2006-09-15 21:56:27Z mrglavas $
 */
public interface XMLDTDValidatorFilter
    extends XMLDocumentFilter {

    /**
     * Returns true if the validator has a DTD grammar
     *
     * @return true if the validator has a DTD grammar
     */
    public boolean hasGrammar();

    /**
     * Return true if validator must validate the document
     *
     * @return true if validator must validate the document
     */
    public boolean validate();

} // interface XMLDTDValidatorFilter


text:
FactoryGirl.define do
  factory :entry, :class => 'Entry' do
    title "hk's weblog's entry"
  end
end