text:
package tcking.github.com.giraffeplayer2;

import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.SeekBar;

import com.github.tcking.giraffeplayer2.R;

import java.util.Locale;

import tcking.github.com.giraffeplayer2.trackselector.TrackSelectorFragment;
import tv.danmaku.ijk.media.player.IMediaPlayer;
import tv.danmaku.ijk.media.player.IjkTimedText;

/**
 * media controller for ListView or RecyclerView
 * Created by tcking on 2017
 */

public class DefaultMediaController extends BaseMediaController {

    protected static final int STATUS_ERROR = -1;
    protected static final int STATUS_IDLE = 0;
    protected static final int STATUS_LOADING = 1;
    protected static final int STATUS_PLAYING = 2;
    protected static final int STATUS_PAUSE = 3;
    protected static final int STATUS_COMPLETED = 4;

    protected long newPosition = -1;
    protected boolean isShowing;
    protected boolean isDragging;

    protected boolean instantSeeking;
    protected SeekBar seekBar;

    protected int volume = -1;
    protected final int maxVolume;

    protected float brightness;
    private int status = STATUS_IDLE;
    private int displayModel = GiraffePlayer.DISPLAY_NORMAL;

    private String generateTime(long time) {
        int totalSeconds = (int) (time / 1000);
        int seconds = totalSeconds % 60;
        int minutes = (totalSeconds / 60) % 60;
        int hours = totalSeconds / 3600;
        return hours > 0 ? String.format("%02d:%02d:%02d", hours, minutes, seconds) : String.format("%02d:%02d", minutes, seconds);
    }

    protected final SeekBar.OnSeekBarChangeListener seekListener = new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (!fromUser)
                return;
            if (!videoView.isCurrentActivePlayer()) {
                return;
            }
            $.id(R.id.app_video_status).gone();//移动时隐藏掉状态image
            GiraffePlayer player = videoView.getPlayer();
            int newPosition = (int) (player.getDuration() * (progress * 1.0 / 1000));
            String time = generateTime(newPosition);
            if (instantSeeking) {
                player.seekTo(newPosition);

            }
            $.id(R.id.app_video_currentTime).text(time);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            isDragging = true;
            show(3600000);
            handler.removeMessages(MESSAGE_SHOW_PROGRESS);
            if (instantSeeking) {
                audioManager.setStreamMute(AudioManager.STREAM_MUSIC, true);
            }
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            if (!videoView.isCurrentActivePlayer()) {
                return;
            }
            GiraffePlayer player = videoView.getPlayer();
            if (!instantSeeking) {
                player.seekTo((int) (player.getDuration() * (seekBar.getProgress() * 1.0 / 1000)));
            }
            show(defaultTimeout);
            handler.removeMessages(MESSAGE_SHOW_PROGRESS);
            audioManager.setStreamMute(AudioManager.STREAM_MUSIC, false);
            isDragging = false;
            handler.sendEmptyMessageDelayed(MESSAGE_SHOW_PROGRESS, 1000);
        }
    };

    protected void updatePausePlay() {
        if (videoView.isCurrentActivePlayer()) {
            boolean playing = videoView.getPlayer().isPlaying();
            if (playing) {
                $.id(R.id.app_video_play).image(R.drawable.ic_stop_white_24dp);
            } else {
                $.id(R.id.app_video_play).image(R.drawable.ic_play_arrow_white_24dp);
            }
        } else {
            $.id(R.id.app_video_play).image(R.drawable.ic_play_arrow_white_24dp);
            $.id(R.id.app_video_currentTime).text("");
            $.id(R.id.app_video_endTime).text("");
        }
    }

    protected long setProgress() {
        if (isDragging) {
            return 0;
        }
        //check player is active
        boolean currentPlayer = videoView.isCurrentActivePlayer();
        if (!currentPlayer) {
            seekBar.setProgress(0);
            return 0;
        }

        //check player is ready
        GiraffePlayer player = videoView.getPlayer();
        int currentState = player.getCurrentState();
        if (currentState == GiraffePlayer.STATE_IDLE ||
                currentState == GiraffePlayer.STATE_PREPARING ||
                currentState == GiraffePlayer.STATE_ERROR) {
            return 0;
        }

        long position = player.getCurrentPosition();
        int duration = player.getDuration();

        if (seekBar != null) {
            if (duration > 0) {
                long pos = 1000L * position / duration;
                seekBar.setProgress((int) pos);
            }
            int percent = player.getBufferPercentage();
            seekBar.setSecondaryProgress(percent * 10);
        }

        $.id(R.id.app_video_currentTime).text(generateTime(position));
        if (duration == 0) {//live stream
            $.id(R.id.app_video_endTime).text(R.string.giraffe_player_live);
        } else {
            $.id(R.id.app_video_endTime).text(generateTime(duration));
        }
        return position;
    }

    protected void show(int timeout) {
        if (!isShowing) {
            if (videoView.getVideoInfo().isShowTopBar() || displayModel == GiraffePlayer.DISPLAY_FULL_WINDOW) {
                $.id(R.id.app_video_top_box).visible();
                $.id(R.id.app_video_title).text(videoView.getVideoInfo().getTitle());
            } else {
                $.id(R.id.app_video_top_box).gone();
            }
            showBottomControl(true);
            isShowing = true;
        }
        updatePausePlay();
        handler.sendEmptyMessage(MESSAGE_SHOW_PROGRESS);
        handler.removeMessages(MESSAGE_FADE_OUT);
        if (timeout != 0) {
            handler.sendMessageDelayed(handler.obtainMessage(MESSAGE_FADE_OUT), timeout);
        }

    }

    protected void showBottomControl(boolean show) {
        if (displayModel == GiraffePlayer.DISPLAY_FLOAT) {
            show = false;
        }
//        $.id(R.id.app_video_play).visibility(show ? View.VISIBLE : View.GONE);
//        $.id(R.id.app_video_currentTime).visibility(show ? View.VISIBLE : View.GONE);
//        $.id(R.id.app_video_endTime).visibility(show ? View.VISIBLE : View.GONE);
//        $.id(R.id.app_video_seekBar).visibility(show ? View.VISIBLE : View.GONE);
//        $.id(R.id.app_video_fullscreen).visibility(show ? View.VISIBLE : View.GONE);
        $.id(R.id.app_video_bottom_box).visibility(show ? View.VISIBLE : View.GONE);

    }

    protected void hide(boolean force) {
        if (force || isShowing) {
            handler.removeMessages(MESSAGE_SHOW_PROGRESS);
            showBottomControl(false);
            $.id(R.id.app_video_top_box).gone();
//            $.id(R.id.app_video_fullscreen).invisible();
            isShowing = false;
        }

    }

    public DefaultMediaController(Context context) {
        super(context);
        maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
    }

    @Override
    protected View makeControllerView() {
        return LayoutInflater.from(context).inflate(R.layout.giraffe_media_controller, videoView, false);
    }

    protected final View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            GiraffePlayer player = videoView.getPlayer();
            if (v.getId() == R.id.app_video_fullscreen) {
                player.toggleFullScreen();
            } else if (v.getId() == R.id.app_video_play) {
                if (player.isPlaying()) {
                    player.pause();
                } else {
                    player.start();
                }
            } else if (v.getId() == R.id.app_video_replay_icon) {
                player.seekTo(0);
                player.start();
//                videoView.seekTo(0);
//                videoView.start();
//                doPauseResume();
            } else if (v.getId() == R.id.app_video_finish) {
                if (!player.onBackPressed()) {
                    ((Activity) videoView.getContext()).finish();
                }
            } else if (v.getId() == R.id.app_video_float_close) {
                player.stop();
                player.setDisplayModel(GiraffePlayer.DISPLAY_NORMAL);
            } else if (v.getId() == R.id.app_video_float_full) {
                player.setDisplayModel(GiraffePlayer.DISPLAY_FULL_WINDOW);
            } else if (v.getId() == R.id.app_video_clarity) {
                Activity activity = (Activity) videoView.getContext();
                if (activity instanceof AppCompatActivity) {
                    TrackSelectorFragment trackSelectorFragment = new TrackSelectorFragment();
                    Bundle bundle = new Bundle();
                    bundle.putString("fingerprint", videoView.getVideoInfo().getFingerprint());
                    trackSelectorFragment.setArguments(bundle);
                    FragmentManager supportFragmentManager = ((AppCompatActivity) activity).getSupportFragmentManager();
                    trackSelectorFragment.show(supportFragmentManager, "player_track");
                }

            }
        }
    };

    @Override
    protected void initView(View view) {
        seekBar = $.id(R.id.app_video_seekBar).view();
        seekBar.setMax(1000);
        seekBar.setOnSeekBarChangeListener(seekListener);
        $.id(R.id.app_video_play).clicked(onClickListener).imageView().setRotation(isRtl()?180:0);
        $.id(R.id.app_video_fullscreen).clicked(onClickListener);
        $.id(R.id.app_video_finish).clicked(onClickListener).imageView().setRotation(isRtl()?180:0);
        $.id(R.id.app_video_replay_icon).clicked(onClickListener).imageView().setRotation(isRtl()?180:0);
        $.id(R.id.app_video_clarity).clicked(onClickListener);
        $.id(R.id.app_video_float_close).clicked(onClickListener);
        $.id(R.id.app_video_float_full).clicked(onClickListener);

        final GestureDetector gestureDetector = new GestureDetector(context, createGestureListener());
        view.setFocusable(true);
        view.setFocusableInTouchMode(true);
        view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                if (displayModel == GiraffePlayer.DISPLAY_FLOAT) {
                    return false;
                }

                if (gestureDetector.onTouchEvent(event)) {
                    return true;
                }

                // 处理手势结束
                switch (event.getAction() & MotionEvent.ACTION_MASK) {
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL:
                    case MotionEvent.ACTION_OUTSIDE:
                        endGesture();
                        break;
                }
                return true;
            }
        });
    }

    protected GestureDetector.OnGestureListener createGestureListener() {
        return new PlayerGestureListener();
    }

//    public class LiteGestureListener extends GestureDetector.SimpleOnGestureListener {
//        @Override
//        public boolean onSingleTapUp(MotionEvent e) {
//            boolean currentPlayer = videoView.isCurrentActivePlayer();
//            if (!currentPlayer) {
//                return true;
//            }
//            if (isShowing) {
//                hide(false);
//            } else {
//                show(defaultTimeout);
//            }
//            return true;
//        }
//    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case MESSAGE_FADE_OUT:
                hide(false);
                break;
            case MESSAGE_HIDE_CENTER_BOX:
                $.id(R.id.app_video_volume_box).gone();
                $.id(R.id.app_video_brightness_box).gone();
                $.id(R.id.app_video_fastForward_box).gone();
                break;
            case MESSAGE_SEEK_NEW_POSITION:
                if (newPosition >= 0) {
                    videoView.getPlayer().seekTo((int) newPosition);
                    newPosition = -1;
                }
                break;
            case MESSAGE_SHOW_PROGRESS:
                setProgress();
                if (!isDragging && isShowing) {
                    msg = handler.obtainMessage(MESSAGE_SHOW_PROGRESS);
                    handler.sendMessageDelayed(msg, 300);
                    updatePausePlay();
                }
                break;
            case MESSAGE_RESTART_PLAY:
//                        play(url);
                break;
        }
        return true;
    }

    @Override
    public void onCompletion(GiraffePlayer giraffePlayer) {
        statusChange(STATUS_COMPLETED);
    }

    @Override
    public void onRelease(GiraffePlayer giraffePlayer) {
        handler.removeCallbacksAndMessages(null);

        $.id(R.id.app_video_play).image(R.drawable.ic_play_arrow_white_24dp);
        $.id(R.id.app_video_currentTime).text("");
        $.id(R.id.app_video_endTime).text("");

        //1.set the cover view visible
        $.id(R.id.app_video_cover).visible();
        //2.set current view as cover
        VideoInfo videoInfo = videoView.getVideoInfo();
        if (videoInfo.isCurrentVideoAsCover()) {
            if (giraffePlayer.getCurrentState() != GiraffePlayer.STATE_ERROR) {
                ScalableTextureView currentDisplay = giraffePlayer.getCurrentDisplay();
                if (currentDisplay != null) {
                    ImageView imageView = $.id(R.id.app_video_cover).imageView();
                    if (imageView != null) {
                        int aspectRatio = videoInfo.getAspectRatio();
                        if (aspectRatio == VideoInfo.AR_ASPECT_FILL_PARENT) {
                            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                        } else if (aspectRatio == VideoInfo.AR_MATCH_PARENT) {
                            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                        } else if (aspectRatio == VideoInfo.AR_ASPECT_WRAP_CONTENT) {
                            imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
                        } else {
                            imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
                        }
                        imageView.setImageBitmap(currentDisplay.getBitmap());
                    }
                }
            }
        }

    }

    @Override
    public void onStart(GiraffePlayer giraffePlayer) {
        $.id(R.id.app_video_replay).gone();
        show(defaultTimeout);
        statusChange(STATUS_PLAYING);
    }

    protected void endGesture() {
        volume = -1;
        brightness = -1f;
        if (newPosition >= 0) {
            handler.removeMessages(MESSAGE_SEEK_NEW_POSITION);
            handler.sendEmptyMessage(MESSAGE_SEEK_NEW_POSITION);
        }
        handler.removeMessages(MESSAGE_HIDE_CENTER_BOX);
        handler.sendEmptyMessageDelayed(MESSAGE_HIDE_CENTER_BOX, 500);
    }

    public class PlayerGestureListener extends GestureDetector.SimpleOnGestureListener {
        private boolean firstTouch;
        private boolean volumeControl;
        private boolean toSeek;

        /**
         * 双击
         */
        @Override
        public boolean onDoubleTap(MotionEvent e) {
//            Toast.makeText(context, "onDoubleTap", Toast.LENGTH_SHORT).show();
            return true;
        }

        @Override
        public boolean onDown(MotionEvent e) {
            firstTouch = true;
            return true;

        }

        /**
         * 滑动
         */
        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            //1. if not the active player,ignore
            boolean currentPlayer = videoView.isCurrentActivePlayer();
            if (!currentPlayer) {
                return true;
            }

            float oldX = e1.getX(), oldY = e1.getY();
            float deltaY = oldY - e2.getY();
            float deltaX = oldX - e2.getX();
            if (firstTouch) {
                toSeek = Math.abs(distanceX) >= Math.abs(distanceY);
                volumeControl = oldX > videoView.getWidth() * 0.5f;
                firstTouch = false;
            }
            GiraffePlayer player = videoView.getPlayer();
            if (toSeek) {
                if (player.canSeekForward()) {
                    onProgressSlide(-deltaX / videoView.getWidth());
                }
            } else {
                //if player in list controllerView,ignore
                if (displayModel == GiraffePlayer.DISPLAY_NORMAL && videoView.inListView()) {
                    return true;
                }
                float percent = deltaY / videoView.getHeight();
                if (volumeControl) {
                    onVolumeSlide(percent);
                } else {
                    onBrightnessSlide(percent);
                }
            }
            return true;
        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            if (isShowing) {
                hide(false);
            } else {
                show(defaultTimeout);
            }
            return true;
        }
    }

    /**
     * 滑动改变声音大小
     *
     * @param percent
     */
    private void onVolumeSlide(float percent) {
        if (volume == -1) {
            volume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            if (volume < 0)
                volume = 0;
        }
        hide(true);

        int index = (int) (percent * maxVolume) + volume;
        if (index > maxVolume)
            index = maxVolume;
        else if (index < 0)
            index = 0;

        // 变更声音
        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, index, 0);

        // 变更进度条
        int i = (int) (index * 1.0 / maxVolume * 100);
        String s = i + "%";
        if (i == 0) {
            s = "off";
        }
        // 显示
        $.id(R.id.app_video_volume_icon).image(i == 0 ? R.drawable.ic_volume_off_white_36dp : R.drawable.ic_volume_up_white_36dp);
        $.id(R.id.app_video_brightness_box).gone();
        $.id(R.id.app_video_volume_box).visible();
        $.id(R.id.app_video_volume_box).visible();
        $.id(R.id.app_video_volume).text(s).visible();
    }

    private void onProgressSlide(float percent) {
        GiraffePlayer player = videoView.getPlayer();
        long position = player.getCurrentPosition();
        long duration = player.getDuration();
        long deltaMax = Math.min(100 * 1000, duration - position);
        long delta = (long) (deltaMax * percent);
        if (isRtl()) {
            delta = -1 * delta;
        }

        newPosition = delta + position;
        if (newPosition > duration) {
            newPosition = duration;
        } else if (newPosition <= 0) {
            newPosition = 0;
            delta = -position;
        }
        int showDelta = (int) delta / 1000;
        if (showDelta != 0) {
            $.id(R.id.app_video_fastForward_box).visible();
            String text = showDelta > 0 ? ("+" + showDelta) : "" + showDelta;
            $.id(R.id.app_video_fastForward).text(text + "s");
            $.id(R.id.app_video_fastForward_target).text(generateTime(newPosition) + "/");
            $.id(R.id.app_video_fastForward_all).text(generateTime(duration));
        }
//        handler.sendEmptyMessage(MESSAGE_SEEK_NEW_POSITION);
    }

    /**
     * 滑动改变亮度
     *
     * @param percent
     */
    private void onBrightnessSlide(float percent) {
        Window window = ((Activity) context).getWindow();
        if (brightness < 0) {
            brightness = window.getAttributes().screenBrightness;
            if (brightness <= 0.00f) {
                brightness = 0.50f;
            } else if (brightness < 0.01f) {
                brightness = 0.01f;
            }
        }
        Log.d(this.getClass().getSimpleName(), "brightness:" + brightness + ",percent:" + percent);
        $.id(R.id.app_video_brightness_box).visible();
        WindowManager.LayoutParams lpa = window.getAttributes();
        lpa.screenBrightness = brightness + percent;
        if (lpa.screenBrightness > 1.0f) {
            lpa.screenBrightness = 1.0f;
        } else if (lpa.screenBrightness < 0.01f) {
            lpa.screenBrightness = 0.01f;
        }
        $.id(R.id.app_video_brightness).text(((int) (lpa.screenBrightness * 100)) + "%");
        window.setAttributes(lpa);

    }

    @Override
    public boolean onInfo(GiraffePlayer giraffePlayer, int what, int extra) {
        switch (what) {
            case IMediaPlayer.MEDIA_INFO_BUFFERING_START:
                statusChange(STATUS_LOADING);
                break;
            case IMediaPlayer.MEDIA_INFO_BUFFERING_END:
                statusChange(STATUS_PLAYING);
                break;
            case IMediaPlayer.MEDIA_INFO_NETWORK_BANDWIDTH:
                //显示 下载速度
//                        Toaster.show("download rate:" + extra);
                break;
            case IMediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START:
                statusChange(STATUS_PLAYING);
                break;

            default:
        }

        return true;
    }

    @Override
    public void onCurrentStateChange(int oldState, int newState) {
        if (context instanceof Activity) {
            if (newState == GiraffePlayer.STATE_LAZYLOADING) {
                $.id(R.id.app_video_loading).gone();
                $.id(R.id.app_video_status).visible()
                        .id(R.id.app_video_status_text)
                        .text(context.getString(R.string.giraffe_player_lazy_loading, 0));
            }
            if (newState == GiraffePlayer.STATE_PLAYING) {
                //set SCREEN_ON
                ((Activity) context).getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
            } else {
                ((Activity) context).getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
            }
        }
    }

    protected void statusChange(int status) {
        this.status = status;

        switch (status) {
            case STATUS_LOADING:
                $.id(R.id.app_video_loading).visible();
                $.id(R.id.app_video_status).gone();
                break;
            case STATUS_PLAYING:
                $.id(R.id.app_video_loading).gone();
                $.id(R.id.app_video_status).gone();
                break;
            case STATUS_COMPLETED:
                handler.removeMessages(MESSAGE_SHOW_PROGRESS);
                showBottomControl(false);
                $.id(R.id.app_video_replay).visible();
                $.id(R.id.app_video_loading).gone();
                $.id(R.id.app_video_status).gone();
                break;
            case STATUS_ERROR:
                $.id(R.id.app_video_status).visible().id(R.id.app_video_status_text).text(R.string.small_problem);
                handler.removeMessages(MESSAGE_SHOW_PROGRESS);
                $.id(R.id.app_video_loading).gone();
                break;
            default:
        }
    }

    @Override
    public boolean onError(GiraffePlayer giraffePlayer, int what, int extra) {
        statusChange(STATUS_ERROR);
        return true;
    }

    @Override
    public void onPrepared(GiraffePlayer giraffePlayer) {
        boolean live = giraffePlayer.getDuration() == 0;
        $.id(R.id.app_video_seekBar).enabled(!live);
        if (giraffePlayer.getTrackInfo().length > 0) {
            $.id(R.id.app_video_clarity).visible();
        } else {
            $.id(R.id.app_video_clarity).gone();
        }
    }

    @Override
    public void onPreparing(GiraffePlayer giraffePlayer) {
        statusChange(STATUS_LOADING);
    }

    @Override
    public void onDisplayModelChange(int oldModel, int newModel) {
        this.displayModel = newModel;
        if (displayModel == GiraffePlayer.DISPLAY_FLOAT) {
            $.id(R.id.app_video_float_close).visible();
            $.id(R.id.app_video_float_full).visible();
            $.id(R.id.app_video_bottom_box).gone();

        } else {
            $.id(R.id.app_video_float_close).gone();
            $.id(R.id.app_video_float_full).gone();
            $.id(R.id.app_video_bottom_box).visible();

        }
//        ((ViewGroup) controllerView.getParent()).removeView(controllerView);
//        if (newModel == GiraffePlayer.DISPLAY_FULL_WINDOW) {
//            ViewGroup top = (ViewGroup) ((Activity) videoView.getContext()).findViewById(android.R.id.content);
//            top.addView(controllerView);
//        } else if (newModel == GiraffePlayer.DISPLAY_NORMAL) {
//            videoView.addView(controllerView);
//        }
    }

    @Override
    public void onTargetStateChange(int oldState, int newState) {
        if (newState != GiraffePlayer.STATE_IDLE) {
            $.id(R.id.app_video_cover).gone();
        }
    }

    @Override
    public void onTimedText(GiraffePlayer giraffePlayer, IjkTimedText text) {
        if (text == null) {
            $.id(R.id.app_video_subtitle).gone();
        } else {
            $.id(R.id.app_video_subtitle).visible().text(text.getText());
        }
    }

    @Override
    public void onLazyLoadProgress(GiraffePlayer giraffePlayer, int progress) {
        $.id(R.id.app_video_loading).gone();
        $.id(R.id.app_video_status).visible();
        $.id(R.id.app_video_status_text)
                .text(context.getString(R.string.giraffe_player_lazy_loading, progress));
    }

    @Override
    public void onLazyLoadError(GiraffePlayer giraffePlayer, String message) {
        $.id(R.id.app_video_loading).gone();
        $.id(R.id.app_video_status).visible();
        $.id(R.id.app_video_status_text)
                .text(context.getString(R.string.giraffe_player_lazy_loading_error, message));
    }

    @Override
    public void onPause(GiraffePlayer giraffePlayer) {
        statusChange(STATUS_PAUSE);
    }

    private boolean isRtl() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            return TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()) == View.LAYOUT_DIRECTION_RTL;
        }
        return false;
    }
}


text:
require 'digest'

##
# Allows writing of tar files

class Gem::Package::TarWriter

  class FileOverflow < StandardError; end

  ##
  # IO wrapper that allows writing a limited amount of data

  class BoundedStream

    ##
    # Maximum number of bytes that can be written

    attr_reader :limit

    ##
    # Number of bytes written

    attr_reader :written

    ##
    # Wraps +io+ and allows up to +limit+ bytes to be written

    def initialize(io, limit)
      @io = io
      @limit = limit
      @written = 0
    end

    ##
    # Writes +data+ onto the IO, raising a FileOverflow exception if the
    # number of bytes will be more than #limit

    def write(data)
      if data.bytesize + @written > @limit
        raise FileOverflow, "You tried to feed more data than fits in the file."
      end
      @io.write data
      @written += data.bytesize
      data.bytesize
    end

  end

  ##
  # IO wrapper that provides only #write

  class RestrictedStream

    ##
    # Creates a new RestrictedStream wrapping +io+

    def initialize(io)
      @io = io
    end

    ##
    # Writes +data+ onto the IO

    def write(data)
      @io.write data
    end

  end

  ##
  # Creates a new TarWriter, yielding it if a block is given

  def self.new(io)
    writer = super

    return writer unless block_given?

    begin
      yield writer
    ensure
      writer.close
    end

    nil
  end

  ##
  # Creates a new TarWriter that will write to +io+

  def initialize(io)
    @io = io
    @closed = false
  end

  ##
  # Adds file +name+ with permissions +mode+, and yields an IO for writing the
  # file to

  def add_file(name, mode) # :yields: io
    check_closed

    name, prefix = split_name name

    init_pos = @io.pos
    @io.write Gem::Package::TarHeader::EMPTY_HEADER # placeholder for the header

    yield RestrictedStream.new(@io) if block_given?

    size = @io.pos - init_pos - 512

    remainder = (512 - (size % 512)) % 512
    @io.write "\0" * remainder

    final_pos = @io.pos
    @io.pos = init_pos

    header = Gem::Package::TarHeader.new :name => name, :mode => mode,
                                         :size => size, :prefix => prefix,
                                         :mtime => Gem.source_date_epoch

    @io.write header
    @io.pos = final_pos

    self
  end

  ##
  # Adds +name+ with permissions +mode+ to the tar, yielding +io+ for writing
  # the file.  The +digest_algorithm+ is written to a read-only +name+.sum
  # file following the given file contents containing the digest name and
  # hexdigest separated by a tab.
  #
  # The created digest object is returned.

  def add_file_digest(name, mode, digest_algorithms) # :yields: io
    digests = digest_algorithms.map do |digest_algorithm|
      digest = digest_algorithm.new
      digest_name =
        if digest.respond_to? :name
          digest.name
        else
          /::([^:]+)$/ =~ digest_algorithm.name
          $1
        end

      [digest_name, digest]
    end

    digests = Hash[*digests.flatten]

    add_file name, mode do |io|
      Gem::Package::DigestIO.wrap io, digests do |digest_io|
        yield digest_io
      end
    end

    digests
  end

  ##
  # Adds +name+ with permissions +mode+ to the tar, yielding +io+ for writing
  # the file.  The +signer+ is used to add a digest file using its
  # digest_algorithm per add_file_digest and a cryptographic signature in
  # +name+.sig.  If the signer has no key only the checksum file is added.
  #
  # Returns the digest.

  def add_file_signed(name, mode, signer)
    digest_algorithms = [
      signer.digest_algorithm,
      Digest::SHA512,
    ].compact.uniq

    digests = add_file_digest name, mode, digest_algorithms do |io|
      yield io
    end

    signature_digest = digests.values.compact.find do |digest|
      digest_name =
        if digest.respond_to? :name
          digest.name
        else
          digest.class.name[/::([^:]+)\z/, 1]
        end

      digest_name == signer.digest_name
    end

    raise "no #{signer.digest_name} in #{digests.values.compact}" unless signature_digest

    if signer.key
      signature = signer.sign signature_digest.digest

      add_file_simple "#{name}.sig", 0444, signature.length do |io|
        io.write signature
      end
    end

    digests
  end

  ##
  # Add file +name+ with permissions +mode+ +size+ bytes long.  Yields an IO
  # to write the file to.

  def add_file_simple(name, mode, size) # :yields: io
    check_closed

    name, prefix = split_name name

    header = Gem::Package::TarHeader.new(:name => name, :mode => mode,
                                         :size => size, :prefix => prefix,
                                         :mtime => Gem.source_date_epoch).to_s

    @io.write header
    os = BoundedStream.new @io, size

    yield os if block_given?

    min_padding = size - os.written
    @io.write("\0" * min_padding)

    remainder = (512 - (size % 512)) % 512
    @io.write("\0" * remainder)

    self
  end

  ##
  # Adds symlink +name+ with permissions +mode+, linking to +target+.

  def add_symlink(name, target, mode)
    check_closed

    name, prefix = split_name name

    header = Gem::Package::TarHeader.new(:name => name, :mode => mode,
                                         :size => 0, :typeflag => "2",
                                         :linkname => target,
                                         :prefix => prefix,
                                         :mtime => Gem.source_date_epoch).to_s

    @io.write header

    self
  end

  ##
  # Raises IOError if the TarWriter is closed

  def check_closed
    raise IOError, "closed #{self.class}" if closed?
  end

  ##
  # Closes the TarWriter

  def close
    check_closed

    @io.write "\0" * 1024
    flush

    @closed = true
  end

  ##
  # Is the TarWriter closed?

  def closed?
    @closed
  end

  ##
  # Flushes the TarWriter's IO

  def flush
    check_closed

    @io.flush if @io.respond_to? :flush
  end

  ##
  # Creates a new directory in the tar file +name+ with +mode+

  def mkdir(name, mode)
    check_closed

    name, prefix = split_name(name)

    header = Gem::Package::TarHeader.new :name => name, :mode => mode,
                                         :typeflag => "5", :size => 0,
                                         :prefix => prefix,
                                         :mtime => Gem.source_date_epoch

    @io.write header

    self
  end

  ##
  # Splits +name+ into a name and prefix that can fit in the TarHeader

  def split_name(name) # :nodoc:
    if name.bytesize > 256
      raise Gem::Package::TooLongFileName.new("File \"#{name}\" has a too long path (should be 256 or less)")
    end

    prefix = ''
    if name.bytesize > 100
      parts = name.split('/', -1) # parts are never empty here
      name = parts.pop            # initially empty for names with a trailing slash ("foo/.../bar/")
      prefix = parts.join('/')    # if empty, then it's impossible to split (parts is empty too)
      while !parts.empty? && (prefix.bytesize > 155 || name.empty?)
        name = parts.pop + '/' + name
        prefix = parts.join('/')
      end

      if name.bytesize > 100 or prefix.empty?
        raise Gem::Package::TooLongFileName.new("File \"#{prefix}/#{name}\" has a too long name (should be 100 or less)")
      end

      if prefix.bytesize > 155
        raise Gem::Package::TooLongFileName.new("File \"#{prefix}/#{name}\" has a too long base path (should be 155 or less)")
      end
    end

    return name, prefix
  end

end

redpajama_set_name: RedPajamaGithub


text:
// ILPDFNull.h
//
// Copyright (c) 2018 Derek Blair
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#import <Foundation/Foundation.h>
#import "ILPDFObject.h"

#define ILPDFNull NSNull

NS_ASSUME_NONNULL_BEGIN

/** ILPDFNull is an alias for NSNull. It represents the Null PDF object. Functionality is added via a category.
 */
@interface ILPDFNull(ILPDFObject) <ILPDFObject>
@end

NS_ASSUME_NONNULL_END


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

        name:<input type="text" x-model="name">
        age:<input type="text" x-model="age">

        <button  x-click="add">start</button>
        <button  x-click="closeInter">close</button>
        <button  x-click="hell">hell</button>


text:
package com.amazonaws.services.simplesystemsmanagement;

import com.amazonaws.*;
import com.amazonaws.regions.*;

import com.amazonaws.services.simplesystemsmanagement.model.*;

/**
 * Interface for accessing Amazon SSM.
 *

 *

 * Amazon EC2 Simple Systems Manager (SSM) enables you to configure and manage
 * your EC2 instances. You can create a configuration document and then
 * associate it with one or more running instances.
 *

 *

 * You can use a configuration document to automate the following tasks for your
 * Windows instances:
 *

 *

 *

 *

 * Join an AWS Directory
 *

 *

 *

 *

 * Install, repair, or uninstall software using an MSI package
 *

 *

 *

 *

 * Run PowerShell scripts
 *

 *

 *

 *

 * Configure CloudWatch Logs to monitor applications and systems
 *

 *

 *

 *

 * Note that configuration documents are not supported on Linux instances.
 *

 */
public interface AWSSimpleSystemsManagement {

    /**
     * Overrides the default endpoint for this client
     * ("https://ssm.us-east-1.amazonaws.com"). Callers can use this method to
     * control which AWS region they want to work with.
     *

     * Callers can pass in just the endpoint (ex: "ssm.us-east-1.amazonaws.com")
     * or a full URL, including the protocol (ex:
     * "https://ssm.us-east-1.amazonaws.com"). If the protocol is not specified
     * here, the default protocol from this client's {@link ClientConfiguration}
     * will be used, which by default is HTTPS.
     *

     * For more information on using AWS regions with the AWS SDK for Java, and
     * a complete list of all available endpoints for all AWS services, see:  http://developer.amazonwebservices.com/connect/entry.jspa?externalID=
     * 3912
     *

     * This method is not threadsafe. An endpoint should be configured when
     * the client is created and before any service requests are made. Changing
     * it afterwards creates inevitable race conditions for any service requests
     * in transit or retrying.
     *
     * @param endpoint
     *        The endpoint (ex: "ssm.us-east-1.amazonaws.com") or a full URL,
     *        including the protocol (ex: "https://ssm.us-east-1.amazonaws.com")
     *        of the region specific AWS endpoint this client will communicate
     *        with.
     */
    void setEndpoint(String endpoint);

    /**
     * An alternative to {@link AWSSimpleSystemsManagement#setEndpoint(String)},
     * sets the regional endpoint for this client's service calls. Callers can
     * use this method to control which AWS region they want to work with.
     *

     * By default, all service endpoints in all regions use the https protocol.
     * To use http instead, specify it in the {@link ClientConfiguration}
     * supplied at construction.
     *

     * This method is not threadsafe. A region should be configured when the
     * client is created and before any service requests are made. Changing it
     * afterwards creates inevitable race conditions for any service requests in
     * transit or retrying.
     *
     * @param region
     *        The region this client will communicate with. See
     *        {@link Region#getRegion(com.amazonaws.regions.Regions)} for
     *        accessing a given region. Must not be null and must be a region
     *        where the service is available.
     *
     * @see Region#getRegion(com.amazonaws.regions.Regions)
     * @see Region#createClient(Class,
     *      com.amazonaws.auth.AWSCredentialsProvider, ClientConfiguration)
     * @see Region#isServiceSupported(String)
     */
    void setRegion(Region region);

    /**
     *

     * Associates the specified configuration document with the specified
     * instance.
     *

     *

     * When you associate a configuration document with an instance, the
     * configuration agent on the instance processes the configuration document
     * and configures the instance as specified.
     *

     *

     * If you associate a configuration document with an instance that already
     * has an associated configuration document, we replace the current
     * configuration document with the new configuration document.
     *

     *
     * @param createAssociationRequest
     * @return Result of the CreateAssociation operation returned by the
     *         service.
     * @throws AssociationAlreadyExistsException
     *         The specified association already exists.
     * @throws AssociationLimitExceededException
     *         You can have at most 2,000 active associations.
     * @throws InternalServerErrorException
     *         An error occurred on the server side.
     * @throws InvalidDocumentException
     *         The configuration document is not valid.
     * @throws InvalidInstanceIdException
     *         You must specify the ID of a running instance.
     */
    CreateAssociationResult createAssociation(
            CreateAssociationRequest createAssociationRequest);

    /**
     *

     * Associates the specified configuration documents with the specified
     * instances.
     *

     *

     * When you associate a configuration document with an instance, the
     * configuration agent on the instance processes the configuration document
     * and configures the instance as specified.
     *

     *

     * If you associate a configuration document with an instance that already
     * has an associated configuration document, we replace the current
     * configuration document with the new configuration document.
     *

     *
     * @param createAssociationBatchRequest
     * @return Result of the CreateAssociationBatch operation returned by the
     *         service.
     * @throws InternalServerErrorException
     *         An error occurred on the server side.
     * @throws InvalidDocumentException
     *         The configuration document is not valid.
     * @throws InvalidInstanceIdException
     *         You must specify the ID of a running instance.
     * @throws DuplicateInstanceIdException
     *         You cannot specify an instance ID in more than one association.
     * @throws AssociationLimitExceededException
     *         You can have at most 2,000 active associations.
     */
    CreateAssociationBatchResult createAssociationBatch(
            CreateAssociationBatchRequest createAssociationBatchRequest);

    /**
     *

     * Creates a configuration document.
     *

     *

     * After you create a configuration document, you can use
     * CreateAssociation to associate it with one or more running
     * instances.
     *

     *
     * @param createDocumentRequest
     * @return Result of the CreateDocument operation returned by the service.
     * @throws DocumentAlreadyExistsException
     *         The specified configuration document already exists.
     * @throws MaxDocumentSizeExceededException
     *         The size limit of a configuration document is 64 KB.
     * @throws InternalServerErrorException
     *         An error occurred on the server side.
     * @throws InvalidDocumentContentException
     *         The content for the configuration document is not valid.
     * @throws DocumentLimitExceededException
     *         You can have at most 100 active configuration documents.
     */
    CreateDocumentResult createDocument(
            CreateDocumentRequest createDocumentRequest);

    /**
     *

     * Disassociates the specified configuration document from the specified
     * instance.
     *

     *

     * When you disassociate a configuration document from an instance, it does
     * not change the configuration of the instance. To change the configuration
     * state of an instance after you disassociate a configuration document, you
     * must create a new configuration document with the desired configuration
     * and associate it with the instance.
     *

     *
     * @param deleteAssociationRequest
     * @return Result of the DeleteAssociation operation returned by the
     *         service.
     * @throws AssociationDoesNotExistException
     *         The specified association does not exist.
     * @throws InternalServerErrorException
     *         An error occurred on the server side.
     * @throws InvalidDocumentException
     *         The configuration document is not valid.
     * @throws InvalidInstanceIdException
     *         You must specify the ID of a running instance.
     * @throws TooManyUpdatesException
     *         There are concurrent updates for a resource that supports one
     *         update at a time.
     */
    DeleteAssociationResult deleteAssociation(
            DeleteAssociationRequest deleteAssociationRequest);

    /**
     *

     * Deletes the specified configuration document.
     *

     *

     * You must use DeleteAssociation to disassociate all instances that
     * are associated with the configuration document before you can delete it.
     *

     *
     * @param deleteDocumentRequest
     * @return Result of the DeleteDocument operation returned by the service.
     * @throws InternalServerErrorException
     *         An error occurred on the server side.
     * @throws InvalidDocumentException
     *         The configuration document is not valid.
     * @throws AssociatedInstancesException
     *         You must disassociate a configuration document from all instances
     *         before you can delete it.
     */
    DeleteDocumentResult deleteDocument(
            DeleteDocumentRequest deleteDocumentRequest);

    /**
     *

     * Describes the associations for the specified configuration document or
     * instance.
     *

     *
     * @param describeAssociationRequest
     * @return Result of the DescribeAssociation operation returned by the
     *         service.
     * @throws AssociationDoesNotExistException
     *         The specified association does not exist.
     * @throws InternalServerErrorException
     *         An error occurred on the server side.
     * @throws InvalidDocumentException
     *         The configuration document is not valid.
     * @throws InvalidInstanceIdException
     *         You must specify the ID of a running instance.
     */
    DescribeAssociationResult describeAssociation(
            DescribeAssociationRequest describeAssociationRequest);

    /**
     *

     * Describes the specified configuration document.
     *

     *
     * @param describeDocumentRequest
     * @return Result of the DescribeDocument operation returned by the service.
     * @throws InternalServerErrorException
     *         An error occurred on the server side.
     * @throws InvalidDocumentException
     *         The configuration document is not valid.
     */
    DescribeDocumentResult describeDocument(
            DescribeDocumentRequest describeDocumentRequest);

    /**
     *

     * Gets the contents of the specified configuration document.
     *

     *
     * @param getDocumentRequest
     * @return Result of the GetDocument operation returned by the service.
     * @throws InternalServerErrorException
     *         An error occurred on the server side.
     * @throws InvalidDocumentException
     *         The configuration document is not valid.
     */
    GetDocumentResult getDocument(GetDocumentRequest getDocumentRequest);

    /**
     *

     * Lists the associations for the specified configuration document or
     * instance.
     *

     *
     * @param listAssociationsRequest
     * @return Result of the ListAssociations operation returned by the service.
     * @throws InternalServerErrorException
     *         An error occurred on the server side.
     * @throws InvalidNextTokenException
     *         The specified token is not valid.
     */
    ListAssociationsResult listAssociations(
            ListAssociationsRequest listAssociationsRequest);

    /**
     *

     * Describes one or more of your configuration documents.
     *

     *
     * @param listDocumentsRequest
     * @return Result of the ListDocuments operation returned by the service.
     * @throws InternalServerErrorException
     *         An error occurred on the server side.
     * @throws InvalidNextTokenException
     *         The specified token is not valid.
     */
    ListDocumentsResult listDocuments(ListDocumentsRequest listDocumentsRequest);

    /**
     * Simplified method form for invoking the ListDocuments operation.
     *
     * @see #listDocuments(ListDocumentsRequest)
     */
    ListDocumentsResult listDocuments();

    /**
     *

     * Updates the status of the configuration document associated with the
     * specified instance.
     *

     *
     * @param updateAssociationStatusRequest
     * @return Result of the UpdateAssociationStatus operation returned by the
     *         service.
     * @throws InternalServerErrorException
     *         An error occurred on the server side.
     * @throws InvalidInstanceIdException
     *         You must specify the ID of a running instance.
     * @throws InvalidDocumentException
     *         The configuration document is not valid.
     * @throws AssociationDoesNotExistException
     *         The specified association does not exist.
     * @throws StatusUnchangedException
     *         The updated status is the same as the current status.
     * @throws TooManyUpdatesException
     *         There are concurrent updates for a resource that supports one
     *         update at a time.
     */
    UpdateAssociationStatusResult updateAssociationStatus(
            UpdateAssociationStatusRequest updateAssociationStatusRequest);

    /**
     * Shuts down this client object, releasing any resources that might be held
     * open. This is an optional method, and callers are not expected to call
     * it, but can if they want to explicitly release any open resources. Once a
     * client has been shutdown, it should not be used to make any more
     * requests.
     */
    void shutdown();

    /**
     * Returns additional metadata for a previously executed successful request,
     * typically used for debugging issues where a service isn't acting as
     * expected. This data isn't considered part of the result data returned by
     * an operation, so it's available through this separate, diagnostic
     * interface.
     *

     * Response metadata is only cached for a limited period of time, so if you
     * need to access this extra diagnostic information for an executed request,
     * you should use this method to retrieve it as soon as possible after
     * executing a request.
     *
     * @param request
     *        The originally executed request.
     *
     * @return The response metadata for the specified request, or null if none
     *         is available.
     */
    ResponseMetadata getCachedResponseMetadata(AmazonWebServiceRequest request);
}


text:
import botocore
from flask import current_app

from .exceptions import FileNotFoundError, ValidationError

class AmazonS3FileValidator(object):
    """A Flask utility for validating files stored in AmazonS3.

    If the application has an `AWS_UNVALIDATED_PREFIX` config, its value
    will be removed from the file key if the file is valid. This enables
    deleting unvalidated files via `Amazon S3 Lifecycle Management`_.

    .. _Amazon S3 Lifecycle Management:
        http://docs.aws.amazon.com/AmazonS3/latest/dev/object-lifecycle-mgmt.html

    Example::

        import boto
        from pontus import AmazonS3FileValidator
        from pontus.exceptions import FileNotFoundError
        from pontus.validators import MimeType

        connection = boto.s3.connection.S3Connection()
        bucket = connection.get_bucket('testbucket')

        try:
            validator = AmazonS3FileValidator(
                key_name='my/file.jpg',
                bucket=bucket,
                validators=[MimeType('image/jpeg')]
            )
        except FileNotFoundError:
            # File was not found
            pass

        if validator.validate():
            # File MIME type was image/jpeg
            pass
        else:
            # File was invalid, printing errors
            print validator.errors

    :param key_name:
        The key of the file stored in Amazon S3.

    :param bucket:
        The Boto S3 Bucket instance.

    :param validators:
        List of validators. A validator can either be an instance of a class
        inheriting :class:`BaseValidator` or a callable
        function that takes Boto S3 Object instance as a parameter.

    :param delete_unvalidated_file:
        Whether to delete the unvalidated file when the new file is copied to new location

    :param new_file_prefix:
        Prefix to be set to the new file that is copied during validation.

    :param new_file_acl:
        Canned ACL set to the new file that is copied during validation.
        Defaults to 'public-read'.

    """
    def __init__(
        self,
        key_name,
        bucket,
        validators=[],
        delete_unvalidated_file=True,
        new_file_prefix='',
        new_file_acl='public-read',
    ):
        self.errors = []
        self.obj = bucket.Object(key_name)
        try:
            self.obj.load()
        except botocore.exceptions.ClientError as e:
            if e.response['Error']['Code'] == '404':
                raise FileNotFoundError(key=key_name)
            else:
                raise e
        self.bucket = bucket
        self.validators = validators
        self.delete_unvalidated_file = delete_unvalidated_file
        self.new_file_prefix = new_file_prefix
        self.new_file_acl = new_file_acl

    def validate(self):
        """
        Validates the given Amazon S3 file with :attr:`validators`. If errors
        occur they are appended to :attr:`errors`. If the file is valid and a
        `AWS_UNVALIDATED_PREFIX` config is present, its value will be removed
        from the file key.

        :return: a boolean indicating if the file vas valid.
        """
        for validator in self.validators:
            try:
                validator(self.obj)
            except ValidationError as e:
                self.errors.append(e.error)

        if not self.errors and self._has_unvalidated_prefix():
            self._move_to_validated()

        return not self.errors

    def _has_unvalidated_prefix(self):
        return (
            current_app.config.get('AWS_UNVALIDATED_PREFIX') and
            self.obj.key.startswith(
                current_app.config.get('AWS_UNVALIDATED_PREFIX')
            )
        )

    def _move_to_validated(self):
        new_name = self.new_file_prefix + self.obj.key[
            len(current_app.config.get('AWS_UNVALIDATED_PREFIX')):
        ]
        new_obj = self.bucket.Object(new_name)
        new_obj.copy({
            'Bucket': self.bucket.name,
            'Key': self.obj.key
        })
        new_obj.Acl().put(ACL=self.new_file_acl)
        if self.delete_unvalidated_file:
            self.obj.delete()
        self.obj = new_obj

    def __repr__(self):
        return '<{cls} key={key!r}>'.format(
            cls=self.__class__.__name__,
            key=self.obj.key
        )


text:
package de.gishmo.gwt.example.module0805.client.widgets;

import com.google.gwt.user.client.ui.IsWidget;

/**
 * Implemented by specialized widget drivers that can answer
 * {@link com.google.gwt.activity.shared.Activity#mayStop() mayStop()} calls for
 * {@link com.google.gwt.activity.shared.Activity Activities}.
 * <p>
 * Note that this interface extends {@link IsWidget}. This is to make it easier
 * to evolve app code in MVP directions piecemeal, just where it is useful. If
 * code that assembles widgets thinks of them strictly as IsWidget instances, it
 * doesn't need to notice as they get refactored in to Presenter / View pairs.
 * Or as they don't.
 */
public interface PresentsWidgets extends IsWidget {
  /**
   * Called (probably from
   * {@link com.google.gwt.activity.shared.Activity#mayStop Activity.mayStop})
   * to see if it's safe to stop this presenter.
   *
   * @return null if it's okay to stop, else a message to ask the user if she's
   *         sure
   */
  String mayStop();

  void start();

  void stop();
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Kew Bull. , Addit. Ser. 9: 521 (1983)

#### Original name
Flammula vinicolor Pat.

### Remarks
null


text:
const Controller = require('egg').Controller;

/**
 * @controller HomeController
 */
class HomeController extends Controller {
  /**
   * @router get /index  路径
   * @summary 接口的小标题信息
   * @description 接口的描述信息
   * @request query integer id 对参数id的描述
   * @request query string name 对参数name的描述
   * @response 200 indexJsonBody
   */
  async index () {
    this.ctx.body = {
      code: 0,
      message: '',
      data: {
        result: this.ctx.query.name || 'none'
      }
    }
  }
}

module.exports = HomeController;


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">

	<link rel='shortcut icon' type='image/x-icon' href='./favicon.ico' />
	<link rel="stylesheet" href="/bower_components/normalize-css/normalize.css">
	<link rel="stylesheet" href="/css/quick-nav.css">

	<title>Overlay Nav</title>

				Quick Nav

About

Contact

Blog

Galleries

				Menu

				About

Contact

Blog


text:
<?php

namespace BackendBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\AbstractFixture;
use Symfony\Component\Yaml\Yaml;

/**
 * Class YamlFixture
 *
 * @package \BackendBundle\DataFixtures\ORM
 */
abstract class YamlFixture extends AbstractFixture
{
    protected function loadData($file)
    {
        /**
         * Loads the data from a YAML file
         *
         * @return mixed|array  The YAML structured mapped into an array
         */
        $path = realpath(dirname(__FILE__) . '/../fixtures/');

        return Yaml::parse(file_get_contents($path . '/' . $file . '.yml'));
    }

}


text:
<?php

/*
 *	Tests
 * for Entity Comentario Functions
 *
 */

$Page->Prefix = '../';

include_once($Page->Prefix . 'simpletest/autorun.php');
include_once($Page->Prefix . 'includes/ComentarioFunctions.inc.php');

class ComentarioFunctionsTests extends UnitTestCase {
    function setup() {
        DbConnect();
        DbTransactionBegin();
    }

    function tearDown() {
        DbTransactionRollback();
        DbDisconnect();
    }

    function testInsert() {
        $result = ComentarioInsert('Texto', 0, 0);
        $this->assertNotNull($result);
        $this->assertTrue($result > 0);
    }

    function testUpdate() {
        $id = ComentarioInsert('Texto', 0, 0);
        ComentarioUpdate($id, 'New Texto', 0, 0);
        $result = ComentarioGetById($id);
        $this->assertNotNull($result);
    }

    function testDelete() {
        $id = ComentarioInsert('Texto', 0, 0);
        $result = ComentarioGetById($id);
        $this->assertTrue($result);
        ComentarioDelete($id);
        $result = ComentarioGetById($id);
        $this->assertFalse($result);
    }

    function testGetById() {
        $id = ComentarioInsert('Texto', 0, 0);
        $result = ComentarioGetById($id);
        $this->assertNotNull($result);
    }

    function testGetByNonexistentId() {
        $id = ComentarioInsert('Texto', 0, 0);
        $result = ComentarioGetById(-1);
        $this->assertFalse($result);
    }
}

?>


text:
echo "ocaml-$1"
opam --version
gcc -dumpfullversion -dumpversion
cat flowtype.opam
cat flow_parser.opam
cat .circleci/config.yml


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <link href="../images/vl_blue.ico" type="image/x-icon" rel="icon"></link>
  <link href="../images/vl_blue.ico" type="image/x-icon" rel="shortcut icon"></link>

  <title>VLFeat - Documentation - Matlab API - PLOTOP - vl_det</title>

  <link href="../vlfeat.css" type="text/css" rel="stylesheet"></link>
  <link href="../pygmentize.css" type="text/css" rel="stylesheet"></link>

VLFeat.org

      Documentation - Matlab API - PLOTOP - vl_det

Home

Download

Tutorials

Applications

Documentation

Matlab API

C API

Man pages

Index

Prev

Next

[MISSRATE, FALSEALRAM] = VL_DET(LABELS, SCORES) computes the
Detection Error Trade-off (DET) curve for the given set LABELS and
SCORES. The function is a simple wrapper to VL_ROC(LABELS,
SCORES). In fact, MISSRATE is simply the false positive rate and
FALSEARALM the false negative rate returned by VL_ROC().

VL_DET(...) without output arguments plots the curves in the
current axis. Note that the DET curves use logarithmic axis.

VL_DET(..., OPT, ARG, ...) accepts the same options as VL_ROC().

REFERENCES:
[1] A. Martin, G. Doddington, T. Kamm, M. Ordowski, and
M. Przybocki. The DET curve in assessment of detection task
performance. In Proc. Conf. on Speech Communication and Technology,
1997.

      © 2007-13 The authors of VLFeat


text:
define(["knockout"],
		function(ko){
	/*
		Generates the SQLAlchemy representation on the model.
	*/

	function SQLAlchemy(params){
		this.models = params.models;
		this.body = ko.computed(this.to_text,this,{deferEvalutation:true});
	}

	SQLAlchemy.prototype.to_text = function(models){
		var includes = [
		    "from blueshed.model_helpers.base import Base",
			"from sqlalchemy.types import String, Integer, Numeric, DateTime, Date, Time, Enum, Boolean, Text",
			"from sqlalchemy.schema import Table, Column, ForeignKey",
			"from sqlalchemy.orm import relationship, backref",
			"from sqlalchemy.ext.declarative.api import declared_attr, has_inherited_table, declarative_base",
			"import re",
			"",
			"",
			""
		];
		var indent = "    ";
		var result = [];
		var my_models = {};
		var many_2_many = [];
		var models = ko.toJS(this.models);
		models.map(function(m){
			my_models[m.name]=m;
			return m;
		},this).map(function(model){
			var statics = [];
			var attributes = [];
			result.push("class " + model.name + "(Base):");
			result.push(indent);
			attributes.push(indent + "id = Column(Integer, primary_key=True)");
			model.attrs.map(function(attr){
				this.attr_python(attr, attributes, model, statics, my_models, many_2_many, indent);
			},this);
			models.map(function(other_model){
				other_model.attrs.map(function(attr){
					if(attr.type == model.name && attr.backref){
						this.rel_attr_python(attr, attributes, other_model, statics, my_models, many_2_many, indent);
					}
				},this);
			},this);
			result = result.concat(statics).concat(attributes);
			result.push("");
			result.push("");
		},this);
		result = includes.concat(many_2_many).concat(result);
		result = result.join("\n");
		return result;
	};

	SQLAlchemy.prototype.rel_attr_python = function(attr, out, model, statics, models, many_to_many, indent){
		var scalar = models[attr.type];
		if(attr.m2m === true){
				var fkey_from = model.name.toUnderscore() + ".id";
				var fkey_to = attr.type.toUnderscore() + ".id";
				var field_from = attr.name + "_id";
				var field_to = attr.type.toUnderscore() + "_id";
				var backref = attr.backref ? ", back_populates='" + attr.name + "'" : '';
				var secondary_table = model.name.toLowerCase() + "_" + attr.name + "_" + attr.type.toLowerCase();
				var primaryjoin = model.name + ".id==" + secondary_table + ".c." + field_from;
				var secondaryjoin = attr.type + ".id==" + secondary_table + ".c." + field_to;

				out.push(indent + attr.backref + " = relationship('" + model.name + "',");
				out.push(indent + indent + "secondaryjoin='" + primaryjoin + "',");
				out.push(indent + indent + "primaryjoin='" + secondaryjoin + "',");
				out.push(indent + indent + "secondary='" + secondary_table + "',");
				out.push(indent + indent + "lazy='joined'" + backref + ")");
		} else {
			var fkey = attr.type.toUnderscore() + ".id";
			var backref =  attr.backref ? ",\n" + indent + indent + "back_populates='" + attr.name + "'" : '';
			var primaryjoin = model.name + "." + attr.name +"_id==" + attr.type + ".id";
			out.push(indent + attr.backref + " = relationship('" + model.name + "', uselist=True, ");
			if(attr.cascade==true){
				out.push(indent + indent + "cascade='all,delete-orphan, passive_deletes=True, ");
			}
			out.push(indent + indent + "primaryjoin='"+ primaryjoin + "',");
			out.push(indent + indent + "remote_side='"+ model.name + "." + attr.name +"_id'" + backref + ")");
		}
	};

	SQLAlchemy.prototype.attr_python = function(attr, out, model, statics, models, many_to_many, indent){
		var doc = attr.doc ? ", doc='"+ attr.doc + "'" :"";
		if(attr.type === "String"){
			out.push(indent  + attr.name + " = Column(String(" + attr.size + ")" + doc + ")");
		}
		else if(attr.type === "Numeric"){
			out.push(indent  +  attr.name + " = Column(Numeric(" + attr.precision + "," + attr.scale + ")" + doc + ")");
		}
		else if(attr.type === "Boolean"){
			out.push(indent  +  attr.name + " = Column(Boolean()" + doc + ")");
		}
		else if(attr.type === "Enum"){
			var values = attr.values ? attr.values.split(",") : [];
			var enum_list = [];
			for(var i=0; i < values.length; i++){
				enum_list.push("'" + values[i].trim() + "'");
			}
			statics.push(indent + attr.name.toUpperCase() + " = [" + enum_list.join(",") + "]");
			statics.push(indent);
			out.push(indent  +  attr.name + " = Column(Enum(*" + attr.name.toUpperCase() + ")" + doc + ")");
		}
		else if(["Datetime"].indexOf(attr.type) !== -1){
			out.push(indent  +  attr.name + " = Column(DateTime" + doc + ")");
		}
		else if(["Integer","Date","Time","Text"].indexOf(attr.type) !== -1){
			out.push(indent  +  attr.name + " = Column(" + attr.type + "" + doc + ")");
		} else {
			var scalar = models[attr.type];
			if(attr.m2m === true){
				var fkey_from = model.name.toUnderscore() + ".id";
				var fkey_to = attr.type.toUnderscore() + ".id";
				var field_from = attr.name + "_id";
				var field_to = attr.type.toUnderscore() + "_id";
				var backref = attr.backref ? ", back_populates='" + attr.backref + "'" : '';
				var comment = attr.backref ?
					"mysql_comment='{\\\"back_ref\\\":\\\""+model.name+"."+attr.name+"\\\", \\\"back_populates\\\":\\\""+attr.type+"."+attr.backref + "\\\"}'" :
					"mysql_comment='{\\\"back_ref\\\":\\\""+attr.type+"."+attr.name+"\\\"}'";
				var secondary_table = model.name.toLowerCase() + "_" + attr.name + "_" + attr.type.toLowerCase();
				var primaryjoin = model.name + ".id==" + secondary_table + ".c." + field_from;
				var secondaryjoin = attr.type + ".id==" + secondary_table + ".c." + field_to;

				out.push(indent + attr.name + " = relationship('" + attr.type + "',");
				out.push(indent + indent + "primaryjoin='" + primaryjoin + "',");
				out.push(indent + indent + "secondaryjoin='" + secondaryjoin + "',");
				out.push(indent + indent + "secondary='" + secondary_table + "',");
				out.push(indent + indent + "lazy='joined'" + backref + doc + ")");

				many_to_many.push(secondary_table + " = Table('" + secondary_table + "', Base.metadata,");
				many_to_many.push(indent + "Column('" + field_from + "', Integer, ForeignKey('" + fkey_from + "')),");
				many_to_many.push(indent + "Column('" + field_to + "', Integer, ForeignKey('" + fkey_to + "')),");
				many_to_many.push(indent + comment + ",");
				many_to_many.push(indent + "mysql_engine='InnoDB')");
				many_to_many.push("");
				many_to_many.push("");

			} else {
				var fkey = attr.type.toUnderscore() + ".id";
				var backref =  attr.backref ? ",\n" + indent + indent + "back_populates='" + attr.backref + "'" : '';
				var primaryjoin = model.name + "." + attr.name +"_id==" + attr.type + ".id";
				out.push(indent + attr.name + "_id = Column(Integer, ForeignKey('" + fkey + "'" + (
						attr.cascade ? ", ondelete='CASCADE'" : ""
						) +  "))");
				out.push(indent + attr.name + " = relationship('" + attr.type + "', uselist=False,");
				out.push(indent + indent + "primaryjoin='"+ primaryjoin + "', ");
				out.push(indent + indent + "remote_side='"+ attr.type +".id'" + backref + "" + doc + ")");
			}
		}
	};

	return {
		template: "

",
		viewModel: SQLAlchemy
	};

});


text:
app.factory('Device', function($resource){
	return $resource('/api/device/:id', {}, {
	});
});


text:
(function () {
  "use strict";

  Class('MissionControl.TemplateMediatorMap', {

    _injector: null,

    Constructor: function(injector) {
      if(injector) {
        this._injector = injector;
      } else {
        throw new Error('Injector instance is needed as constructor parameter to setup the mappings.');
      }
    },

    map: function (template) {
      return new MissionControl.mappings.TemplateMediatorMapping(template, this._injector);
    }

  });

}());


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/devtools/artifactregistry/v1beta2/version.proto

namespace Google\Cloud\ArtifactRegistry\V1beta2;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * The request to list versions.
 *
 * Generated from protobuf message google.devtools.artifactregistry.v1beta2.ListVersionsRequest
 */
class ListVersionsRequest extends \Google\Protobuf\Internal\Message
{
    /**
     * The name of the parent resource whose versions will be listed.
     *
     * Generated from protobuf field string parent = 1;
     */
    private $parent = '';
    /**
     * The maximum number of versions to return. Maximum page size is 1,000.
     *
     * Generated from protobuf field int32 page_size = 2;
     */
    private $page_size = 0;
    /**
     * The next_page_token value returned from a previous list request, if any.
     *
     * Generated from protobuf field string page_token = 3;
     */
    private $page_token = '';
    /**
     * The view that should be returned in the response.
     *
     * Generated from protobuf field .google.devtools.artifactregistry.v1beta2.VersionView view = 4;
     */
    private $view = 0;
    /**
     * Optional. The field to order the results by.
     *
     * Generated from protobuf field string order_by = 5 [(.google.api.field_behavior) = OPTIONAL];
     */
    private $order_by = '';

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type string $parent
     *           The name of the parent resource whose versions will be listed.
     *     @type int $page_size
     *           The maximum number of versions to return. Maximum page size is 1,000.
     *     @type string $page_token
     *           The next_page_token value returned from a previous list request, if any.
     *     @type int $view
     *           The view that should be returned in the response.
     *     @type string $order_by
     *           Optional. The field to order the results by.
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Devtools\Artifactregistry\V1Beta2\Version::initOnce();
        parent::__construct($data);
    }

    /**
     * The name of the parent resource whose versions will be listed.
     *
     * Generated from protobuf field string parent = 1;
     * @return string
     */
    public function getParent()
    {
        return $this->parent;
    }

    /**
     * The name of the parent resource whose versions will be listed.
     *
     * Generated from protobuf field string parent = 1;
     * @param string $var
     * @return $this
     */
    public function setParent($var)
    {
        GPBUtil::checkString($var, True);
        $this->parent = $var;

        return $this;
    }

    /**
     * The maximum number of versions to return. Maximum page size is 1,000.
     *
     * Generated from protobuf field int32 page_size = 2;
     * @return int
     */
    public function getPageSize()
    {
        return $this->page_size;
    }

    /**
     * The maximum number of versions to return. Maximum page size is 1,000.
     *
     * Generated from protobuf field int32 page_size = 2;
     * @param int $var
     * @return $this
     */
    public function setPageSize($var)
    {
        GPBUtil::checkInt32($var);
        $this->page_size = $var;

        return $this;
    }

    /**
     * The next_page_token value returned from a previous list request, if any.
     *
     * Generated from protobuf field string page_token = 3;
     * @return string
     */
    public function getPageToken()
    {
        return $this->page_token;
    }

    /**
     * The next_page_token value returned from a previous list request, if any.
     *
     * Generated from protobuf field string page_token = 3;
     * @param string $var
     * @return $this
     */
    public function setPageToken($var)
    {
        GPBUtil::checkString($var, True);
        $this->page_token = $var;

        return $this;
    }

    /**
     * The view that should be returned in the response.
     *
     * Generated from protobuf field .google.devtools.artifactregistry.v1beta2.VersionView view = 4;
     * @return int
     */
    public function getView()
    {
        return $this->view;
    }

    /**
     * The view that should be returned in the response.
     *
     * Generated from protobuf field .google.devtools.artifactregistry.v1beta2.VersionView view = 4;
     * @param int $var
     * @return $this
     */
    public function setView($var)
    {
        GPBUtil::checkEnum($var, \Google\Cloud\ArtifactRegistry\V1beta2\VersionView::class);
        $this->view = $var;

        return $this;
    }

    /**
     * Optional. The field to order the results by.
     *
     * Generated from protobuf field string order_by = 5 [(.google.api.field_behavior) = OPTIONAL];
     * @return string
     */
    public function getOrderBy()
    {
        return $this->order_by;
    }

    /**
     * Optional. The field to order the results by.
     *
     * Generated from protobuf field string order_by = 5 [(.google.api.field_behavior) = OPTIONAL];
     * @param string $var
     * @return $this
     */
    public function setOrderBy($var)
    {
        GPBUtil::checkString($var, True);
        $this->order_by = $var;

        return $this;
    }

}


text:
namespace System.Web.Configuration {

    public enum CustomErrorsMode {
        RemoteOnly = 0,
        On = 1,
        Off = 2
    }
}


text:
package net.jahhan.lmq.sender;

import net.jahhan.lmq.common.util.Tools;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import java.util.Properties;

/**
 * Created by alvin on 17-7-24. This is simple example for mqtt async java client sender mqtt msg
 */
public class MqttAsyncSimpleSendDemo {
    public static void main(String[] args) throws Exception {
        Properties properties = Tools.loadProperties();
        final String brokerUrl = properties.getProperty("brokerUrl");
        final String groupId = properties.getProperty("groupId");
        final String topic = properties.getProperty("topic");
        final int qosLevel = Integer.parseInt(properties.getProperty("qos"));
        final Boolean cleanSession = Boolean.parseBoolean(properties.getProperty("cleanSession"));
        String clientId = groupId + "@@@SEND0001";
        String accessKey = properties.getProperty("accessKey");
        String secretKey = properties.getProperty("secretKey");
        final MemoryPersistence memoryPersistence = new MemoryPersistence();
        final MqttAsyncClient mqttAsyncClient = new MqttAsyncClient(brokerUrl, clientId, memoryPersistence);
        MqttConnectOptions connOpts = new MqttConnectOptions();
        //cal the sign as password,sign=BASE64(MAC.SHA1(groupId,secretKey))
        String sign = Tools.macSignature(clientId.split("@@@")[0], secretKey);
        connOpts.setUserName(accessKey);
        connOpts.setPassword(sign.toCharArray());
        connOpts.setCleanSession(cleanSession);
        connOpts.setKeepAliveInterval(90);
        connOpts.setAutomaticReconnect(true);
        mqttAsyncClient.setCallback(new MqttCallbackExtended() {
            @Override
            public void connectComplete(boolean reconnect, String serverURI) {
                System.out.println("connect success");
            }

            @Override
            public void connectionLost(Throwable throwable) {
                throwable.printStackTrace();
            }

            @Override
            public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
                System.out.println("receive msg from topic " + s + " , body is " + new String(mqttMessage.getPayload()));
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
                System.out.println("sender msg succeed");
            }
        });
        //this is sync invoke wait complete
        mqttAsyncClient.connect(connOpts).waitForCompletion();
        while (true) {
            try {
                //async sender normal pub sub msg
                final String mqttSendTopic = topic + "/qos" + qosLevel;
                MqttMessage message = new MqttMessage("hello lmq pub sub msg".getBytes());
                message.setQos(qosLevel);
                //this is async invoke ,doesn't care the complete token
                IMqttDeliveryToken token = mqttAsyncClient.publish(mqttSendTopic, message);
            } catch (Exception e) {
                e.printStackTrace();
            }
            Thread.sleep(1000);
        }
    }
}


text:
package com.intellij.openapi.vcs.history.actions;

import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.AnActionExtensionProvider;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.ExtendableAction;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.FilePath;
import com.intellij.openapi.vcs.VcsDataKeys;
import com.intellij.openapi.vcs.changes.ChangeListManager;
import com.intellij.openapi.vcs.history.*;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.ObjectUtils;
import org.jetbrains.annotations.NotNull;

public class ShowDiffAfterWithLocalAction extends ExtendableAction implements DumbAware {
  private static final ExtensionPointName<AnActionExtensionProvider> EP_NAME =
    ExtensionPointName.create("com.intellij.openapi.vcs.history.actions.ShowDiffAfterWithLocalAction.ExtensionProvider");

  public ShowDiffAfterWithLocalAction() {
    super(EP_NAME);
  }

  @Override
  public void defaultActionPerformed(@NotNull AnActionEvent e) {
    Project project = e.getRequiredData(CommonDataKeys.PROJECT);
    if (ChangeListManager.getInstance(project).isFreezedWithNotification(null)) return;

    VcsRevisionNumber currentRevisionNumber = e.getRequiredData(VcsDataKeys.HISTORY_SESSION).getCurrentRevisionNumber();
    VcsFileRevision selectedRevision = e.getRequiredData(VcsDataKeys.VCS_FILE_REVISIONS)[0];
    FilePath filePath = e.getRequiredData(VcsDataKeys.FILE_PATH);
    VirtualFile virtualFile = e.getRequiredData(CommonDataKeys.VIRTUAL_FILE);

    if (currentRevisionNumber != null && selectedRevision != null) {
      DiffFromHistoryHandler diffHandler = ObjectUtils.notNull(e.getRequiredData(VcsDataKeys.HISTORY_PROVIDER).getHistoryDiffHandler(),
                                                               new StandardDiffFromHistoryHandler());
      diffHandler.showDiffForTwo(project, filePath,
                                 selectedRevision, new CurrentRevision(virtualFile, currentRevisionNumber));
    }
  }

  @Override
  public void defaultUpdate(@NotNull AnActionEvent e) {
    VcsFileRevision[] selectedRevisions = e.getData(VcsDataKeys.VCS_FILE_REVISIONS);
    VirtualFile virtualFile = e.getData(CommonDataKeys.VIRTUAL_FILE);
    VcsHistorySession historySession = e.getData(VcsDataKeys.HISTORY_SESSION);

    e.getPresentation().setVisible(true);
    e.getPresentation().setEnabled(selectedRevisions != null && selectedRevisions.length == 1 && virtualFile != null &&
                                   historySession != null && historySession.getCurrentRevisionNumber() != null &&
                                   historySession.isContentAvailable(selectedRevisions[0]) &&
                                   e.getData(VcsDataKeys.FILE_PATH) != null && e.getData(VcsDataKeys.HISTORY_PROVIDER) != null &&
                                   e.getData(CommonDataKeys.PROJECT) != null);
  }
}


text:
package domains;

import java.util.ArrayList;

/**
 * Created by HuYijia on 2015/1/5.
 */
public class ShoppingListChart {
    private ArrayList<ListItem> listItems=new ArrayList<ListItem>();
    private boolean hasPromotion=false;

    public  ShoppingListChart(){}

    public ShoppingListChart(ShoppingChart shoppingChart){
        ArrayList<Item> items=shoppingChart.getItems();

        for(int i=0;i<items.size();i++)
        {
            Item item=items.get(i);

            if(!this.hasThisProduct(item.getBarCode()))
            {
                ListItem listItem=new ListItem(item);
                listItems.add(listItem);
            }
            else
            {
                for(int j=0;j<listItems.size();j++)
                {
                    if(listItems.get(j).getBarCode().equals(item.getBarCode()))
                    {
                        listItems.get(j).create();
                    }
                }
            }
        }

        chargePromotion();
    }

    public void chargePromotion()
    {
        for(int i=0;i<listItems.size();i++)
        {
            if(listItems.get(i).canBePromotion())
            {
                this.hasPromotion=true;
            }
        }
    }

    public boolean hasThisProduct(String barCode)
    {
        for(int i=0;i<listItems.size();i++)
        {
            ListItem listItem=listItems.get(i);
            if(listItem.getBarCode().equals(barCode))
            {
                return true;
            }
        }
        return false;
    }

    public ArrayList<ListItem> getListItems() {
        return listItems;
    }

    public void setListItems(ArrayList<ListItem> listItems) {
        this.listItems = listItems;
    }

    public  boolean isPromotion()
    {
        return  hasPromotion;
    }
}


text:
/**
 * Module dependencies.
 */

var _ = require('@sailshq/lodash');
var async = require('async');
var chalk = require('chalk');

/**
 * Sails.prototype.lift()
 *
 * Load the app, then bind process listeners and emit the internal "ready" event.
 * The "ready" event is listened for by core hooks; for example, the HTTP hook uses
 * it to start listening for requests.
 *
 * > This method also logs the ASCII art for the characteristic ship.
 *
 * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 * @param {Dictionary?} configOverride
 *        Overrides that will be deep-merged (w/ precedence) on top of existing configuration.
 * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 * @callback {Function?} done
 *        @param {Error?} err
 *
 * A Node-style callback that wil be triggered when the lift has completed (one way or another)
 * > If the `done` callback is omitted, then:
 * >  • If the lift fails, Sails will log the underlying fatal error using `sails.log.error()`.
 * >  • Otherwise, Sails will log "App lifted successfully." using `sails.log.verbose()`.
 * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 * @api public
 * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 */

module.exports = function lift(configOverride, done) {

  var sails = this;

  // configOverride is optional.
  if (_.isFunction(configOverride)) {
    done = configOverride;
    configOverride = {};
  }

  // Callback is optional (but recommended.)
  done = done || function defaultCallback(err) {
    if (err) {
      sails.log.error('Failed to lift app:',err);
      sails.log.error('(You are seeing this error message because no callback was provided to `.lift()`.)');
      return;
    }

    sails.log.verbose('App lifted successfully.');
    sails.log.verbose('(You are seeing this log message because no callback was provided to `.lift()`.)');
  };

  async.series([

    function (next) {
      sails.load(configOverride, next);
    },

    function (next){
      sails.initialize(next);
    },

  ], function whenSailsIsReady(err) {
    if (err) {
      sails.lower(function (additionalErrLoweringSails){

        if (additionalErrLoweringSails) {
          sails.log.error('When trying to lower the app as a result of a failed lift, encountered an error:', additionalErrLoweringSails);
        }//>-

        return done(err);

      });//</sails.lower>
      return;

    }//-•

    // If `config.noShip` is set, skip the startup message.
    // Otherwise, gather app meta-info and log startup message (the boat).
    if (!_.isObject(sails.config.log) || !sails.config.log.noShip) {

      sails.log.ship && sails.log.ship();
      sails.log.info(('Server lifted in `' + sails.config.appPath + '`'));

      // > Note that we don't try to include the "To see your app, visit this URL" stuff
      // > unless we're pretty sure which URL it would be a good idea to try and visit.
      // > (even then, it's not 100% or anything.  But at least with these checks, it's
      // > not wrong MOST of the time.)
      if (!sails.config.ssl && !sails.config.http.serverOptions && !sails.config.explicitHost && process.env.NODE_ENV !== 'production') {
        sails.log.info(chalk.underline('To see your app, visit http://localhost:'+sails.config.port));
      }
      sails.log.info(('To shut down Sails, press <CTRL> + C at any time.'));
      sails.log.blank();
      sails.log(chalk.grey(Array(56).join('-')));
      sails.log(chalk.grey(':: ' + new Date()));
      sails.log.blank();
      sails.log('Environment : ' + sails.config.environment);

      // Only log the host if an explicit host is set
      if (!_.isUndefined(sails.config.explicitHost)) {
        sails.log('Host        : ' + sails.config.explicitHost); // 12 - 4 = 8 spaces
      }
      sails.log('Port        : ' + sails.config.port); // 12 - 4 = 8 spaces
      sails.log(chalk.grey(Array(56).join('-')));
    }//>-

    // Emit 'lifted' event.
    sails.emit('lifted');

    // Set `isLifted` (private dignostic flag)
    sails.isLifted = true;

    // try {console.timeEnd('core_lift');}catch(e){}

    return done(undefined, sails);

  });//</async.series()>
};


text:
GPS 1 (12/10/15)

git clone:Clone a remote repository to your local directory
git status:Check on the status of tracked/untracked files
git add: Adds a file to the stage for commit
git commit -m: commit the file with appropriate commit message
git push: push the committed file to the remote repository
git checkout -b: This creates a new branch
cd: Change directory
touch: create new file
../: move up directory tree
ls: list contents of directory
open: open file


text:
        <form method="post" action=".">
            {% csrf_token %}
            Captricity Token: <input type="text" value="{{ user.captricity_api_token }}" name="captricity-api-token" />

            CMIS username: <input type="text" value="{{ user.cmis_user }}" name="cmis_user" />

            CMIS password: <input type="text" value="{{ user.cmis_pass }}" name="cmis_pass" />

            <input type="submit" value="Submit" />
        </form>


text:
FOUNDATION_EXPORT NSString *const XBHighlightColorAttributeName;

FOUNDATION_EXPORT NSString *const XBHighlightColor1Key;
FOUNDATION_EXPORT NSString *const XBHighlightColor2Key;
FOUNDATION_EXPORT NSString *const XBHighlightColor3Key;
FOUNDATION_EXPORT NSString *const XBHighlightColor4Key;


text:
PRG="$0"
PRGDIR=`dirname "$PRG"`
[ -z "$COLLECTOR_HOME" ] && COLLECTOR_HOME=`cd "$PRGDIR/.." >/dev/null; pwd`

COLLECT_LOG_DIR="${COLLECTOR_HOME}/logs"
JAVA_OPTS=" -Xms256M -Xmx512M"

if [ ! -d "${COLLECTOR_HOME}/logs" ]; then
    mkdir -p "${COLLECT_LOG_DIR}"
fi

_RUNJAVA=${JAVA_HOME}/bin/java
[ -z "$JAVA_HOME" ] && _RUNJAVA=java

CLASSPATH="$COLLECTOR_HOME/config:$CLASSPATH"
for i in "$COLLECTOR_HOME"/libs/*.jar
do
    CLASSPATH="$i:$CLASSPATH"
done
COLLECTOR_OPTIONS=" -Dcollector.logDir=${COLLECT_LOG_DIR}"
echo "Starting collector...."

eval exec "\"$_RUNJAVA\" ${JAVA_OPTS} ${COLLECTOR_OPTIONS} -classpath $CLASSPATH org.skywalking.apm.collector.boot.CollectorBootStartUp \
        2>${COLLECT_LOG_DIR}/collector.log 1> /dev/null &"

if [ $? -eq 0 ]; then
    sleep 1
	echo "Skywalking Web started successfully!"
else
	echo "Skywalking Web started failure!"
	exit 1
fi


text:
<Record>
<Term>Trandolaprilat</Term>
<SemanticType>Pharmacologic Substance</SemanticType>
<ParentTerm>ACE Inhibitor</ParentTerm>
<ClassificationPath>Chemicals_and_Drugs_Kind/Drug, Food, Chemical or Biomedical Material/Pharmacologic Substance/Enzyme Inhibitor/ACE Inhibitor/Trandolaprilat</ClassificationPath>
<BroaderTerm>Chemicals_and_Drugs_Kind</BroaderTerm>
<BroaderTerm>Enzyme Inhibitor</BroaderTerm>
<BroaderTerm>Pharmacologic Substance</BroaderTerm>
<BroaderTerm>Trandolaprilat</BroaderTerm>
<BroaderTerm>ACE Inhibitor</BroaderTerm>
<BroaderTerm>Drug, Food, Chemical or Biomedical Material</BroaderTerm>
<Synonym>TRANDOLAPRILAT</Synonym>
<Synonym>Trandolaprilat</Synonym>
<Source>NCI Thesaurus</Source>
</Record>


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <corners android:radius="10dip"/>
    <stroke android:color="@color/black" android:width="2dip"/>
    <solid android:color="@color/grey"/>
</shape>


text:
package utilities.parameters;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.ext.DefaultHandler2;

/**
 * A {@link DefaultHandler2} to parse the parameter xml file.
 */
public class XMLParameterParser extends DefaultHandler2 {

	/**
	 * For logging purposes.
	 */
	private final static Logger LOG = LogManager.getLogger();

	/**
	 * Parsed {@link String} representations of a parameter value (i.e., the string in the xml parameter file that
	 * defines the parameter value) that equal this {@link String} are interpreted to have null as
	 * parameter value in {@link Parameters}.
	 */
	private final static String NULL_PARAMETER_STRING = "null";

	/**
	 * Holds the name of the xml parameter file.
	 */
	private final String parameterFile;

	/**
	 * Holds the parsed {@link Parameters}. If no parsing has yet taken place, this value is null.
	 */
	private Parameters parameters = null;

	/**
	 * Creates a new {@link XMLParameterParser}.
	 *
	 * @param parameterFile
	 *            the name of the xml parameter file
	 */
	public XMLParameterParser(String parameterFile) {
		this.parameterFile = parameterFile;
	}

	/**
	 * @return Returns the parsed {@link Parameters} for the xml file {@link #parameterFile}.
	 */
	public Parameters getParameters() {
		if (this.parameters == null) {
			this.parseParameters();
		}
		return this.parameters;
	}

	/**
	 * Parses the xml file {@link #parameterFile} and fills the {@link #parameters}.
	 */
	private void parseParameters() {
		// get a factory
		SAXParserFactory spf = SAXParserFactory.newInstance();
		try {
			this.parameters = new Parameters();

			// get a new instance of parser
			SAXParser sp = spf.newSAXParser();
			sp.setProperty("http://xml.org/sax/properties/lexical-handler", this);

			// parse the file and also register this class for call backs
			sp.parse(new File(this.parameterFile), this);

		} catch (SAXException se) {
			se.printStackTrace();
		} catch (ParserConfigurationException pce) {
			pce.printStackTrace();
		} catch (IOException ie) {
			ie.printStackTrace();
		}
	}

	@Override
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		if (qName.equalsIgnoreCase("sweep")) {
			// do nothing
		} else if (qName.equalsIgnoreCase("parameter")) {
			String parameterName = attributes.getValue("name");
			String parameterType = attributes.getValue("constant_type");
			String parameterValueString = attributes.getValue("value");
			// in case the name/type/value are unavailable, we return
			if (parameterName == null || parameterType == null || parameterValueString == null) {
				XMLParameterParser.LOG.warn("One of the necessary attributes seems to be unavailable. Parameter name: '" + parameterName
						+ "', parameter type: '" + parameterType + "', parameter value: '" + parameterValueString
						+ "'. Necessary attributes are 'name', 'constant_type', and 'value'.");
				return;
			}

			if (!parameterValueString.equals(XMLParameterParser.NULL_PARAMETER_STRING)) {
				// create the right parameter value object dependent on the specified type
				Object parameterValue = null;
				// String
				if (parameterType.equalsIgnoreCase("string")) {
					// this is easy, the value is already a String
					parameterValue = parameterValueString;
				}
				// Boolean
				else if (parameterType.equalsIgnoreCase("boolean")) {
					if (!parameterValueString.equalsIgnoreCase("true") && !parameterValueString.equalsIgnoreCase("false")) {
						XMLParameterParser.LOG.error("Parameter '" + parameterName + "' has not a valid boolean value ('true' or 'false')! Given value is '"
								+ parameterValueString + "'. Parameter is ignored.");
						return;
					}
					parameterValue = Boolean.parseBoolean(parameterValueString);

				}
				// Number (Integer or Double)
				else if (parameterType.equalsIgnoreCase("number")) {
					try {
						// integer parameter
						parameterValue = Integer.parseInt(parameterValueString);

					} catch (NumberFormatException e) {
						try {
							// double parameter
							parameterValue = Double.parseDouble(parameterValueString);
						} catch (NumberFormatException e2) {
							XMLParameterParser.LOG.error("Parameter '" + parameterName + "' is not a valid number! Given value is '" + parameterValueString
									+ "'. Parameter is ignored.");
							return;
						}
					}
				}
				// invalid type
				else {
					XMLParameterParser.LOG.error("Parameter '" + parameterName + "' is not of valid type ('string', 'boolean', or 'number')! Given type is '"
							+ parameterType + "'. Parameter is ignored.");
					return;
				}

				// put the parameter in the map
				this.parameters.setParameter(parameterName, parameterValue);
			} else { // parameter value equals null string
				// put the parameter with null value in the map
				this.parameters.setParameter(parameterName, null);
			}
		} else if (qName.equalsIgnoreCase("config") || qName.equalsIgnoreCase("batchruns") || qName.equalsIgnoreCase("setting")) {
			// these are settings for running the simulation via JPPF -- these are ok and ignore them here
		}

		// invalid tag
		else {
			XMLParameterParser.LOG.error("The xml file only expects tags that are 'sweep' or 'parameter'. Given tag is '" + qName + "'.");
		}
	}

	@Override
	public void comment(char[] ch, int start, int length) throws SAXException {
		// TODO
		// System.out.println("XML comment: " + new String(ch, start, length));
	}
}


text:
This cookbook includes support for running tests via Test Kitchen (1.0). This has some requirements.

1. You must be using the Git repository, rather than the downloaded cookbook from the Chef Community Site.
2. You must have Vagrant 1.1 installed.
3. You must have a "sane" Ruby 1.9.3 environment.

Once the above requirements are met, install the additional requirements:

Install the berkshelf plugin for vagrant, and berkshelf to your local Ruby environment.

    vagrant plugin install vagrant-berkshelf
    gem install berkshelf

Install Test Kitchen 1.0 (unreleased yet, use the alpha / prerelease version).

    gem install test-kitchen --pre

Install the Vagrant driver for Test Kitchen.

    gem install kitchen-vagrant

Once the above are installed, you should be able to run Test Kitchen:

    kitchen list
    kitchen test

# A note about the SLES Box

The .kitchen.yml has a platform for SLES 11-sp2. Due to licensing
reasons, we cannot distribute the base box. You can however build your
own using the Bento definition `sles-11-sp2`, and import it separate
from test-kitchen's run.

Before exporting the box, do ensure that the vagrant user has
NOPASSWD: ALL in /etc/sudoers.

# A note about the OmniOS Box

This patch to test-kitchen is required to test using the OmniOS box,
as the path to `pkgadd` (`/usr/sbin`) is not in the default `vagrant`
user's path when logging in without a TTY.

https://github.com/opscode/test-kitchen/pull/164

If your local version of Vagrant is 1.2.0 or higher, you may need to
install the `vagrant-guest-omnios` plugin to get OS detection for
OmniOS to work properly.

https://github.com/clintoncwolfe/vagrant-guest-omnios

TL;DR:

    vagrant plugin install vagrant-guest-omnios


text:
package com.github.mizool.core.exception;

import java.io.Serializable;

import lombok.Builder;
import lombok.Value;

@Value
@Builder(toBuilder = true)
public class RuleViolation implements Serializable
{
    private final String fieldName;
    private final String errorId;
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SentinelKernel.System.FileSystem.Listing
{
    public class File : Base
    {
        //TODO:UInt64? Size until ulong works.. nullable types have a problem right now
        public File(FileSystem aFileSystem, string aName, UInt64 aSize)
            : base(aFileSystem, aName)
        {
            mSize = aSize;
        }
    }
}